SemaOpenMP.cpp 862 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642
  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/StringExtras.h"
  38. #include "llvm/Frontend/OpenMP/OMPAssume.h"
  39. #include "llvm/Frontend/OpenMP/OMPConstants.h"
  40. #include <set>
  41. using namespace clang;
  42. using namespace llvm::omp;
  43. //===----------------------------------------------------------------------===//
  44. // Stack of data-sharing attributes for variables
  45. //===----------------------------------------------------------------------===//
  46. static const Expr *checkMapClauseExpressionBase(
  47. Sema &SemaRef, Expr *E,
  48. OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
  49. OpenMPClauseKind CKind, OpenMPDirectiveKind DKind, bool NoDiagnose);
  50. namespace {
  51. /// Default data sharing attributes, which can be applied to directive.
  52. enum DefaultDataSharingAttributes {
  53. DSA_unspecified = 0, /// Data sharing attribute not specified.
  54. DSA_none = 1 << 0, /// Default data sharing attribute 'none'.
  55. DSA_shared = 1 << 1, /// Default data sharing attribute 'shared'.
  56. DSA_firstprivate = 1 << 2, /// Default data sharing attribute 'firstprivate'.
  57. };
  58. /// Stack for tracking declarations used in OpenMP directives and
  59. /// clauses and their data-sharing attributes.
  60. class DSAStackTy {
  61. public:
  62. struct DSAVarData {
  63. OpenMPDirectiveKind DKind = OMPD_unknown;
  64. OpenMPClauseKind CKind = OMPC_unknown;
  65. unsigned Modifier = 0;
  66. const Expr *RefExpr = nullptr;
  67. DeclRefExpr *PrivateCopy = nullptr;
  68. SourceLocation ImplicitDSALoc;
  69. bool AppliedToPointee = false;
  70. DSAVarData() = default;
  71. DSAVarData(OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
  72. const Expr *RefExpr, DeclRefExpr *PrivateCopy,
  73. SourceLocation ImplicitDSALoc, unsigned Modifier,
  74. bool AppliedToPointee)
  75. : DKind(DKind), CKind(CKind), Modifier(Modifier), RefExpr(RefExpr),
  76. PrivateCopy(PrivateCopy), ImplicitDSALoc(ImplicitDSALoc),
  77. AppliedToPointee(AppliedToPointee) {}
  78. };
  79. using OperatorOffsetTy =
  80. llvm::SmallVector<std::pair<Expr *, OverloadedOperatorKind>, 4>;
  81. using DoacrossDependMapTy =
  82. llvm::DenseMap<OMPDependClause *, OperatorOffsetTy>;
  83. /// Kind of the declaration used in the uses_allocators clauses.
  84. enum class UsesAllocatorsDeclKind {
  85. /// Predefined allocator
  86. PredefinedAllocator,
  87. /// User-defined allocator
  88. UserDefinedAllocator,
  89. /// The declaration that represent allocator trait
  90. AllocatorTrait,
  91. };
  92. private:
  93. struct DSAInfo {
  94. OpenMPClauseKind Attributes = OMPC_unknown;
  95. unsigned Modifier = 0;
  96. /// Pointer to a reference expression and a flag which shows that the
  97. /// variable is marked as lastprivate(true) or not (false).
  98. llvm::PointerIntPair<const Expr *, 1, bool> RefExpr;
  99. DeclRefExpr *PrivateCopy = nullptr;
  100. /// true if the attribute is applied to the pointee, not the variable
  101. /// itself.
  102. bool AppliedToPointee = false;
  103. };
  104. using DeclSAMapTy = llvm::SmallDenseMap<const ValueDecl *, DSAInfo, 8>;
  105. using UsedRefMapTy = llvm::SmallDenseMap<const ValueDecl *, const Expr *, 8>;
  106. using LCDeclInfo = std::pair<unsigned, VarDecl *>;
  107. using LoopControlVariablesMapTy =
  108. llvm::SmallDenseMap<const ValueDecl *, LCDeclInfo, 8>;
  109. /// Struct that associates a component with the clause kind where they are
  110. /// found.
  111. struct MappedExprComponentTy {
  112. OMPClauseMappableExprCommon::MappableExprComponentLists Components;
  113. OpenMPClauseKind Kind = OMPC_unknown;
  114. };
  115. using MappedExprComponentsTy =
  116. llvm::DenseMap<const ValueDecl *, MappedExprComponentTy>;
  117. using CriticalsWithHintsTy =
  118. llvm::StringMap<std::pair<const OMPCriticalDirective *, llvm::APSInt>>;
  119. struct ReductionData {
  120. using BOKPtrType = llvm::PointerEmbeddedInt<BinaryOperatorKind, 16>;
  121. SourceRange ReductionRange;
  122. llvm::PointerUnion<const Expr *, BOKPtrType> ReductionOp;
  123. ReductionData() = default;
  124. void set(BinaryOperatorKind BO, SourceRange RR) {
  125. ReductionRange = RR;
  126. ReductionOp = BO;
  127. }
  128. void set(const Expr *RefExpr, SourceRange RR) {
  129. ReductionRange = RR;
  130. ReductionOp = RefExpr;
  131. }
  132. };
  133. using DeclReductionMapTy =
  134. llvm::SmallDenseMap<const ValueDecl *, ReductionData, 4>;
  135. struct DefaultmapInfo {
  136. OpenMPDefaultmapClauseModifier ImplicitBehavior =
  137. OMPC_DEFAULTMAP_MODIFIER_unknown;
  138. SourceLocation SLoc;
  139. DefaultmapInfo() = default;
  140. DefaultmapInfo(OpenMPDefaultmapClauseModifier M, SourceLocation Loc)
  141. : ImplicitBehavior(M), SLoc(Loc) {}
  142. };
  143. struct SharingMapTy {
  144. DeclSAMapTy SharingMap;
  145. DeclReductionMapTy ReductionMap;
  146. UsedRefMapTy AlignedMap;
  147. UsedRefMapTy NontemporalMap;
  148. MappedExprComponentsTy MappedExprComponents;
  149. LoopControlVariablesMapTy LCVMap;
  150. DefaultDataSharingAttributes DefaultAttr = DSA_unspecified;
  151. SourceLocation DefaultAttrLoc;
  152. DefaultmapInfo DefaultmapMap[OMPC_DEFAULTMAP_unknown];
  153. OpenMPDirectiveKind Directive = OMPD_unknown;
  154. DeclarationNameInfo DirectiveName;
  155. Scope *CurScope = nullptr;
  156. DeclContext *Context = nullptr;
  157. SourceLocation ConstructLoc;
  158. /// Set of 'depend' clauses with 'sink|source' dependence kind. Required to
  159. /// get the data (loop counters etc.) about enclosing loop-based construct.
  160. /// This data is required during codegen.
  161. DoacrossDependMapTy DoacrossDepends;
  162. /// First argument (Expr *) contains optional argument of the
  163. /// 'ordered' clause, the second one is true if the regions has 'ordered'
  164. /// clause, false otherwise.
  165. llvm::Optional<std::pair<const Expr *, OMPOrderedClause *>> OrderedRegion;
  166. unsigned AssociatedLoops = 1;
  167. bool HasMutipleLoops = false;
  168. const Decl *PossiblyLoopCounter = nullptr;
  169. bool NowaitRegion = false;
  170. bool CancelRegion = false;
  171. bool LoopStart = false;
  172. bool BodyComplete = false;
  173. SourceLocation PrevScanLocation;
  174. SourceLocation PrevOrderedLocation;
  175. SourceLocation InnerTeamsRegionLoc;
  176. /// Reference to the taskgroup task_reduction reference expression.
  177. Expr *TaskgroupReductionRef = nullptr;
  178. llvm::DenseSet<QualType> MappedClassesQualTypes;
  179. SmallVector<Expr *, 4> InnerUsedAllocators;
  180. llvm::DenseSet<CanonicalDeclPtr<Decl>> ImplicitTaskFirstprivates;
  181. /// List of globals marked as declare target link in this target region
  182. /// (isOpenMPTargetExecutionDirective(Directive) == true).
  183. llvm::SmallVector<DeclRefExpr *, 4> DeclareTargetLinkVarDecls;
  184. /// List of decls used in inclusive/exclusive clauses of the scan directive.
  185. llvm::DenseSet<CanonicalDeclPtr<Decl>> UsedInScanDirective;
  186. llvm::DenseMap<CanonicalDeclPtr<const Decl>, UsesAllocatorsDeclKind>
  187. UsesAllocatorsDecls;
  188. Expr *DeclareMapperVar = nullptr;
  189. SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name,
  190. Scope *CurScope, SourceLocation Loc)
  191. : Directive(DKind), DirectiveName(Name), CurScope(CurScope),
  192. ConstructLoc(Loc) {}
  193. SharingMapTy() = default;
  194. };
  195. using StackTy = SmallVector<SharingMapTy, 4>;
  196. /// Stack of used declaration and their data-sharing attributes.
  197. DeclSAMapTy Threadprivates;
  198. const FunctionScopeInfo *CurrentNonCapturingFunctionScope = nullptr;
  199. SmallVector<std::pair<StackTy, const FunctionScopeInfo *>, 4> Stack;
  200. /// true, if check for DSA must be from parent directive, false, if
  201. /// from current directive.
  202. OpenMPClauseKind ClauseKindMode = OMPC_unknown;
  203. Sema &SemaRef;
  204. bool ForceCapturing = false;
  205. /// true if all the variables in the target executable directives must be
  206. /// captured by reference.
  207. bool ForceCaptureByReferenceInTargetExecutable = false;
  208. CriticalsWithHintsTy Criticals;
  209. unsigned IgnoredStackElements = 0;
  210. /// Iterators over the stack iterate in order from innermost to outermost
  211. /// directive.
  212. using const_iterator = StackTy::const_reverse_iterator;
  213. const_iterator begin() const {
  214. return Stack.empty() ? const_iterator()
  215. : Stack.back().first.rbegin() + IgnoredStackElements;
  216. }
  217. const_iterator end() const {
  218. return Stack.empty() ? const_iterator() : Stack.back().first.rend();
  219. }
  220. using iterator = StackTy::reverse_iterator;
  221. iterator begin() {
  222. return Stack.empty() ? iterator()
  223. : Stack.back().first.rbegin() + IgnoredStackElements;
  224. }
  225. iterator end() {
  226. return Stack.empty() ? iterator() : Stack.back().first.rend();
  227. }
  228. // Convenience operations to get at the elements of the stack.
  229. bool isStackEmpty() const {
  230. return Stack.empty() ||
  231. Stack.back().second != CurrentNonCapturingFunctionScope ||
  232. Stack.back().first.size() <= IgnoredStackElements;
  233. }
  234. size_t getStackSize() const {
  235. return isStackEmpty() ? 0
  236. : Stack.back().first.size() - IgnoredStackElements;
  237. }
  238. SharingMapTy *getTopOfStackOrNull() {
  239. size_t Size = getStackSize();
  240. if (Size == 0)
  241. return nullptr;
  242. return &Stack.back().first[Size - 1];
  243. }
  244. const SharingMapTy *getTopOfStackOrNull() const {
  245. return const_cast<DSAStackTy &>(*this).getTopOfStackOrNull();
  246. }
  247. SharingMapTy &getTopOfStack() {
  248. assert(!isStackEmpty() && "no current directive");
  249. return *getTopOfStackOrNull();
  250. }
  251. const SharingMapTy &getTopOfStack() const {
  252. return const_cast<DSAStackTy &>(*this).getTopOfStack();
  253. }
  254. SharingMapTy *getSecondOnStackOrNull() {
  255. size_t Size = getStackSize();
  256. if (Size <= 1)
  257. return nullptr;
  258. return &Stack.back().first[Size - 2];
  259. }
  260. const SharingMapTy *getSecondOnStackOrNull() const {
  261. return const_cast<DSAStackTy &>(*this).getSecondOnStackOrNull();
  262. }
  263. /// Get the stack element at a certain level (previously returned by
  264. /// \c getNestingLevel).
  265. ///
  266. /// Note that nesting levels count from outermost to innermost, and this is
  267. /// the reverse of our iteration order where new inner levels are pushed at
  268. /// the front of the stack.
  269. SharingMapTy &getStackElemAtLevel(unsigned Level) {
  270. assert(Level < getStackSize() && "no such stack element");
  271. return Stack.back().first[Level];
  272. }
  273. const SharingMapTy &getStackElemAtLevel(unsigned Level) const {
  274. return const_cast<DSAStackTy &>(*this).getStackElemAtLevel(Level);
  275. }
  276. DSAVarData getDSA(const_iterator &Iter, ValueDecl *D) const;
  277. /// Checks if the variable is a local for OpenMP region.
  278. bool isOpenMPLocal(VarDecl *D, const_iterator Iter) const;
  279. /// Vector of previously declared requires directives
  280. SmallVector<const OMPRequiresDecl *, 2> RequiresDecls;
  281. /// omp_allocator_handle_t type.
  282. QualType OMPAllocatorHandleT;
  283. /// omp_depend_t type.
  284. QualType OMPDependT;
  285. /// omp_event_handle_t type.
  286. QualType OMPEventHandleT;
  287. /// omp_alloctrait_t type.
  288. QualType OMPAlloctraitT;
  289. /// Expression for the predefined allocators.
  290. Expr *OMPPredefinedAllocators[OMPAllocateDeclAttr::OMPUserDefinedMemAlloc] = {
  291. nullptr};
  292. /// Vector of previously encountered target directives
  293. SmallVector<SourceLocation, 2> TargetLocations;
  294. SourceLocation AtomicLocation;
  295. /// Vector of declare variant construct traits.
  296. SmallVector<llvm::omp::TraitProperty, 8> ConstructTraits;
  297. public:
  298. explicit DSAStackTy(Sema &S) : SemaRef(S) {}
  299. /// Sets omp_allocator_handle_t type.
  300. void setOMPAllocatorHandleT(QualType Ty) { OMPAllocatorHandleT = Ty; }
  301. /// Gets omp_allocator_handle_t type.
  302. QualType getOMPAllocatorHandleT() const { return OMPAllocatorHandleT; }
  303. /// Sets omp_alloctrait_t type.
  304. void setOMPAlloctraitT(QualType Ty) { OMPAlloctraitT = Ty; }
  305. /// Gets omp_alloctrait_t type.
  306. QualType getOMPAlloctraitT() const { return OMPAlloctraitT; }
  307. /// Sets the given default allocator.
  308. void setAllocator(OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind,
  309. Expr *Allocator) {
  310. OMPPredefinedAllocators[AllocatorKind] = Allocator;
  311. }
  312. /// Returns the specified default allocator.
  313. Expr *getAllocator(OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind) const {
  314. return OMPPredefinedAllocators[AllocatorKind];
  315. }
  316. /// Sets omp_depend_t type.
  317. void setOMPDependT(QualType Ty) { OMPDependT = Ty; }
  318. /// Gets omp_depend_t type.
  319. QualType getOMPDependT() const { return OMPDependT; }
  320. /// Sets omp_event_handle_t type.
  321. void setOMPEventHandleT(QualType Ty) { OMPEventHandleT = Ty; }
  322. /// Gets omp_event_handle_t type.
  323. QualType getOMPEventHandleT() const { return OMPEventHandleT; }
  324. bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; }
  325. OpenMPClauseKind getClauseParsingMode() const {
  326. assert(isClauseParsingMode() && "Must be in clause parsing mode.");
  327. return ClauseKindMode;
  328. }
  329. void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; }
  330. bool isBodyComplete() const {
  331. const SharingMapTy *Top = getTopOfStackOrNull();
  332. return Top && Top->BodyComplete;
  333. }
  334. void setBodyComplete() { getTopOfStack().BodyComplete = true; }
  335. bool isForceVarCapturing() const { return ForceCapturing; }
  336. void setForceVarCapturing(bool V) { ForceCapturing = V; }
  337. void setForceCaptureByReferenceInTargetExecutable(bool V) {
  338. ForceCaptureByReferenceInTargetExecutable = V;
  339. }
  340. bool isForceCaptureByReferenceInTargetExecutable() const {
  341. return ForceCaptureByReferenceInTargetExecutable;
  342. }
  343. void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
  344. Scope *CurScope, SourceLocation Loc) {
  345. assert(!IgnoredStackElements &&
  346. "cannot change stack while ignoring elements");
  347. if (Stack.empty() ||
  348. Stack.back().second != CurrentNonCapturingFunctionScope)
  349. Stack.emplace_back(StackTy(), CurrentNonCapturingFunctionScope);
  350. Stack.back().first.emplace_back(DKind, DirName, CurScope, Loc);
  351. Stack.back().first.back().DefaultAttrLoc = Loc;
  352. }
  353. void pop() {
  354. assert(!IgnoredStackElements &&
  355. "cannot change stack while ignoring elements");
  356. assert(!Stack.back().first.empty() &&
  357. "Data-sharing attributes stack is empty!");
  358. Stack.back().first.pop_back();
  359. }
  360. /// RAII object to temporarily leave the scope of a directive when we want to
  361. /// logically operate in its parent.
  362. class ParentDirectiveScope {
  363. DSAStackTy &Self;
  364. bool Active;
  365. public:
  366. ParentDirectiveScope(DSAStackTy &Self, bool Activate)
  367. : Self(Self), Active(false) {
  368. if (Activate)
  369. enable();
  370. }
  371. ~ParentDirectiveScope() { disable(); }
  372. void disable() {
  373. if (Active) {
  374. --Self.IgnoredStackElements;
  375. Active = false;
  376. }
  377. }
  378. void enable() {
  379. if (!Active) {
  380. ++Self.IgnoredStackElements;
  381. Active = true;
  382. }
  383. }
  384. };
  385. /// Marks that we're started loop parsing.
  386. void loopInit() {
  387. assert(isOpenMPLoopDirective(getCurrentDirective()) &&
  388. "Expected loop-based directive.");
  389. getTopOfStack().LoopStart = true;
  390. }
  391. /// Start capturing of the variables in the loop context.
  392. void loopStart() {
  393. assert(isOpenMPLoopDirective(getCurrentDirective()) &&
  394. "Expected loop-based directive.");
  395. getTopOfStack().LoopStart = false;
  396. }
  397. /// true, if variables are captured, false otherwise.
  398. bool isLoopStarted() const {
  399. assert(isOpenMPLoopDirective(getCurrentDirective()) &&
  400. "Expected loop-based directive.");
  401. return !getTopOfStack().LoopStart;
  402. }
  403. /// Marks (or clears) declaration as possibly loop counter.
  404. void resetPossibleLoopCounter(const Decl *D = nullptr) {
  405. getTopOfStack().PossiblyLoopCounter = D ? D->getCanonicalDecl() : D;
  406. }
  407. /// Gets the possible loop counter decl.
  408. const Decl *getPossiblyLoopCunter() const {
  409. return getTopOfStack().PossiblyLoopCounter;
  410. }
  411. /// Start new OpenMP region stack in new non-capturing function.
  412. void pushFunction() {
  413. assert(!IgnoredStackElements &&
  414. "cannot change stack while ignoring elements");
  415. const FunctionScopeInfo *CurFnScope = SemaRef.getCurFunction();
  416. assert(!isa<CapturingScopeInfo>(CurFnScope));
  417. CurrentNonCapturingFunctionScope = CurFnScope;
  418. }
  419. /// Pop region stack for non-capturing function.
  420. void popFunction(const FunctionScopeInfo *OldFSI) {
  421. assert(!IgnoredStackElements &&
  422. "cannot change stack while ignoring elements");
  423. if (!Stack.empty() && Stack.back().second == OldFSI) {
  424. assert(Stack.back().first.empty());
  425. Stack.pop_back();
  426. }
  427. CurrentNonCapturingFunctionScope = nullptr;
  428. for (const FunctionScopeInfo *FSI : llvm::reverse(SemaRef.FunctionScopes)) {
  429. if (!isa<CapturingScopeInfo>(FSI)) {
  430. CurrentNonCapturingFunctionScope = FSI;
  431. break;
  432. }
  433. }
  434. }
  435. void addCriticalWithHint(const OMPCriticalDirective *D, llvm::APSInt Hint) {
  436. Criticals.try_emplace(D->getDirectiveName().getAsString(), D, Hint);
  437. }
  438. const std::pair<const OMPCriticalDirective *, llvm::APSInt>
  439. getCriticalWithHint(const DeclarationNameInfo &Name) const {
  440. auto I = Criticals.find(Name.getAsString());
  441. if (I != Criticals.end())
  442. return I->second;
  443. return std::make_pair(nullptr, llvm::APSInt());
  444. }
  445. /// If 'aligned' declaration for given variable \a D was not seen yet,
  446. /// add it and return NULL; otherwise return previous occurrence's expression
  447. /// for diagnostics.
  448. const Expr *addUniqueAligned(const ValueDecl *D, const Expr *NewDE);
  449. /// If 'nontemporal' declaration for given variable \a D was not seen yet,
  450. /// add it and return NULL; otherwise return previous occurrence's expression
  451. /// for diagnostics.
  452. const Expr *addUniqueNontemporal(const ValueDecl *D, const Expr *NewDE);
  453. /// Register specified variable as loop control variable.
  454. void addLoopControlVariable(const ValueDecl *D, VarDecl *Capture);
  455. /// Check if the specified variable is a loop control variable for
  456. /// current region.
  457. /// \return The index of the loop control variable in the list of associated
  458. /// for-loops (from outer to inner).
  459. const LCDeclInfo isLoopControlVariable(const ValueDecl *D) const;
  460. /// Check if the specified variable is a loop control variable for
  461. /// parent region.
  462. /// \return The index of the loop control variable in the list of associated
  463. /// for-loops (from outer to inner).
  464. const LCDeclInfo isParentLoopControlVariable(const ValueDecl *D) const;
  465. /// Check if the specified variable is a loop control variable for
  466. /// current region.
  467. /// \return The index of the loop control variable in the list of associated
  468. /// for-loops (from outer to inner).
  469. const LCDeclInfo isLoopControlVariable(const ValueDecl *D,
  470. unsigned Level) const;
  471. /// Get the loop control variable for the I-th loop (or nullptr) in
  472. /// parent directive.
  473. const ValueDecl *getParentLoopControlVariable(unsigned I) const;
  474. /// Marks the specified decl \p D as used in scan directive.
  475. void markDeclAsUsedInScanDirective(ValueDecl *D) {
  476. if (SharingMapTy *Stack = getSecondOnStackOrNull())
  477. Stack->UsedInScanDirective.insert(D);
  478. }
  479. /// Checks if the specified declaration was used in the inner scan directive.
  480. bool isUsedInScanDirective(ValueDecl *D) const {
  481. if (const SharingMapTy *Stack = getTopOfStackOrNull())
  482. return Stack->UsedInScanDirective.contains(D);
  483. return false;
  484. }
  485. /// Adds explicit data sharing attribute to the specified declaration.
  486. void addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A,
  487. DeclRefExpr *PrivateCopy = nullptr, unsigned Modifier = 0,
  488. bool AppliedToPointee = false);
  489. /// Adds additional information for the reduction items with the reduction id
  490. /// represented as an operator.
  491. void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
  492. BinaryOperatorKind BOK);
  493. /// Adds additional information for the reduction items with the reduction id
  494. /// represented as reduction identifier.
  495. void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
  496. const Expr *ReductionRef);
  497. /// Returns the location and reduction operation from the innermost parent
  498. /// region for the given \p D.
  499. const DSAVarData
  500. getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR,
  501. BinaryOperatorKind &BOK,
  502. Expr *&TaskgroupDescriptor) const;
  503. /// Returns the location and reduction operation from the innermost parent
  504. /// region for the given \p D.
  505. const DSAVarData
  506. getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR,
  507. const Expr *&ReductionRef,
  508. Expr *&TaskgroupDescriptor) const;
  509. /// Return reduction reference expression for the current taskgroup or
  510. /// parallel/worksharing directives with task reductions.
  511. Expr *getTaskgroupReductionRef() const {
  512. assert((getTopOfStack().Directive == OMPD_taskgroup ||
  513. ((isOpenMPParallelDirective(getTopOfStack().Directive) ||
  514. isOpenMPWorksharingDirective(getTopOfStack().Directive)) &&
  515. !isOpenMPSimdDirective(getTopOfStack().Directive))) &&
  516. "taskgroup reference expression requested for non taskgroup or "
  517. "parallel/worksharing directive.");
  518. return getTopOfStack().TaskgroupReductionRef;
  519. }
  520. /// Checks if the given \p VD declaration is actually a taskgroup reduction
  521. /// descriptor variable at the \p Level of OpenMP regions.
  522. bool isTaskgroupReductionRef(const ValueDecl *VD, unsigned Level) const {
  523. return getStackElemAtLevel(Level).TaskgroupReductionRef &&
  524. cast<DeclRefExpr>(getStackElemAtLevel(Level).TaskgroupReductionRef)
  525. ->getDecl() == VD;
  526. }
  527. /// Returns data sharing attributes from top of the stack for the
  528. /// specified declaration.
  529. const DSAVarData getTopDSA(ValueDecl *D, bool FromParent);
  530. /// Returns data-sharing attributes for the specified declaration.
  531. const DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent) const;
  532. /// Returns data-sharing attributes for the specified declaration.
  533. const DSAVarData getImplicitDSA(ValueDecl *D, unsigned Level) const;
  534. /// Checks if the specified variables has data-sharing attributes which
  535. /// match specified \a CPred predicate in any directive which matches \a DPred
  536. /// predicate.
  537. const DSAVarData
  538. hasDSA(ValueDecl *D,
  539. const llvm::function_ref<bool(OpenMPClauseKind, bool)> CPred,
  540. const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
  541. bool FromParent) const;
  542. /// Checks if the specified variables has data-sharing attributes which
  543. /// match specified \a CPred predicate in any innermost directive which
  544. /// matches \a DPred predicate.
  545. const DSAVarData
  546. hasInnermostDSA(ValueDecl *D,
  547. const llvm::function_ref<bool(OpenMPClauseKind, bool)> CPred,
  548. const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
  549. bool FromParent) const;
  550. /// Checks if the specified variables has explicit data-sharing
  551. /// attributes which match specified \a CPred predicate at the specified
  552. /// OpenMP region.
  553. bool
  554. hasExplicitDSA(const ValueDecl *D,
  555. const llvm::function_ref<bool(OpenMPClauseKind, bool)> CPred,
  556. unsigned Level, bool NotLastprivate = false) const;
  557. /// Returns true if the directive at level \Level matches in the
  558. /// specified \a DPred predicate.
  559. bool hasExplicitDirective(
  560. const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
  561. unsigned Level) const;
  562. /// Finds a directive which matches specified \a DPred predicate.
  563. bool hasDirective(
  564. const llvm::function_ref<bool(
  565. OpenMPDirectiveKind, const DeclarationNameInfo &, SourceLocation)>
  566. DPred,
  567. bool FromParent) const;
  568. /// Returns currently analyzed directive.
  569. OpenMPDirectiveKind getCurrentDirective() const {
  570. const SharingMapTy *Top = getTopOfStackOrNull();
  571. return Top ? Top->Directive : OMPD_unknown;
  572. }
  573. /// Returns directive kind at specified level.
  574. OpenMPDirectiveKind getDirective(unsigned Level) const {
  575. assert(!isStackEmpty() && "No directive at specified level.");
  576. return getStackElemAtLevel(Level).Directive;
  577. }
  578. /// Returns the capture region at the specified level.
  579. OpenMPDirectiveKind getCaptureRegion(unsigned Level,
  580. unsigned OpenMPCaptureLevel) const {
  581. SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
  582. getOpenMPCaptureRegions(CaptureRegions, getDirective(Level));
  583. return CaptureRegions[OpenMPCaptureLevel];
  584. }
  585. /// Returns parent directive.
  586. OpenMPDirectiveKind getParentDirective() const {
  587. const SharingMapTy *Parent = getSecondOnStackOrNull();
  588. return Parent ? Parent->Directive : OMPD_unknown;
  589. }
  590. /// Add requires decl to internal vector
  591. void addRequiresDecl(OMPRequiresDecl *RD) { RequiresDecls.push_back(RD); }
  592. /// Checks if the defined 'requires' directive has specified type of clause.
  593. template <typename ClauseType> bool hasRequiresDeclWithClause() const {
  594. return llvm::any_of(RequiresDecls, [](const OMPRequiresDecl *D) {
  595. return llvm::any_of(D->clauselists(), [](const OMPClause *C) {
  596. return isa<ClauseType>(C);
  597. });
  598. });
  599. }
  600. /// Checks for a duplicate clause amongst previously declared requires
  601. /// directives
  602. bool hasDuplicateRequiresClause(ArrayRef<OMPClause *> ClauseList) const {
  603. bool IsDuplicate = false;
  604. for (OMPClause *CNew : ClauseList) {
  605. for (const OMPRequiresDecl *D : RequiresDecls) {
  606. for (const OMPClause *CPrev : D->clauselists()) {
  607. if (CNew->getClauseKind() == CPrev->getClauseKind()) {
  608. SemaRef.Diag(CNew->getBeginLoc(),
  609. diag::err_omp_requires_clause_redeclaration)
  610. << getOpenMPClauseName(CNew->getClauseKind());
  611. SemaRef.Diag(CPrev->getBeginLoc(),
  612. diag::note_omp_requires_previous_clause)
  613. << getOpenMPClauseName(CPrev->getClauseKind());
  614. IsDuplicate = true;
  615. }
  616. }
  617. }
  618. }
  619. return IsDuplicate;
  620. }
  621. /// Add location of previously encountered target to internal vector
  622. void addTargetDirLocation(SourceLocation LocStart) {
  623. TargetLocations.push_back(LocStart);
  624. }
  625. /// Add location for the first encountered atomicc directive.
  626. void addAtomicDirectiveLoc(SourceLocation Loc) {
  627. if (AtomicLocation.isInvalid())
  628. AtomicLocation = Loc;
  629. }
  630. /// Returns the location of the first encountered atomic directive in the
  631. /// module.
  632. SourceLocation getAtomicDirectiveLoc() const { return AtomicLocation; }
  633. // Return previously encountered target region locations.
  634. ArrayRef<SourceLocation> getEncounteredTargetLocs() const {
  635. return TargetLocations;
  636. }
  637. /// Set default data sharing attribute to none.
  638. void setDefaultDSANone(SourceLocation Loc) {
  639. getTopOfStack().DefaultAttr = DSA_none;
  640. getTopOfStack().DefaultAttrLoc = Loc;
  641. }
  642. /// Set default data sharing attribute to shared.
  643. void setDefaultDSAShared(SourceLocation Loc) {
  644. getTopOfStack().DefaultAttr = DSA_shared;
  645. getTopOfStack().DefaultAttrLoc = Loc;
  646. }
  647. /// Set default data sharing attribute to firstprivate.
  648. void setDefaultDSAFirstPrivate(SourceLocation Loc) {
  649. getTopOfStack().DefaultAttr = DSA_firstprivate;
  650. getTopOfStack().DefaultAttrLoc = Loc;
  651. }
  652. /// Set default data mapping attribute to Modifier:Kind
  653. void setDefaultDMAAttr(OpenMPDefaultmapClauseModifier M,
  654. OpenMPDefaultmapClauseKind Kind, SourceLocation Loc) {
  655. DefaultmapInfo &DMI = getTopOfStack().DefaultmapMap[Kind];
  656. DMI.ImplicitBehavior = M;
  657. DMI.SLoc = Loc;
  658. }
  659. /// Check whether the implicit-behavior has been set in defaultmap
  660. bool checkDefaultmapCategory(OpenMPDefaultmapClauseKind VariableCategory) {
  661. if (VariableCategory == OMPC_DEFAULTMAP_unknown)
  662. return getTopOfStack()
  663. .DefaultmapMap[OMPC_DEFAULTMAP_aggregate]
  664. .ImplicitBehavior != OMPC_DEFAULTMAP_MODIFIER_unknown ||
  665. getTopOfStack()
  666. .DefaultmapMap[OMPC_DEFAULTMAP_scalar]
  667. .ImplicitBehavior != OMPC_DEFAULTMAP_MODIFIER_unknown ||
  668. getTopOfStack()
  669. .DefaultmapMap[OMPC_DEFAULTMAP_pointer]
  670. .ImplicitBehavior != OMPC_DEFAULTMAP_MODIFIER_unknown;
  671. return getTopOfStack().DefaultmapMap[VariableCategory].ImplicitBehavior !=
  672. OMPC_DEFAULTMAP_MODIFIER_unknown;
  673. }
  674. ArrayRef<llvm::omp::TraitProperty> getConstructTraits() {
  675. return ConstructTraits;
  676. }
  677. void handleConstructTrait(ArrayRef<llvm::omp::TraitProperty> Traits,
  678. bool ScopeEntry) {
  679. if (ScopeEntry)
  680. ConstructTraits.append(Traits.begin(), Traits.end());
  681. else
  682. for (llvm::omp::TraitProperty Trait : llvm::reverse(Traits)) {
  683. llvm::omp::TraitProperty Top = ConstructTraits.pop_back_val();
  684. assert(Top == Trait && "Something left a trait on the stack!");
  685. (void)Trait;
  686. (void)Top;
  687. }
  688. }
  689. DefaultDataSharingAttributes getDefaultDSA(unsigned Level) const {
  690. return getStackSize() <= Level ? DSA_unspecified
  691. : getStackElemAtLevel(Level).DefaultAttr;
  692. }
  693. DefaultDataSharingAttributes getDefaultDSA() const {
  694. return isStackEmpty() ? DSA_unspecified : getTopOfStack().DefaultAttr;
  695. }
  696. SourceLocation getDefaultDSALocation() const {
  697. return isStackEmpty() ? SourceLocation() : getTopOfStack().DefaultAttrLoc;
  698. }
  699. OpenMPDefaultmapClauseModifier
  700. getDefaultmapModifier(OpenMPDefaultmapClauseKind Kind) const {
  701. return isStackEmpty()
  702. ? OMPC_DEFAULTMAP_MODIFIER_unknown
  703. : getTopOfStack().DefaultmapMap[Kind].ImplicitBehavior;
  704. }
  705. OpenMPDefaultmapClauseModifier
  706. getDefaultmapModifierAtLevel(unsigned Level,
  707. OpenMPDefaultmapClauseKind Kind) const {
  708. return getStackElemAtLevel(Level).DefaultmapMap[Kind].ImplicitBehavior;
  709. }
  710. bool isDefaultmapCapturedByRef(unsigned Level,
  711. OpenMPDefaultmapClauseKind Kind) const {
  712. OpenMPDefaultmapClauseModifier M =
  713. getDefaultmapModifierAtLevel(Level, Kind);
  714. if (Kind == OMPC_DEFAULTMAP_scalar || Kind == OMPC_DEFAULTMAP_pointer) {
  715. return (M == OMPC_DEFAULTMAP_MODIFIER_alloc) ||
  716. (M == OMPC_DEFAULTMAP_MODIFIER_to) ||
  717. (M == OMPC_DEFAULTMAP_MODIFIER_from) ||
  718. (M == OMPC_DEFAULTMAP_MODIFIER_tofrom);
  719. }
  720. return true;
  721. }
  722. static bool mustBeFirstprivateBase(OpenMPDefaultmapClauseModifier M,
  723. OpenMPDefaultmapClauseKind Kind) {
  724. switch (Kind) {
  725. case OMPC_DEFAULTMAP_scalar:
  726. case OMPC_DEFAULTMAP_pointer:
  727. return (M == OMPC_DEFAULTMAP_MODIFIER_unknown) ||
  728. (M == OMPC_DEFAULTMAP_MODIFIER_firstprivate) ||
  729. (M == OMPC_DEFAULTMAP_MODIFIER_default);
  730. case OMPC_DEFAULTMAP_aggregate:
  731. return M == OMPC_DEFAULTMAP_MODIFIER_firstprivate;
  732. default:
  733. break;
  734. }
  735. llvm_unreachable("Unexpected OpenMPDefaultmapClauseKind enum");
  736. }
  737. bool mustBeFirstprivateAtLevel(unsigned Level,
  738. OpenMPDefaultmapClauseKind Kind) const {
  739. OpenMPDefaultmapClauseModifier M =
  740. getDefaultmapModifierAtLevel(Level, Kind);
  741. return mustBeFirstprivateBase(M, Kind);
  742. }
  743. bool mustBeFirstprivate(OpenMPDefaultmapClauseKind Kind) const {
  744. OpenMPDefaultmapClauseModifier M = getDefaultmapModifier(Kind);
  745. return mustBeFirstprivateBase(M, Kind);
  746. }
  747. /// Checks if the specified variable is a threadprivate.
  748. bool isThreadPrivate(VarDecl *D) {
  749. const DSAVarData DVar = getTopDSA(D, false);
  750. return isOpenMPThreadPrivate(DVar.CKind);
  751. }
  752. /// Marks current region as ordered (it has an 'ordered' clause).
  753. void setOrderedRegion(bool IsOrdered, const Expr *Param,
  754. OMPOrderedClause *Clause) {
  755. if (IsOrdered)
  756. getTopOfStack().OrderedRegion.emplace(Param, Clause);
  757. else
  758. getTopOfStack().OrderedRegion.reset();
  759. }
  760. /// Returns true, if region is ordered (has associated 'ordered' clause),
  761. /// false - otherwise.
  762. bool isOrderedRegion() const {
  763. if (const SharingMapTy *Top = getTopOfStackOrNull())
  764. return Top->OrderedRegion.hasValue();
  765. return false;
  766. }
  767. /// Returns optional parameter for the ordered region.
  768. std::pair<const Expr *, OMPOrderedClause *> getOrderedRegionParam() const {
  769. if (const SharingMapTy *Top = getTopOfStackOrNull())
  770. if (Top->OrderedRegion.hasValue())
  771. return Top->OrderedRegion.getValue();
  772. return std::make_pair(nullptr, nullptr);
  773. }
  774. /// Returns true, if parent region is ordered (has associated
  775. /// 'ordered' clause), false - otherwise.
  776. bool isParentOrderedRegion() const {
  777. if (const SharingMapTy *Parent = getSecondOnStackOrNull())
  778. return Parent->OrderedRegion.hasValue();
  779. return false;
  780. }
  781. /// Returns optional parameter for the ordered region.
  782. std::pair<const Expr *, OMPOrderedClause *>
  783. getParentOrderedRegionParam() const {
  784. if (const SharingMapTy *Parent = getSecondOnStackOrNull())
  785. if (Parent->OrderedRegion.hasValue())
  786. return Parent->OrderedRegion.getValue();
  787. return std::make_pair(nullptr, nullptr);
  788. }
  789. /// Marks current region as nowait (it has a 'nowait' clause).
  790. void setNowaitRegion(bool IsNowait = true) {
  791. getTopOfStack().NowaitRegion = IsNowait;
  792. }
  793. /// Returns true, if parent region is nowait (has associated
  794. /// 'nowait' clause), false - otherwise.
  795. bool isParentNowaitRegion() const {
  796. if (const SharingMapTy *Parent = getSecondOnStackOrNull())
  797. return Parent->NowaitRegion;
  798. return false;
  799. }
  800. /// Marks parent region as cancel region.
  801. void setParentCancelRegion(bool Cancel = true) {
  802. if (SharingMapTy *Parent = getSecondOnStackOrNull())
  803. Parent->CancelRegion |= Cancel;
  804. }
  805. /// Return true if current region has inner cancel construct.
  806. bool isCancelRegion() const {
  807. const SharingMapTy *Top = getTopOfStackOrNull();
  808. return Top ? Top->CancelRegion : false;
  809. }
  810. /// Mark that parent region already has scan directive.
  811. void setParentHasScanDirective(SourceLocation Loc) {
  812. if (SharingMapTy *Parent = getSecondOnStackOrNull())
  813. Parent->PrevScanLocation = Loc;
  814. }
  815. /// Return true if current region has inner cancel construct.
  816. bool doesParentHasScanDirective() const {
  817. const SharingMapTy *Top = getSecondOnStackOrNull();
  818. return Top ? Top->PrevScanLocation.isValid() : false;
  819. }
  820. /// Return true if current region has inner cancel construct.
  821. SourceLocation getParentScanDirectiveLoc() const {
  822. const SharingMapTy *Top = getSecondOnStackOrNull();
  823. return Top ? Top->PrevScanLocation : SourceLocation();
  824. }
  825. /// Mark that parent region already has ordered directive.
  826. void setParentHasOrderedDirective(SourceLocation Loc) {
  827. if (SharingMapTy *Parent = getSecondOnStackOrNull())
  828. Parent->PrevOrderedLocation = Loc;
  829. }
  830. /// Return true if current region has inner ordered construct.
  831. bool doesParentHasOrderedDirective() const {
  832. const SharingMapTy *Top = getSecondOnStackOrNull();
  833. return Top ? Top->PrevOrderedLocation.isValid() : false;
  834. }
  835. /// Returns the location of the previously specified ordered directive.
  836. SourceLocation getParentOrderedDirectiveLoc() const {
  837. const SharingMapTy *Top = getSecondOnStackOrNull();
  838. return Top ? Top->PrevOrderedLocation : SourceLocation();
  839. }
  840. /// Set collapse value for the region.
  841. void setAssociatedLoops(unsigned Val) {
  842. getTopOfStack().AssociatedLoops = Val;
  843. if (Val > 1)
  844. getTopOfStack().HasMutipleLoops = true;
  845. }
  846. /// Return collapse value for region.
  847. unsigned getAssociatedLoops() const {
  848. const SharingMapTy *Top = getTopOfStackOrNull();
  849. return Top ? Top->AssociatedLoops : 0;
  850. }
  851. /// Returns true if the construct is associated with multiple loops.
  852. bool hasMutipleLoops() const {
  853. const SharingMapTy *Top = getTopOfStackOrNull();
  854. return Top ? Top->HasMutipleLoops : false;
  855. }
  856. /// Marks current target region as one with closely nested teams
  857. /// region.
  858. void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
  859. if (SharingMapTy *Parent = getSecondOnStackOrNull())
  860. Parent->InnerTeamsRegionLoc = TeamsRegionLoc;
  861. }
  862. /// Returns true, if current region has closely nested teams region.
  863. bool hasInnerTeamsRegion() const {
  864. return getInnerTeamsRegionLoc().isValid();
  865. }
  866. /// Returns location of the nested teams region (if any).
  867. SourceLocation getInnerTeamsRegionLoc() const {
  868. const SharingMapTy *Top = getTopOfStackOrNull();
  869. return Top ? Top->InnerTeamsRegionLoc : SourceLocation();
  870. }
  871. Scope *getCurScope() const {
  872. const SharingMapTy *Top = getTopOfStackOrNull();
  873. return Top ? Top->CurScope : nullptr;
  874. }
  875. void setContext(DeclContext *DC) { getTopOfStack().Context = DC; }
  876. SourceLocation getConstructLoc() const {
  877. const SharingMapTy *Top = getTopOfStackOrNull();
  878. return Top ? Top->ConstructLoc : SourceLocation();
  879. }
  880. /// Do the check specified in \a Check to all component lists and return true
  881. /// if any issue is found.
  882. bool checkMappableExprComponentListsForDecl(
  883. const ValueDecl *VD, bool CurrentRegionOnly,
  884. const llvm::function_ref<
  885. bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
  886. OpenMPClauseKind)>
  887. Check) const {
  888. if (isStackEmpty())
  889. return false;
  890. auto SI = begin();
  891. auto SE = end();
  892. if (SI == SE)
  893. return false;
  894. if (CurrentRegionOnly)
  895. SE = std::next(SI);
  896. else
  897. std::advance(SI, 1);
  898. for (; SI != SE; ++SI) {
  899. auto MI = SI->MappedExprComponents.find(VD);
  900. if (MI != SI->MappedExprComponents.end())
  901. for (OMPClauseMappableExprCommon::MappableExprComponentListRef L :
  902. MI->second.Components)
  903. if (Check(L, MI->second.Kind))
  904. return true;
  905. }
  906. return false;
  907. }
  908. /// Do the check specified in \a Check to all component lists at a given level
  909. /// and return true if any issue is found.
  910. bool checkMappableExprComponentListsForDeclAtLevel(
  911. const ValueDecl *VD, unsigned Level,
  912. const llvm::function_ref<
  913. bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
  914. OpenMPClauseKind)>
  915. Check) const {
  916. if (getStackSize() <= Level)
  917. return false;
  918. const SharingMapTy &StackElem = getStackElemAtLevel(Level);
  919. auto MI = StackElem.MappedExprComponents.find(VD);
  920. if (MI != StackElem.MappedExprComponents.end())
  921. for (OMPClauseMappableExprCommon::MappableExprComponentListRef L :
  922. MI->second.Components)
  923. if (Check(L, MI->second.Kind))
  924. return true;
  925. return false;
  926. }
  927. /// Create a new mappable expression component list associated with a given
  928. /// declaration and initialize it with the provided list of components.
  929. void addMappableExpressionComponents(
  930. const ValueDecl *VD,
  931. OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
  932. OpenMPClauseKind WhereFoundClauseKind) {
  933. MappedExprComponentTy &MEC = getTopOfStack().MappedExprComponents[VD];
  934. // Create new entry and append the new components there.
  935. MEC.Components.resize(MEC.Components.size() + 1);
  936. MEC.Components.back().append(Components.begin(), Components.end());
  937. MEC.Kind = WhereFoundClauseKind;
  938. }
  939. unsigned getNestingLevel() const {
  940. assert(!isStackEmpty());
  941. return getStackSize() - 1;
  942. }
  943. void addDoacrossDependClause(OMPDependClause *C,
  944. const OperatorOffsetTy &OpsOffs) {
  945. SharingMapTy *Parent = getSecondOnStackOrNull();
  946. assert(Parent && isOpenMPWorksharingDirective(Parent->Directive));
  947. Parent->DoacrossDepends.try_emplace(C, OpsOffs);
  948. }
  949. llvm::iterator_range<DoacrossDependMapTy::const_iterator>
  950. getDoacrossDependClauses() const {
  951. const SharingMapTy &StackElem = getTopOfStack();
  952. if (isOpenMPWorksharingDirective(StackElem.Directive)) {
  953. const DoacrossDependMapTy &Ref = StackElem.DoacrossDepends;
  954. return llvm::make_range(Ref.begin(), Ref.end());
  955. }
  956. return llvm::make_range(StackElem.DoacrossDepends.end(),
  957. StackElem.DoacrossDepends.end());
  958. }
  959. // Store types of classes which have been explicitly mapped
  960. void addMappedClassesQualTypes(QualType QT) {
  961. SharingMapTy &StackElem = getTopOfStack();
  962. StackElem.MappedClassesQualTypes.insert(QT);
  963. }
  964. // Return set of mapped classes types
  965. bool isClassPreviouslyMapped(QualType QT) const {
  966. const SharingMapTy &StackElem = getTopOfStack();
  967. return StackElem.MappedClassesQualTypes.contains(QT);
  968. }
  969. /// Adds global declare target to the parent target region.
  970. void addToParentTargetRegionLinkGlobals(DeclRefExpr *E) {
  971. assert(*OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(
  972. E->getDecl()) == OMPDeclareTargetDeclAttr::MT_Link &&
  973. "Expected declare target link global.");
  974. for (auto &Elem : *this) {
  975. if (isOpenMPTargetExecutionDirective(Elem.Directive)) {
  976. Elem.DeclareTargetLinkVarDecls.push_back(E);
  977. return;
  978. }
  979. }
  980. }
  981. /// Returns the list of globals with declare target link if current directive
  982. /// is target.
  983. ArrayRef<DeclRefExpr *> getLinkGlobals() const {
  984. assert(isOpenMPTargetExecutionDirective(getCurrentDirective()) &&
  985. "Expected target executable directive.");
  986. return getTopOfStack().DeclareTargetLinkVarDecls;
  987. }
  988. /// Adds list of allocators expressions.
  989. void addInnerAllocatorExpr(Expr *E) {
  990. getTopOfStack().InnerUsedAllocators.push_back(E);
  991. }
  992. /// Return list of used allocators.
  993. ArrayRef<Expr *> getInnerAllocators() const {
  994. return getTopOfStack().InnerUsedAllocators;
  995. }
  996. /// Marks the declaration as implicitly firstprivate nin the task-based
  997. /// regions.
  998. void addImplicitTaskFirstprivate(unsigned Level, Decl *D) {
  999. getStackElemAtLevel(Level).ImplicitTaskFirstprivates.insert(D);
  1000. }
  1001. /// Checks if the decl is implicitly firstprivate in the task-based region.
  1002. bool isImplicitTaskFirstprivate(Decl *D) const {
  1003. return getTopOfStack().ImplicitTaskFirstprivates.contains(D);
  1004. }
  1005. /// Marks decl as used in uses_allocators clause as the allocator.
  1006. void addUsesAllocatorsDecl(const Decl *D, UsesAllocatorsDeclKind Kind) {
  1007. getTopOfStack().UsesAllocatorsDecls.try_emplace(D, Kind);
  1008. }
  1009. /// Checks if specified decl is used in uses allocator clause as the
  1010. /// allocator.
  1011. Optional<UsesAllocatorsDeclKind> isUsesAllocatorsDecl(unsigned Level,
  1012. const Decl *D) const {
  1013. const SharingMapTy &StackElem = getTopOfStack();
  1014. auto I = StackElem.UsesAllocatorsDecls.find(D);
  1015. if (I == StackElem.UsesAllocatorsDecls.end())
  1016. return None;
  1017. return I->getSecond();
  1018. }
  1019. Optional<UsesAllocatorsDeclKind> isUsesAllocatorsDecl(const Decl *D) const {
  1020. const SharingMapTy &StackElem = getTopOfStack();
  1021. auto I = StackElem.UsesAllocatorsDecls.find(D);
  1022. if (I == StackElem.UsesAllocatorsDecls.end())
  1023. return None;
  1024. return I->getSecond();
  1025. }
  1026. void addDeclareMapperVarRef(Expr *Ref) {
  1027. SharingMapTy &StackElem = getTopOfStack();
  1028. StackElem.DeclareMapperVar = Ref;
  1029. }
  1030. const Expr *getDeclareMapperVarRef() const {
  1031. const SharingMapTy *Top = getTopOfStackOrNull();
  1032. return Top ? Top->DeclareMapperVar : nullptr;
  1033. }
  1034. };
  1035. bool isImplicitTaskingRegion(OpenMPDirectiveKind DKind) {
  1036. return isOpenMPParallelDirective(DKind) || isOpenMPTeamsDirective(DKind);
  1037. }
  1038. bool isImplicitOrExplicitTaskingRegion(OpenMPDirectiveKind DKind) {
  1039. return isImplicitTaskingRegion(DKind) || isOpenMPTaskingDirective(DKind) ||
  1040. DKind == OMPD_unknown;
  1041. }
  1042. } // namespace
  1043. static const Expr *getExprAsWritten(const Expr *E) {
  1044. if (const auto *FE = dyn_cast<FullExpr>(E))
  1045. E = FE->getSubExpr();
  1046. if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
  1047. E = MTE->getSubExpr();
  1048. while (const auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
  1049. E = Binder->getSubExpr();
  1050. if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
  1051. E = ICE->getSubExprAsWritten();
  1052. return E->IgnoreParens();
  1053. }
  1054. static Expr *getExprAsWritten(Expr *E) {
  1055. return const_cast<Expr *>(getExprAsWritten(const_cast<const Expr *>(E)));
  1056. }
  1057. static const ValueDecl *getCanonicalDecl(const ValueDecl *D) {
  1058. if (const auto *CED = dyn_cast<OMPCapturedExprDecl>(D))
  1059. if (const auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
  1060. D = ME->getMemberDecl();
  1061. const auto *VD = dyn_cast<VarDecl>(D);
  1062. const auto *FD = dyn_cast<FieldDecl>(D);
  1063. if (VD != nullptr) {
  1064. VD = VD->getCanonicalDecl();
  1065. D = VD;
  1066. } else {
  1067. assert(FD);
  1068. FD = FD->getCanonicalDecl();
  1069. D = FD;
  1070. }
  1071. return D;
  1072. }
  1073. static ValueDecl *getCanonicalDecl(ValueDecl *D) {
  1074. return const_cast<ValueDecl *>(
  1075. getCanonicalDecl(const_cast<const ValueDecl *>(D)));
  1076. }
  1077. DSAStackTy::DSAVarData DSAStackTy::getDSA(const_iterator &Iter,
  1078. ValueDecl *D) const {
  1079. D = getCanonicalDecl(D);
  1080. auto *VD = dyn_cast<VarDecl>(D);
  1081. const auto *FD = dyn_cast<FieldDecl>(D);
  1082. DSAVarData DVar;
  1083. if (Iter == end()) {
  1084. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  1085. // in a region but not in construct]
  1086. // File-scope or namespace-scope variables referenced in called routines
  1087. // in the region are shared unless they appear in a threadprivate
  1088. // directive.
  1089. if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(VD))
  1090. DVar.CKind = OMPC_shared;
  1091. // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
  1092. // in a region but not in construct]
  1093. // Variables with static storage duration that are declared in called
  1094. // routines in the region are shared.
  1095. if (VD && VD->hasGlobalStorage())
  1096. DVar.CKind = OMPC_shared;
  1097. // Non-static data members are shared by default.
  1098. if (FD)
  1099. DVar.CKind = OMPC_shared;
  1100. return DVar;
  1101. }
  1102. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  1103. // in a Construct, C/C++, predetermined, p.1]
  1104. // Variables with automatic storage duration that are declared in a scope
  1105. // inside the construct are private.
  1106. if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() &&
  1107. (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) {
  1108. DVar.CKind = OMPC_private;
  1109. return DVar;
  1110. }
  1111. DVar.DKind = Iter->Directive;
  1112. // Explicitly specified attributes and local variables with predetermined
  1113. // attributes.
  1114. if (Iter->SharingMap.count(D)) {
  1115. const DSAInfo &Data = Iter->SharingMap.lookup(D);
  1116. DVar.RefExpr = Data.RefExpr.getPointer();
  1117. DVar.PrivateCopy = Data.PrivateCopy;
  1118. DVar.CKind = Data.Attributes;
  1119. DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
  1120. DVar.Modifier = Data.Modifier;
  1121. DVar.AppliedToPointee = Data.AppliedToPointee;
  1122. return DVar;
  1123. }
  1124. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  1125. // in a Construct, C/C++, implicitly determined, p.1]
  1126. // In a parallel or task construct, the data-sharing attributes of these
  1127. // variables are determined by the default clause, if present.
  1128. switch (Iter->DefaultAttr) {
  1129. case DSA_shared:
  1130. DVar.CKind = OMPC_shared;
  1131. DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
  1132. return DVar;
  1133. case DSA_none:
  1134. return DVar;
  1135. case DSA_firstprivate:
  1136. if (VD->getStorageDuration() == SD_Static &&
  1137. VD->getDeclContext()->isFileContext()) {
  1138. DVar.CKind = OMPC_unknown;
  1139. } else {
  1140. DVar.CKind = OMPC_firstprivate;
  1141. }
  1142. DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
  1143. return DVar;
  1144. case DSA_unspecified:
  1145. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  1146. // in a Construct, implicitly determined, p.2]
  1147. // In a parallel construct, if no default clause is present, these
  1148. // variables are shared.
  1149. DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
  1150. if ((isOpenMPParallelDirective(DVar.DKind) &&
  1151. !isOpenMPTaskLoopDirective(DVar.DKind)) ||
  1152. isOpenMPTeamsDirective(DVar.DKind)) {
  1153. DVar.CKind = OMPC_shared;
  1154. return DVar;
  1155. }
  1156. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  1157. // in a Construct, implicitly determined, p.4]
  1158. // In a task construct, if no default clause is present, a variable that in
  1159. // the enclosing context is determined to be shared by all implicit tasks
  1160. // bound to the current team is shared.
  1161. if (isOpenMPTaskingDirective(DVar.DKind)) {
  1162. DSAVarData DVarTemp;
  1163. const_iterator I = Iter, E = end();
  1164. do {
  1165. ++I;
  1166. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
  1167. // Referenced in a Construct, implicitly determined, p.6]
  1168. // In a task construct, if no default clause is present, a variable
  1169. // whose data-sharing attribute is not determined by the rules above is
  1170. // firstprivate.
  1171. DVarTemp = getDSA(I, D);
  1172. if (DVarTemp.CKind != OMPC_shared) {
  1173. DVar.RefExpr = nullptr;
  1174. DVar.CKind = OMPC_firstprivate;
  1175. return DVar;
  1176. }
  1177. } while (I != E && !isImplicitTaskingRegion(I->Directive));
  1178. DVar.CKind =
  1179. (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
  1180. return DVar;
  1181. }
  1182. }
  1183. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  1184. // in a Construct, implicitly determined, p.3]
  1185. // For constructs other than task, if no default clause is present, these
  1186. // variables inherit their data-sharing attributes from the enclosing
  1187. // context.
  1188. return getDSA(++Iter, D);
  1189. }
  1190. const Expr *DSAStackTy::addUniqueAligned(const ValueDecl *D,
  1191. const Expr *NewDE) {
  1192. assert(!isStackEmpty() && "Data sharing attributes stack is empty");
  1193. D = getCanonicalDecl(D);
  1194. SharingMapTy &StackElem = getTopOfStack();
  1195. auto It = StackElem.AlignedMap.find(D);
  1196. if (It == StackElem.AlignedMap.end()) {
  1197. assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
  1198. StackElem.AlignedMap[D] = NewDE;
  1199. return nullptr;
  1200. }
  1201. assert(It->second && "Unexpected nullptr expr in the aligned map");
  1202. return It->second;
  1203. }
  1204. const Expr *DSAStackTy::addUniqueNontemporal(const ValueDecl *D,
  1205. const Expr *NewDE) {
  1206. assert(!isStackEmpty() && "Data sharing attributes stack is empty");
  1207. D = getCanonicalDecl(D);
  1208. SharingMapTy &StackElem = getTopOfStack();
  1209. auto It = StackElem.NontemporalMap.find(D);
  1210. if (It == StackElem.NontemporalMap.end()) {
  1211. assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
  1212. StackElem.NontemporalMap[D] = NewDE;
  1213. return nullptr;
  1214. }
  1215. assert(It->second && "Unexpected nullptr expr in the aligned map");
  1216. return It->second;
  1217. }
  1218. void DSAStackTy::addLoopControlVariable(const ValueDecl *D, VarDecl *Capture) {
  1219. assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
  1220. D = getCanonicalDecl(D);
  1221. SharingMapTy &StackElem = getTopOfStack();
  1222. StackElem.LCVMap.try_emplace(
  1223. D, LCDeclInfo(StackElem.LCVMap.size() + 1, Capture));
  1224. }
  1225. const DSAStackTy::LCDeclInfo
  1226. DSAStackTy::isLoopControlVariable(const ValueDecl *D) const {
  1227. assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
  1228. D = getCanonicalDecl(D);
  1229. const SharingMapTy &StackElem = getTopOfStack();
  1230. auto It = StackElem.LCVMap.find(D);
  1231. if (It != StackElem.LCVMap.end())
  1232. return It->second;
  1233. return {0, nullptr};
  1234. }
  1235. const DSAStackTy::LCDeclInfo
  1236. DSAStackTy::isLoopControlVariable(const ValueDecl *D, unsigned Level) const {
  1237. assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
  1238. D = getCanonicalDecl(D);
  1239. for (unsigned I = Level + 1; I > 0; --I) {
  1240. const SharingMapTy &StackElem = getStackElemAtLevel(I - 1);
  1241. auto It = StackElem.LCVMap.find(D);
  1242. if (It != StackElem.LCVMap.end())
  1243. return It->second;
  1244. }
  1245. return {0, nullptr};
  1246. }
  1247. const DSAStackTy::LCDeclInfo
  1248. DSAStackTy::isParentLoopControlVariable(const ValueDecl *D) const {
  1249. const SharingMapTy *Parent = getSecondOnStackOrNull();
  1250. assert(Parent && "Data-sharing attributes stack is empty");
  1251. D = getCanonicalDecl(D);
  1252. auto It = Parent->LCVMap.find(D);
  1253. if (It != Parent->LCVMap.end())
  1254. return It->second;
  1255. return {0, nullptr};
  1256. }
  1257. const ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) const {
  1258. const SharingMapTy *Parent = getSecondOnStackOrNull();
  1259. assert(Parent && "Data-sharing attributes stack is empty");
  1260. if (Parent->LCVMap.size() < I)
  1261. return nullptr;
  1262. for (const auto &Pair : Parent->LCVMap)
  1263. if (Pair.second.first == I)
  1264. return Pair.first;
  1265. return nullptr;
  1266. }
  1267. void DSAStackTy::addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A,
  1268. DeclRefExpr *PrivateCopy, unsigned Modifier,
  1269. bool AppliedToPointee) {
  1270. D = getCanonicalDecl(D);
  1271. if (A == OMPC_threadprivate) {
  1272. DSAInfo &Data = Threadprivates[D];
  1273. Data.Attributes = A;
  1274. Data.RefExpr.setPointer(E);
  1275. Data.PrivateCopy = nullptr;
  1276. Data.Modifier = Modifier;
  1277. } else {
  1278. DSAInfo &Data = getTopOfStack().SharingMap[D];
  1279. assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) ||
  1280. (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) ||
  1281. (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) ||
  1282. (isLoopControlVariable(D).first && A == OMPC_private));
  1283. Data.Modifier = Modifier;
  1284. if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) {
  1285. Data.RefExpr.setInt(/*IntVal=*/true);
  1286. return;
  1287. }
  1288. const bool IsLastprivate =
  1289. A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate;
  1290. Data.Attributes = A;
  1291. Data.RefExpr.setPointerAndInt(E, IsLastprivate);
  1292. Data.PrivateCopy = PrivateCopy;
  1293. Data.AppliedToPointee = AppliedToPointee;
  1294. if (PrivateCopy) {
  1295. DSAInfo &Data = getTopOfStack().SharingMap[PrivateCopy->getDecl()];
  1296. Data.Modifier = Modifier;
  1297. Data.Attributes = A;
  1298. Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate);
  1299. Data.PrivateCopy = nullptr;
  1300. Data.AppliedToPointee = AppliedToPointee;
  1301. }
  1302. }
  1303. }
  1304. /// Build a variable declaration for OpenMP loop iteration variable.
  1305. static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
  1306. StringRef Name, const AttrVec *Attrs = nullptr,
  1307. DeclRefExpr *OrigRef = nullptr) {
  1308. DeclContext *DC = SemaRef.CurContext;
  1309. IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
  1310. TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
  1311. auto *Decl =
  1312. VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
  1313. if (Attrs) {
  1314. for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end());
  1315. I != E; ++I)
  1316. Decl->addAttr(*I);
  1317. }
  1318. Decl->setImplicit();
  1319. if (OrigRef) {
  1320. Decl->addAttr(
  1321. OMPReferencedVarAttr::CreateImplicit(SemaRef.Context, OrigRef));
  1322. }
  1323. return Decl;
  1324. }
  1325. static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
  1326. SourceLocation Loc,
  1327. bool RefersToCapture = false) {
  1328. D->setReferenced();
  1329. D->markUsed(S.Context);
  1330. return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
  1331. SourceLocation(), D, RefersToCapture, Loc, Ty,
  1332. VK_LValue);
  1333. }
  1334. void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
  1335. BinaryOperatorKind BOK) {
  1336. D = getCanonicalDecl(D);
  1337. assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
  1338. assert(
  1339. getTopOfStack().SharingMap[D].Attributes == OMPC_reduction &&
  1340. "Additional reduction info may be specified only for reduction items.");
  1341. ReductionData &ReductionData = getTopOfStack().ReductionMap[D];
  1342. assert(ReductionData.ReductionRange.isInvalid() &&
  1343. (getTopOfStack().Directive == OMPD_taskgroup ||
  1344. ((isOpenMPParallelDirective(getTopOfStack().Directive) ||
  1345. isOpenMPWorksharingDirective(getTopOfStack().Directive)) &&
  1346. !isOpenMPSimdDirective(getTopOfStack().Directive))) &&
  1347. "Additional reduction info may be specified only once for reduction "
  1348. "items.");
  1349. ReductionData.set(BOK, SR);
  1350. Expr *&TaskgroupReductionRef = getTopOfStack().TaskgroupReductionRef;
  1351. if (!TaskgroupReductionRef) {
  1352. VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(),
  1353. SemaRef.Context.VoidPtrTy, ".task_red.");
  1354. TaskgroupReductionRef =
  1355. buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
  1356. }
  1357. }
  1358. void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
  1359. const Expr *ReductionRef) {
  1360. D = getCanonicalDecl(D);
  1361. assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
  1362. assert(
  1363. getTopOfStack().SharingMap[D].Attributes == OMPC_reduction &&
  1364. "Additional reduction info may be specified only for reduction items.");
  1365. ReductionData &ReductionData = getTopOfStack().ReductionMap[D];
  1366. assert(ReductionData.ReductionRange.isInvalid() &&
  1367. (getTopOfStack().Directive == OMPD_taskgroup ||
  1368. ((isOpenMPParallelDirective(getTopOfStack().Directive) ||
  1369. isOpenMPWorksharingDirective(getTopOfStack().Directive)) &&
  1370. !isOpenMPSimdDirective(getTopOfStack().Directive))) &&
  1371. "Additional reduction info may be specified only once for reduction "
  1372. "items.");
  1373. ReductionData.set(ReductionRef, SR);
  1374. Expr *&TaskgroupReductionRef = getTopOfStack().TaskgroupReductionRef;
  1375. if (!TaskgroupReductionRef) {
  1376. VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(),
  1377. SemaRef.Context.VoidPtrTy, ".task_red.");
  1378. TaskgroupReductionRef =
  1379. buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
  1380. }
  1381. }
  1382. const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData(
  1383. const ValueDecl *D, SourceRange &SR, BinaryOperatorKind &BOK,
  1384. Expr *&TaskgroupDescriptor) const {
  1385. D = getCanonicalDecl(D);
  1386. assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
  1387. for (const_iterator I = begin() + 1, E = end(); I != E; ++I) {
  1388. const DSAInfo &Data = I->SharingMap.lookup(D);
  1389. if (Data.Attributes != OMPC_reduction ||
  1390. Data.Modifier != OMPC_REDUCTION_task)
  1391. continue;
  1392. const ReductionData &ReductionData = I->ReductionMap.lookup(D);
  1393. if (!ReductionData.ReductionOp ||
  1394. ReductionData.ReductionOp.is<const Expr *>())
  1395. return DSAVarData();
  1396. SR = ReductionData.ReductionRange;
  1397. BOK = ReductionData.ReductionOp.get<ReductionData::BOKPtrType>();
  1398. assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
  1399. "expression for the descriptor is not "
  1400. "set.");
  1401. TaskgroupDescriptor = I->TaskgroupReductionRef;
  1402. return DSAVarData(I->Directive, OMPC_reduction, Data.RefExpr.getPointer(),
  1403. Data.PrivateCopy, I->DefaultAttrLoc, OMPC_REDUCTION_task,
  1404. /*AppliedToPointee=*/false);
  1405. }
  1406. return DSAVarData();
  1407. }
  1408. const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData(
  1409. const ValueDecl *D, SourceRange &SR, const Expr *&ReductionRef,
  1410. Expr *&TaskgroupDescriptor) const {
  1411. D = getCanonicalDecl(D);
  1412. assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
  1413. for (const_iterator I = begin() + 1, E = end(); I != E; ++I) {
  1414. const DSAInfo &Data = I->SharingMap.lookup(D);
  1415. if (Data.Attributes != OMPC_reduction ||
  1416. Data.Modifier != OMPC_REDUCTION_task)
  1417. continue;
  1418. const ReductionData &ReductionData = I->ReductionMap.lookup(D);
  1419. if (!ReductionData.ReductionOp ||
  1420. !ReductionData.ReductionOp.is<const Expr *>())
  1421. return DSAVarData();
  1422. SR = ReductionData.ReductionRange;
  1423. ReductionRef = ReductionData.ReductionOp.get<const Expr *>();
  1424. assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
  1425. "expression for the descriptor is not "
  1426. "set.");
  1427. TaskgroupDescriptor = I->TaskgroupReductionRef;
  1428. return DSAVarData(I->Directive, OMPC_reduction, Data.RefExpr.getPointer(),
  1429. Data.PrivateCopy, I->DefaultAttrLoc, OMPC_REDUCTION_task,
  1430. /*AppliedToPointee=*/false);
  1431. }
  1432. return DSAVarData();
  1433. }
  1434. bool DSAStackTy::isOpenMPLocal(VarDecl *D, const_iterator I) const {
  1435. D = D->getCanonicalDecl();
  1436. for (const_iterator E = end(); I != E; ++I) {
  1437. if (isImplicitOrExplicitTaskingRegion(I->Directive) ||
  1438. isOpenMPTargetExecutionDirective(I->Directive)) {
  1439. if (I->CurScope) {
  1440. Scope *TopScope = I->CurScope->getParent();
  1441. Scope *CurScope = getCurScope();
  1442. while (CurScope && CurScope != TopScope && !CurScope->isDeclScope(D))
  1443. CurScope = CurScope->getParent();
  1444. return CurScope != TopScope;
  1445. }
  1446. for (DeclContext *DC = D->getDeclContext(); DC; DC = DC->getParent())
  1447. if (I->Context == DC)
  1448. return true;
  1449. return false;
  1450. }
  1451. }
  1452. return false;
  1453. }
  1454. static bool isConstNotMutableType(Sema &SemaRef, QualType Type,
  1455. bool AcceptIfMutable = true,
  1456. bool *IsClassType = nullptr) {
  1457. ASTContext &Context = SemaRef.getASTContext();
  1458. Type = Type.getNonReferenceType().getCanonicalType();
  1459. bool IsConstant = Type.isConstant(Context);
  1460. Type = Context.getBaseElementType(Type);
  1461. const CXXRecordDecl *RD = AcceptIfMutable && SemaRef.getLangOpts().CPlusPlus
  1462. ? Type->getAsCXXRecordDecl()
  1463. : nullptr;
  1464. if (const auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD))
  1465. if (const ClassTemplateDecl *CTD = CTSD->getSpecializedTemplate())
  1466. RD = CTD->getTemplatedDecl();
  1467. if (IsClassType)
  1468. *IsClassType = RD;
  1469. return IsConstant && !(SemaRef.getLangOpts().CPlusPlus && RD &&
  1470. RD->hasDefinition() && RD->hasMutableFields());
  1471. }
  1472. static bool rejectConstNotMutableType(Sema &SemaRef, const ValueDecl *D,
  1473. QualType Type, OpenMPClauseKind CKind,
  1474. SourceLocation ELoc,
  1475. bool AcceptIfMutable = true,
  1476. bool ListItemNotVar = false) {
  1477. ASTContext &Context = SemaRef.getASTContext();
  1478. bool IsClassType;
  1479. if (isConstNotMutableType(SemaRef, Type, AcceptIfMutable, &IsClassType)) {
  1480. unsigned Diag = ListItemNotVar ? diag::err_omp_const_list_item
  1481. : IsClassType ? diag::err_omp_const_not_mutable_variable
  1482. : diag::err_omp_const_variable;
  1483. SemaRef.Diag(ELoc, Diag) << getOpenMPClauseName(CKind);
  1484. if (!ListItemNotVar && D) {
  1485. const VarDecl *VD = dyn_cast<VarDecl>(D);
  1486. bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
  1487. VarDecl::DeclarationOnly;
  1488. SemaRef.Diag(D->getLocation(),
  1489. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  1490. << D;
  1491. }
  1492. return true;
  1493. }
  1494. return false;
  1495. }
  1496. const DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D,
  1497. bool FromParent) {
  1498. D = getCanonicalDecl(D);
  1499. DSAVarData DVar;
  1500. auto *VD = dyn_cast<VarDecl>(D);
  1501. auto TI = Threadprivates.find(D);
  1502. if (TI != Threadprivates.end()) {
  1503. DVar.RefExpr = TI->getSecond().RefExpr.getPointer();
  1504. DVar.CKind = OMPC_threadprivate;
  1505. DVar.Modifier = TI->getSecond().Modifier;
  1506. return DVar;
  1507. }
  1508. if (VD && VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
  1509. DVar.RefExpr = buildDeclRefExpr(
  1510. SemaRef, VD, D->getType().getNonReferenceType(),
  1511. VD->getAttr<OMPThreadPrivateDeclAttr>()->getLocation());
  1512. DVar.CKind = OMPC_threadprivate;
  1513. addDSA(D, DVar.RefExpr, OMPC_threadprivate);
  1514. return DVar;
  1515. }
  1516. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  1517. // in a Construct, C/C++, predetermined, p.1]
  1518. // Variables appearing in threadprivate directives are threadprivate.
  1519. if ((VD && VD->getTLSKind() != VarDecl::TLS_None &&
  1520. !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
  1521. SemaRef.getLangOpts().OpenMPUseTLS &&
  1522. SemaRef.getASTContext().getTargetInfo().isTLSSupported())) ||
  1523. (VD && VD->getStorageClass() == SC_Register &&
  1524. VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) {
  1525. DVar.RefExpr = buildDeclRefExpr(
  1526. SemaRef, VD, D->getType().getNonReferenceType(), D->getLocation());
  1527. DVar.CKind = OMPC_threadprivate;
  1528. addDSA(D, DVar.RefExpr, OMPC_threadprivate);
  1529. return DVar;
  1530. }
  1531. if (SemaRef.getLangOpts().OpenMPCUDAMode && VD &&
  1532. VD->isLocalVarDeclOrParm() && !isStackEmpty() &&
  1533. !isLoopControlVariable(D).first) {
  1534. const_iterator IterTarget =
  1535. std::find_if(begin(), end(), [](const SharingMapTy &Data) {
  1536. return isOpenMPTargetExecutionDirective(Data.Directive);
  1537. });
  1538. if (IterTarget != end()) {
  1539. const_iterator ParentIterTarget = IterTarget + 1;
  1540. for (const_iterator Iter = begin(); Iter != ParentIterTarget; ++Iter) {
  1541. if (isOpenMPLocal(VD, Iter)) {
  1542. DVar.RefExpr =
  1543. buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
  1544. D->getLocation());
  1545. DVar.CKind = OMPC_threadprivate;
  1546. return DVar;
  1547. }
  1548. }
  1549. if (!isClauseParsingMode() || IterTarget != begin()) {
  1550. auto DSAIter = IterTarget->SharingMap.find(D);
  1551. if (DSAIter != IterTarget->SharingMap.end() &&
  1552. isOpenMPPrivate(DSAIter->getSecond().Attributes)) {
  1553. DVar.RefExpr = DSAIter->getSecond().RefExpr.getPointer();
  1554. DVar.CKind = OMPC_threadprivate;
  1555. return DVar;
  1556. }
  1557. const_iterator End = end();
  1558. if (!SemaRef.isOpenMPCapturedByRef(D,
  1559. std::distance(ParentIterTarget, End),
  1560. /*OpenMPCaptureLevel=*/0)) {
  1561. DVar.RefExpr =
  1562. buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
  1563. IterTarget->ConstructLoc);
  1564. DVar.CKind = OMPC_threadprivate;
  1565. return DVar;
  1566. }
  1567. }
  1568. }
  1569. }
  1570. if (isStackEmpty())
  1571. // Not in OpenMP execution region and top scope was already checked.
  1572. return DVar;
  1573. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  1574. // in a Construct, C/C++, predetermined, p.4]
  1575. // Static data members are shared.
  1576. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  1577. // in a Construct, C/C++, predetermined, p.7]
  1578. // Variables with static storage duration that are declared in a scope
  1579. // inside the construct are shared.
  1580. if (VD && VD->isStaticDataMember()) {
  1581. // Check for explicitly specified attributes.
  1582. const_iterator I = begin();
  1583. const_iterator EndI = end();
  1584. if (FromParent && I != EndI)
  1585. ++I;
  1586. if (I != EndI) {
  1587. auto It = I->SharingMap.find(D);
  1588. if (It != I->SharingMap.end()) {
  1589. const DSAInfo &Data = It->getSecond();
  1590. DVar.RefExpr = Data.RefExpr.getPointer();
  1591. DVar.PrivateCopy = Data.PrivateCopy;
  1592. DVar.CKind = Data.Attributes;
  1593. DVar.ImplicitDSALoc = I->DefaultAttrLoc;
  1594. DVar.DKind = I->Directive;
  1595. DVar.Modifier = Data.Modifier;
  1596. DVar.AppliedToPointee = Data.AppliedToPointee;
  1597. return DVar;
  1598. }
  1599. }
  1600. DVar.CKind = OMPC_shared;
  1601. return DVar;
  1602. }
  1603. auto &&MatchesAlways = [](OpenMPDirectiveKind) { return true; };
  1604. // The predetermined shared attribute for const-qualified types having no
  1605. // mutable members was removed after OpenMP 3.1.
  1606. if (SemaRef.LangOpts.OpenMP <= 31) {
  1607. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  1608. // in a Construct, C/C++, predetermined, p.6]
  1609. // Variables with const qualified type having no mutable member are
  1610. // shared.
  1611. if (isConstNotMutableType(SemaRef, D->getType())) {
  1612. // Variables with const-qualified type having no mutable member may be
  1613. // listed in a firstprivate clause, even if they are static data members.
  1614. DSAVarData DVarTemp = hasInnermostDSA(
  1615. D,
  1616. [](OpenMPClauseKind C, bool) {
  1617. return C == OMPC_firstprivate || C == OMPC_shared;
  1618. },
  1619. MatchesAlways, FromParent);
  1620. if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
  1621. return DVarTemp;
  1622. DVar.CKind = OMPC_shared;
  1623. return DVar;
  1624. }
  1625. }
  1626. // Explicitly specified attributes and local variables with predetermined
  1627. // attributes.
  1628. const_iterator I = begin();
  1629. const_iterator EndI = end();
  1630. if (FromParent && I != EndI)
  1631. ++I;
  1632. if (I == EndI)
  1633. return DVar;
  1634. auto It = I->SharingMap.find(D);
  1635. if (It != I->SharingMap.end()) {
  1636. const DSAInfo &Data = It->getSecond();
  1637. DVar.RefExpr = Data.RefExpr.getPointer();
  1638. DVar.PrivateCopy = Data.PrivateCopy;
  1639. DVar.CKind = Data.Attributes;
  1640. DVar.ImplicitDSALoc = I->DefaultAttrLoc;
  1641. DVar.DKind = I->Directive;
  1642. DVar.Modifier = Data.Modifier;
  1643. DVar.AppliedToPointee = Data.AppliedToPointee;
  1644. }
  1645. return DVar;
  1646. }
  1647. const DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
  1648. bool FromParent) const {
  1649. if (isStackEmpty()) {
  1650. const_iterator I;
  1651. return getDSA(I, D);
  1652. }
  1653. D = getCanonicalDecl(D);
  1654. const_iterator StartI = begin();
  1655. const_iterator EndI = end();
  1656. if (FromParent && StartI != EndI)
  1657. ++StartI;
  1658. return getDSA(StartI, D);
  1659. }
  1660. const DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
  1661. unsigned Level) const {
  1662. if (getStackSize() <= Level)
  1663. return DSAVarData();
  1664. D = getCanonicalDecl(D);
  1665. const_iterator StartI = std::next(begin(), getStackSize() - 1 - Level);
  1666. return getDSA(StartI, D);
  1667. }
  1668. const DSAStackTy::DSAVarData
  1669. DSAStackTy::hasDSA(ValueDecl *D,
  1670. const llvm::function_ref<bool(OpenMPClauseKind, bool)> CPred,
  1671. const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
  1672. bool FromParent) const {
  1673. if (isStackEmpty())
  1674. return {};
  1675. D = getCanonicalDecl(D);
  1676. const_iterator I = begin();
  1677. const_iterator EndI = end();
  1678. if (FromParent && I != EndI)
  1679. ++I;
  1680. for (; I != EndI; ++I) {
  1681. if (!DPred(I->Directive) &&
  1682. !isImplicitOrExplicitTaskingRegion(I->Directive))
  1683. continue;
  1684. const_iterator NewI = I;
  1685. DSAVarData DVar = getDSA(NewI, D);
  1686. if (I == NewI && CPred(DVar.CKind, DVar.AppliedToPointee))
  1687. return DVar;
  1688. }
  1689. return {};
  1690. }
  1691. const DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA(
  1692. ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind, bool)> CPred,
  1693. const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
  1694. bool FromParent) const {
  1695. if (isStackEmpty())
  1696. return {};
  1697. D = getCanonicalDecl(D);
  1698. const_iterator StartI = begin();
  1699. const_iterator EndI = end();
  1700. if (FromParent && StartI != EndI)
  1701. ++StartI;
  1702. if (StartI == EndI || !DPred(StartI->Directive))
  1703. return {};
  1704. const_iterator NewI = StartI;
  1705. DSAVarData DVar = getDSA(NewI, D);
  1706. return (NewI == StartI && CPred(DVar.CKind, DVar.AppliedToPointee))
  1707. ? DVar
  1708. : DSAVarData();
  1709. }
  1710. bool DSAStackTy::hasExplicitDSA(
  1711. const ValueDecl *D,
  1712. const llvm::function_ref<bool(OpenMPClauseKind, bool)> CPred,
  1713. unsigned Level, bool NotLastprivate) const {
  1714. if (getStackSize() <= Level)
  1715. return false;
  1716. D = getCanonicalDecl(D);
  1717. const SharingMapTy &StackElem = getStackElemAtLevel(Level);
  1718. auto I = StackElem.SharingMap.find(D);
  1719. if (I != StackElem.SharingMap.end() && I->getSecond().RefExpr.getPointer() &&
  1720. CPred(I->getSecond().Attributes, I->getSecond().AppliedToPointee) &&
  1721. (!NotLastprivate || !I->getSecond().RefExpr.getInt()))
  1722. return true;
  1723. // Check predetermined rules for the loop control variables.
  1724. auto LI = StackElem.LCVMap.find(D);
  1725. if (LI != StackElem.LCVMap.end())
  1726. return CPred(OMPC_private, /*AppliedToPointee=*/false);
  1727. return false;
  1728. }
  1729. bool DSAStackTy::hasExplicitDirective(
  1730. const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
  1731. unsigned Level) const {
  1732. if (getStackSize() <= Level)
  1733. return false;
  1734. const SharingMapTy &StackElem = getStackElemAtLevel(Level);
  1735. return DPred(StackElem.Directive);
  1736. }
  1737. bool DSAStackTy::hasDirective(
  1738. const llvm::function_ref<bool(OpenMPDirectiveKind,
  1739. const DeclarationNameInfo &, SourceLocation)>
  1740. DPred,
  1741. bool FromParent) const {
  1742. // We look only in the enclosing region.
  1743. size_t Skip = FromParent ? 2 : 1;
  1744. for (const_iterator I = begin() + std::min(Skip, getStackSize()), E = end();
  1745. I != E; ++I) {
  1746. if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
  1747. return true;
  1748. }
  1749. return false;
  1750. }
  1751. void Sema::InitDataSharingAttributesStack() {
  1752. VarDataSharingAttributesStack = new DSAStackTy(*this);
  1753. }
  1754. #define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
  1755. void Sema::pushOpenMPFunctionRegion() { DSAStack->pushFunction(); }
  1756. void Sema::popOpenMPFunctionRegion(const FunctionScopeInfo *OldFSI) {
  1757. DSAStack->popFunction(OldFSI);
  1758. }
  1759. static bool isOpenMPDeviceDelayedContext(Sema &S) {
  1760. assert(S.LangOpts.OpenMP && S.LangOpts.OpenMPIsDevice &&
  1761. "Expected OpenMP device compilation.");
  1762. return !S.isInOpenMPTargetExecutionDirective();
  1763. }
  1764. namespace {
  1765. /// Status of the function emission on the host/device.
  1766. enum class FunctionEmissionStatus {
  1767. Emitted,
  1768. Discarded,
  1769. Unknown,
  1770. };
  1771. } // anonymous namespace
  1772. Sema::SemaDiagnosticBuilder Sema::diagIfOpenMPDeviceCode(SourceLocation Loc,
  1773. unsigned DiagID,
  1774. FunctionDecl *FD) {
  1775. assert(LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
  1776. "Expected OpenMP device compilation.");
  1777. SemaDiagnosticBuilder::Kind Kind = SemaDiagnosticBuilder::K_Nop;
  1778. if (FD) {
  1779. FunctionEmissionStatus FES = getEmissionStatus(FD);
  1780. switch (FES) {
  1781. case FunctionEmissionStatus::Emitted:
  1782. Kind = SemaDiagnosticBuilder::K_Immediate;
  1783. break;
  1784. case FunctionEmissionStatus::Unknown:
  1785. // TODO: We should always delay diagnostics here in case a target
  1786. // region is in a function we do not emit. However, as the
  1787. // current diagnostics are associated with the function containing
  1788. // the target region and we do not emit that one, we would miss out
  1789. // on diagnostics for the target region itself. We need to anchor
  1790. // the diagnostics with the new generated function *or* ensure we
  1791. // emit diagnostics associated with the surrounding function.
  1792. Kind = isOpenMPDeviceDelayedContext(*this)
  1793. ? SemaDiagnosticBuilder::K_Deferred
  1794. : SemaDiagnosticBuilder::K_Immediate;
  1795. break;
  1796. case FunctionEmissionStatus::TemplateDiscarded:
  1797. case FunctionEmissionStatus::OMPDiscarded:
  1798. Kind = SemaDiagnosticBuilder::K_Nop;
  1799. break;
  1800. case FunctionEmissionStatus::CUDADiscarded:
  1801. llvm_unreachable("CUDADiscarded unexpected in OpenMP device compilation");
  1802. break;
  1803. }
  1804. }
  1805. return SemaDiagnosticBuilder(Kind, Loc, DiagID, FD, *this);
  1806. }
  1807. Sema::SemaDiagnosticBuilder Sema::diagIfOpenMPHostCode(SourceLocation Loc,
  1808. unsigned DiagID,
  1809. FunctionDecl *FD) {
  1810. assert(LangOpts.OpenMP && !LangOpts.OpenMPIsDevice &&
  1811. "Expected OpenMP host compilation.");
  1812. SemaDiagnosticBuilder::Kind Kind = SemaDiagnosticBuilder::K_Nop;
  1813. if (FD) {
  1814. FunctionEmissionStatus FES = getEmissionStatus(FD);
  1815. switch (FES) {
  1816. case FunctionEmissionStatus::Emitted:
  1817. Kind = SemaDiagnosticBuilder::K_Immediate;
  1818. break;
  1819. case FunctionEmissionStatus::Unknown:
  1820. Kind = SemaDiagnosticBuilder::K_Deferred;
  1821. break;
  1822. case FunctionEmissionStatus::TemplateDiscarded:
  1823. case FunctionEmissionStatus::OMPDiscarded:
  1824. case FunctionEmissionStatus::CUDADiscarded:
  1825. Kind = SemaDiagnosticBuilder::K_Nop;
  1826. break;
  1827. }
  1828. }
  1829. return SemaDiagnosticBuilder(Kind, Loc, DiagID, FD, *this);
  1830. }
  1831. static OpenMPDefaultmapClauseKind
  1832. getVariableCategoryFromDecl(const LangOptions &LO, const ValueDecl *VD) {
  1833. if (LO.OpenMP <= 45) {
  1834. if (VD->getType().getNonReferenceType()->isScalarType())
  1835. return OMPC_DEFAULTMAP_scalar;
  1836. return OMPC_DEFAULTMAP_aggregate;
  1837. }
  1838. if (VD->getType().getNonReferenceType()->isAnyPointerType())
  1839. return OMPC_DEFAULTMAP_pointer;
  1840. if (VD->getType().getNonReferenceType()->isScalarType())
  1841. return OMPC_DEFAULTMAP_scalar;
  1842. return OMPC_DEFAULTMAP_aggregate;
  1843. }
  1844. bool Sema::isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level,
  1845. unsigned OpenMPCaptureLevel) const {
  1846. assert(LangOpts.OpenMP && "OpenMP is not allowed");
  1847. ASTContext &Ctx = getASTContext();
  1848. bool IsByRef = true;
  1849. // Find the directive that is associated with the provided scope.
  1850. D = cast<ValueDecl>(D->getCanonicalDecl());
  1851. QualType Ty = D->getType();
  1852. bool IsVariableUsedInMapClause = false;
  1853. if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) {
  1854. // This table summarizes how a given variable should be passed to the device
  1855. // given its type and the clauses where it appears. This table is based on
  1856. // the description in OpenMP 4.5 [2.10.4, target Construct] and
  1857. // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses].
  1858. //
  1859. // =========================================================================
  1860. // | type | defaultmap | pvt | first | is_device_ptr | map | res. |
  1861. // | |(tofrom:scalar)| | pvt | | | |
  1862. // =========================================================================
  1863. // | scl | | | | - | | bycopy|
  1864. // | scl | | - | x | - | - | bycopy|
  1865. // | scl | | x | - | - | - | null |
  1866. // | scl | x | | | - | | byref |
  1867. // | scl | x | - | x | - | - | bycopy|
  1868. // | scl | x | x | - | - | - | null |
  1869. // | scl | | - | - | - | x | byref |
  1870. // | scl | x | - | - | - | x | byref |
  1871. //
  1872. // | agg | n.a. | | | - | | byref |
  1873. // | agg | n.a. | - | x | - | - | byref |
  1874. // | agg | n.a. | x | - | - | - | null |
  1875. // | agg | n.a. | - | - | - | x | byref |
  1876. // | agg | n.a. | - | - | - | x[] | byref |
  1877. //
  1878. // | ptr | n.a. | | | - | | bycopy|
  1879. // | ptr | n.a. | - | x | - | - | bycopy|
  1880. // | ptr | n.a. | x | - | - | - | null |
  1881. // | ptr | n.a. | - | - | - | x | byref |
  1882. // | ptr | n.a. | - | - | - | x[] | bycopy|
  1883. // | ptr | n.a. | - | - | x | | bycopy|
  1884. // | ptr | n.a. | - | - | x | x | bycopy|
  1885. // | ptr | n.a. | - | - | x | x[] | bycopy|
  1886. // =========================================================================
  1887. // Legend:
  1888. // scl - scalar
  1889. // ptr - pointer
  1890. // agg - aggregate
  1891. // x - applies
  1892. // - - invalid in this combination
  1893. // [] - mapped with an array section
  1894. // byref - should be mapped by reference
  1895. // byval - should be mapped by value
  1896. // null - initialize a local variable to null on the device
  1897. //
  1898. // Observations:
  1899. // - All scalar declarations that show up in a map clause have to be passed
  1900. // by reference, because they may have been mapped in the enclosing data
  1901. // environment.
  1902. // - If the scalar value does not fit the size of uintptr, it has to be
  1903. // passed by reference, regardless the result in the table above.
  1904. // - For pointers mapped by value that have either an implicit map or an
  1905. // array section, the runtime library may pass the NULL value to the
  1906. // device instead of the value passed to it by the compiler.
  1907. if (Ty->isReferenceType())
  1908. Ty = Ty->castAs<ReferenceType>()->getPointeeType();
  1909. // Locate map clauses and see if the variable being captured is referred to
  1910. // in any of those clauses. Here we only care about variables, not fields,
  1911. // because fields are part of aggregates.
  1912. bool IsVariableAssociatedWithSection = false;
  1913. DSAStack->checkMappableExprComponentListsForDeclAtLevel(
  1914. D, Level,
  1915. [&IsVariableUsedInMapClause, &IsVariableAssociatedWithSection,
  1916. D](OMPClauseMappableExprCommon::MappableExprComponentListRef
  1917. MapExprComponents,
  1918. OpenMPClauseKind WhereFoundClauseKind) {
  1919. // Only the map clause information influences how a variable is
  1920. // captured. E.g. is_device_ptr does not require changing the default
  1921. // behavior.
  1922. if (WhereFoundClauseKind != OMPC_map)
  1923. return false;
  1924. auto EI = MapExprComponents.rbegin();
  1925. auto EE = MapExprComponents.rend();
  1926. assert(EI != EE && "Invalid map expression!");
  1927. if (isa<DeclRefExpr>(EI->getAssociatedExpression()))
  1928. IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D;
  1929. ++EI;
  1930. if (EI == EE)
  1931. return false;
  1932. if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) ||
  1933. isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) ||
  1934. isa<MemberExpr>(EI->getAssociatedExpression()) ||
  1935. isa<OMPArrayShapingExpr>(EI->getAssociatedExpression())) {
  1936. IsVariableAssociatedWithSection = true;
  1937. // There is nothing more we need to know about this variable.
  1938. return true;
  1939. }
  1940. // Keep looking for more map info.
  1941. return false;
  1942. });
  1943. if (IsVariableUsedInMapClause) {
  1944. // If variable is identified in a map clause it is always captured by
  1945. // reference except if it is a pointer that is dereferenced somehow.
  1946. IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection);
  1947. } else {
  1948. // By default, all the data that has a scalar type is mapped by copy
  1949. // (except for reduction variables).
  1950. // Defaultmap scalar is mutual exclusive to defaultmap pointer
  1951. IsByRef = (DSAStack->isForceCaptureByReferenceInTargetExecutable() &&
  1952. !Ty->isAnyPointerType()) ||
  1953. !Ty->isScalarType() ||
  1954. DSAStack->isDefaultmapCapturedByRef(
  1955. Level, getVariableCategoryFromDecl(LangOpts, D)) ||
  1956. DSAStack->hasExplicitDSA(
  1957. D,
  1958. [](OpenMPClauseKind K, bool AppliedToPointee) {
  1959. return K == OMPC_reduction && !AppliedToPointee;
  1960. },
  1961. Level);
  1962. }
  1963. }
  1964. if (IsByRef && Ty.getNonReferenceType()->isScalarType()) {
  1965. IsByRef =
  1966. ((IsVariableUsedInMapClause &&
  1967. DSAStack->getCaptureRegion(Level, OpenMPCaptureLevel) ==
  1968. OMPD_target) ||
  1969. !(DSAStack->hasExplicitDSA(
  1970. D,
  1971. [](OpenMPClauseKind K, bool AppliedToPointee) -> bool {
  1972. return K == OMPC_firstprivate ||
  1973. (K == OMPC_reduction && AppliedToPointee);
  1974. },
  1975. Level, /*NotLastprivate=*/true) ||
  1976. DSAStack->isUsesAllocatorsDecl(Level, D))) &&
  1977. // If the variable is artificial and must be captured by value - try to
  1978. // capture by value.
  1979. !(isa<OMPCapturedExprDecl>(D) && !D->hasAttr<OMPCaptureNoInitAttr>() &&
  1980. !cast<OMPCapturedExprDecl>(D)->getInit()->isGLValue()) &&
  1981. // If the variable is implicitly firstprivate and scalar - capture by
  1982. // copy
  1983. !(DSAStack->getDefaultDSA() == DSA_firstprivate &&
  1984. !DSAStack->hasExplicitDSA(
  1985. D, [](OpenMPClauseKind K, bool) { return K != OMPC_unknown; },
  1986. Level) &&
  1987. !DSAStack->isLoopControlVariable(D, Level).first);
  1988. }
  1989. // When passing data by copy, we need to make sure it fits the uintptr size
  1990. // and alignment, because the runtime library only deals with uintptr types.
  1991. // If it does not fit the uintptr size, we need to pass the data by reference
  1992. // instead.
  1993. if (!IsByRef &&
  1994. (Ctx.getTypeSizeInChars(Ty) >
  1995. Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) ||
  1996. Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) {
  1997. IsByRef = true;
  1998. }
  1999. return IsByRef;
  2000. }
  2001. unsigned Sema::getOpenMPNestingLevel() const {
  2002. assert(getLangOpts().OpenMP);
  2003. return DSAStack->getNestingLevel();
  2004. }
  2005. bool Sema::isInOpenMPTargetExecutionDirective() const {
  2006. return (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) &&
  2007. !DSAStack->isClauseParsingMode()) ||
  2008. DSAStack->hasDirective(
  2009. [](OpenMPDirectiveKind K, const DeclarationNameInfo &,
  2010. SourceLocation) -> bool {
  2011. return isOpenMPTargetExecutionDirective(K);
  2012. },
  2013. false);
  2014. }
  2015. VarDecl *Sema::isOpenMPCapturedDecl(ValueDecl *D, bool CheckScopeInfo,
  2016. unsigned StopAt) {
  2017. assert(LangOpts.OpenMP && "OpenMP is not allowed");
  2018. D = getCanonicalDecl(D);
  2019. auto *VD = dyn_cast<VarDecl>(D);
  2020. // Do not capture constexpr variables.
  2021. if (VD && VD->isConstexpr())
  2022. return nullptr;
  2023. // If we want to determine whether the variable should be captured from the
  2024. // perspective of the current capturing scope, and we've already left all the
  2025. // capturing scopes of the top directive on the stack, check from the
  2026. // perspective of its parent directive (if any) instead.
  2027. DSAStackTy::ParentDirectiveScope InParentDirectiveRAII(
  2028. *DSAStack, CheckScopeInfo && DSAStack->isBodyComplete());
  2029. // If we are attempting to capture a global variable in a directive with
  2030. // 'target' we return true so that this global is also mapped to the device.
  2031. //
  2032. if (VD && !VD->hasLocalStorage() &&
  2033. (getCurCapturedRegion() || getCurBlock() || getCurLambda())) {
  2034. if (isInOpenMPTargetExecutionDirective()) {
  2035. DSAStackTy::DSAVarData DVarTop =
  2036. DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
  2037. if (DVarTop.CKind != OMPC_unknown && DVarTop.RefExpr)
  2038. return VD;
  2039. // If the declaration is enclosed in a 'declare target' directive,
  2040. // then it should not be captured.
  2041. //
  2042. if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
  2043. return nullptr;
  2044. CapturedRegionScopeInfo *CSI = nullptr;
  2045. for (FunctionScopeInfo *FSI : llvm::drop_begin(
  2046. llvm::reverse(FunctionScopes),
  2047. CheckScopeInfo ? (FunctionScopes.size() - (StopAt + 1)) : 0)) {
  2048. if (!isa<CapturingScopeInfo>(FSI))
  2049. return nullptr;
  2050. if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(FSI))
  2051. if (RSI->CapRegionKind == CR_OpenMP) {
  2052. CSI = RSI;
  2053. break;
  2054. }
  2055. }
  2056. assert(CSI && "Failed to find CapturedRegionScopeInfo");
  2057. SmallVector<OpenMPDirectiveKind, 4> Regions;
  2058. getOpenMPCaptureRegions(Regions,
  2059. DSAStack->getDirective(CSI->OpenMPLevel));
  2060. if (Regions[CSI->OpenMPCaptureLevel] != OMPD_task)
  2061. return VD;
  2062. }
  2063. if (isInOpenMPDeclareTargetContext()) {
  2064. // Try to mark variable as declare target if it is used in capturing
  2065. // regions.
  2066. if (LangOpts.OpenMP <= 45 &&
  2067. !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
  2068. checkDeclIsAllowedInOpenMPTarget(nullptr, VD);
  2069. return nullptr;
  2070. }
  2071. }
  2072. if (CheckScopeInfo) {
  2073. bool OpenMPFound = false;
  2074. for (unsigned I = StopAt + 1; I > 0; --I) {
  2075. FunctionScopeInfo *FSI = FunctionScopes[I - 1];
  2076. if (!isa<CapturingScopeInfo>(FSI))
  2077. return nullptr;
  2078. if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(FSI))
  2079. if (RSI->CapRegionKind == CR_OpenMP) {
  2080. OpenMPFound = true;
  2081. break;
  2082. }
  2083. }
  2084. if (!OpenMPFound)
  2085. return nullptr;
  2086. }
  2087. if (DSAStack->getCurrentDirective() != OMPD_unknown &&
  2088. (!DSAStack->isClauseParsingMode() ||
  2089. DSAStack->getParentDirective() != OMPD_unknown)) {
  2090. auto &&Info = DSAStack->isLoopControlVariable(D);
  2091. if (Info.first ||
  2092. (VD && VD->hasLocalStorage() &&
  2093. isImplicitOrExplicitTaskingRegion(DSAStack->getCurrentDirective())) ||
  2094. (VD && DSAStack->isForceVarCapturing()))
  2095. return VD ? VD : Info.second;
  2096. DSAStackTy::DSAVarData DVarTop =
  2097. DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
  2098. if (DVarTop.CKind != OMPC_unknown && isOpenMPPrivate(DVarTop.CKind) &&
  2099. (!VD || VD->hasLocalStorage() || !DVarTop.AppliedToPointee))
  2100. return VD ? VD : cast<VarDecl>(DVarTop.PrivateCopy->getDecl());
  2101. // Threadprivate variables must not be captured.
  2102. if (isOpenMPThreadPrivate(DVarTop.CKind))
  2103. return nullptr;
  2104. // The variable is not private or it is the variable in the directive with
  2105. // default(none) clause and not used in any clause.
  2106. DSAStackTy::DSAVarData DVarPrivate = DSAStack->hasDSA(
  2107. D,
  2108. [](OpenMPClauseKind C, bool AppliedToPointee) {
  2109. return isOpenMPPrivate(C) && !AppliedToPointee;
  2110. },
  2111. [](OpenMPDirectiveKind) { return true; },
  2112. DSAStack->isClauseParsingMode());
  2113. // Global shared must not be captured.
  2114. if (VD && !VD->hasLocalStorage() && DVarPrivate.CKind == OMPC_unknown &&
  2115. ((DSAStack->getDefaultDSA() != DSA_none &&
  2116. DSAStack->getDefaultDSA() != DSA_firstprivate) ||
  2117. DVarTop.CKind == OMPC_shared))
  2118. return nullptr;
  2119. if (DVarPrivate.CKind != OMPC_unknown ||
  2120. (VD && (DSAStack->getDefaultDSA() == DSA_none ||
  2121. DSAStack->getDefaultDSA() == DSA_firstprivate)))
  2122. return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
  2123. }
  2124. return nullptr;
  2125. }
  2126. void Sema::adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex,
  2127. unsigned Level) const {
  2128. FunctionScopesIndex -= getOpenMPCaptureLevels(DSAStack->getDirective(Level));
  2129. }
  2130. void Sema::startOpenMPLoop() {
  2131. assert(LangOpts.OpenMP && "OpenMP must be enabled.");
  2132. if (isOpenMPLoopDirective(DSAStack->getCurrentDirective()))
  2133. DSAStack->loopInit();
  2134. }
  2135. void Sema::startOpenMPCXXRangeFor() {
  2136. assert(LangOpts.OpenMP && "OpenMP must be enabled.");
  2137. if (isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
  2138. DSAStack->resetPossibleLoopCounter();
  2139. DSAStack->loopStart();
  2140. }
  2141. }
  2142. OpenMPClauseKind Sema::isOpenMPPrivateDecl(ValueDecl *D, unsigned Level,
  2143. unsigned CapLevel) const {
  2144. assert(LangOpts.OpenMP && "OpenMP is not allowed");
  2145. if (DSAStack->hasExplicitDirective(isOpenMPTaskingDirective, Level)) {
  2146. bool IsTriviallyCopyable =
  2147. D->getType().getNonReferenceType().isTriviallyCopyableType(Context) &&
  2148. !D->getType()
  2149. .getNonReferenceType()
  2150. .getCanonicalType()
  2151. ->getAsCXXRecordDecl();
  2152. OpenMPDirectiveKind DKind = DSAStack->getDirective(Level);
  2153. SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
  2154. getOpenMPCaptureRegions(CaptureRegions, DKind);
  2155. if (isOpenMPTaskingDirective(CaptureRegions[CapLevel]) &&
  2156. (IsTriviallyCopyable ||
  2157. !isOpenMPTaskLoopDirective(CaptureRegions[CapLevel]))) {
  2158. if (DSAStack->hasExplicitDSA(
  2159. D,
  2160. [](OpenMPClauseKind K, bool) { return K == OMPC_firstprivate; },
  2161. Level, /*NotLastprivate=*/true))
  2162. return OMPC_firstprivate;
  2163. DSAStackTy::DSAVarData DVar = DSAStack->getImplicitDSA(D, Level);
  2164. if (DVar.CKind != OMPC_shared &&
  2165. !DSAStack->isLoopControlVariable(D, Level).first && !DVar.RefExpr) {
  2166. DSAStack->addImplicitTaskFirstprivate(Level, D);
  2167. return OMPC_firstprivate;
  2168. }
  2169. }
  2170. }
  2171. if (isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
  2172. if (DSAStack->getAssociatedLoops() > 0 && !DSAStack->isLoopStarted()) {
  2173. DSAStack->resetPossibleLoopCounter(D);
  2174. DSAStack->loopStart();
  2175. return OMPC_private;
  2176. }
  2177. if ((DSAStack->getPossiblyLoopCunter() == D->getCanonicalDecl() ||
  2178. DSAStack->isLoopControlVariable(D).first) &&
  2179. !DSAStack->hasExplicitDSA(
  2180. D, [](OpenMPClauseKind K, bool) { return K != OMPC_private; },
  2181. Level) &&
  2182. !isOpenMPSimdDirective(DSAStack->getCurrentDirective()))
  2183. return OMPC_private;
  2184. }
  2185. if (const auto *VD = dyn_cast<VarDecl>(D)) {
  2186. if (DSAStack->isThreadPrivate(const_cast<VarDecl *>(VD)) &&
  2187. DSAStack->isForceVarCapturing() &&
  2188. !DSAStack->hasExplicitDSA(
  2189. D, [](OpenMPClauseKind K, bool) { return K == OMPC_copyin; },
  2190. Level))
  2191. return OMPC_private;
  2192. }
  2193. // User-defined allocators are private since they must be defined in the
  2194. // context of target region.
  2195. if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level) &&
  2196. DSAStack->isUsesAllocatorsDecl(Level, D).getValueOr(
  2197. DSAStackTy::UsesAllocatorsDeclKind::AllocatorTrait) ==
  2198. DSAStackTy::UsesAllocatorsDeclKind::UserDefinedAllocator)
  2199. return OMPC_private;
  2200. return (DSAStack->hasExplicitDSA(
  2201. D, [](OpenMPClauseKind K, bool) { return K == OMPC_private; },
  2202. Level) ||
  2203. (DSAStack->isClauseParsingMode() &&
  2204. DSAStack->getClauseParsingMode() == OMPC_private) ||
  2205. // Consider taskgroup reduction descriptor variable a private
  2206. // to avoid possible capture in the region.
  2207. (DSAStack->hasExplicitDirective(
  2208. [](OpenMPDirectiveKind K) {
  2209. return K == OMPD_taskgroup ||
  2210. ((isOpenMPParallelDirective(K) ||
  2211. isOpenMPWorksharingDirective(K)) &&
  2212. !isOpenMPSimdDirective(K));
  2213. },
  2214. Level) &&
  2215. DSAStack->isTaskgroupReductionRef(D, Level)))
  2216. ? OMPC_private
  2217. : OMPC_unknown;
  2218. }
  2219. void Sema::setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D,
  2220. unsigned Level) {
  2221. assert(LangOpts.OpenMP && "OpenMP is not allowed");
  2222. D = getCanonicalDecl(D);
  2223. OpenMPClauseKind OMPC = OMPC_unknown;
  2224. for (unsigned I = DSAStack->getNestingLevel() + 1; I > Level; --I) {
  2225. const unsigned NewLevel = I - 1;
  2226. if (DSAStack->hasExplicitDSA(
  2227. D,
  2228. [&OMPC](const OpenMPClauseKind K, bool AppliedToPointee) {
  2229. if (isOpenMPPrivate(K) && !AppliedToPointee) {
  2230. OMPC = K;
  2231. return true;
  2232. }
  2233. return false;
  2234. },
  2235. NewLevel))
  2236. break;
  2237. if (DSAStack->checkMappableExprComponentListsForDeclAtLevel(
  2238. D, NewLevel,
  2239. [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
  2240. OpenMPClauseKind) { return true; })) {
  2241. OMPC = OMPC_map;
  2242. break;
  2243. }
  2244. if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
  2245. NewLevel)) {
  2246. OMPC = OMPC_map;
  2247. if (DSAStack->mustBeFirstprivateAtLevel(
  2248. NewLevel, getVariableCategoryFromDecl(LangOpts, D)))
  2249. OMPC = OMPC_firstprivate;
  2250. break;
  2251. }
  2252. }
  2253. if (OMPC != OMPC_unknown)
  2254. FD->addAttr(OMPCaptureKindAttr::CreateImplicit(Context, unsigned(OMPC)));
  2255. }
  2256. bool Sema::isOpenMPTargetCapturedDecl(const ValueDecl *D, unsigned Level,
  2257. unsigned CaptureLevel) const {
  2258. assert(LangOpts.OpenMP && "OpenMP is not allowed");
  2259. // Return true if the current level is no longer enclosed in a target region.
  2260. SmallVector<OpenMPDirectiveKind, 4> Regions;
  2261. getOpenMPCaptureRegions(Regions, DSAStack->getDirective(Level));
  2262. const auto *VD = dyn_cast<VarDecl>(D);
  2263. return VD && !VD->hasLocalStorage() &&
  2264. DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
  2265. Level) &&
  2266. Regions[CaptureLevel] != OMPD_task;
  2267. }
  2268. bool Sema::isOpenMPGlobalCapturedDecl(ValueDecl *D, unsigned Level,
  2269. unsigned CaptureLevel) const {
  2270. assert(LangOpts.OpenMP && "OpenMP is not allowed");
  2271. // Return true if the current level is no longer enclosed in a target region.
  2272. if (const auto *VD = dyn_cast<VarDecl>(D)) {
  2273. if (!VD->hasLocalStorage()) {
  2274. if (isInOpenMPTargetExecutionDirective())
  2275. return true;
  2276. DSAStackTy::DSAVarData TopDVar =
  2277. DSAStack->getTopDSA(D, /*FromParent=*/false);
  2278. unsigned NumLevels =
  2279. getOpenMPCaptureLevels(DSAStack->getDirective(Level));
  2280. if (Level == 0)
  2281. return (NumLevels == CaptureLevel + 1) && TopDVar.CKind != OMPC_shared;
  2282. do {
  2283. --Level;
  2284. DSAStackTy::DSAVarData DVar = DSAStack->getImplicitDSA(D, Level);
  2285. if (DVar.CKind != OMPC_shared)
  2286. return true;
  2287. } while (Level > 0);
  2288. }
  2289. }
  2290. return true;
  2291. }
  2292. void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
  2293. void Sema::ActOnOpenMPBeginDeclareVariant(SourceLocation Loc,
  2294. OMPTraitInfo &TI) {
  2295. OMPDeclareVariantScopes.push_back(OMPDeclareVariantScope(TI));
  2296. }
  2297. void Sema::ActOnOpenMPEndDeclareVariant() {
  2298. assert(isInOpenMPDeclareVariantScope() &&
  2299. "Not in OpenMP declare variant scope!");
  2300. OMPDeclareVariantScopes.pop_back();
  2301. }
  2302. void Sema::finalizeOpenMPDelayedAnalysis(const FunctionDecl *Caller,
  2303. const FunctionDecl *Callee,
  2304. SourceLocation Loc) {
  2305. assert(LangOpts.OpenMP && "Expected OpenMP compilation mode.");
  2306. Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
  2307. OMPDeclareTargetDeclAttr::getDeviceType(Caller->getMostRecentDecl());
  2308. // Ignore host functions during device analyzis.
  2309. if (LangOpts.OpenMPIsDevice &&
  2310. (!DevTy || *DevTy == OMPDeclareTargetDeclAttr::DT_Host))
  2311. return;
  2312. // Ignore nohost functions during host analyzis.
  2313. if (!LangOpts.OpenMPIsDevice && DevTy &&
  2314. *DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
  2315. return;
  2316. const FunctionDecl *FD = Callee->getMostRecentDecl();
  2317. DevTy = OMPDeclareTargetDeclAttr::getDeviceType(FD);
  2318. if (LangOpts.OpenMPIsDevice && DevTy &&
  2319. *DevTy == OMPDeclareTargetDeclAttr::DT_Host) {
  2320. // Diagnose host function called during device codegen.
  2321. StringRef HostDevTy =
  2322. getOpenMPSimpleClauseTypeName(OMPC_device_type, OMPC_DEVICE_TYPE_host);
  2323. Diag(Loc, diag::err_omp_wrong_device_function_call) << HostDevTy << 0;
  2324. Diag(*OMPDeclareTargetDeclAttr::getLocation(FD),
  2325. diag::note_omp_marked_device_type_here)
  2326. << HostDevTy;
  2327. return;
  2328. }
  2329. if (!LangOpts.OpenMPIsDevice && DevTy &&
  2330. *DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) {
  2331. // Diagnose nohost function called during host codegen.
  2332. StringRef NoHostDevTy = getOpenMPSimpleClauseTypeName(
  2333. OMPC_device_type, OMPC_DEVICE_TYPE_nohost);
  2334. Diag(Loc, diag::err_omp_wrong_device_function_call) << NoHostDevTy << 1;
  2335. Diag(*OMPDeclareTargetDeclAttr::getLocation(FD),
  2336. diag::note_omp_marked_device_type_here)
  2337. << NoHostDevTy;
  2338. }
  2339. }
  2340. void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
  2341. const DeclarationNameInfo &DirName,
  2342. Scope *CurScope, SourceLocation Loc) {
  2343. DSAStack->push(DKind, DirName, CurScope, Loc);
  2344. PushExpressionEvaluationContext(
  2345. ExpressionEvaluationContext::PotentiallyEvaluated);
  2346. }
  2347. void Sema::StartOpenMPClause(OpenMPClauseKind K) {
  2348. DSAStack->setClauseParsingMode(K);
  2349. }
  2350. void Sema::EndOpenMPClause() {
  2351. DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
  2352. CleanupVarDeclMarking();
  2353. }
  2354. static std::pair<ValueDecl *, bool>
  2355. getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
  2356. SourceRange &ERange, bool AllowArraySection = false);
  2357. /// Check consistency of the reduction clauses.
  2358. static void checkReductionClauses(Sema &S, DSAStackTy *Stack,
  2359. ArrayRef<OMPClause *> Clauses) {
  2360. bool InscanFound = false;
  2361. SourceLocation InscanLoc;
  2362. // OpenMP 5.0, 2.19.5.4 reduction Clause, Restrictions.
  2363. // A reduction clause without the inscan reduction-modifier may not appear on
  2364. // a construct on which a reduction clause with the inscan reduction-modifier
  2365. // appears.
  2366. for (OMPClause *C : Clauses) {
  2367. if (C->getClauseKind() != OMPC_reduction)
  2368. continue;
  2369. auto *RC = cast<OMPReductionClause>(C);
  2370. if (RC->getModifier() == OMPC_REDUCTION_inscan) {
  2371. InscanFound = true;
  2372. InscanLoc = RC->getModifierLoc();
  2373. continue;
  2374. }
  2375. if (RC->getModifier() == OMPC_REDUCTION_task) {
  2376. // OpenMP 5.0, 2.19.5.4 reduction Clause.
  2377. // A reduction clause with the task reduction-modifier may only appear on
  2378. // a parallel construct, a worksharing construct or a combined or
  2379. // composite construct for which any of the aforementioned constructs is a
  2380. // constituent construct and simd or loop are not constituent constructs.
  2381. OpenMPDirectiveKind CurDir = Stack->getCurrentDirective();
  2382. if (!(isOpenMPParallelDirective(CurDir) ||
  2383. isOpenMPWorksharingDirective(CurDir)) ||
  2384. isOpenMPSimdDirective(CurDir))
  2385. S.Diag(RC->getModifierLoc(),
  2386. diag::err_omp_reduction_task_not_parallel_or_worksharing);
  2387. continue;
  2388. }
  2389. }
  2390. if (InscanFound) {
  2391. for (OMPClause *C : Clauses) {
  2392. if (C->getClauseKind() != OMPC_reduction)
  2393. continue;
  2394. auto *RC = cast<OMPReductionClause>(C);
  2395. if (RC->getModifier() != OMPC_REDUCTION_inscan) {
  2396. S.Diag(RC->getModifier() == OMPC_REDUCTION_unknown
  2397. ? RC->getBeginLoc()
  2398. : RC->getModifierLoc(),
  2399. diag::err_omp_inscan_reduction_expected);
  2400. S.Diag(InscanLoc, diag::note_omp_previous_inscan_reduction);
  2401. continue;
  2402. }
  2403. for (Expr *Ref : RC->varlists()) {
  2404. assert(Ref && "NULL expr in OpenMP nontemporal clause.");
  2405. SourceLocation ELoc;
  2406. SourceRange ERange;
  2407. Expr *SimpleRefExpr = Ref;
  2408. auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
  2409. /*AllowArraySection=*/true);
  2410. ValueDecl *D = Res.first;
  2411. if (!D)
  2412. continue;
  2413. if (!Stack->isUsedInScanDirective(getCanonicalDecl(D))) {
  2414. S.Diag(Ref->getExprLoc(),
  2415. diag::err_omp_reduction_not_inclusive_exclusive)
  2416. << Ref->getSourceRange();
  2417. }
  2418. }
  2419. }
  2420. }
  2421. }
  2422. static void checkAllocateClauses(Sema &S, DSAStackTy *Stack,
  2423. ArrayRef<OMPClause *> Clauses);
  2424. static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
  2425. bool WithInit);
  2426. static void reportOriginalDsa(Sema &SemaRef, const DSAStackTy *Stack,
  2427. const ValueDecl *D,
  2428. const DSAStackTy::DSAVarData &DVar,
  2429. bool IsLoopIterVar = false);
  2430. void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
  2431. // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
  2432. // A variable of class type (or array thereof) that appears in a lastprivate
  2433. // clause requires an accessible, unambiguous default constructor for the
  2434. // class type, unless the list item is also specified in a firstprivate
  2435. // clause.
  2436. if (const auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
  2437. for (OMPClause *C : D->clauses()) {
  2438. if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
  2439. SmallVector<Expr *, 8> PrivateCopies;
  2440. for (Expr *DE : Clause->varlists()) {
  2441. if (DE->isValueDependent() || DE->isTypeDependent()) {
  2442. PrivateCopies.push_back(nullptr);
  2443. continue;
  2444. }
  2445. auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens());
  2446. auto *VD = cast<VarDecl>(DRE->getDecl());
  2447. QualType Type = VD->getType().getNonReferenceType();
  2448. const DSAStackTy::DSAVarData DVar =
  2449. DSAStack->getTopDSA(VD, /*FromParent=*/false);
  2450. if (DVar.CKind == OMPC_lastprivate) {
  2451. // Generate helper private variable and initialize it with the
  2452. // default value. The address of the original variable is replaced
  2453. // by the address of the new private variable in CodeGen. This new
  2454. // variable is not added to IdResolver, so the code in the OpenMP
  2455. // region uses original variable for proper diagnostics.
  2456. VarDecl *VDPrivate = buildVarDecl(
  2457. *this, DE->getExprLoc(), Type.getUnqualifiedType(),
  2458. VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr, DRE);
  2459. ActOnUninitializedDecl(VDPrivate);
  2460. if (VDPrivate->isInvalidDecl()) {
  2461. PrivateCopies.push_back(nullptr);
  2462. continue;
  2463. }
  2464. PrivateCopies.push_back(buildDeclRefExpr(
  2465. *this, VDPrivate, DE->getType(), DE->getExprLoc()));
  2466. } else {
  2467. // The variable is also a firstprivate, so initialization sequence
  2468. // for private copy is generated already.
  2469. PrivateCopies.push_back(nullptr);
  2470. }
  2471. }
  2472. Clause->setPrivateCopies(PrivateCopies);
  2473. continue;
  2474. }
  2475. // Finalize nontemporal clause by handling private copies, if any.
  2476. if (auto *Clause = dyn_cast<OMPNontemporalClause>(C)) {
  2477. SmallVector<Expr *, 8> PrivateRefs;
  2478. for (Expr *RefExpr : Clause->varlists()) {
  2479. assert(RefExpr && "NULL expr in OpenMP nontemporal clause.");
  2480. SourceLocation ELoc;
  2481. SourceRange ERange;
  2482. Expr *SimpleRefExpr = RefExpr;
  2483. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  2484. if (Res.second)
  2485. // It will be analyzed later.
  2486. PrivateRefs.push_back(RefExpr);
  2487. ValueDecl *D = Res.first;
  2488. if (!D)
  2489. continue;
  2490. const DSAStackTy::DSAVarData DVar =
  2491. DSAStack->getTopDSA(D, /*FromParent=*/false);
  2492. PrivateRefs.push_back(DVar.PrivateCopy ? DVar.PrivateCopy
  2493. : SimpleRefExpr);
  2494. }
  2495. Clause->setPrivateRefs(PrivateRefs);
  2496. continue;
  2497. }
  2498. if (auto *Clause = dyn_cast<OMPUsesAllocatorsClause>(C)) {
  2499. for (unsigned I = 0, E = Clause->getNumberOfAllocators(); I < E; ++I) {
  2500. OMPUsesAllocatorsClause::Data D = Clause->getAllocatorData(I);
  2501. auto *DRE = dyn_cast<DeclRefExpr>(D.Allocator->IgnoreParenImpCasts());
  2502. if (!DRE)
  2503. continue;
  2504. ValueDecl *VD = DRE->getDecl();
  2505. if (!VD || !isa<VarDecl>(VD))
  2506. continue;
  2507. DSAStackTy::DSAVarData DVar =
  2508. DSAStack->getTopDSA(VD, /*FromParent=*/false);
  2509. // OpenMP [2.12.5, target Construct]
  2510. // Memory allocators that appear in a uses_allocators clause cannot
  2511. // appear in other data-sharing attribute clauses or data-mapping
  2512. // attribute clauses in the same construct.
  2513. Expr *MapExpr = nullptr;
  2514. if (DVar.RefExpr ||
  2515. DSAStack->checkMappableExprComponentListsForDecl(
  2516. VD, /*CurrentRegionOnly=*/true,
  2517. [VD, &MapExpr](
  2518. OMPClauseMappableExprCommon::MappableExprComponentListRef
  2519. MapExprComponents,
  2520. OpenMPClauseKind C) {
  2521. auto MI = MapExprComponents.rbegin();
  2522. auto ME = MapExprComponents.rend();
  2523. if (MI != ME &&
  2524. MI->getAssociatedDeclaration()->getCanonicalDecl() ==
  2525. VD->getCanonicalDecl()) {
  2526. MapExpr = MI->getAssociatedExpression();
  2527. return true;
  2528. }
  2529. return false;
  2530. })) {
  2531. Diag(D.Allocator->getExprLoc(),
  2532. diag::err_omp_allocator_used_in_clauses)
  2533. << D.Allocator->getSourceRange();
  2534. if (DVar.RefExpr)
  2535. reportOriginalDsa(*this, DSAStack, VD, DVar);
  2536. else
  2537. Diag(MapExpr->getExprLoc(), diag::note_used_here)
  2538. << MapExpr->getSourceRange();
  2539. }
  2540. }
  2541. continue;
  2542. }
  2543. }
  2544. // Check allocate clauses.
  2545. if (!CurContext->isDependentContext())
  2546. checkAllocateClauses(*this, DSAStack, D->clauses());
  2547. checkReductionClauses(*this, DSAStack, D->clauses());
  2548. }
  2549. DSAStack->pop();
  2550. DiscardCleanupsInEvaluationContext();
  2551. PopExpressionEvaluationContext();
  2552. }
  2553. static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
  2554. Expr *NumIterations, Sema &SemaRef,
  2555. Scope *S, DSAStackTy *Stack);
  2556. namespace {
  2557. class VarDeclFilterCCC final : public CorrectionCandidateCallback {
  2558. private:
  2559. Sema &SemaRef;
  2560. public:
  2561. explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
  2562. bool ValidateCandidate(const TypoCorrection &Candidate) override {
  2563. NamedDecl *ND = Candidate.getCorrectionDecl();
  2564. if (const auto *VD = dyn_cast_or_null<VarDecl>(ND)) {
  2565. return VD->hasGlobalStorage() &&
  2566. SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
  2567. SemaRef.getCurScope());
  2568. }
  2569. return false;
  2570. }
  2571. std::unique_ptr<CorrectionCandidateCallback> clone() override {
  2572. return std::make_unique<VarDeclFilterCCC>(*this);
  2573. }
  2574. };
  2575. class VarOrFuncDeclFilterCCC final : public CorrectionCandidateCallback {
  2576. private:
  2577. Sema &SemaRef;
  2578. public:
  2579. explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {}
  2580. bool ValidateCandidate(const TypoCorrection &Candidate) override {
  2581. NamedDecl *ND = Candidate.getCorrectionDecl();
  2582. if (ND && ((isa<VarDecl>(ND) && ND->getKind() == Decl::Var) ||
  2583. isa<FunctionDecl>(ND))) {
  2584. return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
  2585. SemaRef.getCurScope());
  2586. }
  2587. return false;
  2588. }
  2589. std::unique_ptr<CorrectionCandidateCallback> clone() override {
  2590. return std::make_unique<VarOrFuncDeclFilterCCC>(*this);
  2591. }
  2592. };
  2593. } // namespace
  2594. ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
  2595. CXXScopeSpec &ScopeSpec,
  2596. const DeclarationNameInfo &Id,
  2597. OpenMPDirectiveKind Kind) {
  2598. LookupResult Lookup(*this, Id, LookupOrdinaryName);
  2599. LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
  2600. if (Lookup.isAmbiguous())
  2601. return ExprError();
  2602. VarDecl *VD;
  2603. if (!Lookup.isSingleResult()) {
  2604. VarDeclFilterCCC CCC(*this);
  2605. if (TypoCorrection Corrected =
  2606. CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, CCC,
  2607. CTK_ErrorRecovery)) {
  2608. diagnoseTypo(Corrected,
  2609. PDiag(Lookup.empty()
  2610. ? diag::err_undeclared_var_use_suggest
  2611. : diag::err_omp_expected_var_arg_suggest)
  2612. << Id.getName());
  2613. VD = Corrected.getCorrectionDeclAs<VarDecl>();
  2614. } else {
  2615. Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
  2616. : diag::err_omp_expected_var_arg)
  2617. << Id.getName();
  2618. return ExprError();
  2619. }
  2620. } else if (!(VD = Lookup.getAsSingle<VarDecl>())) {
  2621. Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
  2622. Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
  2623. return ExprError();
  2624. }
  2625. Lookup.suppressDiagnostics();
  2626. // OpenMP [2.9.2, Syntax, C/C++]
  2627. // Variables must be file-scope, namespace-scope, or static block-scope.
  2628. if (Kind == OMPD_threadprivate && !VD->hasGlobalStorage()) {
  2629. Diag(Id.getLoc(), diag::err_omp_global_var_arg)
  2630. << getOpenMPDirectiveName(Kind) << !VD->isStaticLocal();
  2631. bool IsDecl =
  2632. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  2633. Diag(VD->getLocation(),
  2634. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  2635. << VD;
  2636. return ExprError();
  2637. }
  2638. VarDecl *CanonicalVD = VD->getCanonicalDecl();
  2639. NamedDecl *ND = CanonicalVD;
  2640. // OpenMP [2.9.2, Restrictions, C/C++, p.2]
  2641. // A threadprivate directive for file-scope variables must appear outside
  2642. // any definition or declaration.
  2643. if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
  2644. !getCurLexicalContext()->isTranslationUnit()) {
  2645. Diag(Id.getLoc(), diag::err_omp_var_scope)
  2646. << getOpenMPDirectiveName(Kind) << VD;
  2647. bool IsDecl =
  2648. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  2649. Diag(VD->getLocation(),
  2650. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  2651. << VD;
  2652. return ExprError();
  2653. }
  2654. // OpenMP [2.9.2, Restrictions, C/C++, p.3]
  2655. // A threadprivate directive for static class member variables must appear
  2656. // in the class definition, in the same scope in which the member
  2657. // variables are declared.
  2658. if (CanonicalVD->isStaticDataMember() &&
  2659. !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
  2660. Diag(Id.getLoc(), diag::err_omp_var_scope)
  2661. << getOpenMPDirectiveName(Kind) << VD;
  2662. bool IsDecl =
  2663. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  2664. Diag(VD->getLocation(),
  2665. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  2666. << VD;
  2667. return ExprError();
  2668. }
  2669. // OpenMP [2.9.2, Restrictions, C/C++, p.4]
  2670. // A threadprivate directive for namespace-scope variables must appear
  2671. // outside any definition or declaration other than the namespace
  2672. // definition itself.
  2673. if (CanonicalVD->getDeclContext()->isNamespace() &&
  2674. (!getCurLexicalContext()->isFileContext() ||
  2675. !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
  2676. Diag(Id.getLoc(), diag::err_omp_var_scope)
  2677. << getOpenMPDirectiveName(Kind) << VD;
  2678. bool IsDecl =
  2679. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  2680. Diag(VD->getLocation(),
  2681. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  2682. << VD;
  2683. return ExprError();
  2684. }
  2685. // OpenMP [2.9.2, Restrictions, C/C++, p.6]
  2686. // A threadprivate directive for static block-scope variables must appear
  2687. // in the scope of the variable and not in a nested scope.
  2688. if (CanonicalVD->isLocalVarDecl() && CurScope &&
  2689. !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
  2690. Diag(Id.getLoc(), diag::err_omp_var_scope)
  2691. << getOpenMPDirectiveName(Kind) << VD;
  2692. bool IsDecl =
  2693. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  2694. Diag(VD->getLocation(),
  2695. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  2696. << VD;
  2697. return ExprError();
  2698. }
  2699. // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
  2700. // A threadprivate directive must lexically precede all references to any
  2701. // of the variables in its list.
  2702. if (Kind == OMPD_threadprivate && VD->isUsed() &&
  2703. !DSAStack->isThreadPrivate(VD)) {
  2704. Diag(Id.getLoc(), diag::err_omp_var_used)
  2705. << getOpenMPDirectiveName(Kind) << VD;
  2706. return ExprError();
  2707. }
  2708. QualType ExprType = VD->getType().getNonReferenceType();
  2709. return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
  2710. SourceLocation(), VD,
  2711. /*RefersToEnclosingVariableOrCapture=*/false,
  2712. Id.getLoc(), ExprType, VK_LValue);
  2713. }
  2714. Sema::DeclGroupPtrTy
  2715. Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
  2716. ArrayRef<Expr *> VarList) {
  2717. if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
  2718. CurContext->addDecl(D);
  2719. return DeclGroupPtrTy::make(DeclGroupRef(D));
  2720. }
  2721. return nullptr;
  2722. }
  2723. namespace {
  2724. class LocalVarRefChecker final
  2725. : public ConstStmtVisitor<LocalVarRefChecker, bool> {
  2726. Sema &SemaRef;
  2727. public:
  2728. bool VisitDeclRefExpr(const DeclRefExpr *E) {
  2729. if (const auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
  2730. if (VD->hasLocalStorage()) {
  2731. SemaRef.Diag(E->getBeginLoc(),
  2732. diag::err_omp_local_var_in_threadprivate_init)
  2733. << E->getSourceRange();
  2734. SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
  2735. << VD << VD->getSourceRange();
  2736. return true;
  2737. }
  2738. }
  2739. return false;
  2740. }
  2741. bool VisitStmt(const Stmt *S) {
  2742. for (const Stmt *Child : S->children()) {
  2743. if (Child && Visit(Child))
  2744. return true;
  2745. }
  2746. return false;
  2747. }
  2748. explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
  2749. };
  2750. } // namespace
  2751. OMPThreadPrivateDecl *
  2752. Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
  2753. SmallVector<Expr *, 8> Vars;
  2754. for (Expr *RefExpr : VarList) {
  2755. auto *DE = cast<DeclRefExpr>(RefExpr);
  2756. auto *VD = cast<VarDecl>(DE->getDecl());
  2757. SourceLocation ILoc = DE->getExprLoc();
  2758. // Mark variable as used.
  2759. VD->setReferenced();
  2760. VD->markUsed(Context);
  2761. QualType QType = VD->getType();
  2762. if (QType->isDependentType() || QType->isInstantiationDependentType()) {
  2763. // It will be analyzed later.
  2764. Vars.push_back(DE);
  2765. continue;
  2766. }
  2767. // OpenMP [2.9.2, Restrictions, C/C++, p.10]
  2768. // A threadprivate variable must not have an incomplete type.
  2769. if (RequireCompleteType(ILoc, VD->getType(),
  2770. diag::err_omp_threadprivate_incomplete_type)) {
  2771. continue;
  2772. }
  2773. // OpenMP [2.9.2, Restrictions, C/C++, p.10]
  2774. // A threadprivate variable must not have a reference type.
  2775. if (VD->getType()->isReferenceType()) {
  2776. Diag(ILoc, diag::err_omp_ref_type_arg)
  2777. << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
  2778. bool IsDecl =
  2779. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  2780. Diag(VD->getLocation(),
  2781. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  2782. << VD;
  2783. continue;
  2784. }
  2785. // Check if this is a TLS variable. If TLS is not being supported, produce
  2786. // the corresponding diagnostic.
  2787. if ((VD->getTLSKind() != VarDecl::TLS_None &&
  2788. !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
  2789. getLangOpts().OpenMPUseTLS &&
  2790. getASTContext().getTargetInfo().isTLSSupported())) ||
  2791. (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
  2792. !VD->isLocalVarDecl())) {
  2793. Diag(ILoc, diag::err_omp_var_thread_local)
  2794. << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
  2795. bool IsDecl =
  2796. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  2797. Diag(VD->getLocation(),
  2798. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  2799. << VD;
  2800. continue;
  2801. }
  2802. // Check if initial value of threadprivate variable reference variable with
  2803. // local storage (it is not supported by runtime).
  2804. if (const Expr *Init = VD->getAnyInitializer()) {
  2805. LocalVarRefChecker Checker(*this);
  2806. if (Checker.Visit(Init))
  2807. continue;
  2808. }
  2809. Vars.push_back(RefExpr);
  2810. DSAStack->addDSA(VD, DE, OMPC_threadprivate);
  2811. VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
  2812. Context, SourceRange(Loc, Loc)));
  2813. if (ASTMutationListener *ML = Context.getASTMutationListener())
  2814. ML->DeclarationMarkedOpenMPThreadPrivate(VD);
  2815. }
  2816. OMPThreadPrivateDecl *D = nullptr;
  2817. if (!Vars.empty()) {
  2818. D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
  2819. Vars);
  2820. D->setAccess(AS_public);
  2821. }
  2822. return D;
  2823. }
  2824. static OMPAllocateDeclAttr::AllocatorTypeTy
  2825. getAllocatorKind(Sema &S, DSAStackTy *Stack, Expr *Allocator) {
  2826. if (!Allocator)
  2827. return OMPAllocateDeclAttr::OMPNullMemAlloc;
  2828. if (Allocator->isTypeDependent() || Allocator->isValueDependent() ||
  2829. Allocator->isInstantiationDependent() ||
  2830. Allocator->containsUnexpandedParameterPack())
  2831. return OMPAllocateDeclAttr::OMPUserDefinedMemAlloc;
  2832. auto AllocatorKindRes = OMPAllocateDeclAttr::OMPUserDefinedMemAlloc;
  2833. const Expr *AE = Allocator->IgnoreParenImpCasts();
  2834. for (int I = 0; I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) {
  2835. auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I);
  2836. const Expr *DefAllocator = Stack->getAllocator(AllocatorKind);
  2837. llvm::FoldingSetNodeID AEId, DAEId;
  2838. AE->Profile(AEId, S.getASTContext(), /*Canonical=*/true);
  2839. DefAllocator->Profile(DAEId, S.getASTContext(), /*Canonical=*/true);
  2840. if (AEId == DAEId) {
  2841. AllocatorKindRes = AllocatorKind;
  2842. break;
  2843. }
  2844. }
  2845. return AllocatorKindRes;
  2846. }
  2847. static bool checkPreviousOMPAllocateAttribute(
  2848. Sema &S, DSAStackTy *Stack, Expr *RefExpr, VarDecl *VD,
  2849. OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind, Expr *Allocator) {
  2850. if (!VD->hasAttr<OMPAllocateDeclAttr>())
  2851. return false;
  2852. const auto *A = VD->getAttr<OMPAllocateDeclAttr>();
  2853. Expr *PrevAllocator = A->getAllocator();
  2854. OMPAllocateDeclAttr::AllocatorTypeTy PrevAllocatorKind =
  2855. getAllocatorKind(S, Stack, PrevAllocator);
  2856. bool AllocatorsMatch = AllocatorKind == PrevAllocatorKind;
  2857. if (AllocatorsMatch &&
  2858. AllocatorKind == OMPAllocateDeclAttr::OMPUserDefinedMemAlloc &&
  2859. Allocator && PrevAllocator) {
  2860. const Expr *AE = Allocator->IgnoreParenImpCasts();
  2861. const Expr *PAE = PrevAllocator->IgnoreParenImpCasts();
  2862. llvm::FoldingSetNodeID AEId, PAEId;
  2863. AE->Profile(AEId, S.Context, /*Canonical=*/true);
  2864. PAE->Profile(PAEId, S.Context, /*Canonical=*/true);
  2865. AllocatorsMatch = AEId == PAEId;
  2866. }
  2867. if (!AllocatorsMatch) {
  2868. SmallString<256> AllocatorBuffer;
  2869. llvm::raw_svector_ostream AllocatorStream(AllocatorBuffer);
  2870. if (Allocator)
  2871. Allocator->printPretty(AllocatorStream, nullptr, S.getPrintingPolicy());
  2872. SmallString<256> PrevAllocatorBuffer;
  2873. llvm::raw_svector_ostream PrevAllocatorStream(PrevAllocatorBuffer);
  2874. if (PrevAllocator)
  2875. PrevAllocator->printPretty(PrevAllocatorStream, nullptr,
  2876. S.getPrintingPolicy());
  2877. SourceLocation AllocatorLoc =
  2878. Allocator ? Allocator->getExprLoc() : RefExpr->getExprLoc();
  2879. SourceRange AllocatorRange =
  2880. Allocator ? Allocator->getSourceRange() : RefExpr->getSourceRange();
  2881. SourceLocation PrevAllocatorLoc =
  2882. PrevAllocator ? PrevAllocator->getExprLoc() : A->getLocation();
  2883. SourceRange PrevAllocatorRange =
  2884. PrevAllocator ? PrevAllocator->getSourceRange() : A->getRange();
  2885. S.Diag(AllocatorLoc, diag::warn_omp_used_different_allocator)
  2886. << (Allocator ? 1 : 0) << AllocatorStream.str()
  2887. << (PrevAllocator ? 1 : 0) << PrevAllocatorStream.str()
  2888. << AllocatorRange;
  2889. S.Diag(PrevAllocatorLoc, diag::note_omp_previous_allocator)
  2890. << PrevAllocatorRange;
  2891. return true;
  2892. }
  2893. return false;
  2894. }
  2895. static void
  2896. applyOMPAllocateAttribute(Sema &S, VarDecl *VD,
  2897. OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind,
  2898. Expr *Allocator, Expr *Alignment, SourceRange SR) {
  2899. if (VD->hasAttr<OMPAllocateDeclAttr>())
  2900. return;
  2901. if (Alignment &&
  2902. (Alignment->isTypeDependent() || Alignment->isValueDependent() ||
  2903. Alignment->isInstantiationDependent() ||
  2904. Alignment->containsUnexpandedParameterPack()))
  2905. // Apply later when we have a usable value.
  2906. return;
  2907. if (Allocator &&
  2908. (Allocator->isTypeDependent() || Allocator->isValueDependent() ||
  2909. Allocator->isInstantiationDependent() ||
  2910. Allocator->containsUnexpandedParameterPack()))
  2911. return;
  2912. auto *A = OMPAllocateDeclAttr::CreateImplicit(S.Context, AllocatorKind,
  2913. Allocator, Alignment, SR);
  2914. VD->addAttr(A);
  2915. if (ASTMutationListener *ML = S.Context.getASTMutationListener())
  2916. ML->DeclarationMarkedOpenMPAllocate(VD, A);
  2917. }
  2918. Sema::DeclGroupPtrTy
  2919. Sema::ActOnOpenMPAllocateDirective(SourceLocation Loc, ArrayRef<Expr *> VarList,
  2920. ArrayRef<OMPClause *> Clauses,
  2921. DeclContext *Owner) {
  2922. assert(Clauses.size() <= 2 && "Expected at most two clauses.");
  2923. Expr *Alignment = nullptr;
  2924. Expr *Allocator = nullptr;
  2925. if (Clauses.empty()) {
  2926. // OpenMP 5.0, 2.11.3 allocate Directive, Restrictions.
  2927. // allocate directives that appear in a target region must specify an
  2928. // allocator clause unless a requires directive with the dynamic_allocators
  2929. // clause is present in the same compilation unit.
  2930. if (LangOpts.OpenMPIsDevice &&
  2931. !DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())
  2932. targetDiag(Loc, diag::err_expected_allocator_clause);
  2933. } else {
  2934. for (const OMPClause *C : Clauses)
  2935. if (const auto *AC = dyn_cast<OMPAllocatorClause>(C))
  2936. Allocator = AC->getAllocator();
  2937. else if (const auto *AC = dyn_cast<OMPAlignClause>(C))
  2938. Alignment = AC->getAlignment();
  2939. else
  2940. llvm_unreachable("Unexpected clause on allocate directive");
  2941. }
  2942. OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind =
  2943. getAllocatorKind(*this, DSAStack, Allocator);
  2944. SmallVector<Expr *, 8> Vars;
  2945. for (Expr *RefExpr : VarList) {
  2946. auto *DE = cast<DeclRefExpr>(RefExpr);
  2947. auto *VD = cast<VarDecl>(DE->getDecl());
  2948. // Check if this is a TLS variable or global register.
  2949. if (VD->getTLSKind() != VarDecl::TLS_None ||
  2950. VD->hasAttr<OMPThreadPrivateDeclAttr>() ||
  2951. (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
  2952. !VD->isLocalVarDecl()))
  2953. continue;
  2954. // If the used several times in the allocate directive, the same allocator
  2955. // must be used.
  2956. if (checkPreviousOMPAllocateAttribute(*this, DSAStack, RefExpr, VD,
  2957. AllocatorKind, Allocator))
  2958. continue;
  2959. // OpenMP, 2.11.3 allocate Directive, Restrictions, C / C++
  2960. // If a list item has a static storage type, the allocator expression in the
  2961. // allocator clause must be a constant expression that evaluates to one of
  2962. // the predefined memory allocator values.
  2963. if (Allocator && VD->hasGlobalStorage()) {
  2964. if (AllocatorKind == OMPAllocateDeclAttr::OMPUserDefinedMemAlloc) {
  2965. Diag(Allocator->getExprLoc(),
  2966. diag::err_omp_expected_predefined_allocator)
  2967. << Allocator->getSourceRange();
  2968. bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
  2969. VarDecl::DeclarationOnly;
  2970. Diag(VD->getLocation(),
  2971. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  2972. << VD;
  2973. continue;
  2974. }
  2975. }
  2976. Vars.push_back(RefExpr);
  2977. applyOMPAllocateAttribute(*this, VD, AllocatorKind, Allocator, Alignment,
  2978. DE->getSourceRange());
  2979. }
  2980. if (Vars.empty())
  2981. return nullptr;
  2982. if (!Owner)
  2983. Owner = getCurLexicalContext();
  2984. auto *D = OMPAllocateDecl::Create(Context, Owner, Loc, Vars, Clauses);
  2985. D->setAccess(AS_public);
  2986. Owner->addDecl(D);
  2987. return DeclGroupPtrTy::make(DeclGroupRef(D));
  2988. }
  2989. Sema::DeclGroupPtrTy
  2990. Sema::ActOnOpenMPRequiresDirective(SourceLocation Loc,
  2991. ArrayRef<OMPClause *> ClauseList) {
  2992. OMPRequiresDecl *D = nullptr;
  2993. if (!CurContext->isFileContext()) {
  2994. Diag(Loc, diag::err_omp_invalid_scope) << "requires";
  2995. } else {
  2996. D = CheckOMPRequiresDecl(Loc, ClauseList);
  2997. if (D) {
  2998. CurContext->addDecl(D);
  2999. DSAStack->addRequiresDecl(D);
  3000. }
  3001. }
  3002. return DeclGroupPtrTy::make(DeclGroupRef(D));
  3003. }
  3004. void Sema::ActOnOpenMPAssumesDirective(SourceLocation Loc,
  3005. OpenMPDirectiveKind DKind,
  3006. ArrayRef<std::string> Assumptions,
  3007. bool SkippedClauses) {
  3008. if (!SkippedClauses && Assumptions.empty())
  3009. Diag(Loc, diag::err_omp_no_clause_for_directive)
  3010. << llvm::omp::getAllAssumeClauseOptions()
  3011. << llvm::omp::getOpenMPDirectiveName(DKind);
  3012. auto *AA = AssumptionAttr::Create(Context, llvm::join(Assumptions, ","), Loc);
  3013. if (DKind == llvm::omp::Directive::OMPD_begin_assumes) {
  3014. OMPAssumeScoped.push_back(AA);
  3015. return;
  3016. }
  3017. // Global assumes without assumption clauses are ignored.
  3018. if (Assumptions.empty())
  3019. return;
  3020. assert(DKind == llvm::omp::Directive::OMPD_assumes &&
  3021. "Unexpected omp assumption directive!");
  3022. OMPAssumeGlobal.push_back(AA);
  3023. // The OMPAssumeGlobal scope above will take care of new declarations but
  3024. // we also want to apply the assumption to existing ones, e.g., to
  3025. // declarations in included headers. To this end, we traverse all existing
  3026. // declaration contexts and annotate function declarations here.
  3027. SmallVector<DeclContext *, 8> DeclContexts;
  3028. auto *Ctx = CurContext;
  3029. while (Ctx->getLexicalParent())
  3030. Ctx = Ctx->getLexicalParent();
  3031. DeclContexts.push_back(Ctx);
  3032. while (!DeclContexts.empty()) {
  3033. DeclContext *DC = DeclContexts.pop_back_val();
  3034. for (auto *SubDC : DC->decls()) {
  3035. if (SubDC->isInvalidDecl())
  3036. continue;
  3037. if (auto *CTD = dyn_cast<ClassTemplateDecl>(SubDC)) {
  3038. DeclContexts.push_back(CTD->getTemplatedDecl());
  3039. for (auto *S : CTD->specializations())
  3040. DeclContexts.push_back(S);
  3041. continue;
  3042. }
  3043. if (auto *DC = dyn_cast<DeclContext>(SubDC))
  3044. DeclContexts.push_back(DC);
  3045. if (auto *F = dyn_cast<FunctionDecl>(SubDC)) {
  3046. F->addAttr(AA);
  3047. continue;
  3048. }
  3049. }
  3050. }
  3051. }
  3052. void Sema::ActOnOpenMPEndAssumesDirective() {
  3053. assert(isInOpenMPAssumeScope() && "Not in OpenMP assumes scope!");
  3054. OMPAssumeScoped.pop_back();
  3055. }
  3056. OMPRequiresDecl *Sema::CheckOMPRequiresDecl(SourceLocation Loc,
  3057. ArrayRef<OMPClause *> ClauseList) {
  3058. /// For target specific clauses, the requires directive cannot be
  3059. /// specified after the handling of any of the target regions in the
  3060. /// current compilation unit.
  3061. ArrayRef<SourceLocation> TargetLocations =
  3062. DSAStack->getEncounteredTargetLocs();
  3063. SourceLocation AtomicLoc = DSAStack->getAtomicDirectiveLoc();
  3064. if (!TargetLocations.empty() || !AtomicLoc.isInvalid()) {
  3065. for (const OMPClause *CNew : ClauseList) {
  3066. // Check if any of the requires clauses affect target regions.
  3067. if (isa<OMPUnifiedSharedMemoryClause>(CNew) ||
  3068. isa<OMPUnifiedAddressClause>(CNew) ||
  3069. isa<OMPReverseOffloadClause>(CNew) ||
  3070. isa<OMPDynamicAllocatorsClause>(CNew)) {
  3071. Diag(Loc, diag::err_omp_directive_before_requires)
  3072. << "target" << getOpenMPClauseName(CNew->getClauseKind());
  3073. for (SourceLocation TargetLoc : TargetLocations) {
  3074. Diag(TargetLoc, diag::note_omp_requires_encountered_directive)
  3075. << "target";
  3076. }
  3077. } else if (!AtomicLoc.isInvalid() &&
  3078. isa<OMPAtomicDefaultMemOrderClause>(CNew)) {
  3079. Diag(Loc, diag::err_omp_directive_before_requires)
  3080. << "atomic" << getOpenMPClauseName(CNew->getClauseKind());
  3081. Diag(AtomicLoc, diag::note_omp_requires_encountered_directive)
  3082. << "atomic";
  3083. }
  3084. }
  3085. }
  3086. if (!DSAStack->hasDuplicateRequiresClause(ClauseList))
  3087. return OMPRequiresDecl::Create(Context, getCurLexicalContext(), Loc,
  3088. ClauseList);
  3089. return nullptr;
  3090. }
  3091. static void reportOriginalDsa(Sema &SemaRef, const DSAStackTy *Stack,
  3092. const ValueDecl *D,
  3093. const DSAStackTy::DSAVarData &DVar,
  3094. bool IsLoopIterVar) {
  3095. if (DVar.RefExpr) {
  3096. SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
  3097. << getOpenMPClauseName(DVar.CKind);
  3098. return;
  3099. }
  3100. enum {
  3101. PDSA_StaticMemberShared,
  3102. PDSA_StaticLocalVarShared,
  3103. PDSA_LoopIterVarPrivate,
  3104. PDSA_LoopIterVarLinear,
  3105. PDSA_LoopIterVarLastprivate,
  3106. PDSA_ConstVarShared,
  3107. PDSA_GlobalVarShared,
  3108. PDSA_TaskVarFirstprivate,
  3109. PDSA_LocalVarPrivate,
  3110. PDSA_Implicit
  3111. } Reason = PDSA_Implicit;
  3112. bool ReportHint = false;
  3113. auto ReportLoc = D->getLocation();
  3114. auto *VD = dyn_cast<VarDecl>(D);
  3115. if (IsLoopIterVar) {
  3116. if (DVar.CKind == OMPC_private)
  3117. Reason = PDSA_LoopIterVarPrivate;
  3118. else if (DVar.CKind == OMPC_lastprivate)
  3119. Reason = PDSA_LoopIterVarLastprivate;
  3120. else
  3121. Reason = PDSA_LoopIterVarLinear;
  3122. } else if (isOpenMPTaskingDirective(DVar.DKind) &&
  3123. DVar.CKind == OMPC_firstprivate) {
  3124. Reason = PDSA_TaskVarFirstprivate;
  3125. ReportLoc = DVar.ImplicitDSALoc;
  3126. } else if (VD && VD->isStaticLocal())
  3127. Reason = PDSA_StaticLocalVarShared;
  3128. else if (VD && VD->isStaticDataMember())
  3129. Reason = PDSA_StaticMemberShared;
  3130. else if (VD && VD->isFileVarDecl())
  3131. Reason = PDSA_GlobalVarShared;
  3132. else if (D->getType().isConstant(SemaRef.getASTContext()))
  3133. Reason = PDSA_ConstVarShared;
  3134. else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
  3135. ReportHint = true;
  3136. Reason = PDSA_LocalVarPrivate;
  3137. }
  3138. if (Reason != PDSA_Implicit) {
  3139. SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
  3140. << Reason << ReportHint
  3141. << getOpenMPDirectiveName(Stack->getCurrentDirective());
  3142. } else if (DVar.ImplicitDSALoc.isValid()) {
  3143. SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
  3144. << getOpenMPClauseName(DVar.CKind);
  3145. }
  3146. }
  3147. static OpenMPMapClauseKind
  3148. getMapClauseKindFromModifier(OpenMPDefaultmapClauseModifier M,
  3149. bool IsAggregateOrDeclareTarget) {
  3150. OpenMPMapClauseKind Kind = OMPC_MAP_unknown;
  3151. switch (M) {
  3152. case OMPC_DEFAULTMAP_MODIFIER_alloc:
  3153. Kind = OMPC_MAP_alloc;
  3154. break;
  3155. case OMPC_DEFAULTMAP_MODIFIER_to:
  3156. Kind = OMPC_MAP_to;
  3157. break;
  3158. case OMPC_DEFAULTMAP_MODIFIER_from:
  3159. Kind = OMPC_MAP_from;
  3160. break;
  3161. case OMPC_DEFAULTMAP_MODIFIER_tofrom:
  3162. Kind = OMPC_MAP_tofrom;
  3163. break;
  3164. case OMPC_DEFAULTMAP_MODIFIER_present:
  3165. // OpenMP 5.1 [2.21.7.3] defaultmap clause, Description]
  3166. // If implicit-behavior is present, each variable referenced in the
  3167. // construct in the category specified by variable-category is treated as if
  3168. // it had been listed in a map clause with the map-type of alloc and
  3169. // map-type-modifier of present.
  3170. Kind = OMPC_MAP_alloc;
  3171. break;
  3172. case OMPC_DEFAULTMAP_MODIFIER_firstprivate:
  3173. case OMPC_DEFAULTMAP_MODIFIER_last:
  3174. llvm_unreachable("Unexpected defaultmap implicit behavior");
  3175. case OMPC_DEFAULTMAP_MODIFIER_none:
  3176. case OMPC_DEFAULTMAP_MODIFIER_default:
  3177. case OMPC_DEFAULTMAP_MODIFIER_unknown:
  3178. // IsAggregateOrDeclareTarget could be true if:
  3179. // 1. the implicit behavior for aggregate is tofrom
  3180. // 2. it's a declare target link
  3181. if (IsAggregateOrDeclareTarget) {
  3182. Kind = OMPC_MAP_tofrom;
  3183. break;
  3184. }
  3185. llvm_unreachable("Unexpected defaultmap implicit behavior");
  3186. }
  3187. assert(Kind != OMPC_MAP_unknown && "Expect map kind to be known");
  3188. return Kind;
  3189. }
  3190. namespace {
  3191. class DSAAttrChecker final : public StmtVisitor<DSAAttrChecker, void> {
  3192. DSAStackTy *Stack;
  3193. Sema &SemaRef;
  3194. bool ErrorFound = false;
  3195. bool TryCaptureCXXThisMembers = false;
  3196. CapturedStmt *CS = nullptr;
  3197. const static unsigned DefaultmapKindNum = OMPC_DEFAULTMAP_pointer + 1;
  3198. llvm::SmallVector<Expr *, 4> ImplicitFirstprivate;
  3199. llvm::SmallVector<Expr *, 4> ImplicitMap[DefaultmapKindNum][OMPC_MAP_delete];
  3200. llvm::SmallVector<OpenMPMapModifierKind, NumberOfOMPMapClauseModifiers>
  3201. ImplicitMapModifier[DefaultmapKindNum];
  3202. Sema::VarsWithInheritedDSAType VarsWithInheritedDSA;
  3203. llvm::SmallDenseSet<const ValueDecl *, 4> ImplicitDeclarations;
  3204. void VisitSubCaptures(OMPExecutableDirective *S) {
  3205. // Check implicitly captured variables.
  3206. if (!S->hasAssociatedStmt() || !S->getAssociatedStmt())
  3207. return;
  3208. if (S->getDirectiveKind() == OMPD_atomic ||
  3209. S->getDirectiveKind() == OMPD_critical ||
  3210. S->getDirectiveKind() == OMPD_section ||
  3211. S->getDirectiveKind() == OMPD_master ||
  3212. S->getDirectiveKind() == OMPD_masked ||
  3213. isOpenMPLoopTransformationDirective(S->getDirectiveKind())) {
  3214. Visit(S->getAssociatedStmt());
  3215. return;
  3216. }
  3217. visitSubCaptures(S->getInnermostCapturedStmt());
  3218. // Try to capture inner this->member references to generate correct mappings
  3219. // and diagnostics.
  3220. if (TryCaptureCXXThisMembers ||
  3221. (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) &&
  3222. llvm::any_of(S->getInnermostCapturedStmt()->captures(),
  3223. [](const CapturedStmt::Capture &C) {
  3224. return C.capturesThis();
  3225. }))) {
  3226. bool SavedTryCaptureCXXThisMembers = TryCaptureCXXThisMembers;
  3227. TryCaptureCXXThisMembers = true;
  3228. Visit(S->getInnermostCapturedStmt()->getCapturedStmt());
  3229. TryCaptureCXXThisMembers = SavedTryCaptureCXXThisMembers;
  3230. }
  3231. // In tasks firstprivates are not captured anymore, need to analyze them
  3232. // explicitly.
  3233. if (isOpenMPTaskingDirective(S->getDirectiveKind()) &&
  3234. !isOpenMPTaskLoopDirective(S->getDirectiveKind())) {
  3235. for (OMPClause *C : S->clauses())
  3236. if (auto *FC = dyn_cast<OMPFirstprivateClause>(C)) {
  3237. for (Expr *Ref : FC->varlists())
  3238. Visit(Ref);
  3239. }
  3240. }
  3241. }
  3242. public:
  3243. void VisitDeclRefExpr(DeclRefExpr *E) {
  3244. if (TryCaptureCXXThisMembers || E->isTypeDependent() ||
  3245. E->isValueDependent() || E->containsUnexpandedParameterPack() ||
  3246. E->isInstantiationDependent())
  3247. return;
  3248. if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
  3249. // Check the datasharing rules for the expressions in the clauses.
  3250. if (!CS || (isa<OMPCapturedExprDecl>(VD) && !CS->capturesVariable(VD) &&
  3251. !Stack->getTopDSA(VD, /*FromParent=*/false).RefExpr)) {
  3252. if (auto *CED = dyn_cast<OMPCapturedExprDecl>(VD))
  3253. if (!CED->hasAttr<OMPCaptureNoInitAttr>()) {
  3254. Visit(CED->getInit());
  3255. return;
  3256. }
  3257. } else if (VD->isImplicit() || isa<OMPCapturedExprDecl>(VD))
  3258. // Do not analyze internal variables and do not enclose them into
  3259. // implicit clauses.
  3260. return;
  3261. VD = VD->getCanonicalDecl();
  3262. // Skip internally declared variables.
  3263. if (VD->hasLocalStorage() && CS && !CS->capturesVariable(VD) &&
  3264. !Stack->isImplicitTaskFirstprivate(VD))
  3265. return;
  3266. // Skip allocators in uses_allocators clauses.
  3267. if (Stack->isUsesAllocatorsDecl(VD).hasValue())
  3268. return;
  3269. DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
  3270. // Check if the variable has explicit DSA set and stop analysis if it so.
  3271. if (DVar.RefExpr || !ImplicitDeclarations.insert(VD).second)
  3272. return;
  3273. // Skip internally declared static variables.
  3274. llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
  3275. OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
  3276. if (VD->hasGlobalStorage() && CS && !CS->capturesVariable(VD) &&
  3277. (Stack->hasRequiresDeclWithClause<OMPUnifiedSharedMemoryClause>() ||
  3278. !Res || *Res != OMPDeclareTargetDeclAttr::MT_Link) &&
  3279. !Stack->isImplicitTaskFirstprivate(VD))
  3280. return;
  3281. SourceLocation ELoc = E->getExprLoc();
  3282. OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
  3283. // The default(none) clause requires that each variable that is referenced
  3284. // in the construct, and does not have a predetermined data-sharing
  3285. // attribute, must have its data-sharing attribute explicitly determined
  3286. // by being listed in a data-sharing attribute clause.
  3287. if (DVar.CKind == OMPC_unknown &&
  3288. (Stack->getDefaultDSA() == DSA_none ||
  3289. Stack->getDefaultDSA() == DSA_firstprivate) &&
  3290. isImplicitOrExplicitTaskingRegion(DKind) &&
  3291. VarsWithInheritedDSA.count(VD) == 0) {
  3292. bool InheritedDSA = Stack->getDefaultDSA() == DSA_none;
  3293. if (!InheritedDSA && Stack->getDefaultDSA() == DSA_firstprivate) {
  3294. DSAStackTy::DSAVarData DVar =
  3295. Stack->getImplicitDSA(VD, /*FromParent=*/false);
  3296. InheritedDSA = DVar.CKind == OMPC_unknown;
  3297. }
  3298. if (InheritedDSA)
  3299. VarsWithInheritedDSA[VD] = E;
  3300. return;
  3301. }
  3302. // OpenMP 5.0 [2.19.7.2, defaultmap clause, Description]
  3303. // If implicit-behavior is none, each variable referenced in the
  3304. // construct that does not have a predetermined data-sharing attribute
  3305. // and does not appear in a to or link clause on a declare target
  3306. // directive must be listed in a data-mapping attribute clause, a
  3307. // data-haring attribute clause (including a data-sharing attribute
  3308. // clause on a combined construct where target. is one of the
  3309. // constituent constructs), or an is_device_ptr clause.
  3310. OpenMPDefaultmapClauseKind ClauseKind =
  3311. getVariableCategoryFromDecl(SemaRef.getLangOpts(), VD);
  3312. if (SemaRef.getLangOpts().OpenMP >= 50) {
  3313. bool IsModifierNone = Stack->getDefaultmapModifier(ClauseKind) ==
  3314. OMPC_DEFAULTMAP_MODIFIER_none;
  3315. if (DVar.CKind == OMPC_unknown && IsModifierNone &&
  3316. VarsWithInheritedDSA.count(VD) == 0 && !Res) {
  3317. // Only check for data-mapping attribute and is_device_ptr here
  3318. // since we have already make sure that the declaration does not
  3319. // have a data-sharing attribute above
  3320. if (!Stack->checkMappableExprComponentListsForDecl(
  3321. VD, /*CurrentRegionOnly=*/true,
  3322. [VD](OMPClauseMappableExprCommon::MappableExprComponentListRef
  3323. MapExprComponents,
  3324. OpenMPClauseKind) {
  3325. auto MI = MapExprComponents.rbegin();
  3326. auto ME = MapExprComponents.rend();
  3327. return MI != ME && MI->getAssociatedDeclaration() == VD;
  3328. })) {
  3329. VarsWithInheritedDSA[VD] = E;
  3330. return;
  3331. }
  3332. }
  3333. }
  3334. if (SemaRef.getLangOpts().OpenMP > 50) {
  3335. bool IsModifierPresent = Stack->getDefaultmapModifier(ClauseKind) ==
  3336. OMPC_DEFAULTMAP_MODIFIER_present;
  3337. if (IsModifierPresent) {
  3338. if (llvm::find(ImplicitMapModifier[ClauseKind],
  3339. OMPC_MAP_MODIFIER_present) ==
  3340. std::end(ImplicitMapModifier[ClauseKind])) {
  3341. ImplicitMapModifier[ClauseKind].push_back(
  3342. OMPC_MAP_MODIFIER_present);
  3343. }
  3344. }
  3345. }
  3346. if (isOpenMPTargetExecutionDirective(DKind) &&
  3347. !Stack->isLoopControlVariable(VD).first) {
  3348. if (!Stack->checkMappableExprComponentListsForDecl(
  3349. VD, /*CurrentRegionOnly=*/true,
  3350. [this](OMPClauseMappableExprCommon::MappableExprComponentListRef
  3351. StackComponents,
  3352. OpenMPClauseKind) {
  3353. if (SemaRef.LangOpts.OpenMP >= 50)
  3354. return !StackComponents.empty();
  3355. // Variable is used if it has been marked as an array, array
  3356. // section, array shaping or the variable iself.
  3357. return StackComponents.size() == 1 ||
  3358. std::all_of(
  3359. std::next(StackComponents.rbegin()),
  3360. StackComponents.rend(),
  3361. [](const OMPClauseMappableExprCommon::
  3362. MappableComponent &MC) {
  3363. return MC.getAssociatedDeclaration() ==
  3364. nullptr &&
  3365. (isa<OMPArraySectionExpr>(
  3366. MC.getAssociatedExpression()) ||
  3367. isa<OMPArrayShapingExpr>(
  3368. MC.getAssociatedExpression()) ||
  3369. isa<ArraySubscriptExpr>(
  3370. MC.getAssociatedExpression()));
  3371. });
  3372. })) {
  3373. bool IsFirstprivate = false;
  3374. // By default lambdas are captured as firstprivates.
  3375. if (const auto *RD =
  3376. VD->getType().getNonReferenceType()->getAsCXXRecordDecl())
  3377. IsFirstprivate = RD->isLambda();
  3378. IsFirstprivate =
  3379. IsFirstprivate || (Stack->mustBeFirstprivate(ClauseKind) && !Res);
  3380. if (IsFirstprivate) {
  3381. ImplicitFirstprivate.emplace_back(E);
  3382. } else {
  3383. OpenMPDefaultmapClauseModifier M =
  3384. Stack->getDefaultmapModifier(ClauseKind);
  3385. OpenMPMapClauseKind Kind = getMapClauseKindFromModifier(
  3386. M, ClauseKind == OMPC_DEFAULTMAP_aggregate || Res);
  3387. ImplicitMap[ClauseKind][Kind].emplace_back(E);
  3388. }
  3389. return;
  3390. }
  3391. }
  3392. // OpenMP [2.9.3.6, Restrictions, p.2]
  3393. // A list item that appears in a reduction clause of the innermost
  3394. // enclosing worksharing or parallel construct may not be accessed in an
  3395. // explicit task.
  3396. DVar = Stack->hasInnermostDSA(
  3397. VD,
  3398. [](OpenMPClauseKind C, bool AppliedToPointee) {
  3399. return C == OMPC_reduction && !AppliedToPointee;
  3400. },
  3401. [](OpenMPDirectiveKind K) {
  3402. return isOpenMPParallelDirective(K) ||
  3403. isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
  3404. },
  3405. /*FromParent=*/true);
  3406. if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
  3407. ErrorFound = true;
  3408. SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
  3409. reportOriginalDsa(SemaRef, Stack, VD, DVar);
  3410. return;
  3411. }
  3412. // Define implicit data-sharing attributes for task.
  3413. DVar = Stack->getImplicitDSA(VD, /*FromParent=*/false);
  3414. if (((isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared) ||
  3415. (Stack->getDefaultDSA() == DSA_firstprivate &&
  3416. DVar.CKind == OMPC_firstprivate && !DVar.RefExpr)) &&
  3417. !Stack->isLoopControlVariable(VD).first) {
  3418. ImplicitFirstprivate.push_back(E);
  3419. return;
  3420. }
  3421. // Store implicitly used globals with declare target link for parent
  3422. // target.
  3423. if (!isOpenMPTargetExecutionDirective(DKind) && Res &&
  3424. *Res == OMPDeclareTargetDeclAttr::MT_Link) {
  3425. Stack->addToParentTargetRegionLinkGlobals(E);
  3426. return;
  3427. }
  3428. }
  3429. }
  3430. void VisitMemberExpr(MemberExpr *E) {
  3431. if (E->isTypeDependent() || E->isValueDependent() ||
  3432. E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
  3433. return;
  3434. auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
  3435. OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
  3436. if (auto *TE = dyn_cast<CXXThisExpr>(E->getBase()->IgnoreParenCasts())) {
  3437. if (!FD)
  3438. return;
  3439. DSAStackTy::DSAVarData DVar = Stack->getTopDSA(FD, /*FromParent=*/false);
  3440. // Check if the variable has explicit DSA set and stop analysis if it
  3441. // so.
  3442. if (DVar.RefExpr || !ImplicitDeclarations.insert(FD).second)
  3443. return;
  3444. if (isOpenMPTargetExecutionDirective(DKind) &&
  3445. !Stack->isLoopControlVariable(FD).first &&
  3446. !Stack->checkMappableExprComponentListsForDecl(
  3447. FD, /*CurrentRegionOnly=*/true,
  3448. [](OMPClauseMappableExprCommon::MappableExprComponentListRef
  3449. StackComponents,
  3450. OpenMPClauseKind) {
  3451. return isa<CXXThisExpr>(
  3452. cast<MemberExpr>(
  3453. StackComponents.back().getAssociatedExpression())
  3454. ->getBase()
  3455. ->IgnoreParens());
  3456. })) {
  3457. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
  3458. // A bit-field cannot appear in a map clause.
  3459. //
  3460. if (FD->isBitField())
  3461. return;
  3462. // Check to see if the member expression is referencing a class that
  3463. // has already been explicitly mapped
  3464. if (Stack->isClassPreviouslyMapped(TE->getType()))
  3465. return;
  3466. OpenMPDefaultmapClauseModifier Modifier =
  3467. Stack->getDefaultmapModifier(OMPC_DEFAULTMAP_aggregate);
  3468. OpenMPDefaultmapClauseKind ClauseKind =
  3469. getVariableCategoryFromDecl(SemaRef.getLangOpts(), FD);
  3470. OpenMPMapClauseKind Kind = getMapClauseKindFromModifier(
  3471. Modifier, /*IsAggregateOrDeclareTarget*/ true);
  3472. ImplicitMap[ClauseKind][Kind].emplace_back(E);
  3473. return;
  3474. }
  3475. SourceLocation ELoc = E->getExprLoc();
  3476. // OpenMP [2.9.3.6, Restrictions, p.2]
  3477. // A list item that appears in a reduction clause of the innermost
  3478. // enclosing worksharing or parallel construct may not be accessed in
  3479. // an explicit task.
  3480. DVar = Stack->hasInnermostDSA(
  3481. FD,
  3482. [](OpenMPClauseKind C, bool AppliedToPointee) {
  3483. return C == OMPC_reduction && !AppliedToPointee;
  3484. },
  3485. [](OpenMPDirectiveKind K) {
  3486. return isOpenMPParallelDirective(K) ||
  3487. isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
  3488. },
  3489. /*FromParent=*/true);
  3490. if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
  3491. ErrorFound = true;
  3492. SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
  3493. reportOriginalDsa(SemaRef, Stack, FD, DVar);
  3494. return;
  3495. }
  3496. // Define implicit data-sharing attributes for task.
  3497. DVar = Stack->getImplicitDSA(FD, /*FromParent=*/false);
  3498. if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
  3499. !Stack->isLoopControlVariable(FD).first) {
  3500. // Check if there is a captured expression for the current field in the
  3501. // region. Do not mark it as firstprivate unless there is no captured
  3502. // expression.
  3503. // TODO: try to make it firstprivate.
  3504. if (DVar.CKind != OMPC_unknown)
  3505. ImplicitFirstprivate.push_back(E);
  3506. }
  3507. return;
  3508. }
  3509. if (isOpenMPTargetExecutionDirective(DKind)) {
  3510. OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
  3511. if (!checkMapClauseExpressionBase(SemaRef, E, CurComponents, OMPC_map,
  3512. Stack->getCurrentDirective(),
  3513. /*NoDiagnose=*/true))
  3514. return;
  3515. const auto *VD = cast<ValueDecl>(
  3516. CurComponents.back().getAssociatedDeclaration()->getCanonicalDecl());
  3517. if (!Stack->checkMappableExprComponentListsForDecl(
  3518. VD, /*CurrentRegionOnly=*/true,
  3519. [&CurComponents](
  3520. OMPClauseMappableExprCommon::MappableExprComponentListRef
  3521. StackComponents,
  3522. OpenMPClauseKind) {
  3523. auto CCI = CurComponents.rbegin();
  3524. auto CCE = CurComponents.rend();
  3525. for (const auto &SC : llvm::reverse(StackComponents)) {
  3526. // Do both expressions have the same kind?
  3527. if (CCI->getAssociatedExpression()->getStmtClass() !=
  3528. SC.getAssociatedExpression()->getStmtClass())
  3529. if (!((isa<OMPArraySectionExpr>(
  3530. SC.getAssociatedExpression()) ||
  3531. isa<OMPArrayShapingExpr>(
  3532. SC.getAssociatedExpression())) &&
  3533. isa<ArraySubscriptExpr>(
  3534. CCI->getAssociatedExpression())))
  3535. return false;
  3536. const Decl *CCD = CCI->getAssociatedDeclaration();
  3537. const Decl *SCD = SC.getAssociatedDeclaration();
  3538. CCD = CCD ? CCD->getCanonicalDecl() : nullptr;
  3539. SCD = SCD ? SCD->getCanonicalDecl() : nullptr;
  3540. if (SCD != CCD)
  3541. return false;
  3542. std::advance(CCI, 1);
  3543. if (CCI == CCE)
  3544. break;
  3545. }
  3546. return true;
  3547. })) {
  3548. Visit(E->getBase());
  3549. }
  3550. } else if (!TryCaptureCXXThisMembers) {
  3551. Visit(E->getBase());
  3552. }
  3553. }
  3554. void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
  3555. for (OMPClause *C : S->clauses()) {
  3556. // Skip analysis of arguments of private clauses for task|target
  3557. // directives.
  3558. if (isa_and_nonnull<OMPPrivateClause>(C))
  3559. continue;
  3560. // Skip analysis of arguments of implicitly defined firstprivate clause
  3561. // for task|target directives.
  3562. // Skip analysis of arguments of implicitly defined map clause for target
  3563. // directives.
  3564. if (C && !((isa<OMPFirstprivateClause>(C) || isa<OMPMapClause>(C)) &&
  3565. C->isImplicit() &&
  3566. !isOpenMPTaskingDirective(Stack->getCurrentDirective()))) {
  3567. for (Stmt *CC : C->children()) {
  3568. if (CC)
  3569. Visit(CC);
  3570. }
  3571. }
  3572. }
  3573. // Check implicitly captured variables.
  3574. VisitSubCaptures(S);
  3575. }
  3576. void VisitOMPLoopTransformationDirective(OMPLoopTransformationDirective *S) {
  3577. // Loop transformation directives do not introduce data sharing
  3578. VisitStmt(S);
  3579. }
  3580. void VisitCallExpr(CallExpr *S) {
  3581. for (Stmt *C : S->arguments()) {
  3582. if (C) {
  3583. // Check implicitly captured variables in the task-based directives to
  3584. // check if they must be firstprivatized.
  3585. Visit(C);
  3586. }
  3587. }
  3588. if (Expr *Callee = S->getCallee())
  3589. if (auto *CE = dyn_cast<MemberExpr>(Callee->IgnoreParenImpCasts()))
  3590. Visit(CE->getBase());
  3591. }
  3592. void VisitStmt(Stmt *S) {
  3593. for (Stmt *C : S->children()) {
  3594. if (C) {
  3595. // Check implicitly captured variables in the task-based directives to
  3596. // check if they must be firstprivatized.
  3597. Visit(C);
  3598. }
  3599. }
  3600. }
  3601. void visitSubCaptures(CapturedStmt *S) {
  3602. for (const CapturedStmt::Capture &Cap : S->captures()) {
  3603. if (!Cap.capturesVariable() && !Cap.capturesVariableByCopy())
  3604. continue;
  3605. VarDecl *VD = Cap.getCapturedVar();
  3606. // Do not try to map the variable if it or its sub-component was mapped
  3607. // already.
  3608. if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) &&
  3609. Stack->checkMappableExprComponentListsForDecl(
  3610. VD, /*CurrentRegionOnly=*/true,
  3611. [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
  3612. OpenMPClauseKind) { return true; }))
  3613. continue;
  3614. DeclRefExpr *DRE = buildDeclRefExpr(
  3615. SemaRef, VD, VD->getType().getNonLValueExprType(SemaRef.Context),
  3616. Cap.getLocation(), /*RefersToCapture=*/true);
  3617. Visit(DRE);
  3618. }
  3619. }
  3620. bool isErrorFound() const { return ErrorFound; }
  3621. ArrayRef<Expr *> getImplicitFirstprivate() const {
  3622. return ImplicitFirstprivate;
  3623. }
  3624. ArrayRef<Expr *> getImplicitMap(OpenMPDefaultmapClauseKind DK,
  3625. OpenMPMapClauseKind MK) const {
  3626. return ImplicitMap[DK][MK];
  3627. }
  3628. ArrayRef<OpenMPMapModifierKind>
  3629. getImplicitMapModifier(OpenMPDefaultmapClauseKind Kind) const {
  3630. return ImplicitMapModifier[Kind];
  3631. }
  3632. const Sema::VarsWithInheritedDSAType &getVarsWithInheritedDSA() const {
  3633. return VarsWithInheritedDSA;
  3634. }
  3635. DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
  3636. : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {
  3637. // Process declare target link variables for the target directives.
  3638. if (isOpenMPTargetExecutionDirective(S->getCurrentDirective())) {
  3639. for (DeclRefExpr *E : Stack->getLinkGlobals())
  3640. Visit(E);
  3641. }
  3642. }
  3643. };
  3644. } // namespace
  3645. static void handleDeclareVariantConstructTrait(DSAStackTy *Stack,
  3646. OpenMPDirectiveKind DKind,
  3647. bool ScopeEntry) {
  3648. SmallVector<llvm::omp::TraitProperty, 8> Traits;
  3649. if (isOpenMPTargetExecutionDirective(DKind))
  3650. Traits.emplace_back(llvm::omp::TraitProperty::construct_target_target);
  3651. if (isOpenMPTeamsDirective(DKind))
  3652. Traits.emplace_back(llvm::omp::TraitProperty::construct_teams_teams);
  3653. if (isOpenMPParallelDirective(DKind))
  3654. Traits.emplace_back(llvm::omp::TraitProperty::construct_parallel_parallel);
  3655. if (isOpenMPWorksharingDirective(DKind))
  3656. Traits.emplace_back(llvm::omp::TraitProperty::construct_for_for);
  3657. if (isOpenMPSimdDirective(DKind))
  3658. Traits.emplace_back(llvm::omp::TraitProperty::construct_simd_simd);
  3659. Stack->handleConstructTrait(Traits, ScopeEntry);
  3660. }
  3661. void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
  3662. switch (DKind) {
  3663. case OMPD_parallel:
  3664. case OMPD_parallel_for:
  3665. case OMPD_parallel_for_simd:
  3666. case OMPD_parallel_sections:
  3667. case OMPD_parallel_master:
  3668. case OMPD_teams:
  3669. case OMPD_teams_distribute:
  3670. case OMPD_teams_distribute_simd: {
  3671. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
  3672. QualType KmpInt32PtrTy =
  3673. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  3674. Sema::CapturedParamNameType Params[] = {
  3675. std::make_pair(".global_tid.", KmpInt32PtrTy),
  3676. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  3677. std::make_pair(StringRef(), QualType()) // __context with shared vars
  3678. };
  3679. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  3680. Params);
  3681. break;
  3682. }
  3683. case OMPD_target_teams:
  3684. case OMPD_target_parallel:
  3685. case OMPD_target_parallel_for:
  3686. case OMPD_target_parallel_for_simd:
  3687. case OMPD_target_teams_distribute:
  3688. case OMPD_target_teams_distribute_simd: {
  3689. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
  3690. QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
  3691. QualType KmpInt32PtrTy =
  3692. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  3693. QualType Args[] = {VoidPtrTy};
  3694. FunctionProtoType::ExtProtoInfo EPI;
  3695. EPI.Variadic = true;
  3696. QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
  3697. Sema::CapturedParamNameType Params[] = {
  3698. std::make_pair(".global_tid.", KmpInt32Ty),
  3699. std::make_pair(".part_id.", KmpInt32PtrTy),
  3700. std::make_pair(".privates.", VoidPtrTy),
  3701. std::make_pair(
  3702. ".copy_fn.",
  3703. Context.getPointerType(CopyFnType).withConst().withRestrict()),
  3704. std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
  3705. std::make_pair(StringRef(), QualType()) // __context with shared vars
  3706. };
  3707. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  3708. Params, /*OpenMPCaptureLevel=*/0);
  3709. // Mark this captured region as inlined, because we don't use outlined
  3710. // function directly.
  3711. getCurCapturedRegion()->TheCapturedDecl->addAttr(
  3712. AlwaysInlineAttr::CreateImplicit(
  3713. Context, {}, AttributeCommonInfo::AS_Keyword,
  3714. AlwaysInlineAttr::Keyword_forceinline));
  3715. Sema::CapturedParamNameType ParamsTarget[] = {
  3716. std::make_pair(StringRef(), QualType()) // __context with shared vars
  3717. };
  3718. // Start a captured region for 'target' with no implicit parameters.
  3719. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  3720. ParamsTarget, /*OpenMPCaptureLevel=*/1);
  3721. Sema::CapturedParamNameType ParamsTeamsOrParallel[] = {
  3722. std::make_pair(".global_tid.", KmpInt32PtrTy),
  3723. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  3724. std::make_pair(StringRef(), QualType()) // __context with shared vars
  3725. };
  3726. // Start a captured region for 'teams' or 'parallel'. Both regions have
  3727. // the same implicit parameters.
  3728. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  3729. ParamsTeamsOrParallel, /*OpenMPCaptureLevel=*/2);
  3730. break;
  3731. }
  3732. case OMPD_target:
  3733. case OMPD_target_simd: {
  3734. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
  3735. QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
  3736. QualType KmpInt32PtrTy =
  3737. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  3738. QualType Args[] = {VoidPtrTy};
  3739. FunctionProtoType::ExtProtoInfo EPI;
  3740. EPI.Variadic = true;
  3741. QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
  3742. Sema::CapturedParamNameType Params[] = {
  3743. std::make_pair(".global_tid.", KmpInt32Ty),
  3744. std::make_pair(".part_id.", KmpInt32PtrTy),
  3745. std::make_pair(".privates.", VoidPtrTy),
  3746. std::make_pair(
  3747. ".copy_fn.",
  3748. Context.getPointerType(CopyFnType).withConst().withRestrict()),
  3749. std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
  3750. std::make_pair(StringRef(), QualType()) // __context with shared vars
  3751. };
  3752. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  3753. Params, /*OpenMPCaptureLevel=*/0);
  3754. // Mark this captured region as inlined, because we don't use outlined
  3755. // function directly.
  3756. getCurCapturedRegion()->TheCapturedDecl->addAttr(
  3757. AlwaysInlineAttr::CreateImplicit(
  3758. Context, {}, AttributeCommonInfo::AS_Keyword,
  3759. AlwaysInlineAttr::Keyword_forceinline));
  3760. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  3761. std::make_pair(StringRef(), QualType()),
  3762. /*OpenMPCaptureLevel=*/1);
  3763. break;
  3764. }
  3765. case OMPD_atomic:
  3766. case OMPD_critical:
  3767. case OMPD_section:
  3768. case OMPD_master:
  3769. case OMPD_masked:
  3770. case OMPD_tile:
  3771. case OMPD_unroll:
  3772. break;
  3773. case OMPD_loop:
  3774. // TODO: 'loop' may require additional parameters depending on the binding.
  3775. // Treat similar to OMPD_simd/OMPD_for for now.
  3776. case OMPD_simd:
  3777. case OMPD_for:
  3778. case OMPD_for_simd:
  3779. case OMPD_sections:
  3780. case OMPD_single:
  3781. case OMPD_taskgroup:
  3782. case OMPD_distribute:
  3783. case OMPD_distribute_simd:
  3784. case OMPD_ordered:
  3785. case OMPD_target_data:
  3786. case OMPD_dispatch: {
  3787. Sema::CapturedParamNameType Params[] = {
  3788. std::make_pair(StringRef(), QualType()) // __context with shared vars
  3789. };
  3790. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  3791. Params);
  3792. break;
  3793. }
  3794. case OMPD_task: {
  3795. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
  3796. QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
  3797. QualType KmpInt32PtrTy =
  3798. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  3799. QualType Args[] = {VoidPtrTy};
  3800. FunctionProtoType::ExtProtoInfo EPI;
  3801. EPI.Variadic = true;
  3802. QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
  3803. Sema::CapturedParamNameType Params[] = {
  3804. std::make_pair(".global_tid.", KmpInt32Ty),
  3805. std::make_pair(".part_id.", KmpInt32PtrTy),
  3806. std::make_pair(".privates.", VoidPtrTy),
  3807. std::make_pair(
  3808. ".copy_fn.",
  3809. Context.getPointerType(CopyFnType).withConst().withRestrict()),
  3810. std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
  3811. std::make_pair(StringRef(), QualType()) // __context with shared vars
  3812. };
  3813. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  3814. Params);
  3815. // Mark this captured region as inlined, because we don't use outlined
  3816. // function directly.
  3817. getCurCapturedRegion()->TheCapturedDecl->addAttr(
  3818. AlwaysInlineAttr::CreateImplicit(
  3819. Context, {}, AttributeCommonInfo::AS_Keyword,
  3820. AlwaysInlineAttr::Keyword_forceinline));
  3821. break;
  3822. }
  3823. case OMPD_taskloop:
  3824. case OMPD_taskloop_simd:
  3825. case OMPD_master_taskloop:
  3826. case OMPD_master_taskloop_simd: {
  3827. QualType KmpInt32Ty =
  3828. Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1)
  3829. .withConst();
  3830. QualType KmpUInt64Ty =
  3831. Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0)
  3832. .withConst();
  3833. QualType KmpInt64Ty =
  3834. Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1)
  3835. .withConst();
  3836. QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
  3837. QualType KmpInt32PtrTy =
  3838. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  3839. QualType Args[] = {VoidPtrTy};
  3840. FunctionProtoType::ExtProtoInfo EPI;
  3841. EPI.Variadic = true;
  3842. QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
  3843. Sema::CapturedParamNameType Params[] = {
  3844. std::make_pair(".global_tid.", KmpInt32Ty),
  3845. std::make_pair(".part_id.", KmpInt32PtrTy),
  3846. std::make_pair(".privates.", VoidPtrTy),
  3847. std::make_pair(
  3848. ".copy_fn.",
  3849. Context.getPointerType(CopyFnType).withConst().withRestrict()),
  3850. std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
  3851. std::make_pair(".lb.", KmpUInt64Ty),
  3852. std::make_pair(".ub.", KmpUInt64Ty),
  3853. std::make_pair(".st.", KmpInt64Ty),
  3854. std::make_pair(".liter.", KmpInt32Ty),
  3855. std::make_pair(".reductions.", VoidPtrTy),
  3856. std::make_pair(StringRef(), QualType()) // __context with shared vars
  3857. };
  3858. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  3859. Params);
  3860. // Mark this captured region as inlined, because we don't use outlined
  3861. // function directly.
  3862. getCurCapturedRegion()->TheCapturedDecl->addAttr(
  3863. AlwaysInlineAttr::CreateImplicit(
  3864. Context, {}, AttributeCommonInfo::AS_Keyword,
  3865. AlwaysInlineAttr::Keyword_forceinline));
  3866. break;
  3867. }
  3868. case OMPD_parallel_master_taskloop:
  3869. case OMPD_parallel_master_taskloop_simd: {
  3870. QualType KmpInt32Ty =
  3871. Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1)
  3872. .withConst();
  3873. QualType KmpUInt64Ty =
  3874. Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0)
  3875. .withConst();
  3876. QualType KmpInt64Ty =
  3877. Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1)
  3878. .withConst();
  3879. QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
  3880. QualType KmpInt32PtrTy =
  3881. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  3882. Sema::CapturedParamNameType ParamsParallel[] = {
  3883. std::make_pair(".global_tid.", KmpInt32PtrTy),
  3884. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  3885. std::make_pair(StringRef(), QualType()) // __context with shared vars
  3886. };
  3887. // Start a captured region for 'parallel'.
  3888. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  3889. ParamsParallel, /*OpenMPCaptureLevel=*/0);
  3890. QualType Args[] = {VoidPtrTy};
  3891. FunctionProtoType::ExtProtoInfo EPI;
  3892. EPI.Variadic = true;
  3893. QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
  3894. Sema::CapturedParamNameType Params[] = {
  3895. std::make_pair(".global_tid.", KmpInt32Ty),
  3896. std::make_pair(".part_id.", KmpInt32PtrTy),
  3897. std::make_pair(".privates.", VoidPtrTy),
  3898. std::make_pair(
  3899. ".copy_fn.",
  3900. Context.getPointerType(CopyFnType).withConst().withRestrict()),
  3901. std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
  3902. std::make_pair(".lb.", KmpUInt64Ty),
  3903. std::make_pair(".ub.", KmpUInt64Ty),
  3904. std::make_pair(".st.", KmpInt64Ty),
  3905. std::make_pair(".liter.", KmpInt32Ty),
  3906. std::make_pair(".reductions.", VoidPtrTy),
  3907. std::make_pair(StringRef(), QualType()) // __context with shared vars
  3908. };
  3909. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  3910. Params, /*OpenMPCaptureLevel=*/1);
  3911. // Mark this captured region as inlined, because we don't use outlined
  3912. // function directly.
  3913. getCurCapturedRegion()->TheCapturedDecl->addAttr(
  3914. AlwaysInlineAttr::CreateImplicit(
  3915. Context, {}, AttributeCommonInfo::AS_Keyword,
  3916. AlwaysInlineAttr::Keyword_forceinline));
  3917. break;
  3918. }
  3919. case OMPD_distribute_parallel_for_simd:
  3920. case OMPD_distribute_parallel_for: {
  3921. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
  3922. QualType KmpInt32PtrTy =
  3923. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  3924. Sema::CapturedParamNameType Params[] = {
  3925. std::make_pair(".global_tid.", KmpInt32PtrTy),
  3926. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  3927. std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
  3928. std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
  3929. std::make_pair(StringRef(), QualType()) // __context with shared vars
  3930. };
  3931. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  3932. Params);
  3933. break;
  3934. }
  3935. case OMPD_target_teams_distribute_parallel_for:
  3936. case OMPD_target_teams_distribute_parallel_for_simd: {
  3937. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
  3938. QualType KmpInt32PtrTy =
  3939. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  3940. QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
  3941. QualType Args[] = {VoidPtrTy};
  3942. FunctionProtoType::ExtProtoInfo EPI;
  3943. EPI.Variadic = true;
  3944. QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
  3945. Sema::CapturedParamNameType Params[] = {
  3946. std::make_pair(".global_tid.", KmpInt32Ty),
  3947. std::make_pair(".part_id.", KmpInt32PtrTy),
  3948. std::make_pair(".privates.", VoidPtrTy),
  3949. std::make_pair(
  3950. ".copy_fn.",
  3951. Context.getPointerType(CopyFnType).withConst().withRestrict()),
  3952. std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
  3953. std::make_pair(StringRef(), QualType()) // __context with shared vars
  3954. };
  3955. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  3956. Params, /*OpenMPCaptureLevel=*/0);
  3957. // Mark this captured region as inlined, because we don't use outlined
  3958. // function directly.
  3959. getCurCapturedRegion()->TheCapturedDecl->addAttr(
  3960. AlwaysInlineAttr::CreateImplicit(
  3961. Context, {}, AttributeCommonInfo::AS_Keyword,
  3962. AlwaysInlineAttr::Keyword_forceinline));
  3963. Sema::CapturedParamNameType ParamsTarget[] = {
  3964. std::make_pair(StringRef(), QualType()) // __context with shared vars
  3965. };
  3966. // Start a captured region for 'target' with no implicit parameters.
  3967. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  3968. ParamsTarget, /*OpenMPCaptureLevel=*/1);
  3969. Sema::CapturedParamNameType ParamsTeams[] = {
  3970. std::make_pair(".global_tid.", KmpInt32PtrTy),
  3971. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  3972. std::make_pair(StringRef(), QualType()) // __context with shared vars
  3973. };
  3974. // Start a captured region for 'target' with no implicit parameters.
  3975. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  3976. ParamsTeams, /*OpenMPCaptureLevel=*/2);
  3977. Sema::CapturedParamNameType ParamsParallel[] = {
  3978. std::make_pair(".global_tid.", KmpInt32PtrTy),
  3979. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  3980. std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
  3981. std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
  3982. std::make_pair(StringRef(), QualType()) // __context with shared vars
  3983. };
  3984. // Start a captured region for 'teams' or 'parallel'. Both regions have
  3985. // the same implicit parameters.
  3986. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  3987. ParamsParallel, /*OpenMPCaptureLevel=*/3);
  3988. break;
  3989. }
  3990. case OMPD_teams_distribute_parallel_for:
  3991. case OMPD_teams_distribute_parallel_for_simd: {
  3992. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
  3993. QualType KmpInt32PtrTy =
  3994. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  3995. Sema::CapturedParamNameType ParamsTeams[] = {
  3996. std::make_pair(".global_tid.", KmpInt32PtrTy),
  3997. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  3998. std::make_pair(StringRef(), QualType()) // __context with shared vars
  3999. };
  4000. // Start a captured region for 'target' with no implicit parameters.
  4001. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  4002. ParamsTeams, /*OpenMPCaptureLevel=*/0);
  4003. Sema::CapturedParamNameType ParamsParallel[] = {
  4004. std::make_pair(".global_tid.", KmpInt32PtrTy),
  4005. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  4006. std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
  4007. std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
  4008. std::make_pair(StringRef(), QualType()) // __context with shared vars
  4009. };
  4010. // Start a captured region for 'teams' or 'parallel'. Both regions have
  4011. // the same implicit parameters.
  4012. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  4013. ParamsParallel, /*OpenMPCaptureLevel=*/1);
  4014. break;
  4015. }
  4016. case OMPD_target_update:
  4017. case OMPD_target_enter_data:
  4018. case OMPD_target_exit_data: {
  4019. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
  4020. QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
  4021. QualType KmpInt32PtrTy =
  4022. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  4023. QualType Args[] = {VoidPtrTy};
  4024. FunctionProtoType::ExtProtoInfo EPI;
  4025. EPI.Variadic = true;
  4026. QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
  4027. Sema::CapturedParamNameType Params[] = {
  4028. std::make_pair(".global_tid.", KmpInt32Ty),
  4029. std::make_pair(".part_id.", KmpInt32PtrTy),
  4030. std::make_pair(".privates.", VoidPtrTy),
  4031. std::make_pair(
  4032. ".copy_fn.",
  4033. Context.getPointerType(CopyFnType).withConst().withRestrict()),
  4034. std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
  4035. std::make_pair(StringRef(), QualType()) // __context with shared vars
  4036. };
  4037. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  4038. Params);
  4039. // Mark this captured region as inlined, because we don't use outlined
  4040. // function directly.
  4041. getCurCapturedRegion()->TheCapturedDecl->addAttr(
  4042. AlwaysInlineAttr::CreateImplicit(
  4043. Context, {}, AttributeCommonInfo::AS_Keyword,
  4044. AlwaysInlineAttr::Keyword_forceinline));
  4045. break;
  4046. }
  4047. case OMPD_threadprivate:
  4048. case OMPD_allocate:
  4049. case OMPD_taskyield:
  4050. case OMPD_barrier:
  4051. case OMPD_taskwait:
  4052. case OMPD_cancellation_point:
  4053. case OMPD_cancel:
  4054. case OMPD_flush:
  4055. case OMPD_depobj:
  4056. case OMPD_scan:
  4057. case OMPD_declare_reduction:
  4058. case OMPD_declare_mapper:
  4059. case OMPD_declare_simd:
  4060. case OMPD_declare_target:
  4061. case OMPD_end_declare_target:
  4062. case OMPD_requires:
  4063. case OMPD_declare_variant:
  4064. case OMPD_begin_declare_variant:
  4065. case OMPD_end_declare_variant:
  4066. case OMPD_metadirective:
  4067. llvm_unreachable("OpenMP Directive is not allowed");
  4068. case OMPD_unknown:
  4069. default:
  4070. llvm_unreachable("Unknown OpenMP directive");
  4071. }
  4072. DSAStack->setContext(CurContext);
  4073. handleDeclareVariantConstructTrait(DSAStack, DKind, /* ScopeEntry */ true);
  4074. }
  4075. int Sema::getNumberOfConstructScopes(unsigned Level) const {
  4076. return getOpenMPCaptureLevels(DSAStack->getDirective(Level));
  4077. }
  4078. int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) {
  4079. SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
  4080. getOpenMPCaptureRegions(CaptureRegions, DKind);
  4081. return CaptureRegions.size();
  4082. }
  4083. static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
  4084. Expr *CaptureExpr, bool WithInit,
  4085. bool AsExpression) {
  4086. assert(CaptureExpr);
  4087. ASTContext &C = S.getASTContext();
  4088. Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
  4089. QualType Ty = Init->getType();
  4090. if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
  4091. if (S.getLangOpts().CPlusPlus) {
  4092. Ty = C.getLValueReferenceType(Ty);
  4093. } else {
  4094. Ty = C.getPointerType(Ty);
  4095. ExprResult Res =
  4096. S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
  4097. if (!Res.isUsable())
  4098. return nullptr;
  4099. Init = Res.get();
  4100. }
  4101. WithInit = true;
  4102. }
  4103. auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty,
  4104. CaptureExpr->getBeginLoc());
  4105. if (!WithInit)
  4106. CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C));
  4107. S.CurContext->addHiddenDecl(CED);
  4108. Sema::TentativeAnalysisScope Trap(S);
  4109. S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false);
  4110. return CED;
  4111. }
  4112. static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
  4113. bool WithInit) {
  4114. OMPCapturedExprDecl *CD;
  4115. if (VarDecl *VD = S.isOpenMPCapturedDecl(D))
  4116. CD = cast<OMPCapturedExprDecl>(VD);
  4117. else
  4118. CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
  4119. /*AsExpression=*/false);
  4120. return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
  4121. CaptureExpr->getExprLoc());
  4122. }
  4123. static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
  4124. CaptureExpr = S.DefaultLvalueConversion(CaptureExpr).get();
  4125. if (!Ref) {
  4126. OMPCapturedExprDecl *CD = buildCaptureDecl(
  4127. S, &S.getASTContext().Idents.get(".capture_expr."), CaptureExpr,
  4128. /*WithInit=*/true, /*AsExpression=*/true);
  4129. Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
  4130. CaptureExpr->getExprLoc());
  4131. }
  4132. ExprResult Res = Ref;
  4133. if (!S.getLangOpts().CPlusPlus &&
  4134. CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
  4135. Ref->getType()->isPointerType()) {
  4136. Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
  4137. if (!Res.isUsable())
  4138. return ExprError();
  4139. }
  4140. return S.DefaultLvalueConversion(Res.get());
  4141. }
  4142. namespace {
  4143. // OpenMP directives parsed in this section are represented as a
  4144. // CapturedStatement with an associated statement. If a syntax error
  4145. // is detected during the parsing of the associated statement, the
  4146. // compiler must abort processing and close the CapturedStatement.
  4147. //
  4148. // Combined directives such as 'target parallel' have more than one
  4149. // nested CapturedStatements. This RAII ensures that we unwind out
  4150. // of all the nested CapturedStatements when an error is found.
  4151. class CaptureRegionUnwinderRAII {
  4152. private:
  4153. Sema &S;
  4154. bool &ErrorFound;
  4155. OpenMPDirectiveKind DKind = OMPD_unknown;
  4156. public:
  4157. CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound,
  4158. OpenMPDirectiveKind DKind)
  4159. : S(S), ErrorFound(ErrorFound), DKind(DKind) {}
  4160. ~CaptureRegionUnwinderRAII() {
  4161. if (ErrorFound) {
  4162. int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind);
  4163. while (--ThisCaptureLevel >= 0)
  4164. S.ActOnCapturedRegionError();
  4165. }
  4166. }
  4167. };
  4168. } // namespace
  4169. void Sema::tryCaptureOpenMPLambdas(ValueDecl *V) {
  4170. // Capture variables captured by reference in lambdas for target-based
  4171. // directives.
  4172. if (!CurContext->isDependentContext() &&
  4173. (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) ||
  4174. isOpenMPTargetDataManagementDirective(
  4175. DSAStack->getCurrentDirective()))) {
  4176. QualType Type = V->getType();
  4177. if (const auto *RD = Type.getCanonicalType()
  4178. .getNonReferenceType()
  4179. ->getAsCXXRecordDecl()) {
  4180. bool SavedForceCaptureByReferenceInTargetExecutable =
  4181. DSAStack->isForceCaptureByReferenceInTargetExecutable();
  4182. DSAStack->setForceCaptureByReferenceInTargetExecutable(
  4183. /*V=*/true);
  4184. if (RD->isLambda()) {
  4185. llvm::DenseMap<const VarDecl *, FieldDecl *> Captures;
  4186. FieldDecl *ThisCapture;
  4187. RD->getCaptureFields(Captures, ThisCapture);
  4188. for (const LambdaCapture &LC : RD->captures()) {
  4189. if (LC.getCaptureKind() == LCK_ByRef) {
  4190. VarDecl *VD = LC.getCapturedVar();
  4191. DeclContext *VDC = VD->getDeclContext();
  4192. if (!VDC->Encloses(CurContext))
  4193. continue;
  4194. MarkVariableReferenced(LC.getLocation(), VD);
  4195. } else if (LC.getCaptureKind() == LCK_This) {
  4196. QualType ThisTy = getCurrentThisType();
  4197. if (!ThisTy.isNull() &&
  4198. Context.typesAreCompatible(ThisTy, ThisCapture->getType()))
  4199. CheckCXXThisCapture(LC.getLocation());
  4200. }
  4201. }
  4202. }
  4203. DSAStack->setForceCaptureByReferenceInTargetExecutable(
  4204. SavedForceCaptureByReferenceInTargetExecutable);
  4205. }
  4206. }
  4207. }
  4208. static bool checkOrderedOrderSpecified(Sema &S,
  4209. const ArrayRef<OMPClause *> Clauses) {
  4210. const OMPOrderedClause *Ordered = nullptr;
  4211. const OMPOrderClause *Order = nullptr;
  4212. for (const OMPClause *Clause : Clauses) {
  4213. if (Clause->getClauseKind() == OMPC_ordered)
  4214. Ordered = cast<OMPOrderedClause>(Clause);
  4215. else if (Clause->getClauseKind() == OMPC_order) {
  4216. Order = cast<OMPOrderClause>(Clause);
  4217. if (Order->getKind() != OMPC_ORDER_concurrent)
  4218. Order = nullptr;
  4219. }
  4220. if (Ordered && Order)
  4221. break;
  4222. }
  4223. if (Ordered && Order) {
  4224. S.Diag(Order->getKindKwLoc(),
  4225. diag::err_omp_simple_clause_incompatible_with_ordered)
  4226. << getOpenMPClauseName(OMPC_order)
  4227. << getOpenMPSimpleClauseTypeName(OMPC_order, OMPC_ORDER_concurrent)
  4228. << SourceRange(Order->getBeginLoc(), Order->getEndLoc());
  4229. S.Diag(Ordered->getBeginLoc(), diag::note_omp_ordered_param)
  4230. << 0 << SourceRange(Ordered->getBeginLoc(), Ordered->getEndLoc());
  4231. return true;
  4232. }
  4233. return false;
  4234. }
  4235. StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
  4236. ArrayRef<OMPClause *> Clauses) {
  4237. handleDeclareVariantConstructTrait(DSAStack, DSAStack->getCurrentDirective(),
  4238. /* ScopeEntry */ false);
  4239. if (DSAStack->getCurrentDirective() == OMPD_atomic ||
  4240. DSAStack->getCurrentDirective() == OMPD_critical ||
  4241. DSAStack->getCurrentDirective() == OMPD_section ||
  4242. DSAStack->getCurrentDirective() == OMPD_master ||
  4243. DSAStack->getCurrentDirective() == OMPD_masked)
  4244. return S;
  4245. bool ErrorFound = false;
  4246. CaptureRegionUnwinderRAII CaptureRegionUnwinder(
  4247. *this, ErrorFound, DSAStack->getCurrentDirective());
  4248. if (!S.isUsable()) {
  4249. ErrorFound = true;
  4250. return StmtError();
  4251. }
  4252. SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
  4253. getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective());
  4254. OMPOrderedClause *OC = nullptr;
  4255. OMPScheduleClause *SC = nullptr;
  4256. SmallVector<const OMPLinearClause *, 4> LCs;
  4257. SmallVector<const OMPClauseWithPreInit *, 4> PICs;
  4258. // This is required for proper codegen.
  4259. for (OMPClause *Clause : Clauses) {
  4260. if (!LangOpts.OpenMPSimd &&
  4261. isOpenMPTaskingDirective(DSAStack->getCurrentDirective()) &&
  4262. Clause->getClauseKind() == OMPC_in_reduction) {
  4263. // Capture taskgroup task_reduction descriptors inside the tasking regions
  4264. // with the corresponding in_reduction items.
  4265. auto *IRC = cast<OMPInReductionClause>(Clause);
  4266. for (Expr *E : IRC->taskgroup_descriptors())
  4267. if (E)
  4268. MarkDeclarationsReferencedInExpr(E);
  4269. }
  4270. if (isOpenMPPrivate(Clause->getClauseKind()) ||
  4271. Clause->getClauseKind() == OMPC_copyprivate ||
  4272. (getLangOpts().OpenMPUseTLS &&
  4273. getASTContext().getTargetInfo().isTLSSupported() &&
  4274. Clause->getClauseKind() == OMPC_copyin)) {
  4275. DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
  4276. // Mark all variables in private list clauses as used in inner region.
  4277. for (Stmt *VarRef : Clause->children()) {
  4278. if (auto *E = cast_or_null<Expr>(VarRef)) {
  4279. MarkDeclarationsReferencedInExpr(E);
  4280. }
  4281. }
  4282. DSAStack->setForceVarCapturing(/*V=*/false);
  4283. } else if (isOpenMPLoopTransformationDirective(
  4284. DSAStack->getCurrentDirective())) {
  4285. assert(CaptureRegions.empty() &&
  4286. "No captured regions in loop transformation directives.");
  4287. } else if (CaptureRegions.size() > 1 ||
  4288. CaptureRegions.back() != OMPD_unknown) {
  4289. if (auto *C = OMPClauseWithPreInit::get(Clause))
  4290. PICs.push_back(C);
  4291. if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
  4292. if (Expr *E = C->getPostUpdateExpr())
  4293. MarkDeclarationsReferencedInExpr(E);
  4294. }
  4295. }
  4296. if (Clause->getClauseKind() == OMPC_schedule)
  4297. SC = cast<OMPScheduleClause>(Clause);
  4298. else if (Clause->getClauseKind() == OMPC_ordered)
  4299. OC = cast<OMPOrderedClause>(Clause);
  4300. else if (Clause->getClauseKind() == OMPC_linear)
  4301. LCs.push_back(cast<OMPLinearClause>(Clause));
  4302. }
  4303. // Capture allocator expressions if used.
  4304. for (Expr *E : DSAStack->getInnerAllocators())
  4305. MarkDeclarationsReferencedInExpr(E);
  4306. // OpenMP, 2.7.1 Loop Construct, Restrictions
  4307. // The nonmonotonic modifier cannot be specified if an ordered clause is
  4308. // specified.
  4309. if (SC &&
  4310. (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
  4311. SC->getSecondScheduleModifier() ==
  4312. OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
  4313. OC) {
  4314. Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
  4315. ? SC->getFirstScheduleModifierLoc()
  4316. : SC->getSecondScheduleModifierLoc(),
  4317. diag::err_omp_simple_clause_incompatible_with_ordered)
  4318. << getOpenMPClauseName(OMPC_schedule)
  4319. << getOpenMPSimpleClauseTypeName(OMPC_schedule,
  4320. OMPC_SCHEDULE_MODIFIER_nonmonotonic)
  4321. << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
  4322. ErrorFound = true;
  4323. }
  4324. // OpenMP 5.0, 2.9.2 Worksharing-Loop Construct, Restrictions.
  4325. // If an order(concurrent) clause is present, an ordered clause may not appear
  4326. // on the same directive.
  4327. if (checkOrderedOrderSpecified(*this, Clauses))
  4328. ErrorFound = true;
  4329. if (!LCs.empty() && OC && OC->getNumForLoops()) {
  4330. for (const OMPLinearClause *C : LCs) {
  4331. Diag(C->getBeginLoc(), diag::err_omp_linear_ordered)
  4332. << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
  4333. }
  4334. ErrorFound = true;
  4335. }
  4336. if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
  4337. isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
  4338. OC->getNumForLoops()) {
  4339. Diag(OC->getBeginLoc(), diag::err_omp_ordered_simd)
  4340. << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
  4341. ErrorFound = true;
  4342. }
  4343. if (ErrorFound) {
  4344. return StmtError();
  4345. }
  4346. StmtResult SR = S;
  4347. unsigned CompletedRegions = 0;
  4348. for (OpenMPDirectiveKind ThisCaptureRegion : llvm::reverse(CaptureRegions)) {
  4349. // Mark all variables in private list clauses as used in inner region.
  4350. // Required for proper codegen of combined directives.
  4351. // TODO: add processing for other clauses.
  4352. if (ThisCaptureRegion != OMPD_unknown) {
  4353. for (const clang::OMPClauseWithPreInit *C : PICs) {
  4354. OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion();
  4355. // Find the particular capture region for the clause if the
  4356. // directive is a combined one with multiple capture regions.
  4357. // If the directive is not a combined one, the capture region
  4358. // associated with the clause is OMPD_unknown and is generated
  4359. // only once.
  4360. if (CaptureRegion == ThisCaptureRegion ||
  4361. CaptureRegion == OMPD_unknown) {
  4362. if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
  4363. for (Decl *D : DS->decls())
  4364. MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
  4365. }
  4366. }
  4367. }
  4368. }
  4369. if (ThisCaptureRegion == OMPD_target) {
  4370. // Capture allocator traits in the target region. They are used implicitly
  4371. // and, thus, are not captured by default.
  4372. for (OMPClause *C : Clauses) {
  4373. if (const auto *UAC = dyn_cast<OMPUsesAllocatorsClause>(C)) {
  4374. for (unsigned I = 0, End = UAC->getNumberOfAllocators(); I < End;
  4375. ++I) {
  4376. OMPUsesAllocatorsClause::Data D = UAC->getAllocatorData(I);
  4377. if (Expr *E = D.AllocatorTraits)
  4378. MarkDeclarationsReferencedInExpr(E);
  4379. }
  4380. continue;
  4381. }
  4382. }
  4383. }
  4384. if (ThisCaptureRegion == OMPD_parallel) {
  4385. // Capture temp arrays for inscan reductions and locals in aligned
  4386. // clauses.
  4387. for (OMPClause *C : Clauses) {
  4388. if (auto *RC = dyn_cast<OMPReductionClause>(C)) {
  4389. if (RC->getModifier() != OMPC_REDUCTION_inscan)
  4390. continue;
  4391. for (Expr *E : RC->copy_array_temps())
  4392. MarkDeclarationsReferencedInExpr(E);
  4393. }
  4394. if (auto *AC = dyn_cast<OMPAlignedClause>(C)) {
  4395. for (Expr *E : AC->varlists())
  4396. MarkDeclarationsReferencedInExpr(E);
  4397. }
  4398. }
  4399. }
  4400. if (++CompletedRegions == CaptureRegions.size())
  4401. DSAStack->setBodyComplete();
  4402. SR = ActOnCapturedRegionEnd(SR.get());
  4403. }
  4404. return SR;
  4405. }
  4406. static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion,
  4407. OpenMPDirectiveKind CancelRegion,
  4408. SourceLocation StartLoc) {
  4409. // CancelRegion is only needed for cancel and cancellation_point.
  4410. if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point)
  4411. return false;
  4412. if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for ||
  4413. CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup)
  4414. return false;
  4415. SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region)
  4416. << getOpenMPDirectiveName(CancelRegion);
  4417. return true;
  4418. }
  4419. static bool checkNestingOfRegions(Sema &SemaRef, const DSAStackTy *Stack,
  4420. OpenMPDirectiveKind CurrentRegion,
  4421. const DeclarationNameInfo &CurrentName,
  4422. OpenMPDirectiveKind CancelRegion,
  4423. OpenMPBindClauseKind BindKind,
  4424. SourceLocation StartLoc) {
  4425. if (Stack->getCurScope()) {
  4426. OpenMPDirectiveKind ParentRegion = Stack->getParentDirective();
  4427. OpenMPDirectiveKind OffendingRegion = ParentRegion;
  4428. bool NestingProhibited = false;
  4429. bool CloseNesting = true;
  4430. bool OrphanSeen = false;
  4431. enum {
  4432. NoRecommend,
  4433. ShouldBeInParallelRegion,
  4434. ShouldBeInOrderedRegion,
  4435. ShouldBeInTargetRegion,
  4436. ShouldBeInTeamsRegion,
  4437. ShouldBeInLoopSimdRegion,
  4438. } Recommend = NoRecommend;
  4439. if (isOpenMPSimdDirective(ParentRegion) &&
  4440. ((SemaRef.LangOpts.OpenMP <= 45 && CurrentRegion != OMPD_ordered) ||
  4441. (SemaRef.LangOpts.OpenMP >= 50 && CurrentRegion != OMPD_ordered &&
  4442. CurrentRegion != OMPD_simd && CurrentRegion != OMPD_atomic &&
  4443. CurrentRegion != OMPD_scan))) {
  4444. // OpenMP [2.16, Nesting of Regions]
  4445. // OpenMP constructs may not be nested inside a simd region.
  4446. // OpenMP [2.8.1,simd Construct, Restrictions]
  4447. // An ordered construct with the simd clause is the only OpenMP
  4448. // construct that can appear in the simd region.
  4449. // Allowing a SIMD construct nested in another SIMD construct is an
  4450. // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
  4451. // message.
  4452. // OpenMP 5.0 [2.9.3.1, simd Construct, Restrictions]
  4453. // The only OpenMP constructs that can be encountered during execution of
  4454. // a simd region are the atomic construct, the loop construct, the simd
  4455. // construct and the ordered construct with the simd clause.
  4456. SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
  4457. ? diag::err_omp_prohibited_region_simd
  4458. : diag::warn_omp_nesting_simd)
  4459. << (SemaRef.LangOpts.OpenMP >= 50 ? 1 : 0);
  4460. return CurrentRegion != OMPD_simd;
  4461. }
  4462. if (ParentRegion == OMPD_atomic) {
  4463. // OpenMP [2.16, Nesting of Regions]
  4464. // OpenMP constructs may not be nested inside an atomic region.
  4465. SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
  4466. return true;
  4467. }
  4468. if (CurrentRegion == OMPD_section) {
  4469. // OpenMP [2.7.2, sections Construct, Restrictions]
  4470. // Orphaned section directives are prohibited. That is, the section
  4471. // directives must appear within the sections construct and must not be
  4472. // encountered elsewhere in the sections region.
  4473. if (ParentRegion != OMPD_sections &&
  4474. ParentRegion != OMPD_parallel_sections) {
  4475. SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
  4476. << (ParentRegion != OMPD_unknown)
  4477. << getOpenMPDirectiveName(ParentRegion);
  4478. return true;
  4479. }
  4480. return false;
  4481. }
  4482. // Allow some constructs (except teams and cancellation constructs) to be
  4483. // orphaned (they could be used in functions, called from OpenMP regions
  4484. // with the required preconditions).
  4485. if (ParentRegion == OMPD_unknown &&
  4486. !isOpenMPNestingTeamsDirective(CurrentRegion) &&
  4487. CurrentRegion != OMPD_cancellation_point &&
  4488. CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_scan)
  4489. return false;
  4490. if (CurrentRegion == OMPD_cancellation_point ||
  4491. CurrentRegion == OMPD_cancel) {
  4492. // OpenMP [2.16, Nesting of Regions]
  4493. // A cancellation point construct for which construct-type-clause is
  4494. // taskgroup must be nested inside a task construct. A cancellation
  4495. // point construct for which construct-type-clause is not taskgroup must
  4496. // be closely nested inside an OpenMP construct that matches the type
  4497. // specified in construct-type-clause.
  4498. // A cancel construct for which construct-type-clause is taskgroup must be
  4499. // nested inside a task construct. A cancel construct for which
  4500. // construct-type-clause is not taskgroup must be closely nested inside an
  4501. // OpenMP construct that matches the type specified in
  4502. // construct-type-clause.
  4503. NestingProhibited =
  4504. !((CancelRegion == OMPD_parallel &&
  4505. (ParentRegion == OMPD_parallel ||
  4506. ParentRegion == OMPD_target_parallel)) ||
  4507. (CancelRegion == OMPD_for &&
  4508. (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
  4509. ParentRegion == OMPD_target_parallel_for ||
  4510. ParentRegion == OMPD_distribute_parallel_for ||
  4511. ParentRegion == OMPD_teams_distribute_parallel_for ||
  4512. ParentRegion == OMPD_target_teams_distribute_parallel_for)) ||
  4513. (CancelRegion == OMPD_taskgroup &&
  4514. (ParentRegion == OMPD_task ||
  4515. (SemaRef.getLangOpts().OpenMP >= 50 &&
  4516. (ParentRegion == OMPD_taskloop ||
  4517. ParentRegion == OMPD_master_taskloop ||
  4518. ParentRegion == OMPD_parallel_master_taskloop)))) ||
  4519. (CancelRegion == OMPD_sections &&
  4520. (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
  4521. ParentRegion == OMPD_parallel_sections)));
  4522. OrphanSeen = ParentRegion == OMPD_unknown;
  4523. } else if (CurrentRegion == OMPD_master || CurrentRegion == OMPD_masked) {
  4524. // OpenMP 5.1 [2.22, Nesting of Regions]
  4525. // A masked region may not be closely nested inside a worksharing, loop,
  4526. // atomic, task, or taskloop region.
  4527. NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
  4528. isOpenMPGenericLoopDirective(ParentRegion) ||
  4529. isOpenMPTaskingDirective(ParentRegion);
  4530. } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
  4531. // OpenMP [2.16, Nesting of Regions]
  4532. // A critical region may not be nested (closely or otherwise) inside a
  4533. // critical region with the same name. Note that this restriction is not
  4534. // sufficient to prevent deadlock.
  4535. SourceLocation PreviousCriticalLoc;
  4536. bool DeadLock = Stack->hasDirective(
  4537. [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
  4538. const DeclarationNameInfo &DNI,
  4539. SourceLocation Loc) {
  4540. if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
  4541. PreviousCriticalLoc = Loc;
  4542. return true;
  4543. }
  4544. return false;
  4545. },
  4546. false /* skip top directive */);
  4547. if (DeadLock) {
  4548. SemaRef.Diag(StartLoc,
  4549. diag::err_omp_prohibited_region_critical_same_name)
  4550. << CurrentName.getName();
  4551. if (PreviousCriticalLoc.isValid())
  4552. SemaRef.Diag(PreviousCriticalLoc,
  4553. diag::note_omp_previous_critical_region);
  4554. return true;
  4555. }
  4556. } else if (CurrentRegion == OMPD_barrier) {
  4557. // OpenMP 5.1 [2.22, Nesting of Regions]
  4558. // A barrier region may not be closely nested inside a worksharing, loop,
  4559. // task, taskloop, critical, ordered, atomic, or masked region.
  4560. NestingProhibited =
  4561. isOpenMPWorksharingDirective(ParentRegion) ||
  4562. isOpenMPGenericLoopDirective(ParentRegion) ||
  4563. isOpenMPTaskingDirective(ParentRegion) ||
  4564. ParentRegion == OMPD_master || ParentRegion == OMPD_masked ||
  4565. ParentRegion == OMPD_parallel_master ||
  4566. ParentRegion == OMPD_critical || ParentRegion == OMPD_ordered;
  4567. } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
  4568. !isOpenMPParallelDirective(CurrentRegion) &&
  4569. !isOpenMPTeamsDirective(CurrentRegion)) {
  4570. // OpenMP 5.1 [2.22, Nesting of Regions]
  4571. // A loop region that binds to a parallel region or a worksharing region
  4572. // may not be closely nested inside a worksharing, loop, task, taskloop,
  4573. // critical, ordered, atomic, or masked region.
  4574. NestingProhibited =
  4575. isOpenMPWorksharingDirective(ParentRegion) ||
  4576. isOpenMPGenericLoopDirective(ParentRegion) ||
  4577. isOpenMPTaskingDirective(ParentRegion) ||
  4578. ParentRegion == OMPD_master || ParentRegion == OMPD_masked ||
  4579. ParentRegion == OMPD_parallel_master ||
  4580. ParentRegion == OMPD_critical || ParentRegion == OMPD_ordered;
  4581. Recommend = ShouldBeInParallelRegion;
  4582. } else if (CurrentRegion == OMPD_ordered) {
  4583. // OpenMP [2.16, Nesting of Regions]
  4584. // An ordered region may not be closely nested inside a critical,
  4585. // atomic, or explicit task region.
  4586. // An ordered region must be closely nested inside a loop region (or
  4587. // parallel loop region) with an ordered clause.
  4588. // OpenMP [2.8.1,simd Construct, Restrictions]
  4589. // An ordered construct with the simd clause is the only OpenMP construct
  4590. // that can appear in the simd region.
  4591. NestingProhibited = ParentRegion == OMPD_critical ||
  4592. isOpenMPTaskingDirective(ParentRegion) ||
  4593. !(isOpenMPSimdDirective(ParentRegion) ||
  4594. Stack->isParentOrderedRegion());
  4595. Recommend = ShouldBeInOrderedRegion;
  4596. } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
  4597. // OpenMP [2.16, Nesting of Regions]
  4598. // If specified, a teams construct must be contained within a target
  4599. // construct.
  4600. NestingProhibited =
  4601. (SemaRef.LangOpts.OpenMP <= 45 && ParentRegion != OMPD_target) ||
  4602. (SemaRef.LangOpts.OpenMP >= 50 && ParentRegion != OMPD_unknown &&
  4603. ParentRegion != OMPD_target);
  4604. OrphanSeen = ParentRegion == OMPD_unknown;
  4605. Recommend = ShouldBeInTargetRegion;
  4606. } else if (CurrentRegion == OMPD_scan) {
  4607. // OpenMP [2.16, Nesting of Regions]
  4608. // If specified, a teams construct must be contained within a target
  4609. // construct.
  4610. NestingProhibited =
  4611. SemaRef.LangOpts.OpenMP < 50 ||
  4612. (ParentRegion != OMPD_simd && ParentRegion != OMPD_for &&
  4613. ParentRegion != OMPD_for_simd && ParentRegion != OMPD_parallel_for &&
  4614. ParentRegion != OMPD_parallel_for_simd);
  4615. OrphanSeen = ParentRegion == OMPD_unknown;
  4616. Recommend = ShouldBeInLoopSimdRegion;
  4617. }
  4618. if (!NestingProhibited &&
  4619. !isOpenMPTargetExecutionDirective(CurrentRegion) &&
  4620. !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
  4621. (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
  4622. // OpenMP [5.1, 2.22, Nesting of Regions]
  4623. // distribute, distribute simd, distribute parallel worksharing-loop,
  4624. // distribute parallel worksharing-loop SIMD, loop, parallel regions,
  4625. // including any parallel regions arising from combined constructs,
  4626. // omp_get_num_teams() regions, and omp_get_team_num() regions are the
  4627. // only OpenMP regions that may be strictly nested inside the teams
  4628. // region.
  4629. NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
  4630. !isOpenMPDistributeDirective(CurrentRegion) &&
  4631. CurrentRegion != OMPD_loop;
  4632. Recommend = ShouldBeInParallelRegion;
  4633. }
  4634. if (!NestingProhibited && CurrentRegion == OMPD_loop) {
  4635. // OpenMP [5.1, 2.11.7, loop Construct, Restrictions]
  4636. // If the bind clause is present on the loop construct and binding is
  4637. // teams then the corresponding loop region must be strictly nested inside
  4638. // a teams region.
  4639. NestingProhibited = BindKind == OMPC_BIND_teams &&
  4640. ParentRegion != OMPD_teams &&
  4641. ParentRegion != OMPD_target_teams;
  4642. Recommend = ShouldBeInTeamsRegion;
  4643. }
  4644. if (!NestingProhibited &&
  4645. isOpenMPNestingDistributeDirective(CurrentRegion)) {
  4646. // OpenMP 4.5 [2.17 Nesting of Regions]
  4647. // The region associated with the distribute construct must be strictly
  4648. // nested inside a teams region
  4649. NestingProhibited =
  4650. (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
  4651. Recommend = ShouldBeInTeamsRegion;
  4652. }
  4653. if (!NestingProhibited &&
  4654. (isOpenMPTargetExecutionDirective(CurrentRegion) ||
  4655. isOpenMPTargetDataManagementDirective(CurrentRegion))) {
  4656. // OpenMP 4.5 [2.17 Nesting of Regions]
  4657. // If a target, target update, target data, target enter data, or
  4658. // target exit data construct is encountered during execution of a
  4659. // target region, the behavior is unspecified.
  4660. NestingProhibited = Stack->hasDirective(
  4661. [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
  4662. SourceLocation) {
  4663. if (isOpenMPTargetExecutionDirective(K)) {
  4664. OffendingRegion = K;
  4665. return true;
  4666. }
  4667. return false;
  4668. },
  4669. false /* don't skip top directive */);
  4670. CloseNesting = false;
  4671. }
  4672. if (NestingProhibited) {
  4673. if (OrphanSeen) {
  4674. SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
  4675. << getOpenMPDirectiveName(CurrentRegion) << Recommend;
  4676. } else {
  4677. SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
  4678. << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
  4679. << Recommend << getOpenMPDirectiveName(CurrentRegion);
  4680. }
  4681. return true;
  4682. }
  4683. }
  4684. return false;
  4685. }
  4686. struct Kind2Unsigned {
  4687. using argument_type = OpenMPDirectiveKind;
  4688. unsigned operator()(argument_type DK) { return unsigned(DK); }
  4689. };
  4690. static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
  4691. ArrayRef<OMPClause *> Clauses,
  4692. ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
  4693. bool ErrorFound = false;
  4694. unsigned NamedModifiersNumber = 0;
  4695. llvm::IndexedMap<const OMPIfClause *, Kind2Unsigned> FoundNameModifiers;
  4696. FoundNameModifiers.resize(llvm::omp::Directive_enumSize + 1);
  4697. SmallVector<SourceLocation, 4> NameModifierLoc;
  4698. for (const OMPClause *C : Clauses) {
  4699. if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
  4700. // At most one if clause without a directive-name-modifier can appear on
  4701. // the directive.
  4702. OpenMPDirectiveKind CurNM = IC->getNameModifier();
  4703. if (FoundNameModifiers[CurNM]) {
  4704. S.Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
  4705. << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
  4706. << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
  4707. ErrorFound = true;
  4708. } else if (CurNM != OMPD_unknown) {
  4709. NameModifierLoc.push_back(IC->getNameModifierLoc());
  4710. ++NamedModifiersNumber;
  4711. }
  4712. FoundNameModifiers[CurNM] = IC;
  4713. if (CurNM == OMPD_unknown)
  4714. continue;
  4715. // Check if the specified name modifier is allowed for the current
  4716. // directive.
  4717. // At most one if clause with the particular directive-name-modifier can
  4718. // appear on the directive.
  4719. if (!llvm::is_contained(AllowedNameModifiers, CurNM)) {
  4720. S.Diag(IC->getNameModifierLoc(),
  4721. diag::err_omp_wrong_if_directive_name_modifier)
  4722. << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
  4723. ErrorFound = true;
  4724. }
  4725. }
  4726. }
  4727. // If any if clause on the directive includes a directive-name-modifier then
  4728. // all if clauses on the directive must include a directive-name-modifier.
  4729. if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
  4730. if (NamedModifiersNumber == AllowedNameModifiers.size()) {
  4731. S.Diag(FoundNameModifiers[OMPD_unknown]->getBeginLoc(),
  4732. diag::err_omp_no_more_if_clause);
  4733. } else {
  4734. std::string Values;
  4735. std::string Sep(", ");
  4736. unsigned AllowedCnt = 0;
  4737. unsigned TotalAllowedNum =
  4738. AllowedNameModifiers.size() - NamedModifiersNumber;
  4739. for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
  4740. ++Cnt) {
  4741. OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
  4742. if (!FoundNameModifiers[NM]) {
  4743. Values += "'";
  4744. Values += getOpenMPDirectiveName(NM);
  4745. Values += "'";
  4746. if (AllowedCnt + 2 == TotalAllowedNum)
  4747. Values += " or ";
  4748. else if (AllowedCnt + 1 != TotalAllowedNum)
  4749. Values += Sep;
  4750. ++AllowedCnt;
  4751. }
  4752. }
  4753. S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getBeginLoc(),
  4754. diag::err_omp_unnamed_if_clause)
  4755. << (TotalAllowedNum > 1) << Values;
  4756. }
  4757. for (SourceLocation Loc : NameModifierLoc) {
  4758. S.Diag(Loc, diag::note_omp_previous_named_if_clause);
  4759. }
  4760. ErrorFound = true;
  4761. }
  4762. return ErrorFound;
  4763. }
  4764. static std::pair<ValueDecl *, bool> getPrivateItem(Sema &S, Expr *&RefExpr,
  4765. SourceLocation &ELoc,
  4766. SourceRange &ERange,
  4767. bool AllowArraySection) {
  4768. if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
  4769. RefExpr->containsUnexpandedParameterPack())
  4770. return std::make_pair(nullptr, true);
  4771. // OpenMP [3.1, C/C++]
  4772. // A list item is a variable name.
  4773. // OpenMP [2.9.3.3, Restrictions, p.1]
  4774. // A variable that is part of another variable (as an array or
  4775. // structure element) cannot appear in a private clause.
  4776. RefExpr = RefExpr->IgnoreParens();
  4777. enum {
  4778. NoArrayExpr = -1,
  4779. ArraySubscript = 0,
  4780. OMPArraySection = 1
  4781. } IsArrayExpr = NoArrayExpr;
  4782. if (AllowArraySection) {
  4783. if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
  4784. Expr *Base = ASE->getBase()->IgnoreParenImpCasts();
  4785. while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
  4786. Base = TempASE->getBase()->IgnoreParenImpCasts();
  4787. RefExpr = Base;
  4788. IsArrayExpr = ArraySubscript;
  4789. } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
  4790. Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
  4791. while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
  4792. Base = TempOASE->getBase()->IgnoreParenImpCasts();
  4793. while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
  4794. Base = TempASE->getBase()->IgnoreParenImpCasts();
  4795. RefExpr = Base;
  4796. IsArrayExpr = OMPArraySection;
  4797. }
  4798. }
  4799. ELoc = RefExpr->getExprLoc();
  4800. ERange = RefExpr->getSourceRange();
  4801. RefExpr = RefExpr->IgnoreParenImpCasts();
  4802. auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
  4803. auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
  4804. if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
  4805. (S.getCurrentThisType().isNull() || !ME ||
  4806. !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
  4807. !isa<FieldDecl>(ME->getMemberDecl()))) {
  4808. if (IsArrayExpr != NoArrayExpr) {
  4809. S.Diag(ELoc, diag::err_omp_expected_base_var_name)
  4810. << IsArrayExpr << ERange;
  4811. } else {
  4812. S.Diag(ELoc,
  4813. AllowArraySection
  4814. ? diag::err_omp_expected_var_name_member_expr_or_array_item
  4815. : diag::err_omp_expected_var_name_member_expr)
  4816. << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
  4817. }
  4818. return std::make_pair(nullptr, false);
  4819. }
  4820. return std::make_pair(
  4821. getCanonicalDecl(DE ? DE->getDecl() : ME->getMemberDecl()), false);
  4822. }
  4823. namespace {
  4824. /// Checks if the allocator is used in uses_allocators clause to be allowed in
  4825. /// target regions.
  4826. class AllocatorChecker final : public ConstStmtVisitor<AllocatorChecker, bool> {
  4827. DSAStackTy *S = nullptr;
  4828. public:
  4829. bool VisitDeclRefExpr(const DeclRefExpr *E) {
  4830. return S->isUsesAllocatorsDecl(E->getDecl())
  4831. .getValueOr(
  4832. DSAStackTy::UsesAllocatorsDeclKind::AllocatorTrait) ==
  4833. DSAStackTy::UsesAllocatorsDeclKind::AllocatorTrait;
  4834. }
  4835. bool VisitStmt(const Stmt *S) {
  4836. for (const Stmt *Child : S->children()) {
  4837. if (Child && Visit(Child))
  4838. return true;
  4839. }
  4840. return false;
  4841. }
  4842. explicit AllocatorChecker(DSAStackTy *S) : S(S) {}
  4843. };
  4844. } // namespace
  4845. static void checkAllocateClauses(Sema &S, DSAStackTy *Stack,
  4846. ArrayRef<OMPClause *> Clauses) {
  4847. assert(!S.CurContext->isDependentContext() &&
  4848. "Expected non-dependent context.");
  4849. auto AllocateRange =
  4850. llvm::make_filter_range(Clauses, OMPAllocateClause::classof);
  4851. llvm::DenseMap<CanonicalDeclPtr<Decl>, CanonicalDeclPtr<VarDecl>> DeclToCopy;
  4852. auto PrivateRange = llvm::make_filter_range(Clauses, [](const OMPClause *C) {
  4853. return isOpenMPPrivate(C->getClauseKind());
  4854. });
  4855. for (OMPClause *Cl : PrivateRange) {
  4856. MutableArrayRef<Expr *>::iterator I, It, Et;
  4857. if (Cl->getClauseKind() == OMPC_private) {
  4858. auto *PC = cast<OMPPrivateClause>(Cl);
  4859. I = PC->private_copies().begin();
  4860. It = PC->varlist_begin();
  4861. Et = PC->varlist_end();
  4862. } else if (Cl->getClauseKind() == OMPC_firstprivate) {
  4863. auto *PC = cast<OMPFirstprivateClause>(Cl);
  4864. I = PC->private_copies().begin();
  4865. It = PC->varlist_begin();
  4866. Et = PC->varlist_end();
  4867. } else if (Cl->getClauseKind() == OMPC_lastprivate) {
  4868. auto *PC = cast<OMPLastprivateClause>(Cl);
  4869. I = PC->private_copies().begin();
  4870. It = PC->varlist_begin();
  4871. Et = PC->varlist_end();
  4872. } else if (Cl->getClauseKind() == OMPC_linear) {
  4873. auto *PC = cast<OMPLinearClause>(Cl);
  4874. I = PC->privates().begin();
  4875. It = PC->varlist_begin();
  4876. Et = PC->varlist_end();
  4877. } else if (Cl->getClauseKind() == OMPC_reduction) {
  4878. auto *PC = cast<OMPReductionClause>(Cl);
  4879. I = PC->privates().begin();
  4880. It = PC->varlist_begin();
  4881. Et = PC->varlist_end();
  4882. } else if (Cl->getClauseKind() == OMPC_task_reduction) {
  4883. auto *PC = cast<OMPTaskReductionClause>(Cl);
  4884. I = PC->privates().begin();
  4885. It = PC->varlist_begin();
  4886. Et = PC->varlist_end();
  4887. } else if (Cl->getClauseKind() == OMPC_in_reduction) {
  4888. auto *PC = cast<OMPInReductionClause>(Cl);
  4889. I = PC->privates().begin();
  4890. It = PC->varlist_begin();
  4891. Et = PC->varlist_end();
  4892. } else {
  4893. llvm_unreachable("Expected private clause.");
  4894. }
  4895. for (Expr *E : llvm::make_range(It, Et)) {
  4896. if (!*I) {
  4897. ++I;
  4898. continue;
  4899. }
  4900. SourceLocation ELoc;
  4901. SourceRange ERange;
  4902. Expr *SimpleRefExpr = E;
  4903. auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
  4904. /*AllowArraySection=*/true);
  4905. DeclToCopy.try_emplace(Res.first,
  4906. cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()));
  4907. ++I;
  4908. }
  4909. }
  4910. for (OMPClause *C : AllocateRange) {
  4911. auto *AC = cast<OMPAllocateClause>(C);
  4912. if (S.getLangOpts().OpenMP >= 50 &&
  4913. !Stack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>() &&
  4914. isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) &&
  4915. AC->getAllocator()) {
  4916. Expr *Allocator = AC->getAllocator();
  4917. // OpenMP, 2.12.5 target Construct
  4918. // Memory allocators that do not appear in a uses_allocators clause cannot
  4919. // appear as an allocator in an allocate clause or be used in the target
  4920. // region unless a requires directive with the dynamic_allocators clause
  4921. // is present in the same compilation unit.
  4922. AllocatorChecker Checker(Stack);
  4923. if (Checker.Visit(Allocator))
  4924. S.Diag(Allocator->getExprLoc(),
  4925. diag::err_omp_allocator_not_in_uses_allocators)
  4926. << Allocator->getSourceRange();
  4927. }
  4928. OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind =
  4929. getAllocatorKind(S, Stack, AC->getAllocator());
  4930. // OpenMP, 2.11.4 allocate Clause, Restrictions.
  4931. // For task, taskloop or target directives, allocation requests to memory
  4932. // allocators with the trait access set to thread result in unspecified
  4933. // behavior.
  4934. if (AllocatorKind == OMPAllocateDeclAttr::OMPThreadMemAlloc &&
  4935. (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
  4936. isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()))) {
  4937. S.Diag(AC->getAllocator()->getExprLoc(),
  4938. diag::warn_omp_allocate_thread_on_task_target_directive)
  4939. << getOpenMPDirectiveName(Stack->getCurrentDirective());
  4940. }
  4941. for (Expr *E : AC->varlists()) {
  4942. SourceLocation ELoc;
  4943. SourceRange ERange;
  4944. Expr *SimpleRefExpr = E;
  4945. auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange);
  4946. ValueDecl *VD = Res.first;
  4947. DSAStackTy::DSAVarData Data = Stack->getTopDSA(VD, /*FromParent=*/false);
  4948. if (!isOpenMPPrivate(Data.CKind)) {
  4949. S.Diag(E->getExprLoc(),
  4950. diag::err_omp_expected_private_copy_for_allocate);
  4951. continue;
  4952. }
  4953. VarDecl *PrivateVD = DeclToCopy[VD];
  4954. if (checkPreviousOMPAllocateAttribute(S, Stack, E, PrivateVD,
  4955. AllocatorKind, AC->getAllocator()))
  4956. continue;
  4957. // Placeholder until allocate clause supports align modifier.
  4958. Expr *Alignment = nullptr;
  4959. applyOMPAllocateAttribute(S, PrivateVD, AllocatorKind, AC->getAllocator(),
  4960. Alignment, E->getSourceRange());
  4961. }
  4962. }
  4963. }
  4964. namespace {
  4965. /// Rewrite statements and expressions for Sema \p Actions CurContext.
  4966. ///
  4967. /// Used to wrap already parsed statements/expressions into a new CapturedStmt
  4968. /// context. DeclRefExpr used inside the new context are changed to refer to the
  4969. /// captured variable instead.
  4970. class CaptureVars : public TreeTransform<CaptureVars> {
  4971. using BaseTransform = TreeTransform<CaptureVars>;
  4972. public:
  4973. CaptureVars(Sema &Actions) : BaseTransform(Actions) {}
  4974. bool AlwaysRebuild() { return true; }
  4975. };
  4976. } // namespace
  4977. static VarDecl *precomputeExpr(Sema &Actions,
  4978. SmallVectorImpl<Stmt *> &BodyStmts, Expr *E,
  4979. StringRef Name) {
  4980. Expr *NewE = AssertSuccess(CaptureVars(Actions).TransformExpr(E));
  4981. VarDecl *NewVar = buildVarDecl(Actions, {}, NewE->getType(), Name, nullptr,
  4982. dyn_cast<DeclRefExpr>(E->IgnoreImplicit()));
  4983. auto *NewDeclStmt = cast<DeclStmt>(AssertSuccess(
  4984. Actions.ActOnDeclStmt(Actions.ConvertDeclToDeclGroup(NewVar), {}, {})));
  4985. Actions.AddInitializerToDecl(NewDeclStmt->getSingleDecl(), NewE, false);
  4986. BodyStmts.push_back(NewDeclStmt);
  4987. return NewVar;
  4988. }
  4989. /// Create a closure that computes the number of iterations of a loop.
  4990. ///
  4991. /// \param Actions The Sema object.
  4992. /// \param LogicalTy Type for the logical iteration number.
  4993. /// \param Rel Comparison operator of the loop condition.
  4994. /// \param StartExpr Value of the loop counter at the first iteration.
  4995. /// \param StopExpr Expression the loop counter is compared against in the loop
  4996. /// condition. \param StepExpr Amount of increment after each iteration.
  4997. ///
  4998. /// \return Closure (CapturedStmt) of the distance calculation.
  4999. static CapturedStmt *buildDistanceFunc(Sema &Actions, QualType LogicalTy,
  5000. BinaryOperator::Opcode Rel,
  5001. Expr *StartExpr, Expr *StopExpr,
  5002. Expr *StepExpr) {
  5003. ASTContext &Ctx = Actions.getASTContext();
  5004. TypeSourceInfo *LogicalTSI = Ctx.getTrivialTypeSourceInfo(LogicalTy);
  5005. // Captured regions currently don't support return values, we use an
  5006. // out-parameter instead. All inputs are implicit captures.
  5007. // TODO: Instead of capturing each DeclRefExpr occurring in
  5008. // StartExpr/StopExpr/Step, these could also be passed as a value capture.
  5009. QualType ResultTy = Ctx.getLValueReferenceType(LogicalTy);
  5010. Sema::CapturedParamNameType Params[] = {{"Distance", ResultTy},
  5011. {StringRef(), QualType()}};
  5012. Actions.ActOnCapturedRegionStart({}, nullptr, CR_Default, Params);
  5013. Stmt *Body;
  5014. {
  5015. Sema::CompoundScopeRAII CompoundScope(Actions);
  5016. CapturedDecl *CS = cast<CapturedDecl>(Actions.CurContext);
  5017. // Get the LValue expression for the result.
  5018. ImplicitParamDecl *DistParam = CS->getParam(0);
  5019. DeclRefExpr *DistRef = Actions.BuildDeclRefExpr(
  5020. DistParam, LogicalTy, VK_LValue, {}, nullptr, nullptr, {}, nullptr);
  5021. SmallVector<Stmt *, 4> BodyStmts;
  5022. // Capture all referenced variable references.
  5023. // TODO: Instead of computing NewStart/NewStop/NewStep inside the
  5024. // CapturedStmt, we could compute them before and capture the result, to be
  5025. // used jointly with the LoopVar function.
  5026. VarDecl *NewStart = precomputeExpr(Actions, BodyStmts, StartExpr, ".start");
  5027. VarDecl *NewStop = precomputeExpr(Actions, BodyStmts, StopExpr, ".stop");
  5028. VarDecl *NewStep = precomputeExpr(Actions, BodyStmts, StepExpr, ".step");
  5029. auto BuildVarRef = [&](VarDecl *VD) {
  5030. return buildDeclRefExpr(Actions, VD, VD->getType(), {});
  5031. };
  5032. IntegerLiteral *Zero = IntegerLiteral::Create(
  5033. Ctx, llvm::APInt(Ctx.getIntWidth(LogicalTy), 0), LogicalTy, {});
  5034. IntegerLiteral *One = IntegerLiteral::Create(
  5035. Ctx, llvm::APInt(Ctx.getIntWidth(LogicalTy), 1), LogicalTy, {});
  5036. Expr *Dist;
  5037. if (Rel == BO_NE) {
  5038. // When using a != comparison, the increment can be +1 or -1. This can be
  5039. // dynamic at runtime, so we need to check for the direction.
  5040. Expr *IsNegStep = AssertSuccess(
  5041. Actions.BuildBinOp(nullptr, {}, BO_LT, BuildVarRef(NewStep), Zero));
  5042. // Positive increment.
  5043. Expr *ForwardRange = AssertSuccess(Actions.BuildBinOp(
  5044. nullptr, {}, BO_Sub, BuildVarRef(NewStop), BuildVarRef(NewStart)));
  5045. ForwardRange = AssertSuccess(
  5046. Actions.BuildCStyleCastExpr({}, LogicalTSI, {}, ForwardRange));
  5047. Expr *ForwardDist = AssertSuccess(Actions.BuildBinOp(
  5048. nullptr, {}, BO_Div, ForwardRange, BuildVarRef(NewStep)));
  5049. // Negative increment.
  5050. Expr *BackwardRange = AssertSuccess(Actions.BuildBinOp(
  5051. nullptr, {}, BO_Sub, BuildVarRef(NewStart), BuildVarRef(NewStop)));
  5052. BackwardRange = AssertSuccess(
  5053. Actions.BuildCStyleCastExpr({}, LogicalTSI, {}, BackwardRange));
  5054. Expr *NegIncAmount = AssertSuccess(
  5055. Actions.BuildUnaryOp(nullptr, {}, UO_Minus, BuildVarRef(NewStep)));
  5056. Expr *BackwardDist = AssertSuccess(
  5057. Actions.BuildBinOp(nullptr, {}, BO_Div, BackwardRange, NegIncAmount));
  5058. // Use the appropriate case.
  5059. Dist = AssertSuccess(Actions.ActOnConditionalOp(
  5060. {}, {}, IsNegStep, BackwardDist, ForwardDist));
  5061. } else {
  5062. assert((Rel == BO_LT || Rel == BO_LE || Rel == BO_GE || Rel == BO_GT) &&
  5063. "Expected one of these relational operators");
  5064. // We can derive the direction from any other comparison operator. It is
  5065. // non well-formed OpenMP if Step increments/decrements in the other
  5066. // directions. Whether at least the first iteration passes the loop
  5067. // condition.
  5068. Expr *HasAnyIteration = AssertSuccess(Actions.BuildBinOp(
  5069. nullptr, {}, Rel, BuildVarRef(NewStart), BuildVarRef(NewStop)));
  5070. // Compute the range between first and last counter value.
  5071. Expr *Range;
  5072. if (Rel == BO_GE || Rel == BO_GT)
  5073. Range = AssertSuccess(Actions.BuildBinOp(
  5074. nullptr, {}, BO_Sub, BuildVarRef(NewStart), BuildVarRef(NewStop)));
  5075. else
  5076. Range = AssertSuccess(Actions.BuildBinOp(
  5077. nullptr, {}, BO_Sub, BuildVarRef(NewStop), BuildVarRef(NewStart)));
  5078. // Ensure unsigned range space.
  5079. Range =
  5080. AssertSuccess(Actions.BuildCStyleCastExpr({}, LogicalTSI, {}, Range));
  5081. if (Rel == BO_LE || Rel == BO_GE) {
  5082. // Add one to the range if the relational operator is inclusive.
  5083. Range =
  5084. AssertSuccess(Actions.BuildBinOp(nullptr, {}, BO_Add, Range, One));
  5085. }
  5086. // Divide by the absolute step amount. If the range is not a multiple of
  5087. // the step size, rounding-up the effective upper bound ensures that the
  5088. // last iteration is included.
  5089. // Note that the rounding-up may cause an overflow in a temporry that
  5090. // could be avoided, but would have occured in a C-style for-loop as well.
  5091. Expr *Divisor = BuildVarRef(NewStep);
  5092. if (Rel == BO_GE || Rel == BO_GT)
  5093. Divisor =
  5094. AssertSuccess(Actions.BuildUnaryOp(nullptr, {}, UO_Minus, Divisor));
  5095. Expr *DivisorMinusOne =
  5096. AssertSuccess(Actions.BuildBinOp(nullptr, {}, BO_Sub, Divisor, One));
  5097. Expr *RangeRoundUp = AssertSuccess(
  5098. Actions.BuildBinOp(nullptr, {}, BO_Add, Range, DivisorMinusOne));
  5099. Dist = AssertSuccess(
  5100. Actions.BuildBinOp(nullptr, {}, BO_Div, RangeRoundUp, Divisor));
  5101. // If there is not at least one iteration, the range contains garbage. Fix
  5102. // to zero in this case.
  5103. Dist = AssertSuccess(
  5104. Actions.ActOnConditionalOp({}, {}, HasAnyIteration, Dist, Zero));
  5105. }
  5106. // Assign the result to the out-parameter.
  5107. Stmt *ResultAssign = AssertSuccess(Actions.BuildBinOp(
  5108. Actions.getCurScope(), {}, BO_Assign, DistRef, Dist));
  5109. BodyStmts.push_back(ResultAssign);
  5110. Body = AssertSuccess(Actions.ActOnCompoundStmt({}, {}, BodyStmts, false));
  5111. }
  5112. return cast<CapturedStmt>(
  5113. AssertSuccess(Actions.ActOnCapturedRegionEnd(Body)));
  5114. }
  5115. /// Create a closure that computes the loop variable from the logical iteration
  5116. /// number.
  5117. ///
  5118. /// \param Actions The Sema object.
  5119. /// \param LoopVarTy Type for the loop variable used for result value.
  5120. /// \param LogicalTy Type for the logical iteration number.
  5121. /// \param StartExpr Value of the loop counter at the first iteration.
  5122. /// \param Step Amount of increment after each iteration.
  5123. /// \param Deref Whether the loop variable is a dereference of the loop
  5124. /// counter variable.
  5125. ///
  5126. /// \return Closure (CapturedStmt) of the loop value calculation.
  5127. static CapturedStmt *buildLoopVarFunc(Sema &Actions, QualType LoopVarTy,
  5128. QualType LogicalTy,
  5129. DeclRefExpr *StartExpr, Expr *Step,
  5130. bool Deref) {
  5131. ASTContext &Ctx = Actions.getASTContext();
  5132. // Pass the result as an out-parameter. Passing as return value would require
  5133. // the OpenMPIRBuilder to know additional C/C++ semantics, such as how to
  5134. // invoke a copy constructor.
  5135. QualType TargetParamTy = Ctx.getLValueReferenceType(LoopVarTy);
  5136. Sema::CapturedParamNameType Params[] = {{"LoopVar", TargetParamTy},
  5137. {"Logical", LogicalTy},
  5138. {StringRef(), QualType()}};
  5139. Actions.ActOnCapturedRegionStart({}, nullptr, CR_Default, Params);
  5140. // Capture the initial iterator which represents the LoopVar value at the
  5141. // zero's logical iteration. Since the original ForStmt/CXXForRangeStmt update
  5142. // it in every iteration, capture it by value before it is modified.
  5143. VarDecl *StartVar = cast<VarDecl>(StartExpr->getDecl());
  5144. bool Invalid = Actions.tryCaptureVariable(StartVar, {},
  5145. Sema::TryCapture_ExplicitByVal, {});
  5146. (void)Invalid;
  5147. assert(!Invalid && "Expecting capture-by-value to work.");
  5148. Expr *Body;
  5149. {
  5150. Sema::CompoundScopeRAII CompoundScope(Actions);
  5151. auto *CS = cast<CapturedDecl>(Actions.CurContext);
  5152. ImplicitParamDecl *TargetParam = CS->getParam(0);
  5153. DeclRefExpr *TargetRef = Actions.BuildDeclRefExpr(
  5154. TargetParam, LoopVarTy, VK_LValue, {}, nullptr, nullptr, {}, nullptr);
  5155. ImplicitParamDecl *IndvarParam = CS->getParam(1);
  5156. DeclRefExpr *LogicalRef = Actions.BuildDeclRefExpr(
  5157. IndvarParam, LogicalTy, VK_LValue, {}, nullptr, nullptr, {}, nullptr);
  5158. // Capture the Start expression.
  5159. CaptureVars Recap(Actions);
  5160. Expr *NewStart = AssertSuccess(Recap.TransformExpr(StartExpr));
  5161. Expr *NewStep = AssertSuccess(Recap.TransformExpr(Step));
  5162. Expr *Skip = AssertSuccess(
  5163. Actions.BuildBinOp(nullptr, {}, BO_Mul, NewStep, LogicalRef));
  5164. // TODO: Explicitly cast to the iterator's difference_type instead of
  5165. // relying on implicit conversion.
  5166. Expr *Advanced =
  5167. AssertSuccess(Actions.BuildBinOp(nullptr, {}, BO_Add, NewStart, Skip));
  5168. if (Deref) {
  5169. // For range-based for-loops convert the loop counter value to a concrete
  5170. // loop variable value by dereferencing the iterator.
  5171. Advanced =
  5172. AssertSuccess(Actions.BuildUnaryOp(nullptr, {}, UO_Deref, Advanced));
  5173. }
  5174. // Assign the result to the output parameter.
  5175. Body = AssertSuccess(Actions.BuildBinOp(Actions.getCurScope(), {},
  5176. BO_Assign, TargetRef, Advanced));
  5177. }
  5178. return cast<CapturedStmt>(
  5179. AssertSuccess(Actions.ActOnCapturedRegionEnd(Body)));
  5180. }
  5181. StmtResult Sema::ActOnOpenMPCanonicalLoop(Stmt *AStmt) {
  5182. ASTContext &Ctx = getASTContext();
  5183. // Extract the common elements of ForStmt and CXXForRangeStmt:
  5184. // Loop variable, repeat condition, increment
  5185. Expr *Cond, *Inc;
  5186. VarDecl *LIVDecl, *LUVDecl;
  5187. if (auto *For = dyn_cast<ForStmt>(AStmt)) {
  5188. Stmt *Init = For->getInit();
  5189. if (auto *LCVarDeclStmt = dyn_cast<DeclStmt>(Init)) {
  5190. // For statement declares loop variable.
  5191. LIVDecl = cast<VarDecl>(LCVarDeclStmt->getSingleDecl());
  5192. } else if (auto *LCAssign = dyn_cast<BinaryOperator>(Init)) {
  5193. // For statement reuses variable.
  5194. assert(LCAssign->getOpcode() == BO_Assign &&
  5195. "init part must be a loop variable assignment");
  5196. auto *CounterRef = cast<DeclRefExpr>(LCAssign->getLHS());
  5197. LIVDecl = cast<VarDecl>(CounterRef->getDecl());
  5198. } else
  5199. llvm_unreachable("Cannot determine loop variable");
  5200. LUVDecl = LIVDecl;
  5201. Cond = For->getCond();
  5202. Inc = For->getInc();
  5203. } else if (auto *RangeFor = dyn_cast<CXXForRangeStmt>(AStmt)) {
  5204. DeclStmt *BeginStmt = RangeFor->getBeginStmt();
  5205. LIVDecl = cast<VarDecl>(BeginStmt->getSingleDecl());
  5206. LUVDecl = RangeFor->getLoopVariable();
  5207. Cond = RangeFor->getCond();
  5208. Inc = RangeFor->getInc();
  5209. } else
  5210. llvm_unreachable("unhandled kind of loop");
  5211. QualType CounterTy = LIVDecl->getType();
  5212. QualType LVTy = LUVDecl->getType();
  5213. // Analyze the loop condition.
  5214. Expr *LHS, *RHS;
  5215. BinaryOperator::Opcode CondRel;
  5216. Cond = Cond->IgnoreImplicit();
  5217. if (auto *CondBinExpr = dyn_cast<BinaryOperator>(Cond)) {
  5218. LHS = CondBinExpr->getLHS();
  5219. RHS = CondBinExpr->getRHS();
  5220. CondRel = CondBinExpr->getOpcode();
  5221. } else if (auto *CondCXXOp = dyn_cast<CXXOperatorCallExpr>(Cond)) {
  5222. assert(CondCXXOp->getNumArgs() == 2 && "Comparison should have 2 operands");
  5223. LHS = CondCXXOp->getArg(0);
  5224. RHS = CondCXXOp->getArg(1);
  5225. switch (CondCXXOp->getOperator()) {
  5226. case OO_ExclaimEqual:
  5227. CondRel = BO_NE;
  5228. break;
  5229. case OO_Less:
  5230. CondRel = BO_LT;
  5231. break;
  5232. case OO_LessEqual:
  5233. CondRel = BO_LE;
  5234. break;
  5235. case OO_Greater:
  5236. CondRel = BO_GT;
  5237. break;
  5238. case OO_GreaterEqual:
  5239. CondRel = BO_GE;
  5240. break;
  5241. default:
  5242. llvm_unreachable("unexpected iterator operator");
  5243. }
  5244. } else
  5245. llvm_unreachable("unexpected loop condition");
  5246. // Normalize such that the loop counter is on the LHS.
  5247. if (!isa<DeclRefExpr>(LHS->IgnoreImplicit()) ||
  5248. cast<DeclRefExpr>(LHS->IgnoreImplicit())->getDecl() != LIVDecl) {
  5249. std::swap(LHS, RHS);
  5250. CondRel = BinaryOperator::reverseComparisonOp(CondRel);
  5251. }
  5252. auto *CounterRef = cast<DeclRefExpr>(LHS->IgnoreImplicit());
  5253. // Decide the bit width for the logical iteration counter. By default use the
  5254. // unsigned ptrdiff_t integer size (for iterators and pointers).
  5255. // TODO: For iterators, use iterator::difference_type,
  5256. // std::iterator_traits<>::difference_type or decltype(it - end).
  5257. QualType LogicalTy = Ctx.getUnsignedPointerDiffType();
  5258. if (CounterTy->isIntegerType()) {
  5259. unsigned BitWidth = Ctx.getIntWidth(CounterTy);
  5260. LogicalTy = Ctx.getIntTypeForBitwidth(BitWidth, false);
  5261. }
  5262. // Analyze the loop increment.
  5263. Expr *Step;
  5264. if (auto *IncUn = dyn_cast<UnaryOperator>(Inc)) {
  5265. int Direction;
  5266. switch (IncUn->getOpcode()) {
  5267. case UO_PreInc:
  5268. case UO_PostInc:
  5269. Direction = 1;
  5270. break;
  5271. case UO_PreDec:
  5272. case UO_PostDec:
  5273. Direction = -1;
  5274. break;
  5275. default:
  5276. llvm_unreachable("unhandled unary increment operator");
  5277. }
  5278. Step = IntegerLiteral::Create(
  5279. Ctx, llvm::APInt(Ctx.getIntWidth(LogicalTy), Direction), LogicalTy, {});
  5280. } else if (auto *IncBin = dyn_cast<BinaryOperator>(Inc)) {
  5281. if (IncBin->getOpcode() == BO_AddAssign) {
  5282. Step = IncBin->getRHS();
  5283. } else if (IncBin->getOpcode() == BO_SubAssign) {
  5284. Step =
  5285. AssertSuccess(BuildUnaryOp(nullptr, {}, UO_Minus, IncBin->getRHS()));
  5286. } else
  5287. llvm_unreachable("unhandled binary increment operator");
  5288. } else if (auto *CondCXXOp = dyn_cast<CXXOperatorCallExpr>(Inc)) {
  5289. switch (CondCXXOp->getOperator()) {
  5290. case OO_PlusPlus:
  5291. Step = IntegerLiteral::Create(
  5292. Ctx, llvm::APInt(Ctx.getIntWidth(LogicalTy), 1), LogicalTy, {});
  5293. break;
  5294. case OO_MinusMinus:
  5295. Step = IntegerLiteral::Create(
  5296. Ctx, llvm::APInt(Ctx.getIntWidth(LogicalTy), -1), LogicalTy, {});
  5297. break;
  5298. case OO_PlusEqual:
  5299. Step = CondCXXOp->getArg(1);
  5300. break;
  5301. case OO_MinusEqual:
  5302. Step = AssertSuccess(
  5303. BuildUnaryOp(nullptr, {}, UO_Minus, CondCXXOp->getArg(1)));
  5304. break;
  5305. default:
  5306. llvm_unreachable("unhandled overloaded increment operator");
  5307. }
  5308. } else
  5309. llvm_unreachable("unknown increment expression");
  5310. CapturedStmt *DistanceFunc =
  5311. buildDistanceFunc(*this, LogicalTy, CondRel, LHS, RHS, Step);
  5312. CapturedStmt *LoopVarFunc = buildLoopVarFunc(
  5313. *this, LVTy, LogicalTy, CounterRef, Step, isa<CXXForRangeStmt>(AStmt));
  5314. DeclRefExpr *LVRef = BuildDeclRefExpr(LUVDecl, LUVDecl->getType(), VK_LValue,
  5315. {}, nullptr, nullptr, {}, nullptr);
  5316. return OMPCanonicalLoop::create(getASTContext(), AStmt, DistanceFunc,
  5317. LoopVarFunc, LVRef);
  5318. }
  5319. StmtResult Sema::ActOnOpenMPLoopnest(Stmt *AStmt) {
  5320. // Handle a literal loop.
  5321. if (isa<ForStmt>(AStmt) || isa<CXXForRangeStmt>(AStmt))
  5322. return ActOnOpenMPCanonicalLoop(AStmt);
  5323. // If not a literal loop, it must be the result of a loop transformation.
  5324. OMPExecutableDirective *LoopTransform = cast<OMPExecutableDirective>(AStmt);
  5325. assert(
  5326. isOpenMPLoopTransformationDirective(LoopTransform->getDirectiveKind()) &&
  5327. "Loop transformation directive expected");
  5328. return LoopTransform;
  5329. }
  5330. static ExprResult buildUserDefinedMapperRef(Sema &SemaRef, Scope *S,
  5331. CXXScopeSpec &MapperIdScopeSpec,
  5332. const DeclarationNameInfo &MapperId,
  5333. QualType Type,
  5334. Expr *UnresolvedMapper);
  5335. /// Perform DFS through the structure/class data members trying to find
  5336. /// member(s) with user-defined 'default' mapper and generate implicit map
  5337. /// clauses for such members with the found 'default' mapper.
  5338. static void
  5339. processImplicitMapsWithDefaultMappers(Sema &S, DSAStackTy *Stack,
  5340. SmallVectorImpl<OMPClause *> &Clauses) {
  5341. // Check for the deault mapper for data members.
  5342. if (S.getLangOpts().OpenMP < 50)
  5343. return;
  5344. SmallVector<OMPClause *, 4> ImplicitMaps;
  5345. for (int Cnt = 0, EndCnt = Clauses.size(); Cnt < EndCnt; ++Cnt) {
  5346. auto *C = dyn_cast<OMPMapClause>(Clauses[Cnt]);
  5347. if (!C)
  5348. continue;
  5349. SmallVector<Expr *, 4> SubExprs;
  5350. auto *MI = C->mapperlist_begin();
  5351. for (auto I = C->varlist_begin(), End = C->varlist_end(); I != End;
  5352. ++I, ++MI) {
  5353. // Expression is mapped using mapper - skip it.
  5354. if (*MI)
  5355. continue;
  5356. Expr *E = *I;
  5357. // Expression is dependent - skip it, build the mapper when it gets
  5358. // instantiated.
  5359. if (E->isTypeDependent() || E->isValueDependent() ||
  5360. E->containsUnexpandedParameterPack())
  5361. continue;
  5362. // Array section - need to check for the mapping of the array section
  5363. // element.
  5364. QualType CanonType = E->getType().getCanonicalType();
  5365. if (CanonType->isSpecificBuiltinType(BuiltinType::OMPArraySection)) {
  5366. const auto *OASE = cast<OMPArraySectionExpr>(E->IgnoreParenImpCasts());
  5367. QualType BaseType =
  5368. OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
  5369. QualType ElemType;
  5370. if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
  5371. ElemType = ATy->getElementType();
  5372. else
  5373. ElemType = BaseType->getPointeeType();
  5374. CanonType = ElemType;
  5375. }
  5376. // DFS over data members in structures/classes.
  5377. SmallVector<std::pair<QualType, FieldDecl *>, 4> Types(
  5378. 1, {CanonType, nullptr});
  5379. llvm::DenseMap<const Type *, Expr *> Visited;
  5380. SmallVector<std::pair<FieldDecl *, unsigned>, 4> ParentChain(
  5381. 1, {nullptr, 1});
  5382. while (!Types.empty()) {
  5383. QualType BaseType;
  5384. FieldDecl *CurFD;
  5385. std::tie(BaseType, CurFD) = Types.pop_back_val();
  5386. while (ParentChain.back().second == 0)
  5387. ParentChain.pop_back();
  5388. --ParentChain.back().second;
  5389. if (BaseType.isNull())
  5390. continue;
  5391. // Only structs/classes are allowed to have mappers.
  5392. const RecordDecl *RD = BaseType.getCanonicalType()->getAsRecordDecl();
  5393. if (!RD)
  5394. continue;
  5395. auto It = Visited.find(BaseType.getTypePtr());
  5396. if (It == Visited.end()) {
  5397. // Try to find the associated user-defined mapper.
  5398. CXXScopeSpec MapperIdScopeSpec;
  5399. DeclarationNameInfo DefaultMapperId;
  5400. DefaultMapperId.setName(S.Context.DeclarationNames.getIdentifier(
  5401. &S.Context.Idents.get("default")));
  5402. DefaultMapperId.setLoc(E->getExprLoc());
  5403. ExprResult ER = buildUserDefinedMapperRef(
  5404. S, Stack->getCurScope(), MapperIdScopeSpec, DefaultMapperId,
  5405. BaseType, /*UnresolvedMapper=*/nullptr);
  5406. if (ER.isInvalid())
  5407. continue;
  5408. It = Visited.try_emplace(BaseType.getTypePtr(), ER.get()).first;
  5409. }
  5410. // Found default mapper.
  5411. if (It->second) {
  5412. auto *OE = new (S.Context) OpaqueValueExpr(E->getExprLoc(), CanonType,
  5413. VK_LValue, OK_Ordinary, E);
  5414. OE->setIsUnique(/*V=*/true);
  5415. Expr *BaseExpr = OE;
  5416. for (const auto &P : ParentChain) {
  5417. if (P.first) {
  5418. BaseExpr = S.BuildMemberExpr(
  5419. BaseExpr, /*IsArrow=*/false, E->getExprLoc(),
  5420. NestedNameSpecifierLoc(), SourceLocation(), P.first,
  5421. DeclAccessPair::make(P.first, P.first->getAccess()),
  5422. /*HadMultipleCandidates=*/false, DeclarationNameInfo(),
  5423. P.first->getType(), VK_LValue, OK_Ordinary);
  5424. BaseExpr = S.DefaultLvalueConversion(BaseExpr).get();
  5425. }
  5426. }
  5427. if (CurFD)
  5428. BaseExpr = S.BuildMemberExpr(
  5429. BaseExpr, /*IsArrow=*/false, E->getExprLoc(),
  5430. NestedNameSpecifierLoc(), SourceLocation(), CurFD,
  5431. DeclAccessPair::make(CurFD, CurFD->getAccess()),
  5432. /*HadMultipleCandidates=*/false, DeclarationNameInfo(),
  5433. CurFD->getType(), VK_LValue, OK_Ordinary);
  5434. SubExprs.push_back(BaseExpr);
  5435. continue;
  5436. }
  5437. // Check for the "default" mapper for data members.
  5438. bool FirstIter = true;
  5439. for (FieldDecl *FD : RD->fields()) {
  5440. if (!FD)
  5441. continue;
  5442. QualType FieldTy = FD->getType();
  5443. if (FieldTy.isNull() ||
  5444. !(FieldTy->isStructureOrClassType() || FieldTy->isUnionType()))
  5445. continue;
  5446. if (FirstIter) {
  5447. FirstIter = false;
  5448. ParentChain.emplace_back(CurFD, 1);
  5449. } else {
  5450. ++ParentChain.back().second;
  5451. }
  5452. Types.emplace_back(FieldTy, FD);
  5453. }
  5454. }
  5455. }
  5456. if (SubExprs.empty())
  5457. continue;
  5458. CXXScopeSpec MapperIdScopeSpec;
  5459. DeclarationNameInfo MapperId;
  5460. if (OMPClause *NewClause = S.ActOnOpenMPMapClause(
  5461. C->getMapTypeModifiers(), C->getMapTypeModifiersLoc(),
  5462. MapperIdScopeSpec, MapperId, C->getMapType(),
  5463. /*IsMapTypeImplicit=*/true, SourceLocation(), SourceLocation(),
  5464. SubExprs, OMPVarListLocTy()))
  5465. Clauses.push_back(NewClause);
  5466. }
  5467. }
  5468. StmtResult Sema::ActOnOpenMPExecutableDirective(
  5469. OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
  5470. OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
  5471. Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
  5472. StmtResult Res = StmtError();
  5473. OpenMPBindClauseKind BindKind = OMPC_BIND_unknown;
  5474. if (const OMPBindClause *BC =
  5475. OMPExecutableDirective::getSingleClause<OMPBindClause>(Clauses))
  5476. BindKind = BC->getBindKind();
  5477. // First check CancelRegion which is then used in checkNestingOfRegions.
  5478. if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) ||
  5479. checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
  5480. BindKind, StartLoc))
  5481. return StmtError();
  5482. llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
  5483. VarsWithInheritedDSAType VarsWithInheritedDSA;
  5484. bool ErrorFound = false;
  5485. ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
  5486. if (AStmt && !CurContext->isDependentContext() && Kind != OMPD_atomic &&
  5487. Kind != OMPD_critical && Kind != OMPD_section && Kind != OMPD_master &&
  5488. Kind != OMPD_masked && !isOpenMPLoopTransformationDirective(Kind)) {
  5489. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  5490. // Check default data sharing attributes for referenced variables.
  5491. DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
  5492. int ThisCaptureLevel = getOpenMPCaptureLevels(Kind);
  5493. Stmt *S = AStmt;
  5494. while (--ThisCaptureLevel >= 0)
  5495. S = cast<CapturedStmt>(S)->getCapturedStmt();
  5496. DSAChecker.Visit(S);
  5497. if (!isOpenMPTargetDataManagementDirective(Kind) &&
  5498. !isOpenMPTaskingDirective(Kind)) {
  5499. // Visit subcaptures to generate implicit clauses for captured vars.
  5500. auto *CS = cast<CapturedStmt>(AStmt);
  5501. SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
  5502. getOpenMPCaptureRegions(CaptureRegions, Kind);
  5503. // Ignore outer tasking regions for target directives.
  5504. if (CaptureRegions.size() > 1 && CaptureRegions.front() == OMPD_task)
  5505. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  5506. DSAChecker.visitSubCaptures(CS);
  5507. }
  5508. if (DSAChecker.isErrorFound())
  5509. return StmtError();
  5510. // Generate list of implicitly defined firstprivate variables.
  5511. VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
  5512. SmallVector<Expr *, 4> ImplicitFirstprivates(
  5513. DSAChecker.getImplicitFirstprivate().begin(),
  5514. DSAChecker.getImplicitFirstprivate().end());
  5515. const unsigned DefaultmapKindNum = OMPC_DEFAULTMAP_pointer + 1;
  5516. SmallVector<Expr *, 4> ImplicitMaps[DefaultmapKindNum][OMPC_MAP_delete];
  5517. SmallVector<OpenMPMapModifierKind, NumberOfOMPMapClauseModifiers>
  5518. ImplicitMapModifiers[DefaultmapKindNum];
  5519. SmallVector<SourceLocation, NumberOfOMPMapClauseModifiers>
  5520. ImplicitMapModifiersLoc[DefaultmapKindNum];
  5521. // Get the original location of present modifier from Defaultmap clause.
  5522. SourceLocation PresentModifierLocs[DefaultmapKindNum];
  5523. for (OMPClause *C : Clauses) {
  5524. if (auto *DMC = dyn_cast<OMPDefaultmapClause>(C))
  5525. if (DMC->getDefaultmapModifier() == OMPC_DEFAULTMAP_MODIFIER_present)
  5526. PresentModifierLocs[DMC->getDefaultmapKind()] =
  5527. DMC->getDefaultmapModifierLoc();
  5528. }
  5529. for (unsigned VC = 0; VC < DefaultmapKindNum; ++VC) {
  5530. auto Kind = static_cast<OpenMPDefaultmapClauseKind>(VC);
  5531. for (unsigned I = 0; I < OMPC_MAP_delete; ++I) {
  5532. ArrayRef<Expr *> ImplicitMap = DSAChecker.getImplicitMap(
  5533. Kind, static_cast<OpenMPMapClauseKind>(I));
  5534. ImplicitMaps[VC][I].append(ImplicitMap.begin(), ImplicitMap.end());
  5535. }
  5536. ArrayRef<OpenMPMapModifierKind> ImplicitModifier =
  5537. DSAChecker.getImplicitMapModifier(Kind);
  5538. ImplicitMapModifiers[VC].append(ImplicitModifier.begin(),
  5539. ImplicitModifier.end());
  5540. std::fill_n(std::back_inserter(ImplicitMapModifiersLoc[VC]),
  5541. ImplicitModifier.size(), PresentModifierLocs[VC]);
  5542. }
  5543. // Mark taskgroup task_reduction descriptors as implicitly firstprivate.
  5544. for (OMPClause *C : Clauses) {
  5545. if (auto *IRC = dyn_cast<OMPInReductionClause>(C)) {
  5546. for (Expr *E : IRC->taskgroup_descriptors())
  5547. if (E)
  5548. ImplicitFirstprivates.emplace_back(E);
  5549. }
  5550. // OpenMP 5.0, 2.10.1 task Construct
  5551. // [detach clause]... The event-handle will be considered as if it was
  5552. // specified on a firstprivate clause.
  5553. if (auto *DC = dyn_cast<OMPDetachClause>(C))
  5554. ImplicitFirstprivates.push_back(DC->getEventHandler());
  5555. }
  5556. if (!ImplicitFirstprivates.empty()) {
  5557. if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
  5558. ImplicitFirstprivates, SourceLocation(), SourceLocation(),
  5559. SourceLocation())) {
  5560. ClausesWithImplicit.push_back(Implicit);
  5561. ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
  5562. ImplicitFirstprivates.size();
  5563. } else {
  5564. ErrorFound = true;
  5565. }
  5566. }
  5567. // OpenMP 5.0 [2.19.7]
  5568. // If a list item appears in a reduction, lastprivate or linear
  5569. // clause on a combined target construct then it is treated as
  5570. // if it also appears in a map clause with a map-type of tofrom
  5571. if (getLangOpts().OpenMP >= 50 && Kind != OMPD_target &&
  5572. isOpenMPTargetExecutionDirective(Kind)) {
  5573. SmallVector<Expr *, 4> ImplicitExprs;
  5574. for (OMPClause *C : Clauses) {
  5575. if (auto *RC = dyn_cast<OMPReductionClause>(C))
  5576. for (Expr *E : RC->varlists())
  5577. if (!isa<DeclRefExpr>(E->IgnoreParenImpCasts()))
  5578. ImplicitExprs.emplace_back(E);
  5579. }
  5580. if (!ImplicitExprs.empty()) {
  5581. ArrayRef<Expr *> Exprs = ImplicitExprs;
  5582. CXXScopeSpec MapperIdScopeSpec;
  5583. DeclarationNameInfo MapperId;
  5584. if (OMPClause *Implicit = ActOnOpenMPMapClause(
  5585. OMPC_MAP_MODIFIER_unknown, SourceLocation(), MapperIdScopeSpec,
  5586. MapperId, OMPC_MAP_tofrom,
  5587. /*IsMapTypeImplicit=*/true, SourceLocation(), SourceLocation(),
  5588. Exprs, OMPVarListLocTy(), /*NoDiagnose=*/true))
  5589. ClausesWithImplicit.emplace_back(Implicit);
  5590. }
  5591. }
  5592. for (unsigned I = 0, E = DefaultmapKindNum; I < E; ++I) {
  5593. int ClauseKindCnt = -1;
  5594. for (ArrayRef<Expr *> ImplicitMap : ImplicitMaps[I]) {
  5595. ++ClauseKindCnt;
  5596. if (ImplicitMap.empty())
  5597. continue;
  5598. CXXScopeSpec MapperIdScopeSpec;
  5599. DeclarationNameInfo MapperId;
  5600. auto Kind = static_cast<OpenMPMapClauseKind>(ClauseKindCnt);
  5601. if (OMPClause *Implicit = ActOnOpenMPMapClause(
  5602. ImplicitMapModifiers[I], ImplicitMapModifiersLoc[I],
  5603. MapperIdScopeSpec, MapperId, Kind, /*IsMapTypeImplicit=*/true,
  5604. SourceLocation(), SourceLocation(), ImplicitMap,
  5605. OMPVarListLocTy())) {
  5606. ClausesWithImplicit.emplace_back(Implicit);
  5607. ErrorFound |= cast<OMPMapClause>(Implicit)->varlist_size() !=
  5608. ImplicitMap.size();
  5609. } else {
  5610. ErrorFound = true;
  5611. }
  5612. }
  5613. }
  5614. // Build expressions for implicit maps of data members with 'default'
  5615. // mappers.
  5616. if (LangOpts.OpenMP >= 50)
  5617. processImplicitMapsWithDefaultMappers(*this, DSAStack,
  5618. ClausesWithImplicit);
  5619. }
  5620. llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
  5621. switch (Kind) {
  5622. case OMPD_parallel:
  5623. Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
  5624. EndLoc);
  5625. AllowedNameModifiers.push_back(OMPD_parallel);
  5626. break;
  5627. case OMPD_simd:
  5628. Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
  5629. VarsWithInheritedDSA);
  5630. if (LangOpts.OpenMP >= 50)
  5631. AllowedNameModifiers.push_back(OMPD_simd);
  5632. break;
  5633. case OMPD_tile:
  5634. Res =
  5635. ActOnOpenMPTileDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
  5636. break;
  5637. case OMPD_unroll:
  5638. Res = ActOnOpenMPUnrollDirective(ClausesWithImplicit, AStmt, StartLoc,
  5639. EndLoc);
  5640. break;
  5641. case OMPD_for:
  5642. Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
  5643. VarsWithInheritedDSA);
  5644. break;
  5645. case OMPD_for_simd:
  5646. Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
  5647. EndLoc, VarsWithInheritedDSA);
  5648. if (LangOpts.OpenMP >= 50)
  5649. AllowedNameModifiers.push_back(OMPD_simd);
  5650. break;
  5651. case OMPD_sections:
  5652. Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
  5653. EndLoc);
  5654. break;
  5655. case OMPD_section:
  5656. assert(ClausesWithImplicit.empty() &&
  5657. "No clauses are allowed for 'omp section' directive");
  5658. Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
  5659. break;
  5660. case OMPD_single:
  5661. Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
  5662. EndLoc);
  5663. break;
  5664. case OMPD_master:
  5665. assert(ClausesWithImplicit.empty() &&
  5666. "No clauses are allowed for 'omp master' directive");
  5667. Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
  5668. break;
  5669. case OMPD_masked:
  5670. Res = ActOnOpenMPMaskedDirective(ClausesWithImplicit, AStmt, StartLoc,
  5671. EndLoc);
  5672. break;
  5673. case OMPD_critical:
  5674. Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
  5675. StartLoc, EndLoc);
  5676. break;
  5677. case OMPD_parallel_for:
  5678. Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
  5679. EndLoc, VarsWithInheritedDSA);
  5680. AllowedNameModifiers.push_back(OMPD_parallel);
  5681. break;
  5682. case OMPD_parallel_for_simd:
  5683. Res = ActOnOpenMPParallelForSimdDirective(
  5684. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  5685. AllowedNameModifiers.push_back(OMPD_parallel);
  5686. if (LangOpts.OpenMP >= 50)
  5687. AllowedNameModifiers.push_back(OMPD_simd);
  5688. break;
  5689. case OMPD_parallel_master:
  5690. Res = ActOnOpenMPParallelMasterDirective(ClausesWithImplicit, AStmt,
  5691. StartLoc, EndLoc);
  5692. AllowedNameModifiers.push_back(OMPD_parallel);
  5693. break;
  5694. case OMPD_parallel_sections:
  5695. Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
  5696. StartLoc, EndLoc);
  5697. AllowedNameModifiers.push_back(OMPD_parallel);
  5698. break;
  5699. case OMPD_task:
  5700. Res =
  5701. ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
  5702. AllowedNameModifiers.push_back(OMPD_task);
  5703. break;
  5704. case OMPD_taskyield:
  5705. assert(ClausesWithImplicit.empty() &&
  5706. "No clauses are allowed for 'omp taskyield' directive");
  5707. assert(AStmt == nullptr &&
  5708. "No associated statement allowed for 'omp taskyield' directive");
  5709. Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
  5710. break;
  5711. case OMPD_barrier:
  5712. assert(ClausesWithImplicit.empty() &&
  5713. "No clauses are allowed for 'omp barrier' directive");
  5714. assert(AStmt == nullptr &&
  5715. "No associated statement allowed for 'omp barrier' directive");
  5716. Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
  5717. break;
  5718. case OMPD_taskwait:
  5719. assert(AStmt == nullptr &&
  5720. "No associated statement allowed for 'omp taskwait' directive");
  5721. Res = ActOnOpenMPTaskwaitDirective(ClausesWithImplicit, StartLoc, EndLoc);
  5722. break;
  5723. case OMPD_taskgroup:
  5724. Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc,
  5725. EndLoc);
  5726. break;
  5727. case OMPD_flush:
  5728. assert(AStmt == nullptr &&
  5729. "No associated statement allowed for 'omp flush' directive");
  5730. Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
  5731. break;
  5732. case OMPD_depobj:
  5733. assert(AStmt == nullptr &&
  5734. "No associated statement allowed for 'omp depobj' directive");
  5735. Res = ActOnOpenMPDepobjDirective(ClausesWithImplicit, StartLoc, EndLoc);
  5736. break;
  5737. case OMPD_scan:
  5738. assert(AStmt == nullptr &&
  5739. "No associated statement allowed for 'omp scan' directive");
  5740. Res = ActOnOpenMPScanDirective(ClausesWithImplicit, StartLoc, EndLoc);
  5741. break;
  5742. case OMPD_ordered:
  5743. Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
  5744. EndLoc);
  5745. break;
  5746. case OMPD_atomic:
  5747. Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
  5748. EndLoc);
  5749. break;
  5750. case OMPD_teams:
  5751. Res =
  5752. ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
  5753. break;
  5754. case OMPD_target:
  5755. Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
  5756. EndLoc);
  5757. AllowedNameModifiers.push_back(OMPD_target);
  5758. break;
  5759. case OMPD_target_parallel:
  5760. Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
  5761. StartLoc, EndLoc);
  5762. AllowedNameModifiers.push_back(OMPD_target);
  5763. AllowedNameModifiers.push_back(OMPD_parallel);
  5764. break;
  5765. case OMPD_target_parallel_for:
  5766. Res = ActOnOpenMPTargetParallelForDirective(
  5767. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  5768. AllowedNameModifiers.push_back(OMPD_target);
  5769. AllowedNameModifiers.push_back(OMPD_parallel);
  5770. break;
  5771. case OMPD_cancellation_point:
  5772. assert(ClausesWithImplicit.empty() &&
  5773. "No clauses are allowed for 'omp cancellation point' directive");
  5774. assert(AStmt == nullptr && "No associated statement allowed for 'omp "
  5775. "cancellation point' directive");
  5776. Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
  5777. break;
  5778. case OMPD_cancel:
  5779. assert(AStmt == nullptr &&
  5780. "No associated statement allowed for 'omp cancel' directive");
  5781. Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
  5782. CancelRegion);
  5783. AllowedNameModifiers.push_back(OMPD_cancel);
  5784. break;
  5785. case OMPD_target_data:
  5786. Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
  5787. EndLoc);
  5788. AllowedNameModifiers.push_back(OMPD_target_data);
  5789. break;
  5790. case OMPD_target_enter_data:
  5791. Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
  5792. EndLoc, AStmt);
  5793. AllowedNameModifiers.push_back(OMPD_target_enter_data);
  5794. break;
  5795. case OMPD_target_exit_data:
  5796. Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
  5797. EndLoc, AStmt);
  5798. AllowedNameModifiers.push_back(OMPD_target_exit_data);
  5799. break;
  5800. case OMPD_taskloop:
  5801. Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
  5802. EndLoc, VarsWithInheritedDSA);
  5803. AllowedNameModifiers.push_back(OMPD_taskloop);
  5804. break;
  5805. case OMPD_taskloop_simd:
  5806. Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
  5807. EndLoc, VarsWithInheritedDSA);
  5808. AllowedNameModifiers.push_back(OMPD_taskloop);
  5809. if (LangOpts.OpenMP >= 50)
  5810. AllowedNameModifiers.push_back(OMPD_simd);
  5811. break;
  5812. case OMPD_master_taskloop:
  5813. Res = ActOnOpenMPMasterTaskLoopDirective(
  5814. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  5815. AllowedNameModifiers.push_back(OMPD_taskloop);
  5816. break;
  5817. case OMPD_master_taskloop_simd:
  5818. Res = ActOnOpenMPMasterTaskLoopSimdDirective(
  5819. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  5820. AllowedNameModifiers.push_back(OMPD_taskloop);
  5821. if (LangOpts.OpenMP >= 50)
  5822. AllowedNameModifiers.push_back(OMPD_simd);
  5823. break;
  5824. case OMPD_parallel_master_taskloop:
  5825. Res = ActOnOpenMPParallelMasterTaskLoopDirective(
  5826. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  5827. AllowedNameModifiers.push_back(OMPD_taskloop);
  5828. AllowedNameModifiers.push_back(OMPD_parallel);
  5829. break;
  5830. case OMPD_parallel_master_taskloop_simd:
  5831. Res = ActOnOpenMPParallelMasterTaskLoopSimdDirective(
  5832. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  5833. AllowedNameModifiers.push_back(OMPD_taskloop);
  5834. AllowedNameModifiers.push_back(OMPD_parallel);
  5835. if (LangOpts.OpenMP >= 50)
  5836. AllowedNameModifiers.push_back(OMPD_simd);
  5837. break;
  5838. case OMPD_distribute:
  5839. Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
  5840. EndLoc, VarsWithInheritedDSA);
  5841. break;
  5842. case OMPD_target_update:
  5843. Res = ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc,
  5844. EndLoc, AStmt);
  5845. AllowedNameModifiers.push_back(OMPD_target_update);
  5846. break;
  5847. case OMPD_distribute_parallel_for:
  5848. Res = ActOnOpenMPDistributeParallelForDirective(
  5849. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  5850. AllowedNameModifiers.push_back(OMPD_parallel);
  5851. break;
  5852. case OMPD_distribute_parallel_for_simd:
  5853. Res = ActOnOpenMPDistributeParallelForSimdDirective(
  5854. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  5855. AllowedNameModifiers.push_back(OMPD_parallel);
  5856. if (LangOpts.OpenMP >= 50)
  5857. AllowedNameModifiers.push_back(OMPD_simd);
  5858. break;
  5859. case OMPD_distribute_simd:
  5860. Res = ActOnOpenMPDistributeSimdDirective(
  5861. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  5862. if (LangOpts.OpenMP >= 50)
  5863. AllowedNameModifiers.push_back(OMPD_simd);
  5864. break;
  5865. case OMPD_target_parallel_for_simd:
  5866. Res = ActOnOpenMPTargetParallelForSimdDirective(
  5867. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  5868. AllowedNameModifiers.push_back(OMPD_target);
  5869. AllowedNameModifiers.push_back(OMPD_parallel);
  5870. if (LangOpts.OpenMP >= 50)
  5871. AllowedNameModifiers.push_back(OMPD_simd);
  5872. break;
  5873. case OMPD_target_simd:
  5874. Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
  5875. EndLoc, VarsWithInheritedDSA);
  5876. AllowedNameModifiers.push_back(OMPD_target);
  5877. if (LangOpts.OpenMP >= 50)
  5878. AllowedNameModifiers.push_back(OMPD_simd);
  5879. break;
  5880. case OMPD_teams_distribute:
  5881. Res = ActOnOpenMPTeamsDistributeDirective(
  5882. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  5883. break;
  5884. case OMPD_teams_distribute_simd:
  5885. Res = ActOnOpenMPTeamsDistributeSimdDirective(
  5886. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  5887. if (LangOpts.OpenMP >= 50)
  5888. AllowedNameModifiers.push_back(OMPD_simd);
  5889. break;
  5890. case OMPD_teams_distribute_parallel_for_simd:
  5891. Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
  5892. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  5893. AllowedNameModifiers.push_back(OMPD_parallel);
  5894. if (LangOpts.OpenMP >= 50)
  5895. AllowedNameModifiers.push_back(OMPD_simd);
  5896. break;
  5897. case OMPD_teams_distribute_parallel_for:
  5898. Res = ActOnOpenMPTeamsDistributeParallelForDirective(
  5899. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  5900. AllowedNameModifiers.push_back(OMPD_parallel);
  5901. break;
  5902. case OMPD_target_teams:
  5903. Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
  5904. EndLoc);
  5905. AllowedNameModifiers.push_back(OMPD_target);
  5906. break;
  5907. case OMPD_target_teams_distribute:
  5908. Res = ActOnOpenMPTargetTeamsDistributeDirective(
  5909. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  5910. AllowedNameModifiers.push_back(OMPD_target);
  5911. break;
  5912. case OMPD_target_teams_distribute_parallel_for:
  5913. Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective(
  5914. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  5915. AllowedNameModifiers.push_back(OMPD_target);
  5916. AllowedNameModifiers.push_back(OMPD_parallel);
  5917. break;
  5918. case OMPD_target_teams_distribute_parallel_for_simd:
  5919. Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
  5920. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  5921. AllowedNameModifiers.push_back(OMPD_target);
  5922. AllowedNameModifiers.push_back(OMPD_parallel);
  5923. if (LangOpts.OpenMP >= 50)
  5924. AllowedNameModifiers.push_back(OMPD_simd);
  5925. break;
  5926. case OMPD_target_teams_distribute_simd:
  5927. Res = ActOnOpenMPTargetTeamsDistributeSimdDirective(
  5928. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  5929. AllowedNameModifiers.push_back(OMPD_target);
  5930. if (LangOpts.OpenMP >= 50)
  5931. AllowedNameModifiers.push_back(OMPD_simd);
  5932. break;
  5933. case OMPD_interop:
  5934. assert(AStmt == nullptr &&
  5935. "No associated statement allowed for 'omp interop' directive");
  5936. Res = ActOnOpenMPInteropDirective(ClausesWithImplicit, StartLoc, EndLoc);
  5937. break;
  5938. case OMPD_dispatch:
  5939. Res = ActOnOpenMPDispatchDirective(ClausesWithImplicit, AStmt, StartLoc,
  5940. EndLoc);
  5941. break;
  5942. case OMPD_loop:
  5943. Res = ActOnOpenMPGenericLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
  5944. EndLoc, VarsWithInheritedDSA);
  5945. break;
  5946. case OMPD_declare_target:
  5947. case OMPD_end_declare_target:
  5948. case OMPD_threadprivate:
  5949. case OMPD_allocate:
  5950. case OMPD_declare_reduction:
  5951. case OMPD_declare_mapper:
  5952. case OMPD_declare_simd:
  5953. case OMPD_requires:
  5954. case OMPD_declare_variant:
  5955. case OMPD_begin_declare_variant:
  5956. case OMPD_end_declare_variant:
  5957. llvm_unreachable("OpenMP Directive is not allowed");
  5958. case OMPD_unknown:
  5959. default:
  5960. llvm_unreachable("Unknown OpenMP directive");
  5961. }
  5962. ErrorFound = Res.isInvalid() || ErrorFound;
  5963. // Check variables in the clauses if default(none) or
  5964. // default(firstprivate) was specified.
  5965. if (DSAStack->getDefaultDSA() == DSA_none ||
  5966. DSAStack->getDefaultDSA() == DSA_firstprivate) {
  5967. DSAAttrChecker DSAChecker(DSAStack, *this, nullptr);
  5968. for (OMPClause *C : Clauses) {
  5969. switch (C->getClauseKind()) {
  5970. case OMPC_num_threads:
  5971. case OMPC_dist_schedule:
  5972. // Do not analyse if no parent teams directive.
  5973. if (isOpenMPTeamsDirective(Kind))
  5974. break;
  5975. continue;
  5976. case OMPC_if:
  5977. if (isOpenMPTeamsDirective(Kind) &&
  5978. cast<OMPIfClause>(C)->getNameModifier() != OMPD_target)
  5979. break;
  5980. if (isOpenMPParallelDirective(Kind) &&
  5981. isOpenMPTaskLoopDirective(Kind) &&
  5982. cast<OMPIfClause>(C)->getNameModifier() != OMPD_parallel)
  5983. break;
  5984. continue;
  5985. case OMPC_schedule:
  5986. case OMPC_detach:
  5987. break;
  5988. case OMPC_grainsize:
  5989. case OMPC_num_tasks:
  5990. case OMPC_final:
  5991. case OMPC_priority:
  5992. case OMPC_novariants:
  5993. case OMPC_nocontext:
  5994. // Do not analyze if no parent parallel directive.
  5995. if (isOpenMPParallelDirective(Kind))
  5996. break;
  5997. continue;
  5998. case OMPC_ordered:
  5999. case OMPC_device:
  6000. case OMPC_num_teams:
  6001. case OMPC_thread_limit:
  6002. case OMPC_hint:
  6003. case OMPC_collapse:
  6004. case OMPC_safelen:
  6005. case OMPC_simdlen:
  6006. case OMPC_sizes:
  6007. case OMPC_default:
  6008. case OMPC_proc_bind:
  6009. case OMPC_private:
  6010. case OMPC_firstprivate:
  6011. case OMPC_lastprivate:
  6012. case OMPC_shared:
  6013. case OMPC_reduction:
  6014. case OMPC_task_reduction:
  6015. case OMPC_in_reduction:
  6016. case OMPC_linear:
  6017. case OMPC_aligned:
  6018. case OMPC_copyin:
  6019. case OMPC_copyprivate:
  6020. case OMPC_nowait:
  6021. case OMPC_untied:
  6022. case OMPC_mergeable:
  6023. case OMPC_allocate:
  6024. case OMPC_read:
  6025. case OMPC_write:
  6026. case OMPC_update:
  6027. case OMPC_capture:
  6028. case OMPC_compare:
  6029. case OMPC_seq_cst:
  6030. case OMPC_acq_rel:
  6031. case OMPC_acquire:
  6032. case OMPC_release:
  6033. case OMPC_relaxed:
  6034. case OMPC_depend:
  6035. case OMPC_threads:
  6036. case OMPC_simd:
  6037. case OMPC_map:
  6038. case OMPC_nogroup:
  6039. case OMPC_defaultmap:
  6040. case OMPC_to:
  6041. case OMPC_from:
  6042. case OMPC_use_device_ptr:
  6043. case OMPC_use_device_addr:
  6044. case OMPC_is_device_ptr:
  6045. case OMPC_nontemporal:
  6046. case OMPC_order:
  6047. case OMPC_destroy:
  6048. case OMPC_inclusive:
  6049. case OMPC_exclusive:
  6050. case OMPC_uses_allocators:
  6051. case OMPC_affinity:
  6052. case OMPC_bind:
  6053. continue;
  6054. case OMPC_allocator:
  6055. case OMPC_flush:
  6056. case OMPC_depobj:
  6057. case OMPC_threadprivate:
  6058. case OMPC_uniform:
  6059. case OMPC_unknown:
  6060. case OMPC_unified_address:
  6061. case OMPC_unified_shared_memory:
  6062. case OMPC_reverse_offload:
  6063. case OMPC_dynamic_allocators:
  6064. case OMPC_atomic_default_mem_order:
  6065. case OMPC_device_type:
  6066. case OMPC_match:
  6067. case OMPC_when:
  6068. default:
  6069. llvm_unreachable("Unexpected clause");
  6070. }
  6071. for (Stmt *CC : C->children()) {
  6072. if (CC)
  6073. DSAChecker.Visit(CC);
  6074. }
  6075. }
  6076. for (const auto &P : DSAChecker.getVarsWithInheritedDSA())
  6077. VarsWithInheritedDSA[P.getFirst()] = P.getSecond();
  6078. }
  6079. for (const auto &P : VarsWithInheritedDSA) {
  6080. if (P.getFirst()->isImplicit() || isa<OMPCapturedExprDecl>(P.getFirst()))
  6081. continue;
  6082. ErrorFound = true;
  6083. if (DSAStack->getDefaultDSA() == DSA_none ||
  6084. DSAStack->getDefaultDSA() == DSA_firstprivate) {
  6085. Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
  6086. << P.first << P.second->getSourceRange();
  6087. Diag(DSAStack->getDefaultDSALocation(), diag::note_omp_default_dsa_none);
  6088. } else if (getLangOpts().OpenMP >= 50) {
  6089. Diag(P.second->getExprLoc(),
  6090. diag::err_omp_defaultmap_no_attr_for_variable)
  6091. << P.first << P.second->getSourceRange();
  6092. Diag(DSAStack->getDefaultDSALocation(),
  6093. diag::note_omp_defaultmap_attr_none);
  6094. }
  6095. }
  6096. if (!AllowedNameModifiers.empty())
  6097. ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
  6098. ErrorFound;
  6099. if (ErrorFound)
  6100. return StmtError();
  6101. if (!CurContext->isDependentContext() &&
  6102. isOpenMPTargetExecutionDirective(Kind) &&
  6103. !(DSAStack->hasRequiresDeclWithClause<OMPUnifiedSharedMemoryClause>() ||
  6104. DSAStack->hasRequiresDeclWithClause<OMPUnifiedAddressClause>() ||
  6105. DSAStack->hasRequiresDeclWithClause<OMPReverseOffloadClause>() ||
  6106. DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())) {
  6107. // Register target to DSA Stack.
  6108. DSAStack->addTargetDirLocation(StartLoc);
  6109. }
  6110. return Res;
  6111. }
  6112. Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
  6113. DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
  6114. ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
  6115. ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
  6116. ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
  6117. assert(Aligneds.size() == Alignments.size());
  6118. assert(Linears.size() == LinModifiers.size());
  6119. assert(Linears.size() == Steps.size());
  6120. if (!DG || DG.get().isNull())
  6121. return DeclGroupPtrTy();
  6122. const int SimdId = 0;
  6123. if (!DG.get().isSingleDecl()) {
  6124. Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd_variant)
  6125. << SimdId;
  6126. return DG;
  6127. }
  6128. Decl *ADecl = DG.get().getSingleDecl();
  6129. if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
  6130. ADecl = FTD->getTemplatedDecl();
  6131. auto *FD = dyn_cast<FunctionDecl>(ADecl);
  6132. if (!FD) {
  6133. Diag(ADecl->getLocation(), diag::err_omp_function_expected) << SimdId;
  6134. return DeclGroupPtrTy();
  6135. }
  6136. // OpenMP [2.8.2, declare simd construct, Description]
  6137. // The parameter of the simdlen clause must be a constant positive integer
  6138. // expression.
  6139. ExprResult SL;
  6140. if (Simdlen)
  6141. SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
  6142. // OpenMP [2.8.2, declare simd construct, Description]
  6143. // The special this pointer can be used as if was one of the arguments to the
  6144. // function in any of the linear, aligned, or uniform clauses.
  6145. // The uniform clause declares one or more arguments to have an invariant
  6146. // value for all concurrent invocations of the function in the execution of a
  6147. // single SIMD loop.
  6148. llvm::DenseMap<const Decl *, const Expr *> UniformedArgs;
  6149. const Expr *UniformedLinearThis = nullptr;
  6150. for (const Expr *E : Uniforms) {
  6151. E = E->IgnoreParenImpCasts();
  6152. if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
  6153. if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
  6154. if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
  6155. FD->getParamDecl(PVD->getFunctionScopeIndex())
  6156. ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
  6157. UniformedArgs.try_emplace(PVD->getCanonicalDecl(), E);
  6158. continue;
  6159. }
  6160. if (isa<CXXThisExpr>(E)) {
  6161. UniformedLinearThis = E;
  6162. continue;
  6163. }
  6164. Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
  6165. << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
  6166. }
  6167. // OpenMP [2.8.2, declare simd construct, Description]
  6168. // The aligned clause declares that the object to which each list item points
  6169. // is aligned to the number of bytes expressed in the optional parameter of
  6170. // the aligned clause.
  6171. // The special this pointer can be used as if was one of the arguments to the
  6172. // function in any of the linear, aligned, or uniform clauses.
  6173. // The type of list items appearing in the aligned clause must be array,
  6174. // pointer, reference to array, or reference to pointer.
  6175. llvm::DenseMap<const Decl *, const Expr *> AlignedArgs;
  6176. const Expr *AlignedThis = nullptr;
  6177. for (const Expr *E : Aligneds) {
  6178. E = E->IgnoreParenImpCasts();
  6179. if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
  6180. if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
  6181. const VarDecl *CanonPVD = PVD->getCanonicalDecl();
  6182. if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
  6183. FD->getParamDecl(PVD->getFunctionScopeIndex())
  6184. ->getCanonicalDecl() == CanonPVD) {
  6185. // OpenMP [2.8.1, simd construct, Restrictions]
  6186. // A list-item cannot appear in more than one aligned clause.
  6187. if (AlignedArgs.count(CanonPVD) > 0) {
  6188. Diag(E->getExprLoc(), diag::err_omp_used_in_clause_twice)
  6189. << 1 << getOpenMPClauseName(OMPC_aligned)
  6190. << E->getSourceRange();
  6191. Diag(AlignedArgs[CanonPVD]->getExprLoc(),
  6192. diag::note_omp_explicit_dsa)
  6193. << getOpenMPClauseName(OMPC_aligned);
  6194. continue;
  6195. }
  6196. AlignedArgs[CanonPVD] = E;
  6197. QualType QTy = PVD->getType()
  6198. .getNonReferenceType()
  6199. .getUnqualifiedType()
  6200. .getCanonicalType();
  6201. const Type *Ty = QTy.getTypePtrOrNull();
  6202. if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
  6203. Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
  6204. << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
  6205. Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
  6206. }
  6207. continue;
  6208. }
  6209. }
  6210. if (isa<CXXThisExpr>(E)) {
  6211. if (AlignedThis) {
  6212. Diag(E->getExprLoc(), diag::err_omp_used_in_clause_twice)
  6213. << 2 << getOpenMPClauseName(OMPC_aligned) << E->getSourceRange();
  6214. Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
  6215. << getOpenMPClauseName(OMPC_aligned);
  6216. }
  6217. AlignedThis = E;
  6218. continue;
  6219. }
  6220. Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
  6221. << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
  6222. }
  6223. // The optional parameter of the aligned clause, alignment, must be a constant
  6224. // positive integer expression. If no optional parameter is specified,
  6225. // implementation-defined default alignments for SIMD instructions on the
  6226. // target platforms are assumed.
  6227. SmallVector<const Expr *, 4> NewAligns;
  6228. for (Expr *E : Alignments) {
  6229. ExprResult Align;
  6230. if (E)
  6231. Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
  6232. NewAligns.push_back(Align.get());
  6233. }
  6234. // OpenMP [2.8.2, declare simd construct, Description]
  6235. // The linear clause declares one or more list items to be private to a SIMD
  6236. // lane and to have a linear relationship with respect to the iteration space
  6237. // of a loop.
  6238. // The special this pointer can be used as if was one of the arguments to the
  6239. // function in any of the linear, aligned, or uniform clauses.
  6240. // When a linear-step expression is specified in a linear clause it must be
  6241. // either a constant integer expression or an integer-typed parameter that is
  6242. // specified in a uniform clause on the directive.
  6243. llvm::DenseMap<const Decl *, const Expr *> LinearArgs;
  6244. const bool IsUniformedThis = UniformedLinearThis != nullptr;
  6245. auto MI = LinModifiers.begin();
  6246. for (const Expr *E : Linears) {
  6247. auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
  6248. ++MI;
  6249. E = E->IgnoreParenImpCasts();
  6250. if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
  6251. if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
  6252. const VarDecl *CanonPVD = PVD->getCanonicalDecl();
  6253. if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
  6254. FD->getParamDecl(PVD->getFunctionScopeIndex())
  6255. ->getCanonicalDecl() == CanonPVD) {
  6256. // OpenMP [2.15.3.7, linear Clause, Restrictions]
  6257. // A list-item cannot appear in more than one linear clause.
  6258. if (LinearArgs.count(CanonPVD) > 0) {
  6259. Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
  6260. << getOpenMPClauseName(OMPC_linear)
  6261. << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
  6262. Diag(LinearArgs[CanonPVD]->getExprLoc(),
  6263. diag::note_omp_explicit_dsa)
  6264. << getOpenMPClauseName(OMPC_linear);
  6265. continue;
  6266. }
  6267. // Each argument can appear in at most one uniform or linear clause.
  6268. if (UniformedArgs.count(CanonPVD) > 0) {
  6269. Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
  6270. << getOpenMPClauseName(OMPC_linear)
  6271. << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
  6272. Diag(UniformedArgs[CanonPVD]->getExprLoc(),
  6273. diag::note_omp_explicit_dsa)
  6274. << getOpenMPClauseName(OMPC_uniform);
  6275. continue;
  6276. }
  6277. LinearArgs[CanonPVD] = E;
  6278. if (E->isValueDependent() || E->isTypeDependent() ||
  6279. E->isInstantiationDependent() ||
  6280. E->containsUnexpandedParameterPack())
  6281. continue;
  6282. (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
  6283. PVD->getOriginalType(),
  6284. /*IsDeclareSimd=*/true);
  6285. continue;
  6286. }
  6287. }
  6288. if (isa<CXXThisExpr>(E)) {
  6289. if (UniformedLinearThis) {
  6290. Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
  6291. << getOpenMPClauseName(OMPC_linear)
  6292. << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
  6293. << E->getSourceRange();
  6294. Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
  6295. << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
  6296. : OMPC_linear);
  6297. continue;
  6298. }
  6299. UniformedLinearThis = E;
  6300. if (E->isValueDependent() || E->isTypeDependent() ||
  6301. E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
  6302. continue;
  6303. (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
  6304. E->getType(), /*IsDeclareSimd=*/true);
  6305. continue;
  6306. }
  6307. Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
  6308. << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
  6309. }
  6310. Expr *Step = nullptr;
  6311. Expr *NewStep = nullptr;
  6312. SmallVector<Expr *, 4> NewSteps;
  6313. for (Expr *E : Steps) {
  6314. // Skip the same step expression, it was checked already.
  6315. if (Step == E || !E) {
  6316. NewSteps.push_back(E ? NewStep : nullptr);
  6317. continue;
  6318. }
  6319. Step = E;
  6320. if (const auto *DRE = dyn_cast<DeclRefExpr>(Step))
  6321. if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
  6322. const VarDecl *CanonPVD = PVD->getCanonicalDecl();
  6323. if (UniformedArgs.count(CanonPVD) == 0) {
  6324. Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
  6325. << Step->getSourceRange();
  6326. } else if (E->isValueDependent() || E->isTypeDependent() ||
  6327. E->isInstantiationDependent() ||
  6328. E->containsUnexpandedParameterPack() ||
  6329. CanonPVD->getType()->hasIntegerRepresentation()) {
  6330. NewSteps.push_back(Step);
  6331. } else {
  6332. Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
  6333. << Step->getSourceRange();
  6334. }
  6335. continue;
  6336. }
  6337. NewStep = Step;
  6338. if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
  6339. !Step->isInstantiationDependent() &&
  6340. !Step->containsUnexpandedParameterPack()) {
  6341. NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
  6342. .get();
  6343. if (NewStep)
  6344. NewStep =
  6345. VerifyIntegerConstantExpression(NewStep, /*FIXME*/ AllowFold).get();
  6346. }
  6347. NewSteps.push_back(NewStep);
  6348. }
  6349. auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
  6350. Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
  6351. Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
  6352. const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
  6353. const_cast<Expr **>(Linears.data()), Linears.size(),
  6354. const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
  6355. NewSteps.data(), NewSteps.size(), SR);
  6356. ADecl->addAttr(NewAttr);
  6357. return DG;
  6358. }
  6359. static void setPrototype(Sema &S, FunctionDecl *FD, FunctionDecl *FDWithProto,
  6360. QualType NewType) {
  6361. assert(NewType->isFunctionProtoType() &&
  6362. "Expected function type with prototype.");
  6363. assert(FD->getType()->isFunctionNoProtoType() &&
  6364. "Expected function with type with no prototype.");
  6365. assert(FDWithProto->getType()->isFunctionProtoType() &&
  6366. "Expected function with prototype.");
  6367. // Synthesize parameters with the same types.
  6368. FD->setType(NewType);
  6369. SmallVector<ParmVarDecl *, 16> Params;
  6370. for (const ParmVarDecl *P : FDWithProto->parameters()) {
  6371. auto *Param = ParmVarDecl::Create(S.getASTContext(), FD, SourceLocation(),
  6372. SourceLocation(), nullptr, P->getType(),
  6373. /*TInfo=*/nullptr, SC_None, nullptr);
  6374. Param->setScopeInfo(0, Params.size());
  6375. Param->setImplicit();
  6376. Params.push_back(Param);
  6377. }
  6378. FD->setParams(Params);
  6379. }
  6380. void Sema::ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(Decl *D) {
  6381. if (D->isInvalidDecl())
  6382. return;
  6383. FunctionDecl *FD = nullptr;
  6384. if (auto *UTemplDecl = dyn_cast<FunctionTemplateDecl>(D))
  6385. FD = UTemplDecl->getTemplatedDecl();
  6386. else
  6387. FD = cast<FunctionDecl>(D);
  6388. assert(FD && "Expected a function declaration!");
  6389. // If we are instantiating templates we do *not* apply scoped assumptions but
  6390. // only global ones. We apply scoped assumption to the template definition
  6391. // though.
  6392. if (!inTemplateInstantiation()) {
  6393. for (AssumptionAttr *AA : OMPAssumeScoped)
  6394. FD->addAttr(AA);
  6395. }
  6396. for (AssumptionAttr *AA : OMPAssumeGlobal)
  6397. FD->addAttr(AA);
  6398. }
  6399. Sema::OMPDeclareVariantScope::OMPDeclareVariantScope(OMPTraitInfo &TI)
  6400. : TI(&TI), NameSuffix(TI.getMangledName()) {}
  6401. void Sema::ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
  6402. Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParamLists,
  6403. SmallVectorImpl<FunctionDecl *> &Bases) {
  6404. if (!D.getIdentifier())
  6405. return;
  6406. OMPDeclareVariantScope &DVScope = OMPDeclareVariantScopes.back();
  6407. // Template specialization is an extension, check if we do it.
  6408. bool IsTemplated = !TemplateParamLists.empty();
  6409. if (IsTemplated &
  6410. !DVScope.TI->isExtensionActive(
  6411. llvm::omp::TraitProperty::implementation_extension_allow_templates))
  6412. return;
  6413. IdentifierInfo *BaseII = D.getIdentifier();
  6414. LookupResult Lookup(*this, DeclarationName(BaseII), D.getIdentifierLoc(),
  6415. LookupOrdinaryName);
  6416. LookupParsedName(Lookup, S, &D.getCXXScopeSpec());
  6417. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  6418. QualType FType = TInfo->getType();
  6419. bool IsConstexpr =
  6420. D.getDeclSpec().getConstexprSpecifier() == ConstexprSpecKind::Constexpr;
  6421. bool IsConsteval =
  6422. D.getDeclSpec().getConstexprSpecifier() == ConstexprSpecKind::Consteval;
  6423. for (auto *Candidate : Lookup) {
  6424. auto *CandidateDecl = Candidate->getUnderlyingDecl();
  6425. FunctionDecl *UDecl = nullptr;
  6426. if (IsTemplated && isa<FunctionTemplateDecl>(CandidateDecl)) {
  6427. auto *FTD = cast<FunctionTemplateDecl>(CandidateDecl);
  6428. if (FTD->getTemplateParameters()->size() == TemplateParamLists.size())
  6429. UDecl = FTD->getTemplatedDecl();
  6430. } else if (!IsTemplated)
  6431. UDecl = dyn_cast<FunctionDecl>(CandidateDecl);
  6432. if (!UDecl)
  6433. continue;
  6434. // Don't specialize constexpr/consteval functions with
  6435. // non-constexpr/consteval functions.
  6436. if (UDecl->isConstexpr() && !IsConstexpr)
  6437. continue;
  6438. if (UDecl->isConsteval() && !IsConsteval)
  6439. continue;
  6440. QualType UDeclTy = UDecl->getType();
  6441. if (!UDeclTy->isDependentType()) {
  6442. QualType NewType = Context.mergeFunctionTypes(
  6443. FType, UDeclTy, /* OfBlockPointer */ false,
  6444. /* Unqualified */ false, /* AllowCXX */ true);
  6445. if (NewType.isNull())
  6446. continue;
  6447. }
  6448. // Found a base!
  6449. Bases.push_back(UDecl);
  6450. }
  6451. bool UseImplicitBase = !DVScope.TI->isExtensionActive(
  6452. llvm::omp::TraitProperty::implementation_extension_disable_implicit_base);
  6453. // If no base was found we create a declaration that we use as base.
  6454. if (Bases.empty() && UseImplicitBase) {
  6455. D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration);
  6456. Decl *BaseD = HandleDeclarator(S, D, TemplateParamLists);
  6457. BaseD->setImplicit(true);
  6458. if (auto *BaseTemplD = dyn_cast<FunctionTemplateDecl>(BaseD))
  6459. Bases.push_back(BaseTemplD->getTemplatedDecl());
  6460. else
  6461. Bases.push_back(cast<FunctionDecl>(BaseD));
  6462. }
  6463. std::string MangledName;
  6464. MangledName += D.getIdentifier()->getName();
  6465. MangledName += getOpenMPVariantManglingSeparatorStr();
  6466. MangledName += DVScope.NameSuffix;
  6467. IdentifierInfo &VariantII = Context.Idents.get(MangledName);
  6468. VariantII.setMangledOpenMPVariantName(true);
  6469. D.SetIdentifier(&VariantII, D.getBeginLoc());
  6470. }
  6471. void Sema::ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(
  6472. Decl *D, SmallVectorImpl<FunctionDecl *> &Bases) {
  6473. // Do not mark function as is used to prevent its emission if this is the
  6474. // only place where it is used.
  6475. EnterExpressionEvaluationContext Unevaluated(
  6476. *this, Sema::ExpressionEvaluationContext::Unevaluated);
  6477. FunctionDecl *FD = nullptr;
  6478. if (auto *UTemplDecl = dyn_cast<FunctionTemplateDecl>(D))
  6479. FD = UTemplDecl->getTemplatedDecl();
  6480. else
  6481. FD = cast<FunctionDecl>(D);
  6482. auto *VariantFuncRef = DeclRefExpr::Create(
  6483. Context, NestedNameSpecifierLoc(), SourceLocation(), FD,
  6484. /* RefersToEnclosingVariableOrCapture */ false,
  6485. /* NameLoc */ FD->getLocation(), FD->getType(),
  6486. ExprValueKind::VK_PRValue);
  6487. OMPDeclareVariantScope &DVScope = OMPDeclareVariantScopes.back();
  6488. auto *OMPDeclareVariantA = OMPDeclareVariantAttr::CreateImplicit(
  6489. Context, VariantFuncRef, DVScope.TI,
  6490. /*NothingArgs=*/nullptr, /*NothingArgsSize=*/0,
  6491. /*NeedDevicePtrArgs=*/nullptr, /*NeedDevicePtrArgsSize=*/0,
  6492. /*AppendArgs=*/nullptr, /*AppendArgsSize=*/0);
  6493. for (FunctionDecl *BaseFD : Bases)
  6494. BaseFD->addAttr(OMPDeclareVariantA);
  6495. }
  6496. ExprResult Sema::ActOnOpenMPCall(ExprResult Call, Scope *Scope,
  6497. SourceLocation LParenLoc,
  6498. MultiExprArg ArgExprs,
  6499. SourceLocation RParenLoc, Expr *ExecConfig) {
  6500. // The common case is a regular call we do not want to specialize at all. Try
  6501. // to make that case fast by bailing early.
  6502. CallExpr *CE = dyn_cast<CallExpr>(Call.get());
  6503. if (!CE)
  6504. return Call;
  6505. FunctionDecl *CalleeFnDecl = CE->getDirectCallee();
  6506. if (!CalleeFnDecl)
  6507. return Call;
  6508. if (!CalleeFnDecl->hasAttr<OMPDeclareVariantAttr>())
  6509. return Call;
  6510. ASTContext &Context = getASTContext();
  6511. std::function<void(StringRef)> DiagUnknownTrait = [this,
  6512. CE](StringRef ISATrait) {
  6513. // TODO Track the selector locations in a way that is accessible here to
  6514. // improve the diagnostic location.
  6515. Diag(CE->getBeginLoc(), diag::warn_unknown_declare_variant_isa_trait)
  6516. << ISATrait;
  6517. };
  6518. TargetOMPContext OMPCtx(Context, std::move(DiagUnknownTrait),
  6519. getCurFunctionDecl(), DSAStack->getConstructTraits());
  6520. QualType CalleeFnType = CalleeFnDecl->getType();
  6521. SmallVector<Expr *, 4> Exprs;
  6522. SmallVector<VariantMatchInfo, 4> VMIs;
  6523. while (CalleeFnDecl) {
  6524. for (OMPDeclareVariantAttr *A :
  6525. CalleeFnDecl->specific_attrs<OMPDeclareVariantAttr>()) {
  6526. Expr *VariantRef = A->getVariantFuncRef();
  6527. VariantMatchInfo VMI;
  6528. OMPTraitInfo &TI = A->getTraitInfo();
  6529. TI.getAsVariantMatchInfo(Context, VMI);
  6530. if (!isVariantApplicableInContext(VMI, OMPCtx,
  6531. /* DeviceSetOnly */ false))
  6532. continue;
  6533. VMIs.push_back(VMI);
  6534. Exprs.push_back(VariantRef);
  6535. }
  6536. CalleeFnDecl = CalleeFnDecl->getPreviousDecl();
  6537. }
  6538. ExprResult NewCall;
  6539. do {
  6540. int BestIdx = getBestVariantMatchForContext(VMIs, OMPCtx);
  6541. if (BestIdx < 0)
  6542. return Call;
  6543. Expr *BestExpr = cast<DeclRefExpr>(Exprs[BestIdx]);
  6544. Decl *BestDecl = cast<DeclRefExpr>(BestExpr)->getDecl();
  6545. {
  6546. // Try to build a (member) call expression for the current best applicable
  6547. // variant expression. We allow this to fail in which case we continue
  6548. // with the next best variant expression. The fail case is part of the
  6549. // implementation defined behavior in the OpenMP standard when it talks
  6550. // about what differences in the function prototypes: "Any differences
  6551. // that the specific OpenMP context requires in the prototype of the
  6552. // variant from the base function prototype are implementation defined."
  6553. // This wording is there to allow the specialized variant to have a
  6554. // different type than the base function. This is intended and OK but if
  6555. // we cannot create a call the difference is not in the "implementation
  6556. // defined range" we allow.
  6557. Sema::TentativeAnalysisScope Trap(*this);
  6558. if (auto *SpecializedMethod = dyn_cast<CXXMethodDecl>(BestDecl)) {
  6559. auto *MemberCall = dyn_cast<CXXMemberCallExpr>(CE);
  6560. BestExpr = MemberExpr::CreateImplicit(
  6561. Context, MemberCall->getImplicitObjectArgument(),
  6562. /* IsArrow */ false, SpecializedMethod, Context.BoundMemberTy,
  6563. MemberCall->getValueKind(), MemberCall->getObjectKind());
  6564. }
  6565. NewCall = BuildCallExpr(Scope, BestExpr, LParenLoc, ArgExprs, RParenLoc,
  6566. ExecConfig);
  6567. if (NewCall.isUsable()) {
  6568. if (CallExpr *NCE = dyn_cast<CallExpr>(NewCall.get())) {
  6569. FunctionDecl *NewCalleeFnDecl = NCE->getDirectCallee();
  6570. QualType NewType = Context.mergeFunctionTypes(
  6571. CalleeFnType, NewCalleeFnDecl->getType(),
  6572. /* OfBlockPointer */ false,
  6573. /* Unqualified */ false, /* AllowCXX */ true);
  6574. if (!NewType.isNull())
  6575. break;
  6576. // Don't use the call if the function type was not compatible.
  6577. NewCall = nullptr;
  6578. }
  6579. }
  6580. }
  6581. VMIs.erase(VMIs.begin() + BestIdx);
  6582. Exprs.erase(Exprs.begin() + BestIdx);
  6583. } while (!VMIs.empty());
  6584. if (!NewCall.isUsable())
  6585. return Call;
  6586. return PseudoObjectExpr::Create(Context, CE, {NewCall.get()}, 0);
  6587. }
  6588. Optional<std::pair<FunctionDecl *, Expr *>>
  6589. Sema::checkOpenMPDeclareVariantFunction(Sema::DeclGroupPtrTy DG,
  6590. Expr *VariantRef, OMPTraitInfo &TI,
  6591. unsigned NumAppendArgs,
  6592. SourceRange SR) {
  6593. if (!DG || DG.get().isNull())
  6594. return None;
  6595. const int VariantId = 1;
  6596. // Must be applied only to single decl.
  6597. if (!DG.get().isSingleDecl()) {
  6598. Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd_variant)
  6599. << VariantId << SR;
  6600. return None;
  6601. }
  6602. Decl *ADecl = DG.get().getSingleDecl();
  6603. if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
  6604. ADecl = FTD->getTemplatedDecl();
  6605. // Decl must be a function.
  6606. auto *FD = dyn_cast<FunctionDecl>(ADecl);
  6607. if (!FD) {
  6608. Diag(ADecl->getLocation(), diag::err_omp_function_expected)
  6609. << VariantId << SR;
  6610. return None;
  6611. }
  6612. auto &&HasMultiVersionAttributes = [](const FunctionDecl *FD) {
  6613. return FD->hasAttrs() &&
  6614. (FD->hasAttr<CPUDispatchAttr>() || FD->hasAttr<CPUSpecificAttr>() ||
  6615. FD->hasAttr<TargetAttr>());
  6616. };
  6617. // OpenMP is not compatible with CPU-specific attributes.
  6618. if (HasMultiVersionAttributes(FD)) {
  6619. Diag(FD->getLocation(), diag::err_omp_declare_variant_incompat_attributes)
  6620. << SR;
  6621. return None;
  6622. }
  6623. // Allow #pragma omp declare variant only if the function is not used.
  6624. if (FD->isUsed(false))
  6625. Diag(SR.getBegin(), diag::warn_omp_declare_variant_after_used)
  6626. << FD->getLocation();
  6627. // Check if the function was emitted already.
  6628. const FunctionDecl *Definition;
  6629. if (!FD->isThisDeclarationADefinition() && FD->isDefined(Definition) &&
  6630. (LangOpts.EmitAllDecls || Context.DeclMustBeEmitted(Definition)))
  6631. Diag(SR.getBegin(), diag::warn_omp_declare_variant_after_emitted)
  6632. << FD->getLocation();
  6633. // The VariantRef must point to function.
  6634. if (!VariantRef) {
  6635. Diag(SR.getBegin(), diag::err_omp_function_expected) << VariantId;
  6636. return None;
  6637. }
  6638. auto ShouldDelayChecks = [](Expr *&E, bool) {
  6639. return E && (E->isTypeDependent() || E->isValueDependent() ||
  6640. E->containsUnexpandedParameterPack() ||
  6641. E->isInstantiationDependent());
  6642. };
  6643. // Do not check templates, wait until instantiation.
  6644. if (FD->isDependentContext() || ShouldDelayChecks(VariantRef, false) ||
  6645. TI.anyScoreOrCondition(ShouldDelayChecks))
  6646. return std::make_pair(FD, VariantRef);
  6647. // Deal with non-constant score and user condition expressions.
  6648. auto HandleNonConstantScoresAndConditions = [this](Expr *&E,
  6649. bool IsScore) -> bool {
  6650. if (!E || E->isIntegerConstantExpr(Context))
  6651. return false;
  6652. if (IsScore) {
  6653. // We warn on non-constant scores and pretend they were not present.
  6654. Diag(E->getExprLoc(), diag::warn_omp_declare_variant_score_not_constant)
  6655. << E;
  6656. E = nullptr;
  6657. } else {
  6658. // We could replace a non-constant user condition with "false" but we
  6659. // will soon need to handle these anyway for the dynamic version of
  6660. // OpenMP context selectors.
  6661. Diag(E->getExprLoc(),
  6662. diag::err_omp_declare_variant_user_condition_not_constant)
  6663. << E;
  6664. }
  6665. return true;
  6666. };
  6667. if (TI.anyScoreOrCondition(HandleNonConstantScoresAndConditions))
  6668. return None;
  6669. QualType AdjustedFnType = FD->getType();
  6670. if (NumAppendArgs) {
  6671. const auto *PTy = AdjustedFnType->getAsAdjusted<FunctionProtoType>();
  6672. if (!PTy) {
  6673. Diag(FD->getLocation(), diag::err_omp_declare_variant_prototype_required)
  6674. << SR;
  6675. return None;
  6676. }
  6677. // Adjust the function type to account for an extra omp_interop_t for each
  6678. // specified in the append_args clause.
  6679. const TypeDecl *TD = nullptr;
  6680. LookupResult Result(*this, &Context.Idents.get("omp_interop_t"),
  6681. SR.getBegin(), Sema::LookupOrdinaryName);
  6682. if (LookupName(Result, getCurScope())) {
  6683. NamedDecl *ND = Result.getFoundDecl();
  6684. TD = dyn_cast_or_null<TypeDecl>(ND);
  6685. }
  6686. if (!TD) {
  6687. Diag(SR.getBegin(), diag::err_omp_interop_type_not_found) << SR;
  6688. return None;
  6689. }
  6690. QualType InteropType = Context.getTypeDeclType(TD);
  6691. if (PTy->isVariadic()) {
  6692. Diag(FD->getLocation(), diag::err_omp_append_args_with_varargs) << SR;
  6693. return None;
  6694. }
  6695. llvm::SmallVector<QualType, 8> Params;
  6696. Params.append(PTy->param_type_begin(), PTy->param_type_end());
  6697. Params.insert(Params.end(), NumAppendArgs, InteropType);
  6698. AdjustedFnType = Context.getFunctionType(PTy->getReturnType(), Params,
  6699. PTy->getExtProtoInfo());
  6700. }
  6701. // Convert VariantRef expression to the type of the original function to
  6702. // resolve possible conflicts.
  6703. ExprResult VariantRefCast = VariantRef;
  6704. if (LangOpts.CPlusPlus) {
  6705. QualType FnPtrType;
  6706. auto *Method = dyn_cast<CXXMethodDecl>(FD);
  6707. if (Method && !Method->isStatic()) {
  6708. const Type *ClassType =
  6709. Context.getTypeDeclType(Method->getParent()).getTypePtr();
  6710. FnPtrType = Context.getMemberPointerType(AdjustedFnType, ClassType);
  6711. ExprResult ER;
  6712. {
  6713. // Build adrr_of unary op to correctly handle type checks for member
  6714. // functions.
  6715. Sema::TentativeAnalysisScope Trap(*this);
  6716. ER = CreateBuiltinUnaryOp(VariantRef->getBeginLoc(), UO_AddrOf,
  6717. VariantRef);
  6718. }
  6719. if (!ER.isUsable()) {
  6720. Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
  6721. << VariantId << VariantRef->getSourceRange();
  6722. return None;
  6723. }
  6724. VariantRef = ER.get();
  6725. } else {
  6726. FnPtrType = Context.getPointerType(AdjustedFnType);
  6727. }
  6728. QualType VarianPtrType = Context.getPointerType(VariantRef->getType());
  6729. if (VarianPtrType.getUnqualifiedType() != FnPtrType.getUnqualifiedType()) {
  6730. ImplicitConversionSequence ICS = TryImplicitConversion(
  6731. VariantRef, FnPtrType.getUnqualifiedType(),
  6732. /*SuppressUserConversions=*/false, AllowedExplicit::None,
  6733. /*InOverloadResolution=*/false,
  6734. /*CStyle=*/false,
  6735. /*AllowObjCWritebackConversion=*/false);
  6736. if (ICS.isFailure()) {
  6737. Diag(VariantRef->getExprLoc(),
  6738. diag::err_omp_declare_variant_incompat_types)
  6739. << VariantRef->getType()
  6740. << ((Method && !Method->isStatic()) ? FnPtrType : FD->getType())
  6741. << (NumAppendArgs ? 1 : 0) << VariantRef->getSourceRange();
  6742. return None;
  6743. }
  6744. VariantRefCast = PerformImplicitConversion(
  6745. VariantRef, FnPtrType.getUnqualifiedType(), AA_Converting);
  6746. if (!VariantRefCast.isUsable())
  6747. return None;
  6748. }
  6749. // Drop previously built artificial addr_of unary op for member functions.
  6750. if (Method && !Method->isStatic()) {
  6751. Expr *PossibleAddrOfVariantRef = VariantRefCast.get();
  6752. if (auto *UO = dyn_cast<UnaryOperator>(
  6753. PossibleAddrOfVariantRef->IgnoreImplicit()))
  6754. VariantRefCast = UO->getSubExpr();
  6755. }
  6756. }
  6757. ExprResult ER = CheckPlaceholderExpr(VariantRefCast.get());
  6758. if (!ER.isUsable() ||
  6759. !ER.get()->IgnoreParenImpCasts()->getType()->isFunctionType()) {
  6760. Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
  6761. << VariantId << VariantRef->getSourceRange();
  6762. return None;
  6763. }
  6764. // The VariantRef must point to function.
  6765. auto *DRE = dyn_cast<DeclRefExpr>(ER.get()->IgnoreParenImpCasts());
  6766. if (!DRE) {
  6767. Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
  6768. << VariantId << VariantRef->getSourceRange();
  6769. return None;
  6770. }
  6771. auto *NewFD = dyn_cast_or_null<FunctionDecl>(DRE->getDecl());
  6772. if (!NewFD) {
  6773. Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
  6774. << VariantId << VariantRef->getSourceRange();
  6775. return None;
  6776. }
  6777. // Check if function types are compatible in C.
  6778. if (!LangOpts.CPlusPlus) {
  6779. QualType NewType =
  6780. Context.mergeFunctionTypes(AdjustedFnType, NewFD->getType());
  6781. if (NewType.isNull()) {
  6782. Diag(VariantRef->getExprLoc(),
  6783. diag::err_omp_declare_variant_incompat_types)
  6784. << NewFD->getType() << FD->getType() << (NumAppendArgs ? 1 : 0)
  6785. << VariantRef->getSourceRange();
  6786. return None;
  6787. }
  6788. if (NewType->isFunctionProtoType()) {
  6789. if (FD->getType()->isFunctionNoProtoType())
  6790. setPrototype(*this, FD, NewFD, NewType);
  6791. else if (NewFD->getType()->isFunctionNoProtoType())
  6792. setPrototype(*this, NewFD, FD, NewType);
  6793. }
  6794. }
  6795. // Check if variant function is not marked with declare variant directive.
  6796. if (NewFD->hasAttrs() && NewFD->hasAttr<OMPDeclareVariantAttr>()) {
  6797. Diag(VariantRef->getExprLoc(),
  6798. diag::warn_omp_declare_variant_marked_as_declare_variant)
  6799. << VariantRef->getSourceRange();
  6800. SourceRange SR =
  6801. NewFD->specific_attr_begin<OMPDeclareVariantAttr>()->getRange();
  6802. Diag(SR.getBegin(), diag::note_omp_marked_declare_variant_here) << SR;
  6803. return None;
  6804. }
  6805. enum DoesntSupport {
  6806. VirtFuncs = 1,
  6807. Constructors = 3,
  6808. Destructors = 4,
  6809. DeletedFuncs = 5,
  6810. DefaultedFuncs = 6,
  6811. ConstexprFuncs = 7,
  6812. ConstevalFuncs = 8,
  6813. };
  6814. if (const auto *CXXFD = dyn_cast<CXXMethodDecl>(FD)) {
  6815. if (CXXFD->isVirtual()) {
  6816. Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
  6817. << VirtFuncs;
  6818. return None;
  6819. }
  6820. if (isa<CXXConstructorDecl>(FD)) {
  6821. Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
  6822. << Constructors;
  6823. return None;
  6824. }
  6825. if (isa<CXXDestructorDecl>(FD)) {
  6826. Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
  6827. << Destructors;
  6828. return None;
  6829. }
  6830. }
  6831. if (FD->isDeleted()) {
  6832. Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
  6833. << DeletedFuncs;
  6834. return None;
  6835. }
  6836. if (FD->isDefaulted()) {
  6837. Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
  6838. << DefaultedFuncs;
  6839. return None;
  6840. }
  6841. if (FD->isConstexpr()) {
  6842. Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
  6843. << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
  6844. return None;
  6845. }
  6846. // Check general compatibility.
  6847. if (areMultiversionVariantFunctionsCompatible(
  6848. FD, NewFD, PartialDiagnostic::NullDiagnostic(),
  6849. PartialDiagnosticAt(SourceLocation(),
  6850. PartialDiagnostic::NullDiagnostic()),
  6851. PartialDiagnosticAt(
  6852. VariantRef->getExprLoc(),
  6853. PDiag(diag::err_omp_declare_variant_doesnt_support)),
  6854. PartialDiagnosticAt(VariantRef->getExprLoc(),
  6855. PDiag(diag::err_omp_declare_variant_diff)
  6856. << FD->getLocation()),
  6857. /*TemplatesSupported=*/true, /*ConstexprSupported=*/false,
  6858. /*CLinkageMayDiffer=*/true))
  6859. return None;
  6860. return std::make_pair(FD, cast<Expr>(DRE));
  6861. }
  6862. void Sema::ActOnOpenMPDeclareVariantDirective(
  6863. FunctionDecl *FD, Expr *VariantRef, OMPTraitInfo &TI,
  6864. ArrayRef<Expr *> AdjustArgsNothing,
  6865. ArrayRef<Expr *> AdjustArgsNeedDevicePtr,
  6866. ArrayRef<OMPDeclareVariantAttr::InteropType> AppendArgs,
  6867. SourceLocation AdjustArgsLoc, SourceLocation AppendArgsLoc,
  6868. SourceRange SR) {
  6869. // OpenMP 5.1 [2.3.5, declare variant directive, Restrictions]
  6870. // An adjust_args clause or append_args clause can only be specified if the
  6871. // dispatch selector of the construct selector set appears in the match
  6872. // clause.
  6873. SmallVector<Expr *, 8> AllAdjustArgs;
  6874. llvm::append_range(AllAdjustArgs, AdjustArgsNothing);
  6875. llvm::append_range(AllAdjustArgs, AdjustArgsNeedDevicePtr);
  6876. if (!AllAdjustArgs.empty() || !AppendArgs.empty()) {
  6877. VariantMatchInfo VMI;
  6878. TI.getAsVariantMatchInfo(Context, VMI);
  6879. if (!llvm::is_contained(
  6880. VMI.ConstructTraits,
  6881. llvm::omp::TraitProperty::construct_dispatch_dispatch)) {
  6882. if (!AllAdjustArgs.empty())
  6883. Diag(AdjustArgsLoc, diag::err_omp_clause_requires_dispatch_construct)
  6884. << getOpenMPClauseName(OMPC_adjust_args);
  6885. if (!AppendArgs.empty())
  6886. Diag(AppendArgsLoc, diag::err_omp_clause_requires_dispatch_construct)
  6887. << getOpenMPClauseName(OMPC_append_args);
  6888. return;
  6889. }
  6890. }
  6891. // OpenMP 5.1 [2.3.5, declare variant directive, Restrictions]
  6892. // Each argument can only appear in a single adjust_args clause for each
  6893. // declare variant directive.
  6894. llvm::SmallPtrSet<const VarDecl *, 4> AdjustVars;
  6895. for (Expr *E : AllAdjustArgs) {
  6896. E = E->IgnoreParenImpCasts();
  6897. if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) {
  6898. if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
  6899. const VarDecl *CanonPVD = PVD->getCanonicalDecl();
  6900. if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
  6901. FD->getParamDecl(PVD->getFunctionScopeIndex())
  6902. ->getCanonicalDecl() == CanonPVD) {
  6903. // It's a parameter of the function, check duplicates.
  6904. if (!AdjustVars.insert(CanonPVD).second) {
  6905. Diag(DRE->getLocation(), diag::err_omp_adjust_arg_multiple_clauses)
  6906. << PVD;
  6907. return;
  6908. }
  6909. continue;
  6910. }
  6911. }
  6912. }
  6913. // Anything that is not a function parameter is an error.
  6914. Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause) << FD << 0;
  6915. return;
  6916. }
  6917. auto *NewAttr = OMPDeclareVariantAttr::CreateImplicit(
  6918. Context, VariantRef, &TI, const_cast<Expr **>(AdjustArgsNothing.data()),
  6919. AdjustArgsNothing.size(),
  6920. const_cast<Expr **>(AdjustArgsNeedDevicePtr.data()),
  6921. AdjustArgsNeedDevicePtr.size(),
  6922. const_cast<OMPDeclareVariantAttr::InteropType *>(AppendArgs.data()),
  6923. AppendArgs.size(), SR);
  6924. FD->addAttr(NewAttr);
  6925. }
  6926. StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
  6927. Stmt *AStmt,
  6928. SourceLocation StartLoc,
  6929. SourceLocation EndLoc) {
  6930. if (!AStmt)
  6931. return StmtError();
  6932. auto *CS = cast<CapturedStmt>(AStmt);
  6933. // 1.2.2 OpenMP Language Terminology
  6934. // Structured block - An executable statement with a single entry at the
  6935. // top and a single exit at the bottom.
  6936. // The point of exit cannot be a branch out of the structured block.
  6937. // longjmp() and throw() must not violate the entry/exit criteria.
  6938. CS->getCapturedDecl()->setNothrow();
  6939. setFunctionHasBranchProtectedScope();
  6940. return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
  6941. DSAStack->getTaskgroupReductionRef(),
  6942. DSAStack->isCancelRegion());
  6943. }
  6944. namespace {
  6945. /// Iteration space of a single for loop.
  6946. struct LoopIterationSpace final {
  6947. /// True if the condition operator is the strict compare operator (<, > or
  6948. /// !=).
  6949. bool IsStrictCompare = false;
  6950. /// Condition of the loop.
  6951. Expr *PreCond = nullptr;
  6952. /// This expression calculates the number of iterations in the loop.
  6953. /// It is always possible to calculate it before starting the loop.
  6954. Expr *NumIterations = nullptr;
  6955. /// The loop counter variable.
  6956. Expr *CounterVar = nullptr;
  6957. /// Private loop counter variable.
  6958. Expr *PrivateCounterVar = nullptr;
  6959. /// This is initializer for the initial value of #CounterVar.
  6960. Expr *CounterInit = nullptr;
  6961. /// This is step for the #CounterVar used to generate its update:
  6962. /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
  6963. Expr *CounterStep = nullptr;
  6964. /// Should step be subtracted?
  6965. bool Subtract = false;
  6966. /// Source range of the loop init.
  6967. SourceRange InitSrcRange;
  6968. /// Source range of the loop condition.
  6969. SourceRange CondSrcRange;
  6970. /// Source range of the loop increment.
  6971. SourceRange IncSrcRange;
  6972. /// Minimum value that can have the loop control variable. Used to support
  6973. /// non-rectangular loops. Applied only for LCV with the non-iterator types,
  6974. /// since only such variables can be used in non-loop invariant expressions.
  6975. Expr *MinValue = nullptr;
  6976. /// Maximum value that can have the loop control variable. Used to support
  6977. /// non-rectangular loops. Applied only for LCV with the non-iterator type,
  6978. /// since only such variables can be used in non-loop invariant expressions.
  6979. Expr *MaxValue = nullptr;
  6980. /// true, if the lower bound depends on the outer loop control var.
  6981. bool IsNonRectangularLB = false;
  6982. /// true, if the upper bound depends on the outer loop control var.
  6983. bool IsNonRectangularUB = false;
  6984. /// Index of the loop this loop depends on and forms non-rectangular loop
  6985. /// nest.
  6986. unsigned LoopDependentIdx = 0;
  6987. /// Final condition for the non-rectangular loop nest support. It is used to
  6988. /// check that the number of iterations for this particular counter must be
  6989. /// finished.
  6990. Expr *FinalCondition = nullptr;
  6991. };
  6992. /// Helper class for checking canonical form of the OpenMP loops and
  6993. /// extracting iteration space of each loop in the loop nest, that will be used
  6994. /// for IR generation.
  6995. class OpenMPIterationSpaceChecker {
  6996. /// Reference to Sema.
  6997. Sema &SemaRef;
  6998. /// Does the loop associated directive support non-rectangular loops?
  6999. bool SupportsNonRectangular;
  7000. /// Data-sharing stack.
  7001. DSAStackTy &Stack;
  7002. /// A location for diagnostics (when there is no some better location).
  7003. SourceLocation DefaultLoc;
  7004. /// A location for diagnostics (when increment is not compatible).
  7005. SourceLocation ConditionLoc;
  7006. /// A source location for referring to loop init later.
  7007. SourceRange InitSrcRange;
  7008. /// A source location for referring to condition later.
  7009. SourceRange ConditionSrcRange;
  7010. /// A source location for referring to increment later.
  7011. SourceRange IncrementSrcRange;
  7012. /// Loop variable.
  7013. ValueDecl *LCDecl = nullptr;
  7014. /// Reference to loop variable.
  7015. Expr *LCRef = nullptr;
  7016. /// Lower bound (initializer for the var).
  7017. Expr *LB = nullptr;
  7018. /// Upper bound.
  7019. Expr *UB = nullptr;
  7020. /// Loop step (increment).
  7021. Expr *Step = nullptr;
  7022. /// This flag is true when condition is one of:
  7023. /// Var < UB
  7024. /// Var <= UB
  7025. /// UB > Var
  7026. /// UB >= Var
  7027. /// This will have no value when the condition is !=
  7028. llvm::Optional<bool> TestIsLessOp;
  7029. /// This flag is true when condition is strict ( < or > ).
  7030. bool TestIsStrictOp = false;
  7031. /// This flag is true when step is subtracted on each iteration.
  7032. bool SubtractStep = false;
  7033. /// The outer loop counter this loop depends on (if any).
  7034. const ValueDecl *DepDecl = nullptr;
  7035. /// Contains number of loop (starts from 1) on which loop counter init
  7036. /// expression of this loop depends on.
  7037. Optional<unsigned> InitDependOnLC;
  7038. /// Contains number of loop (starts from 1) on which loop counter condition
  7039. /// expression of this loop depends on.
  7040. Optional<unsigned> CondDependOnLC;
  7041. /// Checks if the provide statement depends on the loop counter.
  7042. Optional<unsigned> doesDependOnLoopCounter(const Stmt *S, bool IsInitializer);
  7043. /// Original condition required for checking of the exit condition for
  7044. /// non-rectangular loop.
  7045. Expr *Condition = nullptr;
  7046. public:
  7047. OpenMPIterationSpaceChecker(Sema &SemaRef, bool SupportsNonRectangular,
  7048. DSAStackTy &Stack, SourceLocation DefaultLoc)
  7049. : SemaRef(SemaRef), SupportsNonRectangular(SupportsNonRectangular),
  7050. Stack(Stack), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {}
  7051. /// Check init-expr for canonical loop form and save loop counter
  7052. /// variable - #Var and its initialization value - #LB.
  7053. bool checkAndSetInit(Stmt *S, bool EmitDiags = true);
  7054. /// Check test-expr for canonical form, save upper-bound (#UB), flags
  7055. /// for less/greater and for strict/non-strict comparison.
  7056. bool checkAndSetCond(Expr *S);
  7057. /// Check incr-expr for canonical loop form and return true if it
  7058. /// does not conform, otherwise save loop step (#Step).
  7059. bool checkAndSetInc(Expr *S);
  7060. /// Return the loop counter variable.
  7061. ValueDecl *getLoopDecl() const { return LCDecl; }
  7062. /// Return the reference expression to loop counter variable.
  7063. Expr *getLoopDeclRefExpr() const { return LCRef; }
  7064. /// Source range of the loop init.
  7065. SourceRange getInitSrcRange() const { return InitSrcRange; }
  7066. /// Source range of the loop condition.
  7067. SourceRange getConditionSrcRange() const { return ConditionSrcRange; }
  7068. /// Source range of the loop increment.
  7069. SourceRange getIncrementSrcRange() const { return IncrementSrcRange; }
  7070. /// True if the step should be subtracted.
  7071. bool shouldSubtractStep() const { return SubtractStep; }
  7072. /// True, if the compare operator is strict (<, > or !=).
  7073. bool isStrictTestOp() const { return TestIsStrictOp; }
  7074. /// Build the expression to calculate the number of iterations.
  7075. Expr *buildNumIterations(
  7076. Scope *S, ArrayRef<LoopIterationSpace> ResultIterSpaces, bool LimitedType,
  7077. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
  7078. /// Build the precondition expression for the loops.
  7079. Expr *
  7080. buildPreCond(Scope *S, Expr *Cond,
  7081. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
  7082. /// Build reference expression to the counter be used for codegen.
  7083. DeclRefExpr *
  7084. buildCounterVar(llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
  7085. DSAStackTy &DSA) const;
  7086. /// Build reference expression to the private counter be used for
  7087. /// codegen.
  7088. Expr *buildPrivateCounterVar() const;
  7089. /// Build initialization of the counter be used for codegen.
  7090. Expr *buildCounterInit() const;
  7091. /// Build step of the counter be used for codegen.
  7092. Expr *buildCounterStep() const;
  7093. /// Build loop data with counter value for depend clauses in ordered
  7094. /// directives.
  7095. Expr *
  7096. buildOrderedLoopData(Scope *S, Expr *Counter,
  7097. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
  7098. SourceLocation Loc, Expr *Inc = nullptr,
  7099. OverloadedOperatorKind OOK = OO_Amp);
  7100. /// Builds the minimum value for the loop counter.
  7101. std::pair<Expr *, Expr *> buildMinMaxValues(
  7102. Scope *S, llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
  7103. /// Builds final condition for the non-rectangular loops.
  7104. Expr *buildFinalCondition(Scope *S) const;
  7105. /// Return true if any expression is dependent.
  7106. bool dependent() const;
  7107. /// Returns true if the initializer forms non-rectangular loop.
  7108. bool doesInitDependOnLC() const { return InitDependOnLC.hasValue(); }
  7109. /// Returns true if the condition forms non-rectangular loop.
  7110. bool doesCondDependOnLC() const { return CondDependOnLC.hasValue(); }
  7111. /// Returns index of the loop we depend on (starting from 1), or 0 otherwise.
  7112. unsigned getLoopDependentIdx() const {
  7113. return InitDependOnLC.getValueOr(CondDependOnLC.getValueOr(0));
  7114. }
  7115. private:
  7116. /// Check the right-hand side of an assignment in the increment
  7117. /// expression.
  7118. bool checkAndSetIncRHS(Expr *RHS);
  7119. /// Helper to set loop counter variable and its initializer.
  7120. bool setLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB,
  7121. bool EmitDiags);
  7122. /// Helper to set upper bound.
  7123. bool setUB(Expr *NewUB, llvm::Optional<bool> LessOp, bool StrictOp,
  7124. SourceRange SR, SourceLocation SL);
  7125. /// Helper to set loop increment.
  7126. bool setStep(Expr *NewStep, bool Subtract);
  7127. };
  7128. bool OpenMPIterationSpaceChecker::dependent() const {
  7129. if (!LCDecl) {
  7130. assert(!LB && !UB && !Step);
  7131. return false;
  7132. }
  7133. return LCDecl->getType()->isDependentType() ||
  7134. (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
  7135. (Step && Step->isValueDependent());
  7136. }
  7137. bool OpenMPIterationSpaceChecker::setLCDeclAndLB(ValueDecl *NewLCDecl,
  7138. Expr *NewLCRefExpr,
  7139. Expr *NewLB, bool EmitDiags) {
  7140. // State consistency checking to ensure correct usage.
  7141. assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
  7142. UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
  7143. if (!NewLCDecl || !NewLB || NewLB->containsErrors())
  7144. return true;
  7145. LCDecl = getCanonicalDecl(NewLCDecl);
  7146. LCRef = NewLCRefExpr;
  7147. if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
  7148. if (const CXXConstructorDecl *Ctor = CE->getConstructor())
  7149. if ((Ctor->isCopyOrMoveConstructor() ||
  7150. Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
  7151. CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
  7152. NewLB = CE->getArg(0)->IgnoreParenImpCasts();
  7153. LB = NewLB;
  7154. if (EmitDiags)
  7155. InitDependOnLC = doesDependOnLoopCounter(LB, /*IsInitializer=*/true);
  7156. return false;
  7157. }
  7158. bool OpenMPIterationSpaceChecker::setUB(Expr *NewUB,
  7159. llvm::Optional<bool> LessOp,
  7160. bool StrictOp, SourceRange SR,
  7161. SourceLocation SL) {
  7162. // State consistency checking to ensure correct usage.
  7163. assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
  7164. Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
  7165. if (!NewUB || NewUB->containsErrors())
  7166. return true;
  7167. UB = NewUB;
  7168. if (LessOp)
  7169. TestIsLessOp = LessOp;
  7170. TestIsStrictOp = StrictOp;
  7171. ConditionSrcRange = SR;
  7172. ConditionLoc = SL;
  7173. CondDependOnLC = doesDependOnLoopCounter(UB, /*IsInitializer=*/false);
  7174. return false;
  7175. }
  7176. bool OpenMPIterationSpaceChecker::setStep(Expr *NewStep, bool Subtract) {
  7177. // State consistency checking to ensure correct usage.
  7178. assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
  7179. if (!NewStep || NewStep->containsErrors())
  7180. return true;
  7181. if (!NewStep->isValueDependent()) {
  7182. // Check that the step is integer expression.
  7183. SourceLocation StepLoc = NewStep->getBeginLoc();
  7184. ExprResult Val = SemaRef.PerformOpenMPImplicitIntegerConversion(
  7185. StepLoc, getExprAsWritten(NewStep));
  7186. if (Val.isInvalid())
  7187. return true;
  7188. NewStep = Val.get();
  7189. // OpenMP [2.6, Canonical Loop Form, Restrictions]
  7190. // If test-expr is of form var relational-op b and relational-op is < or
  7191. // <= then incr-expr must cause var to increase on each iteration of the
  7192. // loop. If test-expr is of form var relational-op b and relational-op is
  7193. // > or >= then incr-expr must cause var to decrease on each iteration of
  7194. // the loop.
  7195. // If test-expr is of form b relational-op var and relational-op is < or
  7196. // <= then incr-expr must cause var to decrease on each iteration of the
  7197. // loop. If test-expr is of form b relational-op var and relational-op is
  7198. // > or >= then incr-expr must cause var to increase on each iteration of
  7199. // the loop.
  7200. Optional<llvm::APSInt> Result =
  7201. NewStep->getIntegerConstantExpr(SemaRef.Context);
  7202. bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
  7203. bool IsConstNeg =
  7204. Result && Result->isSigned() && (Subtract != Result->isNegative());
  7205. bool IsConstPos =
  7206. Result && Result->isSigned() && (Subtract == Result->isNegative());
  7207. bool IsConstZero = Result && !Result->getBoolValue();
  7208. // != with increment is treated as <; != with decrement is treated as >
  7209. if (!TestIsLessOp.hasValue())
  7210. TestIsLessOp = IsConstPos || (IsUnsigned && !Subtract);
  7211. if (UB &&
  7212. (IsConstZero || (TestIsLessOp.getValue()
  7213. ? (IsConstNeg || (IsUnsigned && Subtract))
  7214. : (IsConstPos || (IsUnsigned && !Subtract))))) {
  7215. SemaRef.Diag(NewStep->getExprLoc(),
  7216. diag::err_omp_loop_incr_not_compatible)
  7217. << LCDecl << TestIsLessOp.getValue() << NewStep->getSourceRange();
  7218. SemaRef.Diag(ConditionLoc,
  7219. diag::note_omp_loop_cond_requres_compatible_incr)
  7220. << TestIsLessOp.getValue() << ConditionSrcRange;
  7221. return true;
  7222. }
  7223. if (TestIsLessOp.getValue() == Subtract) {
  7224. NewStep =
  7225. SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
  7226. .get();
  7227. Subtract = !Subtract;
  7228. }
  7229. }
  7230. Step = NewStep;
  7231. SubtractStep = Subtract;
  7232. return false;
  7233. }
  7234. namespace {
  7235. /// Checker for the non-rectangular loops. Checks if the initializer or
  7236. /// condition expression references loop counter variable.
  7237. class LoopCounterRefChecker final
  7238. : public ConstStmtVisitor<LoopCounterRefChecker, bool> {
  7239. Sema &SemaRef;
  7240. DSAStackTy &Stack;
  7241. const ValueDecl *CurLCDecl = nullptr;
  7242. const ValueDecl *DepDecl = nullptr;
  7243. const ValueDecl *PrevDepDecl = nullptr;
  7244. bool IsInitializer = true;
  7245. bool SupportsNonRectangular;
  7246. unsigned BaseLoopId = 0;
  7247. bool checkDecl(const Expr *E, const ValueDecl *VD) {
  7248. if (getCanonicalDecl(VD) == getCanonicalDecl(CurLCDecl)) {
  7249. SemaRef.Diag(E->getExprLoc(), diag::err_omp_stmt_depends_on_loop_counter)
  7250. << (IsInitializer ? 0 : 1);
  7251. return false;
  7252. }
  7253. const auto &&Data = Stack.isLoopControlVariable(VD);
  7254. // OpenMP, 2.9.1 Canonical Loop Form, Restrictions.
  7255. // The type of the loop iterator on which we depend may not have a random
  7256. // access iterator type.
  7257. if (Data.first && VD->getType()->isRecordType()) {
  7258. SmallString<128> Name;
  7259. llvm::raw_svector_ostream OS(Name);
  7260. VD->getNameForDiagnostic(OS, SemaRef.getPrintingPolicy(),
  7261. /*Qualified=*/true);
  7262. SemaRef.Diag(E->getExprLoc(),
  7263. diag::err_omp_wrong_dependency_iterator_type)
  7264. << OS.str();
  7265. SemaRef.Diag(VD->getLocation(), diag::note_previous_decl) << VD;
  7266. return false;
  7267. }
  7268. if (Data.first && !SupportsNonRectangular) {
  7269. SemaRef.Diag(E->getExprLoc(), diag::err_omp_invariant_dependency);
  7270. return false;
  7271. }
  7272. if (Data.first &&
  7273. (DepDecl || (PrevDepDecl &&
  7274. getCanonicalDecl(VD) != getCanonicalDecl(PrevDepDecl)))) {
  7275. if (!DepDecl && PrevDepDecl)
  7276. DepDecl = PrevDepDecl;
  7277. SmallString<128> Name;
  7278. llvm::raw_svector_ostream OS(Name);
  7279. DepDecl->getNameForDiagnostic(OS, SemaRef.getPrintingPolicy(),
  7280. /*Qualified=*/true);
  7281. SemaRef.Diag(E->getExprLoc(),
  7282. diag::err_omp_invariant_or_linear_dependency)
  7283. << OS.str();
  7284. return false;
  7285. }
  7286. if (Data.first) {
  7287. DepDecl = VD;
  7288. BaseLoopId = Data.first;
  7289. }
  7290. return Data.first;
  7291. }
  7292. public:
  7293. bool VisitDeclRefExpr(const DeclRefExpr *E) {
  7294. const ValueDecl *VD = E->getDecl();
  7295. if (isa<VarDecl>(VD))
  7296. return checkDecl(E, VD);
  7297. return false;
  7298. }
  7299. bool VisitMemberExpr(const MemberExpr *E) {
  7300. if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) {
  7301. const ValueDecl *VD = E->getMemberDecl();
  7302. if (isa<VarDecl>(VD) || isa<FieldDecl>(VD))
  7303. return checkDecl(E, VD);
  7304. }
  7305. return false;
  7306. }
  7307. bool VisitStmt(const Stmt *S) {
  7308. bool Res = false;
  7309. for (const Stmt *Child : S->children())
  7310. Res = (Child && Visit(Child)) || Res;
  7311. return Res;
  7312. }
  7313. explicit LoopCounterRefChecker(Sema &SemaRef, DSAStackTy &Stack,
  7314. const ValueDecl *CurLCDecl, bool IsInitializer,
  7315. const ValueDecl *PrevDepDecl = nullptr,
  7316. bool SupportsNonRectangular = true)
  7317. : SemaRef(SemaRef), Stack(Stack), CurLCDecl(CurLCDecl),
  7318. PrevDepDecl(PrevDepDecl), IsInitializer(IsInitializer),
  7319. SupportsNonRectangular(SupportsNonRectangular) {}
  7320. unsigned getBaseLoopId() const {
  7321. assert(CurLCDecl && "Expected loop dependency.");
  7322. return BaseLoopId;
  7323. }
  7324. const ValueDecl *getDepDecl() const {
  7325. assert(CurLCDecl && "Expected loop dependency.");
  7326. return DepDecl;
  7327. }
  7328. };
  7329. } // namespace
  7330. Optional<unsigned>
  7331. OpenMPIterationSpaceChecker::doesDependOnLoopCounter(const Stmt *S,
  7332. bool IsInitializer) {
  7333. // Check for the non-rectangular loops.
  7334. LoopCounterRefChecker LoopStmtChecker(SemaRef, Stack, LCDecl, IsInitializer,
  7335. DepDecl, SupportsNonRectangular);
  7336. if (LoopStmtChecker.Visit(S)) {
  7337. DepDecl = LoopStmtChecker.getDepDecl();
  7338. return LoopStmtChecker.getBaseLoopId();
  7339. }
  7340. return llvm::None;
  7341. }
  7342. bool OpenMPIterationSpaceChecker::checkAndSetInit(Stmt *S, bool EmitDiags) {
  7343. // Check init-expr for canonical loop form and save loop counter
  7344. // variable - #Var and its initialization value - #LB.
  7345. // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
  7346. // var = lb
  7347. // integer-type var = lb
  7348. // random-access-iterator-type var = lb
  7349. // pointer-type var = lb
  7350. //
  7351. if (!S) {
  7352. if (EmitDiags) {
  7353. SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
  7354. }
  7355. return true;
  7356. }
  7357. if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
  7358. if (!ExprTemp->cleanupsHaveSideEffects())
  7359. S = ExprTemp->getSubExpr();
  7360. InitSrcRange = S->getSourceRange();
  7361. if (Expr *E = dyn_cast<Expr>(S))
  7362. S = E->IgnoreParens();
  7363. if (auto *BO = dyn_cast<BinaryOperator>(S)) {
  7364. if (BO->getOpcode() == BO_Assign) {
  7365. Expr *LHS = BO->getLHS()->IgnoreParens();
  7366. if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
  7367. if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
  7368. if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
  7369. return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
  7370. EmitDiags);
  7371. return setLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS(), EmitDiags);
  7372. }
  7373. if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
  7374. if (ME->isArrow() &&
  7375. isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
  7376. return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
  7377. EmitDiags);
  7378. }
  7379. }
  7380. } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
  7381. if (DS->isSingleDecl()) {
  7382. if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
  7383. if (Var->hasInit() && !Var->getType()->isReferenceType()) {
  7384. // Accept non-canonical init form here but emit ext. warning.
  7385. if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
  7386. SemaRef.Diag(S->getBeginLoc(),
  7387. diag::ext_omp_loop_not_canonical_init)
  7388. << S->getSourceRange();
  7389. return setLCDeclAndLB(
  7390. Var,
  7391. buildDeclRefExpr(SemaRef, Var,
  7392. Var->getType().getNonReferenceType(),
  7393. DS->getBeginLoc()),
  7394. Var->getInit(), EmitDiags);
  7395. }
  7396. }
  7397. }
  7398. } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
  7399. if (CE->getOperator() == OO_Equal) {
  7400. Expr *LHS = CE->getArg(0);
  7401. if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
  7402. if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
  7403. if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
  7404. return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
  7405. EmitDiags);
  7406. return setLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1), EmitDiags);
  7407. }
  7408. if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
  7409. if (ME->isArrow() &&
  7410. isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
  7411. return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
  7412. EmitDiags);
  7413. }
  7414. }
  7415. }
  7416. if (dependent() || SemaRef.CurContext->isDependentContext())
  7417. return false;
  7418. if (EmitDiags) {
  7419. SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_init)
  7420. << S->getSourceRange();
  7421. }
  7422. return true;
  7423. }
  7424. /// Ignore parenthesizes, implicit casts, copy constructor and return the
  7425. /// variable (which may be the loop variable) if possible.
  7426. static const ValueDecl *getInitLCDecl(const Expr *E) {
  7427. if (!E)
  7428. return nullptr;
  7429. E = getExprAsWritten(E);
  7430. if (const auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
  7431. if (const CXXConstructorDecl *Ctor = CE->getConstructor())
  7432. if ((Ctor->isCopyOrMoveConstructor() ||
  7433. Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
  7434. CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
  7435. E = CE->getArg(0)->IgnoreParenImpCasts();
  7436. if (const auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
  7437. if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
  7438. return getCanonicalDecl(VD);
  7439. }
  7440. if (const auto *ME = dyn_cast_or_null<MemberExpr>(E))
  7441. if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
  7442. return getCanonicalDecl(ME->getMemberDecl());
  7443. return nullptr;
  7444. }
  7445. bool OpenMPIterationSpaceChecker::checkAndSetCond(Expr *S) {
  7446. // Check test-expr for canonical form, save upper-bound UB, flags for
  7447. // less/greater and for strict/non-strict comparison.
  7448. // OpenMP [2.9] Canonical loop form. Test-expr may be one of the following:
  7449. // var relational-op b
  7450. // b relational-op var
  7451. //
  7452. bool IneqCondIsCanonical = SemaRef.getLangOpts().OpenMP >= 50;
  7453. if (!S) {
  7454. SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond)
  7455. << (IneqCondIsCanonical ? 1 : 0) << LCDecl;
  7456. return true;
  7457. }
  7458. Condition = S;
  7459. S = getExprAsWritten(S);
  7460. SourceLocation CondLoc = S->getBeginLoc();
  7461. auto &&CheckAndSetCond = [this, IneqCondIsCanonical](
  7462. BinaryOperatorKind Opcode, const Expr *LHS,
  7463. const Expr *RHS, SourceRange SR,
  7464. SourceLocation OpLoc) -> llvm::Optional<bool> {
  7465. if (BinaryOperator::isRelationalOp(Opcode)) {
  7466. if (getInitLCDecl(LHS) == LCDecl)
  7467. return setUB(const_cast<Expr *>(RHS),
  7468. (Opcode == BO_LT || Opcode == BO_LE),
  7469. (Opcode == BO_LT || Opcode == BO_GT), SR, OpLoc);
  7470. if (getInitLCDecl(RHS) == LCDecl)
  7471. return setUB(const_cast<Expr *>(LHS),
  7472. (Opcode == BO_GT || Opcode == BO_GE),
  7473. (Opcode == BO_LT || Opcode == BO_GT), SR, OpLoc);
  7474. } else if (IneqCondIsCanonical && Opcode == BO_NE) {
  7475. return setUB(const_cast<Expr *>(getInitLCDecl(LHS) == LCDecl ? RHS : LHS),
  7476. /*LessOp=*/llvm::None,
  7477. /*StrictOp=*/true, SR, OpLoc);
  7478. }
  7479. return llvm::None;
  7480. };
  7481. llvm::Optional<bool> Res;
  7482. if (auto *RBO = dyn_cast<CXXRewrittenBinaryOperator>(S)) {
  7483. CXXRewrittenBinaryOperator::DecomposedForm DF = RBO->getDecomposedForm();
  7484. Res = CheckAndSetCond(DF.Opcode, DF.LHS, DF.RHS, RBO->getSourceRange(),
  7485. RBO->getOperatorLoc());
  7486. } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
  7487. Res = CheckAndSetCond(BO->getOpcode(), BO->getLHS(), BO->getRHS(),
  7488. BO->getSourceRange(), BO->getOperatorLoc());
  7489. } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
  7490. if (CE->getNumArgs() == 2) {
  7491. Res = CheckAndSetCond(
  7492. BinaryOperator::getOverloadedOpcode(CE->getOperator()), CE->getArg(0),
  7493. CE->getArg(1), CE->getSourceRange(), CE->getOperatorLoc());
  7494. }
  7495. }
  7496. if (Res.hasValue())
  7497. return *Res;
  7498. if (dependent() || SemaRef.CurContext->isDependentContext())
  7499. return false;
  7500. SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
  7501. << (IneqCondIsCanonical ? 1 : 0) << S->getSourceRange() << LCDecl;
  7502. return true;
  7503. }
  7504. bool OpenMPIterationSpaceChecker::checkAndSetIncRHS(Expr *RHS) {
  7505. // RHS of canonical loop form increment can be:
  7506. // var + incr
  7507. // incr + var
  7508. // var - incr
  7509. //
  7510. RHS = RHS->IgnoreParenImpCasts();
  7511. if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
  7512. if (BO->isAdditiveOp()) {
  7513. bool IsAdd = BO->getOpcode() == BO_Add;
  7514. if (getInitLCDecl(BO->getLHS()) == LCDecl)
  7515. return setStep(BO->getRHS(), !IsAdd);
  7516. if (IsAdd && getInitLCDecl(BO->getRHS()) == LCDecl)
  7517. return setStep(BO->getLHS(), /*Subtract=*/false);
  7518. }
  7519. } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
  7520. bool IsAdd = CE->getOperator() == OO_Plus;
  7521. if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
  7522. if (getInitLCDecl(CE->getArg(0)) == LCDecl)
  7523. return setStep(CE->getArg(1), !IsAdd);
  7524. if (IsAdd && getInitLCDecl(CE->getArg(1)) == LCDecl)
  7525. return setStep(CE->getArg(0), /*Subtract=*/false);
  7526. }
  7527. }
  7528. if (dependent() || SemaRef.CurContext->isDependentContext())
  7529. return false;
  7530. SemaRef.Diag(RHS->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
  7531. << RHS->getSourceRange() << LCDecl;
  7532. return true;
  7533. }
  7534. bool OpenMPIterationSpaceChecker::checkAndSetInc(Expr *S) {
  7535. // Check incr-expr for canonical loop form and return true if it
  7536. // does not conform.
  7537. // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
  7538. // ++var
  7539. // var++
  7540. // --var
  7541. // var--
  7542. // var += incr
  7543. // var -= incr
  7544. // var = var + incr
  7545. // var = incr + var
  7546. // var = var - incr
  7547. //
  7548. if (!S) {
  7549. SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
  7550. return true;
  7551. }
  7552. if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
  7553. if (!ExprTemp->cleanupsHaveSideEffects())
  7554. S = ExprTemp->getSubExpr();
  7555. IncrementSrcRange = S->getSourceRange();
  7556. S = S->IgnoreParens();
  7557. if (auto *UO = dyn_cast<UnaryOperator>(S)) {
  7558. if (UO->isIncrementDecrementOp() &&
  7559. getInitLCDecl(UO->getSubExpr()) == LCDecl)
  7560. return setStep(SemaRef
  7561. .ActOnIntegerConstant(UO->getBeginLoc(),
  7562. (UO->isDecrementOp() ? -1 : 1))
  7563. .get(),
  7564. /*Subtract=*/false);
  7565. } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
  7566. switch (BO->getOpcode()) {
  7567. case BO_AddAssign:
  7568. case BO_SubAssign:
  7569. if (getInitLCDecl(BO->getLHS()) == LCDecl)
  7570. return setStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
  7571. break;
  7572. case BO_Assign:
  7573. if (getInitLCDecl(BO->getLHS()) == LCDecl)
  7574. return checkAndSetIncRHS(BO->getRHS());
  7575. break;
  7576. default:
  7577. break;
  7578. }
  7579. } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
  7580. switch (CE->getOperator()) {
  7581. case OO_PlusPlus:
  7582. case OO_MinusMinus:
  7583. if (getInitLCDecl(CE->getArg(0)) == LCDecl)
  7584. return setStep(SemaRef
  7585. .ActOnIntegerConstant(
  7586. CE->getBeginLoc(),
  7587. ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
  7588. .get(),
  7589. /*Subtract=*/false);
  7590. break;
  7591. case OO_PlusEqual:
  7592. case OO_MinusEqual:
  7593. if (getInitLCDecl(CE->getArg(0)) == LCDecl)
  7594. return setStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
  7595. break;
  7596. case OO_Equal:
  7597. if (getInitLCDecl(CE->getArg(0)) == LCDecl)
  7598. return checkAndSetIncRHS(CE->getArg(1));
  7599. break;
  7600. default:
  7601. break;
  7602. }
  7603. }
  7604. if (dependent() || SemaRef.CurContext->isDependentContext())
  7605. return false;
  7606. SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
  7607. << S->getSourceRange() << LCDecl;
  7608. return true;
  7609. }
  7610. static ExprResult
  7611. tryBuildCapture(Sema &SemaRef, Expr *Capture,
  7612. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
  7613. if (SemaRef.CurContext->isDependentContext() || Capture->containsErrors())
  7614. return Capture;
  7615. if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
  7616. return SemaRef.PerformImplicitConversion(
  7617. Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
  7618. /*AllowExplicit=*/true);
  7619. auto I = Captures.find(Capture);
  7620. if (I != Captures.end())
  7621. return buildCapture(SemaRef, Capture, I->second);
  7622. DeclRefExpr *Ref = nullptr;
  7623. ExprResult Res = buildCapture(SemaRef, Capture, Ref);
  7624. Captures[Capture] = Ref;
  7625. return Res;
  7626. }
  7627. /// Calculate number of iterations, transforming to unsigned, if number of
  7628. /// iterations may be larger than the original type.
  7629. static Expr *
  7630. calculateNumIters(Sema &SemaRef, Scope *S, SourceLocation DefaultLoc,
  7631. Expr *Lower, Expr *Upper, Expr *Step, QualType LCTy,
  7632. bool TestIsStrictOp, bool RoundToStep,
  7633. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
  7634. ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
  7635. if (!NewStep.isUsable())
  7636. return nullptr;
  7637. llvm::APSInt LRes, SRes;
  7638. bool IsLowerConst = false, IsStepConst = false;
  7639. if (Optional<llvm::APSInt> Res =
  7640. Lower->getIntegerConstantExpr(SemaRef.Context)) {
  7641. LRes = *Res;
  7642. IsLowerConst = true;
  7643. }
  7644. if (Optional<llvm::APSInt> Res =
  7645. Step->getIntegerConstantExpr(SemaRef.Context)) {
  7646. SRes = *Res;
  7647. IsStepConst = true;
  7648. }
  7649. bool NoNeedToConvert = IsLowerConst && !RoundToStep &&
  7650. ((!TestIsStrictOp && LRes.isNonNegative()) ||
  7651. (TestIsStrictOp && LRes.isStrictlyPositive()));
  7652. bool NeedToReorganize = false;
  7653. // Check if any subexpressions in Lower -Step [+ 1] lead to overflow.
  7654. if (!NoNeedToConvert && IsLowerConst &&
  7655. (TestIsStrictOp || (RoundToStep && IsStepConst))) {
  7656. NoNeedToConvert = true;
  7657. if (RoundToStep) {
  7658. unsigned BW = LRes.getBitWidth() > SRes.getBitWidth()
  7659. ? LRes.getBitWidth()
  7660. : SRes.getBitWidth();
  7661. LRes = LRes.extend(BW + 1);
  7662. LRes.setIsSigned(true);
  7663. SRes = SRes.extend(BW + 1);
  7664. SRes.setIsSigned(true);
  7665. LRes -= SRes;
  7666. NoNeedToConvert = LRes.trunc(BW).extend(BW + 1) == LRes;
  7667. LRes = LRes.trunc(BW);
  7668. }
  7669. if (TestIsStrictOp) {
  7670. unsigned BW = LRes.getBitWidth();
  7671. LRes = LRes.extend(BW + 1);
  7672. LRes.setIsSigned(true);
  7673. ++LRes;
  7674. NoNeedToConvert =
  7675. NoNeedToConvert && LRes.trunc(BW).extend(BW + 1) == LRes;
  7676. // truncate to the original bitwidth.
  7677. LRes = LRes.trunc(BW);
  7678. }
  7679. NeedToReorganize = NoNeedToConvert;
  7680. }
  7681. llvm::APSInt URes;
  7682. bool IsUpperConst = false;
  7683. if (Optional<llvm::APSInt> Res =
  7684. Upper->getIntegerConstantExpr(SemaRef.Context)) {
  7685. URes = *Res;
  7686. IsUpperConst = true;
  7687. }
  7688. if (NoNeedToConvert && IsLowerConst && IsUpperConst &&
  7689. (!RoundToStep || IsStepConst)) {
  7690. unsigned BW = LRes.getBitWidth() > URes.getBitWidth() ? LRes.getBitWidth()
  7691. : URes.getBitWidth();
  7692. LRes = LRes.extend(BW + 1);
  7693. LRes.setIsSigned(true);
  7694. URes = URes.extend(BW + 1);
  7695. URes.setIsSigned(true);
  7696. URes -= LRes;
  7697. NoNeedToConvert = URes.trunc(BW).extend(BW + 1) == URes;
  7698. NeedToReorganize = NoNeedToConvert;
  7699. }
  7700. // If the boundaries are not constant or (Lower - Step [+ 1]) is not constant
  7701. // or less than zero (Upper - (Lower - Step [+ 1]) may overflow) - promote to
  7702. // unsigned.
  7703. if ((!NoNeedToConvert || (LRes.isNegative() && !IsUpperConst)) &&
  7704. !LCTy->isDependentType() && LCTy->isIntegerType()) {
  7705. QualType LowerTy = Lower->getType();
  7706. QualType UpperTy = Upper->getType();
  7707. uint64_t LowerSize = SemaRef.Context.getTypeSize(LowerTy);
  7708. uint64_t UpperSize = SemaRef.Context.getTypeSize(UpperTy);
  7709. if ((LowerSize <= UpperSize && UpperTy->hasSignedIntegerRepresentation()) ||
  7710. (LowerSize > UpperSize && LowerTy->hasSignedIntegerRepresentation())) {
  7711. QualType CastType = SemaRef.Context.getIntTypeForBitwidth(
  7712. LowerSize > UpperSize ? LowerSize : UpperSize, /*Signed=*/0);
  7713. Upper =
  7714. SemaRef
  7715. .PerformImplicitConversion(
  7716. SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Upper).get(),
  7717. CastType, Sema::AA_Converting)
  7718. .get();
  7719. Lower = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Lower).get();
  7720. NewStep = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, NewStep.get());
  7721. }
  7722. }
  7723. if (!Lower || !Upper || NewStep.isInvalid())
  7724. return nullptr;
  7725. ExprResult Diff;
  7726. // If need to reorganize, then calculate the form as Upper - (Lower - Step [+
  7727. // 1]).
  7728. if (NeedToReorganize) {
  7729. Diff = Lower;
  7730. if (RoundToStep) {
  7731. // Lower - Step
  7732. Diff =
  7733. SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Diff.get(), NewStep.get());
  7734. if (!Diff.isUsable())
  7735. return nullptr;
  7736. }
  7737. // Lower - Step [+ 1]
  7738. if (TestIsStrictOp)
  7739. Diff = SemaRef.BuildBinOp(
  7740. S, DefaultLoc, BO_Add, Diff.get(),
  7741. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
  7742. if (!Diff.isUsable())
  7743. return nullptr;
  7744. Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
  7745. if (!Diff.isUsable())
  7746. return nullptr;
  7747. // Upper - (Lower - Step [+ 1]).
  7748. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Diff.get());
  7749. if (!Diff.isUsable())
  7750. return nullptr;
  7751. } else {
  7752. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
  7753. if (!Diff.isUsable() && LCTy->getAsCXXRecordDecl()) {
  7754. // BuildBinOp already emitted error, this one is to point user to upper
  7755. // and lower bound, and to tell what is passed to 'operator-'.
  7756. SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx)
  7757. << Upper->getSourceRange() << Lower->getSourceRange();
  7758. return nullptr;
  7759. }
  7760. if (!Diff.isUsable())
  7761. return nullptr;
  7762. // Upper - Lower [- 1]
  7763. if (TestIsStrictOp)
  7764. Diff = SemaRef.BuildBinOp(
  7765. S, DefaultLoc, BO_Sub, Diff.get(),
  7766. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
  7767. if (!Diff.isUsable())
  7768. return nullptr;
  7769. if (RoundToStep) {
  7770. // Upper - Lower [- 1] + Step
  7771. Diff =
  7772. SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
  7773. if (!Diff.isUsable())
  7774. return nullptr;
  7775. }
  7776. }
  7777. // Parentheses (for dumping/debugging purposes only).
  7778. Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
  7779. if (!Diff.isUsable())
  7780. return nullptr;
  7781. // (Upper - Lower [- 1] + Step) / Step or (Upper - Lower) / Step
  7782. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
  7783. if (!Diff.isUsable())
  7784. return nullptr;
  7785. return Diff.get();
  7786. }
  7787. /// Build the expression to calculate the number of iterations.
  7788. Expr *OpenMPIterationSpaceChecker::buildNumIterations(
  7789. Scope *S, ArrayRef<LoopIterationSpace> ResultIterSpaces, bool LimitedType,
  7790. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
  7791. QualType VarType = LCDecl->getType().getNonReferenceType();
  7792. if (!VarType->isIntegerType() && !VarType->isPointerType() &&
  7793. !SemaRef.getLangOpts().CPlusPlus)
  7794. return nullptr;
  7795. Expr *LBVal = LB;
  7796. Expr *UBVal = UB;
  7797. // LB = TestIsLessOp.getValue() ? min(LB(MinVal), LB(MaxVal)) :
  7798. // max(LB(MinVal), LB(MaxVal))
  7799. if (InitDependOnLC) {
  7800. const LoopIterationSpace &IS = ResultIterSpaces[*InitDependOnLC - 1];
  7801. if (!IS.MinValue || !IS.MaxValue)
  7802. return nullptr;
  7803. // OuterVar = Min
  7804. ExprResult MinValue =
  7805. SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MinValue);
  7806. if (!MinValue.isUsable())
  7807. return nullptr;
  7808. ExprResult LBMinVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
  7809. IS.CounterVar, MinValue.get());
  7810. if (!LBMinVal.isUsable())
  7811. return nullptr;
  7812. // OuterVar = Min, LBVal
  7813. LBMinVal =
  7814. SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, LBMinVal.get(), LBVal);
  7815. if (!LBMinVal.isUsable())
  7816. return nullptr;
  7817. // (OuterVar = Min, LBVal)
  7818. LBMinVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, LBMinVal.get());
  7819. if (!LBMinVal.isUsable())
  7820. return nullptr;
  7821. // OuterVar = Max
  7822. ExprResult MaxValue =
  7823. SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MaxValue);
  7824. if (!MaxValue.isUsable())
  7825. return nullptr;
  7826. ExprResult LBMaxVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
  7827. IS.CounterVar, MaxValue.get());
  7828. if (!LBMaxVal.isUsable())
  7829. return nullptr;
  7830. // OuterVar = Max, LBVal
  7831. LBMaxVal =
  7832. SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, LBMaxVal.get(), LBVal);
  7833. if (!LBMaxVal.isUsable())
  7834. return nullptr;
  7835. // (OuterVar = Max, LBVal)
  7836. LBMaxVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, LBMaxVal.get());
  7837. if (!LBMaxVal.isUsable())
  7838. return nullptr;
  7839. Expr *LBMin = tryBuildCapture(SemaRef, LBMinVal.get(), Captures).get();
  7840. Expr *LBMax = tryBuildCapture(SemaRef, LBMaxVal.get(), Captures).get();
  7841. if (!LBMin || !LBMax)
  7842. return nullptr;
  7843. // LB(MinVal) < LB(MaxVal)
  7844. ExprResult MinLessMaxRes =
  7845. SemaRef.BuildBinOp(S, DefaultLoc, BO_LT, LBMin, LBMax);
  7846. if (!MinLessMaxRes.isUsable())
  7847. return nullptr;
  7848. Expr *MinLessMax =
  7849. tryBuildCapture(SemaRef, MinLessMaxRes.get(), Captures).get();
  7850. if (!MinLessMax)
  7851. return nullptr;
  7852. if (TestIsLessOp.getValue()) {
  7853. // LB(MinVal) < LB(MaxVal) ? LB(MinVal) : LB(MaxVal) - min(LB(MinVal),
  7854. // LB(MaxVal))
  7855. ExprResult MinLB = SemaRef.ActOnConditionalOp(DefaultLoc, DefaultLoc,
  7856. MinLessMax, LBMin, LBMax);
  7857. if (!MinLB.isUsable())
  7858. return nullptr;
  7859. LBVal = MinLB.get();
  7860. } else {
  7861. // LB(MinVal) < LB(MaxVal) ? LB(MaxVal) : LB(MinVal) - max(LB(MinVal),
  7862. // LB(MaxVal))
  7863. ExprResult MaxLB = SemaRef.ActOnConditionalOp(DefaultLoc, DefaultLoc,
  7864. MinLessMax, LBMax, LBMin);
  7865. if (!MaxLB.isUsable())
  7866. return nullptr;
  7867. LBVal = MaxLB.get();
  7868. }
  7869. }
  7870. // UB = TestIsLessOp.getValue() ? max(UB(MinVal), UB(MaxVal)) :
  7871. // min(UB(MinVal), UB(MaxVal))
  7872. if (CondDependOnLC) {
  7873. const LoopIterationSpace &IS = ResultIterSpaces[*CondDependOnLC - 1];
  7874. if (!IS.MinValue || !IS.MaxValue)
  7875. return nullptr;
  7876. // OuterVar = Min
  7877. ExprResult MinValue =
  7878. SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MinValue);
  7879. if (!MinValue.isUsable())
  7880. return nullptr;
  7881. ExprResult UBMinVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
  7882. IS.CounterVar, MinValue.get());
  7883. if (!UBMinVal.isUsable())
  7884. return nullptr;
  7885. // OuterVar = Min, UBVal
  7886. UBMinVal =
  7887. SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, UBMinVal.get(), UBVal);
  7888. if (!UBMinVal.isUsable())
  7889. return nullptr;
  7890. // (OuterVar = Min, UBVal)
  7891. UBMinVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, UBMinVal.get());
  7892. if (!UBMinVal.isUsable())
  7893. return nullptr;
  7894. // OuterVar = Max
  7895. ExprResult MaxValue =
  7896. SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MaxValue);
  7897. if (!MaxValue.isUsable())
  7898. return nullptr;
  7899. ExprResult UBMaxVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
  7900. IS.CounterVar, MaxValue.get());
  7901. if (!UBMaxVal.isUsable())
  7902. return nullptr;
  7903. // OuterVar = Max, UBVal
  7904. UBMaxVal =
  7905. SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, UBMaxVal.get(), UBVal);
  7906. if (!UBMaxVal.isUsable())
  7907. return nullptr;
  7908. // (OuterVar = Max, UBVal)
  7909. UBMaxVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, UBMaxVal.get());
  7910. if (!UBMaxVal.isUsable())
  7911. return nullptr;
  7912. Expr *UBMin = tryBuildCapture(SemaRef, UBMinVal.get(), Captures).get();
  7913. Expr *UBMax = tryBuildCapture(SemaRef, UBMaxVal.get(), Captures).get();
  7914. if (!UBMin || !UBMax)
  7915. return nullptr;
  7916. // UB(MinVal) > UB(MaxVal)
  7917. ExprResult MinGreaterMaxRes =
  7918. SemaRef.BuildBinOp(S, DefaultLoc, BO_GT, UBMin, UBMax);
  7919. if (!MinGreaterMaxRes.isUsable())
  7920. return nullptr;
  7921. Expr *MinGreaterMax =
  7922. tryBuildCapture(SemaRef, MinGreaterMaxRes.get(), Captures).get();
  7923. if (!MinGreaterMax)
  7924. return nullptr;
  7925. if (TestIsLessOp.getValue()) {
  7926. // UB(MinVal) > UB(MaxVal) ? UB(MinVal) : UB(MaxVal) - max(UB(MinVal),
  7927. // UB(MaxVal))
  7928. ExprResult MaxUB = SemaRef.ActOnConditionalOp(
  7929. DefaultLoc, DefaultLoc, MinGreaterMax, UBMin, UBMax);
  7930. if (!MaxUB.isUsable())
  7931. return nullptr;
  7932. UBVal = MaxUB.get();
  7933. } else {
  7934. // UB(MinVal) > UB(MaxVal) ? UB(MaxVal) : UB(MinVal) - min(UB(MinVal),
  7935. // UB(MaxVal))
  7936. ExprResult MinUB = SemaRef.ActOnConditionalOp(
  7937. DefaultLoc, DefaultLoc, MinGreaterMax, UBMax, UBMin);
  7938. if (!MinUB.isUsable())
  7939. return nullptr;
  7940. UBVal = MinUB.get();
  7941. }
  7942. }
  7943. Expr *UBExpr = TestIsLessOp.getValue() ? UBVal : LBVal;
  7944. Expr *LBExpr = TestIsLessOp.getValue() ? LBVal : UBVal;
  7945. Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
  7946. Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
  7947. if (!Upper || !Lower)
  7948. return nullptr;
  7949. ExprResult Diff = calculateNumIters(SemaRef, S, DefaultLoc, Lower, Upper,
  7950. Step, VarType, TestIsStrictOp,
  7951. /*RoundToStep=*/true, Captures);
  7952. if (!Diff.isUsable())
  7953. return nullptr;
  7954. // OpenMP runtime requires 32-bit or 64-bit loop variables.
  7955. QualType Type = Diff.get()->getType();
  7956. ASTContext &C = SemaRef.Context;
  7957. bool UseVarType = VarType->hasIntegerRepresentation() &&
  7958. C.getTypeSize(Type) > C.getTypeSize(VarType);
  7959. if (!Type->isIntegerType() || UseVarType) {
  7960. unsigned NewSize =
  7961. UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
  7962. bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
  7963. : Type->hasSignedIntegerRepresentation();
  7964. Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
  7965. if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
  7966. Diff = SemaRef.PerformImplicitConversion(
  7967. Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
  7968. if (!Diff.isUsable())
  7969. return nullptr;
  7970. }
  7971. }
  7972. if (LimitedType) {
  7973. unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
  7974. if (NewSize != C.getTypeSize(Type)) {
  7975. if (NewSize < C.getTypeSize(Type)) {
  7976. assert(NewSize == 64 && "incorrect loop var size");
  7977. SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
  7978. << InitSrcRange << ConditionSrcRange;
  7979. }
  7980. QualType NewType = C.getIntTypeForBitwidth(
  7981. NewSize, Type->hasSignedIntegerRepresentation() ||
  7982. C.getTypeSize(Type) < NewSize);
  7983. if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
  7984. Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
  7985. Sema::AA_Converting, true);
  7986. if (!Diff.isUsable())
  7987. return nullptr;
  7988. }
  7989. }
  7990. }
  7991. return Diff.get();
  7992. }
  7993. std::pair<Expr *, Expr *> OpenMPIterationSpaceChecker::buildMinMaxValues(
  7994. Scope *S, llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
  7995. // Do not build for iterators, they cannot be used in non-rectangular loop
  7996. // nests.
  7997. if (LCDecl->getType()->isRecordType())
  7998. return std::make_pair(nullptr, nullptr);
  7999. // If we subtract, the min is in the condition, otherwise the min is in the
  8000. // init value.
  8001. Expr *MinExpr = nullptr;
  8002. Expr *MaxExpr = nullptr;
  8003. Expr *LBExpr = TestIsLessOp.getValue() ? LB : UB;
  8004. Expr *UBExpr = TestIsLessOp.getValue() ? UB : LB;
  8005. bool LBNonRect = TestIsLessOp.getValue() ? InitDependOnLC.hasValue()
  8006. : CondDependOnLC.hasValue();
  8007. bool UBNonRect = TestIsLessOp.getValue() ? CondDependOnLC.hasValue()
  8008. : InitDependOnLC.hasValue();
  8009. Expr *Lower =
  8010. LBNonRect ? LBExpr : tryBuildCapture(SemaRef, LBExpr, Captures).get();
  8011. Expr *Upper =
  8012. UBNonRect ? UBExpr : tryBuildCapture(SemaRef, UBExpr, Captures).get();
  8013. if (!Upper || !Lower)
  8014. return std::make_pair(nullptr, nullptr);
  8015. if (TestIsLessOp.getValue())
  8016. MinExpr = Lower;
  8017. else
  8018. MaxExpr = Upper;
  8019. // Build minimum/maximum value based on number of iterations.
  8020. QualType VarType = LCDecl->getType().getNonReferenceType();
  8021. ExprResult Diff = calculateNumIters(SemaRef, S, DefaultLoc, Lower, Upper,
  8022. Step, VarType, TestIsStrictOp,
  8023. /*RoundToStep=*/false, Captures);
  8024. if (!Diff.isUsable())
  8025. return std::make_pair(nullptr, nullptr);
  8026. // ((Upper - Lower [- 1]) / Step) * Step
  8027. // Parentheses (for dumping/debugging purposes only).
  8028. Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
  8029. if (!Diff.isUsable())
  8030. return std::make_pair(nullptr, nullptr);
  8031. ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
  8032. if (!NewStep.isUsable())
  8033. return std::make_pair(nullptr, nullptr);
  8034. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Mul, Diff.get(), NewStep.get());
  8035. if (!Diff.isUsable())
  8036. return std::make_pair(nullptr, nullptr);
  8037. // Parentheses (for dumping/debugging purposes only).
  8038. Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
  8039. if (!Diff.isUsable())
  8040. return std::make_pair(nullptr, nullptr);
  8041. // Convert to the ptrdiff_t, if original type is pointer.
  8042. if (VarType->isAnyPointerType() &&
  8043. !SemaRef.Context.hasSameType(
  8044. Diff.get()->getType(),
  8045. SemaRef.Context.getUnsignedPointerDiffType())) {
  8046. Diff = SemaRef.PerformImplicitConversion(
  8047. Diff.get(), SemaRef.Context.getUnsignedPointerDiffType(),
  8048. Sema::AA_Converting, /*AllowExplicit=*/true);
  8049. }
  8050. if (!Diff.isUsable())
  8051. return std::make_pair(nullptr, nullptr);
  8052. if (TestIsLessOp.getValue()) {
  8053. // MinExpr = Lower;
  8054. // MaxExpr = Lower + (((Upper - Lower [- 1]) / Step) * Step)
  8055. Diff = SemaRef.BuildBinOp(
  8056. S, DefaultLoc, BO_Add,
  8057. SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Lower).get(),
  8058. Diff.get());
  8059. if (!Diff.isUsable())
  8060. return std::make_pair(nullptr, nullptr);
  8061. } else {
  8062. // MaxExpr = Upper;
  8063. // MinExpr = Upper - (((Upper - Lower [- 1]) / Step) * Step)
  8064. Diff = SemaRef.BuildBinOp(
  8065. S, DefaultLoc, BO_Sub,
  8066. SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Upper).get(),
  8067. Diff.get());
  8068. if (!Diff.isUsable())
  8069. return std::make_pair(nullptr, nullptr);
  8070. }
  8071. // Convert to the original type.
  8072. if (SemaRef.Context.hasSameType(Diff.get()->getType(), VarType))
  8073. Diff = SemaRef.PerformImplicitConversion(Diff.get(), VarType,
  8074. Sema::AA_Converting,
  8075. /*AllowExplicit=*/true);
  8076. if (!Diff.isUsable())
  8077. return std::make_pair(nullptr, nullptr);
  8078. Sema::TentativeAnalysisScope Trap(SemaRef);
  8079. Diff = SemaRef.ActOnFinishFullExpr(Diff.get(), /*DiscardedValue=*/false);
  8080. if (!Diff.isUsable())
  8081. return std::make_pair(nullptr, nullptr);
  8082. if (TestIsLessOp.getValue())
  8083. MaxExpr = Diff.get();
  8084. else
  8085. MinExpr = Diff.get();
  8086. return std::make_pair(MinExpr, MaxExpr);
  8087. }
  8088. Expr *OpenMPIterationSpaceChecker::buildFinalCondition(Scope *S) const {
  8089. if (InitDependOnLC || CondDependOnLC)
  8090. return Condition;
  8091. return nullptr;
  8092. }
  8093. Expr *OpenMPIterationSpaceChecker::buildPreCond(
  8094. Scope *S, Expr *Cond,
  8095. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
  8096. // Do not build a precondition when the condition/initialization is dependent
  8097. // to prevent pessimistic early loop exit.
  8098. // TODO: this can be improved by calculating min/max values but not sure that
  8099. // it will be very effective.
  8100. if (CondDependOnLC || InitDependOnLC)
  8101. return SemaRef
  8102. .PerformImplicitConversion(
  8103. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get(),
  8104. SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
  8105. /*AllowExplicit=*/true)
  8106. .get();
  8107. // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
  8108. Sema::TentativeAnalysisScope Trap(SemaRef);
  8109. ExprResult NewLB = tryBuildCapture(SemaRef, LB, Captures);
  8110. ExprResult NewUB = tryBuildCapture(SemaRef, UB, Captures);
  8111. if (!NewLB.isUsable() || !NewUB.isUsable())
  8112. return nullptr;
  8113. ExprResult CondExpr = SemaRef.BuildBinOp(
  8114. S, DefaultLoc,
  8115. TestIsLessOp.getValue() ? (TestIsStrictOp ? BO_LT : BO_LE)
  8116. : (TestIsStrictOp ? BO_GT : BO_GE),
  8117. NewLB.get(), NewUB.get());
  8118. if (CondExpr.isUsable()) {
  8119. if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
  8120. SemaRef.Context.BoolTy))
  8121. CondExpr = SemaRef.PerformImplicitConversion(
  8122. CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
  8123. /*AllowExplicit=*/true);
  8124. }
  8125. // Otherwise use original loop condition and evaluate it in runtime.
  8126. return CondExpr.isUsable() ? CondExpr.get() : Cond;
  8127. }
  8128. /// Build reference expression to the counter be used for codegen.
  8129. DeclRefExpr *OpenMPIterationSpaceChecker::buildCounterVar(
  8130. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
  8131. DSAStackTy &DSA) const {
  8132. auto *VD = dyn_cast<VarDecl>(LCDecl);
  8133. if (!VD) {
  8134. VD = SemaRef.isOpenMPCapturedDecl(LCDecl);
  8135. DeclRefExpr *Ref = buildDeclRefExpr(
  8136. SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
  8137. const DSAStackTy::DSAVarData Data =
  8138. DSA.getTopDSA(LCDecl, /*FromParent=*/false);
  8139. // If the loop control decl is explicitly marked as private, do not mark it
  8140. // as captured again.
  8141. if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
  8142. Captures.insert(std::make_pair(LCRef, Ref));
  8143. return Ref;
  8144. }
  8145. return cast<DeclRefExpr>(LCRef);
  8146. }
  8147. Expr *OpenMPIterationSpaceChecker::buildPrivateCounterVar() const {
  8148. if (LCDecl && !LCDecl->isInvalidDecl()) {
  8149. QualType Type = LCDecl->getType().getNonReferenceType();
  8150. VarDecl *PrivateVar = buildVarDecl(
  8151. SemaRef, DefaultLoc, Type, LCDecl->getName(),
  8152. LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr,
  8153. isa<VarDecl>(LCDecl)
  8154. ? buildDeclRefExpr(SemaRef, cast<VarDecl>(LCDecl), Type, DefaultLoc)
  8155. : nullptr);
  8156. if (PrivateVar->isInvalidDecl())
  8157. return nullptr;
  8158. return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
  8159. }
  8160. return nullptr;
  8161. }
  8162. /// Build initialization of the counter to be used for codegen.
  8163. Expr *OpenMPIterationSpaceChecker::buildCounterInit() const { return LB; }
  8164. /// Build step of the counter be used for codegen.
  8165. Expr *OpenMPIterationSpaceChecker::buildCounterStep() const { return Step; }
  8166. Expr *OpenMPIterationSpaceChecker::buildOrderedLoopData(
  8167. Scope *S, Expr *Counter,
  8168. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, SourceLocation Loc,
  8169. Expr *Inc, OverloadedOperatorKind OOK) {
  8170. Expr *Cnt = SemaRef.DefaultLvalueConversion(Counter).get();
  8171. if (!Cnt)
  8172. return nullptr;
  8173. if (Inc) {
  8174. assert((OOK == OO_Plus || OOK == OO_Minus) &&
  8175. "Expected only + or - operations for depend clauses.");
  8176. BinaryOperatorKind BOK = (OOK == OO_Plus) ? BO_Add : BO_Sub;
  8177. Cnt = SemaRef.BuildBinOp(S, Loc, BOK, Cnt, Inc).get();
  8178. if (!Cnt)
  8179. return nullptr;
  8180. }
  8181. QualType VarType = LCDecl->getType().getNonReferenceType();
  8182. if (!VarType->isIntegerType() && !VarType->isPointerType() &&
  8183. !SemaRef.getLangOpts().CPlusPlus)
  8184. return nullptr;
  8185. // Upper - Lower
  8186. Expr *Upper = TestIsLessOp.getValue()
  8187. ? Cnt
  8188. : tryBuildCapture(SemaRef, LB, Captures).get();
  8189. Expr *Lower = TestIsLessOp.getValue()
  8190. ? tryBuildCapture(SemaRef, LB, Captures).get()
  8191. : Cnt;
  8192. if (!Upper || !Lower)
  8193. return nullptr;
  8194. ExprResult Diff = calculateNumIters(
  8195. SemaRef, S, DefaultLoc, Lower, Upper, Step, VarType,
  8196. /*TestIsStrictOp=*/false, /*RoundToStep=*/false, Captures);
  8197. if (!Diff.isUsable())
  8198. return nullptr;
  8199. return Diff.get();
  8200. }
  8201. } // namespace
  8202. void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
  8203. assert(getLangOpts().OpenMP && "OpenMP is not active.");
  8204. assert(Init && "Expected loop in canonical form.");
  8205. unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
  8206. if (AssociatedLoops > 0 &&
  8207. isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
  8208. DSAStack->loopStart();
  8209. OpenMPIterationSpaceChecker ISC(*this, /*SupportsNonRectangular=*/true,
  8210. *DSAStack, ForLoc);
  8211. if (!ISC.checkAndSetInit(Init, /*EmitDiags=*/false)) {
  8212. if (ValueDecl *D = ISC.getLoopDecl()) {
  8213. auto *VD = dyn_cast<VarDecl>(D);
  8214. DeclRefExpr *PrivateRef = nullptr;
  8215. if (!VD) {
  8216. if (VarDecl *Private = isOpenMPCapturedDecl(D)) {
  8217. VD = Private;
  8218. } else {
  8219. PrivateRef = buildCapture(*this, D, ISC.getLoopDeclRefExpr(),
  8220. /*WithInit=*/false);
  8221. VD = cast<VarDecl>(PrivateRef->getDecl());
  8222. }
  8223. }
  8224. DSAStack->addLoopControlVariable(D, VD);
  8225. const Decl *LD = DSAStack->getPossiblyLoopCunter();
  8226. if (LD != D->getCanonicalDecl()) {
  8227. DSAStack->resetPossibleLoopCounter();
  8228. if (auto *Var = dyn_cast_or_null<VarDecl>(LD))
  8229. MarkDeclarationsReferencedInExpr(
  8230. buildDeclRefExpr(*this, const_cast<VarDecl *>(Var),
  8231. Var->getType().getNonLValueExprType(Context),
  8232. ForLoc, /*RefersToCapture=*/true));
  8233. }
  8234. OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
  8235. // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables
  8236. // Referenced in a Construct, C/C++]. The loop iteration variable in the
  8237. // associated for-loop of a simd construct with just one associated
  8238. // for-loop may be listed in a linear clause with a constant-linear-step
  8239. // that is the increment of the associated for-loop. The loop iteration
  8240. // variable(s) in the associated for-loop(s) of a for or parallel for
  8241. // construct may be listed in a private or lastprivate clause.
  8242. DSAStackTy::DSAVarData DVar =
  8243. DSAStack->getTopDSA(D, /*FromParent=*/false);
  8244. // If LoopVarRefExpr is nullptr it means the corresponding loop variable
  8245. // is declared in the loop and it is predetermined as a private.
  8246. Expr *LoopDeclRefExpr = ISC.getLoopDeclRefExpr();
  8247. OpenMPClauseKind PredeterminedCKind =
  8248. isOpenMPSimdDirective(DKind)
  8249. ? (DSAStack->hasMutipleLoops() ? OMPC_lastprivate : OMPC_linear)
  8250. : OMPC_private;
  8251. if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
  8252. DVar.CKind != PredeterminedCKind && DVar.RefExpr &&
  8253. (LangOpts.OpenMP <= 45 || (DVar.CKind != OMPC_lastprivate &&
  8254. DVar.CKind != OMPC_private))) ||
  8255. ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
  8256. DKind == OMPD_master_taskloop ||
  8257. DKind == OMPD_parallel_master_taskloop ||
  8258. isOpenMPDistributeDirective(DKind)) &&
  8259. !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
  8260. DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
  8261. (DVar.CKind != OMPC_private || DVar.RefExpr)) {
  8262. Diag(Init->getBeginLoc(), diag::err_omp_loop_var_dsa)
  8263. << getOpenMPClauseName(DVar.CKind)
  8264. << getOpenMPDirectiveName(DKind)
  8265. << getOpenMPClauseName(PredeterminedCKind);
  8266. if (DVar.RefExpr == nullptr)
  8267. DVar.CKind = PredeterminedCKind;
  8268. reportOriginalDsa(*this, DSAStack, D, DVar,
  8269. /*IsLoopIterVar=*/true);
  8270. } else if (LoopDeclRefExpr) {
  8271. // Make the loop iteration variable private (for worksharing
  8272. // constructs), linear (for simd directives with the only one
  8273. // associated loop) or lastprivate (for simd directives with several
  8274. // collapsed or ordered loops).
  8275. if (DVar.CKind == OMPC_unknown)
  8276. DSAStack->addDSA(D, LoopDeclRefExpr, PredeterminedCKind,
  8277. PrivateRef);
  8278. }
  8279. }
  8280. }
  8281. DSAStack->setAssociatedLoops(AssociatedLoops - 1);
  8282. }
  8283. }
  8284. /// Called on a for stmt to check and extract its iteration space
  8285. /// for further processing (such as collapsing).
  8286. static bool checkOpenMPIterationSpace(
  8287. OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
  8288. unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
  8289. unsigned TotalNestedLoopCount, Expr *CollapseLoopCountExpr,
  8290. Expr *OrderedLoopCountExpr,
  8291. Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
  8292. llvm::MutableArrayRef<LoopIterationSpace> ResultIterSpaces,
  8293. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
  8294. bool SupportsNonRectangular = !isOpenMPLoopTransformationDirective(DKind);
  8295. // OpenMP [2.9.1, Canonical Loop Form]
  8296. // for (init-expr; test-expr; incr-expr) structured-block
  8297. // for (range-decl: range-expr) structured-block
  8298. if (auto *CanonLoop = dyn_cast_or_null<OMPCanonicalLoop>(S))
  8299. S = CanonLoop->getLoopStmt();
  8300. auto *For = dyn_cast_or_null<ForStmt>(S);
  8301. auto *CXXFor = dyn_cast_or_null<CXXForRangeStmt>(S);
  8302. // Ranged for is supported only in OpenMP 5.0.
  8303. if (!For && (SemaRef.LangOpts.OpenMP <= 45 || !CXXFor)) {
  8304. SemaRef.Diag(S->getBeginLoc(), diag::err_omp_not_for)
  8305. << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
  8306. << getOpenMPDirectiveName(DKind) << TotalNestedLoopCount
  8307. << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
  8308. if (TotalNestedLoopCount > 1) {
  8309. if (CollapseLoopCountExpr && OrderedLoopCountExpr)
  8310. SemaRef.Diag(DSA.getConstructLoc(),
  8311. diag::note_omp_collapse_ordered_expr)
  8312. << 2 << CollapseLoopCountExpr->getSourceRange()
  8313. << OrderedLoopCountExpr->getSourceRange();
  8314. else if (CollapseLoopCountExpr)
  8315. SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
  8316. diag::note_omp_collapse_ordered_expr)
  8317. << 0 << CollapseLoopCountExpr->getSourceRange();
  8318. else
  8319. SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
  8320. diag::note_omp_collapse_ordered_expr)
  8321. << 1 << OrderedLoopCountExpr->getSourceRange();
  8322. }
  8323. return true;
  8324. }
  8325. assert(((For && For->getBody()) || (CXXFor && CXXFor->getBody())) &&
  8326. "No loop body.");
  8327. // Postpone analysis in dependent contexts for ranged for loops.
  8328. if (CXXFor && SemaRef.CurContext->isDependentContext())
  8329. return false;
  8330. OpenMPIterationSpaceChecker ISC(SemaRef, SupportsNonRectangular, DSA,
  8331. For ? For->getForLoc() : CXXFor->getForLoc());
  8332. // Check init.
  8333. Stmt *Init = For ? For->getInit() : CXXFor->getBeginStmt();
  8334. if (ISC.checkAndSetInit(Init))
  8335. return true;
  8336. bool HasErrors = false;
  8337. // Check loop variable's type.
  8338. if (ValueDecl *LCDecl = ISC.getLoopDecl()) {
  8339. // OpenMP [2.6, Canonical Loop Form]
  8340. // Var is one of the following:
  8341. // A variable of signed or unsigned integer type.
  8342. // For C++, a variable of a random access iterator type.
  8343. // For C, a variable of a pointer type.
  8344. QualType VarType = LCDecl->getType().getNonReferenceType();
  8345. if (!VarType->isDependentType() && !VarType->isIntegerType() &&
  8346. !VarType->isPointerType() &&
  8347. !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
  8348. SemaRef.Diag(Init->getBeginLoc(), diag::err_omp_loop_variable_type)
  8349. << SemaRef.getLangOpts().CPlusPlus;
  8350. HasErrors = true;
  8351. }
  8352. // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
  8353. // a Construct
  8354. // The loop iteration variable(s) in the associated for-loop(s) of a for or
  8355. // parallel for construct is (are) private.
  8356. // The loop iteration variable in the associated for-loop of a simd
  8357. // construct with just one associated for-loop is linear with a
  8358. // constant-linear-step that is the increment of the associated for-loop.
  8359. // Exclude loop var from the list of variables with implicitly defined data
  8360. // sharing attributes.
  8361. VarsWithImplicitDSA.erase(LCDecl);
  8362. assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
  8363. // Check test-expr.
  8364. HasErrors |= ISC.checkAndSetCond(For ? For->getCond() : CXXFor->getCond());
  8365. // Check incr-expr.
  8366. HasErrors |= ISC.checkAndSetInc(For ? For->getInc() : CXXFor->getInc());
  8367. }
  8368. if (ISC.dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
  8369. return HasErrors;
  8370. // Build the loop's iteration space representation.
  8371. ResultIterSpaces[CurrentNestedLoopCount].PreCond = ISC.buildPreCond(
  8372. DSA.getCurScope(), For ? For->getCond() : CXXFor->getCond(), Captures);
  8373. ResultIterSpaces[CurrentNestedLoopCount].NumIterations =
  8374. ISC.buildNumIterations(DSA.getCurScope(), ResultIterSpaces,
  8375. (isOpenMPWorksharingDirective(DKind) ||
  8376. isOpenMPGenericLoopDirective(DKind) ||
  8377. isOpenMPTaskLoopDirective(DKind) ||
  8378. isOpenMPDistributeDirective(DKind) ||
  8379. isOpenMPLoopTransformationDirective(DKind)),
  8380. Captures);
  8381. ResultIterSpaces[CurrentNestedLoopCount].CounterVar =
  8382. ISC.buildCounterVar(Captures, DSA);
  8383. ResultIterSpaces[CurrentNestedLoopCount].PrivateCounterVar =
  8384. ISC.buildPrivateCounterVar();
  8385. ResultIterSpaces[CurrentNestedLoopCount].CounterInit = ISC.buildCounterInit();
  8386. ResultIterSpaces[CurrentNestedLoopCount].CounterStep = ISC.buildCounterStep();
  8387. ResultIterSpaces[CurrentNestedLoopCount].InitSrcRange = ISC.getInitSrcRange();
  8388. ResultIterSpaces[CurrentNestedLoopCount].CondSrcRange =
  8389. ISC.getConditionSrcRange();
  8390. ResultIterSpaces[CurrentNestedLoopCount].IncSrcRange =
  8391. ISC.getIncrementSrcRange();
  8392. ResultIterSpaces[CurrentNestedLoopCount].Subtract = ISC.shouldSubtractStep();
  8393. ResultIterSpaces[CurrentNestedLoopCount].IsStrictCompare =
  8394. ISC.isStrictTestOp();
  8395. std::tie(ResultIterSpaces[CurrentNestedLoopCount].MinValue,
  8396. ResultIterSpaces[CurrentNestedLoopCount].MaxValue) =
  8397. ISC.buildMinMaxValues(DSA.getCurScope(), Captures);
  8398. ResultIterSpaces[CurrentNestedLoopCount].FinalCondition =
  8399. ISC.buildFinalCondition(DSA.getCurScope());
  8400. ResultIterSpaces[CurrentNestedLoopCount].IsNonRectangularLB =
  8401. ISC.doesInitDependOnLC();
  8402. ResultIterSpaces[CurrentNestedLoopCount].IsNonRectangularUB =
  8403. ISC.doesCondDependOnLC();
  8404. ResultIterSpaces[CurrentNestedLoopCount].LoopDependentIdx =
  8405. ISC.getLoopDependentIdx();
  8406. HasErrors |=
  8407. (ResultIterSpaces[CurrentNestedLoopCount].PreCond == nullptr ||
  8408. ResultIterSpaces[CurrentNestedLoopCount].NumIterations == nullptr ||
  8409. ResultIterSpaces[CurrentNestedLoopCount].CounterVar == nullptr ||
  8410. ResultIterSpaces[CurrentNestedLoopCount].PrivateCounterVar == nullptr ||
  8411. ResultIterSpaces[CurrentNestedLoopCount].CounterInit == nullptr ||
  8412. ResultIterSpaces[CurrentNestedLoopCount].CounterStep == nullptr);
  8413. if (!HasErrors && DSA.isOrderedRegion()) {
  8414. if (DSA.getOrderedRegionParam().second->getNumForLoops()) {
  8415. if (CurrentNestedLoopCount <
  8416. DSA.getOrderedRegionParam().second->getLoopNumIterations().size()) {
  8417. DSA.getOrderedRegionParam().second->setLoopNumIterations(
  8418. CurrentNestedLoopCount,
  8419. ResultIterSpaces[CurrentNestedLoopCount].NumIterations);
  8420. DSA.getOrderedRegionParam().second->setLoopCounter(
  8421. CurrentNestedLoopCount,
  8422. ResultIterSpaces[CurrentNestedLoopCount].CounterVar);
  8423. }
  8424. }
  8425. for (auto &Pair : DSA.getDoacrossDependClauses()) {
  8426. if (CurrentNestedLoopCount >= Pair.first->getNumLoops()) {
  8427. // Erroneous case - clause has some problems.
  8428. continue;
  8429. }
  8430. if (Pair.first->getDependencyKind() == OMPC_DEPEND_sink &&
  8431. Pair.second.size() <= CurrentNestedLoopCount) {
  8432. // Erroneous case - clause has some problems.
  8433. Pair.first->setLoopData(CurrentNestedLoopCount, nullptr);
  8434. continue;
  8435. }
  8436. Expr *CntValue;
  8437. if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
  8438. CntValue = ISC.buildOrderedLoopData(
  8439. DSA.getCurScope(),
  8440. ResultIterSpaces[CurrentNestedLoopCount].CounterVar, Captures,
  8441. Pair.first->getDependencyLoc());
  8442. else
  8443. CntValue = ISC.buildOrderedLoopData(
  8444. DSA.getCurScope(),
  8445. ResultIterSpaces[CurrentNestedLoopCount].CounterVar, Captures,
  8446. Pair.first->getDependencyLoc(),
  8447. Pair.second[CurrentNestedLoopCount].first,
  8448. Pair.second[CurrentNestedLoopCount].second);
  8449. Pair.first->setLoopData(CurrentNestedLoopCount, CntValue);
  8450. }
  8451. }
  8452. return HasErrors;
  8453. }
  8454. /// Build 'VarRef = Start.
  8455. static ExprResult
  8456. buildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
  8457. ExprResult Start, bool IsNonRectangularLB,
  8458. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
  8459. // Build 'VarRef = Start.
  8460. ExprResult NewStart = IsNonRectangularLB
  8461. ? Start.get()
  8462. : tryBuildCapture(SemaRef, Start.get(), Captures);
  8463. if (!NewStart.isUsable())
  8464. return ExprError();
  8465. if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
  8466. VarRef.get()->getType())) {
  8467. NewStart = SemaRef.PerformImplicitConversion(
  8468. NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
  8469. /*AllowExplicit=*/true);
  8470. if (!NewStart.isUsable())
  8471. return ExprError();
  8472. }
  8473. ExprResult Init =
  8474. SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
  8475. return Init;
  8476. }
  8477. /// Build 'VarRef = Start + Iter * Step'.
  8478. static ExprResult buildCounterUpdate(
  8479. Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
  8480. ExprResult Start, ExprResult Iter, ExprResult Step, bool Subtract,
  8481. bool IsNonRectangularLB,
  8482. llvm::MapVector<const Expr *, DeclRefExpr *> *Captures = nullptr) {
  8483. // Add parentheses (for debugging purposes only).
  8484. Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
  8485. if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
  8486. !Step.isUsable())
  8487. return ExprError();
  8488. ExprResult NewStep = Step;
  8489. if (Captures)
  8490. NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
  8491. if (NewStep.isInvalid())
  8492. return ExprError();
  8493. ExprResult Update =
  8494. SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
  8495. if (!Update.isUsable())
  8496. return ExprError();
  8497. // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
  8498. // 'VarRef = Start (+|-) Iter * Step'.
  8499. if (!Start.isUsable())
  8500. return ExprError();
  8501. ExprResult NewStart = SemaRef.ActOnParenExpr(Loc, Loc, Start.get());
  8502. if (!NewStart.isUsable())
  8503. return ExprError();
  8504. if (Captures && !IsNonRectangularLB)
  8505. NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
  8506. if (NewStart.isInvalid())
  8507. return ExprError();
  8508. // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
  8509. ExprResult SavedUpdate = Update;
  8510. ExprResult UpdateVal;
  8511. if (VarRef.get()->getType()->isOverloadableType() ||
  8512. NewStart.get()->getType()->isOverloadableType() ||
  8513. Update.get()->getType()->isOverloadableType()) {
  8514. Sema::TentativeAnalysisScope Trap(SemaRef);
  8515. Update =
  8516. SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
  8517. if (Update.isUsable()) {
  8518. UpdateVal =
  8519. SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
  8520. VarRef.get(), SavedUpdate.get());
  8521. if (UpdateVal.isUsable()) {
  8522. Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
  8523. UpdateVal.get());
  8524. }
  8525. }
  8526. }
  8527. // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
  8528. if (!Update.isUsable() || !UpdateVal.isUsable()) {
  8529. Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
  8530. NewStart.get(), SavedUpdate.get());
  8531. if (!Update.isUsable())
  8532. return ExprError();
  8533. if (!SemaRef.Context.hasSameType(Update.get()->getType(),
  8534. VarRef.get()->getType())) {
  8535. Update = SemaRef.PerformImplicitConversion(
  8536. Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
  8537. if (!Update.isUsable())
  8538. return ExprError();
  8539. }
  8540. Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
  8541. }
  8542. return Update;
  8543. }
  8544. /// Convert integer expression \a E to make it have at least \a Bits
  8545. /// bits.
  8546. static ExprResult widenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
  8547. if (E == nullptr)
  8548. return ExprError();
  8549. ASTContext &C = SemaRef.Context;
  8550. QualType OldType = E->getType();
  8551. unsigned HasBits = C.getTypeSize(OldType);
  8552. if (HasBits >= Bits)
  8553. return ExprResult(E);
  8554. // OK to convert to signed, because new type has more bits than old.
  8555. QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
  8556. return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
  8557. true);
  8558. }
  8559. /// Check if the given expression \a E is a constant integer that fits
  8560. /// into \a Bits bits.
  8561. static bool fitsInto(unsigned Bits, bool Signed, const Expr *E, Sema &SemaRef) {
  8562. if (E == nullptr)
  8563. return false;
  8564. if (Optional<llvm::APSInt> Result =
  8565. E->getIntegerConstantExpr(SemaRef.Context))
  8566. return Signed ? Result->isSignedIntN(Bits) : Result->isIntN(Bits);
  8567. return false;
  8568. }
  8569. /// Build preinits statement for the given declarations.
  8570. static Stmt *buildPreInits(ASTContext &Context,
  8571. MutableArrayRef<Decl *> PreInits) {
  8572. if (!PreInits.empty()) {
  8573. return new (Context) DeclStmt(
  8574. DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
  8575. SourceLocation(), SourceLocation());
  8576. }
  8577. return nullptr;
  8578. }
  8579. /// Build preinits statement for the given declarations.
  8580. static Stmt *
  8581. buildPreInits(ASTContext &Context,
  8582. const llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
  8583. if (!Captures.empty()) {
  8584. SmallVector<Decl *, 16> PreInits;
  8585. for (const auto &Pair : Captures)
  8586. PreInits.push_back(Pair.second->getDecl());
  8587. return buildPreInits(Context, PreInits);
  8588. }
  8589. return nullptr;
  8590. }
  8591. /// Build postupdate expression for the given list of postupdates expressions.
  8592. static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
  8593. Expr *PostUpdate = nullptr;
  8594. if (!PostUpdates.empty()) {
  8595. for (Expr *E : PostUpdates) {
  8596. Expr *ConvE = S.BuildCStyleCastExpr(
  8597. E->getExprLoc(),
  8598. S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
  8599. E->getExprLoc(), E)
  8600. .get();
  8601. PostUpdate = PostUpdate
  8602. ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
  8603. PostUpdate, ConvE)
  8604. .get()
  8605. : ConvE;
  8606. }
  8607. }
  8608. return PostUpdate;
  8609. }
  8610. /// Called on a for stmt to check itself and nested loops (if any).
  8611. /// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
  8612. /// number of collapsed loops otherwise.
  8613. static unsigned
  8614. checkOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
  8615. Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
  8616. DSAStackTy &DSA,
  8617. Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
  8618. OMPLoopBasedDirective::HelperExprs &Built) {
  8619. unsigned NestedLoopCount = 1;
  8620. bool SupportsNonPerfectlyNested = (SemaRef.LangOpts.OpenMP >= 50) &&
  8621. !isOpenMPLoopTransformationDirective(DKind);
  8622. if (CollapseLoopCountExpr) {
  8623. // Found 'collapse' clause - calculate collapse number.
  8624. Expr::EvalResult Result;
  8625. if (!CollapseLoopCountExpr->isValueDependent() &&
  8626. CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) {
  8627. NestedLoopCount = Result.Val.getInt().getLimitedValue();
  8628. } else {
  8629. Built.clear(/*Size=*/1);
  8630. return 1;
  8631. }
  8632. }
  8633. unsigned OrderedLoopCount = 1;
  8634. if (OrderedLoopCountExpr) {
  8635. // Found 'ordered' clause - calculate collapse number.
  8636. Expr::EvalResult EVResult;
  8637. if (!OrderedLoopCountExpr->isValueDependent() &&
  8638. OrderedLoopCountExpr->EvaluateAsInt(EVResult,
  8639. SemaRef.getASTContext())) {
  8640. llvm::APSInt Result = EVResult.Val.getInt();
  8641. if (Result.getLimitedValue() < NestedLoopCount) {
  8642. SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
  8643. diag::err_omp_wrong_ordered_loop_count)
  8644. << OrderedLoopCountExpr->getSourceRange();
  8645. SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
  8646. diag::note_collapse_loop_count)
  8647. << CollapseLoopCountExpr->getSourceRange();
  8648. }
  8649. OrderedLoopCount = Result.getLimitedValue();
  8650. } else {
  8651. Built.clear(/*Size=*/1);
  8652. return 1;
  8653. }
  8654. }
  8655. // This is helper routine for loop directives (e.g., 'for', 'simd',
  8656. // 'for simd', etc.).
  8657. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  8658. unsigned NumLoops = std::max(OrderedLoopCount, NestedLoopCount);
  8659. SmallVector<LoopIterationSpace, 4> IterSpaces(NumLoops);
  8660. if (!OMPLoopBasedDirective::doForAllLoops(
  8661. AStmt->IgnoreContainers(!isOpenMPLoopTransformationDirective(DKind)),
  8662. SupportsNonPerfectlyNested, NumLoops,
  8663. [DKind, &SemaRef, &DSA, NumLoops, NestedLoopCount,
  8664. CollapseLoopCountExpr, OrderedLoopCountExpr, &VarsWithImplicitDSA,
  8665. &IterSpaces, &Captures](unsigned Cnt, Stmt *CurStmt) {
  8666. if (checkOpenMPIterationSpace(
  8667. DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
  8668. NumLoops, CollapseLoopCountExpr, OrderedLoopCountExpr,
  8669. VarsWithImplicitDSA, IterSpaces, Captures))
  8670. return true;
  8671. if (Cnt > 0 && Cnt >= NestedLoopCount &&
  8672. IterSpaces[Cnt].CounterVar) {
  8673. // Handle initialization of captured loop iterator variables.
  8674. auto *DRE = cast<DeclRefExpr>(IterSpaces[Cnt].CounterVar);
  8675. if (isa<OMPCapturedExprDecl>(DRE->getDecl())) {
  8676. Captures[DRE] = DRE;
  8677. }
  8678. }
  8679. return false;
  8680. },
  8681. [&SemaRef, &Captures](OMPLoopTransformationDirective *Transform) {
  8682. Stmt *DependentPreInits = Transform->getPreInits();
  8683. if (!DependentPreInits)
  8684. return;
  8685. for (Decl *C : cast<DeclStmt>(DependentPreInits)->getDeclGroup()) {
  8686. auto *D = cast<VarDecl>(C);
  8687. DeclRefExpr *Ref = buildDeclRefExpr(SemaRef, D, D->getType(),
  8688. Transform->getBeginLoc());
  8689. Captures[Ref] = Ref;
  8690. }
  8691. }))
  8692. return 0;
  8693. Built.clear(/* size */ NestedLoopCount);
  8694. if (SemaRef.CurContext->isDependentContext())
  8695. return NestedLoopCount;
  8696. // An example of what is generated for the following code:
  8697. //
  8698. // #pragma omp simd collapse(2) ordered(2)
  8699. // for (i = 0; i < NI; ++i)
  8700. // for (k = 0; k < NK; ++k)
  8701. // for (j = J0; j < NJ; j+=2) {
  8702. // <loop body>
  8703. // }
  8704. //
  8705. // We generate the code below.
  8706. // Note: the loop body may be outlined in CodeGen.
  8707. // Note: some counters may be C++ classes, operator- is used to find number of
  8708. // iterations and operator+= to calculate counter value.
  8709. // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
  8710. // or i64 is currently supported).
  8711. //
  8712. // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
  8713. // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
  8714. // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
  8715. // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
  8716. // // similar updates for vars in clauses (e.g. 'linear')
  8717. // <loop body (using local i and j)>
  8718. // }
  8719. // i = NI; // assign final values of counters
  8720. // j = NJ;
  8721. //
  8722. // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
  8723. // the iteration counts of the collapsed for loops.
  8724. // Precondition tests if there is at least one iteration (all conditions are
  8725. // true).
  8726. auto PreCond = ExprResult(IterSpaces[0].PreCond);
  8727. Expr *N0 = IterSpaces[0].NumIterations;
  8728. ExprResult LastIteration32 =
  8729. widenIterationCount(/*Bits=*/32,
  8730. SemaRef
  8731. .PerformImplicitConversion(
  8732. N0->IgnoreImpCasts(), N0->getType(),
  8733. Sema::AA_Converting, /*AllowExplicit=*/true)
  8734. .get(),
  8735. SemaRef);
  8736. ExprResult LastIteration64 = widenIterationCount(
  8737. /*Bits=*/64,
  8738. SemaRef
  8739. .PerformImplicitConversion(N0->IgnoreImpCasts(), N0->getType(),
  8740. Sema::AA_Converting,
  8741. /*AllowExplicit=*/true)
  8742. .get(),
  8743. SemaRef);
  8744. if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
  8745. return NestedLoopCount;
  8746. ASTContext &C = SemaRef.Context;
  8747. bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
  8748. Scope *CurScope = DSA.getCurScope();
  8749. for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
  8750. if (PreCond.isUsable()) {
  8751. PreCond =
  8752. SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
  8753. PreCond.get(), IterSpaces[Cnt].PreCond);
  8754. }
  8755. Expr *N = IterSpaces[Cnt].NumIterations;
  8756. SourceLocation Loc = N->getExprLoc();
  8757. AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
  8758. if (LastIteration32.isUsable())
  8759. LastIteration32 = SemaRef.BuildBinOp(
  8760. CurScope, Loc, BO_Mul, LastIteration32.get(),
  8761. SemaRef
  8762. .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
  8763. Sema::AA_Converting,
  8764. /*AllowExplicit=*/true)
  8765. .get());
  8766. if (LastIteration64.isUsable())
  8767. LastIteration64 = SemaRef.BuildBinOp(
  8768. CurScope, Loc, BO_Mul, LastIteration64.get(),
  8769. SemaRef
  8770. .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
  8771. Sema::AA_Converting,
  8772. /*AllowExplicit=*/true)
  8773. .get());
  8774. }
  8775. // Choose either the 32-bit or 64-bit version.
  8776. ExprResult LastIteration = LastIteration64;
  8777. if (SemaRef.getLangOpts().OpenMPOptimisticCollapse ||
  8778. (LastIteration32.isUsable() &&
  8779. C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
  8780. (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
  8781. fitsInto(
  8782. /*Bits=*/32,
  8783. LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
  8784. LastIteration64.get(), SemaRef))))
  8785. LastIteration = LastIteration32;
  8786. QualType VType = LastIteration.get()->getType();
  8787. QualType RealVType = VType;
  8788. QualType StrideVType = VType;
  8789. if (isOpenMPTaskLoopDirective(DKind)) {
  8790. VType =
  8791. SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
  8792. StrideVType =
  8793. SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
  8794. }
  8795. if (!LastIteration.isUsable())
  8796. return 0;
  8797. // Save the number of iterations.
  8798. ExprResult NumIterations = LastIteration;
  8799. {
  8800. LastIteration = SemaRef.BuildBinOp(
  8801. CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
  8802. LastIteration.get(),
  8803. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
  8804. if (!LastIteration.isUsable())
  8805. return 0;
  8806. }
  8807. // Calculate the last iteration number beforehand instead of doing this on
  8808. // each iteration. Do not do this if the number of iterations may be kfold-ed.
  8809. bool IsConstant = LastIteration.get()->isIntegerConstantExpr(SemaRef.Context);
  8810. ExprResult CalcLastIteration;
  8811. if (!IsConstant) {
  8812. ExprResult SaveRef =
  8813. tryBuildCapture(SemaRef, LastIteration.get(), Captures);
  8814. LastIteration = SaveRef;
  8815. // Prepare SaveRef + 1.
  8816. NumIterations = SemaRef.BuildBinOp(
  8817. CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
  8818. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
  8819. if (!NumIterations.isUsable())
  8820. return 0;
  8821. }
  8822. SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
  8823. // Build variables passed into runtime, necessary for worksharing directives.
  8824. ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB;
  8825. if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
  8826. isOpenMPDistributeDirective(DKind) ||
  8827. isOpenMPGenericLoopDirective(DKind) ||
  8828. isOpenMPLoopTransformationDirective(DKind)) {
  8829. // Lower bound variable, initialized with zero.
  8830. VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
  8831. LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
  8832. SemaRef.AddInitializerToDecl(LBDecl,
  8833. SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
  8834. /*DirectInit*/ false);
  8835. // Upper bound variable, initialized with last iteration number.
  8836. VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
  8837. UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
  8838. SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
  8839. /*DirectInit*/ false);
  8840. // A 32-bit variable-flag where runtime returns 1 for the last iteration.
  8841. // This will be used to implement clause 'lastprivate'.
  8842. QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
  8843. VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
  8844. IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
  8845. SemaRef.AddInitializerToDecl(ILDecl,
  8846. SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
  8847. /*DirectInit*/ false);
  8848. // Stride variable returned by runtime (we initialize it to 1 by default).
  8849. VarDecl *STDecl =
  8850. buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
  8851. ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
  8852. SemaRef.AddInitializerToDecl(STDecl,
  8853. SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
  8854. /*DirectInit*/ false);
  8855. // Build expression: UB = min(UB, LastIteration)
  8856. // It is necessary for CodeGen of directives with static scheduling.
  8857. ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
  8858. UB.get(), LastIteration.get());
  8859. ExprResult CondOp = SemaRef.ActOnConditionalOp(
  8860. LastIteration.get()->getExprLoc(), InitLoc, IsUBGreater.get(),
  8861. LastIteration.get(), UB.get());
  8862. EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
  8863. CondOp.get());
  8864. EUB = SemaRef.ActOnFinishFullExpr(EUB.get(), /*DiscardedValue*/ false);
  8865. // If we have a combined directive that combines 'distribute', 'for' or
  8866. // 'simd' we need to be able to access the bounds of the schedule of the
  8867. // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
  8868. // by scheduling 'distribute' have to be passed to the schedule of 'for'.
  8869. if (isOpenMPLoopBoundSharingDirective(DKind)) {
  8870. // Lower bound variable, initialized with zero.
  8871. VarDecl *CombLBDecl =
  8872. buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb");
  8873. CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc);
  8874. SemaRef.AddInitializerToDecl(
  8875. CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
  8876. /*DirectInit*/ false);
  8877. // Upper bound variable, initialized with last iteration number.
  8878. VarDecl *CombUBDecl =
  8879. buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub");
  8880. CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc);
  8881. SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(),
  8882. /*DirectInit*/ false);
  8883. ExprResult CombIsUBGreater = SemaRef.BuildBinOp(
  8884. CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get());
  8885. ExprResult CombCondOp =
  8886. SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(),
  8887. LastIteration.get(), CombUB.get());
  8888. CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(),
  8889. CombCondOp.get());
  8890. CombEUB =
  8891. SemaRef.ActOnFinishFullExpr(CombEUB.get(), /*DiscardedValue*/ false);
  8892. const CapturedDecl *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
  8893. // We expect to have at least 2 more parameters than the 'parallel'
  8894. // directive does - the lower and upper bounds of the previous schedule.
  8895. assert(CD->getNumParams() >= 4 &&
  8896. "Unexpected number of parameters in loop combined directive");
  8897. // Set the proper type for the bounds given what we learned from the
  8898. // enclosed loops.
  8899. ImplicitParamDecl *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
  8900. ImplicitParamDecl *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
  8901. // Previous lower and upper bounds are obtained from the region
  8902. // parameters.
  8903. PrevLB =
  8904. buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
  8905. PrevUB =
  8906. buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
  8907. }
  8908. }
  8909. // Build the iteration variable and its initialization before loop.
  8910. ExprResult IV;
  8911. ExprResult Init, CombInit;
  8912. {
  8913. VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
  8914. IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
  8915. Expr *RHS = (isOpenMPWorksharingDirective(DKind) ||
  8916. isOpenMPGenericLoopDirective(DKind) ||
  8917. isOpenMPTaskLoopDirective(DKind) ||
  8918. isOpenMPDistributeDirective(DKind) ||
  8919. isOpenMPLoopTransformationDirective(DKind))
  8920. ? LB.get()
  8921. : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
  8922. Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
  8923. Init = SemaRef.ActOnFinishFullExpr(Init.get(), /*DiscardedValue*/ false);
  8924. if (isOpenMPLoopBoundSharingDirective(DKind)) {
  8925. Expr *CombRHS =
  8926. (isOpenMPWorksharingDirective(DKind) ||
  8927. isOpenMPGenericLoopDirective(DKind) ||
  8928. isOpenMPTaskLoopDirective(DKind) ||
  8929. isOpenMPDistributeDirective(DKind))
  8930. ? CombLB.get()
  8931. : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
  8932. CombInit =
  8933. SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS);
  8934. CombInit =
  8935. SemaRef.ActOnFinishFullExpr(CombInit.get(), /*DiscardedValue*/ false);
  8936. }
  8937. }
  8938. bool UseStrictCompare =
  8939. RealVType->hasUnsignedIntegerRepresentation() &&
  8940. llvm::all_of(IterSpaces, [](const LoopIterationSpace &LIS) {
  8941. return LIS.IsStrictCompare;
  8942. });
  8943. // Loop condition (IV < NumIterations) or (IV <= UB or IV < UB + 1 (for
  8944. // unsigned IV)) for worksharing loops.
  8945. SourceLocation CondLoc = AStmt->getBeginLoc();
  8946. Expr *BoundUB = UB.get();
  8947. if (UseStrictCompare) {
  8948. BoundUB =
  8949. SemaRef
  8950. .BuildBinOp(CurScope, CondLoc, BO_Add, BoundUB,
  8951. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
  8952. .get();
  8953. BoundUB =
  8954. SemaRef.ActOnFinishFullExpr(BoundUB, /*DiscardedValue*/ false).get();
  8955. }
  8956. ExprResult Cond =
  8957. (isOpenMPWorksharingDirective(DKind) ||
  8958. isOpenMPGenericLoopDirective(DKind) ||
  8959. isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind) ||
  8960. isOpenMPLoopTransformationDirective(DKind))
  8961. ? SemaRef.BuildBinOp(CurScope, CondLoc,
  8962. UseStrictCompare ? BO_LT : BO_LE, IV.get(),
  8963. BoundUB)
  8964. : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
  8965. NumIterations.get());
  8966. ExprResult CombDistCond;
  8967. if (isOpenMPLoopBoundSharingDirective(DKind)) {
  8968. CombDistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
  8969. NumIterations.get());
  8970. }
  8971. ExprResult CombCond;
  8972. if (isOpenMPLoopBoundSharingDirective(DKind)) {
  8973. Expr *BoundCombUB = CombUB.get();
  8974. if (UseStrictCompare) {
  8975. BoundCombUB =
  8976. SemaRef
  8977. .BuildBinOp(
  8978. CurScope, CondLoc, BO_Add, BoundCombUB,
  8979. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
  8980. .get();
  8981. BoundCombUB =
  8982. SemaRef.ActOnFinishFullExpr(BoundCombUB, /*DiscardedValue*/ false)
  8983. .get();
  8984. }
  8985. CombCond =
  8986. SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
  8987. IV.get(), BoundCombUB);
  8988. }
  8989. // Loop increment (IV = IV + 1)
  8990. SourceLocation IncLoc = AStmt->getBeginLoc();
  8991. ExprResult Inc =
  8992. SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
  8993. SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
  8994. if (!Inc.isUsable())
  8995. return 0;
  8996. Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
  8997. Inc = SemaRef.ActOnFinishFullExpr(Inc.get(), /*DiscardedValue*/ false);
  8998. if (!Inc.isUsable())
  8999. return 0;
  9000. // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
  9001. // Used for directives with static scheduling.
  9002. // In combined construct, add combined version that use CombLB and CombUB
  9003. // base variables for the update
  9004. ExprResult NextLB, NextUB, CombNextLB, CombNextUB;
  9005. if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
  9006. isOpenMPGenericLoopDirective(DKind) ||
  9007. isOpenMPDistributeDirective(DKind) ||
  9008. isOpenMPLoopTransformationDirective(DKind)) {
  9009. // LB + ST
  9010. NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
  9011. if (!NextLB.isUsable())
  9012. return 0;
  9013. // LB = LB + ST
  9014. NextLB =
  9015. SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
  9016. NextLB =
  9017. SemaRef.ActOnFinishFullExpr(NextLB.get(), /*DiscardedValue*/ false);
  9018. if (!NextLB.isUsable())
  9019. return 0;
  9020. // UB + ST
  9021. NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
  9022. if (!NextUB.isUsable())
  9023. return 0;
  9024. // UB = UB + ST
  9025. NextUB =
  9026. SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
  9027. NextUB =
  9028. SemaRef.ActOnFinishFullExpr(NextUB.get(), /*DiscardedValue*/ false);
  9029. if (!NextUB.isUsable())
  9030. return 0;
  9031. if (isOpenMPLoopBoundSharingDirective(DKind)) {
  9032. CombNextLB =
  9033. SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get());
  9034. if (!NextLB.isUsable())
  9035. return 0;
  9036. // LB = LB + ST
  9037. CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(),
  9038. CombNextLB.get());
  9039. CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get(),
  9040. /*DiscardedValue*/ false);
  9041. if (!CombNextLB.isUsable())
  9042. return 0;
  9043. // UB + ST
  9044. CombNextUB =
  9045. SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get());
  9046. if (!CombNextUB.isUsable())
  9047. return 0;
  9048. // UB = UB + ST
  9049. CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(),
  9050. CombNextUB.get());
  9051. CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get(),
  9052. /*DiscardedValue*/ false);
  9053. if (!CombNextUB.isUsable())
  9054. return 0;
  9055. }
  9056. }
  9057. // Create increment expression for distribute loop when combined in a same
  9058. // directive with for as IV = IV + ST; ensure upper bound expression based
  9059. // on PrevUB instead of NumIterations - used to implement 'for' when found
  9060. // in combination with 'distribute', like in 'distribute parallel for'
  9061. SourceLocation DistIncLoc = AStmt->getBeginLoc();
  9062. ExprResult DistCond, DistInc, PrevEUB, ParForInDistCond;
  9063. if (isOpenMPLoopBoundSharingDirective(DKind)) {
  9064. DistCond = SemaRef.BuildBinOp(
  9065. CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE, IV.get(), BoundUB);
  9066. assert(DistCond.isUsable() && "distribute cond expr was not built");
  9067. DistInc =
  9068. SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get());
  9069. assert(DistInc.isUsable() && "distribute inc expr was not built");
  9070. DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(),
  9071. DistInc.get());
  9072. DistInc =
  9073. SemaRef.ActOnFinishFullExpr(DistInc.get(), /*DiscardedValue*/ false);
  9074. assert(DistInc.isUsable() && "distribute inc expr was not built");
  9075. // Build expression: UB = min(UB, prevUB) for #for in composite or combined
  9076. // construct
  9077. ExprResult NewPrevUB = PrevUB;
  9078. SourceLocation DistEUBLoc = AStmt->getBeginLoc();
  9079. if (!SemaRef.Context.hasSameType(UB.get()->getType(),
  9080. PrevUB.get()->getType())) {
  9081. NewPrevUB = SemaRef.BuildCStyleCastExpr(
  9082. DistEUBLoc,
  9083. SemaRef.Context.getTrivialTypeSourceInfo(UB.get()->getType()),
  9084. DistEUBLoc, NewPrevUB.get());
  9085. if (!NewPrevUB.isUsable())
  9086. return 0;
  9087. }
  9088. ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT,
  9089. UB.get(), NewPrevUB.get());
  9090. ExprResult CondOp = SemaRef.ActOnConditionalOp(
  9091. DistEUBLoc, DistEUBLoc, IsUBGreater.get(), NewPrevUB.get(), UB.get());
  9092. PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(),
  9093. CondOp.get());
  9094. PrevEUB =
  9095. SemaRef.ActOnFinishFullExpr(PrevEUB.get(), /*DiscardedValue*/ false);
  9096. // Build IV <= PrevUB or IV < PrevUB + 1 for unsigned IV to be used in
  9097. // parallel for is in combination with a distribute directive with
  9098. // schedule(static, 1)
  9099. Expr *BoundPrevUB = PrevUB.get();
  9100. if (UseStrictCompare) {
  9101. BoundPrevUB =
  9102. SemaRef
  9103. .BuildBinOp(
  9104. CurScope, CondLoc, BO_Add, BoundPrevUB,
  9105. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
  9106. .get();
  9107. BoundPrevUB =
  9108. SemaRef.ActOnFinishFullExpr(BoundPrevUB, /*DiscardedValue*/ false)
  9109. .get();
  9110. }
  9111. ParForInDistCond =
  9112. SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
  9113. IV.get(), BoundPrevUB);
  9114. }
  9115. // Build updates and final values of the loop counters.
  9116. bool HasErrors = false;
  9117. Built.Counters.resize(NestedLoopCount);
  9118. Built.Inits.resize(NestedLoopCount);
  9119. Built.Updates.resize(NestedLoopCount);
  9120. Built.Finals.resize(NestedLoopCount);
  9121. Built.DependentCounters.resize(NestedLoopCount);
  9122. Built.DependentInits.resize(NestedLoopCount);
  9123. Built.FinalsConditions.resize(NestedLoopCount);
  9124. {
  9125. // We implement the following algorithm for obtaining the
  9126. // original loop iteration variable values based on the
  9127. // value of the collapsed loop iteration variable IV.
  9128. //
  9129. // Let n+1 be the number of collapsed loops in the nest.
  9130. // Iteration variables (I0, I1, .... In)
  9131. // Iteration counts (N0, N1, ... Nn)
  9132. //
  9133. // Acc = IV;
  9134. //
  9135. // To compute Ik for loop k, 0 <= k <= n, generate:
  9136. // Prod = N(k+1) * N(k+2) * ... * Nn;
  9137. // Ik = Acc / Prod;
  9138. // Acc -= Ik * Prod;
  9139. //
  9140. ExprResult Acc = IV;
  9141. for (unsigned int Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
  9142. LoopIterationSpace &IS = IterSpaces[Cnt];
  9143. SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
  9144. ExprResult Iter;
  9145. // Compute prod
  9146. ExprResult Prod = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
  9147. for (unsigned int K = Cnt + 1; K < NestedLoopCount; ++K)
  9148. Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Prod.get(),
  9149. IterSpaces[K].NumIterations);
  9150. // Iter = Acc / Prod
  9151. // If there is at least one more inner loop to avoid
  9152. // multiplication by 1.
  9153. if (Cnt + 1 < NestedLoopCount)
  9154. Iter =
  9155. SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, Acc.get(), Prod.get());
  9156. else
  9157. Iter = Acc;
  9158. if (!Iter.isUsable()) {
  9159. HasErrors = true;
  9160. break;
  9161. }
  9162. // Update Acc:
  9163. // Acc -= Iter * Prod
  9164. // Check if there is at least one more inner loop to avoid
  9165. // multiplication by 1.
  9166. if (Cnt + 1 < NestedLoopCount)
  9167. Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Iter.get(),
  9168. Prod.get());
  9169. else
  9170. Prod = Iter;
  9171. Acc = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Sub, Acc.get(), Prod.get());
  9172. // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
  9173. auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
  9174. DeclRefExpr *CounterVar = buildDeclRefExpr(
  9175. SemaRef, VD, IS.CounterVar->getType(), IS.CounterVar->getExprLoc(),
  9176. /*RefersToCapture=*/true);
  9177. ExprResult Init =
  9178. buildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
  9179. IS.CounterInit, IS.IsNonRectangularLB, Captures);
  9180. if (!Init.isUsable()) {
  9181. HasErrors = true;
  9182. break;
  9183. }
  9184. ExprResult Update = buildCounterUpdate(
  9185. SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
  9186. IS.CounterStep, IS.Subtract, IS.IsNonRectangularLB, &Captures);
  9187. if (!Update.isUsable()) {
  9188. HasErrors = true;
  9189. break;
  9190. }
  9191. // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
  9192. ExprResult Final =
  9193. buildCounterUpdate(SemaRef, CurScope, UpdLoc, CounterVar,
  9194. IS.CounterInit, IS.NumIterations, IS.CounterStep,
  9195. IS.Subtract, IS.IsNonRectangularLB, &Captures);
  9196. if (!Final.isUsable()) {
  9197. HasErrors = true;
  9198. break;
  9199. }
  9200. if (!Update.isUsable() || !Final.isUsable()) {
  9201. HasErrors = true;
  9202. break;
  9203. }
  9204. // Save results
  9205. Built.Counters[Cnt] = IS.CounterVar;
  9206. Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
  9207. Built.Inits[Cnt] = Init.get();
  9208. Built.Updates[Cnt] = Update.get();
  9209. Built.Finals[Cnt] = Final.get();
  9210. Built.DependentCounters[Cnt] = nullptr;
  9211. Built.DependentInits[Cnt] = nullptr;
  9212. Built.FinalsConditions[Cnt] = nullptr;
  9213. if (IS.IsNonRectangularLB || IS.IsNonRectangularUB) {
  9214. Built.DependentCounters[Cnt] =
  9215. Built.Counters[NestedLoopCount - 1 - IS.LoopDependentIdx];
  9216. Built.DependentInits[Cnt] =
  9217. Built.Inits[NestedLoopCount - 1 - IS.LoopDependentIdx];
  9218. Built.FinalsConditions[Cnt] = IS.FinalCondition;
  9219. }
  9220. }
  9221. }
  9222. if (HasErrors)
  9223. return 0;
  9224. // Save results
  9225. Built.IterationVarRef = IV.get();
  9226. Built.LastIteration = LastIteration.get();
  9227. Built.NumIterations = NumIterations.get();
  9228. Built.CalcLastIteration = SemaRef
  9229. .ActOnFinishFullExpr(CalcLastIteration.get(),
  9230. /*DiscardedValue=*/false)
  9231. .get();
  9232. Built.PreCond = PreCond.get();
  9233. Built.PreInits = buildPreInits(C, Captures);
  9234. Built.Cond = Cond.get();
  9235. Built.Init = Init.get();
  9236. Built.Inc = Inc.get();
  9237. Built.LB = LB.get();
  9238. Built.UB = UB.get();
  9239. Built.IL = IL.get();
  9240. Built.ST = ST.get();
  9241. Built.EUB = EUB.get();
  9242. Built.NLB = NextLB.get();
  9243. Built.NUB = NextUB.get();
  9244. Built.PrevLB = PrevLB.get();
  9245. Built.PrevUB = PrevUB.get();
  9246. Built.DistInc = DistInc.get();
  9247. Built.PrevEUB = PrevEUB.get();
  9248. Built.DistCombinedFields.LB = CombLB.get();
  9249. Built.DistCombinedFields.UB = CombUB.get();
  9250. Built.DistCombinedFields.EUB = CombEUB.get();
  9251. Built.DistCombinedFields.Init = CombInit.get();
  9252. Built.DistCombinedFields.Cond = CombCond.get();
  9253. Built.DistCombinedFields.NLB = CombNextLB.get();
  9254. Built.DistCombinedFields.NUB = CombNextUB.get();
  9255. Built.DistCombinedFields.DistCond = CombDistCond.get();
  9256. Built.DistCombinedFields.ParForInDistCond = ParForInDistCond.get();
  9257. return NestedLoopCount;
  9258. }
  9259. static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
  9260. auto CollapseClauses =
  9261. OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
  9262. if (CollapseClauses.begin() != CollapseClauses.end())
  9263. return (*CollapseClauses.begin())->getNumForLoops();
  9264. return nullptr;
  9265. }
  9266. static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
  9267. auto OrderedClauses =
  9268. OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
  9269. if (OrderedClauses.begin() != OrderedClauses.end())
  9270. return (*OrderedClauses.begin())->getNumForLoops();
  9271. return nullptr;
  9272. }
  9273. static bool checkSimdlenSafelenSpecified(Sema &S,
  9274. const ArrayRef<OMPClause *> Clauses) {
  9275. const OMPSafelenClause *Safelen = nullptr;
  9276. const OMPSimdlenClause *Simdlen = nullptr;
  9277. for (const OMPClause *Clause : Clauses) {
  9278. if (Clause->getClauseKind() == OMPC_safelen)
  9279. Safelen = cast<OMPSafelenClause>(Clause);
  9280. else if (Clause->getClauseKind() == OMPC_simdlen)
  9281. Simdlen = cast<OMPSimdlenClause>(Clause);
  9282. if (Safelen && Simdlen)
  9283. break;
  9284. }
  9285. if (Simdlen && Safelen) {
  9286. const Expr *SimdlenLength = Simdlen->getSimdlen();
  9287. const Expr *SafelenLength = Safelen->getSafelen();
  9288. if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
  9289. SimdlenLength->isInstantiationDependent() ||
  9290. SimdlenLength->containsUnexpandedParameterPack())
  9291. return false;
  9292. if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
  9293. SafelenLength->isInstantiationDependent() ||
  9294. SafelenLength->containsUnexpandedParameterPack())
  9295. return false;
  9296. Expr::EvalResult SimdlenResult, SafelenResult;
  9297. SimdlenLength->EvaluateAsInt(SimdlenResult, S.Context);
  9298. SafelenLength->EvaluateAsInt(SafelenResult, S.Context);
  9299. llvm::APSInt SimdlenRes = SimdlenResult.Val.getInt();
  9300. llvm::APSInt SafelenRes = SafelenResult.Val.getInt();
  9301. // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
  9302. // If both simdlen and safelen clauses are specified, the value of the
  9303. // simdlen parameter must be less than or equal to the value of the safelen
  9304. // parameter.
  9305. if (SimdlenRes > SafelenRes) {
  9306. S.Diag(SimdlenLength->getExprLoc(),
  9307. diag::err_omp_wrong_simdlen_safelen_values)
  9308. << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
  9309. return true;
  9310. }
  9311. }
  9312. return false;
  9313. }
  9314. StmtResult
  9315. Sema::ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
  9316. SourceLocation StartLoc, SourceLocation EndLoc,
  9317. VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  9318. if (!AStmt)
  9319. return StmtError();
  9320. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  9321. OMPLoopBasedDirective::HelperExprs B;
  9322. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  9323. // define the nested loops number.
  9324. unsigned NestedLoopCount = checkOpenMPLoop(
  9325. OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
  9326. AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
  9327. if (NestedLoopCount == 0)
  9328. return StmtError();
  9329. assert((CurContext->isDependentContext() || B.builtAll()) &&
  9330. "omp simd loop exprs were not built");
  9331. if (!CurContext->isDependentContext()) {
  9332. // Finalize the clauses that need pre-built expressions for CodeGen.
  9333. for (OMPClause *C : Clauses) {
  9334. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  9335. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  9336. B.NumIterations, *this, CurScope,
  9337. DSAStack))
  9338. return StmtError();
  9339. }
  9340. }
  9341. if (checkSimdlenSafelenSpecified(*this, Clauses))
  9342. return StmtError();
  9343. setFunctionHasBranchProtectedScope();
  9344. return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
  9345. Clauses, AStmt, B);
  9346. }
  9347. StmtResult
  9348. Sema::ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
  9349. SourceLocation StartLoc, SourceLocation EndLoc,
  9350. VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  9351. if (!AStmt)
  9352. return StmtError();
  9353. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  9354. OMPLoopBasedDirective::HelperExprs B;
  9355. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  9356. // define the nested loops number.
  9357. unsigned NestedLoopCount = checkOpenMPLoop(
  9358. OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
  9359. AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
  9360. if (NestedLoopCount == 0)
  9361. return StmtError();
  9362. assert((CurContext->isDependentContext() || B.builtAll()) &&
  9363. "omp for loop exprs were not built");
  9364. if (!CurContext->isDependentContext()) {
  9365. // Finalize the clauses that need pre-built expressions for CodeGen.
  9366. for (OMPClause *C : Clauses) {
  9367. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  9368. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  9369. B.NumIterations, *this, CurScope,
  9370. DSAStack))
  9371. return StmtError();
  9372. }
  9373. }
  9374. setFunctionHasBranchProtectedScope();
  9375. return OMPForDirective::Create(
  9376. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
  9377. DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
  9378. }
  9379. StmtResult Sema::ActOnOpenMPForSimdDirective(
  9380. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  9381. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  9382. if (!AStmt)
  9383. return StmtError();
  9384. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  9385. OMPLoopBasedDirective::HelperExprs B;
  9386. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  9387. // define the nested loops number.
  9388. unsigned NestedLoopCount =
  9389. checkOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
  9390. getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
  9391. VarsWithImplicitDSA, B);
  9392. if (NestedLoopCount == 0)
  9393. return StmtError();
  9394. assert((CurContext->isDependentContext() || B.builtAll()) &&
  9395. "omp for simd loop exprs were not built");
  9396. if (!CurContext->isDependentContext()) {
  9397. // Finalize the clauses that need pre-built expressions for CodeGen.
  9398. for (OMPClause *C : Clauses) {
  9399. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  9400. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  9401. B.NumIterations, *this, CurScope,
  9402. DSAStack))
  9403. return StmtError();
  9404. }
  9405. }
  9406. if (checkSimdlenSafelenSpecified(*this, Clauses))
  9407. return StmtError();
  9408. setFunctionHasBranchProtectedScope();
  9409. return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
  9410. Clauses, AStmt, B);
  9411. }
  9412. StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
  9413. Stmt *AStmt,
  9414. SourceLocation StartLoc,
  9415. SourceLocation EndLoc) {
  9416. if (!AStmt)
  9417. return StmtError();
  9418. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  9419. auto BaseStmt = AStmt;
  9420. while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
  9421. BaseStmt = CS->getCapturedStmt();
  9422. if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
  9423. auto S = C->children();
  9424. if (S.begin() == S.end())
  9425. return StmtError();
  9426. // All associated statements must be '#pragma omp section' except for
  9427. // the first one.
  9428. for (Stmt *SectionStmt : llvm::drop_begin(S)) {
  9429. if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
  9430. if (SectionStmt)
  9431. Diag(SectionStmt->getBeginLoc(),
  9432. diag::err_omp_sections_substmt_not_section);
  9433. return StmtError();
  9434. }
  9435. cast<OMPSectionDirective>(SectionStmt)
  9436. ->setHasCancel(DSAStack->isCancelRegion());
  9437. }
  9438. } else {
  9439. Diag(AStmt->getBeginLoc(), diag::err_omp_sections_not_compound_stmt);
  9440. return StmtError();
  9441. }
  9442. setFunctionHasBranchProtectedScope();
  9443. return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
  9444. DSAStack->getTaskgroupReductionRef(),
  9445. DSAStack->isCancelRegion());
  9446. }
  9447. StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
  9448. SourceLocation StartLoc,
  9449. SourceLocation EndLoc) {
  9450. if (!AStmt)
  9451. return StmtError();
  9452. setFunctionHasBranchProtectedScope();
  9453. DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
  9454. return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
  9455. DSAStack->isCancelRegion());
  9456. }
  9457. static Expr *getDirectCallExpr(Expr *E) {
  9458. E = E->IgnoreParenCasts()->IgnoreImplicit();
  9459. if (auto *CE = dyn_cast<CallExpr>(E))
  9460. if (CE->getDirectCallee())
  9461. return E;
  9462. return nullptr;
  9463. }
  9464. StmtResult Sema::ActOnOpenMPDispatchDirective(ArrayRef<OMPClause *> Clauses,
  9465. Stmt *AStmt,
  9466. SourceLocation StartLoc,
  9467. SourceLocation EndLoc) {
  9468. if (!AStmt)
  9469. return StmtError();
  9470. Stmt *S = cast<CapturedStmt>(AStmt)->getCapturedStmt();
  9471. // 5.1 OpenMP
  9472. // expression-stmt : an expression statement with one of the following forms:
  9473. // expression = target-call ( [expression-list] );
  9474. // target-call ( [expression-list] );
  9475. SourceLocation TargetCallLoc;
  9476. if (!CurContext->isDependentContext()) {
  9477. Expr *TargetCall = nullptr;
  9478. auto *E = dyn_cast<Expr>(S);
  9479. if (!E) {
  9480. Diag(S->getBeginLoc(), diag::err_omp_dispatch_statement_call);
  9481. return StmtError();
  9482. }
  9483. E = E->IgnoreParenCasts()->IgnoreImplicit();
  9484. if (auto *BO = dyn_cast<BinaryOperator>(E)) {
  9485. if (BO->getOpcode() == BO_Assign)
  9486. TargetCall = getDirectCallExpr(BO->getRHS());
  9487. } else {
  9488. if (auto *COCE = dyn_cast<CXXOperatorCallExpr>(E))
  9489. if (COCE->getOperator() == OO_Equal)
  9490. TargetCall = getDirectCallExpr(COCE->getArg(1));
  9491. if (!TargetCall)
  9492. TargetCall = getDirectCallExpr(E);
  9493. }
  9494. if (!TargetCall) {
  9495. Diag(E->getBeginLoc(), diag::err_omp_dispatch_statement_call);
  9496. return StmtError();
  9497. }
  9498. TargetCallLoc = TargetCall->getExprLoc();
  9499. }
  9500. setFunctionHasBranchProtectedScope();
  9501. return OMPDispatchDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
  9502. TargetCallLoc);
  9503. }
  9504. StmtResult Sema::ActOnOpenMPGenericLoopDirective(
  9505. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  9506. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  9507. if (!AStmt)
  9508. return StmtError();
  9509. // OpenMP 5.1 [2.11.7, loop construct]
  9510. // A list item may not appear in a lastprivate clause unless it is the
  9511. // loop iteration variable of a loop that is associated with the construct.
  9512. for (OMPClause *C : Clauses) {
  9513. if (auto *LPC = dyn_cast<OMPLastprivateClause>(C)) {
  9514. for (Expr *RefExpr : LPC->varlists()) {
  9515. SourceLocation ELoc;
  9516. SourceRange ERange;
  9517. Expr *SimpleRefExpr = RefExpr;
  9518. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  9519. if (ValueDecl *D = Res.first) {
  9520. auto &&Info = DSAStack->isLoopControlVariable(D);
  9521. if (!Info.first) {
  9522. Diag(ELoc, diag::err_omp_lastprivate_loop_var_non_loop_iteration);
  9523. return StmtError();
  9524. }
  9525. }
  9526. }
  9527. }
  9528. }
  9529. auto *CS = cast<CapturedStmt>(AStmt);
  9530. // 1.2.2 OpenMP Language Terminology
  9531. // Structured block - An executable statement with a single entry at the
  9532. // top and a single exit at the bottom.
  9533. // The point of exit cannot be a branch out of the structured block.
  9534. // longjmp() and throw() must not violate the entry/exit criteria.
  9535. CS->getCapturedDecl()->setNothrow();
  9536. OMPLoopDirective::HelperExprs B;
  9537. // In presence of clause 'collapse', it will define the nested loops number.
  9538. unsigned NestedLoopCount = checkOpenMPLoop(
  9539. OMPD_loop, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
  9540. AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
  9541. if (NestedLoopCount == 0)
  9542. return StmtError();
  9543. assert((CurContext->isDependentContext() || B.builtAll()) &&
  9544. "omp loop exprs were not built");
  9545. setFunctionHasBranchProtectedScope();
  9546. return OMPGenericLoopDirective::Create(Context, StartLoc, EndLoc,
  9547. NestedLoopCount, Clauses, AStmt, B);
  9548. }
  9549. StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
  9550. Stmt *AStmt,
  9551. SourceLocation StartLoc,
  9552. SourceLocation EndLoc) {
  9553. if (!AStmt)
  9554. return StmtError();
  9555. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  9556. setFunctionHasBranchProtectedScope();
  9557. // OpenMP [2.7.3, single Construct, Restrictions]
  9558. // The copyprivate clause must not be used with the nowait clause.
  9559. const OMPClause *Nowait = nullptr;
  9560. const OMPClause *Copyprivate = nullptr;
  9561. for (const OMPClause *Clause : Clauses) {
  9562. if (Clause->getClauseKind() == OMPC_nowait)
  9563. Nowait = Clause;
  9564. else if (Clause->getClauseKind() == OMPC_copyprivate)
  9565. Copyprivate = Clause;
  9566. if (Copyprivate && Nowait) {
  9567. Diag(Copyprivate->getBeginLoc(),
  9568. diag::err_omp_single_copyprivate_with_nowait);
  9569. Diag(Nowait->getBeginLoc(), diag::note_omp_nowait_clause_here);
  9570. return StmtError();
  9571. }
  9572. }
  9573. return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
  9574. }
  9575. StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
  9576. SourceLocation StartLoc,
  9577. SourceLocation EndLoc) {
  9578. if (!AStmt)
  9579. return StmtError();
  9580. setFunctionHasBranchProtectedScope();
  9581. return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
  9582. }
  9583. StmtResult Sema::ActOnOpenMPMaskedDirective(ArrayRef<OMPClause *> Clauses,
  9584. Stmt *AStmt,
  9585. SourceLocation StartLoc,
  9586. SourceLocation EndLoc) {
  9587. if (!AStmt)
  9588. return StmtError();
  9589. setFunctionHasBranchProtectedScope();
  9590. return OMPMaskedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
  9591. }
  9592. StmtResult Sema::ActOnOpenMPCriticalDirective(
  9593. const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
  9594. Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
  9595. if (!AStmt)
  9596. return StmtError();
  9597. bool ErrorFound = false;
  9598. llvm::APSInt Hint;
  9599. SourceLocation HintLoc;
  9600. bool DependentHint = false;
  9601. for (const OMPClause *C : Clauses) {
  9602. if (C->getClauseKind() == OMPC_hint) {
  9603. if (!DirName.getName()) {
  9604. Diag(C->getBeginLoc(), diag::err_omp_hint_clause_no_name);
  9605. ErrorFound = true;
  9606. }
  9607. Expr *E = cast<OMPHintClause>(C)->getHint();
  9608. if (E->isTypeDependent() || E->isValueDependent() ||
  9609. E->isInstantiationDependent()) {
  9610. DependentHint = true;
  9611. } else {
  9612. Hint = E->EvaluateKnownConstInt(Context);
  9613. HintLoc = C->getBeginLoc();
  9614. }
  9615. }
  9616. }
  9617. if (ErrorFound)
  9618. return StmtError();
  9619. const auto Pair = DSAStack->getCriticalWithHint(DirName);
  9620. if (Pair.first && DirName.getName() && !DependentHint) {
  9621. if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
  9622. Diag(StartLoc, diag::err_omp_critical_with_hint);
  9623. if (HintLoc.isValid())
  9624. Diag(HintLoc, diag::note_omp_critical_hint_here)
  9625. << 0 << toString(Hint, /*Radix=*/10, /*Signed=*/false);
  9626. else
  9627. Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
  9628. if (const auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
  9629. Diag(C->getBeginLoc(), diag::note_omp_critical_hint_here)
  9630. << 1
  9631. << toString(C->getHint()->EvaluateKnownConstInt(Context),
  9632. /*Radix=*/10, /*Signed=*/false);
  9633. } else {
  9634. Diag(Pair.first->getBeginLoc(), diag::note_omp_critical_no_hint) << 1;
  9635. }
  9636. }
  9637. }
  9638. setFunctionHasBranchProtectedScope();
  9639. auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
  9640. Clauses, AStmt);
  9641. if (!Pair.first && DirName.getName() && !DependentHint)
  9642. DSAStack->addCriticalWithHint(Dir, Hint);
  9643. return Dir;
  9644. }
  9645. StmtResult Sema::ActOnOpenMPParallelForDirective(
  9646. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  9647. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  9648. if (!AStmt)
  9649. return StmtError();
  9650. auto *CS = cast<CapturedStmt>(AStmt);
  9651. // 1.2.2 OpenMP Language Terminology
  9652. // Structured block - An executable statement with a single entry at the
  9653. // top and a single exit at the bottom.
  9654. // The point of exit cannot be a branch out of the structured block.
  9655. // longjmp() and throw() must not violate the entry/exit criteria.
  9656. CS->getCapturedDecl()->setNothrow();
  9657. OMPLoopBasedDirective::HelperExprs B;
  9658. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  9659. // define the nested loops number.
  9660. unsigned NestedLoopCount =
  9661. checkOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
  9662. getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
  9663. VarsWithImplicitDSA, B);
  9664. if (NestedLoopCount == 0)
  9665. return StmtError();
  9666. assert((CurContext->isDependentContext() || B.builtAll()) &&
  9667. "omp parallel for loop exprs were not built");
  9668. if (!CurContext->isDependentContext()) {
  9669. // Finalize the clauses that need pre-built expressions for CodeGen.
  9670. for (OMPClause *C : Clauses) {
  9671. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  9672. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  9673. B.NumIterations, *this, CurScope,
  9674. DSAStack))
  9675. return StmtError();
  9676. }
  9677. }
  9678. setFunctionHasBranchProtectedScope();
  9679. return OMPParallelForDirective::Create(
  9680. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
  9681. DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
  9682. }
  9683. StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
  9684. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  9685. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  9686. if (!AStmt)
  9687. return StmtError();
  9688. auto *CS = cast<CapturedStmt>(AStmt);
  9689. // 1.2.2 OpenMP Language Terminology
  9690. // Structured block - An executable statement with a single entry at the
  9691. // top and a single exit at the bottom.
  9692. // The point of exit cannot be a branch out of the structured block.
  9693. // longjmp() and throw() must not violate the entry/exit criteria.
  9694. CS->getCapturedDecl()->setNothrow();
  9695. OMPLoopBasedDirective::HelperExprs B;
  9696. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  9697. // define the nested loops number.
  9698. unsigned NestedLoopCount =
  9699. checkOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
  9700. getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
  9701. VarsWithImplicitDSA, B);
  9702. if (NestedLoopCount == 0)
  9703. return StmtError();
  9704. if (!CurContext->isDependentContext()) {
  9705. // Finalize the clauses that need pre-built expressions for CodeGen.
  9706. for (OMPClause *C : Clauses) {
  9707. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  9708. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  9709. B.NumIterations, *this, CurScope,
  9710. DSAStack))
  9711. return StmtError();
  9712. }
  9713. }
  9714. if (checkSimdlenSafelenSpecified(*this, Clauses))
  9715. return StmtError();
  9716. setFunctionHasBranchProtectedScope();
  9717. return OMPParallelForSimdDirective::Create(
  9718. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  9719. }
  9720. StmtResult
  9721. Sema::ActOnOpenMPParallelMasterDirective(ArrayRef<OMPClause *> Clauses,
  9722. Stmt *AStmt, SourceLocation StartLoc,
  9723. SourceLocation EndLoc) {
  9724. if (!AStmt)
  9725. return StmtError();
  9726. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  9727. auto *CS = cast<CapturedStmt>(AStmt);
  9728. // 1.2.2 OpenMP Language Terminology
  9729. // Structured block - An executable statement with a single entry at the
  9730. // top and a single exit at the bottom.
  9731. // The point of exit cannot be a branch out of the structured block.
  9732. // longjmp() and throw() must not violate the entry/exit criteria.
  9733. CS->getCapturedDecl()->setNothrow();
  9734. setFunctionHasBranchProtectedScope();
  9735. return OMPParallelMasterDirective::Create(
  9736. Context, StartLoc, EndLoc, Clauses, AStmt,
  9737. DSAStack->getTaskgroupReductionRef());
  9738. }
  9739. StmtResult
  9740. Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
  9741. Stmt *AStmt, SourceLocation StartLoc,
  9742. SourceLocation EndLoc) {
  9743. if (!AStmt)
  9744. return StmtError();
  9745. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  9746. auto BaseStmt = AStmt;
  9747. while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
  9748. BaseStmt = CS->getCapturedStmt();
  9749. if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
  9750. auto S = C->children();
  9751. if (S.begin() == S.end())
  9752. return StmtError();
  9753. // All associated statements must be '#pragma omp section' except for
  9754. // the first one.
  9755. for (Stmt *SectionStmt : llvm::drop_begin(S)) {
  9756. if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
  9757. if (SectionStmt)
  9758. Diag(SectionStmt->getBeginLoc(),
  9759. diag::err_omp_parallel_sections_substmt_not_section);
  9760. return StmtError();
  9761. }
  9762. cast<OMPSectionDirective>(SectionStmt)
  9763. ->setHasCancel(DSAStack->isCancelRegion());
  9764. }
  9765. } else {
  9766. Diag(AStmt->getBeginLoc(),
  9767. diag::err_omp_parallel_sections_not_compound_stmt);
  9768. return StmtError();
  9769. }
  9770. setFunctionHasBranchProtectedScope();
  9771. return OMPParallelSectionsDirective::Create(
  9772. Context, StartLoc, EndLoc, Clauses, AStmt,
  9773. DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
  9774. }
  9775. /// Find and diagnose mutually exclusive clause kinds.
  9776. static bool checkMutuallyExclusiveClauses(
  9777. Sema &S, ArrayRef<OMPClause *> Clauses,
  9778. ArrayRef<OpenMPClauseKind> MutuallyExclusiveClauses) {
  9779. const OMPClause *PrevClause = nullptr;
  9780. bool ErrorFound = false;
  9781. for (const OMPClause *C : Clauses) {
  9782. if (llvm::is_contained(MutuallyExclusiveClauses, C->getClauseKind())) {
  9783. if (!PrevClause) {
  9784. PrevClause = C;
  9785. } else if (PrevClause->getClauseKind() != C->getClauseKind()) {
  9786. S.Diag(C->getBeginLoc(), diag::err_omp_clauses_mutually_exclusive)
  9787. << getOpenMPClauseName(C->getClauseKind())
  9788. << getOpenMPClauseName(PrevClause->getClauseKind());
  9789. S.Diag(PrevClause->getBeginLoc(), diag::note_omp_previous_clause)
  9790. << getOpenMPClauseName(PrevClause->getClauseKind());
  9791. ErrorFound = true;
  9792. }
  9793. }
  9794. }
  9795. return ErrorFound;
  9796. }
  9797. StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
  9798. Stmt *AStmt, SourceLocation StartLoc,
  9799. SourceLocation EndLoc) {
  9800. if (!AStmt)
  9801. return StmtError();
  9802. // OpenMP 5.0, 2.10.1 task Construct
  9803. // If a detach clause appears on the directive, then a mergeable clause cannot
  9804. // appear on the same directive.
  9805. if (checkMutuallyExclusiveClauses(*this, Clauses,
  9806. {OMPC_detach, OMPC_mergeable}))
  9807. return StmtError();
  9808. auto *CS = cast<CapturedStmt>(AStmt);
  9809. // 1.2.2 OpenMP Language Terminology
  9810. // Structured block - An executable statement with a single entry at the
  9811. // top and a single exit at the bottom.
  9812. // The point of exit cannot be a branch out of the structured block.
  9813. // longjmp() and throw() must not violate the entry/exit criteria.
  9814. CS->getCapturedDecl()->setNothrow();
  9815. setFunctionHasBranchProtectedScope();
  9816. return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
  9817. DSAStack->isCancelRegion());
  9818. }
  9819. StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
  9820. SourceLocation EndLoc) {
  9821. return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
  9822. }
  9823. StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
  9824. SourceLocation EndLoc) {
  9825. return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
  9826. }
  9827. StmtResult Sema::ActOnOpenMPTaskwaitDirective(ArrayRef<OMPClause *> Clauses,
  9828. SourceLocation StartLoc,
  9829. SourceLocation EndLoc) {
  9830. return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc, Clauses);
  9831. }
  9832. StmtResult Sema::ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
  9833. Stmt *AStmt,
  9834. SourceLocation StartLoc,
  9835. SourceLocation EndLoc) {
  9836. if (!AStmt)
  9837. return StmtError();
  9838. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  9839. setFunctionHasBranchProtectedScope();
  9840. return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, Clauses,
  9841. AStmt,
  9842. DSAStack->getTaskgroupReductionRef());
  9843. }
  9844. StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
  9845. SourceLocation StartLoc,
  9846. SourceLocation EndLoc) {
  9847. OMPFlushClause *FC = nullptr;
  9848. OMPClause *OrderClause = nullptr;
  9849. for (OMPClause *C : Clauses) {
  9850. if (C->getClauseKind() == OMPC_flush)
  9851. FC = cast<OMPFlushClause>(C);
  9852. else
  9853. OrderClause = C;
  9854. }
  9855. OpenMPClauseKind MemOrderKind = OMPC_unknown;
  9856. SourceLocation MemOrderLoc;
  9857. for (const OMPClause *C : Clauses) {
  9858. if (C->getClauseKind() == OMPC_acq_rel ||
  9859. C->getClauseKind() == OMPC_acquire ||
  9860. C->getClauseKind() == OMPC_release) {
  9861. if (MemOrderKind != OMPC_unknown) {
  9862. Diag(C->getBeginLoc(), diag::err_omp_several_mem_order_clauses)
  9863. << getOpenMPDirectiveName(OMPD_flush) << 1
  9864. << SourceRange(C->getBeginLoc(), C->getEndLoc());
  9865. Diag(MemOrderLoc, diag::note_omp_previous_mem_order_clause)
  9866. << getOpenMPClauseName(MemOrderKind);
  9867. } else {
  9868. MemOrderKind = C->getClauseKind();
  9869. MemOrderLoc = C->getBeginLoc();
  9870. }
  9871. }
  9872. }
  9873. if (FC && OrderClause) {
  9874. Diag(FC->getLParenLoc(), diag::err_omp_flush_order_clause_and_list)
  9875. << getOpenMPClauseName(OrderClause->getClauseKind());
  9876. Diag(OrderClause->getBeginLoc(), diag::note_omp_flush_order_clause_here)
  9877. << getOpenMPClauseName(OrderClause->getClauseKind());
  9878. return StmtError();
  9879. }
  9880. return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
  9881. }
  9882. StmtResult Sema::ActOnOpenMPDepobjDirective(ArrayRef<OMPClause *> Clauses,
  9883. SourceLocation StartLoc,
  9884. SourceLocation EndLoc) {
  9885. if (Clauses.empty()) {
  9886. Diag(StartLoc, diag::err_omp_depobj_expected);
  9887. return StmtError();
  9888. } else if (Clauses[0]->getClauseKind() != OMPC_depobj) {
  9889. Diag(Clauses[0]->getBeginLoc(), diag::err_omp_depobj_expected);
  9890. return StmtError();
  9891. }
  9892. // Only depobj expression and another single clause is allowed.
  9893. if (Clauses.size() > 2) {
  9894. Diag(Clauses[2]->getBeginLoc(),
  9895. diag::err_omp_depobj_single_clause_expected);
  9896. return StmtError();
  9897. } else if (Clauses.size() < 1) {
  9898. Diag(Clauses[0]->getEndLoc(), diag::err_omp_depobj_single_clause_expected);
  9899. return StmtError();
  9900. }
  9901. return OMPDepobjDirective::Create(Context, StartLoc, EndLoc, Clauses);
  9902. }
  9903. StmtResult Sema::ActOnOpenMPScanDirective(ArrayRef<OMPClause *> Clauses,
  9904. SourceLocation StartLoc,
  9905. SourceLocation EndLoc) {
  9906. // Check that exactly one clause is specified.
  9907. if (Clauses.size() != 1) {
  9908. Diag(Clauses.empty() ? EndLoc : Clauses[1]->getBeginLoc(),
  9909. diag::err_omp_scan_single_clause_expected);
  9910. return StmtError();
  9911. }
  9912. // Check that scan directive is used in the scopeof the OpenMP loop body.
  9913. if (Scope *S = DSAStack->getCurScope()) {
  9914. Scope *ParentS = S->getParent();
  9915. if (!ParentS || ParentS->getParent() != ParentS->getBreakParent() ||
  9916. !ParentS->getBreakParent()->isOpenMPLoopScope())
  9917. return StmtError(Diag(StartLoc, diag::err_omp_orphaned_device_directive)
  9918. << getOpenMPDirectiveName(OMPD_scan) << 5);
  9919. }
  9920. // Check that only one instance of scan directives is used in the same outer
  9921. // region.
  9922. if (DSAStack->doesParentHasScanDirective()) {
  9923. Diag(StartLoc, diag::err_omp_several_directives_in_region) << "scan";
  9924. Diag(DSAStack->getParentScanDirectiveLoc(),
  9925. diag::note_omp_previous_directive)
  9926. << "scan";
  9927. return StmtError();
  9928. }
  9929. DSAStack->setParentHasScanDirective(StartLoc);
  9930. return OMPScanDirective::Create(Context, StartLoc, EndLoc, Clauses);
  9931. }
  9932. StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
  9933. Stmt *AStmt,
  9934. SourceLocation StartLoc,
  9935. SourceLocation EndLoc) {
  9936. const OMPClause *DependFound = nullptr;
  9937. const OMPClause *DependSourceClause = nullptr;
  9938. const OMPClause *DependSinkClause = nullptr;
  9939. bool ErrorFound = false;
  9940. const OMPThreadsClause *TC = nullptr;
  9941. const OMPSIMDClause *SC = nullptr;
  9942. for (const OMPClause *C : Clauses) {
  9943. if (auto *DC = dyn_cast<OMPDependClause>(C)) {
  9944. DependFound = C;
  9945. if (DC->getDependencyKind() == OMPC_DEPEND_source) {
  9946. if (DependSourceClause) {
  9947. Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
  9948. << getOpenMPDirectiveName(OMPD_ordered)
  9949. << getOpenMPClauseName(OMPC_depend) << 2;
  9950. ErrorFound = true;
  9951. } else {
  9952. DependSourceClause = C;
  9953. }
  9954. if (DependSinkClause) {
  9955. Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
  9956. << 0;
  9957. ErrorFound = true;
  9958. }
  9959. } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
  9960. if (DependSourceClause) {
  9961. Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
  9962. << 1;
  9963. ErrorFound = true;
  9964. }
  9965. DependSinkClause = C;
  9966. }
  9967. } else if (C->getClauseKind() == OMPC_threads) {
  9968. TC = cast<OMPThreadsClause>(C);
  9969. } else if (C->getClauseKind() == OMPC_simd) {
  9970. SC = cast<OMPSIMDClause>(C);
  9971. }
  9972. }
  9973. if (!ErrorFound && !SC &&
  9974. isOpenMPSimdDirective(DSAStack->getParentDirective())) {
  9975. // OpenMP [2.8.1,simd Construct, Restrictions]
  9976. // An ordered construct with the simd clause is the only OpenMP construct
  9977. // that can appear in the simd region.
  9978. Diag(StartLoc, diag::err_omp_prohibited_region_simd)
  9979. << (LangOpts.OpenMP >= 50 ? 1 : 0);
  9980. ErrorFound = true;
  9981. } else if (DependFound && (TC || SC)) {
  9982. Diag(DependFound->getBeginLoc(), diag::err_omp_depend_clause_thread_simd)
  9983. << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
  9984. ErrorFound = true;
  9985. } else if (DependFound && !DSAStack->getParentOrderedRegionParam().first) {
  9986. Diag(DependFound->getBeginLoc(),
  9987. diag::err_omp_ordered_directive_without_param);
  9988. ErrorFound = true;
  9989. } else if (TC || Clauses.empty()) {
  9990. if (const Expr *Param = DSAStack->getParentOrderedRegionParam().first) {
  9991. SourceLocation ErrLoc = TC ? TC->getBeginLoc() : StartLoc;
  9992. Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
  9993. << (TC != nullptr);
  9994. Diag(Param->getBeginLoc(), diag::note_omp_ordered_param) << 1;
  9995. ErrorFound = true;
  9996. }
  9997. }
  9998. if ((!AStmt && !DependFound) || ErrorFound)
  9999. return StmtError();
  10000. // OpenMP 5.0, 2.17.9, ordered Construct, Restrictions.
  10001. // During execution of an iteration of a worksharing-loop or a loop nest
  10002. // within a worksharing-loop, simd, or worksharing-loop SIMD region, a thread
  10003. // must not execute more than one ordered region corresponding to an ordered
  10004. // construct without a depend clause.
  10005. if (!DependFound) {
  10006. if (DSAStack->doesParentHasOrderedDirective()) {
  10007. Diag(StartLoc, diag::err_omp_several_directives_in_region) << "ordered";
  10008. Diag(DSAStack->getParentOrderedDirectiveLoc(),
  10009. diag::note_omp_previous_directive)
  10010. << "ordered";
  10011. return StmtError();
  10012. }
  10013. DSAStack->setParentHasOrderedDirective(StartLoc);
  10014. }
  10015. if (AStmt) {
  10016. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  10017. setFunctionHasBranchProtectedScope();
  10018. }
  10019. return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
  10020. }
  10021. namespace {
  10022. /// Helper class for checking expression in 'omp atomic [update]'
  10023. /// construct.
  10024. class OpenMPAtomicUpdateChecker {
  10025. /// Error results for atomic update expressions.
  10026. enum ExprAnalysisErrorCode {
  10027. /// A statement is not an expression statement.
  10028. NotAnExpression,
  10029. /// Expression is not builtin binary or unary operation.
  10030. NotABinaryOrUnaryExpression,
  10031. /// Unary operation is not post-/pre- increment/decrement operation.
  10032. NotAnUnaryIncDecExpression,
  10033. /// An expression is not of scalar type.
  10034. NotAScalarType,
  10035. /// A binary operation is not an assignment operation.
  10036. NotAnAssignmentOp,
  10037. /// RHS part of the binary operation is not a binary expression.
  10038. NotABinaryExpression,
  10039. /// RHS part is not additive/multiplicative/shift/biwise binary
  10040. /// expression.
  10041. NotABinaryOperator,
  10042. /// RHS binary operation does not have reference to the updated LHS
  10043. /// part.
  10044. NotAnUpdateExpression,
  10045. /// No errors is found.
  10046. NoError
  10047. };
  10048. /// Reference to Sema.
  10049. Sema &SemaRef;
  10050. /// A location for note diagnostics (when error is found).
  10051. SourceLocation NoteLoc;
  10052. /// 'x' lvalue part of the source atomic expression.
  10053. Expr *X;
  10054. /// 'expr' rvalue part of the source atomic expression.
  10055. Expr *E;
  10056. /// Helper expression of the form
  10057. /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
  10058. /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
  10059. Expr *UpdateExpr;
  10060. /// Is 'x' a LHS in a RHS part of full update expression. It is
  10061. /// important for non-associative operations.
  10062. bool IsXLHSInRHSPart;
  10063. BinaryOperatorKind Op;
  10064. SourceLocation OpLoc;
  10065. /// true if the source expression is a postfix unary operation, false
  10066. /// if it is a prefix unary operation.
  10067. bool IsPostfixUpdate;
  10068. public:
  10069. OpenMPAtomicUpdateChecker(Sema &SemaRef)
  10070. : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
  10071. IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
  10072. /// Check specified statement that it is suitable for 'atomic update'
  10073. /// constructs and extract 'x', 'expr' and Operation from the original
  10074. /// expression. If DiagId and NoteId == 0, then only check is performed
  10075. /// without error notification.
  10076. /// \param DiagId Diagnostic which should be emitted if error is found.
  10077. /// \param NoteId Diagnostic note for the main error message.
  10078. /// \return true if statement is not an update expression, false otherwise.
  10079. bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
  10080. /// Return the 'x' lvalue part of the source atomic expression.
  10081. Expr *getX() const { return X; }
  10082. /// Return the 'expr' rvalue part of the source atomic expression.
  10083. Expr *getExpr() const { return E; }
  10084. /// Return the update expression used in calculation of the updated
  10085. /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
  10086. /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
  10087. Expr *getUpdateExpr() const { return UpdateExpr; }
  10088. /// Return true if 'x' is LHS in RHS part of full update expression,
  10089. /// false otherwise.
  10090. bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
  10091. /// true if the source expression is a postfix unary operation, false
  10092. /// if it is a prefix unary operation.
  10093. bool isPostfixUpdate() const { return IsPostfixUpdate; }
  10094. private:
  10095. bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
  10096. unsigned NoteId = 0);
  10097. };
  10098. bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
  10099. BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
  10100. ExprAnalysisErrorCode ErrorFound = NoError;
  10101. SourceLocation ErrorLoc, NoteLoc;
  10102. SourceRange ErrorRange, NoteRange;
  10103. // Allowed constructs are:
  10104. // x = x binop expr;
  10105. // x = expr binop x;
  10106. if (AtomicBinOp->getOpcode() == BO_Assign) {
  10107. X = AtomicBinOp->getLHS();
  10108. if (const auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
  10109. AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
  10110. if (AtomicInnerBinOp->isMultiplicativeOp() ||
  10111. AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
  10112. AtomicInnerBinOp->isBitwiseOp()) {
  10113. Op = AtomicInnerBinOp->getOpcode();
  10114. OpLoc = AtomicInnerBinOp->getOperatorLoc();
  10115. Expr *LHS = AtomicInnerBinOp->getLHS();
  10116. Expr *RHS = AtomicInnerBinOp->getRHS();
  10117. llvm::FoldingSetNodeID XId, LHSId, RHSId;
  10118. X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
  10119. /*Canonical=*/true);
  10120. LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
  10121. /*Canonical=*/true);
  10122. RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
  10123. /*Canonical=*/true);
  10124. if (XId == LHSId) {
  10125. E = RHS;
  10126. IsXLHSInRHSPart = true;
  10127. } else if (XId == RHSId) {
  10128. E = LHS;
  10129. IsXLHSInRHSPart = false;
  10130. } else {
  10131. ErrorLoc = AtomicInnerBinOp->getExprLoc();
  10132. ErrorRange = AtomicInnerBinOp->getSourceRange();
  10133. NoteLoc = X->getExprLoc();
  10134. NoteRange = X->getSourceRange();
  10135. ErrorFound = NotAnUpdateExpression;
  10136. }
  10137. } else {
  10138. ErrorLoc = AtomicInnerBinOp->getExprLoc();
  10139. ErrorRange = AtomicInnerBinOp->getSourceRange();
  10140. NoteLoc = AtomicInnerBinOp->getOperatorLoc();
  10141. NoteRange = SourceRange(NoteLoc, NoteLoc);
  10142. ErrorFound = NotABinaryOperator;
  10143. }
  10144. } else {
  10145. NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
  10146. NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
  10147. ErrorFound = NotABinaryExpression;
  10148. }
  10149. } else {
  10150. ErrorLoc = AtomicBinOp->getExprLoc();
  10151. ErrorRange = AtomicBinOp->getSourceRange();
  10152. NoteLoc = AtomicBinOp->getOperatorLoc();
  10153. NoteRange = SourceRange(NoteLoc, NoteLoc);
  10154. ErrorFound = NotAnAssignmentOp;
  10155. }
  10156. if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
  10157. SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
  10158. SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
  10159. return true;
  10160. }
  10161. if (SemaRef.CurContext->isDependentContext())
  10162. E = X = UpdateExpr = nullptr;
  10163. return ErrorFound != NoError;
  10164. }
  10165. bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
  10166. unsigned NoteId) {
  10167. ExprAnalysisErrorCode ErrorFound = NoError;
  10168. SourceLocation ErrorLoc, NoteLoc;
  10169. SourceRange ErrorRange, NoteRange;
  10170. // Allowed constructs are:
  10171. // x++;
  10172. // x--;
  10173. // ++x;
  10174. // --x;
  10175. // x binop= expr;
  10176. // x = x binop expr;
  10177. // x = expr binop x;
  10178. if (auto *AtomicBody = dyn_cast<Expr>(S)) {
  10179. AtomicBody = AtomicBody->IgnoreParenImpCasts();
  10180. if (AtomicBody->getType()->isScalarType() ||
  10181. AtomicBody->isInstantiationDependent()) {
  10182. if (const auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
  10183. AtomicBody->IgnoreParenImpCasts())) {
  10184. // Check for Compound Assignment Operation
  10185. Op = BinaryOperator::getOpForCompoundAssignment(
  10186. AtomicCompAssignOp->getOpcode());
  10187. OpLoc = AtomicCompAssignOp->getOperatorLoc();
  10188. E = AtomicCompAssignOp->getRHS();
  10189. X = AtomicCompAssignOp->getLHS()->IgnoreParens();
  10190. IsXLHSInRHSPart = true;
  10191. } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
  10192. AtomicBody->IgnoreParenImpCasts())) {
  10193. // Check for Binary Operation
  10194. if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
  10195. return true;
  10196. } else if (const auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
  10197. AtomicBody->IgnoreParenImpCasts())) {
  10198. // Check for Unary Operation
  10199. if (AtomicUnaryOp->isIncrementDecrementOp()) {
  10200. IsPostfixUpdate = AtomicUnaryOp->isPostfix();
  10201. Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
  10202. OpLoc = AtomicUnaryOp->getOperatorLoc();
  10203. X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
  10204. E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
  10205. IsXLHSInRHSPart = true;
  10206. } else {
  10207. ErrorFound = NotAnUnaryIncDecExpression;
  10208. ErrorLoc = AtomicUnaryOp->getExprLoc();
  10209. ErrorRange = AtomicUnaryOp->getSourceRange();
  10210. NoteLoc = AtomicUnaryOp->getOperatorLoc();
  10211. NoteRange = SourceRange(NoteLoc, NoteLoc);
  10212. }
  10213. } else if (!AtomicBody->isInstantiationDependent()) {
  10214. ErrorFound = NotABinaryOrUnaryExpression;
  10215. NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
  10216. NoteRange = ErrorRange = AtomicBody->getSourceRange();
  10217. }
  10218. } else {
  10219. ErrorFound = NotAScalarType;
  10220. NoteLoc = ErrorLoc = AtomicBody->getBeginLoc();
  10221. NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
  10222. }
  10223. } else {
  10224. ErrorFound = NotAnExpression;
  10225. NoteLoc = ErrorLoc = S->getBeginLoc();
  10226. NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
  10227. }
  10228. if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
  10229. SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
  10230. SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
  10231. return true;
  10232. }
  10233. if (SemaRef.CurContext->isDependentContext())
  10234. E = X = UpdateExpr = nullptr;
  10235. if (ErrorFound == NoError && E && X) {
  10236. // Build an update expression of form 'OpaqueValueExpr(x) binop
  10237. // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
  10238. // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
  10239. auto *OVEX = new (SemaRef.getASTContext())
  10240. OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_PRValue);
  10241. auto *OVEExpr = new (SemaRef.getASTContext())
  10242. OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_PRValue);
  10243. ExprResult Update =
  10244. SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
  10245. IsXLHSInRHSPart ? OVEExpr : OVEX);
  10246. if (Update.isInvalid())
  10247. return true;
  10248. Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
  10249. Sema::AA_Casting);
  10250. if (Update.isInvalid())
  10251. return true;
  10252. UpdateExpr = Update.get();
  10253. }
  10254. return ErrorFound != NoError;
  10255. }
  10256. } // namespace
  10257. StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
  10258. Stmt *AStmt,
  10259. SourceLocation StartLoc,
  10260. SourceLocation EndLoc) {
  10261. // Register location of the first atomic directive.
  10262. DSAStack->addAtomicDirectiveLoc(StartLoc);
  10263. if (!AStmt)
  10264. return StmtError();
  10265. // 1.2.2 OpenMP Language Terminology
  10266. // Structured block - An executable statement with a single entry at the
  10267. // top and a single exit at the bottom.
  10268. // The point of exit cannot be a branch out of the structured block.
  10269. // longjmp() and throw() must not violate the entry/exit criteria.
  10270. OpenMPClauseKind AtomicKind = OMPC_unknown;
  10271. SourceLocation AtomicKindLoc;
  10272. OpenMPClauseKind MemOrderKind = OMPC_unknown;
  10273. SourceLocation MemOrderLoc;
  10274. for (const OMPClause *C : Clauses) {
  10275. switch (C->getClauseKind()) {
  10276. case OMPC_read:
  10277. case OMPC_write:
  10278. case OMPC_update:
  10279. case OMPC_capture:
  10280. case OMPC_compare: {
  10281. if (AtomicKind != OMPC_unknown) {
  10282. Diag(C->getBeginLoc(), diag::err_omp_atomic_several_clauses)
  10283. << SourceRange(C->getBeginLoc(), C->getEndLoc());
  10284. Diag(AtomicKindLoc, diag::note_omp_previous_mem_order_clause)
  10285. << getOpenMPClauseName(AtomicKind);
  10286. } else {
  10287. AtomicKind = C->getClauseKind();
  10288. AtomicKindLoc = C->getBeginLoc();
  10289. }
  10290. break;
  10291. }
  10292. case OMPC_seq_cst:
  10293. case OMPC_acq_rel:
  10294. case OMPC_acquire:
  10295. case OMPC_release:
  10296. case OMPC_relaxed: {
  10297. if (MemOrderKind != OMPC_unknown) {
  10298. Diag(C->getBeginLoc(), diag::err_omp_several_mem_order_clauses)
  10299. << getOpenMPDirectiveName(OMPD_atomic) << 0
  10300. << SourceRange(C->getBeginLoc(), C->getEndLoc());
  10301. Diag(MemOrderLoc, diag::note_omp_previous_mem_order_clause)
  10302. << getOpenMPClauseName(MemOrderKind);
  10303. } else {
  10304. MemOrderKind = C->getClauseKind();
  10305. MemOrderLoc = C->getBeginLoc();
  10306. }
  10307. break;
  10308. }
  10309. // The following clauses are allowed, but we don't need to do anything here.
  10310. case OMPC_hint:
  10311. break;
  10312. default:
  10313. llvm_unreachable("unknown clause is encountered");
  10314. }
  10315. }
  10316. // OpenMP 5.0, 2.17.7 atomic Construct, Restrictions
  10317. // If atomic-clause is read then memory-order-clause must not be acq_rel or
  10318. // release.
  10319. // If atomic-clause is write then memory-order-clause must not be acq_rel or
  10320. // acquire.
  10321. // If atomic-clause is update or not present then memory-order-clause must not
  10322. // be acq_rel or acquire.
  10323. if ((AtomicKind == OMPC_read &&
  10324. (MemOrderKind == OMPC_acq_rel || MemOrderKind == OMPC_release)) ||
  10325. ((AtomicKind == OMPC_write || AtomicKind == OMPC_update ||
  10326. AtomicKind == OMPC_unknown) &&
  10327. (MemOrderKind == OMPC_acq_rel || MemOrderKind == OMPC_acquire))) {
  10328. SourceLocation Loc = AtomicKindLoc;
  10329. if (AtomicKind == OMPC_unknown)
  10330. Loc = StartLoc;
  10331. Diag(Loc, diag::err_omp_atomic_incompatible_mem_order_clause)
  10332. << getOpenMPClauseName(AtomicKind)
  10333. << (AtomicKind == OMPC_unknown ? 1 : 0)
  10334. << getOpenMPClauseName(MemOrderKind);
  10335. Diag(MemOrderLoc, diag::note_omp_previous_mem_order_clause)
  10336. << getOpenMPClauseName(MemOrderKind);
  10337. }
  10338. Stmt *Body = AStmt;
  10339. if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
  10340. Body = EWC->getSubExpr();
  10341. Expr *X = nullptr;
  10342. Expr *V = nullptr;
  10343. Expr *E = nullptr;
  10344. Expr *UE = nullptr;
  10345. bool IsXLHSInRHSPart = false;
  10346. bool IsPostfixUpdate = false;
  10347. // OpenMP [2.12.6, atomic Construct]
  10348. // In the next expressions:
  10349. // * x and v (as applicable) are both l-value expressions with scalar type.
  10350. // * During the execution of an atomic region, multiple syntactic
  10351. // occurrences of x must designate the same storage location.
  10352. // * Neither of v and expr (as applicable) may access the storage location
  10353. // designated by x.
  10354. // * Neither of x and expr (as applicable) may access the storage location
  10355. // designated by v.
  10356. // * expr is an expression with scalar type.
  10357. // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
  10358. // * binop, binop=, ++, and -- are not overloaded operators.
  10359. // * The expression x binop expr must be numerically equivalent to x binop
  10360. // (expr). This requirement is satisfied if the operators in expr have
  10361. // precedence greater than binop, or by using parentheses around expr or
  10362. // subexpressions of expr.
  10363. // * The expression expr binop x must be numerically equivalent to (expr)
  10364. // binop x. This requirement is satisfied if the operators in expr have
  10365. // precedence equal to or greater than binop, or by using parentheses around
  10366. // expr or subexpressions of expr.
  10367. // * For forms that allow multiple occurrences of x, the number of times
  10368. // that x is evaluated is unspecified.
  10369. if (AtomicKind == OMPC_read) {
  10370. enum {
  10371. NotAnExpression,
  10372. NotAnAssignmentOp,
  10373. NotAScalarType,
  10374. NotAnLValue,
  10375. NoError
  10376. } ErrorFound = NoError;
  10377. SourceLocation ErrorLoc, NoteLoc;
  10378. SourceRange ErrorRange, NoteRange;
  10379. // If clause is read:
  10380. // v = x;
  10381. if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
  10382. const auto *AtomicBinOp =
  10383. dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
  10384. if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
  10385. X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
  10386. V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
  10387. if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
  10388. (V->isInstantiationDependent() || V->getType()->isScalarType())) {
  10389. if (!X->isLValue() || !V->isLValue()) {
  10390. const Expr *NotLValueExpr = X->isLValue() ? V : X;
  10391. ErrorFound = NotAnLValue;
  10392. ErrorLoc = AtomicBinOp->getExprLoc();
  10393. ErrorRange = AtomicBinOp->getSourceRange();
  10394. NoteLoc = NotLValueExpr->getExprLoc();
  10395. NoteRange = NotLValueExpr->getSourceRange();
  10396. }
  10397. } else if (!X->isInstantiationDependent() ||
  10398. !V->isInstantiationDependent()) {
  10399. const Expr *NotScalarExpr =
  10400. (X->isInstantiationDependent() || X->getType()->isScalarType())
  10401. ? V
  10402. : X;
  10403. ErrorFound = NotAScalarType;
  10404. ErrorLoc = AtomicBinOp->getExprLoc();
  10405. ErrorRange = AtomicBinOp->getSourceRange();
  10406. NoteLoc = NotScalarExpr->getExprLoc();
  10407. NoteRange = NotScalarExpr->getSourceRange();
  10408. }
  10409. } else if (!AtomicBody->isInstantiationDependent()) {
  10410. ErrorFound = NotAnAssignmentOp;
  10411. ErrorLoc = AtomicBody->getExprLoc();
  10412. ErrorRange = AtomicBody->getSourceRange();
  10413. NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
  10414. : AtomicBody->getExprLoc();
  10415. NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
  10416. : AtomicBody->getSourceRange();
  10417. }
  10418. } else {
  10419. ErrorFound = NotAnExpression;
  10420. NoteLoc = ErrorLoc = Body->getBeginLoc();
  10421. NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
  10422. }
  10423. if (ErrorFound != NoError) {
  10424. Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
  10425. << ErrorRange;
  10426. Diag(NoteLoc, diag::note_omp_atomic_read_write)
  10427. << ErrorFound << NoteRange;
  10428. return StmtError();
  10429. }
  10430. if (CurContext->isDependentContext())
  10431. V = X = nullptr;
  10432. } else if (AtomicKind == OMPC_write) {
  10433. enum {
  10434. NotAnExpression,
  10435. NotAnAssignmentOp,
  10436. NotAScalarType,
  10437. NotAnLValue,
  10438. NoError
  10439. } ErrorFound = NoError;
  10440. SourceLocation ErrorLoc, NoteLoc;
  10441. SourceRange ErrorRange, NoteRange;
  10442. // If clause is write:
  10443. // x = expr;
  10444. if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
  10445. const auto *AtomicBinOp =
  10446. dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
  10447. if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
  10448. X = AtomicBinOp->getLHS();
  10449. E = AtomicBinOp->getRHS();
  10450. if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
  10451. (E->isInstantiationDependent() || E->getType()->isScalarType())) {
  10452. if (!X->isLValue()) {
  10453. ErrorFound = NotAnLValue;
  10454. ErrorLoc = AtomicBinOp->getExprLoc();
  10455. ErrorRange = AtomicBinOp->getSourceRange();
  10456. NoteLoc = X->getExprLoc();
  10457. NoteRange = X->getSourceRange();
  10458. }
  10459. } else if (!X->isInstantiationDependent() ||
  10460. !E->isInstantiationDependent()) {
  10461. const Expr *NotScalarExpr =
  10462. (X->isInstantiationDependent() || X->getType()->isScalarType())
  10463. ? E
  10464. : X;
  10465. ErrorFound = NotAScalarType;
  10466. ErrorLoc = AtomicBinOp->getExprLoc();
  10467. ErrorRange = AtomicBinOp->getSourceRange();
  10468. NoteLoc = NotScalarExpr->getExprLoc();
  10469. NoteRange = NotScalarExpr->getSourceRange();
  10470. }
  10471. } else if (!AtomicBody->isInstantiationDependent()) {
  10472. ErrorFound = NotAnAssignmentOp;
  10473. ErrorLoc = AtomicBody->getExprLoc();
  10474. ErrorRange = AtomicBody->getSourceRange();
  10475. NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
  10476. : AtomicBody->getExprLoc();
  10477. NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
  10478. : AtomicBody->getSourceRange();
  10479. }
  10480. } else {
  10481. ErrorFound = NotAnExpression;
  10482. NoteLoc = ErrorLoc = Body->getBeginLoc();
  10483. NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
  10484. }
  10485. if (ErrorFound != NoError) {
  10486. Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
  10487. << ErrorRange;
  10488. Diag(NoteLoc, diag::note_omp_atomic_read_write)
  10489. << ErrorFound << NoteRange;
  10490. return StmtError();
  10491. }
  10492. if (CurContext->isDependentContext())
  10493. E = X = nullptr;
  10494. } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
  10495. // If clause is update:
  10496. // x++;
  10497. // x--;
  10498. // ++x;
  10499. // --x;
  10500. // x binop= expr;
  10501. // x = x binop expr;
  10502. // x = expr binop x;
  10503. OpenMPAtomicUpdateChecker Checker(*this);
  10504. if (Checker.checkStatement(
  10505. Body,
  10506. (AtomicKind == OMPC_update)
  10507. ? diag::err_omp_atomic_update_not_expression_statement
  10508. : diag::err_omp_atomic_not_expression_statement,
  10509. diag::note_omp_atomic_update))
  10510. return StmtError();
  10511. if (!CurContext->isDependentContext()) {
  10512. E = Checker.getExpr();
  10513. X = Checker.getX();
  10514. UE = Checker.getUpdateExpr();
  10515. IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
  10516. }
  10517. } else if (AtomicKind == OMPC_capture) {
  10518. enum {
  10519. NotAnAssignmentOp,
  10520. NotACompoundStatement,
  10521. NotTwoSubstatements,
  10522. NotASpecificExpression,
  10523. NoError
  10524. } ErrorFound = NoError;
  10525. SourceLocation ErrorLoc, NoteLoc;
  10526. SourceRange ErrorRange, NoteRange;
  10527. if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
  10528. // If clause is a capture:
  10529. // v = x++;
  10530. // v = x--;
  10531. // v = ++x;
  10532. // v = --x;
  10533. // v = x binop= expr;
  10534. // v = x = x binop expr;
  10535. // v = x = expr binop x;
  10536. const auto *AtomicBinOp =
  10537. dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
  10538. if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
  10539. V = AtomicBinOp->getLHS();
  10540. Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
  10541. OpenMPAtomicUpdateChecker Checker(*this);
  10542. if (Checker.checkStatement(
  10543. Body, diag::err_omp_atomic_capture_not_expression_statement,
  10544. diag::note_omp_atomic_update))
  10545. return StmtError();
  10546. E = Checker.getExpr();
  10547. X = Checker.getX();
  10548. UE = Checker.getUpdateExpr();
  10549. IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
  10550. IsPostfixUpdate = Checker.isPostfixUpdate();
  10551. } else if (!AtomicBody->isInstantiationDependent()) {
  10552. ErrorLoc = AtomicBody->getExprLoc();
  10553. ErrorRange = AtomicBody->getSourceRange();
  10554. NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
  10555. : AtomicBody->getExprLoc();
  10556. NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
  10557. : AtomicBody->getSourceRange();
  10558. ErrorFound = NotAnAssignmentOp;
  10559. }
  10560. if (ErrorFound != NoError) {
  10561. Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
  10562. << ErrorRange;
  10563. Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
  10564. return StmtError();
  10565. }
  10566. if (CurContext->isDependentContext())
  10567. UE = V = E = X = nullptr;
  10568. } else {
  10569. // If clause is a capture:
  10570. // { v = x; x = expr; }
  10571. // { v = x; x++; }
  10572. // { v = x; x--; }
  10573. // { v = x; ++x; }
  10574. // { v = x; --x; }
  10575. // { v = x; x binop= expr; }
  10576. // { v = x; x = x binop expr; }
  10577. // { v = x; x = expr binop x; }
  10578. // { x++; v = x; }
  10579. // { x--; v = x; }
  10580. // { ++x; v = x; }
  10581. // { --x; v = x; }
  10582. // { x binop= expr; v = x; }
  10583. // { x = x binop expr; v = x; }
  10584. // { x = expr binop x; v = x; }
  10585. if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
  10586. // Check that this is { expr1; expr2; }
  10587. if (CS->size() == 2) {
  10588. Stmt *First = CS->body_front();
  10589. Stmt *Second = CS->body_back();
  10590. if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
  10591. First = EWC->getSubExpr()->IgnoreParenImpCasts();
  10592. if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
  10593. Second = EWC->getSubExpr()->IgnoreParenImpCasts();
  10594. // Need to find what subexpression is 'v' and what is 'x'.
  10595. OpenMPAtomicUpdateChecker Checker(*this);
  10596. bool IsUpdateExprFound = !Checker.checkStatement(Second);
  10597. BinaryOperator *BinOp = nullptr;
  10598. if (IsUpdateExprFound) {
  10599. BinOp = dyn_cast<BinaryOperator>(First);
  10600. IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
  10601. }
  10602. if (IsUpdateExprFound && !CurContext->isDependentContext()) {
  10603. // { v = x; x++; }
  10604. // { v = x; x--; }
  10605. // { v = x; ++x; }
  10606. // { v = x; --x; }
  10607. // { v = x; x binop= expr; }
  10608. // { v = x; x = x binop expr; }
  10609. // { v = x; x = expr binop x; }
  10610. // Check that the first expression has form v = x.
  10611. Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
  10612. llvm::FoldingSetNodeID XId, PossibleXId;
  10613. Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
  10614. PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
  10615. IsUpdateExprFound = XId == PossibleXId;
  10616. if (IsUpdateExprFound) {
  10617. V = BinOp->getLHS();
  10618. X = Checker.getX();
  10619. E = Checker.getExpr();
  10620. UE = Checker.getUpdateExpr();
  10621. IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
  10622. IsPostfixUpdate = true;
  10623. }
  10624. }
  10625. if (!IsUpdateExprFound) {
  10626. IsUpdateExprFound = !Checker.checkStatement(First);
  10627. BinOp = nullptr;
  10628. if (IsUpdateExprFound) {
  10629. BinOp = dyn_cast<BinaryOperator>(Second);
  10630. IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
  10631. }
  10632. if (IsUpdateExprFound && !CurContext->isDependentContext()) {
  10633. // { x++; v = x; }
  10634. // { x--; v = x; }
  10635. // { ++x; v = x; }
  10636. // { --x; v = x; }
  10637. // { x binop= expr; v = x; }
  10638. // { x = x binop expr; v = x; }
  10639. // { x = expr binop x; v = x; }
  10640. // Check that the second expression has form v = x.
  10641. Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
  10642. llvm::FoldingSetNodeID XId, PossibleXId;
  10643. Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
  10644. PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
  10645. IsUpdateExprFound = XId == PossibleXId;
  10646. if (IsUpdateExprFound) {
  10647. V = BinOp->getLHS();
  10648. X = Checker.getX();
  10649. E = Checker.getExpr();
  10650. UE = Checker.getUpdateExpr();
  10651. IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
  10652. IsPostfixUpdate = false;
  10653. }
  10654. }
  10655. }
  10656. if (!IsUpdateExprFound) {
  10657. // { v = x; x = expr; }
  10658. auto *FirstExpr = dyn_cast<Expr>(First);
  10659. auto *SecondExpr = dyn_cast<Expr>(Second);
  10660. if (!FirstExpr || !SecondExpr ||
  10661. !(FirstExpr->isInstantiationDependent() ||
  10662. SecondExpr->isInstantiationDependent())) {
  10663. auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
  10664. if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
  10665. ErrorFound = NotAnAssignmentOp;
  10666. NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
  10667. : First->getBeginLoc();
  10668. NoteRange = ErrorRange = FirstBinOp
  10669. ? FirstBinOp->getSourceRange()
  10670. : SourceRange(ErrorLoc, ErrorLoc);
  10671. } else {
  10672. auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
  10673. if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
  10674. ErrorFound = NotAnAssignmentOp;
  10675. NoteLoc = ErrorLoc = SecondBinOp
  10676. ? SecondBinOp->getOperatorLoc()
  10677. : Second->getBeginLoc();
  10678. NoteRange = ErrorRange =
  10679. SecondBinOp ? SecondBinOp->getSourceRange()
  10680. : SourceRange(ErrorLoc, ErrorLoc);
  10681. } else {
  10682. Expr *PossibleXRHSInFirst =
  10683. FirstBinOp->getRHS()->IgnoreParenImpCasts();
  10684. Expr *PossibleXLHSInSecond =
  10685. SecondBinOp->getLHS()->IgnoreParenImpCasts();
  10686. llvm::FoldingSetNodeID X1Id, X2Id;
  10687. PossibleXRHSInFirst->Profile(X1Id, Context,
  10688. /*Canonical=*/true);
  10689. PossibleXLHSInSecond->Profile(X2Id, Context,
  10690. /*Canonical=*/true);
  10691. IsUpdateExprFound = X1Id == X2Id;
  10692. if (IsUpdateExprFound) {
  10693. V = FirstBinOp->getLHS();
  10694. X = SecondBinOp->getLHS();
  10695. E = SecondBinOp->getRHS();
  10696. UE = nullptr;
  10697. IsXLHSInRHSPart = false;
  10698. IsPostfixUpdate = true;
  10699. } else {
  10700. ErrorFound = NotASpecificExpression;
  10701. ErrorLoc = FirstBinOp->getExprLoc();
  10702. ErrorRange = FirstBinOp->getSourceRange();
  10703. NoteLoc = SecondBinOp->getLHS()->getExprLoc();
  10704. NoteRange = SecondBinOp->getRHS()->getSourceRange();
  10705. }
  10706. }
  10707. }
  10708. }
  10709. }
  10710. } else {
  10711. NoteLoc = ErrorLoc = Body->getBeginLoc();
  10712. NoteRange = ErrorRange =
  10713. SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
  10714. ErrorFound = NotTwoSubstatements;
  10715. }
  10716. } else {
  10717. NoteLoc = ErrorLoc = Body->getBeginLoc();
  10718. NoteRange = ErrorRange =
  10719. SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
  10720. ErrorFound = NotACompoundStatement;
  10721. }
  10722. }
  10723. if (ErrorFound != NoError) {
  10724. Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
  10725. << ErrorRange;
  10726. Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
  10727. return StmtError();
  10728. }
  10729. if (CurContext->isDependentContext())
  10730. UE = V = E = X = nullptr;
  10731. } else if (AtomicKind == OMPC_compare) {
  10732. // TODO: For now we emit an error here and in emitOMPAtomicExpr we ignore
  10733. // code gen.
  10734. unsigned DiagID = Diags.getCustomDiagID(
  10735. DiagnosticsEngine::Error, "atomic compare is not supported for now");
  10736. Diag(AtomicKindLoc, DiagID);
  10737. }
  10738. setFunctionHasBranchProtectedScope();
  10739. return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
  10740. X, V, E, UE, IsXLHSInRHSPart,
  10741. IsPostfixUpdate);
  10742. }
  10743. StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
  10744. Stmt *AStmt,
  10745. SourceLocation StartLoc,
  10746. SourceLocation EndLoc) {
  10747. if (!AStmt)
  10748. return StmtError();
  10749. auto *CS = cast<CapturedStmt>(AStmt);
  10750. // 1.2.2 OpenMP Language Terminology
  10751. // Structured block - An executable statement with a single entry at the
  10752. // top and a single exit at the bottom.
  10753. // The point of exit cannot be a branch out of the structured block.
  10754. // longjmp() and throw() must not violate the entry/exit criteria.
  10755. CS->getCapturedDecl()->setNothrow();
  10756. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target);
  10757. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  10758. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  10759. // 1.2.2 OpenMP Language Terminology
  10760. // Structured block - An executable statement with a single entry at the
  10761. // top and a single exit at the bottom.
  10762. // The point of exit cannot be a branch out of the structured block.
  10763. // longjmp() and throw() must not violate the entry/exit criteria.
  10764. CS->getCapturedDecl()->setNothrow();
  10765. }
  10766. // OpenMP [2.16, Nesting of Regions]
  10767. // If specified, a teams construct must be contained within a target
  10768. // construct. That target construct must contain no statements or directives
  10769. // outside of the teams construct.
  10770. if (DSAStack->hasInnerTeamsRegion()) {
  10771. const Stmt *S = CS->IgnoreContainers(/*IgnoreCaptured=*/true);
  10772. bool OMPTeamsFound = true;
  10773. if (const auto *CS = dyn_cast<CompoundStmt>(S)) {
  10774. auto I = CS->body_begin();
  10775. while (I != CS->body_end()) {
  10776. const auto *OED = dyn_cast<OMPExecutableDirective>(*I);
  10777. if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind()) ||
  10778. OMPTeamsFound) {
  10779. OMPTeamsFound = false;
  10780. break;
  10781. }
  10782. ++I;
  10783. }
  10784. assert(I != CS->body_end() && "Not found statement");
  10785. S = *I;
  10786. } else {
  10787. const auto *OED = dyn_cast<OMPExecutableDirective>(S);
  10788. OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
  10789. }
  10790. if (!OMPTeamsFound) {
  10791. Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
  10792. Diag(DSAStack->getInnerTeamsRegionLoc(),
  10793. diag::note_omp_nested_teams_construct_here);
  10794. Diag(S->getBeginLoc(), diag::note_omp_nested_statement_here)
  10795. << isa<OMPExecutableDirective>(S);
  10796. return StmtError();
  10797. }
  10798. }
  10799. setFunctionHasBranchProtectedScope();
  10800. return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
  10801. }
  10802. StmtResult
  10803. Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
  10804. Stmt *AStmt, SourceLocation StartLoc,
  10805. SourceLocation EndLoc) {
  10806. if (!AStmt)
  10807. return StmtError();
  10808. auto *CS = cast<CapturedStmt>(AStmt);
  10809. // 1.2.2 OpenMP Language Terminology
  10810. // Structured block - An executable statement with a single entry at the
  10811. // top and a single exit at the bottom.
  10812. // The point of exit cannot be a branch out of the structured block.
  10813. // longjmp() and throw() must not violate the entry/exit criteria.
  10814. CS->getCapturedDecl()->setNothrow();
  10815. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel);
  10816. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  10817. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  10818. // 1.2.2 OpenMP Language Terminology
  10819. // Structured block - An executable statement with a single entry at the
  10820. // top and a single exit at the bottom.
  10821. // The point of exit cannot be a branch out of the structured block.
  10822. // longjmp() and throw() must not violate the entry/exit criteria.
  10823. CS->getCapturedDecl()->setNothrow();
  10824. }
  10825. setFunctionHasBranchProtectedScope();
  10826. return OMPTargetParallelDirective::Create(
  10827. Context, StartLoc, EndLoc, Clauses, AStmt,
  10828. DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
  10829. }
  10830. StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
  10831. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  10832. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  10833. if (!AStmt)
  10834. return StmtError();
  10835. auto *CS = cast<CapturedStmt>(AStmt);
  10836. // 1.2.2 OpenMP Language Terminology
  10837. // Structured block - An executable statement with a single entry at the
  10838. // top and a single exit at the bottom.
  10839. // The point of exit cannot be a branch out of the structured block.
  10840. // longjmp() and throw() must not violate the entry/exit criteria.
  10841. CS->getCapturedDecl()->setNothrow();
  10842. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
  10843. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  10844. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  10845. // 1.2.2 OpenMP Language Terminology
  10846. // Structured block - An executable statement with a single entry at the
  10847. // top and a single exit at the bottom.
  10848. // The point of exit cannot be a branch out of the structured block.
  10849. // longjmp() and throw() must not violate the entry/exit criteria.
  10850. CS->getCapturedDecl()->setNothrow();
  10851. }
  10852. OMPLoopBasedDirective::HelperExprs B;
  10853. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  10854. // define the nested loops number.
  10855. unsigned NestedLoopCount =
  10856. checkOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
  10857. getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
  10858. VarsWithImplicitDSA, B);
  10859. if (NestedLoopCount == 0)
  10860. return StmtError();
  10861. assert((CurContext->isDependentContext() || B.builtAll()) &&
  10862. "omp target parallel for loop exprs were not built");
  10863. if (!CurContext->isDependentContext()) {
  10864. // Finalize the clauses that need pre-built expressions for CodeGen.
  10865. for (OMPClause *C : Clauses) {
  10866. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  10867. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  10868. B.NumIterations, *this, CurScope,
  10869. DSAStack))
  10870. return StmtError();
  10871. }
  10872. }
  10873. setFunctionHasBranchProtectedScope();
  10874. return OMPTargetParallelForDirective::Create(
  10875. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
  10876. DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
  10877. }
  10878. /// Check for existence of a map clause in the list of clauses.
  10879. static bool hasClauses(ArrayRef<OMPClause *> Clauses,
  10880. const OpenMPClauseKind K) {
  10881. return llvm::any_of(
  10882. Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; });
  10883. }
  10884. template <typename... Params>
  10885. static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K,
  10886. const Params... ClauseTypes) {
  10887. return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...);
  10888. }
  10889. StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
  10890. Stmt *AStmt,
  10891. SourceLocation StartLoc,
  10892. SourceLocation EndLoc) {
  10893. if (!AStmt)
  10894. return StmtError();
  10895. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  10896. // OpenMP [2.12.2, target data Construct, Restrictions]
  10897. // At least one map, use_device_addr or use_device_ptr clause must appear on
  10898. // the directive.
  10899. if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr) &&
  10900. (LangOpts.OpenMP < 50 || !hasClauses(Clauses, OMPC_use_device_addr))) {
  10901. StringRef Expected;
  10902. if (LangOpts.OpenMP < 50)
  10903. Expected = "'map' or 'use_device_ptr'";
  10904. else
  10905. Expected = "'map', 'use_device_ptr', or 'use_device_addr'";
  10906. Diag(StartLoc, diag::err_omp_no_clause_for_directive)
  10907. << Expected << getOpenMPDirectiveName(OMPD_target_data);
  10908. return StmtError();
  10909. }
  10910. setFunctionHasBranchProtectedScope();
  10911. return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
  10912. AStmt);
  10913. }
  10914. StmtResult
  10915. Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
  10916. SourceLocation StartLoc,
  10917. SourceLocation EndLoc, Stmt *AStmt) {
  10918. if (!AStmt)
  10919. return StmtError();
  10920. auto *CS = cast<CapturedStmt>(AStmt);
  10921. // 1.2.2 OpenMP Language Terminology
  10922. // Structured block - An executable statement with a single entry at the
  10923. // top and a single exit at the bottom.
  10924. // The point of exit cannot be a branch out of the structured block.
  10925. // longjmp() and throw() must not violate the entry/exit criteria.
  10926. CS->getCapturedDecl()->setNothrow();
  10927. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_enter_data);
  10928. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  10929. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  10930. // 1.2.2 OpenMP Language Terminology
  10931. // Structured block - An executable statement with a single entry at the
  10932. // top and a single exit at the bottom.
  10933. // The point of exit cannot be a branch out of the structured block.
  10934. // longjmp() and throw() must not violate the entry/exit criteria.
  10935. CS->getCapturedDecl()->setNothrow();
  10936. }
  10937. // OpenMP [2.10.2, Restrictions, p. 99]
  10938. // At least one map clause must appear on the directive.
  10939. if (!hasClauses(Clauses, OMPC_map)) {
  10940. Diag(StartLoc, diag::err_omp_no_clause_for_directive)
  10941. << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data);
  10942. return StmtError();
  10943. }
  10944. return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
  10945. AStmt);
  10946. }
  10947. StmtResult
  10948. Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
  10949. SourceLocation StartLoc,
  10950. SourceLocation EndLoc, Stmt *AStmt) {
  10951. if (!AStmt)
  10952. return StmtError();
  10953. auto *CS = cast<CapturedStmt>(AStmt);
  10954. // 1.2.2 OpenMP Language Terminology
  10955. // Structured block - An executable statement with a single entry at the
  10956. // top and a single exit at the bottom.
  10957. // The point of exit cannot be a branch out of the structured block.
  10958. // longjmp() and throw() must not violate the entry/exit criteria.
  10959. CS->getCapturedDecl()->setNothrow();
  10960. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_exit_data);
  10961. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  10962. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  10963. // 1.2.2 OpenMP Language Terminology
  10964. // Structured block - An executable statement with a single entry at the
  10965. // top and a single exit at the bottom.
  10966. // The point of exit cannot be a branch out of the structured block.
  10967. // longjmp() and throw() must not violate the entry/exit criteria.
  10968. CS->getCapturedDecl()->setNothrow();
  10969. }
  10970. // OpenMP [2.10.3, Restrictions, p. 102]
  10971. // At least one map clause must appear on the directive.
  10972. if (!hasClauses(Clauses, OMPC_map)) {
  10973. Diag(StartLoc, diag::err_omp_no_clause_for_directive)
  10974. << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data);
  10975. return StmtError();
  10976. }
  10977. return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
  10978. AStmt);
  10979. }
  10980. StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
  10981. SourceLocation StartLoc,
  10982. SourceLocation EndLoc,
  10983. Stmt *AStmt) {
  10984. if (!AStmt)
  10985. return StmtError();
  10986. auto *CS = cast<CapturedStmt>(AStmt);
  10987. // 1.2.2 OpenMP Language Terminology
  10988. // Structured block - An executable statement with a single entry at the
  10989. // top and a single exit at the bottom.
  10990. // The point of exit cannot be a branch out of the structured block.
  10991. // longjmp() and throw() must not violate the entry/exit criteria.
  10992. CS->getCapturedDecl()->setNothrow();
  10993. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_update);
  10994. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  10995. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  10996. // 1.2.2 OpenMP Language Terminology
  10997. // Structured block - An executable statement with a single entry at the
  10998. // top and a single exit at the bottom.
  10999. // The point of exit cannot be a branch out of the structured block.
  11000. // longjmp() and throw() must not violate the entry/exit criteria.
  11001. CS->getCapturedDecl()->setNothrow();
  11002. }
  11003. if (!hasClauses(Clauses, OMPC_to, OMPC_from)) {
  11004. Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
  11005. return StmtError();
  11006. }
  11007. return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses,
  11008. AStmt);
  11009. }
  11010. StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
  11011. Stmt *AStmt, SourceLocation StartLoc,
  11012. SourceLocation EndLoc) {
  11013. if (!AStmt)
  11014. return StmtError();
  11015. auto *CS = cast<CapturedStmt>(AStmt);
  11016. // 1.2.2 OpenMP Language Terminology
  11017. // Structured block - An executable statement with a single entry at the
  11018. // top and a single exit at the bottom.
  11019. // The point of exit cannot be a branch out of the structured block.
  11020. // longjmp() and throw() must not violate the entry/exit criteria.
  11021. CS->getCapturedDecl()->setNothrow();
  11022. setFunctionHasBranchProtectedScope();
  11023. DSAStack->setParentTeamsRegionLoc(StartLoc);
  11024. return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
  11025. }
  11026. StmtResult
  11027. Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
  11028. SourceLocation EndLoc,
  11029. OpenMPDirectiveKind CancelRegion) {
  11030. if (DSAStack->isParentNowaitRegion()) {
  11031. Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
  11032. return StmtError();
  11033. }
  11034. if (DSAStack->isParentOrderedRegion()) {
  11035. Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
  11036. return StmtError();
  11037. }
  11038. return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
  11039. CancelRegion);
  11040. }
  11041. StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
  11042. SourceLocation StartLoc,
  11043. SourceLocation EndLoc,
  11044. OpenMPDirectiveKind CancelRegion) {
  11045. if (DSAStack->isParentNowaitRegion()) {
  11046. Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
  11047. return StmtError();
  11048. }
  11049. if (DSAStack->isParentOrderedRegion()) {
  11050. Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
  11051. return StmtError();
  11052. }
  11053. DSAStack->setParentCancelRegion(/*Cancel=*/true);
  11054. return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
  11055. CancelRegion);
  11056. }
  11057. static bool checkReductionClauseWithNogroup(Sema &S,
  11058. ArrayRef<OMPClause *> Clauses) {
  11059. const OMPClause *ReductionClause = nullptr;
  11060. const OMPClause *NogroupClause = nullptr;
  11061. for (const OMPClause *C : Clauses) {
  11062. if (C->getClauseKind() == OMPC_reduction) {
  11063. ReductionClause = C;
  11064. if (NogroupClause)
  11065. break;
  11066. continue;
  11067. }
  11068. if (C->getClauseKind() == OMPC_nogroup) {
  11069. NogroupClause = C;
  11070. if (ReductionClause)
  11071. break;
  11072. continue;
  11073. }
  11074. }
  11075. if (ReductionClause && NogroupClause) {
  11076. S.Diag(ReductionClause->getBeginLoc(), diag::err_omp_reduction_with_nogroup)
  11077. << SourceRange(NogroupClause->getBeginLoc(),
  11078. NogroupClause->getEndLoc());
  11079. return true;
  11080. }
  11081. return false;
  11082. }
  11083. StmtResult Sema::ActOnOpenMPTaskLoopDirective(
  11084. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  11085. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  11086. if (!AStmt)
  11087. return StmtError();
  11088. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  11089. OMPLoopBasedDirective::HelperExprs B;
  11090. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  11091. // define the nested loops number.
  11092. unsigned NestedLoopCount =
  11093. checkOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
  11094. /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
  11095. VarsWithImplicitDSA, B);
  11096. if (NestedLoopCount == 0)
  11097. return StmtError();
  11098. assert((CurContext->isDependentContext() || B.builtAll()) &&
  11099. "omp for loop exprs were not built");
  11100. // OpenMP, [2.9.2 taskloop Construct, Restrictions]
  11101. // The grainsize clause and num_tasks clause are mutually exclusive and may
  11102. // not appear on the same taskloop directive.
  11103. if (checkMutuallyExclusiveClauses(*this, Clauses,
  11104. {OMPC_grainsize, OMPC_num_tasks}))
  11105. return StmtError();
  11106. // OpenMP, [2.9.2 taskloop Construct, Restrictions]
  11107. // If a reduction clause is present on the taskloop directive, the nogroup
  11108. // clause must not be specified.
  11109. if (checkReductionClauseWithNogroup(*this, Clauses))
  11110. return StmtError();
  11111. setFunctionHasBranchProtectedScope();
  11112. return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
  11113. NestedLoopCount, Clauses, AStmt, B,
  11114. DSAStack->isCancelRegion());
  11115. }
  11116. StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
  11117. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  11118. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  11119. if (!AStmt)
  11120. return StmtError();
  11121. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  11122. OMPLoopBasedDirective::HelperExprs B;
  11123. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  11124. // define the nested loops number.
  11125. unsigned NestedLoopCount =
  11126. checkOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
  11127. /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
  11128. VarsWithImplicitDSA, B);
  11129. if (NestedLoopCount == 0)
  11130. return StmtError();
  11131. assert((CurContext->isDependentContext() || B.builtAll()) &&
  11132. "omp for loop exprs were not built");
  11133. if (!CurContext->isDependentContext()) {
  11134. // Finalize the clauses that need pre-built expressions for CodeGen.
  11135. for (OMPClause *C : Clauses) {
  11136. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  11137. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  11138. B.NumIterations, *this, CurScope,
  11139. DSAStack))
  11140. return StmtError();
  11141. }
  11142. }
  11143. // OpenMP, [2.9.2 taskloop Construct, Restrictions]
  11144. // The grainsize clause and num_tasks clause are mutually exclusive and may
  11145. // not appear on the same taskloop directive.
  11146. if (checkMutuallyExclusiveClauses(*this, Clauses,
  11147. {OMPC_grainsize, OMPC_num_tasks}))
  11148. return StmtError();
  11149. // OpenMP, [2.9.2 taskloop Construct, Restrictions]
  11150. // If a reduction clause is present on the taskloop directive, the nogroup
  11151. // clause must not be specified.
  11152. if (checkReductionClauseWithNogroup(*this, Clauses))
  11153. return StmtError();
  11154. if (checkSimdlenSafelenSpecified(*this, Clauses))
  11155. return StmtError();
  11156. setFunctionHasBranchProtectedScope();
  11157. return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
  11158. NestedLoopCount, Clauses, AStmt, B);
  11159. }
  11160. StmtResult Sema::ActOnOpenMPMasterTaskLoopDirective(
  11161. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  11162. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  11163. if (!AStmt)
  11164. return StmtError();
  11165. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  11166. OMPLoopBasedDirective::HelperExprs B;
  11167. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  11168. // define the nested loops number.
  11169. unsigned NestedLoopCount =
  11170. checkOpenMPLoop(OMPD_master_taskloop, getCollapseNumberExpr(Clauses),
  11171. /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
  11172. VarsWithImplicitDSA, B);
  11173. if (NestedLoopCount == 0)
  11174. return StmtError();
  11175. assert((CurContext->isDependentContext() || B.builtAll()) &&
  11176. "omp for loop exprs were not built");
  11177. // OpenMP, [2.9.2 taskloop Construct, Restrictions]
  11178. // The grainsize clause and num_tasks clause are mutually exclusive and may
  11179. // not appear on the same taskloop directive.
  11180. if (checkMutuallyExclusiveClauses(*this, Clauses,
  11181. {OMPC_grainsize, OMPC_num_tasks}))
  11182. return StmtError();
  11183. // OpenMP, [2.9.2 taskloop Construct, Restrictions]
  11184. // If a reduction clause is present on the taskloop directive, the nogroup
  11185. // clause must not be specified.
  11186. if (checkReductionClauseWithNogroup(*this, Clauses))
  11187. return StmtError();
  11188. setFunctionHasBranchProtectedScope();
  11189. return OMPMasterTaskLoopDirective::Create(Context, StartLoc, EndLoc,
  11190. NestedLoopCount, Clauses, AStmt, B,
  11191. DSAStack->isCancelRegion());
  11192. }
  11193. StmtResult Sema::ActOnOpenMPMasterTaskLoopSimdDirective(
  11194. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  11195. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  11196. if (!AStmt)
  11197. return StmtError();
  11198. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  11199. OMPLoopBasedDirective::HelperExprs B;
  11200. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  11201. // define the nested loops number.
  11202. unsigned NestedLoopCount =
  11203. checkOpenMPLoop(OMPD_master_taskloop_simd, getCollapseNumberExpr(Clauses),
  11204. /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
  11205. VarsWithImplicitDSA, B);
  11206. if (NestedLoopCount == 0)
  11207. return StmtError();
  11208. assert((CurContext->isDependentContext() || B.builtAll()) &&
  11209. "omp for loop exprs were not built");
  11210. if (!CurContext->isDependentContext()) {
  11211. // Finalize the clauses that need pre-built expressions for CodeGen.
  11212. for (OMPClause *C : Clauses) {
  11213. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  11214. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  11215. B.NumIterations, *this, CurScope,
  11216. DSAStack))
  11217. return StmtError();
  11218. }
  11219. }
  11220. // OpenMP, [2.9.2 taskloop Construct, Restrictions]
  11221. // The grainsize clause and num_tasks clause are mutually exclusive and may
  11222. // not appear on the same taskloop directive.
  11223. if (checkMutuallyExclusiveClauses(*this, Clauses,
  11224. {OMPC_grainsize, OMPC_num_tasks}))
  11225. return StmtError();
  11226. // OpenMP, [2.9.2 taskloop Construct, Restrictions]
  11227. // If a reduction clause is present on the taskloop directive, the nogroup
  11228. // clause must not be specified.
  11229. if (checkReductionClauseWithNogroup(*this, Clauses))
  11230. return StmtError();
  11231. if (checkSimdlenSafelenSpecified(*this, Clauses))
  11232. return StmtError();
  11233. setFunctionHasBranchProtectedScope();
  11234. return OMPMasterTaskLoopSimdDirective::Create(
  11235. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  11236. }
  11237. StmtResult Sema::ActOnOpenMPParallelMasterTaskLoopDirective(
  11238. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  11239. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  11240. if (!AStmt)
  11241. return StmtError();
  11242. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  11243. auto *CS = cast<CapturedStmt>(AStmt);
  11244. // 1.2.2 OpenMP Language Terminology
  11245. // Structured block - An executable statement with a single entry at the
  11246. // top and a single exit at the bottom.
  11247. // The point of exit cannot be a branch out of the structured block.
  11248. // longjmp() and throw() must not violate the entry/exit criteria.
  11249. CS->getCapturedDecl()->setNothrow();
  11250. for (int ThisCaptureLevel =
  11251. getOpenMPCaptureLevels(OMPD_parallel_master_taskloop);
  11252. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  11253. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  11254. // 1.2.2 OpenMP Language Terminology
  11255. // Structured block - An executable statement with a single entry at the
  11256. // top and a single exit at the bottom.
  11257. // The point of exit cannot be a branch out of the structured block.
  11258. // longjmp() and throw() must not violate the entry/exit criteria.
  11259. CS->getCapturedDecl()->setNothrow();
  11260. }
  11261. OMPLoopBasedDirective::HelperExprs B;
  11262. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  11263. // define the nested loops number.
  11264. unsigned NestedLoopCount = checkOpenMPLoop(
  11265. OMPD_parallel_master_taskloop, getCollapseNumberExpr(Clauses),
  11266. /*OrderedLoopCountExpr=*/nullptr, CS, *this, *DSAStack,
  11267. VarsWithImplicitDSA, B);
  11268. if (NestedLoopCount == 0)
  11269. return StmtError();
  11270. assert((CurContext->isDependentContext() || B.builtAll()) &&
  11271. "omp for loop exprs were not built");
  11272. // OpenMP, [2.9.2 taskloop Construct, Restrictions]
  11273. // The grainsize clause and num_tasks clause are mutually exclusive and may
  11274. // not appear on the same taskloop directive.
  11275. if (checkMutuallyExclusiveClauses(*this, Clauses,
  11276. {OMPC_grainsize, OMPC_num_tasks}))
  11277. return StmtError();
  11278. // OpenMP, [2.9.2 taskloop Construct, Restrictions]
  11279. // If a reduction clause is present on the taskloop directive, the nogroup
  11280. // clause must not be specified.
  11281. if (checkReductionClauseWithNogroup(*this, Clauses))
  11282. return StmtError();
  11283. setFunctionHasBranchProtectedScope();
  11284. return OMPParallelMasterTaskLoopDirective::Create(
  11285. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
  11286. DSAStack->isCancelRegion());
  11287. }
  11288. StmtResult Sema::ActOnOpenMPParallelMasterTaskLoopSimdDirective(
  11289. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  11290. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  11291. if (!AStmt)
  11292. return StmtError();
  11293. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  11294. auto *CS = cast<CapturedStmt>(AStmt);
  11295. // 1.2.2 OpenMP Language Terminology
  11296. // Structured block - An executable statement with a single entry at the
  11297. // top and a single exit at the bottom.
  11298. // The point of exit cannot be a branch out of the structured block.
  11299. // longjmp() and throw() must not violate the entry/exit criteria.
  11300. CS->getCapturedDecl()->setNothrow();
  11301. for (int ThisCaptureLevel =
  11302. getOpenMPCaptureLevels(OMPD_parallel_master_taskloop_simd);
  11303. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  11304. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  11305. // 1.2.2 OpenMP Language Terminology
  11306. // Structured block - An executable statement with a single entry at the
  11307. // top and a single exit at the bottom.
  11308. // The point of exit cannot be a branch out of the structured block.
  11309. // longjmp() and throw() must not violate the entry/exit criteria.
  11310. CS->getCapturedDecl()->setNothrow();
  11311. }
  11312. OMPLoopBasedDirective::HelperExprs B;
  11313. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  11314. // define the nested loops number.
  11315. unsigned NestedLoopCount = checkOpenMPLoop(
  11316. OMPD_parallel_master_taskloop_simd, getCollapseNumberExpr(Clauses),
  11317. /*OrderedLoopCountExpr=*/nullptr, CS, *this, *DSAStack,
  11318. VarsWithImplicitDSA, B);
  11319. if (NestedLoopCount == 0)
  11320. return StmtError();
  11321. assert((CurContext->isDependentContext() || B.builtAll()) &&
  11322. "omp for loop exprs were not built");
  11323. if (!CurContext->isDependentContext()) {
  11324. // Finalize the clauses that need pre-built expressions for CodeGen.
  11325. for (OMPClause *C : Clauses) {
  11326. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  11327. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  11328. B.NumIterations, *this, CurScope,
  11329. DSAStack))
  11330. return StmtError();
  11331. }
  11332. }
  11333. // OpenMP, [2.9.2 taskloop Construct, Restrictions]
  11334. // The grainsize clause and num_tasks clause are mutually exclusive and may
  11335. // not appear on the same taskloop directive.
  11336. if (checkMutuallyExclusiveClauses(*this, Clauses,
  11337. {OMPC_grainsize, OMPC_num_tasks}))
  11338. return StmtError();
  11339. // OpenMP, [2.9.2 taskloop Construct, Restrictions]
  11340. // If a reduction clause is present on the taskloop directive, the nogroup
  11341. // clause must not be specified.
  11342. if (checkReductionClauseWithNogroup(*this, Clauses))
  11343. return StmtError();
  11344. if (checkSimdlenSafelenSpecified(*this, Clauses))
  11345. return StmtError();
  11346. setFunctionHasBranchProtectedScope();
  11347. return OMPParallelMasterTaskLoopSimdDirective::Create(
  11348. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  11349. }
  11350. StmtResult Sema::ActOnOpenMPDistributeDirective(
  11351. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  11352. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  11353. if (!AStmt)
  11354. return StmtError();
  11355. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  11356. OMPLoopBasedDirective::HelperExprs B;
  11357. // In presence of clause 'collapse' with number of loops, it will
  11358. // define the nested loops number.
  11359. unsigned NestedLoopCount =
  11360. checkOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
  11361. nullptr /*ordered not a clause on distribute*/, AStmt,
  11362. *this, *DSAStack, VarsWithImplicitDSA, B);
  11363. if (NestedLoopCount == 0)
  11364. return StmtError();
  11365. assert((CurContext->isDependentContext() || B.builtAll()) &&
  11366. "omp for loop exprs were not built");
  11367. setFunctionHasBranchProtectedScope();
  11368. return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
  11369. NestedLoopCount, Clauses, AStmt, B);
  11370. }
  11371. StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
  11372. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  11373. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  11374. if (!AStmt)
  11375. return StmtError();
  11376. auto *CS = cast<CapturedStmt>(AStmt);
  11377. // 1.2.2 OpenMP Language Terminology
  11378. // Structured block - An executable statement with a single entry at the
  11379. // top and a single exit at the bottom.
  11380. // The point of exit cannot be a branch out of the structured block.
  11381. // longjmp() and throw() must not violate the entry/exit criteria.
  11382. CS->getCapturedDecl()->setNothrow();
  11383. for (int ThisCaptureLevel =
  11384. getOpenMPCaptureLevels(OMPD_distribute_parallel_for);
  11385. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  11386. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  11387. // 1.2.2 OpenMP Language Terminology
  11388. // Structured block - An executable statement with a single entry at the
  11389. // top and a single exit at the bottom.
  11390. // The point of exit cannot be a branch out of the structured block.
  11391. // longjmp() and throw() must not violate the entry/exit criteria.
  11392. CS->getCapturedDecl()->setNothrow();
  11393. }
  11394. OMPLoopBasedDirective::HelperExprs B;
  11395. // In presence of clause 'collapse' with number of loops, it will
  11396. // define the nested loops number.
  11397. unsigned NestedLoopCount = checkOpenMPLoop(
  11398. OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
  11399. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  11400. VarsWithImplicitDSA, B);
  11401. if (NestedLoopCount == 0)
  11402. return StmtError();
  11403. assert((CurContext->isDependentContext() || B.builtAll()) &&
  11404. "omp for loop exprs were not built");
  11405. setFunctionHasBranchProtectedScope();
  11406. return OMPDistributeParallelForDirective::Create(
  11407. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
  11408. DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
  11409. }
  11410. StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
  11411. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  11412. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  11413. if (!AStmt)
  11414. return StmtError();
  11415. auto *CS = cast<CapturedStmt>(AStmt);
  11416. // 1.2.2 OpenMP Language Terminology
  11417. // Structured block - An executable statement with a single entry at the
  11418. // top and a single exit at the bottom.
  11419. // The point of exit cannot be a branch out of the structured block.
  11420. // longjmp() and throw() must not violate the entry/exit criteria.
  11421. CS->getCapturedDecl()->setNothrow();
  11422. for (int ThisCaptureLevel =
  11423. getOpenMPCaptureLevels(OMPD_distribute_parallel_for_simd);
  11424. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  11425. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  11426. // 1.2.2 OpenMP Language Terminology
  11427. // Structured block - An executable statement with a single entry at the
  11428. // top and a single exit at the bottom.
  11429. // The point of exit cannot be a branch out of the structured block.
  11430. // longjmp() and throw() must not violate the entry/exit criteria.
  11431. CS->getCapturedDecl()->setNothrow();
  11432. }
  11433. OMPLoopBasedDirective::HelperExprs B;
  11434. // In presence of clause 'collapse' with number of loops, it will
  11435. // define the nested loops number.
  11436. unsigned NestedLoopCount = checkOpenMPLoop(
  11437. OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
  11438. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  11439. VarsWithImplicitDSA, B);
  11440. if (NestedLoopCount == 0)
  11441. return StmtError();
  11442. assert((CurContext->isDependentContext() || B.builtAll()) &&
  11443. "omp for loop exprs were not built");
  11444. if (!CurContext->isDependentContext()) {
  11445. // Finalize the clauses that need pre-built expressions for CodeGen.
  11446. for (OMPClause *C : Clauses) {
  11447. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  11448. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  11449. B.NumIterations, *this, CurScope,
  11450. DSAStack))
  11451. return StmtError();
  11452. }
  11453. }
  11454. if (checkSimdlenSafelenSpecified(*this, Clauses))
  11455. return StmtError();
  11456. setFunctionHasBranchProtectedScope();
  11457. return OMPDistributeParallelForSimdDirective::Create(
  11458. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  11459. }
  11460. StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
  11461. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  11462. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  11463. if (!AStmt)
  11464. return StmtError();
  11465. auto *CS = cast<CapturedStmt>(AStmt);
  11466. // 1.2.2 OpenMP Language Terminology
  11467. // Structured block - An executable statement with a single entry at the
  11468. // top and a single exit at the bottom.
  11469. // The point of exit cannot be a branch out of the structured block.
  11470. // longjmp() and throw() must not violate the entry/exit criteria.
  11471. CS->getCapturedDecl()->setNothrow();
  11472. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_distribute_simd);
  11473. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  11474. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  11475. // 1.2.2 OpenMP Language Terminology
  11476. // Structured block - An executable statement with a single entry at the
  11477. // top and a single exit at the bottom.
  11478. // The point of exit cannot be a branch out of the structured block.
  11479. // longjmp() and throw() must not violate the entry/exit criteria.
  11480. CS->getCapturedDecl()->setNothrow();
  11481. }
  11482. OMPLoopBasedDirective::HelperExprs B;
  11483. // In presence of clause 'collapse' with number of loops, it will
  11484. // define the nested loops number.
  11485. unsigned NestedLoopCount =
  11486. checkOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
  11487. nullptr /*ordered not a clause on distribute*/, CS, *this,
  11488. *DSAStack, VarsWithImplicitDSA, B);
  11489. if (NestedLoopCount == 0)
  11490. return StmtError();
  11491. assert((CurContext->isDependentContext() || B.builtAll()) &&
  11492. "omp for loop exprs were not built");
  11493. if (!CurContext->isDependentContext()) {
  11494. // Finalize the clauses that need pre-built expressions for CodeGen.
  11495. for (OMPClause *C : Clauses) {
  11496. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  11497. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  11498. B.NumIterations, *this, CurScope,
  11499. DSAStack))
  11500. return StmtError();
  11501. }
  11502. }
  11503. if (checkSimdlenSafelenSpecified(*this, Clauses))
  11504. return StmtError();
  11505. setFunctionHasBranchProtectedScope();
  11506. return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
  11507. NestedLoopCount, Clauses, AStmt, B);
  11508. }
  11509. StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
  11510. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  11511. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  11512. if (!AStmt)
  11513. return StmtError();
  11514. auto *CS = cast<CapturedStmt>(AStmt);
  11515. // 1.2.2 OpenMP Language Terminology
  11516. // Structured block - An executable statement with a single entry at the
  11517. // top and a single exit at the bottom.
  11518. // The point of exit cannot be a branch out of the structured block.
  11519. // longjmp() and throw() must not violate the entry/exit criteria.
  11520. CS->getCapturedDecl()->setNothrow();
  11521. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
  11522. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  11523. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  11524. // 1.2.2 OpenMP Language Terminology
  11525. // Structured block - An executable statement with a single entry at the
  11526. // top and a single exit at the bottom.
  11527. // The point of exit cannot be a branch out of the structured block.
  11528. // longjmp() and throw() must not violate the entry/exit criteria.
  11529. CS->getCapturedDecl()->setNothrow();
  11530. }
  11531. OMPLoopBasedDirective::HelperExprs B;
  11532. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  11533. // define the nested loops number.
  11534. unsigned NestedLoopCount = checkOpenMPLoop(
  11535. OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
  11536. getOrderedNumberExpr(Clauses), CS, *this, *DSAStack, VarsWithImplicitDSA,
  11537. B);
  11538. if (NestedLoopCount == 0)
  11539. return StmtError();
  11540. assert((CurContext->isDependentContext() || B.builtAll()) &&
  11541. "omp target parallel for simd loop exprs were not built");
  11542. if (!CurContext->isDependentContext()) {
  11543. // Finalize the clauses that need pre-built expressions for CodeGen.
  11544. for (OMPClause *C : Clauses) {
  11545. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  11546. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  11547. B.NumIterations, *this, CurScope,
  11548. DSAStack))
  11549. return StmtError();
  11550. }
  11551. }
  11552. if (checkSimdlenSafelenSpecified(*this, Clauses))
  11553. return StmtError();
  11554. setFunctionHasBranchProtectedScope();
  11555. return OMPTargetParallelForSimdDirective::Create(
  11556. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  11557. }
  11558. StmtResult Sema::ActOnOpenMPTargetSimdDirective(
  11559. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  11560. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  11561. if (!AStmt)
  11562. return StmtError();
  11563. auto *CS = cast<CapturedStmt>(AStmt);
  11564. // 1.2.2 OpenMP Language Terminology
  11565. // Structured block - An executable statement with a single entry at the
  11566. // top and a single exit at the bottom.
  11567. // The point of exit cannot be a branch out of the structured block.
  11568. // longjmp() and throw() must not violate the entry/exit criteria.
  11569. CS->getCapturedDecl()->setNothrow();
  11570. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_simd);
  11571. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  11572. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  11573. // 1.2.2 OpenMP Language Terminology
  11574. // Structured block - An executable statement with a single entry at the
  11575. // top and a single exit at the bottom.
  11576. // The point of exit cannot be a branch out of the structured block.
  11577. // longjmp() and throw() must not violate the entry/exit criteria.
  11578. CS->getCapturedDecl()->setNothrow();
  11579. }
  11580. OMPLoopBasedDirective::HelperExprs B;
  11581. // In presence of clause 'collapse' with number of loops, it will define the
  11582. // nested loops number.
  11583. unsigned NestedLoopCount =
  11584. checkOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
  11585. getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
  11586. VarsWithImplicitDSA, B);
  11587. if (NestedLoopCount == 0)
  11588. return StmtError();
  11589. assert((CurContext->isDependentContext() || B.builtAll()) &&
  11590. "omp target simd loop exprs were not built");
  11591. if (!CurContext->isDependentContext()) {
  11592. // Finalize the clauses that need pre-built expressions for CodeGen.
  11593. for (OMPClause *C : Clauses) {
  11594. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  11595. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  11596. B.NumIterations, *this, CurScope,
  11597. DSAStack))
  11598. return StmtError();
  11599. }
  11600. }
  11601. if (checkSimdlenSafelenSpecified(*this, Clauses))
  11602. return StmtError();
  11603. setFunctionHasBranchProtectedScope();
  11604. return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
  11605. NestedLoopCount, Clauses, AStmt, B);
  11606. }
  11607. StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
  11608. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  11609. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  11610. if (!AStmt)
  11611. return StmtError();
  11612. auto *CS = cast<CapturedStmt>(AStmt);
  11613. // 1.2.2 OpenMP Language Terminology
  11614. // Structured block - An executable statement with a single entry at the
  11615. // top and a single exit at the bottom.
  11616. // The point of exit cannot be a branch out of the structured block.
  11617. // longjmp() and throw() must not violate the entry/exit criteria.
  11618. CS->getCapturedDecl()->setNothrow();
  11619. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_teams_distribute);
  11620. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  11621. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  11622. // 1.2.2 OpenMP Language Terminology
  11623. // Structured block - An executable statement with a single entry at the
  11624. // top and a single exit at the bottom.
  11625. // The point of exit cannot be a branch out of the structured block.
  11626. // longjmp() and throw() must not violate the entry/exit criteria.
  11627. CS->getCapturedDecl()->setNothrow();
  11628. }
  11629. OMPLoopBasedDirective::HelperExprs B;
  11630. // In presence of clause 'collapse' with number of loops, it will
  11631. // define the nested loops number.
  11632. unsigned NestedLoopCount =
  11633. checkOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
  11634. nullptr /*ordered not a clause on distribute*/, CS, *this,
  11635. *DSAStack, VarsWithImplicitDSA, B);
  11636. if (NestedLoopCount == 0)
  11637. return StmtError();
  11638. assert((CurContext->isDependentContext() || B.builtAll()) &&
  11639. "omp teams distribute loop exprs were not built");
  11640. setFunctionHasBranchProtectedScope();
  11641. DSAStack->setParentTeamsRegionLoc(StartLoc);
  11642. return OMPTeamsDistributeDirective::Create(
  11643. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  11644. }
  11645. StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
  11646. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  11647. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  11648. if (!AStmt)
  11649. return StmtError();
  11650. auto *CS = cast<CapturedStmt>(AStmt);
  11651. // 1.2.2 OpenMP Language Terminology
  11652. // Structured block - An executable statement with a single entry at the
  11653. // top and a single exit at the bottom.
  11654. // The point of exit cannot be a branch out of the structured block.
  11655. // longjmp() and throw() must not violate the entry/exit criteria.
  11656. CS->getCapturedDecl()->setNothrow();
  11657. for (int ThisCaptureLevel =
  11658. getOpenMPCaptureLevels(OMPD_teams_distribute_simd);
  11659. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  11660. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  11661. // 1.2.2 OpenMP Language Terminology
  11662. // Structured block - An executable statement with a single entry at the
  11663. // top and a single exit at the bottom.
  11664. // The point of exit cannot be a branch out of the structured block.
  11665. // longjmp() and throw() must not violate the entry/exit criteria.
  11666. CS->getCapturedDecl()->setNothrow();
  11667. }
  11668. OMPLoopBasedDirective::HelperExprs B;
  11669. // In presence of clause 'collapse' with number of loops, it will
  11670. // define the nested loops number.
  11671. unsigned NestedLoopCount = checkOpenMPLoop(
  11672. OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
  11673. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  11674. VarsWithImplicitDSA, B);
  11675. if (NestedLoopCount == 0)
  11676. return StmtError();
  11677. assert((CurContext->isDependentContext() || B.builtAll()) &&
  11678. "omp teams distribute simd loop exprs were not built");
  11679. if (!CurContext->isDependentContext()) {
  11680. // Finalize the clauses that need pre-built expressions for CodeGen.
  11681. for (OMPClause *C : Clauses) {
  11682. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  11683. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  11684. B.NumIterations, *this, CurScope,
  11685. DSAStack))
  11686. return StmtError();
  11687. }
  11688. }
  11689. if (checkSimdlenSafelenSpecified(*this, Clauses))
  11690. return StmtError();
  11691. setFunctionHasBranchProtectedScope();
  11692. DSAStack->setParentTeamsRegionLoc(StartLoc);
  11693. return OMPTeamsDistributeSimdDirective::Create(
  11694. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  11695. }
  11696. StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
  11697. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  11698. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  11699. if (!AStmt)
  11700. return StmtError();
  11701. auto *CS = cast<CapturedStmt>(AStmt);
  11702. // 1.2.2 OpenMP Language Terminology
  11703. // Structured block - An executable statement with a single entry at the
  11704. // top and a single exit at the bottom.
  11705. // The point of exit cannot be a branch out of the structured block.
  11706. // longjmp() and throw() must not violate the entry/exit criteria.
  11707. CS->getCapturedDecl()->setNothrow();
  11708. for (int ThisCaptureLevel =
  11709. getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for_simd);
  11710. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  11711. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  11712. // 1.2.2 OpenMP Language Terminology
  11713. // Structured block - An executable statement with a single entry at the
  11714. // top and a single exit at the bottom.
  11715. // The point of exit cannot be a branch out of the structured block.
  11716. // longjmp() and throw() must not violate the entry/exit criteria.
  11717. CS->getCapturedDecl()->setNothrow();
  11718. }
  11719. OMPLoopBasedDirective::HelperExprs B;
  11720. // In presence of clause 'collapse' with number of loops, it will
  11721. // define the nested loops number.
  11722. unsigned NestedLoopCount = checkOpenMPLoop(
  11723. OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
  11724. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  11725. VarsWithImplicitDSA, B);
  11726. if (NestedLoopCount == 0)
  11727. return StmtError();
  11728. assert((CurContext->isDependentContext() || B.builtAll()) &&
  11729. "omp for loop exprs were not built");
  11730. if (!CurContext->isDependentContext()) {
  11731. // Finalize the clauses that need pre-built expressions for CodeGen.
  11732. for (OMPClause *C : Clauses) {
  11733. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  11734. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  11735. B.NumIterations, *this, CurScope,
  11736. DSAStack))
  11737. return StmtError();
  11738. }
  11739. }
  11740. if (checkSimdlenSafelenSpecified(*this, Clauses))
  11741. return StmtError();
  11742. setFunctionHasBranchProtectedScope();
  11743. DSAStack->setParentTeamsRegionLoc(StartLoc);
  11744. return OMPTeamsDistributeParallelForSimdDirective::Create(
  11745. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  11746. }
  11747. StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
  11748. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  11749. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  11750. if (!AStmt)
  11751. return StmtError();
  11752. auto *CS = cast<CapturedStmt>(AStmt);
  11753. // 1.2.2 OpenMP Language Terminology
  11754. // Structured block - An executable statement with a single entry at the
  11755. // top and a single exit at the bottom.
  11756. // The point of exit cannot be a branch out of the structured block.
  11757. // longjmp() and throw() must not violate the entry/exit criteria.
  11758. CS->getCapturedDecl()->setNothrow();
  11759. for (int ThisCaptureLevel =
  11760. getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for);
  11761. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  11762. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  11763. // 1.2.2 OpenMP Language Terminology
  11764. // Structured block - An executable statement with a single entry at the
  11765. // top and a single exit at the bottom.
  11766. // The point of exit cannot be a branch out of the structured block.
  11767. // longjmp() and throw() must not violate the entry/exit criteria.
  11768. CS->getCapturedDecl()->setNothrow();
  11769. }
  11770. OMPLoopBasedDirective::HelperExprs B;
  11771. // In presence of clause 'collapse' with number of loops, it will
  11772. // define the nested loops number.
  11773. unsigned NestedLoopCount = checkOpenMPLoop(
  11774. OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
  11775. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  11776. VarsWithImplicitDSA, B);
  11777. if (NestedLoopCount == 0)
  11778. return StmtError();
  11779. assert((CurContext->isDependentContext() || B.builtAll()) &&
  11780. "omp for loop exprs were not built");
  11781. setFunctionHasBranchProtectedScope();
  11782. DSAStack->setParentTeamsRegionLoc(StartLoc);
  11783. return OMPTeamsDistributeParallelForDirective::Create(
  11784. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
  11785. DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
  11786. }
  11787. StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
  11788. Stmt *AStmt,
  11789. SourceLocation StartLoc,
  11790. SourceLocation EndLoc) {
  11791. if (!AStmt)
  11792. return StmtError();
  11793. auto *CS = cast<CapturedStmt>(AStmt);
  11794. // 1.2.2 OpenMP Language Terminology
  11795. // Structured block - An executable statement with a single entry at the
  11796. // top and a single exit at the bottom.
  11797. // The point of exit cannot be a branch out of the structured block.
  11798. // longjmp() and throw() must not violate the entry/exit criteria.
  11799. CS->getCapturedDecl()->setNothrow();
  11800. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_teams);
  11801. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  11802. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  11803. // 1.2.2 OpenMP Language Terminology
  11804. // Structured block - An executable statement with a single entry at the
  11805. // top and a single exit at the bottom.
  11806. // The point of exit cannot be a branch out of the structured block.
  11807. // longjmp() and throw() must not violate the entry/exit criteria.
  11808. CS->getCapturedDecl()->setNothrow();
  11809. }
  11810. setFunctionHasBranchProtectedScope();
  11811. return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
  11812. AStmt);
  11813. }
  11814. StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective(
  11815. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  11816. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  11817. if (!AStmt)
  11818. return StmtError();
  11819. auto *CS = cast<CapturedStmt>(AStmt);
  11820. // 1.2.2 OpenMP Language Terminology
  11821. // Structured block - An executable statement with a single entry at the
  11822. // top and a single exit at the bottom.
  11823. // The point of exit cannot be a branch out of the structured block.
  11824. // longjmp() and throw() must not violate the entry/exit criteria.
  11825. CS->getCapturedDecl()->setNothrow();
  11826. for (int ThisCaptureLevel =
  11827. getOpenMPCaptureLevels(OMPD_target_teams_distribute);
  11828. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  11829. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  11830. // 1.2.2 OpenMP Language Terminology
  11831. // Structured block - An executable statement with a single entry at the
  11832. // top and a single exit at the bottom.
  11833. // The point of exit cannot be a branch out of the structured block.
  11834. // longjmp() and throw() must not violate the entry/exit criteria.
  11835. CS->getCapturedDecl()->setNothrow();
  11836. }
  11837. OMPLoopBasedDirective::HelperExprs B;
  11838. // In presence of clause 'collapse' with number of loops, it will
  11839. // define the nested loops number.
  11840. unsigned NestedLoopCount = checkOpenMPLoop(
  11841. OMPD_target_teams_distribute, getCollapseNumberExpr(Clauses),
  11842. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  11843. VarsWithImplicitDSA, B);
  11844. if (NestedLoopCount == 0)
  11845. return StmtError();
  11846. assert((CurContext->isDependentContext() || B.builtAll()) &&
  11847. "omp target teams distribute loop exprs were not built");
  11848. setFunctionHasBranchProtectedScope();
  11849. return OMPTargetTeamsDistributeDirective::Create(
  11850. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  11851. }
  11852. StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective(
  11853. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  11854. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  11855. if (!AStmt)
  11856. return StmtError();
  11857. auto *CS = cast<CapturedStmt>(AStmt);
  11858. // 1.2.2 OpenMP Language Terminology
  11859. // Structured block - An executable statement with a single entry at the
  11860. // top and a single exit at the bottom.
  11861. // The point of exit cannot be a branch out of the structured block.
  11862. // longjmp() and throw() must not violate the entry/exit criteria.
  11863. CS->getCapturedDecl()->setNothrow();
  11864. for (int ThisCaptureLevel =
  11865. getOpenMPCaptureLevels(OMPD_target_teams_distribute_parallel_for);
  11866. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  11867. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  11868. // 1.2.2 OpenMP Language Terminology
  11869. // Structured block - An executable statement with a single entry at the
  11870. // top and a single exit at the bottom.
  11871. // The point of exit cannot be a branch out of the structured block.
  11872. // longjmp() and throw() must not violate the entry/exit criteria.
  11873. CS->getCapturedDecl()->setNothrow();
  11874. }
  11875. OMPLoopBasedDirective::HelperExprs B;
  11876. // In presence of clause 'collapse' with number of loops, it will
  11877. // define the nested loops number.
  11878. unsigned NestedLoopCount = checkOpenMPLoop(
  11879. OMPD_target_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
  11880. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  11881. VarsWithImplicitDSA, B);
  11882. if (NestedLoopCount == 0)
  11883. return StmtError();
  11884. assert((CurContext->isDependentContext() || B.builtAll()) &&
  11885. "omp target teams distribute parallel for loop exprs were not built");
  11886. if (!CurContext->isDependentContext()) {
  11887. // Finalize the clauses that need pre-built expressions for CodeGen.
  11888. for (OMPClause *C : Clauses) {
  11889. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  11890. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  11891. B.NumIterations, *this, CurScope,
  11892. DSAStack))
  11893. return StmtError();
  11894. }
  11895. }
  11896. setFunctionHasBranchProtectedScope();
  11897. return OMPTargetTeamsDistributeParallelForDirective::Create(
  11898. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
  11899. DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
  11900. }
  11901. StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
  11902. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  11903. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  11904. if (!AStmt)
  11905. return StmtError();
  11906. auto *CS = cast<CapturedStmt>(AStmt);
  11907. // 1.2.2 OpenMP Language Terminology
  11908. // Structured block - An executable statement with a single entry at the
  11909. // top and a single exit at the bottom.
  11910. // The point of exit cannot be a branch out of the structured block.
  11911. // longjmp() and throw() must not violate the entry/exit criteria.
  11912. CS->getCapturedDecl()->setNothrow();
  11913. for (int ThisCaptureLevel = getOpenMPCaptureLevels(
  11914. OMPD_target_teams_distribute_parallel_for_simd);
  11915. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  11916. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  11917. // 1.2.2 OpenMP Language Terminology
  11918. // Structured block - An executable statement with a single entry at the
  11919. // top and a single exit at the bottom.
  11920. // The point of exit cannot be a branch out of the structured block.
  11921. // longjmp() and throw() must not violate the entry/exit criteria.
  11922. CS->getCapturedDecl()->setNothrow();
  11923. }
  11924. OMPLoopBasedDirective::HelperExprs B;
  11925. // In presence of clause 'collapse' with number of loops, it will
  11926. // define the nested loops number.
  11927. unsigned NestedLoopCount =
  11928. checkOpenMPLoop(OMPD_target_teams_distribute_parallel_for_simd,
  11929. getCollapseNumberExpr(Clauses),
  11930. nullptr /*ordered not a clause on distribute*/, CS, *this,
  11931. *DSAStack, VarsWithImplicitDSA, B);
  11932. if (NestedLoopCount == 0)
  11933. return StmtError();
  11934. assert((CurContext->isDependentContext() || B.builtAll()) &&
  11935. "omp target teams distribute parallel for simd loop exprs were not "
  11936. "built");
  11937. if (!CurContext->isDependentContext()) {
  11938. // Finalize the clauses that need pre-built expressions for CodeGen.
  11939. for (OMPClause *C : Clauses) {
  11940. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  11941. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  11942. B.NumIterations, *this, CurScope,
  11943. DSAStack))
  11944. return StmtError();
  11945. }
  11946. }
  11947. if (checkSimdlenSafelenSpecified(*this, Clauses))
  11948. return StmtError();
  11949. setFunctionHasBranchProtectedScope();
  11950. return OMPTargetTeamsDistributeParallelForSimdDirective::Create(
  11951. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  11952. }
  11953. StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective(
  11954. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  11955. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  11956. if (!AStmt)
  11957. return StmtError();
  11958. auto *CS = cast<CapturedStmt>(AStmt);
  11959. // 1.2.2 OpenMP Language Terminology
  11960. // Structured block - An executable statement with a single entry at the
  11961. // top and a single exit at the bottom.
  11962. // The point of exit cannot be a branch out of the structured block.
  11963. // longjmp() and throw() must not violate the entry/exit criteria.
  11964. CS->getCapturedDecl()->setNothrow();
  11965. for (int ThisCaptureLevel =
  11966. getOpenMPCaptureLevels(OMPD_target_teams_distribute_simd);
  11967. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  11968. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  11969. // 1.2.2 OpenMP Language Terminology
  11970. // Structured block - An executable statement with a single entry at the
  11971. // top and a single exit at the bottom.
  11972. // The point of exit cannot be a branch out of the structured block.
  11973. // longjmp() and throw() must not violate the entry/exit criteria.
  11974. CS->getCapturedDecl()->setNothrow();
  11975. }
  11976. OMPLoopBasedDirective::HelperExprs B;
  11977. // In presence of clause 'collapse' with number of loops, it will
  11978. // define the nested loops number.
  11979. unsigned NestedLoopCount = checkOpenMPLoop(
  11980. OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses),
  11981. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  11982. VarsWithImplicitDSA, B);
  11983. if (NestedLoopCount == 0)
  11984. return StmtError();
  11985. assert((CurContext->isDependentContext() || B.builtAll()) &&
  11986. "omp target teams distribute simd loop exprs were not built");
  11987. if (!CurContext->isDependentContext()) {
  11988. // Finalize the clauses that need pre-built expressions for CodeGen.
  11989. for (OMPClause *C : Clauses) {
  11990. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  11991. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  11992. B.NumIterations, *this, CurScope,
  11993. DSAStack))
  11994. return StmtError();
  11995. }
  11996. }
  11997. if (checkSimdlenSafelenSpecified(*this, Clauses))
  11998. return StmtError();
  11999. setFunctionHasBranchProtectedScope();
  12000. return OMPTargetTeamsDistributeSimdDirective::Create(
  12001. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  12002. }
  12003. bool Sema::checkTransformableLoopNest(
  12004. OpenMPDirectiveKind Kind, Stmt *AStmt, int NumLoops,
  12005. SmallVectorImpl<OMPLoopBasedDirective::HelperExprs> &LoopHelpers,
  12006. Stmt *&Body,
  12007. SmallVectorImpl<SmallVector<llvm::PointerUnion<Stmt *, Decl *>, 0>>
  12008. &OriginalInits) {
  12009. OriginalInits.emplace_back();
  12010. bool Result = OMPLoopBasedDirective::doForAllLoops(
  12011. AStmt->IgnoreContainers(), /*TryImperfectlyNestedLoops=*/false, NumLoops,
  12012. [this, &LoopHelpers, &Body, &OriginalInits, Kind](unsigned Cnt,
  12013. Stmt *CurStmt) {
  12014. VarsWithInheritedDSAType TmpDSA;
  12015. unsigned SingleNumLoops =
  12016. checkOpenMPLoop(Kind, nullptr, nullptr, CurStmt, *this, *DSAStack,
  12017. TmpDSA, LoopHelpers[Cnt]);
  12018. if (SingleNumLoops == 0)
  12019. return true;
  12020. assert(SingleNumLoops == 1 && "Expect single loop iteration space");
  12021. if (auto *For = dyn_cast<ForStmt>(CurStmt)) {
  12022. OriginalInits.back().push_back(For->getInit());
  12023. Body = For->getBody();
  12024. } else {
  12025. assert(isa<CXXForRangeStmt>(CurStmt) &&
  12026. "Expected canonical for or range-based for loops.");
  12027. auto *CXXFor = cast<CXXForRangeStmt>(CurStmt);
  12028. OriginalInits.back().push_back(CXXFor->getBeginStmt());
  12029. Body = CXXFor->getBody();
  12030. }
  12031. OriginalInits.emplace_back();
  12032. return false;
  12033. },
  12034. [&OriginalInits](OMPLoopBasedDirective *Transform) {
  12035. Stmt *DependentPreInits;
  12036. if (auto *Dir = dyn_cast<OMPTileDirective>(Transform))
  12037. DependentPreInits = Dir->getPreInits();
  12038. else if (auto *Dir = dyn_cast<OMPUnrollDirective>(Transform))
  12039. DependentPreInits = Dir->getPreInits();
  12040. else
  12041. llvm_unreachable("Unhandled loop transformation");
  12042. if (!DependentPreInits)
  12043. return;
  12044. for (Decl *C : cast<DeclStmt>(DependentPreInits)->getDeclGroup())
  12045. OriginalInits.back().push_back(C);
  12046. });
  12047. assert(OriginalInits.back().empty() && "No preinit after innermost loop");
  12048. OriginalInits.pop_back();
  12049. return Result;
  12050. }
  12051. StmtResult Sema::ActOnOpenMPTileDirective(ArrayRef<OMPClause *> Clauses,
  12052. Stmt *AStmt, SourceLocation StartLoc,
  12053. SourceLocation EndLoc) {
  12054. auto SizesClauses =
  12055. OMPExecutableDirective::getClausesOfKind<OMPSizesClause>(Clauses);
  12056. if (SizesClauses.empty()) {
  12057. // A missing 'sizes' clause is already reported by the parser.
  12058. return StmtError();
  12059. }
  12060. const OMPSizesClause *SizesClause = *SizesClauses.begin();
  12061. unsigned NumLoops = SizesClause->getNumSizes();
  12062. // Empty statement should only be possible if there already was an error.
  12063. if (!AStmt)
  12064. return StmtError();
  12065. // Verify and diagnose loop nest.
  12066. SmallVector<OMPLoopBasedDirective::HelperExprs, 4> LoopHelpers(NumLoops);
  12067. Stmt *Body = nullptr;
  12068. SmallVector<SmallVector<llvm::PointerUnion<Stmt *, Decl *>, 0>, 4>
  12069. OriginalInits;
  12070. if (!checkTransformableLoopNest(OMPD_tile, AStmt, NumLoops, LoopHelpers, Body,
  12071. OriginalInits))
  12072. return StmtError();
  12073. // Delay tiling to when template is completely instantiated.
  12074. if (CurContext->isDependentContext())
  12075. return OMPTileDirective::Create(Context, StartLoc, EndLoc, Clauses,
  12076. NumLoops, AStmt, nullptr, nullptr);
  12077. SmallVector<Decl *, 4> PreInits;
  12078. // Create iteration variables for the generated loops.
  12079. SmallVector<VarDecl *, 4> FloorIndVars;
  12080. SmallVector<VarDecl *, 4> TileIndVars;
  12081. FloorIndVars.resize(NumLoops);
  12082. TileIndVars.resize(NumLoops);
  12083. for (unsigned I = 0; I < NumLoops; ++I) {
  12084. OMPLoopBasedDirective::HelperExprs &LoopHelper = LoopHelpers[I];
  12085. assert(LoopHelper.Counters.size() == 1 &&
  12086. "Expect single-dimensional loop iteration space");
  12087. auto *OrigCntVar = cast<DeclRefExpr>(LoopHelper.Counters.front());
  12088. std::string OrigVarName = OrigCntVar->getNameInfo().getAsString();
  12089. DeclRefExpr *IterVarRef = cast<DeclRefExpr>(LoopHelper.IterationVarRef);
  12090. QualType CntTy = IterVarRef->getType();
  12091. // Iteration variable for the floor (i.e. outer) loop.
  12092. {
  12093. std::string FloorCntName =
  12094. (Twine(".floor_") + llvm::utostr(I) + ".iv." + OrigVarName).str();
  12095. VarDecl *FloorCntDecl =
  12096. buildVarDecl(*this, {}, CntTy, FloorCntName, nullptr, OrigCntVar);
  12097. FloorIndVars[I] = FloorCntDecl;
  12098. }
  12099. // Iteration variable for the tile (i.e. inner) loop.
  12100. {
  12101. std::string TileCntName =
  12102. (Twine(".tile_") + llvm::utostr(I) + ".iv." + OrigVarName).str();
  12103. // Reuse the iteration variable created by checkOpenMPLoop. It is also
  12104. // used by the expressions to derive the original iteration variable's
  12105. // value from the logical iteration number.
  12106. auto *TileCntDecl = cast<VarDecl>(IterVarRef->getDecl());
  12107. TileCntDecl->setDeclName(&PP.getIdentifierTable().get(TileCntName));
  12108. TileIndVars[I] = TileCntDecl;
  12109. }
  12110. for (auto &P : OriginalInits[I]) {
  12111. if (auto *D = P.dyn_cast<Decl *>())
  12112. PreInits.push_back(D);
  12113. else if (auto *PI = dyn_cast_or_null<DeclStmt>(P.dyn_cast<Stmt *>()))
  12114. PreInits.append(PI->decl_begin(), PI->decl_end());
  12115. }
  12116. if (auto *PI = cast_or_null<DeclStmt>(LoopHelper.PreInits))
  12117. PreInits.append(PI->decl_begin(), PI->decl_end());
  12118. // Gather declarations for the data members used as counters.
  12119. for (Expr *CounterRef : LoopHelper.Counters) {
  12120. auto *CounterDecl = cast<DeclRefExpr>(CounterRef)->getDecl();
  12121. if (isa<OMPCapturedExprDecl>(CounterDecl))
  12122. PreInits.push_back(CounterDecl);
  12123. }
  12124. }
  12125. // Once the original iteration values are set, append the innermost body.
  12126. Stmt *Inner = Body;
  12127. // Create tile loops from the inside to the outside.
  12128. for (int I = NumLoops - 1; I >= 0; --I) {
  12129. OMPLoopBasedDirective::HelperExprs &LoopHelper = LoopHelpers[I];
  12130. Expr *NumIterations = LoopHelper.NumIterations;
  12131. auto *OrigCntVar = cast<DeclRefExpr>(LoopHelper.Counters[0]);
  12132. QualType CntTy = OrigCntVar->getType();
  12133. Expr *DimTileSize = SizesClause->getSizesRefs()[I];
  12134. Scope *CurScope = getCurScope();
  12135. // Commonly used variables.
  12136. DeclRefExpr *TileIV = buildDeclRefExpr(*this, TileIndVars[I], CntTy,
  12137. OrigCntVar->getExprLoc());
  12138. DeclRefExpr *FloorIV = buildDeclRefExpr(*this, FloorIndVars[I], CntTy,
  12139. OrigCntVar->getExprLoc());
  12140. // For init-statement: auto .tile.iv = .floor.iv
  12141. AddInitializerToDecl(TileIndVars[I], DefaultLvalueConversion(FloorIV).get(),
  12142. /*DirectInit=*/false);
  12143. Decl *CounterDecl = TileIndVars[I];
  12144. StmtResult InitStmt = new (Context)
  12145. DeclStmt(DeclGroupRef::Create(Context, &CounterDecl, 1),
  12146. OrigCntVar->getBeginLoc(), OrigCntVar->getEndLoc());
  12147. if (!InitStmt.isUsable())
  12148. return StmtError();
  12149. // For cond-expression: .tile.iv < min(.floor.iv + DimTileSize,
  12150. // NumIterations)
  12151. ExprResult EndOfTile = BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(),
  12152. BO_Add, FloorIV, DimTileSize);
  12153. if (!EndOfTile.isUsable())
  12154. return StmtError();
  12155. ExprResult IsPartialTile =
  12156. BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(), BO_LT,
  12157. NumIterations, EndOfTile.get());
  12158. if (!IsPartialTile.isUsable())
  12159. return StmtError();
  12160. ExprResult MinTileAndIterSpace = ActOnConditionalOp(
  12161. LoopHelper.Cond->getBeginLoc(), LoopHelper.Cond->getEndLoc(),
  12162. IsPartialTile.get(), NumIterations, EndOfTile.get());
  12163. if (!MinTileAndIterSpace.isUsable())
  12164. return StmtError();
  12165. ExprResult CondExpr = BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(),
  12166. BO_LT, TileIV, MinTileAndIterSpace.get());
  12167. if (!CondExpr.isUsable())
  12168. return StmtError();
  12169. // For incr-statement: ++.tile.iv
  12170. ExprResult IncrStmt =
  12171. BuildUnaryOp(CurScope, LoopHelper.Inc->getExprLoc(), UO_PreInc, TileIV);
  12172. if (!IncrStmt.isUsable())
  12173. return StmtError();
  12174. // Statements to set the original iteration variable's value from the
  12175. // logical iteration number.
  12176. // Generated for loop is:
  12177. // Original_for_init;
  12178. // for (auto .tile.iv = .floor.iv; .tile.iv < min(.floor.iv + DimTileSize,
  12179. // NumIterations); ++.tile.iv) {
  12180. // Original_Body;
  12181. // Original_counter_update;
  12182. // }
  12183. // FIXME: If the innermost body is an loop itself, inserting these
  12184. // statements stops it being recognized as a perfectly nested loop (e.g.
  12185. // for applying tiling again). If this is the case, sink the expressions
  12186. // further into the inner loop.
  12187. SmallVector<Stmt *, 4> BodyParts;
  12188. BodyParts.append(LoopHelper.Updates.begin(), LoopHelper.Updates.end());
  12189. BodyParts.push_back(Inner);
  12190. Inner = CompoundStmt::Create(Context, BodyParts, Inner->getBeginLoc(),
  12191. Inner->getEndLoc());
  12192. Inner = new (Context)
  12193. ForStmt(Context, InitStmt.get(), CondExpr.get(), nullptr,
  12194. IncrStmt.get(), Inner, LoopHelper.Init->getBeginLoc(),
  12195. LoopHelper.Init->getBeginLoc(), LoopHelper.Inc->getEndLoc());
  12196. }
  12197. // Create floor loops from the inside to the outside.
  12198. for (int I = NumLoops - 1; I >= 0; --I) {
  12199. auto &LoopHelper = LoopHelpers[I];
  12200. Expr *NumIterations = LoopHelper.NumIterations;
  12201. DeclRefExpr *OrigCntVar = cast<DeclRefExpr>(LoopHelper.Counters[0]);
  12202. QualType CntTy = OrigCntVar->getType();
  12203. Expr *DimTileSize = SizesClause->getSizesRefs()[I];
  12204. Scope *CurScope = getCurScope();
  12205. // Commonly used variables.
  12206. DeclRefExpr *FloorIV = buildDeclRefExpr(*this, FloorIndVars[I], CntTy,
  12207. OrigCntVar->getExprLoc());
  12208. // For init-statement: auto .floor.iv = 0
  12209. AddInitializerToDecl(
  12210. FloorIndVars[I],
  12211. ActOnIntegerConstant(LoopHelper.Init->getExprLoc(), 0).get(),
  12212. /*DirectInit=*/false);
  12213. Decl *CounterDecl = FloorIndVars[I];
  12214. StmtResult InitStmt = new (Context)
  12215. DeclStmt(DeclGroupRef::Create(Context, &CounterDecl, 1),
  12216. OrigCntVar->getBeginLoc(), OrigCntVar->getEndLoc());
  12217. if (!InitStmt.isUsable())
  12218. return StmtError();
  12219. // For cond-expression: .floor.iv < NumIterations
  12220. ExprResult CondExpr = BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(),
  12221. BO_LT, FloorIV, NumIterations);
  12222. if (!CondExpr.isUsable())
  12223. return StmtError();
  12224. // For incr-statement: .floor.iv += DimTileSize
  12225. ExprResult IncrStmt = BuildBinOp(CurScope, LoopHelper.Inc->getExprLoc(),
  12226. BO_AddAssign, FloorIV, DimTileSize);
  12227. if (!IncrStmt.isUsable())
  12228. return StmtError();
  12229. Inner = new (Context)
  12230. ForStmt(Context, InitStmt.get(), CondExpr.get(), nullptr,
  12231. IncrStmt.get(), Inner, LoopHelper.Init->getBeginLoc(),
  12232. LoopHelper.Init->getBeginLoc(), LoopHelper.Inc->getEndLoc());
  12233. }
  12234. return OMPTileDirective::Create(Context, StartLoc, EndLoc, Clauses, NumLoops,
  12235. AStmt, Inner,
  12236. buildPreInits(Context, PreInits));
  12237. }
  12238. StmtResult Sema::ActOnOpenMPUnrollDirective(ArrayRef<OMPClause *> Clauses,
  12239. Stmt *AStmt,
  12240. SourceLocation StartLoc,
  12241. SourceLocation EndLoc) {
  12242. // Empty statement should only be possible if there already was an error.
  12243. if (!AStmt)
  12244. return StmtError();
  12245. if (checkMutuallyExclusiveClauses(*this, Clauses, {OMPC_partial, OMPC_full}))
  12246. return StmtError();
  12247. const OMPFullClause *FullClause =
  12248. OMPExecutableDirective::getSingleClause<OMPFullClause>(Clauses);
  12249. const OMPPartialClause *PartialClause =
  12250. OMPExecutableDirective::getSingleClause<OMPPartialClause>(Clauses);
  12251. assert(!(FullClause && PartialClause) &&
  12252. "mutual exclusivity must have been checked before");
  12253. constexpr unsigned NumLoops = 1;
  12254. Stmt *Body = nullptr;
  12255. SmallVector<OMPLoopBasedDirective::HelperExprs, NumLoops> LoopHelpers(
  12256. NumLoops);
  12257. SmallVector<SmallVector<llvm::PointerUnion<Stmt *, Decl *>, 0>, NumLoops + 1>
  12258. OriginalInits;
  12259. if (!checkTransformableLoopNest(OMPD_unroll, AStmt, NumLoops, LoopHelpers,
  12260. Body, OriginalInits))
  12261. return StmtError();
  12262. unsigned NumGeneratedLoops = PartialClause ? 1 : 0;
  12263. // Delay unrolling to when template is completely instantiated.
  12264. if (CurContext->isDependentContext())
  12265. return OMPUnrollDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
  12266. NumGeneratedLoops, nullptr, nullptr);
  12267. OMPLoopBasedDirective::HelperExprs &LoopHelper = LoopHelpers.front();
  12268. if (FullClause) {
  12269. if (!VerifyPositiveIntegerConstantInClause(
  12270. LoopHelper.NumIterations, OMPC_full, /*StrictlyPositive=*/false,
  12271. /*SuppressExprDiags=*/true)
  12272. .isUsable()) {
  12273. Diag(AStmt->getBeginLoc(), diag::err_omp_unroll_full_variable_trip_count);
  12274. Diag(FullClause->getBeginLoc(), diag::note_omp_directive_here)
  12275. << "#pragma omp unroll full";
  12276. return StmtError();
  12277. }
  12278. }
  12279. // The generated loop may only be passed to other loop-associated directive
  12280. // when a partial clause is specified. Without the requirement it is
  12281. // sufficient to generate loop unroll metadata at code-generation.
  12282. if (NumGeneratedLoops == 0)
  12283. return OMPUnrollDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
  12284. NumGeneratedLoops, nullptr, nullptr);
  12285. // Otherwise, we need to provide a de-sugared/transformed AST that can be
  12286. // associated with another loop directive.
  12287. //
  12288. // The canonical loop analysis return by checkTransformableLoopNest assumes
  12289. // the following structure to be the same loop without transformations or
  12290. // directives applied: \code OriginalInits; LoopHelper.PreInits;
  12291. // LoopHelper.Counters;
  12292. // for (; IV < LoopHelper.NumIterations; ++IV) {
  12293. // LoopHelper.Updates;
  12294. // Body;
  12295. // }
  12296. // \endcode
  12297. // where IV is a variable declared and initialized to 0 in LoopHelper.PreInits
  12298. // and referenced by LoopHelper.IterationVarRef.
  12299. //
  12300. // The unrolling directive transforms this into the following loop:
  12301. // \code
  12302. // OriginalInits; \
  12303. // LoopHelper.PreInits; > NewPreInits
  12304. // LoopHelper.Counters; /
  12305. // for (auto UIV = 0; UIV < LoopHelper.NumIterations; UIV+=Factor) {
  12306. // #pragma clang loop unroll_count(Factor)
  12307. // for (IV = UIV; IV < UIV + Factor && UIV < LoopHelper.NumIterations; ++IV)
  12308. // {
  12309. // LoopHelper.Updates;
  12310. // Body;
  12311. // }
  12312. // }
  12313. // \endcode
  12314. // where UIV is a new logical iteration counter. IV must be the same VarDecl
  12315. // as the original LoopHelper.IterationVarRef because LoopHelper.Updates
  12316. // references it. If the partially unrolled loop is associated with another
  12317. // loop directive (like an OMPForDirective), it will use checkOpenMPLoop to
  12318. // analyze this loop, i.e. the outer loop must fulfill the constraints of an
  12319. // OpenMP canonical loop. The inner loop is not an associable canonical loop
  12320. // and only exists to defer its unrolling to LLVM's LoopUnroll instead of
  12321. // doing it in the frontend (by adding loop metadata). NewPreInits becomes a
  12322. // property of the OMPLoopBasedDirective instead of statements in
  12323. // CompoundStatement. This is to allow the loop to become a non-outermost loop
  12324. // of a canonical loop nest where these PreInits are emitted before the
  12325. // outermost directive.
  12326. // Determine the PreInit declarations.
  12327. SmallVector<Decl *, 4> PreInits;
  12328. assert(OriginalInits.size() == 1 &&
  12329. "Expecting a single-dimensional loop iteration space");
  12330. for (auto &P : OriginalInits[0]) {
  12331. if (auto *D = P.dyn_cast<Decl *>())
  12332. PreInits.push_back(D);
  12333. else if (auto *PI = dyn_cast_or_null<DeclStmt>(P.dyn_cast<Stmt *>()))
  12334. PreInits.append(PI->decl_begin(), PI->decl_end());
  12335. }
  12336. if (auto *PI = cast_or_null<DeclStmt>(LoopHelper.PreInits))
  12337. PreInits.append(PI->decl_begin(), PI->decl_end());
  12338. // Gather declarations for the data members used as counters.
  12339. for (Expr *CounterRef : LoopHelper.Counters) {
  12340. auto *CounterDecl = cast<DeclRefExpr>(CounterRef)->getDecl();
  12341. if (isa<OMPCapturedExprDecl>(CounterDecl))
  12342. PreInits.push_back(CounterDecl);
  12343. }
  12344. auto *IterationVarRef = cast<DeclRefExpr>(LoopHelper.IterationVarRef);
  12345. QualType IVTy = IterationVarRef->getType();
  12346. assert(LoopHelper.Counters.size() == 1 &&
  12347. "Expecting a single-dimensional loop iteration space");
  12348. auto *OrigVar = cast<DeclRefExpr>(LoopHelper.Counters.front());
  12349. // Determine the unroll factor.
  12350. uint64_t Factor;
  12351. SourceLocation FactorLoc;
  12352. if (Expr *FactorVal = PartialClause->getFactor()) {
  12353. Factor =
  12354. FactorVal->getIntegerConstantExpr(Context).getValue().getZExtValue();
  12355. FactorLoc = FactorVal->getExprLoc();
  12356. } else {
  12357. // TODO: Use a better profitability model.
  12358. Factor = 2;
  12359. }
  12360. assert(Factor > 0 && "Expected positive unroll factor");
  12361. auto MakeFactorExpr = [this, Factor, IVTy, FactorLoc]() {
  12362. return IntegerLiteral::Create(
  12363. Context, llvm::APInt(Context.getIntWidth(IVTy), Factor), IVTy,
  12364. FactorLoc);
  12365. };
  12366. // Iteration variable SourceLocations.
  12367. SourceLocation OrigVarLoc = OrigVar->getExprLoc();
  12368. SourceLocation OrigVarLocBegin = OrigVar->getBeginLoc();
  12369. SourceLocation OrigVarLocEnd = OrigVar->getEndLoc();
  12370. // Internal variable names.
  12371. std::string OrigVarName = OrigVar->getNameInfo().getAsString();
  12372. std::string OuterIVName = (Twine(".unrolled.iv.") + OrigVarName).str();
  12373. std::string InnerIVName = (Twine(".unroll_inner.iv.") + OrigVarName).str();
  12374. std::string InnerTripCountName =
  12375. (Twine(".unroll_inner.tripcount.") + OrigVarName).str();
  12376. // Create the iteration variable for the unrolled loop.
  12377. VarDecl *OuterIVDecl =
  12378. buildVarDecl(*this, {}, IVTy, OuterIVName, nullptr, OrigVar);
  12379. auto MakeOuterRef = [this, OuterIVDecl, IVTy, OrigVarLoc]() {
  12380. return buildDeclRefExpr(*this, OuterIVDecl, IVTy, OrigVarLoc);
  12381. };
  12382. // Iteration variable for the inner loop: Reuse the iteration variable created
  12383. // by checkOpenMPLoop.
  12384. auto *InnerIVDecl = cast<VarDecl>(IterationVarRef->getDecl());
  12385. InnerIVDecl->setDeclName(&PP.getIdentifierTable().get(InnerIVName));
  12386. auto MakeInnerRef = [this, InnerIVDecl, IVTy, OrigVarLoc]() {
  12387. return buildDeclRefExpr(*this, InnerIVDecl, IVTy, OrigVarLoc);
  12388. };
  12389. // Make a copy of the NumIterations expression for each use: By the AST
  12390. // constraints, every expression object in a DeclContext must be unique.
  12391. CaptureVars CopyTransformer(*this);
  12392. auto MakeNumIterations = [&CopyTransformer, &LoopHelper]() -> Expr * {
  12393. return AssertSuccess(
  12394. CopyTransformer.TransformExpr(LoopHelper.NumIterations));
  12395. };
  12396. // Inner For init-statement: auto .unroll_inner.iv = .unrolled.iv
  12397. ExprResult LValueConv = DefaultLvalueConversion(MakeOuterRef());
  12398. AddInitializerToDecl(InnerIVDecl, LValueConv.get(), /*DirectInit=*/false);
  12399. StmtResult InnerInit = new (Context)
  12400. DeclStmt(DeclGroupRef(InnerIVDecl), OrigVarLocBegin, OrigVarLocEnd);
  12401. if (!InnerInit.isUsable())
  12402. return StmtError();
  12403. // Inner For cond-expression:
  12404. // \code
  12405. // .unroll_inner.iv < .unrolled.iv + Factor &&
  12406. // .unroll_inner.iv < NumIterations
  12407. // \endcode
  12408. // This conjunction of two conditions allows ScalarEvolution to derive the
  12409. // maximum trip count of the inner loop.
  12410. ExprResult EndOfTile = BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(),
  12411. BO_Add, MakeOuterRef(), MakeFactorExpr());
  12412. if (!EndOfTile.isUsable())
  12413. return StmtError();
  12414. ExprResult InnerCond1 = BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(),
  12415. BO_LT, MakeInnerRef(), EndOfTile.get());
  12416. if (!InnerCond1.isUsable())
  12417. return StmtError();
  12418. ExprResult InnerCond2 =
  12419. BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(), BO_LT, MakeInnerRef(),
  12420. MakeNumIterations());
  12421. if (!InnerCond2.isUsable())
  12422. return StmtError();
  12423. ExprResult InnerCond =
  12424. BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(), BO_LAnd,
  12425. InnerCond1.get(), InnerCond2.get());
  12426. if (!InnerCond.isUsable())
  12427. return StmtError();
  12428. // Inner For incr-statement: ++.unroll_inner.iv
  12429. ExprResult InnerIncr = BuildUnaryOp(CurScope, LoopHelper.Inc->getExprLoc(),
  12430. UO_PreInc, MakeInnerRef());
  12431. if (!InnerIncr.isUsable())
  12432. return StmtError();
  12433. // Inner For statement.
  12434. SmallVector<Stmt *> InnerBodyStmts;
  12435. InnerBodyStmts.append(LoopHelper.Updates.begin(), LoopHelper.Updates.end());
  12436. InnerBodyStmts.push_back(Body);
  12437. CompoundStmt *InnerBody = CompoundStmt::Create(
  12438. Context, InnerBodyStmts, Body->getBeginLoc(), Body->getEndLoc());
  12439. ForStmt *InnerFor = new (Context)
  12440. ForStmt(Context, InnerInit.get(), InnerCond.get(), nullptr,
  12441. InnerIncr.get(), InnerBody, LoopHelper.Init->getBeginLoc(),
  12442. LoopHelper.Init->getBeginLoc(), LoopHelper.Inc->getEndLoc());
  12443. // Unroll metadata for the inner loop.
  12444. // This needs to take into account the remainder portion of the unrolled loop,
  12445. // hence `unroll(full)` does not apply here, even though the LoopUnroll pass
  12446. // supports multiple loop exits. Instead, unroll using a factor equivalent to
  12447. // the maximum trip count, which will also generate a remainder loop. Just
  12448. // `unroll(enable)` (which could have been useful if the user has not
  12449. // specified a concrete factor; even though the outer loop cannot be
  12450. // influenced anymore, would avoid more code bloat than necessary) will refuse
  12451. // the loop because "Won't unroll; remainder loop could not be generated when
  12452. // assuming runtime trip count". Even if it did work, it must not choose a
  12453. // larger unroll factor than the maximum loop length, or it would always just
  12454. // execute the remainder loop.
  12455. LoopHintAttr *UnrollHintAttr =
  12456. LoopHintAttr::CreateImplicit(Context, LoopHintAttr::UnrollCount,
  12457. LoopHintAttr::Numeric, MakeFactorExpr());
  12458. AttributedStmt *InnerUnrolled =
  12459. AttributedStmt::Create(Context, StartLoc, {UnrollHintAttr}, InnerFor);
  12460. // Outer For init-statement: auto .unrolled.iv = 0
  12461. AddInitializerToDecl(
  12462. OuterIVDecl, ActOnIntegerConstant(LoopHelper.Init->getExprLoc(), 0).get(),
  12463. /*DirectInit=*/false);
  12464. StmtResult OuterInit = new (Context)
  12465. DeclStmt(DeclGroupRef(OuterIVDecl), OrigVarLocBegin, OrigVarLocEnd);
  12466. if (!OuterInit.isUsable())
  12467. return StmtError();
  12468. // Outer For cond-expression: .unrolled.iv < NumIterations
  12469. ExprResult OuterConde =
  12470. BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(), BO_LT, MakeOuterRef(),
  12471. MakeNumIterations());
  12472. if (!OuterConde.isUsable())
  12473. return StmtError();
  12474. // Outer For incr-statement: .unrolled.iv += Factor
  12475. ExprResult OuterIncr =
  12476. BuildBinOp(CurScope, LoopHelper.Inc->getExprLoc(), BO_AddAssign,
  12477. MakeOuterRef(), MakeFactorExpr());
  12478. if (!OuterIncr.isUsable())
  12479. return StmtError();
  12480. // Outer For statement.
  12481. ForStmt *OuterFor = new (Context)
  12482. ForStmt(Context, OuterInit.get(), OuterConde.get(), nullptr,
  12483. OuterIncr.get(), InnerUnrolled, LoopHelper.Init->getBeginLoc(),
  12484. LoopHelper.Init->getBeginLoc(), LoopHelper.Inc->getEndLoc());
  12485. return OMPUnrollDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
  12486. NumGeneratedLoops, OuterFor,
  12487. buildPreInits(Context, PreInits));
  12488. }
  12489. OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
  12490. SourceLocation StartLoc,
  12491. SourceLocation LParenLoc,
  12492. SourceLocation EndLoc) {
  12493. OMPClause *Res = nullptr;
  12494. switch (Kind) {
  12495. case OMPC_final:
  12496. Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
  12497. break;
  12498. case OMPC_num_threads:
  12499. Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
  12500. break;
  12501. case OMPC_safelen:
  12502. Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
  12503. break;
  12504. case OMPC_simdlen:
  12505. Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
  12506. break;
  12507. case OMPC_allocator:
  12508. Res = ActOnOpenMPAllocatorClause(Expr, StartLoc, LParenLoc, EndLoc);
  12509. break;
  12510. case OMPC_collapse:
  12511. Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
  12512. break;
  12513. case OMPC_ordered:
  12514. Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
  12515. break;
  12516. case OMPC_num_teams:
  12517. Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
  12518. break;
  12519. case OMPC_thread_limit:
  12520. Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
  12521. break;
  12522. case OMPC_priority:
  12523. Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
  12524. break;
  12525. case OMPC_grainsize:
  12526. Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
  12527. break;
  12528. case OMPC_num_tasks:
  12529. Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
  12530. break;
  12531. case OMPC_hint:
  12532. Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
  12533. break;
  12534. case OMPC_depobj:
  12535. Res = ActOnOpenMPDepobjClause(Expr, StartLoc, LParenLoc, EndLoc);
  12536. break;
  12537. case OMPC_detach:
  12538. Res = ActOnOpenMPDetachClause(Expr, StartLoc, LParenLoc, EndLoc);
  12539. break;
  12540. case OMPC_novariants:
  12541. Res = ActOnOpenMPNovariantsClause(Expr, StartLoc, LParenLoc, EndLoc);
  12542. break;
  12543. case OMPC_nocontext:
  12544. Res = ActOnOpenMPNocontextClause(Expr, StartLoc, LParenLoc, EndLoc);
  12545. break;
  12546. case OMPC_filter:
  12547. Res = ActOnOpenMPFilterClause(Expr, StartLoc, LParenLoc, EndLoc);
  12548. break;
  12549. case OMPC_partial:
  12550. Res = ActOnOpenMPPartialClause(Expr, StartLoc, LParenLoc, EndLoc);
  12551. break;
  12552. case OMPC_align:
  12553. Res = ActOnOpenMPAlignClause(Expr, StartLoc, LParenLoc, EndLoc);
  12554. break;
  12555. case OMPC_device:
  12556. case OMPC_if:
  12557. case OMPC_default:
  12558. case OMPC_proc_bind:
  12559. case OMPC_schedule:
  12560. case OMPC_private:
  12561. case OMPC_firstprivate:
  12562. case OMPC_lastprivate:
  12563. case OMPC_shared:
  12564. case OMPC_reduction:
  12565. case OMPC_task_reduction:
  12566. case OMPC_in_reduction:
  12567. case OMPC_linear:
  12568. case OMPC_aligned:
  12569. case OMPC_copyin:
  12570. case OMPC_copyprivate:
  12571. case OMPC_nowait:
  12572. case OMPC_untied:
  12573. case OMPC_mergeable:
  12574. case OMPC_threadprivate:
  12575. case OMPC_sizes:
  12576. case OMPC_allocate:
  12577. case OMPC_flush:
  12578. case OMPC_read:
  12579. case OMPC_write:
  12580. case OMPC_update:
  12581. case OMPC_capture:
  12582. case OMPC_compare:
  12583. case OMPC_seq_cst:
  12584. case OMPC_acq_rel:
  12585. case OMPC_acquire:
  12586. case OMPC_release:
  12587. case OMPC_relaxed:
  12588. case OMPC_depend:
  12589. case OMPC_threads:
  12590. case OMPC_simd:
  12591. case OMPC_map:
  12592. case OMPC_nogroup:
  12593. case OMPC_dist_schedule:
  12594. case OMPC_defaultmap:
  12595. case OMPC_unknown:
  12596. case OMPC_uniform:
  12597. case OMPC_to:
  12598. case OMPC_from:
  12599. case OMPC_use_device_ptr:
  12600. case OMPC_use_device_addr:
  12601. case OMPC_is_device_ptr:
  12602. case OMPC_unified_address:
  12603. case OMPC_unified_shared_memory:
  12604. case OMPC_reverse_offload:
  12605. case OMPC_dynamic_allocators:
  12606. case OMPC_atomic_default_mem_order:
  12607. case OMPC_device_type:
  12608. case OMPC_match:
  12609. case OMPC_nontemporal:
  12610. case OMPC_order:
  12611. case OMPC_destroy:
  12612. case OMPC_inclusive:
  12613. case OMPC_exclusive:
  12614. case OMPC_uses_allocators:
  12615. case OMPC_affinity:
  12616. case OMPC_when:
  12617. case OMPC_bind:
  12618. default:
  12619. llvm_unreachable("Clause is not allowed.");
  12620. }
  12621. return Res;
  12622. }
  12623. // An OpenMP directive such as 'target parallel' has two captured regions:
  12624. // for the 'target' and 'parallel' respectively. This function returns
  12625. // the region in which to capture expressions associated with a clause.
  12626. // A return value of OMPD_unknown signifies that the expression should not
  12627. // be captured.
  12628. static OpenMPDirectiveKind getOpenMPCaptureRegionForClause(
  12629. OpenMPDirectiveKind DKind, OpenMPClauseKind CKind, unsigned OpenMPVersion,
  12630. OpenMPDirectiveKind NameModifier = OMPD_unknown) {
  12631. OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
  12632. switch (CKind) {
  12633. case OMPC_if:
  12634. switch (DKind) {
  12635. case OMPD_target_parallel_for_simd:
  12636. if (OpenMPVersion >= 50 &&
  12637. (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)) {
  12638. CaptureRegion = OMPD_parallel;
  12639. break;
  12640. }
  12641. LLVM_FALLTHROUGH;
  12642. case OMPD_target_parallel:
  12643. case OMPD_target_parallel_for:
  12644. // If this clause applies to the nested 'parallel' region, capture within
  12645. // the 'target' region, otherwise do not capture.
  12646. if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
  12647. CaptureRegion = OMPD_target;
  12648. break;
  12649. case OMPD_target_teams_distribute_parallel_for_simd:
  12650. if (OpenMPVersion >= 50 &&
  12651. (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)) {
  12652. CaptureRegion = OMPD_parallel;
  12653. break;
  12654. }
  12655. LLVM_FALLTHROUGH;
  12656. case OMPD_target_teams_distribute_parallel_for:
  12657. // If this clause applies to the nested 'parallel' region, capture within
  12658. // the 'teams' region, otherwise do not capture.
  12659. if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
  12660. CaptureRegion = OMPD_teams;
  12661. break;
  12662. case OMPD_teams_distribute_parallel_for_simd:
  12663. if (OpenMPVersion >= 50 &&
  12664. (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)) {
  12665. CaptureRegion = OMPD_parallel;
  12666. break;
  12667. }
  12668. LLVM_FALLTHROUGH;
  12669. case OMPD_teams_distribute_parallel_for:
  12670. CaptureRegion = OMPD_teams;
  12671. break;
  12672. case OMPD_target_update:
  12673. case OMPD_target_enter_data:
  12674. case OMPD_target_exit_data:
  12675. CaptureRegion = OMPD_task;
  12676. break;
  12677. case OMPD_parallel_master_taskloop:
  12678. if (NameModifier == OMPD_unknown || NameModifier == OMPD_taskloop)
  12679. CaptureRegion = OMPD_parallel;
  12680. break;
  12681. case OMPD_parallel_master_taskloop_simd:
  12682. if ((OpenMPVersion <= 45 && NameModifier == OMPD_unknown) ||
  12683. NameModifier == OMPD_taskloop) {
  12684. CaptureRegion = OMPD_parallel;
  12685. break;
  12686. }
  12687. if (OpenMPVersion <= 45)
  12688. break;
  12689. if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)
  12690. CaptureRegion = OMPD_taskloop;
  12691. break;
  12692. case OMPD_parallel_for_simd:
  12693. if (OpenMPVersion <= 45)
  12694. break;
  12695. if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)
  12696. CaptureRegion = OMPD_parallel;
  12697. break;
  12698. case OMPD_taskloop_simd:
  12699. case OMPD_master_taskloop_simd:
  12700. if (OpenMPVersion <= 45)
  12701. break;
  12702. if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)
  12703. CaptureRegion = OMPD_taskloop;
  12704. break;
  12705. case OMPD_distribute_parallel_for_simd:
  12706. if (OpenMPVersion <= 45)
  12707. break;
  12708. if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)
  12709. CaptureRegion = OMPD_parallel;
  12710. break;
  12711. case OMPD_target_simd:
  12712. if (OpenMPVersion >= 50 &&
  12713. (NameModifier == OMPD_unknown || NameModifier == OMPD_simd))
  12714. CaptureRegion = OMPD_target;
  12715. break;
  12716. case OMPD_teams_distribute_simd:
  12717. case OMPD_target_teams_distribute_simd:
  12718. if (OpenMPVersion >= 50 &&
  12719. (NameModifier == OMPD_unknown || NameModifier == OMPD_simd))
  12720. CaptureRegion = OMPD_teams;
  12721. break;
  12722. case OMPD_cancel:
  12723. case OMPD_parallel:
  12724. case OMPD_parallel_master:
  12725. case OMPD_parallel_sections:
  12726. case OMPD_parallel_for:
  12727. case OMPD_target:
  12728. case OMPD_target_teams:
  12729. case OMPD_target_teams_distribute:
  12730. case OMPD_distribute_parallel_for:
  12731. case OMPD_task:
  12732. case OMPD_taskloop:
  12733. case OMPD_master_taskloop:
  12734. case OMPD_target_data:
  12735. case OMPD_simd:
  12736. case OMPD_for_simd:
  12737. case OMPD_distribute_simd:
  12738. // Do not capture if-clause expressions.
  12739. break;
  12740. case OMPD_threadprivate:
  12741. case OMPD_allocate:
  12742. case OMPD_taskyield:
  12743. case OMPD_barrier:
  12744. case OMPD_taskwait:
  12745. case OMPD_cancellation_point:
  12746. case OMPD_flush:
  12747. case OMPD_depobj:
  12748. case OMPD_scan:
  12749. case OMPD_declare_reduction:
  12750. case OMPD_declare_mapper:
  12751. case OMPD_declare_simd:
  12752. case OMPD_declare_variant:
  12753. case OMPD_begin_declare_variant:
  12754. case OMPD_end_declare_variant:
  12755. case OMPD_declare_target:
  12756. case OMPD_end_declare_target:
  12757. case OMPD_loop:
  12758. case OMPD_teams:
  12759. case OMPD_tile:
  12760. case OMPD_unroll:
  12761. case OMPD_for:
  12762. case OMPD_sections:
  12763. case OMPD_section:
  12764. case OMPD_single:
  12765. case OMPD_master:
  12766. case OMPD_masked:
  12767. case OMPD_critical:
  12768. case OMPD_taskgroup:
  12769. case OMPD_distribute:
  12770. case OMPD_ordered:
  12771. case OMPD_atomic:
  12772. case OMPD_teams_distribute:
  12773. case OMPD_requires:
  12774. case OMPD_metadirective:
  12775. llvm_unreachable("Unexpected OpenMP directive with if-clause");
  12776. case OMPD_unknown:
  12777. default:
  12778. llvm_unreachable("Unknown OpenMP directive");
  12779. }
  12780. break;
  12781. case OMPC_num_threads:
  12782. switch (DKind) {
  12783. case OMPD_target_parallel:
  12784. case OMPD_target_parallel_for:
  12785. case OMPD_target_parallel_for_simd:
  12786. CaptureRegion = OMPD_target;
  12787. break;
  12788. case OMPD_teams_distribute_parallel_for:
  12789. case OMPD_teams_distribute_parallel_for_simd:
  12790. case OMPD_target_teams_distribute_parallel_for:
  12791. case OMPD_target_teams_distribute_parallel_for_simd:
  12792. CaptureRegion = OMPD_teams;
  12793. break;
  12794. case OMPD_parallel:
  12795. case OMPD_parallel_master:
  12796. case OMPD_parallel_sections:
  12797. case OMPD_parallel_for:
  12798. case OMPD_parallel_for_simd:
  12799. case OMPD_distribute_parallel_for:
  12800. case OMPD_distribute_parallel_for_simd:
  12801. case OMPD_parallel_master_taskloop:
  12802. case OMPD_parallel_master_taskloop_simd:
  12803. // Do not capture num_threads-clause expressions.
  12804. break;
  12805. case OMPD_target_data:
  12806. case OMPD_target_enter_data:
  12807. case OMPD_target_exit_data:
  12808. case OMPD_target_update:
  12809. case OMPD_target:
  12810. case OMPD_target_simd:
  12811. case OMPD_target_teams:
  12812. case OMPD_target_teams_distribute:
  12813. case OMPD_target_teams_distribute_simd:
  12814. case OMPD_cancel:
  12815. case OMPD_task:
  12816. case OMPD_taskloop:
  12817. case OMPD_taskloop_simd:
  12818. case OMPD_master_taskloop:
  12819. case OMPD_master_taskloop_simd:
  12820. case OMPD_threadprivate:
  12821. case OMPD_allocate:
  12822. case OMPD_taskyield:
  12823. case OMPD_barrier:
  12824. case OMPD_taskwait:
  12825. case OMPD_cancellation_point:
  12826. case OMPD_flush:
  12827. case OMPD_depobj:
  12828. case OMPD_scan:
  12829. case OMPD_declare_reduction:
  12830. case OMPD_declare_mapper:
  12831. case OMPD_declare_simd:
  12832. case OMPD_declare_variant:
  12833. case OMPD_begin_declare_variant:
  12834. case OMPD_end_declare_variant:
  12835. case OMPD_declare_target:
  12836. case OMPD_end_declare_target:
  12837. case OMPD_loop:
  12838. case OMPD_teams:
  12839. case OMPD_simd:
  12840. case OMPD_tile:
  12841. case OMPD_unroll:
  12842. case OMPD_for:
  12843. case OMPD_for_simd:
  12844. case OMPD_sections:
  12845. case OMPD_section:
  12846. case OMPD_single:
  12847. case OMPD_master:
  12848. case OMPD_masked:
  12849. case OMPD_critical:
  12850. case OMPD_taskgroup:
  12851. case OMPD_distribute:
  12852. case OMPD_ordered:
  12853. case OMPD_atomic:
  12854. case OMPD_distribute_simd:
  12855. case OMPD_teams_distribute:
  12856. case OMPD_teams_distribute_simd:
  12857. case OMPD_requires:
  12858. case OMPD_metadirective:
  12859. llvm_unreachable("Unexpected OpenMP directive with num_threads-clause");
  12860. case OMPD_unknown:
  12861. default:
  12862. llvm_unreachable("Unknown OpenMP directive");
  12863. }
  12864. break;
  12865. case OMPC_num_teams:
  12866. switch (DKind) {
  12867. case OMPD_target_teams:
  12868. case OMPD_target_teams_distribute:
  12869. case OMPD_target_teams_distribute_simd:
  12870. case OMPD_target_teams_distribute_parallel_for:
  12871. case OMPD_target_teams_distribute_parallel_for_simd:
  12872. CaptureRegion = OMPD_target;
  12873. break;
  12874. case OMPD_teams_distribute_parallel_for:
  12875. case OMPD_teams_distribute_parallel_for_simd:
  12876. case OMPD_teams:
  12877. case OMPD_teams_distribute:
  12878. case OMPD_teams_distribute_simd:
  12879. // Do not capture num_teams-clause expressions.
  12880. break;
  12881. case OMPD_distribute_parallel_for:
  12882. case OMPD_distribute_parallel_for_simd:
  12883. case OMPD_task:
  12884. case OMPD_taskloop:
  12885. case OMPD_taskloop_simd:
  12886. case OMPD_master_taskloop:
  12887. case OMPD_master_taskloop_simd:
  12888. case OMPD_parallel_master_taskloop:
  12889. case OMPD_parallel_master_taskloop_simd:
  12890. case OMPD_target_data:
  12891. case OMPD_target_enter_data:
  12892. case OMPD_target_exit_data:
  12893. case OMPD_target_update:
  12894. case OMPD_cancel:
  12895. case OMPD_parallel:
  12896. case OMPD_parallel_master:
  12897. case OMPD_parallel_sections:
  12898. case OMPD_parallel_for:
  12899. case OMPD_parallel_for_simd:
  12900. case OMPD_target:
  12901. case OMPD_target_simd:
  12902. case OMPD_target_parallel:
  12903. case OMPD_target_parallel_for:
  12904. case OMPD_target_parallel_for_simd:
  12905. case OMPD_threadprivate:
  12906. case OMPD_allocate:
  12907. case OMPD_taskyield:
  12908. case OMPD_barrier:
  12909. case OMPD_taskwait:
  12910. case OMPD_cancellation_point:
  12911. case OMPD_flush:
  12912. case OMPD_depobj:
  12913. case OMPD_scan:
  12914. case OMPD_declare_reduction:
  12915. case OMPD_declare_mapper:
  12916. case OMPD_declare_simd:
  12917. case OMPD_declare_variant:
  12918. case OMPD_begin_declare_variant:
  12919. case OMPD_end_declare_variant:
  12920. case OMPD_declare_target:
  12921. case OMPD_end_declare_target:
  12922. case OMPD_loop:
  12923. case OMPD_simd:
  12924. case OMPD_tile:
  12925. case OMPD_unroll:
  12926. case OMPD_for:
  12927. case OMPD_for_simd:
  12928. case OMPD_sections:
  12929. case OMPD_section:
  12930. case OMPD_single:
  12931. case OMPD_master:
  12932. case OMPD_masked:
  12933. case OMPD_critical:
  12934. case OMPD_taskgroup:
  12935. case OMPD_distribute:
  12936. case OMPD_ordered:
  12937. case OMPD_atomic:
  12938. case OMPD_distribute_simd:
  12939. case OMPD_requires:
  12940. case OMPD_metadirective:
  12941. llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
  12942. case OMPD_unknown:
  12943. default:
  12944. llvm_unreachable("Unknown OpenMP directive");
  12945. }
  12946. break;
  12947. case OMPC_thread_limit:
  12948. switch (DKind) {
  12949. case OMPD_target_teams:
  12950. case OMPD_target_teams_distribute:
  12951. case OMPD_target_teams_distribute_simd:
  12952. case OMPD_target_teams_distribute_parallel_for:
  12953. case OMPD_target_teams_distribute_parallel_for_simd:
  12954. CaptureRegion = OMPD_target;
  12955. break;
  12956. case OMPD_teams_distribute_parallel_for:
  12957. case OMPD_teams_distribute_parallel_for_simd:
  12958. case OMPD_teams:
  12959. case OMPD_teams_distribute:
  12960. case OMPD_teams_distribute_simd:
  12961. // Do not capture thread_limit-clause expressions.
  12962. break;
  12963. case OMPD_distribute_parallel_for:
  12964. case OMPD_distribute_parallel_for_simd:
  12965. case OMPD_task:
  12966. case OMPD_taskloop:
  12967. case OMPD_taskloop_simd:
  12968. case OMPD_master_taskloop:
  12969. case OMPD_master_taskloop_simd:
  12970. case OMPD_parallel_master_taskloop:
  12971. case OMPD_parallel_master_taskloop_simd:
  12972. case OMPD_target_data:
  12973. case OMPD_target_enter_data:
  12974. case OMPD_target_exit_data:
  12975. case OMPD_target_update:
  12976. case OMPD_cancel:
  12977. case OMPD_parallel:
  12978. case OMPD_parallel_master:
  12979. case OMPD_parallel_sections:
  12980. case OMPD_parallel_for:
  12981. case OMPD_parallel_for_simd:
  12982. case OMPD_target:
  12983. case OMPD_target_simd:
  12984. case OMPD_target_parallel:
  12985. case OMPD_target_parallel_for:
  12986. case OMPD_target_parallel_for_simd:
  12987. case OMPD_threadprivate:
  12988. case OMPD_allocate:
  12989. case OMPD_taskyield:
  12990. case OMPD_barrier:
  12991. case OMPD_taskwait:
  12992. case OMPD_cancellation_point:
  12993. case OMPD_flush:
  12994. case OMPD_depobj:
  12995. case OMPD_scan:
  12996. case OMPD_declare_reduction:
  12997. case OMPD_declare_mapper:
  12998. case OMPD_declare_simd:
  12999. case OMPD_declare_variant:
  13000. case OMPD_begin_declare_variant:
  13001. case OMPD_end_declare_variant:
  13002. case OMPD_declare_target:
  13003. case OMPD_end_declare_target:
  13004. case OMPD_loop:
  13005. case OMPD_simd:
  13006. case OMPD_tile:
  13007. case OMPD_unroll:
  13008. case OMPD_for:
  13009. case OMPD_for_simd:
  13010. case OMPD_sections:
  13011. case OMPD_section:
  13012. case OMPD_single:
  13013. case OMPD_master:
  13014. case OMPD_masked:
  13015. case OMPD_critical:
  13016. case OMPD_taskgroup:
  13017. case OMPD_distribute:
  13018. case OMPD_ordered:
  13019. case OMPD_atomic:
  13020. case OMPD_distribute_simd:
  13021. case OMPD_requires:
  13022. case OMPD_metadirective:
  13023. llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause");
  13024. case OMPD_unknown:
  13025. default:
  13026. llvm_unreachable("Unknown OpenMP directive");
  13027. }
  13028. break;
  13029. case OMPC_schedule:
  13030. switch (DKind) {
  13031. case OMPD_parallel_for:
  13032. case OMPD_parallel_for_simd:
  13033. case OMPD_distribute_parallel_for:
  13034. case OMPD_distribute_parallel_for_simd:
  13035. case OMPD_teams_distribute_parallel_for:
  13036. case OMPD_teams_distribute_parallel_for_simd:
  13037. case OMPD_target_parallel_for:
  13038. case OMPD_target_parallel_for_simd:
  13039. case OMPD_target_teams_distribute_parallel_for:
  13040. case OMPD_target_teams_distribute_parallel_for_simd:
  13041. CaptureRegion = OMPD_parallel;
  13042. break;
  13043. case OMPD_for:
  13044. case OMPD_for_simd:
  13045. // Do not capture schedule-clause expressions.
  13046. break;
  13047. case OMPD_task:
  13048. case OMPD_taskloop:
  13049. case OMPD_taskloop_simd:
  13050. case OMPD_master_taskloop:
  13051. case OMPD_master_taskloop_simd:
  13052. case OMPD_parallel_master_taskloop:
  13053. case OMPD_parallel_master_taskloop_simd:
  13054. case OMPD_target_data:
  13055. case OMPD_target_enter_data:
  13056. case OMPD_target_exit_data:
  13057. case OMPD_target_update:
  13058. case OMPD_teams:
  13059. case OMPD_teams_distribute:
  13060. case OMPD_teams_distribute_simd:
  13061. case OMPD_target_teams_distribute:
  13062. case OMPD_target_teams_distribute_simd:
  13063. case OMPD_target:
  13064. case OMPD_target_simd:
  13065. case OMPD_target_parallel:
  13066. case OMPD_cancel:
  13067. case OMPD_parallel:
  13068. case OMPD_parallel_master:
  13069. case OMPD_parallel_sections:
  13070. case OMPD_threadprivate:
  13071. case OMPD_allocate:
  13072. case OMPD_taskyield:
  13073. case OMPD_barrier:
  13074. case OMPD_taskwait:
  13075. case OMPD_cancellation_point:
  13076. case OMPD_flush:
  13077. case OMPD_depobj:
  13078. case OMPD_scan:
  13079. case OMPD_declare_reduction:
  13080. case OMPD_declare_mapper:
  13081. case OMPD_declare_simd:
  13082. case OMPD_declare_variant:
  13083. case OMPD_begin_declare_variant:
  13084. case OMPD_end_declare_variant:
  13085. case OMPD_declare_target:
  13086. case OMPD_end_declare_target:
  13087. case OMPD_loop:
  13088. case OMPD_simd:
  13089. case OMPD_tile:
  13090. case OMPD_unroll:
  13091. case OMPD_sections:
  13092. case OMPD_section:
  13093. case OMPD_single:
  13094. case OMPD_master:
  13095. case OMPD_masked:
  13096. case OMPD_critical:
  13097. case OMPD_taskgroup:
  13098. case OMPD_distribute:
  13099. case OMPD_ordered:
  13100. case OMPD_atomic:
  13101. case OMPD_distribute_simd:
  13102. case OMPD_target_teams:
  13103. case OMPD_requires:
  13104. case OMPD_metadirective:
  13105. llvm_unreachable("Unexpected OpenMP directive with schedule clause");
  13106. case OMPD_unknown:
  13107. default:
  13108. llvm_unreachable("Unknown OpenMP directive");
  13109. }
  13110. break;
  13111. case OMPC_dist_schedule:
  13112. switch (DKind) {
  13113. case OMPD_teams_distribute_parallel_for:
  13114. case OMPD_teams_distribute_parallel_for_simd:
  13115. case OMPD_teams_distribute:
  13116. case OMPD_teams_distribute_simd:
  13117. case OMPD_target_teams_distribute_parallel_for:
  13118. case OMPD_target_teams_distribute_parallel_for_simd:
  13119. case OMPD_target_teams_distribute:
  13120. case OMPD_target_teams_distribute_simd:
  13121. CaptureRegion = OMPD_teams;
  13122. break;
  13123. case OMPD_distribute_parallel_for:
  13124. case OMPD_distribute_parallel_for_simd:
  13125. case OMPD_distribute:
  13126. case OMPD_distribute_simd:
  13127. // Do not capture dist_schedule-clause expressions.
  13128. break;
  13129. case OMPD_parallel_for:
  13130. case OMPD_parallel_for_simd:
  13131. case OMPD_target_parallel_for_simd:
  13132. case OMPD_target_parallel_for:
  13133. case OMPD_task:
  13134. case OMPD_taskloop:
  13135. case OMPD_taskloop_simd:
  13136. case OMPD_master_taskloop:
  13137. case OMPD_master_taskloop_simd:
  13138. case OMPD_parallel_master_taskloop:
  13139. case OMPD_parallel_master_taskloop_simd:
  13140. case OMPD_target_data:
  13141. case OMPD_target_enter_data:
  13142. case OMPD_target_exit_data:
  13143. case OMPD_target_update:
  13144. case OMPD_teams:
  13145. case OMPD_target:
  13146. case OMPD_target_simd:
  13147. case OMPD_target_parallel:
  13148. case OMPD_cancel:
  13149. case OMPD_parallel:
  13150. case OMPD_parallel_master:
  13151. case OMPD_parallel_sections:
  13152. case OMPD_threadprivate:
  13153. case OMPD_allocate:
  13154. case OMPD_taskyield:
  13155. case OMPD_barrier:
  13156. case OMPD_taskwait:
  13157. case OMPD_cancellation_point:
  13158. case OMPD_flush:
  13159. case OMPD_depobj:
  13160. case OMPD_scan:
  13161. case OMPD_declare_reduction:
  13162. case OMPD_declare_mapper:
  13163. case OMPD_declare_simd:
  13164. case OMPD_declare_variant:
  13165. case OMPD_begin_declare_variant:
  13166. case OMPD_end_declare_variant:
  13167. case OMPD_declare_target:
  13168. case OMPD_end_declare_target:
  13169. case OMPD_loop:
  13170. case OMPD_simd:
  13171. case OMPD_tile:
  13172. case OMPD_unroll:
  13173. case OMPD_for:
  13174. case OMPD_for_simd:
  13175. case OMPD_sections:
  13176. case OMPD_section:
  13177. case OMPD_single:
  13178. case OMPD_master:
  13179. case OMPD_masked:
  13180. case OMPD_critical:
  13181. case OMPD_taskgroup:
  13182. case OMPD_ordered:
  13183. case OMPD_atomic:
  13184. case OMPD_target_teams:
  13185. case OMPD_requires:
  13186. case OMPD_metadirective:
  13187. llvm_unreachable("Unexpected OpenMP directive with dist_schedule clause");
  13188. case OMPD_unknown:
  13189. default:
  13190. llvm_unreachable("Unknown OpenMP directive");
  13191. }
  13192. break;
  13193. case OMPC_device:
  13194. switch (DKind) {
  13195. case OMPD_target_update:
  13196. case OMPD_target_enter_data:
  13197. case OMPD_target_exit_data:
  13198. case OMPD_target:
  13199. case OMPD_target_simd:
  13200. case OMPD_target_teams:
  13201. case OMPD_target_parallel:
  13202. case OMPD_target_teams_distribute:
  13203. case OMPD_target_teams_distribute_simd:
  13204. case OMPD_target_parallel_for:
  13205. case OMPD_target_parallel_for_simd:
  13206. case OMPD_target_teams_distribute_parallel_for:
  13207. case OMPD_target_teams_distribute_parallel_for_simd:
  13208. case OMPD_dispatch:
  13209. CaptureRegion = OMPD_task;
  13210. break;
  13211. case OMPD_target_data:
  13212. case OMPD_interop:
  13213. // Do not capture device-clause expressions.
  13214. break;
  13215. case OMPD_teams_distribute_parallel_for:
  13216. case OMPD_teams_distribute_parallel_for_simd:
  13217. case OMPD_teams:
  13218. case OMPD_teams_distribute:
  13219. case OMPD_teams_distribute_simd:
  13220. case OMPD_distribute_parallel_for:
  13221. case OMPD_distribute_parallel_for_simd:
  13222. case OMPD_task:
  13223. case OMPD_taskloop:
  13224. case OMPD_taskloop_simd:
  13225. case OMPD_master_taskloop:
  13226. case OMPD_master_taskloop_simd:
  13227. case OMPD_parallel_master_taskloop:
  13228. case OMPD_parallel_master_taskloop_simd:
  13229. case OMPD_cancel:
  13230. case OMPD_parallel:
  13231. case OMPD_parallel_master:
  13232. case OMPD_parallel_sections:
  13233. case OMPD_parallel_for:
  13234. case OMPD_parallel_for_simd:
  13235. case OMPD_threadprivate:
  13236. case OMPD_allocate:
  13237. case OMPD_taskyield:
  13238. case OMPD_barrier:
  13239. case OMPD_taskwait:
  13240. case OMPD_cancellation_point:
  13241. case OMPD_flush:
  13242. case OMPD_depobj:
  13243. case OMPD_scan:
  13244. case OMPD_declare_reduction:
  13245. case OMPD_declare_mapper:
  13246. case OMPD_declare_simd:
  13247. case OMPD_declare_variant:
  13248. case OMPD_begin_declare_variant:
  13249. case OMPD_end_declare_variant:
  13250. case OMPD_declare_target:
  13251. case OMPD_end_declare_target:
  13252. case OMPD_loop:
  13253. case OMPD_simd:
  13254. case OMPD_tile:
  13255. case OMPD_unroll:
  13256. case OMPD_for:
  13257. case OMPD_for_simd:
  13258. case OMPD_sections:
  13259. case OMPD_section:
  13260. case OMPD_single:
  13261. case OMPD_master:
  13262. case OMPD_masked:
  13263. case OMPD_critical:
  13264. case OMPD_taskgroup:
  13265. case OMPD_distribute:
  13266. case OMPD_ordered:
  13267. case OMPD_atomic:
  13268. case OMPD_distribute_simd:
  13269. case OMPD_requires:
  13270. case OMPD_metadirective:
  13271. llvm_unreachable("Unexpected OpenMP directive with device-clause");
  13272. case OMPD_unknown:
  13273. default:
  13274. llvm_unreachable("Unknown OpenMP directive");
  13275. }
  13276. break;
  13277. case OMPC_grainsize:
  13278. case OMPC_num_tasks:
  13279. case OMPC_final:
  13280. case OMPC_priority:
  13281. switch (DKind) {
  13282. case OMPD_task:
  13283. case OMPD_taskloop:
  13284. case OMPD_taskloop_simd:
  13285. case OMPD_master_taskloop:
  13286. case OMPD_master_taskloop_simd:
  13287. break;
  13288. case OMPD_parallel_master_taskloop:
  13289. case OMPD_parallel_master_taskloop_simd:
  13290. CaptureRegion = OMPD_parallel;
  13291. break;
  13292. case OMPD_target_update:
  13293. case OMPD_target_enter_data:
  13294. case OMPD_target_exit_data:
  13295. case OMPD_target:
  13296. case OMPD_target_simd:
  13297. case OMPD_target_teams:
  13298. case OMPD_target_parallel:
  13299. case OMPD_target_teams_distribute:
  13300. case OMPD_target_teams_distribute_simd:
  13301. case OMPD_target_parallel_for:
  13302. case OMPD_target_parallel_for_simd:
  13303. case OMPD_target_teams_distribute_parallel_for:
  13304. case OMPD_target_teams_distribute_parallel_for_simd:
  13305. case OMPD_target_data:
  13306. case OMPD_teams_distribute_parallel_for:
  13307. case OMPD_teams_distribute_parallel_for_simd:
  13308. case OMPD_teams:
  13309. case OMPD_teams_distribute:
  13310. case OMPD_teams_distribute_simd:
  13311. case OMPD_distribute_parallel_for:
  13312. case OMPD_distribute_parallel_for_simd:
  13313. case OMPD_cancel:
  13314. case OMPD_parallel:
  13315. case OMPD_parallel_master:
  13316. case OMPD_parallel_sections:
  13317. case OMPD_parallel_for:
  13318. case OMPD_parallel_for_simd:
  13319. case OMPD_threadprivate:
  13320. case OMPD_allocate:
  13321. case OMPD_taskyield:
  13322. case OMPD_barrier:
  13323. case OMPD_taskwait:
  13324. case OMPD_cancellation_point:
  13325. case OMPD_flush:
  13326. case OMPD_depobj:
  13327. case OMPD_scan:
  13328. case OMPD_declare_reduction:
  13329. case OMPD_declare_mapper:
  13330. case OMPD_declare_simd:
  13331. case OMPD_declare_variant:
  13332. case OMPD_begin_declare_variant:
  13333. case OMPD_end_declare_variant:
  13334. case OMPD_declare_target:
  13335. case OMPD_end_declare_target:
  13336. case OMPD_loop:
  13337. case OMPD_simd:
  13338. case OMPD_tile:
  13339. case OMPD_unroll:
  13340. case OMPD_for:
  13341. case OMPD_for_simd:
  13342. case OMPD_sections:
  13343. case OMPD_section:
  13344. case OMPD_single:
  13345. case OMPD_master:
  13346. case OMPD_masked:
  13347. case OMPD_critical:
  13348. case OMPD_taskgroup:
  13349. case OMPD_distribute:
  13350. case OMPD_ordered:
  13351. case OMPD_atomic:
  13352. case OMPD_distribute_simd:
  13353. case OMPD_requires:
  13354. case OMPD_metadirective:
  13355. llvm_unreachable("Unexpected OpenMP directive with grainsize-clause");
  13356. case OMPD_unknown:
  13357. default:
  13358. llvm_unreachable("Unknown OpenMP directive");
  13359. }
  13360. break;
  13361. case OMPC_novariants:
  13362. case OMPC_nocontext:
  13363. switch (DKind) {
  13364. case OMPD_dispatch:
  13365. CaptureRegion = OMPD_task;
  13366. break;
  13367. default:
  13368. llvm_unreachable("Unexpected OpenMP directive");
  13369. }
  13370. break;
  13371. case OMPC_filter:
  13372. // Do not capture filter-clause expressions.
  13373. break;
  13374. case OMPC_when:
  13375. if (DKind == OMPD_metadirective) {
  13376. CaptureRegion = OMPD_metadirective;
  13377. } else if (DKind == OMPD_unknown) {
  13378. llvm_unreachable("Unknown OpenMP directive");
  13379. } else {
  13380. llvm_unreachable("Unexpected OpenMP directive with when clause");
  13381. }
  13382. break;
  13383. case OMPC_firstprivate:
  13384. case OMPC_lastprivate:
  13385. case OMPC_reduction:
  13386. case OMPC_task_reduction:
  13387. case OMPC_in_reduction:
  13388. case OMPC_linear:
  13389. case OMPC_default:
  13390. case OMPC_proc_bind:
  13391. case OMPC_safelen:
  13392. case OMPC_simdlen:
  13393. case OMPC_sizes:
  13394. case OMPC_allocator:
  13395. case OMPC_collapse:
  13396. case OMPC_private:
  13397. case OMPC_shared:
  13398. case OMPC_aligned:
  13399. case OMPC_copyin:
  13400. case OMPC_copyprivate:
  13401. case OMPC_ordered:
  13402. case OMPC_nowait:
  13403. case OMPC_untied:
  13404. case OMPC_mergeable:
  13405. case OMPC_threadprivate:
  13406. case OMPC_allocate:
  13407. case OMPC_flush:
  13408. case OMPC_depobj:
  13409. case OMPC_read:
  13410. case OMPC_write:
  13411. case OMPC_update:
  13412. case OMPC_capture:
  13413. case OMPC_compare:
  13414. case OMPC_seq_cst:
  13415. case OMPC_acq_rel:
  13416. case OMPC_acquire:
  13417. case OMPC_release:
  13418. case OMPC_relaxed:
  13419. case OMPC_depend:
  13420. case OMPC_threads:
  13421. case OMPC_simd:
  13422. case OMPC_map:
  13423. case OMPC_nogroup:
  13424. case OMPC_hint:
  13425. case OMPC_defaultmap:
  13426. case OMPC_unknown:
  13427. case OMPC_uniform:
  13428. case OMPC_to:
  13429. case OMPC_from:
  13430. case OMPC_use_device_ptr:
  13431. case OMPC_use_device_addr:
  13432. case OMPC_is_device_ptr:
  13433. case OMPC_unified_address:
  13434. case OMPC_unified_shared_memory:
  13435. case OMPC_reverse_offload:
  13436. case OMPC_dynamic_allocators:
  13437. case OMPC_atomic_default_mem_order:
  13438. case OMPC_device_type:
  13439. case OMPC_match:
  13440. case OMPC_nontemporal:
  13441. case OMPC_order:
  13442. case OMPC_destroy:
  13443. case OMPC_detach:
  13444. case OMPC_inclusive:
  13445. case OMPC_exclusive:
  13446. case OMPC_uses_allocators:
  13447. case OMPC_affinity:
  13448. case OMPC_bind:
  13449. default:
  13450. llvm_unreachable("Unexpected OpenMP clause.");
  13451. }
  13452. return CaptureRegion;
  13453. }
  13454. OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
  13455. Expr *Condition, SourceLocation StartLoc,
  13456. SourceLocation LParenLoc,
  13457. SourceLocation NameModifierLoc,
  13458. SourceLocation ColonLoc,
  13459. SourceLocation EndLoc) {
  13460. Expr *ValExpr = Condition;
  13461. Stmt *HelperValStmt = nullptr;
  13462. OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
  13463. if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
  13464. !Condition->isInstantiationDependent() &&
  13465. !Condition->containsUnexpandedParameterPack()) {
  13466. ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
  13467. if (Val.isInvalid())
  13468. return nullptr;
  13469. ValExpr = Val.get();
  13470. OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
  13471. CaptureRegion = getOpenMPCaptureRegionForClause(
  13472. DKind, OMPC_if, LangOpts.OpenMP, NameModifier);
  13473. if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
  13474. ValExpr = MakeFullExpr(ValExpr).get();
  13475. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  13476. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  13477. HelperValStmt = buildPreInits(Context, Captures);
  13478. }
  13479. }
  13480. return new (Context)
  13481. OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
  13482. LParenLoc, NameModifierLoc, ColonLoc, EndLoc);
  13483. }
  13484. OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
  13485. SourceLocation StartLoc,
  13486. SourceLocation LParenLoc,
  13487. SourceLocation EndLoc) {
  13488. Expr *ValExpr = Condition;
  13489. Stmt *HelperValStmt = nullptr;
  13490. OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
  13491. if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
  13492. !Condition->isInstantiationDependent() &&
  13493. !Condition->containsUnexpandedParameterPack()) {
  13494. ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
  13495. if (Val.isInvalid())
  13496. return nullptr;
  13497. ValExpr = MakeFullExpr(Val.get()).get();
  13498. OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
  13499. CaptureRegion =
  13500. getOpenMPCaptureRegionForClause(DKind, OMPC_final, LangOpts.OpenMP);
  13501. if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
  13502. ValExpr = MakeFullExpr(ValExpr).get();
  13503. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  13504. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  13505. HelperValStmt = buildPreInits(Context, Captures);
  13506. }
  13507. }
  13508. return new (Context) OMPFinalClause(ValExpr, HelperValStmt, CaptureRegion,
  13509. StartLoc, LParenLoc, EndLoc);
  13510. }
  13511. ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
  13512. Expr *Op) {
  13513. if (!Op)
  13514. return ExprError();
  13515. class IntConvertDiagnoser : public ICEConvertDiagnoser {
  13516. public:
  13517. IntConvertDiagnoser()
  13518. : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
  13519. SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
  13520. QualType T) override {
  13521. return S.Diag(Loc, diag::err_omp_not_integral) << T;
  13522. }
  13523. SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
  13524. QualType T) override {
  13525. return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
  13526. }
  13527. SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
  13528. QualType T,
  13529. QualType ConvTy) override {
  13530. return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
  13531. }
  13532. SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
  13533. QualType ConvTy) override {
  13534. return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
  13535. << ConvTy->isEnumeralType() << ConvTy;
  13536. }
  13537. SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
  13538. QualType T) override {
  13539. return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
  13540. }
  13541. SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
  13542. QualType ConvTy) override {
  13543. return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
  13544. << ConvTy->isEnumeralType() << ConvTy;
  13545. }
  13546. SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
  13547. QualType) override {
  13548. llvm_unreachable("conversion functions are permitted");
  13549. }
  13550. } ConvertDiagnoser;
  13551. return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
  13552. }
  13553. static bool
  13554. isNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef, OpenMPClauseKind CKind,
  13555. bool StrictlyPositive, bool BuildCapture = false,
  13556. OpenMPDirectiveKind DKind = OMPD_unknown,
  13557. OpenMPDirectiveKind *CaptureRegion = nullptr,
  13558. Stmt **HelperValStmt = nullptr) {
  13559. if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
  13560. !ValExpr->isInstantiationDependent()) {
  13561. SourceLocation Loc = ValExpr->getExprLoc();
  13562. ExprResult Value =
  13563. SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
  13564. if (Value.isInvalid())
  13565. return false;
  13566. ValExpr = Value.get();
  13567. // The expression must evaluate to a non-negative integer value.
  13568. if (Optional<llvm::APSInt> Result =
  13569. ValExpr->getIntegerConstantExpr(SemaRef.Context)) {
  13570. if (Result->isSigned() &&
  13571. !((!StrictlyPositive && Result->isNonNegative()) ||
  13572. (StrictlyPositive && Result->isStrictlyPositive()))) {
  13573. SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
  13574. << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
  13575. << ValExpr->getSourceRange();
  13576. return false;
  13577. }
  13578. }
  13579. if (!BuildCapture)
  13580. return true;
  13581. *CaptureRegion =
  13582. getOpenMPCaptureRegionForClause(DKind, CKind, SemaRef.LangOpts.OpenMP);
  13583. if (*CaptureRegion != OMPD_unknown &&
  13584. !SemaRef.CurContext->isDependentContext()) {
  13585. ValExpr = SemaRef.MakeFullExpr(ValExpr).get();
  13586. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  13587. ValExpr = tryBuildCapture(SemaRef, ValExpr, Captures).get();
  13588. *HelperValStmt = buildPreInits(SemaRef.Context, Captures);
  13589. }
  13590. }
  13591. return true;
  13592. }
  13593. OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
  13594. SourceLocation StartLoc,
  13595. SourceLocation LParenLoc,
  13596. SourceLocation EndLoc) {
  13597. Expr *ValExpr = NumThreads;
  13598. Stmt *HelperValStmt = nullptr;
  13599. // OpenMP [2.5, Restrictions]
  13600. // The num_threads expression must evaluate to a positive integer value.
  13601. if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
  13602. /*StrictlyPositive=*/true))
  13603. return nullptr;
  13604. OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
  13605. OpenMPDirectiveKind CaptureRegion =
  13606. getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads, LangOpts.OpenMP);
  13607. if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
  13608. ValExpr = MakeFullExpr(ValExpr).get();
  13609. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  13610. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  13611. HelperValStmt = buildPreInits(Context, Captures);
  13612. }
  13613. return new (Context) OMPNumThreadsClause(
  13614. ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
  13615. }
  13616. ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
  13617. OpenMPClauseKind CKind,
  13618. bool StrictlyPositive,
  13619. bool SuppressExprDiags) {
  13620. if (!E)
  13621. return ExprError();
  13622. if (E->isValueDependent() || E->isTypeDependent() ||
  13623. E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
  13624. return E;
  13625. llvm::APSInt Result;
  13626. ExprResult ICE;
  13627. if (SuppressExprDiags) {
  13628. // Use a custom diagnoser that suppresses 'note' diagnostics about the
  13629. // expression.
  13630. struct SuppressedDiagnoser : public Sema::VerifyICEDiagnoser {
  13631. SuppressedDiagnoser() : VerifyICEDiagnoser(/*Suppress=*/true) {}
  13632. Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
  13633. SourceLocation Loc) override {
  13634. llvm_unreachable("Diagnostic suppressed");
  13635. }
  13636. } Diagnoser;
  13637. ICE = VerifyIntegerConstantExpression(E, &Result, Diagnoser, AllowFold);
  13638. } else {
  13639. ICE = VerifyIntegerConstantExpression(E, &Result, /*FIXME*/ AllowFold);
  13640. }
  13641. if (ICE.isInvalid())
  13642. return ExprError();
  13643. if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
  13644. (!StrictlyPositive && !Result.isNonNegative())) {
  13645. Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
  13646. << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
  13647. << E->getSourceRange();
  13648. return ExprError();
  13649. }
  13650. if ((CKind == OMPC_aligned || CKind == OMPC_align) && !Result.isPowerOf2()) {
  13651. Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
  13652. << E->getSourceRange();
  13653. return ExprError();
  13654. }
  13655. if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
  13656. DSAStack->setAssociatedLoops(Result.getExtValue());
  13657. else if (CKind == OMPC_ordered)
  13658. DSAStack->setAssociatedLoops(Result.getExtValue());
  13659. return ICE;
  13660. }
  13661. OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
  13662. SourceLocation LParenLoc,
  13663. SourceLocation EndLoc) {
  13664. // OpenMP [2.8.1, simd construct, Description]
  13665. // The parameter of the safelen clause must be a constant
  13666. // positive integer expression.
  13667. ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
  13668. if (Safelen.isInvalid())
  13669. return nullptr;
  13670. return new (Context)
  13671. OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
  13672. }
  13673. OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
  13674. SourceLocation LParenLoc,
  13675. SourceLocation EndLoc) {
  13676. // OpenMP [2.8.1, simd construct, Description]
  13677. // The parameter of the simdlen clause must be a constant
  13678. // positive integer expression.
  13679. ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
  13680. if (Simdlen.isInvalid())
  13681. return nullptr;
  13682. return new (Context)
  13683. OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
  13684. }
  13685. /// Tries to find omp_allocator_handle_t type.
  13686. static bool findOMPAllocatorHandleT(Sema &S, SourceLocation Loc,
  13687. DSAStackTy *Stack) {
  13688. QualType OMPAllocatorHandleT = Stack->getOMPAllocatorHandleT();
  13689. if (!OMPAllocatorHandleT.isNull())
  13690. return true;
  13691. // Build the predefined allocator expressions.
  13692. bool ErrorFound = false;
  13693. for (int I = 0; I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) {
  13694. auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I);
  13695. StringRef Allocator =
  13696. OMPAllocateDeclAttr::ConvertAllocatorTypeTyToStr(AllocatorKind);
  13697. DeclarationName AllocatorName = &S.getASTContext().Idents.get(Allocator);
  13698. auto *VD = dyn_cast_or_null<ValueDecl>(
  13699. S.LookupSingleName(S.TUScope, AllocatorName, Loc, Sema::LookupAnyName));
  13700. if (!VD) {
  13701. ErrorFound = true;
  13702. break;
  13703. }
  13704. QualType AllocatorType =
  13705. VD->getType().getNonLValueExprType(S.getASTContext());
  13706. ExprResult Res = S.BuildDeclRefExpr(VD, AllocatorType, VK_LValue, Loc);
  13707. if (!Res.isUsable()) {
  13708. ErrorFound = true;
  13709. break;
  13710. }
  13711. if (OMPAllocatorHandleT.isNull())
  13712. OMPAllocatorHandleT = AllocatorType;
  13713. if (!S.getASTContext().hasSameType(OMPAllocatorHandleT, AllocatorType)) {
  13714. ErrorFound = true;
  13715. break;
  13716. }
  13717. Stack->setAllocator(AllocatorKind, Res.get());
  13718. }
  13719. if (ErrorFound) {
  13720. S.Diag(Loc, diag::err_omp_implied_type_not_found)
  13721. << "omp_allocator_handle_t";
  13722. return false;
  13723. }
  13724. OMPAllocatorHandleT.addConst();
  13725. Stack->setOMPAllocatorHandleT(OMPAllocatorHandleT);
  13726. return true;
  13727. }
  13728. OMPClause *Sema::ActOnOpenMPAllocatorClause(Expr *A, SourceLocation StartLoc,
  13729. SourceLocation LParenLoc,
  13730. SourceLocation EndLoc) {
  13731. // OpenMP [2.11.3, allocate Directive, Description]
  13732. // allocator is an expression of omp_allocator_handle_t type.
  13733. if (!findOMPAllocatorHandleT(*this, A->getExprLoc(), DSAStack))
  13734. return nullptr;
  13735. ExprResult Allocator = DefaultLvalueConversion(A);
  13736. if (Allocator.isInvalid())
  13737. return nullptr;
  13738. Allocator = PerformImplicitConversion(Allocator.get(),
  13739. DSAStack->getOMPAllocatorHandleT(),
  13740. Sema::AA_Initializing,
  13741. /*AllowExplicit=*/true);
  13742. if (Allocator.isInvalid())
  13743. return nullptr;
  13744. return new (Context)
  13745. OMPAllocatorClause(Allocator.get(), StartLoc, LParenLoc, EndLoc);
  13746. }
  13747. OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
  13748. SourceLocation StartLoc,
  13749. SourceLocation LParenLoc,
  13750. SourceLocation EndLoc) {
  13751. // OpenMP [2.7.1, loop construct, Description]
  13752. // OpenMP [2.8.1, simd construct, Description]
  13753. // OpenMP [2.9.6, distribute construct, Description]
  13754. // The parameter of the collapse clause must be a constant
  13755. // positive integer expression.
  13756. ExprResult NumForLoopsResult =
  13757. VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
  13758. if (NumForLoopsResult.isInvalid())
  13759. return nullptr;
  13760. return new (Context)
  13761. OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
  13762. }
  13763. OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
  13764. SourceLocation EndLoc,
  13765. SourceLocation LParenLoc,
  13766. Expr *NumForLoops) {
  13767. // OpenMP [2.7.1, loop construct, Description]
  13768. // OpenMP [2.8.1, simd construct, Description]
  13769. // OpenMP [2.9.6, distribute construct, Description]
  13770. // The parameter of the ordered clause must be a constant
  13771. // positive integer expression if any.
  13772. if (NumForLoops && LParenLoc.isValid()) {
  13773. ExprResult NumForLoopsResult =
  13774. VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
  13775. if (NumForLoopsResult.isInvalid())
  13776. return nullptr;
  13777. NumForLoops = NumForLoopsResult.get();
  13778. } else {
  13779. NumForLoops = nullptr;
  13780. }
  13781. auto *Clause = OMPOrderedClause::Create(
  13782. Context, NumForLoops, NumForLoops ? DSAStack->getAssociatedLoops() : 0,
  13783. StartLoc, LParenLoc, EndLoc);
  13784. DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops, Clause);
  13785. return Clause;
  13786. }
  13787. OMPClause *Sema::ActOnOpenMPSimpleClause(
  13788. OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
  13789. SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
  13790. OMPClause *Res = nullptr;
  13791. switch (Kind) {
  13792. case OMPC_default:
  13793. Res = ActOnOpenMPDefaultClause(static_cast<DefaultKind>(Argument),
  13794. ArgumentLoc, StartLoc, LParenLoc, EndLoc);
  13795. break;
  13796. case OMPC_proc_bind:
  13797. Res = ActOnOpenMPProcBindClause(static_cast<ProcBindKind>(Argument),
  13798. ArgumentLoc, StartLoc, LParenLoc, EndLoc);
  13799. break;
  13800. case OMPC_atomic_default_mem_order:
  13801. Res = ActOnOpenMPAtomicDefaultMemOrderClause(
  13802. static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Argument),
  13803. ArgumentLoc, StartLoc, LParenLoc, EndLoc);
  13804. break;
  13805. case OMPC_order:
  13806. Res = ActOnOpenMPOrderClause(static_cast<OpenMPOrderClauseKind>(Argument),
  13807. ArgumentLoc, StartLoc, LParenLoc, EndLoc);
  13808. break;
  13809. case OMPC_update:
  13810. Res = ActOnOpenMPUpdateClause(static_cast<OpenMPDependClauseKind>(Argument),
  13811. ArgumentLoc, StartLoc, LParenLoc, EndLoc);
  13812. break;
  13813. case OMPC_bind:
  13814. Res = ActOnOpenMPBindClause(static_cast<OpenMPBindClauseKind>(Argument),
  13815. ArgumentLoc, StartLoc, LParenLoc, EndLoc);
  13816. break;
  13817. case OMPC_if:
  13818. case OMPC_final:
  13819. case OMPC_num_threads:
  13820. case OMPC_safelen:
  13821. case OMPC_simdlen:
  13822. case OMPC_sizes:
  13823. case OMPC_allocator:
  13824. case OMPC_collapse:
  13825. case OMPC_schedule:
  13826. case OMPC_private:
  13827. case OMPC_firstprivate:
  13828. case OMPC_lastprivate:
  13829. case OMPC_shared:
  13830. case OMPC_reduction:
  13831. case OMPC_task_reduction:
  13832. case OMPC_in_reduction:
  13833. case OMPC_linear:
  13834. case OMPC_aligned:
  13835. case OMPC_copyin:
  13836. case OMPC_copyprivate:
  13837. case OMPC_ordered:
  13838. case OMPC_nowait:
  13839. case OMPC_untied:
  13840. case OMPC_mergeable:
  13841. case OMPC_threadprivate:
  13842. case OMPC_allocate:
  13843. case OMPC_flush:
  13844. case OMPC_depobj:
  13845. case OMPC_read:
  13846. case OMPC_write:
  13847. case OMPC_capture:
  13848. case OMPC_compare:
  13849. case OMPC_seq_cst:
  13850. case OMPC_acq_rel:
  13851. case OMPC_acquire:
  13852. case OMPC_release:
  13853. case OMPC_relaxed:
  13854. case OMPC_depend:
  13855. case OMPC_device:
  13856. case OMPC_threads:
  13857. case OMPC_simd:
  13858. case OMPC_map:
  13859. case OMPC_num_teams:
  13860. case OMPC_thread_limit:
  13861. case OMPC_priority:
  13862. case OMPC_grainsize:
  13863. case OMPC_nogroup:
  13864. case OMPC_num_tasks:
  13865. case OMPC_hint:
  13866. case OMPC_dist_schedule:
  13867. case OMPC_defaultmap:
  13868. case OMPC_unknown:
  13869. case OMPC_uniform:
  13870. case OMPC_to:
  13871. case OMPC_from:
  13872. case OMPC_use_device_ptr:
  13873. case OMPC_use_device_addr:
  13874. case OMPC_is_device_ptr:
  13875. case OMPC_unified_address:
  13876. case OMPC_unified_shared_memory:
  13877. case OMPC_reverse_offload:
  13878. case OMPC_dynamic_allocators:
  13879. case OMPC_device_type:
  13880. case OMPC_match:
  13881. case OMPC_nontemporal:
  13882. case OMPC_destroy:
  13883. case OMPC_novariants:
  13884. case OMPC_nocontext:
  13885. case OMPC_detach:
  13886. case OMPC_inclusive:
  13887. case OMPC_exclusive:
  13888. case OMPC_uses_allocators:
  13889. case OMPC_affinity:
  13890. case OMPC_when:
  13891. default:
  13892. llvm_unreachable("Clause is not allowed.");
  13893. }
  13894. return Res;
  13895. }
  13896. static std::string
  13897. getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
  13898. ArrayRef<unsigned> Exclude = llvm::None) {
  13899. SmallString<256> Buffer;
  13900. llvm::raw_svector_ostream Out(Buffer);
  13901. unsigned Skipped = Exclude.size();
  13902. auto S = Exclude.begin(), E = Exclude.end();
  13903. for (unsigned I = First; I < Last; ++I) {
  13904. if (std::find(S, E, I) != E) {
  13905. --Skipped;
  13906. continue;
  13907. }
  13908. Out << "'" << getOpenMPSimpleClauseTypeName(K, I) << "'";
  13909. if (I + Skipped + 2 == Last)
  13910. Out << " or ";
  13911. else if (I + Skipped + 1 != Last)
  13912. Out << ", ";
  13913. }
  13914. return std::string(Out.str());
  13915. }
  13916. OMPClause *Sema::ActOnOpenMPDefaultClause(DefaultKind Kind,
  13917. SourceLocation KindKwLoc,
  13918. SourceLocation StartLoc,
  13919. SourceLocation LParenLoc,
  13920. SourceLocation EndLoc) {
  13921. if (Kind == OMP_DEFAULT_unknown) {
  13922. Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
  13923. << getListOfPossibleValues(OMPC_default, /*First=*/0,
  13924. /*Last=*/unsigned(OMP_DEFAULT_unknown))
  13925. << getOpenMPClauseName(OMPC_default);
  13926. return nullptr;
  13927. }
  13928. switch (Kind) {
  13929. case OMP_DEFAULT_none:
  13930. DSAStack->setDefaultDSANone(KindKwLoc);
  13931. break;
  13932. case OMP_DEFAULT_shared:
  13933. DSAStack->setDefaultDSAShared(KindKwLoc);
  13934. break;
  13935. case OMP_DEFAULT_firstprivate:
  13936. DSAStack->setDefaultDSAFirstPrivate(KindKwLoc);
  13937. break;
  13938. default:
  13939. llvm_unreachable("DSA unexpected in OpenMP default clause");
  13940. }
  13941. return new (Context)
  13942. OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
  13943. }
  13944. OMPClause *Sema::ActOnOpenMPProcBindClause(ProcBindKind Kind,
  13945. SourceLocation KindKwLoc,
  13946. SourceLocation StartLoc,
  13947. SourceLocation LParenLoc,
  13948. SourceLocation EndLoc) {
  13949. if (Kind == OMP_PROC_BIND_unknown) {
  13950. Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
  13951. << getListOfPossibleValues(OMPC_proc_bind,
  13952. /*First=*/unsigned(OMP_PROC_BIND_master),
  13953. /*Last=*/
  13954. unsigned(LangOpts.OpenMP > 50
  13955. ? OMP_PROC_BIND_primary
  13956. : OMP_PROC_BIND_spread) +
  13957. 1)
  13958. << getOpenMPClauseName(OMPC_proc_bind);
  13959. return nullptr;
  13960. }
  13961. if (Kind == OMP_PROC_BIND_primary && LangOpts.OpenMP < 51)
  13962. Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
  13963. << getListOfPossibleValues(OMPC_proc_bind,
  13964. /*First=*/unsigned(OMP_PROC_BIND_master),
  13965. /*Last=*/
  13966. unsigned(OMP_PROC_BIND_spread) + 1)
  13967. << getOpenMPClauseName(OMPC_proc_bind);
  13968. return new (Context)
  13969. OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
  13970. }
  13971. OMPClause *Sema::ActOnOpenMPAtomicDefaultMemOrderClause(
  13972. OpenMPAtomicDefaultMemOrderClauseKind Kind, SourceLocation KindKwLoc,
  13973. SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
  13974. if (Kind == OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown) {
  13975. Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
  13976. << getListOfPossibleValues(
  13977. OMPC_atomic_default_mem_order, /*First=*/0,
  13978. /*Last=*/OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown)
  13979. << getOpenMPClauseName(OMPC_atomic_default_mem_order);
  13980. return nullptr;
  13981. }
  13982. return new (Context) OMPAtomicDefaultMemOrderClause(Kind, KindKwLoc, StartLoc,
  13983. LParenLoc, EndLoc);
  13984. }
  13985. OMPClause *Sema::ActOnOpenMPOrderClause(OpenMPOrderClauseKind Kind,
  13986. SourceLocation KindKwLoc,
  13987. SourceLocation StartLoc,
  13988. SourceLocation LParenLoc,
  13989. SourceLocation EndLoc) {
  13990. if (Kind == OMPC_ORDER_unknown) {
  13991. static_assert(OMPC_ORDER_unknown > 0,
  13992. "OMPC_ORDER_unknown not greater than 0");
  13993. Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
  13994. << getListOfPossibleValues(OMPC_order, /*First=*/0,
  13995. /*Last=*/OMPC_ORDER_unknown)
  13996. << getOpenMPClauseName(OMPC_order);
  13997. return nullptr;
  13998. }
  13999. return new (Context)
  14000. OMPOrderClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
  14001. }
  14002. OMPClause *Sema::ActOnOpenMPUpdateClause(OpenMPDependClauseKind Kind,
  14003. SourceLocation KindKwLoc,
  14004. SourceLocation StartLoc,
  14005. SourceLocation LParenLoc,
  14006. SourceLocation EndLoc) {
  14007. if (Kind == OMPC_DEPEND_unknown || Kind == OMPC_DEPEND_source ||
  14008. Kind == OMPC_DEPEND_sink || Kind == OMPC_DEPEND_depobj) {
  14009. unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink,
  14010. OMPC_DEPEND_depobj};
  14011. Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
  14012. << getListOfPossibleValues(OMPC_depend, /*First=*/0,
  14013. /*Last=*/OMPC_DEPEND_unknown, Except)
  14014. << getOpenMPClauseName(OMPC_update);
  14015. return nullptr;
  14016. }
  14017. return OMPUpdateClause::Create(Context, StartLoc, LParenLoc, KindKwLoc, Kind,
  14018. EndLoc);
  14019. }
  14020. OMPClause *Sema::ActOnOpenMPSizesClause(ArrayRef<Expr *> SizeExprs,
  14021. SourceLocation StartLoc,
  14022. SourceLocation LParenLoc,
  14023. SourceLocation EndLoc) {
  14024. for (Expr *SizeExpr : SizeExprs) {
  14025. ExprResult NumForLoopsResult = VerifyPositiveIntegerConstantInClause(
  14026. SizeExpr, OMPC_sizes, /*StrictlyPositive=*/true);
  14027. if (!NumForLoopsResult.isUsable())
  14028. return nullptr;
  14029. }
  14030. DSAStack->setAssociatedLoops(SizeExprs.size());
  14031. return OMPSizesClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  14032. SizeExprs);
  14033. }
  14034. OMPClause *Sema::ActOnOpenMPFullClause(SourceLocation StartLoc,
  14035. SourceLocation EndLoc) {
  14036. return OMPFullClause::Create(Context, StartLoc, EndLoc);
  14037. }
  14038. OMPClause *Sema::ActOnOpenMPPartialClause(Expr *FactorExpr,
  14039. SourceLocation StartLoc,
  14040. SourceLocation LParenLoc,
  14041. SourceLocation EndLoc) {
  14042. if (FactorExpr) {
  14043. // If an argument is specified, it must be a constant (or an unevaluated
  14044. // template expression).
  14045. ExprResult FactorResult = VerifyPositiveIntegerConstantInClause(
  14046. FactorExpr, OMPC_partial, /*StrictlyPositive=*/true);
  14047. if (FactorResult.isInvalid())
  14048. return nullptr;
  14049. FactorExpr = FactorResult.get();
  14050. }
  14051. return OMPPartialClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  14052. FactorExpr);
  14053. }
  14054. OMPClause *Sema::ActOnOpenMPAlignClause(Expr *A, SourceLocation StartLoc,
  14055. SourceLocation LParenLoc,
  14056. SourceLocation EndLoc) {
  14057. ExprResult AlignVal;
  14058. AlignVal = VerifyPositiveIntegerConstantInClause(A, OMPC_align);
  14059. if (AlignVal.isInvalid())
  14060. return nullptr;
  14061. return OMPAlignClause::Create(Context, AlignVal.get(), StartLoc, LParenLoc,
  14062. EndLoc);
  14063. }
  14064. OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
  14065. OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
  14066. SourceLocation StartLoc, SourceLocation LParenLoc,
  14067. ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
  14068. SourceLocation EndLoc) {
  14069. OMPClause *Res = nullptr;
  14070. switch (Kind) {
  14071. case OMPC_schedule:
  14072. enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
  14073. assert(Argument.size() == NumberOfElements &&
  14074. ArgumentLoc.size() == NumberOfElements);
  14075. Res = ActOnOpenMPScheduleClause(
  14076. static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
  14077. static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
  14078. static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
  14079. StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
  14080. ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
  14081. break;
  14082. case OMPC_if:
  14083. assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
  14084. Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
  14085. Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
  14086. DelimLoc, EndLoc);
  14087. break;
  14088. case OMPC_dist_schedule:
  14089. Res = ActOnOpenMPDistScheduleClause(
  14090. static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
  14091. StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
  14092. break;
  14093. case OMPC_defaultmap:
  14094. enum { Modifier, DefaultmapKind };
  14095. Res = ActOnOpenMPDefaultmapClause(
  14096. static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
  14097. static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
  14098. StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
  14099. EndLoc);
  14100. break;
  14101. case OMPC_device:
  14102. assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
  14103. Res = ActOnOpenMPDeviceClause(
  14104. static_cast<OpenMPDeviceClauseModifier>(Argument.back()), Expr,
  14105. StartLoc, LParenLoc, ArgumentLoc.back(), EndLoc);
  14106. break;
  14107. case OMPC_final:
  14108. case OMPC_num_threads:
  14109. case OMPC_safelen:
  14110. case OMPC_simdlen:
  14111. case OMPC_sizes:
  14112. case OMPC_allocator:
  14113. case OMPC_collapse:
  14114. case OMPC_default:
  14115. case OMPC_proc_bind:
  14116. case OMPC_private:
  14117. case OMPC_firstprivate:
  14118. case OMPC_lastprivate:
  14119. case OMPC_shared:
  14120. case OMPC_reduction:
  14121. case OMPC_task_reduction:
  14122. case OMPC_in_reduction:
  14123. case OMPC_linear:
  14124. case OMPC_aligned:
  14125. case OMPC_copyin:
  14126. case OMPC_copyprivate:
  14127. case OMPC_ordered:
  14128. case OMPC_nowait:
  14129. case OMPC_untied:
  14130. case OMPC_mergeable:
  14131. case OMPC_threadprivate:
  14132. case OMPC_allocate:
  14133. case OMPC_flush:
  14134. case OMPC_depobj:
  14135. case OMPC_read:
  14136. case OMPC_write:
  14137. case OMPC_update:
  14138. case OMPC_capture:
  14139. case OMPC_compare:
  14140. case OMPC_seq_cst:
  14141. case OMPC_acq_rel:
  14142. case OMPC_acquire:
  14143. case OMPC_release:
  14144. case OMPC_relaxed:
  14145. case OMPC_depend:
  14146. case OMPC_threads:
  14147. case OMPC_simd:
  14148. case OMPC_map:
  14149. case OMPC_num_teams:
  14150. case OMPC_thread_limit:
  14151. case OMPC_priority:
  14152. case OMPC_grainsize:
  14153. case OMPC_nogroup:
  14154. case OMPC_num_tasks:
  14155. case OMPC_hint:
  14156. case OMPC_unknown:
  14157. case OMPC_uniform:
  14158. case OMPC_to:
  14159. case OMPC_from:
  14160. case OMPC_use_device_ptr:
  14161. case OMPC_use_device_addr:
  14162. case OMPC_is_device_ptr:
  14163. case OMPC_unified_address:
  14164. case OMPC_unified_shared_memory:
  14165. case OMPC_reverse_offload:
  14166. case OMPC_dynamic_allocators:
  14167. case OMPC_atomic_default_mem_order:
  14168. case OMPC_device_type:
  14169. case OMPC_match:
  14170. case OMPC_nontemporal:
  14171. case OMPC_order:
  14172. case OMPC_destroy:
  14173. case OMPC_novariants:
  14174. case OMPC_nocontext:
  14175. case OMPC_detach:
  14176. case OMPC_inclusive:
  14177. case OMPC_exclusive:
  14178. case OMPC_uses_allocators:
  14179. case OMPC_affinity:
  14180. case OMPC_when:
  14181. case OMPC_bind:
  14182. default:
  14183. llvm_unreachable("Clause is not allowed.");
  14184. }
  14185. return Res;
  14186. }
  14187. static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
  14188. OpenMPScheduleClauseModifier M2,
  14189. SourceLocation M1Loc, SourceLocation M2Loc) {
  14190. if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
  14191. SmallVector<unsigned, 2> Excluded;
  14192. if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
  14193. Excluded.push_back(M2);
  14194. if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
  14195. Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
  14196. if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
  14197. Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
  14198. S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
  14199. << getListOfPossibleValues(OMPC_schedule,
  14200. /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
  14201. /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
  14202. Excluded)
  14203. << getOpenMPClauseName(OMPC_schedule);
  14204. return true;
  14205. }
  14206. return false;
  14207. }
  14208. OMPClause *Sema::ActOnOpenMPScheduleClause(
  14209. OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
  14210. OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
  14211. SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
  14212. SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
  14213. if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
  14214. checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
  14215. return nullptr;
  14216. // OpenMP, 2.7.1, Loop Construct, Restrictions
  14217. // Either the monotonic modifier or the nonmonotonic modifier can be specified
  14218. // but not both.
  14219. if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
  14220. (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
  14221. M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
  14222. (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
  14223. M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
  14224. Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
  14225. << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
  14226. << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
  14227. return nullptr;
  14228. }
  14229. if (Kind == OMPC_SCHEDULE_unknown) {
  14230. std::string Values;
  14231. if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
  14232. unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
  14233. Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
  14234. /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
  14235. Exclude);
  14236. } else {
  14237. Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
  14238. /*Last=*/OMPC_SCHEDULE_unknown);
  14239. }
  14240. Diag(KindLoc, diag::err_omp_unexpected_clause_value)
  14241. << Values << getOpenMPClauseName(OMPC_schedule);
  14242. return nullptr;
  14243. }
  14244. // OpenMP, 2.7.1, Loop Construct, Restrictions
  14245. // The nonmonotonic modifier can only be specified with schedule(dynamic) or
  14246. // schedule(guided).
  14247. // OpenMP 5.0 does not have this restriction.
  14248. if (LangOpts.OpenMP < 50 &&
  14249. (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
  14250. M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
  14251. Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
  14252. Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
  14253. diag::err_omp_schedule_nonmonotonic_static);
  14254. return nullptr;
  14255. }
  14256. Expr *ValExpr = ChunkSize;
  14257. Stmt *HelperValStmt = nullptr;
  14258. if (ChunkSize) {
  14259. if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
  14260. !ChunkSize->isInstantiationDependent() &&
  14261. !ChunkSize->containsUnexpandedParameterPack()) {
  14262. SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
  14263. ExprResult Val =
  14264. PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
  14265. if (Val.isInvalid())
  14266. return nullptr;
  14267. ValExpr = Val.get();
  14268. // OpenMP [2.7.1, Restrictions]
  14269. // chunk_size must be a loop invariant integer expression with a positive
  14270. // value.
  14271. if (Optional<llvm::APSInt> Result =
  14272. ValExpr->getIntegerConstantExpr(Context)) {
  14273. if (Result->isSigned() && !Result->isStrictlyPositive()) {
  14274. Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
  14275. << "schedule" << 1 << ChunkSize->getSourceRange();
  14276. return nullptr;
  14277. }
  14278. } else if (getOpenMPCaptureRegionForClause(
  14279. DSAStack->getCurrentDirective(), OMPC_schedule,
  14280. LangOpts.OpenMP) != OMPD_unknown &&
  14281. !CurContext->isDependentContext()) {
  14282. ValExpr = MakeFullExpr(ValExpr).get();
  14283. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  14284. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  14285. HelperValStmt = buildPreInits(Context, Captures);
  14286. }
  14287. }
  14288. }
  14289. return new (Context)
  14290. OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
  14291. ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
  14292. }
  14293. OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
  14294. SourceLocation StartLoc,
  14295. SourceLocation EndLoc) {
  14296. OMPClause *Res = nullptr;
  14297. switch (Kind) {
  14298. case OMPC_ordered:
  14299. Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
  14300. break;
  14301. case OMPC_nowait:
  14302. Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
  14303. break;
  14304. case OMPC_untied:
  14305. Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
  14306. break;
  14307. case OMPC_mergeable:
  14308. Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
  14309. break;
  14310. case OMPC_read:
  14311. Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
  14312. break;
  14313. case OMPC_write:
  14314. Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
  14315. break;
  14316. case OMPC_update:
  14317. Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
  14318. break;
  14319. case OMPC_capture:
  14320. Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
  14321. break;
  14322. case OMPC_compare:
  14323. Res = ActOnOpenMPCompareClause(StartLoc, EndLoc);
  14324. break;
  14325. case OMPC_seq_cst:
  14326. Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
  14327. break;
  14328. case OMPC_acq_rel:
  14329. Res = ActOnOpenMPAcqRelClause(StartLoc, EndLoc);
  14330. break;
  14331. case OMPC_acquire:
  14332. Res = ActOnOpenMPAcquireClause(StartLoc, EndLoc);
  14333. break;
  14334. case OMPC_release:
  14335. Res = ActOnOpenMPReleaseClause(StartLoc, EndLoc);
  14336. break;
  14337. case OMPC_relaxed:
  14338. Res = ActOnOpenMPRelaxedClause(StartLoc, EndLoc);
  14339. break;
  14340. case OMPC_threads:
  14341. Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
  14342. break;
  14343. case OMPC_simd:
  14344. Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
  14345. break;
  14346. case OMPC_nogroup:
  14347. Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
  14348. break;
  14349. case OMPC_unified_address:
  14350. Res = ActOnOpenMPUnifiedAddressClause(StartLoc, EndLoc);
  14351. break;
  14352. case OMPC_unified_shared_memory:
  14353. Res = ActOnOpenMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
  14354. break;
  14355. case OMPC_reverse_offload:
  14356. Res = ActOnOpenMPReverseOffloadClause(StartLoc, EndLoc);
  14357. break;
  14358. case OMPC_dynamic_allocators:
  14359. Res = ActOnOpenMPDynamicAllocatorsClause(StartLoc, EndLoc);
  14360. break;
  14361. case OMPC_destroy:
  14362. Res = ActOnOpenMPDestroyClause(/*InteropVar=*/nullptr, StartLoc,
  14363. /*LParenLoc=*/SourceLocation(),
  14364. /*VarLoc=*/SourceLocation(), EndLoc);
  14365. break;
  14366. case OMPC_full:
  14367. Res = ActOnOpenMPFullClause(StartLoc, EndLoc);
  14368. break;
  14369. case OMPC_partial:
  14370. Res = ActOnOpenMPPartialClause(nullptr, StartLoc, /*LParenLoc=*/{}, EndLoc);
  14371. break;
  14372. case OMPC_if:
  14373. case OMPC_final:
  14374. case OMPC_num_threads:
  14375. case OMPC_safelen:
  14376. case OMPC_simdlen:
  14377. case OMPC_sizes:
  14378. case OMPC_allocator:
  14379. case OMPC_collapse:
  14380. case OMPC_schedule:
  14381. case OMPC_private:
  14382. case OMPC_firstprivate:
  14383. case OMPC_lastprivate:
  14384. case OMPC_shared:
  14385. case OMPC_reduction:
  14386. case OMPC_task_reduction:
  14387. case OMPC_in_reduction:
  14388. case OMPC_linear:
  14389. case OMPC_aligned:
  14390. case OMPC_copyin:
  14391. case OMPC_copyprivate:
  14392. case OMPC_default:
  14393. case OMPC_proc_bind:
  14394. case OMPC_threadprivate:
  14395. case OMPC_allocate:
  14396. case OMPC_flush:
  14397. case OMPC_depobj:
  14398. case OMPC_depend:
  14399. case OMPC_device:
  14400. case OMPC_map:
  14401. case OMPC_num_teams:
  14402. case OMPC_thread_limit:
  14403. case OMPC_priority:
  14404. case OMPC_grainsize:
  14405. case OMPC_num_tasks:
  14406. case OMPC_hint:
  14407. case OMPC_dist_schedule:
  14408. case OMPC_defaultmap:
  14409. case OMPC_unknown:
  14410. case OMPC_uniform:
  14411. case OMPC_to:
  14412. case OMPC_from:
  14413. case OMPC_use_device_ptr:
  14414. case OMPC_use_device_addr:
  14415. case OMPC_is_device_ptr:
  14416. case OMPC_atomic_default_mem_order:
  14417. case OMPC_device_type:
  14418. case OMPC_match:
  14419. case OMPC_nontemporal:
  14420. case OMPC_order:
  14421. case OMPC_novariants:
  14422. case OMPC_nocontext:
  14423. case OMPC_detach:
  14424. case OMPC_inclusive:
  14425. case OMPC_exclusive:
  14426. case OMPC_uses_allocators:
  14427. case OMPC_affinity:
  14428. case OMPC_when:
  14429. default:
  14430. llvm_unreachable("Clause is not allowed.");
  14431. }
  14432. return Res;
  14433. }
  14434. OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
  14435. SourceLocation EndLoc) {
  14436. DSAStack->setNowaitRegion();
  14437. return new (Context) OMPNowaitClause(StartLoc, EndLoc);
  14438. }
  14439. OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
  14440. SourceLocation EndLoc) {
  14441. return new (Context) OMPUntiedClause(StartLoc, EndLoc);
  14442. }
  14443. OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
  14444. SourceLocation EndLoc) {
  14445. return new (Context) OMPMergeableClause(StartLoc, EndLoc);
  14446. }
  14447. OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
  14448. SourceLocation EndLoc) {
  14449. return new (Context) OMPReadClause(StartLoc, EndLoc);
  14450. }
  14451. OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
  14452. SourceLocation EndLoc) {
  14453. return new (Context) OMPWriteClause(StartLoc, EndLoc);
  14454. }
  14455. OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
  14456. SourceLocation EndLoc) {
  14457. return OMPUpdateClause::Create(Context, StartLoc, EndLoc);
  14458. }
  14459. OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
  14460. SourceLocation EndLoc) {
  14461. return new (Context) OMPCaptureClause(StartLoc, EndLoc);
  14462. }
  14463. OMPClause *Sema::ActOnOpenMPCompareClause(SourceLocation StartLoc,
  14464. SourceLocation EndLoc) {
  14465. return new (Context) OMPCompareClause(StartLoc, EndLoc);
  14466. }
  14467. OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
  14468. SourceLocation EndLoc) {
  14469. return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
  14470. }
  14471. OMPClause *Sema::ActOnOpenMPAcqRelClause(SourceLocation StartLoc,
  14472. SourceLocation EndLoc) {
  14473. return new (Context) OMPAcqRelClause(StartLoc, EndLoc);
  14474. }
  14475. OMPClause *Sema::ActOnOpenMPAcquireClause(SourceLocation StartLoc,
  14476. SourceLocation EndLoc) {
  14477. return new (Context) OMPAcquireClause(StartLoc, EndLoc);
  14478. }
  14479. OMPClause *Sema::ActOnOpenMPReleaseClause(SourceLocation StartLoc,
  14480. SourceLocation EndLoc) {
  14481. return new (Context) OMPReleaseClause(StartLoc, EndLoc);
  14482. }
  14483. OMPClause *Sema::ActOnOpenMPRelaxedClause(SourceLocation StartLoc,
  14484. SourceLocation EndLoc) {
  14485. return new (Context) OMPRelaxedClause(StartLoc, EndLoc);
  14486. }
  14487. OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
  14488. SourceLocation EndLoc) {
  14489. return new (Context) OMPThreadsClause(StartLoc, EndLoc);
  14490. }
  14491. OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
  14492. SourceLocation EndLoc) {
  14493. return new (Context) OMPSIMDClause(StartLoc, EndLoc);
  14494. }
  14495. OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
  14496. SourceLocation EndLoc) {
  14497. return new (Context) OMPNogroupClause(StartLoc, EndLoc);
  14498. }
  14499. OMPClause *Sema::ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc,
  14500. SourceLocation EndLoc) {
  14501. return new (Context) OMPUnifiedAddressClause(StartLoc, EndLoc);
  14502. }
  14503. OMPClause *Sema::ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc,
  14504. SourceLocation EndLoc) {
  14505. return new (Context) OMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
  14506. }
  14507. OMPClause *Sema::ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc,
  14508. SourceLocation EndLoc) {
  14509. return new (Context) OMPReverseOffloadClause(StartLoc, EndLoc);
  14510. }
  14511. OMPClause *Sema::ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc,
  14512. SourceLocation EndLoc) {
  14513. return new (Context) OMPDynamicAllocatorsClause(StartLoc, EndLoc);
  14514. }
  14515. StmtResult Sema::ActOnOpenMPInteropDirective(ArrayRef<OMPClause *> Clauses,
  14516. SourceLocation StartLoc,
  14517. SourceLocation EndLoc) {
  14518. // OpenMP 5.1 [2.15.1, interop Construct, Restrictions]
  14519. // At least one action-clause must appear on a directive.
  14520. if (!hasClauses(Clauses, OMPC_init, OMPC_use, OMPC_destroy, OMPC_nowait)) {
  14521. StringRef Expected = "'init', 'use', 'destroy', or 'nowait'";
  14522. Diag(StartLoc, diag::err_omp_no_clause_for_directive)
  14523. << Expected << getOpenMPDirectiveName(OMPD_interop);
  14524. return StmtError();
  14525. }
  14526. // OpenMP 5.1 [2.15.1, interop Construct, Restrictions]
  14527. // A depend clause can only appear on the directive if a targetsync
  14528. // interop-type is present or the interop-var was initialized with
  14529. // the targetsync interop-type.
  14530. // If there is any 'init' clause diagnose if there is no 'init' clause with
  14531. // interop-type of 'targetsync'. Cases involving other directives cannot be
  14532. // diagnosed.
  14533. const OMPDependClause *DependClause = nullptr;
  14534. bool HasInitClause = false;
  14535. bool IsTargetSync = false;
  14536. for (const OMPClause *C : Clauses) {
  14537. if (IsTargetSync)
  14538. break;
  14539. if (const auto *InitClause = dyn_cast<OMPInitClause>(C)) {
  14540. HasInitClause = true;
  14541. if (InitClause->getIsTargetSync())
  14542. IsTargetSync = true;
  14543. } else if (const auto *DC = dyn_cast<OMPDependClause>(C)) {
  14544. DependClause = DC;
  14545. }
  14546. }
  14547. if (DependClause && HasInitClause && !IsTargetSync) {
  14548. Diag(DependClause->getBeginLoc(), diag::err_omp_interop_bad_depend_clause);
  14549. return StmtError();
  14550. }
  14551. // OpenMP 5.1 [2.15.1, interop Construct, Restrictions]
  14552. // Each interop-var may be specified for at most one action-clause of each
  14553. // interop construct.
  14554. llvm::SmallPtrSet<const VarDecl *, 4> InteropVars;
  14555. for (const OMPClause *C : Clauses) {
  14556. OpenMPClauseKind ClauseKind = C->getClauseKind();
  14557. const DeclRefExpr *DRE = nullptr;
  14558. SourceLocation VarLoc;
  14559. if (ClauseKind == OMPC_init) {
  14560. const auto *IC = cast<OMPInitClause>(C);
  14561. VarLoc = IC->getVarLoc();
  14562. DRE = dyn_cast_or_null<DeclRefExpr>(IC->getInteropVar());
  14563. } else if (ClauseKind == OMPC_use) {
  14564. const auto *UC = cast<OMPUseClause>(C);
  14565. VarLoc = UC->getVarLoc();
  14566. DRE = dyn_cast_or_null<DeclRefExpr>(UC->getInteropVar());
  14567. } else if (ClauseKind == OMPC_destroy) {
  14568. const auto *DC = cast<OMPDestroyClause>(C);
  14569. VarLoc = DC->getVarLoc();
  14570. DRE = dyn_cast_or_null<DeclRefExpr>(DC->getInteropVar());
  14571. }
  14572. if (!DRE)
  14573. continue;
  14574. if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
  14575. if (!InteropVars.insert(VD->getCanonicalDecl()).second) {
  14576. Diag(VarLoc, diag::err_omp_interop_var_multiple_actions) << VD;
  14577. return StmtError();
  14578. }
  14579. }
  14580. }
  14581. return OMPInteropDirective::Create(Context, StartLoc, EndLoc, Clauses);
  14582. }
  14583. static bool isValidInteropVariable(Sema &SemaRef, Expr *InteropVarExpr,
  14584. SourceLocation VarLoc,
  14585. OpenMPClauseKind Kind) {
  14586. if (InteropVarExpr->isValueDependent() || InteropVarExpr->isTypeDependent() ||
  14587. InteropVarExpr->isInstantiationDependent() ||
  14588. InteropVarExpr->containsUnexpandedParameterPack())
  14589. return true;
  14590. const auto *DRE = dyn_cast<DeclRefExpr>(InteropVarExpr);
  14591. if (!DRE || !isa<VarDecl>(DRE->getDecl())) {
  14592. SemaRef.Diag(VarLoc, diag::err_omp_interop_variable_expected) << 0;
  14593. return false;
  14594. }
  14595. // Interop variable should be of type omp_interop_t.
  14596. bool HasError = false;
  14597. QualType InteropType;
  14598. LookupResult Result(SemaRef, &SemaRef.Context.Idents.get("omp_interop_t"),
  14599. VarLoc, Sema::LookupOrdinaryName);
  14600. if (SemaRef.LookupName(Result, SemaRef.getCurScope())) {
  14601. NamedDecl *ND = Result.getFoundDecl();
  14602. if (const auto *TD = dyn_cast<TypeDecl>(ND)) {
  14603. InteropType = QualType(TD->getTypeForDecl(), 0);
  14604. } else {
  14605. HasError = true;
  14606. }
  14607. } else {
  14608. HasError = true;
  14609. }
  14610. if (HasError) {
  14611. SemaRef.Diag(VarLoc, diag::err_omp_implied_type_not_found)
  14612. << "omp_interop_t";
  14613. return false;
  14614. }
  14615. QualType VarType = InteropVarExpr->getType().getUnqualifiedType();
  14616. if (!SemaRef.Context.hasSameType(InteropType, VarType)) {
  14617. SemaRef.Diag(VarLoc, diag::err_omp_interop_variable_wrong_type);
  14618. return false;
  14619. }
  14620. // OpenMP 5.1 [2.15.1, interop Construct, Restrictions]
  14621. // The interop-var passed to init or destroy must be non-const.
  14622. if ((Kind == OMPC_init || Kind == OMPC_destroy) &&
  14623. isConstNotMutableType(SemaRef, InteropVarExpr->getType())) {
  14624. SemaRef.Diag(VarLoc, diag::err_omp_interop_variable_expected)
  14625. << /*non-const*/ 1;
  14626. return false;
  14627. }
  14628. return true;
  14629. }
  14630. OMPClause *
  14631. Sema::ActOnOpenMPInitClause(Expr *InteropVar, ArrayRef<Expr *> PrefExprs,
  14632. bool IsTarget, bool IsTargetSync,
  14633. SourceLocation StartLoc, SourceLocation LParenLoc,
  14634. SourceLocation VarLoc, SourceLocation EndLoc) {
  14635. if (!isValidInteropVariable(*this, InteropVar, VarLoc, OMPC_init))
  14636. return nullptr;
  14637. // Check prefer_type values. These foreign-runtime-id values are either
  14638. // string literals or constant integral expressions.
  14639. for (const Expr *E : PrefExprs) {
  14640. if (E->isValueDependent() || E->isTypeDependent() ||
  14641. E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
  14642. continue;
  14643. if (E->isIntegerConstantExpr(Context))
  14644. continue;
  14645. if (isa<StringLiteral>(E))
  14646. continue;
  14647. Diag(E->getExprLoc(), diag::err_omp_interop_prefer_type);
  14648. return nullptr;
  14649. }
  14650. return OMPInitClause::Create(Context, InteropVar, PrefExprs, IsTarget,
  14651. IsTargetSync, StartLoc, LParenLoc, VarLoc,
  14652. EndLoc);
  14653. }
  14654. OMPClause *Sema::ActOnOpenMPUseClause(Expr *InteropVar, SourceLocation StartLoc,
  14655. SourceLocation LParenLoc,
  14656. SourceLocation VarLoc,
  14657. SourceLocation EndLoc) {
  14658. if (!isValidInteropVariable(*this, InteropVar, VarLoc, OMPC_use))
  14659. return nullptr;
  14660. return new (Context)
  14661. OMPUseClause(InteropVar, StartLoc, LParenLoc, VarLoc, EndLoc);
  14662. }
  14663. OMPClause *Sema::ActOnOpenMPDestroyClause(Expr *InteropVar,
  14664. SourceLocation StartLoc,
  14665. SourceLocation LParenLoc,
  14666. SourceLocation VarLoc,
  14667. SourceLocation EndLoc) {
  14668. if (InteropVar &&
  14669. !isValidInteropVariable(*this, InteropVar, VarLoc, OMPC_destroy))
  14670. return nullptr;
  14671. return new (Context)
  14672. OMPDestroyClause(InteropVar, StartLoc, LParenLoc, VarLoc, EndLoc);
  14673. }
  14674. OMPClause *Sema::ActOnOpenMPNovariantsClause(Expr *Condition,
  14675. SourceLocation StartLoc,
  14676. SourceLocation LParenLoc,
  14677. SourceLocation EndLoc) {
  14678. Expr *ValExpr = Condition;
  14679. Stmt *HelperValStmt = nullptr;
  14680. OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
  14681. if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
  14682. !Condition->isInstantiationDependent() &&
  14683. !Condition->containsUnexpandedParameterPack()) {
  14684. ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
  14685. if (Val.isInvalid())
  14686. return nullptr;
  14687. ValExpr = MakeFullExpr(Val.get()).get();
  14688. OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
  14689. CaptureRegion = getOpenMPCaptureRegionForClause(DKind, OMPC_novariants,
  14690. LangOpts.OpenMP);
  14691. if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
  14692. ValExpr = MakeFullExpr(ValExpr).get();
  14693. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  14694. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  14695. HelperValStmt = buildPreInits(Context, Captures);
  14696. }
  14697. }
  14698. return new (Context) OMPNovariantsClause(
  14699. ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
  14700. }
  14701. OMPClause *Sema::ActOnOpenMPNocontextClause(Expr *Condition,
  14702. SourceLocation StartLoc,
  14703. SourceLocation LParenLoc,
  14704. SourceLocation EndLoc) {
  14705. Expr *ValExpr = Condition;
  14706. Stmt *HelperValStmt = nullptr;
  14707. OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
  14708. if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
  14709. !Condition->isInstantiationDependent() &&
  14710. !Condition->containsUnexpandedParameterPack()) {
  14711. ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
  14712. if (Val.isInvalid())
  14713. return nullptr;
  14714. ValExpr = MakeFullExpr(Val.get()).get();
  14715. OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
  14716. CaptureRegion =
  14717. getOpenMPCaptureRegionForClause(DKind, OMPC_nocontext, LangOpts.OpenMP);
  14718. if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
  14719. ValExpr = MakeFullExpr(ValExpr).get();
  14720. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  14721. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  14722. HelperValStmt = buildPreInits(Context, Captures);
  14723. }
  14724. }
  14725. return new (Context) OMPNocontextClause(ValExpr, HelperValStmt, CaptureRegion,
  14726. StartLoc, LParenLoc, EndLoc);
  14727. }
  14728. OMPClause *Sema::ActOnOpenMPFilterClause(Expr *ThreadID,
  14729. SourceLocation StartLoc,
  14730. SourceLocation LParenLoc,
  14731. SourceLocation EndLoc) {
  14732. Expr *ValExpr = ThreadID;
  14733. Stmt *HelperValStmt = nullptr;
  14734. OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
  14735. OpenMPDirectiveKind CaptureRegion =
  14736. getOpenMPCaptureRegionForClause(DKind, OMPC_filter, LangOpts.OpenMP);
  14737. if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
  14738. ValExpr = MakeFullExpr(ValExpr).get();
  14739. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  14740. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  14741. HelperValStmt = buildPreInits(Context, Captures);
  14742. }
  14743. return new (Context) OMPFilterClause(ValExpr, HelperValStmt, CaptureRegion,
  14744. StartLoc, LParenLoc, EndLoc);
  14745. }
  14746. OMPClause *Sema::ActOnOpenMPVarListClause(
  14747. OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *DepModOrTailExpr,
  14748. const OMPVarListLocTy &Locs, SourceLocation ColonLoc,
  14749. CXXScopeSpec &ReductionOrMapperIdScopeSpec,
  14750. DeclarationNameInfo &ReductionOrMapperId, int ExtraModifier,
  14751. ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
  14752. ArrayRef<SourceLocation> MapTypeModifiersLoc, bool IsMapTypeImplicit,
  14753. SourceLocation ExtraModifierLoc,
  14754. ArrayRef<OpenMPMotionModifierKind> MotionModifiers,
  14755. ArrayRef<SourceLocation> MotionModifiersLoc) {
  14756. SourceLocation StartLoc = Locs.StartLoc;
  14757. SourceLocation LParenLoc = Locs.LParenLoc;
  14758. SourceLocation EndLoc = Locs.EndLoc;
  14759. OMPClause *Res = nullptr;
  14760. switch (Kind) {
  14761. case OMPC_private:
  14762. Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
  14763. break;
  14764. case OMPC_firstprivate:
  14765. Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
  14766. break;
  14767. case OMPC_lastprivate:
  14768. assert(0 <= ExtraModifier && ExtraModifier <= OMPC_LASTPRIVATE_unknown &&
  14769. "Unexpected lastprivate modifier.");
  14770. Res = ActOnOpenMPLastprivateClause(
  14771. VarList, static_cast<OpenMPLastprivateModifier>(ExtraModifier),
  14772. ExtraModifierLoc, ColonLoc, StartLoc, LParenLoc, EndLoc);
  14773. break;
  14774. case OMPC_shared:
  14775. Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
  14776. break;
  14777. case OMPC_reduction:
  14778. assert(0 <= ExtraModifier && ExtraModifier <= OMPC_REDUCTION_unknown &&
  14779. "Unexpected lastprivate modifier.");
  14780. Res = ActOnOpenMPReductionClause(
  14781. VarList, static_cast<OpenMPReductionClauseModifier>(ExtraModifier),
  14782. StartLoc, LParenLoc, ExtraModifierLoc, ColonLoc, EndLoc,
  14783. ReductionOrMapperIdScopeSpec, ReductionOrMapperId);
  14784. break;
  14785. case OMPC_task_reduction:
  14786. Res = ActOnOpenMPTaskReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
  14787. EndLoc, ReductionOrMapperIdScopeSpec,
  14788. ReductionOrMapperId);
  14789. break;
  14790. case OMPC_in_reduction:
  14791. Res = ActOnOpenMPInReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
  14792. EndLoc, ReductionOrMapperIdScopeSpec,
  14793. ReductionOrMapperId);
  14794. break;
  14795. case OMPC_linear:
  14796. assert(0 <= ExtraModifier && ExtraModifier <= OMPC_LINEAR_unknown &&
  14797. "Unexpected linear modifier.");
  14798. Res = ActOnOpenMPLinearClause(
  14799. VarList, DepModOrTailExpr, StartLoc, LParenLoc,
  14800. static_cast<OpenMPLinearClauseKind>(ExtraModifier), ExtraModifierLoc,
  14801. ColonLoc, EndLoc);
  14802. break;
  14803. case OMPC_aligned:
  14804. Res = ActOnOpenMPAlignedClause(VarList, DepModOrTailExpr, StartLoc,
  14805. LParenLoc, ColonLoc, EndLoc);
  14806. break;
  14807. case OMPC_copyin:
  14808. Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
  14809. break;
  14810. case OMPC_copyprivate:
  14811. Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
  14812. break;
  14813. case OMPC_flush:
  14814. Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
  14815. break;
  14816. case OMPC_depend:
  14817. assert(0 <= ExtraModifier && ExtraModifier <= OMPC_DEPEND_unknown &&
  14818. "Unexpected depend modifier.");
  14819. Res = ActOnOpenMPDependClause(
  14820. DepModOrTailExpr, static_cast<OpenMPDependClauseKind>(ExtraModifier),
  14821. ExtraModifierLoc, ColonLoc, VarList, StartLoc, LParenLoc, EndLoc);
  14822. break;
  14823. case OMPC_map:
  14824. assert(0 <= ExtraModifier && ExtraModifier <= OMPC_MAP_unknown &&
  14825. "Unexpected map modifier.");
  14826. Res = ActOnOpenMPMapClause(
  14827. MapTypeModifiers, MapTypeModifiersLoc, ReductionOrMapperIdScopeSpec,
  14828. ReductionOrMapperId, static_cast<OpenMPMapClauseKind>(ExtraModifier),
  14829. IsMapTypeImplicit, ExtraModifierLoc, ColonLoc, VarList, Locs);
  14830. break;
  14831. case OMPC_to:
  14832. Res = ActOnOpenMPToClause(MotionModifiers, MotionModifiersLoc,
  14833. ReductionOrMapperIdScopeSpec, ReductionOrMapperId,
  14834. ColonLoc, VarList, Locs);
  14835. break;
  14836. case OMPC_from:
  14837. Res = ActOnOpenMPFromClause(MotionModifiers, MotionModifiersLoc,
  14838. ReductionOrMapperIdScopeSpec,
  14839. ReductionOrMapperId, ColonLoc, VarList, Locs);
  14840. break;
  14841. case OMPC_use_device_ptr:
  14842. Res = ActOnOpenMPUseDevicePtrClause(VarList, Locs);
  14843. break;
  14844. case OMPC_use_device_addr:
  14845. Res = ActOnOpenMPUseDeviceAddrClause(VarList, Locs);
  14846. break;
  14847. case OMPC_is_device_ptr:
  14848. Res = ActOnOpenMPIsDevicePtrClause(VarList, Locs);
  14849. break;
  14850. case OMPC_allocate:
  14851. Res = ActOnOpenMPAllocateClause(DepModOrTailExpr, VarList, StartLoc,
  14852. LParenLoc, ColonLoc, EndLoc);
  14853. break;
  14854. case OMPC_nontemporal:
  14855. Res = ActOnOpenMPNontemporalClause(VarList, StartLoc, LParenLoc, EndLoc);
  14856. break;
  14857. case OMPC_inclusive:
  14858. Res = ActOnOpenMPInclusiveClause(VarList, StartLoc, LParenLoc, EndLoc);
  14859. break;
  14860. case OMPC_exclusive:
  14861. Res = ActOnOpenMPExclusiveClause(VarList, StartLoc, LParenLoc, EndLoc);
  14862. break;
  14863. case OMPC_affinity:
  14864. Res = ActOnOpenMPAffinityClause(StartLoc, LParenLoc, ColonLoc, EndLoc,
  14865. DepModOrTailExpr, VarList);
  14866. break;
  14867. case OMPC_if:
  14868. case OMPC_depobj:
  14869. case OMPC_final:
  14870. case OMPC_num_threads:
  14871. case OMPC_safelen:
  14872. case OMPC_simdlen:
  14873. case OMPC_sizes:
  14874. case OMPC_allocator:
  14875. case OMPC_collapse:
  14876. case OMPC_default:
  14877. case OMPC_proc_bind:
  14878. case OMPC_schedule:
  14879. case OMPC_ordered:
  14880. case OMPC_nowait:
  14881. case OMPC_untied:
  14882. case OMPC_mergeable:
  14883. case OMPC_threadprivate:
  14884. case OMPC_read:
  14885. case OMPC_write:
  14886. case OMPC_update:
  14887. case OMPC_capture:
  14888. case OMPC_compare:
  14889. case OMPC_seq_cst:
  14890. case OMPC_acq_rel:
  14891. case OMPC_acquire:
  14892. case OMPC_release:
  14893. case OMPC_relaxed:
  14894. case OMPC_device:
  14895. case OMPC_threads:
  14896. case OMPC_simd:
  14897. case OMPC_num_teams:
  14898. case OMPC_thread_limit:
  14899. case OMPC_priority:
  14900. case OMPC_grainsize:
  14901. case OMPC_nogroup:
  14902. case OMPC_num_tasks:
  14903. case OMPC_hint:
  14904. case OMPC_dist_schedule:
  14905. case OMPC_defaultmap:
  14906. case OMPC_unknown:
  14907. case OMPC_uniform:
  14908. case OMPC_unified_address:
  14909. case OMPC_unified_shared_memory:
  14910. case OMPC_reverse_offload:
  14911. case OMPC_dynamic_allocators:
  14912. case OMPC_atomic_default_mem_order:
  14913. case OMPC_device_type:
  14914. case OMPC_match:
  14915. case OMPC_order:
  14916. case OMPC_destroy:
  14917. case OMPC_novariants:
  14918. case OMPC_nocontext:
  14919. case OMPC_detach:
  14920. case OMPC_uses_allocators:
  14921. case OMPC_when:
  14922. case OMPC_bind:
  14923. default:
  14924. llvm_unreachable("Clause is not allowed.");
  14925. }
  14926. return Res;
  14927. }
  14928. ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
  14929. ExprObjectKind OK, SourceLocation Loc) {
  14930. ExprResult Res = BuildDeclRefExpr(
  14931. Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
  14932. if (!Res.isUsable())
  14933. return ExprError();
  14934. if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
  14935. Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
  14936. if (!Res.isUsable())
  14937. return ExprError();
  14938. }
  14939. if (VK != VK_LValue && Res.get()->isGLValue()) {
  14940. Res = DefaultLvalueConversion(Res.get());
  14941. if (!Res.isUsable())
  14942. return ExprError();
  14943. }
  14944. return Res;
  14945. }
  14946. OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
  14947. SourceLocation StartLoc,
  14948. SourceLocation LParenLoc,
  14949. SourceLocation EndLoc) {
  14950. SmallVector<Expr *, 8> Vars;
  14951. SmallVector<Expr *, 8> PrivateCopies;
  14952. for (Expr *RefExpr : VarList) {
  14953. assert(RefExpr && "NULL expr in OpenMP private clause.");
  14954. SourceLocation ELoc;
  14955. SourceRange ERange;
  14956. Expr *SimpleRefExpr = RefExpr;
  14957. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  14958. if (Res.second) {
  14959. // It will be analyzed later.
  14960. Vars.push_back(RefExpr);
  14961. PrivateCopies.push_back(nullptr);
  14962. }
  14963. ValueDecl *D = Res.first;
  14964. if (!D)
  14965. continue;
  14966. QualType Type = D->getType();
  14967. auto *VD = dyn_cast<VarDecl>(D);
  14968. // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
  14969. // A variable that appears in a private clause must not have an incomplete
  14970. // type or a reference type.
  14971. if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
  14972. continue;
  14973. Type = Type.getNonReferenceType();
  14974. // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
  14975. // A variable that is privatized must not have a const-qualified type
  14976. // unless it is of class type with a mutable member. This restriction does
  14977. // not apply to the firstprivate clause.
  14978. //
  14979. // OpenMP 3.1 [2.9.3.3, private clause, Restrictions]
  14980. // A variable that appears in a private clause must not have a
  14981. // const-qualified type unless it is of class type with a mutable member.
  14982. if (rejectConstNotMutableType(*this, D, Type, OMPC_private, ELoc))
  14983. continue;
  14984. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  14985. // in a Construct]
  14986. // Variables with the predetermined data-sharing attributes may not be
  14987. // listed in data-sharing attributes clauses, except for the cases
  14988. // listed below. For these exceptions only, listing a predetermined
  14989. // variable in a data-sharing attribute clause is allowed and overrides
  14990. // the variable's predetermined data-sharing attributes.
  14991. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
  14992. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
  14993. Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
  14994. << getOpenMPClauseName(OMPC_private);
  14995. reportOriginalDsa(*this, DSAStack, D, DVar);
  14996. continue;
  14997. }
  14998. OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
  14999. // Variably modified types are not supported for tasks.
  15000. if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
  15001. isOpenMPTaskingDirective(CurrDir)) {
  15002. Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
  15003. << getOpenMPClauseName(OMPC_private) << Type
  15004. << getOpenMPDirectiveName(CurrDir);
  15005. bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
  15006. VarDecl::DeclarationOnly;
  15007. Diag(D->getLocation(),
  15008. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  15009. << D;
  15010. continue;
  15011. }
  15012. // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
  15013. // A list item cannot appear in both a map clause and a data-sharing
  15014. // attribute clause on the same construct
  15015. //
  15016. // OpenMP 5.0 [2.19.7.1, Restrictions, p.7]
  15017. // A list item cannot appear in both a map clause and a data-sharing
  15018. // attribute clause on the same construct unless the construct is a
  15019. // combined construct.
  15020. if ((LangOpts.OpenMP <= 45 && isOpenMPTargetExecutionDirective(CurrDir)) ||
  15021. CurrDir == OMPD_target) {
  15022. OpenMPClauseKind ConflictKind;
  15023. if (DSAStack->checkMappableExprComponentListsForDecl(
  15024. VD, /*CurrentRegionOnly=*/true,
  15025. [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
  15026. OpenMPClauseKind WhereFoundClauseKind) -> bool {
  15027. ConflictKind = WhereFoundClauseKind;
  15028. return true;
  15029. })) {
  15030. Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
  15031. << getOpenMPClauseName(OMPC_private)
  15032. << getOpenMPClauseName(ConflictKind)
  15033. << getOpenMPDirectiveName(CurrDir);
  15034. reportOriginalDsa(*this, DSAStack, D, DVar);
  15035. continue;
  15036. }
  15037. }
  15038. // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
  15039. // A variable of class type (or array thereof) that appears in a private
  15040. // clause requires an accessible, unambiguous default constructor for the
  15041. // class type.
  15042. // Generate helper private variable and initialize it with the default
  15043. // value. The address of the original variable is replaced by the address of
  15044. // the new private variable in CodeGen. This new variable is not added to
  15045. // IdResolver, so the code in the OpenMP region uses original variable for
  15046. // proper diagnostics.
  15047. Type = Type.getUnqualifiedType();
  15048. VarDecl *VDPrivate =
  15049. buildVarDecl(*this, ELoc, Type, D->getName(),
  15050. D->hasAttrs() ? &D->getAttrs() : nullptr,
  15051. VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
  15052. ActOnUninitializedDecl(VDPrivate);
  15053. if (VDPrivate->isInvalidDecl())
  15054. continue;
  15055. DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
  15056. *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
  15057. DeclRefExpr *Ref = nullptr;
  15058. if (!VD && !CurContext->isDependentContext())
  15059. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
  15060. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
  15061. Vars.push_back((VD || CurContext->isDependentContext())
  15062. ? RefExpr->IgnoreParens()
  15063. : Ref);
  15064. PrivateCopies.push_back(VDPrivateRefExpr);
  15065. }
  15066. if (Vars.empty())
  15067. return nullptr;
  15068. return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
  15069. PrivateCopies);
  15070. }
  15071. OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
  15072. SourceLocation StartLoc,
  15073. SourceLocation LParenLoc,
  15074. SourceLocation EndLoc) {
  15075. SmallVector<Expr *, 8> Vars;
  15076. SmallVector<Expr *, 8> PrivateCopies;
  15077. SmallVector<Expr *, 8> Inits;
  15078. SmallVector<Decl *, 4> ExprCaptures;
  15079. bool IsImplicitClause =
  15080. StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
  15081. SourceLocation ImplicitClauseLoc = DSAStack->getConstructLoc();
  15082. for (Expr *RefExpr : VarList) {
  15083. assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
  15084. SourceLocation ELoc;
  15085. SourceRange ERange;
  15086. Expr *SimpleRefExpr = RefExpr;
  15087. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  15088. if (Res.second) {
  15089. // It will be analyzed later.
  15090. Vars.push_back(RefExpr);
  15091. PrivateCopies.push_back(nullptr);
  15092. Inits.push_back(nullptr);
  15093. }
  15094. ValueDecl *D = Res.first;
  15095. if (!D)
  15096. continue;
  15097. ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
  15098. QualType Type = D->getType();
  15099. auto *VD = dyn_cast<VarDecl>(D);
  15100. // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
  15101. // A variable that appears in a private clause must not have an incomplete
  15102. // type or a reference type.
  15103. if (RequireCompleteType(ELoc, Type,
  15104. diag::err_omp_firstprivate_incomplete_type))
  15105. continue;
  15106. Type = Type.getNonReferenceType();
  15107. // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
  15108. // A variable of class type (or array thereof) that appears in a private
  15109. // clause requires an accessible, unambiguous copy constructor for the
  15110. // class type.
  15111. QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
  15112. // If an implicit firstprivate variable found it was checked already.
  15113. DSAStackTy::DSAVarData TopDVar;
  15114. if (!IsImplicitClause) {
  15115. DSAStackTy::DSAVarData DVar =
  15116. DSAStack->getTopDSA(D, /*FromParent=*/false);
  15117. TopDVar = DVar;
  15118. OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
  15119. bool IsConstant = ElemType.isConstant(Context);
  15120. // OpenMP [2.4.13, Data-sharing Attribute Clauses]
  15121. // A list item that specifies a given variable may not appear in more
  15122. // than one clause on the same directive, except that a variable may be
  15123. // specified in both firstprivate and lastprivate clauses.
  15124. // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
  15125. // A list item may appear in a firstprivate or lastprivate clause but not
  15126. // both.
  15127. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
  15128. (isOpenMPDistributeDirective(CurrDir) ||
  15129. DVar.CKind != OMPC_lastprivate) &&
  15130. DVar.RefExpr) {
  15131. Diag(ELoc, diag::err_omp_wrong_dsa)
  15132. << getOpenMPClauseName(DVar.CKind)
  15133. << getOpenMPClauseName(OMPC_firstprivate);
  15134. reportOriginalDsa(*this, DSAStack, D, DVar);
  15135. continue;
  15136. }
  15137. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  15138. // in a Construct]
  15139. // Variables with the predetermined data-sharing attributes may not be
  15140. // listed in data-sharing attributes clauses, except for the cases
  15141. // listed below. For these exceptions only, listing a predetermined
  15142. // variable in a data-sharing attribute clause is allowed and overrides
  15143. // the variable's predetermined data-sharing attributes.
  15144. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  15145. // in a Construct, C/C++, p.2]
  15146. // Variables with const-qualified type having no mutable member may be
  15147. // listed in a firstprivate clause, even if they are static data members.
  15148. if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
  15149. DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
  15150. Diag(ELoc, diag::err_omp_wrong_dsa)
  15151. << getOpenMPClauseName(DVar.CKind)
  15152. << getOpenMPClauseName(OMPC_firstprivate);
  15153. reportOriginalDsa(*this, DSAStack, D, DVar);
  15154. continue;
  15155. }
  15156. // OpenMP [2.9.3.4, Restrictions, p.2]
  15157. // A list item that is private within a parallel region must not appear
  15158. // in a firstprivate clause on a worksharing construct if any of the
  15159. // worksharing regions arising from the worksharing construct ever bind
  15160. // to any of the parallel regions arising from the parallel construct.
  15161. // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
  15162. // A list item that is private within a teams region must not appear in a
  15163. // firstprivate clause on a distribute construct if any of the distribute
  15164. // regions arising from the distribute construct ever bind to any of the
  15165. // teams regions arising from the teams construct.
  15166. // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
  15167. // A list item that appears in a reduction clause of a teams construct
  15168. // must not appear in a firstprivate clause on a distribute construct if
  15169. // any of the distribute regions arising from the distribute construct
  15170. // ever bind to any of the teams regions arising from the teams construct.
  15171. if ((isOpenMPWorksharingDirective(CurrDir) ||
  15172. isOpenMPDistributeDirective(CurrDir)) &&
  15173. !isOpenMPParallelDirective(CurrDir) &&
  15174. !isOpenMPTeamsDirective(CurrDir)) {
  15175. DVar = DSAStack->getImplicitDSA(D, true);
  15176. if (DVar.CKind != OMPC_shared &&
  15177. (isOpenMPParallelDirective(DVar.DKind) ||
  15178. isOpenMPTeamsDirective(DVar.DKind) ||
  15179. DVar.DKind == OMPD_unknown)) {
  15180. Diag(ELoc, diag::err_omp_required_access)
  15181. << getOpenMPClauseName(OMPC_firstprivate)
  15182. << getOpenMPClauseName(OMPC_shared);
  15183. reportOriginalDsa(*this, DSAStack, D, DVar);
  15184. continue;
  15185. }
  15186. }
  15187. // OpenMP [2.9.3.4, Restrictions, p.3]
  15188. // A list item that appears in a reduction clause of a parallel construct
  15189. // must not appear in a firstprivate clause on a worksharing or task
  15190. // construct if any of the worksharing or task regions arising from the
  15191. // worksharing or task construct ever bind to any of the parallel regions
  15192. // arising from the parallel construct.
  15193. // OpenMP [2.9.3.4, Restrictions, p.4]
  15194. // A list item that appears in a reduction clause in worksharing
  15195. // construct must not appear in a firstprivate clause in a task construct
  15196. // encountered during execution of any of the worksharing regions arising
  15197. // from the worksharing construct.
  15198. if (isOpenMPTaskingDirective(CurrDir)) {
  15199. DVar = DSAStack->hasInnermostDSA(
  15200. D,
  15201. [](OpenMPClauseKind C, bool AppliedToPointee) {
  15202. return C == OMPC_reduction && !AppliedToPointee;
  15203. },
  15204. [](OpenMPDirectiveKind K) {
  15205. return isOpenMPParallelDirective(K) ||
  15206. isOpenMPWorksharingDirective(K) ||
  15207. isOpenMPTeamsDirective(K);
  15208. },
  15209. /*FromParent=*/true);
  15210. if (DVar.CKind == OMPC_reduction &&
  15211. (isOpenMPParallelDirective(DVar.DKind) ||
  15212. isOpenMPWorksharingDirective(DVar.DKind) ||
  15213. isOpenMPTeamsDirective(DVar.DKind))) {
  15214. Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
  15215. << getOpenMPDirectiveName(DVar.DKind);
  15216. reportOriginalDsa(*this, DSAStack, D, DVar);
  15217. continue;
  15218. }
  15219. }
  15220. // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
  15221. // A list item cannot appear in both a map clause and a data-sharing
  15222. // attribute clause on the same construct
  15223. //
  15224. // OpenMP 5.0 [2.19.7.1, Restrictions, p.7]
  15225. // A list item cannot appear in both a map clause and a data-sharing
  15226. // attribute clause on the same construct unless the construct is a
  15227. // combined construct.
  15228. if ((LangOpts.OpenMP <= 45 &&
  15229. isOpenMPTargetExecutionDirective(CurrDir)) ||
  15230. CurrDir == OMPD_target) {
  15231. OpenMPClauseKind ConflictKind;
  15232. if (DSAStack->checkMappableExprComponentListsForDecl(
  15233. VD, /*CurrentRegionOnly=*/true,
  15234. [&ConflictKind](
  15235. OMPClauseMappableExprCommon::MappableExprComponentListRef,
  15236. OpenMPClauseKind WhereFoundClauseKind) {
  15237. ConflictKind = WhereFoundClauseKind;
  15238. return true;
  15239. })) {
  15240. Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
  15241. << getOpenMPClauseName(OMPC_firstprivate)
  15242. << getOpenMPClauseName(ConflictKind)
  15243. << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
  15244. reportOriginalDsa(*this, DSAStack, D, DVar);
  15245. continue;
  15246. }
  15247. }
  15248. }
  15249. // Variably modified types are not supported for tasks.
  15250. if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
  15251. isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
  15252. Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
  15253. << getOpenMPClauseName(OMPC_firstprivate) << Type
  15254. << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
  15255. bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
  15256. VarDecl::DeclarationOnly;
  15257. Diag(D->getLocation(),
  15258. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  15259. << D;
  15260. continue;
  15261. }
  15262. Type = Type.getUnqualifiedType();
  15263. VarDecl *VDPrivate =
  15264. buildVarDecl(*this, ELoc, Type, D->getName(),
  15265. D->hasAttrs() ? &D->getAttrs() : nullptr,
  15266. VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
  15267. // Generate helper private variable and initialize it with the value of the
  15268. // original variable. The address of the original variable is replaced by
  15269. // the address of the new private variable in the CodeGen. This new variable
  15270. // is not added to IdResolver, so the code in the OpenMP region uses
  15271. // original variable for proper diagnostics and variable capturing.
  15272. Expr *VDInitRefExpr = nullptr;
  15273. // For arrays generate initializer for single element and replace it by the
  15274. // original array element in CodeGen.
  15275. if (Type->isArrayType()) {
  15276. VarDecl *VDInit =
  15277. buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
  15278. VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
  15279. Expr *Init = DefaultLvalueConversion(VDInitRefExpr).get();
  15280. ElemType = ElemType.getUnqualifiedType();
  15281. VarDecl *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
  15282. ".firstprivate.temp");
  15283. InitializedEntity Entity =
  15284. InitializedEntity::InitializeVariable(VDInitTemp);
  15285. InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
  15286. InitializationSequence InitSeq(*this, Entity, Kind, Init);
  15287. ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
  15288. if (Result.isInvalid())
  15289. VDPrivate->setInvalidDecl();
  15290. else
  15291. VDPrivate->setInit(Result.getAs<Expr>());
  15292. // Remove temp variable declaration.
  15293. Context.Deallocate(VDInitTemp);
  15294. } else {
  15295. VarDecl *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
  15296. ".firstprivate.temp");
  15297. VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
  15298. RefExpr->getExprLoc());
  15299. AddInitializerToDecl(VDPrivate,
  15300. DefaultLvalueConversion(VDInitRefExpr).get(),
  15301. /*DirectInit=*/false);
  15302. }
  15303. if (VDPrivate->isInvalidDecl()) {
  15304. if (IsImplicitClause) {
  15305. Diag(RefExpr->getExprLoc(),
  15306. diag::note_omp_task_predetermined_firstprivate_here);
  15307. }
  15308. continue;
  15309. }
  15310. CurContext->addDecl(VDPrivate);
  15311. DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
  15312. *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
  15313. RefExpr->getExprLoc());
  15314. DeclRefExpr *Ref = nullptr;
  15315. if (!VD && !CurContext->isDependentContext()) {
  15316. if (TopDVar.CKind == OMPC_lastprivate) {
  15317. Ref = TopDVar.PrivateCopy;
  15318. } else {
  15319. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
  15320. if (!isOpenMPCapturedDecl(D))
  15321. ExprCaptures.push_back(Ref->getDecl());
  15322. }
  15323. }
  15324. if (!IsImplicitClause)
  15325. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
  15326. Vars.push_back((VD || CurContext->isDependentContext())
  15327. ? RefExpr->IgnoreParens()
  15328. : Ref);
  15329. PrivateCopies.push_back(VDPrivateRefExpr);
  15330. Inits.push_back(VDInitRefExpr);
  15331. }
  15332. if (Vars.empty())
  15333. return nullptr;
  15334. return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  15335. Vars, PrivateCopies, Inits,
  15336. buildPreInits(Context, ExprCaptures));
  15337. }
  15338. OMPClause *Sema::ActOnOpenMPLastprivateClause(
  15339. ArrayRef<Expr *> VarList, OpenMPLastprivateModifier LPKind,
  15340. SourceLocation LPKindLoc, SourceLocation ColonLoc, SourceLocation StartLoc,
  15341. SourceLocation LParenLoc, SourceLocation EndLoc) {
  15342. if (LPKind == OMPC_LASTPRIVATE_unknown && LPKindLoc.isValid()) {
  15343. assert(ColonLoc.isValid() && "Colon location must be valid.");
  15344. Diag(LPKindLoc, diag::err_omp_unexpected_clause_value)
  15345. << getListOfPossibleValues(OMPC_lastprivate, /*First=*/0,
  15346. /*Last=*/OMPC_LASTPRIVATE_unknown)
  15347. << getOpenMPClauseName(OMPC_lastprivate);
  15348. return nullptr;
  15349. }
  15350. SmallVector<Expr *, 8> Vars;
  15351. SmallVector<Expr *, 8> SrcExprs;
  15352. SmallVector<Expr *, 8> DstExprs;
  15353. SmallVector<Expr *, 8> AssignmentOps;
  15354. SmallVector<Decl *, 4> ExprCaptures;
  15355. SmallVector<Expr *, 4> ExprPostUpdates;
  15356. for (Expr *RefExpr : VarList) {
  15357. assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
  15358. SourceLocation ELoc;
  15359. SourceRange ERange;
  15360. Expr *SimpleRefExpr = RefExpr;
  15361. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  15362. if (Res.second) {
  15363. // It will be analyzed later.
  15364. Vars.push_back(RefExpr);
  15365. SrcExprs.push_back(nullptr);
  15366. DstExprs.push_back(nullptr);
  15367. AssignmentOps.push_back(nullptr);
  15368. }
  15369. ValueDecl *D = Res.first;
  15370. if (!D)
  15371. continue;
  15372. QualType Type = D->getType();
  15373. auto *VD = dyn_cast<VarDecl>(D);
  15374. // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
  15375. // A variable that appears in a lastprivate clause must not have an
  15376. // incomplete type or a reference type.
  15377. if (RequireCompleteType(ELoc, Type,
  15378. diag::err_omp_lastprivate_incomplete_type))
  15379. continue;
  15380. Type = Type.getNonReferenceType();
  15381. // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
  15382. // A variable that is privatized must not have a const-qualified type
  15383. // unless it is of class type with a mutable member. This restriction does
  15384. // not apply to the firstprivate clause.
  15385. //
  15386. // OpenMP 3.1 [2.9.3.5, lastprivate clause, Restrictions]
  15387. // A variable that appears in a lastprivate clause must not have a
  15388. // const-qualified type unless it is of class type with a mutable member.
  15389. if (rejectConstNotMutableType(*this, D, Type, OMPC_lastprivate, ELoc))
  15390. continue;
  15391. // OpenMP 5.0 [2.19.4.5 lastprivate Clause, Restrictions]
  15392. // A list item that appears in a lastprivate clause with the conditional
  15393. // modifier must be a scalar variable.
  15394. if (LPKind == OMPC_LASTPRIVATE_conditional && !Type->isScalarType()) {
  15395. Diag(ELoc, diag::err_omp_lastprivate_conditional_non_scalar);
  15396. bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
  15397. VarDecl::DeclarationOnly;
  15398. Diag(D->getLocation(),
  15399. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  15400. << D;
  15401. continue;
  15402. }
  15403. OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
  15404. // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
  15405. // in a Construct]
  15406. // Variables with the predetermined data-sharing attributes may not be
  15407. // listed in data-sharing attributes clauses, except for the cases
  15408. // listed below.
  15409. // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
  15410. // A list item may appear in a firstprivate or lastprivate clause but not
  15411. // both.
  15412. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
  15413. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
  15414. (isOpenMPDistributeDirective(CurrDir) ||
  15415. DVar.CKind != OMPC_firstprivate) &&
  15416. (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
  15417. Diag(ELoc, diag::err_omp_wrong_dsa)
  15418. << getOpenMPClauseName(DVar.CKind)
  15419. << getOpenMPClauseName(OMPC_lastprivate);
  15420. reportOriginalDsa(*this, DSAStack, D, DVar);
  15421. continue;
  15422. }
  15423. // OpenMP [2.14.3.5, Restrictions, p.2]
  15424. // A list item that is private within a parallel region, or that appears in
  15425. // the reduction clause of a parallel construct, must not appear in a
  15426. // lastprivate clause on a worksharing construct if any of the corresponding
  15427. // worksharing regions ever binds to any of the corresponding parallel
  15428. // regions.
  15429. DSAStackTy::DSAVarData TopDVar = DVar;
  15430. if (isOpenMPWorksharingDirective(CurrDir) &&
  15431. !isOpenMPParallelDirective(CurrDir) &&
  15432. !isOpenMPTeamsDirective(CurrDir)) {
  15433. DVar = DSAStack->getImplicitDSA(D, true);
  15434. if (DVar.CKind != OMPC_shared) {
  15435. Diag(ELoc, diag::err_omp_required_access)
  15436. << getOpenMPClauseName(OMPC_lastprivate)
  15437. << getOpenMPClauseName(OMPC_shared);
  15438. reportOriginalDsa(*this, DSAStack, D, DVar);
  15439. continue;
  15440. }
  15441. }
  15442. // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
  15443. // A variable of class type (or array thereof) that appears in a
  15444. // lastprivate clause requires an accessible, unambiguous default
  15445. // constructor for the class type, unless the list item is also specified
  15446. // in a firstprivate clause.
  15447. // A variable of class type (or array thereof) that appears in a
  15448. // lastprivate clause requires an accessible, unambiguous copy assignment
  15449. // operator for the class type.
  15450. Type = Context.getBaseElementType(Type).getNonReferenceType();
  15451. VarDecl *SrcVD = buildVarDecl(*this, ERange.getBegin(),
  15452. Type.getUnqualifiedType(), ".lastprivate.src",
  15453. D->hasAttrs() ? &D->getAttrs() : nullptr);
  15454. DeclRefExpr *PseudoSrcExpr =
  15455. buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
  15456. VarDecl *DstVD =
  15457. buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
  15458. D->hasAttrs() ? &D->getAttrs() : nullptr);
  15459. DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
  15460. // For arrays generate assignment operation for single element and replace
  15461. // it by the original array element in CodeGen.
  15462. ExprResult AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
  15463. PseudoDstExpr, PseudoSrcExpr);
  15464. if (AssignmentOp.isInvalid())
  15465. continue;
  15466. AssignmentOp =
  15467. ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
  15468. if (AssignmentOp.isInvalid())
  15469. continue;
  15470. DeclRefExpr *Ref = nullptr;
  15471. if (!VD && !CurContext->isDependentContext()) {
  15472. if (TopDVar.CKind == OMPC_firstprivate) {
  15473. Ref = TopDVar.PrivateCopy;
  15474. } else {
  15475. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
  15476. if (!isOpenMPCapturedDecl(D))
  15477. ExprCaptures.push_back(Ref->getDecl());
  15478. }
  15479. if ((TopDVar.CKind == OMPC_firstprivate && !TopDVar.PrivateCopy) ||
  15480. (!isOpenMPCapturedDecl(D) &&
  15481. Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
  15482. ExprResult RefRes = DefaultLvalueConversion(Ref);
  15483. if (!RefRes.isUsable())
  15484. continue;
  15485. ExprResult PostUpdateRes =
  15486. BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
  15487. RefRes.get());
  15488. if (!PostUpdateRes.isUsable())
  15489. continue;
  15490. ExprPostUpdates.push_back(
  15491. IgnoredValueConversions(PostUpdateRes.get()).get());
  15492. }
  15493. }
  15494. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
  15495. Vars.push_back((VD || CurContext->isDependentContext())
  15496. ? RefExpr->IgnoreParens()
  15497. : Ref);
  15498. SrcExprs.push_back(PseudoSrcExpr);
  15499. DstExprs.push_back(PseudoDstExpr);
  15500. AssignmentOps.push_back(AssignmentOp.get());
  15501. }
  15502. if (Vars.empty())
  15503. return nullptr;
  15504. return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  15505. Vars, SrcExprs, DstExprs, AssignmentOps,
  15506. LPKind, LPKindLoc, ColonLoc,
  15507. buildPreInits(Context, ExprCaptures),
  15508. buildPostUpdate(*this, ExprPostUpdates));
  15509. }
  15510. OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
  15511. SourceLocation StartLoc,
  15512. SourceLocation LParenLoc,
  15513. SourceLocation EndLoc) {
  15514. SmallVector<Expr *, 8> Vars;
  15515. for (Expr *RefExpr : VarList) {
  15516. assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
  15517. SourceLocation ELoc;
  15518. SourceRange ERange;
  15519. Expr *SimpleRefExpr = RefExpr;
  15520. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  15521. if (Res.second) {
  15522. // It will be analyzed later.
  15523. Vars.push_back(RefExpr);
  15524. }
  15525. ValueDecl *D = Res.first;
  15526. if (!D)
  15527. continue;
  15528. auto *VD = dyn_cast<VarDecl>(D);
  15529. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  15530. // in a Construct]
  15531. // Variables with the predetermined data-sharing attributes may not be
  15532. // listed in data-sharing attributes clauses, except for the cases
  15533. // listed below. For these exceptions only, listing a predetermined
  15534. // variable in a data-sharing attribute clause is allowed and overrides
  15535. // the variable's predetermined data-sharing attributes.
  15536. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
  15537. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
  15538. DVar.RefExpr) {
  15539. Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
  15540. << getOpenMPClauseName(OMPC_shared);
  15541. reportOriginalDsa(*this, DSAStack, D, DVar);
  15542. continue;
  15543. }
  15544. DeclRefExpr *Ref = nullptr;
  15545. if (!VD && isOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
  15546. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
  15547. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
  15548. Vars.push_back((VD || !Ref || CurContext->isDependentContext())
  15549. ? RefExpr->IgnoreParens()
  15550. : Ref);
  15551. }
  15552. if (Vars.empty())
  15553. return nullptr;
  15554. return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
  15555. }
  15556. namespace {
  15557. class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
  15558. DSAStackTy *Stack;
  15559. public:
  15560. bool VisitDeclRefExpr(DeclRefExpr *E) {
  15561. if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
  15562. DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
  15563. if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
  15564. return false;
  15565. if (DVar.CKind != OMPC_unknown)
  15566. return true;
  15567. DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
  15568. VD,
  15569. [](OpenMPClauseKind C, bool AppliedToPointee) {
  15570. return isOpenMPPrivate(C) && !AppliedToPointee;
  15571. },
  15572. [](OpenMPDirectiveKind) { return true; },
  15573. /*FromParent=*/true);
  15574. return DVarPrivate.CKind != OMPC_unknown;
  15575. }
  15576. return false;
  15577. }
  15578. bool VisitStmt(Stmt *S) {
  15579. for (Stmt *Child : S->children()) {
  15580. if (Child && Visit(Child))
  15581. return true;
  15582. }
  15583. return false;
  15584. }
  15585. explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
  15586. };
  15587. } // namespace
  15588. namespace {
  15589. // Transform MemberExpression for specified FieldDecl of current class to
  15590. // DeclRefExpr to specified OMPCapturedExprDecl.
  15591. class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
  15592. typedef TreeTransform<TransformExprToCaptures> BaseTransform;
  15593. ValueDecl *Field = nullptr;
  15594. DeclRefExpr *CapturedExpr = nullptr;
  15595. public:
  15596. TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
  15597. : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
  15598. ExprResult TransformMemberExpr(MemberExpr *E) {
  15599. if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
  15600. E->getMemberDecl() == Field) {
  15601. CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
  15602. return CapturedExpr;
  15603. }
  15604. return BaseTransform::TransformMemberExpr(E);
  15605. }
  15606. DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
  15607. };
  15608. } // namespace
  15609. template <typename T, typename U>
  15610. static T filterLookupForUDReductionAndMapper(
  15611. SmallVectorImpl<U> &Lookups, const llvm::function_ref<T(ValueDecl *)> Gen) {
  15612. for (U &Set : Lookups) {
  15613. for (auto *D : Set) {
  15614. if (T Res = Gen(cast<ValueDecl>(D)))
  15615. return Res;
  15616. }
  15617. }
  15618. return T();
  15619. }
  15620. static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D) {
  15621. assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case");
  15622. for (auto RD : D->redecls()) {
  15623. // Don't bother with extra checks if we already know this one isn't visible.
  15624. if (RD == D)
  15625. continue;
  15626. auto ND = cast<NamedDecl>(RD);
  15627. if (LookupResult::isVisible(SemaRef, ND))
  15628. return ND;
  15629. }
  15630. return nullptr;
  15631. }
  15632. static void
  15633. argumentDependentLookup(Sema &SemaRef, const DeclarationNameInfo &Id,
  15634. SourceLocation Loc, QualType Ty,
  15635. SmallVectorImpl<UnresolvedSet<8>> &Lookups) {
  15636. // Find all of the associated namespaces and classes based on the
  15637. // arguments we have.
  15638. Sema::AssociatedNamespaceSet AssociatedNamespaces;
  15639. Sema::AssociatedClassSet AssociatedClasses;
  15640. OpaqueValueExpr OVE(Loc, Ty, VK_LValue);
  15641. SemaRef.FindAssociatedClassesAndNamespaces(Loc, &OVE, AssociatedNamespaces,
  15642. AssociatedClasses);
  15643. // C++ [basic.lookup.argdep]p3:
  15644. // Let X be the lookup set produced by unqualified lookup (3.4.1)
  15645. // and let Y be the lookup set produced by argument dependent
  15646. // lookup (defined as follows). If X contains [...] then Y is
  15647. // empty. Otherwise Y is the set of declarations found in the
  15648. // namespaces associated with the argument types as described
  15649. // below. The set of declarations found by the lookup of the name
  15650. // is the union of X and Y.
  15651. //
  15652. // Here, we compute Y and add its members to the overloaded
  15653. // candidate set.
  15654. for (auto *NS : AssociatedNamespaces) {
  15655. // When considering an associated namespace, the lookup is the
  15656. // same as the lookup performed when the associated namespace is
  15657. // used as a qualifier (3.4.3.2) except that:
  15658. //
  15659. // -- Any using-directives in the associated namespace are
  15660. // ignored.
  15661. //
  15662. // -- Any namespace-scope friend functions declared in
  15663. // associated classes are visible within their respective
  15664. // namespaces even if they are not visible during an ordinary
  15665. // lookup (11.4).
  15666. DeclContext::lookup_result R = NS->lookup(Id.getName());
  15667. for (auto *D : R) {
  15668. auto *Underlying = D;
  15669. if (auto *USD = dyn_cast<UsingShadowDecl>(D))
  15670. Underlying = USD->getTargetDecl();
  15671. if (!isa<OMPDeclareReductionDecl>(Underlying) &&
  15672. !isa<OMPDeclareMapperDecl>(Underlying))
  15673. continue;
  15674. if (!SemaRef.isVisible(D)) {
  15675. D = findAcceptableDecl(SemaRef, D);
  15676. if (!D)
  15677. continue;
  15678. if (auto *USD = dyn_cast<UsingShadowDecl>(D))
  15679. Underlying = USD->getTargetDecl();
  15680. }
  15681. Lookups.emplace_back();
  15682. Lookups.back().addDecl(Underlying);
  15683. }
  15684. }
  15685. }
  15686. static ExprResult
  15687. buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
  15688. Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
  15689. const DeclarationNameInfo &ReductionId, QualType Ty,
  15690. CXXCastPath &BasePath, Expr *UnresolvedReduction) {
  15691. if (ReductionIdScopeSpec.isInvalid())
  15692. return ExprError();
  15693. SmallVector<UnresolvedSet<8>, 4> Lookups;
  15694. if (S) {
  15695. LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
  15696. Lookup.suppressDiagnostics();
  15697. while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
  15698. NamedDecl *D = Lookup.getRepresentativeDecl();
  15699. do {
  15700. S = S->getParent();
  15701. } while (S && !S->isDeclScope(D));
  15702. if (S)
  15703. S = S->getParent();
  15704. Lookups.emplace_back();
  15705. Lookups.back().append(Lookup.begin(), Lookup.end());
  15706. Lookup.clear();
  15707. }
  15708. } else if (auto *ULE =
  15709. cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
  15710. Lookups.push_back(UnresolvedSet<8>());
  15711. Decl *PrevD = nullptr;
  15712. for (NamedDecl *D : ULE->decls()) {
  15713. if (D == PrevD)
  15714. Lookups.push_back(UnresolvedSet<8>());
  15715. else if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(D))
  15716. Lookups.back().addDecl(DRD);
  15717. PrevD = D;
  15718. }
  15719. }
  15720. if (SemaRef.CurContext->isDependentContext() || Ty->isDependentType() ||
  15721. Ty->isInstantiationDependentType() ||
  15722. Ty->containsUnexpandedParameterPack() ||
  15723. filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) {
  15724. return !D->isInvalidDecl() &&
  15725. (D->getType()->isDependentType() ||
  15726. D->getType()->isInstantiationDependentType() ||
  15727. D->getType()->containsUnexpandedParameterPack());
  15728. })) {
  15729. UnresolvedSet<8> ResSet;
  15730. for (const UnresolvedSet<8> &Set : Lookups) {
  15731. if (Set.empty())
  15732. continue;
  15733. ResSet.append(Set.begin(), Set.end());
  15734. // The last item marks the end of all declarations at the specified scope.
  15735. ResSet.addDecl(Set[Set.size() - 1]);
  15736. }
  15737. return UnresolvedLookupExpr::Create(
  15738. SemaRef.Context, /*NamingClass=*/nullptr,
  15739. ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
  15740. /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
  15741. }
  15742. // Lookup inside the classes.
  15743. // C++ [over.match.oper]p3:
  15744. // For a unary operator @ with an operand of a type whose
  15745. // cv-unqualified version is T1, and for a binary operator @ with
  15746. // a left operand of a type whose cv-unqualified version is T1 and
  15747. // a right operand of a type whose cv-unqualified version is T2,
  15748. // three sets of candidate functions, designated member
  15749. // candidates, non-member candidates and built-in candidates, are
  15750. // constructed as follows:
  15751. // -- If T1 is a complete class type or a class currently being
  15752. // defined, the set of member candidates is the result of the
  15753. // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
  15754. // the set of member candidates is empty.
  15755. LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
  15756. Lookup.suppressDiagnostics();
  15757. if (const auto *TyRec = Ty->getAs<RecordType>()) {
  15758. // Complete the type if it can be completed.
  15759. // If the type is neither complete nor being defined, bail out now.
  15760. if (SemaRef.isCompleteType(Loc, Ty) || TyRec->isBeingDefined() ||
  15761. TyRec->getDecl()->getDefinition()) {
  15762. Lookup.clear();
  15763. SemaRef.LookupQualifiedName(Lookup, TyRec->getDecl());
  15764. if (Lookup.empty()) {
  15765. Lookups.emplace_back();
  15766. Lookups.back().append(Lookup.begin(), Lookup.end());
  15767. }
  15768. }
  15769. }
  15770. // Perform ADL.
  15771. if (SemaRef.getLangOpts().CPlusPlus)
  15772. argumentDependentLookup(SemaRef, ReductionId, Loc, Ty, Lookups);
  15773. if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
  15774. Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
  15775. if (!D->isInvalidDecl() &&
  15776. SemaRef.Context.hasSameType(D->getType(), Ty))
  15777. return D;
  15778. return nullptr;
  15779. }))
  15780. return SemaRef.BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(),
  15781. VK_LValue, Loc);
  15782. if (SemaRef.getLangOpts().CPlusPlus) {
  15783. if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
  15784. Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
  15785. if (!D->isInvalidDecl() &&
  15786. SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
  15787. !Ty.isMoreQualifiedThan(D->getType()))
  15788. return D;
  15789. return nullptr;
  15790. })) {
  15791. CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
  15792. /*DetectVirtual=*/false);
  15793. if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
  15794. if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
  15795. VD->getType().getUnqualifiedType()))) {
  15796. if (SemaRef.CheckBaseClassAccess(
  15797. Loc, VD->getType(), Ty, Paths.front(),
  15798. /*DiagID=*/0) != Sema::AR_inaccessible) {
  15799. SemaRef.BuildBasePathArray(Paths, BasePath);
  15800. return SemaRef.BuildDeclRefExpr(
  15801. VD, VD->getType().getNonReferenceType(), VK_LValue, Loc);
  15802. }
  15803. }
  15804. }
  15805. }
  15806. }
  15807. if (ReductionIdScopeSpec.isSet()) {
  15808. SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier)
  15809. << Ty << Range;
  15810. return ExprError();
  15811. }
  15812. return ExprEmpty();
  15813. }
  15814. namespace {
  15815. /// Data for the reduction-based clauses.
  15816. struct ReductionData {
  15817. /// List of original reduction items.
  15818. SmallVector<Expr *, 8> Vars;
  15819. /// List of private copies of the reduction items.
  15820. SmallVector<Expr *, 8> Privates;
  15821. /// LHS expressions for the reduction_op expressions.
  15822. SmallVector<Expr *, 8> LHSs;
  15823. /// RHS expressions for the reduction_op expressions.
  15824. SmallVector<Expr *, 8> RHSs;
  15825. /// Reduction operation expression.
  15826. SmallVector<Expr *, 8> ReductionOps;
  15827. /// inscan copy operation expressions.
  15828. SmallVector<Expr *, 8> InscanCopyOps;
  15829. /// inscan copy temp array expressions for prefix sums.
  15830. SmallVector<Expr *, 8> InscanCopyArrayTemps;
  15831. /// inscan copy temp array element expressions for prefix sums.
  15832. SmallVector<Expr *, 8> InscanCopyArrayElems;
  15833. /// Taskgroup descriptors for the corresponding reduction items in
  15834. /// in_reduction clauses.
  15835. SmallVector<Expr *, 8> TaskgroupDescriptors;
  15836. /// List of captures for clause.
  15837. SmallVector<Decl *, 4> ExprCaptures;
  15838. /// List of postupdate expressions.
  15839. SmallVector<Expr *, 4> ExprPostUpdates;
  15840. /// Reduction modifier.
  15841. unsigned RedModifier = 0;
  15842. ReductionData() = delete;
  15843. /// Reserves required memory for the reduction data.
  15844. ReductionData(unsigned Size, unsigned Modifier = 0) : RedModifier(Modifier) {
  15845. Vars.reserve(Size);
  15846. Privates.reserve(Size);
  15847. LHSs.reserve(Size);
  15848. RHSs.reserve(Size);
  15849. ReductionOps.reserve(Size);
  15850. if (RedModifier == OMPC_REDUCTION_inscan) {
  15851. InscanCopyOps.reserve(Size);
  15852. InscanCopyArrayTemps.reserve(Size);
  15853. InscanCopyArrayElems.reserve(Size);
  15854. }
  15855. TaskgroupDescriptors.reserve(Size);
  15856. ExprCaptures.reserve(Size);
  15857. ExprPostUpdates.reserve(Size);
  15858. }
  15859. /// Stores reduction item and reduction operation only (required for dependent
  15860. /// reduction item).
  15861. void push(Expr *Item, Expr *ReductionOp) {
  15862. Vars.emplace_back(Item);
  15863. Privates.emplace_back(nullptr);
  15864. LHSs.emplace_back(nullptr);
  15865. RHSs.emplace_back(nullptr);
  15866. ReductionOps.emplace_back(ReductionOp);
  15867. TaskgroupDescriptors.emplace_back(nullptr);
  15868. if (RedModifier == OMPC_REDUCTION_inscan) {
  15869. InscanCopyOps.push_back(nullptr);
  15870. InscanCopyArrayTemps.push_back(nullptr);
  15871. InscanCopyArrayElems.push_back(nullptr);
  15872. }
  15873. }
  15874. /// Stores reduction data.
  15875. void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS, Expr *ReductionOp,
  15876. Expr *TaskgroupDescriptor, Expr *CopyOp, Expr *CopyArrayTemp,
  15877. Expr *CopyArrayElem) {
  15878. Vars.emplace_back(Item);
  15879. Privates.emplace_back(Private);
  15880. LHSs.emplace_back(LHS);
  15881. RHSs.emplace_back(RHS);
  15882. ReductionOps.emplace_back(ReductionOp);
  15883. TaskgroupDescriptors.emplace_back(TaskgroupDescriptor);
  15884. if (RedModifier == OMPC_REDUCTION_inscan) {
  15885. InscanCopyOps.push_back(CopyOp);
  15886. InscanCopyArrayTemps.push_back(CopyArrayTemp);
  15887. InscanCopyArrayElems.push_back(CopyArrayElem);
  15888. } else {
  15889. assert(CopyOp == nullptr && CopyArrayTemp == nullptr &&
  15890. CopyArrayElem == nullptr &&
  15891. "Copy operation must be used for inscan reductions only.");
  15892. }
  15893. }
  15894. };
  15895. } // namespace
  15896. static bool checkOMPArraySectionConstantForReduction(
  15897. ASTContext &Context, const OMPArraySectionExpr *OASE, bool &SingleElement,
  15898. SmallVectorImpl<llvm::APSInt> &ArraySizes) {
  15899. const Expr *Length = OASE->getLength();
  15900. if (Length == nullptr) {
  15901. // For array sections of the form [1:] or [:], we would need to analyze
  15902. // the lower bound...
  15903. if (OASE->getColonLocFirst().isValid())
  15904. return false;
  15905. // This is an array subscript which has implicit length 1!
  15906. SingleElement = true;
  15907. ArraySizes.push_back(llvm::APSInt::get(1));
  15908. } else {
  15909. Expr::EvalResult Result;
  15910. if (!Length->EvaluateAsInt(Result, Context))
  15911. return false;
  15912. llvm::APSInt ConstantLengthValue = Result.Val.getInt();
  15913. SingleElement = (ConstantLengthValue.getSExtValue() == 1);
  15914. ArraySizes.push_back(ConstantLengthValue);
  15915. }
  15916. // Get the base of this array section and walk up from there.
  15917. const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
  15918. // We require length = 1 for all array sections except the right-most to
  15919. // guarantee that the memory region is contiguous and has no holes in it.
  15920. while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) {
  15921. Length = TempOASE->getLength();
  15922. if (Length == nullptr) {
  15923. // For array sections of the form [1:] or [:], we would need to analyze
  15924. // the lower bound...
  15925. if (OASE->getColonLocFirst().isValid())
  15926. return false;
  15927. // This is an array subscript which has implicit length 1!
  15928. ArraySizes.push_back(llvm::APSInt::get(1));
  15929. } else {
  15930. Expr::EvalResult Result;
  15931. if (!Length->EvaluateAsInt(Result, Context))
  15932. return false;
  15933. llvm::APSInt ConstantLengthValue = Result.Val.getInt();
  15934. if (ConstantLengthValue.getSExtValue() != 1)
  15935. return false;
  15936. ArraySizes.push_back(ConstantLengthValue);
  15937. }
  15938. Base = TempOASE->getBase()->IgnoreParenImpCasts();
  15939. }
  15940. // If we have a single element, we don't need to add the implicit lengths.
  15941. if (!SingleElement) {
  15942. while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) {
  15943. // Has implicit length 1!
  15944. ArraySizes.push_back(llvm::APSInt::get(1));
  15945. Base = TempASE->getBase()->IgnoreParenImpCasts();
  15946. }
  15947. }
  15948. // This array section can be privatized as a single value or as a constant
  15949. // sized array.
  15950. return true;
  15951. }
  15952. static BinaryOperatorKind
  15953. getRelatedCompoundReductionOp(BinaryOperatorKind BOK) {
  15954. if (BOK == BO_Add)
  15955. return BO_AddAssign;
  15956. if (BOK == BO_Mul)
  15957. return BO_MulAssign;
  15958. if (BOK == BO_And)
  15959. return BO_AndAssign;
  15960. if (BOK == BO_Or)
  15961. return BO_OrAssign;
  15962. if (BOK == BO_Xor)
  15963. return BO_XorAssign;
  15964. return BOK;
  15965. }
  15966. static bool actOnOMPReductionKindClause(
  15967. Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind,
  15968. ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
  15969. SourceLocation ColonLoc, SourceLocation EndLoc,
  15970. CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
  15971. ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) {
  15972. DeclarationName DN = ReductionId.getName();
  15973. OverloadedOperatorKind OOK = DN.getCXXOverloadedOperator();
  15974. BinaryOperatorKind BOK = BO_Comma;
  15975. ASTContext &Context = S.Context;
  15976. // OpenMP [2.14.3.6, reduction clause]
  15977. // C
  15978. // reduction-identifier is either an identifier or one of the following
  15979. // operators: +, -, *, &, |, ^, && and ||
  15980. // C++
  15981. // reduction-identifier is either an id-expression or one of the following
  15982. // operators: +, -, *, &, |, ^, && and ||
  15983. switch (OOK) {
  15984. case OO_Plus:
  15985. case OO_Minus:
  15986. BOK = BO_Add;
  15987. break;
  15988. case OO_Star:
  15989. BOK = BO_Mul;
  15990. break;
  15991. case OO_Amp:
  15992. BOK = BO_And;
  15993. break;
  15994. case OO_Pipe:
  15995. BOK = BO_Or;
  15996. break;
  15997. case OO_Caret:
  15998. BOK = BO_Xor;
  15999. break;
  16000. case OO_AmpAmp:
  16001. BOK = BO_LAnd;
  16002. break;
  16003. case OO_PipePipe:
  16004. BOK = BO_LOr;
  16005. break;
  16006. case OO_New:
  16007. case OO_Delete:
  16008. case OO_Array_New:
  16009. case OO_Array_Delete:
  16010. case OO_Slash:
  16011. case OO_Percent:
  16012. case OO_Tilde:
  16013. case OO_Exclaim:
  16014. case OO_Equal:
  16015. case OO_Less:
  16016. case OO_Greater:
  16017. case OO_LessEqual:
  16018. case OO_GreaterEqual:
  16019. case OO_PlusEqual:
  16020. case OO_MinusEqual:
  16021. case OO_StarEqual:
  16022. case OO_SlashEqual:
  16023. case OO_PercentEqual:
  16024. case OO_CaretEqual:
  16025. case OO_AmpEqual:
  16026. case OO_PipeEqual:
  16027. case OO_LessLess:
  16028. case OO_GreaterGreater:
  16029. case OO_LessLessEqual:
  16030. case OO_GreaterGreaterEqual:
  16031. case OO_EqualEqual:
  16032. case OO_ExclaimEqual:
  16033. case OO_Spaceship:
  16034. case OO_PlusPlus:
  16035. case OO_MinusMinus:
  16036. case OO_Comma:
  16037. case OO_ArrowStar:
  16038. case OO_Arrow:
  16039. case OO_Call:
  16040. case OO_Subscript:
  16041. case OO_Conditional:
  16042. case OO_Coawait:
  16043. case NUM_OVERLOADED_OPERATORS:
  16044. llvm_unreachable("Unexpected reduction identifier");
  16045. case OO_None:
  16046. if (IdentifierInfo *II = DN.getAsIdentifierInfo()) {
  16047. if (II->isStr("max"))
  16048. BOK = BO_GT;
  16049. else if (II->isStr("min"))
  16050. BOK = BO_LT;
  16051. }
  16052. break;
  16053. }
  16054. SourceRange ReductionIdRange;
  16055. if (ReductionIdScopeSpec.isValid())
  16056. ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
  16057. else
  16058. ReductionIdRange.setBegin(ReductionId.getBeginLoc());
  16059. ReductionIdRange.setEnd(ReductionId.getEndLoc());
  16060. auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
  16061. bool FirstIter = true;
  16062. for (Expr *RefExpr : VarList) {
  16063. assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
  16064. // OpenMP [2.1, C/C++]
  16065. // A list item is a variable or array section, subject to the restrictions
  16066. // specified in Section 2.4 on page 42 and in each of the sections
  16067. // describing clauses and directives for which a list appears.
  16068. // OpenMP [2.14.3.3, Restrictions, p.1]
  16069. // A variable that is part of another variable (as an array or
  16070. // structure element) cannot appear in a private clause.
  16071. if (!FirstIter && IR != ER)
  16072. ++IR;
  16073. FirstIter = false;
  16074. SourceLocation ELoc;
  16075. SourceRange ERange;
  16076. Expr *SimpleRefExpr = RefExpr;
  16077. auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
  16078. /*AllowArraySection=*/true);
  16079. if (Res.second) {
  16080. // Try to find 'declare reduction' corresponding construct before using
  16081. // builtin/overloaded operators.
  16082. QualType Type = Context.DependentTy;
  16083. CXXCastPath BasePath;
  16084. ExprResult DeclareReductionRef = buildDeclareReductionRef(
  16085. S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
  16086. ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
  16087. Expr *ReductionOp = nullptr;
  16088. if (S.CurContext->isDependentContext() &&
  16089. (DeclareReductionRef.isUnset() ||
  16090. isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
  16091. ReductionOp = DeclareReductionRef.get();
  16092. // It will be analyzed later.
  16093. RD.push(RefExpr, ReductionOp);
  16094. }
  16095. ValueDecl *D = Res.first;
  16096. if (!D)
  16097. continue;
  16098. Expr *TaskgroupDescriptor = nullptr;
  16099. QualType Type;
  16100. auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
  16101. auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
  16102. if (ASE) {
  16103. Type = ASE->getType().getNonReferenceType();
  16104. } else if (OASE) {
  16105. QualType BaseType =
  16106. OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
  16107. if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
  16108. Type = ATy->getElementType();
  16109. else
  16110. Type = BaseType->getPointeeType();
  16111. Type = Type.getNonReferenceType();
  16112. } else {
  16113. Type = Context.getBaseElementType(D->getType().getNonReferenceType());
  16114. }
  16115. auto *VD = dyn_cast<VarDecl>(D);
  16116. // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
  16117. // A variable that appears in a private clause must not have an incomplete
  16118. // type or a reference type.
  16119. if (S.RequireCompleteType(ELoc, D->getType(),
  16120. diag::err_omp_reduction_incomplete_type))
  16121. continue;
  16122. // OpenMP [2.14.3.6, reduction clause, Restrictions]
  16123. // A list item that appears in a reduction clause must not be
  16124. // const-qualified.
  16125. if (rejectConstNotMutableType(S, D, Type, ClauseKind, ELoc,
  16126. /*AcceptIfMutable*/ false, ASE || OASE))
  16127. continue;
  16128. OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective();
  16129. // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
  16130. // If a list-item is a reference type then it must bind to the same object
  16131. // for all threads of the team.
  16132. if (!ASE && !OASE) {
  16133. if (VD) {
  16134. VarDecl *VDDef = VD->getDefinition();
  16135. if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
  16136. DSARefChecker Check(Stack);
  16137. if (Check.Visit(VDDef->getInit())) {
  16138. S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg)
  16139. << getOpenMPClauseName(ClauseKind) << ERange;
  16140. S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
  16141. continue;
  16142. }
  16143. }
  16144. }
  16145. // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
  16146. // in a Construct]
  16147. // Variables with the predetermined data-sharing attributes may not be
  16148. // listed in data-sharing attributes clauses, except for the cases
  16149. // listed below. For these exceptions only, listing a predetermined
  16150. // variable in a data-sharing attribute clause is allowed and overrides
  16151. // the variable's predetermined data-sharing attributes.
  16152. // OpenMP [2.14.3.6, Restrictions, p.3]
  16153. // Any number of reduction clauses can be specified on the directive,
  16154. // but a list item can appear only once in the reduction clauses for that
  16155. // directive.
  16156. DSAStackTy::DSAVarData DVar = Stack->getTopDSA(D, /*FromParent=*/false);
  16157. if (DVar.CKind == OMPC_reduction) {
  16158. S.Diag(ELoc, diag::err_omp_once_referenced)
  16159. << getOpenMPClauseName(ClauseKind);
  16160. if (DVar.RefExpr)
  16161. S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
  16162. continue;
  16163. }
  16164. if (DVar.CKind != OMPC_unknown) {
  16165. S.Diag(ELoc, diag::err_omp_wrong_dsa)
  16166. << getOpenMPClauseName(DVar.CKind)
  16167. << getOpenMPClauseName(OMPC_reduction);
  16168. reportOriginalDsa(S, Stack, D, DVar);
  16169. continue;
  16170. }
  16171. // OpenMP [2.14.3.6, Restrictions, p.1]
  16172. // A list item that appears in a reduction clause of a worksharing
  16173. // construct must be shared in the parallel regions to which any of the
  16174. // worksharing regions arising from the worksharing construct bind.
  16175. if (isOpenMPWorksharingDirective(CurrDir) &&
  16176. !isOpenMPParallelDirective(CurrDir) &&
  16177. !isOpenMPTeamsDirective(CurrDir)) {
  16178. DVar = Stack->getImplicitDSA(D, true);
  16179. if (DVar.CKind != OMPC_shared) {
  16180. S.Diag(ELoc, diag::err_omp_required_access)
  16181. << getOpenMPClauseName(OMPC_reduction)
  16182. << getOpenMPClauseName(OMPC_shared);
  16183. reportOriginalDsa(S, Stack, D, DVar);
  16184. continue;
  16185. }
  16186. }
  16187. } else {
  16188. // Threadprivates cannot be shared between threads, so dignose if the base
  16189. // is a threadprivate variable.
  16190. DSAStackTy::DSAVarData DVar = Stack->getTopDSA(D, /*FromParent=*/false);
  16191. if (DVar.CKind == OMPC_threadprivate) {
  16192. S.Diag(ELoc, diag::err_omp_wrong_dsa)
  16193. << getOpenMPClauseName(DVar.CKind)
  16194. << getOpenMPClauseName(OMPC_reduction);
  16195. reportOriginalDsa(S, Stack, D, DVar);
  16196. continue;
  16197. }
  16198. }
  16199. // Try to find 'declare reduction' corresponding construct before using
  16200. // builtin/overloaded operators.
  16201. CXXCastPath BasePath;
  16202. ExprResult DeclareReductionRef = buildDeclareReductionRef(
  16203. S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
  16204. ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
  16205. if (DeclareReductionRef.isInvalid())
  16206. continue;
  16207. if (S.CurContext->isDependentContext() &&
  16208. (DeclareReductionRef.isUnset() ||
  16209. isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
  16210. RD.push(RefExpr, DeclareReductionRef.get());
  16211. continue;
  16212. }
  16213. if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
  16214. // Not allowed reduction identifier is found.
  16215. S.Diag(ReductionId.getBeginLoc(),
  16216. diag::err_omp_unknown_reduction_identifier)
  16217. << Type << ReductionIdRange;
  16218. continue;
  16219. }
  16220. // OpenMP [2.14.3.6, reduction clause, Restrictions]
  16221. // The type of a list item that appears in a reduction clause must be valid
  16222. // for the reduction-identifier. For a max or min reduction in C, the type
  16223. // of the list item must be an allowed arithmetic data type: char, int,
  16224. // float, double, or _Bool, possibly modified with long, short, signed, or
  16225. // unsigned. For a max or min reduction in C++, the type of the list item
  16226. // must be an allowed arithmetic data type: char, wchar_t, int, float,
  16227. // double, or bool, possibly modified with long, short, signed, or unsigned.
  16228. if (DeclareReductionRef.isUnset()) {
  16229. if ((BOK == BO_GT || BOK == BO_LT) &&
  16230. !(Type->isScalarType() ||
  16231. (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
  16232. S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
  16233. << getOpenMPClauseName(ClauseKind) << S.getLangOpts().CPlusPlus;
  16234. if (!ASE && !OASE) {
  16235. bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
  16236. VarDecl::DeclarationOnly;
  16237. S.Diag(D->getLocation(),
  16238. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  16239. << D;
  16240. }
  16241. continue;
  16242. }
  16243. if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
  16244. !S.getLangOpts().CPlusPlus && Type->isFloatingType()) {
  16245. S.Diag(ELoc, diag::err_omp_clause_floating_type_arg)
  16246. << getOpenMPClauseName(ClauseKind);
  16247. if (!ASE && !OASE) {
  16248. bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
  16249. VarDecl::DeclarationOnly;
  16250. S.Diag(D->getLocation(),
  16251. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  16252. << D;
  16253. }
  16254. continue;
  16255. }
  16256. }
  16257. Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
  16258. VarDecl *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs",
  16259. D->hasAttrs() ? &D->getAttrs() : nullptr);
  16260. VarDecl *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(),
  16261. D->hasAttrs() ? &D->getAttrs() : nullptr);
  16262. QualType PrivateTy = Type;
  16263. // Try if we can determine constant lengths for all array sections and avoid
  16264. // the VLA.
  16265. bool ConstantLengthOASE = false;
  16266. if (OASE) {
  16267. bool SingleElement;
  16268. llvm::SmallVector<llvm::APSInt, 4> ArraySizes;
  16269. ConstantLengthOASE = checkOMPArraySectionConstantForReduction(
  16270. Context, OASE, SingleElement, ArraySizes);
  16271. // If we don't have a single element, we must emit a constant array type.
  16272. if (ConstantLengthOASE && !SingleElement) {
  16273. for (llvm::APSInt &Size : ArraySizes)
  16274. PrivateTy = Context.getConstantArrayType(PrivateTy, Size, nullptr,
  16275. ArrayType::Normal,
  16276. /*IndexTypeQuals=*/0);
  16277. }
  16278. }
  16279. if ((OASE && !ConstantLengthOASE) ||
  16280. (!OASE && !ASE &&
  16281. D->getType().getNonReferenceType()->isVariablyModifiedType())) {
  16282. if (!Context.getTargetInfo().isVLASupported()) {
  16283. if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective())) {
  16284. S.Diag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
  16285. S.Diag(ELoc, diag::note_vla_unsupported);
  16286. continue;
  16287. } else {
  16288. S.targetDiag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
  16289. S.targetDiag(ELoc, diag::note_vla_unsupported);
  16290. }
  16291. }
  16292. // For arrays/array sections only:
  16293. // Create pseudo array type for private copy. The size for this array will
  16294. // be generated during codegen.
  16295. // For array subscripts or single variables Private Ty is the same as Type
  16296. // (type of the variable or single array element).
  16297. PrivateTy = Context.getVariableArrayType(
  16298. Type,
  16299. new (Context)
  16300. OpaqueValueExpr(ELoc, Context.getSizeType(), VK_PRValue),
  16301. ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
  16302. } else if (!ASE && !OASE &&
  16303. Context.getAsArrayType(D->getType().getNonReferenceType())) {
  16304. PrivateTy = D->getType().getNonReferenceType();
  16305. }
  16306. // Private copy.
  16307. VarDecl *PrivateVD =
  16308. buildVarDecl(S, ELoc, PrivateTy, D->getName(),
  16309. D->hasAttrs() ? &D->getAttrs() : nullptr,
  16310. VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
  16311. // Add initializer for private variable.
  16312. Expr *Init = nullptr;
  16313. DeclRefExpr *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc);
  16314. DeclRefExpr *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc);
  16315. if (DeclareReductionRef.isUsable()) {
  16316. auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
  16317. auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
  16318. if (DRD->getInitializer()) {
  16319. Init = DRDRef;
  16320. RHSVD->setInit(DRDRef);
  16321. RHSVD->setInitStyle(VarDecl::CallInit);
  16322. }
  16323. } else {
  16324. switch (BOK) {
  16325. case BO_Add:
  16326. case BO_Xor:
  16327. case BO_Or:
  16328. case BO_LOr:
  16329. // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
  16330. if (Type->isScalarType() || Type->isAnyComplexType())
  16331. Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get();
  16332. break;
  16333. case BO_Mul:
  16334. case BO_LAnd:
  16335. if (Type->isScalarType() || Type->isAnyComplexType()) {
  16336. // '*' and '&&' reduction ops - initializer is '1'.
  16337. Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get();
  16338. }
  16339. break;
  16340. case BO_And: {
  16341. // '&' reduction op - initializer is '~0'.
  16342. QualType OrigType = Type;
  16343. if (auto *ComplexTy = OrigType->getAs<ComplexType>())
  16344. Type = ComplexTy->getElementType();
  16345. if (Type->isRealFloatingType()) {
  16346. llvm::APFloat InitValue = llvm::APFloat::getAllOnesValue(
  16347. Context.getFloatTypeSemantics(Type));
  16348. Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
  16349. Type, ELoc);
  16350. } else if (Type->isScalarType()) {
  16351. uint64_t Size = Context.getTypeSize(Type);
  16352. QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
  16353. llvm::APInt InitValue = llvm::APInt::getAllOnes(Size);
  16354. Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
  16355. }
  16356. if (Init && OrigType->isAnyComplexType()) {
  16357. // Init = 0xFFFF + 0xFFFFi;
  16358. auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
  16359. Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
  16360. }
  16361. Type = OrigType;
  16362. break;
  16363. }
  16364. case BO_LT:
  16365. case BO_GT: {
  16366. // 'min' reduction op - initializer is 'Largest representable number in
  16367. // the reduction list item type'.
  16368. // 'max' reduction op - initializer is 'Least representable number in
  16369. // the reduction list item type'.
  16370. if (Type->isIntegerType() || Type->isPointerType()) {
  16371. bool IsSigned = Type->hasSignedIntegerRepresentation();
  16372. uint64_t Size = Context.getTypeSize(Type);
  16373. QualType IntTy =
  16374. Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
  16375. llvm::APInt InitValue =
  16376. (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
  16377. : llvm::APInt::getMinValue(Size)
  16378. : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
  16379. : llvm::APInt::getMaxValue(Size);
  16380. Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
  16381. if (Type->isPointerType()) {
  16382. // Cast to pointer type.
  16383. ExprResult CastExpr = S.BuildCStyleCastExpr(
  16384. ELoc, Context.getTrivialTypeSourceInfo(Type, ELoc), ELoc, Init);
  16385. if (CastExpr.isInvalid())
  16386. continue;
  16387. Init = CastExpr.get();
  16388. }
  16389. } else if (Type->isRealFloatingType()) {
  16390. llvm::APFloat InitValue = llvm::APFloat::getLargest(
  16391. Context.getFloatTypeSemantics(Type), BOK != BO_LT);
  16392. Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
  16393. Type, ELoc);
  16394. }
  16395. break;
  16396. }
  16397. case BO_PtrMemD:
  16398. case BO_PtrMemI:
  16399. case BO_MulAssign:
  16400. case BO_Div:
  16401. case BO_Rem:
  16402. case BO_Sub:
  16403. case BO_Shl:
  16404. case BO_Shr:
  16405. case BO_LE:
  16406. case BO_GE:
  16407. case BO_EQ:
  16408. case BO_NE:
  16409. case BO_Cmp:
  16410. case BO_AndAssign:
  16411. case BO_XorAssign:
  16412. case BO_OrAssign:
  16413. case BO_Assign:
  16414. case BO_AddAssign:
  16415. case BO_SubAssign:
  16416. case BO_DivAssign:
  16417. case BO_RemAssign:
  16418. case BO_ShlAssign:
  16419. case BO_ShrAssign:
  16420. case BO_Comma:
  16421. llvm_unreachable("Unexpected reduction operation");
  16422. }
  16423. }
  16424. if (Init && DeclareReductionRef.isUnset()) {
  16425. S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false);
  16426. // Store initializer for single element in private copy. Will be used
  16427. // during codegen.
  16428. PrivateVD->setInit(RHSVD->getInit());
  16429. PrivateVD->setInitStyle(RHSVD->getInitStyle());
  16430. } else if (!Init) {
  16431. S.ActOnUninitializedDecl(RHSVD);
  16432. // Store initializer for single element in private copy. Will be used
  16433. // during codegen.
  16434. PrivateVD->setInit(RHSVD->getInit());
  16435. PrivateVD->setInitStyle(RHSVD->getInitStyle());
  16436. }
  16437. if (RHSVD->isInvalidDecl())
  16438. continue;
  16439. if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) {
  16440. S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible)
  16441. << Type << ReductionIdRange;
  16442. bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
  16443. VarDecl::DeclarationOnly;
  16444. S.Diag(D->getLocation(),
  16445. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  16446. << D;
  16447. continue;
  16448. }
  16449. DeclRefExpr *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc);
  16450. ExprResult ReductionOp;
  16451. if (DeclareReductionRef.isUsable()) {
  16452. QualType RedTy = DeclareReductionRef.get()->getType();
  16453. QualType PtrRedTy = Context.getPointerType(RedTy);
  16454. ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
  16455. ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
  16456. if (!BasePath.empty()) {
  16457. LHS = S.DefaultLvalueConversion(LHS.get());
  16458. RHS = S.DefaultLvalueConversion(RHS.get());
  16459. LHS = ImplicitCastExpr::Create(
  16460. Context, PtrRedTy, CK_UncheckedDerivedToBase, LHS.get(), &BasePath,
  16461. LHS.get()->getValueKind(), FPOptionsOverride());
  16462. RHS = ImplicitCastExpr::Create(
  16463. Context, PtrRedTy, CK_UncheckedDerivedToBase, RHS.get(), &BasePath,
  16464. RHS.get()->getValueKind(), FPOptionsOverride());
  16465. }
  16466. FunctionProtoType::ExtProtoInfo EPI;
  16467. QualType Params[] = {PtrRedTy, PtrRedTy};
  16468. QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
  16469. auto *OVE = new (Context) OpaqueValueExpr(
  16470. ELoc, Context.getPointerType(FnTy), VK_PRValue, OK_Ordinary,
  16471. S.DefaultLvalueConversion(DeclareReductionRef.get()).get());
  16472. Expr *Args[] = {LHS.get(), RHS.get()};
  16473. ReductionOp =
  16474. CallExpr::Create(Context, OVE, Args, Context.VoidTy, VK_PRValue, ELoc,
  16475. S.CurFPFeatureOverrides());
  16476. } else {
  16477. BinaryOperatorKind CombBOK = getRelatedCompoundReductionOp(BOK);
  16478. if (Type->isRecordType() && CombBOK != BOK) {
  16479. Sema::TentativeAnalysisScope Trap(S);
  16480. ReductionOp =
  16481. S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
  16482. CombBOK, LHSDRE, RHSDRE);
  16483. }
  16484. if (!ReductionOp.isUsable()) {
  16485. ReductionOp =
  16486. S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(), BOK,
  16487. LHSDRE, RHSDRE);
  16488. if (ReductionOp.isUsable()) {
  16489. if (BOK != BO_LT && BOK != BO_GT) {
  16490. ReductionOp =
  16491. S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
  16492. BO_Assign, LHSDRE, ReductionOp.get());
  16493. } else {
  16494. auto *ConditionalOp = new (Context)
  16495. ConditionalOperator(ReductionOp.get(), ELoc, LHSDRE, ELoc,
  16496. RHSDRE, Type, VK_LValue, OK_Ordinary);
  16497. ReductionOp =
  16498. S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
  16499. BO_Assign, LHSDRE, ConditionalOp);
  16500. }
  16501. }
  16502. }
  16503. if (ReductionOp.isUsable())
  16504. ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get(),
  16505. /*DiscardedValue*/ false);
  16506. if (!ReductionOp.isUsable())
  16507. continue;
  16508. }
  16509. // Add copy operations for inscan reductions.
  16510. // LHS = RHS;
  16511. ExprResult CopyOpRes, TempArrayRes, TempArrayElem;
  16512. if (ClauseKind == OMPC_reduction &&
  16513. RD.RedModifier == OMPC_REDUCTION_inscan) {
  16514. ExprResult RHS = S.DefaultLvalueConversion(RHSDRE);
  16515. CopyOpRes = S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, LHSDRE,
  16516. RHS.get());
  16517. if (!CopyOpRes.isUsable())
  16518. continue;
  16519. CopyOpRes =
  16520. S.ActOnFinishFullExpr(CopyOpRes.get(), /*DiscardedValue=*/true);
  16521. if (!CopyOpRes.isUsable())
  16522. continue;
  16523. // For simd directive and simd-based directives in simd mode no need to
  16524. // construct temp array, need just a single temp element.
  16525. if (Stack->getCurrentDirective() == OMPD_simd ||
  16526. (S.getLangOpts().OpenMPSimd &&
  16527. isOpenMPSimdDirective(Stack->getCurrentDirective()))) {
  16528. VarDecl *TempArrayVD =
  16529. buildVarDecl(S, ELoc, PrivateTy, D->getName(),
  16530. D->hasAttrs() ? &D->getAttrs() : nullptr);
  16531. // Add a constructor to the temp decl.
  16532. S.ActOnUninitializedDecl(TempArrayVD);
  16533. TempArrayRes = buildDeclRefExpr(S, TempArrayVD, PrivateTy, ELoc);
  16534. } else {
  16535. // Build temp array for prefix sum.
  16536. auto *Dim = new (S.Context)
  16537. OpaqueValueExpr(ELoc, S.Context.getSizeType(), VK_PRValue);
  16538. QualType ArrayTy =
  16539. S.Context.getVariableArrayType(PrivateTy, Dim, ArrayType::Normal,
  16540. /*IndexTypeQuals=*/0, {ELoc, ELoc});
  16541. VarDecl *TempArrayVD =
  16542. buildVarDecl(S, ELoc, ArrayTy, D->getName(),
  16543. D->hasAttrs() ? &D->getAttrs() : nullptr);
  16544. // Add a constructor to the temp decl.
  16545. S.ActOnUninitializedDecl(TempArrayVD);
  16546. TempArrayRes = buildDeclRefExpr(S, TempArrayVD, ArrayTy, ELoc);
  16547. TempArrayElem =
  16548. S.DefaultFunctionArrayLvalueConversion(TempArrayRes.get());
  16549. auto *Idx = new (S.Context)
  16550. OpaqueValueExpr(ELoc, S.Context.getSizeType(), VK_PRValue);
  16551. TempArrayElem = S.CreateBuiltinArraySubscriptExpr(TempArrayElem.get(),
  16552. ELoc, Idx, ELoc);
  16553. }
  16554. }
  16555. // OpenMP [2.15.4.6, Restrictions, p.2]
  16556. // A list item that appears in an in_reduction clause of a task construct
  16557. // must appear in a task_reduction clause of a construct associated with a
  16558. // taskgroup region that includes the participating task in its taskgroup
  16559. // set. The construct associated with the innermost region that meets this
  16560. // condition must specify the same reduction-identifier as the in_reduction
  16561. // clause.
  16562. if (ClauseKind == OMPC_in_reduction) {
  16563. SourceRange ParentSR;
  16564. BinaryOperatorKind ParentBOK;
  16565. const Expr *ParentReductionOp = nullptr;
  16566. Expr *ParentBOKTD = nullptr, *ParentReductionOpTD = nullptr;
  16567. DSAStackTy::DSAVarData ParentBOKDSA =
  16568. Stack->getTopMostTaskgroupReductionData(D, ParentSR, ParentBOK,
  16569. ParentBOKTD);
  16570. DSAStackTy::DSAVarData ParentReductionOpDSA =
  16571. Stack->getTopMostTaskgroupReductionData(
  16572. D, ParentSR, ParentReductionOp, ParentReductionOpTD);
  16573. bool IsParentBOK = ParentBOKDSA.DKind != OMPD_unknown;
  16574. bool IsParentReductionOp = ParentReductionOpDSA.DKind != OMPD_unknown;
  16575. if ((DeclareReductionRef.isUnset() && IsParentReductionOp) ||
  16576. (DeclareReductionRef.isUsable() && IsParentBOK) ||
  16577. (IsParentBOK && BOK != ParentBOK) || IsParentReductionOp) {
  16578. bool EmitError = true;
  16579. if (IsParentReductionOp && DeclareReductionRef.isUsable()) {
  16580. llvm::FoldingSetNodeID RedId, ParentRedId;
  16581. ParentReductionOp->Profile(ParentRedId, Context, /*Canonical=*/true);
  16582. DeclareReductionRef.get()->Profile(RedId, Context,
  16583. /*Canonical=*/true);
  16584. EmitError = RedId != ParentRedId;
  16585. }
  16586. if (EmitError) {
  16587. S.Diag(ReductionId.getBeginLoc(),
  16588. diag::err_omp_reduction_identifier_mismatch)
  16589. << ReductionIdRange << RefExpr->getSourceRange();
  16590. S.Diag(ParentSR.getBegin(),
  16591. diag::note_omp_previous_reduction_identifier)
  16592. << ParentSR
  16593. << (IsParentBOK ? ParentBOKDSA.RefExpr
  16594. : ParentReductionOpDSA.RefExpr)
  16595. ->getSourceRange();
  16596. continue;
  16597. }
  16598. }
  16599. TaskgroupDescriptor = IsParentBOK ? ParentBOKTD : ParentReductionOpTD;
  16600. }
  16601. DeclRefExpr *Ref = nullptr;
  16602. Expr *VarsExpr = RefExpr->IgnoreParens();
  16603. if (!VD && !S.CurContext->isDependentContext()) {
  16604. if (ASE || OASE) {
  16605. TransformExprToCaptures RebuildToCapture(S, D);
  16606. VarsExpr =
  16607. RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
  16608. Ref = RebuildToCapture.getCapturedExpr();
  16609. } else {
  16610. VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false);
  16611. }
  16612. if (!S.isOpenMPCapturedDecl(D)) {
  16613. RD.ExprCaptures.emplace_back(Ref->getDecl());
  16614. if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
  16615. ExprResult RefRes = S.DefaultLvalueConversion(Ref);
  16616. if (!RefRes.isUsable())
  16617. continue;
  16618. ExprResult PostUpdateRes =
  16619. S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
  16620. RefRes.get());
  16621. if (!PostUpdateRes.isUsable())
  16622. continue;
  16623. if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
  16624. Stack->getCurrentDirective() == OMPD_taskgroup) {
  16625. S.Diag(RefExpr->getExprLoc(),
  16626. diag::err_omp_reduction_non_addressable_expression)
  16627. << RefExpr->getSourceRange();
  16628. continue;
  16629. }
  16630. RD.ExprPostUpdates.emplace_back(
  16631. S.IgnoredValueConversions(PostUpdateRes.get()).get());
  16632. }
  16633. }
  16634. }
  16635. // All reduction items are still marked as reduction (to do not increase
  16636. // code base size).
  16637. unsigned Modifier = RD.RedModifier;
  16638. // Consider task_reductions as reductions with task modifier. Required for
  16639. // correct analysis of in_reduction clauses.
  16640. if (CurrDir == OMPD_taskgroup && ClauseKind == OMPC_task_reduction)
  16641. Modifier = OMPC_REDUCTION_task;
  16642. Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref, Modifier,
  16643. ASE || OASE);
  16644. if (Modifier == OMPC_REDUCTION_task &&
  16645. (CurrDir == OMPD_taskgroup ||
  16646. ((isOpenMPParallelDirective(CurrDir) ||
  16647. isOpenMPWorksharingDirective(CurrDir)) &&
  16648. !isOpenMPSimdDirective(CurrDir)))) {
  16649. if (DeclareReductionRef.isUsable())
  16650. Stack->addTaskgroupReductionData(D, ReductionIdRange,
  16651. DeclareReductionRef.get());
  16652. else
  16653. Stack->addTaskgroupReductionData(D, ReductionIdRange, BOK);
  16654. }
  16655. RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get(),
  16656. TaskgroupDescriptor, CopyOpRes.get(), TempArrayRes.get(),
  16657. TempArrayElem.get());
  16658. }
  16659. return RD.Vars.empty();
  16660. }
  16661. OMPClause *Sema::ActOnOpenMPReductionClause(
  16662. ArrayRef<Expr *> VarList, OpenMPReductionClauseModifier Modifier,
  16663. SourceLocation StartLoc, SourceLocation LParenLoc,
  16664. SourceLocation ModifierLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
  16665. CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
  16666. ArrayRef<Expr *> UnresolvedReductions) {
  16667. if (ModifierLoc.isValid() && Modifier == OMPC_REDUCTION_unknown) {
  16668. Diag(LParenLoc, diag::err_omp_unexpected_clause_value)
  16669. << getListOfPossibleValues(OMPC_reduction, /*First=*/0,
  16670. /*Last=*/OMPC_REDUCTION_unknown)
  16671. << getOpenMPClauseName(OMPC_reduction);
  16672. return nullptr;
  16673. }
  16674. // OpenMP 5.0, 2.19.5.4 reduction Clause, Restrictions
  16675. // A reduction clause with the inscan reduction-modifier may only appear on a
  16676. // worksharing-loop construct, a worksharing-loop SIMD construct, a simd
  16677. // construct, a parallel worksharing-loop construct or a parallel
  16678. // worksharing-loop SIMD construct.
  16679. if (Modifier == OMPC_REDUCTION_inscan &&
  16680. (DSAStack->getCurrentDirective() != OMPD_for &&
  16681. DSAStack->getCurrentDirective() != OMPD_for_simd &&
  16682. DSAStack->getCurrentDirective() != OMPD_simd &&
  16683. DSAStack->getCurrentDirective() != OMPD_parallel_for &&
  16684. DSAStack->getCurrentDirective() != OMPD_parallel_for_simd)) {
  16685. Diag(ModifierLoc, diag::err_omp_wrong_inscan_reduction);
  16686. return nullptr;
  16687. }
  16688. ReductionData RD(VarList.size(), Modifier);
  16689. if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_reduction, VarList,
  16690. StartLoc, LParenLoc, ColonLoc, EndLoc,
  16691. ReductionIdScopeSpec, ReductionId,
  16692. UnresolvedReductions, RD))
  16693. return nullptr;
  16694. return OMPReductionClause::Create(
  16695. Context, StartLoc, LParenLoc, ModifierLoc, ColonLoc, EndLoc, Modifier,
  16696. RD.Vars, ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
  16697. RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.InscanCopyOps,
  16698. RD.InscanCopyArrayTemps, RD.InscanCopyArrayElems,
  16699. buildPreInits(Context, RD.ExprCaptures),
  16700. buildPostUpdate(*this, RD.ExprPostUpdates));
  16701. }
  16702. OMPClause *Sema::ActOnOpenMPTaskReductionClause(
  16703. ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
  16704. SourceLocation ColonLoc, SourceLocation EndLoc,
  16705. CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
  16706. ArrayRef<Expr *> UnresolvedReductions) {
  16707. ReductionData RD(VarList.size());
  16708. if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_task_reduction, VarList,
  16709. StartLoc, LParenLoc, ColonLoc, EndLoc,
  16710. ReductionIdScopeSpec, ReductionId,
  16711. UnresolvedReductions, RD))
  16712. return nullptr;
  16713. return OMPTaskReductionClause::Create(
  16714. Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
  16715. ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
  16716. RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
  16717. buildPreInits(Context, RD.ExprCaptures),
  16718. buildPostUpdate(*this, RD.ExprPostUpdates));
  16719. }
  16720. OMPClause *Sema::ActOnOpenMPInReductionClause(
  16721. ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
  16722. SourceLocation ColonLoc, SourceLocation EndLoc,
  16723. CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
  16724. ArrayRef<Expr *> UnresolvedReductions) {
  16725. ReductionData RD(VarList.size());
  16726. if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_in_reduction, VarList,
  16727. StartLoc, LParenLoc, ColonLoc, EndLoc,
  16728. ReductionIdScopeSpec, ReductionId,
  16729. UnresolvedReductions, RD))
  16730. return nullptr;
  16731. return OMPInReductionClause::Create(
  16732. Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
  16733. ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
  16734. RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.TaskgroupDescriptors,
  16735. buildPreInits(Context, RD.ExprCaptures),
  16736. buildPostUpdate(*this, RD.ExprPostUpdates));
  16737. }
  16738. bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
  16739. SourceLocation LinLoc) {
  16740. if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
  16741. LinKind == OMPC_LINEAR_unknown) {
  16742. Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
  16743. return true;
  16744. }
  16745. return false;
  16746. }
  16747. bool Sema::CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc,
  16748. OpenMPLinearClauseKind LinKind, QualType Type,
  16749. bool IsDeclareSimd) {
  16750. const auto *VD = dyn_cast_or_null<VarDecl>(D);
  16751. // A variable must not have an incomplete type or a reference type.
  16752. if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
  16753. return true;
  16754. if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
  16755. !Type->isReferenceType()) {
  16756. Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
  16757. << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
  16758. return true;
  16759. }
  16760. Type = Type.getNonReferenceType();
  16761. // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
  16762. // A variable that is privatized must not have a const-qualified type
  16763. // unless it is of class type with a mutable member. This restriction does
  16764. // not apply to the firstprivate clause, nor to the linear clause on
  16765. // declarative directives (like declare simd).
  16766. if (!IsDeclareSimd &&
  16767. rejectConstNotMutableType(*this, D, Type, OMPC_linear, ELoc))
  16768. return true;
  16769. // A list item must be of integral or pointer type.
  16770. Type = Type.getUnqualifiedType().getCanonicalType();
  16771. const auto *Ty = Type.getTypePtrOrNull();
  16772. if (!Ty || (LinKind != OMPC_LINEAR_ref && !Ty->isDependentType() &&
  16773. !Ty->isIntegralType(Context) && !Ty->isPointerType())) {
  16774. Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
  16775. if (D) {
  16776. bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
  16777. VarDecl::DeclarationOnly;
  16778. Diag(D->getLocation(),
  16779. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  16780. << D;
  16781. }
  16782. return true;
  16783. }
  16784. return false;
  16785. }
  16786. OMPClause *Sema::ActOnOpenMPLinearClause(
  16787. ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
  16788. SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
  16789. SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
  16790. SmallVector<Expr *, 8> Vars;
  16791. SmallVector<Expr *, 8> Privates;
  16792. SmallVector<Expr *, 8> Inits;
  16793. SmallVector<Decl *, 4> ExprCaptures;
  16794. SmallVector<Expr *, 4> ExprPostUpdates;
  16795. if (CheckOpenMPLinearModifier(LinKind, LinLoc))
  16796. LinKind = OMPC_LINEAR_val;
  16797. for (Expr *RefExpr : VarList) {
  16798. assert(RefExpr && "NULL expr in OpenMP linear clause.");
  16799. SourceLocation ELoc;
  16800. SourceRange ERange;
  16801. Expr *SimpleRefExpr = RefExpr;
  16802. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  16803. if (Res.second) {
  16804. // It will be analyzed later.
  16805. Vars.push_back(RefExpr);
  16806. Privates.push_back(nullptr);
  16807. Inits.push_back(nullptr);
  16808. }
  16809. ValueDecl *D = Res.first;
  16810. if (!D)
  16811. continue;
  16812. QualType Type = D->getType();
  16813. auto *VD = dyn_cast<VarDecl>(D);
  16814. // OpenMP [2.14.3.7, linear clause]
  16815. // A list-item cannot appear in more than one linear clause.
  16816. // A list-item that appears in a linear clause cannot appear in any
  16817. // other data-sharing attribute clause.
  16818. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
  16819. if (DVar.RefExpr) {
  16820. Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
  16821. << getOpenMPClauseName(OMPC_linear);
  16822. reportOriginalDsa(*this, DSAStack, D, DVar);
  16823. continue;
  16824. }
  16825. if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
  16826. continue;
  16827. Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
  16828. // Build private copy of original var.
  16829. VarDecl *Private =
  16830. buildVarDecl(*this, ELoc, Type, D->getName(),
  16831. D->hasAttrs() ? &D->getAttrs() : nullptr,
  16832. VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
  16833. DeclRefExpr *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
  16834. // Build var to save initial value.
  16835. VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
  16836. Expr *InitExpr;
  16837. DeclRefExpr *Ref = nullptr;
  16838. if (!VD && !CurContext->isDependentContext()) {
  16839. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
  16840. if (!isOpenMPCapturedDecl(D)) {
  16841. ExprCaptures.push_back(Ref->getDecl());
  16842. if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
  16843. ExprResult RefRes = DefaultLvalueConversion(Ref);
  16844. if (!RefRes.isUsable())
  16845. continue;
  16846. ExprResult PostUpdateRes =
  16847. BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
  16848. SimpleRefExpr, RefRes.get());
  16849. if (!PostUpdateRes.isUsable())
  16850. continue;
  16851. ExprPostUpdates.push_back(
  16852. IgnoredValueConversions(PostUpdateRes.get()).get());
  16853. }
  16854. }
  16855. }
  16856. if (LinKind == OMPC_LINEAR_uval)
  16857. InitExpr = VD ? VD->getInit() : SimpleRefExpr;
  16858. else
  16859. InitExpr = VD ? SimpleRefExpr : Ref;
  16860. AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
  16861. /*DirectInit=*/false);
  16862. DeclRefExpr *InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
  16863. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
  16864. Vars.push_back((VD || CurContext->isDependentContext())
  16865. ? RefExpr->IgnoreParens()
  16866. : Ref);
  16867. Privates.push_back(PrivateRef);
  16868. Inits.push_back(InitRef);
  16869. }
  16870. if (Vars.empty())
  16871. return nullptr;
  16872. Expr *StepExpr = Step;
  16873. Expr *CalcStepExpr = nullptr;
  16874. if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
  16875. !Step->isInstantiationDependent() &&
  16876. !Step->containsUnexpandedParameterPack()) {
  16877. SourceLocation StepLoc = Step->getBeginLoc();
  16878. ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
  16879. if (Val.isInvalid())
  16880. return nullptr;
  16881. StepExpr = Val.get();
  16882. // Build var to save the step value.
  16883. VarDecl *SaveVar =
  16884. buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
  16885. ExprResult SaveRef =
  16886. buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
  16887. ExprResult CalcStep =
  16888. BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
  16889. CalcStep = ActOnFinishFullExpr(CalcStep.get(), /*DiscardedValue*/ false);
  16890. // Warn about zero linear step (it would be probably better specified as
  16891. // making corresponding variables 'const').
  16892. if (Optional<llvm::APSInt> Result =
  16893. StepExpr->getIntegerConstantExpr(Context)) {
  16894. if (!Result->isNegative() && !Result->isStrictlyPositive())
  16895. Diag(StepLoc, diag::warn_omp_linear_step_zero)
  16896. << Vars[0] << (Vars.size() > 1);
  16897. } else if (CalcStep.isUsable()) {
  16898. // Calculate the step beforehand instead of doing this on each iteration.
  16899. // (This is not used if the number of iterations may be kfold-ed).
  16900. CalcStepExpr = CalcStep.get();
  16901. }
  16902. }
  16903. return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
  16904. ColonLoc, EndLoc, Vars, Privates, Inits,
  16905. StepExpr, CalcStepExpr,
  16906. buildPreInits(Context, ExprCaptures),
  16907. buildPostUpdate(*this, ExprPostUpdates));
  16908. }
  16909. static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
  16910. Expr *NumIterations, Sema &SemaRef,
  16911. Scope *S, DSAStackTy *Stack) {
  16912. // Walk the vars and build update/final expressions for the CodeGen.
  16913. SmallVector<Expr *, 8> Updates;
  16914. SmallVector<Expr *, 8> Finals;
  16915. SmallVector<Expr *, 8> UsedExprs;
  16916. Expr *Step = Clause.getStep();
  16917. Expr *CalcStep = Clause.getCalcStep();
  16918. // OpenMP [2.14.3.7, linear clause]
  16919. // If linear-step is not specified it is assumed to be 1.
  16920. if (!Step)
  16921. Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
  16922. else if (CalcStep)
  16923. Step = cast<BinaryOperator>(CalcStep)->getLHS();
  16924. bool HasErrors = false;
  16925. auto CurInit = Clause.inits().begin();
  16926. auto CurPrivate = Clause.privates().begin();
  16927. OpenMPLinearClauseKind LinKind = Clause.getModifier();
  16928. for (Expr *RefExpr : Clause.varlists()) {
  16929. SourceLocation ELoc;
  16930. SourceRange ERange;
  16931. Expr *SimpleRefExpr = RefExpr;
  16932. auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange);
  16933. ValueDecl *D = Res.first;
  16934. if (Res.second || !D) {
  16935. Updates.push_back(nullptr);
  16936. Finals.push_back(nullptr);
  16937. HasErrors = true;
  16938. continue;
  16939. }
  16940. auto &&Info = Stack->isLoopControlVariable(D);
  16941. // OpenMP [2.15.11, distribute simd Construct]
  16942. // A list item may not appear in a linear clause, unless it is the loop
  16943. // iteration variable.
  16944. if (isOpenMPDistributeDirective(Stack->getCurrentDirective()) &&
  16945. isOpenMPSimdDirective(Stack->getCurrentDirective()) && !Info.first) {
  16946. SemaRef.Diag(ELoc,
  16947. diag::err_omp_linear_distribute_var_non_loop_iteration);
  16948. Updates.push_back(nullptr);
  16949. Finals.push_back(nullptr);
  16950. HasErrors = true;
  16951. continue;
  16952. }
  16953. Expr *InitExpr = *CurInit;
  16954. // Build privatized reference to the current linear var.
  16955. auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
  16956. Expr *CapturedRef;
  16957. if (LinKind == OMPC_LINEAR_uval)
  16958. CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
  16959. else
  16960. CapturedRef =
  16961. buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
  16962. DE->getType().getUnqualifiedType(), DE->getExprLoc(),
  16963. /*RefersToCapture=*/true);
  16964. // Build update: Var = InitExpr + IV * Step
  16965. ExprResult Update;
  16966. if (!Info.first)
  16967. Update = buildCounterUpdate(
  16968. SemaRef, S, RefExpr->getExprLoc(), *CurPrivate, InitExpr, IV, Step,
  16969. /*Subtract=*/false, /*IsNonRectangularLB=*/false);
  16970. else
  16971. Update = *CurPrivate;
  16972. Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getBeginLoc(),
  16973. /*DiscardedValue*/ false);
  16974. // Build final: Var = PrivCopy;
  16975. ExprResult Final;
  16976. if (!Info.first)
  16977. Final = SemaRef.BuildBinOp(
  16978. S, RefExpr->getExprLoc(), BO_Assign, CapturedRef,
  16979. SemaRef.DefaultLvalueConversion(*CurPrivate).get());
  16980. else
  16981. Final = *CurPrivate;
  16982. Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getBeginLoc(),
  16983. /*DiscardedValue*/ false);
  16984. if (!Update.isUsable() || !Final.isUsable()) {
  16985. Updates.push_back(nullptr);
  16986. Finals.push_back(nullptr);
  16987. UsedExprs.push_back(nullptr);
  16988. HasErrors = true;
  16989. } else {
  16990. Updates.push_back(Update.get());
  16991. Finals.push_back(Final.get());
  16992. if (!Info.first)
  16993. UsedExprs.push_back(SimpleRefExpr);
  16994. }
  16995. ++CurInit;
  16996. ++CurPrivate;
  16997. }
  16998. if (Expr *S = Clause.getStep())
  16999. UsedExprs.push_back(S);
  17000. // Fill the remaining part with the nullptr.
  17001. UsedExprs.append(Clause.varlist_size() + 1 - UsedExprs.size(), nullptr);
  17002. Clause.setUpdates(Updates);
  17003. Clause.setFinals(Finals);
  17004. Clause.setUsedExprs(UsedExprs);
  17005. return HasErrors;
  17006. }
  17007. OMPClause *Sema::ActOnOpenMPAlignedClause(
  17008. ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
  17009. SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
  17010. SmallVector<Expr *, 8> Vars;
  17011. for (Expr *RefExpr : VarList) {
  17012. assert(RefExpr && "NULL expr in OpenMP linear clause.");
  17013. SourceLocation ELoc;
  17014. SourceRange ERange;
  17015. Expr *SimpleRefExpr = RefExpr;
  17016. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  17017. if (Res.second) {
  17018. // It will be analyzed later.
  17019. Vars.push_back(RefExpr);
  17020. }
  17021. ValueDecl *D = Res.first;
  17022. if (!D)
  17023. continue;
  17024. QualType QType = D->getType();
  17025. auto *VD = dyn_cast<VarDecl>(D);
  17026. // OpenMP [2.8.1, simd construct, Restrictions]
  17027. // The type of list items appearing in the aligned clause must be
  17028. // array, pointer, reference to array, or reference to pointer.
  17029. QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
  17030. const Type *Ty = QType.getTypePtrOrNull();
  17031. if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
  17032. Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
  17033. << QType << getLangOpts().CPlusPlus << ERange;
  17034. bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
  17035. VarDecl::DeclarationOnly;
  17036. Diag(D->getLocation(),
  17037. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  17038. << D;
  17039. continue;
  17040. }
  17041. // OpenMP [2.8.1, simd construct, Restrictions]
  17042. // A list-item cannot appear in more than one aligned clause.
  17043. if (const Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
  17044. Diag(ELoc, diag::err_omp_used_in_clause_twice)
  17045. << 0 << getOpenMPClauseName(OMPC_aligned) << ERange;
  17046. Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
  17047. << getOpenMPClauseName(OMPC_aligned);
  17048. continue;
  17049. }
  17050. DeclRefExpr *Ref = nullptr;
  17051. if (!VD && isOpenMPCapturedDecl(D))
  17052. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
  17053. Vars.push_back(DefaultFunctionArrayConversion(
  17054. (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
  17055. .get());
  17056. }
  17057. // OpenMP [2.8.1, simd construct, Description]
  17058. // The parameter of the aligned clause, alignment, must be a constant
  17059. // positive integer expression.
  17060. // If no optional parameter is specified, implementation-defined default
  17061. // alignments for SIMD instructions on the target platforms are assumed.
  17062. if (Alignment != nullptr) {
  17063. ExprResult AlignResult =
  17064. VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
  17065. if (AlignResult.isInvalid())
  17066. return nullptr;
  17067. Alignment = AlignResult.get();
  17068. }
  17069. if (Vars.empty())
  17070. return nullptr;
  17071. return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
  17072. EndLoc, Vars, Alignment);
  17073. }
  17074. OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
  17075. SourceLocation StartLoc,
  17076. SourceLocation LParenLoc,
  17077. SourceLocation EndLoc) {
  17078. SmallVector<Expr *, 8> Vars;
  17079. SmallVector<Expr *, 8> SrcExprs;
  17080. SmallVector<Expr *, 8> DstExprs;
  17081. SmallVector<Expr *, 8> AssignmentOps;
  17082. for (Expr *RefExpr : VarList) {
  17083. assert(RefExpr && "NULL expr in OpenMP copyin clause.");
  17084. if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
  17085. // It will be analyzed later.
  17086. Vars.push_back(RefExpr);
  17087. SrcExprs.push_back(nullptr);
  17088. DstExprs.push_back(nullptr);
  17089. AssignmentOps.push_back(nullptr);
  17090. continue;
  17091. }
  17092. SourceLocation ELoc = RefExpr->getExprLoc();
  17093. // OpenMP [2.1, C/C++]
  17094. // A list item is a variable name.
  17095. // OpenMP [2.14.4.1, Restrictions, p.1]
  17096. // A list item that appears in a copyin clause must be threadprivate.
  17097. auto *DE = dyn_cast<DeclRefExpr>(RefExpr);
  17098. if (!DE || !isa<VarDecl>(DE->getDecl())) {
  17099. Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
  17100. << 0 << RefExpr->getSourceRange();
  17101. continue;
  17102. }
  17103. Decl *D = DE->getDecl();
  17104. auto *VD = cast<VarDecl>(D);
  17105. QualType Type = VD->getType();
  17106. if (Type->isDependentType() || Type->isInstantiationDependentType()) {
  17107. // It will be analyzed later.
  17108. Vars.push_back(DE);
  17109. SrcExprs.push_back(nullptr);
  17110. DstExprs.push_back(nullptr);
  17111. AssignmentOps.push_back(nullptr);
  17112. continue;
  17113. }
  17114. // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
  17115. // A list item that appears in a copyin clause must be threadprivate.
  17116. if (!DSAStack->isThreadPrivate(VD)) {
  17117. Diag(ELoc, diag::err_omp_required_access)
  17118. << getOpenMPClauseName(OMPC_copyin)
  17119. << getOpenMPDirectiveName(OMPD_threadprivate);
  17120. continue;
  17121. }
  17122. // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
  17123. // A variable of class type (or array thereof) that appears in a
  17124. // copyin clause requires an accessible, unambiguous copy assignment
  17125. // operator for the class type.
  17126. QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
  17127. VarDecl *SrcVD =
  17128. buildVarDecl(*this, DE->getBeginLoc(), ElemType.getUnqualifiedType(),
  17129. ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
  17130. DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(
  17131. *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
  17132. VarDecl *DstVD =
  17133. buildVarDecl(*this, DE->getBeginLoc(), ElemType, ".copyin.dst",
  17134. VD->hasAttrs() ? &VD->getAttrs() : nullptr);
  17135. DeclRefExpr *PseudoDstExpr =
  17136. buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
  17137. // For arrays generate assignment operation for single element and replace
  17138. // it by the original array element in CodeGen.
  17139. ExprResult AssignmentOp =
  17140. BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign, PseudoDstExpr,
  17141. PseudoSrcExpr);
  17142. if (AssignmentOp.isInvalid())
  17143. continue;
  17144. AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
  17145. /*DiscardedValue*/ false);
  17146. if (AssignmentOp.isInvalid())
  17147. continue;
  17148. DSAStack->addDSA(VD, DE, OMPC_copyin);
  17149. Vars.push_back(DE);
  17150. SrcExprs.push_back(PseudoSrcExpr);
  17151. DstExprs.push_back(PseudoDstExpr);
  17152. AssignmentOps.push_back(AssignmentOp.get());
  17153. }
  17154. if (Vars.empty())
  17155. return nullptr;
  17156. return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
  17157. SrcExprs, DstExprs, AssignmentOps);
  17158. }
  17159. OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
  17160. SourceLocation StartLoc,
  17161. SourceLocation LParenLoc,
  17162. SourceLocation EndLoc) {
  17163. SmallVector<Expr *, 8> Vars;
  17164. SmallVector<Expr *, 8> SrcExprs;
  17165. SmallVector<Expr *, 8> DstExprs;
  17166. SmallVector<Expr *, 8> AssignmentOps;
  17167. for (Expr *RefExpr : VarList) {
  17168. assert(RefExpr && "NULL expr in OpenMP linear clause.");
  17169. SourceLocation ELoc;
  17170. SourceRange ERange;
  17171. Expr *SimpleRefExpr = RefExpr;
  17172. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  17173. if (Res.second) {
  17174. // It will be analyzed later.
  17175. Vars.push_back(RefExpr);
  17176. SrcExprs.push_back(nullptr);
  17177. DstExprs.push_back(nullptr);
  17178. AssignmentOps.push_back(nullptr);
  17179. }
  17180. ValueDecl *D = Res.first;
  17181. if (!D)
  17182. continue;
  17183. QualType Type = D->getType();
  17184. auto *VD = dyn_cast<VarDecl>(D);
  17185. // OpenMP [2.14.4.2, Restrictions, p.2]
  17186. // A list item that appears in a copyprivate clause may not appear in a
  17187. // private or firstprivate clause on the single construct.
  17188. if (!VD || !DSAStack->isThreadPrivate(VD)) {
  17189. DSAStackTy::DSAVarData DVar =
  17190. DSAStack->getTopDSA(D, /*FromParent=*/false);
  17191. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
  17192. DVar.RefExpr) {
  17193. Diag(ELoc, diag::err_omp_wrong_dsa)
  17194. << getOpenMPClauseName(DVar.CKind)
  17195. << getOpenMPClauseName(OMPC_copyprivate);
  17196. reportOriginalDsa(*this, DSAStack, D, DVar);
  17197. continue;
  17198. }
  17199. // OpenMP [2.11.4.2, Restrictions, p.1]
  17200. // All list items that appear in a copyprivate clause must be either
  17201. // threadprivate or private in the enclosing context.
  17202. if (DVar.CKind == OMPC_unknown) {
  17203. DVar = DSAStack->getImplicitDSA(D, false);
  17204. if (DVar.CKind == OMPC_shared) {
  17205. Diag(ELoc, diag::err_omp_required_access)
  17206. << getOpenMPClauseName(OMPC_copyprivate)
  17207. << "threadprivate or private in the enclosing context";
  17208. reportOriginalDsa(*this, DSAStack, D, DVar);
  17209. continue;
  17210. }
  17211. }
  17212. }
  17213. // Variably modified types are not supported.
  17214. if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
  17215. Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
  17216. << getOpenMPClauseName(OMPC_copyprivate) << Type
  17217. << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
  17218. bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
  17219. VarDecl::DeclarationOnly;
  17220. Diag(D->getLocation(),
  17221. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  17222. << D;
  17223. continue;
  17224. }
  17225. // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
  17226. // A variable of class type (or array thereof) that appears in a
  17227. // copyin clause requires an accessible, unambiguous copy assignment
  17228. // operator for the class type.
  17229. Type = Context.getBaseElementType(Type.getNonReferenceType())
  17230. .getUnqualifiedType();
  17231. VarDecl *SrcVD =
  17232. buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.src",
  17233. D->hasAttrs() ? &D->getAttrs() : nullptr);
  17234. DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
  17235. VarDecl *DstVD =
  17236. buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.dst",
  17237. D->hasAttrs() ? &D->getAttrs() : nullptr);
  17238. DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
  17239. ExprResult AssignmentOp = BuildBinOp(
  17240. DSAStack->getCurScope(), ELoc, BO_Assign, PseudoDstExpr, PseudoSrcExpr);
  17241. if (AssignmentOp.isInvalid())
  17242. continue;
  17243. AssignmentOp =
  17244. ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
  17245. if (AssignmentOp.isInvalid())
  17246. continue;
  17247. // No need to mark vars as copyprivate, they are already threadprivate or
  17248. // implicitly private.
  17249. assert(VD || isOpenMPCapturedDecl(D));
  17250. Vars.push_back(
  17251. VD ? RefExpr->IgnoreParens()
  17252. : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
  17253. SrcExprs.push_back(PseudoSrcExpr);
  17254. DstExprs.push_back(PseudoDstExpr);
  17255. AssignmentOps.push_back(AssignmentOp.get());
  17256. }
  17257. if (Vars.empty())
  17258. return nullptr;
  17259. return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  17260. Vars, SrcExprs, DstExprs, AssignmentOps);
  17261. }
  17262. OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
  17263. SourceLocation StartLoc,
  17264. SourceLocation LParenLoc,
  17265. SourceLocation EndLoc) {
  17266. if (VarList.empty())
  17267. return nullptr;
  17268. return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
  17269. }
  17270. /// Tries to find omp_depend_t. type.
  17271. static bool findOMPDependT(Sema &S, SourceLocation Loc, DSAStackTy *Stack,
  17272. bool Diagnose = true) {
  17273. QualType OMPDependT = Stack->getOMPDependT();
  17274. if (!OMPDependT.isNull())
  17275. return true;
  17276. IdentifierInfo *II = &S.PP.getIdentifierTable().get("omp_depend_t");
  17277. ParsedType PT = S.getTypeName(*II, Loc, S.getCurScope());
  17278. if (!PT.getAsOpaquePtr() || PT.get().isNull()) {
  17279. if (Diagnose)
  17280. S.Diag(Loc, diag::err_omp_implied_type_not_found) << "omp_depend_t";
  17281. return false;
  17282. }
  17283. Stack->setOMPDependT(PT.get());
  17284. return true;
  17285. }
  17286. OMPClause *Sema::ActOnOpenMPDepobjClause(Expr *Depobj, SourceLocation StartLoc,
  17287. SourceLocation LParenLoc,
  17288. SourceLocation EndLoc) {
  17289. if (!Depobj)
  17290. return nullptr;
  17291. bool OMPDependTFound = findOMPDependT(*this, StartLoc, DSAStack);
  17292. // OpenMP 5.0, 2.17.10.1 depobj Construct
  17293. // depobj is an lvalue expression of type omp_depend_t.
  17294. if (!Depobj->isTypeDependent() && !Depobj->isValueDependent() &&
  17295. !Depobj->isInstantiationDependent() &&
  17296. !Depobj->containsUnexpandedParameterPack() &&
  17297. (OMPDependTFound &&
  17298. !Context.typesAreCompatible(DSAStack->getOMPDependT(), Depobj->getType(),
  17299. /*CompareUnqualified=*/true))) {
  17300. Diag(Depobj->getExprLoc(), diag::err_omp_expected_omp_depend_t_lvalue)
  17301. << 0 << Depobj->getType() << Depobj->getSourceRange();
  17302. }
  17303. if (!Depobj->isLValue()) {
  17304. Diag(Depobj->getExprLoc(), diag::err_omp_expected_omp_depend_t_lvalue)
  17305. << 1 << Depobj->getSourceRange();
  17306. }
  17307. return OMPDepobjClause::Create(Context, StartLoc, LParenLoc, EndLoc, Depobj);
  17308. }
  17309. OMPClause *
  17310. Sema::ActOnOpenMPDependClause(Expr *DepModifier, OpenMPDependClauseKind DepKind,
  17311. SourceLocation DepLoc, SourceLocation ColonLoc,
  17312. ArrayRef<Expr *> VarList, SourceLocation StartLoc,
  17313. SourceLocation LParenLoc, SourceLocation EndLoc) {
  17314. if (DSAStack->getCurrentDirective() == OMPD_ordered &&
  17315. DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
  17316. Diag(DepLoc, diag::err_omp_unexpected_clause_value)
  17317. << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
  17318. return nullptr;
  17319. }
  17320. if (DSAStack->getCurrentDirective() == OMPD_taskwait &&
  17321. DepKind == OMPC_DEPEND_mutexinoutset) {
  17322. Diag(DepLoc, diag::err_omp_taskwait_depend_mutexinoutset_not_allowed);
  17323. return nullptr;
  17324. }
  17325. if ((DSAStack->getCurrentDirective() != OMPD_ordered ||
  17326. DSAStack->getCurrentDirective() == OMPD_depobj) &&
  17327. (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
  17328. DepKind == OMPC_DEPEND_sink ||
  17329. ((LangOpts.OpenMP < 50 ||
  17330. DSAStack->getCurrentDirective() == OMPD_depobj) &&
  17331. DepKind == OMPC_DEPEND_depobj))) {
  17332. SmallVector<unsigned, 3> Except;
  17333. Except.push_back(OMPC_DEPEND_source);
  17334. Except.push_back(OMPC_DEPEND_sink);
  17335. if (LangOpts.OpenMP < 50 || DSAStack->getCurrentDirective() == OMPD_depobj)
  17336. Except.push_back(OMPC_DEPEND_depobj);
  17337. std::string Expected = (LangOpts.OpenMP >= 50 && !DepModifier)
  17338. ? "depend modifier(iterator) or "
  17339. : "";
  17340. Diag(DepLoc, diag::err_omp_unexpected_clause_value)
  17341. << Expected + getListOfPossibleValues(OMPC_depend, /*First=*/0,
  17342. /*Last=*/OMPC_DEPEND_unknown,
  17343. Except)
  17344. << getOpenMPClauseName(OMPC_depend);
  17345. return nullptr;
  17346. }
  17347. if (DepModifier &&
  17348. (DepKind == OMPC_DEPEND_source || DepKind == OMPC_DEPEND_sink)) {
  17349. Diag(DepModifier->getExprLoc(),
  17350. diag::err_omp_depend_sink_source_with_modifier);
  17351. return nullptr;
  17352. }
  17353. if (DepModifier &&
  17354. !DepModifier->getType()->isSpecificBuiltinType(BuiltinType::OMPIterator))
  17355. Diag(DepModifier->getExprLoc(), diag::err_omp_depend_modifier_not_iterator);
  17356. SmallVector<Expr *, 8> Vars;
  17357. DSAStackTy::OperatorOffsetTy OpsOffs;
  17358. llvm::APSInt DepCounter(/*BitWidth=*/32);
  17359. llvm::APSInt TotalDepCount(/*BitWidth=*/32);
  17360. if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) {
  17361. if (const Expr *OrderedCountExpr =
  17362. DSAStack->getParentOrderedRegionParam().first) {
  17363. TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
  17364. TotalDepCount.setIsUnsigned(/*Val=*/true);
  17365. }
  17366. }
  17367. for (Expr *RefExpr : VarList) {
  17368. assert(RefExpr && "NULL expr in OpenMP shared clause.");
  17369. if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
  17370. // It will be analyzed later.
  17371. Vars.push_back(RefExpr);
  17372. continue;
  17373. }
  17374. SourceLocation ELoc = RefExpr->getExprLoc();
  17375. Expr *SimpleExpr = RefExpr->IgnoreParenCasts();
  17376. if (DepKind == OMPC_DEPEND_sink) {
  17377. if (DSAStack->getParentOrderedRegionParam().first &&
  17378. DepCounter >= TotalDepCount) {
  17379. Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
  17380. continue;
  17381. }
  17382. ++DepCounter;
  17383. // OpenMP [2.13.9, Summary]
  17384. // depend(dependence-type : vec), where dependence-type is:
  17385. // 'sink' and where vec is the iteration vector, which has the form:
  17386. // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
  17387. // where n is the value specified by the ordered clause in the loop
  17388. // directive, xi denotes the loop iteration variable of the i-th nested
  17389. // loop associated with the loop directive, and di is a constant
  17390. // non-negative integer.
  17391. if (CurContext->isDependentContext()) {
  17392. // It will be analyzed later.
  17393. Vars.push_back(RefExpr);
  17394. continue;
  17395. }
  17396. SimpleExpr = SimpleExpr->IgnoreImplicit();
  17397. OverloadedOperatorKind OOK = OO_None;
  17398. SourceLocation OOLoc;
  17399. Expr *LHS = SimpleExpr;
  17400. Expr *RHS = nullptr;
  17401. if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
  17402. OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
  17403. OOLoc = BO->getOperatorLoc();
  17404. LHS = BO->getLHS()->IgnoreParenImpCasts();
  17405. RHS = BO->getRHS()->IgnoreParenImpCasts();
  17406. } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
  17407. OOK = OCE->getOperator();
  17408. OOLoc = OCE->getOperatorLoc();
  17409. LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
  17410. RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
  17411. } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
  17412. OOK = MCE->getMethodDecl()
  17413. ->getNameInfo()
  17414. .getName()
  17415. .getCXXOverloadedOperator();
  17416. OOLoc = MCE->getCallee()->getExprLoc();
  17417. LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
  17418. RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
  17419. }
  17420. SourceLocation ELoc;
  17421. SourceRange ERange;
  17422. auto Res = getPrivateItem(*this, LHS, ELoc, ERange);
  17423. if (Res.second) {
  17424. // It will be analyzed later.
  17425. Vars.push_back(RefExpr);
  17426. }
  17427. ValueDecl *D = Res.first;
  17428. if (!D)
  17429. continue;
  17430. if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
  17431. Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
  17432. continue;
  17433. }
  17434. if (RHS) {
  17435. ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
  17436. RHS, OMPC_depend, /*StrictlyPositive=*/false);
  17437. if (RHSRes.isInvalid())
  17438. continue;
  17439. }
  17440. if (!CurContext->isDependentContext() &&
  17441. DSAStack->getParentOrderedRegionParam().first &&
  17442. DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
  17443. const ValueDecl *VD =
  17444. DSAStack->getParentLoopControlVariable(DepCounter.getZExtValue());
  17445. if (VD)
  17446. Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
  17447. << 1 << VD;
  17448. else
  17449. Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) << 0;
  17450. continue;
  17451. }
  17452. OpsOffs.emplace_back(RHS, OOK);
  17453. } else {
  17454. bool OMPDependTFound = LangOpts.OpenMP >= 50;
  17455. if (OMPDependTFound)
  17456. OMPDependTFound = findOMPDependT(*this, StartLoc, DSAStack,
  17457. DepKind == OMPC_DEPEND_depobj);
  17458. if (DepKind == OMPC_DEPEND_depobj) {
  17459. // OpenMP 5.0, 2.17.11 depend Clause, Restrictions, C/C++
  17460. // List items used in depend clauses with the depobj dependence type
  17461. // must be expressions of the omp_depend_t type.
  17462. if (!RefExpr->isValueDependent() && !RefExpr->isTypeDependent() &&
  17463. !RefExpr->isInstantiationDependent() &&
  17464. !RefExpr->containsUnexpandedParameterPack() &&
  17465. (OMPDependTFound &&
  17466. !Context.hasSameUnqualifiedType(DSAStack->getOMPDependT(),
  17467. RefExpr->getType()))) {
  17468. Diag(ELoc, diag::err_omp_expected_omp_depend_t_lvalue)
  17469. << 0 << RefExpr->getType() << RefExpr->getSourceRange();
  17470. continue;
  17471. }
  17472. if (!RefExpr->isLValue()) {
  17473. Diag(ELoc, diag::err_omp_expected_omp_depend_t_lvalue)
  17474. << 1 << RefExpr->getType() << RefExpr->getSourceRange();
  17475. continue;
  17476. }
  17477. } else {
  17478. // OpenMP 5.0 [2.17.11, Restrictions]
  17479. // List items used in depend clauses cannot be zero-length array
  17480. // sections.
  17481. QualType ExprTy = RefExpr->getType().getNonReferenceType();
  17482. const auto *OASE = dyn_cast<OMPArraySectionExpr>(SimpleExpr);
  17483. if (OASE) {
  17484. QualType BaseType =
  17485. OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
  17486. if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
  17487. ExprTy = ATy->getElementType();
  17488. else
  17489. ExprTy = BaseType->getPointeeType();
  17490. ExprTy = ExprTy.getNonReferenceType();
  17491. const Expr *Length = OASE->getLength();
  17492. Expr::EvalResult Result;
  17493. if (Length && !Length->isValueDependent() &&
  17494. Length->EvaluateAsInt(Result, Context) &&
  17495. Result.Val.getInt().isZero()) {
  17496. Diag(ELoc,
  17497. diag::err_omp_depend_zero_length_array_section_not_allowed)
  17498. << SimpleExpr->getSourceRange();
  17499. continue;
  17500. }
  17501. }
  17502. // OpenMP 5.0, 2.17.11 depend Clause, Restrictions, C/C++
  17503. // List items used in depend clauses with the in, out, inout or
  17504. // mutexinoutset dependence types cannot be expressions of the
  17505. // omp_depend_t type.
  17506. if (!RefExpr->isValueDependent() && !RefExpr->isTypeDependent() &&
  17507. !RefExpr->isInstantiationDependent() &&
  17508. !RefExpr->containsUnexpandedParameterPack() &&
  17509. (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
  17510. (OMPDependTFound &&
  17511. DSAStack->getOMPDependT().getTypePtr() == ExprTy.getTypePtr()))) {
  17512. Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
  17513. << (LangOpts.OpenMP >= 50 ? 1 : 0)
  17514. << (LangOpts.OpenMP >= 50 ? 1 : 0) << RefExpr->getSourceRange();
  17515. continue;
  17516. }
  17517. auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
  17518. if (ASE && !ASE->getBase()->isTypeDependent() &&
  17519. !ASE->getBase()->getType().getNonReferenceType()->isPointerType() &&
  17520. !ASE->getBase()->getType().getNonReferenceType()->isArrayType()) {
  17521. Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
  17522. << (LangOpts.OpenMP >= 50 ? 1 : 0)
  17523. << (LangOpts.OpenMP >= 50 ? 1 : 0) << RefExpr->getSourceRange();
  17524. continue;
  17525. }
  17526. ExprResult Res;
  17527. {
  17528. Sema::TentativeAnalysisScope Trap(*this);
  17529. Res = CreateBuiltinUnaryOp(ELoc, UO_AddrOf,
  17530. RefExpr->IgnoreParenImpCasts());
  17531. }
  17532. if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr) &&
  17533. !isa<OMPArrayShapingExpr>(SimpleExpr)) {
  17534. Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
  17535. << (LangOpts.OpenMP >= 50 ? 1 : 0)
  17536. << (LangOpts.OpenMP >= 50 ? 1 : 0) << RefExpr->getSourceRange();
  17537. continue;
  17538. }
  17539. }
  17540. }
  17541. Vars.push_back(RefExpr->IgnoreParenImpCasts());
  17542. }
  17543. if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
  17544. TotalDepCount > VarList.size() &&
  17545. DSAStack->getParentOrderedRegionParam().first &&
  17546. DSAStack->getParentLoopControlVariable(VarList.size() + 1)) {
  17547. Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration)
  17548. << 1 << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
  17549. }
  17550. if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
  17551. Vars.empty())
  17552. return nullptr;
  17553. auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  17554. DepModifier, DepKind, DepLoc, ColonLoc,
  17555. Vars, TotalDepCount.getZExtValue());
  17556. if ((DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) &&
  17557. DSAStack->isParentOrderedRegion())
  17558. DSAStack->addDoacrossDependClause(C, OpsOffs);
  17559. return C;
  17560. }
  17561. OMPClause *Sema::ActOnOpenMPDeviceClause(OpenMPDeviceClauseModifier Modifier,
  17562. Expr *Device, SourceLocation StartLoc,
  17563. SourceLocation LParenLoc,
  17564. SourceLocation ModifierLoc,
  17565. SourceLocation EndLoc) {
  17566. assert((ModifierLoc.isInvalid() || LangOpts.OpenMP >= 50) &&
  17567. "Unexpected device modifier in OpenMP < 50.");
  17568. bool ErrorFound = false;
  17569. if (ModifierLoc.isValid() && Modifier == OMPC_DEVICE_unknown) {
  17570. std::string Values =
  17571. getListOfPossibleValues(OMPC_device, /*First=*/0, OMPC_DEVICE_unknown);
  17572. Diag(ModifierLoc, diag::err_omp_unexpected_clause_value)
  17573. << Values << getOpenMPClauseName(OMPC_device);
  17574. ErrorFound = true;
  17575. }
  17576. Expr *ValExpr = Device;
  17577. Stmt *HelperValStmt = nullptr;
  17578. // OpenMP [2.9.1, Restrictions]
  17579. // The device expression must evaluate to a non-negative integer value.
  17580. ErrorFound = !isNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
  17581. /*StrictlyPositive=*/false) ||
  17582. ErrorFound;
  17583. if (ErrorFound)
  17584. return nullptr;
  17585. OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
  17586. OpenMPDirectiveKind CaptureRegion =
  17587. getOpenMPCaptureRegionForClause(DKind, OMPC_device, LangOpts.OpenMP);
  17588. if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
  17589. ValExpr = MakeFullExpr(ValExpr).get();
  17590. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  17591. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  17592. HelperValStmt = buildPreInits(Context, Captures);
  17593. }
  17594. return new (Context)
  17595. OMPDeviceClause(Modifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
  17596. LParenLoc, ModifierLoc, EndLoc);
  17597. }
  17598. static bool checkTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
  17599. DSAStackTy *Stack, QualType QTy,
  17600. bool FullCheck = true) {
  17601. if (SemaRef.RequireCompleteType(SL, QTy, diag::err_incomplete_type))
  17602. return false;
  17603. if (FullCheck && !SemaRef.CurContext->isDependentContext() &&
  17604. !QTy.isTriviallyCopyableType(SemaRef.Context))
  17605. SemaRef.Diag(SL, diag::warn_omp_non_trivial_type_mapped) << QTy << SR;
  17606. return true;
  17607. }
  17608. /// Return true if it can be proven that the provided array expression
  17609. /// (array section or array subscript) does NOT specify the whole size of the
  17610. /// array whose base type is \a BaseQTy.
  17611. static bool checkArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
  17612. const Expr *E,
  17613. QualType BaseQTy) {
  17614. const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
  17615. // If this is an array subscript, it refers to the whole size if the size of
  17616. // the dimension is constant and equals 1. Also, an array section assumes the
  17617. // format of an array subscript if no colon is used.
  17618. if (isa<ArraySubscriptExpr>(E) ||
  17619. (OASE && OASE->getColonLocFirst().isInvalid())) {
  17620. if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
  17621. return ATy->getSize().getSExtValue() != 1;
  17622. // Size can't be evaluated statically.
  17623. return false;
  17624. }
  17625. assert(OASE && "Expecting array section if not an array subscript.");
  17626. const Expr *LowerBound = OASE->getLowerBound();
  17627. const Expr *Length = OASE->getLength();
  17628. // If there is a lower bound that does not evaluates to zero, we are not
  17629. // covering the whole dimension.
  17630. if (LowerBound) {
  17631. Expr::EvalResult Result;
  17632. if (!LowerBound->EvaluateAsInt(Result, SemaRef.getASTContext()))
  17633. return false; // Can't get the integer value as a constant.
  17634. llvm::APSInt ConstLowerBound = Result.Val.getInt();
  17635. if (ConstLowerBound.getSExtValue())
  17636. return true;
  17637. }
  17638. // If we don't have a length we covering the whole dimension.
  17639. if (!Length)
  17640. return false;
  17641. // If the base is a pointer, we don't have a way to get the size of the
  17642. // pointee.
  17643. if (BaseQTy->isPointerType())
  17644. return false;
  17645. // We can only check if the length is the same as the size of the dimension
  17646. // if we have a constant array.
  17647. const auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
  17648. if (!CATy)
  17649. return false;
  17650. Expr::EvalResult Result;
  17651. if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
  17652. return false; // Can't get the integer value as a constant.
  17653. llvm::APSInt ConstLength = Result.Val.getInt();
  17654. return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
  17655. }
  17656. // Return true if it can be proven that the provided array expression (array
  17657. // section or array subscript) does NOT specify a single element of the array
  17658. // whose base type is \a BaseQTy.
  17659. static bool checkArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
  17660. const Expr *E,
  17661. QualType BaseQTy) {
  17662. const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
  17663. // An array subscript always refer to a single element. Also, an array section
  17664. // assumes the format of an array subscript if no colon is used.
  17665. if (isa<ArraySubscriptExpr>(E) ||
  17666. (OASE && OASE->getColonLocFirst().isInvalid()))
  17667. return false;
  17668. assert(OASE && "Expecting array section if not an array subscript.");
  17669. const Expr *Length = OASE->getLength();
  17670. // If we don't have a length we have to check if the array has unitary size
  17671. // for this dimension. Also, we should always expect a length if the base type
  17672. // is pointer.
  17673. if (!Length) {
  17674. if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
  17675. return ATy->getSize().getSExtValue() != 1;
  17676. // We cannot assume anything.
  17677. return false;
  17678. }
  17679. // Check if the length evaluates to 1.
  17680. Expr::EvalResult Result;
  17681. if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
  17682. return false; // Can't get the integer value as a constant.
  17683. llvm::APSInt ConstLength = Result.Val.getInt();
  17684. return ConstLength.getSExtValue() != 1;
  17685. }
  17686. // The base of elements of list in a map clause have to be either:
  17687. // - a reference to variable or field.
  17688. // - a member expression.
  17689. // - an array expression.
  17690. //
  17691. // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
  17692. // reference to 'r'.
  17693. //
  17694. // If we have:
  17695. //
  17696. // struct SS {
  17697. // Bla S;
  17698. // foo() {
  17699. // #pragma omp target map (S.Arr[:12]);
  17700. // }
  17701. // }
  17702. //
  17703. // We want to retrieve the member expression 'this->S';
  17704. // OpenMP 5.0 [2.19.7.1, map Clause, Restrictions, p.2]
  17705. // If a list item is an array section, it must specify contiguous storage.
  17706. //
  17707. // For this restriction it is sufficient that we make sure only references
  17708. // to variables or fields and array expressions, and that no array sections
  17709. // exist except in the rightmost expression (unless they cover the whole
  17710. // dimension of the array). E.g. these would be invalid:
  17711. //
  17712. // r.ArrS[3:5].Arr[6:7]
  17713. //
  17714. // r.ArrS[3:5].x
  17715. //
  17716. // but these would be valid:
  17717. // r.ArrS[3].Arr[6:7]
  17718. //
  17719. // r.ArrS[3].x
  17720. namespace {
  17721. class MapBaseChecker final : public StmtVisitor<MapBaseChecker, bool> {
  17722. Sema &SemaRef;
  17723. OpenMPClauseKind CKind = OMPC_unknown;
  17724. OpenMPDirectiveKind DKind = OMPD_unknown;
  17725. OMPClauseMappableExprCommon::MappableExprComponentList &Components;
  17726. bool IsNonContiguous = false;
  17727. bool NoDiagnose = false;
  17728. const Expr *RelevantExpr = nullptr;
  17729. bool AllowUnitySizeArraySection = true;
  17730. bool AllowWholeSizeArraySection = true;
  17731. bool AllowAnotherPtr = true;
  17732. SourceLocation ELoc;
  17733. SourceRange ERange;
  17734. void emitErrorMsg() {
  17735. // If nothing else worked, this is not a valid map clause expression.
  17736. if (SemaRef.getLangOpts().OpenMP < 50) {
  17737. SemaRef.Diag(ELoc,
  17738. diag::err_omp_expected_named_var_member_or_array_expression)
  17739. << ERange;
  17740. } else {
  17741. SemaRef.Diag(ELoc, diag::err_omp_non_lvalue_in_map_or_motion_clauses)
  17742. << getOpenMPClauseName(CKind) << ERange;
  17743. }
  17744. }
  17745. public:
  17746. bool VisitDeclRefExpr(DeclRefExpr *DRE) {
  17747. if (!isa<VarDecl>(DRE->getDecl())) {
  17748. emitErrorMsg();
  17749. return false;
  17750. }
  17751. assert(!RelevantExpr && "RelevantExpr is expected to be nullptr");
  17752. RelevantExpr = DRE;
  17753. // Record the component.
  17754. Components.emplace_back(DRE, DRE->getDecl(), IsNonContiguous);
  17755. return true;
  17756. }
  17757. bool VisitMemberExpr(MemberExpr *ME) {
  17758. Expr *E = ME;
  17759. Expr *BaseE = ME->getBase()->IgnoreParenCasts();
  17760. if (isa<CXXThisExpr>(BaseE)) {
  17761. assert(!RelevantExpr && "RelevantExpr is expected to be nullptr");
  17762. // We found a base expression: this->Val.
  17763. RelevantExpr = ME;
  17764. } else {
  17765. E = BaseE;
  17766. }
  17767. if (!isa<FieldDecl>(ME->getMemberDecl())) {
  17768. if (!NoDiagnose) {
  17769. SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
  17770. << ME->getSourceRange();
  17771. return false;
  17772. }
  17773. if (RelevantExpr)
  17774. return false;
  17775. return Visit(E);
  17776. }
  17777. auto *FD = cast<FieldDecl>(ME->getMemberDecl());
  17778. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
  17779. // A bit-field cannot appear in a map clause.
  17780. //
  17781. if (FD->isBitField()) {
  17782. if (!NoDiagnose) {
  17783. SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
  17784. << ME->getSourceRange() << getOpenMPClauseName(CKind);
  17785. return false;
  17786. }
  17787. if (RelevantExpr)
  17788. return false;
  17789. return Visit(E);
  17790. }
  17791. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
  17792. // If the type of a list item is a reference to a type T then the type
  17793. // will be considered to be T for all purposes of this clause.
  17794. QualType CurType = BaseE->getType().getNonReferenceType();
  17795. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
  17796. // A list item cannot be a variable that is a member of a structure with
  17797. // a union type.
  17798. //
  17799. if (CurType->isUnionType()) {
  17800. if (!NoDiagnose) {
  17801. SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
  17802. << ME->getSourceRange();
  17803. return false;
  17804. }
  17805. return RelevantExpr || Visit(E);
  17806. }
  17807. // If we got a member expression, we should not expect any array section
  17808. // before that:
  17809. //
  17810. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
  17811. // If a list item is an element of a structure, only the rightmost symbol
  17812. // of the variable reference can be an array section.
  17813. //
  17814. AllowUnitySizeArraySection = false;
  17815. AllowWholeSizeArraySection = false;
  17816. // Record the component.
  17817. Components.emplace_back(ME, FD, IsNonContiguous);
  17818. return RelevantExpr || Visit(E);
  17819. }
  17820. bool VisitArraySubscriptExpr(ArraySubscriptExpr *AE) {
  17821. Expr *E = AE->getBase()->IgnoreParenImpCasts();
  17822. if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
  17823. if (!NoDiagnose) {
  17824. SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
  17825. << 0 << AE->getSourceRange();
  17826. return false;
  17827. }
  17828. return RelevantExpr || Visit(E);
  17829. }
  17830. // If we got an array subscript that express the whole dimension we
  17831. // can have any array expressions before. If it only expressing part of
  17832. // the dimension, we can only have unitary-size array expressions.
  17833. if (checkArrayExpressionDoesNotReferToWholeSize(SemaRef, AE, E->getType()))
  17834. AllowWholeSizeArraySection = false;
  17835. if (const auto *TE = dyn_cast<CXXThisExpr>(E->IgnoreParenCasts())) {
  17836. Expr::EvalResult Result;
  17837. if (!AE->getIdx()->isValueDependent() &&
  17838. AE->getIdx()->EvaluateAsInt(Result, SemaRef.getASTContext()) &&
  17839. !Result.Val.getInt().isZero()) {
  17840. SemaRef.Diag(AE->getIdx()->getExprLoc(),
  17841. diag::err_omp_invalid_map_this_expr);
  17842. SemaRef.Diag(AE->getIdx()->getExprLoc(),
  17843. diag::note_omp_invalid_subscript_on_this_ptr_map);
  17844. }
  17845. assert(!RelevantExpr && "RelevantExpr is expected to be nullptr");
  17846. RelevantExpr = TE;
  17847. }
  17848. // Record the component - we don't have any declaration associated.
  17849. Components.emplace_back(AE, nullptr, IsNonContiguous);
  17850. return RelevantExpr || Visit(E);
  17851. }
  17852. bool VisitOMPArraySectionExpr(OMPArraySectionExpr *OASE) {
  17853. // After OMP 5.0 Array section in reduction clause will be implicitly
  17854. // mapped
  17855. assert(!(SemaRef.getLangOpts().OpenMP < 50 && NoDiagnose) &&
  17856. "Array sections cannot be implicitly mapped.");
  17857. Expr *E = OASE->getBase()->IgnoreParenImpCasts();
  17858. QualType CurType =
  17859. OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
  17860. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
  17861. // If the type of a list item is a reference to a type T then the type
  17862. // will be considered to be T for all purposes of this clause.
  17863. if (CurType->isReferenceType())
  17864. CurType = CurType->getPointeeType();
  17865. bool IsPointer = CurType->isAnyPointerType();
  17866. if (!IsPointer && !CurType->isArrayType()) {
  17867. SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
  17868. << 0 << OASE->getSourceRange();
  17869. return false;
  17870. }
  17871. bool NotWhole =
  17872. checkArrayExpressionDoesNotReferToWholeSize(SemaRef, OASE, CurType);
  17873. bool NotUnity =
  17874. checkArrayExpressionDoesNotReferToUnitySize(SemaRef, OASE, CurType);
  17875. if (AllowWholeSizeArraySection) {
  17876. // Any array section is currently allowed. Allowing a whole size array
  17877. // section implies allowing a unity array section as well.
  17878. //
  17879. // If this array section refers to the whole dimension we can still
  17880. // accept other array sections before this one, except if the base is a
  17881. // pointer. Otherwise, only unitary sections are accepted.
  17882. if (NotWhole || IsPointer)
  17883. AllowWholeSizeArraySection = false;
  17884. } else if (DKind == OMPD_target_update &&
  17885. SemaRef.getLangOpts().OpenMP >= 50) {
  17886. if (IsPointer && !AllowAnotherPtr)
  17887. SemaRef.Diag(ELoc, diag::err_omp_section_length_undefined)
  17888. << /*array of unknown bound */ 1;
  17889. else
  17890. IsNonContiguous = true;
  17891. } else if (AllowUnitySizeArraySection && NotUnity) {
  17892. // A unity or whole array section is not allowed and that is not
  17893. // compatible with the properties of the current array section.
  17894. if (NoDiagnose)
  17895. return false;
  17896. SemaRef.Diag(ELoc,
  17897. diag::err_array_section_does_not_specify_contiguous_storage)
  17898. << OASE->getSourceRange();
  17899. return false;
  17900. }
  17901. if (IsPointer)
  17902. AllowAnotherPtr = false;
  17903. if (const auto *TE = dyn_cast<CXXThisExpr>(E)) {
  17904. Expr::EvalResult ResultR;
  17905. Expr::EvalResult ResultL;
  17906. if (!OASE->getLength()->isValueDependent() &&
  17907. OASE->getLength()->EvaluateAsInt(ResultR, SemaRef.getASTContext()) &&
  17908. !ResultR.Val.getInt().isOne()) {
  17909. SemaRef.Diag(OASE->getLength()->getExprLoc(),
  17910. diag::err_omp_invalid_map_this_expr);
  17911. SemaRef.Diag(OASE->getLength()->getExprLoc(),
  17912. diag::note_omp_invalid_length_on_this_ptr_mapping);
  17913. }
  17914. if (OASE->getLowerBound() && !OASE->getLowerBound()->isValueDependent() &&
  17915. OASE->getLowerBound()->EvaluateAsInt(ResultL,
  17916. SemaRef.getASTContext()) &&
  17917. !ResultL.Val.getInt().isZero()) {
  17918. SemaRef.Diag(OASE->getLowerBound()->getExprLoc(),
  17919. diag::err_omp_invalid_map_this_expr);
  17920. SemaRef.Diag(OASE->getLowerBound()->getExprLoc(),
  17921. diag::note_omp_invalid_lower_bound_on_this_ptr_mapping);
  17922. }
  17923. assert(!RelevantExpr && "RelevantExpr is expected to be nullptr");
  17924. RelevantExpr = TE;
  17925. }
  17926. // Record the component - we don't have any declaration associated.
  17927. Components.emplace_back(OASE, nullptr, /*IsNonContiguous=*/false);
  17928. return RelevantExpr || Visit(E);
  17929. }
  17930. bool VisitOMPArrayShapingExpr(OMPArrayShapingExpr *E) {
  17931. Expr *Base = E->getBase();
  17932. // Record the component - we don't have any declaration associated.
  17933. Components.emplace_back(E, nullptr, IsNonContiguous);
  17934. return Visit(Base->IgnoreParenImpCasts());
  17935. }
  17936. bool VisitUnaryOperator(UnaryOperator *UO) {
  17937. if (SemaRef.getLangOpts().OpenMP < 50 || !UO->isLValue() ||
  17938. UO->getOpcode() != UO_Deref) {
  17939. emitErrorMsg();
  17940. return false;
  17941. }
  17942. if (!RelevantExpr) {
  17943. // Record the component if haven't found base decl.
  17944. Components.emplace_back(UO, nullptr, /*IsNonContiguous=*/false);
  17945. }
  17946. return RelevantExpr || Visit(UO->getSubExpr()->IgnoreParenImpCasts());
  17947. }
  17948. bool VisitBinaryOperator(BinaryOperator *BO) {
  17949. if (SemaRef.getLangOpts().OpenMP < 50 || !BO->getType()->isPointerType()) {
  17950. emitErrorMsg();
  17951. return false;
  17952. }
  17953. // Pointer arithmetic is the only thing we expect to happen here so after we
  17954. // make sure the binary operator is a pointer type, the we only thing need
  17955. // to to is to visit the subtree that has the same type as root (so that we
  17956. // know the other subtree is just an offset)
  17957. Expr *LE = BO->getLHS()->IgnoreParenImpCasts();
  17958. Expr *RE = BO->getRHS()->IgnoreParenImpCasts();
  17959. Components.emplace_back(BO, nullptr, false);
  17960. assert((LE->getType().getTypePtr() == BO->getType().getTypePtr() ||
  17961. RE->getType().getTypePtr() == BO->getType().getTypePtr()) &&
  17962. "Either LHS or RHS have base decl inside");
  17963. if (BO->getType().getTypePtr() == LE->getType().getTypePtr())
  17964. return RelevantExpr || Visit(LE);
  17965. return RelevantExpr || Visit(RE);
  17966. }
  17967. bool VisitCXXThisExpr(CXXThisExpr *CTE) {
  17968. assert(!RelevantExpr && "RelevantExpr is expected to be nullptr");
  17969. RelevantExpr = CTE;
  17970. Components.emplace_back(CTE, nullptr, IsNonContiguous);
  17971. return true;
  17972. }
  17973. bool VisitCXXOperatorCallExpr(CXXOperatorCallExpr *COCE) {
  17974. assert(!RelevantExpr && "RelevantExpr is expected to be nullptr");
  17975. Components.emplace_back(COCE, nullptr, IsNonContiguous);
  17976. return true;
  17977. }
  17978. bool VisitOpaqueValueExpr(OpaqueValueExpr *E) {
  17979. Expr *Source = E->getSourceExpr();
  17980. if (!Source) {
  17981. emitErrorMsg();
  17982. return false;
  17983. }
  17984. return Visit(Source);
  17985. }
  17986. bool VisitStmt(Stmt *) {
  17987. emitErrorMsg();
  17988. return false;
  17989. }
  17990. const Expr *getFoundBase() const { return RelevantExpr; }
  17991. explicit MapBaseChecker(
  17992. Sema &SemaRef, OpenMPClauseKind CKind, OpenMPDirectiveKind DKind,
  17993. OMPClauseMappableExprCommon::MappableExprComponentList &Components,
  17994. bool NoDiagnose, SourceLocation &ELoc, SourceRange &ERange)
  17995. : SemaRef(SemaRef), CKind(CKind), DKind(DKind), Components(Components),
  17996. NoDiagnose(NoDiagnose), ELoc(ELoc), ERange(ERange) {}
  17997. };
  17998. } // namespace
  17999. /// Return the expression of the base of the mappable expression or null if it
  18000. /// cannot be determined and do all the necessary checks to see if the
  18001. /// expression is valid as a standalone mappable expression. In the process,
  18002. /// record all the components of the expression.
  18003. static const Expr *checkMapClauseExpressionBase(
  18004. Sema &SemaRef, Expr *E,
  18005. OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
  18006. OpenMPClauseKind CKind, OpenMPDirectiveKind DKind, bool NoDiagnose) {
  18007. SourceLocation ELoc = E->getExprLoc();
  18008. SourceRange ERange = E->getSourceRange();
  18009. MapBaseChecker Checker(SemaRef, CKind, DKind, CurComponents, NoDiagnose, ELoc,
  18010. ERange);
  18011. if (Checker.Visit(E->IgnoreParens())) {
  18012. // Check if the highest dimension array section has length specified
  18013. if (SemaRef.getLangOpts().OpenMP >= 50 && !CurComponents.empty() &&
  18014. (CKind == OMPC_to || CKind == OMPC_from)) {
  18015. auto CI = CurComponents.rbegin();
  18016. auto CE = CurComponents.rend();
  18017. for (; CI != CE; ++CI) {
  18018. const auto *OASE =
  18019. dyn_cast<OMPArraySectionExpr>(CI->getAssociatedExpression());
  18020. if (!OASE)
  18021. continue;
  18022. if (OASE && OASE->getLength())
  18023. break;
  18024. SemaRef.Diag(ELoc, diag::err_array_section_does_not_specify_length)
  18025. << ERange;
  18026. }
  18027. }
  18028. return Checker.getFoundBase();
  18029. }
  18030. return nullptr;
  18031. }
  18032. // Return true if expression E associated with value VD has conflicts with other
  18033. // map information.
  18034. static bool checkMapConflicts(
  18035. Sema &SemaRef, DSAStackTy *DSAS, const ValueDecl *VD, const Expr *E,
  18036. bool CurrentRegionOnly,
  18037. OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
  18038. OpenMPClauseKind CKind) {
  18039. assert(VD && E);
  18040. SourceLocation ELoc = E->getExprLoc();
  18041. SourceRange ERange = E->getSourceRange();
  18042. // In order to easily check the conflicts we need to match each component of
  18043. // the expression under test with the components of the expressions that are
  18044. // already in the stack.
  18045. assert(!CurComponents.empty() && "Map clause expression with no components!");
  18046. assert(CurComponents.back().getAssociatedDeclaration() == VD &&
  18047. "Map clause expression with unexpected base!");
  18048. // Variables to help detecting enclosing problems in data environment nests.
  18049. bool IsEnclosedByDataEnvironmentExpr = false;
  18050. const Expr *EnclosingExpr = nullptr;
  18051. bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
  18052. VD, CurrentRegionOnly,
  18053. [&IsEnclosedByDataEnvironmentExpr, &SemaRef, VD, CurrentRegionOnly, ELoc,
  18054. ERange, CKind, &EnclosingExpr,
  18055. CurComponents](OMPClauseMappableExprCommon::MappableExprComponentListRef
  18056. StackComponents,
  18057. OpenMPClauseKind Kind) {
  18058. if (CKind == Kind && SemaRef.LangOpts.OpenMP >= 50)
  18059. return false;
  18060. assert(!StackComponents.empty() &&
  18061. "Map clause expression with no components!");
  18062. assert(StackComponents.back().getAssociatedDeclaration() == VD &&
  18063. "Map clause expression with unexpected base!");
  18064. (void)VD;
  18065. // The whole expression in the stack.
  18066. const Expr *RE = StackComponents.front().getAssociatedExpression();
  18067. // Expressions must start from the same base. Here we detect at which
  18068. // point both expressions diverge from each other and see if we can
  18069. // detect if the memory referred to both expressions is contiguous and
  18070. // do not overlap.
  18071. auto CI = CurComponents.rbegin();
  18072. auto CE = CurComponents.rend();
  18073. auto SI = StackComponents.rbegin();
  18074. auto SE = StackComponents.rend();
  18075. for (; CI != CE && SI != SE; ++CI, ++SI) {
  18076. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
  18077. // At most one list item can be an array item derived from a given
  18078. // variable in map clauses of the same construct.
  18079. if (CurrentRegionOnly &&
  18080. (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
  18081. isa<OMPArraySectionExpr>(CI->getAssociatedExpression()) ||
  18082. isa<OMPArrayShapingExpr>(CI->getAssociatedExpression())) &&
  18083. (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
  18084. isa<OMPArraySectionExpr>(SI->getAssociatedExpression()) ||
  18085. isa<OMPArrayShapingExpr>(SI->getAssociatedExpression()))) {
  18086. SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
  18087. diag::err_omp_multiple_array_items_in_map_clause)
  18088. << CI->getAssociatedExpression()->getSourceRange();
  18089. SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
  18090. diag::note_used_here)
  18091. << SI->getAssociatedExpression()->getSourceRange();
  18092. return true;
  18093. }
  18094. // Do both expressions have the same kind?
  18095. if (CI->getAssociatedExpression()->getStmtClass() !=
  18096. SI->getAssociatedExpression()->getStmtClass())
  18097. break;
  18098. // Are we dealing with different variables/fields?
  18099. if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
  18100. break;
  18101. }
  18102. // Check if the extra components of the expressions in the enclosing
  18103. // data environment are redundant for the current base declaration.
  18104. // If they are, the maps completely overlap, which is legal.
  18105. for (; SI != SE; ++SI) {
  18106. QualType Type;
  18107. if (const auto *ASE =
  18108. dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
  18109. Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
  18110. } else if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(
  18111. SI->getAssociatedExpression())) {
  18112. const Expr *E = OASE->getBase()->IgnoreParenImpCasts();
  18113. Type =
  18114. OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
  18115. } else if (const auto *OASE = dyn_cast<OMPArrayShapingExpr>(
  18116. SI->getAssociatedExpression())) {
  18117. Type = OASE->getBase()->getType()->getPointeeType();
  18118. }
  18119. if (Type.isNull() || Type->isAnyPointerType() ||
  18120. checkArrayExpressionDoesNotReferToWholeSize(
  18121. SemaRef, SI->getAssociatedExpression(), Type))
  18122. break;
  18123. }
  18124. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
  18125. // List items of map clauses in the same construct must not share
  18126. // original storage.
  18127. //
  18128. // If the expressions are exactly the same or one is a subset of the
  18129. // other, it means they are sharing storage.
  18130. if (CI == CE && SI == SE) {
  18131. if (CurrentRegionOnly) {
  18132. if (CKind == OMPC_map) {
  18133. SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
  18134. } else {
  18135. assert(CKind == OMPC_to || CKind == OMPC_from);
  18136. SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
  18137. << ERange;
  18138. }
  18139. SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
  18140. << RE->getSourceRange();
  18141. return true;
  18142. }
  18143. // If we find the same expression in the enclosing data environment,
  18144. // that is legal.
  18145. IsEnclosedByDataEnvironmentExpr = true;
  18146. return false;
  18147. }
  18148. QualType DerivedType =
  18149. std::prev(CI)->getAssociatedDeclaration()->getType();
  18150. SourceLocation DerivedLoc =
  18151. std::prev(CI)->getAssociatedExpression()->getExprLoc();
  18152. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
  18153. // If the type of a list item is a reference to a type T then the type
  18154. // will be considered to be T for all purposes of this clause.
  18155. DerivedType = DerivedType.getNonReferenceType();
  18156. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
  18157. // A variable for which the type is pointer and an array section
  18158. // derived from that variable must not appear as list items of map
  18159. // clauses of the same construct.
  18160. //
  18161. // Also, cover one of the cases in:
  18162. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
  18163. // If any part of the original storage of a list item has corresponding
  18164. // storage in the device data environment, all of the original storage
  18165. // must have corresponding storage in the device data environment.
  18166. //
  18167. if (DerivedType->isAnyPointerType()) {
  18168. if (CI == CE || SI == SE) {
  18169. SemaRef.Diag(
  18170. DerivedLoc,
  18171. diag::err_omp_pointer_mapped_along_with_derived_section)
  18172. << DerivedLoc;
  18173. SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
  18174. << RE->getSourceRange();
  18175. return true;
  18176. }
  18177. if (CI->getAssociatedExpression()->getStmtClass() !=
  18178. SI->getAssociatedExpression()->getStmtClass() ||
  18179. CI->getAssociatedDeclaration()->getCanonicalDecl() ==
  18180. SI->getAssociatedDeclaration()->getCanonicalDecl()) {
  18181. assert(CI != CE && SI != SE);
  18182. SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_dereferenced)
  18183. << DerivedLoc;
  18184. SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
  18185. << RE->getSourceRange();
  18186. return true;
  18187. }
  18188. }
  18189. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
  18190. // List items of map clauses in the same construct must not share
  18191. // original storage.
  18192. //
  18193. // An expression is a subset of the other.
  18194. if (CurrentRegionOnly && (CI == CE || SI == SE)) {
  18195. if (CKind == OMPC_map) {
  18196. if (CI != CE || SI != SE) {
  18197. // Allow constructs like this: map(s, s.ptr[0:1]), where s.ptr is
  18198. // a pointer.
  18199. auto Begin =
  18200. CI != CE ? CurComponents.begin() : StackComponents.begin();
  18201. auto End = CI != CE ? CurComponents.end() : StackComponents.end();
  18202. auto It = Begin;
  18203. while (It != End && !It->getAssociatedDeclaration())
  18204. std::advance(It, 1);
  18205. assert(It != End &&
  18206. "Expected at least one component with the declaration.");
  18207. if (It != Begin && It->getAssociatedDeclaration()
  18208. ->getType()
  18209. .getCanonicalType()
  18210. ->isAnyPointerType()) {
  18211. IsEnclosedByDataEnvironmentExpr = false;
  18212. EnclosingExpr = nullptr;
  18213. return false;
  18214. }
  18215. }
  18216. SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
  18217. } else {
  18218. assert(CKind == OMPC_to || CKind == OMPC_from);
  18219. SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
  18220. << ERange;
  18221. }
  18222. SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
  18223. << RE->getSourceRange();
  18224. return true;
  18225. }
  18226. // The current expression uses the same base as other expression in the
  18227. // data environment but does not contain it completely.
  18228. if (!CurrentRegionOnly && SI != SE)
  18229. EnclosingExpr = RE;
  18230. // The current expression is a subset of the expression in the data
  18231. // environment.
  18232. IsEnclosedByDataEnvironmentExpr |=
  18233. (!CurrentRegionOnly && CI != CE && SI == SE);
  18234. return false;
  18235. });
  18236. if (CurrentRegionOnly)
  18237. return FoundError;
  18238. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
  18239. // If any part of the original storage of a list item has corresponding
  18240. // storage in the device data environment, all of the original storage must
  18241. // have corresponding storage in the device data environment.
  18242. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
  18243. // If a list item is an element of a structure, and a different element of
  18244. // the structure has a corresponding list item in the device data environment
  18245. // prior to a task encountering the construct associated with the map clause,
  18246. // then the list item must also have a corresponding list item in the device
  18247. // data environment prior to the task encountering the construct.
  18248. //
  18249. if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
  18250. SemaRef.Diag(ELoc,
  18251. diag::err_omp_original_storage_is_shared_and_does_not_contain)
  18252. << ERange;
  18253. SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
  18254. << EnclosingExpr->getSourceRange();
  18255. return true;
  18256. }
  18257. return FoundError;
  18258. }
  18259. // Look up the user-defined mapper given the mapper name and mapped type, and
  18260. // build a reference to it.
  18261. static ExprResult buildUserDefinedMapperRef(Sema &SemaRef, Scope *S,
  18262. CXXScopeSpec &MapperIdScopeSpec,
  18263. const DeclarationNameInfo &MapperId,
  18264. QualType Type,
  18265. Expr *UnresolvedMapper) {
  18266. if (MapperIdScopeSpec.isInvalid())
  18267. return ExprError();
  18268. // Get the actual type for the array type.
  18269. if (Type->isArrayType()) {
  18270. assert(Type->getAsArrayTypeUnsafe() && "Expect to get a valid array type");
  18271. Type = Type->getAsArrayTypeUnsafe()->getElementType().getCanonicalType();
  18272. }
  18273. // Find all user-defined mappers with the given MapperId.
  18274. SmallVector<UnresolvedSet<8>, 4> Lookups;
  18275. LookupResult Lookup(SemaRef, MapperId, Sema::LookupOMPMapperName);
  18276. Lookup.suppressDiagnostics();
  18277. if (S) {
  18278. while (S && SemaRef.LookupParsedName(Lookup, S, &MapperIdScopeSpec)) {
  18279. NamedDecl *D = Lookup.getRepresentativeDecl();
  18280. while (S && !S->isDeclScope(D))
  18281. S = S->getParent();
  18282. if (S)
  18283. S = S->getParent();
  18284. Lookups.emplace_back();
  18285. Lookups.back().append(Lookup.begin(), Lookup.end());
  18286. Lookup.clear();
  18287. }
  18288. } else if (auto *ULE = cast_or_null<UnresolvedLookupExpr>(UnresolvedMapper)) {
  18289. // Extract the user-defined mappers with the given MapperId.
  18290. Lookups.push_back(UnresolvedSet<8>());
  18291. for (NamedDecl *D : ULE->decls()) {
  18292. auto *DMD = cast<OMPDeclareMapperDecl>(D);
  18293. assert(DMD && "Expect valid OMPDeclareMapperDecl during instantiation.");
  18294. Lookups.back().addDecl(DMD);
  18295. }
  18296. }
  18297. // Defer the lookup for dependent types. The results will be passed through
  18298. // UnresolvedMapper on instantiation.
  18299. if (SemaRef.CurContext->isDependentContext() || Type->isDependentType() ||
  18300. Type->isInstantiationDependentType() ||
  18301. Type->containsUnexpandedParameterPack() ||
  18302. filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) {
  18303. return !D->isInvalidDecl() &&
  18304. (D->getType()->isDependentType() ||
  18305. D->getType()->isInstantiationDependentType() ||
  18306. D->getType()->containsUnexpandedParameterPack());
  18307. })) {
  18308. UnresolvedSet<8> URS;
  18309. for (const UnresolvedSet<8> &Set : Lookups) {
  18310. if (Set.empty())
  18311. continue;
  18312. URS.append(Set.begin(), Set.end());
  18313. }
  18314. return UnresolvedLookupExpr::Create(
  18315. SemaRef.Context, /*NamingClass=*/nullptr,
  18316. MapperIdScopeSpec.getWithLocInContext(SemaRef.Context), MapperId,
  18317. /*ADL=*/false, /*Overloaded=*/true, URS.begin(), URS.end());
  18318. }
  18319. SourceLocation Loc = MapperId.getLoc();
  18320. // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
  18321. // The type must be of struct, union or class type in C and C++
  18322. if (!Type->isStructureOrClassType() && !Type->isUnionType() &&
  18323. (MapperIdScopeSpec.isSet() || MapperId.getAsString() != "default")) {
  18324. SemaRef.Diag(Loc, diag::err_omp_mapper_wrong_type);
  18325. return ExprError();
  18326. }
  18327. // Perform argument dependent lookup.
  18328. if (SemaRef.getLangOpts().CPlusPlus && !MapperIdScopeSpec.isSet())
  18329. argumentDependentLookup(SemaRef, MapperId, Loc, Type, Lookups);
  18330. // Return the first user-defined mapper with the desired type.
  18331. if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
  18332. Lookups, [&SemaRef, Type](ValueDecl *D) -> ValueDecl * {
  18333. if (!D->isInvalidDecl() &&
  18334. SemaRef.Context.hasSameType(D->getType(), Type))
  18335. return D;
  18336. return nullptr;
  18337. }))
  18338. return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
  18339. // Find the first user-defined mapper with a type derived from the desired
  18340. // type.
  18341. if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
  18342. Lookups, [&SemaRef, Type, Loc](ValueDecl *D) -> ValueDecl * {
  18343. if (!D->isInvalidDecl() &&
  18344. SemaRef.IsDerivedFrom(Loc, Type, D->getType()) &&
  18345. !Type.isMoreQualifiedThan(D->getType()))
  18346. return D;
  18347. return nullptr;
  18348. })) {
  18349. CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
  18350. /*DetectVirtual=*/false);
  18351. if (SemaRef.IsDerivedFrom(Loc, Type, VD->getType(), Paths)) {
  18352. if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
  18353. VD->getType().getUnqualifiedType()))) {
  18354. if (SemaRef.CheckBaseClassAccess(
  18355. Loc, VD->getType(), Type, Paths.front(),
  18356. /*DiagID=*/0) != Sema::AR_inaccessible) {
  18357. return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
  18358. }
  18359. }
  18360. }
  18361. }
  18362. // Report error if a mapper is specified, but cannot be found.
  18363. if (MapperIdScopeSpec.isSet() || MapperId.getAsString() != "default") {
  18364. SemaRef.Diag(Loc, diag::err_omp_invalid_mapper)
  18365. << Type << MapperId.getName();
  18366. return ExprError();
  18367. }
  18368. return ExprEmpty();
  18369. }
  18370. namespace {
  18371. // Utility struct that gathers all the related lists associated with a mappable
  18372. // expression.
  18373. struct MappableVarListInfo {
  18374. // The list of expressions.
  18375. ArrayRef<Expr *> VarList;
  18376. // The list of processed expressions.
  18377. SmallVector<Expr *, 16> ProcessedVarList;
  18378. // The mappble components for each expression.
  18379. OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
  18380. // The base declaration of the variable.
  18381. SmallVector<ValueDecl *, 16> VarBaseDeclarations;
  18382. // The reference to the user-defined mapper associated with every expression.
  18383. SmallVector<Expr *, 16> UDMapperList;
  18384. MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
  18385. // We have a list of components and base declarations for each entry in the
  18386. // variable list.
  18387. VarComponents.reserve(VarList.size());
  18388. VarBaseDeclarations.reserve(VarList.size());
  18389. }
  18390. };
  18391. } // namespace
  18392. // Check the validity of the provided variable list for the provided clause kind
  18393. // \a CKind. In the check process the valid expressions, mappable expression
  18394. // components, variables, and user-defined mappers are extracted and used to
  18395. // fill \a ProcessedVarList, \a VarComponents, \a VarBaseDeclarations, and \a
  18396. // UDMapperList in MVLI. \a MapType, \a IsMapTypeImplicit, \a MapperIdScopeSpec,
  18397. // and \a MapperId are expected to be valid if the clause kind is 'map'.
  18398. static void checkMappableExpressionList(
  18399. Sema &SemaRef, DSAStackTy *DSAS, OpenMPClauseKind CKind,
  18400. MappableVarListInfo &MVLI, SourceLocation StartLoc,
  18401. CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo MapperId,
  18402. ArrayRef<Expr *> UnresolvedMappers,
  18403. OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
  18404. ArrayRef<OpenMPMapModifierKind> Modifiers = None,
  18405. bool IsMapTypeImplicit = false, bool NoDiagnose = false) {
  18406. // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
  18407. assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
  18408. "Unexpected clause kind with mappable expressions!");
  18409. // If the identifier of user-defined mapper is not specified, it is "default".
  18410. // We do not change the actual name in this clause to distinguish whether a
  18411. // mapper is specified explicitly, i.e., it is not explicitly specified when
  18412. // MapperId.getName() is empty.
  18413. if (!MapperId.getName() || MapperId.getName().isEmpty()) {
  18414. auto &DeclNames = SemaRef.getASTContext().DeclarationNames;
  18415. MapperId.setName(DeclNames.getIdentifier(
  18416. &SemaRef.getASTContext().Idents.get("default")));
  18417. MapperId.setLoc(StartLoc);
  18418. }
  18419. // Iterators to find the current unresolved mapper expression.
  18420. auto UMIt = UnresolvedMappers.begin(), UMEnd = UnresolvedMappers.end();
  18421. bool UpdateUMIt = false;
  18422. Expr *UnresolvedMapper = nullptr;
  18423. bool HasHoldModifier =
  18424. llvm::is_contained(Modifiers, OMPC_MAP_MODIFIER_ompx_hold);
  18425. // Keep track of the mappable components and base declarations in this clause.
  18426. // Each entry in the list is going to have a list of components associated. We
  18427. // record each set of the components so that we can build the clause later on.
  18428. // In the end we should have the same amount of declarations and component
  18429. // lists.
  18430. for (Expr *RE : MVLI.VarList) {
  18431. assert(RE && "Null expr in omp to/from/map clause");
  18432. SourceLocation ELoc = RE->getExprLoc();
  18433. // Find the current unresolved mapper expression.
  18434. if (UpdateUMIt && UMIt != UMEnd) {
  18435. UMIt++;
  18436. assert(
  18437. UMIt != UMEnd &&
  18438. "Expect the size of UnresolvedMappers to match with that of VarList");
  18439. }
  18440. UpdateUMIt = true;
  18441. if (UMIt != UMEnd)
  18442. UnresolvedMapper = *UMIt;
  18443. const Expr *VE = RE->IgnoreParenLValueCasts();
  18444. if (VE->isValueDependent() || VE->isTypeDependent() ||
  18445. VE->isInstantiationDependent() ||
  18446. VE->containsUnexpandedParameterPack()) {
  18447. // Try to find the associated user-defined mapper.
  18448. ExprResult ER = buildUserDefinedMapperRef(
  18449. SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
  18450. VE->getType().getCanonicalType(), UnresolvedMapper);
  18451. if (ER.isInvalid())
  18452. continue;
  18453. MVLI.UDMapperList.push_back(ER.get());
  18454. // We can only analyze this information once the missing information is
  18455. // resolved.
  18456. MVLI.ProcessedVarList.push_back(RE);
  18457. continue;
  18458. }
  18459. Expr *SimpleExpr = RE->IgnoreParenCasts();
  18460. if (!RE->isLValue()) {
  18461. if (SemaRef.getLangOpts().OpenMP < 50) {
  18462. SemaRef.Diag(
  18463. ELoc, diag::err_omp_expected_named_var_member_or_array_expression)
  18464. << RE->getSourceRange();
  18465. } else {
  18466. SemaRef.Diag(ELoc, diag::err_omp_non_lvalue_in_map_or_motion_clauses)
  18467. << getOpenMPClauseName(CKind) << RE->getSourceRange();
  18468. }
  18469. continue;
  18470. }
  18471. OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
  18472. ValueDecl *CurDeclaration = nullptr;
  18473. // Obtain the array or member expression bases if required. Also, fill the
  18474. // components array with all the components identified in the process.
  18475. const Expr *BE =
  18476. checkMapClauseExpressionBase(SemaRef, SimpleExpr, CurComponents, CKind,
  18477. DSAS->getCurrentDirective(), NoDiagnose);
  18478. if (!BE)
  18479. continue;
  18480. assert(!CurComponents.empty() &&
  18481. "Invalid mappable expression information.");
  18482. if (const auto *TE = dyn_cast<CXXThisExpr>(BE)) {
  18483. // Add store "this" pointer to class in DSAStackTy for future checking
  18484. DSAS->addMappedClassesQualTypes(TE->getType());
  18485. // Try to find the associated user-defined mapper.
  18486. ExprResult ER = buildUserDefinedMapperRef(
  18487. SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
  18488. VE->getType().getCanonicalType(), UnresolvedMapper);
  18489. if (ER.isInvalid())
  18490. continue;
  18491. MVLI.UDMapperList.push_back(ER.get());
  18492. // Skip restriction checking for variable or field declarations
  18493. MVLI.ProcessedVarList.push_back(RE);
  18494. MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
  18495. MVLI.VarComponents.back().append(CurComponents.begin(),
  18496. CurComponents.end());
  18497. MVLI.VarBaseDeclarations.push_back(nullptr);
  18498. continue;
  18499. }
  18500. // For the following checks, we rely on the base declaration which is
  18501. // expected to be associated with the last component. The declaration is
  18502. // expected to be a variable or a field (if 'this' is being mapped).
  18503. CurDeclaration = CurComponents.back().getAssociatedDeclaration();
  18504. assert(CurDeclaration && "Null decl on map clause.");
  18505. assert(
  18506. CurDeclaration->isCanonicalDecl() &&
  18507. "Expecting components to have associated only canonical declarations.");
  18508. auto *VD = dyn_cast<VarDecl>(CurDeclaration);
  18509. const auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
  18510. assert((VD || FD) && "Only variables or fields are expected here!");
  18511. (void)FD;
  18512. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
  18513. // threadprivate variables cannot appear in a map clause.
  18514. // OpenMP 4.5 [2.10.5, target update Construct]
  18515. // threadprivate variables cannot appear in a from clause.
  18516. if (VD && DSAS->isThreadPrivate(VD)) {
  18517. if (NoDiagnose)
  18518. continue;
  18519. DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
  18520. SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
  18521. << getOpenMPClauseName(CKind);
  18522. reportOriginalDsa(SemaRef, DSAS, VD, DVar);
  18523. continue;
  18524. }
  18525. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
  18526. // A list item cannot appear in both a map clause and a data-sharing
  18527. // attribute clause on the same construct.
  18528. // Check conflicts with other map clause expressions. We check the conflicts
  18529. // with the current construct separately from the enclosing data
  18530. // environment, because the restrictions are different. We only have to
  18531. // check conflicts across regions for the map clauses.
  18532. if (checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
  18533. /*CurrentRegionOnly=*/true, CurComponents, CKind))
  18534. break;
  18535. if (CKind == OMPC_map &&
  18536. (SemaRef.getLangOpts().OpenMP <= 45 || StartLoc.isValid()) &&
  18537. checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
  18538. /*CurrentRegionOnly=*/false, CurComponents, CKind))
  18539. break;
  18540. // OpenMP 4.5 [2.10.5, target update Construct]
  18541. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
  18542. // If the type of a list item is a reference to a type T then the type will
  18543. // be considered to be T for all purposes of this clause.
  18544. auto I = llvm::find_if(
  18545. CurComponents,
  18546. [](const OMPClauseMappableExprCommon::MappableComponent &MC) {
  18547. return MC.getAssociatedDeclaration();
  18548. });
  18549. assert(I != CurComponents.end() && "Null decl on map clause.");
  18550. (void)I;
  18551. QualType Type;
  18552. auto *ASE = dyn_cast<ArraySubscriptExpr>(VE->IgnoreParens());
  18553. auto *OASE = dyn_cast<OMPArraySectionExpr>(VE->IgnoreParens());
  18554. auto *OAShE = dyn_cast<OMPArrayShapingExpr>(VE->IgnoreParens());
  18555. if (ASE) {
  18556. Type = ASE->getType().getNonReferenceType();
  18557. } else if (OASE) {
  18558. QualType BaseType =
  18559. OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
  18560. if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
  18561. Type = ATy->getElementType();
  18562. else
  18563. Type = BaseType->getPointeeType();
  18564. Type = Type.getNonReferenceType();
  18565. } else if (OAShE) {
  18566. Type = OAShE->getBase()->getType()->getPointeeType();
  18567. } else {
  18568. Type = VE->getType();
  18569. }
  18570. // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
  18571. // A list item in a to or from clause must have a mappable type.
  18572. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
  18573. // A list item must have a mappable type.
  18574. if (!checkTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
  18575. DSAS, Type, /*FullCheck=*/true))
  18576. continue;
  18577. if (CKind == OMPC_map) {
  18578. // target enter data
  18579. // OpenMP [2.10.2, Restrictions, p. 99]
  18580. // A map-type must be specified in all map clauses and must be either
  18581. // to or alloc.
  18582. OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
  18583. if (DKind == OMPD_target_enter_data &&
  18584. !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
  18585. SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
  18586. << (IsMapTypeImplicit ? 1 : 0)
  18587. << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
  18588. << getOpenMPDirectiveName(DKind);
  18589. continue;
  18590. }
  18591. // target exit_data
  18592. // OpenMP [2.10.3, Restrictions, p. 102]
  18593. // A map-type must be specified in all map clauses and must be either
  18594. // from, release, or delete.
  18595. if (DKind == OMPD_target_exit_data &&
  18596. !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
  18597. MapType == OMPC_MAP_delete)) {
  18598. SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
  18599. << (IsMapTypeImplicit ? 1 : 0)
  18600. << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
  18601. << getOpenMPDirectiveName(DKind);
  18602. continue;
  18603. }
  18604. // The 'ompx_hold' modifier is specifically intended to be used on a
  18605. // 'target' or 'target data' directive to prevent data from being unmapped
  18606. // during the associated statement. It is not permitted on a 'target
  18607. // enter data' or 'target exit data' directive, which have no associated
  18608. // statement.
  18609. if ((DKind == OMPD_target_enter_data || DKind == OMPD_target_exit_data) &&
  18610. HasHoldModifier) {
  18611. SemaRef.Diag(StartLoc,
  18612. diag::err_omp_invalid_map_type_modifier_for_directive)
  18613. << getOpenMPSimpleClauseTypeName(OMPC_map,
  18614. OMPC_MAP_MODIFIER_ompx_hold)
  18615. << getOpenMPDirectiveName(DKind);
  18616. continue;
  18617. }
  18618. // target, target data
  18619. // OpenMP 5.0 [2.12.2, Restrictions, p. 163]
  18620. // OpenMP 5.0 [2.12.5, Restrictions, p. 174]
  18621. // A map-type in a map clause must be to, from, tofrom or alloc
  18622. if ((DKind == OMPD_target_data ||
  18623. isOpenMPTargetExecutionDirective(DKind)) &&
  18624. !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_from ||
  18625. MapType == OMPC_MAP_tofrom || MapType == OMPC_MAP_alloc)) {
  18626. SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
  18627. << (IsMapTypeImplicit ? 1 : 0)
  18628. << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
  18629. << getOpenMPDirectiveName(DKind);
  18630. continue;
  18631. }
  18632. // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
  18633. // A list item cannot appear in both a map clause and a data-sharing
  18634. // attribute clause on the same construct
  18635. //
  18636. // OpenMP 5.0 [2.19.7.1, Restrictions, p.7]
  18637. // A list item cannot appear in both a map clause and a data-sharing
  18638. // attribute clause on the same construct unless the construct is a
  18639. // combined construct.
  18640. if (VD && ((SemaRef.LangOpts.OpenMP <= 45 &&
  18641. isOpenMPTargetExecutionDirective(DKind)) ||
  18642. DKind == OMPD_target)) {
  18643. DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
  18644. if (isOpenMPPrivate(DVar.CKind)) {
  18645. SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
  18646. << getOpenMPClauseName(DVar.CKind)
  18647. << getOpenMPClauseName(OMPC_map)
  18648. << getOpenMPDirectiveName(DSAS->getCurrentDirective());
  18649. reportOriginalDsa(SemaRef, DSAS, CurDeclaration, DVar);
  18650. continue;
  18651. }
  18652. }
  18653. }
  18654. // Try to find the associated user-defined mapper.
  18655. ExprResult ER = buildUserDefinedMapperRef(
  18656. SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
  18657. Type.getCanonicalType(), UnresolvedMapper);
  18658. if (ER.isInvalid())
  18659. continue;
  18660. MVLI.UDMapperList.push_back(ER.get());
  18661. // Save the current expression.
  18662. MVLI.ProcessedVarList.push_back(RE);
  18663. // Store the components in the stack so that they can be used to check
  18664. // against other clauses later on.
  18665. DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
  18666. /*WhereFoundClauseKind=*/OMPC_map);
  18667. // Save the components and declaration to create the clause. For purposes of
  18668. // the clause creation, any component list that has has base 'this' uses
  18669. // null as base declaration.
  18670. MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
  18671. MVLI.VarComponents.back().append(CurComponents.begin(),
  18672. CurComponents.end());
  18673. MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
  18674. : CurDeclaration);
  18675. }
  18676. }
  18677. OMPClause *Sema::ActOnOpenMPMapClause(
  18678. ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
  18679. ArrayRef<SourceLocation> MapTypeModifiersLoc,
  18680. CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId,
  18681. OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, SourceLocation MapLoc,
  18682. SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
  18683. const OMPVarListLocTy &Locs, bool NoDiagnose,
  18684. ArrayRef<Expr *> UnresolvedMappers) {
  18685. OpenMPMapModifierKind Modifiers[] = {
  18686. OMPC_MAP_MODIFIER_unknown, OMPC_MAP_MODIFIER_unknown,
  18687. OMPC_MAP_MODIFIER_unknown, OMPC_MAP_MODIFIER_unknown,
  18688. OMPC_MAP_MODIFIER_unknown};
  18689. SourceLocation ModifiersLoc[NumberOfOMPMapClauseModifiers];
  18690. // Process map-type-modifiers, flag errors for duplicate modifiers.
  18691. unsigned Count = 0;
  18692. for (unsigned I = 0, E = MapTypeModifiers.size(); I < E; ++I) {
  18693. if (MapTypeModifiers[I] != OMPC_MAP_MODIFIER_unknown &&
  18694. llvm::is_contained(Modifiers, MapTypeModifiers[I])) {
  18695. Diag(MapTypeModifiersLoc[I], diag::err_omp_duplicate_map_type_modifier);
  18696. continue;
  18697. }
  18698. assert(Count < NumberOfOMPMapClauseModifiers &&
  18699. "Modifiers exceed the allowed number of map type modifiers");
  18700. Modifiers[Count] = MapTypeModifiers[I];
  18701. ModifiersLoc[Count] = MapTypeModifiersLoc[I];
  18702. ++Count;
  18703. }
  18704. MappableVarListInfo MVLI(VarList);
  18705. checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, Locs.StartLoc,
  18706. MapperIdScopeSpec, MapperId, UnresolvedMappers,
  18707. MapType, Modifiers, IsMapTypeImplicit,
  18708. NoDiagnose);
  18709. // We need to produce a map clause even if we don't have variables so that
  18710. // other diagnostics related with non-existing map clauses are accurate.
  18711. return OMPMapClause::Create(Context, Locs, MVLI.ProcessedVarList,
  18712. MVLI.VarBaseDeclarations, MVLI.VarComponents,
  18713. MVLI.UDMapperList, Modifiers, ModifiersLoc,
  18714. MapperIdScopeSpec.getWithLocInContext(Context),
  18715. MapperId, MapType, IsMapTypeImplicit, MapLoc);
  18716. }
  18717. QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
  18718. TypeResult ParsedType) {
  18719. assert(ParsedType.isUsable());
  18720. QualType ReductionType = GetTypeFromParser(ParsedType.get());
  18721. if (ReductionType.isNull())
  18722. return QualType();
  18723. // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
  18724. // A type name in a declare reduction directive cannot be a function type, an
  18725. // array type, a reference type, or a type qualified with const, volatile or
  18726. // restrict.
  18727. if (ReductionType.hasQualifiers()) {
  18728. Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
  18729. return QualType();
  18730. }
  18731. if (ReductionType->isFunctionType()) {
  18732. Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
  18733. return QualType();
  18734. }
  18735. if (ReductionType->isReferenceType()) {
  18736. Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
  18737. return QualType();
  18738. }
  18739. if (ReductionType->isArrayType()) {
  18740. Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
  18741. return QualType();
  18742. }
  18743. return ReductionType;
  18744. }
  18745. Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
  18746. Scope *S, DeclContext *DC, DeclarationName Name,
  18747. ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
  18748. AccessSpecifier AS, Decl *PrevDeclInScope) {
  18749. SmallVector<Decl *, 8> Decls;
  18750. Decls.reserve(ReductionTypes.size());
  18751. LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
  18752. forRedeclarationInCurContext());
  18753. // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
  18754. // A reduction-identifier may not be re-declared in the current scope for the
  18755. // same type or for a type that is compatible according to the base language
  18756. // rules.
  18757. llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
  18758. OMPDeclareReductionDecl *PrevDRD = nullptr;
  18759. bool InCompoundScope = true;
  18760. if (S != nullptr) {
  18761. // Find previous declaration with the same name not referenced in other
  18762. // declarations.
  18763. FunctionScopeInfo *ParentFn = getEnclosingFunction();
  18764. InCompoundScope =
  18765. (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
  18766. LookupName(Lookup, S);
  18767. FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
  18768. /*AllowInlineNamespace=*/false);
  18769. llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
  18770. LookupResult::Filter Filter = Lookup.makeFilter();
  18771. while (Filter.hasNext()) {
  18772. auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
  18773. if (InCompoundScope) {
  18774. auto I = UsedAsPrevious.find(PrevDecl);
  18775. if (I == UsedAsPrevious.end())
  18776. UsedAsPrevious[PrevDecl] = false;
  18777. if (OMPDeclareReductionDecl *D = PrevDecl->getPrevDeclInScope())
  18778. UsedAsPrevious[D] = true;
  18779. }
  18780. PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
  18781. PrevDecl->getLocation();
  18782. }
  18783. Filter.done();
  18784. if (InCompoundScope) {
  18785. for (const auto &PrevData : UsedAsPrevious) {
  18786. if (!PrevData.second) {
  18787. PrevDRD = PrevData.first;
  18788. break;
  18789. }
  18790. }
  18791. }
  18792. } else if (PrevDeclInScope != nullptr) {
  18793. auto *PrevDRDInScope = PrevDRD =
  18794. cast<OMPDeclareReductionDecl>(PrevDeclInScope);
  18795. do {
  18796. PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
  18797. PrevDRDInScope->getLocation();
  18798. PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
  18799. } while (PrevDRDInScope != nullptr);
  18800. }
  18801. for (const auto &TyData : ReductionTypes) {
  18802. const auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
  18803. bool Invalid = false;
  18804. if (I != PreviousRedeclTypes.end()) {
  18805. Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
  18806. << TyData.first;
  18807. Diag(I->second, diag::note_previous_definition);
  18808. Invalid = true;
  18809. }
  18810. PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
  18811. auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
  18812. Name, TyData.first, PrevDRD);
  18813. DC->addDecl(DRD);
  18814. DRD->setAccess(AS);
  18815. Decls.push_back(DRD);
  18816. if (Invalid)
  18817. DRD->setInvalidDecl();
  18818. else
  18819. PrevDRD = DRD;
  18820. }
  18821. return DeclGroupPtrTy::make(
  18822. DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
  18823. }
  18824. void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
  18825. auto *DRD = cast<OMPDeclareReductionDecl>(D);
  18826. // Enter new function scope.
  18827. PushFunctionScope();
  18828. setFunctionHasBranchProtectedScope();
  18829. getCurFunction()->setHasOMPDeclareReductionCombiner();
  18830. if (S != nullptr)
  18831. PushDeclContext(S, DRD);
  18832. else
  18833. CurContext = DRD;
  18834. PushExpressionEvaluationContext(
  18835. ExpressionEvaluationContext::PotentiallyEvaluated);
  18836. QualType ReductionType = DRD->getType();
  18837. // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
  18838. // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
  18839. // uses semantics of argument handles by value, but it should be passed by
  18840. // reference. C lang does not support references, so pass all parameters as
  18841. // pointers.
  18842. // Create 'T omp_in;' variable.
  18843. VarDecl *OmpInParm =
  18844. buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
  18845. // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
  18846. // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
  18847. // uses semantics of argument handles by value, but it should be passed by
  18848. // reference. C lang does not support references, so pass all parameters as
  18849. // pointers.
  18850. // Create 'T omp_out;' variable.
  18851. VarDecl *OmpOutParm =
  18852. buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
  18853. if (S != nullptr) {
  18854. PushOnScopeChains(OmpInParm, S);
  18855. PushOnScopeChains(OmpOutParm, S);
  18856. } else {
  18857. DRD->addDecl(OmpInParm);
  18858. DRD->addDecl(OmpOutParm);
  18859. }
  18860. Expr *InE =
  18861. ::buildDeclRefExpr(*this, OmpInParm, ReductionType, D->getLocation());
  18862. Expr *OutE =
  18863. ::buildDeclRefExpr(*this, OmpOutParm, ReductionType, D->getLocation());
  18864. DRD->setCombinerData(InE, OutE);
  18865. }
  18866. void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
  18867. auto *DRD = cast<OMPDeclareReductionDecl>(D);
  18868. DiscardCleanupsInEvaluationContext();
  18869. PopExpressionEvaluationContext();
  18870. PopDeclContext();
  18871. PopFunctionScopeInfo();
  18872. if (Combiner != nullptr)
  18873. DRD->setCombiner(Combiner);
  18874. else
  18875. DRD->setInvalidDecl();
  18876. }
  18877. VarDecl *Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
  18878. auto *DRD = cast<OMPDeclareReductionDecl>(D);
  18879. // Enter new function scope.
  18880. PushFunctionScope();
  18881. setFunctionHasBranchProtectedScope();
  18882. if (S != nullptr)
  18883. PushDeclContext(S, DRD);
  18884. else
  18885. CurContext = DRD;
  18886. PushExpressionEvaluationContext(
  18887. ExpressionEvaluationContext::PotentiallyEvaluated);
  18888. QualType ReductionType = DRD->getType();
  18889. // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
  18890. // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
  18891. // uses semantics of argument handles by value, but it should be passed by
  18892. // reference. C lang does not support references, so pass all parameters as
  18893. // pointers.
  18894. // Create 'T omp_priv;' variable.
  18895. VarDecl *OmpPrivParm =
  18896. buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
  18897. // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
  18898. // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
  18899. // uses semantics of argument handles by value, but it should be passed by
  18900. // reference. C lang does not support references, so pass all parameters as
  18901. // pointers.
  18902. // Create 'T omp_orig;' variable.
  18903. VarDecl *OmpOrigParm =
  18904. buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
  18905. if (S != nullptr) {
  18906. PushOnScopeChains(OmpPrivParm, S);
  18907. PushOnScopeChains(OmpOrigParm, S);
  18908. } else {
  18909. DRD->addDecl(OmpPrivParm);
  18910. DRD->addDecl(OmpOrigParm);
  18911. }
  18912. Expr *OrigE =
  18913. ::buildDeclRefExpr(*this, OmpOrigParm, ReductionType, D->getLocation());
  18914. Expr *PrivE =
  18915. ::buildDeclRefExpr(*this, OmpPrivParm, ReductionType, D->getLocation());
  18916. DRD->setInitializerData(OrigE, PrivE);
  18917. return OmpPrivParm;
  18918. }
  18919. void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
  18920. VarDecl *OmpPrivParm) {
  18921. auto *DRD = cast<OMPDeclareReductionDecl>(D);
  18922. DiscardCleanupsInEvaluationContext();
  18923. PopExpressionEvaluationContext();
  18924. PopDeclContext();
  18925. PopFunctionScopeInfo();
  18926. if (Initializer != nullptr) {
  18927. DRD->setInitializer(Initializer, OMPDeclareReductionDecl::CallInit);
  18928. } else if (OmpPrivParm->hasInit()) {
  18929. DRD->setInitializer(OmpPrivParm->getInit(),
  18930. OmpPrivParm->isDirectInit()
  18931. ? OMPDeclareReductionDecl::DirectInit
  18932. : OMPDeclareReductionDecl::CopyInit);
  18933. } else {
  18934. DRD->setInvalidDecl();
  18935. }
  18936. }
  18937. Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
  18938. Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
  18939. for (Decl *D : DeclReductions.get()) {
  18940. if (IsValid) {
  18941. if (S)
  18942. PushOnScopeChains(cast<OMPDeclareReductionDecl>(D), S,
  18943. /*AddToContext=*/false);
  18944. } else {
  18945. D->setInvalidDecl();
  18946. }
  18947. }
  18948. return DeclReductions;
  18949. }
  18950. TypeResult Sema::ActOnOpenMPDeclareMapperVarDecl(Scope *S, Declarator &D) {
  18951. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  18952. QualType T = TInfo->getType();
  18953. if (D.isInvalidType())
  18954. return true;
  18955. if (getLangOpts().CPlusPlus) {
  18956. // Check that there are no default arguments (C++ only).
  18957. CheckExtraCXXDefaultArguments(D);
  18958. }
  18959. return CreateParsedType(T, TInfo);
  18960. }
  18961. QualType Sema::ActOnOpenMPDeclareMapperType(SourceLocation TyLoc,
  18962. TypeResult ParsedType) {
  18963. assert(ParsedType.isUsable() && "Expect usable parsed mapper type");
  18964. QualType MapperType = GetTypeFromParser(ParsedType.get());
  18965. assert(!MapperType.isNull() && "Expect valid mapper type");
  18966. // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
  18967. // The type must be of struct, union or class type in C and C++
  18968. if (!MapperType->isStructureOrClassType() && !MapperType->isUnionType()) {
  18969. Diag(TyLoc, diag::err_omp_mapper_wrong_type);
  18970. return QualType();
  18971. }
  18972. return MapperType;
  18973. }
  18974. Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareMapperDirective(
  18975. Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType,
  18976. SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS,
  18977. Expr *MapperVarRef, ArrayRef<OMPClause *> Clauses, Decl *PrevDeclInScope) {
  18978. LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPMapperName,
  18979. forRedeclarationInCurContext());
  18980. // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
  18981. // A mapper-identifier may not be redeclared in the current scope for the
  18982. // same type or for a type that is compatible according to the base language
  18983. // rules.
  18984. llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
  18985. OMPDeclareMapperDecl *PrevDMD = nullptr;
  18986. bool InCompoundScope = true;
  18987. if (S != nullptr) {
  18988. // Find previous declaration with the same name not referenced in other
  18989. // declarations.
  18990. FunctionScopeInfo *ParentFn = getEnclosingFunction();
  18991. InCompoundScope =
  18992. (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
  18993. LookupName(Lookup, S);
  18994. FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
  18995. /*AllowInlineNamespace=*/false);
  18996. llvm::DenseMap<OMPDeclareMapperDecl *, bool> UsedAsPrevious;
  18997. LookupResult::Filter Filter = Lookup.makeFilter();
  18998. while (Filter.hasNext()) {
  18999. auto *PrevDecl = cast<OMPDeclareMapperDecl>(Filter.next());
  19000. if (InCompoundScope) {
  19001. auto I = UsedAsPrevious.find(PrevDecl);
  19002. if (I == UsedAsPrevious.end())
  19003. UsedAsPrevious[PrevDecl] = false;
  19004. if (OMPDeclareMapperDecl *D = PrevDecl->getPrevDeclInScope())
  19005. UsedAsPrevious[D] = true;
  19006. }
  19007. PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
  19008. PrevDecl->getLocation();
  19009. }
  19010. Filter.done();
  19011. if (InCompoundScope) {
  19012. for (const auto &PrevData : UsedAsPrevious) {
  19013. if (!PrevData.second) {
  19014. PrevDMD = PrevData.first;
  19015. break;
  19016. }
  19017. }
  19018. }
  19019. } else if (PrevDeclInScope) {
  19020. auto *PrevDMDInScope = PrevDMD =
  19021. cast<OMPDeclareMapperDecl>(PrevDeclInScope);
  19022. do {
  19023. PreviousRedeclTypes[PrevDMDInScope->getType().getCanonicalType()] =
  19024. PrevDMDInScope->getLocation();
  19025. PrevDMDInScope = PrevDMDInScope->getPrevDeclInScope();
  19026. } while (PrevDMDInScope != nullptr);
  19027. }
  19028. const auto I = PreviousRedeclTypes.find(MapperType.getCanonicalType());
  19029. bool Invalid = false;
  19030. if (I != PreviousRedeclTypes.end()) {
  19031. Diag(StartLoc, diag::err_omp_declare_mapper_redefinition)
  19032. << MapperType << Name;
  19033. Diag(I->second, diag::note_previous_definition);
  19034. Invalid = true;
  19035. }
  19036. // Build expressions for implicit maps of data members with 'default'
  19037. // mappers.
  19038. SmallVector<OMPClause *, 4> ClausesWithImplicit(Clauses.begin(),
  19039. Clauses.end());
  19040. if (LangOpts.OpenMP >= 50)
  19041. processImplicitMapsWithDefaultMappers(*this, DSAStack, ClausesWithImplicit);
  19042. auto *DMD =
  19043. OMPDeclareMapperDecl::Create(Context, DC, StartLoc, Name, MapperType, VN,
  19044. ClausesWithImplicit, PrevDMD);
  19045. if (S)
  19046. PushOnScopeChains(DMD, S);
  19047. else
  19048. DC->addDecl(DMD);
  19049. DMD->setAccess(AS);
  19050. if (Invalid)
  19051. DMD->setInvalidDecl();
  19052. auto *VD = cast<DeclRefExpr>(MapperVarRef)->getDecl();
  19053. VD->setDeclContext(DMD);
  19054. VD->setLexicalDeclContext(DMD);
  19055. DMD->addDecl(VD);
  19056. DMD->setMapperVarRef(MapperVarRef);
  19057. return DeclGroupPtrTy::make(DeclGroupRef(DMD));
  19058. }
  19059. ExprResult
  19060. Sema::ActOnOpenMPDeclareMapperDirectiveVarDecl(Scope *S, QualType MapperType,
  19061. SourceLocation StartLoc,
  19062. DeclarationName VN) {
  19063. TypeSourceInfo *TInfo =
  19064. Context.getTrivialTypeSourceInfo(MapperType, StartLoc);
  19065. auto *VD = VarDecl::Create(Context, Context.getTranslationUnitDecl(),
  19066. StartLoc, StartLoc, VN.getAsIdentifierInfo(),
  19067. MapperType, TInfo, SC_None);
  19068. if (S)
  19069. PushOnScopeChains(VD, S, /*AddToContext=*/false);
  19070. Expr *E = buildDeclRefExpr(*this, VD, MapperType, StartLoc);
  19071. DSAStack->addDeclareMapperVarRef(E);
  19072. return E;
  19073. }
  19074. bool Sema::isOpenMPDeclareMapperVarDeclAllowed(const VarDecl *VD) const {
  19075. assert(LangOpts.OpenMP && "Expected OpenMP mode.");
  19076. const Expr *Ref = DSAStack->getDeclareMapperVarRef();
  19077. if (const auto *DRE = cast_or_null<DeclRefExpr>(Ref)) {
  19078. if (VD->getCanonicalDecl() == DRE->getDecl()->getCanonicalDecl())
  19079. return true;
  19080. if (VD->isUsableInConstantExpressions(Context))
  19081. return true;
  19082. return false;
  19083. }
  19084. return true;
  19085. }
  19086. const ValueDecl *Sema::getOpenMPDeclareMapperVarName() const {
  19087. assert(LangOpts.OpenMP && "Expected OpenMP mode.");
  19088. return cast<DeclRefExpr>(DSAStack->getDeclareMapperVarRef())->getDecl();
  19089. }
  19090. OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
  19091. SourceLocation StartLoc,
  19092. SourceLocation LParenLoc,
  19093. SourceLocation EndLoc) {
  19094. Expr *ValExpr = NumTeams;
  19095. Stmt *HelperValStmt = nullptr;
  19096. // OpenMP [teams Constrcut, Restrictions]
  19097. // The num_teams expression must evaluate to a positive integer value.
  19098. if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
  19099. /*StrictlyPositive=*/true))
  19100. return nullptr;
  19101. OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
  19102. OpenMPDirectiveKind CaptureRegion =
  19103. getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams, LangOpts.OpenMP);
  19104. if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
  19105. ValExpr = MakeFullExpr(ValExpr).get();
  19106. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  19107. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  19108. HelperValStmt = buildPreInits(Context, Captures);
  19109. }
  19110. return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion,
  19111. StartLoc, LParenLoc, EndLoc);
  19112. }
  19113. OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
  19114. SourceLocation StartLoc,
  19115. SourceLocation LParenLoc,
  19116. SourceLocation EndLoc) {
  19117. Expr *ValExpr = ThreadLimit;
  19118. Stmt *HelperValStmt = nullptr;
  19119. // OpenMP [teams Constrcut, Restrictions]
  19120. // The thread_limit expression must evaluate to a positive integer value.
  19121. if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
  19122. /*StrictlyPositive=*/true))
  19123. return nullptr;
  19124. OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
  19125. OpenMPDirectiveKind CaptureRegion = getOpenMPCaptureRegionForClause(
  19126. DKind, OMPC_thread_limit, LangOpts.OpenMP);
  19127. if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
  19128. ValExpr = MakeFullExpr(ValExpr).get();
  19129. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  19130. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  19131. HelperValStmt = buildPreInits(Context, Captures);
  19132. }
  19133. return new (Context) OMPThreadLimitClause(
  19134. ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
  19135. }
  19136. OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
  19137. SourceLocation StartLoc,
  19138. SourceLocation LParenLoc,
  19139. SourceLocation EndLoc) {
  19140. Expr *ValExpr = Priority;
  19141. Stmt *HelperValStmt = nullptr;
  19142. OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
  19143. // OpenMP [2.9.1, task Constrcut]
  19144. // The priority-value is a non-negative numerical scalar expression.
  19145. if (!isNonNegativeIntegerValue(
  19146. ValExpr, *this, OMPC_priority,
  19147. /*StrictlyPositive=*/false, /*BuildCapture=*/true,
  19148. DSAStack->getCurrentDirective(), &CaptureRegion, &HelperValStmt))
  19149. return nullptr;
  19150. return new (Context) OMPPriorityClause(ValExpr, HelperValStmt, CaptureRegion,
  19151. StartLoc, LParenLoc, EndLoc);
  19152. }
  19153. OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
  19154. SourceLocation StartLoc,
  19155. SourceLocation LParenLoc,
  19156. SourceLocation EndLoc) {
  19157. Expr *ValExpr = Grainsize;
  19158. Stmt *HelperValStmt = nullptr;
  19159. OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
  19160. // OpenMP [2.9.2, taskloop Constrcut]
  19161. // The parameter of the grainsize clause must be a positive integer
  19162. // expression.
  19163. if (!isNonNegativeIntegerValue(
  19164. ValExpr, *this, OMPC_grainsize,
  19165. /*StrictlyPositive=*/true, /*BuildCapture=*/true,
  19166. DSAStack->getCurrentDirective(), &CaptureRegion, &HelperValStmt))
  19167. return nullptr;
  19168. return new (Context) OMPGrainsizeClause(ValExpr, HelperValStmt, CaptureRegion,
  19169. StartLoc, LParenLoc, EndLoc);
  19170. }
  19171. OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
  19172. SourceLocation StartLoc,
  19173. SourceLocation LParenLoc,
  19174. SourceLocation EndLoc) {
  19175. Expr *ValExpr = NumTasks;
  19176. Stmt *HelperValStmt = nullptr;
  19177. OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
  19178. // OpenMP [2.9.2, taskloop Constrcut]
  19179. // The parameter of the num_tasks clause must be a positive integer
  19180. // expression.
  19181. if (!isNonNegativeIntegerValue(
  19182. ValExpr, *this, OMPC_num_tasks,
  19183. /*StrictlyPositive=*/true, /*BuildCapture=*/true,
  19184. DSAStack->getCurrentDirective(), &CaptureRegion, &HelperValStmt))
  19185. return nullptr;
  19186. return new (Context) OMPNumTasksClause(ValExpr, HelperValStmt, CaptureRegion,
  19187. StartLoc, LParenLoc, EndLoc);
  19188. }
  19189. OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
  19190. SourceLocation LParenLoc,
  19191. SourceLocation EndLoc) {
  19192. // OpenMP [2.13.2, critical construct, Description]
  19193. // ... where hint-expression is an integer constant expression that evaluates
  19194. // to a valid lock hint.
  19195. ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
  19196. if (HintExpr.isInvalid())
  19197. return nullptr;
  19198. return new (Context)
  19199. OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
  19200. }
  19201. /// Tries to find omp_event_handle_t type.
  19202. static bool findOMPEventHandleT(Sema &S, SourceLocation Loc,
  19203. DSAStackTy *Stack) {
  19204. QualType OMPEventHandleT = Stack->getOMPEventHandleT();
  19205. if (!OMPEventHandleT.isNull())
  19206. return true;
  19207. IdentifierInfo *II = &S.PP.getIdentifierTable().get("omp_event_handle_t");
  19208. ParsedType PT = S.getTypeName(*II, Loc, S.getCurScope());
  19209. if (!PT.getAsOpaquePtr() || PT.get().isNull()) {
  19210. S.Diag(Loc, diag::err_omp_implied_type_not_found) << "omp_event_handle_t";
  19211. return false;
  19212. }
  19213. Stack->setOMPEventHandleT(PT.get());
  19214. return true;
  19215. }
  19216. OMPClause *Sema::ActOnOpenMPDetachClause(Expr *Evt, SourceLocation StartLoc,
  19217. SourceLocation LParenLoc,
  19218. SourceLocation EndLoc) {
  19219. if (!Evt->isValueDependent() && !Evt->isTypeDependent() &&
  19220. !Evt->isInstantiationDependent() &&
  19221. !Evt->containsUnexpandedParameterPack()) {
  19222. if (!findOMPEventHandleT(*this, Evt->getExprLoc(), DSAStack))
  19223. return nullptr;
  19224. // OpenMP 5.0, 2.10.1 task Construct.
  19225. // event-handle is a variable of the omp_event_handle_t type.
  19226. auto *Ref = dyn_cast<DeclRefExpr>(Evt->IgnoreParenImpCasts());
  19227. if (!Ref) {
  19228. Diag(Evt->getExprLoc(), diag::err_omp_var_expected)
  19229. << "omp_event_handle_t" << 0 << Evt->getSourceRange();
  19230. return nullptr;
  19231. }
  19232. auto *VD = dyn_cast_or_null<VarDecl>(Ref->getDecl());
  19233. if (!VD) {
  19234. Diag(Evt->getExprLoc(), diag::err_omp_var_expected)
  19235. << "omp_event_handle_t" << 0 << Evt->getSourceRange();
  19236. return nullptr;
  19237. }
  19238. if (!Context.hasSameUnqualifiedType(DSAStack->getOMPEventHandleT(),
  19239. VD->getType()) ||
  19240. VD->getType().isConstant(Context)) {
  19241. Diag(Evt->getExprLoc(), diag::err_omp_var_expected)
  19242. << "omp_event_handle_t" << 1 << VD->getType()
  19243. << Evt->getSourceRange();
  19244. return nullptr;
  19245. }
  19246. // OpenMP 5.0, 2.10.1 task Construct
  19247. // [detach clause]... The event-handle will be considered as if it was
  19248. // specified on a firstprivate clause.
  19249. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, /*FromParent=*/false);
  19250. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
  19251. DVar.RefExpr) {
  19252. Diag(Evt->getExprLoc(), diag::err_omp_wrong_dsa)
  19253. << getOpenMPClauseName(DVar.CKind)
  19254. << getOpenMPClauseName(OMPC_firstprivate);
  19255. reportOriginalDsa(*this, DSAStack, VD, DVar);
  19256. return nullptr;
  19257. }
  19258. }
  19259. return new (Context) OMPDetachClause(Evt, StartLoc, LParenLoc, EndLoc);
  19260. }
  19261. OMPClause *Sema::ActOnOpenMPDistScheduleClause(
  19262. OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
  19263. SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
  19264. SourceLocation EndLoc) {
  19265. if (Kind == OMPC_DIST_SCHEDULE_unknown) {
  19266. std::string Values;
  19267. Values += "'";
  19268. Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
  19269. Values += "'";
  19270. Diag(KindLoc, diag::err_omp_unexpected_clause_value)
  19271. << Values << getOpenMPClauseName(OMPC_dist_schedule);
  19272. return nullptr;
  19273. }
  19274. Expr *ValExpr = ChunkSize;
  19275. Stmt *HelperValStmt = nullptr;
  19276. if (ChunkSize) {
  19277. if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
  19278. !ChunkSize->isInstantiationDependent() &&
  19279. !ChunkSize->containsUnexpandedParameterPack()) {
  19280. SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
  19281. ExprResult Val =
  19282. PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
  19283. if (Val.isInvalid())
  19284. return nullptr;
  19285. ValExpr = Val.get();
  19286. // OpenMP [2.7.1, Restrictions]
  19287. // chunk_size must be a loop invariant integer expression with a positive
  19288. // value.
  19289. if (Optional<llvm::APSInt> Result =
  19290. ValExpr->getIntegerConstantExpr(Context)) {
  19291. if (Result->isSigned() && !Result->isStrictlyPositive()) {
  19292. Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
  19293. << "dist_schedule" << ChunkSize->getSourceRange();
  19294. return nullptr;
  19295. }
  19296. } else if (getOpenMPCaptureRegionForClause(
  19297. DSAStack->getCurrentDirective(), OMPC_dist_schedule,
  19298. LangOpts.OpenMP) != OMPD_unknown &&
  19299. !CurContext->isDependentContext()) {
  19300. ValExpr = MakeFullExpr(ValExpr).get();
  19301. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  19302. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  19303. HelperValStmt = buildPreInits(Context, Captures);
  19304. }
  19305. }
  19306. }
  19307. return new (Context)
  19308. OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
  19309. Kind, ValExpr, HelperValStmt);
  19310. }
  19311. OMPClause *Sema::ActOnOpenMPDefaultmapClause(
  19312. OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
  19313. SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
  19314. SourceLocation KindLoc, SourceLocation EndLoc) {
  19315. if (getLangOpts().OpenMP < 50) {
  19316. if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom ||
  19317. Kind != OMPC_DEFAULTMAP_scalar) {
  19318. std::string Value;
  19319. SourceLocation Loc;
  19320. Value += "'";
  19321. if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
  19322. Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
  19323. OMPC_DEFAULTMAP_MODIFIER_tofrom);
  19324. Loc = MLoc;
  19325. } else {
  19326. Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
  19327. OMPC_DEFAULTMAP_scalar);
  19328. Loc = KindLoc;
  19329. }
  19330. Value += "'";
  19331. Diag(Loc, diag::err_omp_unexpected_clause_value)
  19332. << Value << getOpenMPClauseName(OMPC_defaultmap);
  19333. return nullptr;
  19334. }
  19335. } else {
  19336. bool isDefaultmapModifier = (M != OMPC_DEFAULTMAP_MODIFIER_unknown);
  19337. bool isDefaultmapKind = (Kind != OMPC_DEFAULTMAP_unknown) ||
  19338. (LangOpts.OpenMP >= 50 && KindLoc.isInvalid());
  19339. if (!isDefaultmapKind || !isDefaultmapModifier) {
  19340. StringRef KindValue = "'scalar', 'aggregate', 'pointer'";
  19341. if (LangOpts.OpenMP == 50) {
  19342. StringRef ModifierValue = "'alloc', 'from', 'to', 'tofrom', "
  19343. "'firstprivate', 'none', 'default'";
  19344. if (!isDefaultmapKind && isDefaultmapModifier) {
  19345. Diag(KindLoc, diag::err_omp_unexpected_clause_value)
  19346. << KindValue << getOpenMPClauseName(OMPC_defaultmap);
  19347. } else if (isDefaultmapKind && !isDefaultmapModifier) {
  19348. Diag(MLoc, diag::err_omp_unexpected_clause_value)
  19349. << ModifierValue << getOpenMPClauseName(OMPC_defaultmap);
  19350. } else {
  19351. Diag(MLoc, diag::err_omp_unexpected_clause_value)
  19352. << ModifierValue << getOpenMPClauseName(OMPC_defaultmap);
  19353. Diag(KindLoc, diag::err_omp_unexpected_clause_value)
  19354. << KindValue << getOpenMPClauseName(OMPC_defaultmap);
  19355. }
  19356. } else {
  19357. StringRef ModifierValue =
  19358. "'alloc', 'from', 'to', 'tofrom', "
  19359. "'firstprivate', 'none', 'default', 'present'";
  19360. if (!isDefaultmapKind && isDefaultmapModifier) {
  19361. Diag(KindLoc, diag::err_omp_unexpected_clause_value)
  19362. << KindValue << getOpenMPClauseName(OMPC_defaultmap);
  19363. } else if (isDefaultmapKind && !isDefaultmapModifier) {
  19364. Diag(MLoc, diag::err_omp_unexpected_clause_value)
  19365. << ModifierValue << getOpenMPClauseName(OMPC_defaultmap);
  19366. } else {
  19367. Diag(MLoc, diag::err_omp_unexpected_clause_value)
  19368. << ModifierValue << getOpenMPClauseName(OMPC_defaultmap);
  19369. Diag(KindLoc, diag::err_omp_unexpected_clause_value)
  19370. << KindValue << getOpenMPClauseName(OMPC_defaultmap);
  19371. }
  19372. }
  19373. return nullptr;
  19374. }
  19375. // OpenMP [5.0, 2.12.5, Restrictions, p. 174]
  19376. // At most one defaultmap clause for each category can appear on the
  19377. // directive.
  19378. if (DSAStack->checkDefaultmapCategory(Kind)) {
  19379. Diag(StartLoc, diag::err_omp_one_defaultmap_each_category);
  19380. return nullptr;
  19381. }
  19382. }
  19383. if (Kind == OMPC_DEFAULTMAP_unknown) {
  19384. // Variable category is not specified - mark all categories.
  19385. DSAStack->setDefaultDMAAttr(M, OMPC_DEFAULTMAP_aggregate, StartLoc);
  19386. DSAStack->setDefaultDMAAttr(M, OMPC_DEFAULTMAP_scalar, StartLoc);
  19387. DSAStack->setDefaultDMAAttr(M, OMPC_DEFAULTMAP_pointer, StartLoc);
  19388. } else {
  19389. DSAStack->setDefaultDMAAttr(M, Kind, StartLoc);
  19390. }
  19391. return new (Context)
  19392. OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
  19393. }
  19394. bool Sema::ActOnStartOpenMPDeclareTargetContext(
  19395. DeclareTargetContextInfo &DTCI) {
  19396. DeclContext *CurLexicalContext = getCurLexicalContext();
  19397. if (!CurLexicalContext->isFileContext() &&
  19398. !CurLexicalContext->isExternCContext() &&
  19399. !CurLexicalContext->isExternCXXContext() &&
  19400. !isa<CXXRecordDecl>(CurLexicalContext) &&
  19401. !isa<ClassTemplateDecl>(CurLexicalContext) &&
  19402. !isa<ClassTemplatePartialSpecializationDecl>(CurLexicalContext) &&
  19403. !isa<ClassTemplateSpecializationDecl>(CurLexicalContext)) {
  19404. Diag(DTCI.Loc, diag::err_omp_region_not_file_context);
  19405. return false;
  19406. }
  19407. DeclareTargetNesting.push_back(DTCI);
  19408. return true;
  19409. }
  19410. const Sema::DeclareTargetContextInfo
  19411. Sema::ActOnOpenMPEndDeclareTargetDirective() {
  19412. assert(!DeclareTargetNesting.empty() &&
  19413. "check isInOpenMPDeclareTargetContext() first!");
  19414. return DeclareTargetNesting.pop_back_val();
  19415. }
  19416. void Sema::ActOnFinishedOpenMPDeclareTargetContext(
  19417. DeclareTargetContextInfo &DTCI) {
  19418. for (auto &It : DTCI.ExplicitlyMapped)
  19419. ActOnOpenMPDeclareTargetName(It.first, It.second.Loc, It.second.MT, DTCI);
  19420. }
  19421. NamedDecl *Sema::lookupOpenMPDeclareTargetName(Scope *CurScope,
  19422. CXXScopeSpec &ScopeSpec,
  19423. const DeclarationNameInfo &Id) {
  19424. LookupResult Lookup(*this, Id, LookupOrdinaryName);
  19425. LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
  19426. if (Lookup.isAmbiguous())
  19427. return nullptr;
  19428. Lookup.suppressDiagnostics();
  19429. if (!Lookup.isSingleResult()) {
  19430. VarOrFuncDeclFilterCCC CCC(*this);
  19431. if (TypoCorrection Corrected =
  19432. CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, CCC,
  19433. CTK_ErrorRecovery)) {
  19434. diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
  19435. << Id.getName());
  19436. checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
  19437. return nullptr;
  19438. }
  19439. Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
  19440. return nullptr;
  19441. }
  19442. NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
  19443. if (!isa<VarDecl>(ND) && !isa<FunctionDecl>(ND) &&
  19444. !isa<FunctionTemplateDecl>(ND)) {
  19445. Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
  19446. return nullptr;
  19447. }
  19448. return ND;
  19449. }
  19450. void Sema::ActOnOpenMPDeclareTargetName(NamedDecl *ND, SourceLocation Loc,
  19451. OMPDeclareTargetDeclAttr::MapTypeTy MT,
  19452. DeclareTargetContextInfo &DTCI) {
  19453. assert((isa<VarDecl>(ND) || isa<FunctionDecl>(ND) ||
  19454. isa<FunctionTemplateDecl>(ND)) &&
  19455. "Expected variable, function or function template.");
  19456. // Diagnose marking after use as it may lead to incorrect diagnosis and
  19457. // codegen.
  19458. if (LangOpts.OpenMP >= 50 &&
  19459. (ND->isUsed(/*CheckUsedAttr=*/false) || ND->isReferenced()))
  19460. Diag(Loc, diag::warn_omp_declare_target_after_first_use);
  19461. // Explicit declare target lists have precedence.
  19462. const unsigned Level = -1;
  19463. auto *VD = cast<ValueDecl>(ND);
  19464. llvm::Optional<OMPDeclareTargetDeclAttr *> ActiveAttr =
  19465. OMPDeclareTargetDeclAttr::getActiveAttr(VD);
  19466. if (ActiveAttr.hasValue() && ActiveAttr.getValue()->getDevType() != DTCI.DT &&
  19467. ActiveAttr.getValue()->getLevel() == Level) {
  19468. Diag(Loc, diag::err_omp_device_type_mismatch)
  19469. << OMPDeclareTargetDeclAttr::ConvertDevTypeTyToStr(DTCI.DT)
  19470. << OMPDeclareTargetDeclAttr::ConvertDevTypeTyToStr(
  19471. ActiveAttr.getValue()->getDevType());
  19472. return;
  19473. }
  19474. if (ActiveAttr.hasValue() && ActiveAttr.getValue()->getMapType() != MT &&
  19475. ActiveAttr.getValue()->getLevel() == Level) {
  19476. Diag(Loc, diag::err_omp_declare_target_to_and_link) << ND;
  19477. return;
  19478. }
  19479. if (ActiveAttr.hasValue() && ActiveAttr.getValue()->getLevel() == Level)
  19480. return;
  19481. Expr *IndirectE = nullptr;
  19482. bool IsIndirect = false;
  19483. if (DTCI.Indirect.hasValue()) {
  19484. IndirectE = DTCI.Indirect.getValue();
  19485. if (!IndirectE)
  19486. IsIndirect = true;
  19487. }
  19488. auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(
  19489. Context, MT, DTCI.DT, IndirectE, IsIndirect, Level,
  19490. SourceRange(Loc, Loc));
  19491. ND->addAttr(A);
  19492. if (ASTMutationListener *ML = Context.getASTMutationListener())
  19493. ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
  19494. checkDeclIsAllowedInOpenMPTarget(nullptr, ND, Loc);
  19495. }
  19496. static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
  19497. Sema &SemaRef, Decl *D) {
  19498. if (!D || !isa<VarDecl>(D))
  19499. return;
  19500. auto *VD = cast<VarDecl>(D);
  19501. Optional<OMPDeclareTargetDeclAttr::MapTypeTy> MapTy =
  19502. OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
  19503. if (SemaRef.LangOpts.OpenMP >= 50 &&
  19504. (SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true) ||
  19505. SemaRef.getCurBlock() || SemaRef.getCurCapturedRegion()) &&
  19506. VD->hasGlobalStorage()) {
  19507. if (!MapTy || *MapTy != OMPDeclareTargetDeclAttr::MT_To) {
  19508. // OpenMP 5.0, 2.12.7 declare target Directive, Restrictions
  19509. // If a lambda declaration and definition appears between a
  19510. // declare target directive and the matching end declare target
  19511. // directive, all variables that are captured by the lambda
  19512. // expression must also appear in a to clause.
  19513. SemaRef.Diag(VD->getLocation(),
  19514. diag::err_omp_lambda_capture_in_declare_target_not_to);
  19515. SemaRef.Diag(SL, diag::note_var_explicitly_captured_here)
  19516. << VD << 0 << SR;
  19517. return;
  19518. }
  19519. }
  19520. if (MapTy.hasValue())
  19521. return;
  19522. SemaRef.Diag(VD->getLocation(), diag::warn_omp_not_in_target_context);
  19523. SemaRef.Diag(SL, diag::note_used_here) << SR;
  19524. }
  19525. static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
  19526. Sema &SemaRef, DSAStackTy *Stack,
  19527. ValueDecl *VD) {
  19528. return OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD) ||
  19529. checkTypeMappable(SL, SR, SemaRef, Stack, VD->getType(),
  19530. /*FullCheck=*/false);
  19531. }
  19532. void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D,
  19533. SourceLocation IdLoc) {
  19534. if (!D || D->isInvalidDecl())
  19535. return;
  19536. SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
  19537. SourceLocation SL = E ? E->getBeginLoc() : D->getLocation();
  19538. if (auto *VD = dyn_cast<VarDecl>(D)) {
  19539. // Only global variables can be marked as declare target.
  19540. if (!VD->isFileVarDecl() && !VD->isStaticLocal() &&
  19541. !VD->isStaticDataMember())
  19542. return;
  19543. // 2.10.6: threadprivate variable cannot appear in a declare target
  19544. // directive.
  19545. if (DSAStack->isThreadPrivate(VD)) {
  19546. Diag(SL, diag::err_omp_threadprivate_in_target);
  19547. reportOriginalDsa(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
  19548. return;
  19549. }
  19550. }
  19551. if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(D))
  19552. D = FTD->getTemplatedDecl();
  19553. if (auto *FD = dyn_cast<FunctionDecl>(D)) {
  19554. llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
  19555. OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(FD);
  19556. if (IdLoc.isValid() && Res && *Res == OMPDeclareTargetDeclAttr::MT_Link) {
  19557. Diag(IdLoc, diag::err_omp_function_in_link_clause);
  19558. Diag(FD->getLocation(), diag::note_defined_here) << FD;
  19559. return;
  19560. }
  19561. }
  19562. if (auto *VD = dyn_cast<ValueDecl>(D)) {
  19563. // Problem if any with var declared with incomplete type will be reported
  19564. // as normal, so no need to check it here.
  19565. if ((E || !VD->getType()->isIncompleteType()) &&
  19566. !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD))
  19567. return;
  19568. if (!E && isInOpenMPDeclareTargetContext()) {
  19569. // Checking declaration inside declare target region.
  19570. if (isa<VarDecl>(D) || isa<FunctionDecl>(D) ||
  19571. isa<FunctionTemplateDecl>(D)) {
  19572. llvm::Optional<OMPDeclareTargetDeclAttr *> ActiveAttr =
  19573. OMPDeclareTargetDeclAttr::getActiveAttr(VD);
  19574. unsigned Level = DeclareTargetNesting.size();
  19575. if (ActiveAttr.hasValue() && ActiveAttr.getValue()->getLevel() >= Level)
  19576. return;
  19577. DeclareTargetContextInfo &DTCI = DeclareTargetNesting.back();
  19578. Expr *IndirectE = nullptr;
  19579. bool IsIndirect = false;
  19580. if (DTCI.Indirect.hasValue()) {
  19581. IndirectE = DTCI.Indirect.getValue();
  19582. if (!IndirectE)
  19583. IsIndirect = true;
  19584. }
  19585. auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(
  19586. Context, OMPDeclareTargetDeclAttr::MT_To, DTCI.DT, IndirectE,
  19587. IsIndirect, Level, SourceRange(DTCI.Loc, DTCI.Loc));
  19588. D->addAttr(A);
  19589. if (ASTMutationListener *ML = Context.getASTMutationListener())
  19590. ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
  19591. }
  19592. return;
  19593. }
  19594. }
  19595. if (!E)
  19596. return;
  19597. checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
  19598. }
  19599. OMPClause *Sema::ActOnOpenMPToClause(
  19600. ArrayRef<OpenMPMotionModifierKind> MotionModifiers,
  19601. ArrayRef<SourceLocation> MotionModifiersLoc,
  19602. CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId,
  19603. SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
  19604. const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) {
  19605. OpenMPMotionModifierKind Modifiers[] = {OMPC_MOTION_MODIFIER_unknown,
  19606. OMPC_MOTION_MODIFIER_unknown};
  19607. SourceLocation ModifiersLoc[NumberOfOMPMotionModifiers];
  19608. // Process motion-modifiers, flag errors for duplicate modifiers.
  19609. unsigned Count = 0;
  19610. for (unsigned I = 0, E = MotionModifiers.size(); I < E; ++I) {
  19611. if (MotionModifiers[I] != OMPC_MOTION_MODIFIER_unknown &&
  19612. llvm::is_contained(Modifiers, MotionModifiers[I])) {
  19613. Diag(MotionModifiersLoc[I], diag::err_omp_duplicate_motion_modifier);
  19614. continue;
  19615. }
  19616. assert(Count < NumberOfOMPMotionModifiers &&
  19617. "Modifiers exceed the allowed number of motion modifiers");
  19618. Modifiers[Count] = MotionModifiers[I];
  19619. ModifiersLoc[Count] = MotionModifiersLoc[I];
  19620. ++Count;
  19621. }
  19622. MappableVarListInfo MVLI(VarList);
  19623. checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, Locs.StartLoc,
  19624. MapperIdScopeSpec, MapperId, UnresolvedMappers);
  19625. if (MVLI.ProcessedVarList.empty())
  19626. return nullptr;
  19627. return OMPToClause::Create(
  19628. Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
  19629. MVLI.VarComponents, MVLI.UDMapperList, Modifiers, ModifiersLoc,
  19630. MapperIdScopeSpec.getWithLocInContext(Context), MapperId);
  19631. }
  19632. OMPClause *Sema::ActOnOpenMPFromClause(
  19633. ArrayRef<OpenMPMotionModifierKind> MotionModifiers,
  19634. ArrayRef<SourceLocation> MotionModifiersLoc,
  19635. CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId,
  19636. SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
  19637. const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) {
  19638. OpenMPMotionModifierKind Modifiers[] = {OMPC_MOTION_MODIFIER_unknown,
  19639. OMPC_MOTION_MODIFIER_unknown};
  19640. SourceLocation ModifiersLoc[NumberOfOMPMotionModifiers];
  19641. // Process motion-modifiers, flag errors for duplicate modifiers.
  19642. unsigned Count = 0;
  19643. for (unsigned I = 0, E = MotionModifiers.size(); I < E; ++I) {
  19644. if (MotionModifiers[I] != OMPC_MOTION_MODIFIER_unknown &&
  19645. llvm::is_contained(Modifiers, MotionModifiers[I])) {
  19646. Diag(MotionModifiersLoc[I], diag::err_omp_duplicate_motion_modifier);
  19647. continue;
  19648. }
  19649. assert(Count < NumberOfOMPMotionModifiers &&
  19650. "Modifiers exceed the allowed number of motion modifiers");
  19651. Modifiers[Count] = MotionModifiers[I];
  19652. ModifiersLoc[Count] = MotionModifiersLoc[I];
  19653. ++Count;
  19654. }
  19655. MappableVarListInfo MVLI(VarList);
  19656. checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, Locs.StartLoc,
  19657. MapperIdScopeSpec, MapperId, UnresolvedMappers);
  19658. if (MVLI.ProcessedVarList.empty())
  19659. return nullptr;
  19660. return OMPFromClause::Create(
  19661. Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
  19662. MVLI.VarComponents, MVLI.UDMapperList, Modifiers, ModifiersLoc,
  19663. MapperIdScopeSpec.getWithLocInContext(Context), MapperId);
  19664. }
  19665. OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
  19666. const OMPVarListLocTy &Locs) {
  19667. MappableVarListInfo MVLI(VarList);
  19668. SmallVector<Expr *, 8> PrivateCopies;
  19669. SmallVector<Expr *, 8> Inits;
  19670. for (Expr *RefExpr : VarList) {
  19671. assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
  19672. SourceLocation ELoc;
  19673. SourceRange ERange;
  19674. Expr *SimpleRefExpr = RefExpr;
  19675. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  19676. if (Res.second) {
  19677. // It will be analyzed later.
  19678. MVLI.ProcessedVarList.push_back(RefExpr);
  19679. PrivateCopies.push_back(nullptr);
  19680. Inits.push_back(nullptr);
  19681. }
  19682. ValueDecl *D = Res.first;
  19683. if (!D)
  19684. continue;
  19685. QualType Type = D->getType();
  19686. Type = Type.getNonReferenceType().getUnqualifiedType();
  19687. auto *VD = dyn_cast<VarDecl>(D);
  19688. // Item should be a pointer or reference to pointer.
  19689. if (!Type->isPointerType()) {
  19690. Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
  19691. << 0 << RefExpr->getSourceRange();
  19692. continue;
  19693. }
  19694. // Build the private variable and the expression that refers to it.
  19695. auto VDPrivate =
  19696. buildVarDecl(*this, ELoc, Type, D->getName(),
  19697. D->hasAttrs() ? &D->getAttrs() : nullptr,
  19698. VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
  19699. if (VDPrivate->isInvalidDecl())
  19700. continue;
  19701. CurContext->addDecl(VDPrivate);
  19702. DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
  19703. *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
  19704. // Add temporary variable to initialize the private copy of the pointer.
  19705. VarDecl *VDInit =
  19706. buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
  19707. DeclRefExpr *VDInitRefExpr = buildDeclRefExpr(
  19708. *this, VDInit, RefExpr->getType(), RefExpr->getExprLoc());
  19709. AddInitializerToDecl(VDPrivate,
  19710. DefaultLvalueConversion(VDInitRefExpr).get(),
  19711. /*DirectInit=*/false);
  19712. // If required, build a capture to implement the privatization initialized
  19713. // with the current list item value.
  19714. DeclRefExpr *Ref = nullptr;
  19715. if (!VD)
  19716. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
  19717. MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
  19718. PrivateCopies.push_back(VDPrivateRefExpr);
  19719. Inits.push_back(VDInitRefExpr);
  19720. // We need to add a data sharing attribute for this variable to make sure it
  19721. // is correctly captured. A variable that shows up in a use_device_ptr has
  19722. // similar properties of a first private variable.
  19723. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
  19724. // Create a mappable component for the list item. List items in this clause
  19725. // only need a component.
  19726. MVLI.VarBaseDeclarations.push_back(D);
  19727. MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
  19728. MVLI.VarComponents.back().emplace_back(SimpleRefExpr, D,
  19729. /*IsNonContiguous=*/false);
  19730. }
  19731. if (MVLI.ProcessedVarList.empty())
  19732. return nullptr;
  19733. return OMPUseDevicePtrClause::Create(
  19734. Context, Locs, MVLI.ProcessedVarList, PrivateCopies, Inits,
  19735. MVLI.VarBaseDeclarations, MVLI.VarComponents);
  19736. }
  19737. OMPClause *Sema::ActOnOpenMPUseDeviceAddrClause(ArrayRef<Expr *> VarList,
  19738. const OMPVarListLocTy &Locs) {
  19739. MappableVarListInfo MVLI(VarList);
  19740. for (Expr *RefExpr : VarList) {
  19741. assert(RefExpr && "NULL expr in OpenMP use_device_addr clause.");
  19742. SourceLocation ELoc;
  19743. SourceRange ERange;
  19744. Expr *SimpleRefExpr = RefExpr;
  19745. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
  19746. /*AllowArraySection=*/true);
  19747. if (Res.second) {
  19748. // It will be analyzed later.
  19749. MVLI.ProcessedVarList.push_back(RefExpr);
  19750. }
  19751. ValueDecl *D = Res.first;
  19752. if (!D)
  19753. continue;
  19754. auto *VD = dyn_cast<VarDecl>(D);
  19755. // If required, build a capture to implement the privatization initialized
  19756. // with the current list item value.
  19757. DeclRefExpr *Ref = nullptr;
  19758. if (!VD)
  19759. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
  19760. MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
  19761. // We need to add a data sharing attribute for this variable to make sure it
  19762. // is correctly captured. A variable that shows up in a use_device_addr has
  19763. // similar properties of a first private variable.
  19764. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
  19765. // Create a mappable component for the list item. List items in this clause
  19766. // only need a component.
  19767. MVLI.VarBaseDeclarations.push_back(D);
  19768. MVLI.VarComponents.emplace_back();
  19769. Expr *Component = SimpleRefExpr;
  19770. if (VD && (isa<OMPArraySectionExpr>(RefExpr->IgnoreParenImpCasts()) ||
  19771. isa<ArraySubscriptExpr>(RefExpr->IgnoreParenImpCasts())))
  19772. Component = DefaultFunctionArrayLvalueConversion(SimpleRefExpr).get();
  19773. MVLI.VarComponents.back().emplace_back(Component, D,
  19774. /*IsNonContiguous=*/false);
  19775. }
  19776. if (MVLI.ProcessedVarList.empty())
  19777. return nullptr;
  19778. return OMPUseDeviceAddrClause::Create(Context, Locs, MVLI.ProcessedVarList,
  19779. MVLI.VarBaseDeclarations,
  19780. MVLI.VarComponents);
  19781. }
  19782. OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
  19783. const OMPVarListLocTy &Locs) {
  19784. MappableVarListInfo MVLI(VarList);
  19785. for (Expr *RefExpr : VarList) {
  19786. assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
  19787. SourceLocation ELoc;
  19788. SourceRange ERange;
  19789. Expr *SimpleRefExpr = RefExpr;
  19790. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  19791. if (Res.second) {
  19792. // It will be analyzed later.
  19793. MVLI.ProcessedVarList.push_back(RefExpr);
  19794. }
  19795. ValueDecl *D = Res.first;
  19796. if (!D)
  19797. continue;
  19798. QualType Type = D->getType();
  19799. // item should be a pointer or array or reference to pointer or array
  19800. if (!Type.getNonReferenceType()->isPointerType() &&
  19801. !Type.getNonReferenceType()->isArrayType()) {
  19802. Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
  19803. << 0 << RefExpr->getSourceRange();
  19804. continue;
  19805. }
  19806. // Check if the declaration in the clause does not show up in any data
  19807. // sharing attribute.
  19808. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
  19809. if (isOpenMPPrivate(DVar.CKind)) {
  19810. Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
  19811. << getOpenMPClauseName(DVar.CKind)
  19812. << getOpenMPClauseName(OMPC_is_device_ptr)
  19813. << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
  19814. reportOriginalDsa(*this, DSAStack, D, DVar);
  19815. continue;
  19816. }
  19817. const Expr *ConflictExpr;
  19818. if (DSAStack->checkMappableExprComponentListsForDecl(
  19819. D, /*CurrentRegionOnly=*/true,
  19820. [&ConflictExpr](
  19821. OMPClauseMappableExprCommon::MappableExprComponentListRef R,
  19822. OpenMPClauseKind) -> bool {
  19823. ConflictExpr = R.front().getAssociatedExpression();
  19824. return true;
  19825. })) {
  19826. Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
  19827. Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
  19828. << ConflictExpr->getSourceRange();
  19829. continue;
  19830. }
  19831. // Store the components in the stack so that they can be used to check
  19832. // against other clauses later on.
  19833. OMPClauseMappableExprCommon::MappableComponent MC(
  19834. SimpleRefExpr, D, /*IsNonContiguous=*/false);
  19835. DSAStack->addMappableExpressionComponents(
  19836. D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
  19837. // Record the expression we've just processed.
  19838. MVLI.ProcessedVarList.push_back(SimpleRefExpr);
  19839. // Create a mappable component for the list item. List items in this clause
  19840. // only need a component. We use a null declaration to signal fields in
  19841. // 'this'.
  19842. assert((isa<DeclRefExpr>(SimpleRefExpr) ||
  19843. isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
  19844. "Unexpected device pointer expression!");
  19845. MVLI.VarBaseDeclarations.push_back(
  19846. isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
  19847. MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
  19848. MVLI.VarComponents.back().push_back(MC);
  19849. }
  19850. if (MVLI.ProcessedVarList.empty())
  19851. return nullptr;
  19852. return OMPIsDevicePtrClause::Create(Context, Locs, MVLI.ProcessedVarList,
  19853. MVLI.VarBaseDeclarations,
  19854. MVLI.VarComponents);
  19855. }
  19856. OMPClause *Sema::ActOnOpenMPAllocateClause(
  19857. Expr *Allocator, ArrayRef<Expr *> VarList, SourceLocation StartLoc,
  19858. SourceLocation ColonLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
  19859. if (Allocator) {
  19860. // OpenMP [2.11.4 allocate Clause, Description]
  19861. // allocator is an expression of omp_allocator_handle_t type.
  19862. if (!findOMPAllocatorHandleT(*this, Allocator->getExprLoc(), DSAStack))
  19863. return nullptr;
  19864. ExprResult AllocatorRes = DefaultLvalueConversion(Allocator);
  19865. if (AllocatorRes.isInvalid())
  19866. return nullptr;
  19867. AllocatorRes = PerformImplicitConversion(AllocatorRes.get(),
  19868. DSAStack->getOMPAllocatorHandleT(),
  19869. Sema::AA_Initializing,
  19870. /*AllowExplicit=*/true);
  19871. if (AllocatorRes.isInvalid())
  19872. return nullptr;
  19873. Allocator = AllocatorRes.get();
  19874. } else {
  19875. // OpenMP 5.0, 2.11.4 allocate Clause, Restrictions.
  19876. // allocate clauses that appear on a target construct or on constructs in a
  19877. // target region must specify an allocator expression unless a requires
  19878. // directive with the dynamic_allocators clause is present in the same
  19879. // compilation unit.
  19880. if (LangOpts.OpenMPIsDevice &&
  19881. !DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())
  19882. targetDiag(StartLoc, diag::err_expected_allocator_expression);
  19883. }
  19884. // Analyze and build list of variables.
  19885. SmallVector<Expr *, 8> Vars;
  19886. for (Expr *RefExpr : VarList) {
  19887. assert(RefExpr && "NULL expr in OpenMP private clause.");
  19888. SourceLocation ELoc;
  19889. SourceRange ERange;
  19890. Expr *SimpleRefExpr = RefExpr;
  19891. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  19892. if (Res.second) {
  19893. // It will be analyzed later.
  19894. Vars.push_back(RefExpr);
  19895. }
  19896. ValueDecl *D = Res.first;
  19897. if (!D)
  19898. continue;
  19899. auto *VD = dyn_cast<VarDecl>(D);
  19900. DeclRefExpr *Ref = nullptr;
  19901. if (!VD && !CurContext->isDependentContext())
  19902. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
  19903. Vars.push_back((VD || CurContext->isDependentContext())
  19904. ? RefExpr->IgnoreParens()
  19905. : Ref);
  19906. }
  19907. if (Vars.empty())
  19908. return nullptr;
  19909. if (Allocator)
  19910. DSAStack->addInnerAllocatorExpr(Allocator);
  19911. return OMPAllocateClause::Create(Context, StartLoc, LParenLoc, Allocator,
  19912. ColonLoc, EndLoc, Vars);
  19913. }
  19914. OMPClause *Sema::ActOnOpenMPNontemporalClause(ArrayRef<Expr *> VarList,
  19915. SourceLocation StartLoc,
  19916. SourceLocation LParenLoc,
  19917. SourceLocation EndLoc) {
  19918. SmallVector<Expr *, 8> Vars;
  19919. for (Expr *RefExpr : VarList) {
  19920. assert(RefExpr && "NULL expr in OpenMP nontemporal clause.");
  19921. SourceLocation ELoc;
  19922. SourceRange ERange;
  19923. Expr *SimpleRefExpr = RefExpr;
  19924. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  19925. if (Res.second)
  19926. // It will be analyzed later.
  19927. Vars.push_back(RefExpr);
  19928. ValueDecl *D = Res.first;
  19929. if (!D)
  19930. continue;
  19931. // OpenMP 5.0, 2.9.3.1 simd Construct, Restrictions.
  19932. // A list-item cannot appear in more than one nontemporal clause.
  19933. if (const Expr *PrevRef =
  19934. DSAStack->addUniqueNontemporal(D, SimpleRefExpr)) {
  19935. Diag(ELoc, diag::err_omp_used_in_clause_twice)
  19936. << 0 << getOpenMPClauseName(OMPC_nontemporal) << ERange;
  19937. Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
  19938. << getOpenMPClauseName(OMPC_nontemporal);
  19939. continue;
  19940. }
  19941. Vars.push_back(RefExpr);
  19942. }
  19943. if (Vars.empty())
  19944. return nullptr;
  19945. return OMPNontemporalClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  19946. Vars);
  19947. }
  19948. OMPClause *Sema::ActOnOpenMPInclusiveClause(ArrayRef<Expr *> VarList,
  19949. SourceLocation StartLoc,
  19950. SourceLocation LParenLoc,
  19951. SourceLocation EndLoc) {
  19952. SmallVector<Expr *, 8> Vars;
  19953. for (Expr *RefExpr : VarList) {
  19954. assert(RefExpr && "NULL expr in OpenMP nontemporal clause.");
  19955. SourceLocation ELoc;
  19956. SourceRange ERange;
  19957. Expr *SimpleRefExpr = RefExpr;
  19958. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
  19959. /*AllowArraySection=*/true);
  19960. if (Res.second)
  19961. // It will be analyzed later.
  19962. Vars.push_back(RefExpr);
  19963. ValueDecl *D = Res.first;
  19964. if (!D)
  19965. continue;
  19966. const DSAStackTy::DSAVarData DVar =
  19967. DSAStack->getTopDSA(D, /*FromParent=*/true);
  19968. // OpenMP 5.0, 2.9.6, scan Directive, Restrictions.
  19969. // A list item that appears in the inclusive or exclusive clause must appear
  19970. // in a reduction clause with the inscan modifier on the enclosing
  19971. // worksharing-loop, worksharing-loop SIMD, or simd construct.
  19972. if (DVar.CKind != OMPC_reduction || DVar.Modifier != OMPC_REDUCTION_inscan)
  19973. Diag(ELoc, diag::err_omp_inclusive_exclusive_not_reduction)
  19974. << RefExpr->getSourceRange();
  19975. if (DSAStack->getParentDirective() != OMPD_unknown)
  19976. DSAStack->markDeclAsUsedInScanDirective(D);
  19977. Vars.push_back(RefExpr);
  19978. }
  19979. if (Vars.empty())
  19980. return nullptr;
  19981. return OMPInclusiveClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
  19982. }
  19983. OMPClause *Sema::ActOnOpenMPExclusiveClause(ArrayRef<Expr *> VarList,
  19984. SourceLocation StartLoc,
  19985. SourceLocation LParenLoc,
  19986. SourceLocation EndLoc) {
  19987. SmallVector<Expr *, 8> Vars;
  19988. for (Expr *RefExpr : VarList) {
  19989. assert(RefExpr && "NULL expr in OpenMP nontemporal clause.");
  19990. SourceLocation ELoc;
  19991. SourceRange ERange;
  19992. Expr *SimpleRefExpr = RefExpr;
  19993. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
  19994. /*AllowArraySection=*/true);
  19995. if (Res.second)
  19996. // It will be analyzed later.
  19997. Vars.push_back(RefExpr);
  19998. ValueDecl *D = Res.first;
  19999. if (!D)
  20000. continue;
  20001. OpenMPDirectiveKind ParentDirective = DSAStack->getParentDirective();
  20002. DSAStackTy::DSAVarData DVar;
  20003. if (ParentDirective != OMPD_unknown)
  20004. DVar = DSAStack->getTopDSA(D, /*FromParent=*/true);
  20005. // OpenMP 5.0, 2.9.6, scan Directive, Restrictions.
  20006. // A list item that appears in the inclusive or exclusive clause must appear
  20007. // in a reduction clause with the inscan modifier on the enclosing
  20008. // worksharing-loop, worksharing-loop SIMD, or simd construct.
  20009. if (ParentDirective == OMPD_unknown || DVar.CKind != OMPC_reduction ||
  20010. DVar.Modifier != OMPC_REDUCTION_inscan) {
  20011. Diag(ELoc, diag::err_omp_inclusive_exclusive_not_reduction)
  20012. << RefExpr->getSourceRange();
  20013. } else {
  20014. DSAStack->markDeclAsUsedInScanDirective(D);
  20015. }
  20016. Vars.push_back(RefExpr);
  20017. }
  20018. if (Vars.empty())
  20019. return nullptr;
  20020. return OMPExclusiveClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
  20021. }
  20022. /// Tries to find omp_alloctrait_t type.
  20023. static bool findOMPAlloctraitT(Sema &S, SourceLocation Loc, DSAStackTy *Stack) {
  20024. QualType OMPAlloctraitT = Stack->getOMPAlloctraitT();
  20025. if (!OMPAlloctraitT.isNull())
  20026. return true;
  20027. IdentifierInfo &II = S.PP.getIdentifierTable().get("omp_alloctrait_t");
  20028. ParsedType PT = S.getTypeName(II, Loc, S.getCurScope());
  20029. if (!PT.getAsOpaquePtr() || PT.get().isNull()) {
  20030. S.Diag(Loc, diag::err_omp_implied_type_not_found) << "omp_alloctrait_t";
  20031. return false;
  20032. }
  20033. Stack->setOMPAlloctraitT(PT.get());
  20034. return true;
  20035. }
  20036. OMPClause *Sema::ActOnOpenMPUsesAllocatorClause(
  20037. SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc,
  20038. ArrayRef<UsesAllocatorsData> Data) {
  20039. // OpenMP [2.12.5, target Construct]
  20040. // allocator is an identifier of omp_allocator_handle_t type.
  20041. if (!findOMPAllocatorHandleT(*this, StartLoc, DSAStack))
  20042. return nullptr;
  20043. // OpenMP [2.12.5, target Construct]
  20044. // allocator-traits-array is an identifier of const omp_alloctrait_t * type.
  20045. if (llvm::any_of(
  20046. Data,
  20047. [](const UsesAllocatorsData &D) { return D.AllocatorTraits; }) &&
  20048. !findOMPAlloctraitT(*this, StartLoc, DSAStack))
  20049. return nullptr;
  20050. llvm::SmallPtrSet<CanonicalDeclPtr<Decl>, 4> PredefinedAllocators;
  20051. for (int I = 0; I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) {
  20052. auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I);
  20053. StringRef Allocator =
  20054. OMPAllocateDeclAttr::ConvertAllocatorTypeTyToStr(AllocatorKind);
  20055. DeclarationName AllocatorName = &Context.Idents.get(Allocator);
  20056. PredefinedAllocators.insert(LookupSingleName(
  20057. TUScope, AllocatorName, StartLoc, Sema::LookupAnyName));
  20058. }
  20059. SmallVector<OMPUsesAllocatorsClause::Data, 4> NewData;
  20060. for (const UsesAllocatorsData &D : Data) {
  20061. Expr *AllocatorExpr = nullptr;
  20062. // Check allocator expression.
  20063. if (D.Allocator->isTypeDependent()) {
  20064. AllocatorExpr = D.Allocator;
  20065. } else {
  20066. // Traits were specified - need to assign new allocator to the specified
  20067. // allocator, so it must be an lvalue.
  20068. AllocatorExpr = D.Allocator->IgnoreParenImpCasts();
  20069. auto *DRE = dyn_cast<DeclRefExpr>(AllocatorExpr);
  20070. bool IsPredefinedAllocator = false;
  20071. if (DRE)
  20072. IsPredefinedAllocator = PredefinedAllocators.count(DRE->getDecl());
  20073. if (!DRE ||
  20074. !(Context.hasSameUnqualifiedType(
  20075. AllocatorExpr->getType(), DSAStack->getOMPAllocatorHandleT()) ||
  20076. Context.typesAreCompatible(AllocatorExpr->getType(),
  20077. DSAStack->getOMPAllocatorHandleT(),
  20078. /*CompareUnqualified=*/true)) ||
  20079. (!IsPredefinedAllocator &&
  20080. (AllocatorExpr->getType().isConstant(Context) ||
  20081. !AllocatorExpr->isLValue()))) {
  20082. Diag(D.Allocator->getExprLoc(), diag::err_omp_var_expected)
  20083. << "omp_allocator_handle_t" << (DRE ? 1 : 0)
  20084. << AllocatorExpr->getType() << D.Allocator->getSourceRange();
  20085. continue;
  20086. }
  20087. // OpenMP [2.12.5, target Construct]
  20088. // Predefined allocators appearing in a uses_allocators clause cannot have
  20089. // traits specified.
  20090. if (IsPredefinedAllocator && D.AllocatorTraits) {
  20091. Diag(D.AllocatorTraits->getExprLoc(),
  20092. diag::err_omp_predefined_allocator_with_traits)
  20093. << D.AllocatorTraits->getSourceRange();
  20094. Diag(D.Allocator->getExprLoc(), diag::note_omp_predefined_allocator)
  20095. << cast<NamedDecl>(DRE->getDecl())->getName()
  20096. << D.Allocator->getSourceRange();
  20097. continue;
  20098. }
  20099. // OpenMP [2.12.5, target Construct]
  20100. // Non-predefined allocators appearing in a uses_allocators clause must
  20101. // have traits specified.
  20102. if (!IsPredefinedAllocator && !D.AllocatorTraits) {
  20103. Diag(D.Allocator->getExprLoc(),
  20104. diag::err_omp_nonpredefined_allocator_without_traits);
  20105. continue;
  20106. }
  20107. // No allocator traits - just convert it to rvalue.
  20108. if (!D.AllocatorTraits)
  20109. AllocatorExpr = DefaultLvalueConversion(AllocatorExpr).get();
  20110. DSAStack->addUsesAllocatorsDecl(
  20111. DRE->getDecl(),
  20112. IsPredefinedAllocator
  20113. ? DSAStackTy::UsesAllocatorsDeclKind::PredefinedAllocator
  20114. : DSAStackTy::UsesAllocatorsDeclKind::UserDefinedAllocator);
  20115. }
  20116. Expr *AllocatorTraitsExpr = nullptr;
  20117. if (D.AllocatorTraits) {
  20118. if (D.AllocatorTraits->isTypeDependent()) {
  20119. AllocatorTraitsExpr = D.AllocatorTraits;
  20120. } else {
  20121. // OpenMP [2.12.5, target Construct]
  20122. // Arrays that contain allocator traits that appear in a uses_allocators
  20123. // clause must be constant arrays, have constant values and be defined
  20124. // in the same scope as the construct in which the clause appears.
  20125. AllocatorTraitsExpr = D.AllocatorTraits->IgnoreParenImpCasts();
  20126. // Check that traits expr is a constant array.
  20127. QualType TraitTy;
  20128. if (const ArrayType *Ty =
  20129. AllocatorTraitsExpr->getType()->getAsArrayTypeUnsafe())
  20130. if (const auto *ConstArrayTy = dyn_cast<ConstantArrayType>(Ty))
  20131. TraitTy = ConstArrayTy->getElementType();
  20132. if (TraitTy.isNull() ||
  20133. !(Context.hasSameUnqualifiedType(TraitTy,
  20134. DSAStack->getOMPAlloctraitT()) ||
  20135. Context.typesAreCompatible(TraitTy, DSAStack->getOMPAlloctraitT(),
  20136. /*CompareUnqualified=*/true))) {
  20137. Diag(D.AllocatorTraits->getExprLoc(),
  20138. diag::err_omp_expected_array_alloctraits)
  20139. << AllocatorTraitsExpr->getType();
  20140. continue;
  20141. }
  20142. // Do not map by default allocator traits if it is a standalone
  20143. // variable.
  20144. if (auto *DRE = dyn_cast<DeclRefExpr>(AllocatorTraitsExpr))
  20145. DSAStack->addUsesAllocatorsDecl(
  20146. DRE->getDecl(),
  20147. DSAStackTy::UsesAllocatorsDeclKind::AllocatorTrait);
  20148. }
  20149. }
  20150. OMPUsesAllocatorsClause::Data &NewD = NewData.emplace_back();
  20151. NewD.Allocator = AllocatorExpr;
  20152. NewD.AllocatorTraits = AllocatorTraitsExpr;
  20153. NewD.LParenLoc = D.LParenLoc;
  20154. NewD.RParenLoc = D.RParenLoc;
  20155. }
  20156. return OMPUsesAllocatorsClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  20157. NewData);
  20158. }
  20159. OMPClause *Sema::ActOnOpenMPAffinityClause(
  20160. SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
  20161. SourceLocation EndLoc, Expr *Modifier, ArrayRef<Expr *> Locators) {
  20162. SmallVector<Expr *, 8> Vars;
  20163. for (Expr *RefExpr : Locators) {
  20164. assert(RefExpr && "NULL expr in OpenMP shared clause.");
  20165. if (isa<DependentScopeDeclRefExpr>(RefExpr) || RefExpr->isTypeDependent()) {
  20166. // It will be analyzed later.
  20167. Vars.push_back(RefExpr);
  20168. continue;
  20169. }
  20170. SourceLocation ELoc = RefExpr->getExprLoc();
  20171. Expr *SimpleExpr = RefExpr->IgnoreParenImpCasts();
  20172. if (!SimpleExpr->isLValue()) {
  20173. Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
  20174. << 1 << 0 << RefExpr->getSourceRange();
  20175. continue;
  20176. }
  20177. ExprResult Res;
  20178. {
  20179. Sema::TentativeAnalysisScope Trap(*this);
  20180. Res = CreateBuiltinUnaryOp(ELoc, UO_AddrOf, SimpleExpr);
  20181. }
  20182. if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr) &&
  20183. !isa<OMPArrayShapingExpr>(SimpleExpr)) {
  20184. Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
  20185. << 1 << 0 << RefExpr->getSourceRange();
  20186. continue;
  20187. }
  20188. Vars.push_back(SimpleExpr);
  20189. }
  20190. return OMPAffinityClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
  20191. EndLoc, Modifier, Vars);
  20192. }
  20193. OMPClause *Sema::ActOnOpenMPBindClause(OpenMPBindClauseKind Kind,
  20194. SourceLocation KindLoc,
  20195. SourceLocation StartLoc,
  20196. SourceLocation LParenLoc,
  20197. SourceLocation EndLoc) {
  20198. if (Kind == OMPC_BIND_unknown) {
  20199. Diag(KindLoc, diag::err_omp_unexpected_clause_value)
  20200. << getListOfPossibleValues(OMPC_bind, /*First=*/0,
  20201. /*Last=*/unsigned(OMPC_BIND_unknown))
  20202. << getOpenMPClauseName(OMPC_bind);
  20203. return nullptr;
  20204. }
  20205. return OMPBindClause::Create(Context, Kind, KindLoc, StartLoc, LParenLoc,
  20206. EndLoc);
  20207. }