SemaOpenMP.cpp 645 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282
  1. //===--- SemaOpenMP.cpp - Semantic Analysis for OpenMP constructs ---------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. /// \file
  9. /// This file implements semantic analysis for OpenMP directives and
  10. /// clauses.
  11. ///
  12. //===----------------------------------------------------------------------===//
  13. #include "TreeTransform.h"
  14. #include "clang/AST/ASTContext.h"
  15. #include "clang/AST/ASTMutationListener.h"
  16. #include "clang/AST/CXXInheritance.h"
  17. #include "clang/AST/Decl.h"
  18. #include "clang/AST/DeclCXX.h"
  19. #include "clang/AST/DeclOpenMP.h"
  20. #include "clang/AST/StmtCXX.h"
  21. #include "clang/AST/StmtOpenMP.h"
  22. #include "clang/AST/StmtVisitor.h"
  23. #include "clang/AST/TypeOrdering.h"
  24. #include "clang/Basic/OpenMPKinds.h"
  25. #include "clang/Sema/Initialization.h"
  26. #include "clang/Sema/Lookup.h"
  27. #include "clang/Sema/Scope.h"
  28. #include "clang/Sema/ScopeInfo.h"
  29. #include "clang/Sema/SemaInternal.h"
  30. #include "llvm/ADT/PointerEmbeddedInt.h"
  31. using namespace clang;
  32. //===----------------------------------------------------------------------===//
  33. // Stack of data-sharing attributes for variables
  34. //===----------------------------------------------------------------------===//
  35. static const Expr *checkMapClauseExpressionBase(
  36. Sema &SemaRef, Expr *E,
  37. OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
  38. OpenMPClauseKind CKind, bool NoDiagnose);
  39. namespace {
  40. /// Default data sharing attributes, which can be applied to directive.
  41. enum DefaultDataSharingAttributes {
  42. DSA_unspecified = 0, /// Data sharing attribute not specified.
  43. DSA_none = 1 << 0, /// Default data sharing attribute 'none'.
  44. DSA_shared = 1 << 1, /// Default data sharing attribute 'shared'.
  45. };
  46. /// Attributes of the defaultmap clause.
  47. enum DefaultMapAttributes {
  48. DMA_unspecified, /// Default mapping is not specified.
  49. DMA_tofrom_scalar, /// Default mapping is 'tofrom:scalar'.
  50. };
  51. /// Stack for tracking declarations used in OpenMP directives and
  52. /// clauses and their data-sharing attributes.
  53. class DSAStackTy {
  54. public:
  55. struct DSAVarData {
  56. OpenMPDirectiveKind DKind = OMPD_unknown;
  57. OpenMPClauseKind CKind = OMPC_unknown;
  58. const Expr *RefExpr = nullptr;
  59. DeclRefExpr *PrivateCopy = nullptr;
  60. SourceLocation ImplicitDSALoc;
  61. DSAVarData() = default;
  62. DSAVarData(OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
  63. const Expr *RefExpr, DeclRefExpr *PrivateCopy,
  64. SourceLocation ImplicitDSALoc)
  65. : DKind(DKind), CKind(CKind), RefExpr(RefExpr),
  66. PrivateCopy(PrivateCopy), ImplicitDSALoc(ImplicitDSALoc) {}
  67. };
  68. using OperatorOffsetTy =
  69. llvm::SmallVector<std::pair<Expr *, OverloadedOperatorKind>, 4>;
  70. using DoacrossDependMapTy =
  71. llvm::DenseMap<OMPDependClause *, OperatorOffsetTy>;
  72. private:
  73. struct DSAInfo {
  74. OpenMPClauseKind Attributes = OMPC_unknown;
  75. /// Pointer to a reference expression and a flag which shows that the
  76. /// variable is marked as lastprivate(true) or not (false).
  77. llvm::PointerIntPair<const Expr *, 1, bool> RefExpr;
  78. DeclRefExpr *PrivateCopy = nullptr;
  79. };
  80. using DeclSAMapTy = llvm::SmallDenseMap<const ValueDecl *, DSAInfo, 8>;
  81. using AlignedMapTy = llvm::SmallDenseMap<const ValueDecl *, const Expr *, 8>;
  82. using LCDeclInfo = std::pair<unsigned, VarDecl *>;
  83. using LoopControlVariablesMapTy =
  84. llvm::SmallDenseMap<const ValueDecl *, LCDeclInfo, 8>;
  85. /// Struct that associates a component with the clause kind where they are
  86. /// found.
  87. struct MappedExprComponentTy {
  88. OMPClauseMappableExprCommon::MappableExprComponentLists Components;
  89. OpenMPClauseKind Kind = OMPC_unknown;
  90. };
  91. using MappedExprComponentsTy =
  92. llvm::DenseMap<const ValueDecl *, MappedExprComponentTy>;
  93. using CriticalsWithHintsTy =
  94. llvm::StringMap<std::pair<const OMPCriticalDirective *, llvm::APSInt>>;
  95. struct ReductionData {
  96. using BOKPtrType = llvm::PointerEmbeddedInt<BinaryOperatorKind, 16>;
  97. SourceRange ReductionRange;
  98. llvm::PointerUnion<const Expr *, BOKPtrType> ReductionOp;
  99. ReductionData() = default;
  100. void set(BinaryOperatorKind BO, SourceRange RR) {
  101. ReductionRange = RR;
  102. ReductionOp = BO;
  103. }
  104. void set(const Expr *RefExpr, SourceRange RR) {
  105. ReductionRange = RR;
  106. ReductionOp = RefExpr;
  107. }
  108. };
  109. using DeclReductionMapTy =
  110. llvm::SmallDenseMap<const ValueDecl *, ReductionData, 4>;
  111. struct SharingMapTy {
  112. DeclSAMapTy SharingMap;
  113. DeclReductionMapTy ReductionMap;
  114. AlignedMapTy AlignedMap;
  115. MappedExprComponentsTy MappedExprComponents;
  116. LoopControlVariablesMapTy LCVMap;
  117. DefaultDataSharingAttributes DefaultAttr = DSA_unspecified;
  118. SourceLocation DefaultAttrLoc;
  119. DefaultMapAttributes DefaultMapAttr = DMA_unspecified;
  120. SourceLocation DefaultMapAttrLoc;
  121. OpenMPDirectiveKind Directive = OMPD_unknown;
  122. DeclarationNameInfo DirectiveName;
  123. Scope *CurScope = nullptr;
  124. SourceLocation ConstructLoc;
  125. /// Set of 'depend' clauses with 'sink|source' dependence kind. Required to
  126. /// get the data (loop counters etc.) about enclosing loop-based construct.
  127. /// This data is required during codegen.
  128. DoacrossDependMapTy DoacrossDepends;
  129. /// First argument (Expr *) contains optional argument of the
  130. /// 'ordered' clause, the second one is true if the regions has 'ordered'
  131. /// clause, false otherwise.
  132. llvm::Optional<std::pair<const Expr *, OMPOrderedClause *>> OrderedRegion;
  133. unsigned AssociatedLoops = 1;
  134. bool HasMutipleLoops = false;
  135. const Decl *PossiblyLoopCounter = nullptr;
  136. bool NowaitRegion = false;
  137. bool CancelRegion = false;
  138. bool LoopStart = false;
  139. bool BodyComplete = false;
  140. SourceLocation InnerTeamsRegionLoc;
  141. /// Reference to the taskgroup task_reduction reference expression.
  142. Expr *TaskgroupReductionRef = nullptr;
  143. llvm::DenseSet<QualType> MappedClassesQualTypes;
  144. /// List of globals marked as declare target link in this target region
  145. /// (isOpenMPTargetExecutionDirective(Directive) == true).
  146. llvm::SmallVector<DeclRefExpr *, 4> DeclareTargetLinkVarDecls;
  147. SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name,
  148. Scope *CurScope, SourceLocation Loc)
  149. : Directive(DKind), DirectiveName(Name), CurScope(CurScope),
  150. ConstructLoc(Loc) {}
  151. SharingMapTy() = default;
  152. };
  153. using StackTy = SmallVector<SharingMapTy, 4>;
  154. /// Stack of used declaration and their data-sharing attributes.
  155. DeclSAMapTy Threadprivates;
  156. const FunctionScopeInfo *CurrentNonCapturingFunctionScope = nullptr;
  157. SmallVector<std::pair<StackTy, const FunctionScopeInfo *>, 4> Stack;
  158. /// true, if check for DSA must be from parent directive, false, if
  159. /// from current directive.
  160. OpenMPClauseKind ClauseKindMode = OMPC_unknown;
  161. Sema &SemaRef;
  162. bool ForceCapturing = false;
  163. /// true if all the variables in the target executable directives must be
  164. /// captured by reference.
  165. bool ForceCaptureByReferenceInTargetExecutable = false;
  166. CriticalsWithHintsTy Criticals;
  167. unsigned IgnoredStackElements = 0;
  168. /// Iterators over the stack iterate in order from innermost to outermost
  169. /// directive.
  170. using const_iterator = StackTy::const_reverse_iterator;
  171. const_iterator begin() const {
  172. return Stack.empty() ? const_iterator()
  173. : Stack.back().first.rbegin() + IgnoredStackElements;
  174. }
  175. const_iterator end() const {
  176. return Stack.empty() ? const_iterator() : Stack.back().first.rend();
  177. }
  178. using iterator = StackTy::reverse_iterator;
  179. iterator begin() {
  180. return Stack.empty() ? iterator()
  181. : Stack.back().first.rbegin() + IgnoredStackElements;
  182. }
  183. iterator end() {
  184. return Stack.empty() ? iterator() : Stack.back().first.rend();
  185. }
  186. // Convenience operations to get at the elements of the stack.
  187. bool isStackEmpty() const {
  188. return Stack.empty() ||
  189. Stack.back().second != CurrentNonCapturingFunctionScope ||
  190. Stack.back().first.size() <= IgnoredStackElements;
  191. }
  192. size_t getStackSize() const {
  193. return isStackEmpty() ? 0
  194. : Stack.back().first.size() - IgnoredStackElements;
  195. }
  196. SharingMapTy *getTopOfStackOrNull() {
  197. size_t Size = getStackSize();
  198. if (Size == 0)
  199. return nullptr;
  200. return &Stack.back().first[Size - 1];
  201. }
  202. const SharingMapTy *getTopOfStackOrNull() const {
  203. return const_cast<DSAStackTy&>(*this).getTopOfStackOrNull();
  204. }
  205. SharingMapTy &getTopOfStack() {
  206. assert(!isStackEmpty() && "no current directive");
  207. return *getTopOfStackOrNull();
  208. }
  209. const SharingMapTy &getTopOfStack() const {
  210. return const_cast<DSAStackTy&>(*this).getTopOfStack();
  211. }
  212. SharingMapTy *getSecondOnStackOrNull() {
  213. size_t Size = getStackSize();
  214. if (Size <= 1)
  215. return nullptr;
  216. return &Stack.back().first[Size - 2];
  217. }
  218. const SharingMapTy *getSecondOnStackOrNull() const {
  219. return const_cast<DSAStackTy&>(*this).getSecondOnStackOrNull();
  220. }
  221. /// Get the stack element at a certain level (previously returned by
  222. /// \c getNestingLevel).
  223. ///
  224. /// Note that nesting levels count from outermost to innermost, and this is
  225. /// the reverse of our iteration order where new inner levels are pushed at
  226. /// the front of the stack.
  227. SharingMapTy &getStackElemAtLevel(unsigned Level) {
  228. assert(Level < getStackSize() && "no such stack element");
  229. return Stack.back().first[Level];
  230. }
  231. const SharingMapTy &getStackElemAtLevel(unsigned Level) const {
  232. return const_cast<DSAStackTy&>(*this).getStackElemAtLevel(Level);
  233. }
  234. DSAVarData getDSA(const_iterator &Iter, ValueDecl *D) const;
  235. /// Checks if the variable is a local for OpenMP region.
  236. bool isOpenMPLocal(VarDecl *D, const_iterator Iter) const;
  237. /// Vector of previously declared requires directives
  238. SmallVector<const OMPRequiresDecl *, 2> RequiresDecls;
  239. /// omp_allocator_handle_t type.
  240. QualType OMPAllocatorHandleT;
  241. /// Expression for the predefined allocators.
  242. Expr *OMPPredefinedAllocators[OMPAllocateDeclAttr::OMPUserDefinedMemAlloc] = {
  243. nullptr};
  244. /// Vector of previously encountered target directives
  245. SmallVector<SourceLocation, 2> TargetLocations;
  246. public:
  247. explicit DSAStackTy(Sema &S) : SemaRef(S) {}
  248. /// Sets omp_allocator_handle_t type.
  249. void setOMPAllocatorHandleT(QualType Ty) { OMPAllocatorHandleT = Ty; }
  250. /// Gets omp_allocator_handle_t type.
  251. QualType getOMPAllocatorHandleT() const { return OMPAllocatorHandleT; }
  252. /// Sets the given default allocator.
  253. void setAllocator(OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind,
  254. Expr *Allocator) {
  255. OMPPredefinedAllocators[AllocatorKind] = Allocator;
  256. }
  257. /// Returns the specified default allocator.
  258. Expr *getAllocator(OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind) const {
  259. return OMPPredefinedAllocators[AllocatorKind];
  260. }
  261. bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; }
  262. OpenMPClauseKind getClauseParsingMode() const {
  263. assert(isClauseParsingMode() && "Must be in clause parsing mode.");
  264. return ClauseKindMode;
  265. }
  266. void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; }
  267. bool isBodyComplete() const {
  268. const SharingMapTy *Top = getTopOfStackOrNull();
  269. return Top && Top->BodyComplete;
  270. }
  271. void setBodyComplete() {
  272. getTopOfStack().BodyComplete = true;
  273. }
  274. bool isForceVarCapturing() const { return ForceCapturing; }
  275. void setForceVarCapturing(bool V) { ForceCapturing = V; }
  276. void setForceCaptureByReferenceInTargetExecutable(bool V) {
  277. ForceCaptureByReferenceInTargetExecutable = V;
  278. }
  279. bool isForceCaptureByReferenceInTargetExecutable() const {
  280. return ForceCaptureByReferenceInTargetExecutable;
  281. }
  282. void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
  283. Scope *CurScope, SourceLocation Loc) {
  284. assert(!IgnoredStackElements &&
  285. "cannot change stack while ignoring elements");
  286. if (Stack.empty() ||
  287. Stack.back().second != CurrentNonCapturingFunctionScope)
  288. Stack.emplace_back(StackTy(), CurrentNonCapturingFunctionScope);
  289. Stack.back().first.emplace_back(DKind, DirName, CurScope, Loc);
  290. Stack.back().first.back().DefaultAttrLoc = Loc;
  291. }
  292. void pop() {
  293. assert(!IgnoredStackElements &&
  294. "cannot change stack while ignoring elements");
  295. assert(!Stack.back().first.empty() &&
  296. "Data-sharing attributes stack is empty!");
  297. Stack.back().first.pop_back();
  298. }
  299. /// RAII object to temporarily leave the scope of a directive when we want to
  300. /// logically operate in its parent.
  301. class ParentDirectiveScope {
  302. DSAStackTy &Self;
  303. bool Active;
  304. public:
  305. ParentDirectiveScope(DSAStackTy &Self, bool Activate)
  306. : Self(Self), Active(false) {
  307. if (Activate)
  308. enable();
  309. }
  310. ~ParentDirectiveScope() { disable(); }
  311. void disable() {
  312. if (Active) {
  313. --Self.IgnoredStackElements;
  314. Active = false;
  315. }
  316. }
  317. void enable() {
  318. if (!Active) {
  319. ++Self.IgnoredStackElements;
  320. Active = true;
  321. }
  322. }
  323. };
  324. /// Marks that we're started loop parsing.
  325. void loopInit() {
  326. assert(isOpenMPLoopDirective(getCurrentDirective()) &&
  327. "Expected loop-based directive.");
  328. getTopOfStack().LoopStart = true;
  329. }
  330. /// Start capturing of the variables in the loop context.
  331. void loopStart() {
  332. assert(isOpenMPLoopDirective(getCurrentDirective()) &&
  333. "Expected loop-based directive.");
  334. getTopOfStack().LoopStart = false;
  335. }
  336. /// true, if variables are captured, false otherwise.
  337. bool isLoopStarted() const {
  338. assert(isOpenMPLoopDirective(getCurrentDirective()) &&
  339. "Expected loop-based directive.");
  340. return !getTopOfStack().LoopStart;
  341. }
  342. /// Marks (or clears) declaration as possibly loop counter.
  343. void resetPossibleLoopCounter(const Decl *D = nullptr) {
  344. getTopOfStack().PossiblyLoopCounter =
  345. D ? D->getCanonicalDecl() : D;
  346. }
  347. /// Gets the possible loop counter decl.
  348. const Decl *getPossiblyLoopCunter() const {
  349. return getTopOfStack().PossiblyLoopCounter;
  350. }
  351. /// Start new OpenMP region stack in new non-capturing function.
  352. void pushFunction() {
  353. assert(!IgnoredStackElements &&
  354. "cannot change stack while ignoring elements");
  355. const FunctionScopeInfo *CurFnScope = SemaRef.getCurFunction();
  356. assert(!isa<CapturingScopeInfo>(CurFnScope));
  357. CurrentNonCapturingFunctionScope = CurFnScope;
  358. }
  359. /// Pop region stack for non-capturing function.
  360. void popFunction(const FunctionScopeInfo *OldFSI) {
  361. assert(!IgnoredStackElements &&
  362. "cannot change stack while ignoring elements");
  363. if (!Stack.empty() && Stack.back().second == OldFSI) {
  364. assert(Stack.back().first.empty());
  365. Stack.pop_back();
  366. }
  367. CurrentNonCapturingFunctionScope = nullptr;
  368. for (const FunctionScopeInfo *FSI : llvm::reverse(SemaRef.FunctionScopes)) {
  369. if (!isa<CapturingScopeInfo>(FSI)) {
  370. CurrentNonCapturingFunctionScope = FSI;
  371. break;
  372. }
  373. }
  374. }
  375. void addCriticalWithHint(const OMPCriticalDirective *D, llvm::APSInt Hint) {
  376. Criticals.try_emplace(D->getDirectiveName().getAsString(), D, Hint);
  377. }
  378. const std::pair<const OMPCriticalDirective *, llvm::APSInt>
  379. getCriticalWithHint(const DeclarationNameInfo &Name) const {
  380. auto I = Criticals.find(Name.getAsString());
  381. if (I != Criticals.end())
  382. return I->second;
  383. return std::make_pair(nullptr, llvm::APSInt());
  384. }
  385. /// If 'aligned' declaration for given variable \a D was not seen yet,
  386. /// add it and return NULL; otherwise return previous occurrence's expression
  387. /// for diagnostics.
  388. const Expr *addUniqueAligned(const ValueDecl *D, const Expr *NewDE);
  389. /// Register specified variable as loop control variable.
  390. void addLoopControlVariable(const ValueDecl *D, VarDecl *Capture);
  391. /// Check if the specified variable is a loop control variable for
  392. /// current region.
  393. /// \return The index of the loop control variable in the list of associated
  394. /// for-loops (from outer to inner).
  395. const LCDeclInfo isLoopControlVariable(const ValueDecl *D) const;
  396. /// Check if the specified variable is a loop control variable for
  397. /// parent region.
  398. /// \return The index of the loop control variable in the list of associated
  399. /// for-loops (from outer to inner).
  400. const LCDeclInfo isParentLoopControlVariable(const ValueDecl *D) const;
  401. /// Get the loop control variable for the I-th loop (or nullptr) in
  402. /// parent directive.
  403. const ValueDecl *getParentLoopControlVariable(unsigned I) const;
  404. /// Adds explicit data sharing attribute to the specified declaration.
  405. void addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A,
  406. DeclRefExpr *PrivateCopy = nullptr);
  407. /// Adds additional information for the reduction items with the reduction id
  408. /// represented as an operator.
  409. void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
  410. BinaryOperatorKind BOK);
  411. /// Adds additional information for the reduction items with the reduction id
  412. /// represented as reduction identifier.
  413. void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
  414. const Expr *ReductionRef);
  415. /// Returns the location and reduction operation from the innermost parent
  416. /// region for the given \p D.
  417. const DSAVarData
  418. getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR,
  419. BinaryOperatorKind &BOK,
  420. Expr *&TaskgroupDescriptor) const;
  421. /// Returns the location and reduction operation from the innermost parent
  422. /// region for the given \p D.
  423. const DSAVarData
  424. getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR,
  425. const Expr *&ReductionRef,
  426. Expr *&TaskgroupDescriptor) const;
  427. /// Return reduction reference expression for the current taskgroup.
  428. Expr *getTaskgroupReductionRef() const {
  429. assert(getTopOfStack().Directive == OMPD_taskgroup &&
  430. "taskgroup reference expression requested for non taskgroup "
  431. "directive.");
  432. return getTopOfStack().TaskgroupReductionRef;
  433. }
  434. /// Checks if the given \p VD declaration is actually a taskgroup reduction
  435. /// descriptor variable at the \p Level of OpenMP regions.
  436. bool isTaskgroupReductionRef(const ValueDecl *VD, unsigned Level) const {
  437. return getStackElemAtLevel(Level).TaskgroupReductionRef &&
  438. cast<DeclRefExpr>(getStackElemAtLevel(Level).TaskgroupReductionRef)
  439. ->getDecl() == VD;
  440. }
  441. /// Returns data sharing attributes from top of the stack for the
  442. /// specified declaration.
  443. const DSAVarData getTopDSA(ValueDecl *D, bool FromParent);
  444. /// Returns data-sharing attributes for the specified declaration.
  445. const DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent) const;
  446. /// Checks if the specified variables has data-sharing attributes which
  447. /// match specified \a CPred predicate in any directive which matches \a DPred
  448. /// predicate.
  449. const DSAVarData
  450. hasDSA(ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
  451. const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
  452. bool FromParent) const;
  453. /// Checks if the specified variables has data-sharing attributes which
  454. /// match specified \a CPred predicate in any innermost directive which
  455. /// matches \a DPred predicate.
  456. const DSAVarData
  457. hasInnermostDSA(ValueDecl *D,
  458. const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
  459. const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
  460. bool FromParent) const;
  461. /// Checks if the specified variables has explicit data-sharing
  462. /// attributes which match specified \a CPred predicate at the specified
  463. /// OpenMP region.
  464. bool hasExplicitDSA(const ValueDecl *D,
  465. const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
  466. unsigned Level, bool NotLastprivate = false) const;
  467. /// Returns true if the directive at level \Level matches in the
  468. /// specified \a DPred predicate.
  469. bool hasExplicitDirective(
  470. const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
  471. unsigned Level) const;
  472. /// Finds a directive which matches specified \a DPred predicate.
  473. bool hasDirective(
  474. const llvm::function_ref<bool(
  475. OpenMPDirectiveKind, const DeclarationNameInfo &, SourceLocation)>
  476. DPred,
  477. bool FromParent) const;
  478. /// Returns currently analyzed directive.
  479. OpenMPDirectiveKind getCurrentDirective() const {
  480. const SharingMapTy *Top = getTopOfStackOrNull();
  481. return Top ? Top->Directive : OMPD_unknown;
  482. }
  483. /// Returns directive kind at specified level.
  484. OpenMPDirectiveKind getDirective(unsigned Level) const {
  485. assert(!isStackEmpty() && "No directive at specified level.");
  486. return getStackElemAtLevel(Level).Directive;
  487. }
  488. /// Returns the capture region at the specified level.
  489. OpenMPDirectiveKind getCaptureRegion(unsigned Level,
  490. unsigned OpenMPCaptureLevel) const {
  491. SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
  492. getOpenMPCaptureRegions(CaptureRegions, getDirective(Level));
  493. return CaptureRegions[OpenMPCaptureLevel];
  494. }
  495. /// Returns parent directive.
  496. OpenMPDirectiveKind getParentDirective() const {
  497. const SharingMapTy *Parent = getSecondOnStackOrNull();
  498. return Parent ? Parent->Directive : OMPD_unknown;
  499. }
  500. /// Add requires decl to internal vector
  501. void addRequiresDecl(OMPRequiresDecl *RD) {
  502. RequiresDecls.push_back(RD);
  503. }
  504. /// Checks if the defined 'requires' directive has specified type of clause.
  505. template <typename ClauseType>
  506. bool hasRequiresDeclWithClause() {
  507. return llvm::any_of(RequiresDecls, [](const OMPRequiresDecl *D) {
  508. return llvm::any_of(D->clauselists(), [](const OMPClause *C) {
  509. return isa<ClauseType>(C);
  510. });
  511. });
  512. }
  513. /// Checks for a duplicate clause amongst previously declared requires
  514. /// directives
  515. bool hasDuplicateRequiresClause(ArrayRef<OMPClause *> ClauseList) const {
  516. bool IsDuplicate = false;
  517. for (OMPClause *CNew : ClauseList) {
  518. for (const OMPRequiresDecl *D : RequiresDecls) {
  519. for (const OMPClause *CPrev : D->clauselists()) {
  520. if (CNew->getClauseKind() == CPrev->getClauseKind()) {
  521. SemaRef.Diag(CNew->getBeginLoc(),
  522. diag::err_omp_requires_clause_redeclaration)
  523. << getOpenMPClauseName(CNew->getClauseKind());
  524. SemaRef.Diag(CPrev->getBeginLoc(),
  525. diag::note_omp_requires_previous_clause)
  526. << getOpenMPClauseName(CPrev->getClauseKind());
  527. IsDuplicate = true;
  528. }
  529. }
  530. }
  531. }
  532. return IsDuplicate;
  533. }
  534. /// Add location of previously encountered target to internal vector
  535. void addTargetDirLocation(SourceLocation LocStart) {
  536. TargetLocations.push_back(LocStart);
  537. }
  538. // Return previously encountered target region locations.
  539. ArrayRef<SourceLocation> getEncounteredTargetLocs() const {
  540. return TargetLocations;
  541. }
  542. /// Set default data sharing attribute to none.
  543. void setDefaultDSANone(SourceLocation Loc) {
  544. getTopOfStack().DefaultAttr = DSA_none;
  545. getTopOfStack().DefaultAttrLoc = Loc;
  546. }
  547. /// Set default data sharing attribute to shared.
  548. void setDefaultDSAShared(SourceLocation Loc) {
  549. getTopOfStack().DefaultAttr = DSA_shared;
  550. getTopOfStack().DefaultAttrLoc = Loc;
  551. }
  552. /// Set default data mapping attribute to 'tofrom:scalar'.
  553. void setDefaultDMAToFromScalar(SourceLocation Loc) {
  554. getTopOfStack().DefaultMapAttr = DMA_tofrom_scalar;
  555. getTopOfStack().DefaultMapAttrLoc = Loc;
  556. }
  557. DefaultDataSharingAttributes getDefaultDSA() const {
  558. return isStackEmpty() ? DSA_unspecified
  559. : getTopOfStack().DefaultAttr;
  560. }
  561. SourceLocation getDefaultDSALocation() const {
  562. return isStackEmpty() ? SourceLocation()
  563. : getTopOfStack().DefaultAttrLoc;
  564. }
  565. DefaultMapAttributes getDefaultDMA() const {
  566. return isStackEmpty() ? DMA_unspecified
  567. : getTopOfStack().DefaultMapAttr;
  568. }
  569. DefaultMapAttributes getDefaultDMAAtLevel(unsigned Level) const {
  570. return getStackElemAtLevel(Level).DefaultMapAttr;
  571. }
  572. SourceLocation getDefaultDMALocation() const {
  573. return isStackEmpty() ? SourceLocation()
  574. : getTopOfStack().DefaultMapAttrLoc;
  575. }
  576. /// Checks if the specified variable is a threadprivate.
  577. bool isThreadPrivate(VarDecl *D) {
  578. const DSAVarData DVar = getTopDSA(D, false);
  579. return isOpenMPThreadPrivate(DVar.CKind);
  580. }
  581. /// Marks current region as ordered (it has an 'ordered' clause).
  582. void setOrderedRegion(bool IsOrdered, const Expr *Param,
  583. OMPOrderedClause *Clause) {
  584. if (IsOrdered)
  585. getTopOfStack().OrderedRegion.emplace(Param, Clause);
  586. else
  587. getTopOfStack().OrderedRegion.reset();
  588. }
  589. /// Returns true, if region is ordered (has associated 'ordered' clause),
  590. /// false - otherwise.
  591. bool isOrderedRegion() const {
  592. if (const SharingMapTy *Top = getTopOfStackOrNull())
  593. return Top->OrderedRegion.hasValue();
  594. return false;
  595. }
  596. /// Returns optional parameter for the ordered region.
  597. std::pair<const Expr *, OMPOrderedClause *> getOrderedRegionParam() const {
  598. if (const SharingMapTy *Top = getTopOfStackOrNull())
  599. if (Top->OrderedRegion.hasValue())
  600. return Top->OrderedRegion.getValue();
  601. return std::make_pair(nullptr, nullptr);
  602. }
  603. /// Returns true, if parent region is ordered (has associated
  604. /// 'ordered' clause), false - otherwise.
  605. bool isParentOrderedRegion() const {
  606. if (const SharingMapTy *Parent = getSecondOnStackOrNull())
  607. return Parent->OrderedRegion.hasValue();
  608. return false;
  609. }
  610. /// Returns optional parameter for the ordered region.
  611. std::pair<const Expr *, OMPOrderedClause *>
  612. getParentOrderedRegionParam() const {
  613. if (const SharingMapTy *Parent = getSecondOnStackOrNull())
  614. if (Parent->OrderedRegion.hasValue())
  615. return Parent->OrderedRegion.getValue();
  616. return std::make_pair(nullptr, nullptr);
  617. }
  618. /// Marks current region as nowait (it has a 'nowait' clause).
  619. void setNowaitRegion(bool IsNowait = true) {
  620. getTopOfStack().NowaitRegion = IsNowait;
  621. }
  622. /// Returns true, if parent region is nowait (has associated
  623. /// 'nowait' clause), false - otherwise.
  624. bool isParentNowaitRegion() const {
  625. if (const SharingMapTy *Parent = getSecondOnStackOrNull())
  626. return Parent->NowaitRegion;
  627. return false;
  628. }
  629. /// Marks parent region as cancel region.
  630. void setParentCancelRegion(bool Cancel = true) {
  631. if (SharingMapTy *Parent = getSecondOnStackOrNull())
  632. Parent->CancelRegion |= Cancel;
  633. }
  634. /// Return true if current region has inner cancel construct.
  635. bool isCancelRegion() const {
  636. const SharingMapTy *Top = getTopOfStackOrNull();
  637. return Top ? Top->CancelRegion : false;
  638. }
  639. /// Set collapse value for the region.
  640. void setAssociatedLoops(unsigned Val) {
  641. getTopOfStack().AssociatedLoops = Val;
  642. if (Val > 1)
  643. getTopOfStack().HasMutipleLoops = true;
  644. }
  645. /// Return collapse value for region.
  646. unsigned getAssociatedLoops() const {
  647. const SharingMapTy *Top = getTopOfStackOrNull();
  648. return Top ? Top->AssociatedLoops : 0;
  649. }
  650. /// Returns true if the construct is associated with multiple loops.
  651. bool hasMutipleLoops() const {
  652. const SharingMapTy *Top = getTopOfStackOrNull();
  653. return Top ? Top->HasMutipleLoops : false;
  654. }
  655. /// Marks current target region as one with closely nested teams
  656. /// region.
  657. void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
  658. if (SharingMapTy *Parent = getSecondOnStackOrNull())
  659. Parent->InnerTeamsRegionLoc = TeamsRegionLoc;
  660. }
  661. /// Returns true, if current region has closely nested teams region.
  662. bool hasInnerTeamsRegion() const {
  663. return getInnerTeamsRegionLoc().isValid();
  664. }
  665. /// Returns location of the nested teams region (if any).
  666. SourceLocation getInnerTeamsRegionLoc() const {
  667. const SharingMapTy *Top = getTopOfStackOrNull();
  668. return Top ? Top->InnerTeamsRegionLoc : SourceLocation();
  669. }
  670. Scope *getCurScope() const {
  671. const SharingMapTy *Top = getTopOfStackOrNull();
  672. return Top ? Top->CurScope : nullptr;
  673. }
  674. SourceLocation getConstructLoc() const {
  675. const SharingMapTy *Top = getTopOfStackOrNull();
  676. return Top ? Top->ConstructLoc : SourceLocation();
  677. }
  678. /// Do the check specified in \a Check to all component lists and return true
  679. /// if any issue is found.
  680. bool checkMappableExprComponentListsForDecl(
  681. const ValueDecl *VD, bool CurrentRegionOnly,
  682. const llvm::function_ref<
  683. bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
  684. OpenMPClauseKind)>
  685. Check) const {
  686. if (isStackEmpty())
  687. return false;
  688. auto SI = begin();
  689. auto SE = end();
  690. if (SI == SE)
  691. return false;
  692. if (CurrentRegionOnly)
  693. SE = std::next(SI);
  694. else
  695. std::advance(SI, 1);
  696. for (; SI != SE; ++SI) {
  697. auto MI = SI->MappedExprComponents.find(VD);
  698. if (MI != SI->MappedExprComponents.end())
  699. for (OMPClauseMappableExprCommon::MappableExprComponentListRef L :
  700. MI->second.Components)
  701. if (Check(L, MI->second.Kind))
  702. return true;
  703. }
  704. return false;
  705. }
  706. /// Do the check specified in \a Check to all component lists at a given level
  707. /// and return true if any issue is found.
  708. bool checkMappableExprComponentListsForDeclAtLevel(
  709. const ValueDecl *VD, unsigned Level,
  710. const llvm::function_ref<
  711. bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
  712. OpenMPClauseKind)>
  713. Check) const {
  714. if (getStackSize() <= Level)
  715. return false;
  716. const SharingMapTy &StackElem = getStackElemAtLevel(Level);
  717. auto MI = StackElem.MappedExprComponents.find(VD);
  718. if (MI != StackElem.MappedExprComponents.end())
  719. for (OMPClauseMappableExprCommon::MappableExprComponentListRef L :
  720. MI->second.Components)
  721. if (Check(L, MI->second.Kind))
  722. return true;
  723. return false;
  724. }
  725. /// Create a new mappable expression component list associated with a given
  726. /// declaration and initialize it with the provided list of components.
  727. void addMappableExpressionComponents(
  728. const ValueDecl *VD,
  729. OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
  730. OpenMPClauseKind WhereFoundClauseKind) {
  731. MappedExprComponentTy &MEC = getTopOfStack().MappedExprComponents[VD];
  732. // Create new entry and append the new components there.
  733. MEC.Components.resize(MEC.Components.size() + 1);
  734. MEC.Components.back().append(Components.begin(), Components.end());
  735. MEC.Kind = WhereFoundClauseKind;
  736. }
  737. unsigned getNestingLevel() const {
  738. assert(!isStackEmpty());
  739. return getStackSize() - 1;
  740. }
  741. void addDoacrossDependClause(OMPDependClause *C,
  742. const OperatorOffsetTy &OpsOffs) {
  743. SharingMapTy *Parent = getSecondOnStackOrNull();
  744. assert(Parent && isOpenMPWorksharingDirective(Parent->Directive));
  745. Parent->DoacrossDepends.try_emplace(C, OpsOffs);
  746. }
  747. llvm::iterator_range<DoacrossDependMapTy::const_iterator>
  748. getDoacrossDependClauses() const {
  749. const SharingMapTy &StackElem = getTopOfStack();
  750. if (isOpenMPWorksharingDirective(StackElem.Directive)) {
  751. const DoacrossDependMapTy &Ref = StackElem.DoacrossDepends;
  752. return llvm::make_range(Ref.begin(), Ref.end());
  753. }
  754. return llvm::make_range(StackElem.DoacrossDepends.end(),
  755. StackElem.DoacrossDepends.end());
  756. }
  757. // Store types of classes which have been explicitly mapped
  758. void addMappedClassesQualTypes(QualType QT) {
  759. SharingMapTy &StackElem = getTopOfStack();
  760. StackElem.MappedClassesQualTypes.insert(QT);
  761. }
  762. // Return set of mapped classes types
  763. bool isClassPreviouslyMapped(QualType QT) const {
  764. const SharingMapTy &StackElem = getTopOfStack();
  765. return StackElem.MappedClassesQualTypes.count(QT) != 0;
  766. }
  767. /// Adds global declare target to the parent target region.
  768. void addToParentTargetRegionLinkGlobals(DeclRefExpr *E) {
  769. assert(*OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(
  770. E->getDecl()) == OMPDeclareTargetDeclAttr::MT_Link &&
  771. "Expected declare target link global.");
  772. for (auto &Elem : *this) {
  773. if (isOpenMPTargetExecutionDirective(Elem.Directive)) {
  774. Elem.DeclareTargetLinkVarDecls.push_back(E);
  775. return;
  776. }
  777. }
  778. }
  779. /// Returns the list of globals with declare target link if current directive
  780. /// is target.
  781. ArrayRef<DeclRefExpr *> getLinkGlobals() const {
  782. assert(isOpenMPTargetExecutionDirective(getCurrentDirective()) &&
  783. "Expected target executable directive.");
  784. return getTopOfStack().DeclareTargetLinkVarDecls;
  785. }
  786. };
  787. bool isImplicitTaskingRegion(OpenMPDirectiveKind DKind) {
  788. return isOpenMPParallelDirective(DKind) || isOpenMPTeamsDirective(DKind);
  789. }
  790. bool isImplicitOrExplicitTaskingRegion(OpenMPDirectiveKind DKind) {
  791. return isImplicitTaskingRegion(DKind) || isOpenMPTaskingDirective(DKind) ||
  792. DKind == OMPD_unknown;
  793. }
  794. } // namespace
  795. static const Expr *getExprAsWritten(const Expr *E) {
  796. if (const auto *FE = dyn_cast<FullExpr>(E))
  797. E = FE->getSubExpr();
  798. if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
  799. E = MTE->GetTemporaryExpr();
  800. while (const auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
  801. E = Binder->getSubExpr();
  802. if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
  803. E = ICE->getSubExprAsWritten();
  804. return E->IgnoreParens();
  805. }
  806. static Expr *getExprAsWritten(Expr *E) {
  807. return const_cast<Expr *>(getExprAsWritten(const_cast<const Expr *>(E)));
  808. }
  809. static const ValueDecl *getCanonicalDecl(const ValueDecl *D) {
  810. if (const auto *CED = dyn_cast<OMPCapturedExprDecl>(D))
  811. if (const auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
  812. D = ME->getMemberDecl();
  813. const auto *VD = dyn_cast<VarDecl>(D);
  814. const auto *FD = dyn_cast<FieldDecl>(D);
  815. if (VD != nullptr) {
  816. VD = VD->getCanonicalDecl();
  817. D = VD;
  818. } else {
  819. assert(FD);
  820. FD = FD->getCanonicalDecl();
  821. D = FD;
  822. }
  823. return D;
  824. }
  825. static ValueDecl *getCanonicalDecl(ValueDecl *D) {
  826. return const_cast<ValueDecl *>(
  827. getCanonicalDecl(const_cast<const ValueDecl *>(D)));
  828. }
  829. DSAStackTy::DSAVarData DSAStackTy::getDSA(const_iterator &Iter,
  830. ValueDecl *D) const {
  831. D = getCanonicalDecl(D);
  832. auto *VD = dyn_cast<VarDecl>(D);
  833. const auto *FD = dyn_cast<FieldDecl>(D);
  834. DSAVarData DVar;
  835. if (Iter == end()) {
  836. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  837. // in a region but not in construct]
  838. // File-scope or namespace-scope variables referenced in called routines
  839. // in the region are shared unless they appear in a threadprivate
  840. // directive.
  841. if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(VD))
  842. DVar.CKind = OMPC_shared;
  843. // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
  844. // in a region but not in construct]
  845. // Variables with static storage duration that are declared in called
  846. // routines in the region are shared.
  847. if (VD && VD->hasGlobalStorage())
  848. DVar.CKind = OMPC_shared;
  849. // Non-static data members are shared by default.
  850. if (FD)
  851. DVar.CKind = OMPC_shared;
  852. return DVar;
  853. }
  854. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  855. // in a Construct, C/C++, predetermined, p.1]
  856. // Variables with automatic storage duration that are declared in a scope
  857. // inside the construct are private.
  858. if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() &&
  859. (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) {
  860. DVar.CKind = OMPC_private;
  861. return DVar;
  862. }
  863. DVar.DKind = Iter->Directive;
  864. // Explicitly specified attributes and local variables with predetermined
  865. // attributes.
  866. if (Iter->SharingMap.count(D)) {
  867. const DSAInfo &Data = Iter->SharingMap.lookup(D);
  868. DVar.RefExpr = Data.RefExpr.getPointer();
  869. DVar.PrivateCopy = Data.PrivateCopy;
  870. DVar.CKind = Data.Attributes;
  871. DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
  872. return DVar;
  873. }
  874. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  875. // in a Construct, C/C++, implicitly determined, p.1]
  876. // In a parallel or task construct, the data-sharing attributes of these
  877. // variables are determined by the default clause, if present.
  878. switch (Iter->DefaultAttr) {
  879. case DSA_shared:
  880. DVar.CKind = OMPC_shared;
  881. DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
  882. return DVar;
  883. case DSA_none:
  884. return DVar;
  885. case DSA_unspecified:
  886. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  887. // in a Construct, implicitly determined, p.2]
  888. // In a parallel construct, if no default clause is present, these
  889. // variables are shared.
  890. DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
  891. if (isOpenMPParallelDirective(DVar.DKind) ||
  892. isOpenMPTeamsDirective(DVar.DKind)) {
  893. DVar.CKind = OMPC_shared;
  894. return DVar;
  895. }
  896. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  897. // in a Construct, implicitly determined, p.4]
  898. // In a task construct, if no default clause is present, a variable that in
  899. // the enclosing context is determined to be shared by all implicit tasks
  900. // bound to the current team is shared.
  901. if (isOpenMPTaskingDirective(DVar.DKind)) {
  902. DSAVarData DVarTemp;
  903. const_iterator I = Iter, E = end();
  904. do {
  905. ++I;
  906. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
  907. // Referenced in a Construct, implicitly determined, p.6]
  908. // In a task construct, if no default clause is present, a variable
  909. // whose data-sharing attribute is not determined by the rules above is
  910. // firstprivate.
  911. DVarTemp = getDSA(I, D);
  912. if (DVarTemp.CKind != OMPC_shared) {
  913. DVar.RefExpr = nullptr;
  914. DVar.CKind = OMPC_firstprivate;
  915. return DVar;
  916. }
  917. } while (I != E && !isImplicitTaskingRegion(I->Directive));
  918. DVar.CKind =
  919. (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
  920. return DVar;
  921. }
  922. }
  923. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  924. // in a Construct, implicitly determined, p.3]
  925. // For constructs other than task, if no default clause is present, these
  926. // variables inherit their data-sharing attributes from the enclosing
  927. // context.
  928. return getDSA(++Iter, D);
  929. }
  930. const Expr *DSAStackTy::addUniqueAligned(const ValueDecl *D,
  931. const Expr *NewDE) {
  932. assert(!isStackEmpty() && "Data sharing attributes stack is empty");
  933. D = getCanonicalDecl(D);
  934. SharingMapTy &StackElem = getTopOfStack();
  935. auto It = StackElem.AlignedMap.find(D);
  936. if (It == StackElem.AlignedMap.end()) {
  937. assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
  938. StackElem.AlignedMap[D] = NewDE;
  939. return nullptr;
  940. }
  941. assert(It->second && "Unexpected nullptr expr in the aligned map");
  942. return It->second;
  943. }
  944. void DSAStackTy::addLoopControlVariable(const ValueDecl *D, VarDecl *Capture) {
  945. assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
  946. D = getCanonicalDecl(D);
  947. SharingMapTy &StackElem = getTopOfStack();
  948. StackElem.LCVMap.try_emplace(
  949. D, LCDeclInfo(StackElem.LCVMap.size() + 1, Capture));
  950. }
  951. const DSAStackTy::LCDeclInfo
  952. DSAStackTy::isLoopControlVariable(const ValueDecl *D) const {
  953. assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
  954. D = getCanonicalDecl(D);
  955. const SharingMapTy &StackElem = getTopOfStack();
  956. auto It = StackElem.LCVMap.find(D);
  957. if (It != StackElem.LCVMap.end())
  958. return It->second;
  959. return {0, nullptr};
  960. }
  961. const DSAStackTy::LCDeclInfo
  962. DSAStackTy::isParentLoopControlVariable(const ValueDecl *D) const {
  963. const SharingMapTy *Parent = getSecondOnStackOrNull();
  964. assert(Parent && "Data-sharing attributes stack is empty");
  965. D = getCanonicalDecl(D);
  966. auto It = Parent->LCVMap.find(D);
  967. if (It != Parent->LCVMap.end())
  968. return It->second;
  969. return {0, nullptr};
  970. }
  971. const ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) const {
  972. const SharingMapTy *Parent = getSecondOnStackOrNull();
  973. assert(Parent && "Data-sharing attributes stack is empty");
  974. if (Parent->LCVMap.size() < I)
  975. return nullptr;
  976. for (const auto &Pair : Parent->LCVMap)
  977. if (Pair.second.first == I)
  978. return Pair.first;
  979. return nullptr;
  980. }
  981. void DSAStackTy::addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A,
  982. DeclRefExpr *PrivateCopy) {
  983. D = getCanonicalDecl(D);
  984. if (A == OMPC_threadprivate) {
  985. DSAInfo &Data = Threadprivates[D];
  986. Data.Attributes = A;
  987. Data.RefExpr.setPointer(E);
  988. Data.PrivateCopy = nullptr;
  989. } else {
  990. DSAInfo &Data = getTopOfStack().SharingMap[D];
  991. assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) ||
  992. (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) ||
  993. (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) ||
  994. (isLoopControlVariable(D).first && A == OMPC_private));
  995. if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) {
  996. Data.RefExpr.setInt(/*IntVal=*/true);
  997. return;
  998. }
  999. const bool IsLastprivate =
  1000. A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate;
  1001. Data.Attributes = A;
  1002. Data.RefExpr.setPointerAndInt(E, IsLastprivate);
  1003. Data.PrivateCopy = PrivateCopy;
  1004. if (PrivateCopy) {
  1005. DSAInfo &Data = getTopOfStack().SharingMap[PrivateCopy->getDecl()];
  1006. Data.Attributes = A;
  1007. Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate);
  1008. Data.PrivateCopy = nullptr;
  1009. }
  1010. }
  1011. }
  1012. /// Build a variable declaration for OpenMP loop iteration variable.
  1013. static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
  1014. StringRef Name, const AttrVec *Attrs = nullptr,
  1015. DeclRefExpr *OrigRef = nullptr) {
  1016. DeclContext *DC = SemaRef.CurContext;
  1017. IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
  1018. TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
  1019. auto *Decl =
  1020. VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
  1021. if (Attrs) {
  1022. for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end());
  1023. I != E; ++I)
  1024. Decl->addAttr(*I);
  1025. }
  1026. Decl->setImplicit();
  1027. if (OrigRef) {
  1028. Decl->addAttr(
  1029. OMPReferencedVarAttr::CreateImplicit(SemaRef.Context, OrigRef));
  1030. }
  1031. return Decl;
  1032. }
  1033. static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
  1034. SourceLocation Loc,
  1035. bool RefersToCapture = false) {
  1036. D->setReferenced();
  1037. D->markUsed(S.Context);
  1038. return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
  1039. SourceLocation(), D, RefersToCapture, Loc, Ty,
  1040. VK_LValue);
  1041. }
  1042. void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
  1043. BinaryOperatorKind BOK) {
  1044. D = getCanonicalDecl(D);
  1045. assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
  1046. assert(
  1047. getTopOfStack().SharingMap[D].Attributes == OMPC_reduction &&
  1048. "Additional reduction info may be specified only for reduction items.");
  1049. ReductionData &ReductionData = getTopOfStack().ReductionMap[D];
  1050. assert(ReductionData.ReductionRange.isInvalid() &&
  1051. getTopOfStack().Directive == OMPD_taskgroup &&
  1052. "Additional reduction info may be specified only once for reduction "
  1053. "items.");
  1054. ReductionData.set(BOK, SR);
  1055. Expr *&TaskgroupReductionRef =
  1056. getTopOfStack().TaskgroupReductionRef;
  1057. if (!TaskgroupReductionRef) {
  1058. VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(),
  1059. SemaRef.Context.VoidPtrTy, ".task_red.");
  1060. TaskgroupReductionRef =
  1061. buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
  1062. }
  1063. }
  1064. void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
  1065. const Expr *ReductionRef) {
  1066. D = getCanonicalDecl(D);
  1067. assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
  1068. assert(
  1069. getTopOfStack().SharingMap[D].Attributes == OMPC_reduction &&
  1070. "Additional reduction info may be specified only for reduction items.");
  1071. ReductionData &ReductionData = getTopOfStack().ReductionMap[D];
  1072. assert(ReductionData.ReductionRange.isInvalid() &&
  1073. getTopOfStack().Directive == OMPD_taskgroup &&
  1074. "Additional reduction info may be specified only once for reduction "
  1075. "items.");
  1076. ReductionData.set(ReductionRef, SR);
  1077. Expr *&TaskgroupReductionRef =
  1078. getTopOfStack().TaskgroupReductionRef;
  1079. if (!TaskgroupReductionRef) {
  1080. VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(),
  1081. SemaRef.Context.VoidPtrTy, ".task_red.");
  1082. TaskgroupReductionRef =
  1083. buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
  1084. }
  1085. }
  1086. const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData(
  1087. const ValueDecl *D, SourceRange &SR, BinaryOperatorKind &BOK,
  1088. Expr *&TaskgroupDescriptor) const {
  1089. D = getCanonicalDecl(D);
  1090. assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
  1091. for (const_iterator I = begin() + 1, E = end(); I != E; ++I) {
  1092. const DSAInfo &Data = I->SharingMap.lookup(D);
  1093. if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
  1094. continue;
  1095. const ReductionData &ReductionData = I->ReductionMap.lookup(D);
  1096. if (!ReductionData.ReductionOp ||
  1097. ReductionData.ReductionOp.is<const Expr *>())
  1098. return DSAVarData();
  1099. SR = ReductionData.ReductionRange;
  1100. BOK = ReductionData.ReductionOp.get<ReductionData::BOKPtrType>();
  1101. assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
  1102. "expression for the descriptor is not "
  1103. "set.");
  1104. TaskgroupDescriptor = I->TaskgroupReductionRef;
  1105. return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
  1106. Data.PrivateCopy, I->DefaultAttrLoc);
  1107. }
  1108. return DSAVarData();
  1109. }
  1110. const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData(
  1111. const ValueDecl *D, SourceRange &SR, const Expr *&ReductionRef,
  1112. Expr *&TaskgroupDescriptor) const {
  1113. D = getCanonicalDecl(D);
  1114. assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
  1115. for (const_iterator I = begin() + 1, E = end(); I != E; ++I) {
  1116. const DSAInfo &Data = I->SharingMap.lookup(D);
  1117. if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
  1118. continue;
  1119. const ReductionData &ReductionData = I->ReductionMap.lookup(D);
  1120. if (!ReductionData.ReductionOp ||
  1121. !ReductionData.ReductionOp.is<const Expr *>())
  1122. return DSAVarData();
  1123. SR = ReductionData.ReductionRange;
  1124. ReductionRef = ReductionData.ReductionOp.get<const Expr *>();
  1125. assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
  1126. "expression for the descriptor is not "
  1127. "set.");
  1128. TaskgroupDescriptor = I->TaskgroupReductionRef;
  1129. return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
  1130. Data.PrivateCopy, I->DefaultAttrLoc);
  1131. }
  1132. return DSAVarData();
  1133. }
  1134. bool DSAStackTy::isOpenMPLocal(VarDecl *D, const_iterator I) const {
  1135. D = D->getCanonicalDecl();
  1136. for (const_iterator E = end(); I != E; ++I) {
  1137. if (isImplicitOrExplicitTaskingRegion(I->Directive) ||
  1138. isOpenMPTargetExecutionDirective(I->Directive)) {
  1139. Scope *TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
  1140. Scope *CurScope = getCurScope();
  1141. while (CurScope && CurScope != TopScope && !CurScope->isDeclScope(D))
  1142. CurScope = CurScope->getParent();
  1143. return CurScope != TopScope;
  1144. }
  1145. }
  1146. return false;
  1147. }
  1148. static bool isConstNotMutableType(Sema &SemaRef, QualType Type,
  1149. bool AcceptIfMutable = true,
  1150. bool *IsClassType = nullptr) {
  1151. ASTContext &Context = SemaRef.getASTContext();
  1152. Type = Type.getNonReferenceType().getCanonicalType();
  1153. bool IsConstant = Type.isConstant(Context);
  1154. Type = Context.getBaseElementType(Type);
  1155. const CXXRecordDecl *RD = AcceptIfMutable && SemaRef.getLangOpts().CPlusPlus
  1156. ? Type->getAsCXXRecordDecl()
  1157. : nullptr;
  1158. if (const auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD))
  1159. if (const ClassTemplateDecl *CTD = CTSD->getSpecializedTemplate())
  1160. RD = CTD->getTemplatedDecl();
  1161. if (IsClassType)
  1162. *IsClassType = RD;
  1163. return IsConstant && !(SemaRef.getLangOpts().CPlusPlus && RD &&
  1164. RD->hasDefinition() && RD->hasMutableFields());
  1165. }
  1166. static bool rejectConstNotMutableType(Sema &SemaRef, const ValueDecl *D,
  1167. QualType Type, OpenMPClauseKind CKind,
  1168. SourceLocation ELoc,
  1169. bool AcceptIfMutable = true,
  1170. bool ListItemNotVar = false) {
  1171. ASTContext &Context = SemaRef.getASTContext();
  1172. bool IsClassType;
  1173. if (isConstNotMutableType(SemaRef, Type, AcceptIfMutable, &IsClassType)) {
  1174. unsigned Diag = ListItemNotVar
  1175. ? diag::err_omp_const_list_item
  1176. : IsClassType ? diag::err_omp_const_not_mutable_variable
  1177. : diag::err_omp_const_variable;
  1178. SemaRef.Diag(ELoc, Diag) << getOpenMPClauseName(CKind);
  1179. if (!ListItemNotVar && D) {
  1180. const VarDecl *VD = dyn_cast<VarDecl>(D);
  1181. bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
  1182. VarDecl::DeclarationOnly;
  1183. SemaRef.Diag(D->getLocation(),
  1184. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  1185. << D;
  1186. }
  1187. return true;
  1188. }
  1189. return false;
  1190. }
  1191. const DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D,
  1192. bool FromParent) {
  1193. D = getCanonicalDecl(D);
  1194. DSAVarData DVar;
  1195. auto *VD = dyn_cast<VarDecl>(D);
  1196. auto TI = Threadprivates.find(D);
  1197. if (TI != Threadprivates.end()) {
  1198. DVar.RefExpr = TI->getSecond().RefExpr.getPointer();
  1199. DVar.CKind = OMPC_threadprivate;
  1200. return DVar;
  1201. }
  1202. if (VD && VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
  1203. DVar.RefExpr = buildDeclRefExpr(
  1204. SemaRef, VD, D->getType().getNonReferenceType(),
  1205. VD->getAttr<OMPThreadPrivateDeclAttr>()->getLocation());
  1206. DVar.CKind = OMPC_threadprivate;
  1207. addDSA(D, DVar.RefExpr, OMPC_threadprivate);
  1208. return DVar;
  1209. }
  1210. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  1211. // in a Construct, C/C++, predetermined, p.1]
  1212. // Variables appearing in threadprivate directives are threadprivate.
  1213. if ((VD && VD->getTLSKind() != VarDecl::TLS_None &&
  1214. !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
  1215. SemaRef.getLangOpts().OpenMPUseTLS &&
  1216. SemaRef.getASTContext().getTargetInfo().isTLSSupported())) ||
  1217. (VD && VD->getStorageClass() == SC_Register &&
  1218. VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) {
  1219. DVar.RefExpr = buildDeclRefExpr(
  1220. SemaRef, VD, D->getType().getNonReferenceType(), D->getLocation());
  1221. DVar.CKind = OMPC_threadprivate;
  1222. addDSA(D, DVar.RefExpr, OMPC_threadprivate);
  1223. return DVar;
  1224. }
  1225. if (SemaRef.getLangOpts().OpenMPCUDAMode && VD &&
  1226. VD->isLocalVarDeclOrParm() && !isStackEmpty() &&
  1227. !isLoopControlVariable(D).first) {
  1228. const_iterator IterTarget =
  1229. std::find_if(begin(), end(), [](const SharingMapTy &Data) {
  1230. return isOpenMPTargetExecutionDirective(Data.Directive);
  1231. });
  1232. if (IterTarget != end()) {
  1233. const_iterator ParentIterTarget = IterTarget + 1;
  1234. for (const_iterator Iter = begin();
  1235. Iter != ParentIterTarget; ++Iter) {
  1236. if (isOpenMPLocal(VD, Iter)) {
  1237. DVar.RefExpr =
  1238. buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
  1239. D->getLocation());
  1240. DVar.CKind = OMPC_threadprivate;
  1241. return DVar;
  1242. }
  1243. }
  1244. if (!isClauseParsingMode() || IterTarget != begin()) {
  1245. auto DSAIter = IterTarget->SharingMap.find(D);
  1246. if (DSAIter != IterTarget->SharingMap.end() &&
  1247. isOpenMPPrivate(DSAIter->getSecond().Attributes)) {
  1248. DVar.RefExpr = DSAIter->getSecond().RefExpr.getPointer();
  1249. DVar.CKind = OMPC_threadprivate;
  1250. return DVar;
  1251. }
  1252. const_iterator End = end();
  1253. if (!SemaRef.isOpenMPCapturedByRef(
  1254. D, std::distance(ParentIterTarget, End),
  1255. /*OpenMPCaptureLevel=*/0)) {
  1256. DVar.RefExpr =
  1257. buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
  1258. IterTarget->ConstructLoc);
  1259. DVar.CKind = OMPC_threadprivate;
  1260. return DVar;
  1261. }
  1262. }
  1263. }
  1264. }
  1265. if (isStackEmpty())
  1266. // Not in OpenMP execution region and top scope was already checked.
  1267. return DVar;
  1268. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  1269. // in a Construct, C/C++, predetermined, p.4]
  1270. // Static data members are shared.
  1271. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  1272. // in a Construct, C/C++, predetermined, p.7]
  1273. // Variables with static storage duration that are declared in a scope
  1274. // inside the construct are shared.
  1275. if (VD && VD->isStaticDataMember()) {
  1276. // Check for explicitly specified attributes.
  1277. const_iterator I = begin();
  1278. const_iterator EndI = end();
  1279. if (FromParent && I != EndI)
  1280. ++I;
  1281. auto It = I->SharingMap.find(D);
  1282. if (It != I->SharingMap.end()) {
  1283. const DSAInfo &Data = It->getSecond();
  1284. DVar.RefExpr = Data.RefExpr.getPointer();
  1285. DVar.PrivateCopy = Data.PrivateCopy;
  1286. DVar.CKind = Data.Attributes;
  1287. DVar.ImplicitDSALoc = I->DefaultAttrLoc;
  1288. DVar.DKind = I->Directive;
  1289. return DVar;
  1290. }
  1291. DVar.CKind = OMPC_shared;
  1292. return DVar;
  1293. }
  1294. auto &&MatchesAlways = [](OpenMPDirectiveKind) { return true; };
  1295. // The predetermined shared attribute for const-qualified types having no
  1296. // mutable members was removed after OpenMP 3.1.
  1297. if (SemaRef.LangOpts.OpenMP <= 31) {
  1298. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  1299. // in a Construct, C/C++, predetermined, p.6]
  1300. // Variables with const qualified type having no mutable member are
  1301. // shared.
  1302. if (isConstNotMutableType(SemaRef, D->getType())) {
  1303. // Variables with const-qualified type having no mutable member may be
  1304. // listed in a firstprivate clause, even if they are static data members.
  1305. DSAVarData DVarTemp = hasInnermostDSA(
  1306. D,
  1307. [](OpenMPClauseKind C) {
  1308. return C == OMPC_firstprivate || C == OMPC_shared;
  1309. },
  1310. MatchesAlways, FromParent);
  1311. if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
  1312. return DVarTemp;
  1313. DVar.CKind = OMPC_shared;
  1314. return DVar;
  1315. }
  1316. }
  1317. // Explicitly specified attributes and local variables with predetermined
  1318. // attributes.
  1319. const_iterator I = begin();
  1320. const_iterator EndI = end();
  1321. if (FromParent && I != EndI)
  1322. ++I;
  1323. auto It = I->SharingMap.find(D);
  1324. if (It != I->SharingMap.end()) {
  1325. const DSAInfo &Data = It->getSecond();
  1326. DVar.RefExpr = Data.RefExpr.getPointer();
  1327. DVar.PrivateCopy = Data.PrivateCopy;
  1328. DVar.CKind = Data.Attributes;
  1329. DVar.ImplicitDSALoc = I->DefaultAttrLoc;
  1330. DVar.DKind = I->Directive;
  1331. }
  1332. return DVar;
  1333. }
  1334. const DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
  1335. bool FromParent) const {
  1336. if (isStackEmpty()) {
  1337. const_iterator I;
  1338. return getDSA(I, D);
  1339. }
  1340. D = getCanonicalDecl(D);
  1341. const_iterator StartI = begin();
  1342. const_iterator EndI = end();
  1343. if (FromParent && StartI != EndI)
  1344. ++StartI;
  1345. return getDSA(StartI, D);
  1346. }
  1347. const DSAStackTy::DSAVarData
  1348. DSAStackTy::hasDSA(ValueDecl *D,
  1349. const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
  1350. const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
  1351. bool FromParent) const {
  1352. if (isStackEmpty())
  1353. return {};
  1354. D = getCanonicalDecl(D);
  1355. const_iterator I = begin();
  1356. const_iterator EndI = end();
  1357. if (FromParent && I != EndI)
  1358. ++I;
  1359. for (; I != EndI; ++I) {
  1360. if (!DPred(I->Directive) &&
  1361. !isImplicitOrExplicitTaskingRegion(I->Directive))
  1362. continue;
  1363. const_iterator NewI = I;
  1364. DSAVarData DVar = getDSA(NewI, D);
  1365. if (I == NewI && CPred(DVar.CKind))
  1366. return DVar;
  1367. }
  1368. return {};
  1369. }
  1370. const DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA(
  1371. ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
  1372. const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
  1373. bool FromParent) const {
  1374. if (isStackEmpty())
  1375. return {};
  1376. D = getCanonicalDecl(D);
  1377. const_iterator StartI = begin();
  1378. const_iterator EndI = end();
  1379. if (FromParent && StartI != EndI)
  1380. ++StartI;
  1381. if (StartI == EndI || !DPred(StartI->Directive))
  1382. return {};
  1383. const_iterator NewI = StartI;
  1384. DSAVarData DVar = getDSA(NewI, D);
  1385. return (NewI == StartI && CPred(DVar.CKind)) ? DVar : DSAVarData();
  1386. }
  1387. bool DSAStackTy::hasExplicitDSA(
  1388. const ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
  1389. unsigned Level, bool NotLastprivate) const {
  1390. if (getStackSize() <= Level)
  1391. return false;
  1392. D = getCanonicalDecl(D);
  1393. const SharingMapTy &StackElem = getStackElemAtLevel(Level);
  1394. auto I = StackElem.SharingMap.find(D);
  1395. if (I != StackElem.SharingMap.end() &&
  1396. I->getSecond().RefExpr.getPointer() &&
  1397. CPred(I->getSecond().Attributes) &&
  1398. (!NotLastprivate || !I->getSecond().RefExpr.getInt()))
  1399. return true;
  1400. // Check predetermined rules for the loop control variables.
  1401. auto LI = StackElem.LCVMap.find(D);
  1402. if (LI != StackElem.LCVMap.end())
  1403. return CPred(OMPC_private);
  1404. return false;
  1405. }
  1406. bool DSAStackTy::hasExplicitDirective(
  1407. const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
  1408. unsigned Level) const {
  1409. if (getStackSize() <= Level)
  1410. return false;
  1411. const SharingMapTy &StackElem = getStackElemAtLevel(Level);
  1412. return DPred(StackElem.Directive);
  1413. }
  1414. bool DSAStackTy::hasDirective(
  1415. const llvm::function_ref<bool(OpenMPDirectiveKind,
  1416. const DeclarationNameInfo &, SourceLocation)>
  1417. DPred,
  1418. bool FromParent) const {
  1419. // We look only in the enclosing region.
  1420. size_t Skip = FromParent ? 2 : 1;
  1421. for (const_iterator I = begin() + std::min(Skip, getStackSize()), E = end();
  1422. I != E; ++I) {
  1423. if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
  1424. return true;
  1425. }
  1426. return false;
  1427. }
  1428. void Sema::InitDataSharingAttributesStack() {
  1429. VarDataSharingAttributesStack = new DSAStackTy(*this);
  1430. }
  1431. #define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
  1432. void Sema::pushOpenMPFunctionRegion() {
  1433. DSAStack->pushFunction();
  1434. }
  1435. void Sema::popOpenMPFunctionRegion(const FunctionScopeInfo *OldFSI) {
  1436. DSAStack->popFunction(OldFSI);
  1437. }
  1438. static bool isOpenMPDeviceDelayedContext(Sema &S) {
  1439. assert(S.LangOpts.OpenMP && S.LangOpts.OpenMPIsDevice &&
  1440. "Expected OpenMP device compilation.");
  1441. return !S.isInOpenMPTargetExecutionDirective() &&
  1442. !S.isInOpenMPDeclareTargetContext();
  1443. }
  1444. namespace {
  1445. /// Status of the function emission on the host/device.
  1446. enum class FunctionEmissionStatus {
  1447. Emitted,
  1448. Discarded,
  1449. Unknown,
  1450. };
  1451. } // anonymous namespace
  1452. /// Do we know that we will eventually codegen the given function?
  1453. static FunctionEmissionStatus isKnownDeviceEmitted(Sema &S, FunctionDecl *FD) {
  1454. assert(S.LangOpts.OpenMP && S.LangOpts.OpenMPIsDevice &&
  1455. "Expected OpenMP device compilation.");
  1456. // Templates are emitted when they're instantiated.
  1457. if (FD->isDependentContext())
  1458. return FunctionEmissionStatus::Discarded;
  1459. Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
  1460. OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
  1461. if (DevTy.hasValue())
  1462. return (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
  1463. ? FunctionEmissionStatus::Discarded
  1464. : FunctionEmissionStatus::Emitted;
  1465. // Otherwise, the function is known-emitted if it's in our set of
  1466. // known-emitted functions.
  1467. return (S.DeviceKnownEmittedFns.count(FD) > 0)
  1468. ? FunctionEmissionStatus::Emitted
  1469. : FunctionEmissionStatus::Unknown;
  1470. }
  1471. Sema::DeviceDiagBuilder Sema::diagIfOpenMPDeviceCode(SourceLocation Loc,
  1472. unsigned DiagID) {
  1473. assert(LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
  1474. "Expected OpenMP device compilation.");
  1475. FunctionEmissionStatus FES =
  1476. isKnownDeviceEmitted(*this, getCurFunctionDecl());
  1477. DeviceDiagBuilder::Kind Kind = DeviceDiagBuilder::K_Nop;
  1478. switch (FES) {
  1479. case FunctionEmissionStatus::Emitted:
  1480. Kind = DeviceDiagBuilder::K_Immediate;
  1481. break;
  1482. case FunctionEmissionStatus::Unknown:
  1483. Kind = isOpenMPDeviceDelayedContext(*this) ? DeviceDiagBuilder::K_Deferred
  1484. : DeviceDiagBuilder::K_Immediate;
  1485. break;
  1486. case FunctionEmissionStatus::Discarded:
  1487. Kind = DeviceDiagBuilder::K_Nop;
  1488. break;
  1489. }
  1490. return DeviceDiagBuilder(Kind, Loc, DiagID, getCurFunctionDecl(), *this);
  1491. }
  1492. /// Do we know that we will eventually codegen the given function?
  1493. static FunctionEmissionStatus isKnownHostEmitted(Sema &S, FunctionDecl *FD) {
  1494. assert(S.LangOpts.OpenMP && !S.LangOpts.OpenMPIsDevice &&
  1495. "Expected OpenMP host compilation.");
  1496. // In OpenMP 4.5 all the functions are host functions.
  1497. if (S.LangOpts.OpenMP <= 45)
  1498. return FunctionEmissionStatus::Emitted;
  1499. Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
  1500. OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
  1501. if (DevTy.hasValue())
  1502. return (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
  1503. ? FunctionEmissionStatus::Discarded
  1504. : FunctionEmissionStatus::Emitted;
  1505. // Otherwise, the function is known-emitted if it's in our set of
  1506. // known-emitted functions.
  1507. return (S.DeviceKnownEmittedFns.count(FD) > 0)
  1508. ? FunctionEmissionStatus::Emitted
  1509. : FunctionEmissionStatus::Unknown;
  1510. }
  1511. Sema::DeviceDiagBuilder Sema::diagIfOpenMPHostCode(SourceLocation Loc,
  1512. unsigned DiagID) {
  1513. assert(LangOpts.OpenMP && !LangOpts.OpenMPIsDevice &&
  1514. "Expected OpenMP host compilation.");
  1515. FunctionEmissionStatus FES =
  1516. isKnownHostEmitted(*this, getCurFunctionDecl());
  1517. DeviceDiagBuilder::Kind Kind = DeviceDiagBuilder::K_Nop;
  1518. switch (FES) {
  1519. case FunctionEmissionStatus::Emitted:
  1520. Kind = DeviceDiagBuilder::K_Immediate;
  1521. break;
  1522. case FunctionEmissionStatus::Unknown:
  1523. Kind = DeviceDiagBuilder::K_Deferred;
  1524. break;
  1525. case FunctionEmissionStatus::Discarded:
  1526. Kind = DeviceDiagBuilder::K_Nop;
  1527. break;
  1528. }
  1529. return DeviceDiagBuilder(Kind, Loc, DiagID, getCurFunctionDecl(), *this);
  1530. }
  1531. void Sema::checkOpenMPDeviceFunction(SourceLocation Loc, FunctionDecl *Callee,
  1532. bool CheckForDelayedContext) {
  1533. assert(LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
  1534. "Expected OpenMP device compilation.");
  1535. assert(Callee && "Callee may not be null.");
  1536. Callee = Callee->getMostRecentDecl();
  1537. FunctionDecl *Caller = getCurFunctionDecl();
  1538. // host only function are not available on the device.
  1539. if (Caller &&
  1540. (isKnownDeviceEmitted(*this, Caller) == FunctionEmissionStatus::Emitted ||
  1541. (!isOpenMPDeviceDelayedContext(*this) &&
  1542. isKnownDeviceEmitted(*this, Caller) ==
  1543. FunctionEmissionStatus::Unknown)) &&
  1544. isKnownDeviceEmitted(*this, Callee) ==
  1545. FunctionEmissionStatus::Discarded) {
  1546. StringRef HostDevTy =
  1547. getOpenMPSimpleClauseTypeName(OMPC_device_type, OMPC_DEVICE_TYPE_host);
  1548. Diag(Loc, diag::err_omp_wrong_device_function_call) << HostDevTy << 0;
  1549. Diag(Callee->getAttr<OMPDeclareTargetDeclAttr>()->getLocation(),
  1550. diag::note_omp_marked_device_type_here)
  1551. << HostDevTy;
  1552. return;
  1553. }
  1554. // If the caller is known-emitted, mark the callee as known-emitted.
  1555. // Otherwise, mark the call in our call graph so we can traverse it later.
  1556. if ((CheckForDelayedContext && !isOpenMPDeviceDelayedContext(*this)) ||
  1557. (!Caller && !CheckForDelayedContext) ||
  1558. (Caller &&
  1559. isKnownDeviceEmitted(*this, Caller) == FunctionEmissionStatus::Emitted))
  1560. markKnownEmitted(*this, Caller, Callee, Loc,
  1561. [CheckForDelayedContext](Sema &S, FunctionDecl *FD) {
  1562. return CheckForDelayedContext &&
  1563. isKnownDeviceEmitted(S, FD) ==
  1564. FunctionEmissionStatus::Emitted;
  1565. });
  1566. else if (Caller)
  1567. DeviceCallGraph[Caller].insert({Callee, Loc});
  1568. }
  1569. void Sema::checkOpenMPHostFunction(SourceLocation Loc, FunctionDecl *Callee,
  1570. bool CheckCaller) {
  1571. assert(LangOpts.OpenMP && !LangOpts.OpenMPIsDevice &&
  1572. "Expected OpenMP host compilation.");
  1573. assert(Callee && "Callee may not be null.");
  1574. Callee = Callee->getMostRecentDecl();
  1575. FunctionDecl *Caller = getCurFunctionDecl();
  1576. // device only function are not available on the host.
  1577. if (Caller &&
  1578. isKnownHostEmitted(*this, Caller) == FunctionEmissionStatus::Emitted &&
  1579. isKnownHostEmitted(*this, Callee) == FunctionEmissionStatus::Discarded) {
  1580. StringRef NoHostDevTy = getOpenMPSimpleClauseTypeName(
  1581. OMPC_device_type, OMPC_DEVICE_TYPE_nohost);
  1582. Diag(Loc, diag::err_omp_wrong_device_function_call) << NoHostDevTy << 1;
  1583. Diag(Callee->getAttr<OMPDeclareTargetDeclAttr>()->getLocation(),
  1584. diag::note_omp_marked_device_type_here)
  1585. << NoHostDevTy;
  1586. return;
  1587. }
  1588. // If the caller is known-emitted, mark the callee as known-emitted.
  1589. // Otherwise, mark the call in our call graph so we can traverse it later.
  1590. if ((!CheckCaller && !Caller) ||
  1591. (Caller &&
  1592. isKnownHostEmitted(*this, Caller) == FunctionEmissionStatus::Emitted))
  1593. markKnownEmitted(
  1594. *this, Caller, Callee, Loc, [CheckCaller](Sema &S, FunctionDecl *FD) {
  1595. return CheckCaller &&
  1596. isKnownHostEmitted(S, FD) == FunctionEmissionStatus::Emitted;
  1597. });
  1598. else if (Caller)
  1599. DeviceCallGraph[Caller].insert({Callee, Loc});
  1600. }
  1601. void Sema::checkOpenMPDeviceExpr(const Expr *E) {
  1602. assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
  1603. "OpenMP device compilation mode is expected.");
  1604. QualType Ty = E->getType();
  1605. if ((Ty->isFloat16Type() && !Context.getTargetInfo().hasFloat16Type()) ||
  1606. ((Ty->isFloat128Type() ||
  1607. (Ty->isRealFloatingType() && Context.getTypeSize(Ty) == 128)) &&
  1608. !Context.getTargetInfo().hasFloat128Type()) ||
  1609. (Ty->isIntegerType() && Context.getTypeSize(Ty) == 128 &&
  1610. !Context.getTargetInfo().hasInt128Type()))
  1611. targetDiag(E->getExprLoc(), diag::err_omp_unsupported_type)
  1612. << static_cast<unsigned>(Context.getTypeSize(Ty)) << Ty
  1613. << Context.getTargetInfo().getTriple().str() << E->getSourceRange();
  1614. }
  1615. bool Sema::isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level,
  1616. unsigned OpenMPCaptureLevel) const {
  1617. assert(LangOpts.OpenMP && "OpenMP is not allowed");
  1618. ASTContext &Ctx = getASTContext();
  1619. bool IsByRef = true;
  1620. // Find the directive that is associated with the provided scope.
  1621. D = cast<ValueDecl>(D->getCanonicalDecl());
  1622. QualType Ty = D->getType();
  1623. bool IsVariableUsedInMapClause = false;
  1624. if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) {
  1625. // This table summarizes how a given variable should be passed to the device
  1626. // given its type and the clauses where it appears. This table is based on
  1627. // the description in OpenMP 4.5 [2.10.4, target Construct] and
  1628. // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses].
  1629. //
  1630. // =========================================================================
  1631. // | type | defaultmap | pvt | first | is_device_ptr | map | res. |
  1632. // | |(tofrom:scalar)| | pvt | | | |
  1633. // =========================================================================
  1634. // | scl | | | | - | | bycopy|
  1635. // | scl | | - | x | - | - | bycopy|
  1636. // | scl | | x | - | - | - | null |
  1637. // | scl | x | | | - | | byref |
  1638. // | scl | x | - | x | - | - | bycopy|
  1639. // | scl | x | x | - | - | - | null |
  1640. // | scl | | - | - | - | x | byref |
  1641. // | scl | x | - | - | - | x | byref |
  1642. //
  1643. // | agg | n.a. | | | - | | byref |
  1644. // | agg | n.a. | - | x | - | - | byref |
  1645. // | agg | n.a. | x | - | - | - | null |
  1646. // | agg | n.a. | - | - | - | x | byref |
  1647. // | agg | n.a. | - | - | - | x[] | byref |
  1648. //
  1649. // | ptr | n.a. | | | - | | bycopy|
  1650. // | ptr | n.a. | - | x | - | - | bycopy|
  1651. // | ptr | n.a. | x | - | - | - | null |
  1652. // | ptr | n.a. | - | - | - | x | byref |
  1653. // | ptr | n.a. | - | - | - | x[] | bycopy|
  1654. // | ptr | n.a. | - | - | x | | bycopy|
  1655. // | ptr | n.a. | - | - | x | x | bycopy|
  1656. // | ptr | n.a. | - | - | x | x[] | bycopy|
  1657. // =========================================================================
  1658. // Legend:
  1659. // scl - scalar
  1660. // ptr - pointer
  1661. // agg - aggregate
  1662. // x - applies
  1663. // - - invalid in this combination
  1664. // [] - mapped with an array section
  1665. // byref - should be mapped by reference
  1666. // byval - should be mapped by value
  1667. // null - initialize a local variable to null on the device
  1668. //
  1669. // Observations:
  1670. // - All scalar declarations that show up in a map clause have to be passed
  1671. // by reference, because they may have been mapped in the enclosing data
  1672. // environment.
  1673. // - If the scalar value does not fit the size of uintptr, it has to be
  1674. // passed by reference, regardless the result in the table above.
  1675. // - For pointers mapped by value that have either an implicit map or an
  1676. // array section, the runtime library may pass the NULL value to the
  1677. // device instead of the value passed to it by the compiler.
  1678. if (Ty->isReferenceType())
  1679. Ty = Ty->castAs<ReferenceType>()->getPointeeType();
  1680. // Locate map clauses and see if the variable being captured is referred to
  1681. // in any of those clauses. Here we only care about variables, not fields,
  1682. // because fields are part of aggregates.
  1683. bool IsVariableAssociatedWithSection = false;
  1684. DSAStack->checkMappableExprComponentListsForDeclAtLevel(
  1685. D, Level,
  1686. [&IsVariableUsedInMapClause, &IsVariableAssociatedWithSection, D](
  1687. OMPClauseMappableExprCommon::MappableExprComponentListRef
  1688. MapExprComponents,
  1689. OpenMPClauseKind WhereFoundClauseKind) {
  1690. // Only the map clause information influences how a variable is
  1691. // captured. E.g. is_device_ptr does not require changing the default
  1692. // behavior.
  1693. if (WhereFoundClauseKind != OMPC_map)
  1694. return false;
  1695. auto EI = MapExprComponents.rbegin();
  1696. auto EE = MapExprComponents.rend();
  1697. assert(EI != EE && "Invalid map expression!");
  1698. if (isa<DeclRefExpr>(EI->getAssociatedExpression()))
  1699. IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D;
  1700. ++EI;
  1701. if (EI == EE)
  1702. return false;
  1703. if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) ||
  1704. isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) ||
  1705. isa<MemberExpr>(EI->getAssociatedExpression())) {
  1706. IsVariableAssociatedWithSection = true;
  1707. // There is nothing more we need to know about this variable.
  1708. return true;
  1709. }
  1710. // Keep looking for more map info.
  1711. return false;
  1712. });
  1713. if (IsVariableUsedInMapClause) {
  1714. // If variable is identified in a map clause it is always captured by
  1715. // reference except if it is a pointer that is dereferenced somehow.
  1716. IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection);
  1717. } else {
  1718. // By default, all the data that has a scalar type is mapped by copy
  1719. // (except for reduction variables).
  1720. IsByRef =
  1721. (DSAStack->isForceCaptureByReferenceInTargetExecutable() &&
  1722. !Ty->isAnyPointerType()) ||
  1723. !Ty->isScalarType() ||
  1724. DSAStack->getDefaultDMAAtLevel(Level) == DMA_tofrom_scalar ||
  1725. DSAStack->hasExplicitDSA(
  1726. D, [](OpenMPClauseKind K) { return K == OMPC_reduction; }, Level);
  1727. }
  1728. }
  1729. if (IsByRef && Ty.getNonReferenceType()->isScalarType()) {
  1730. IsByRef =
  1731. ((IsVariableUsedInMapClause &&
  1732. DSAStack->getCaptureRegion(Level, OpenMPCaptureLevel) ==
  1733. OMPD_target) ||
  1734. !DSAStack->hasExplicitDSA(
  1735. D,
  1736. [](OpenMPClauseKind K) -> bool { return K == OMPC_firstprivate; },
  1737. Level, /*NotLastprivate=*/true)) &&
  1738. // If the variable is artificial and must be captured by value - try to
  1739. // capture by value.
  1740. !(isa<OMPCapturedExprDecl>(D) && !D->hasAttr<OMPCaptureNoInitAttr>() &&
  1741. !cast<OMPCapturedExprDecl>(D)->getInit()->isGLValue());
  1742. }
  1743. // When passing data by copy, we need to make sure it fits the uintptr size
  1744. // and alignment, because the runtime library only deals with uintptr types.
  1745. // If it does not fit the uintptr size, we need to pass the data by reference
  1746. // instead.
  1747. if (!IsByRef &&
  1748. (Ctx.getTypeSizeInChars(Ty) >
  1749. Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) ||
  1750. Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) {
  1751. IsByRef = true;
  1752. }
  1753. return IsByRef;
  1754. }
  1755. unsigned Sema::getOpenMPNestingLevel() const {
  1756. assert(getLangOpts().OpenMP);
  1757. return DSAStack->getNestingLevel();
  1758. }
  1759. bool Sema::isInOpenMPTargetExecutionDirective() const {
  1760. return (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) &&
  1761. !DSAStack->isClauseParsingMode()) ||
  1762. DSAStack->hasDirective(
  1763. [](OpenMPDirectiveKind K, const DeclarationNameInfo &,
  1764. SourceLocation) -> bool {
  1765. return isOpenMPTargetExecutionDirective(K);
  1766. },
  1767. false);
  1768. }
  1769. VarDecl *Sema::isOpenMPCapturedDecl(ValueDecl *D, bool CheckScopeInfo,
  1770. unsigned StopAt) {
  1771. assert(LangOpts.OpenMP && "OpenMP is not allowed");
  1772. D = getCanonicalDecl(D);
  1773. // If we want to determine whether the variable should be captured from the
  1774. // perspective of the current capturing scope, and we've already left all the
  1775. // capturing scopes of the top directive on the stack, check from the
  1776. // perspective of its parent directive (if any) instead.
  1777. DSAStackTy::ParentDirectiveScope InParentDirectiveRAII(
  1778. *DSAStack, CheckScopeInfo && DSAStack->isBodyComplete());
  1779. // If we are attempting to capture a global variable in a directive with
  1780. // 'target' we return true so that this global is also mapped to the device.
  1781. //
  1782. auto *VD = dyn_cast<VarDecl>(D);
  1783. if (VD && !VD->hasLocalStorage() &&
  1784. (getCurCapturedRegion() || getCurBlock() || getCurLambda())) {
  1785. if (isInOpenMPDeclareTargetContext()) {
  1786. // Try to mark variable as declare target if it is used in capturing
  1787. // regions.
  1788. if (LangOpts.OpenMP <= 45 &&
  1789. !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
  1790. checkDeclIsAllowedInOpenMPTarget(nullptr, VD);
  1791. return nullptr;
  1792. } else if (isInOpenMPTargetExecutionDirective()) {
  1793. // If the declaration is enclosed in a 'declare target' directive,
  1794. // then it should not be captured.
  1795. //
  1796. if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
  1797. return nullptr;
  1798. return VD;
  1799. }
  1800. }
  1801. if (CheckScopeInfo) {
  1802. bool OpenMPFound = false;
  1803. for (unsigned I = StopAt + 1; I > 0; --I) {
  1804. FunctionScopeInfo *FSI = FunctionScopes[I - 1];
  1805. if(!isa<CapturingScopeInfo>(FSI))
  1806. return nullptr;
  1807. if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(FSI))
  1808. if (RSI->CapRegionKind == CR_OpenMP) {
  1809. OpenMPFound = true;
  1810. break;
  1811. }
  1812. }
  1813. if (!OpenMPFound)
  1814. return nullptr;
  1815. }
  1816. if (DSAStack->getCurrentDirective() != OMPD_unknown &&
  1817. (!DSAStack->isClauseParsingMode() ||
  1818. DSAStack->getParentDirective() != OMPD_unknown)) {
  1819. auto &&Info = DSAStack->isLoopControlVariable(D);
  1820. if (Info.first ||
  1821. (VD && VD->hasLocalStorage() &&
  1822. isImplicitOrExplicitTaskingRegion(DSAStack->getCurrentDirective())) ||
  1823. (VD && DSAStack->isForceVarCapturing()))
  1824. return VD ? VD : Info.second;
  1825. DSAStackTy::DSAVarData DVarPrivate =
  1826. DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
  1827. if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
  1828. return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
  1829. // Threadprivate variables must not be captured.
  1830. if (isOpenMPThreadPrivate(DVarPrivate.CKind))
  1831. return nullptr;
  1832. // The variable is not private or it is the variable in the directive with
  1833. // default(none) clause and not used in any clause.
  1834. DVarPrivate = DSAStack->hasDSA(D, isOpenMPPrivate,
  1835. [](OpenMPDirectiveKind) { return true; },
  1836. DSAStack->isClauseParsingMode());
  1837. if (DVarPrivate.CKind != OMPC_unknown ||
  1838. (VD && DSAStack->getDefaultDSA() == DSA_none))
  1839. return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
  1840. }
  1841. return nullptr;
  1842. }
  1843. void Sema::adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex,
  1844. unsigned Level) const {
  1845. SmallVector<OpenMPDirectiveKind, 4> Regions;
  1846. getOpenMPCaptureRegions(Regions, DSAStack->getDirective(Level));
  1847. FunctionScopesIndex -= Regions.size();
  1848. }
  1849. void Sema::startOpenMPLoop() {
  1850. assert(LangOpts.OpenMP && "OpenMP must be enabled.");
  1851. if (isOpenMPLoopDirective(DSAStack->getCurrentDirective()))
  1852. DSAStack->loopInit();
  1853. }
  1854. void Sema::startOpenMPCXXRangeFor() {
  1855. assert(LangOpts.OpenMP && "OpenMP must be enabled.");
  1856. if (isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
  1857. DSAStack->resetPossibleLoopCounter();
  1858. DSAStack->loopStart();
  1859. }
  1860. }
  1861. bool Sema::isOpenMPPrivateDecl(const ValueDecl *D, unsigned Level) const {
  1862. assert(LangOpts.OpenMP && "OpenMP is not allowed");
  1863. if (isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
  1864. if (DSAStack->getAssociatedLoops() > 0 &&
  1865. !DSAStack->isLoopStarted()) {
  1866. DSAStack->resetPossibleLoopCounter(D);
  1867. DSAStack->loopStart();
  1868. return true;
  1869. }
  1870. if ((DSAStack->getPossiblyLoopCunter() == D->getCanonicalDecl() ||
  1871. DSAStack->isLoopControlVariable(D).first) &&
  1872. !DSAStack->hasExplicitDSA(
  1873. D, [](OpenMPClauseKind K) { return K != OMPC_private; }, Level) &&
  1874. !isOpenMPSimdDirective(DSAStack->getCurrentDirective()))
  1875. return true;
  1876. }
  1877. if (const auto *VD = dyn_cast<VarDecl>(D)) {
  1878. if (DSAStack->isThreadPrivate(const_cast<VarDecl *>(VD)) &&
  1879. DSAStack->isForceVarCapturing() &&
  1880. !DSAStack->hasExplicitDSA(
  1881. D, [](OpenMPClauseKind K) { return K == OMPC_copyin; }, Level))
  1882. return true;
  1883. }
  1884. return DSAStack->hasExplicitDSA(
  1885. D, [](OpenMPClauseKind K) { return K == OMPC_private; }, Level) ||
  1886. (DSAStack->isClauseParsingMode() &&
  1887. DSAStack->getClauseParsingMode() == OMPC_private) ||
  1888. // Consider taskgroup reduction descriptor variable a private to avoid
  1889. // possible capture in the region.
  1890. (DSAStack->hasExplicitDirective(
  1891. [](OpenMPDirectiveKind K) { return K == OMPD_taskgroup; },
  1892. Level) &&
  1893. DSAStack->isTaskgroupReductionRef(D, Level));
  1894. }
  1895. void Sema::setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D,
  1896. unsigned Level) {
  1897. assert(LangOpts.OpenMP && "OpenMP is not allowed");
  1898. D = getCanonicalDecl(D);
  1899. OpenMPClauseKind OMPC = OMPC_unknown;
  1900. for (unsigned I = DSAStack->getNestingLevel() + 1; I > Level; --I) {
  1901. const unsigned NewLevel = I - 1;
  1902. if (DSAStack->hasExplicitDSA(D,
  1903. [&OMPC](const OpenMPClauseKind K) {
  1904. if (isOpenMPPrivate(K)) {
  1905. OMPC = K;
  1906. return true;
  1907. }
  1908. return false;
  1909. },
  1910. NewLevel))
  1911. break;
  1912. if (DSAStack->checkMappableExprComponentListsForDeclAtLevel(
  1913. D, NewLevel,
  1914. [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
  1915. OpenMPClauseKind) { return true; })) {
  1916. OMPC = OMPC_map;
  1917. break;
  1918. }
  1919. if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
  1920. NewLevel)) {
  1921. OMPC = OMPC_map;
  1922. if (D->getType()->isScalarType() &&
  1923. DSAStack->getDefaultDMAAtLevel(NewLevel) !=
  1924. DefaultMapAttributes::DMA_tofrom_scalar)
  1925. OMPC = OMPC_firstprivate;
  1926. break;
  1927. }
  1928. }
  1929. if (OMPC != OMPC_unknown)
  1930. FD->addAttr(OMPCaptureKindAttr::CreateImplicit(Context, OMPC));
  1931. }
  1932. bool Sema::isOpenMPTargetCapturedDecl(const ValueDecl *D,
  1933. unsigned Level) const {
  1934. assert(LangOpts.OpenMP && "OpenMP is not allowed");
  1935. // Return true if the current level is no longer enclosed in a target region.
  1936. const auto *VD = dyn_cast<VarDecl>(D);
  1937. return VD && !VD->hasLocalStorage() &&
  1938. DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
  1939. Level);
  1940. }
  1941. void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
  1942. void Sema::finalizeOpenMPDelayedAnalysis() {
  1943. assert(LangOpts.OpenMP && "Expected OpenMP compilation mode.");
  1944. // Diagnose implicit declare target functions and their callees.
  1945. for (const auto &CallerCallees : DeviceCallGraph) {
  1946. Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
  1947. OMPDeclareTargetDeclAttr::getDeviceType(
  1948. CallerCallees.getFirst()->getMostRecentDecl());
  1949. // Ignore host functions during device analyzis.
  1950. if (LangOpts.OpenMPIsDevice && DevTy &&
  1951. *DevTy == OMPDeclareTargetDeclAttr::DT_Host)
  1952. continue;
  1953. // Ignore nohost functions during host analyzis.
  1954. if (!LangOpts.OpenMPIsDevice && DevTy &&
  1955. *DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
  1956. continue;
  1957. for (const std::pair<CanonicalDeclPtr<FunctionDecl>, SourceLocation>
  1958. &Callee : CallerCallees.getSecond()) {
  1959. const FunctionDecl *FD = Callee.first->getMostRecentDecl();
  1960. Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
  1961. OMPDeclareTargetDeclAttr::getDeviceType(FD);
  1962. if (LangOpts.OpenMPIsDevice && DevTy &&
  1963. *DevTy == OMPDeclareTargetDeclAttr::DT_Host) {
  1964. // Diagnose host function called during device codegen.
  1965. StringRef HostDevTy = getOpenMPSimpleClauseTypeName(
  1966. OMPC_device_type, OMPC_DEVICE_TYPE_host);
  1967. Diag(Callee.second, diag::err_omp_wrong_device_function_call)
  1968. << HostDevTy << 0;
  1969. Diag(FD->getAttr<OMPDeclareTargetDeclAttr>()->getLocation(),
  1970. diag::note_omp_marked_device_type_here)
  1971. << HostDevTy;
  1972. continue;
  1973. }
  1974. if (!LangOpts.OpenMPIsDevice && DevTy &&
  1975. *DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) {
  1976. // Diagnose nohost function called during host codegen.
  1977. StringRef NoHostDevTy = getOpenMPSimpleClauseTypeName(
  1978. OMPC_device_type, OMPC_DEVICE_TYPE_nohost);
  1979. Diag(Callee.second, diag::err_omp_wrong_device_function_call)
  1980. << NoHostDevTy << 1;
  1981. Diag(FD->getAttr<OMPDeclareTargetDeclAttr>()->getLocation(),
  1982. diag::note_omp_marked_device_type_here)
  1983. << NoHostDevTy;
  1984. continue;
  1985. }
  1986. }
  1987. }
  1988. }
  1989. void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
  1990. const DeclarationNameInfo &DirName,
  1991. Scope *CurScope, SourceLocation Loc) {
  1992. DSAStack->push(DKind, DirName, CurScope, Loc);
  1993. PushExpressionEvaluationContext(
  1994. ExpressionEvaluationContext::PotentiallyEvaluated);
  1995. }
  1996. void Sema::StartOpenMPClause(OpenMPClauseKind K) {
  1997. DSAStack->setClauseParsingMode(K);
  1998. }
  1999. void Sema::EndOpenMPClause() {
  2000. DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
  2001. }
  2002. static void checkAllocateClauses(Sema &S, DSAStackTy *Stack,
  2003. ArrayRef<OMPClause *> Clauses);
  2004. void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
  2005. // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
  2006. // A variable of class type (or array thereof) that appears in a lastprivate
  2007. // clause requires an accessible, unambiguous default constructor for the
  2008. // class type, unless the list item is also specified in a firstprivate
  2009. // clause.
  2010. if (const auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
  2011. for (OMPClause *C : D->clauses()) {
  2012. if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
  2013. SmallVector<Expr *, 8> PrivateCopies;
  2014. for (Expr *DE : Clause->varlists()) {
  2015. if (DE->isValueDependent() || DE->isTypeDependent()) {
  2016. PrivateCopies.push_back(nullptr);
  2017. continue;
  2018. }
  2019. auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens());
  2020. auto *VD = cast<VarDecl>(DRE->getDecl());
  2021. QualType Type = VD->getType().getNonReferenceType();
  2022. const DSAStackTy::DSAVarData DVar =
  2023. DSAStack->getTopDSA(VD, /*FromParent=*/false);
  2024. if (DVar.CKind == OMPC_lastprivate) {
  2025. // Generate helper private variable and initialize it with the
  2026. // default value. The address of the original variable is replaced
  2027. // by the address of the new private variable in CodeGen. This new
  2028. // variable is not added to IdResolver, so the code in the OpenMP
  2029. // region uses original variable for proper diagnostics.
  2030. VarDecl *VDPrivate = buildVarDecl(
  2031. *this, DE->getExprLoc(), Type.getUnqualifiedType(),
  2032. VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr, DRE);
  2033. ActOnUninitializedDecl(VDPrivate);
  2034. if (VDPrivate->isInvalidDecl()) {
  2035. PrivateCopies.push_back(nullptr);
  2036. continue;
  2037. }
  2038. PrivateCopies.push_back(buildDeclRefExpr(
  2039. *this, VDPrivate, DE->getType(), DE->getExprLoc()));
  2040. } else {
  2041. // The variable is also a firstprivate, so initialization sequence
  2042. // for private copy is generated already.
  2043. PrivateCopies.push_back(nullptr);
  2044. }
  2045. }
  2046. Clause->setPrivateCopies(PrivateCopies);
  2047. }
  2048. }
  2049. // Check allocate clauses.
  2050. if (!CurContext->isDependentContext())
  2051. checkAllocateClauses(*this, DSAStack, D->clauses());
  2052. }
  2053. DSAStack->pop();
  2054. DiscardCleanupsInEvaluationContext();
  2055. PopExpressionEvaluationContext();
  2056. }
  2057. static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
  2058. Expr *NumIterations, Sema &SemaRef,
  2059. Scope *S, DSAStackTy *Stack);
  2060. namespace {
  2061. class VarDeclFilterCCC final : public CorrectionCandidateCallback {
  2062. private:
  2063. Sema &SemaRef;
  2064. public:
  2065. explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
  2066. bool ValidateCandidate(const TypoCorrection &Candidate) override {
  2067. NamedDecl *ND = Candidate.getCorrectionDecl();
  2068. if (const auto *VD = dyn_cast_or_null<VarDecl>(ND)) {
  2069. return VD->hasGlobalStorage() &&
  2070. SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
  2071. SemaRef.getCurScope());
  2072. }
  2073. return false;
  2074. }
  2075. std::unique_ptr<CorrectionCandidateCallback> clone() override {
  2076. return std::make_unique<VarDeclFilterCCC>(*this);
  2077. }
  2078. };
  2079. class VarOrFuncDeclFilterCCC final : public CorrectionCandidateCallback {
  2080. private:
  2081. Sema &SemaRef;
  2082. public:
  2083. explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {}
  2084. bool ValidateCandidate(const TypoCorrection &Candidate) override {
  2085. NamedDecl *ND = Candidate.getCorrectionDecl();
  2086. if (ND && ((isa<VarDecl>(ND) && ND->getKind() == Decl::Var) ||
  2087. isa<FunctionDecl>(ND))) {
  2088. return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
  2089. SemaRef.getCurScope());
  2090. }
  2091. return false;
  2092. }
  2093. std::unique_ptr<CorrectionCandidateCallback> clone() override {
  2094. return std::make_unique<VarOrFuncDeclFilterCCC>(*this);
  2095. }
  2096. };
  2097. } // namespace
  2098. ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
  2099. CXXScopeSpec &ScopeSpec,
  2100. const DeclarationNameInfo &Id,
  2101. OpenMPDirectiveKind Kind) {
  2102. LookupResult Lookup(*this, Id, LookupOrdinaryName);
  2103. LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
  2104. if (Lookup.isAmbiguous())
  2105. return ExprError();
  2106. VarDecl *VD;
  2107. if (!Lookup.isSingleResult()) {
  2108. VarDeclFilterCCC CCC(*this);
  2109. if (TypoCorrection Corrected =
  2110. CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, CCC,
  2111. CTK_ErrorRecovery)) {
  2112. diagnoseTypo(Corrected,
  2113. PDiag(Lookup.empty()
  2114. ? diag::err_undeclared_var_use_suggest
  2115. : diag::err_omp_expected_var_arg_suggest)
  2116. << Id.getName());
  2117. VD = Corrected.getCorrectionDeclAs<VarDecl>();
  2118. } else {
  2119. Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
  2120. : diag::err_omp_expected_var_arg)
  2121. << Id.getName();
  2122. return ExprError();
  2123. }
  2124. } else if (!(VD = Lookup.getAsSingle<VarDecl>())) {
  2125. Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
  2126. Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
  2127. return ExprError();
  2128. }
  2129. Lookup.suppressDiagnostics();
  2130. // OpenMP [2.9.2, Syntax, C/C++]
  2131. // Variables must be file-scope, namespace-scope, or static block-scope.
  2132. if (Kind == OMPD_threadprivate && !VD->hasGlobalStorage()) {
  2133. Diag(Id.getLoc(), diag::err_omp_global_var_arg)
  2134. << getOpenMPDirectiveName(Kind) << !VD->isStaticLocal();
  2135. bool IsDecl =
  2136. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  2137. Diag(VD->getLocation(),
  2138. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  2139. << VD;
  2140. return ExprError();
  2141. }
  2142. VarDecl *CanonicalVD = VD->getCanonicalDecl();
  2143. NamedDecl *ND = CanonicalVD;
  2144. // OpenMP [2.9.2, Restrictions, C/C++, p.2]
  2145. // A threadprivate directive for file-scope variables must appear outside
  2146. // any definition or declaration.
  2147. if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
  2148. !getCurLexicalContext()->isTranslationUnit()) {
  2149. Diag(Id.getLoc(), diag::err_omp_var_scope)
  2150. << getOpenMPDirectiveName(Kind) << VD;
  2151. bool IsDecl =
  2152. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  2153. Diag(VD->getLocation(),
  2154. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  2155. << VD;
  2156. return ExprError();
  2157. }
  2158. // OpenMP [2.9.2, Restrictions, C/C++, p.3]
  2159. // A threadprivate directive for static class member variables must appear
  2160. // in the class definition, in the same scope in which the member
  2161. // variables are declared.
  2162. if (CanonicalVD->isStaticDataMember() &&
  2163. !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
  2164. Diag(Id.getLoc(), diag::err_omp_var_scope)
  2165. << getOpenMPDirectiveName(Kind) << VD;
  2166. bool IsDecl =
  2167. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  2168. Diag(VD->getLocation(),
  2169. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  2170. << VD;
  2171. return ExprError();
  2172. }
  2173. // OpenMP [2.9.2, Restrictions, C/C++, p.4]
  2174. // A threadprivate directive for namespace-scope variables must appear
  2175. // outside any definition or declaration other than the namespace
  2176. // definition itself.
  2177. if (CanonicalVD->getDeclContext()->isNamespace() &&
  2178. (!getCurLexicalContext()->isFileContext() ||
  2179. !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
  2180. Diag(Id.getLoc(), diag::err_omp_var_scope)
  2181. << getOpenMPDirectiveName(Kind) << VD;
  2182. bool IsDecl =
  2183. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  2184. Diag(VD->getLocation(),
  2185. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  2186. << VD;
  2187. return ExprError();
  2188. }
  2189. // OpenMP [2.9.2, Restrictions, C/C++, p.6]
  2190. // A threadprivate directive for static block-scope variables must appear
  2191. // in the scope of the variable and not in a nested scope.
  2192. if (CanonicalVD->isLocalVarDecl() && CurScope &&
  2193. !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
  2194. Diag(Id.getLoc(), diag::err_omp_var_scope)
  2195. << getOpenMPDirectiveName(Kind) << VD;
  2196. bool IsDecl =
  2197. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  2198. Diag(VD->getLocation(),
  2199. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  2200. << VD;
  2201. return ExprError();
  2202. }
  2203. // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
  2204. // A threadprivate directive must lexically precede all references to any
  2205. // of the variables in its list.
  2206. if (Kind == OMPD_threadprivate && VD->isUsed() &&
  2207. !DSAStack->isThreadPrivate(VD)) {
  2208. Diag(Id.getLoc(), diag::err_omp_var_used)
  2209. << getOpenMPDirectiveName(Kind) << VD;
  2210. return ExprError();
  2211. }
  2212. QualType ExprType = VD->getType().getNonReferenceType();
  2213. return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
  2214. SourceLocation(), VD,
  2215. /*RefersToEnclosingVariableOrCapture=*/false,
  2216. Id.getLoc(), ExprType, VK_LValue);
  2217. }
  2218. Sema::DeclGroupPtrTy
  2219. Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
  2220. ArrayRef<Expr *> VarList) {
  2221. if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
  2222. CurContext->addDecl(D);
  2223. return DeclGroupPtrTy::make(DeclGroupRef(D));
  2224. }
  2225. return nullptr;
  2226. }
  2227. namespace {
  2228. class LocalVarRefChecker final
  2229. : public ConstStmtVisitor<LocalVarRefChecker, bool> {
  2230. Sema &SemaRef;
  2231. public:
  2232. bool VisitDeclRefExpr(const DeclRefExpr *E) {
  2233. if (const auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
  2234. if (VD->hasLocalStorage()) {
  2235. SemaRef.Diag(E->getBeginLoc(),
  2236. diag::err_omp_local_var_in_threadprivate_init)
  2237. << E->getSourceRange();
  2238. SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
  2239. << VD << VD->getSourceRange();
  2240. return true;
  2241. }
  2242. }
  2243. return false;
  2244. }
  2245. bool VisitStmt(const Stmt *S) {
  2246. for (const Stmt *Child : S->children()) {
  2247. if (Child && Visit(Child))
  2248. return true;
  2249. }
  2250. return false;
  2251. }
  2252. explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
  2253. };
  2254. } // namespace
  2255. OMPThreadPrivateDecl *
  2256. Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
  2257. SmallVector<Expr *, 8> Vars;
  2258. for (Expr *RefExpr : VarList) {
  2259. auto *DE = cast<DeclRefExpr>(RefExpr);
  2260. auto *VD = cast<VarDecl>(DE->getDecl());
  2261. SourceLocation ILoc = DE->getExprLoc();
  2262. // Mark variable as used.
  2263. VD->setReferenced();
  2264. VD->markUsed(Context);
  2265. QualType QType = VD->getType();
  2266. if (QType->isDependentType() || QType->isInstantiationDependentType()) {
  2267. // It will be analyzed later.
  2268. Vars.push_back(DE);
  2269. continue;
  2270. }
  2271. // OpenMP [2.9.2, Restrictions, C/C++, p.10]
  2272. // A threadprivate variable must not have an incomplete type.
  2273. if (RequireCompleteType(ILoc, VD->getType(),
  2274. diag::err_omp_threadprivate_incomplete_type)) {
  2275. continue;
  2276. }
  2277. // OpenMP [2.9.2, Restrictions, C/C++, p.10]
  2278. // A threadprivate variable must not have a reference type.
  2279. if (VD->getType()->isReferenceType()) {
  2280. Diag(ILoc, diag::err_omp_ref_type_arg)
  2281. << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
  2282. bool IsDecl =
  2283. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  2284. Diag(VD->getLocation(),
  2285. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  2286. << VD;
  2287. continue;
  2288. }
  2289. // Check if this is a TLS variable. If TLS is not being supported, produce
  2290. // the corresponding diagnostic.
  2291. if ((VD->getTLSKind() != VarDecl::TLS_None &&
  2292. !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
  2293. getLangOpts().OpenMPUseTLS &&
  2294. getASTContext().getTargetInfo().isTLSSupported())) ||
  2295. (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
  2296. !VD->isLocalVarDecl())) {
  2297. Diag(ILoc, diag::err_omp_var_thread_local)
  2298. << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
  2299. bool IsDecl =
  2300. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  2301. Diag(VD->getLocation(),
  2302. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  2303. << VD;
  2304. continue;
  2305. }
  2306. // Check if initial value of threadprivate variable reference variable with
  2307. // local storage (it is not supported by runtime).
  2308. if (const Expr *Init = VD->getAnyInitializer()) {
  2309. LocalVarRefChecker Checker(*this);
  2310. if (Checker.Visit(Init))
  2311. continue;
  2312. }
  2313. Vars.push_back(RefExpr);
  2314. DSAStack->addDSA(VD, DE, OMPC_threadprivate);
  2315. VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
  2316. Context, SourceRange(Loc, Loc)));
  2317. if (ASTMutationListener *ML = Context.getASTMutationListener())
  2318. ML->DeclarationMarkedOpenMPThreadPrivate(VD);
  2319. }
  2320. OMPThreadPrivateDecl *D = nullptr;
  2321. if (!Vars.empty()) {
  2322. D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
  2323. Vars);
  2324. D->setAccess(AS_public);
  2325. }
  2326. return D;
  2327. }
  2328. static OMPAllocateDeclAttr::AllocatorTypeTy
  2329. getAllocatorKind(Sema &S, DSAStackTy *Stack, Expr *Allocator) {
  2330. if (!Allocator)
  2331. return OMPAllocateDeclAttr::OMPDefaultMemAlloc;
  2332. if (Allocator->isTypeDependent() || Allocator->isValueDependent() ||
  2333. Allocator->isInstantiationDependent() ||
  2334. Allocator->containsUnexpandedParameterPack())
  2335. return OMPAllocateDeclAttr::OMPUserDefinedMemAlloc;
  2336. auto AllocatorKindRes = OMPAllocateDeclAttr::OMPUserDefinedMemAlloc;
  2337. const Expr *AE = Allocator->IgnoreParenImpCasts();
  2338. for (int I = OMPAllocateDeclAttr::OMPDefaultMemAlloc;
  2339. I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) {
  2340. auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I);
  2341. const Expr *DefAllocator = Stack->getAllocator(AllocatorKind);
  2342. llvm::FoldingSetNodeID AEId, DAEId;
  2343. AE->Profile(AEId, S.getASTContext(), /*Canonical=*/true);
  2344. DefAllocator->Profile(DAEId, S.getASTContext(), /*Canonical=*/true);
  2345. if (AEId == DAEId) {
  2346. AllocatorKindRes = AllocatorKind;
  2347. break;
  2348. }
  2349. }
  2350. return AllocatorKindRes;
  2351. }
  2352. static bool checkPreviousOMPAllocateAttribute(
  2353. Sema &S, DSAStackTy *Stack, Expr *RefExpr, VarDecl *VD,
  2354. OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind, Expr *Allocator) {
  2355. if (!VD->hasAttr<OMPAllocateDeclAttr>())
  2356. return false;
  2357. const auto *A = VD->getAttr<OMPAllocateDeclAttr>();
  2358. Expr *PrevAllocator = A->getAllocator();
  2359. OMPAllocateDeclAttr::AllocatorTypeTy PrevAllocatorKind =
  2360. getAllocatorKind(S, Stack, PrevAllocator);
  2361. bool AllocatorsMatch = AllocatorKind == PrevAllocatorKind;
  2362. if (AllocatorsMatch &&
  2363. AllocatorKind == OMPAllocateDeclAttr::OMPUserDefinedMemAlloc &&
  2364. Allocator && PrevAllocator) {
  2365. const Expr *AE = Allocator->IgnoreParenImpCasts();
  2366. const Expr *PAE = PrevAllocator->IgnoreParenImpCasts();
  2367. llvm::FoldingSetNodeID AEId, PAEId;
  2368. AE->Profile(AEId, S.Context, /*Canonical=*/true);
  2369. PAE->Profile(PAEId, S.Context, /*Canonical=*/true);
  2370. AllocatorsMatch = AEId == PAEId;
  2371. }
  2372. if (!AllocatorsMatch) {
  2373. SmallString<256> AllocatorBuffer;
  2374. llvm::raw_svector_ostream AllocatorStream(AllocatorBuffer);
  2375. if (Allocator)
  2376. Allocator->printPretty(AllocatorStream, nullptr, S.getPrintingPolicy());
  2377. SmallString<256> PrevAllocatorBuffer;
  2378. llvm::raw_svector_ostream PrevAllocatorStream(PrevAllocatorBuffer);
  2379. if (PrevAllocator)
  2380. PrevAllocator->printPretty(PrevAllocatorStream, nullptr,
  2381. S.getPrintingPolicy());
  2382. SourceLocation AllocatorLoc =
  2383. Allocator ? Allocator->getExprLoc() : RefExpr->getExprLoc();
  2384. SourceRange AllocatorRange =
  2385. Allocator ? Allocator->getSourceRange() : RefExpr->getSourceRange();
  2386. SourceLocation PrevAllocatorLoc =
  2387. PrevAllocator ? PrevAllocator->getExprLoc() : A->getLocation();
  2388. SourceRange PrevAllocatorRange =
  2389. PrevAllocator ? PrevAllocator->getSourceRange() : A->getRange();
  2390. S.Diag(AllocatorLoc, diag::warn_omp_used_different_allocator)
  2391. << (Allocator ? 1 : 0) << AllocatorStream.str()
  2392. << (PrevAllocator ? 1 : 0) << PrevAllocatorStream.str()
  2393. << AllocatorRange;
  2394. S.Diag(PrevAllocatorLoc, diag::note_omp_previous_allocator)
  2395. << PrevAllocatorRange;
  2396. return true;
  2397. }
  2398. return false;
  2399. }
  2400. static void
  2401. applyOMPAllocateAttribute(Sema &S, VarDecl *VD,
  2402. OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind,
  2403. Expr *Allocator, SourceRange SR) {
  2404. if (VD->hasAttr<OMPAllocateDeclAttr>())
  2405. return;
  2406. if (Allocator &&
  2407. (Allocator->isTypeDependent() || Allocator->isValueDependent() ||
  2408. Allocator->isInstantiationDependent() ||
  2409. Allocator->containsUnexpandedParameterPack()))
  2410. return;
  2411. auto *A = OMPAllocateDeclAttr::CreateImplicit(S.Context, AllocatorKind,
  2412. Allocator, SR);
  2413. VD->addAttr(A);
  2414. if (ASTMutationListener *ML = S.Context.getASTMutationListener())
  2415. ML->DeclarationMarkedOpenMPAllocate(VD, A);
  2416. }
  2417. Sema::DeclGroupPtrTy Sema::ActOnOpenMPAllocateDirective(
  2418. SourceLocation Loc, ArrayRef<Expr *> VarList,
  2419. ArrayRef<OMPClause *> Clauses, DeclContext *Owner) {
  2420. assert(Clauses.size() <= 1 && "Expected at most one clause.");
  2421. Expr *Allocator = nullptr;
  2422. if (Clauses.empty()) {
  2423. // OpenMP 5.0, 2.11.3 allocate Directive, Restrictions.
  2424. // allocate directives that appear in a target region must specify an
  2425. // allocator clause unless a requires directive with the dynamic_allocators
  2426. // clause is present in the same compilation unit.
  2427. if (LangOpts.OpenMPIsDevice &&
  2428. !DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())
  2429. targetDiag(Loc, diag::err_expected_allocator_clause);
  2430. } else {
  2431. Allocator = cast<OMPAllocatorClause>(Clauses.back())->getAllocator();
  2432. }
  2433. OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind =
  2434. getAllocatorKind(*this, DSAStack, Allocator);
  2435. SmallVector<Expr *, 8> Vars;
  2436. for (Expr *RefExpr : VarList) {
  2437. auto *DE = cast<DeclRefExpr>(RefExpr);
  2438. auto *VD = cast<VarDecl>(DE->getDecl());
  2439. // Check if this is a TLS variable or global register.
  2440. if (VD->getTLSKind() != VarDecl::TLS_None ||
  2441. VD->hasAttr<OMPThreadPrivateDeclAttr>() ||
  2442. (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
  2443. !VD->isLocalVarDecl()))
  2444. continue;
  2445. // If the used several times in the allocate directive, the same allocator
  2446. // must be used.
  2447. if (checkPreviousOMPAllocateAttribute(*this, DSAStack, RefExpr, VD,
  2448. AllocatorKind, Allocator))
  2449. continue;
  2450. // OpenMP, 2.11.3 allocate Directive, Restrictions, C / C++
  2451. // If a list item has a static storage type, the allocator expression in the
  2452. // allocator clause must be a constant expression that evaluates to one of
  2453. // the predefined memory allocator values.
  2454. if (Allocator && VD->hasGlobalStorage()) {
  2455. if (AllocatorKind == OMPAllocateDeclAttr::OMPUserDefinedMemAlloc) {
  2456. Diag(Allocator->getExprLoc(),
  2457. diag::err_omp_expected_predefined_allocator)
  2458. << Allocator->getSourceRange();
  2459. bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
  2460. VarDecl::DeclarationOnly;
  2461. Diag(VD->getLocation(),
  2462. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  2463. << VD;
  2464. continue;
  2465. }
  2466. }
  2467. Vars.push_back(RefExpr);
  2468. applyOMPAllocateAttribute(*this, VD, AllocatorKind, Allocator,
  2469. DE->getSourceRange());
  2470. }
  2471. if (Vars.empty())
  2472. return nullptr;
  2473. if (!Owner)
  2474. Owner = getCurLexicalContext();
  2475. auto *D = OMPAllocateDecl::Create(Context, Owner, Loc, Vars, Clauses);
  2476. D->setAccess(AS_public);
  2477. Owner->addDecl(D);
  2478. return DeclGroupPtrTy::make(DeclGroupRef(D));
  2479. }
  2480. Sema::DeclGroupPtrTy
  2481. Sema::ActOnOpenMPRequiresDirective(SourceLocation Loc,
  2482. ArrayRef<OMPClause *> ClauseList) {
  2483. OMPRequiresDecl *D = nullptr;
  2484. if (!CurContext->isFileContext()) {
  2485. Diag(Loc, diag::err_omp_invalid_scope) << "requires";
  2486. } else {
  2487. D = CheckOMPRequiresDecl(Loc, ClauseList);
  2488. if (D) {
  2489. CurContext->addDecl(D);
  2490. DSAStack->addRequiresDecl(D);
  2491. }
  2492. }
  2493. return DeclGroupPtrTy::make(DeclGroupRef(D));
  2494. }
  2495. OMPRequiresDecl *Sema::CheckOMPRequiresDecl(SourceLocation Loc,
  2496. ArrayRef<OMPClause *> ClauseList) {
  2497. /// For target specific clauses, the requires directive cannot be
  2498. /// specified after the handling of any of the target regions in the
  2499. /// current compilation unit.
  2500. ArrayRef<SourceLocation> TargetLocations =
  2501. DSAStack->getEncounteredTargetLocs();
  2502. if (!TargetLocations.empty()) {
  2503. for (const OMPClause *CNew : ClauseList) {
  2504. // Check if any of the requires clauses affect target regions.
  2505. if (isa<OMPUnifiedSharedMemoryClause>(CNew) ||
  2506. isa<OMPUnifiedAddressClause>(CNew) ||
  2507. isa<OMPReverseOffloadClause>(CNew) ||
  2508. isa<OMPDynamicAllocatorsClause>(CNew)) {
  2509. Diag(Loc, diag::err_omp_target_before_requires)
  2510. << getOpenMPClauseName(CNew->getClauseKind());
  2511. for (SourceLocation TargetLoc : TargetLocations) {
  2512. Diag(TargetLoc, diag::note_omp_requires_encountered_target);
  2513. }
  2514. }
  2515. }
  2516. }
  2517. if (!DSAStack->hasDuplicateRequiresClause(ClauseList))
  2518. return OMPRequiresDecl::Create(Context, getCurLexicalContext(), Loc,
  2519. ClauseList);
  2520. return nullptr;
  2521. }
  2522. static void reportOriginalDsa(Sema &SemaRef, const DSAStackTy *Stack,
  2523. const ValueDecl *D,
  2524. const DSAStackTy::DSAVarData &DVar,
  2525. bool IsLoopIterVar = false) {
  2526. if (DVar.RefExpr) {
  2527. SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
  2528. << getOpenMPClauseName(DVar.CKind);
  2529. return;
  2530. }
  2531. enum {
  2532. PDSA_StaticMemberShared,
  2533. PDSA_StaticLocalVarShared,
  2534. PDSA_LoopIterVarPrivate,
  2535. PDSA_LoopIterVarLinear,
  2536. PDSA_LoopIterVarLastprivate,
  2537. PDSA_ConstVarShared,
  2538. PDSA_GlobalVarShared,
  2539. PDSA_TaskVarFirstprivate,
  2540. PDSA_LocalVarPrivate,
  2541. PDSA_Implicit
  2542. } Reason = PDSA_Implicit;
  2543. bool ReportHint = false;
  2544. auto ReportLoc = D->getLocation();
  2545. auto *VD = dyn_cast<VarDecl>(D);
  2546. if (IsLoopIterVar) {
  2547. if (DVar.CKind == OMPC_private)
  2548. Reason = PDSA_LoopIterVarPrivate;
  2549. else if (DVar.CKind == OMPC_lastprivate)
  2550. Reason = PDSA_LoopIterVarLastprivate;
  2551. else
  2552. Reason = PDSA_LoopIterVarLinear;
  2553. } else if (isOpenMPTaskingDirective(DVar.DKind) &&
  2554. DVar.CKind == OMPC_firstprivate) {
  2555. Reason = PDSA_TaskVarFirstprivate;
  2556. ReportLoc = DVar.ImplicitDSALoc;
  2557. } else if (VD && VD->isStaticLocal())
  2558. Reason = PDSA_StaticLocalVarShared;
  2559. else if (VD && VD->isStaticDataMember())
  2560. Reason = PDSA_StaticMemberShared;
  2561. else if (VD && VD->isFileVarDecl())
  2562. Reason = PDSA_GlobalVarShared;
  2563. else if (D->getType().isConstant(SemaRef.getASTContext()))
  2564. Reason = PDSA_ConstVarShared;
  2565. else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
  2566. ReportHint = true;
  2567. Reason = PDSA_LocalVarPrivate;
  2568. }
  2569. if (Reason != PDSA_Implicit) {
  2570. SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
  2571. << Reason << ReportHint
  2572. << getOpenMPDirectiveName(Stack->getCurrentDirective());
  2573. } else if (DVar.ImplicitDSALoc.isValid()) {
  2574. SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
  2575. << getOpenMPClauseName(DVar.CKind);
  2576. }
  2577. }
  2578. namespace {
  2579. class DSAAttrChecker final : public StmtVisitor<DSAAttrChecker, void> {
  2580. DSAStackTy *Stack;
  2581. Sema &SemaRef;
  2582. bool ErrorFound = false;
  2583. CapturedStmt *CS = nullptr;
  2584. llvm::SmallVector<Expr *, 4> ImplicitFirstprivate;
  2585. llvm::SmallVector<Expr *, 4> ImplicitMap;
  2586. Sema::VarsWithInheritedDSAType VarsWithInheritedDSA;
  2587. llvm::SmallDenseSet<const ValueDecl *, 4> ImplicitDeclarations;
  2588. void VisitSubCaptures(OMPExecutableDirective *S) {
  2589. // Check implicitly captured variables.
  2590. if (!S->hasAssociatedStmt() || !S->getAssociatedStmt())
  2591. return;
  2592. visitSubCaptures(S->getInnermostCapturedStmt());
  2593. }
  2594. public:
  2595. void VisitDeclRefExpr(DeclRefExpr *E) {
  2596. if (E->isTypeDependent() || E->isValueDependent() ||
  2597. E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
  2598. return;
  2599. if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
  2600. // Check the datasharing rules for the expressions in the clauses.
  2601. if (!CS) {
  2602. if (auto *CED = dyn_cast<OMPCapturedExprDecl>(VD))
  2603. if (!CED->hasAttr<OMPCaptureNoInitAttr>()) {
  2604. Visit(CED->getInit());
  2605. return;
  2606. }
  2607. } else if (VD->isImplicit() || isa<OMPCapturedExprDecl>(VD))
  2608. // Do not analyze internal variables and do not enclose them into
  2609. // implicit clauses.
  2610. return;
  2611. VD = VD->getCanonicalDecl();
  2612. // Skip internally declared variables.
  2613. if (VD->hasLocalStorage() && CS && !CS->capturesVariable(VD))
  2614. return;
  2615. DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
  2616. // Check if the variable has explicit DSA set and stop analysis if it so.
  2617. if (DVar.RefExpr || !ImplicitDeclarations.insert(VD).second)
  2618. return;
  2619. // Skip internally declared static variables.
  2620. llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
  2621. OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
  2622. if (VD->hasGlobalStorage() && CS && !CS->capturesVariable(VD) &&
  2623. (Stack->hasRequiresDeclWithClause<OMPUnifiedSharedMemoryClause>() ||
  2624. !Res || *Res != OMPDeclareTargetDeclAttr::MT_Link))
  2625. return;
  2626. SourceLocation ELoc = E->getExprLoc();
  2627. OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
  2628. // The default(none) clause requires that each variable that is referenced
  2629. // in the construct, and does not have a predetermined data-sharing
  2630. // attribute, must have its data-sharing attribute explicitly determined
  2631. // by being listed in a data-sharing attribute clause.
  2632. if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
  2633. isImplicitOrExplicitTaskingRegion(DKind) &&
  2634. VarsWithInheritedDSA.count(VD) == 0) {
  2635. VarsWithInheritedDSA[VD] = E;
  2636. return;
  2637. }
  2638. if (isOpenMPTargetExecutionDirective(DKind) &&
  2639. !Stack->isLoopControlVariable(VD).first) {
  2640. if (!Stack->checkMappableExprComponentListsForDecl(
  2641. VD, /*CurrentRegionOnly=*/true,
  2642. [](OMPClauseMappableExprCommon::MappableExprComponentListRef
  2643. StackComponents,
  2644. OpenMPClauseKind) {
  2645. // Variable is used if it has been marked as an array, array
  2646. // section or the variable iself.
  2647. return StackComponents.size() == 1 ||
  2648. std::all_of(
  2649. std::next(StackComponents.rbegin()),
  2650. StackComponents.rend(),
  2651. [](const OMPClauseMappableExprCommon::
  2652. MappableComponent &MC) {
  2653. return MC.getAssociatedDeclaration() ==
  2654. nullptr &&
  2655. (isa<OMPArraySectionExpr>(
  2656. MC.getAssociatedExpression()) ||
  2657. isa<ArraySubscriptExpr>(
  2658. MC.getAssociatedExpression()));
  2659. });
  2660. })) {
  2661. bool IsFirstprivate = false;
  2662. // By default lambdas are captured as firstprivates.
  2663. if (const auto *RD =
  2664. VD->getType().getNonReferenceType()->getAsCXXRecordDecl())
  2665. IsFirstprivate = RD->isLambda();
  2666. IsFirstprivate =
  2667. IsFirstprivate ||
  2668. (VD->getType().getNonReferenceType()->isScalarType() &&
  2669. Stack->getDefaultDMA() != DMA_tofrom_scalar && !Res);
  2670. if (IsFirstprivate)
  2671. ImplicitFirstprivate.emplace_back(E);
  2672. else
  2673. ImplicitMap.emplace_back(E);
  2674. return;
  2675. }
  2676. }
  2677. // OpenMP [2.9.3.6, Restrictions, p.2]
  2678. // A list item that appears in a reduction clause of the innermost
  2679. // enclosing worksharing or parallel construct may not be accessed in an
  2680. // explicit task.
  2681. DVar = Stack->hasInnermostDSA(
  2682. VD, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
  2683. [](OpenMPDirectiveKind K) {
  2684. return isOpenMPParallelDirective(K) ||
  2685. isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
  2686. },
  2687. /*FromParent=*/true);
  2688. if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
  2689. ErrorFound = true;
  2690. SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
  2691. reportOriginalDsa(SemaRef, Stack, VD, DVar);
  2692. return;
  2693. }
  2694. // Define implicit data-sharing attributes for task.
  2695. DVar = Stack->getImplicitDSA(VD, /*FromParent=*/false);
  2696. if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
  2697. !Stack->isLoopControlVariable(VD).first) {
  2698. ImplicitFirstprivate.push_back(E);
  2699. return;
  2700. }
  2701. // Store implicitly used globals with declare target link for parent
  2702. // target.
  2703. if (!isOpenMPTargetExecutionDirective(DKind) && Res &&
  2704. *Res == OMPDeclareTargetDeclAttr::MT_Link) {
  2705. Stack->addToParentTargetRegionLinkGlobals(E);
  2706. return;
  2707. }
  2708. }
  2709. }
  2710. void VisitMemberExpr(MemberExpr *E) {
  2711. if (E->isTypeDependent() || E->isValueDependent() ||
  2712. E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
  2713. return;
  2714. auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
  2715. OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
  2716. if (auto *TE = dyn_cast<CXXThisExpr>(E->getBase()->IgnoreParens())) {
  2717. if (!FD)
  2718. return;
  2719. DSAStackTy::DSAVarData DVar = Stack->getTopDSA(FD, /*FromParent=*/false);
  2720. // Check if the variable has explicit DSA set and stop analysis if it
  2721. // so.
  2722. if (DVar.RefExpr || !ImplicitDeclarations.insert(FD).second)
  2723. return;
  2724. if (isOpenMPTargetExecutionDirective(DKind) &&
  2725. !Stack->isLoopControlVariable(FD).first &&
  2726. !Stack->checkMappableExprComponentListsForDecl(
  2727. FD, /*CurrentRegionOnly=*/true,
  2728. [](OMPClauseMappableExprCommon::MappableExprComponentListRef
  2729. StackComponents,
  2730. OpenMPClauseKind) {
  2731. return isa<CXXThisExpr>(
  2732. cast<MemberExpr>(
  2733. StackComponents.back().getAssociatedExpression())
  2734. ->getBase()
  2735. ->IgnoreParens());
  2736. })) {
  2737. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
  2738. // A bit-field cannot appear in a map clause.
  2739. //
  2740. if (FD->isBitField())
  2741. return;
  2742. // Check to see if the member expression is referencing a class that
  2743. // has already been explicitly mapped
  2744. if (Stack->isClassPreviouslyMapped(TE->getType()))
  2745. return;
  2746. ImplicitMap.emplace_back(E);
  2747. return;
  2748. }
  2749. SourceLocation ELoc = E->getExprLoc();
  2750. // OpenMP [2.9.3.6, Restrictions, p.2]
  2751. // A list item that appears in a reduction clause of the innermost
  2752. // enclosing worksharing or parallel construct may not be accessed in
  2753. // an explicit task.
  2754. DVar = Stack->hasInnermostDSA(
  2755. FD, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
  2756. [](OpenMPDirectiveKind K) {
  2757. return isOpenMPParallelDirective(K) ||
  2758. isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
  2759. },
  2760. /*FromParent=*/true);
  2761. if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
  2762. ErrorFound = true;
  2763. SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
  2764. reportOriginalDsa(SemaRef, Stack, FD, DVar);
  2765. return;
  2766. }
  2767. // Define implicit data-sharing attributes for task.
  2768. DVar = Stack->getImplicitDSA(FD, /*FromParent=*/false);
  2769. if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
  2770. !Stack->isLoopControlVariable(FD).first) {
  2771. // Check if there is a captured expression for the current field in the
  2772. // region. Do not mark it as firstprivate unless there is no captured
  2773. // expression.
  2774. // TODO: try to make it firstprivate.
  2775. if (DVar.CKind != OMPC_unknown)
  2776. ImplicitFirstprivate.push_back(E);
  2777. }
  2778. return;
  2779. }
  2780. if (isOpenMPTargetExecutionDirective(DKind)) {
  2781. OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
  2782. if (!checkMapClauseExpressionBase(SemaRef, E, CurComponents, OMPC_map,
  2783. /*NoDiagnose=*/true))
  2784. return;
  2785. const auto *VD = cast<ValueDecl>(
  2786. CurComponents.back().getAssociatedDeclaration()->getCanonicalDecl());
  2787. if (!Stack->checkMappableExprComponentListsForDecl(
  2788. VD, /*CurrentRegionOnly=*/true,
  2789. [&CurComponents](
  2790. OMPClauseMappableExprCommon::MappableExprComponentListRef
  2791. StackComponents,
  2792. OpenMPClauseKind) {
  2793. auto CCI = CurComponents.rbegin();
  2794. auto CCE = CurComponents.rend();
  2795. for (const auto &SC : llvm::reverse(StackComponents)) {
  2796. // Do both expressions have the same kind?
  2797. if (CCI->getAssociatedExpression()->getStmtClass() !=
  2798. SC.getAssociatedExpression()->getStmtClass())
  2799. if (!(isa<OMPArraySectionExpr>(
  2800. SC.getAssociatedExpression()) &&
  2801. isa<ArraySubscriptExpr>(
  2802. CCI->getAssociatedExpression())))
  2803. return false;
  2804. const Decl *CCD = CCI->getAssociatedDeclaration();
  2805. const Decl *SCD = SC.getAssociatedDeclaration();
  2806. CCD = CCD ? CCD->getCanonicalDecl() : nullptr;
  2807. SCD = SCD ? SCD->getCanonicalDecl() : nullptr;
  2808. if (SCD != CCD)
  2809. return false;
  2810. std::advance(CCI, 1);
  2811. if (CCI == CCE)
  2812. break;
  2813. }
  2814. return true;
  2815. })) {
  2816. Visit(E->getBase());
  2817. }
  2818. } else {
  2819. Visit(E->getBase());
  2820. }
  2821. }
  2822. void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
  2823. for (OMPClause *C : S->clauses()) {
  2824. // Skip analysis of arguments of implicitly defined firstprivate clause
  2825. // for task|target directives.
  2826. // Skip analysis of arguments of implicitly defined map clause for target
  2827. // directives.
  2828. if (C && !((isa<OMPFirstprivateClause>(C) || isa<OMPMapClause>(C)) &&
  2829. C->isImplicit())) {
  2830. for (Stmt *CC : C->children()) {
  2831. if (CC)
  2832. Visit(CC);
  2833. }
  2834. }
  2835. }
  2836. // Check implicitly captured variables.
  2837. VisitSubCaptures(S);
  2838. }
  2839. void VisitStmt(Stmt *S) {
  2840. for (Stmt *C : S->children()) {
  2841. if (C) {
  2842. // Check implicitly captured variables in the task-based directives to
  2843. // check if they must be firstprivatized.
  2844. Visit(C);
  2845. }
  2846. }
  2847. }
  2848. void visitSubCaptures(CapturedStmt *S) {
  2849. for (const CapturedStmt::Capture &Cap : S->captures()) {
  2850. if (!Cap.capturesVariable() && !Cap.capturesVariableByCopy())
  2851. continue;
  2852. VarDecl *VD = Cap.getCapturedVar();
  2853. // Do not try to map the variable if it or its sub-component was mapped
  2854. // already.
  2855. if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) &&
  2856. Stack->checkMappableExprComponentListsForDecl(
  2857. VD, /*CurrentRegionOnly=*/true,
  2858. [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
  2859. OpenMPClauseKind) { return true; }))
  2860. continue;
  2861. DeclRefExpr *DRE = buildDeclRefExpr(
  2862. SemaRef, VD, VD->getType().getNonLValueExprType(SemaRef.Context),
  2863. Cap.getLocation(), /*RefersToCapture=*/true);
  2864. Visit(DRE);
  2865. }
  2866. }
  2867. bool isErrorFound() const { return ErrorFound; }
  2868. ArrayRef<Expr *> getImplicitFirstprivate() const {
  2869. return ImplicitFirstprivate;
  2870. }
  2871. ArrayRef<Expr *> getImplicitMap() const { return ImplicitMap; }
  2872. const Sema::VarsWithInheritedDSAType &getVarsWithInheritedDSA() const {
  2873. return VarsWithInheritedDSA;
  2874. }
  2875. DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
  2876. : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {
  2877. // Process declare target link variables for the target directives.
  2878. if (isOpenMPTargetExecutionDirective(S->getCurrentDirective())) {
  2879. for (DeclRefExpr *E : Stack->getLinkGlobals())
  2880. Visit(E);
  2881. }
  2882. }
  2883. };
  2884. } // namespace
  2885. void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
  2886. switch (DKind) {
  2887. case OMPD_parallel:
  2888. case OMPD_parallel_for:
  2889. case OMPD_parallel_for_simd:
  2890. case OMPD_parallel_sections:
  2891. case OMPD_teams:
  2892. case OMPD_teams_distribute:
  2893. case OMPD_teams_distribute_simd: {
  2894. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
  2895. QualType KmpInt32PtrTy =
  2896. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  2897. Sema::CapturedParamNameType Params[] = {
  2898. std::make_pair(".global_tid.", KmpInt32PtrTy),
  2899. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  2900. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2901. };
  2902. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2903. Params);
  2904. break;
  2905. }
  2906. case OMPD_target_teams:
  2907. case OMPD_target_parallel:
  2908. case OMPD_target_parallel_for:
  2909. case OMPD_target_parallel_for_simd:
  2910. case OMPD_target_teams_distribute:
  2911. case OMPD_target_teams_distribute_simd: {
  2912. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
  2913. QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
  2914. QualType KmpInt32PtrTy =
  2915. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  2916. QualType Args[] = {VoidPtrTy};
  2917. FunctionProtoType::ExtProtoInfo EPI;
  2918. EPI.Variadic = true;
  2919. QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
  2920. Sema::CapturedParamNameType Params[] = {
  2921. std::make_pair(".global_tid.", KmpInt32Ty),
  2922. std::make_pair(".part_id.", KmpInt32PtrTy),
  2923. std::make_pair(".privates.", VoidPtrTy),
  2924. std::make_pair(
  2925. ".copy_fn.",
  2926. Context.getPointerType(CopyFnType).withConst().withRestrict()),
  2927. std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
  2928. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2929. };
  2930. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2931. Params, /*OpenMPCaptureLevel=*/0);
  2932. // Mark this captured region as inlined, because we don't use outlined
  2933. // function directly.
  2934. getCurCapturedRegion()->TheCapturedDecl->addAttr(
  2935. AlwaysInlineAttr::CreateImplicit(
  2936. Context, {}, AttributeCommonInfo::AS_Keyword,
  2937. AlwaysInlineAttr::Keyword_forceinline));
  2938. Sema::CapturedParamNameType ParamsTarget[] = {
  2939. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2940. };
  2941. // Start a captured region for 'target' with no implicit parameters.
  2942. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2943. ParamsTarget, /*OpenMPCaptureLevel=*/1);
  2944. Sema::CapturedParamNameType ParamsTeamsOrParallel[] = {
  2945. std::make_pair(".global_tid.", KmpInt32PtrTy),
  2946. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  2947. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2948. };
  2949. // Start a captured region for 'teams' or 'parallel'. Both regions have
  2950. // the same implicit parameters.
  2951. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2952. ParamsTeamsOrParallel, /*OpenMPCaptureLevel=*/2);
  2953. break;
  2954. }
  2955. case OMPD_target:
  2956. case OMPD_target_simd: {
  2957. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
  2958. QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
  2959. QualType KmpInt32PtrTy =
  2960. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  2961. QualType Args[] = {VoidPtrTy};
  2962. FunctionProtoType::ExtProtoInfo EPI;
  2963. EPI.Variadic = true;
  2964. QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
  2965. Sema::CapturedParamNameType Params[] = {
  2966. std::make_pair(".global_tid.", KmpInt32Ty),
  2967. std::make_pair(".part_id.", KmpInt32PtrTy),
  2968. std::make_pair(".privates.", VoidPtrTy),
  2969. std::make_pair(
  2970. ".copy_fn.",
  2971. Context.getPointerType(CopyFnType).withConst().withRestrict()),
  2972. std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
  2973. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2974. };
  2975. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2976. Params, /*OpenMPCaptureLevel=*/0);
  2977. // Mark this captured region as inlined, because we don't use outlined
  2978. // function directly.
  2979. getCurCapturedRegion()->TheCapturedDecl->addAttr(
  2980. AlwaysInlineAttr::CreateImplicit(
  2981. Context, {}, AttributeCommonInfo::AS_Keyword,
  2982. AlwaysInlineAttr::Keyword_forceinline));
  2983. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2984. std::make_pair(StringRef(), QualType()),
  2985. /*OpenMPCaptureLevel=*/1);
  2986. break;
  2987. }
  2988. case OMPD_simd:
  2989. case OMPD_for:
  2990. case OMPD_for_simd:
  2991. case OMPD_sections:
  2992. case OMPD_section:
  2993. case OMPD_single:
  2994. case OMPD_master:
  2995. case OMPD_critical:
  2996. case OMPD_taskgroup:
  2997. case OMPD_distribute:
  2998. case OMPD_distribute_simd:
  2999. case OMPD_ordered:
  3000. case OMPD_atomic:
  3001. case OMPD_target_data: {
  3002. Sema::CapturedParamNameType Params[] = {
  3003. std::make_pair(StringRef(), QualType()) // __context with shared vars
  3004. };
  3005. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  3006. Params);
  3007. break;
  3008. }
  3009. case OMPD_task: {
  3010. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
  3011. QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
  3012. QualType KmpInt32PtrTy =
  3013. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  3014. QualType Args[] = {VoidPtrTy};
  3015. FunctionProtoType::ExtProtoInfo EPI;
  3016. EPI.Variadic = true;
  3017. QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
  3018. Sema::CapturedParamNameType Params[] = {
  3019. std::make_pair(".global_tid.", KmpInt32Ty),
  3020. std::make_pair(".part_id.", KmpInt32PtrTy),
  3021. std::make_pair(".privates.", VoidPtrTy),
  3022. std::make_pair(
  3023. ".copy_fn.",
  3024. Context.getPointerType(CopyFnType).withConst().withRestrict()),
  3025. std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
  3026. std::make_pair(StringRef(), QualType()) // __context with shared vars
  3027. };
  3028. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  3029. Params);
  3030. // Mark this captured region as inlined, because we don't use outlined
  3031. // function directly.
  3032. getCurCapturedRegion()->TheCapturedDecl->addAttr(
  3033. AlwaysInlineAttr::CreateImplicit(
  3034. Context, {}, AttributeCommonInfo::AS_Keyword,
  3035. AlwaysInlineAttr::Keyword_forceinline));
  3036. break;
  3037. }
  3038. case OMPD_taskloop:
  3039. case OMPD_taskloop_simd: {
  3040. QualType KmpInt32Ty =
  3041. Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1)
  3042. .withConst();
  3043. QualType KmpUInt64Ty =
  3044. Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0)
  3045. .withConst();
  3046. QualType KmpInt64Ty =
  3047. Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1)
  3048. .withConst();
  3049. QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
  3050. QualType KmpInt32PtrTy =
  3051. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  3052. QualType Args[] = {VoidPtrTy};
  3053. FunctionProtoType::ExtProtoInfo EPI;
  3054. EPI.Variadic = true;
  3055. QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
  3056. Sema::CapturedParamNameType Params[] = {
  3057. std::make_pair(".global_tid.", KmpInt32Ty),
  3058. std::make_pair(".part_id.", KmpInt32PtrTy),
  3059. std::make_pair(".privates.", VoidPtrTy),
  3060. std::make_pair(
  3061. ".copy_fn.",
  3062. Context.getPointerType(CopyFnType).withConst().withRestrict()),
  3063. std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
  3064. std::make_pair(".lb.", KmpUInt64Ty),
  3065. std::make_pair(".ub.", KmpUInt64Ty),
  3066. std::make_pair(".st.", KmpInt64Ty),
  3067. std::make_pair(".liter.", KmpInt32Ty),
  3068. std::make_pair(".reductions.", VoidPtrTy),
  3069. std::make_pair(StringRef(), QualType()) // __context with shared vars
  3070. };
  3071. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  3072. Params);
  3073. // Mark this captured region as inlined, because we don't use outlined
  3074. // function directly.
  3075. getCurCapturedRegion()->TheCapturedDecl->addAttr(
  3076. AlwaysInlineAttr::CreateImplicit(
  3077. Context, {}, AttributeCommonInfo::AS_Keyword,
  3078. AlwaysInlineAttr::Keyword_forceinline));
  3079. break;
  3080. }
  3081. case OMPD_distribute_parallel_for_simd:
  3082. case OMPD_distribute_parallel_for: {
  3083. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
  3084. QualType KmpInt32PtrTy =
  3085. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  3086. Sema::CapturedParamNameType Params[] = {
  3087. std::make_pair(".global_tid.", KmpInt32PtrTy),
  3088. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  3089. std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
  3090. std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
  3091. std::make_pair(StringRef(), QualType()) // __context with shared vars
  3092. };
  3093. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  3094. Params);
  3095. break;
  3096. }
  3097. case OMPD_target_teams_distribute_parallel_for:
  3098. case OMPD_target_teams_distribute_parallel_for_simd: {
  3099. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
  3100. QualType KmpInt32PtrTy =
  3101. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  3102. QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
  3103. QualType Args[] = {VoidPtrTy};
  3104. FunctionProtoType::ExtProtoInfo EPI;
  3105. EPI.Variadic = true;
  3106. QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
  3107. Sema::CapturedParamNameType Params[] = {
  3108. std::make_pair(".global_tid.", KmpInt32Ty),
  3109. std::make_pair(".part_id.", KmpInt32PtrTy),
  3110. std::make_pair(".privates.", VoidPtrTy),
  3111. std::make_pair(
  3112. ".copy_fn.",
  3113. Context.getPointerType(CopyFnType).withConst().withRestrict()),
  3114. std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
  3115. std::make_pair(StringRef(), QualType()) // __context with shared vars
  3116. };
  3117. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  3118. Params, /*OpenMPCaptureLevel=*/0);
  3119. // Mark this captured region as inlined, because we don't use outlined
  3120. // function directly.
  3121. getCurCapturedRegion()->TheCapturedDecl->addAttr(
  3122. AlwaysInlineAttr::CreateImplicit(
  3123. Context, {}, AttributeCommonInfo::AS_Keyword,
  3124. AlwaysInlineAttr::Keyword_forceinline));
  3125. Sema::CapturedParamNameType ParamsTarget[] = {
  3126. std::make_pair(StringRef(), QualType()) // __context with shared vars
  3127. };
  3128. // Start a captured region for 'target' with no implicit parameters.
  3129. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  3130. ParamsTarget, /*OpenMPCaptureLevel=*/1);
  3131. Sema::CapturedParamNameType ParamsTeams[] = {
  3132. std::make_pair(".global_tid.", KmpInt32PtrTy),
  3133. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  3134. std::make_pair(StringRef(), QualType()) // __context with shared vars
  3135. };
  3136. // Start a captured region for 'target' with no implicit parameters.
  3137. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  3138. ParamsTeams, /*OpenMPCaptureLevel=*/2);
  3139. Sema::CapturedParamNameType ParamsParallel[] = {
  3140. std::make_pair(".global_tid.", KmpInt32PtrTy),
  3141. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  3142. std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
  3143. std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
  3144. std::make_pair(StringRef(), QualType()) // __context with shared vars
  3145. };
  3146. // Start a captured region for 'teams' or 'parallel'. Both regions have
  3147. // the same implicit parameters.
  3148. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  3149. ParamsParallel, /*OpenMPCaptureLevel=*/3);
  3150. break;
  3151. }
  3152. case OMPD_teams_distribute_parallel_for:
  3153. case OMPD_teams_distribute_parallel_for_simd: {
  3154. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
  3155. QualType KmpInt32PtrTy =
  3156. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  3157. Sema::CapturedParamNameType ParamsTeams[] = {
  3158. std::make_pair(".global_tid.", KmpInt32PtrTy),
  3159. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  3160. std::make_pair(StringRef(), QualType()) // __context with shared vars
  3161. };
  3162. // Start a captured region for 'target' with no implicit parameters.
  3163. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  3164. ParamsTeams, /*OpenMPCaptureLevel=*/0);
  3165. Sema::CapturedParamNameType ParamsParallel[] = {
  3166. std::make_pair(".global_tid.", KmpInt32PtrTy),
  3167. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  3168. std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
  3169. std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
  3170. std::make_pair(StringRef(), QualType()) // __context with shared vars
  3171. };
  3172. // Start a captured region for 'teams' or 'parallel'. Both regions have
  3173. // the same implicit parameters.
  3174. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  3175. ParamsParallel, /*OpenMPCaptureLevel=*/1);
  3176. break;
  3177. }
  3178. case OMPD_target_update:
  3179. case OMPD_target_enter_data:
  3180. case OMPD_target_exit_data: {
  3181. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
  3182. QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
  3183. QualType KmpInt32PtrTy =
  3184. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  3185. QualType Args[] = {VoidPtrTy};
  3186. FunctionProtoType::ExtProtoInfo EPI;
  3187. EPI.Variadic = true;
  3188. QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
  3189. Sema::CapturedParamNameType Params[] = {
  3190. std::make_pair(".global_tid.", KmpInt32Ty),
  3191. std::make_pair(".part_id.", KmpInt32PtrTy),
  3192. std::make_pair(".privates.", VoidPtrTy),
  3193. std::make_pair(
  3194. ".copy_fn.",
  3195. Context.getPointerType(CopyFnType).withConst().withRestrict()),
  3196. std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
  3197. std::make_pair(StringRef(), QualType()) // __context with shared vars
  3198. };
  3199. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  3200. Params);
  3201. // Mark this captured region as inlined, because we don't use outlined
  3202. // function directly.
  3203. getCurCapturedRegion()->TheCapturedDecl->addAttr(
  3204. AlwaysInlineAttr::CreateImplicit(
  3205. Context, {}, AttributeCommonInfo::AS_Keyword,
  3206. AlwaysInlineAttr::Keyword_forceinline));
  3207. break;
  3208. }
  3209. case OMPD_threadprivate:
  3210. case OMPD_allocate:
  3211. case OMPD_taskyield:
  3212. case OMPD_barrier:
  3213. case OMPD_taskwait:
  3214. case OMPD_cancellation_point:
  3215. case OMPD_cancel:
  3216. case OMPD_flush:
  3217. case OMPD_declare_reduction:
  3218. case OMPD_declare_mapper:
  3219. case OMPD_declare_simd:
  3220. case OMPD_declare_target:
  3221. case OMPD_end_declare_target:
  3222. case OMPD_requires:
  3223. case OMPD_declare_variant:
  3224. llvm_unreachable("OpenMP Directive is not allowed");
  3225. case OMPD_unknown:
  3226. llvm_unreachable("Unknown OpenMP directive");
  3227. }
  3228. }
  3229. int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) {
  3230. SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
  3231. getOpenMPCaptureRegions(CaptureRegions, DKind);
  3232. return CaptureRegions.size();
  3233. }
  3234. static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
  3235. Expr *CaptureExpr, bool WithInit,
  3236. bool AsExpression) {
  3237. assert(CaptureExpr);
  3238. ASTContext &C = S.getASTContext();
  3239. Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
  3240. QualType Ty = Init->getType();
  3241. if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
  3242. if (S.getLangOpts().CPlusPlus) {
  3243. Ty = C.getLValueReferenceType(Ty);
  3244. } else {
  3245. Ty = C.getPointerType(Ty);
  3246. ExprResult Res =
  3247. S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
  3248. if (!Res.isUsable())
  3249. return nullptr;
  3250. Init = Res.get();
  3251. }
  3252. WithInit = true;
  3253. }
  3254. auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty,
  3255. CaptureExpr->getBeginLoc());
  3256. if (!WithInit)
  3257. CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C));
  3258. S.CurContext->addHiddenDecl(CED);
  3259. S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false);
  3260. return CED;
  3261. }
  3262. static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
  3263. bool WithInit) {
  3264. OMPCapturedExprDecl *CD;
  3265. if (VarDecl *VD = S.isOpenMPCapturedDecl(D))
  3266. CD = cast<OMPCapturedExprDecl>(VD);
  3267. else
  3268. CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
  3269. /*AsExpression=*/false);
  3270. return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
  3271. CaptureExpr->getExprLoc());
  3272. }
  3273. static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
  3274. CaptureExpr = S.DefaultLvalueConversion(CaptureExpr).get();
  3275. if (!Ref) {
  3276. OMPCapturedExprDecl *CD = buildCaptureDecl(
  3277. S, &S.getASTContext().Idents.get(".capture_expr."), CaptureExpr,
  3278. /*WithInit=*/true, /*AsExpression=*/true);
  3279. Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
  3280. CaptureExpr->getExprLoc());
  3281. }
  3282. ExprResult Res = Ref;
  3283. if (!S.getLangOpts().CPlusPlus &&
  3284. CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
  3285. Ref->getType()->isPointerType()) {
  3286. Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
  3287. if (!Res.isUsable())
  3288. return ExprError();
  3289. }
  3290. return S.DefaultLvalueConversion(Res.get());
  3291. }
  3292. namespace {
  3293. // OpenMP directives parsed in this section are represented as a
  3294. // CapturedStatement with an associated statement. If a syntax error
  3295. // is detected during the parsing of the associated statement, the
  3296. // compiler must abort processing and close the CapturedStatement.
  3297. //
  3298. // Combined directives such as 'target parallel' have more than one
  3299. // nested CapturedStatements. This RAII ensures that we unwind out
  3300. // of all the nested CapturedStatements when an error is found.
  3301. class CaptureRegionUnwinderRAII {
  3302. private:
  3303. Sema &S;
  3304. bool &ErrorFound;
  3305. OpenMPDirectiveKind DKind = OMPD_unknown;
  3306. public:
  3307. CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound,
  3308. OpenMPDirectiveKind DKind)
  3309. : S(S), ErrorFound(ErrorFound), DKind(DKind) {}
  3310. ~CaptureRegionUnwinderRAII() {
  3311. if (ErrorFound) {
  3312. int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind);
  3313. while (--ThisCaptureLevel >= 0)
  3314. S.ActOnCapturedRegionError();
  3315. }
  3316. }
  3317. };
  3318. } // namespace
  3319. void Sema::tryCaptureOpenMPLambdas(ValueDecl *V) {
  3320. // Capture variables captured by reference in lambdas for target-based
  3321. // directives.
  3322. if (!CurContext->isDependentContext() &&
  3323. (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) ||
  3324. isOpenMPTargetDataManagementDirective(
  3325. DSAStack->getCurrentDirective()))) {
  3326. QualType Type = V->getType();
  3327. if (const auto *RD = Type.getCanonicalType()
  3328. .getNonReferenceType()
  3329. ->getAsCXXRecordDecl()) {
  3330. bool SavedForceCaptureByReferenceInTargetExecutable =
  3331. DSAStack->isForceCaptureByReferenceInTargetExecutable();
  3332. DSAStack->setForceCaptureByReferenceInTargetExecutable(
  3333. /*V=*/true);
  3334. if (RD->isLambda()) {
  3335. llvm::DenseMap<const VarDecl *, FieldDecl *> Captures;
  3336. FieldDecl *ThisCapture;
  3337. RD->getCaptureFields(Captures, ThisCapture);
  3338. for (const LambdaCapture &LC : RD->captures()) {
  3339. if (LC.getCaptureKind() == LCK_ByRef) {
  3340. VarDecl *VD = LC.getCapturedVar();
  3341. DeclContext *VDC = VD->getDeclContext();
  3342. if (!VDC->Encloses(CurContext))
  3343. continue;
  3344. MarkVariableReferenced(LC.getLocation(), VD);
  3345. } else if (LC.getCaptureKind() == LCK_This) {
  3346. QualType ThisTy = getCurrentThisType();
  3347. if (!ThisTy.isNull() &&
  3348. Context.typesAreCompatible(ThisTy, ThisCapture->getType()))
  3349. CheckCXXThisCapture(LC.getLocation());
  3350. }
  3351. }
  3352. }
  3353. DSAStack->setForceCaptureByReferenceInTargetExecutable(
  3354. SavedForceCaptureByReferenceInTargetExecutable);
  3355. }
  3356. }
  3357. }
  3358. StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
  3359. ArrayRef<OMPClause *> Clauses) {
  3360. bool ErrorFound = false;
  3361. CaptureRegionUnwinderRAII CaptureRegionUnwinder(
  3362. *this, ErrorFound, DSAStack->getCurrentDirective());
  3363. if (!S.isUsable()) {
  3364. ErrorFound = true;
  3365. return StmtError();
  3366. }
  3367. SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
  3368. getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective());
  3369. OMPOrderedClause *OC = nullptr;
  3370. OMPScheduleClause *SC = nullptr;
  3371. SmallVector<const OMPLinearClause *, 4> LCs;
  3372. SmallVector<const OMPClauseWithPreInit *, 4> PICs;
  3373. // This is required for proper codegen.
  3374. for (OMPClause *Clause : Clauses) {
  3375. if (isOpenMPTaskingDirective(DSAStack->getCurrentDirective()) &&
  3376. Clause->getClauseKind() == OMPC_in_reduction) {
  3377. // Capture taskgroup task_reduction descriptors inside the tasking regions
  3378. // with the corresponding in_reduction items.
  3379. auto *IRC = cast<OMPInReductionClause>(Clause);
  3380. for (Expr *E : IRC->taskgroup_descriptors())
  3381. if (E)
  3382. MarkDeclarationsReferencedInExpr(E);
  3383. }
  3384. if (isOpenMPPrivate(Clause->getClauseKind()) ||
  3385. Clause->getClauseKind() == OMPC_copyprivate ||
  3386. (getLangOpts().OpenMPUseTLS &&
  3387. getASTContext().getTargetInfo().isTLSSupported() &&
  3388. Clause->getClauseKind() == OMPC_copyin)) {
  3389. DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
  3390. // Mark all variables in private list clauses as used in inner region.
  3391. for (Stmt *VarRef : Clause->children()) {
  3392. if (auto *E = cast_or_null<Expr>(VarRef)) {
  3393. MarkDeclarationsReferencedInExpr(E);
  3394. }
  3395. }
  3396. DSAStack->setForceVarCapturing(/*V=*/false);
  3397. } else if (CaptureRegions.size() > 1 ||
  3398. CaptureRegions.back() != OMPD_unknown) {
  3399. if (auto *C = OMPClauseWithPreInit::get(Clause))
  3400. PICs.push_back(C);
  3401. if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
  3402. if (Expr *E = C->getPostUpdateExpr())
  3403. MarkDeclarationsReferencedInExpr(E);
  3404. }
  3405. }
  3406. if (Clause->getClauseKind() == OMPC_schedule)
  3407. SC = cast<OMPScheduleClause>(Clause);
  3408. else if (Clause->getClauseKind() == OMPC_ordered)
  3409. OC = cast<OMPOrderedClause>(Clause);
  3410. else if (Clause->getClauseKind() == OMPC_linear)
  3411. LCs.push_back(cast<OMPLinearClause>(Clause));
  3412. }
  3413. // OpenMP, 2.7.1 Loop Construct, Restrictions
  3414. // The nonmonotonic modifier cannot be specified if an ordered clause is
  3415. // specified.
  3416. if (SC &&
  3417. (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
  3418. SC->getSecondScheduleModifier() ==
  3419. OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
  3420. OC) {
  3421. Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
  3422. ? SC->getFirstScheduleModifierLoc()
  3423. : SC->getSecondScheduleModifierLoc(),
  3424. diag::err_omp_schedule_nonmonotonic_ordered)
  3425. << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
  3426. ErrorFound = true;
  3427. }
  3428. if (!LCs.empty() && OC && OC->getNumForLoops()) {
  3429. for (const OMPLinearClause *C : LCs) {
  3430. Diag(C->getBeginLoc(), diag::err_omp_linear_ordered)
  3431. << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
  3432. }
  3433. ErrorFound = true;
  3434. }
  3435. if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
  3436. isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
  3437. OC->getNumForLoops()) {
  3438. Diag(OC->getBeginLoc(), diag::err_omp_ordered_simd)
  3439. << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
  3440. ErrorFound = true;
  3441. }
  3442. if (ErrorFound) {
  3443. return StmtError();
  3444. }
  3445. StmtResult SR = S;
  3446. unsigned CompletedRegions = 0;
  3447. for (OpenMPDirectiveKind ThisCaptureRegion : llvm::reverse(CaptureRegions)) {
  3448. // Mark all variables in private list clauses as used in inner region.
  3449. // Required for proper codegen of combined directives.
  3450. // TODO: add processing for other clauses.
  3451. if (ThisCaptureRegion != OMPD_unknown) {
  3452. for (const clang::OMPClauseWithPreInit *C : PICs) {
  3453. OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion();
  3454. // Find the particular capture region for the clause if the
  3455. // directive is a combined one with multiple capture regions.
  3456. // If the directive is not a combined one, the capture region
  3457. // associated with the clause is OMPD_unknown and is generated
  3458. // only once.
  3459. if (CaptureRegion == ThisCaptureRegion ||
  3460. CaptureRegion == OMPD_unknown) {
  3461. if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
  3462. for (Decl *D : DS->decls())
  3463. MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
  3464. }
  3465. }
  3466. }
  3467. }
  3468. if (++CompletedRegions == CaptureRegions.size())
  3469. DSAStack->setBodyComplete();
  3470. SR = ActOnCapturedRegionEnd(SR.get());
  3471. }
  3472. return SR;
  3473. }
  3474. static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion,
  3475. OpenMPDirectiveKind CancelRegion,
  3476. SourceLocation StartLoc) {
  3477. // CancelRegion is only needed for cancel and cancellation_point.
  3478. if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point)
  3479. return false;
  3480. if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for ||
  3481. CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup)
  3482. return false;
  3483. SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region)
  3484. << getOpenMPDirectiveName(CancelRegion);
  3485. return true;
  3486. }
  3487. static bool checkNestingOfRegions(Sema &SemaRef, const DSAStackTy *Stack,
  3488. OpenMPDirectiveKind CurrentRegion,
  3489. const DeclarationNameInfo &CurrentName,
  3490. OpenMPDirectiveKind CancelRegion,
  3491. SourceLocation StartLoc) {
  3492. if (Stack->getCurScope()) {
  3493. OpenMPDirectiveKind ParentRegion = Stack->getParentDirective();
  3494. OpenMPDirectiveKind OffendingRegion = ParentRegion;
  3495. bool NestingProhibited = false;
  3496. bool CloseNesting = true;
  3497. bool OrphanSeen = false;
  3498. enum {
  3499. NoRecommend,
  3500. ShouldBeInParallelRegion,
  3501. ShouldBeInOrderedRegion,
  3502. ShouldBeInTargetRegion,
  3503. ShouldBeInTeamsRegion
  3504. } Recommend = NoRecommend;
  3505. if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) {
  3506. // OpenMP [2.16, Nesting of Regions]
  3507. // OpenMP constructs may not be nested inside a simd region.
  3508. // OpenMP [2.8.1,simd Construct, Restrictions]
  3509. // An ordered construct with the simd clause is the only OpenMP
  3510. // construct that can appear in the simd region.
  3511. // Allowing a SIMD construct nested in another SIMD construct is an
  3512. // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
  3513. // message.
  3514. SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
  3515. ? diag::err_omp_prohibited_region_simd
  3516. : diag::warn_omp_nesting_simd);
  3517. return CurrentRegion != OMPD_simd;
  3518. }
  3519. if (ParentRegion == OMPD_atomic) {
  3520. // OpenMP [2.16, Nesting of Regions]
  3521. // OpenMP constructs may not be nested inside an atomic region.
  3522. SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
  3523. return true;
  3524. }
  3525. if (CurrentRegion == OMPD_section) {
  3526. // OpenMP [2.7.2, sections Construct, Restrictions]
  3527. // Orphaned section directives are prohibited. That is, the section
  3528. // directives must appear within the sections construct and must not be
  3529. // encountered elsewhere in the sections region.
  3530. if (ParentRegion != OMPD_sections &&
  3531. ParentRegion != OMPD_parallel_sections) {
  3532. SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
  3533. << (ParentRegion != OMPD_unknown)
  3534. << getOpenMPDirectiveName(ParentRegion);
  3535. return true;
  3536. }
  3537. return false;
  3538. }
  3539. // Allow some constructs (except teams and cancellation constructs) to be
  3540. // orphaned (they could be used in functions, called from OpenMP regions
  3541. // with the required preconditions).
  3542. if (ParentRegion == OMPD_unknown &&
  3543. !isOpenMPNestingTeamsDirective(CurrentRegion) &&
  3544. CurrentRegion != OMPD_cancellation_point &&
  3545. CurrentRegion != OMPD_cancel)
  3546. return false;
  3547. if (CurrentRegion == OMPD_cancellation_point ||
  3548. CurrentRegion == OMPD_cancel) {
  3549. // OpenMP [2.16, Nesting of Regions]
  3550. // A cancellation point construct for which construct-type-clause is
  3551. // taskgroup must be nested inside a task construct. A cancellation
  3552. // point construct for which construct-type-clause is not taskgroup must
  3553. // be closely nested inside an OpenMP construct that matches the type
  3554. // specified in construct-type-clause.
  3555. // A cancel construct for which construct-type-clause is taskgroup must be
  3556. // nested inside a task construct. A cancel construct for which
  3557. // construct-type-clause is not taskgroup must be closely nested inside an
  3558. // OpenMP construct that matches the type specified in
  3559. // construct-type-clause.
  3560. NestingProhibited =
  3561. !((CancelRegion == OMPD_parallel &&
  3562. (ParentRegion == OMPD_parallel ||
  3563. ParentRegion == OMPD_target_parallel)) ||
  3564. (CancelRegion == OMPD_for &&
  3565. (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
  3566. ParentRegion == OMPD_target_parallel_for ||
  3567. ParentRegion == OMPD_distribute_parallel_for ||
  3568. ParentRegion == OMPD_teams_distribute_parallel_for ||
  3569. ParentRegion == OMPD_target_teams_distribute_parallel_for)) ||
  3570. (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
  3571. (CancelRegion == OMPD_sections &&
  3572. (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
  3573. ParentRegion == OMPD_parallel_sections)));
  3574. OrphanSeen = ParentRegion == OMPD_unknown;
  3575. } else if (CurrentRegion == OMPD_master) {
  3576. // OpenMP [2.16, Nesting of Regions]
  3577. // A master region may not be closely nested inside a worksharing,
  3578. // atomic, or explicit task region.
  3579. NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
  3580. isOpenMPTaskingDirective(ParentRegion);
  3581. } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
  3582. // OpenMP [2.16, Nesting of Regions]
  3583. // A critical region may not be nested (closely or otherwise) inside a
  3584. // critical region with the same name. Note that this restriction is not
  3585. // sufficient to prevent deadlock.
  3586. SourceLocation PreviousCriticalLoc;
  3587. bool DeadLock = Stack->hasDirective(
  3588. [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
  3589. const DeclarationNameInfo &DNI,
  3590. SourceLocation Loc) {
  3591. if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
  3592. PreviousCriticalLoc = Loc;
  3593. return true;
  3594. }
  3595. return false;
  3596. },
  3597. false /* skip top directive */);
  3598. if (DeadLock) {
  3599. SemaRef.Diag(StartLoc,
  3600. diag::err_omp_prohibited_region_critical_same_name)
  3601. << CurrentName.getName();
  3602. if (PreviousCriticalLoc.isValid())
  3603. SemaRef.Diag(PreviousCriticalLoc,
  3604. diag::note_omp_previous_critical_region);
  3605. return true;
  3606. }
  3607. } else if (CurrentRegion == OMPD_barrier) {
  3608. // OpenMP [2.16, Nesting of Regions]
  3609. // A barrier region may not be closely nested inside a worksharing,
  3610. // explicit task, critical, ordered, atomic, or master region.
  3611. NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
  3612. isOpenMPTaskingDirective(ParentRegion) ||
  3613. ParentRegion == OMPD_master ||
  3614. ParentRegion == OMPD_critical ||
  3615. ParentRegion == OMPD_ordered;
  3616. } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
  3617. !isOpenMPParallelDirective(CurrentRegion) &&
  3618. !isOpenMPTeamsDirective(CurrentRegion)) {
  3619. // OpenMP [2.16, Nesting of Regions]
  3620. // A worksharing region may not be closely nested inside a worksharing,
  3621. // explicit task, critical, ordered, atomic, or master region.
  3622. NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
  3623. isOpenMPTaskingDirective(ParentRegion) ||
  3624. ParentRegion == OMPD_master ||
  3625. ParentRegion == OMPD_critical ||
  3626. ParentRegion == OMPD_ordered;
  3627. Recommend = ShouldBeInParallelRegion;
  3628. } else if (CurrentRegion == OMPD_ordered) {
  3629. // OpenMP [2.16, Nesting of Regions]
  3630. // An ordered region may not be closely nested inside a critical,
  3631. // atomic, or explicit task region.
  3632. // An ordered region must be closely nested inside a loop region (or
  3633. // parallel loop region) with an ordered clause.
  3634. // OpenMP [2.8.1,simd Construct, Restrictions]
  3635. // An ordered construct with the simd clause is the only OpenMP construct
  3636. // that can appear in the simd region.
  3637. NestingProhibited = ParentRegion == OMPD_critical ||
  3638. isOpenMPTaskingDirective(ParentRegion) ||
  3639. !(isOpenMPSimdDirective(ParentRegion) ||
  3640. Stack->isParentOrderedRegion());
  3641. Recommend = ShouldBeInOrderedRegion;
  3642. } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
  3643. // OpenMP [2.16, Nesting of Regions]
  3644. // If specified, a teams construct must be contained within a target
  3645. // construct.
  3646. NestingProhibited =
  3647. (SemaRef.LangOpts.OpenMP <= 45 && ParentRegion != OMPD_target) ||
  3648. (SemaRef.LangOpts.OpenMP >= 50 && ParentRegion != OMPD_unknown &&
  3649. ParentRegion != OMPD_target);
  3650. OrphanSeen = ParentRegion == OMPD_unknown;
  3651. Recommend = ShouldBeInTargetRegion;
  3652. }
  3653. if (!NestingProhibited &&
  3654. !isOpenMPTargetExecutionDirective(CurrentRegion) &&
  3655. !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
  3656. (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
  3657. // OpenMP [2.16, Nesting of Regions]
  3658. // distribute, parallel, parallel sections, parallel workshare, and the
  3659. // parallel loop and parallel loop SIMD constructs are the only OpenMP
  3660. // constructs that can be closely nested in the teams region.
  3661. NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
  3662. !isOpenMPDistributeDirective(CurrentRegion);
  3663. Recommend = ShouldBeInParallelRegion;
  3664. }
  3665. if (!NestingProhibited &&
  3666. isOpenMPNestingDistributeDirective(CurrentRegion)) {
  3667. // OpenMP 4.5 [2.17 Nesting of Regions]
  3668. // The region associated with the distribute construct must be strictly
  3669. // nested inside a teams region
  3670. NestingProhibited =
  3671. (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
  3672. Recommend = ShouldBeInTeamsRegion;
  3673. }
  3674. if (!NestingProhibited &&
  3675. (isOpenMPTargetExecutionDirective(CurrentRegion) ||
  3676. isOpenMPTargetDataManagementDirective(CurrentRegion))) {
  3677. // OpenMP 4.5 [2.17 Nesting of Regions]
  3678. // If a target, target update, target data, target enter data, or
  3679. // target exit data construct is encountered during execution of a
  3680. // target region, the behavior is unspecified.
  3681. NestingProhibited = Stack->hasDirective(
  3682. [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
  3683. SourceLocation) {
  3684. if (isOpenMPTargetExecutionDirective(K)) {
  3685. OffendingRegion = K;
  3686. return true;
  3687. }
  3688. return false;
  3689. },
  3690. false /* don't skip top directive */);
  3691. CloseNesting = false;
  3692. }
  3693. if (NestingProhibited) {
  3694. if (OrphanSeen) {
  3695. SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
  3696. << getOpenMPDirectiveName(CurrentRegion) << Recommend;
  3697. } else {
  3698. SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
  3699. << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
  3700. << Recommend << getOpenMPDirectiveName(CurrentRegion);
  3701. }
  3702. return true;
  3703. }
  3704. }
  3705. return false;
  3706. }
  3707. static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
  3708. ArrayRef<OMPClause *> Clauses,
  3709. ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
  3710. bool ErrorFound = false;
  3711. unsigned NamedModifiersNumber = 0;
  3712. SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers(
  3713. OMPD_unknown + 1);
  3714. SmallVector<SourceLocation, 4> NameModifierLoc;
  3715. for (const OMPClause *C : Clauses) {
  3716. if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
  3717. // At most one if clause without a directive-name-modifier can appear on
  3718. // the directive.
  3719. OpenMPDirectiveKind CurNM = IC->getNameModifier();
  3720. if (FoundNameModifiers[CurNM]) {
  3721. S.Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
  3722. << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
  3723. << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
  3724. ErrorFound = true;
  3725. } else if (CurNM != OMPD_unknown) {
  3726. NameModifierLoc.push_back(IC->getNameModifierLoc());
  3727. ++NamedModifiersNumber;
  3728. }
  3729. FoundNameModifiers[CurNM] = IC;
  3730. if (CurNM == OMPD_unknown)
  3731. continue;
  3732. // Check if the specified name modifier is allowed for the current
  3733. // directive.
  3734. // At most one if clause with the particular directive-name-modifier can
  3735. // appear on the directive.
  3736. bool MatchFound = false;
  3737. for (auto NM : AllowedNameModifiers) {
  3738. if (CurNM == NM) {
  3739. MatchFound = true;
  3740. break;
  3741. }
  3742. }
  3743. if (!MatchFound) {
  3744. S.Diag(IC->getNameModifierLoc(),
  3745. diag::err_omp_wrong_if_directive_name_modifier)
  3746. << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
  3747. ErrorFound = true;
  3748. }
  3749. }
  3750. }
  3751. // If any if clause on the directive includes a directive-name-modifier then
  3752. // all if clauses on the directive must include a directive-name-modifier.
  3753. if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
  3754. if (NamedModifiersNumber == AllowedNameModifiers.size()) {
  3755. S.Diag(FoundNameModifiers[OMPD_unknown]->getBeginLoc(),
  3756. diag::err_omp_no_more_if_clause);
  3757. } else {
  3758. std::string Values;
  3759. std::string Sep(", ");
  3760. unsigned AllowedCnt = 0;
  3761. unsigned TotalAllowedNum =
  3762. AllowedNameModifiers.size() - NamedModifiersNumber;
  3763. for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
  3764. ++Cnt) {
  3765. OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
  3766. if (!FoundNameModifiers[NM]) {
  3767. Values += "'";
  3768. Values += getOpenMPDirectiveName(NM);
  3769. Values += "'";
  3770. if (AllowedCnt + 2 == TotalAllowedNum)
  3771. Values += " or ";
  3772. else if (AllowedCnt + 1 != TotalAllowedNum)
  3773. Values += Sep;
  3774. ++AllowedCnt;
  3775. }
  3776. }
  3777. S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getBeginLoc(),
  3778. diag::err_omp_unnamed_if_clause)
  3779. << (TotalAllowedNum > 1) << Values;
  3780. }
  3781. for (SourceLocation Loc : NameModifierLoc) {
  3782. S.Diag(Loc, diag::note_omp_previous_named_if_clause);
  3783. }
  3784. ErrorFound = true;
  3785. }
  3786. return ErrorFound;
  3787. }
  3788. static std::pair<ValueDecl *, bool>
  3789. getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
  3790. SourceRange &ERange, bool AllowArraySection = false) {
  3791. if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
  3792. RefExpr->containsUnexpandedParameterPack())
  3793. return std::make_pair(nullptr, true);
  3794. // OpenMP [3.1, C/C++]
  3795. // A list item is a variable name.
  3796. // OpenMP [2.9.3.3, Restrictions, p.1]
  3797. // A variable that is part of another variable (as an array or
  3798. // structure element) cannot appear in a private clause.
  3799. RefExpr = RefExpr->IgnoreParens();
  3800. enum {
  3801. NoArrayExpr = -1,
  3802. ArraySubscript = 0,
  3803. OMPArraySection = 1
  3804. } IsArrayExpr = NoArrayExpr;
  3805. if (AllowArraySection) {
  3806. if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
  3807. Expr *Base = ASE->getBase()->IgnoreParenImpCasts();
  3808. while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
  3809. Base = TempASE->getBase()->IgnoreParenImpCasts();
  3810. RefExpr = Base;
  3811. IsArrayExpr = ArraySubscript;
  3812. } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
  3813. Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
  3814. while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
  3815. Base = TempOASE->getBase()->IgnoreParenImpCasts();
  3816. while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
  3817. Base = TempASE->getBase()->IgnoreParenImpCasts();
  3818. RefExpr = Base;
  3819. IsArrayExpr = OMPArraySection;
  3820. }
  3821. }
  3822. ELoc = RefExpr->getExprLoc();
  3823. ERange = RefExpr->getSourceRange();
  3824. RefExpr = RefExpr->IgnoreParenImpCasts();
  3825. auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
  3826. auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
  3827. if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
  3828. (S.getCurrentThisType().isNull() || !ME ||
  3829. !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
  3830. !isa<FieldDecl>(ME->getMemberDecl()))) {
  3831. if (IsArrayExpr != NoArrayExpr) {
  3832. S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr
  3833. << ERange;
  3834. } else {
  3835. S.Diag(ELoc,
  3836. AllowArraySection
  3837. ? diag::err_omp_expected_var_name_member_expr_or_array_item
  3838. : diag::err_omp_expected_var_name_member_expr)
  3839. << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
  3840. }
  3841. return std::make_pair(nullptr, false);
  3842. }
  3843. return std::make_pair(
  3844. getCanonicalDecl(DE ? DE->getDecl() : ME->getMemberDecl()), false);
  3845. }
  3846. static void checkAllocateClauses(Sema &S, DSAStackTy *Stack,
  3847. ArrayRef<OMPClause *> Clauses) {
  3848. assert(!S.CurContext->isDependentContext() &&
  3849. "Expected non-dependent context.");
  3850. auto AllocateRange =
  3851. llvm::make_filter_range(Clauses, OMPAllocateClause::classof);
  3852. llvm::DenseMap<CanonicalDeclPtr<Decl>, CanonicalDeclPtr<VarDecl>>
  3853. DeclToCopy;
  3854. auto PrivateRange = llvm::make_filter_range(Clauses, [](const OMPClause *C) {
  3855. return isOpenMPPrivate(C->getClauseKind());
  3856. });
  3857. for (OMPClause *Cl : PrivateRange) {
  3858. MutableArrayRef<Expr *>::iterator I, It, Et;
  3859. if (Cl->getClauseKind() == OMPC_private) {
  3860. auto *PC = cast<OMPPrivateClause>(Cl);
  3861. I = PC->private_copies().begin();
  3862. It = PC->varlist_begin();
  3863. Et = PC->varlist_end();
  3864. } else if (Cl->getClauseKind() == OMPC_firstprivate) {
  3865. auto *PC = cast<OMPFirstprivateClause>(Cl);
  3866. I = PC->private_copies().begin();
  3867. It = PC->varlist_begin();
  3868. Et = PC->varlist_end();
  3869. } else if (Cl->getClauseKind() == OMPC_lastprivate) {
  3870. auto *PC = cast<OMPLastprivateClause>(Cl);
  3871. I = PC->private_copies().begin();
  3872. It = PC->varlist_begin();
  3873. Et = PC->varlist_end();
  3874. } else if (Cl->getClauseKind() == OMPC_linear) {
  3875. auto *PC = cast<OMPLinearClause>(Cl);
  3876. I = PC->privates().begin();
  3877. It = PC->varlist_begin();
  3878. Et = PC->varlist_end();
  3879. } else if (Cl->getClauseKind() == OMPC_reduction) {
  3880. auto *PC = cast<OMPReductionClause>(Cl);
  3881. I = PC->privates().begin();
  3882. It = PC->varlist_begin();
  3883. Et = PC->varlist_end();
  3884. } else if (Cl->getClauseKind() == OMPC_task_reduction) {
  3885. auto *PC = cast<OMPTaskReductionClause>(Cl);
  3886. I = PC->privates().begin();
  3887. It = PC->varlist_begin();
  3888. Et = PC->varlist_end();
  3889. } else if (Cl->getClauseKind() == OMPC_in_reduction) {
  3890. auto *PC = cast<OMPInReductionClause>(Cl);
  3891. I = PC->privates().begin();
  3892. It = PC->varlist_begin();
  3893. Et = PC->varlist_end();
  3894. } else {
  3895. llvm_unreachable("Expected private clause.");
  3896. }
  3897. for (Expr *E : llvm::make_range(It, Et)) {
  3898. if (!*I) {
  3899. ++I;
  3900. continue;
  3901. }
  3902. SourceLocation ELoc;
  3903. SourceRange ERange;
  3904. Expr *SimpleRefExpr = E;
  3905. auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
  3906. /*AllowArraySection=*/true);
  3907. DeclToCopy.try_emplace(Res.first,
  3908. cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()));
  3909. ++I;
  3910. }
  3911. }
  3912. for (OMPClause *C : AllocateRange) {
  3913. auto *AC = cast<OMPAllocateClause>(C);
  3914. OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind =
  3915. getAllocatorKind(S, Stack, AC->getAllocator());
  3916. // OpenMP, 2.11.4 allocate Clause, Restrictions.
  3917. // For task, taskloop or target directives, allocation requests to memory
  3918. // allocators with the trait access set to thread result in unspecified
  3919. // behavior.
  3920. if (AllocatorKind == OMPAllocateDeclAttr::OMPThreadMemAlloc &&
  3921. (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
  3922. isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()))) {
  3923. S.Diag(AC->getAllocator()->getExprLoc(),
  3924. diag::warn_omp_allocate_thread_on_task_target_directive)
  3925. << getOpenMPDirectiveName(Stack->getCurrentDirective());
  3926. }
  3927. for (Expr *E : AC->varlists()) {
  3928. SourceLocation ELoc;
  3929. SourceRange ERange;
  3930. Expr *SimpleRefExpr = E;
  3931. auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange);
  3932. ValueDecl *VD = Res.first;
  3933. DSAStackTy::DSAVarData Data = Stack->getTopDSA(VD, /*FromParent=*/false);
  3934. if (!isOpenMPPrivate(Data.CKind)) {
  3935. S.Diag(E->getExprLoc(),
  3936. diag::err_omp_expected_private_copy_for_allocate);
  3937. continue;
  3938. }
  3939. VarDecl *PrivateVD = DeclToCopy[VD];
  3940. if (checkPreviousOMPAllocateAttribute(S, Stack, E, PrivateVD,
  3941. AllocatorKind, AC->getAllocator()))
  3942. continue;
  3943. applyOMPAllocateAttribute(S, PrivateVD, AllocatorKind, AC->getAllocator(),
  3944. E->getSourceRange());
  3945. }
  3946. }
  3947. }
  3948. StmtResult Sema::ActOnOpenMPExecutableDirective(
  3949. OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
  3950. OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
  3951. Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
  3952. StmtResult Res = StmtError();
  3953. // First check CancelRegion which is then used in checkNestingOfRegions.
  3954. if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) ||
  3955. checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
  3956. StartLoc))
  3957. return StmtError();
  3958. llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
  3959. VarsWithInheritedDSAType VarsWithInheritedDSA;
  3960. bool ErrorFound = false;
  3961. ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
  3962. if (AStmt && !CurContext->isDependentContext()) {
  3963. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  3964. // Check default data sharing attributes for referenced variables.
  3965. DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
  3966. int ThisCaptureLevel = getOpenMPCaptureLevels(Kind);
  3967. Stmt *S = AStmt;
  3968. while (--ThisCaptureLevel >= 0)
  3969. S = cast<CapturedStmt>(S)->getCapturedStmt();
  3970. DSAChecker.Visit(S);
  3971. if (!isOpenMPTargetDataManagementDirective(Kind) &&
  3972. !isOpenMPTaskingDirective(Kind)) {
  3973. // Visit subcaptures to generate implicit clauses for captured vars.
  3974. auto *CS = cast<CapturedStmt>(AStmt);
  3975. SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
  3976. getOpenMPCaptureRegions(CaptureRegions, Kind);
  3977. // Ignore outer tasking regions for target directives.
  3978. if (CaptureRegions.size() > 1 && CaptureRegions.front() == OMPD_task)
  3979. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  3980. DSAChecker.visitSubCaptures(CS);
  3981. }
  3982. if (DSAChecker.isErrorFound())
  3983. return StmtError();
  3984. // Generate list of implicitly defined firstprivate variables.
  3985. VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
  3986. SmallVector<Expr *, 4> ImplicitFirstprivates(
  3987. DSAChecker.getImplicitFirstprivate().begin(),
  3988. DSAChecker.getImplicitFirstprivate().end());
  3989. SmallVector<Expr *, 4> ImplicitMaps(DSAChecker.getImplicitMap().begin(),
  3990. DSAChecker.getImplicitMap().end());
  3991. // Mark taskgroup task_reduction descriptors as implicitly firstprivate.
  3992. for (OMPClause *C : Clauses) {
  3993. if (auto *IRC = dyn_cast<OMPInReductionClause>(C)) {
  3994. for (Expr *E : IRC->taskgroup_descriptors())
  3995. if (E)
  3996. ImplicitFirstprivates.emplace_back(E);
  3997. }
  3998. }
  3999. if (!ImplicitFirstprivates.empty()) {
  4000. if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
  4001. ImplicitFirstprivates, SourceLocation(), SourceLocation(),
  4002. SourceLocation())) {
  4003. ClausesWithImplicit.push_back(Implicit);
  4004. ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
  4005. ImplicitFirstprivates.size();
  4006. } else {
  4007. ErrorFound = true;
  4008. }
  4009. }
  4010. if (!ImplicitMaps.empty()) {
  4011. CXXScopeSpec MapperIdScopeSpec;
  4012. DeclarationNameInfo MapperId;
  4013. if (OMPClause *Implicit = ActOnOpenMPMapClause(
  4014. llvm::None, llvm::None, MapperIdScopeSpec, MapperId,
  4015. OMPC_MAP_tofrom, /*IsMapTypeImplicit=*/true, SourceLocation(),
  4016. SourceLocation(), ImplicitMaps, OMPVarListLocTy())) {
  4017. ClausesWithImplicit.emplace_back(Implicit);
  4018. ErrorFound |=
  4019. cast<OMPMapClause>(Implicit)->varlist_size() != ImplicitMaps.size();
  4020. } else {
  4021. ErrorFound = true;
  4022. }
  4023. }
  4024. }
  4025. llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
  4026. switch (Kind) {
  4027. case OMPD_parallel:
  4028. Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
  4029. EndLoc);
  4030. AllowedNameModifiers.push_back(OMPD_parallel);
  4031. break;
  4032. case OMPD_simd:
  4033. Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
  4034. VarsWithInheritedDSA);
  4035. break;
  4036. case OMPD_for:
  4037. Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
  4038. VarsWithInheritedDSA);
  4039. break;
  4040. case OMPD_for_simd:
  4041. Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
  4042. EndLoc, VarsWithInheritedDSA);
  4043. break;
  4044. case OMPD_sections:
  4045. Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
  4046. EndLoc);
  4047. break;
  4048. case OMPD_section:
  4049. assert(ClausesWithImplicit.empty() &&
  4050. "No clauses are allowed for 'omp section' directive");
  4051. Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
  4052. break;
  4053. case OMPD_single:
  4054. Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
  4055. EndLoc);
  4056. break;
  4057. case OMPD_master:
  4058. assert(ClausesWithImplicit.empty() &&
  4059. "No clauses are allowed for 'omp master' directive");
  4060. Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
  4061. break;
  4062. case OMPD_critical:
  4063. Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
  4064. StartLoc, EndLoc);
  4065. break;
  4066. case OMPD_parallel_for:
  4067. Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
  4068. EndLoc, VarsWithInheritedDSA);
  4069. AllowedNameModifiers.push_back(OMPD_parallel);
  4070. break;
  4071. case OMPD_parallel_for_simd:
  4072. Res = ActOnOpenMPParallelForSimdDirective(
  4073. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  4074. AllowedNameModifiers.push_back(OMPD_parallel);
  4075. break;
  4076. case OMPD_parallel_sections:
  4077. Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
  4078. StartLoc, EndLoc);
  4079. AllowedNameModifiers.push_back(OMPD_parallel);
  4080. break;
  4081. case OMPD_task:
  4082. Res =
  4083. ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
  4084. AllowedNameModifiers.push_back(OMPD_task);
  4085. break;
  4086. case OMPD_taskyield:
  4087. assert(ClausesWithImplicit.empty() &&
  4088. "No clauses are allowed for 'omp taskyield' directive");
  4089. assert(AStmt == nullptr &&
  4090. "No associated statement allowed for 'omp taskyield' directive");
  4091. Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
  4092. break;
  4093. case OMPD_barrier:
  4094. assert(ClausesWithImplicit.empty() &&
  4095. "No clauses are allowed for 'omp barrier' directive");
  4096. assert(AStmt == nullptr &&
  4097. "No associated statement allowed for 'omp barrier' directive");
  4098. Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
  4099. break;
  4100. case OMPD_taskwait:
  4101. assert(ClausesWithImplicit.empty() &&
  4102. "No clauses are allowed for 'omp taskwait' directive");
  4103. assert(AStmt == nullptr &&
  4104. "No associated statement allowed for 'omp taskwait' directive");
  4105. Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
  4106. break;
  4107. case OMPD_taskgroup:
  4108. Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc,
  4109. EndLoc);
  4110. break;
  4111. case OMPD_flush:
  4112. assert(AStmt == nullptr &&
  4113. "No associated statement allowed for 'omp flush' directive");
  4114. Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
  4115. break;
  4116. case OMPD_ordered:
  4117. Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
  4118. EndLoc);
  4119. break;
  4120. case OMPD_atomic:
  4121. Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
  4122. EndLoc);
  4123. break;
  4124. case OMPD_teams:
  4125. Res =
  4126. ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
  4127. break;
  4128. case OMPD_target:
  4129. Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
  4130. EndLoc);
  4131. AllowedNameModifiers.push_back(OMPD_target);
  4132. break;
  4133. case OMPD_target_parallel:
  4134. Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
  4135. StartLoc, EndLoc);
  4136. AllowedNameModifiers.push_back(OMPD_target);
  4137. AllowedNameModifiers.push_back(OMPD_parallel);
  4138. break;
  4139. case OMPD_target_parallel_for:
  4140. Res = ActOnOpenMPTargetParallelForDirective(
  4141. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  4142. AllowedNameModifiers.push_back(OMPD_target);
  4143. AllowedNameModifiers.push_back(OMPD_parallel);
  4144. break;
  4145. case OMPD_cancellation_point:
  4146. assert(ClausesWithImplicit.empty() &&
  4147. "No clauses are allowed for 'omp cancellation point' directive");
  4148. assert(AStmt == nullptr && "No associated statement allowed for 'omp "
  4149. "cancellation point' directive");
  4150. Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
  4151. break;
  4152. case OMPD_cancel:
  4153. assert(AStmt == nullptr &&
  4154. "No associated statement allowed for 'omp cancel' directive");
  4155. Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
  4156. CancelRegion);
  4157. AllowedNameModifiers.push_back(OMPD_cancel);
  4158. break;
  4159. case OMPD_target_data:
  4160. Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
  4161. EndLoc);
  4162. AllowedNameModifiers.push_back(OMPD_target_data);
  4163. break;
  4164. case OMPD_target_enter_data:
  4165. Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
  4166. EndLoc, AStmt);
  4167. AllowedNameModifiers.push_back(OMPD_target_enter_data);
  4168. break;
  4169. case OMPD_target_exit_data:
  4170. Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
  4171. EndLoc, AStmt);
  4172. AllowedNameModifiers.push_back(OMPD_target_exit_data);
  4173. break;
  4174. case OMPD_taskloop:
  4175. Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
  4176. EndLoc, VarsWithInheritedDSA);
  4177. AllowedNameModifiers.push_back(OMPD_taskloop);
  4178. break;
  4179. case OMPD_taskloop_simd:
  4180. Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
  4181. EndLoc, VarsWithInheritedDSA);
  4182. AllowedNameModifiers.push_back(OMPD_taskloop);
  4183. break;
  4184. case OMPD_distribute:
  4185. Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
  4186. EndLoc, VarsWithInheritedDSA);
  4187. break;
  4188. case OMPD_target_update:
  4189. Res = ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc,
  4190. EndLoc, AStmt);
  4191. AllowedNameModifiers.push_back(OMPD_target_update);
  4192. break;
  4193. case OMPD_distribute_parallel_for:
  4194. Res = ActOnOpenMPDistributeParallelForDirective(
  4195. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  4196. AllowedNameModifiers.push_back(OMPD_parallel);
  4197. break;
  4198. case OMPD_distribute_parallel_for_simd:
  4199. Res = ActOnOpenMPDistributeParallelForSimdDirective(
  4200. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  4201. AllowedNameModifiers.push_back(OMPD_parallel);
  4202. break;
  4203. case OMPD_distribute_simd:
  4204. Res = ActOnOpenMPDistributeSimdDirective(
  4205. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  4206. break;
  4207. case OMPD_target_parallel_for_simd:
  4208. Res = ActOnOpenMPTargetParallelForSimdDirective(
  4209. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  4210. AllowedNameModifiers.push_back(OMPD_target);
  4211. AllowedNameModifiers.push_back(OMPD_parallel);
  4212. break;
  4213. case OMPD_target_simd:
  4214. Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
  4215. EndLoc, VarsWithInheritedDSA);
  4216. AllowedNameModifiers.push_back(OMPD_target);
  4217. break;
  4218. case OMPD_teams_distribute:
  4219. Res = ActOnOpenMPTeamsDistributeDirective(
  4220. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  4221. break;
  4222. case OMPD_teams_distribute_simd:
  4223. Res = ActOnOpenMPTeamsDistributeSimdDirective(
  4224. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  4225. break;
  4226. case OMPD_teams_distribute_parallel_for_simd:
  4227. Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
  4228. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  4229. AllowedNameModifiers.push_back(OMPD_parallel);
  4230. break;
  4231. case OMPD_teams_distribute_parallel_for:
  4232. Res = ActOnOpenMPTeamsDistributeParallelForDirective(
  4233. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  4234. AllowedNameModifiers.push_back(OMPD_parallel);
  4235. break;
  4236. case OMPD_target_teams:
  4237. Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
  4238. EndLoc);
  4239. AllowedNameModifiers.push_back(OMPD_target);
  4240. break;
  4241. case OMPD_target_teams_distribute:
  4242. Res = ActOnOpenMPTargetTeamsDistributeDirective(
  4243. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  4244. AllowedNameModifiers.push_back(OMPD_target);
  4245. break;
  4246. case OMPD_target_teams_distribute_parallel_for:
  4247. Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective(
  4248. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  4249. AllowedNameModifiers.push_back(OMPD_target);
  4250. AllowedNameModifiers.push_back(OMPD_parallel);
  4251. break;
  4252. case OMPD_target_teams_distribute_parallel_for_simd:
  4253. Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
  4254. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  4255. AllowedNameModifiers.push_back(OMPD_target);
  4256. AllowedNameModifiers.push_back(OMPD_parallel);
  4257. break;
  4258. case OMPD_target_teams_distribute_simd:
  4259. Res = ActOnOpenMPTargetTeamsDistributeSimdDirective(
  4260. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  4261. AllowedNameModifiers.push_back(OMPD_target);
  4262. break;
  4263. case OMPD_declare_target:
  4264. case OMPD_end_declare_target:
  4265. case OMPD_threadprivate:
  4266. case OMPD_allocate:
  4267. case OMPD_declare_reduction:
  4268. case OMPD_declare_mapper:
  4269. case OMPD_declare_simd:
  4270. case OMPD_requires:
  4271. case OMPD_declare_variant:
  4272. llvm_unreachable("OpenMP Directive is not allowed");
  4273. case OMPD_unknown:
  4274. llvm_unreachable("Unknown OpenMP directive");
  4275. }
  4276. ErrorFound = Res.isInvalid() || ErrorFound;
  4277. // Check variables in the clauses if default(none) was specified.
  4278. if (DSAStack->getDefaultDSA() == DSA_none) {
  4279. DSAAttrChecker DSAChecker(DSAStack, *this, nullptr);
  4280. for (OMPClause *C : Clauses) {
  4281. switch (C->getClauseKind()) {
  4282. case OMPC_num_threads:
  4283. case OMPC_dist_schedule:
  4284. // Do not analyse if no parent teams directive.
  4285. if (isOpenMPTeamsDirective(DSAStack->getCurrentDirective()))
  4286. break;
  4287. continue;
  4288. case OMPC_if:
  4289. if (isOpenMPTeamsDirective(DSAStack->getCurrentDirective()) &&
  4290. cast<OMPIfClause>(C)->getNameModifier() != OMPD_target)
  4291. break;
  4292. continue;
  4293. case OMPC_schedule:
  4294. break;
  4295. case OMPC_ordered:
  4296. case OMPC_device:
  4297. case OMPC_num_teams:
  4298. case OMPC_thread_limit:
  4299. case OMPC_priority:
  4300. case OMPC_grainsize:
  4301. case OMPC_num_tasks:
  4302. case OMPC_hint:
  4303. case OMPC_collapse:
  4304. case OMPC_safelen:
  4305. case OMPC_simdlen:
  4306. case OMPC_final:
  4307. case OMPC_default:
  4308. case OMPC_proc_bind:
  4309. case OMPC_private:
  4310. case OMPC_firstprivate:
  4311. case OMPC_lastprivate:
  4312. case OMPC_shared:
  4313. case OMPC_reduction:
  4314. case OMPC_task_reduction:
  4315. case OMPC_in_reduction:
  4316. case OMPC_linear:
  4317. case OMPC_aligned:
  4318. case OMPC_copyin:
  4319. case OMPC_copyprivate:
  4320. case OMPC_nowait:
  4321. case OMPC_untied:
  4322. case OMPC_mergeable:
  4323. case OMPC_allocate:
  4324. case OMPC_read:
  4325. case OMPC_write:
  4326. case OMPC_update:
  4327. case OMPC_capture:
  4328. case OMPC_seq_cst:
  4329. case OMPC_depend:
  4330. case OMPC_threads:
  4331. case OMPC_simd:
  4332. case OMPC_map:
  4333. case OMPC_nogroup:
  4334. case OMPC_defaultmap:
  4335. case OMPC_to:
  4336. case OMPC_from:
  4337. case OMPC_use_device_ptr:
  4338. case OMPC_is_device_ptr:
  4339. continue;
  4340. case OMPC_allocator:
  4341. case OMPC_flush:
  4342. case OMPC_threadprivate:
  4343. case OMPC_uniform:
  4344. case OMPC_unknown:
  4345. case OMPC_unified_address:
  4346. case OMPC_unified_shared_memory:
  4347. case OMPC_reverse_offload:
  4348. case OMPC_dynamic_allocators:
  4349. case OMPC_atomic_default_mem_order:
  4350. case OMPC_device_type:
  4351. case OMPC_match:
  4352. llvm_unreachable("Unexpected clause");
  4353. }
  4354. for (Stmt *CC : C->children()) {
  4355. if (CC)
  4356. DSAChecker.Visit(CC);
  4357. }
  4358. }
  4359. for (auto &P : DSAChecker.getVarsWithInheritedDSA())
  4360. VarsWithInheritedDSA[P.getFirst()] = P.getSecond();
  4361. }
  4362. for (const auto &P : VarsWithInheritedDSA) {
  4363. if (P.getFirst()->isImplicit() || isa<OMPCapturedExprDecl>(P.getFirst()))
  4364. continue;
  4365. ErrorFound = true;
  4366. Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
  4367. << P.first << P.second->getSourceRange();
  4368. Diag(DSAStack->getDefaultDSALocation(), diag::note_omp_default_dsa_none);
  4369. }
  4370. if (!AllowedNameModifiers.empty())
  4371. ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
  4372. ErrorFound;
  4373. if (ErrorFound)
  4374. return StmtError();
  4375. if (!(Res.getAs<OMPExecutableDirective>()->isStandaloneDirective())) {
  4376. Res.getAs<OMPExecutableDirective>()
  4377. ->getStructuredBlock()
  4378. ->setIsOMPStructuredBlock(true);
  4379. }
  4380. if (!CurContext->isDependentContext() &&
  4381. isOpenMPTargetExecutionDirective(Kind) &&
  4382. !(DSAStack->hasRequiresDeclWithClause<OMPUnifiedSharedMemoryClause>() ||
  4383. DSAStack->hasRequiresDeclWithClause<OMPUnifiedAddressClause>() ||
  4384. DSAStack->hasRequiresDeclWithClause<OMPReverseOffloadClause>() ||
  4385. DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())) {
  4386. // Register target to DSA Stack.
  4387. DSAStack->addTargetDirLocation(StartLoc);
  4388. }
  4389. return Res;
  4390. }
  4391. Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
  4392. DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
  4393. ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
  4394. ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
  4395. ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
  4396. assert(Aligneds.size() == Alignments.size());
  4397. assert(Linears.size() == LinModifiers.size());
  4398. assert(Linears.size() == Steps.size());
  4399. if (!DG || DG.get().isNull())
  4400. return DeclGroupPtrTy();
  4401. const int SimdId = 0;
  4402. if (!DG.get().isSingleDecl()) {
  4403. Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd_variant)
  4404. << SimdId;
  4405. return DG;
  4406. }
  4407. Decl *ADecl = DG.get().getSingleDecl();
  4408. if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
  4409. ADecl = FTD->getTemplatedDecl();
  4410. auto *FD = dyn_cast<FunctionDecl>(ADecl);
  4411. if (!FD) {
  4412. Diag(ADecl->getLocation(), diag::err_omp_function_expected) << SimdId;
  4413. return DeclGroupPtrTy();
  4414. }
  4415. // OpenMP [2.8.2, declare simd construct, Description]
  4416. // The parameter of the simdlen clause must be a constant positive integer
  4417. // expression.
  4418. ExprResult SL;
  4419. if (Simdlen)
  4420. SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
  4421. // OpenMP [2.8.2, declare simd construct, Description]
  4422. // The special this pointer can be used as if was one of the arguments to the
  4423. // function in any of the linear, aligned, or uniform clauses.
  4424. // The uniform clause declares one or more arguments to have an invariant
  4425. // value for all concurrent invocations of the function in the execution of a
  4426. // single SIMD loop.
  4427. llvm::DenseMap<const Decl *, const Expr *> UniformedArgs;
  4428. const Expr *UniformedLinearThis = nullptr;
  4429. for (const Expr *E : Uniforms) {
  4430. E = E->IgnoreParenImpCasts();
  4431. if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
  4432. if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
  4433. if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
  4434. FD->getParamDecl(PVD->getFunctionScopeIndex())
  4435. ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
  4436. UniformedArgs.try_emplace(PVD->getCanonicalDecl(), E);
  4437. continue;
  4438. }
  4439. if (isa<CXXThisExpr>(E)) {
  4440. UniformedLinearThis = E;
  4441. continue;
  4442. }
  4443. Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
  4444. << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
  4445. }
  4446. // OpenMP [2.8.2, declare simd construct, Description]
  4447. // The aligned clause declares that the object to which each list item points
  4448. // is aligned to the number of bytes expressed in the optional parameter of
  4449. // the aligned clause.
  4450. // The special this pointer can be used as if was one of the arguments to the
  4451. // function in any of the linear, aligned, or uniform clauses.
  4452. // The type of list items appearing in the aligned clause must be array,
  4453. // pointer, reference to array, or reference to pointer.
  4454. llvm::DenseMap<const Decl *, const Expr *> AlignedArgs;
  4455. const Expr *AlignedThis = nullptr;
  4456. for (const Expr *E : Aligneds) {
  4457. E = E->IgnoreParenImpCasts();
  4458. if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
  4459. if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
  4460. const VarDecl *CanonPVD = PVD->getCanonicalDecl();
  4461. if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
  4462. FD->getParamDecl(PVD->getFunctionScopeIndex())
  4463. ->getCanonicalDecl() == CanonPVD) {
  4464. // OpenMP [2.8.1, simd construct, Restrictions]
  4465. // A list-item cannot appear in more than one aligned clause.
  4466. if (AlignedArgs.count(CanonPVD) > 0) {
  4467. Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
  4468. << 1 << E->getSourceRange();
  4469. Diag(AlignedArgs[CanonPVD]->getExprLoc(),
  4470. diag::note_omp_explicit_dsa)
  4471. << getOpenMPClauseName(OMPC_aligned);
  4472. continue;
  4473. }
  4474. AlignedArgs[CanonPVD] = E;
  4475. QualType QTy = PVD->getType()
  4476. .getNonReferenceType()
  4477. .getUnqualifiedType()
  4478. .getCanonicalType();
  4479. const Type *Ty = QTy.getTypePtrOrNull();
  4480. if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
  4481. Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
  4482. << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
  4483. Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
  4484. }
  4485. continue;
  4486. }
  4487. }
  4488. if (isa<CXXThisExpr>(E)) {
  4489. if (AlignedThis) {
  4490. Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
  4491. << 2 << E->getSourceRange();
  4492. Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
  4493. << getOpenMPClauseName(OMPC_aligned);
  4494. }
  4495. AlignedThis = E;
  4496. continue;
  4497. }
  4498. Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
  4499. << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
  4500. }
  4501. // The optional parameter of the aligned clause, alignment, must be a constant
  4502. // positive integer expression. If no optional parameter is specified,
  4503. // implementation-defined default alignments for SIMD instructions on the
  4504. // target platforms are assumed.
  4505. SmallVector<const Expr *, 4> NewAligns;
  4506. for (Expr *E : Alignments) {
  4507. ExprResult Align;
  4508. if (E)
  4509. Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
  4510. NewAligns.push_back(Align.get());
  4511. }
  4512. // OpenMP [2.8.2, declare simd construct, Description]
  4513. // The linear clause declares one or more list items to be private to a SIMD
  4514. // lane and to have a linear relationship with respect to the iteration space
  4515. // of a loop.
  4516. // The special this pointer can be used as if was one of the arguments to the
  4517. // function in any of the linear, aligned, or uniform clauses.
  4518. // When a linear-step expression is specified in a linear clause it must be
  4519. // either a constant integer expression or an integer-typed parameter that is
  4520. // specified in a uniform clause on the directive.
  4521. llvm::DenseMap<const Decl *, const Expr *> LinearArgs;
  4522. const bool IsUniformedThis = UniformedLinearThis != nullptr;
  4523. auto MI = LinModifiers.begin();
  4524. for (const Expr *E : Linears) {
  4525. auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
  4526. ++MI;
  4527. E = E->IgnoreParenImpCasts();
  4528. if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
  4529. if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
  4530. const VarDecl *CanonPVD = PVD->getCanonicalDecl();
  4531. if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
  4532. FD->getParamDecl(PVD->getFunctionScopeIndex())
  4533. ->getCanonicalDecl() == CanonPVD) {
  4534. // OpenMP [2.15.3.7, linear Clause, Restrictions]
  4535. // A list-item cannot appear in more than one linear clause.
  4536. if (LinearArgs.count(CanonPVD) > 0) {
  4537. Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
  4538. << getOpenMPClauseName(OMPC_linear)
  4539. << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
  4540. Diag(LinearArgs[CanonPVD]->getExprLoc(),
  4541. diag::note_omp_explicit_dsa)
  4542. << getOpenMPClauseName(OMPC_linear);
  4543. continue;
  4544. }
  4545. // Each argument can appear in at most one uniform or linear clause.
  4546. if (UniformedArgs.count(CanonPVD) > 0) {
  4547. Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
  4548. << getOpenMPClauseName(OMPC_linear)
  4549. << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
  4550. Diag(UniformedArgs[CanonPVD]->getExprLoc(),
  4551. diag::note_omp_explicit_dsa)
  4552. << getOpenMPClauseName(OMPC_uniform);
  4553. continue;
  4554. }
  4555. LinearArgs[CanonPVD] = E;
  4556. if (E->isValueDependent() || E->isTypeDependent() ||
  4557. E->isInstantiationDependent() ||
  4558. E->containsUnexpandedParameterPack())
  4559. continue;
  4560. (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
  4561. PVD->getOriginalType());
  4562. continue;
  4563. }
  4564. }
  4565. if (isa<CXXThisExpr>(E)) {
  4566. if (UniformedLinearThis) {
  4567. Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
  4568. << getOpenMPClauseName(OMPC_linear)
  4569. << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
  4570. << E->getSourceRange();
  4571. Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
  4572. << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
  4573. : OMPC_linear);
  4574. continue;
  4575. }
  4576. UniformedLinearThis = E;
  4577. if (E->isValueDependent() || E->isTypeDependent() ||
  4578. E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
  4579. continue;
  4580. (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
  4581. E->getType());
  4582. continue;
  4583. }
  4584. Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
  4585. << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
  4586. }
  4587. Expr *Step = nullptr;
  4588. Expr *NewStep = nullptr;
  4589. SmallVector<Expr *, 4> NewSteps;
  4590. for (Expr *E : Steps) {
  4591. // Skip the same step expression, it was checked already.
  4592. if (Step == E || !E) {
  4593. NewSteps.push_back(E ? NewStep : nullptr);
  4594. continue;
  4595. }
  4596. Step = E;
  4597. if (const auto *DRE = dyn_cast<DeclRefExpr>(Step))
  4598. if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
  4599. const VarDecl *CanonPVD = PVD->getCanonicalDecl();
  4600. if (UniformedArgs.count(CanonPVD) == 0) {
  4601. Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
  4602. << Step->getSourceRange();
  4603. } else if (E->isValueDependent() || E->isTypeDependent() ||
  4604. E->isInstantiationDependent() ||
  4605. E->containsUnexpandedParameterPack() ||
  4606. CanonPVD->getType()->hasIntegerRepresentation()) {
  4607. NewSteps.push_back(Step);
  4608. } else {
  4609. Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
  4610. << Step->getSourceRange();
  4611. }
  4612. continue;
  4613. }
  4614. NewStep = Step;
  4615. if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
  4616. !Step->isInstantiationDependent() &&
  4617. !Step->containsUnexpandedParameterPack()) {
  4618. NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
  4619. .get();
  4620. if (NewStep)
  4621. NewStep = VerifyIntegerConstantExpression(NewStep).get();
  4622. }
  4623. NewSteps.push_back(NewStep);
  4624. }
  4625. auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
  4626. Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
  4627. Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
  4628. const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
  4629. const_cast<Expr **>(Linears.data()), Linears.size(),
  4630. const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
  4631. NewSteps.data(), NewSteps.size(), SR);
  4632. ADecl->addAttr(NewAttr);
  4633. return DG;
  4634. }
  4635. Optional<std::pair<FunctionDecl *, Expr *>>
  4636. Sema::checkOpenMPDeclareVariantFunction(Sema::DeclGroupPtrTy DG,
  4637. Expr *VariantRef, SourceRange SR) {
  4638. if (!DG || DG.get().isNull())
  4639. return None;
  4640. const int VariantId = 1;
  4641. // Must be applied only to single decl.
  4642. if (!DG.get().isSingleDecl()) {
  4643. Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd_variant)
  4644. << VariantId << SR;
  4645. return None;
  4646. }
  4647. Decl *ADecl = DG.get().getSingleDecl();
  4648. if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
  4649. ADecl = FTD->getTemplatedDecl();
  4650. // Decl must be a function.
  4651. auto *FD = dyn_cast<FunctionDecl>(ADecl);
  4652. if (!FD) {
  4653. Diag(ADecl->getLocation(), diag::err_omp_function_expected)
  4654. << VariantId << SR;
  4655. return None;
  4656. }
  4657. auto &&HasMultiVersionAttributes = [](const FunctionDecl *FD) {
  4658. return FD->hasAttrs() &&
  4659. (FD->hasAttr<CPUDispatchAttr>() || FD->hasAttr<CPUSpecificAttr>() ||
  4660. FD->hasAttr<TargetAttr>());
  4661. };
  4662. // OpenMP is not compatible with CPU-specific attributes.
  4663. if (HasMultiVersionAttributes(FD)) {
  4664. Diag(FD->getLocation(), diag::err_omp_declare_variant_incompat_attributes)
  4665. << SR;
  4666. return None;
  4667. }
  4668. // Allow #pragma omp declare variant only if the function is not used.
  4669. if (FD->isUsed(false))
  4670. Diag(SR.getBegin(), diag::warn_omp_declare_variant_after_used)
  4671. << FD->getLocation();
  4672. // Check if the function was emitted already.
  4673. const FunctionDecl *Definition;
  4674. if (!FD->isThisDeclarationADefinition() && FD->isDefined(Definition) &&
  4675. (LangOpts.EmitAllDecls || Context.DeclMustBeEmitted(Definition)))
  4676. Diag(SR.getBegin(), diag::warn_omp_declare_variant_after_emitted)
  4677. << FD->getLocation();
  4678. // The VariantRef must point to function.
  4679. if (!VariantRef) {
  4680. Diag(SR.getBegin(), diag::err_omp_function_expected) << VariantId;
  4681. return None;
  4682. }
  4683. // Do not check templates, wait until instantiation.
  4684. if (VariantRef->isTypeDependent() || VariantRef->isValueDependent() ||
  4685. VariantRef->containsUnexpandedParameterPack() ||
  4686. VariantRef->isInstantiationDependent() || FD->isDependentContext())
  4687. return std::make_pair(FD, VariantRef);
  4688. // Convert VariantRef expression to the type of the original function to
  4689. // resolve possible conflicts.
  4690. ExprResult VariantRefCast;
  4691. if (LangOpts.CPlusPlus) {
  4692. QualType FnPtrType;
  4693. auto *Method = dyn_cast<CXXMethodDecl>(FD);
  4694. if (Method && !Method->isStatic()) {
  4695. const Type *ClassType =
  4696. Context.getTypeDeclType(Method->getParent()).getTypePtr();
  4697. FnPtrType = Context.getMemberPointerType(FD->getType(), ClassType);
  4698. ExprResult ER;
  4699. {
  4700. // Build adrr_of unary op to correctly handle type checks for member
  4701. // functions.
  4702. Sema::TentativeAnalysisScope Trap(*this);
  4703. ER = CreateBuiltinUnaryOp(VariantRef->getBeginLoc(), UO_AddrOf,
  4704. VariantRef);
  4705. }
  4706. if (!ER.isUsable()) {
  4707. Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
  4708. << VariantId << VariantRef->getSourceRange();
  4709. return None;
  4710. }
  4711. VariantRef = ER.get();
  4712. } else {
  4713. FnPtrType = Context.getPointerType(FD->getType());
  4714. }
  4715. ImplicitConversionSequence ICS =
  4716. TryImplicitConversion(VariantRef, FnPtrType.getUnqualifiedType(),
  4717. /*SuppressUserConversions=*/false,
  4718. /*AllowExplicit=*/false,
  4719. /*InOverloadResolution=*/false,
  4720. /*CStyle=*/false,
  4721. /*AllowObjCWritebackConversion=*/false);
  4722. if (ICS.isFailure()) {
  4723. Diag(VariantRef->getExprLoc(),
  4724. diag::err_omp_declare_variant_incompat_types)
  4725. << VariantRef->getType() << FnPtrType << VariantRef->getSourceRange();
  4726. return None;
  4727. }
  4728. VariantRefCast = PerformImplicitConversion(
  4729. VariantRef, FnPtrType.getUnqualifiedType(), AA_Converting);
  4730. if (!VariantRefCast.isUsable())
  4731. return None;
  4732. // Drop previously built artificial addr_of unary op for member functions.
  4733. if (Method && !Method->isStatic()) {
  4734. Expr *PossibleAddrOfVariantRef = VariantRefCast.get();
  4735. if (auto *UO = dyn_cast<UnaryOperator>(
  4736. PossibleAddrOfVariantRef->IgnoreImplicit()))
  4737. VariantRefCast = UO->getSubExpr();
  4738. }
  4739. } else {
  4740. VariantRefCast = VariantRef;
  4741. }
  4742. ExprResult ER = CheckPlaceholderExpr(VariantRefCast.get());
  4743. if (!ER.isUsable() ||
  4744. !ER.get()->IgnoreParenImpCasts()->getType()->isFunctionType()) {
  4745. Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
  4746. << VariantId << VariantRef->getSourceRange();
  4747. return None;
  4748. }
  4749. // The VariantRef must point to function.
  4750. auto *DRE = dyn_cast<DeclRefExpr>(ER.get()->IgnoreParenImpCasts());
  4751. if (!DRE) {
  4752. Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
  4753. << VariantId << VariantRef->getSourceRange();
  4754. return None;
  4755. }
  4756. auto *NewFD = dyn_cast_or_null<FunctionDecl>(DRE->getDecl());
  4757. if (!NewFD) {
  4758. Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
  4759. << VariantId << VariantRef->getSourceRange();
  4760. return None;
  4761. }
  4762. // Check if variant function is not marked with declare variant directive.
  4763. if (NewFD->hasAttrs() && NewFD->hasAttr<OMPDeclareVariantAttr>()) {
  4764. Diag(VariantRef->getExprLoc(),
  4765. diag::warn_omp_declare_variant_marked_as_declare_variant)
  4766. << VariantRef->getSourceRange();
  4767. SourceRange SR =
  4768. NewFD->specific_attr_begin<OMPDeclareVariantAttr>()->getRange();
  4769. Diag(SR.getBegin(), diag::note_omp_marked_declare_variant_here) << SR;
  4770. return None;
  4771. }
  4772. enum DoesntSupport {
  4773. VirtFuncs = 1,
  4774. Constructors = 3,
  4775. Destructors = 4,
  4776. DeletedFuncs = 5,
  4777. DefaultedFuncs = 6,
  4778. ConstexprFuncs = 7,
  4779. ConstevalFuncs = 8,
  4780. };
  4781. if (const auto *CXXFD = dyn_cast<CXXMethodDecl>(FD)) {
  4782. if (CXXFD->isVirtual()) {
  4783. Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
  4784. << VirtFuncs;
  4785. return None;
  4786. }
  4787. if (isa<CXXConstructorDecl>(FD)) {
  4788. Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
  4789. << Constructors;
  4790. return None;
  4791. }
  4792. if (isa<CXXDestructorDecl>(FD)) {
  4793. Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
  4794. << Destructors;
  4795. return None;
  4796. }
  4797. }
  4798. if (FD->isDeleted()) {
  4799. Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
  4800. << DeletedFuncs;
  4801. return None;
  4802. }
  4803. if (FD->isDefaulted()) {
  4804. Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
  4805. << DefaultedFuncs;
  4806. return None;
  4807. }
  4808. if (FD->isConstexpr()) {
  4809. Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
  4810. << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
  4811. return None;
  4812. }
  4813. // Check general compatibility.
  4814. if (areMultiversionVariantFunctionsCompatible(
  4815. FD, NewFD, PDiag(diag::err_omp_declare_variant_noproto),
  4816. PartialDiagnosticAt(
  4817. SR.getBegin(),
  4818. PDiag(diag::note_omp_declare_variant_specified_here) << SR),
  4819. PartialDiagnosticAt(
  4820. VariantRef->getExprLoc(),
  4821. PDiag(diag::err_omp_declare_variant_doesnt_support)),
  4822. PartialDiagnosticAt(VariantRef->getExprLoc(),
  4823. PDiag(diag::err_omp_declare_variant_diff)
  4824. << FD->getLocation()),
  4825. /*TemplatesSupported=*/true, /*ConstexprSupported=*/false,
  4826. /*CLinkageMayDiffer=*/true))
  4827. return None;
  4828. return std::make_pair(FD, cast<Expr>(DRE));
  4829. }
  4830. void Sema::ActOnOpenMPDeclareVariantDirective(
  4831. FunctionDecl *FD, Expr *VariantRef, SourceRange SR,
  4832. const Sema::OpenMPDeclareVariantCtsSelectorData &Data) {
  4833. if (Data.CtxSet == OMPDeclareVariantAttr::CtxSetUnknown ||
  4834. Data.Ctx == OMPDeclareVariantAttr::CtxUnknown)
  4835. return;
  4836. Expr *Score = nullptr;
  4837. OMPDeclareVariantAttr::ScoreType ST = OMPDeclareVariantAttr::ScoreUnknown;
  4838. if (Data.CtxScore.isUsable()) {
  4839. ST = OMPDeclareVariantAttr::ScoreSpecified;
  4840. Score = Data.CtxScore.get();
  4841. if (!Score->isTypeDependent() && !Score->isValueDependent() &&
  4842. !Score->isInstantiationDependent() &&
  4843. !Score->containsUnexpandedParameterPack()) {
  4844. llvm::APSInt Result;
  4845. ExprResult ICE = VerifyIntegerConstantExpression(Score, &Result);
  4846. if (ICE.isInvalid())
  4847. return;
  4848. }
  4849. }
  4850. auto *NewAttr = OMPDeclareVariantAttr::CreateImplicit(
  4851. Context, VariantRef, Score, Data.CtxSet, ST, Data.Ctx,
  4852. Data.ImplVendors.begin(), Data.ImplVendors.size(), SR);
  4853. FD->addAttr(NewAttr);
  4854. }
  4855. void Sema::markOpenMPDeclareVariantFuncsReferenced(SourceLocation Loc,
  4856. FunctionDecl *Func,
  4857. bool MightBeOdrUse) {
  4858. assert(LangOpts.OpenMP && "Expected OpenMP mode.");
  4859. if (!Func->isDependentContext() && Func->hasAttrs()) {
  4860. for (OMPDeclareVariantAttr *A :
  4861. Func->specific_attrs<OMPDeclareVariantAttr>()) {
  4862. // TODO: add checks for active OpenMP context where possible.
  4863. Expr *VariantRef = A->getVariantFuncRef();
  4864. auto *DRE = dyn_cast<DeclRefExpr>(VariantRef->IgnoreParenImpCasts());
  4865. auto *F = cast<FunctionDecl>(DRE->getDecl());
  4866. if (!F->isDefined() && F->isTemplateInstantiation())
  4867. InstantiateFunctionDefinition(Loc, F->getFirstDecl());
  4868. MarkFunctionReferenced(Loc, F, MightBeOdrUse);
  4869. }
  4870. }
  4871. }
  4872. StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
  4873. Stmt *AStmt,
  4874. SourceLocation StartLoc,
  4875. SourceLocation EndLoc) {
  4876. if (!AStmt)
  4877. return StmtError();
  4878. auto *CS = cast<CapturedStmt>(AStmt);
  4879. // 1.2.2 OpenMP Language Terminology
  4880. // Structured block - An executable statement with a single entry at the
  4881. // top and a single exit at the bottom.
  4882. // The point of exit cannot be a branch out of the structured block.
  4883. // longjmp() and throw() must not violate the entry/exit criteria.
  4884. CS->getCapturedDecl()->setNothrow();
  4885. setFunctionHasBranchProtectedScope();
  4886. return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
  4887. DSAStack->isCancelRegion());
  4888. }
  4889. namespace {
  4890. /// Iteration space of a single for loop.
  4891. struct LoopIterationSpace final {
  4892. /// True if the condition operator is the strict compare operator (<, > or
  4893. /// !=).
  4894. bool IsStrictCompare = false;
  4895. /// Condition of the loop.
  4896. Expr *PreCond = nullptr;
  4897. /// This expression calculates the number of iterations in the loop.
  4898. /// It is always possible to calculate it before starting the loop.
  4899. Expr *NumIterations = nullptr;
  4900. /// The loop counter variable.
  4901. Expr *CounterVar = nullptr;
  4902. /// Private loop counter variable.
  4903. Expr *PrivateCounterVar = nullptr;
  4904. /// This is initializer for the initial value of #CounterVar.
  4905. Expr *CounterInit = nullptr;
  4906. /// This is step for the #CounterVar used to generate its update:
  4907. /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
  4908. Expr *CounterStep = nullptr;
  4909. /// Should step be subtracted?
  4910. bool Subtract = false;
  4911. /// Source range of the loop init.
  4912. SourceRange InitSrcRange;
  4913. /// Source range of the loop condition.
  4914. SourceRange CondSrcRange;
  4915. /// Source range of the loop increment.
  4916. SourceRange IncSrcRange;
  4917. /// Minimum value that can have the loop control variable. Used to support
  4918. /// non-rectangular loops. Applied only for LCV with the non-iterator types,
  4919. /// since only such variables can be used in non-loop invariant expressions.
  4920. Expr *MinValue = nullptr;
  4921. /// Maximum value that can have the loop control variable. Used to support
  4922. /// non-rectangular loops. Applied only for LCV with the non-iterator type,
  4923. /// since only such variables can be used in non-loop invariant expressions.
  4924. Expr *MaxValue = nullptr;
  4925. /// true, if the lower bound depends on the outer loop control var.
  4926. bool IsNonRectangularLB = false;
  4927. /// true, if the upper bound depends on the outer loop control var.
  4928. bool IsNonRectangularUB = false;
  4929. /// Index of the loop this loop depends on and forms non-rectangular loop
  4930. /// nest.
  4931. unsigned LoopDependentIdx = 0;
  4932. /// Final condition for the non-rectangular loop nest support. It is used to
  4933. /// check that the number of iterations for this particular counter must be
  4934. /// finished.
  4935. Expr *FinalCondition = nullptr;
  4936. };
  4937. /// Helper class for checking canonical form of the OpenMP loops and
  4938. /// extracting iteration space of each loop in the loop nest, that will be used
  4939. /// for IR generation.
  4940. class OpenMPIterationSpaceChecker {
  4941. /// Reference to Sema.
  4942. Sema &SemaRef;
  4943. /// Data-sharing stack.
  4944. DSAStackTy &Stack;
  4945. /// A location for diagnostics (when there is no some better location).
  4946. SourceLocation DefaultLoc;
  4947. /// A location for diagnostics (when increment is not compatible).
  4948. SourceLocation ConditionLoc;
  4949. /// A source location for referring to loop init later.
  4950. SourceRange InitSrcRange;
  4951. /// A source location for referring to condition later.
  4952. SourceRange ConditionSrcRange;
  4953. /// A source location for referring to increment later.
  4954. SourceRange IncrementSrcRange;
  4955. /// Loop variable.
  4956. ValueDecl *LCDecl = nullptr;
  4957. /// Reference to loop variable.
  4958. Expr *LCRef = nullptr;
  4959. /// Lower bound (initializer for the var).
  4960. Expr *LB = nullptr;
  4961. /// Upper bound.
  4962. Expr *UB = nullptr;
  4963. /// Loop step (increment).
  4964. Expr *Step = nullptr;
  4965. /// This flag is true when condition is one of:
  4966. /// Var < UB
  4967. /// Var <= UB
  4968. /// UB > Var
  4969. /// UB >= Var
  4970. /// This will have no value when the condition is !=
  4971. llvm::Optional<bool> TestIsLessOp;
  4972. /// This flag is true when condition is strict ( < or > ).
  4973. bool TestIsStrictOp = false;
  4974. /// This flag is true when step is subtracted on each iteration.
  4975. bool SubtractStep = false;
  4976. /// The outer loop counter this loop depends on (if any).
  4977. const ValueDecl *DepDecl = nullptr;
  4978. /// Contains number of loop (starts from 1) on which loop counter init
  4979. /// expression of this loop depends on.
  4980. Optional<unsigned> InitDependOnLC;
  4981. /// Contains number of loop (starts from 1) on which loop counter condition
  4982. /// expression of this loop depends on.
  4983. Optional<unsigned> CondDependOnLC;
  4984. /// Checks if the provide statement depends on the loop counter.
  4985. Optional<unsigned> doesDependOnLoopCounter(const Stmt *S, bool IsInitializer);
  4986. /// Original condition required for checking of the exit condition for
  4987. /// non-rectangular loop.
  4988. Expr *Condition = nullptr;
  4989. public:
  4990. OpenMPIterationSpaceChecker(Sema &SemaRef, DSAStackTy &Stack,
  4991. SourceLocation DefaultLoc)
  4992. : SemaRef(SemaRef), Stack(Stack), DefaultLoc(DefaultLoc),
  4993. ConditionLoc(DefaultLoc) {}
  4994. /// Check init-expr for canonical loop form and save loop counter
  4995. /// variable - #Var and its initialization value - #LB.
  4996. bool checkAndSetInit(Stmt *S, bool EmitDiags = true);
  4997. /// Check test-expr for canonical form, save upper-bound (#UB), flags
  4998. /// for less/greater and for strict/non-strict comparison.
  4999. bool checkAndSetCond(Expr *S);
  5000. /// Check incr-expr for canonical loop form and return true if it
  5001. /// does not conform, otherwise save loop step (#Step).
  5002. bool checkAndSetInc(Expr *S);
  5003. /// Return the loop counter variable.
  5004. ValueDecl *getLoopDecl() const { return LCDecl; }
  5005. /// Return the reference expression to loop counter variable.
  5006. Expr *getLoopDeclRefExpr() const { return LCRef; }
  5007. /// Source range of the loop init.
  5008. SourceRange getInitSrcRange() const { return InitSrcRange; }
  5009. /// Source range of the loop condition.
  5010. SourceRange getConditionSrcRange() const { return ConditionSrcRange; }
  5011. /// Source range of the loop increment.
  5012. SourceRange getIncrementSrcRange() const { return IncrementSrcRange; }
  5013. /// True if the step should be subtracted.
  5014. bool shouldSubtractStep() const { return SubtractStep; }
  5015. /// True, if the compare operator is strict (<, > or !=).
  5016. bool isStrictTestOp() const { return TestIsStrictOp; }
  5017. /// Build the expression to calculate the number of iterations.
  5018. Expr *buildNumIterations(
  5019. Scope *S, ArrayRef<LoopIterationSpace> ResultIterSpaces, bool LimitedType,
  5020. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
  5021. /// Build the precondition expression for the loops.
  5022. Expr *
  5023. buildPreCond(Scope *S, Expr *Cond,
  5024. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
  5025. /// Build reference expression to the counter be used for codegen.
  5026. DeclRefExpr *
  5027. buildCounterVar(llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
  5028. DSAStackTy &DSA) const;
  5029. /// Build reference expression to the private counter be used for
  5030. /// codegen.
  5031. Expr *buildPrivateCounterVar() const;
  5032. /// Build initialization of the counter be used for codegen.
  5033. Expr *buildCounterInit() const;
  5034. /// Build step of the counter be used for codegen.
  5035. Expr *buildCounterStep() const;
  5036. /// Build loop data with counter value for depend clauses in ordered
  5037. /// directives.
  5038. Expr *
  5039. buildOrderedLoopData(Scope *S, Expr *Counter,
  5040. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
  5041. SourceLocation Loc, Expr *Inc = nullptr,
  5042. OverloadedOperatorKind OOK = OO_Amp);
  5043. /// Builds the minimum value for the loop counter.
  5044. std::pair<Expr *, Expr *> buildMinMaxValues(
  5045. Scope *S, llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
  5046. /// Builds final condition for the non-rectangular loops.
  5047. Expr *buildFinalCondition(Scope *S) const;
  5048. /// Return true if any expression is dependent.
  5049. bool dependent() const;
  5050. /// Returns true if the initializer forms non-rectangular loop.
  5051. bool doesInitDependOnLC() const { return InitDependOnLC.hasValue(); }
  5052. /// Returns true if the condition forms non-rectangular loop.
  5053. bool doesCondDependOnLC() const { return CondDependOnLC.hasValue(); }
  5054. /// Returns index of the loop we depend on (starting from 1), or 0 otherwise.
  5055. unsigned getLoopDependentIdx() const {
  5056. return InitDependOnLC.getValueOr(CondDependOnLC.getValueOr(0));
  5057. }
  5058. private:
  5059. /// Check the right-hand side of an assignment in the increment
  5060. /// expression.
  5061. bool checkAndSetIncRHS(Expr *RHS);
  5062. /// Helper to set loop counter variable and its initializer.
  5063. bool setLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB,
  5064. bool EmitDiags);
  5065. /// Helper to set upper bound.
  5066. bool setUB(Expr *NewUB, llvm::Optional<bool> LessOp, bool StrictOp,
  5067. SourceRange SR, SourceLocation SL);
  5068. /// Helper to set loop increment.
  5069. bool setStep(Expr *NewStep, bool Subtract);
  5070. };
  5071. bool OpenMPIterationSpaceChecker::dependent() const {
  5072. if (!LCDecl) {
  5073. assert(!LB && !UB && !Step);
  5074. return false;
  5075. }
  5076. return LCDecl->getType()->isDependentType() ||
  5077. (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
  5078. (Step && Step->isValueDependent());
  5079. }
  5080. bool OpenMPIterationSpaceChecker::setLCDeclAndLB(ValueDecl *NewLCDecl,
  5081. Expr *NewLCRefExpr,
  5082. Expr *NewLB, bool EmitDiags) {
  5083. // State consistency checking to ensure correct usage.
  5084. assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
  5085. UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
  5086. if (!NewLCDecl || !NewLB)
  5087. return true;
  5088. LCDecl = getCanonicalDecl(NewLCDecl);
  5089. LCRef = NewLCRefExpr;
  5090. if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
  5091. if (const CXXConstructorDecl *Ctor = CE->getConstructor())
  5092. if ((Ctor->isCopyOrMoveConstructor() ||
  5093. Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
  5094. CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
  5095. NewLB = CE->getArg(0)->IgnoreParenImpCasts();
  5096. LB = NewLB;
  5097. if (EmitDiags)
  5098. InitDependOnLC = doesDependOnLoopCounter(LB, /*IsInitializer=*/true);
  5099. return false;
  5100. }
  5101. bool OpenMPIterationSpaceChecker::setUB(Expr *NewUB,
  5102. llvm::Optional<bool> LessOp,
  5103. bool StrictOp, SourceRange SR,
  5104. SourceLocation SL) {
  5105. // State consistency checking to ensure correct usage.
  5106. assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
  5107. Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
  5108. if (!NewUB)
  5109. return true;
  5110. UB = NewUB;
  5111. if (LessOp)
  5112. TestIsLessOp = LessOp;
  5113. TestIsStrictOp = StrictOp;
  5114. ConditionSrcRange = SR;
  5115. ConditionLoc = SL;
  5116. CondDependOnLC = doesDependOnLoopCounter(UB, /*IsInitializer=*/false);
  5117. return false;
  5118. }
  5119. bool OpenMPIterationSpaceChecker::setStep(Expr *NewStep, bool Subtract) {
  5120. // State consistency checking to ensure correct usage.
  5121. assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
  5122. if (!NewStep)
  5123. return true;
  5124. if (!NewStep->isValueDependent()) {
  5125. // Check that the step is integer expression.
  5126. SourceLocation StepLoc = NewStep->getBeginLoc();
  5127. ExprResult Val = SemaRef.PerformOpenMPImplicitIntegerConversion(
  5128. StepLoc, getExprAsWritten(NewStep));
  5129. if (Val.isInvalid())
  5130. return true;
  5131. NewStep = Val.get();
  5132. // OpenMP [2.6, Canonical Loop Form, Restrictions]
  5133. // If test-expr is of form var relational-op b and relational-op is < or
  5134. // <= then incr-expr must cause var to increase on each iteration of the
  5135. // loop. If test-expr is of form var relational-op b and relational-op is
  5136. // > or >= then incr-expr must cause var to decrease on each iteration of
  5137. // the loop.
  5138. // If test-expr is of form b relational-op var and relational-op is < or
  5139. // <= then incr-expr must cause var to decrease on each iteration of the
  5140. // loop. If test-expr is of form b relational-op var and relational-op is
  5141. // > or >= then incr-expr must cause var to increase on each iteration of
  5142. // the loop.
  5143. llvm::APSInt Result;
  5144. bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
  5145. bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
  5146. bool IsConstNeg =
  5147. IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
  5148. bool IsConstPos =
  5149. IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
  5150. bool IsConstZero = IsConstant && !Result.getBoolValue();
  5151. // != with increment is treated as <; != with decrement is treated as >
  5152. if (!TestIsLessOp.hasValue())
  5153. TestIsLessOp = IsConstPos || (IsUnsigned && !Subtract);
  5154. if (UB && (IsConstZero ||
  5155. (TestIsLessOp.getValue() ?
  5156. (IsConstNeg || (IsUnsigned && Subtract)) :
  5157. (IsConstPos || (IsUnsigned && !Subtract))))) {
  5158. SemaRef.Diag(NewStep->getExprLoc(),
  5159. diag::err_omp_loop_incr_not_compatible)
  5160. << LCDecl << TestIsLessOp.getValue() << NewStep->getSourceRange();
  5161. SemaRef.Diag(ConditionLoc,
  5162. diag::note_omp_loop_cond_requres_compatible_incr)
  5163. << TestIsLessOp.getValue() << ConditionSrcRange;
  5164. return true;
  5165. }
  5166. if (TestIsLessOp.getValue() == Subtract) {
  5167. NewStep =
  5168. SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
  5169. .get();
  5170. Subtract = !Subtract;
  5171. }
  5172. }
  5173. Step = NewStep;
  5174. SubtractStep = Subtract;
  5175. return false;
  5176. }
  5177. namespace {
  5178. /// Checker for the non-rectangular loops. Checks if the initializer or
  5179. /// condition expression references loop counter variable.
  5180. class LoopCounterRefChecker final
  5181. : public ConstStmtVisitor<LoopCounterRefChecker, bool> {
  5182. Sema &SemaRef;
  5183. DSAStackTy &Stack;
  5184. const ValueDecl *CurLCDecl = nullptr;
  5185. const ValueDecl *DepDecl = nullptr;
  5186. const ValueDecl *PrevDepDecl = nullptr;
  5187. bool IsInitializer = true;
  5188. unsigned BaseLoopId = 0;
  5189. bool checkDecl(const Expr *E, const ValueDecl *VD) {
  5190. if (getCanonicalDecl(VD) == getCanonicalDecl(CurLCDecl)) {
  5191. SemaRef.Diag(E->getExprLoc(), diag::err_omp_stmt_depends_on_loop_counter)
  5192. << (IsInitializer ? 0 : 1);
  5193. return false;
  5194. }
  5195. const auto &&Data = Stack.isLoopControlVariable(VD);
  5196. // OpenMP, 2.9.1 Canonical Loop Form, Restrictions.
  5197. // The type of the loop iterator on which we depend may not have a random
  5198. // access iterator type.
  5199. if (Data.first && VD->getType()->isRecordType()) {
  5200. SmallString<128> Name;
  5201. llvm::raw_svector_ostream OS(Name);
  5202. VD->getNameForDiagnostic(OS, SemaRef.getPrintingPolicy(),
  5203. /*Qualified=*/true);
  5204. SemaRef.Diag(E->getExprLoc(),
  5205. diag::err_omp_wrong_dependency_iterator_type)
  5206. << OS.str();
  5207. SemaRef.Diag(VD->getLocation(), diag::note_previous_decl) << VD;
  5208. return false;
  5209. }
  5210. if (Data.first &&
  5211. (DepDecl || (PrevDepDecl &&
  5212. getCanonicalDecl(VD) != getCanonicalDecl(PrevDepDecl)))) {
  5213. if (!DepDecl && PrevDepDecl)
  5214. DepDecl = PrevDepDecl;
  5215. SmallString<128> Name;
  5216. llvm::raw_svector_ostream OS(Name);
  5217. DepDecl->getNameForDiagnostic(OS, SemaRef.getPrintingPolicy(),
  5218. /*Qualified=*/true);
  5219. SemaRef.Diag(E->getExprLoc(),
  5220. diag::err_omp_invariant_or_linear_dependency)
  5221. << OS.str();
  5222. return false;
  5223. }
  5224. if (Data.first) {
  5225. DepDecl = VD;
  5226. BaseLoopId = Data.first;
  5227. }
  5228. return Data.first;
  5229. }
  5230. public:
  5231. bool VisitDeclRefExpr(const DeclRefExpr *E) {
  5232. const ValueDecl *VD = E->getDecl();
  5233. if (isa<VarDecl>(VD))
  5234. return checkDecl(E, VD);
  5235. return false;
  5236. }
  5237. bool VisitMemberExpr(const MemberExpr *E) {
  5238. if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) {
  5239. const ValueDecl *VD = E->getMemberDecl();
  5240. if (isa<VarDecl>(VD) || isa<FieldDecl>(VD))
  5241. return checkDecl(E, VD);
  5242. }
  5243. return false;
  5244. }
  5245. bool VisitStmt(const Stmt *S) {
  5246. bool Res = false;
  5247. for (const Stmt *Child : S->children())
  5248. Res = (Child && Visit(Child)) || Res;
  5249. return Res;
  5250. }
  5251. explicit LoopCounterRefChecker(Sema &SemaRef, DSAStackTy &Stack,
  5252. const ValueDecl *CurLCDecl, bool IsInitializer,
  5253. const ValueDecl *PrevDepDecl = nullptr)
  5254. : SemaRef(SemaRef), Stack(Stack), CurLCDecl(CurLCDecl),
  5255. PrevDepDecl(PrevDepDecl), IsInitializer(IsInitializer) {}
  5256. unsigned getBaseLoopId() const {
  5257. assert(CurLCDecl && "Expected loop dependency.");
  5258. return BaseLoopId;
  5259. }
  5260. const ValueDecl *getDepDecl() const {
  5261. assert(CurLCDecl && "Expected loop dependency.");
  5262. return DepDecl;
  5263. }
  5264. };
  5265. } // namespace
  5266. Optional<unsigned>
  5267. OpenMPIterationSpaceChecker::doesDependOnLoopCounter(const Stmt *S,
  5268. bool IsInitializer) {
  5269. // Check for the non-rectangular loops.
  5270. LoopCounterRefChecker LoopStmtChecker(SemaRef, Stack, LCDecl, IsInitializer,
  5271. DepDecl);
  5272. if (LoopStmtChecker.Visit(S)) {
  5273. DepDecl = LoopStmtChecker.getDepDecl();
  5274. return LoopStmtChecker.getBaseLoopId();
  5275. }
  5276. return llvm::None;
  5277. }
  5278. bool OpenMPIterationSpaceChecker::checkAndSetInit(Stmt *S, bool EmitDiags) {
  5279. // Check init-expr for canonical loop form and save loop counter
  5280. // variable - #Var and its initialization value - #LB.
  5281. // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
  5282. // var = lb
  5283. // integer-type var = lb
  5284. // random-access-iterator-type var = lb
  5285. // pointer-type var = lb
  5286. //
  5287. if (!S) {
  5288. if (EmitDiags) {
  5289. SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
  5290. }
  5291. return true;
  5292. }
  5293. if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
  5294. if (!ExprTemp->cleanupsHaveSideEffects())
  5295. S = ExprTemp->getSubExpr();
  5296. InitSrcRange = S->getSourceRange();
  5297. if (Expr *E = dyn_cast<Expr>(S))
  5298. S = E->IgnoreParens();
  5299. if (auto *BO = dyn_cast<BinaryOperator>(S)) {
  5300. if (BO->getOpcode() == BO_Assign) {
  5301. Expr *LHS = BO->getLHS()->IgnoreParens();
  5302. if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
  5303. if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
  5304. if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
  5305. return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
  5306. EmitDiags);
  5307. return setLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS(), EmitDiags);
  5308. }
  5309. if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
  5310. if (ME->isArrow() &&
  5311. isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
  5312. return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
  5313. EmitDiags);
  5314. }
  5315. }
  5316. } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
  5317. if (DS->isSingleDecl()) {
  5318. if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
  5319. if (Var->hasInit() && !Var->getType()->isReferenceType()) {
  5320. // Accept non-canonical init form here but emit ext. warning.
  5321. if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
  5322. SemaRef.Diag(S->getBeginLoc(),
  5323. diag::ext_omp_loop_not_canonical_init)
  5324. << S->getSourceRange();
  5325. return setLCDeclAndLB(
  5326. Var,
  5327. buildDeclRefExpr(SemaRef, Var,
  5328. Var->getType().getNonReferenceType(),
  5329. DS->getBeginLoc()),
  5330. Var->getInit(), EmitDiags);
  5331. }
  5332. }
  5333. }
  5334. } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
  5335. if (CE->getOperator() == OO_Equal) {
  5336. Expr *LHS = CE->getArg(0);
  5337. if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
  5338. if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
  5339. if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
  5340. return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
  5341. EmitDiags);
  5342. return setLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1), EmitDiags);
  5343. }
  5344. if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
  5345. if (ME->isArrow() &&
  5346. isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
  5347. return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
  5348. EmitDiags);
  5349. }
  5350. }
  5351. }
  5352. if (dependent() || SemaRef.CurContext->isDependentContext())
  5353. return false;
  5354. if (EmitDiags) {
  5355. SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_init)
  5356. << S->getSourceRange();
  5357. }
  5358. return true;
  5359. }
  5360. /// Ignore parenthesizes, implicit casts, copy constructor and return the
  5361. /// variable (which may be the loop variable) if possible.
  5362. static const ValueDecl *getInitLCDecl(const Expr *E) {
  5363. if (!E)
  5364. return nullptr;
  5365. E = getExprAsWritten(E);
  5366. if (const auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
  5367. if (const CXXConstructorDecl *Ctor = CE->getConstructor())
  5368. if ((Ctor->isCopyOrMoveConstructor() ||
  5369. Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
  5370. CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
  5371. E = CE->getArg(0)->IgnoreParenImpCasts();
  5372. if (const auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
  5373. if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
  5374. return getCanonicalDecl(VD);
  5375. }
  5376. if (const auto *ME = dyn_cast_or_null<MemberExpr>(E))
  5377. if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
  5378. return getCanonicalDecl(ME->getMemberDecl());
  5379. return nullptr;
  5380. }
  5381. bool OpenMPIterationSpaceChecker::checkAndSetCond(Expr *S) {
  5382. // Check test-expr for canonical form, save upper-bound UB, flags for
  5383. // less/greater and for strict/non-strict comparison.
  5384. // OpenMP [2.9] Canonical loop form. Test-expr may be one of the following:
  5385. // var relational-op b
  5386. // b relational-op var
  5387. //
  5388. bool IneqCondIsCanonical = SemaRef.getLangOpts().OpenMP >= 50;
  5389. if (!S) {
  5390. SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond)
  5391. << (IneqCondIsCanonical ? 1 : 0) << LCDecl;
  5392. return true;
  5393. }
  5394. Condition = S;
  5395. S = getExprAsWritten(S);
  5396. SourceLocation CondLoc = S->getBeginLoc();
  5397. if (auto *BO = dyn_cast<BinaryOperator>(S)) {
  5398. if (BO->isRelationalOp()) {
  5399. if (getInitLCDecl(BO->getLHS()) == LCDecl)
  5400. return setUB(BO->getRHS(),
  5401. (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
  5402. (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
  5403. BO->getSourceRange(), BO->getOperatorLoc());
  5404. if (getInitLCDecl(BO->getRHS()) == LCDecl)
  5405. return setUB(BO->getLHS(),
  5406. (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
  5407. (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
  5408. BO->getSourceRange(), BO->getOperatorLoc());
  5409. } else if (IneqCondIsCanonical && BO->getOpcode() == BO_NE)
  5410. return setUB(
  5411. getInitLCDecl(BO->getLHS()) == LCDecl ? BO->getRHS() : BO->getLHS(),
  5412. /*LessOp=*/llvm::None,
  5413. /*StrictOp=*/true, BO->getSourceRange(), BO->getOperatorLoc());
  5414. } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
  5415. if (CE->getNumArgs() == 2) {
  5416. auto Op = CE->getOperator();
  5417. switch (Op) {
  5418. case OO_Greater:
  5419. case OO_GreaterEqual:
  5420. case OO_Less:
  5421. case OO_LessEqual:
  5422. if (getInitLCDecl(CE->getArg(0)) == LCDecl)
  5423. return setUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
  5424. Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
  5425. CE->getOperatorLoc());
  5426. if (getInitLCDecl(CE->getArg(1)) == LCDecl)
  5427. return setUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
  5428. Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
  5429. CE->getOperatorLoc());
  5430. break;
  5431. case OO_ExclaimEqual:
  5432. if (IneqCondIsCanonical)
  5433. return setUB(getInitLCDecl(CE->getArg(0)) == LCDecl ? CE->getArg(1)
  5434. : CE->getArg(0),
  5435. /*LessOp=*/llvm::None,
  5436. /*StrictOp=*/true, CE->getSourceRange(),
  5437. CE->getOperatorLoc());
  5438. break;
  5439. default:
  5440. break;
  5441. }
  5442. }
  5443. }
  5444. if (dependent() || SemaRef.CurContext->isDependentContext())
  5445. return false;
  5446. SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
  5447. << (IneqCondIsCanonical ? 1 : 0) << S->getSourceRange() << LCDecl;
  5448. return true;
  5449. }
  5450. bool OpenMPIterationSpaceChecker::checkAndSetIncRHS(Expr *RHS) {
  5451. // RHS of canonical loop form increment can be:
  5452. // var + incr
  5453. // incr + var
  5454. // var - incr
  5455. //
  5456. RHS = RHS->IgnoreParenImpCasts();
  5457. if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
  5458. if (BO->isAdditiveOp()) {
  5459. bool IsAdd = BO->getOpcode() == BO_Add;
  5460. if (getInitLCDecl(BO->getLHS()) == LCDecl)
  5461. return setStep(BO->getRHS(), !IsAdd);
  5462. if (IsAdd && getInitLCDecl(BO->getRHS()) == LCDecl)
  5463. return setStep(BO->getLHS(), /*Subtract=*/false);
  5464. }
  5465. } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
  5466. bool IsAdd = CE->getOperator() == OO_Plus;
  5467. if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
  5468. if (getInitLCDecl(CE->getArg(0)) == LCDecl)
  5469. return setStep(CE->getArg(1), !IsAdd);
  5470. if (IsAdd && getInitLCDecl(CE->getArg(1)) == LCDecl)
  5471. return setStep(CE->getArg(0), /*Subtract=*/false);
  5472. }
  5473. }
  5474. if (dependent() || SemaRef.CurContext->isDependentContext())
  5475. return false;
  5476. SemaRef.Diag(RHS->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
  5477. << RHS->getSourceRange() << LCDecl;
  5478. return true;
  5479. }
  5480. bool OpenMPIterationSpaceChecker::checkAndSetInc(Expr *S) {
  5481. // Check incr-expr for canonical loop form and return true if it
  5482. // does not conform.
  5483. // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
  5484. // ++var
  5485. // var++
  5486. // --var
  5487. // var--
  5488. // var += incr
  5489. // var -= incr
  5490. // var = var + incr
  5491. // var = incr + var
  5492. // var = var - incr
  5493. //
  5494. if (!S) {
  5495. SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
  5496. return true;
  5497. }
  5498. if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
  5499. if (!ExprTemp->cleanupsHaveSideEffects())
  5500. S = ExprTemp->getSubExpr();
  5501. IncrementSrcRange = S->getSourceRange();
  5502. S = S->IgnoreParens();
  5503. if (auto *UO = dyn_cast<UnaryOperator>(S)) {
  5504. if (UO->isIncrementDecrementOp() &&
  5505. getInitLCDecl(UO->getSubExpr()) == LCDecl)
  5506. return setStep(SemaRef
  5507. .ActOnIntegerConstant(UO->getBeginLoc(),
  5508. (UO->isDecrementOp() ? -1 : 1))
  5509. .get(),
  5510. /*Subtract=*/false);
  5511. } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
  5512. switch (BO->getOpcode()) {
  5513. case BO_AddAssign:
  5514. case BO_SubAssign:
  5515. if (getInitLCDecl(BO->getLHS()) == LCDecl)
  5516. return setStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
  5517. break;
  5518. case BO_Assign:
  5519. if (getInitLCDecl(BO->getLHS()) == LCDecl)
  5520. return checkAndSetIncRHS(BO->getRHS());
  5521. break;
  5522. default:
  5523. break;
  5524. }
  5525. } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
  5526. switch (CE->getOperator()) {
  5527. case OO_PlusPlus:
  5528. case OO_MinusMinus:
  5529. if (getInitLCDecl(CE->getArg(0)) == LCDecl)
  5530. return setStep(SemaRef
  5531. .ActOnIntegerConstant(
  5532. CE->getBeginLoc(),
  5533. ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
  5534. .get(),
  5535. /*Subtract=*/false);
  5536. break;
  5537. case OO_PlusEqual:
  5538. case OO_MinusEqual:
  5539. if (getInitLCDecl(CE->getArg(0)) == LCDecl)
  5540. return setStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
  5541. break;
  5542. case OO_Equal:
  5543. if (getInitLCDecl(CE->getArg(0)) == LCDecl)
  5544. return checkAndSetIncRHS(CE->getArg(1));
  5545. break;
  5546. default:
  5547. break;
  5548. }
  5549. }
  5550. if (dependent() || SemaRef.CurContext->isDependentContext())
  5551. return false;
  5552. SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
  5553. << S->getSourceRange() << LCDecl;
  5554. return true;
  5555. }
  5556. static ExprResult
  5557. tryBuildCapture(Sema &SemaRef, Expr *Capture,
  5558. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
  5559. if (SemaRef.CurContext->isDependentContext())
  5560. return ExprResult(Capture);
  5561. if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
  5562. return SemaRef.PerformImplicitConversion(
  5563. Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
  5564. /*AllowExplicit=*/true);
  5565. auto I = Captures.find(Capture);
  5566. if (I != Captures.end())
  5567. return buildCapture(SemaRef, Capture, I->second);
  5568. DeclRefExpr *Ref = nullptr;
  5569. ExprResult Res = buildCapture(SemaRef, Capture, Ref);
  5570. Captures[Capture] = Ref;
  5571. return Res;
  5572. }
  5573. /// Build the expression to calculate the number of iterations.
  5574. Expr *OpenMPIterationSpaceChecker::buildNumIterations(
  5575. Scope *S, ArrayRef<LoopIterationSpace> ResultIterSpaces, bool LimitedType,
  5576. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
  5577. ExprResult Diff;
  5578. QualType VarType = LCDecl->getType().getNonReferenceType();
  5579. if (VarType->isIntegerType() || VarType->isPointerType() ||
  5580. SemaRef.getLangOpts().CPlusPlus) {
  5581. Expr *LBVal = LB;
  5582. Expr *UBVal = UB;
  5583. // LB = TestIsLessOp.getValue() ? min(LB(MinVal), LB(MaxVal)) :
  5584. // max(LB(MinVal), LB(MaxVal))
  5585. if (InitDependOnLC) {
  5586. const LoopIterationSpace &IS =
  5587. ResultIterSpaces[ResultIterSpaces.size() - 1 -
  5588. InitDependOnLC.getValueOr(
  5589. CondDependOnLC.getValueOr(0))];
  5590. if (!IS.MinValue || !IS.MaxValue)
  5591. return nullptr;
  5592. // OuterVar = Min
  5593. ExprResult MinValue =
  5594. SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MinValue);
  5595. if (!MinValue.isUsable())
  5596. return nullptr;
  5597. ExprResult LBMinVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
  5598. IS.CounterVar, MinValue.get());
  5599. if (!LBMinVal.isUsable())
  5600. return nullptr;
  5601. // OuterVar = Min, LBVal
  5602. LBMinVal =
  5603. SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, LBMinVal.get(), LBVal);
  5604. if (!LBMinVal.isUsable())
  5605. return nullptr;
  5606. // (OuterVar = Min, LBVal)
  5607. LBMinVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, LBMinVal.get());
  5608. if (!LBMinVal.isUsable())
  5609. return nullptr;
  5610. // OuterVar = Max
  5611. ExprResult MaxValue =
  5612. SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MaxValue);
  5613. if (!MaxValue.isUsable())
  5614. return nullptr;
  5615. ExprResult LBMaxVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
  5616. IS.CounterVar, MaxValue.get());
  5617. if (!LBMaxVal.isUsable())
  5618. return nullptr;
  5619. // OuterVar = Max, LBVal
  5620. LBMaxVal =
  5621. SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, LBMaxVal.get(), LBVal);
  5622. if (!LBMaxVal.isUsable())
  5623. return nullptr;
  5624. // (OuterVar = Max, LBVal)
  5625. LBMaxVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, LBMaxVal.get());
  5626. if (!LBMaxVal.isUsable())
  5627. return nullptr;
  5628. Expr *LBMin = tryBuildCapture(SemaRef, LBMinVal.get(), Captures).get();
  5629. Expr *LBMax = tryBuildCapture(SemaRef, LBMaxVal.get(), Captures).get();
  5630. if (!LBMin || !LBMax)
  5631. return nullptr;
  5632. // LB(MinVal) < LB(MaxVal)
  5633. ExprResult MinLessMaxRes =
  5634. SemaRef.BuildBinOp(S, DefaultLoc, BO_LT, LBMin, LBMax);
  5635. if (!MinLessMaxRes.isUsable())
  5636. return nullptr;
  5637. Expr *MinLessMax =
  5638. tryBuildCapture(SemaRef, MinLessMaxRes.get(), Captures).get();
  5639. if (!MinLessMax)
  5640. return nullptr;
  5641. if (TestIsLessOp.getValue()) {
  5642. // LB(MinVal) < LB(MaxVal) ? LB(MinVal) : LB(MaxVal) - min(LB(MinVal),
  5643. // LB(MaxVal))
  5644. ExprResult MinLB = SemaRef.ActOnConditionalOp(DefaultLoc, DefaultLoc,
  5645. MinLessMax, LBMin, LBMax);
  5646. if (!MinLB.isUsable())
  5647. return nullptr;
  5648. LBVal = MinLB.get();
  5649. } else {
  5650. // LB(MinVal) < LB(MaxVal) ? LB(MaxVal) : LB(MinVal) - max(LB(MinVal),
  5651. // LB(MaxVal))
  5652. ExprResult MaxLB = SemaRef.ActOnConditionalOp(DefaultLoc, DefaultLoc,
  5653. MinLessMax, LBMax, LBMin);
  5654. if (!MaxLB.isUsable())
  5655. return nullptr;
  5656. LBVal = MaxLB.get();
  5657. }
  5658. }
  5659. // UB = TestIsLessOp.getValue() ? max(UB(MinVal), UB(MaxVal)) :
  5660. // min(UB(MinVal), UB(MaxVal))
  5661. if (CondDependOnLC) {
  5662. const LoopIterationSpace &IS =
  5663. ResultIterSpaces[ResultIterSpaces.size() - 1 -
  5664. InitDependOnLC.getValueOr(
  5665. CondDependOnLC.getValueOr(0))];
  5666. if (!IS.MinValue || !IS.MaxValue)
  5667. return nullptr;
  5668. // OuterVar = Min
  5669. ExprResult MinValue =
  5670. SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MinValue);
  5671. if (!MinValue.isUsable())
  5672. return nullptr;
  5673. ExprResult UBMinVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
  5674. IS.CounterVar, MinValue.get());
  5675. if (!UBMinVal.isUsable())
  5676. return nullptr;
  5677. // OuterVar = Min, UBVal
  5678. UBMinVal =
  5679. SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, UBMinVal.get(), UBVal);
  5680. if (!UBMinVal.isUsable())
  5681. return nullptr;
  5682. // (OuterVar = Min, UBVal)
  5683. UBMinVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, UBMinVal.get());
  5684. if (!UBMinVal.isUsable())
  5685. return nullptr;
  5686. // OuterVar = Max
  5687. ExprResult MaxValue =
  5688. SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MaxValue);
  5689. if (!MaxValue.isUsable())
  5690. return nullptr;
  5691. ExprResult UBMaxVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
  5692. IS.CounterVar, MaxValue.get());
  5693. if (!UBMaxVal.isUsable())
  5694. return nullptr;
  5695. // OuterVar = Max, UBVal
  5696. UBMaxVal =
  5697. SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, UBMaxVal.get(), UBVal);
  5698. if (!UBMaxVal.isUsable())
  5699. return nullptr;
  5700. // (OuterVar = Max, UBVal)
  5701. UBMaxVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, UBMaxVal.get());
  5702. if (!UBMaxVal.isUsable())
  5703. return nullptr;
  5704. Expr *UBMin = tryBuildCapture(SemaRef, UBMinVal.get(), Captures).get();
  5705. Expr *UBMax = tryBuildCapture(SemaRef, UBMaxVal.get(), Captures).get();
  5706. if (!UBMin || !UBMax)
  5707. return nullptr;
  5708. // UB(MinVal) > UB(MaxVal)
  5709. ExprResult MinGreaterMaxRes =
  5710. SemaRef.BuildBinOp(S, DefaultLoc, BO_GT, UBMin, UBMax);
  5711. if (!MinGreaterMaxRes.isUsable())
  5712. return nullptr;
  5713. Expr *MinGreaterMax =
  5714. tryBuildCapture(SemaRef, MinGreaterMaxRes.get(), Captures).get();
  5715. if (!MinGreaterMax)
  5716. return nullptr;
  5717. if (TestIsLessOp.getValue()) {
  5718. // UB(MinVal) > UB(MaxVal) ? UB(MinVal) : UB(MaxVal) - max(UB(MinVal),
  5719. // UB(MaxVal))
  5720. ExprResult MaxUB = SemaRef.ActOnConditionalOp(
  5721. DefaultLoc, DefaultLoc, MinGreaterMax, UBMin, UBMax);
  5722. if (!MaxUB.isUsable())
  5723. return nullptr;
  5724. UBVal = MaxUB.get();
  5725. } else {
  5726. // UB(MinVal) > UB(MaxVal) ? UB(MaxVal) : UB(MinVal) - min(UB(MinVal),
  5727. // UB(MaxVal))
  5728. ExprResult MinUB = SemaRef.ActOnConditionalOp(
  5729. DefaultLoc, DefaultLoc, MinGreaterMax, UBMax, UBMin);
  5730. if (!MinUB.isUsable())
  5731. return nullptr;
  5732. UBVal = MinUB.get();
  5733. }
  5734. }
  5735. // Upper - Lower
  5736. Expr *UBExpr = TestIsLessOp.getValue() ? UBVal : LBVal;
  5737. Expr *LBExpr = TestIsLessOp.getValue() ? LBVal : UBVal;
  5738. Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
  5739. Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
  5740. if (!Upper || !Lower)
  5741. return nullptr;
  5742. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
  5743. if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
  5744. // BuildBinOp already emitted error, this one is to point user to upper
  5745. // and lower bound, and to tell what is passed to 'operator-'.
  5746. SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx)
  5747. << Upper->getSourceRange() << Lower->getSourceRange();
  5748. return nullptr;
  5749. }
  5750. }
  5751. if (!Diff.isUsable())
  5752. return nullptr;
  5753. // Upper - Lower [- 1]
  5754. if (TestIsStrictOp)
  5755. Diff = SemaRef.BuildBinOp(
  5756. S, DefaultLoc, BO_Sub, Diff.get(),
  5757. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
  5758. if (!Diff.isUsable())
  5759. return nullptr;
  5760. // Upper - Lower [- 1] + Step
  5761. ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
  5762. if (!NewStep.isUsable())
  5763. return nullptr;
  5764. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
  5765. if (!Diff.isUsable())
  5766. return nullptr;
  5767. // Parentheses (for dumping/debugging purposes only).
  5768. Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
  5769. if (!Diff.isUsable())
  5770. return nullptr;
  5771. // (Upper - Lower [- 1] + Step) / Step
  5772. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
  5773. if (!Diff.isUsable())
  5774. return nullptr;
  5775. // OpenMP runtime requires 32-bit or 64-bit loop variables.
  5776. QualType Type = Diff.get()->getType();
  5777. ASTContext &C = SemaRef.Context;
  5778. bool UseVarType = VarType->hasIntegerRepresentation() &&
  5779. C.getTypeSize(Type) > C.getTypeSize(VarType);
  5780. if (!Type->isIntegerType() || UseVarType) {
  5781. unsigned NewSize =
  5782. UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
  5783. bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
  5784. : Type->hasSignedIntegerRepresentation();
  5785. Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
  5786. if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
  5787. Diff = SemaRef.PerformImplicitConversion(
  5788. Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
  5789. if (!Diff.isUsable())
  5790. return nullptr;
  5791. }
  5792. }
  5793. if (LimitedType) {
  5794. unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
  5795. if (NewSize != C.getTypeSize(Type)) {
  5796. if (NewSize < C.getTypeSize(Type)) {
  5797. assert(NewSize == 64 && "incorrect loop var size");
  5798. SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
  5799. << InitSrcRange << ConditionSrcRange;
  5800. }
  5801. QualType NewType = C.getIntTypeForBitwidth(
  5802. NewSize, Type->hasSignedIntegerRepresentation() ||
  5803. C.getTypeSize(Type) < NewSize);
  5804. if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
  5805. Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
  5806. Sema::AA_Converting, true);
  5807. if (!Diff.isUsable())
  5808. return nullptr;
  5809. }
  5810. }
  5811. }
  5812. return Diff.get();
  5813. }
  5814. std::pair<Expr *, Expr *> OpenMPIterationSpaceChecker::buildMinMaxValues(
  5815. Scope *S, llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
  5816. // Do not build for iterators, they cannot be used in non-rectangular loop
  5817. // nests.
  5818. if (LCDecl->getType()->isRecordType())
  5819. return std::make_pair(nullptr, nullptr);
  5820. // If we subtract, the min is in the condition, otherwise the min is in the
  5821. // init value.
  5822. Expr *MinExpr = nullptr;
  5823. Expr *MaxExpr = nullptr;
  5824. Expr *LBExpr = TestIsLessOp.getValue() ? LB : UB;
  5825. Expr *UBExpr = TestIsLessOp.getValue() ? UB : LB;
  5826. bool LBNonRect = TestIsLessOp.getValue() ? InitDependOnLC.hasValue()
  5827. : CondDependOnLC.hasValue();
  5828. bool UBNonRect = TestIsLessOp.getValue() ? CondDependOnLC.hasValue()
  5829. : InitDependOnLC.hasValue();
  5830. Expr *Lower =
  5831. LBNonRect ? LBExpr : tryBuildCapture(SemaRef, LBExpr, Captures).get();
  5832. Expr *Upper =
  5833. UBNonRect ? UBExpr : tryBuildCapture(SemaRef, UBExpr, Captures).get();
  5834. if (!Upper || !Lower)
  5835. return std::make_pair(nullptr, nullptr);
  5836. if (TestIsLessOp.getValue())
  5837. MinExpr = Lower;
  5838. else
  5839. MaxExpr = Upper;
  5840. // Build minimum/maximum value based on number of iterations.
  5841. ExprResult Diff;
  5842. QualType VarType = LCDecl->getType().getNonReferenceType();
  5843. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
  5844. if (!Diff.isUsable())
  5845. return std::make_pair(nullptr, nullptr);
  5846. // Upper - Lower [- 1]
  5847. if (TestIsStrictOp)
  5848. Diff = SemaRef.BuildBinOp(
  5849. S, DefaultLoc, BO_Sub, Diff.get(),
  5850. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
  5851. if (!Diff.isUsable())
  5852. return std::make_pair(nullptr, nullptr);
  5853. // Upper - Lower [- 1] + Step
  5854. ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
  5855. if (!NewStep.isUsable())
  5856. return std::make_pair(nullptr, nullptr);
  5857. // Parentheses (for dumping/debugging purposes only).
  5858. Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
  5859. if (!Diff.isUsable())
  5860. return std::make_pair(nullptr, nullptr);
  5861. // (Upper - Lower [- 1]) / Step
  5862. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
  5863. if (!Diff.isUsable())
  5864. return std::make_pair(nullptr, nullptr);
  5865. // ((Upper - Lower [- 1]) / Step) * Step
  5866. // Parentheses (for dumping/debugging purposes only).
  5867. Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
  5868. if (!Diff.isUsable())
  5869. return std::make_pair(nullptr, nullptr);
  5870. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Mul, Diff.get(), NewStep.get());
  5871. if (!Diff.isUsable())
  5872. return std::make_pair(nullptr, nullptr);
  5873. // Convert to the original type or ptrdiff_t, if original type is pointer.
  5874. if (!VarType->isAnyPointerType() &&
  5875. !SemaRef.Context.hasSameType(Diff.get()->getType(), VarType)) {
  5876. Diff = SemaRef.PerformImplicitConversion(
  5877. Diff.get(), VarType, Sema::AA_Converting, /*AllowExplicit=*/true);
  5878. } else if (VarType->isAnyPointerType() &&
  5879. !SemaRef.Context.hasSameType(
  5880. Diff.get()->getType(),
  5881. SemaRef.Context.getUnsignedPointerDiffType())) {
  5882. Diff = SemaRef.PerformImplicitConversion(
  5883. Diff.get(), SemaRef.Context.getUnsignedPointerDiffType(),
  5884. Sema::AA_Converting, /*AllowExplicit=*/true);
  5885. }
  5886. if (!Diff.isUsable())
  5887. return std::make_pair(nullptr, nullptr);
  5888. // Parentheses (for dumping/debugging purposes only).
  5889. Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
  5890. if (!Diff.isUsable())
  5891. return std::make_pair(nullptr, nullptr);
  5892. if (TestIsLessOp.getValue()) {
  5893. // MinExpr = Lower;
  5894. // MaxExpr = Lower + (((Upper - Lower [- 1]) / Step) * Step)
  5895. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Lower, Diff.get());
  5896. if (!Diff.isUsable())
  5897. return std::make_pair(nullptr, nullptr);
  5898. Diff = SemaRef.ActOnFinishFullExpr(Diff.get(), /*DiscardedValue*/ false);
  5899. if (!Diff.isUsable())
  5900. return std::make_pair(nullptr, nullptr);
  5901. MaxExpr = Diff.get();
  5902. } else {
  5903. // MaxExpr = Upper;
  5904. // MinExpr = Upper - (((Upper - Lower [- 1]) / Step) * Step)
  5905. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Diff.get());
  5906. if (!Diff.isUsable())
  5907. return std::make_pair(nullptr, nullptr);
  5908. Diff = SemaRef.ActOnFinishFullExpr(Diff.get(), /*DiscardedValue*/ false);
  5909. if (!Diff.isUsable())
  5910. return std::make_pair(nullptr, nullptr);
  5911. MinExpr = Diff.get();
  5912. }
  5913. return std::make_pair(MinExpr, MaxExpr);
  5914. }
  5915. Expr *OpenMPIterationSpaceChecker::buildFinalCondition(Scope *S) const {
  5916. if (InitDependOnLC || CondDependOnLC)
  5917. return Condition;
  5918. return nullptr;
  5919. }
  5920. Expr *OpenMPIterationSpaceChecker::buildPreCond(
  5921. Scope *S, Expr *Cond,
  5922. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
  5923. // Do not build a precondition when the condition/initialization is dependent
  5924. // to prevent pessimistic early loop exit.
  5925. // TODO: this can be improved by calculating min/max values but not sure that
  5926. // it will be very effective.
  5927. if (CondDependOnLC || InitDependOnLC)
  5928. return SemaRef.PerformImplicitConversion(
  5929. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get(),
  5930. SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
  5931. /*AllowExplicit=*/true).get();
  5932. // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
  5933. Sema::TentativeAnalysisScope Trap(SemaRef);
  5934. ExprResult NewLB = tryBuildCapture(SemaRef, LB, Captures);
  5935. ExprResult NewUB = tryBuildCapture(SemaRef, UB, Captures);
  5936. if (!NewLB.isUsable() || !NewUB.isUsable())
  5937. return nullptr;
  5938. ExprResult CondExpr =
  5939. SemaRef.BuildBinOp(S, DefaultLoc,
  5940. TestIsLessOp.getValue() ?
  5941. (TestIsStrictOp ? BO_LT : BO_LE) :
  5942. (TestIsStrictOp ? BO_GT : BO_GE),
  5943. NewLB.get(), NewUB.get());
  5944. if (CondExpr.isUsable()) {
  5945. if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
  5946. SemaRef.Context.BoolTy))
  5947. CondExpr = SemaRef.PerformImplicitConversion(
  5948. CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
  5949. /*AllowExplicit=*/true);
  5950. }
  5951. // Otherwise use original loop condition and evaluate it in runtime.
  5952. return CondExpr.isUsable() ? CondExpr.get() : Cond;
  5953. }
  5954. /// Build reference expression to the counter be used for codegen.
  5955. DeclRefExpr *OpenMPIterationSpaceChecker::buildCounterVar(
  5956. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
  5957. DSAStackTy &DSA) const {
  5958. auto *VD = dyn_cast<VarDecl>(LCDecl);
  5959. if (!VD) {
  5960. VD = SemaRef.isOpenMPCapturedDecl(LCDecl);
  5961. DeclRefExpr *Ref = buildDeclRefExpr(
  5962. SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
  5963. const DSAStackTy::DSAVarData Data =
  5964. DSA.getTopDSA(LCDecl, /*FromParent=*/false);
  5965. // If the loop control decl is explicitly marked as private, do not mark it
  5966. // as captured again.
  5967. if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
  5968. Captures.insert(std::make_pair(LCRef, Ref));
  5969. return Ref;
  5970. }
  5971. return cast<DeclRefExpr>(LCRef);
  5972. }
  5973. Expr *OpenMPIterationSpaceChecker::buildPrivateCounterVar() const {
  5974. if (LCDecl && !LCDecl->isInvalidDecl()) {
  5975. QualType Type = LCDecl->getType().getNonReferenceType();
  5976. VarDecl *PrivateVar = buildVarDecl(
  5977. SemaRef, DefaultLoc, Type, LCDecl->getName(),
  5978. LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr,
  5979. isa<VarDecl>(LCDecl)
  5980. ? buildDeclRefExpr(SemaRef, cast<VarDecl>(LCDecl), Type, DefaultLoc)
  5981. : nullptr);
  5982. if (PrivateVar->isInvalidDecl())
  5983. return nullptr;
  5984. return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
  5985. }
  5986. return nullptr;
  5987. }
  5988. /// Build initialization of the counter to be used for codegen.
  5989. Expr *OpenMPIterationSpaceChecker::buildCounterInit() const { return LB; }
  5990. /// Build step of the counter be used for codegen.
  5991. Expr *OpenMPIterationSpaceChecker::buildCounterStep() const { return Step; }
  5992. Expr *OpenMPIterationSpaceChecker::buildOrderedLoopData(
  5993. Scope *S, Expr *Counter,
  5994. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, SourceLocation Loc,
  5995. Expr *Inc, OverloadedOperatorKind OOK) {
  5996. Expr *Cnt = SemaRef.DefaultLvalueConversion(Counter).get();
  5997. if (!Cnt)
  5998. return nullptr;
  5999. if (Inc) {
  6000. assert((OOK == OO_Plus || OOK == OO_Minus) &&
  6001. "Expected only + or - operations for depend clauses.");
  6002. BinaryOperatorKind BOK = (OOK == OO_Plus) ? BO_Add : BO_Sub;
  6003. Cnt = SemaRef.BuildBinOp(S, Loc, BOK, Cnt, Inc).get();
  6004. if (!Cnt)
  6005. return nullptr;
  6006. }
  6007. ExprResult Diff;
  6008. QualType VarType = LCDecl->getType().getNonReferenceType();
  6009. if (VarType->isIntegerType() || VarType->isPointerType() ||
  6010. SemaRef.getLangOpts().CPlusPlus) {
  6011. // Upper - Lower
  6012. Expr *Upper = TestIsLessOp.getValue()
  6013. ? Cnt
  6014. : tryBuildCapture(SemaRef, UB, Captures).get();
  6015. Expr *Lower = TestIsLessOp.getValue()
  6016. ? tryBuildCapture(SemaRef, LB, Captures).get()
  6017. : Cnt;
  6018. if (!Upper || !Lower)
  6019. return nullptr;
  6020. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
  6021. if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
  6022. // BuildBinOp already emitted error, this one is to point user to upper
  6023. // and lower bound, and to tell what is passed to 'operator-'.
  6024. SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx)
  6025. << Upper->getSourceRange() << Lower->getSourceRange();
  6026. return nullptr;
  6027. }
  6028. }
  6029. if (!Diff.isUsable())
  6030. return nullptr;
  6031. // Parentheses (for dumping/debugging purposes only).
  6032. Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
  6033. if (!Diff.isUsable())
  6034. return nullptr;
  6035. ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
  6036. if (!NewStep.isUsable())
  6037. return nullptr;
  6038. // (Upper - Lower) / Step
  6039. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
  6040. if (!Diff.isUsable())
  6041. return nullptr;
  6042. return Diff.get();
  6043. }
  6044. } // namespace
  6045. void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
  6046. assert(getLangOpts().OpenMP && "OpenMP is not active.");
  6047. assert(Init && "Expected loop in canonical form.");
  6048. unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
  6049. if (AssociatedLoops > 0 &&
  6050. isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
  6051. DSAStack->loopStart();
  6052. OpenMPIterationSpaceChecker ISC(*this, *DSAStack, ForLoc);
  6053. if (!ISC.checkAndSetInit(Init, /*EmitDiags=*/false)) {
  6054. if (ValueDecl *D = ISC.getLoopDecl()) {
  6055. auto *VD = dyn_cast<VarDecl>(D);
  6056. DeclRefExpr *PrivateRef = nullptr;
  6057. if (!VD) {
  6058. if (VarDecl *Private = isOpenMPCapturedDecl(D)) {
  6059. VD = Private;
  6060. } else {
  6061. PrivateRef = buildCapture(*this, D, ISC.getLoopDeclRefExpr(),
  6062. /*WithInit=*/false);
  6063. VD = cast<VarDecl>(PrivateRef->getDecl());
  6064. }
  6065. }
  6066. DSAStack->addLoopControlVariable(D, VD);
  6067. const Decl *LD = DSAStack->getPossiblyLoopCunter();
  6068. if (LD != D->getCanonicalDecl()) {
  6069. DSAStack->resetPossibleLoopCounter();
  6070. if (auto *Var = dyn_cast_or_null<VarDecl>(LD))
  6071. MarkDeclarationsReferencedInExpr(
  6072. buildDeclRefExpr(*this, const_cast<VarDecl *>(Var),
  6073. Var->getType().getNonLValueExprType(Context),
  6074. ForLoc, /*RefersToCapture=*/true));
  6075. }
  6076. OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
  6077. // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables
  6078. // Referenced in a Construct, C/C++]. The loop iteration variable in the
  6079. // associated for-loop of a simd construct with just one associated
  6080. // for-loop may be listed in a linear clause with a constant-linear-step
  6081. // that is the increment of the associated for-loop. The loop iteration
  6082. // variable(s) in the associated for-loop(s) of a for or parallel for
  6083. // construct may be listed in a private or lastprivate clause.
  6084. DSAStackTy::DSAVarData DVar =
  6085. DSAStack->getTopDSA(D, /*FromParent=*/false);
  6086. // If LoopVarRefExpr is nullptr it means the corresponding loop variable
  6087. // is declared in the loop and it is predetermined as a private.
  6088. Expr *LoopDeclRefExpr = ISC.getLoopDeclRefExpr();
  6089. OpenMPClauseKind PredeterminedCKind =
  6090. isOpenMPSimdDirective(DKind)
  6091. ? (DSAStack->hasMutipleLoops() ? OMPC_lastprivate : OMPC_linear)
  6092. : OMPC_private;
  6093. if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
  6094. DVar.CKind != PredeterminedCKind && DVar.RefExpr &&
  6095. (LangOpts.OpenMP <= 45 || (DVar.CKind != OMPC_lastprivate &&
  6096. DVar.CKind != OMPC_private))) ||
  6097. ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
  6098. isOpenMPDistributeDirective(DKind)) &&
  6099. !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
  6100. DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
  6101. (DVar.CKind != OMPC_private || DVar.RefExpr)) {
  6102. Diag(Init->getBeginLoc(), diag::err_omp_loop_var_dsa)
  6103. << getOpenMPClauseName(DVar.CKind)
  6104. << getOpenMPDirectiveName(DKind)
  6105. << getOpenMPClauseName(PredeterminedCKind);
  6106. if (DVar.RefExpr == nullptr)
  6107. DVar.CKind = PredeterminedCKind;
  6108. reportOriginalDsa(*this, DSAStack, D, DVar,
  6109. /*IsLoopIterVar=*/true);
  6110. } else if (LoopDeclRefExpr) {
  6111. // Make the loop iteration variable private (for worksharing
  6112. // constructs), linear (for simd directives with the only one
  6113. // associated loop) or lastprivate (for simd directives with several
  6114. // collapsed or ordered loops).
  6115. if (DVar.CKind == OMPC_unknown)
  6116. DSAStack->addDSA(D, LoopDeclRefExpr, PredeterminedCKind,
  6117. PrivateRef);
  6118. }
  6119. }
  6120. }
  6121. DSAStack->setAssociatedLoops(AssociatedLoops - 1);
  6122. }
  6123. }
  6124. /// Called on a for stmt to check and extract its iteration space
  6125. /// for further processing (such as collapsing).
  6126. static bool checkOpenMPIterationSpace(
  6127. OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
  6128. unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
  6129. unsigned TotalNestedLoopCount, Expr *CollapseLoopCountExpr,
  6130. Expr *OrderedLoopCountExpr,
  6131. Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
  6132. llvm::MutableArrayRef<LoopIterationSpace> ResultIterSpaces,
  6133. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
  6134. // OpenMP [2.9.1, Canonical Loop Form]
  6135. // for (init-expr; test-expr; incr-expr) structured-block
  6136. // for (range-decl: range-expr) structured-block
  6137. auto *For = dyn_cast_or_null<ForStmt>(S);
  6138. auto *CXXFor = dyn_cast_or_null<CXXForRangeStmt>(S);
  6139. // Ranged for is supported only in OpenMP 5.0.
  6140. if (!For && (SemaRef.LangOpts.OpenMP <= 45 || !CXXFor)) {
  6141. SemaRef.Diag(S->getBeginLoc(), diag::err_omp_not_for)
  6142. << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
  6143. << getOpenMPDirectiveName(DKind) << TotalNestedLoopCount
  6144. << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
  6145. if (TotalNestedLoopCount > 1) {
  6146. if (CollapseLoopCountExpr && OrderedLoopCountExpr)
  6147. SemaRef.Diag(DSA.getConstructLoc(),
  6148. diag::note_omp_collapse_ordered_expr)
  6149. << 2 << CollapseLoopCountExpr->getSourceRange()
  6150. << OrderedLoopCountExpr->getSourceRange();
  6151. else if (CollapseLoopCountExpr)
  6152. SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
  6153. diag::note_omp_collapse_ordered_expr)
  6154. << 0 << CollapseLoopCountExpr->getSourceRange();
  6155. else
  6156. SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
  6157. diag::note_omp_collapse_ordered_expr)
  6158. << 1 << OrderedLoopCountExpr->getSourceRange();
  6159. }
  6160. return true;
  6161. }
  6162. assert(((For && For->getBody()) || (CXXFor && CXXFor->getBody())) &&
  6163. "No loop body.");
  6164. OpenMPIterationSpaceChecker ISC(SemaRef, DSA,
  6165. For ? For->getForLoc() : CXXFor->getForLoc());
  6166. // Check init.
  6167. Stmt *Init = For ? For->getInit() : CXXFor->getBeginStmt();
  6168. if (ISC.checkAndSetInit(Init))
  6169. return true;
  6170. bool HasErrors = false;
  6171. // Check loop variable's type.
  6172. if (ValueDecl *LCDecl = ISC.getLoopDecl()) {
  6173. // OpenMP [2.6, Canonical Loop Form]
  6174. // Var is one of the following:
  6175. // A variable of signed or unsigned integer type.
  6176. // For C++, a variable of a random access iterator type.
  6177. // For C, a variable of a pointer type.
  6178. QualType VarType = LCDecl->getType().getNonReferenceType();
  6179. if (!VarType->isDependentType() && !VarType->isIntegerType() &&
  6180. !VarType->isPointerType() &&
  6181. !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
  6182. SemaRef.Diag(Init->getBeginLoc(), diag::err_omp_loop_variable_type)
  6183. << SemaRef.getLangOpts().CPlusPlus;
  6184. HasErrors = true;
  6185. }
  6186. // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
  6187. // a Construct
  6188. // The loop iteration variable(s) in the associated for-loop(s) of a for or
  6189. // parallel for construct is (are) private.
  6190. // The loop iteration variable in the associated for-loop of a simd
  6191. // construct with just one associated for-loop is linear with a
  6192. // constant-linear-step that is the increment of the associated for-loop.
  6193. // Exclude loop var from the list of variables with implicitly defined data
  6194. // sharing attributes.
  6195. VarsWithImplicitDSA.erase(LCDecl);
  6196. assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
  6197. // Check test-expr.
  6198. HasErrors |= ISC.checkAndSetCond(For ? For->getCond() : CXXFor->getCond());
  6199. // Check incr-expr.
  6200. HasErrors |= ISC.checkAndSetInc(For ? For->getInc() : CXXFor->getInc());
  6201. }
  6202. if (ISC.dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
  6203. return HasErrors;
  6204. // Build the loop's iteration space representation.
  6205. ResultIterSpaces[CurrentNestedLoopCount].PreCond = ISC.buildPreCond(
  6206. DSA.getCurScope(), For ? For->getCond() : CXXFor->getCond(), Captures);
  6207. ResultIterSpaces[CurrentNestedLoopCount].NumIterations =
  6208. ISC.buildNumIterations(DSA.getCurScope(), ResultIterSpaces,
  6209. (isOpenMPWorksharingDirective(DKind) ||
  6210. isOpenMPTaskLoopDirective(DKind) ||
  6211. isOpenMPDistributeDirective(DKind)),
  6212. Captures);
  6213. ResultIterSpaces[CurrentNestedLoopCount].CounterVar =
  6214. ISC.buildCounterVar(Captures, DSA);
  6215. ResultIterSpaces[CurrentNestedLoopCount].PrivateCounterVar =
  6216. ISC.buildPrivateCounterVar();
  6217. ResultIterSpaces[CurrentNestedLoopCount].CounterInit = ISC.buildCounterInit();
  6218. ResultIterSpaces[CurrentNestedLoopCount].CounterStep = ISC.buildCounterStep();
  6219. ResultIterSpaces[CurrentNestedLoopCount].InitSrcRange = ISC.getInitSrcRange();
  6220. ResultIterSpaces[CurrentNestedLoopCount].CondSrcRange =
  6221. ISC.getConditionSrcRange();
  6222. ResultIterSpaces[CurrentNestedLoopCount].IncSrcRange =
  6223. ISC.getIncrementSrcRange();
  6224. ResultIterSpaces[CurrentNestedLoopCount].Subtract = ISC.shouldSubtractStep();
  6225. ResultIterSpaces[CurrentNestedLoopCount].IsStrictCompare =
  6226. ISC.isStrictTestOp();
  6227. std::tie(ResultIterSpaces[CurrentNestedLoopCount].MinValue,
  6228. ResultIterSpaces[CurrentNestedLoopCount].MaxValue) =
  6229. ISC.buildMinMaxValues(DSA.getCurScope(), Captures);
  6230. ResultIterSpaces[CurrentNestedLoopCount].FinalCondition =
  6231. ISC.buildFinalCondition(DSA.getCurScope());
  6232. ResultIterSpaces[CurrentNestedLoopCount].IsNonRectangularLB =
  6233. ISC.doesInitDependOnLC();
  6234. ResultIterSpaces[CurrentNestedLoopCount].IsNonRectangularUB =
  6235. ISC.doesCondDependOnLC();
  6236. ResultIterSpaces[CurrentNestedLoopCount].LoopDependentIdx =
  6237. ISC.getLoopDependentIdx();
  6238. HasErrors |=
  6239. (ResultIterSpaces[CurrentNestedLoopCount].PreCond == nullptr ||
  6240. ResultIterSpaces[CurrentNestedLoopCount].NumIterations == nullptr ||
  6241. ResultIterSpaces[CurrentNestedLoopCount].CounterVar == nullptr ||
  6242. ResultIterSpaces[CurrentNestedLoopCount].PrivateCounterVar == nullptr ||
  6243. ResultIterSpaces[CurrentNestedLoopCount].CounterInit == nullptr ||
  6244. ResultIterSpaces[CurrentNestedLoopCount].CounterStep == nullptr);
  6245. if (!HasErrors && DSA.isOrderedRegion()) {
  6246. if (DSA.getOrderedRegionParam().second->getNumForLoops()) {
  6247. if (CurrentNestedLoopCount <
  6248. DSA.getOrderedRegionParam().second->getLoopNumIterations().size()) {
  6249. DSA.getOrderedRegionParam().second->setLoopNumIterations(
  6250. CurrentNestedLoopCount,
  6251. ResultIterSpaces[CurrentNestedLoopCount].NumIterations);
  6252. DSA.getOrderedRegionParam().second->setLoopCounter(
  6253. CurrentNestedLoopCount,
  6254. ResultIterSpaces[CurrentNestedLoopCount].CounterVar);
  6255. }
  6256. }
  6257. for (auto &Pair : DSA.getDoacrossDependClauses()) {
  6258. if (CurrentNestedLoopCount >= Pair.first->getNumLoops()) {
  6259. // Erroneous case - clause has some problems.
  6260. continue;
  6261. }
  6262. if (Pair.first->getDependencyKind() == OMPC_DEPEND_sink &&
  6263. Pair.second.size() <= CurrentNestedLoopCount) {
  6264. // Erroneous case - clause has some problems.
  6265. Pair.first->setLoopData(CurrentNestedLoopCount, nullptr);
  6266. continue;
  6267. }
  6268. Expr *CntValue;
  6269. if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
  6270. CntValue = ISC.buildOrderedLoopData(
  6271. DSA.getCurScope(),
  6272. ResultIterSpaces[CurrentNestedLoopCount].CounterVar, Captures,
  6273. Pair.first->getDependencyLoc());
  6274. else
  6275. CntValue = ISC.buildOrderedLoopData(
  6276. DSA.getCurScope(),
  6277. ResultIterSpaces[CurrentNestedLoopCount].CounterVar, Captures,
  6278. Pair.first->getDependencyLoc(),
  6279. Pair.second[CurrentNestedLoopCount].first,
  6280. Pair.second[CurrentNestedLoopCount].second);
  6281. Pair.first->setLoopData(CurrentNestedLoopCount, CntValue);
  6282. }
  6283. }
  6284. return HasErrors;
  6285. }
  6286. /// Build 'VarRef = Start.
  6287. static ExprResult
  6288. buildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
  6289. ExprResult Start, bool IsNonRectangularLB,
  6290. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
  6291. // Build 'VarRef = Start.
  6292. ExprResult NewStart = IsNonRectangularLB
  6293. ? Start.get()
  6294. : tryBuildCapture(SemaRef, Start.get(), Captures);
  6295. if (!NewStart.isUsable())
  6296. return ExprError();
  6297. if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
  6298. VarRef.get()->getType())) {
  6299. NewStart = SemaRef.PerformImplicitConversion(
  6300. NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
  6301. /*AllowExplicit=*/true);
  6302. if (!NewStart.isUsable())
  6303. return ExprError();
  6304. }
  6305. ExprResult Init =
  6306. SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
  6307. return Init;
  6308. }
  6309. /// Build 'VarRef = Start + Iter * Step'.
  6310. static ExprResult buildCounterUpdate(
  6311. Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
  6312. ExprResult Start, ExprResult Iter, ExprResult Step, bool Subtract,
  6313. bool IsNonRectangularLB,
  6314. llvm::MapVector<const Expr *, DeclRefExpr *> *Captures = nullptr) {
  6315. // Add parentheses (for debugging purposes only).
  6316. Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
  6317. if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
  6318. !Step.isUsable())
  6319. return ExprError();
  6320. ExprResult NewStep = Step;
  6321. if (Captures)
  6322. NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
  6323. if (NewStep.isInvalid())
  6324. return ExprError();
  6325. ExprResult Update =
  6326. SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
  6327. if (!Update.isUsable())
  6328. return ExprError();
  6329. // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
  6330. // 'VarRef = Start (+|-) Iter * Step'.
  6331. if (!Start.isUsable())
  6332. return ExprError();
  6333. ExprResult NewStart = SemaRef.ActOnParenExpr(Loc, Loc, Start.get());
  6334. if (!NewStart.isUsable())
  6335. return ExprError();
  6336. if (Captures && !IsNonRectangularLB)
  6337. NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
  6338. if (NewStart.isInvalid())
  6339. return ExprError();
  6340. // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
  6341. ExprResult SavedUpdate = Update;
  6342. ExprResult UpdateVal;
  6343. if (VarRef.get()->getType()->isOverloadableType() ||
  6344. NewStart.get()->getType()->isOverloadableType() ||
  6345. Update.get()->getType()->isOverloadableType()) {
  6346. Sema::TentativeAnalysisScope Trap(SemaRef);
  6347. Update =
  6348. SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
  6349. if (Update.isUsable()) {
  6350. UpdateVal =
  6351. SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
  6352. VarRef.get(), SavedUpdate.get());
  6353. if (UpdateVal.isUsable()) {
  6354. Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
  6355. UpdateVal.get());
  6356. }
  6357. }
  6358. }
  6359. // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
  6360. if (!Update.isUsable() || !UpdateVal.isUsable()) {
  6361. Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
  6362. NewStart.get(), SavedUpdate.get());
  6363. if (!Update.isUsable())
  6364. return ExprError();
  6365. if (!SemaRef.Context.hasSameType(Update.get()->getType(),
  6366. VarRef.get()->getType())) {
  6367. Update = SemaRef.PerformImplicitConversion(
  6368. Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
  6369. if (!Update.isUsable())
  6370. return ExprError();
  6371. }
  6372. Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
  6373. }
  6374. return Update;
  6375. }
  6376. /// Convert integer expression \a E to make it have at least \a Bits
  6377. /// bits.
  6378. static ExprResult widenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
  6379. if (E == nullptr)
  6380. return ExprError();
  6381. ASTContext &C = SemaRef.Context;
  6382. QualType OldType = E->getType();
  6383. unsigned HasBits = C.getTypeSize(OldType);
  6384. if (HasBits >= Bits)
  6385. return ExprResult(E);
  6386. // OK to convert to signed, because new type has more bits than old.
  6387. QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
  6388. return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
  6389. true);
  6390. }
  6391. /// Check if the given expression \a E is a constant integer that fits
  6392. /// into \a Bits bits.
  6393. static bool fitsInto(unsigned Bits, bool Signed, const Expr *E, Sema &SemaRef) {
  6394. if (E == nullptr)
  6395. return false;
  6396. llvm::APSInt Result;
  6397. if (E->isIntegerConstantExpr(Result, SemaRef.Context))
  6398. return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
  6399. return false;
  6400. }
  6401. /// Build preinits statement for the given declarations.
  6402. static Stmt *buildPreInits(ASTContext &Context,
  6403. MutableArrayRef<Decl *> PreInits) {
  6404. if (!PreInits.empty()) {
  6405. return new (Context) DeclStmt(
  6406. DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
  6407. SourceLocation(), SourceLocation());
  6408. }
  6409. return nullptr;
  6410. }
  6411. /// Build preinits statement for the given declarations.
  6412. static Stmt *
  6413. buildPreInits(ASTContext &Context,
  6414. const llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
  6415. if (!Captures.empty()) {
  6416. SmallVector<Decl *, 16> PreInits;
  6417. for (const auto &Pair : Captures)
  6418. PreInits.push_back(Pair.second->getDecl());
  6419. return buildPreInits(Context, PreInits);
  6420. }
  6421. return nullptr;
  6422. }
  6423. /// Build postupdate expression for the given list of postupdates expressions.
  6424. static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
  6425. Expr *PostUpdate = nullptr;
  6426. if (!PostUpdates.empty()) {
  6427. for (Expr *E : PostUpdates) {
  6428. Expr *ConvE = S.BuildCStyleCastExpr(
  6429. E->getExprLoc(),
  6430. S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
  6431. E->getExprLoc(), E)
  6432. .get();
  6433. PostUpdate = PostUpdate
  6434. ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
  6435. PostUpdate, ConvE)
  6436. .get()
  6437. : ConvE;
  6438. }
  6439. }
  6440. return PostUpdate;
  6441. }
  6442. /// Called on a for stmt to check itself and nested loops (if any).
  6443. /// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
  6444. /// number of collapsed loops otherwise.
  6445. static unsigned
  6446. checkOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
  6447. Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
  6448. DSAStackTy &DSA,
  6449. Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
  6450. OMPLoopDirective::HelperExprs &Built) {
  6451. unsigned NestedLoopCount = 1;
  6452. if (CollapseLoopCountExpr) {
  6453. // Found 'collapse' clause - calculate collapse number.
  6454. Expr::EvalResult Result;
  6455. if (!CollapseLoopCountExpr->isValueDependent() &&
  6456. CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) {
  6457. NestedLoopCount = Result.Val.getInt().getLimitedValue();
  6458. } else {
  6459. Built.clear(/*Size=*/1);
  6460. return 1;
  6461. }
  6462. }
  6463. unsigned OrderedLoopCount = 1;
  6464. if (OrderedLoopCountExpr) {
  6465. // Found 'ordered' clause - calculate collapse number.
  6466. Expr::EvalResult EVResult;
  6467. if (!OrderedLoopCountExpr->isValueDependent() &&
  6468. OrderedLoopCountExpr->EvaluateAsInt(EVResult,
  6469. SemaRef.getASTContext())) {
  6470. llvm::APSInt Result = EVResult.Val.getInt();
  6471. if (Result.getLimitedValue() < NestedLoopCount) {
  6472. SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
  6473. diag::err_omp_wrong_ordered_loop_count)
  6474. << OrderedLoopCountExpr->getSourceRange();
  6475. SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
  6476. diag::note_collapse_loop_count)
  6477. << CollapseLoopCountExpr->getSourceRange();
  6478. }
  6479. OrderedLoopCount = Result.getLimitedValue();
  6480. } else {
  6481. Built.clear(/*Size=*/1);
  6482. return 1;
  6483. }
  6484. }
  6485. // This is helper routine for loop directives (e.g., 'for', 'simd',
  6486. // 'for simd', etc.).
  6487. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  6488. SmallVector<LoopIterationSpace, 4> IterSpaces(
  6489. std::max(OrderedLoopCount, NestedLoopCount));
  6490. Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
  6491. for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
  6492. if (checkOpenMPIterationSpace(
  6493. DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
  6494. std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr,
  6495. OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces, Captures))
  6496. return 0;
  6497. // Move on to the next nested for loop, or to the loop body.
  6498. // OpenMP [2.8.1, simd construct, Restrictions]
  6499. // All loops associated with the construct must be perfectly nested; that
  6500. // is, there must be no intervening code nor any OpenMP directive between
  6501. // any two loops.
  6502. if (auto *For = dyn_cast<ForStmt>(CurStmt)) {
  6503. CurStmt = For->getBody();
  6504. } else {
  6505. assert(isa<CXXForRangeStmt>(CurStmt) &&
  6506. "Expected canonical for or range-based for loops.");
  6507. CurStmt = cast<CXXForRangeStmt>(CurStmt)->getBody();
  6508. }
  6509. CurStmt = CurStmt->IgnoreContainers();
  6510. }
  6511. for (unsigned Cnt = NestedLoopCount; Cnt < OrderedLoopCount; ++Cnt) {
  6512. if (checkOpenMPIterationSpace(
  6513. DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
  6514. std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr,
  6515. OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces, Captures))
  6516. return 0;
  6517. if (Cnt > 0 && IterSpaces[Cnt].CounterVar) {
  6518. // Handle initialization of captured loop iterator variables.
  6519. auto *DRE = cast<DeclRefExpr>(IterSpaces[Cnt].CounterVar);
  6520. if (isa<OMPCapturedExprDecl>(DRE->getDecl())) {
  6521. Captures[DRE] = DRE;
  6522. }
  6523. }
  6524. // Move on to the next nested for loop, or to the loop body.
  6525. // OpenMP [2.8.1, simd construct, Restrictions]
  6526. // All loops associated with the construct must be perfectly nested; that
  6527. // is, there must be no intervening code nor any OpenMP directive between
  6528. // any two loops.
  6529. if (auto *For = dyn_cast<ForStmt>(CurStmt)) {
  6530. CurStmt = For->getBody();
  6531. } else {
  6532. assert(isa<CXXForRangeStmt>(CurStmt) &&
  6533. "Expected canonical for or range-based for loops.");
  6534. CurStmt = cast<CXXForRangeStmt>(CurStmt)->getBody();
  6535. }
  6536. CurStmt = CurStmt->IgnoreContainers();
  6537. }
  6538. Built.clear(/* size */ NestedLoopCount);
  6539. if (SemaRef.CurContext->isDependentContext())
  6540. return NestedLoopCount;
  6541. // An example of what is generated for the following code:
  6542. //
  6543. // #pragma omp simd collapse(2) ordered(2)
  6544. // for (i = 0; i < NI; ++i)
  6545. // for (k = 0; k < NK; ++k)
  6546. // for (j = J0; j < NJ; j+=2) {
  6547. // <loop body>
  6548. // }
  6549. //
  6550. // We generate the code below.
  6551. // Note: the loop body may be outlined in CodeGen.
  6552. // Note: some counters may be C++ classes, operator- is used to find number of
  6553. // iterations and operator+= to calculate counter value.
  6554. // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
  6555. // or i64 is currently supported).
  6556. //
  6557. // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
  6558. // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
  6559. // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
  6560. // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
  6561. // // similar updates for vars in clauses (e.g. 'linear')
  6562. // <loop body (using local i and j)>
  6563. // }
  6564. // i = NI; // assign final values of counters
  6565. // j = NJ;
  6566. //
  6567. // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
  6568. // the iteration counts of the collapsed for loops.
  6569. // Precondition tests if there is at least one iteration (all conditions are
  6570. // true).
  6571. auto PreCond = ExprResult(IterSpaces[0].PreCond);
  6572. Expr *N0 = IterSpaces[0].NumIterations;
  6573. ExprResult LastIteration32 =
  6574. widenIterationCount(/*Bits=*/32,
  6575. SemaRef
  6576. .PerformImplicitConversion(
  6577. N0->IgnoreImpCasts(), N0->getType(),
  6578. Sema::AA_Converting, /*AllowExplicit=*/true)
  6579. .get(),
  6580. SemaRef);
  6581. ExprResult LastIteration64 = widenIterationCount(
  6582. /*Bits=*/64,
  6583. SemaRef
  6584. .PerformImplicitConversion(N0->IgnoreImpCasts(), N0->getType(),
  6585. Sema::AA_Converting,
  6586. /*AllowExplicit=*/true)
  6587. .get(),
  6588. SemaRef);
  6589. if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
  6590. return NestedLoopCount;
  6591. ASTContext &C = SemaRef.Context;
  6592. bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
  6593. Scope *CurScope = DSA.getCurScope();
  6594. for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
  6595. if (PreCond.isUsable()) {
  6596. PreCond =
  6597. SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
  6598. PreCond.get(), IterSpaces[Cnt].PreCond);
  6599. }
  6600. Expr *N = IterSpaces[Cnt].NumIterations;
  6601. SourceLocation Loc = N->getExprLoc();
  6602. AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
  6603. if (LastIteration32.isUsable())
  6604. LastIteration32 = SemaRef.BuildBinOp(
  6605. CurScope, Loc, BO_Mul, LastIteration32.get(),
  6606. SemaRef
  6607. .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
  6608. Sema::AA_Converting,
  6609. /*AllowExplicit=*/true)
  6610. .get());
  6611. if (LastIteration64.isUsable())
  6612. LastIteration64 = SemaRef.BuildBinOp(
  6613. CurScope, Loc, BO_Mul, LastIteration64.get(),
  6614. SemaRef
  6615. .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
  6616. Sema::AA_Converting,
  6617. /*AllowExplicit=*/true)
  6618. .get());
  6619. }
  6620. // Choose either the 32-bit or 64-bit version.
  6621. ExprResult LastIteration = LastIteration64;
  6622. if (SemaRef.getLangOpts().OpenMPOptimisticCollapse ||
  6623. (LastIteration32.isUsable() &&
  6624. C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
  6625. (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
  6626. fitsInto(
  6627. /*Bits=*/32,
  6628. LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
  6629. LastIteration64.get(), SemaRef))))
  6630. LastIteration = LastIteration32;
  6631. QualType VType = LastIteration.get()->getType();
  6632. QualType RealVType = VType;
  6633. QualType StrideVType = VType;
  6634. if (isOpenMPTaskLoopDirective(DKind)) {
  6635. VType =
  6636. SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
  6637. StrideVType =
  6638. SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
  6639. }
  6640. if (!LastIteration.isUsable())
  6641. return 0;
  6642. // Save the number of iterations.
  6643. ExprResult NumIterations = LastIteration;
  6644. {
  6645. LastIteration = SemaRef.BuildBinOp(
  6646. CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
  6647. LastIteration.get(),
  6648. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
  6649. if (!LastIteration.isUsable())
  6650. return 0;
  6651. }
  6652. // Calculate the last iteration number beforehand instead of doing this on
  6653. // each iteration. Do not do this if the number of iterations may be kfold-ed.
  6654. llvm::APSInt Result;
  6655. bool IsConstant =
  6656. LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
  6657. ExprResult CalcLastIteration;
  6658. if (!IsConstant) {
  6659. ExprResult SaveRef =
  6660. tryBuildCapture(SemaRef, LastIteration.get(), Captures);
  6661. LastIteration = SaveRef;
  6662. // Prepare SaveRef + 1.
  6663. NumIterations = SemaRef.BuildBinOp(
  6664. CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
  6665. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
  6666. if (!NumIterations.isUsable())
  6667. return 0;
  6668. }
  6669. SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
  6670. // Build variables passed into runtime, necessary for worksharing directives.
  6671. ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB;
  6672. if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
  6673. isOpenMPDistributeDirective(DKind)) {
  6674. // Lower bound variable, initialized with zero.
  6675. VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
  6676. LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
  6677. SemaRef.AddInitializerToDecl(LBDecl,
  6678. SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
  6679. /*DirectInit*/ false);
  6680. // Upper bound variable, initialized with last iteration number.
  6681. VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
  6682. UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
  6683. SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
  6684. /*DirectInit*/ false);
  6685. // A 32-bit variable-flag where runtime returns 1 for the last iteration.
  6686. // This will be used to implement clause 'lastprivate'.
  6687. QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
  6688. VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
  6689. IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
  6690. SemaRef.AddInitializerToDecl(ILDecl,
  6691. SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
  6692. /*DirectInit*/ false);
  6693. // Stride variable returned by runtime (we initialize it to 1 by default).
  6694. VarDecl *STDecl =
  6695. buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
  6696. ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
  6697. SemaRef.AddInitializerToDecl(STDecl,
  6698. SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
  6699. /*DirectInit*/ false);
  6700. // Build expression: UB = min(UB, LastIteration)
  6701. // It is necessary for CodeGen of directives with static scheduling.
  6702. ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
  6703. UB.get(), LastIteration.get());
  6704. ExprResult CondOp = SemaRef.ActOnConditionalOp(
  6705. LastIteration.get()->getExprLoc(), InitLoc, IsUBGreater.get(),
  6706. LastIteration.get(), UB.get());
  6707. EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
  6708. CondOp.get());
  6709. EUB = SemaRef.ActOnFinishFullExpr(EUB.get(), /*DiscardedValue*/ false);
  6710. // If we have a combined directive that combines 'distribute', 'for' or
  6711. // 'simd' we need to be able to access the bounds of the schedule of the
  6712. // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
  6713. // by scheduling 'distribute' have to be passed to the schedule of 'for'.
  6714. if (isOpenMPLoopBoundSharingDirective(DKind)) {
  6715. // Lower bound variable, initialized with zero.
  6716. VarDecl *CombLBDecl =
  6717. buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb");
  6718. CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc);
  6719. SemaRef.AddInitializerToDecl(
  6720. CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
  6721. /*DirectInit*/ false);
  6722. // Upper bound variable, initialized with last iteration number.
  6723. VarDecl *CombUBDecl =
  6724. buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub");
  6725. CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc);
  6726. SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(),
  6727. /*DirectInit*/ false);
  6728. ExprResult CombIsUBGreater = SemaRef.BuildBinOp(
  6729. CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get());
  6730. ExprResult CombCondOp =
  6731. SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(),
  6732. LastIteration.get(), CombUB.get());
  6733. CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(),
  6734. CombCondOp.get());
  6735. CombEUB =
  6736. SemaRef.ActOnFinishFullExpr(CombEUB.get(), /*DiscardedValue*/ false);
  6737. const CapturedDecl *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
  6738. // We expect to have at least 2 more parameters than the 'parallel'
  6739. // directive does - the lower and upper bounds of the previous schedule.
  6740. assert(CD->getNumParams() >= 4 &&
  6741. "Unexpected number of parameters in loop combined directive");
  6742. // Set the proper type for the bounds given what we learned from the
  6743. // enclosed loops.
  6744. ImplicitParamDecl *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
  6745. ImplicitParamDecl *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
  6746. // Previous lower and upper bounds are obtained from the region
  6747. // parameters.
  6748. PrevLB =
  6749. buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
  6750. PrevUB =
  6751. buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
  6752. }
  6753. }
  6754. // Build the iteration variable and its initialization before loop.
  6755. ExprResult IV;
  6756. ExprResult Init, CombInit;
  6757. {
  6758. VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
  6759. IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
  6760. Expr *RHS =
  6761. (isOpenMPWorksharingDirective(DKind) ||
  6762. isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
  6763. ? LB.get()
  6764. : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
  6765. Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
  6766. Init = SemaRef.ActOnFinishFullExpr(Init.get(), /*DiscardedValue*/ false);
  6767. if (isOpenMPLoopBoundSharingDirective(DKind)) {
  6768. Expr *CombRHS =
  6769. (isOpenMPWorksharingDirective(DKind) ||
  6770. isOpenMPTaskLoopDirective(DKind) ||
  6771. isOpenMPDistributeDirective(DKind))
  6772. ? CombLB.get()
  6773. : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
  6774. CombInit =
  6775. SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS);
  6776. CombInit =
  6777. SemaRef.ActOnFinishFullExpr(CombInit.get(), /*DiscardedValue*/ false);
  6778. }
  6779. }
  6780. bool UseStrictCompare =
  6781. RealVType->hasUnsignedIntegerRepresentation() &&
  6782. llvm::all_of(IterSpaces, [](const LoopIterationSpace &LIS) {
  6783. return LIS.IsStrictCompare;
  6784. });
  6785. // Loop condition (IV < NumIterations) or (IV <= UB or IV < UB + 1 (for
  6786. // unsigned IV)) for worksharing loops.
  6787. SourceLocation CondLoc = AStmt->getBeginLoc();
  6788. Expr *BoundUB = UB.get();
  6789. if (UseStrictCompare) {
  6790. BoundUB =
  6791. SemaRef
  6792. .BuildBinOp(CurScope, CondLoc, BO_Add, BoundUB,
  6793. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
  6794. .get();
  6795. BoundUB =
  6796. SemaRef.ActOnFinishFullExpr(BoundUB, /*DiscardedValue*/ false).get();
  6797. }
  6798. ExprResult Cond =
  6799. (isOpenMPWorksharingDirective(DKind) ||
  6800. isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
  6801. ? SemaRef.BuildBinOp(CurScope, CondLoc,
  6802. UseStrictCompare ? BO_LT : BO_LE, IV.get(),
  6803. BoundUB)
  6804. : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
  6805. NumIterations.get());
  6806. ExprResult CombDistCond;
  6807. if (isOpenMPLoopBoundSharingDirective(DKind)) {
  6808. CombDistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
  6809. NumIterations.get());
  6810. }
  6811. ExprResult CombCond;
  6812. if (isOpenMPLoopBoundSharingDirective(DKind)) {
  6813. Expr *BoundCombUB = CombUB.get();
  6814. if (UseStrictCompare) {
  6815. BoundCombUB =
  6816. SemaRef
  6817. .BuildBinOp(
  6818. CurScope, CondLoc, BO_Add, BoundCombUB,
  6819. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
  6820. .get();
  6821. BoundCombUB =
  6822. SemaRef.ActOnFinishFullExpr(BoundCombUB, /*DiscardedValue*/ false)
  6823. .get();
  6824. }
  6825. CombCond =
  6826. SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
  6827. IV.get(), BoundCombUB);
  6828. }
  6829. // Loop increment (IV = IV + 1)
  6830. SourceLocation IncLoc = AStmt->getBeginLoc();
  6831. ExprResult Inc =
  6832. SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
  6833. SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
  6834. if (!Inc.isUsable())
  6835. return 0;
  6836. Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
  6837. Inc = SemaRef.ActOnFinishFullExpr(Inc.get(), /*DiscardedValue*/ false);
  6838. if (!Inc.isUsable())
  6839. return 0;
  6840. // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
  6841. // Used for directives with static scheduling.
  6842. // In combined construct, add combined version that use CombLB and CombUB
  6843. // base variables for the update
  6844. ExprResult NextLB, NextUB, CombNextLB, CombNextUB;
  6845. if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
  6846. isOpenMPDistributeDirective(DKind)) {
  6847. // LB + ST
  6848. NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
  6849. if (!NextLB.isUsable())
  6850. return 0;
  6851. // LB = LB + ST
  6852. NextLB =
  6853. SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
  6854. NextLB =
  6855. SemaRef.ActOnFinishFullExpr(NextLB.get(), /*DiscardedValue*/ false);
  6856. if (!NextLB.isUsable())
  6857. return 0;
  6858. // UB + ST
  6859. NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
  6860. if (!NextUB.isUsable())
  6861. return 0;
  6862. // UB = UB + ST
  6863. NextUB =
  6864. SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
  6865. NextUB =
  6866. SemaRef.ActOnFinishFullExpr(NextUB.get(), /*DiscardedValue*/ false);
  6867. if (!NextUB.isUsable())
  6868. return 0;
  6869. if (isOpenMPLoopBoundSharingDirective(DKind)) {
  6870. CombNextLB =
  6871. SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get());
  6872. if (!NextLB.isUsable())
  6873. return 0;
  6874. // LB = LB + ST
  6875. CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(),
  6876. CombNextLB.get());
  6877. CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get(),
  6878. /*DiscardedValue*/ false);
  6879. if (!CombNextLB.isUsable())
  6880. return 0;
  6881. // UB + ST
  6882. CombNextUB =
  6883. SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get());
  6884. if (!CombNextUB.isUsable())
  6885. return 0;
  6886. // UB = UB + ST
  6887. CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(),
  6888. CombNextUB.get());
  6889. CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get(),
  6890. /*DiscardedValue*/ false);
  6891. if (!CombNextUB.isUsable())
  6892. return 0;
  6893. }
  6894. }
  6895. // Create increment expression for distribute loop when combined in a same
  6896. // directive with for as IV = IV + ST; ensure upper bound expression based
  6897. // on PrevUB instead of NumIterations - used to implement 'for' when found
  6898. // in combination with 'distribute', like in 'distribute parallel for'
  6899. SourceLocation DistIncLoc = AStmt->getBeginLoc();
  6900. ExprResult DistCond, DistInc, PrevEUB, ParForInDistCond;
  6901. if (isOpenMPLoopBoundSharingDirective(DKind)) {
  6902. DistCond = SemaRef.BuildBinOp(
  6903. CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE, IV.get(), BoundUB);
  6904. assert(DistCond.isUsable() && "distribute cond expr was not built");
  6905. DistInc =
  6906. SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get());
  6907. assert(DistInc.isUsable() && "distribute inc expr was not built");
  6908. DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(),
  6909. DistInc.get());
  6910. DistInc =
  6911. SemaRef.ActOnFinishFullExpr(DistInc.get(), /*DiscardedValue*/ false);
  6912. assert(DistInc.isUsable() && "distribute inc expr was not built");
  6913. // Build expression: UB = min(UB, prevUB) for #for in composite or combined
  6914. // construct
  6915. SourceLocation DistEUBLoc = AStmt->getBeginLoc();
  6916. ExprResult IsUBGreater =
  6917. SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, UB.get(), PrevUB.get());
  6918. ExprResult CondOp = SemaRef.ActOnConditionalOp(
  6919. DistEUBLoc, DistEUBLoc, IsUBGreater.get(), PrevUB.get(), UB.get());
  6920. PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(),
  6921. CondOp.get());
  6922. PrevEUB =
  6923. SemaRef.ActOnFinishFullExpr(PrevEUB.get(), /*DiscardedValue*/ false);
  6924. // Build IV <= PrevUB or IV < PrevUB + 1 for unsigned IV to be used in
  6925. // parallel for is in combination with a distribute directive with
  6926. // schedule(static, 1)
  6927. Expr *BoundPrevUB = PrevUB.get();
  6928. if (UseStrictCompare) {
  6929. BoundPrevUB =
  6930. SemaRef
  6931. .BuildBinOp(
  6932. CurScope, CondLoc, BO_Add, BoundPrevUB,
  6933. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
  6934. .get();
  6935. BoundPrevUB =
  6936. SemaRef.ActOnFinishFullExpr(BoundPrevUB, /*DiscardedValue*/ false)
  6937. .get();
  6938. }
  6939. ParForInDistCond =
  6940. SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
  6941. IV.get(), BoundPrevUB);
  6942. }
  6943. // Build updates and final values of the loop counters.
  6944. bool HasErrors = false;
  6945. Built.Counters.resize(NestedLoopCount);
  6946. Built.Inits.resize(NestedLoopCount);
  6947. Built.Updates.resize(NestedLoopCount);
  6948. Built.Finals.resize(NestedLoopCount);
  6949. Built.DependentCounters.resize(NestedLoopCount);
  6950. Built.DependentInits.resize(NestedLoopCount);
  6951. Built.FinalsConditions.resize(NestedLoopCount);
  6952. {
  6953. // We implement the following algorithm for obtaining the
  6954. // original loop iteration variable values based on the
  6955. // value of the collapsed loop iteration variable IV.
  6956. //
  6957. // Let n+1 be the number of collapsed loops in the nest.
  6958. // Iteration variables (I0, I1, .... In)
  6959. // Iteration counts (N0, N1, ... Nn)
  6960. //
  6961. // Acc = IV;
  6962. //
  6963. // To compute Ik for loop k, 0 <= k <= n, generate:
  6964. // Prod = N(k+1) * N(k+2) * ... * Nn;
  6965. // Ik = Acc / Prod;
  6966. // Acc -= Ik * Prod;
  6967. //
  6968. ExprResult Acc = IV;
  6969. for (unsigned int Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
  6970. LoopIterationSpace &IS = IterSpaces[Cnt];
  6971. SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
  6972. ExprResult Iter;
  6973. // Compute prod
  6974. ExprResult Prod =
  6975. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
  6976. for (unsigned int K = Cnt+1; K < NestedLoopCount; ++K)
  6977. Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Prod.get(),
  6978. IterSpaces[K].NumIterations);
  6979. // Iter = Acc / Prod
  6980. // If there is at least one more inner loop to avoid
  6981. // multiplication by 1.
  6982. if (Cnt + 1 < NestedLoopCount)
  6983. Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div,
  6984. Acc.get(), Prod.get());
  6985. else
  6986. Iter = Acc;
  6987. if (!Iter.isUsable()) {
  6988. HasErrors = true;
  6989. break;
  6990. }
  6991. // Update Acc:
  6992. // Acc -= Iter * Prod
  6993. // Check if there is at least one more inner loop to avoid
  6994. // multiplication by 1.
  6995. if (Cnt + 1 < NestedLoopCount)
  6996. Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul,
  6997. Iter.get(), Prod.get());
  6998. else
  6999. Prod = Iter;
  7000. Acc = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Sub,
  7001. Acc.get(), Prod.get());
  7002. // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
  7003. auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
  7004. DeclRefExpr *CounterVar = buildDeclRefExpr(
  7005. SemaRef, VD, IS.CounterVar->getType(), IS.CounterVar->getExprLoc(),
  7006. /*RefersToCapture=*/true);
  7007. ExprResult Init =
  7008. buildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
  7009. IS.CounterInit, IS.IsNonRectangularLB, Captures);
  7010. if (!Init.isUsable()) {
  7011. HasErrors = true;
  7012. break;
  7013. }
  7014. ExprResult Update = buildCounterUpdate(
  7015. SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
  7016. IS.CounterStep, IS.Subtract, IS.IsNonRectangularLB, &Captures);
  7017. if (!Update.isUsable()) {
  7018. HasErrors = true;
  7019. break;
  7020. }
  7021. // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
  7022. ExprResult Final =
  7023. buildCounterUpdate(SemaRef, CurScope, UpdLoc, CounterVar,
  7024. IS.CounterInit, IS.NumIterations, IS.CounterStep,
  7025. IS.Subtract, IS.IsNonRectangularLB, &Captures);
  7026. if (!Final.isUsable()) {
  7027. HasErrors = true;
  7028. break;
  7029. }
  7030. if (!Update.isUsable() || !Final.isUsable()) {
  7031. HasErrors = true;
  7032. break;
  7033. }
  7034. // Save results
  7035. Built.Counters[Cnt] = IS.CounterVar;
  7036. Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
  7037. Built.Inits[Cnt] = Init.get();
  7038. Built.Updates[Cnt] = Update.get();
  7039. Built.Finals[Cnt] = Final.get();
  7040. Built.DependentCounters[Cnt] = nullptr;
  7041. Built.DependentInits[Cnt] = nullptr;
  7042. Built.FinalsConditions[Cnt] = nullptr;
  7043. if (IS.IsNonRectangularLB || IS.IsNonRectangularUB) {
  7044. Built.DependentCounters[Cnt] =
  7045. Built.Counters[NestedLoopCount - 1 - IS.LoopDependentIdx];
  7046. Built.DependentInits[Cnt] =
  7047. Built.Inits[NestedLoopCount - 1 - IS.LoopDependentIdx];
  7048. Built.FinalsConditions[Cnt] = IS.FinalCondition;
  7049. }
  7050. }
  7051. }
  7052. if (HasErrors)
  7053. return 0;
  7054. // Save results
  7055. Built.IterationVarRef = IV.get();
  7056. Built.LastIteration = LastIteration.get();
  7057. Built.NumIterations = NumIterations.get();
  7058. Built.CalcLastIteration = SemaRef
  7059. .ActOnFinishFullExpr(CalcLastIteration.get(),
  7060. /*DiscardedValue=*/false)
  7061. .get();
  7062. Built.PreCond = PreCond.get();
  7063. Built.PreInits = buildPreInits(C, Captures);
  7064. Built.Cond = Cond.get();
  7065. Built.Init = Init.get();
  7066. Built.Inc = Inc.get();
  7067. Built.LB = LB.get();
  7068. Built.UB = UB.get();
  7069. Built.IL = IL.get();
  7070. Built.ST = ST.get();
  7071. Built.EUB = EUB.get();
  7072. Built.NLB = NextLB.get();
  7073. Built.NUB = NextUB.get();
  7074. Built.PrevLB = PrevLB.get();
  7075. Built.PrevUB = PrevUB.get();
  7076. Built.DistInc = DistInc.get();
  7077. Built.PrevEUB = PrevEUB.get();
  7078. Built.DistCombinedFields.LB = CombLB.get();
  7079. Built.DistCombinedFields.UB = CombUB.get();
  7080. Built.DistCombinedFields.EUB = CombEUB.get();
  7081. Built.DistCombinedFields.Init = CombInit.get();
  7082. Built.DistCombinedFields.Cond = CombCond.get();
  7083. Built.DistCombinedFields.NLB = CombNextLB.get();
  7084. Built.DistCombinedFields.NUB = CombNextUB.get();
  7085. Built.DistCombinedFields.DistCond = CombDistCond.get();
  7086. Built.DistCombinedFields.ParForInDistCond = ParForInDistCond.get();
  7087. return NestedLoopCount;
  7088. }
  7089. static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
  7090. auto CollapseClauses =
  7091. OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
  7092. if (CollapseClauses.begin() != CollapseClauses.end())
  7093. return (*CollapseClauses.begin())->getNumForLoops();
  7094. return nullptr;
  7095. }
  7096. static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
  7097. auto OrderedClauses =
  7098. OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
  7099. if (OrderedClauses.begin() != OrderedClauses.end())
  7100. return (*OrderedClauses.begin())->getNumForLoops();
  7101. return nullptr;
  7102. }
  7103. static bool checkSimdlenSafelenSpecified(Sema &S,
  7104. const ArrayRef<OMPClause *> Clauses) {
  7105. const OMPSafelenClause *Safelen = nullptr;
  7106. const OMPSimdlenClause *Simdlen = nullptr;
  7107. for (const OMPClause *Clause : Clauses) {
  7108. if (Clause->getClauseKind() == OMPC_safelen)
  7109. Safelen = cast<OMPSafelenClause>(Clause);
  7110. else if (Clause->getClauseKind() == OMPC_simdlen)
  7111. Simdlen = cast<OMPSimdlenClause>(Clause);
  7112. if (Safelen && Simdlen)
  7113. break;
  7114. }
  7115. if (Simdlen && Safelen) {
  7116. const Expr *SimdlenLength = Simdlen->getSimdlen();
  7117. const Expr *SafelenLength = Safelen->getSafelen();
  7118. if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
  7119. SimdlenLength->isInstantiationDependent() ||
  7120. SimdlenLength->containsUnexpandedParameterPack())
  7121. return false;
  7122. if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
  7123. SafelenLength->isInstantiationDependent() ||
  7124. SafelenLength->containsUnexpandedParameterPack())
  7125. return false;
  7126. Expr::EvalResult SimdlenResult, SafelenResult;
  7127. SimdlenLength->EvaluateAsInt(SimdlenResult, S.Context);
  7128. SafelenLength->EvaluateAsInt(SafelenResult, S.Context);
  7129. llvm::APSInt SimdlenRes = SimdlenResult.Val.getInt();
  7130. llvm::APSInt SafelenRes = SafelenResult.Val.getInt();
  7131. // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
  7132. // If both simdlen and safelen clauses are specified, the value of the
  7133. // simdlen parameter must be less than or equal to the value of the safelen
  7134. // parameter.
  7135. if (SimdlenRes > SafelenRes) {
  7136. S.Diag(SimdlenLength->getExprLoc(),
  7137. diag::err_omp_wrong_simdlen_safelen_values)
  7138. << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
  7139. return true;
  7140. }
  7141. }
  7142. return false;
  7143. }
  7144. StmtResult
  7145. Sema::ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
  7146. SourceLocation StartLoc, SourceLocation EndLoc,
  7147. VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  7148. if (!AStmt)
  7149. return StmtError();
  7150. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  7151. OMPLoopDirective::HelperExprs B;
  7152. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  7153. // define the nested loops number.
  7154. unsigned NestedLoopCount = checkOpenMPLoop(
  7155. OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
  7156. AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
  7157. if (NestedLoopCount == 0)
  7158. return StmtError();
  7159. assert((CurContext->isDependentContext() || B.builtAll()) &&
  7160. "omp simd loop exprs were not built");
  7161. if (!CurContext->isDependentContext()) {
  7162. // Finalize the clauses that need pre-built expressions for CodeGen.
  7163. for (OMPClause *C : Clauses) {
  7164. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  7165. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  7166. B.NumIterations, *this, CurScope,
  7167. DSAStack))
  7168. return StmtError();
  7169. }
  7170. }
  7171. if (checkSimdlenSafelenSpecified(*this, Clauses))
  7172. return StmtError();
  7173. setFunctionHasBranchProtectedScope();
  7174. return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
  7175. Clauses, AStmt, B);
  7176. }
  7177. StmtResult
  7178. Sema::ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
  7179. SourceLocation StartLoc, SourceLocation EndLoc,
  7180. VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  7181. if (!AStmt)
  7182. return StmtError();
  7183. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  7184. OMPLoopDirective::HelperExprs B;
  7185. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  7186. // define the nested loops number.
  7187. unsigned NestedLoopCount = checkOpenMPLoop(
  7188. OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
  7189. AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
  7190. if (NestedLoopCount == 0)
  7191. return StmtError();
  7192. assert((CurContext->isDependentContext() || B.builtAll()) &&
  7193. "omp for loop exprs were not built");
  7194. if (!CurContext->isDependentContext()) {
  7195. // Finalize the clauses that need pre-built expressions for CodeGen.
  7196. for (OMPClause *C : Clauses) {
  7197. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  7198. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  7199. B.NumIterations, *this, CurScope,
  7200. DSAStack))
  7201. return StmtError();
  7202. }
  7203. }
  7204. setFunctionHasBranchProtectedScope();
  7205. return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
  7206. Clauses, AStmt, B, DSAStack->isCancelRegion());
  7207. }
  7208. StmtResult Sema::ActOnOpenMPForSimdDirective(
  7209. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  7210. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  7211. if (!AStmt)
  7212. return StmtError();
  7213. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  7214. OMPLoopDirective::HelperExprs B;
  7215. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  7216. // define the nested loops number.
  7217. unsigned NestedLoopCount =
  7218. checkOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
  7219. getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
  7220. VarsWithImplicitDSA, B);
  7221. if (NestedLoopCount == 0)
  7222. return StmtError();
  7223. assert((CurContext->isDependentContext() || B.builtAll()) &&
  7224. "omp for simd loop exprs were not built");
  7225. if (!CurContext->isDependentContext()) {
  7226. // Finalize the clauses that need pre-built expressions for CodeGen.
  7227. for (OMPClause *C : Clauses) {
  7228. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  7229. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  7230. B.NumIterations, *this, CurScope,
  7231. DSAStack))
  7232. return StmtError();
  7233. }
  7234. }
  7235. if (checkSimdlenSafelenSpecified(*this, Clauses))
  7236. return StmtError();
  7237. setFunctionHasBranchProtectedScope();
  7238. return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
  7239. Clauses, AStmt, B);
  7240. }
  7241. StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
  7242. Stmt *AStmt,
  7243. SourceLocation StartLoc,
  7244. SourceLocation EndLoc) {
  7245. if (!AStmt)
  7246. return StmtError();
  7247. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  7248. auto BaseStmt = AStmt;
  7249. while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
  7250. BaseStmt = CS->getCapturedStmt();
  7251. if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
  7252. auto S = C->children();
  7253. if (S.begin() == S.end())
  7254. return StmtError();
  7255. // All associated statements must be '#pragma omp section' except for
  7256. // the first one.
  7257. for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
  7258. if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
  7259. if (SectionStmt)
  7260. Diag(SectionStmt->getBeginLoc(),
  7261. diag::err_omp_sections_substmt_not_section);
  7262. return StmtError();
  7263. }
  7264. cast<OMPSectionDirective>(SectionStmt)
  7265. ->setHasCancel(DSAStack->isCancelRegion());
  7266. }
  7267. } else {
  7268. Diag(AStmt->getBeginLoc(), diag::err_omp_sections_not_compound_stmt);
  7269. return StmtError();
  7270. }
  7271. setFunctionHasBranchProtectedScope();
  7272. return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
  7273. DSAStack->isCancelRegion());
  7274. }
  7275. StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
  7276. SourceLocation StartLoc,
  7277. SourceLocation EndLoc) {
  7278. if (!AStmt)
  7279. return StmtError();
  7280. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  7281. setFunctionHasBranchProtectedScope();
  7282. DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
  7283. return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
  7284. DSAStack->isCancelRegion());
  7285. }
  7286. StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
  7287. Stmt *AStmt,
  7288. SourceLocation StartLoc,
  7289. SourceLocation EndLoc) {
  7290. if (!AStmt)
  7291. return StmtError();
  7292. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  7293. setFunctionHasBranchProtectedScope();
  7294. // OpenMP [2.7.3, single Construct, Restrictions]
  7295. // The copyprivate clause must not be used with the nowait clause.
  7296. const OMPClause *Nowait = nullptr;
  7297. const OMPClause *Copyprivate = nullptr;
  7298. for (const OMPClause *Clause : Clauses) {
  7299. if (Clause->getClauseKind() == OMPC_nowait)
  7300. Nowait = Clause;
  7301. else if (Clause->getClauseKind() == OMPC_copyprivate)
  7302. Copyprivate = Clause;
  7303. if (Copyprivate && Nowait) {
  7304. Diag(Copyprivate->getBeginLoc(),
  7305. diag::err_omp_single_copyprivate_with_nowait);
  7306. Diag(Nowait->getBeginLoc(), diag::note_omp_nowait_clause_here);
  7307. return StmtError();
  7308. }
  7309. }
  7310. return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
  7311. }
  7312. StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
  7313. SourceLocation StartLoc,
  7314. SourceLocation EndLoc) {
  7315. if (!AStmt)
  7316. return StmtError();
  7317. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  7318. setFunctionHasBranchProtectedScope();
  7319. return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
  7320. }
  7321. StmtResult Sema::ActOnOpenMPCriticalDirective(
  7322. const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
  7323. Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
  7324. if (!AStmt)
  7325. return StmtError();
  7326. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  7327. bool ErrorFound = false;
  7328. llvm::APSInt Hint;
  7329. SourceLocation HintLoc;
  7330. bool DependentHint = false;
  7331. for (const OMPClause *C : Clauses) {
  7332. if (C->getClauseKind() == OMPC_hint) {
  7333. if (!DirName.getName()) {
  7334. Diag(C->getBeginLoc(), diag::err_omp_hint_clause_no_name);
  7335. ErrorFound = true;
  7336. }
  7337. Expr *E = cast<OMPHintClause>(C)->getHint();
  7338. if (E->isTypeDependent() || E->isValueDependent() ||
  7339. E->isInstantiationDependent()) {
  7340. DependentHint = true;
  7341. } else {
  7342. Hint = E->EvaluateKnownConstInt(Context);
  7343. HintLoc = C->getBeginLoc();
  7344. }
  7345. }
  7346. }
  7347. if (ErrorFound)
  7348. return StmtError();
  7349. const auto Pair = DSAStack->getCriticalWithHint(DirName);
  7350. if (Pair.first && DirName.getName() && !DependentHint) {
  7351. if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
  7352. Diag(StartLoc, diag::err_omp_critical_with_hint);
  7353. if (HintLoc.isValid())
  7354. Diag(HintLoc, diag::note_omp_critical_hint_here)
  7355. << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
  7356. else
  7357. Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
  7358. if (const auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
  7359. Diag(C->getBeginLoc(), diag::note_omp_critical_hint_here)
  7360. << 1
  7361. << C->getHint()->EvaluateKnownConstInt(Context).toString(
  7362. /*Radix=*/10, /*Signed=*/false);
  7363. } else {
  7364. Diag(Pair.first->getBeginLoc(), diag::note_omp_critical_no_hint) << 1;
  7365. }
  7366. }
  7367. }
  7368. setFunctionHasBranchProtectedScope();
  7369. auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
  7370. Clauses, AStmt);
  7371. if (!Pair.first && DirName.getName() && !DependentHint)
  7372. DSAStack->addCriticalWithHint(Dir, Hint);
  7373. return Dir;
  7374. }
  7375. StmtResult Sema::ActOnOpenMPParallelForDirective(
  7376. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  7377. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  7378. if (!AStmt)
  7379. return StmtError();
  7380. auto *CS = cast<CapturedStmt>(AStmt);
  7381. // 1.2.2 OpenMP Language Terminology
  7382. // Structured block - An executable statement with a single entry at the
  7383. // top and a single exit at the bottom.
  7384. // The point of exit cannot be a branch out of the structured block.
  7385. // longjmp() and throw() must not violate the entry/exit criteria.
  7386. CS->getCapturedDecl()->setNothrow();
  7387. OMPLoopDirective::HelperExprs B;
  7388. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  7389. // define the nested loops number.
  7390. unsigned NestedLoopCount =
  7391. checkOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
  7392. getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
  7393. VarsWithImplicitDSA, B);
  7394. if (NestedLoopCount == 0)
  7395. return StmtError();
  7396. assert((CurContext->isDependentContext() || B.builtAll()) &&
  7397. "omp parallel for loop exprs were not built");
  7398. if (!CurContext->isDependentContext()) {
  7399. // Finalize the clauses that need pre-built expressions for CodeGen.
  7400. for (OMPClause *C : Clauses) {
  7401. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  7402. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  7403. B.NumIterations, *this, CurScope,
  7404. DSAStack))
  7405. return StmtError();
  7406. }
  7407. }
  7408. setFunctionHasBranchProtectedScope();
  7409. return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
  7410. NestedLoopCount, Clauses, AStmt, B,
  7411. DSAStack->isCancelRegion());
  7412. }
  7413. StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
  7414. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  7415. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  7416. if (!AStmt)
  7417. return StmtError();
  7418. auto *CS = cast<CapturedStmt>(AStmt);
  7419. // 1.2.2 OpenMP Language Terminology
  7420. // Structured block - An executable statement with a single entry at the
  7421. // top and a single exit at the bottom.
  7422. // The point of exit cannot be a branch out of the structured block.
  7423. // longjmp() and throw() must not violate the entry/exit criteria.
  7424. CS->getCapturedDecl()->setNothrow();
  7425. OMPLoopDirective::HelperExprs B;
  7426. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  7427. // define the nested loops number.
  7428. unsigned NestedLoopCount =
  7429. checkOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
  7430. getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
  7431. VarsWithImplicitDSA, B);
  7432. if (NestedLoopCount == 0)
  7433. return StmtError();
  7434. if (!CurContext->isDependentContext()) {
  7435. // Finalize the clauses that need pre-built expressions for CodeGen.
  7436. for (OMPClause *C : Clauses) {
  7437. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  7438. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  7439. B.NumIterations, *this, CurScope,
  7440. DSAStack))
  7441. return StmtError();
  7442. }
  7443. }
  7444. if (checkSimdlenSafelenSpecified(*this, Clauses))
  7445. return StmtError();
  7446. setFunctionHasBranchProtectedScope();
  7447. return OMPParallelForSimdDirective::Create(
  7448. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  7449. }
  7450. StmtResult
  7451. Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
  7452. Stmt *AStmt, SourceLocation StartLoc,
  7453. SourceLocation EndLoc) {
  7454. if (!AStmt)
  7455. return StmtError();
  7456. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  7457. auto BaseStmt = AStmt;
  7458. while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
  7459. BaseStmt = CS->getCapturedStmt();
  7460. if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
  7461. auto S = C->children();
  7462. if (S.begin() == S.end())
  7463. return StmtError();
  7464. // All associated statements must be '#pragma omp section' except for
  7465. // the first one.
  7466. for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
  7467. if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
  7468. if (SectionStmt)
  7469. Diag(SectionStmt->getBeginLoc(),
  7470. diag::err_omp_parallel_sections_substmt_not_section);
  7471. return StmtError();
  7472. }
  7473. cast<OMPSectionDirective>(SectionStmt)
  7474. ->setHasCancel(DSAStack->isCancelRegion());
  7475. }
  7476. } else {
  7477. Diag(AStmt->getBeginLoc(),
  7478. diag::err_omp_parallel_sections_not_compound_stmt);
  7479. return StmtError();
  7480. }
  7481. setFunctionHasBranchProtectedScope();
  7482. return OMPParallelSectionsDirective::Create(
  7483. Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
  7484. }
  7485. StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
  7486. Stmt *AStmt, SourceLocation StartLoc,
  7487. SourceLocation EndLoc) {
  7488. if (!AStmt)
  7489. return StmtError();
  7490. auto *CS = cast<CapturedStmt>(AStmt);
  7491. // 1.2.2 OpenMP Language Terminology
  7492. // Structured block - An executable statement with a single entry at the
  7493. // top and a single exit at the bottom.
  7494. // The point of exit cannot be a branch out of the structured block.
  7495. // longjmp() and throw() must not violate the entry/exit criteria.
  7496. CS->getCapturedDecl()->setNothrow();
  7497. setFunctionHasBranchProtectedScope();
  7498. return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
  7499. DSAStack->isCancelRegion());
  7500. }
  7501. StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
  7502. SourceLocation EndLoc) {
  7503. return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
  7504. }
  7505. StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
  7506. SourceLocation EndLoc) {
  7507. return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
  7508. }
  7509. StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
  7510. SourceLocation EndLoc) {
  7511. return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
  7512. }
  7513. StmtResult Sema::ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
  7514. Stmt *AStmt,
  7515. SourceLocation StartLoc,
  7516. SourceLocation EndLoc) {
  7517. if (!AStmt)
  7518. return StmtError();
  7519. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  7520. setFunctionHasBranchProtectedScope();
  7521. return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, Clauses,
  7522. AStmt,
  7523. DSAStack->getTaskgroupReductionRef());
  7524. }
  7525. StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
  7526. SourceLocation StartLoc,
  7527. SourceLocation EndLoc) {
  7528. assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
  7529. return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
  7530. }
  7531. StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
  7532. Stmt *AStmt,
  7533. SourceLocation StartLoc,
  7534. SourceLocation EndLoc) {
  7535. const OMPClause *DependFound = nullptr;
  7536. const OMPClause *DependSourceClause = nullptr;
  7537. const OMPClause *DependSinkClause = nullptr;
  7538. bool ErrorFound = false;
  7539. const OMPThreadsClause *TC = nullptr;
  7540. const OMPSIMDClause *SC = nullptr;
  7541. for (const OMPClause *C : Clauses) {
  7542. if (auto *DC = dyn_cast<OMPDependClause>(C)) {
  7543. DependFound = C;
  7544. if (DC->getDependencyKind() == OMPC_DEPEND_source) {
  7545. if (DependSourceClause) {
  7546. Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
  7547. << getOpenMPDirectiveName(OMPD_ordered)
  7548. << getOpenMPClauseName(OMPC_depend) << 2;
  7549. ErrorFound = true;
  7550. } else {
  7551. DependSourceClause = C;
  7552. }
  7553. if (DependSinkClause) {
  7554. Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
  7555. << 0;
  7556. ErrorFound = true;
  7557. }
  7558. } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
  7559. if (DependSourceClause) {
  7560. Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
  7561. << 1;
  7562. ErrorFound = true;
  7563. }
  7564. DependSinkClause = C;
  7565. }
  7566. } else if (C->getClauseKind() == OMPC_threads) {
  7567. TC = cast<OMPThreadsClause>(C);
  7568. } else if (C->getClauseKind() == OMPC_simd) {
  7569. SC = cast<OMPSIMDClause>(C);
  7570. }
  7571. }
  7572. if (!ErrorFound && !SC &&
  7573. isOpenMPSimdDirective(DSAStack->getParentDirective())) {
  7574. // OpenMP [2.8.1,simd Construct, Restrictions]
  7575. // An ordered construct with the simd clause is the only OpenMP construct
  7576. // that can appear in the simd region.
  7577. Diag(StartLoc, diag::err_omp_prohibited_region_simd);
  7578. ErrorFound = true;
  7579. } else if (DependFound && (TC || SC)) {
  7580. Diag(DependFound->getBeginLoc(), diag::err_omp_depend_clause_thread_simd)
  7581. << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
  7582. ErrorFound = true;
  7583. } else if (DependFound && !DSAStack->getParentOrderedRegionParam().first) {
  7584. Diag(DependFound->getBeginLoc(),
  7585. diag::err_omp_ordered_directive_without_param);
  7586. ErrorFound = true;
  7587. } else if (TC || Clauses.empty()) {
  7588. if (const Expr *Param = DSAStack->getParentOrderedRegionParam().first) {
  7589. SourceLocation ErrLoc = TC ? TC->getBeginLoc() : StartLoc;
  7590. Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
  7591. << (TC != nullptr);
  7592. Diag(Param->getBeginLoc(), diag::note_omp_ordered_param);
  7593. ErrorFound = true;
  7594. }
  7595. }
  7596. if ((!AStmt && !DependFound) || ErrorFound)
  7597. return StmtError();
  7598. if (AStmt) {
  7599. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  7600. setFunctionHasBranchProtectedScope();
  7601. }
  7602. return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
  7603. }
  7604. namespace {
  7605. /// Helper class for checking expression in 'omp atomic [update]'
  7606. /// construct.
  7607. class OpenMPAtomicUpdateChecker {
  7608. /// Error results for atomic update expressions.
  7609. enum ExprAnalysisErrorCode {
  7610. /// A statement is not an expression statement.
  7611. NotAnExpression,
  7612. /// Expression is not builtin binary or unary operation.
  7613. NotABinaryOrUnaryExpression,
  7614. /// Unary operation is not post-/pre- increment/decrement operation.
  7615. NotAnUnaryIncDecExpression,
  7616. /// An expression is not of scalar type.
  7617. NotAScalarType,
  7618. /// A binary operation is not an assignment operation.
  7619. NotAnAssignmentOp,
  7620. /// RHS part of the binary operation is not a binary expression.
  7621. NotABinaryExpression,
  7622. /// RHS part is not additive/multiplicative/shift/biwise binary
  7623. /// expression.
  7624. NotABinaryOperator,
  7625. /// RHS binary operation does not have reference to the updated LHS
  7626. /// part.
  7627. NotAnUpdateExpression,
  7628. /// No errors is found.
  7629. NoError
  7630. };
  7631. /// Reference to Sema.
  7632. Sema &SemaRef;
  7633. /// A location for note diagnostics (when error is found).
  7634. SourceLocation NoteLoc;
  7635. /// 'x' lvalue part of the source atomic expression.
  7636. Expr *X;
  7637. /// 'expr' rvalue part of the source atomic expression.
  7638. Expr *E;
  7639. /// Helper expression of the form
  7640. /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
  7641. /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
  7642. Expr *UpdateExpr;
  7643. /// Is 'x' a LHS in a RHS part of full update expression. It is
  7644. /// important for non-associative operations.
  7645. bool IsXLHSInRHSPart;
  7646. BinaryOperatorKind Op;
  7647. SourceLocation OpLoc;
  7648. /// true if the source expression is a postfix unary operation, false
  7649. /// if it is a prefix unary operation.
  7650. bool IsPostfixUpdate;
  7651. public:
  7652. OpenMPAtomicUpdateChecker(Sema &SemaRef)
  7653. : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
  7654. IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
  7655. /// Check specified statement that it is suitable for 'atomic update'
  7656. /// constructs and extract 'x', 'expr' and Operation from the original
  7657. /// expression. If DiagId and NoteId == 0, then only check is performed
  7658. /// without error notification.
  7659. /// \param DiagId Diagnostic which should be emitted if error is found.
  7660. /// \param NoteId Diagnostic note for the main error message.
  7661. /// \return true if statement is not an update expression, false otherwise.
  7662. bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
  7663. /// Return the 'x' lvalue part of the source atomic expression.
  7664. Expr *getX() const { return X; }
  7665. /// Return the 'expr' rvalue part of the source atomic expression.
  7666. Expr *getExpr() const { return E; }
  7667. /// Return the update expression used in calculation of the updated
  7668. /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
  7669. /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
  7670. Expr *getUpdateExpr() const { return UpdateExpr; }
  7671. /// Return true if 'x' is LHS in RHS part of full update expression,
  7672. /// false otherwise.
  7673. bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
  7674. /// true if the source expression is a postfix unary operation, false
  7675. /// if it is a prefix unary operation.
  7676. bool isPostfixUpdate() const { return IsPostfixUpdate; }
  7677. private:
  7678. bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
  7679. unsigned NoteId = 0);
  7680. };
  7681. } // namespace
  7682. bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
  7683. BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
  7684. ExprAnalysisErrorCode ErrorFound = NoError;
  7685. SourceLocation ErrorLoc, NoteLoc;
  7686. SourceRange ErrorRange, NoteRange;
  7687. // Allowed constructs are:
  7688. // x = x binop expr;
  7689. // x = expr binop x;
  7690. if (AtomicBinOp->getOpcode() == BO_Assign) {
  7691. X = AtomicBinOp->getLHS();
  7692. if (const auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
  7693. AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
  7694. if (AtomicInnerBinOp->isMultiplicativeOp() ||
  7695. AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
  7696. AtomicInnerBinOp->isBitwiseOp()) {
  7697. Op = AtomicInnerBinOp->getOpcode();
  7698. OpLoc = AtomicInnerBinOp->getOperatorLoc();
  7699. Expr *LHS = AtomicInnerBinOp->getLHS();
  7700. Expr *RHS = AtomicInnerBinOp->getRHS();
  7701. llvm::FoldingSetNodeID XId, LHSId, RHSId;
  7702. X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
  7703. /*Canonical=*/true);
  7704. LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
  7705. /*Canonical=*/true);
  7706. RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
  7707. /*Canonical=*/true);
  7708. if (XId == LHSId) {
  7709. E = RHS;
  7710. IsXLHSInRHSPart = true;
  7711. } else if (XId == RHSId) {
  7712. E = LHS;
  7713. IsXLHSInRHSPart = false;
  7714. } else {
  7715. ErrorLoc = AtomicInnerBinOp->getExprLoc();
  7716. ErrorRange = AtomicInnerBinOp->getSourceRange();
  7717. NoteLoc = X->getExprLoc();
  7718. NoteRange = X->getSourceRange();
  7719. ErrorFound = NotAnUpdateExpression;
  7720. }
  7721. } else {
  7722. ErrorLoc = AtomicInnerBinOp->getExprLoc();
  7723. ErrorRange = AtomicInnerBinOp->getSourceRange();
  7724. NoteLoc = AtomicInnerBinOp->getOperatorLoc();
  7725. NoteRange = SourceRange(NoteLoc, NoteLoc);
  7726. ErrorFound = NotABinaryOperator;
  7727. }
  7728. } else {
  7729. NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
  7730. NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
  7731. ErrorFound = NotABinaryExpression;
  7732. }
  7733. } else {
  7734. ErrorLoc = AtomicBinOp->getExprLoc();
  7735. ErrorRange = AtomicBinOp->getSourceRange();
  7736. NoteLoc = AtomicBinOp->getOperatorLoc();
  7737. NoteRange = SourceRange(NoteLoc, NoteLoc);
  7738. ErrorFound = NotAnAssignmentOp;
  7739. }
  7740. if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
  7741. SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
  7742. SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
  7743. return true;
  7744. }
  7745. if (SemaRef.CurContext->isDependentContext())
  7746. E = X = UpdateExpr = nullptr;
  7747. return ErrorFound != NoError;
  7748. }
  7749. bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
  7750. unsigned NoteId) {
  7751. ExprAnalysisErrorCode ErrorFound = NoError;
  7752. SourceLocation ErrorLoc, NoteLoc;
  7753. SourceRange ErrorRange, NoteRange;
  7754. // Allowed constructs are:
  7755. // x++;
  7756. // x--;
  7757. // ++x;
  7758. // --x;
  7759. // x binop= expr;
  7760. // x = x binop expr;
  7761. // x = expr binop x;
  7762. if (auto *AtomicBody = dyn_cast<Expr>(S)) {
  7763. AtomicBody = AtomicBody->IgnoreParenImpCasts();
  7764. if (AtomicBody->getType()->isScalarType() ||
  7765. AtomicBody->isInstantiationDependent()) {
  7766. if (const auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
  7767. AtomicBody->IgnoreParenImpCasts())) {
  7768. // Check for Compound Assignment Operation
  7769. Op = BinaryOperator::getOpForCompoundAssignment(
  7770. AtomicCompAssignOp->getOpcode());
  7771. OpLoc = AtomicCompAssignOp->getOperatorLoc();
  7772. E = AtomicCompAssignOp->getRHS();
  7773. X = AtomicCompAssignOp->getLHS()->IgnoreParens();
  7774. IsXLHSInRHSPart = true;
  7775. } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
  7776. AtomicBody->IgnoreParenImpCasts())) {
  7777. // Check for Binary Operation
  7778. if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
  7779. return true;
  7780. } else if (const auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
  7781. AtomicBody->IgnoreParenImpCasts())) {
  7782. // Check for Unary Operation
  7783. if (AtomicUnaryOp->isIncrementDecrementOp()) {
  7784. IsPostfixUpdate = AtomicUnaryOp->isPostfix();
  7785. Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
  7786. OpLoc = AtomicUnaryOp->getOperatorLoc();
  7787. X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
  7788. E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
  7789. IsXLHSInRHSPart = true;
  7790. } else {
  7791. ErrorFound = NotAnUnaryIncDecExpression;
  7792. ErrorLoc = AtomicUnaryOp->getExprLoc();
  7793. ErrorRange = AtomicUnaryOp->getSourceRange();
  7794. NoteLoc = AtomicUnaryOp->getOperatorLoc();
  7795. NoteRange = SourceRange(NoteLoc, NoteLoc);
  7796. }
  7797. } else if (!AtomicBody->isInstantiationDependent()) {
  7798. ErrorFound = NotABinaryOrUnaryExpression;
  7799. NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
  7800. NoteRange = ErrorRange = AtomicBody->getSourceRange();
  7801. }
  7802. } else {
  7803. ErrorFound = NotAScalarType;
  7804. NoteLoc = ErrorLoc = AtomicBody->getBeginLoc();
  7805. NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
  7806. }
  7807. } else {
  7808. ErrorFound = NotAnExpression;
  7809. NoteLoc = ErrorLoc = S->getBeginLoc();
  7810. NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
  7811. }
  7812. if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
  7813. SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
  7814. SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
  7815. return true;
  7816. }
  7817. if (SemaRef.CurContext->isDependentContext())
  7818. E = X = UpdateExpr = nullptr;
  7819. if (ErrorFound == NoError && E && X) {
  7820. // Build an update expression of form 'OpaqueValueExpr(x) binop
  7821. // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
  7822. // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
  7823. auto *OVEX = new (SemaRef.getASTContext())
  7824. OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
  7825. auto *OVEExpr = new (SemaRef.getASTContext())
  7826. OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
  7827. ExprResult Update =
  7828. SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
  7829. IsXLHSInRHSPart ? OVEExpr : OVEX);
  7830. if (Update.isInvalid())
  7831. return true;
  7832. Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
  7833. Sema::AA_Casting);
  7834. if (Update.isInvalid())
  7835. return true;
  7836. UpdateExpr = Update.get();
  7837. }
  7838. return ErrorFound != NoError;
  7839. }
  7840. StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
  7841. Stmt *AStmt,
  7842. SourceLocation StartLoc,
  7843. SourceLocation EndLoc) {
  7844. if (!AStmt)
  7845. return StmtError();
  7846. auto *CS = cast<CapturedStmt>(AStmt);
  7847. // 1.2.2 OpenMP Language Terminology
  7848. // Structured block - An executable statement with a single entry at the
  7849. // top and a single exit at the bottom.
  7850. // The point of exit cannot be a branch out of the structured block.
  7851. // longjmp() and throw() must not violate the entry/exit criteria.
  7852. OpenMPClauseKind AtomicKind = OMPC_unknown;
  7853. SourceLocation AtomicKindLoc;
  7854. for (const OMPClause *C : Clauses) {
  7855. if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
  7856. C->getClauseKind() == OMPC_update ||
  7857. C->getClauseKind() == OMPC_capture) {
  7858. if (AtomicKind != OMPC_unknown) {
  7859. Diag(C->getBeginLoc(), diag::err_omp_atomic_several_clauses)
  7860. << SourceRange(C->getBeginLoc(), C->getEndLoc());
  7861. Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
  7862. << getOpenMPClauseName(AtomicKind);
  7863. } else {
  7864. AtomicKind = C->getClauseKind();
  7865. AtomicKindLoc = C->getBeginLoc();
  7866. }
  7867. }
  7868. }
  7869. Stmt *Body = CS->getCapturedStmt();
  7870. if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
  7871. Body = EWC->getSubExpr();
  7872. Expr *X = nullptr;
  7873. Expr *V = nullptr;
  7874. Expr *E = nullptr;
  7875. Expr *UE = nullptr;
  7876. bool IsXLHSInRHSPart = false;
  7877. bool IsPostfixUpdate = false;
  7878. // OpenMP [2.12.6, atomic Construct]
  7879. // In the next expressions:
  7880. // * x and v (as applicable) are both l-value expressions with scalar type.
  7881. // * During the execution of an atomic region, multiple syntactic
  7882. // occurrences of x must designate the same storage location.
  7883. // * Neither of v and expr (as applicable) may access the storage location
  7884. // designated by x.
  7885. // * Neither of x and expr (as applicable) may access the storage location
  7886. // designated by v.
  7887. // * expr is an expression with scalar type.
  7888. // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
  7889. // * binop, binop=, ++, and -- are not overloaded operators.
  7890. // * The expression x binop expr must be numerically equivalent to x binop
  7891. // (expr). This requirement is satisfied if the operators in expr have
  7892. // precedence greater than binop, or by using parentheses around expr or
  7893. // subexpressions of expr.
  7894. // * The expression expr binop x must be numerically equivalent to (expr)
  7895. // binop x. This requirement is satisfied if the operators in expr have
  7896. // precedence equal to or greater than binop, or by using parentheses around
  7897. // expr or subexpressions of expr.
  7898. // * For forms that allow multiple occurrences of x, the number of times
  7899. // that x is evaluated is unspecified.
  7900. if (AtomicKind == OMPC_read) {
  7901. enum {
  7902. NotAnExpression,
  7903. NotAnAssignmentOp,
  7904. NotAScalarType,
  7905. NotAnLValue,
  7906. NoError
  7907. } ErrorFound = NoError;
  7908. SourceLocation ErrorLoc, NoteLoc;
  7909. SourceRange ErrorRange, NoteRange;
  7910. // If clause is read:
  7911. // v = x;
  7912. if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
  7913. const auto *AtomicBinOp =
  7914. dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
  7915. if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
  7916. X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
  7917. V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
  7918. if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
  7919. (V->isInstantiationDependent() || V->getType()->isScalarType())) {
  7920. if (!X->isLValue() || !V->isLValue()) {
  7921. const Expr *NotLValueExpr = X->isLValue() ? V : X;
  7922. ErrorFound = NotAnLValue;
  7923. ErrorLoc = AtomicBinOp->getExprLoc();
  7924. ErrorRange = AtomicBinOp->getSourceRange();
  7925. NoteLoc = NotLValueExpr->getExprLoc();
  7926. NoteRange = NotLValueExpr->getSourceRange();
  7927. }
  7928. } else if (!X->isInstantiationDependent() ||
  7929. !V->isInstantiationDependent()) {
  7930. const Expr *NotScalarExpr =
  7931. (X->isInstantiationDependent() || X->getType()->isScalarType())
  7932. ? V
  7933. : X;
  7934. ErrorFound = NotAScalarType;
  7935. ErrorLoc = AtomicBinOp->getExprLoc();
  7936. ErrorRange = AtomicBinOp->getSourceRange();
  7937. NoteLoc = NotScalarExpr->getExprLoc();
  7938. NoteRange = NotScalarExpr->getSourceRange();
  7939. }
  7940. } else if (!AtomicBody->isInstantiationDependent()) {
  7941. ErrorFound = NotAnAssignmentOp;
  7942. ErrorLoc = AtomicBody->getExprLoc();
  7943. ErrorRange = AtomicBody->getSourceRange();
  7944. NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
  7945. : AtomicBody->getExprLoc();
  7946. NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
  7947. : AtomicBody->getSourceRange();
  7948. }
  7949. } else {
  7950. ErrorFound = NotAnExpression;
  7951. NoteLoc = ErrorLoc = Body->getBeginLoc();
  7952. NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
  7953. }
  7954. if (ErrorFound != NoError) {
  7955. Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
  7956. << ErrorRange;
  7957. Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
  7958. << NoteRange;
  7959. return StmtError();
  7960. }
  7961. if (CurContext->isDependentContext())
  7962. V = X = nullptr;
  7963. } else if (AtomicKind == OMPC_write) {
  7964. enum {
  7965. NotAnExpression,
  7966. NotAnAssignmentOp,
  7967. NotAScalarType,
  7968. NotAnLValue,
  7969. NoError
  7970. } ErrorFound = NoError;
  7971. SourceLocation ErrorLoc, NoteLoc;
  7972. SourceRange ErrorRange, NoteRange;
  7973. // If clause is write:
  7974. // x = expr;
  7975. if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
  7976. const auto *AtomicBinOp =
  7977. dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
  7978. if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
  7979. X = AtomicBinOp->getLHS();
  7980. E = AtomicBinOp->getRHS();
  7981. if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
  7982. (E->isInstantiationDependent() || E->getType()->isScalarType())) {
  7983. if (!X->isLValue()) {
  7984. ErrorFound = NotAnLValue;
  7985. ErrorLoc = AtomicBinOp->getExprLoc();
  7986. ErrorRange = AtomicBinOp->getSourceRange();
  7987. NoteLoc = X->getExprLoc();
  7988. NoteRange = X->getSourceRange();
  7989. }
  7990. } else if (!X->isInstantiationDependent() ||
  7991. !E->isInstantiationDependent()) {
  7992. const Expr *NotScalarExpr =
  7993. (X->isInstantiationDependent() || X->getType()->isScalarType())
  7994. ? E
  7995. : X;
  7996. ErrorFound = NotAScalarType;
  7997. ErrorLoc = AtomicBinOp->getExprLoc();
  7998. ErrorRange = AtomicBinOp->getSourceRange();
  7999. NoteLoc = NotScalarExpr->getExprLoc();
  8000. NoteRange = NotScalarExpr->getSourceRange();
  8001. }
  8002. } else if (!AtomicBody->isInstantiationDependent()) {
  8003. ErrorFound = NotAnAssignmentOp;
  8004. ErrorLoc = AtomicBody->getExprLoc();
  8005. ErrorRange = AtomicBody->getSourceRange();
  8006. NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
  8007. : AtomicBody->getExprLoc();
  8008. NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
  8009. : AtomicBody->getSourceRange();
  8010. }
  8011. } else {
  8012. ErrorFound = NotAnExpression;
  8013. NoteLoc = ErrorLoc = Body->getBeginLoc();
  8014. NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
  8015. }
  8016. if (ErrorFound != NoError) {
  8017. Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
  8018. << ErrorRange;
  8019. Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
  8020. << NoteRange;
  8021. return StmtError();
  8022. }
  8023. if (CurContext->isDependentContext())
  8024. E = X = nullptr;
  8025. } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
  8026. // If clause is update:
  8027. // x++;
  8028. // x--;
  8029. // ++x;
  8030. // --x;
  8031. // x binop= expr;
  8032. // x = x binop expr;
  8033. // x = expr binop x;
  8034. OpenMPAtomicUpdateChecker Checker(*this);
  8035. if (Checker.checkStatement(
  8036. Body, (AtomicKind == OMPC_update)
  8037. ? diag::err_omp_atomic_update_not_expression_statement
  8038. : diag::err_omp_atomic_not_expression_statement,
  8039. diag::note_omp_atomic_update))
  8040. return StmtError();
  8041. if (!CurContext->isDependentContext()) {
  8042. E = Checker.getExpr();
  8043. X = Checker.getX();
  8044. UE = Checker.getUpdateExpr();
  8045. IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
  8046. }
  8047. } else if (AtomicKind == OMPC_capture) {
  8048. enum {
  8049. NotAnAssignmentOp,
  8050. NotACompoundStatement,
  8051. NotTwoSubstatements,
  8052. NotASpecificExpression,
  8053. NoError
  8054. } ErrorFound = NoError;
  8055. SourceLocation ErrorLoc, NoteLoc;
  8056. SourceRange ErrorRange, NoteRange;
  8057. if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
  8058. // If clause is a capture:
  8059. // v = x++;
  8060. // v = x--;
  8061. // v = ++x;
  8062. // v = --x;
  8063. // v = x binop= expr;
  8064. // v = x = x binop expr;
  8065. // v = x = expr binop x;
  8066. const auto *AtomicBinOp =
  8067. dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
  8068. if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
  8069. V = AtomicBinOp->getLHS();
  8070. Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
  8071. OpenMPAtomicUpdateChecker Checker(*this);
  8072. if (Checker.checkStatement(
  8073. Body, diag::err_omp_atomic_capture_not_expression_statement,
  8074. diag::note_omp_atomic_update))
  8075. return StmtError();
  8076. E = Checker.getExpr();
  8077. X = Checker.getX();
  8078. UE = Checker.getUpdateExpr();
  8079. IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
  8080. IsPostfixUpdate = Checker.isPostfixUpdate();
  8081. } else if (!AtomicBody->isInstantiationDependent()) {
  8082. ErrorLoc = AtomicBody->getExprLoc();
  8083. ErrorRange = AtomicBody->getSourceRange();
  8084. NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
  8085. : AtomicBody->getExprLoc();
  8086. NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
  8087. : AtomicBody->getSourceRange();
  8088. ErrorFound = NotAnAssignmentOp;
  8089. }
  8090. if (ErrorFound != NoError) {
  8091. Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
  8092. << ErrorRange;
  8093. Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
  8094. return StmtError();
  8095. }
  8096. if (CurContext->isDependentContext())
  8097. UE = V = E = X = nullptr;
  8098. } else {
  8099. // If clause is a capture:
  8100. // { v = x; x = expr; }
  8101. // { v = x; x++; }
  8102. // { v = x; x--; }
  8103. // { v = x; ++x; }
  8104. // { v = x; --x; }
  8105. // { v = x; x binop= expr; }
  8106. // { v = x; x = x binop expr; }
  8107. // { v = x; x = expr binop x; }
  8108. // { x++; v = x; }
  8109. // { x--; v = x; }
  8110. // { ++x; v = x; }
  8111. // { --x; v = x; }
  8112. // { x binop= expr; v = x; }
  8113. // { x = x binop expr; v = x; }
  8114. // { x = expr binop x; v = x; }
  8115. if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
  8116. // Check that this is { expr1; expr2; }
  8117. if (CS->size() == 2) {
  8118. Stmt *First = CS->body_front();
  8119. Stmt *Second = CS->body_back();
  8120. if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
  8121. First = EWC->getSubExpr()->IgnoreParenImpCasts();
  8122. if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
  8123. Second = EWC->getSubExpr()->IgnoreParenImpCasts();
  8124. // Need to find what subexpression is 'v' and what is 'x'.
  8125. OpenMPAtomicUpdateChecker Checker(*this);
  8126. bool IsUpdateExprFound = !Checker.checkStatement(Second);
  8127. BinaryOperator *BinOp = nullptr;
  8128. if (IsUpdateExprFound) {
  8129. BinOp = dyn_cast<BinaryOperator>(First);
  8130. IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
  8131. }
  8132. if (IsUpdateExprFound && !CurContext->isDependentContext()) {
  8133. // { v = x; x++; }
  8134. // { v = x; x--; }
  8135. // { v = x; ++x; }
  8136. // { v = x; --x; }
  8137. // { v = x; x binop= expr; }
  8138. // { v = x; x = x binop expr; }
  8139. // { v = x; x = expr binop x; }
  8140. // Check that the first expression has form v = x.
  8141. Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
  8142. llvm::FoldingSetNodeID XId, PossibleXId;
  8143. Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
  8144. PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
  8145. IsUpdateExprFound = XId == PossibleXId;
  8146. if (IsUpdateExprFound) {
  8147. V = BinOp->getLHS();
  8148. X = Checker.getX();
  8149. E = Checker.getExpr();
  8150. UE = Checker.getUpdateExpr();
  8151. IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
  8152. IsPostfixUpdate = true;
  8153. }
  8154. }
  8155. if (!IsUpdateExprFound) {
  8156. IsUpdateExprFound = !Checker.checkStatement(First);
  8157. BinOp = nullptr;
  8158. if (IsUpdateExprFound) {
  8159. BinOp = dyn_cast<BinaryOperator>(Second);
  8160. IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
  8161. }
  8162. if (IsUpdateExprFound && !CurContext->isDependentContext()) {
  8163. // { x++; v = x; }
  8164. // { x--; v = x; }
  8165. // { ++x; v = x; }
  8166. // { --x; v = x; }
  8167. // { x binop= expr; v = x; }
  8168. // { x = x binop expr; v = x; }
  8169. // { x = expr binop x; v = x; }
  8170. // Check that the second expression has form v = x.
  8171. Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
  8172. llvm::FoldingSetNodeID XId, PossibleXId;
  8173. Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
  8174. PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
  8175. IsUpdateExprFound = XId == PossibleXId;
  8176. if (IsUpdateExprFound) {
  8177. V = BinOp->getLHS();
  8178. X = Checker.getX();
  8179. E = Checker.getExpr();
  8180. UE = Checker.getUpdateExpr();
  8181. IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
  8182. IsPostfixUpdate = false;
  8183. }
  8184. }
  8185. }
  8186. if (!IsUpdateExprFound) {
  8187. // { v = x; x = expr; }
  8188. auto *FirstExpr = dyn_cast<Expr>(First);
  8189. auto *SecondExpr = dyn_cast<Expr>(Second);
  8190. if (!FirstExpr || !SecondExpr ||
  8191. !(FirstExpr->isInstantiationDependent() ||
  8192. SecondExpr->isInstantiationDependent())) {
  8193. auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
  8194. if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
  8195. ErrorFound = NotAnAssignmentOp;
  8196. NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
  8197. : First->getBeginLoc();
  8198. NoteRange = ErrorRange = FirstBinOp
  8199. ? FirstBinOp->getSourceRange()
  8200. : SourceRange(ErrorLoc, ErrorLoc);
  8201. } else {
  8202. auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
  8203. if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
  8204. ErrorFound = NotAnAssignmentOp;
  8205. NoteLoc = ErrorLoc = SecondBinOp
  8206. ? SecondBinOp->getOperatorLoc()
  8207. : Second->getBeginLoc();
  8208. NoteRange = ErrorRange =
  8209. SecondBinOp ? SecondBinOp->getSourceRange()
  8210. : SourceRange(ErrorLoc, ErrorLoc);
  8211. } else {
  8212. Expr *PossibleXRHSInFirst =
  8213. FirstBinOp->getRHS()->IgnoreParenImpCasts();
  8214. Expr *PossibleXLHSInSecond =
  8215. SecondBinOp->getLHS()->IgnoreParenImpCasts();
  8216. llvm::FoldingSetNodeID X1Id, X2Id;
  8217. PossibleXRHSInFirst->Profile(X1Id, Context,
  8218. /*Canonical=*/true);
  8219. PossibleXLHSInSecond->Profile(X2Id, Context,
  8220. /*Canonical=*/true);
  8221. IsUpdateExprFound = X1Id == X2Id;
  8222. if (IsUpdateExprFound) {
  8223. V = FirstBinOp->getLHS();
  8224. X = SecondBinOp->getLHS();
  8225. E = SecondBinOp->getRHS();
  8226. UE = nullptr;
  8227. IsXLHSInRHSPart = false;
  8228. IsPostfixUpdate = true;
  8229. } else {
  8230. ErrorFound = NotASpecificExpression;
  8231. ErrorLoc = FirstBinOp->getExprLoc();
  8232. ErrorRange = FirstBinOp->getSourceRange();
  8233. NoteLoc = SecondBinOp->getLHS()->getExprLoc();
  8234. NoteRange = SecondBinOp->getRHS()->getSourceRange();
  8235. }
  8236. }
  8237. }
  8238. }
  8239. }
  8240. } else {
  8241. NoteLoc = ErrorLoc = Body->getBeginLoc();
  8242. NoteRange = ErrorRange =
  8243. SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
  8244. ErrorFound = NotTwoSubstatements;
  8245. }
  8246. } else {
  8247. NoteLoc = ErrorLoc = Body->getBeginLoc();
  8248. NoteRange = ErrorRange =
  8249. SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
  8250. ErrorFound = NotACompoundStatement;
  8251. }
  8252. if (ErrorFound != NoError) {
  8253. Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
  8254. << ErrorRange;
  8255. Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
  8256. return StmtError();
  8257. }
  8258. if (CurContext->isDependentContext())
  8259. UE = V = E = X = nullptr;
  8260. }
  8261. }
  8262. setFunctionHasBranchProtectedScope();
  8263. return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
  8264. X, V, E, UE, IsXLHSInRHSPart,
  8265. IsPostfixUpdate);
  8266. }
  8267. StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
  8268. Stmt *AStmt,
  8269. SourceLocation StartLoc,
  8270. SourceLocation EndLoc) {
  8271. if (!AStmt)
  8272. return StmtError();
  8273. auto *CS = cast<CapturedStmt>(AStmt);
  8274. // 1.2.2 OpenMP Language Terminology
  8275. // Structured block - An executable statement with a single entry at the
  8276. // top and a single exit at the bottom.
  8277. // The point of exit cannot be a branch out of the structured block.
  8278. // longjmp() and throw() must not violate the entry/exit criteria.
  8279. CS->getCapturedDecl()->setNothrow();
  8280. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target);
  8281. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  8282. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  8283. // 1.2.2 OpenMP Language Terminology
  8284. // Structured block - An executable statement with a single entry at the
  8285. // top and a single exit at the bottom.
  8286. // The point of exit cannot be a branch out of the structured block.
  8287. // longjmp() and throw() must not violate the entry/exit criteria.
  8288. CS->getCapturedDecl()->setNothrow();
  8289. }
  8290. // OpenMP [2.16, Nesting of Regions]
  8291. // If specified, a teams construct must be contained within a target
  8292. // construct. That target construct must contain no statements or directives
  8293. // outside of the teams construct.
  8294. if (DSAStack->hasInnerTeamsRegion()) {
  8295. const Stmt *S = CS->IgnoreContainers(/*IgnoreCaptured=*/true);
  8296. bool OMPTeamsFound = true;
  8297. if (const auto *CS = dyn_cast<CompoundStmt>(S)) {
  8298. auto I = CS->body_begin();
  8299. while (I != CS->body_end()) {
  8300. const auto *OED = dyn_cast<OMPExecutableDirective>(*I);
  8301. if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind()) ||
  8302. OMPTeamsFound) {
  8303. OMPTeamsFound = false;
  8304. break;
  8305. }
  8306. ++I;
  8307. }
  8308. assert(I != CS->body_end() && "Not found statement");
  8309. S = *I;
  8310. } else {
  8311. const auto *OED = dyn_cast<OMPExecutableDirective>(S);
  8312. OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
  8313. }
  8314. if (!OMPTeamsFound) {
  8315. Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
  8316. Diag(DSAStack->getInnerTeamsRegionLoc(),
  8317. diag::note_omp_nested_teams_construct_here);
  8318. Diag(S->getBeginLoc(), diag::note_omp_nested_statement_here)
  8319. << isa<OMPExecutableDirective>(S);
  8320. return StmtError();
  8321. }
  8322. }
  8323. setFunctionHasBranchProtectedScope();
  8324. return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
  8325. }
  8326. StmtResult
  8327. Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
  8328. Stmt *AStmt, SourceLocation StartLoc,
  8329. SourceLocation EndLoc) {
  8330. if (!AStmt)
  8331. return StmtError();
  8332. auto *CS = cast<CapturedStmt>(AStmt);
  8333. // 1.2.2 OpenMP Language Terminology
  8334. // Structured block - An executable statement with a single entry at the
  8335. // top and a single exit at the bottom.
  8336. // The point of exit cannot be a branch out of the structured block.
  8337. // longjmp() and throw() must not violate the entry/exit criteria.
  8338. CS->getCapturedDecl()->setNothrow();
  8339. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel);
  8340. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  8341. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  8342. // 1.2.2 OpenMP Language Terminology
  8343. // Structured block - An executable statement with a single entry at the
  8344. // top and a single exit at the bottom.
  8345. // The point of exit cannot be a branch out of the structured block.
  8346. // longjmp() and throw() must not violate the entry/exit criteria.
  8347. CS->getCapturedDecl()->setNothrow();
  8348. }
  8349. setFunctionHasBranchProtectedScope();
  8350. return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
  8351. AStmt);
  8352. }
  8353. StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
  8354. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  8355. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  8356. if (!AStmt)
  8357. return StmtError();
  8358. auto *CS = cast<CapturedStmt>(AStmt);
  8359. // 1.2.2 OpenMP Language Terminology
  8360. // Structured block - An executable statement with a single entry at the
  8361. // top and a single exit at the bottom.
  8362. // The point of exit cannot be a branch out of the structured block.
  8363. // longjmp() and throw() must not violate the entry/exit criteria.
  8364. CS->getCapturedDecl()->setNothrow();
  8365. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
  8366. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  8367. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  8368. // 1.2.2 OpenMP Language Terminology
  8369. // Structured block - An executable statement with a single entry at the
  8370. // top and a single exit at the bottom.
  8371. // The point of exit cannot be a branch out of the structured block.
  8372. // longjmp() and throw() must not violate the entry/exit criteria.
  8373. CS->getCapturedDecl()->setNothrow();
  8374. }
  8375. OMPLoopDirective::HelperExprs B;
  8376. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  8377. // define the nested loops number.
  8378. unsigned NestedLoopCount =
  8379. checkOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
  8380. getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
  8381. VarsWithImplicitDSA, B);
  8382. if (NestedLoopCount == 0)
  8383. return StmtError();
  8384. assert((CurContext->isDependentContext() || B.builtAll()) &&
  8385. "omp target parallel for loop exprs were not built");
  8386. if (!CurContext->isDependentContext()) {
  8387. // Finalize the clauses that need pre-built expressions for CodeGen.
  8388. for (OMPClause *C : Clauses) {
  8389. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  8390. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  8391. B.NumIterations, *this, CurScope,
  8392. DSAStack))
  8393. return StmtError();
  8394. }
  8395. }
  8396. setFunctionHasBranchProtectedScope();
  8397. return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc,
  8398. NestedLoopCount, Clauses, AStmt,
  8399. B, DSAStack->isCancelRegion());
  8400. }
  8401. /// Check for existence of a map clause in the list of clauses.
  8402. static bool hasClauses(ArrayRef<OMPClause *> Clauses,
  8403. const OpenMPClauseKind K) {
  8404. return llvm::any_of(
  8405. Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; });
  8406. }
  8407. template <typename... Params>
  8408. static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K,
  8409. const Params... ClauseTypes) {
  8410. return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...);
  8411. }
  8412. StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
  8413. Stmt *AStmt,
  8414. SourceLocation StartLoc,
  8415. SourceLocation EndLoc) {
  8416. if (!AStmt)
  8417. return StmtError();
  8418. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  8419. // OpenMP [2.10.1, Restrictions, p. 97]
  8420. // At least one map clause must appear on the directive.
  8421. if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr)) {
  8422. Diag(StartLoc, diag::err_omp_no_clause_for_directive)
  8423. << "'map' or 'use_device_ptr'"
  8424. << getOpenMPDirectiveName(OMPD_target_data);
  8425. return StmtError();
  8426. }
  8427. setFunctionHasBranchProtectedScope();
  8428. return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
  8429. AStmt);
  8430. }
  8431. StmtResult
  8432. Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
  8433. SourceLocation StartLoc,
  8434. SourceLocation EndLoc, Stmt *AStmt) {
  8435. if (!AStmt)
  8436. return StmtError();
  8437. auto *CS = cast<CapturedStmt>(AStmt);
  8438. // 1.2.2 OpenMP Language Terminology
  8439. // Structured block - An executable statement with a single entry at the
  8440. // top and a single exit at the bottom.
  8441. // The point of exit cannot be a branch out of the structured block.
  8442. // longjmp() and throw() must not violate the entry/exit criteria.
  8443. CS->getCapturedDecl()->setNothrow();
  8444. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_enter_data);
  8445. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  8446. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  8447. // 1.2.2 OpenMP Language Terminology
  8448. // Structured block - An executable statement with a single entry at the
  8449. // top and a single exit at the bottom.
  8450. // The point of exit cannot be a branch out of the structured block.
  8451. // longjmp() and throw() must not violate the entry/exit criteria.
  8452. CS->getCapturedDecl()->setNothrow();
  8453. }
  8454. // OpenMP [2.10.2, Restrictions, p. 99]
  8455. // At least one map clause must appear on the directive.
  8456. if (!hasClauses(Clauses, OMPC_map)) {
  8457. Diag(StartLoc, diag::err_omp_no_clause_for_directive)
  8458. << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data);
  8459. return StmtError();
  8460. }
  8461. return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
  8462. AStmt);
  8463. }
  8464. StmtResult
  8465. Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
  8466. SourceLocation StartLoc,
  8467. SourceLocation EndLoc, Stmt *AStmt) {
  8468. if (!AStmt)
  8469. return StmtError();
  8470. auto *CS = cast<CapturedStmt>(AStmt);
  8471. // 1.2.2 OpenMP Language Terminology
  8472. // Structured block - An executable statement with a single entry at the
  8473. // top and a single exit at the bottom.
  8474. // The point of exit cannot be a branch out of the structured block.
  8475. // longjmp() and throw() must not violate the entry/exit criteria.
  8476. CS->getCapturedDecl()->setNothrow();
  8477. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_exit_data);
  8478. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  8479. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  8480. // 1.2.2 OpenMP Language Terminology
  8481. // Structured block - An executable statement with a single entry at the
  8482. // top and a single exit at the bottom.
  8483. // The point of exit cannot be a branch out of the structured block.
  8484. // longjmp() and throw() must not violate the entry/exit criteria.
  8485. CS->getCapturedDecl()->setNothrow();
  8486. }
  8487. // OpenMP [2.10.3, Restrictions, p. 102]
  8488. // At least one map clause must appear on the directive.
  8489. if (!hasClauses(Clauses, OMPC_map)) {
  8490. Diag(StartLoc, diag::err_omp_no_clause_for_directive)
  8491. << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data);
  8492. return StmtError();
  8493. }
  8494. return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
  8495. AStmt);
  8496. }
  8497. StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
  8498. SourceLocation StartLoc,
  8499. SourceLocation EndLoc,
  8500. Stmt *AStmt) {
  8501. if (!AStmt)
  8502. return StmtError();
  8503. auto *CS = cast<CapturedStmt>(AStmt);
  8504. // 1.2.2 OpenMP Language Terminology
  8505. // Structured block - An executable statement with a single entry at the
  8506. // top and a single exit at the bottom.
  8507. // The point of exit cannot be a branch out of the structured block.
  8508. // longjmp() and throw() must not violate the entry/exit criteria.
  8509. CS->getCapturedDecl()->setNothrow();
  8510. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_update);
  8511. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  8512. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  8513. // 1.2.2 OpenMP Language Terminology
  8514. // Structured block - An executable statement with a single entry at the
  8515. // top and a single exit at the bottom.
  8516. // The point of exit cannot be a branch out of the structured block.
  8517. // longjmp() and throw() must not violate the entry/exit criteria.
  8518. CS->getCapturedDecl()->setNothrow();
  8519. }
  8520. if (!hasClauses(Clauses, OMPC_to, OMPC_from)) {
  8521. Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
  8522. return StmtError();
  8523. }
  8524. return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses,
  8525. AStmt);
  8526. }
  8527. StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
  8528. Stmt *AStmt, SourceLocation StartLoc,
  8529. SourceLocation EndLoc) {
  8530. if (!AStmt)
  8531. return StmtError();
  8532. auto *CS = cast<CapturedStmt>(AStmt);
  8533. // 1.2.2 OpenMP Language Terminology
  8534. // Structured block - An executable statement with a single entry at the
  8535. // top and a single exit at the bottom.
  8536. // The point of exit cannot be a branch out of the structured block.
  8537. // longjmp() and throw() must not violate the entry/exit criteria.
  8538. CS->getCapturedDecl()->setNothrow();
  8539. setFunctionHasBranchProtectedScope();
  8540. DSAStack->setParentTeamsRegionLoc(StartLoc);
  8541. return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
  8542. }
  8543. StmtResult
  8544. Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
  8545. SourceLocation EndLoc,
  8546. OpenMPDirectiveKind CancelRegion) {
  8547. if (DSAStack->isParentNowaitRegion()) {
  8548. Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
  8549. return StmtError();
  8550. }
  8551. if (DSAStack->isParentOrderedRegion()) {
  8552. Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
  8553. return StmtError();
  8554. }
  8555. return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
  8556. CancelRegion);
  8557. }
  8558. StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
  8559. SourceLocation StartLoc,
  8560. SourceLocation EndLoc,
  8561. OpenMPDirectiveKind CancelRegion) {
  8562. if (DSAStack->isParentNowaitRegion()) {
  8563. Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
  8564. return StmtError();
  8565. }
  8566. if (DSAStack->isParentOrderedRegion()) {
  8567. Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
  8568. return StmtError();
  8569. }
  8570. DSAStack->setParentCancelRegion(/*Cancel=*/true);
  8571. return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
  8572. CancelRegion);
  8573. }
  8574. static bool checkGrainsizeNumTasksClauses(Sema &S,
  8575. ArrayRef<OMPClause *> Clauses) {
  8576. const OMPClause *PrevClause = nullptr;
  8577. bool ErrorFound = false;
  8578. for (const OMPClause *C : Clauses) {
  8579. if (C->getClauseKind() == OMPC_grainsize ||
  8580. C->getClauseKind() == OMPC_num_tasks) {
  8581. if (!PrevClause)
  8582. PrevClause = C;
  8583. else if (PrevClause->getClauseKind() != C->getClauseKind()) {
  8584. S.Diag(C->getBeginLoc(),
  8585. diag::err_omp_grainsize_num_tasks_mutually_exclusive)
  8586. << getOpenMPClauseName(C->getClauseKind())
  8587. << getOpenMPClauseName(PrevClause->getClauseKind());
  8588. S.Diag(PrevClause->getBeginLoc(),
  8589. diag::note_omp_previous_grainsize_num_tasks)
  8590. << getOpenMPClauseName(PrevClause->getClauseKind());
  8591. ErrorFound = true;
  8592. }
  8593. }
  8594. }
  8595. return ErrorFound;
  8596. }
  8597. static bool checkReductionClauseWithNogroup(Sema &S,
  8598. ArrayRef<OMPClause *> Clauses) {
  8599. const OMPClause *ReductionClause = nullptr;
  8600. const OMPClause *NogroupClause = nullptr;
  8601. for (const OMPClause *C : Clauses) {
  8602. if (C->getClauseKind() == OMPC_reduction) {
  8603. ReductionClause = C;
  8604. if (NogroupClause)
  8605. break;
  8606. continue;
  8607. }
  8608. if (C->getClauseKind() == OMPC_nogroup) {
  8609. NogroupClause = C;
  8610. if (ReductionClause)
  8611. break;
  8612. continue;
  8613. }
  8614. }
  8615. if (ReductionClause && NogroupClause) {
  8616. S.Diag(ReductionClause->getBeginLoc(), diag::err_omp_reduction_with_nogroup)
  8617. << SourceRange(NogroupClause->getBeginLoc(),
  8618. NogroupClause->getEndLoc());
  8619. return true;
  8620. }
  8621. return false;
  8622. }
  8623. StmtResult Sema::ActOnOpenMPTaskLoopDirective(
  8624. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  8625. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  8626. if (!AStmt)
  8627. return StmtError();
  8628. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  8629. OMPLoopDirective::HelperExprs B;
  8630. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  8631. // define the nested loops number.
  8632. unsigned NestedLoopCount =
  8633. checkOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
  8634. /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
  8635. VarsWithImplicitDSA, B);
  8636. if (NestedLoopCount == 0)
  8637. return StmtError();
  8638. assert((CurContext->isDependentContext() || B.builtAll()) &&
  8639. "omp for loop exprs were not built");
  8640. // OpenMP, [2.9.2 taskloop Construct, Restrictions]
  8641. // The grainsize clause and num_tasks clause are mutually exclusive and may
  8642. // not appear on the same taskloop directive.
  8643. if (checkGrainsizeNumTasksClauses(*this, Clauses))
  8644. return StmtError();
  8645. // OpenMP, [2.9.2 taskloop Construct, Restrictions]
  8646. // If a reduction clause is present on the taskloop directive, the nogroup
  8647. // clause must not be specified.
  8648. if (checkReductionClauseWithNogroup(*this, Clauses))
  8649. return StmtError();
  8650. setFunctionHasBranchProtectedScope();
  8651. return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
  8652. NestedLoopCount, Clauses, AStmt, B);
  8653. }
  8654. StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
  8655. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  8656. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  8657. if (!AStmt)
  8658. return StmtError();
  8659. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  8660. OMPLoopDirective::HelperExprs B;
  8661. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  8662. // define the nested loops number.
  8663. unsigned NestedLoopCount =
  8664. checkOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
  8665. /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
  8666. VarsWithImplicitDSA, B);
  8667. if (NestedLoopCount == 0)
  8668. return StmtError();
  8669. assert((CurContext->isDependentContext() || B.builtAll()) &&
  8670. "omp for loop exprs were not built");
  8671. if (!CurContext->isDependentContext()) {
  8672. // Finalize the clauses that need pre-built expressions for CodeGen.
  8673. for (OMPClause *C : Clauses) {
  8674. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  8675. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  8676. B.NumIterations, *this, CurScope,
  8677. DSAStack))
  8678. return StmtError();
  8679. }
  8680. }
  8681. // OpenMP, [2.9.2 taskloop Construct, Restrictions]
  8682. // The grainsize clause and num_tasks clause are mutually exclusive and may
  8683. // not appear on the same taskloop directive.
  8684. if (checkGrainsizeNumTasksClauses(*this, Clauses))
  8685. return StmtError();
  8686. // OpenMP, [2.9.2 taskloop Construct, Restrictions]
  8687. // If a reduction clause is present on the taskloop directive, the nogroup
  8688. // clause must not be specified.
  8689. if (checkReductionClauseWithNogroup(*this, Clauses))
  8690. return StmtError();
  8691. if (checkSimdlenSafelenSpecified(*this, Clauses))
  8692. return StmtError();
  8693. setFunctionHasBranchProtectedScope();
  8694. return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
  8695. NestedLoopCount, Clauses, AStmt, B);
  8696. }
  8697. StmtResult Sema::ActOnOpenMPDistributeDirective(
  8698. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  8699. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  8700. if (!AStmt)
  8701. return StmtError();
  8702. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  8703. OMPLoopDirective::HelperExprs B;
  8704. // In presence of clause 'collapse' with number of loops, it will
  8705. // define the nested loops number.
  8706. unsigned NestedLoopCount =
  8707. checkOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
  8708. nullptr /*ordered not a clause on distribute*/, AStmt,
  8709. *this, *DSAStack, VarsWithImplicitDSA, B);
  8710. if (NestedLoopCount == 0)
  8711. return StmtError();
  8712. assert((CurContext->isDependentContext() || B.builtAll()) &&
  8713. "omp for loop exprs were not built");
  8714. setFunctionHasBranchProtectedScope();
  8715. return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
  8716. NestedLoopCount, Clauses, AStmt, B);
  8717. }
  8718. StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
  8719. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  8720. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  8721. if (!AStmt)
  8722. return StmtError();
  8723. auto *CS = cast<CapturedStmt>(AStmt);
  8724. // 1.2.2 OpenMP Language Terminology
  8725. // Structured block - An executable statement with a single entry at the
  8726. // top and a single exit at the bottom.
  8727. // The point of exit cannot be a branch out of the structured block.
  8728. // longjmp() and throw() must not violate the entry/exit criteria.
  8729. CS->getCapturedDecl()->setNothrow();
  8730. for (int ThisCaptureLevel =
  8731. getOpenMPCaptureLevels(OMPD_distribute_parallel_for);
  8732. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  8733. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  8734. // 1.2.2 OpenMP Language Terminology
  8735. // Structured block - An executable statement with a single entry at the
  8736. // top and a single exit at the bottom.
  8737. // The point of exit cannot be a branch out of the structured block.
  8738. // longjmp() and throw() must not violate the entry/exit criteria.
  8739. CS->getCapturedDecl()->setNothrow();
  8740. }
  8741. OMPLoopDirective::HelperExprs B;
  8742. // In presence of clause 'collapse' with number of loops, it will
  8743. // define the nested loops number.
  8744. unsigned NestedLoopCount = checkOpenMPLoop(
  8745. OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
  8746. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  8747. VarsWithImplicitDSA, B);
  8748. if (NestedLoopCount == 0)
  8749. return StmtError();
  8750. assert((CurContext->isDependentContext() || B.builtAll()) &&
  8751. "omp for loop exprs were not built");
  8752. setFunctionHasBranchProtectedScope();
  8753. return OMPDistributeParallelForDirective::Create(
  8754. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
  8755. DSAStack->isCancelRegion());
  8756. }
  8757. StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
  8758. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  8759. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  8760. if (!AStmt)
  8761. return StmtError();
  8762. auto *CS = cast<CapturedStmt>(AStmt);
  8763. // 1.2.2 OpenMP Language Terminology
  8764. // Structured block - An executable statement with a single entry at the
  8765. // top and a single exit at the bottom.
  8766. // The point of exit cannot be a branch out of the structured block.
  8767. // longjmp() and throw() must not violate the entry/exit criteria.
  8768. CS->getCapturedDecl()->setNothrow();
  8769. for (int ThisCaptureLevel =
  8770. getOpenMPCaptureLevels(OMPD_distribute_parallel_for_simd);
  8771. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  8772. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  8773. // 1.2.2 OpenMP Language Terminology
  8774. // Structured block - An executable statement with a single entry at the
  8775. // top and a single exit at the bottom.
  8776. // The point of exit cannot be a branch out of the structured block.
  8777. // longjmp() and throw() must not violate the entry/exit criteria.
  8778. CS->getCapturedDecl()->setNothrow();
  8779. }
  8780. OMPLoopDirective::HelperExprs B;
  8781. // In presence of clause 'collapse' with number of loops, it will
  8782. // define the nested loops number.
  8783. unsigned NestedLoopCount = checkOpenMPLoop(
  8784. OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
  8785. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  8786. VarsWithImplicitDSA, B);
  8787. if (NestedLoopCount == 0)
  8788. return StmtError();
  8789. assert((CurContext->isDependentContext() || B.builtAll()) &&
  8790. "omp for loop exprs were not built");
  8791. if (!CurContext->isDependentContext()) {
  8792. // Finalize the clauses that need pre-built expressions for CodeGen.
  8793. for (OMPClause *C : Clauses) {
  8794. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  8795. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  8796. B.NumIterations, *this, CurScope,
  8797. DSAStack))
  8798. return StmtError();
  8799. }
  8800. }
  8801. if (checkSimdlenSafelenSpecified(*this, Clauses))
  8802. return StmtError();
  8803. setFunctionHasBranchProtectedScope();
  8804. return OMPDistributeParallelForSimdDirective::Create(
  8805. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  8806. }
  8807. StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
  8808. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  8809. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  8810. if (!AStmt)
  8811. return StmtError();
  8812. auto *CS = cast<CapturedStmt>(AStmt);
  8813. // 1.2.2 OpenMP Language Terminology
  8814. // Structured block - An executable statement with a single entry at the
  8815. // top and a single exit at the bottom.
  8816. // The point of exit cannot be a branch out of the structured block.
  8817. // longjmp() and throw() must not violate the entry/exit criteria.
  8818. CS->getCapturedDecl()->setNothrow();
  8819. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_distribute_simd);
  8820. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  8821. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  8822. // 1.2.2 OpenMP Language Terminology
  8823. // Structured block - An executable statement with a single entry at the
  8824. // top and a single exit at the bottom.
  8825. // The point of exit cannot be a branch out of the structured block.
  8826. // longjmp() and throw() must not violate the entry/exit criteria.
  8827. CS->getCapturedDecl()->setNothrow();
  8828. }
  8829. OMPLoopDirective::HelperExprs B;
  8830. // In presence of clause 'collapse' with number of loops, it will
  8831. // define the nested loops number.
  8832. unsigned NestedLoopCount =
  8833. checkOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
  8834. nullptr /*ordered not a clause on distribute*/, CS, *this,
  8835. *DSAStack, VarsWithImplicitDSA, B);
  8836. if (NestedLoopCount == 0)
  8837. return StmtError();
  8838. assert((CurContext->isDependentContext() || B.builtAll()) &&
  8839. "omp for loop exprs were not built");
  8840. if (!CurContext->isDependentContext()) {
  8841. // Finalize the clauses that need pre-built expressions for CodeGen.
  8842. for (OMPClause *C : Clauses) {
  8843. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  8844. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  8845. B.NumIterations, *this, CurScope,
  8846. DSAStack))
  8847. return StmtError();
  8848. }
  8849. }
  8850. if (checkSimdlenSafelenSpecified(*this, Clauses))
  8851. return StmtError();
  8852. setFunctionHasBranchProtectedScope();
  8853. return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
  8854. NestedLoopCount, Clauses, AStmt, B);
  8855. }
  8856. StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
  8857. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  8858. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  8859. if (!AStmt)
  8860. return StmtError();
  8861. auto *CS = cast<CapturedStmt>(AStmt);
  8862. // 1.2.2 OpenMP Language Terminology
  8863. // Structured block - An executable statement with a single entry at the
  8864. // top and a single exit at the bottom.
  8865. // The point of exit cannot be a branch out of the structured block.
  8866. // longjmp() and throw() must not violate the entry/exit criteria.
  8867. CS->getCapturedDecl()->setNothrow();
  8868. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
  8869. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  8870. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  8871. // 1.2.2 OpenMP Language Terminology
  8872. // Structured block - An executable statement with a single entry at the
  8873. // top and a single exit at the bottom.
  8874. // The point of exit cannot be a branch out of the structured block.
  8875. // longjmp() and throw() must not violate the entry/exit criteria.
  8876. CS->getCapturedDecl()->setNothrow();
  8877. }
  8878. OMPLoopDirective::HelperExprs B;
  8879. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  8880. // define the nested loops number.
  8881. unsigned NestedLoopCount = checkOpenMPLoop(
  8882. OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
  8883. getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
  8884. VarsWithImplicitDSA, B);
  8885. if (NestedLoopCount == 0)
  8886. return StmtError();
  8887. assert((CurContext->isDependentContext() || B.builtAll()) &&
  8888. "omp target parallel for simd loop exprs were not built");
  8889. if (!CurContext->isDependentContext()) {
  8890. // Finalize the clauses that need pre-built expressions for CodeGen.
  8891. for (OMPClause *C : Clauses) {
  8892. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  8893. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  8894. B.NumIterations, *this, CurScope,
  8895. DSAStack))
  8896. return StmtError();
  8897. }
  8898. }
  8899. if (checkSimdlenSafelenSpecified(*this, Clauses))
  8900. return StmtError();
  8901. setFunctionHasBranchProtectedScope();
  8902. return OMPTargetParallelForSimdDirective::Create(
  8903. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  8904. }
  8905. StmtResult Sema::ActOnOpenMPTargetSimdDirective(
  8906. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  8907. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  8908. if (!AStmt)
  8909. return StmtError();
  8910. auto *CS = cast<CapturedStmt>(AStmt);
  8911. // 1.2.2 OpenMP Language Terminology
  8912. // Structured block - An executable statement with a single entry at the
  8913. // top and a single exit at the bottom.
  8914. // The point of exit cannot be a branch out of the structured block.
  8915. // longjmp() and throw() must not violate the entry/exit criteria.
  8916. CS->getCapturedDecl()->setNothrow();
  8917. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_simd);
  8918. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  8919. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  8920. // 1.2.2 OpenMP Language Terminology
  8921. // Structured block - An executable statement with a single entry at the
  8922. // top and a single exit at the bottom.
  8923. // The point of exit cannot be a branch out of the structured block.
  8924. // longjmp() and throw() must not violate the entry/exit criteria.
  8925. CS->getCapturedDecl()->setNothrow();
  8926. }
  8927. OMPLoopDirective::HelperExprs B;
  8928. // In presence of clause 'collapse' with number of loops, it will define the
  8929. // nested loops number.
  8930. unsigned NestedLoopCount =
  8931. checkOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
  8932. getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
  8933. VarsWithImplicitDSA, B);
  8934. if (NestedLoopCount == 0)
  8935. return StmtError();
  8936. assert((CurContext->isDependentContext() || B.builtAll()) &&
  8937. "omp target simd loop exprs were not built");
  8938. if (!CurContext->isDependentContext()) {
  8939. // Finalize the clauses that need pre-built expressions for CodeGen.
  8940. for (OMPClause *C : Clauses) {
  8941. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  8942. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  8943. B.NumIterations, *this, CurScope,
  8944. DSAStack))
  8945. return StmtError();
  8946. }
  8947. }
  8948. if (checkSimdlenSafelenSpecified(*this, Clauses))
  8949. return StmtError();
  8950. setFunctionHasBranchProtectedScope();
  8951. return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
  8952. NestedLoopCount, Clauses, AStmt, B);
  8953. }
  8954. StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
  8955. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  8956. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  8957. if (!AStmt)
  8958. return StmtError();
  8959. auto *CS = cast<CapturedStmt>(AStmt);
  8960. // 1.2.2 OpenMP Language Terminology
  8961. // Structured block - An executable statement with a single entry at the
  8962. // top and a single exit at the bottom.
  8963. // The point of exit cannot be a branch out of the structured block.
  8964. // longjmp() and throw() must not violate the entry/exit criteria.
  8965. CS->getCapturedDecl()->setNothrow();
  8966. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_teams_distribute);
  8967. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  8968. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  8969. // 1.2.2 OpenMP Language Terminology
  8970. // Structured block - An executable statement with a single entry at the
  8971. // top and a single exit at the bottom.
  8972. // The point of exit cannot be a branch out of the structured block.
  8973. // longjmp() and throw() must not violate the entry/exit criteria.
  8974. CS->getCapturedDecl()->setNothrow();
  8975. }
  8976. OMPLoopDirective::HelperExprs B;
  8977. // In presence of clause 'collapse' with number of loops, it will
  8978. // define the nested loops number.
  8979. unsigned NestedLoopCount =
  8980. checkOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
  8981. nullptr /*ordered not a clause on distribute*/, CS, *this,
  8982. *DSAStack, VarsWithImplicitDSA, B);
  8983. if (NestedLoopCount == 0)
  8984. return StmtError();
  8985. assert((CurContext->isDependentContext() || B.builtAll()) &&
  8986. "omp teams distribute loop exprs were not built");
  8987. setFunctionHasBranchProtectedScope();
  8988. DSAStack->setParentTeamsRegionLoc(StartLoc);
  8989. return OMPTeamsDistributeDirective::Create(
  8990. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  8991. }
  8992. StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
  8993. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  8994. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  8995. if (!AStmt)
  8996. return StmtError();
  8997. auto *CS = cast<CapturedStmt>(AStmt);
  8998. // 1.2.2 OpenMP Language Terminology
  8999. // Structured block - An executable statement with a single entry at the
  9000. // top and a single exit at the bottom.
  9001. // The point of exit cannot be a branch out of the structured block.
  9002. // longjmp() and throw() must not violate the entry/exit criteria.
  9003. CS->getCapturedDecl()->setNothrow();
  9004. for (int ThisCaptureLevel =
  9005. getOpenMPCaptureLevels(OMPD_teams_distribute_simd);
  9006. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  9007. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  9008. // 1.2.2 OpenMP Language Terminology
  9009. // Structured block - An executable statement with a single entry at the
  9010. // top and a single exit at the bottom.
  9011. // The point of exit cannot be a branch out of the structured block.
  9012. // longjmp() and throw() must not violate the entry/exit criteria.
  9013. CS->getCapturedDecl()->setNothrow();
  9014. }
  9015. OMPLoopDirective::HelperExprs B;
  9016. // In presence of clause 'collapse' with number of loops, it will
  9017. // define the nested loops number.
  9018. unsigned NestedLoopCount = checkOpenMPLoop(
  9019. OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
  9020. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  9021. VarsWithImplicitDSA, B);
  9022. if (NestedLoopCount == 0)
  9023. return StmtError();
  9024. assert((CurContext->isDependentContext() || B.builtAll()) &&
  9025. "omp teams distribute simd loop exprs were not built");
  9026. if (!CurContext->isDependentContext()) {
  9027. // Finalize the clauses that need pre-built expressions for CodeGen.
  9028. for (OMPClause *C : Clauses) {
  9029. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  9030. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  9031. B.NumIterations, *this, CurScope,
  9032. DSAStack))
  9033. return StmtError();
  9034. }
  9035. }
  9036. if (checkSimdlenSafelenSpecified(*this, Clauses))
  9037. return StmtError();
  9038. setFunctionHasBranchProtectedScope();
  9039. DSAStack->setParentTeamsRegionLoc(StartLoc);
  9040. return OMPTeamsDistributeSimdDirective::Create(
  9041. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  9042. }
  9043. StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
  9044. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  9045. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  9046. if (!AStmt)
  9047. return StmtError();
  9048. auto *CS = cast<CapturedStmt>(AStmt);
  9049. // 1.2.2 OpenMP Language Terminology
  9050. // Structured block - An executable statement with a single entry at the
  9051. // top and a single exit at the bottom.
  9052. // The point of exit cannot be a branch out of the structured block.
  9053. // longjmp() and throw() must not violate the entry/exit criteria.
  9054. CS->getCapturedDecl()->setNothrow();
  9055. for (int ThisCaptureLevel =
  9056. getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for_simd);
  9057. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  9058. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  9059. // 1.2.2 OpenMP Language Terminology
  9060. // Structured block - An executable statement with a single entry at the
  9061. // top and a single exit at the bottom.
  9062. // The point of exit cannot be a branch out of the structured block.
  9063. // longjmp() and throw() must not violate the entry/exit criteria.
  9064. CS->getCapturedDecl()->setNothrow();
  9065. }
  9066. OMPLoopDirective::HelperExprs B;
  9067. // In presence of clause 'collapse' with number of loops, it will
  9068. // define the nested loops number.
  9069. unsigned NestedLoopCount = checkOpenMPLoop(
  9070. OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
  9071. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  9072. VarsWithImplicitDSA, B);
  9073. if (NestedLoopCount == 0)
  9074. return StmtError();
  9075. assert((CurContext->isDependentContext() || B.builtAll()) &&
  9076. "omp for loop exprs were not built");
  9077. if (!CurContext->isDependentContext()) {
  9078. // Finalize the clauses that need pre-built expressions for CodeGen.
  9079. for (OMPClause *C : Clauses) {
  9080. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  9081. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  9082. B.NumIterations, *this, CurScope,
  9083. DSAStack))
  9084. return StmtError();
  9085. }
  9086. }
  9087. if (checkSimdlenSafelenSpecified(*this, Clauses))
  9088. return StmtError();
  9089. setFunctionHasBranchProtectedScope();
  9090. DSAStack->setParentTeamsRegionLoc(StartLoc);
  9091. return OMPTeamsDistributeParallelForSimdDirective::Create(
  9092. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  9093. }
  9094. StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
  9095. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  9096. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  9097. if (!AStmt)
  9098. return StmtError();
  9099. auto *CS = cast<CapturedStmt>(AStmt);
  9100. // 1.2.2 OpenMP Language Terminology
  9101. // Structured block - An executable statement with a single entry at the
  9102. // top and a single exit at the bottom.
  9103. // The point of exit cannot be a branch out of the structured block.
  9104. // longjmp() and throw() must not violate the entry/exit criteria.
  9105. CS->getCapturedDecl()->setNothrow();
  9106. for (int ThisCaptureLevel =
  9107. getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for);
  9108. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  9109. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  9110. // 1.2.2 OpenMP Language Terminology
  9111. // Structured block - An executable statement with a single entry at the
  9112. // top and a single exit at the bottom.
  9113. // The point of exit cannot be a branch out of the structured block.
  9114. // longjmp() and throw() must not violate the entry/exit criteria.
  9115. CS->getCapturedDecl()->setNothrow();
  9116. }
  9117. OMPLoopDirective::HelperExprs B;
  9118. // In presence of clause 'collapse' with number of loops, it will
  9119. // define the nested loops number.
  9120. unsigned NestedLoopCount = checkOpenMPLoop(
  9121. OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
  9122. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  9123. VarsWithImplicitDSA, B);
  9124. if (NestedLoopCount == 0)
  9125. return StmtError();
  9126. assert((CurContext->isDependentContext() || B.builtAll()) &&
  9127. "omp for loop exprs were not built");
  9128. setFunctionHasBranchProtectedScope();
  9129. DSAStack->setParentTeamsRegionLoc(StartLoc);
  9130. return OMPTeamsDistributeParallelForDirective::Create(
  9131. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
  9132. DSAStack->isCancelRegion());
  9133. }
  9134. StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
  9135. Stmt *AStmt,
  9136. SourceLocation StartLoc,
  9137. SourceLocation EndLoc) {
  9138. if (!AStmt)
  9139. return StmtError();
  9140. auto *CS = cast<CapturedStmt>(AStmt);
  9141. // 1.2.2 OpenMP Language Terminology
  9142. // Structured block - An executable statement with a single entry at the
  9143. // top and a single exit at the bottom.
  9144. // The point of exit cannot be a branch out of the structured block.
  9145. // longjmp() and throw() must not violate the entry/exit criteria.
  9146. CS->getCapturedDecl()->setNothrow();
  9147. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_teams);
  9148. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  9149. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  9150. // 1.2.2 OpenMP Language Terminology
  9151. // Structured block - An executable statement with a single entry at the
  9152. // top and a single exit at the bottom.
  9153. // The point of exit cannot be a branch out of the structured block.
  9154. // longjmp() and throw() must not violate the entry/exit criteria.
  9155. CS->getCapturedDecl()->setNothrow();
  9156. }
  9157. setFunctionHasBranchProtectedScope();
  9158. return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
  9159. AStmt);
  9160. }
  9161. StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective(
  9162. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  9163. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  9164. if (!AStmt)
  9165. return StmtError();
  9166. auto *CS = cast<CapturedStmt>(AStmt);
  9167. // 1.2.2 OpenMP Language Terminology
  9168. // Structured block - An executable statement with a single entry at the
  9169. // top and a single exit at the bottom.
  9170. // The point of exit cannot be a branch out of the structured block.
  9171. // longjmp() and throw() must not violate the entry/exit criteria.
  9172. CS->getCapturedDecl()->setNothrow();
  9173. for (int ThisCaptureLevel =
  9174. getOpenMPCaptureLevels(OMPD_target_teams_distribute);
  9175. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  9176. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  9177. // 1.2.2 OpenMP Language Terminology
  9178. // Structured block - An executable statement with a single entry at the
  9179. // top and a single exit at the bottom.
  9180. // The point of exit cannot be a branch out of the structured block.
  9181. // longjmp() and throw() must not violate the entry/exit criteria.
  9182. CS->getCapturedDecl()->setNothrow();
  9183. }
  9184. OMPLoopDirective::HelperExprs B;
  9185. // In presence of clause 'collapse' with number of loops, it will
  9186. // define the nested loops number.
  9187. unsigned NestedLoopCount = checkOpenMPLoop(
  9188. OMPD_target_teams_distribute, getCollapseNumberExpr(Clauses),
  9189. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  9190. VarsWithImplicitDSA, B);
  9191. if (NestedLoopCount == 0)
  9192. return StmtError();
  9193. assert((CurContext->isDependentContext() || B.builtAll()) &&
  9194. "omp target teams distribute loop exprs were not built");
  9195. setFunctionHasBranchProtectedScope();
  9196. return OMPTargetTeamsDistributeDirective::Create(
  9197. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  9198. }
  9199. StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective(
  9200. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  9201. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  9202. if (!AStmt)
  9203. return StmtError();
  9204. auto *CS = cast<CapturedStmt>(AStmt);
  9205. // 1.2.2 OpenMP Language Terminology
  9206. // Structured block - An executable statement with a single entry at the
  9207. // top and a single exit at the bottom.
  9208. // The point of exit cannot be a branch out of the structured block.
  9209. // longjmp() and throw() must not violate the entry/exit criteria.
  9210. CS->getCapturedDecl()->setNothrow();
  9211. for (int ThisCaptureLevel =
  9212. getOpenMPCaptureLevels(OMPD_target_teams_distribute_parallel_for);
  9213. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  9214. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  9215. // 1.2.2 OpenMP Language Terminology
  9216. // Structured block - An executable statement with a single entry at the
  9217. // top and a single exit at the bottom.
  9218. // The point of exit cannot be a branch out of the structured block.
  9219. // longjmp() and throw() must not violate the entry/exit criteria.
  9220. CS->getCapturedDecl()->setNothrow();
  9221. }
  9222. OMPLoopDirective::HelperExprs B;
  9223. // In presence of clause 'collapse' with number of loops, it will
  9224. // define the nested loops number.
  9225. unsigned NestedLoopCount = checkOpenMPLoop(
  9226. OMPD_target_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
  9227. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  9228. VarsWithImplicitDSA, B);
  9229. if (NestedLoopCount == 0)
  9230. return StmtError();
  9231. assert((CurContext->isDependentContext() || B.builtAll()) &&
  9232. "omp target teams distribute parallel for loop exprs were not built");
  9233. if (!CurContext->isDependentContext()) {
  9234. // Finalize the clauses that need pre-built expressions for CodeGen.
  9235. for (OMPClause *C : Clauses) {
  9236. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  9237. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  9238. B.NumIterations, *this, CurScope,
  9239. DSAStack))
  9240. return StmtError();
  9241. }
  9242. }
  9243. setFunctionHasBranchProtectedScope();
  9244. return OMPTargetTeamsDistributeParallelForDirective::Create(
  9245. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
  9246. DSAStack->isCancelRegion());
  9247. }
  9248. StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
  9249. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  9250. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  9251. if (!AStmt)
  9252. return StmtError();
  9253. auto *CS = cast<CapturedStmt>(AStmt);
  9254. // 1.2.2 OpenMP Language Terminology
  9255. // Structured block - An executable statement with a single entry at the
  9256. // top and a single exit at the bottom.
  9257. // The point of exit cannot be a branch out of the structured block.
  9258. // longjmp() and throw() must not violate the entry/exit criteria.
  9259. CS->getCapturedDecl()->setNothrow();
  9260. for (int ThisCaptureLevel = getOpenMPCaptureLevels(
  9261. OMPD_target_teams_distribute_parallel_for_simd);
  9262. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  9263. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  9264. // 1.2.2 OpenMP Language Terminology
  9265. // Structured block - An executable statement with a single entry at the
  9266. // top and a single exit at the bottom.
  9267. // The point of exit cannot be a branch out of the structured block.
  9268. // longjmp() and throw() must not violate the entry/exit criteria.
  9269. CS->getCapturedDecl()->setNothrow();
  9270. }
  9271. OMPLoopDirective::HelperExprs B;
  9272. // In presence of clause 'collapse' with number of loops, it will
  9273. // define the nested loops number.
  9274. unsigned NestedLoopCount =
  9275. checkOpenMPLoop(OMPD_target_teams_distribute_parallel_for_simd,
  9276. getCollapseNumberExpr(Clauses),
  9277. nullptr /*ordered not a clause on distribute*/, CS, *this,
  9278. *DSAStack, VarsWithImplicitDSA, B);
  9279. if (NestedLoopCount == 0)
  9280. return StmtError();
  9281. assert((CurContext->isDependentContext() || B.builtAll()) &&
  9282. "omp target teams distribute parallel for simd loop exprs were not "
  9283. "built");
  9284. if (!CurContext->isDependentContext()) {
  9285. // Finalize the clauses that need pre-built expressions for CodeGen.
  9286. for (OMPClause *C : Clauses) {
  9287. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  9288. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  9289. B.NumIterations, *this, CurScope,
  9290. DSAStack))
  9291. return StmtError();
  9292. }
  9293. }
  9294. if (checkSimdlenSafelenSpecified(*this, Clauses))
  9295. return StmtError();
  9296. setFunctionHasBranchProtectedScope();
  9297. return OMPTargetTeamsDistributeParallelForSimdDirective::Create(
  9298. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  9299. }
  9300. StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective(
  9301. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  9302. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  9303. if (!AStmt)
  9304. return StmtError();
  9305. auto *CS = cast<CapturedStmt>(AStmt);
  9306. // 1.2.2 OpenMP Language Terminology
  9307. // Structured block - An executable statement with a single entry at the
  9308. // top and a single exit at the bottom.
  9309. // The point of exit cannot be a branch out of the structured block.
  9310. // longjmp() and throw() must not violate the entry/exit criteria.
  9311. CS->getCapturedDecl()->setNothrow();
  9312. for (int ThisCaptureLevel =
  9313. getOpenMPCaptureLevels(OMPD_target_teams_distribute_simd);
  9314. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  9315. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  9316. // 1.2.2 OpenMP Language Terminology
  9317. // Structured block - An executable statement with a single entry at the
  9318. // top and a single exit at the bottom.
  9319. // The point of exit cannot be a branch out of the structured block.
  9320. // longjmp() and throw() must not violate the entry/exit criteria.
  9321. CS->getCapturedDecl()->setNothrow();
  9322. }
  9323. OMPLoopDirective::HelperExprs B;
  9324. // In presence of clause 'collapse' with number of loops, it will
  9325. // define the nested loops number.
  9326. unsigned NestedLoopCount = checkOpenMPLoop(
  9327. OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses),
  9328. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  9329. VarsWithImplicitDSA, B);
  9330. if (NestedLoopCount == 0)
  9331. return StmtError();
  9332. assert((CurContext->isDependentContext() || B.builtAll()) &&
  9333. "omp target teams distribute simd loop exprs were not built");
  9334. if (!CurContext->isDependentContext()) {
  9335. // Finalize the clauses that need pre-built expressions for CodeGen.
  9336. for (OMPClause *C : Clauses) {
  9337. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  9338. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  9339. B.NumIterations, *this, CurScope,
  9340. DSAStack))
  9341. return StmtError();
  9342. }
  9343. }
  9344. if (checkSimdlenSafelenSpecified(*this, Clauses))
  9345. return StmtError();
  9346. setFunctionHasBranchProtectedScope();
  9347. return OMPTargetTeamsDistributeSimdDirective::Create(
  9348. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  9349. }
  9350. OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
  9351. SourceLocation StartLoc,
  9352. SourceLocation LParenLoc,
  9353. SourceLocation EndLoc) {
  9354. OMPClause *Res = nullptr;
  9355. switch (Kind) {
  9356. case OMPC_final:
  9357. Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
  9358. break;
  9359. case OMPC_num_threads:
  9360. Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
  9361. break;
  9362. case OMPC_safelen:
  9363. Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
  9364. break;
  9365. case OMPC_simdlen:
  9366. Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
  9367. break;
  9368. case OMPC_allocator:
  9369. Res = ActOnOpenMPAllocatorClause(Expr, StartLoc, LParenLoc, EndLoc);
  9370. break;
  9371. case OMPC_collapse:
  9372. Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
  9373. break;
  9374. case OMPC_ordered:
  9375. Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
  9376. break;
  9377. case OMPC_device:
  9378. Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
  9379. break;
  9380. case OMPC_num_teams:
  9381. Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
  9382. break;
  9383. case OMPC_thread_limit:
  9384. Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
  9385. break;
  9386. case OMPC_priority:
  9387. Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
  9388. break;
  9389. case OMPC_grainsize:
  9390. Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
  9391. break;
  9392. case OMPC_num_tasks:
  9393. Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
  9394. break;
  9395. case OMPC_hint:
  9396. Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
  9397. break;
  9398. case OMPC_if:
  9399. case OMPC_default:
  9400. case OMPC_proc_bind:
  9401. case OMPC_schedule:
  9402. case OMPC_private:
  9403. case OMPC_firstprivate:
  9404. case OMPC_lastprivate:
  9405. case OMPC_shared:
  9406. case OMPC_reduction:
  9407. case OMPC_task_reduction:
  9408. case OMPC_in_reduction:
  9409. case OMPC_linear:
  9410. case OMPC_aligned:
  9411. case OMPC_copyin:
  9412. case OMPC_copyprivate:
  9413. case OMPC_nowait:
  9414. case OMPC_untied:
  9415. case OMPC_mergeable:
  9416. case OMPC_threadprivate:
  9417. case OMPC_allocate:
  9418. case OMPC_flush:
  9419. case OMPC_read:
  9420. case OMPC_write:
  9421. case OMPC_update:
  9422. case OMPC_capture:
  9423. case OMPC_seq_cst:
  9424. case OMPC_depend:
  9425. case OMPC_threads:
  9426. case OMPC_simd:
  9427. case OMPC_map:
  9428. case OMPC_nogroup:
  9429. case OMPC_dist_schedule:
  9430. case OMPC_defaultmap:
  9431. case OMPC_unknown:
  9432. case OMPC_uniform:
  9433. case OMPC_to:
  9434. case OMPC_from:
  9435. case OMPC_use_device_ptr:
  9436. case OMPC_is_device_ptr:
  9437. case OMPC_unified_address:
  9438. case OMPC_unified_shared_memory:
  9439. case OMPC_reverse_offload:
  9440. case OMPC_dynamic_allocators:
  9441. case OMPC_atomic_default_mem_order:
  9442. case OMPC_device_type:
  9443. case OMPC_match:
  9444. llvm_unreachable("Clause is not allowed.");
  9445. }
  9446. return Res;
  9447. }
  9448. // An OpenMP directive such as 'target parallel' has two captured regions:
  9449. // for the 'target' and 'parallel' respectively. This function returns
  9450. // the region in which to capture expressions associated with a clause.
  9451. // A return value of OMPD_unknown signifies that the expression should not
  9452. // be captured.
  9453. static OpenMPDirectiveKind getOpenMPCaptureRegionForClause(
  9454. OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
  9455. OpenMPDirectiveKind NameModifier = OMPD_unknown) {
  9456. OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
  9457. switch (CKind) {
  9458. case OMPC_if:
  9459. switch (DKind) {
  9460. case OMPD_target_parallel:
  9461. case OMPD_target_parallel_for:
  9462. case OMPD_target_parallel_for_simd:
  9463. // If this clause applies to the nested 'parallel' region, capture within
  9464. // the 'target' region, otherwise do not capture.
  9465. if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
  9466. CaptureRegion = OMPD_target;
  9467. break;
  9468. case OMPD_target_teams_distribute_parallel_for:
  9469. case OMPD_target_teams_distribute_parallel_for_simd:
  9470. // If this clause applies to the nested 'parallel' region, capture within
  9471. // the 'teams' region, otherwise do not capture.
  9472. if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
  9473. CaptureRegion = OMPD_teams;
  9474. break;
  9475. case OMPD_teams_distribute_parallel_for:
  9476. case OMPD_teams_distribute_parallel_for_simd:
  9477. CaptureRegion = OMPD_teams;
  9478. break;
  9479. case OMPD_target_update:
  9480. case OMPD_target_enter_data:
  9481. case OMPD_target_exit_data:
  9482. CaptureRegion = OMPD_task;
  9483. break;
  9484. case OMPD_cancel:
  9485. case OMPD_parallel:
  9486. case OMPD_parallel_sections:
  9487. case OMPD_parallel_for:
  9488. case OMPD_parallel_for_simd:
  9489. case OMPD_target:
  9490. case OMPD_target_simd:
  9491. case OMPD_target_teams:
  9492. case OMPD_target_teams_distribute:
  9493. case OMPD_target_teams_distribute_simd:
  9494. case OMPD_distribute_parallel_for:
  9495. case OMPD_distribute_parallel_for_simd:
  9496. case OMPD_task:
  9497. case OMPD_taskloop:
  9498. case OMPD_taskloop_simd:
  9499. case OMPD_target_data:
  9500. // Do not capture if-clause expressions.
  9501. break;
  9502. case OMPD_threadprivate:
  9503. case OMPD_allocate:
  9504. case OMPD_taskyield:
  9505. case OMPD_barrier:
  9506. case OMPD_taskwait:
  9507. case OMPD_cancellation_point:
  9508. case OMPD_flush:
  9509. case OMPD_declare_reduction:
  9510. case OMPD_declare_mapper:
  9511. case OMPD_declare_simd:
  9512. case OMPD_declare_variant:
  9513. case OMPD_declare_target:
  9514. case OMPD_end_declare_target:
  9515. case OMPD_teams:
  9516. case OMPD_simd:
  9517. case OMPD_for:
  9518. case OMPD_for_simd:
  9519. case OMPD_sections:
  9520. case OMPD_section:
  9521. case OMPD_single:
  9522. case OMPD_master:
  9523. case OMPD_critical:
  9524. case OMPD_taskgroup:
  9525. case OMPD_distribute:
  9526. case OMPD_ordered:
  9527. case OMPD_atomic:
  9528. case OMPD_distribute_simd:
  9529. case OMPD_teams_distribute:
  9530. case OMPD_teams_distribute_simd:
  9531. case OMPD_requires:
  9532. llvm_unreachable("Unexpected OpenMP directive with if-clause");
  9533. case OMPD_unknown:
  9534. llvm_unreachable("Unknown OpenMP directive");
  9535. }
  9536. break;
  9537. case OMPC_num_threads:
  9538. switch (DKind) {
  9539. case OMPD_target_parallel:
  9540. case OMPD_target_parallel_for:
  9541. case OMPD_target_parallel_for_simd:
  9542. CaptureRegion = OMPD_target;
  9543. break;
  9544. case OMPD_teams_distribute_parallel_for:
  9545. case OMPD_teams_distribute_parallel_for_simd:
  9546. case OMPD_target_teams_distribute_parallel_for:
  9547. case OMPD_target_teams_distribute_parallel_for_simd:
  9548. CaptureRegion = OMPD_teams;
  9549. break;
  9550. case OMPD_parallel:
  9551. case OMPD_parallel_sections:
  9552. case OMPD_parallel_for:
  9553. case OMPD_parallel_for_simd:
  9554. case OMPD_distribute_parallel_for:
  9555. case OMPD_distribute_parallel_for_simd:
  9556. // Do not capture num_threads-clause expressions.
  9557. break;
  9558. case OMPD_target_data:
  9559. case OMPD_target_enter_data:
  9560. case OMPD_target_exit_data:
  9561. case OMPD_target_update:
  9562. case OMPD_target:
  9563. case OMPD_target_simd:
  9564. case OMPD_target_teams:
  9565. case OMPD_target_teams_distribute:
  9566. case OMPD_target_teams_distribute_simd:
  9567. case OMPD_cancel:
  9568. case OMPD_task:
  9569. case OMPD_taskloop:
  9570. case OMPD_taskloop_simd:
  9571. case OMPD_threadprivate:
  9572. case OMPD_allocate:
  9573. case OMPD_taskyield:
  9574. case OMPD_barrier:
  9575. case OMPD_taskwait:
  9576. case OMPD_cancellation_point:
  9577. case OMPD_flush:
  9578. case OMPD_declare_reduction:
  9579. case OMPD_declare_mapper:
  9580. case OMPD_declare_simd:
  9581. case OMPD_declare_variant:
  9582. case OMPD_declare_target:
  9583. case OMPD_end_declare_target:
  9584. case OMPD_teams:
  9585. case OMPD_simd:
  9586. case OMPD_for:
  9587. case OMPD_for_simd:
  9588. case OMPD_sections:
  9589. case OMPD_section:
  9590. case OMPD_single:
  9591. case OMPD_master:
  9592. case OMPD_critical:
  9593. case OMPD_taskgroup:
  9594. case OMPD_distribute:
  9595. case OMPD_ordered:
  9596. case OMPD_atomic:
  9597. case OMPD_distribute_simd:
  9598. case OMPD_teams_distribute:
  9599. case OMPD_teams_distribute_simd:
  9600. case OMPD_requires:
  9601. llvm_unreachable("Unexpected OpenMP directive with num_threads-clause");
  9602. case OMPD_unknown:
  9603. llvm_unreachable("Unknown OpenMP directive");
  9604. }
  9605. break;
  9606. case OMPC_num_teams:
  9607. switch (DKind) {
  9608. case OMPD_target_teams:
  9609. case OMPD_target_teams_distribute:
  9610. case OMPD_target_teams_distribute_simd:
  9611. case OMPD_target_teams_distribute_parallel_for:
  9612. case OMPD_target_teams_distribute_parallel_for_simd:
  9613. CaptureRegion = OMPD_target;
  9614. break;
  9615. case OMPD_teams_distribute_parallel_for:
  9616. case OMPD_teams_distribute_parallel_for_simd:
  9617. case OMPD_teams:
  9618. case OMPD_teams_distribute:
  9619. case OMPD_teams_distribute_simd:
  9620. // Do not capture num_teams-clause expressions.
  9621. break;
  9622. case OMPD_distribute_parallel_for:
  9623. case OMPD_distribute_parallel_for_simd:
  9624. case OMPD_task:
  9625. case OMPD_taskloop:
  9626. case OMPD_taskloop_simd:
  9627. case OMPD_target_data:
  9628. case OMPD_target_enter_data:
  9629. case OMPD_target_exit_data:
  9630. case OMPD_target_update:
  9631. case OMPD_cancel:
  9632. case OMPD_parallel:
  9633. case OMPD_parallel_sections:
  9634. case OMPD_parallel_for:
  9635. case OMPD_parallel_for_simd:
  9636. case OMPD_target:
  9637. case OMPD_target_simd:
  9638. case OMPD_target_parallel:
  9639. case OMPD_target_parallel_for:
  9640. case OMPD_target_parallel_for_simd:
  9641. case OMPD_threadprivate:
  9642. case OMPD_allocate:
  9643. case OMPD_taskyield:
  9644. case OMPD_barrier:
  9645. case OMPD_taskwait:
  9646. case OMPD_cancellation_point:
  9647. case OMPD_flush:
  9648. case OMPD_declare_reduction:
  9649. case OMPD_declare_mapper:
  9650. case OMPD_declare_simd:
  9651. case OMPD_declare_variant:
  9652. case OMPD_declare_target:
  9653. case OMPD_end_declare_target:
  9654. case OMPD_simd:
  9655. case OMPD_for:
  9656. case OMPD_for_simd:
  9657. case OMPD_sections:
  9658. case OMPD_section:
  9659. case OMPD_single:
  9660. case OMPD_master:
  9661. case OMPD_critical:
  9662. case OMPD_taskgroup:
  9663. case OMPD_distribute:
  9664. case OMPD_ordered:
  9665. case OMPD_atomic:
  9666. case OMPD_distribute_simd:
  9667. case OMPD_requires:
  9668. llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
  9669. case OMPD_unknown:
  9670. llvm_unreachable("Unknown OpenMP directive");
  9671. }
  9672. break;
  9673. case OMPC_thread_limit:
  9674. switch (DKind) {
  9675. case OMPD_target_teams:
  9676. case OMPD_target_teams_distribute:
  9677. case OMPD_target_teams_distribute_simd:
  9678. case OMPD_target_teams_distribute_parallel_for:
  9679. case OMPD_target_teams_distribute_parallel_for_simd:
  9680. CaptureRegion = OMPD_target;
  9681. break;
  9682. case OMPD_teams_distribute_parallel_for:
  9683. case OMPD_teams_distribute_parallel_for_simd:
  9684. case OMPD_teams:
  9685. case OMPD_teams_distribute:
  9686. case OMPD_teams_distribute_simd:
  9687. // Do not capture thread_limit-clause expressions.
  9688. break;
  9689. case OMPD_distribute_parallel_for:
  9690. case OMPD_distribute_parallel_for_simd:
  9691. case OMPD_task:
  9692. case OMPD_taskloop:
  9693. case OMPD_taskloop_simd:
  9694. case OMPD_target_data:
  9695. case OMPD_target_enter_data:
  9696. case OMPD_target_exit_data:
  9697. case OMPD_target_update:
  9698. case OMPD_cancel:
  9699. case OMPD_parallel:
  9700. case OMPD_parallel_sections:
  9701. case OMPD_parallel_for:
  9702. case OMPD_parallel_for_simd:
  9703. case OMPD_target:
  9704. case OMPD_target_simd:
  9705. case OMPD_target_parallel:
  9706. case OMPD_target_parallel_for:
  9707. case OMPD_target_parallel_for_simd:
  9708. case OMPD_threadprivate:
  9709. case OMPD_allocate:
  9710. case OMPD_taskyield:
  9711. case OMPD_barrier:
  9712. case OMPD_taskwait:
  9713. case OMPD_cancellation_point:
  9714. case OMPD_flush:
  9715. case OMPD_declare_reduction:
  9716. case OMPD_declare_mapper:
  9717. case OMPD_declare_simd:
  9718. case OMPD_declare_variant:
  9719. case OMPD_declare_target:
  9720. case OMPD_end_declare_target:
  9721. case OMPD_simd:
  9722. case OMPD_for:
  9723. case OMPD_for_simd:
  9724. case OMPD_sections:
  9725. case OMPD_section:
  9726. case OMPD_single:
  9727. case OMPD_master:
  9728. case OMPD_critical:
  9729. case OMPD_taskgroup:
  9730. case OMPD_distribute:
  9731. case OMPD_ordered:
  9732. case OMPD_atomic:
  9733. case OMPD_distribute_simd:
  9734. case OMPD_requires:
  9735. llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause");
  9736. case OMPD_unknown:
  9737. llvm_unreachable("Unknown OpenMP directive");
  9738. }
  9739. break;
  9740. case OMPC_schedule:
  9741. switch (DKind) {
  9742. case OMPD_parallel_for:
  9743. case OMPD_parallel_for_simd:
  9744. case OMPD_distribute_parallel_for:
  9745. case OMPD_distribute_parallel_for_simd:
  9746. case OMPD_teams_distribute_parallel_for:
  9747. case OMPD_teams_distribute_parallel_for_simd:
  9748. case OMPD_target_parallel_for:
  9749. case OMPD_target_parallel_for_simd:
  9750. case OMPD_target_teams_distribute_parallel_for:
  9751. case OMPD_target_teams_distribute_parallel_for_simd:
  9752. CaptureRegion = OMPD_parallel;
  9753. break;
  9754. case OMPD_for:
  9755. case OMPD_for_simd:
  9756. // Do not capture schedule-clause expressions.
  9757. break;
  9758. case OMPD_task:
  9759. case OMPD_taskloop:
  9760. case OMPD_taskloop_simd:
  9761. case OMPD_target_data:
  9762. case OMPD_target_enter_data:
  9763. case OMPD_target_exit_data:
  9764. case OMPD_target_update:
  9765. case OMPD_teams:
  9766. case OMPD_teams_distribute:
  9767. case OMPD_teams_distribute_simd:
  9768. case OMPD_target_teams_distribute:
  9769. case OMPD_target_teams_distribute_simd:
  9770. case OMPD_target:
  9771. case OMPD_target_simd:
  9772. case OMPD_target_parallel:
  9773. case OMPD_cancel:
  9774. case OMPD_parallel:
  9775. case OMPD_parallel_sections:
  9776. case OMPD_threadprivate:
  9777. case OMPD_allocate:
  9778. case OMPD_taskyield:
  9779. case OMPD_barrier:
  9780. case OMPD_taskwait:
  9781. case OMPD_cancellation_point:
  9782. case OMPD_flush:
  9783. case OMPD_declare_reduction:
  9784. case OMPD_declare_mapper:
  9785. case OMPD_declare_simd:
  9786. case OMPD_declare_variant:
  9787. case OMPD_declare_target:
  9788. case OMPD_end_declare_target:
  9789. case OMPD_simd:
  9790. case OMPD_sections:
  9791. case OMPD_section:
  9792. case OMPD_single:
  9793. case OMPD_master:
  9794. case OMPD_critical:
  9795. case OMPD_taskgroup:
  9796. case OMPD_distribute:
  9797. case OMPD_ordered:
  9798. case OMPD_atomic:
  9799. case OMPD_distribute_simd:
  9800. case OMPD_target_teams:
  9801. case OMPD_requires:
  9802. llvm_unreachable("Unexpected OpenMP directive with schedule clause");
  9803. case OMPD_unknown:
  9804. llvm_unreachable("Unknown OpenMP directive");
  9805. }
  9806. break;
  9807. case OMPC_dist_schedule:
  9808. switch (DKind) {
  9809. case OMPD_teams_distribute_parallel_for:
  9810. case OMPD_teams_distribute_parallel_for_simd:
  9811. case OMPD_teams_distribute:
  9812. case OMPD_teams_distribute_simd:
  9813. case OMPD_target_teams_distribute_parallel_for:
  9814. case OMPD_target_teams_distribute_parallel_for_simd:
  9815. case OMPD_target_teams_distribute:
  9816. case OMPD_target_teams_distribute_simd:
  9817. CaptureRegion = OMPD_teams;
  9818. break;
  9819. case OMPD_distribute_parallel_for:
  9820. case OMPD_distribute_parallel_for_simd:
  9821. case OMPD_distribute:
  9822. case OMPD_distribute_simd:
  9823. // Do not capture thread_limit-clause expressions.
  9824. break;
  9825. case OMPD_parallel_for:
  9826. case OMPD_parallel_for_simd:
  9827. case OMPD_target_parallel_for_simd:
  9828. case OMPD_target_parallel_for:
  9829. case OMPD_task:
  9830. case OMPD_taskloop:
  9831. case OMPD_taskloop_simd:
  9832. case OMPD_target_data:
  9833. case OMPD_target_enter_data:
  9834. case OMPD_target_exit_data:
  9835. case OMPD_target_update:
  9836. case OMPD_teams:
  9837. case OMPD_target:
  9838. case OMPD_target_simd:
  9839. case OMPD_target_parallel:
  9840. case OMPD_cancel:
  9841. case OMPD_parallel:
  9842. case OMPD_parallel_sections:
  9843. case OMPD_threadprivate:
  9844. case OMPD_allocate:
  9845. case OMPD_taskyield:
  9846. case OMPD_barrier:
  9847. case OMPD_taskwait:
  9848. case OMPD_cancellation_point:
  9849. case OMPD_flush:
  9850. case OMPD_declare_reduction:
  9851. case OMPD_declare_mapper:
  9852. case OMPD_declare_simd:
  9853. case OMPD_declare_variant:
  9854. case OMPD_declare_target:
  9855. case OMPD_end_declare_target:
  9856. case OMPD_simd:
  9857. case OMPD_for:
  9858. case OMPD_for_simd:
  9859. case OMPD_sections:
  9860. case OMPD_section:
  9861. case OMPD_single:
  9862. case OMPD_master:
  9863. case OMPD_critical:
  9864. case OMPD_taskgroup:
  9865. case OMPD_ordered:
  9866. case OMPD_atomic:
  9867. case OMPD_target_teams:
  9868. case OMPD_requires:
  9869. llvm_unreachable("Unexpected OpenMP directive with schedule clause");
  9870. case OMPD_unknown:
  9871. llvm_unreachable("Unknown OpenMP directive");
  9872. }
  9873. break;
  9874. case OMPC_device:
  9875. switch (DKind) {
  9876. case OMPD_target_update:
  9877. case OMPD_target_enter_data:
  9878. case OMPD_target_exit_data:
  9879. case OMPD_target:
  9880. case OMPD_target_simd:
  9881. case OMPD_target_teams:
  9882. case OMPD_target_parallel:
  9883. case OMPD_target_teams_distribute:
  9884. case OMPD_target_teams_distribute_simd:
  9885. case OMPD_target_parallel_for:
  9886. case OMPD_target_parallel_for_simd:
  9887. case OMPD_target_teams_distribute_parallel_for:
  9888. case OMPD_target_teams_distribute_parallel_for_simd:
  9889. CaptureRegion = OMPD_task;
  9890. break;
  9891. case OMPD_target_data:
  9892. // Do not capture device-clause expressions.
  9893. break;
  9894. case OMPD_teams_distribute_parallel_for:
  9895. case OMPD_teams_distribute_parallel_for_simd:
  9896. case OMPD_teams:
  9897. case OMPD_teams_distribute:
  9898. case OMPD_teams_distribute_simd:
  9899. case OMPD_distribute_parallel_for:
  9900. case OMPD_distribute_parallel_for_simd:
  9901. case OMPD_task:
  9902. case OMPD_taskloop:
  9903. case OMPD_taskloop_simd:
  9904. case OMPD_cancel:
  9905. case OMPD_parallel:
  9906. case OMPD_parallel_sections:
  9907. case OMPD_parallel_for:
  9908. case OMPD_parallel_for_simd:
  9909. case OMPD_threadprivate:
  9910. case OMPD_allocate:
  9911. case OMPD_taskyield:
  9912. case OMPD_barrier:
  9913. case OMPD_taskwait:
  9914. case OMPD_cancellation_point:
  9915. case OMPD_flush:
  9916. case OMPD_declare_reduction:
  9917. case OMPD_declare_mapper:
  9918. case OMPD_declare_simd:
  9919. case OMPD_declare_variant:
  9920. case OMPD_declare_target:
  9921. case OMPD_end_declare_target:
  9922. case OMPD_simd:
  9923. case OMPD_for:
  9924. case OMPD_for_simd:
  9925. case OMPD_sections:
  9926. case OMPD_section:
  9927. case OMPD_single:
  9928. case OMPD_master:
  9929. case OMPD_critical:
  9930. case OMPD_taskgroup:
  9931. case OMPD_distribute:
  9932. case OMPD_ordered:
  9933. case OMPD_atomic:
  9934. case OMPD_distribute_simd:
  9935. case OMPD_requires:
  9936. llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
  9937. case OMPD_unknown:
  9938. llvm_unreachable("Unknown OpenMP directive");
  9939. }
  9940. break;
  9941. case OMPC_firstprivate:
  9942. case OMPC_lastprivate:
  9943. case OMPC_reduction:
  9944. case OMPC_task_reduction:
  9945. case OMPC_in_reduction:
  9946. case OMPC_linear:
  9947. case OMPC_default:
  9948. case OMPC_proc_bind:
  9949. case OMPC_final:
  9950. case OMPC_safelen:
  9951. case OMPC_simdlen:
  9952. case OMPC_allocator:
  9953. case OMPC_collapse:
  9954. case OMPC_private:
  9955. case OMPC_shared:
  9956. case OMPC_aligned:
  9957. case OMPC_copyin:
  9958. case OMPC_copyprivate:
  9959. case OMPC_ordered:
  9960. case OMPC_nowait:
  9961. case OMPC_untied:
  9962. case OMPC_mergeable:
  9963. case OMPC_threadprivate:
  9964. case OMPC_allocate:
  9965. case OMPC_flush:
  9966. case OMPC_read:
  9967. case OMPC_write:
  9968. case OMPC_update:
  9969. case OMPC_capture:
  9970. case OMPC_seq_cst:
  9971. case OMPC_depend:
  9972. case OMPC_threads:
  9973. case OMPC_simd:
  9974. case OMPC_map:
  9975. case OMPC_priority:
  9976. case OMPC_grainsize:
  9977. case OMPC_nogroup:
  9978. case OMPC_num_tasks:
  9979. case OMPC_hint:
  9980. case OMPC_defaultmap:
  9981. case OMPC_unknown:
  9982. case OMPC_uniform:
  9983. case OMPC_to:
  9984. case OMPC_from:
  9985. case OMPC_use_device_ptr:
  9986. case OMPC_is_device_ptr:
  9987. case OMPC_unified_address:
  9988. case OMPC_unified_shared_memory:
  9989. case OMPC_reverse_offload:
  9990. case OMPC_dynamic_allocators:
  9991. case OMPC_atomic_default_mem_order:
  9992. case OMPC_device_type:
  9993. case OMPC_match:
  9994. llvm_unreachable("Unexpected OpenMP clause.");
  9995. }
  9996. return CaptureRegion;
  9997. }
  9998. OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
  9999. Expr *Condition, SourceLocation StartLoc,
  10000. SourceLocation LParenLoc,
  10001. SourceLocation NameModifierLoc,
  10002. SourceLocation ColonLoc,
  10003. SourceLocation EndLoc) {
  10004. Expr *ValExpr = Condition;
  10005. Stmt *HelperValStmt = nullptr;
  10006. OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
  10007. if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
  10008. !Condition->isInstantiationDependent() &&
  10009. !Condition->containsUnexpandedParameterPack()) {
  10010. ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
  10011. if (Val.isInvalid())
  10012. return nullptr;
  10013. ValExpr = Val.get();
  10014. OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
  10015. CaptureRegion =
  10016. getOpenMPCaptureRegionForClause(DKind, OMPC_if, NameModifier);
  10017. if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
  10018. ValExpr = MakeFullExpr(ValExpr).get();
  10019. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  10020. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  10021. HelperValStmt = buildPreInits(Context, Captures);
  10022. }
  10023. }
  10024. return new (Context)
  10025. OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
  10026. LParenLoc, NameModifierLoc, ColonLoc, EndLoc);
  10027. }
  10028. OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
  10029. SourceLocation StartLoc,
  10030. SourceLocation LParenLoc,
  10031. SourceLocation EndLoc) {
  10032. Expr *ValExpr = Condition;
  10033. if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
  10034. !Condition->isInstantiationDependent() &&
  10035. !Condition->containsUnexpandedParameterPack()) {
  10036. ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
  10037. if (Val.isInvalid())
  10038. return nullptr;
  10039. ValExpr = MakeFullExpr(Val.get()).get();
  10040. }
  10041. return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
  10042. }
  10043. ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
  10044. Expr *Op) {
  10045. if (!Op)
  10046. return ExprError();
  10047. class IntConvertDiagnoser : public ICEConvertDiagnoser {
  10048. public:
  10049. IntConvertDiagnoser()
  10050. : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
  10051. SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
  10052. QualType T) override {
  10053. return S.Diag(Loc, diag::err_omp_not_integral) << T;
  10054. }
  10055. SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
  10056. QualType T) override {
  10057. return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
  10058. }
  10059. SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
  10060. QualType T,
  10061. QualType ConvTy) override {
  10062. return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
  10063. }
  10064. SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
  10065. QualType ConvTy) override {
  10066. return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
  10067. << ConvTy->isEnumeralType() << ConvTy;
  10068. }
  10069. SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
  10070. QualType T) override {
  10071. return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
  10072. }
  10073. SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
  10074. QualType ConvTy) override {
  10075. return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
  10076. << ConvTy->isEnumeralType() << ConvTy;
  10077. }
  10078. SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
  10079. QualType) override {
  10080. llvm_unreachable("conversion functions are permitted");
  10081. }
  10082. } ConvertDiagnoser;
  10083. return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
  10084. }
  10085. static bool isNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef,
  10086. OpenMPClauseKind CKind,
  10087. bool StrictlyPositive) {
  10088. if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
  10089. !ValExpr->isInstantiationDependent()) {
  10090. SourceLocation Loc = ValExpr->getExprLoc();
  10091. ExprResult Value =
  10092. SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
  10093. if (Value.isInvalid())
  10094. return false;
  10095. ValExpr = Value.get();
  10096. // The expression must evaluate to a non-negative integer value.
  10097. llvm::APSInt Result;
  10098. if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
  10099. Result.isSigned() &&
  10100. !((!StrictlyPositive && Result.isNonNegative()) ||
  10101. (StrictlyPositive && Result.isStrictlyPositive()))) {
  10102. SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
  10103. << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
  10104. << ValExpr->getSourceRange();
  10105. return false;
  10106. }
  10107. }
  10108. return true;
  10109. }
  10110. OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
  10111. SourceLocation StartLoc,
  10112. SourceLocation LParenLoc,
  10113. SourceLocation EndLoc) {
  10114. Expr *ValExpr = NumThreads;
  10115. Stmt *HelperValStmt = nullptr;
  10116. // OpenMP [2.5, Restrictions]
  10117. // The num_threads expression must evaluate to a positive integer value.
  10118. if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
  10119. /*StrictlyPositive=*/true))
  10120. return nullptr;
  10121. OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
  10122. OpenMPDirectiveKind CaptureRegion =
  10123. getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads);
  10124. if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
  10125. ValExpr = MakeFullExpr(ValExpr).get();
  10126. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  10127. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  10128. HelperValStmt = buildPreInits(Context, Captures);
  10129. }
  10130. return new (Context) OMPNumThreadsClause(
  10131. ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
  10132. }
  10133. ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
  10134. OpenMPClauseKind CKind,
  10135. bool StrictlyPositive) {
  10136. if (!E)
  10137. return ExprError();
  10138. if (E->isValueDependent() || E->isTypeDependent() ||
  10139. E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
  10140. return E;
  10141. llvm::APSInt Result;
  10142. ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
  10143. if (ICE.isInvalid())
  10144. return ExprError();
  10145. if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
  10146. (!StrictlyPositive && !Result.isNonNegative())) {
  10147. Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
  10148. << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
  10149. << E->getSourceRange();
  10150. return ExprError();
  10151. }
  10152. if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
  10153. Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
  10154. << E->getSourceRange();
  10155. return ExprError();
  10156. }
  10157. if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
  10158. DSAStack->setAssociatedLoops(Result.getExtValue());
  10159. else if (CKind == OMPC_ordered)
  10160. DSAStack->setAssociatedLoops(Result.getExtValue());
  10161. return ICE;
  10162. }
  10163. OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
  10164. SourceLocation LParenLoc,
  10165. SourceLocation EndLoc) {
  10166. // OpenMP [2.8.1, simd construct, Description]
  10167. // The parameter of the safelen clause must be a constant
  10168. // positive integer expression.
  10169. ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
  10170. if (Safelen.isInvalid())
  10171. return nullptr;
  10172. return new (Context)
  10173. OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
  10174. }
  10175. OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
  10176. SourceLocation LParenLoc,
  10177. SourceLocation EndLoc) {
  10178. // OpenMP [2.8.1, simd construct, Description]
  10179. // The parameter of the simdlen clause must be a constant
  10180. // positive integer expression.
  10181. ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
  10182. if (Simdlen.isInvalid())
  10183. return nullptr;
  10184. return new (Context)
  10185. OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
  10186. }
  10187. /// Tries to find omp_allocator_handle_t type.
  10188. static bool findOMPAllocatorHandleT(Sema &S, SourceLocation Loc,
  10189. DSAStackTy *Stack) {
  10190. QualType OMPAllocatorHandleT = Stack->getOMPAllocatorHandleT();
  10191. if (!OMPAllocatorHandleT.isNull())
  10192. return true;
  10193. // Build the predefined allocator expressions.
  10194. bool ErrorFound = false;
  10195. for (int I = OMPAllocateDeclAttr::OMPDefaultMemAlloc;
  10196. I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) {
  10197. auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I);
  10198. StringRef Allocator =
  10199. OMPAllocateDeclAttr::ConvertAllocatorTypeTyToStr(AllocatorKind);
  10200. DeclarationName AllocatorName = &S.getASTContext().Idents.get(Allocator);
  10201. auto *VD = dyn_cast_or_null<ValueDecl>(
  10202. S.LookupSingleName(S.TUScope, AllocatorName, Loc, Sema::LookupAnyName));
  10203. if (!VD) {
  10204. ErrorFound = true;
  10205. break;
  10206. }
  10207. QualType AllocatorType =
  10208. VD->getType().getNonLValueExprType(S.getASTContext());
  10209. ExprResult Res = S.BuildDeclRefExpr(VD, AllocatorType, VK_LValue, Loc);
  10210. if (!Res.isUsable()) {
  10211. ErrorFound = true;
  10212. break;
  10213. }
  10214. if (OMPAllocatorHandleT.isNull())
  10215. OMPAllocatorHandleT = AllocatorType;
  10216. if (!S.getASTContext().hasSameType(OMPAllocatorHandleT, AllocatorType)) {
  10217. ErrorFound = true;
  10218. break;
  10219. }
  10220. Stack->setAllocator(AllocatorKind, Res.get());
  10221. }
  10222. if (ErrorFound) {
  10223. S.Diag(Loc, diag::err_implied_omp_allocator_handle_t_not_found);
  10224. return false;
  10225. }
  10226. OMPAllocatorHandleT.addConst();
  10227. Stack->setOMPAllocatorHandleT(OMPAllocatorHandleT);
  10228. return true;
  10229. }
  10230. OMPClause *Sema::ActOnOpenMPAllocatorClause(Expr *A, SourceLocation StartLoc,
  10231. SourceLocation LParenLoc,
  10232. SourceLocation EndLoc) {
  10233. // OpenMP [2.11.3, allocate Directive, Description]
  10234. // allocator is an expression of omp_allocator_handle_t type.
  10235. if (!findOMPAllocatorHandleT(*this, A->getExprLoc(), DSAStack))
  10236. return nullptr;
  10237. ExprResult Allocator = DefaultLvalueConversion(A);
  10238. if (Allocator.isInvalid())
  10239. return nullptr;
  10240. Allocator = PerformImplicitConversion(Allocator.get(),
  10241. DSAStack->getOMPAllocatorHandleT(),
  10242. Sema::AA_Initializing,
  10243. /*AllowExplicit=*/true);
  10244. if (Allocator.isInvalid())
  10245. return nullptr;
  10246. return new (Context)
  10247. OMPAllocatorClause(Allocator.get(), StartLoc, LParenLoc, EndLoc);
  10248. }
  10249. OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
  10250. SourceLocation StartLoc,
  10251. SourceLocation LParenLoc,
  10252. SourceLocation EndLoc) {
  10253. // OpenMP [2.7.1, loop construct, Description]
  10254. // OpenMP [2.8.1, simd construct, Description]
  10255. // OpenMP [2.9.6, distribute construct, Description]
  10256. // The parameter of the collapse clause must be a constant
  10257. // positive integer expression.
  10258. ExprResult NumForLoopsResult =
  10259. VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
  10260. if (NumForLoopsResult.isInvalid())
  10261. return nullptr;
  10262. return new (Context)
  10263. OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
  10264. }
  10265. OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
  10266. SourceLocation EndLoc,
  10267. SourceLocation LParenLoc,
  10268. Expr *NumForLoops) {
  10269. // OpenMP [2.7.1, loop construct, Description]
  10270. // OpenMP [2.8.1, simd construct, Description]
  10271. // OpenMP [2.9.6, distribute construct, Description]
  10272. // The parameter of the ordered clause must be a constant
  10273. // positive integer expression if any.
  10274. if (NumForLoops && LParenLoc.isValid()) {
  10275. ExprResult NumForLoopsResult =
  10276. VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
  10277. if (NumForLoopsResult.isInvalid())
  10278. return nullptr;
  10279. NumForLoops = NumForLoopsResult.get();
  10280. } else {
  10281. NumForLoops = nullptr;
  10282. }
  10283. auto *Clause = OMPOrderedClause::Create(
  10284. Context, NumForLoops, NumForLoops ? DSAStack->getAssociatedLoops() : 0,
  10285. StartLoc, LParenLoc, EndLoc);
  10286. DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops, Clause);
  10287. return Clause;
  10288. }
  10289. OMPClause *Sema::ActOnOpenMPSimpleClause(
  10290. OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
  10291. SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
  10292. OMPClause *Res = nullptr;
  10293. switch (Kind) {
  10294. case OMPC_default:
  10295. Res =
  10296. ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
  10297. ArgumentLoc, StartLoc, LParenLoc, EndLoc);
  10298. break;
  10299. case OMPC_proc_bind:
  10300. Res = ActOnOpenMPProcBindClause(
  10301. static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
  10302. LParenLoc, EndLoc);
  10303. break;
  10304. case OMPC_atomic_default_mem_order:
  10305. Res = ActOnOpenMPAtomicDefaultMemOrderClause(
  10306. static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Argument),
  10307. ArgumentLoc, StartLoc, LParenLoc, EndLoc);
  10308. break;
  10309. case OMPC_if:
  10310. case OMPC_final:
  10311. case OMPC_num_threads:
  10312. case OMPC_safelen:
  10313. case OMPC_simdlen:
  10314. case OMPC_allocator:
  10315. case OMPC_collapse:
  10316. case OMPC_schedule:
  10317. case OMPC_private:
  10318. case OMPC_firstprivate:
  10319. case OMPC_lastprivate:
  10320. case OMPC_shared:
  10321. case OMPC_reduction:
  10322. case OMPC_task_reduction:
  10323. case OMPC_in_reduction:
  10324. case OMPC_linear:
  10325. case OMPC_aligned:
  10326. case OMPC_copyin:
  10327. case OMPC_copyprivate:
  10328. case OMPC_ordered:
  10329. case OMPC_nowait:
  10330. case OMPC_untied:
  10331. case OMPC_mergeable:
  10332. case OMPC_threadprivate:
  10333. case OMPC_allocate:
  10334. case OMPC_flush:
  10335. case OMPC_read:
  10336. case OMPC_write:
  10337. case OMPC_update:
  10338. case OMPC_capture:
  10339. case OMPC_seq_cst:
  10340. case OMPC_depend:
  10341. case OMPC_device:
  10342. case OMPC_threads:
  10343. case OMPC_simd:
  10344. case OMPC_map:
  10345. case OMPC_num_teams:
  10346. case OMPC_thread_limit:
  10347. case OMPC_priority:
  10348. case OMPC_grainsize:
  10349. case OMPC_nogroup:
  10350. case OMPC_num_tasks:
  10351. case OMPC_hint:
  10352. case OMPC_dist_schedule:
  10353. case OMPC_defaultmap:
  10354. case OMPC_unknown:
  10355. case OMPC_uniform:
  10356. case OMPC_to:
  10357. case OMPC_from:
  10358. case OMPC_use_device_ptr:
  10359. case OMPC_is_device_ptr:
  10360. case OMPC_unified_address:
  10361. case OMPC_unified_shared_memory:
  10362. case OMPC_reverse_offload:
  10363. case OMPC_dynamic_allocators:
  10364. case OMPC_device_type:
  10365. case OMPC_match:
  10366. llvm_unreachable("Clause is not allowed.");
  10367. }
  10368. return Res;
  10369. }
  10370. static std::string
  10371. getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
  10372. ArrayRef<unsigned> Exclude = llvm::None) {
  10373. SmallString<256> Buffer;
  10374. llvm::raw_svector_ostream Out(Buffer);
  10375. unsigned Bound = Last >= 2 ? Last - 2 : 0;
  10376. unsigned Skipped = Exclude.size();
  10377. auto S = Exclude.begin(), E = Exclude.end();
  10378. for (unsigned I = First; I < Last; ++I) {
  10379. if (std::find(S, E, I) != E) {
  10380. --Skipped;
  10381. continue;
  10382. }
  10383. Out << "'" << getOpenMPSimpleClauseTypeName(K, I) << "'";
  10384. if (I == Bound - Skipped)
  10385. Out << " or ";
  10386. else if (I != Bound + 1 - Skipped)
  10387. Out << ", ";
  10388. }
  10389. return Out.str();
  10390. }
  10391. OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
  10392. SourceLocation KindKwLoc,
  10393. SourceLocation StartLoc,
  10394. SourceLocation LParenLoc,
  10395. SourceLocation EndLoc) {
  10396. if (Kind == OMPC_DEFAULT_unknown) {
  10397. static_assert(OMPC_DEFAULT_unknown > 0,
  10398. "OMPC_DEFAULT_unknown not greater than 0");
  10399. Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
  10400. << getListOfPossibleValues(OMPC_default, /*First=*/0,
  10401. /*Last=*/OMPC_DEFAULT_unknown)
  10402. << getOpenMPClauseName(OMPC_default);
  10403. return nullptr;
  10404. }
  10405. switch (Kind) {
  10406. case OMPC_DEFAULT_none:
  10407. DSAStack->setDefaultDSANone(KindKwLoc);
  10408. break;
  10409. case OMPC_DEFAULT_shared:
  10410. DSAStack->setDefaultDSAShared(KindKwLoc);
  10411. break;
  10412. case OMPC_DEFAULT_unknown:
  10413. llvm_unreachable("Clause kind is not allowed.");
  10414. break;
  10415. }
  10416. return new (Context)
  10417. OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
  10418. }
  10419. OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
  10420. SourceLocation KindKwLoc,
  10421. SourceLocation StartLoc,
  10422. SourceLocation LParenLoc,
  10423. SourceLocation EndLoc) {
  10424. if (Kind == OMPC_PROC_BIND_unknown) {
  10425. Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
  10426. << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0,
  10427. /*Last=*/OMPC_PROC_BIND_unknown)
  10428. << getOpenMPClauseName(OMPC_proc_bind);
  10429. return nullptr;
  10430. }
  10431. return new (Context)
  10432. OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
  10433. }
  10434. OMPClause *Sema::ActOnOpenMPAtomicDefaultMemOrderClause(
  10435. OpenMPAtomicDefaultMemOrderClauseKind Kind, SourceLocation KindKwLoc,
  10436. SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
  10437. if (Kind == OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown) {
  10438. Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
  10439. << getListOfPossibleValues(
  10440. OMPC_atomic_default_mem_order, /*First=*/0,
  10441. /*Last=*/OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown)
  10442. << getOpenMPClauseName(OMPC_atomic_default_mem_order);
  10443. return nullptr;
  10444. }
  10445. return new (Context) OMPAtomicDefaultMemOrderClause(Kind, KindKwLoc, StartLoc,
  10446. LParenLoc, EndLoc);
  10447. }
  10448. OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
  10449. OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
  10450. SourceLocation StartLoc, SourceLocation LParenLoc,
  10451. ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
  10452. SourceLocation EndLoc) {
  10453. OMPClause *Res = nullptr;
  10454. switch (Kind) {
  10455. case OMPC_schedule:
  10456. enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
  10457. assert(Argument.size() == NumberOfElements &&
  10458. ArgumentLoc.size() == NumberOfElements);
  10459. Res = ActOnOpenMPScheduleClause(
  10460. static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
  10461. static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
  10462. static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
  10463. StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
  10464. ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
  10465. break;
  10466. case OMPC_if:
  10467. assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
  10468. Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
  10469. Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
  10470. DelimLoc, EndLoc);
  10471. break;
  10472. case OMPC_dist_schedule:
  10473. Res = ActOnOpenMPDistScheduleClause(
  10474. static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
  10475. StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
  10476. break;
  10477. case OMPC_defaultmap:
  10478. enum { Modifier, DefaultmapKind };
  10479. Res = ActOnOpenMPDefaultmapClause(
  10480. static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
  10481. static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
  10482. StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
  10483. EndLoc);
  10484. break;
  10485. case OMPC_final:
  10486. case OMPC_num_threads:
  10487. case OMPC_safelen:
  10488. case OMPC_simdlen:
  10489. case OMPC_allocator:
  10490. case OMPC_collapse:
  10491. case OMPC_default:
  10492. case OMPC_proc_bind:
  10493. case OMPC_private:
  10494. case OMPC_firstprivate:
  10495. case OMPC_lastprivate:
  10496. case OMPC_shared:
  10497. case OMPC_reduction:
  10498. case OMPC_task_reduction:
  10499. case OMPC_in_reduction:
  10500. case OMPC_linear:
  10501. case OMPC_aligned:
  10502. case OMPC_copyin:
  10503. case OMPC_copyprivate:
  10504. case OMPC_ordered:
  10505. case OMPC_nowait:
  10506. case OMPC_untied:
  10507. case OMPC_mergeable:
  10508. case OMPC_threadprivate:
  10509. case OMPC_allocate:
  10510. case OMPC_flush:
  10511. case OMPC_read:
  10512. case OMPC_write:
  10513. case OMPC_update:
  10514. case OMPC_capture:
  10515. case OMPC_seq_cst:
  10516. case OMPC_depend:
  10517. case OMPC_device:
  10518. case OMPC_threads:
  10519. case OMPC_simd:
  10520. case OMPC_map:
  10521. case OMPC_num_teams:
  10522. case OMPC_thread_limit:
  10523. case OMPC_priority:
  10524. case OMPC_grainsize:
  10525. case OMPC_nogroup:
  10526. case OMPC_num_tasks:
  10527. case OMPC_hint:
  10528. case OMPC_unknown:
  10529. case OMPC_uniform:
  10530. case OMPC_to:
  10531. case OMPC_from:
  10532. case OMPC_use_device_ptr:
  10533. case OMPC_is_device_ptr:
  10534. case OMPC_unified_address:
  10535. case OMPC_unified_shared_memory:
  10536. case OMPC_reverse_offload:
  10537. case OMPC_dynamic_allocators:
  10538. case OMPC_atomic_default_mem_order:
  10539. case OMPC_device_type:
  10540. case OMPC_match:
  10541. llvm_unreachable("Clause is not allowed.");
  10542. }
  10543. return Res;
  10544. }
  10545. static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
  10546. OpenMPScheduleClauseModifier M2,
  10547. SourceLocation M1Loc, SourceLocation M2Loc) {
  10548. if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
  10549. SmallVector<unsigned, 2> Excluded;
  10550. if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
  10551. Excluded.push_back(M2);
  10552. if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
  10553. Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
  10554. if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
  10555. Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
  10556. S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
  10557. << getListOfPossibleValues(OMPC_schedule,
  10558. /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
  10559. /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
  10560. Excluded)
  10561. << getOpenMPClauseName(OMPC_schedule);
  10562. return true;
  10563. }
  10564. return false;
  10565. }
  10566. OMPClause *Sema::ActOnOpenMPScheduleClause(
  10567. OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
  10568. OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
  10569. SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
  10570. SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
  10571. if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
  10572. checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
  10573. return nullptr;
  10574. // OpenMP, 2.7.1, Loop Construct, Restrictions
  10575. // Either the monotonic modifier or the nonmonotonic modifier can be specified
  10576. // but not both.
  10577. if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
  10578. (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
  10579. M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
  10580. (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
  10581. M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
  10582. Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
  10583. << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
  10584. << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
  10585. return nullptr;
  10586. }
  10587. if (Kind == OMPC_SCHEDULE_unknown) {
  10588. std::string Values;
  10589. if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
  10590. unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
  10591. Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
  10592. /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
  10593. Exclude);
  10594. } else {
  10595. Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
  10596. /*Last=*/OMPC_SCHEDULE_unknown);
  10597. }
  10598. Diag(KindLoc, diag::err_omp_unexpected_clause_value)
  10599. << Values << getOpenMPClauseName(OMPC_schedule);
  10600. return nullptr;
  10601. }
  10602. // OpenMP, 2.7.1, Loop Construct, Restrictions
  10603. // The nonmonotonic modifier can only be specified with schedule(dynamic) or
  10604. // schedule(guided).
  10605. if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
  10606. M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
  10607. Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
  10608. Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
  10609. diag::err_omp_schedule_nonmonotonic_static);
  10610. return nullptr;
  10611. }
  10612. Expr *ValExpr = ChunkSize;
  10613. Stmt *HelperValStmt = nullptr;
  10614. if (ChunkSize) {
  10615. if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
  10616. !ChunkSize->isInstantiationDependent() &&
  10617. !ChunkSize->containsUnexpandedParameterPack()) {
  10618. SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
  10619. ExprResult Val =
  10620. PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
  10621. if (Val.isInvalid())
  10622. return nullptr;
  10623. ValExpr = Val.get();
  10624. // OpenMP [2.7.1, Restrictions]
  10625. // chunk_size must be a loop invariant integer expression with a positive
  10626. // value.
  10627. llvm::APSInt Result;
  10628. if (ValExpr->isIntegerConstantExpr(Result, Context)) {
  10629. if (Result.isSigned() && !Result.isStrictlyPositive()) {
  10630. Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
  10631. << "schedule" << 1 << ChunkSize->getSourceRange();
  10632. return nullptr;
  10633. }
  10634. } else if (getOpenMPCaptureRegionForClause(
  10635. DSAStack->getCurrentDirective(), OMPC_schedule) !=
  10636. OMPD_unknown &&
  10637. !CurContext->isDependentContext()) {
  10638. ValExpr = MakeFullExpr(ValExpr).get();
  10639. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  10640. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  10641. HelperValStmt = buildPreInits(Context, Captures);
  10642. }
  10643. }
  10644. }
  10645. return new (Context)
  10646. OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
  10647. ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
  10648. }
  10649. OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
  10650. SourceLocation StartLoc,
  10651. SourceLocation EndLoc) {
  10652. OMPClause *Res = nullptr;
  10653. switch (Kind) {
  10654. case OMPC_ordered:
  10655. Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
  10656. break;
  10657. case OMPC_nowait:
  10658. Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
  10659. break;
  10660. case OMPC_untied:
  10661. Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
  10662. break;
  10663. case OMPC_mergeable:
  10664. Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
  10665. break;
  10666. case OMPC_read:
  10667. Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
  10668. break;
  10669. case OMPC_write:
  10670. Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
  10671. break;
  10672. case OMPC_update:
  10673. Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
  10674. break;
  10675. case OMPC_capture:
  10676. Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
  10677. break;
  10678. case OMPC_seq_cst:
  10679. Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
  10680. break;
  10681. case OMPC_threads:
  10682. Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
  10683. break;
  10684. case OMPC_simd:
  10685. Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
  10686. break;
  10687. case OMPC_nogroup:
  10688. Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
  10689. break;
  10690. case OMPC_unified_address:
  10691. Res = ActOnOpenMPUnifiedAddressClause(StartLoc, EndLoc);
  10692. break;
  10693. case OMPC_unified_shared_memory:
  10694. Res = ActOnOpenMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
  10695. break;
  10696. case OMPC_reverse_offload:
  10697. Res = ActOnOpenMPReverseOffloadClause(StartLoc, EndLoc);
  10698. break;
  10699. case OMPC_dynamic_allocators:
  10700. Res = ActOnOpenMPDynamicAllocatorsClause(StartLoc, EndLoc);
  10701. break;
  10702. case OMPC_if:
  10703. case OMPC_final:
  10704. case OMPC_num_threads:
  10705. case OMPC_safelen:
  10706. case OMPC_simdlen:
  10707. case OMPC_allocator:
  10708. case OMPC_collapse:
  10709. case OMPC_schedule:
  10710. case OMPC_private:
  10711. case OMPC_firstprivate:
  10712. case OMPC_lastprivate:
  10713. case OMPC_shared:
  10714. case OMPC_reduction:
  10715. case OMPC_task_reduction:
  10716. case OMPC_in_reduction:
  10717. case OMPC_linear:
  10718. case OMPC_aligned:
  10719. case OMPC_copyin:
  10720. case OMPC_copyprivate:
  10721. case OMPC_default:
  10722. case OMPC_proc_bind:
  10723. case OMPC_threadprivate:
  10724. case OMPC_allocate:
  10725. case OMPC_flush:
  10726. case OMPC_depend:
  10727. case OMPC_device:
  10728. case OMPC_map:
  10729. case OMPC_num_teams:
  10730. case OMPC_thread_limit:
  10731. case OMPC_priority:
  10732. case OMPC_grainsize:
  10733. case OMPC_num_tasks:
  10734. case OMPC_hint:
  10735. case OMPC_dist_schedule:
  10736. case OMPC_defaultmap:
  10737. case OMPC_unknown:
  10738. case OMPC_uniform:
  10739. case OMPC_to:
  10740. case OMPC_from:
  10741. case OMPC_use_device_ptr:
  10742. case OMPC_is_device_ptr:
  10743. case OMPC_atomic_default_mem_order:
  10744. case OMPC_device_type:
  10745. case OMPC_match:
  10746. llvm_unreachable("Clause is not allowed.");
  10747. }
  10748. return Res;
  10749. }
  10750. OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
  10751. SourceLocation EndLoc) {
  10752. DSAStack->setNowaitRegion();
  10753. return new (Context) OMPNowaitClause(StartLoc, EndLoc);
  10754. }
  10755. OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
  10756. SourceLocation EndLoc) {
  10757. return new (Context) OMPUntiedClause(StartLoc, EndLoc);
  10758. }
  10759. OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
  10760. SourceLocation EndLoc) {
  10761. return new (Context) OMPMergeableClause(StartLoc, EndLoc);
  10762. }
  10763. OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
  10764. SourceLocation EndLoc) {
  10765. return new (Context) OMPReadClause(StartLoc, EndLoc);
  10766. }
  10767. OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
  10768. SourceLocation EndLoc) {
  10769. return new (Context) OMPWriteClause(StartLoc, EndLoc);
  10770. }
  10771. OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
  10772. SourceLocation EndLoc) {
  10773. return new (Context) OMPUpdateClause(StartLoc, EndLoc);
  10774. }
  10775. OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
  10776. SourceLocation EndLoc) {
  10777. return new (Context) OMPCaptureClause(StartLoc, EndLoc);
  10778. }
  10779. OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
  10780. SourceLocation EndLoc) {
  10781. return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
  10782. }
  10783. OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
  10784. SourceLocation EndLoc) {
  10785. return new (Context) OMPThreadsClause(StartLoc, EndLoc);
  10786. }
  10787. OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
  10788. SourceLocation EndLoc) {
  10789. return new (Context) OMPSIMDClause(StartLoc, EndLoc);
  10790. }
  10791. OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
  10792. SourceLocation EndLoc) {
  10793. return new (Context) OMPNogroupClause(StartLoc, EndLoc);
  10794. }
  10795. OMPClause *Sema::ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc,
  10796. SourceLocation EndLoc) {
  10797. return new (Context) OMPUnifiedAddressClause(StartLoc, EndLoc);
  10798. }
  10799. OMPClause *Sema::ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc,
  10800. SourceLocation EndLoc) {
  10801. return new (Context) OMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
  10802. }
  10803. OMPClause *Sema::ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc,
  10804. SourceLocation EndLoc) {
  10805. return new (Context) OMPReverseOffloadClause(StartLoc, EndLoc);
  10806. }
  10807. OMPClause *Sema::ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc,
  10808. SourceLocation EndLoc) {
  10809. return new (Context) OMPDynamicAllocatorsClause(StartLoc, EndLoc);
  10810. }
  10811. OMPClause *Sema::ActOnOpenMPVarListClause(
  10812. OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
  10813. const OMPVarListLocTy &Locs, SourceLocation ColonLoc,
  10814. CXXScopeSpec &ReductionOrMapperIdScopeSpec,
  10815. DeclarationNameInfo &ReductionOrMapperId, OpenMPDependClauseKind DepKind,
  10816. OpenMPLinearClauseKind LinKind,
  10817. ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
  10818. ArrayRef<SourceLocation> MapTypeModifiersLoc, OpenMPMapClauseKind MapType,
  10819. bool IsMapTypeImplicit, SourceLocation DepLinMapLoc) {
  10820. SourceLocation StartLoc = Locs.StartLoc;
  10821. SourceLocation LParenLoc = Locs.LParenLoc;
  10822. SourceLocation EndLoc = Locs.EndLoc;
  10823. OMPClause *Res = nullptr;
  10824. switch (Kind) {
  10825. case OMPC_private:
  10826. Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
  10827. break;
  10828. case OMPC_firstprivate:
  10829. Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
  10830. break;
  10831. case OMPC_lastprivate:
  10832. Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
  10833. break;
  10834. case OMPC_shared:
  10835. Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
  10836. break;
  10837. case OMPC_reduction:
  10838. Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
  10839. EndLoc, ReductionOrMapperIdScopeSpec,
  10840. ReductionOrMapperId);
  10841. break;
  10842. case OMPC_task_reduction:
  10843. Res = ActOnOpenMPTaskReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
  10844. EndLoc, ReductionOrMapperIdScopeSpec,
  10845. ReductionOrMapperId);
  10846. break;
  10847. case OMPC_in_reduction:
  10848. Res = ActOnOpenMPInReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
  10849. EndLoc, ReductionOrMapperIdScopeSpec,
  10850. ReductionOrMapperId);
  10851. break;
  10852. case OMPC_linear:
  10853. Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
  10854. LinKind, DepLinMapLoc, ColonLoc, EndLoc);
  10855. break;
  10856. case OMPC_aligned:
  10857. Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
  10858. ColonLoc, EndLoc);
  10859. break;
  10860. case OMPC_copyin:
  10861. Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
  10862. break;
  10863. case OMPC_copyprivate:
  10864. Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
  10865. break;
  10866. case OMPC_flush:
  10867. Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
  10868. break;
  10869. case OMPC_depend:
  10870. Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList,
  10871. StartLoc, LParenLoc, EndLoc);
  10872. break;
  10873. case OMPC_map:
  10874. Res = ActOnOpenMPMapClause(MapTypeModifiers, MapTypeModifiersLoc,
  10875. ReductionOrMapperIdScopeSpec,
  10876. ReductionOrMapperId, MapType, IsMapTypeImplicit,
  10877. DepLinMapLoc, ColonLoc, VarList, Locs);
  10878. break;
  10879. case OMPC_to:
  10880. Res = ActOnOpenMPToClause(VarList, ReductionOrMapperIdScopeSpec,
  10881. ReductionOrMapperId, Locs);
  10882. break;
  10883. case OMPC_from:
  10884. Res = ActOnOpenMPFromClause(VarList, ReductionOrMapperIdScopeSpec,
  10885. ReductionOrMapperId, Locs);
  10886. break;
  10887. case OMPC_use_device_ptr:
  10888. Res = ActOnOpenMPUseDevicePtrClause(VarList, Locs);
  10889. break;
  10890. case OMPC_is_device_ptr:
  10891. Res = ActOnOpenMPIsDevicePtrClause(VarList, Locs);
  10892. break;
  10893. case OMPC_allocate:
  10894. Res = ActOnOpenMPAllocateClause(TailExpr, VarList, StartLoc, LParenLoc,
  10895. ColonLoc, EndLoc);
  10896. break;
  10897. case OMPC_if:
  10898. case OMPC_final:
  10899. case OMPC_num_threads:
  10900. case OMPC_safelen:
  10901. case OMPC_simdlen:
  10902. case OMPC_allocator:
  10903. case OMPC_collapse:
  10904. case OMPC_default:
  10905. case OMPC_proc_bind:
  10906. case OMPC_schedule:
  10907. case OMPC_ordered:
  10908. case OMPC_nowait:
  10909. case OMPC_untied:
  10910. case OMPC_mergeable:
  10911. case OMPC_threadprivate:
  10912. case OMPC_read:
  10913. case OMPC_write:
  10914. case OMPC_update:
  10915. case OMPC_capture:
  10916. case OMPC_seq_cst:
  10917. case OMPC_device:
  10918. case OMPC_threads:
  10919. case OMPC_simd:
  10920. case OMPC_num_teams:
  10921. case OMPC_thread_limit:
  10922. case OMPC_priority:
  10923. case OMPC_grainsize:
  10924. case OMPC_nogroup:
  10925. case OMPC_num_tasks:
  10926. case OMPC_hint:
  10927. case OMPC_dist_schedule:
  10928. case OMPC_defaultmap:
  10929. case OMPC_unknown:
  10930. case OMPC_uniform:
  10931. case OMPC_unified_address:
  10932. case OMPC_unified_shared_memory:
  10933. case OMPC_reverse_offload:
  10934. case OMPC_dynamic_allocators:
  10935. case OMPC_atomic_default_mem_order:
  10936. case OMPC_device_type:
  10937. case OMPC_match:
  10938. llvm_unreachable("Clause is not allowed.");
  10939. }
  10940. return Res;
  10941. }
  10942. ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
  10943. ExprObjectKind OK, SourceLocation Loc) {
  10944. ExprResult Res = BuildDeclRefExpr(
  10945. Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
  10946. if (!Res.isUsable())
  10947. return ExprError();
  10948. if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
  10949. Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
  10950. if (!Res.isUsable())
  10951. return ExprError();
  10952. }
  10953. if (VK != VK_LValue && Res.get()->isGLValue()) {
  10954. Res = DefaultLvalueConversion(Res.get());
  10955. if (!Res.isUsable())
  10956. return ExprError();
  10957. }
  10958. return Res;
  10959. }
  10960. OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
  10961. SourceLocation StartLoc,
  10962. SourceLocation LParenLoc,
  10963. SourceLocation EndLoc) {
  10964. SmallVector<Expr *, 8> Vars;
  10965. SmallVector<Expr *, 8> PrivateCopies;
  10966. for (Expr *RefExpr : VarList) {
  10967. assert(RefExpr && "NULL expr in OpenMP private clause.");
  10968. SourceLocation ELoc;
  10969. SourceRange ERange;
  10970. Expr *SimpleRefExpr = RefExpr;
  10971. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  10972. if (Res.second) {
  10973. // It will be analyzed later.
  10974. Vars.push_back(RefExpr);
  10975. PrivateCopies.push_back(nullptr);
  10976. }
  10977. ValueDecl *D = Res.first;
  10978. if (!D)
  10979. continue;
  10980. QualType Type = D->getType();
  10981. auto *VD = dyn_cast<VarDecl>(D);
  10982. // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
  10983. // A variable that appears in a private clause must not have an incomplete
  10984. // type or a reference type.
  10985. if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
  10986. continue;
  10987. Type = Type.getNonReferenceType();
  10988. // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
  10989. // A variable that is privatized must not have a const-qualified type
  10990. // unless it is of class type with a mutable member. This restriction does
  10991. // not apply to the firstprivate clause.
  10992. //
  10993. // OpenMP 3.1 [2.9.3.3, private clause, Restrictions]
  10994. // A variable that appears in a private clause must not have a
  10995. // const-qualified type unless it is of class type with a mutable member.
  10996. if (rejectConstNotMutableType(*this, D, Type, OMPC_private, ELoc))
  10997. continue;
  10998. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  10999. // in a Construct]
  11000. // Variables with the predetermined data-sharing attributes may not be
  11001. // listed in data-sharing attributes clauses, except for the cases
  11002. // listed below. For these exceptions only, listing a predetermined
  11003. // variable in a data-sharing attribute clause is allowed and overrides
  11004. // the variable's predetermined data-sharing attributes.
  11005. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
  11006. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
  11007. Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
  11008. << getOpenMPClauseName(OMPC_private);
  11009. reportOriginalDsa(*this, DSAStack, D, DVar);
  11010. continue;
  11011. }
  11012. OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
  11013. // Variably modified types are not supported for tasks.
  11014. if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
  11015. isOpenMPTaskingDirective(CurrDir)) {
  11016. Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
  11017. << getOpenMPClauseName(OMPC_private) << Type
  11018. << getOpenMPDirectiveName(CurrDir);
  11019. bool IsDecl =
  11020. !VD ||
  11021. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  11022. Diag(D->getLocation(),
  11023. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  11024. << D;
  11025. continue;
  11026. }
  11027. // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
  11028. // A list item cannot appear in both a map clause and a data-sharing
  11029. // attribute clause on the same construct
  11030. //
  11031. // OpenMP 5.0 [2.19.7.1, Restrictions, p.7]
  11032. // A list item cannot appear in both a map clause and a data-sharing
  11033. // attribute clause on the same construct unless the construct is a
  11034. // combined construct.
  11035. if ((LangOpts.OpenMP <= 45 && isOpenMPTargetExecutionDirective(CurrDir)) ||
  11036. CurrDir == OMPD_target) {
  11037. OpenMPClauseKind ConflictKind;
  11038. if (DSAStack->checkMappableExprComponentListsForDecl(
  11039. VD, /*CurrentRegionOnly=*/true,
  11040. [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
  11041. OpenMPClauseKind WhereFoundClauseKind) -> bool {
  11042. ConflictKind = WhereFoundClauseKind;
  11043. return true;
  11044. })) {
  11045. Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
  11046. << getOpenMPClauseName(OMPC_private)
  11047. << getOpenMPClauseName(ConflictKind)
  11048. << getOpenMPDirectiveName(CurrDir);
  11049. reportOriginalDsa(*this, DSAStack, D, DVar);
  11050. continue;
  11051. }
  11052. }
  11053. // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
  11054. // A variable of class type (or array thereof) that appears in a private
  11055. // clause requires an accessible, unambiguous default constructor for the
  11056. // class type.
  11057. // Generate helper private variable and initialize it with the default
  11058. // value. The address of the original variable is replaced by the address of
  11059. // the new private variable in CodeGen. This new variable is not added to
  11060. // IdResolver, so the code in the OpenMP region uses original variable for
  11061. // proper diagnostics.
  11062. Type = Type.getUnqualifiedType();
  11063. VarDecl *VDPrivate =
  11064. buildVarDecl(*this, ELoc, Type, D->getName(),
  11065. D->hasAttrs() ? &D->getAttrs() : nullptr,
  11066. VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
  11067. ActOnUninitializedDecl(VDPrivate);
  11068. if (VDPrivate->isInvalidDecl())
  11069. continue;
  11070. DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
  11071. *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
  11072. DeclRefExpr *Ref = nullptr;
  11073. if (!VD && !CurContext->isDependentContext())
  11074. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
  11075. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
  11076. Vars.push_back((VD || CurContext->isDependentContext())
  11077. ? RefExpr->IgnoreParens()
  11078. : Ref);
  11079. PrivateCopies.push_back(VDPrivateRefExpr);
  11080. }
  11081. if (Vars.empty())
  11082. return nullptr;
  11083. return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
  11084. PrivateCopies);
  11085. }
  11086. namespace {
  11087. class DiagsUninitializedSeveretyRAII {
  11088. private:
  11089. DiagnosticsEngine &Diags;
  11090. SourceLocation SavedLoc;
  11091. bool IsIgnored = false;
  11092. public:
  11093. DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
  11094. bool IsIgnored)
  11095. : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
  11096. if (!IsIgnored) {
  11097. Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
  11098. /*Map*/ diag::Severity::Ignored, Loc);
  11099. }
  11100. }
  11101. ~DiagsUninitializedSeveretyRAII() {
  11102. if (!IsIgnored)
  11103. Diags.popMappings(SavedLoc);
  11104. }
  11105. };
  11106. }
  11107. OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
  11108. SourceLocation StartLoc,
  11109. SourceLocation LParenLoc,
  11110. SourceLocation EndLoc) {
  11111. SmallVector<Expr *, 8> Vars;
  11112. SmallVector<Expr *, 8> PrivateCopies;
  11113. SmallVector<Expr *, 8> Inits;
  11114. SmallVector<Decl *, 4> ExprCaptures;
  11115. bool IsImplicitClause =
  11116. StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
  11117. SourceLocation ImplicitClauseLoc = DSAStack->getConstructLoc();
  11118. for (Expr *RefExpr : VarList) {
  11119. assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
  11120. SourceLocation ELoc;
  11121. SourceRange ERange;
  11122. Expr *SimpleRefExpr = RefExpr;
  11123. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  11124. if (Res.second) {
  11125. // It will be analyzed later.
  11126. Vars.push_back(RefExpr);
  11127. PrivateCopies.push_back(nullptr);
  11128. Inits.push_back(nullptr);
  11129. }
  11130. ValueDecl *D = Res.first;
  11131. if (!D)
  11132. continue;
  11133. ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
  11134. QualType Type = D->getType();
  11135. auto *VD = dyn_cast<VarDecl>(D);
  11136. // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
  11137. // A variable that appears in a private clause must not have an incomplete
  11138. // type or a reference type.
  11139. if (RequireCompleteType(ELoc, Type,
  11140. diag::err_omp_firstprivate_incomplete_type))
  11141. continue;
  11142. Type = Type.getNonReferenceType();
  11143. // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
  11144. // A variable of class type (or array thereof) that appears in a private
  11145. // clause requires an accessible, unambiguous copy constructor for the
  11146. // class type.
  11147. QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
  11148. // If an implicit firstprivate variable found it was checked already.
  11149. DSAStackTy::DSAVarData TopDVar;
  11150. if (!IsImplicitClause) {
  11151. DSAStackTy::DSAVarData DVar =
  11152. DSAStack->getTopDSA(D, /*FromParent=*/false);
  11153. TopDVar = DVar;
  11154. OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
  11155. bool IsConstant = ElemType.isConstant(Context);
  11156. // OpenMP [2.4.13, Data-sharing Attribute Clauses]
  11157. // A list item that specifies a given variable may not appear in more
  11158. // than one clause on the same directive, except that a variable may be
  11159. // specified in both firstprivate and lastprivate clauses.
  11160. // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
  11161. // A list item may appear in a firstprivate or lastprivate clause but not
  11162. // both.
  11163. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
  11164. (isOpenMPDistributeDirective(CurrDir) ||
  11165. DVar.CKind != OMPC_lastprivate) &&
  11166. DVar.RefExpr) {
  11167. Diag(ELoc, diag::err_omp_wrong_dsa)
  11168. << getOpenMPClauseName(DVar.CKind)
  11169. << getOpenMPClauseName(OMPC_firstprivate);
  11170. reportOriginalDsa(*this, DSAStack, D, DVar);
  11171. continue;
  11172. }
  11173. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  11174. // in a Construct]
  11175. // Variables with the predetermined data-sharing attributes may not be
  11176. // listed in data-sharing attributes clauses, except for the cases
  11177. // listed below. For these exceptions only, listing a predetermined
  11178. // variable in a data-sharing attribute clause is allowed and overrides
  11179. // the variable's predetermined data-sharing attributes.
  11180. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  11181. // in a Construct, C/C++, p.2]
  11182. // Variables with const-qualified type having no mutable member may be
  11183. // listed in a firstprivate clause, even if they are static data members.
  11184. if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
  11185. DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
  11186. Diag(ELoc, diag::err_omp_wrong_dsa)
  11187. << getOpenMPClauseName(DVar.CKind)
  11188. << getOpenMPClauseName(OMPC_firstprivate);
  11189. reportOriginalDsa(*this, DSAStack, D, DVar);
  11190. continue;
  11191. }
  11192. // OpenMP [2.9.3.4, Restrictions, p.2]
  11193. // A list item that is private within a parallel region must not appear
  11194. // in a firstprivate clause on a worksharing construct if any of the
  11195. // worksharing regions arising from the worksharing construct ever bind
  11196. // to any of the parallel regions arising from the parallel construct.
  11197. // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
  11198. // A list item that is private within a teams region must not appear in a
  11199. // firstprivate clause on a distribute construct if any of the distribute
  11200. // regions arising from the distribute construct ever bind to any of the
  11201. // teams regions arising from the teams construct.
  11202. // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
  11203. // A list item that appears in a reduction clause of a teams construct
  11204. // must not appear in a firstprivate clause on a distribute construct if
  11205. // any of the distribute regions arising from the distribute construct
  11206. // ever bind to any of the teams regions arising from the teams construct.
  11207. if ((isOpenMPWorksharingDirective(CurrDir) ||
  11208. isOpenMPDistributeDirective(CurrDir)) &&
  11209. !isOpenMPParallelDirective(CurrDir) &&
  11210. !isOpenMPTeamsDirective(CurrDir)) {
  11211. DVar = DSAStack->getImplicitDSA(D, true);
  11212. if (DVar.CKind != OMPC_shared &&
  11213. (isOpenMPParallelDirective(DVar.DKind) ||
  11214. isOpenMPTeamsDirective(DVar.DKind) ||
  11215. DVar.DKind == OMPD_unknown)) {
  11216. Diag(ELoc, diag::err_omp_required_access)
  11217. << getOpenMPClauseName(OMPC_firstprivate)
  11218. << getOpenMPClauseName(OMPC_shared);
  11219. reportOriginalDsa(*this, DSAStack, D, DVar);
  11220. continue;
  11221. }
  11222. }
  11223. // OpenMP [2.9.3.4, Restrictions, p.3]
  11224. // A list item that appears in a reduction clause of a parallel construct
  11225. // must not appear in a firstprivate clause on a worksharing or task
  11226. // construct if any of the worksharing or task regions arising from the
  11227. // worksharing or task construct ever bind to any of the parallel regions
  11228. // arising from the parallel construct.
  11229. // OpenMP [2.9.3.4, Restrictions, p.4]
  11230. // A list item that appears in a reduction clause in worksharing
  11231. // construct must not appear in a firstprivate clause in a task construct
  11232. // encountered during execution of any of the worksharing regions arising
  11233. // from the worksharing construct.
  11234. if (isOpenMPTaskingDirective(CurrDir)) {
  11235. DVar = DSAStack->hasInnermostDSA(
  11236. D, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
  11237. [](OpenMPDirectiveKind K) {
  11238. return isOpenMPParallelDirective(K) ||
  11239. isOpenMPWorksharingDirective(K) ||
  11240. isOpenMPTeamsDirective(K);
  11241. },
  11242. /*FromParent=*/true);
  11243. if (DVar.CKind == OMPC_reduction &&
  11244. (isOpenMPParallelDirective(DVar.DKind) ||
  11245. isOpenMPWorksharingDirective(DVar.DKind) ||
  11246. isOpenMPTeamsDirective(DVar.DKind))) {
  11247. Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
  11248. << getOpenMPDirectiveName(DVar.DKind);
  11249. reportOriginalDsa(*this, DSAStack, D, DVar);
  11250. continue;
  11251. }
  11252. }
  11253. // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
  11254. // A list item cannot appear in both a map clause and a data-sharing
  11255. // attribute clause on the same construct
  11256. //
  11257. // OpenMP 5.0 [2.19.7.1, Restrictions, p.7]
  11258. // A list item cannot appear in both a map clause and a data-sharing
  11259. // attribute clause on the same construct unless the construct is a
  11260. // combined construct.
  11261. if ((LangOpts.OpenMP <= 45 &&
  11262. isOpenMPTargetExecutionDirective(CurrDir)) ||
  11263. CurrDir == OMPD_target) {
  11264. OpenMPClauseKind ConflictKind;
  11265. if (DSAStack->checkMappableExprComponentListsForDecl(
  11266. VD, /*CurrentRegionOnly=*/true,
  11267. [&ConflictKind](
  11268. OMPClauseMappableExprCommon::MappableExprComponentListRef,
  11269. OpenMPClauseKind WhereFoundClauseKind) {
  11270. ConflictKind = WhereFoundClauseKind;
  11271. return true;
  11272. })) {
  11273. Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
  11274. << getOpenMPClauseName(OMPC_firstprivate)
  11275. << getOpenMPClauseName(ConflictKind)
  11276. << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
  11277. reportOriginalDsa(*this, DSAStack, D, DVar);
  11278. continue;
  11279. }
  11280. }
  11281. }
  11282. // Variably modified types are not supported for tasks.
  11283. if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
  11284. isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
  11285. Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
  11286. << getOpenMPClauseName(OMPC_firstprivate) << Type
  11287. << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
  11288. bool IsDecl =
  11289. !VD ||
  11290. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  11291. Diag(D->getLocation(),
  11292. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  11293. << D;
  11294. continue;
  11295. }
  11296. Type = Type.getUnqualifiedType();
  11297. VarDecl *VDPrivate =
  11298. buildVarDecl(*this, ELoc, Type, D->getName(),
  11299. D->hasAttrs() ? &D->getAttrs() : nullptr,
  11300. VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
  11301. // Generate helper private variable and initialize it with the value of the
  11302. // original variable. The address of the original variable is replaced by
  11303. // the address of the new private variable in the CodeGen. This new variable
  11304. // is not added to IdResolver, so the code in the OpenMP region uses
  11305. // original variable for proper diagnostics and variable capturing.
  11306. Expr *VDInitRefExpr = nullptr;
  11307. // For arrays generate initializer for single element and replace it by the
  11308. // original array element in CodeGen.
  11309. if (Type->isArrayType()) {
  11310. VarDecl *VDInit =
  11311. buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
  11312. VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
  11313. Expr *Init = DefaultLvalueConversion(VDInitRefExpr).get();
  11314. ElemType = ElemType.getUnqualifiedType();
  11315. VarDecl *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
  11316. ".firstprivate.temp");
  11317. InitializedEntity Entity =
  11318. InitializedEntity::InitializeVariable(VDInitTemp);
  11319. InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
  11320. InitializationSequence InitSeq(*this, Entity, Kind, Init);
  11321. ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
  11322. if (Result.isInvalid())
  11323. VDPrivate->setInvalidDecl();
  11324. else
  11325. VDPrivate->setInit(Result.getAs<Expr>());
  11326. // Remove temp variable declaration.
  11327. Context.Deallocate(VDInitTemp);
  11328. } else {
  11329. VarDecl *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
  11330. ".firstprivate.temp");
  11331. VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
  11332. RefExpr->getExprLoc());
  11333. AddInitializerToDecl(VDPrivate,
  11334. DefaultLvalueConversion(VDInitRefExpr).get(),
  11335. /*DirectInit=*/false);
  11336. }
  11337. if (VDPrivate->isInvalidDecl()) {
  11338. if (IsImplicitClause) {
  11339. Diag(RefExpr->getExprLoc(),
  11340. diag::note_omp_task_predetermined_firstprivate_here);
  11341. }
  11342. continue;
  11343. }
  11344. CurContext->addDecl(VDPrivate);
  11345. DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
  11346. *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
  11347. RefExpr->getExprLoc());
  11348. DeclRefExpr *Ref = nullptr;
  11349. if (!VD && !CurContext->isDependentContext()) {
  11350. if (TopDVar.CKind == OMPC_lastprivate) {
  11351. Ref = TopDVar.PrivateCopy;
  11352. } else {
  11353. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
  11354. if (!isOpenMPCapturedDecl(D))
  11355. ExprCaptures.push_back(Ref->getDecl());
  11356. }
  11357. }
  11358. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
  11359. Vars.push_back((VD || CurContext->isDependentContext())
  11360. ? RefExpr->IgnoreParens()
  11361. : Ref);
  11362. PrivateCopies.push_back(VDPrivateRefExpr);
  11363. Inits.push_back(VDInitRefExpr);
  11364. }
  11365. if (Vars.empty())
  11366. return nullptr;
  11367. return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  11368. Vars, PrivateCopies, Inits,
  11369. buildPreInits(Context, ExprCaptures));
  11370. }
  11371. OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
  11372. SourceLocation StartLoc,
  11373. SourceLocation LParenLoc,
  11374. SourceLocation EndLoc) {
  11375. SmallVector<Expr *, 8> Vars;
  11376. SmallVector<Expr *, 8> SrcExprs;
  11377. SmallVector<Expr *, 8> DstExprs;
  11378. SmallVector<Expr *, 8> AssignmentOps;
  11379. SmallVector<Decl *, 4> ExprCaptures;
  11380. SmallVector<Expr *, 4> ExprPostUpdates;
  11381. for (Expr *RefExpr : VarList) {
  11382. assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
  11383. SourceLocation ELoc;
  11384. SourceRange ERange;
  11385. Expr *SimpleRefExpr = RefExpr;
  11386. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  11387. if (Res.second) {
  11388. // It will be analyzed later.
  11389. Vars.push_back(RefExpr);
  11390. SrcExprs.push_back(nullptr);
  11391. DstExprs.push_back(nullptr);
  11392. AssignmentOps.push_back(nullptr);
  11393. }
  11394. ValueDecl *D = Res.first;
  11395. if (!D)
  11396. continue;
  11397. QualType Type = D->getType();
  11398. auto *VD = dyn_cast<VarDecl>(D);
  11399. // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
  11400. // A variable that appears in a lastprivate clause must not have an
  11401. // incomplete type or a reference type.
  11402. if (RequireCompleteType(ELoc, Type,
  11403. diag::err_omp_lastprivate_incomplete_type))
  11404. continue;
  11405. Type = Type.getNonReferenceType();
  11406. // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
  11407. // A variable that is privatized must not have a const-qualified type
  11408. // unless it is of class type with a mutable member. This restriction does
  11409. // not apply to the firstprivate clause.
  11410. //
  11411. // OpenMP 3.1 [2.9.3.5, lastprivate clause, Restrictions]
  11412. // A variable that appears in a lastprivate clause must not have a
  11413. // const-qualified type unless it is of class type with a mutable member.
  11414. if (rejectConstNotMutableType(*this, D, Type, OMPC_lastprivate, ELoc))
  11415. continue;
  11416. OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
  11417. // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
  11418. // in a Construct]
  11419. // Variables with the predetermined data-sharing attributes may not be
  11420. // listed in data-sharing attributes clauses, except for the cases
  11421. // listed below.
  11422. // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
  11423. // A list item may appear in a firstprivate or lastprivate clause but not
  11424. // both.
  11425. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
  11426. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
  11427. (isOpenMPDistributeDirective(CurrDir) ||
  11428. DVar.CKind != OMPC_firstprivate) &&
  11429. (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
  11430. Diag(ELoc, diag::err_omp_wrong_dsa)
  11431. << getOpenMPClauseName(DVar.CKind)
  11432. << getOpenMPClauseName(OMPC_lastprivate);
  11433. reportOriginalDsa(*this, DSAStack, D, DVar);
  11434. continue;
  11435. }
  11436. // OpenMP [2.14.3.5, Restrictions, p.2]
  11437. // A list item that is private within a parallel region, or that appears in
  11438. // the reduction clause of a parallel construct, must not appear in a
  11439. // lastprivate clause on a worksharing construct if any of the corresponding
  11440. // worksharing regions ever binds to any of the corresponding parallel
  11441. // regions.
  11442. DSAStackTy::DSAVarData TopDVar = DVar;
  11443. if (isOpenMPWorksharingDirective(CurrDir) &&
  11444. !isOpenMPParallelDirective(CurrDir) &&
  11445. !isOpenMPTeamsDirective(CurrDir)) {
  11446. DVar = DSAStack->getImplicitDSA(D, true);
  11447. if (DVar.CKind != OMPC_shared) {
  11448. Diag(ELoc, diag::err_omp_required_access)
  11449. << getOpenMPClauseName(OMPC_lastprivate)
  11450. << getOpenMPClauseName(OMPC_shared);
  11451. reportOriginalDsa(*this, DSAStack, D, DVar);
  11452. continue;
  11453. }
  11454. }
  11455. // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
  11456. // A variable of class type (or array thereof) that appears in a
  11457. // lastprivate clause requires an accessible, unambiguous default
  11458. // constructor for the class type, unless the list item is also specified
  11459. // in a firstprivate clause.
  11460. // A variable of class type (or array thereof) that appears in a
  11461. // lastprivate clause requires an accessible, unambiguous copy assignment
  11462. // operator for the class type.
  11463. Type = Context.getBaseElementType(Type).getNonReferenceType();
  11464. VarDecl *SrcVD = buildVarDecl(*this, ERange.getBegin(),
  11465. Type.getUnqualifiedType(), ".lastprivate.src",
  11466. D->hasAttrs() ? &D->getAttrs() : nullptr);
  11467. DeclRefExpr *PseudoSrcExpr =
  11468. buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
  11469. VarDecl *DstVD =
  11470. buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
  11471. D->hasAttrs() ? &D->getAttrs() : nullptr);
  11472. DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
  11473. // For arrays generate assignment operation for single element and replace
  11474. // it by the original array element in CodeGen.
  11475. ExprResult AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
  11476. PseudoDstExpr, PseudoSrcExpr);
  11477. if (AssignmentOp.isInvalid())
  11478. continue;
  11479. AssignmentOp =
  11480. ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
  11481. if (AssignmentOp.isInvalid())
  11482. continue;
  11483. DeclRefExpr *Ref = nullptr;
  11484. if (!VD && !CurContext->isDependentContext()) {
  11485. if (TopDVar.CKind == OMPC_firstprivate) {
  11486. Ref = TopDVar.PrivateCopy;
  11487. } else {
  11488. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
  11489. if (!isOpenMPCapturedDecl(D))
  11490. ExprCaptures.push_back(Ref->getDecl());
  11491. }
  11492. if (TopDVar.CKind == OMPC_firstprivate ||
  11493. (!isOpenMPCapturedDecl(D) &&
  11494. Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
  11495. ExprResult RefRes = DefaultLvalueConversion(Ref);
  11496. if (!RefRes.isUsable())
  11497. continue;
  11498. ExprResult PostUpdateRes =
  11499. BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
  11500. RefRes.get());
  11501. if (!PostUpdateRes.isUsable())
  11502. continue;
  11503. ExprPostUpdates.push_back(
  11504. IgnoredValueConversions(PostUpdateRes.get()).get());
  11505. }
  11506. }
  11507. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
  11508. Vars.push_back((VD || CurContext->isDependentContext())
  11509. ? RefExpr->IgnoreParens()
  11510. : Ref);
  11511. SrcExprs.push_back(PseudoSrcExpr);
  11512. DstExprs.push_back(PseudoDstExpr);
  11513. AssignmentOps.push_back(AssignmentOp.get());
  11514. }
  11515. if (Vars.empty())
  11516. return nullptr;
  11517. return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  11518. Vars, SrcExprs, DstExprs, AssignmentOps,
  11519. buildPreInits(Context, ExprCaptures),
  11520. buildPostUpdate(*this, ExprPostUpdates));
  11521. }
  11522. OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
  11523. SourceLocation StartLoc,
  11524. SourceLocation LParenLoc,
  11525. SourceLocation EndLoc) {
  11526. SmallVector<Expr *, 8> Vars;
  11527. for (Expr *RefExpr : VarList) {
  11528. assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
  11529. SourceLocation ELoc;
  11530. SourceRange ERange;
  11531. Expr *SimpleRefExpr = RefExpr;
  11532. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  11533. if (Res.second) {
  11534. // It will be analyzed later.
  11535. Vars.push_back(RefExpr);
  11536. }
  11537. ValueDecl *D = Res.first;
  11538. if (!D)
  11539. continue;
  11540. auto *VD = dyn_cast<VarDecl>(D);
  11541. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  11542. // in a Construct]
  11543. // Variables with the predetermined data-sharing attributes may not be
  11544. // listed in data-sharing attributes clauses, except for the cases
  11545. // listed below. For these exceptions only, listing a predetermined
  11546. // variable in a data-sharing attribute clause is allowed and overrides
  11547. // the variable's predetermined data-sharing attributes.
  11548. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
  11549. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
  11550. DVar.RefExpr) {
  11551. Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
  11552. << getOpenMPClauseName(OMPC_shared);
  11553. reportOriginalDsa(*this, DSAStack, D, DVar);
  11554. continue;
  11555. }
  11556. DeclRefExpr *Ref = nullptr;
  11557. if (!VD && isOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
  11558. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
  11559. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
  11560. Vars.push_back((VD || !Ref || CurContext->isDependentContext())
  11561. ? RefExpr->IgnoreParens()
  11562. : Ref);
  11563. }
  11564. if (Vars.empty())
  11565. return nullptr;
  11566. return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
  11567. }
  11568. namespace {
  11569. class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
  11570. DSAStackTy *Stack;
  11571. public:
  11572. bool VisitDeclRefExpr(DeclRefExpr *E) {
  11573. if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
  11574. DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
  11575. if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
  11576. return false;
  11577. if (DVar.CKind != OMPC_unknown)
  11578. return true;
  11579. DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
  11580. VD, isOpenMPPrivate, [](OpenMPDirectiveKind) { return true; },
  11581. /*FromParent=*/true);
  11582. return DVarPrivate.CKind != OMPC_unknown;
  11583. }
  11584. return false;
  11585. }
  11586. bool VisitStmt(Stmt *S) {
  11587. for (Stmt *Child : S->children()) {
  11588. if (Child && Visit(Child))
  11589. return true;
  11590. }
  11591. return false;
  11592. }
  11593. explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
  11594. };
  11595. } // namespace
  11596. namespace {
  11597. // Transform MemberExpression for specified FieldDecl of current class to
  11598. // DeclRefExpr to specified OMPCapturedExprDecl.
  11599. class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
  11600. typedef TreeTransform<TransformExprToCaptures> BaseTransform;
  11601. ValueDecl *Field = nullptr;
  11602. DeclRefExpr *CapturedExpr = nullptr;
  11603. public:
  11604. TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
  11605. : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
  11606. ExprResult TransformMemberExpr(MemberExpr *E) {
  11607. if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
  11608. E->getMemberDecl() == Field) {
  11609. CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
  11610. return CapturedExpr;
  11611. }
  11612. return BaseTransform::TransformMemberExpr(E);
  11613. }
  11614. DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
  11615. };
  11616. } // namespace
  11617. template <typename T, typename U>
  11618. static T filterLookupForUDReductionAndMapper(
  11619. SmallVectorImpl<U> &Lookups, const llvm::function_ref<T(ValueDecl *)> Gen) {
  11620. for (U &Set : Lookups) {
  11621. for (auto *D : Set) {
  11622. if (T Res = Gen(cast<ValueDecl>(D)))
  11623. return Res;
  11624. }
  11625. }
  11626. return T();
  11627. }
  11628. static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D) {
  11629. assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case");
  11630. for (auto RD : D->redecls()) {
  11631. // Don't bother with extra checks if we already know this one isn't visible.
  11632. if (RD == D)
  11633. continue;
  11634. auto ND = cast<NamedDecl>(RD);
  11635. if (LookupResult::isVisible(SemaRef, ND))
  11636. return ND;
  11637. }
  11638. return nullptr;
  11639. }
  11640. static void
  11641. argumentDependentLookup(Sema &SemaRef, const DeclarationNameInfo &Id,
  11642. SourceLocation Loc, QualType Ty,
  11643. SmallVectorImpl<UnresolvedSet<8>> &Lookups) {
  11644. // Find all of the associated namespaces and classes based on the
  11645. // arguments we have.
  11646. Sema::AssociatedNamespaceSet AssociatedNamespaces;
  11647. Sema::AssociatedClassSet AssociatedClasses;
  11648. OpaqueValueExpr OVE(Loc, Ty, VK_LValue);
  11649. SemaRef.FindAssociatedClassesAndNamespaces(Loc, &OVE, AssociatedNamespaces,
  11650. AssociatedClasses);
  11651. // C++ [basic.lookup.argdep]p3:
  11652. // Let X be the lookup set produced by unqualified lookup (3.4.1)
  11653. // and let Y be the lookup set produced by argument dependent
  11654. // lookup (defined as follows). If X contains [...] then Y is
  11655. // empty. Otherwise Y is the set of declarations found in the
  11656. // namespaces associated with the argument types as described
  11657. // below. The set of declarations found by the lookup of the name
  11658. // is the union of X and Y.
  11659. //
  11660. // Here, we compute Y and add its members to the overloaded
  11661. // candidate set.
  11662. for (auto *NS : AssociatedNamespaces) {
  11663. // When considering an associated namespace, the lookup is the
  11664. // same as the lookup performed when the associated namespace is
  11665. // used as a qualifier (3.4.3.2) except that:
  11666. //
  11667. // -- Any using-directives in the associated namespace are
  11668. // ignored.
  11669. //
  11670. // -- Any namespace-scope friend functions declared in
  11671. // associated classes are visible within their respective
  11672. // namespaces even if they are not visible during an ordinary
  11673. // lookup (11.4).
  11674. DeclContext::lookup_result R = NS->lookup(Id.getName());
  11675. for (auto *D : R) {
  11676. auto *Underlying = D;
  11677. if (auto *USD = dyn_cast<UsingShadowDecl>(D))
  11678. Underlying = USD->getTargetDecl();
  11679. if (!isa<OMPDeclareReductionDecl>(Underlying) &&
  11680. !isa<OMPDeclareMapperDecl>(Underlying))
  11681. continue;
  11682. if (!SemaRef.isVisible(D)) {
  11683. D = findAcceptableDecl(SemaRef, D);
  11684. if (!D)
  11685. continue;
  11686. if (auto *USD = dyn_cast<UsingShadowDecl>(D))
  11687. Underlying = USD->getTargetDecl();
  11688. }
  11689. Lookups.emplace_back();
  11690. Lookups.back().addDecl(Underlying);
  11691. }
  11692. }
  11693. }
  11694. static ExprResult
  11695. buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
  11696. Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
  11697. const DeclarationNameInfo &ReductionId, QualType Ty,
  11698. CXXCastPath &BasePath, Expr *UnresolvedReduction) {
  11699. if (ReductionIdScopeSpec.isInvalid())
  11700. return ExprError();
  11701. SmallVector<UnresolvedSet<8>, 4> Lookups;
  11702. if (S) {
  11703. LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
  11704. Lookup.suppressDiagnostics();
  11705. while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
  11706. NamedDecl *D = Lookup.getRepresentativeDecl();
  11707. do {
  11708. S = S->getParent();
  11709. } while (S && !S->isDeclScope(D));
  11710. if (S)
  11711. S = S->getParent();
  11712. Lookups.emplace_back();
  11713. Lookups.back().append(Lookup.begin(), Lookup.end());
  11714. Lookup.clear();
  11715. }
  11716. } else if (auto *ULE =
  11717. cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
  11718. Lookups.push_back(UnresolvedSet<8>());
  11719. Decl *PrevD = nullptr;
  11720. for (NamedDecl *D : ULE->decls()) {
  11721. if (D == PrevD)
  11722. Lookups.push_back(UnresolvedSet<8>());
  11723. else if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(D))
  11724. Lookups.back().addDecl(DRD);
  11725. PrevD = D;
  11726. }
  11727. }
  11728. if (SemaRef.CurContext->isDependentContext() || Ty->isDependentType() ||
  11729. Ty->isInstantiationDependentType() ||
  11730. Ty->containsUnexpandedParameterPack() ||
  11731. filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) {
  11732. return !D->isInvalidDecl() &&
  11733. (D->getType()->isDependentType() ||
  11734. D->getType()->isInstantiationDependentType() ||
  11735. D->getType()->containsUnexpandedParameterPack());
  11736. })) {
  11737. UnresolvedSet<8> ResSet;
  11738. for (const UnresolvedSet<8> &Set : Lookups) {
  11739. if (Set.empty())
  11740. continue;
  11741. ResSet.append(Set.begin(), Set.end());
  11742. // The last item marks the end of all declarations at the specified scope.
  11743. ResSet.addDecl(Set[Set.size() - 1]);
  11744. }
  11745. return UnresolvedLookupExpr::Create(
  11746. SemaRef.Context, /*NamingClass=*/nullptr,
  11747. ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
  11748. /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
  11749. }
  11750. // Lookup inside the classes.
  11751. // C++ [over.match.oper]p3:
  11752. // For a unary operator @ with an operand of a type whose
  11753. // cv-unqualified version is T1, and for a binary operator @ with
  11754. // a left operand of a type whose cv-unqualified version is T1 and
  11755. // a right operand of a type whose cv-unqualified version is T2,
  11756. // three sets of candidate functions, designated member
  11757. // candidates, non-member candidates and built-in candidates, are
  11758. // constructed as follows:
  11759. // -- If T1 is a complete class type or a class currently being
  11760. // defined, the set of member candidates is the result of the
  11761. // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
  11762. // the set of member candidates is empty.
  11763. LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
  11764. Lookup.suppressDiagnostics();
  11765. if (const auto *TyRec = Ty->getAs<RecordType>()) {
  11766. // Complete the type if it can be completed.
  11767. // If the type is neither complete nor being defined, bail out now.
  11768. if (SemaRef.isCompleteType(Loc, Ty) || TyRec->isBeingDefined() ||
  11769. TyRec->getDecl()->getDefinition()) {
  11770. Lookup.clear();
  11771. SemaRef.LookupQualifiedName(Lookup, TyRec->getDecl());
  11772. if (Lookup.empty()) {
  11773. Lookups.emplace_back();
  11774. Lookups.back().append(Lookup.begin(), Lookup.end());
  11775. }
  11776. }
  11777. }
  11778. // Perform ADL.
  11779. if (SemaRef.getLangOpts().CPlusPlus)
  11780. argumentDependentLookup(SemaRef, ReductionId, Loc, Ty, Lookups);
  11781. if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
  11782. Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
  11783. if (!D->isInvalidDecl() &&
  11784. SemaRef.Context.hasSameType(D->getType(), Ty))
  11785. return D;
  11786. return nullptr;
  11787. }))
  11788. return SemaRef.BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(),
  11789. VK_LValue, Loc);
  11790. if (SemaRef.getLangOpts().CPlusPlus) {
  11791. if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
  11792. Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
  11793. if (!D->isInvalidDecl() &&
  11794. SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
  11795. !Ty.isMoreQualifiedThan(D->getType()))
  11796. return D;
  11797. return nullptr;
  11798. })) {
  11799. CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
  11800. /*DetectVirtual=*/false);
  11801. if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
  11802. if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
  11803. VD->getType().getUnqualifiedType()))) {
  11804. if (SemaRef.CheckBaseClassAccess(
  11805. Loc, VD->getType(), Ty, Paths.front(),
  11806. /*DiagID=*/0) != Sema::AR_inaccessible) {
  11807. SemaRef.BuildBasePathArray(Paths, BasePath);
  11808. return SemaRef.BuildDeclRefExpr(
  11809. VD, VD->getType().getNonReferenceType(), VK_LValue, Loc);
  11810. }
  11811. }
  11812. }
  11813. }
  11814. }
  11815. if (ReductionIdScopeSpec.isSet()) {
  11816. SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range;
  11817. return ExprError();
  11818. }
  11819. return ExprEmpty();
  11820. }
  11821. namespace {
  11822. /// Data for the reduction-based clauses.
  11823. struct ReductionData {
  11824. /// List of original reduction items.
  11825. SmallVector<Expr *, 8> Vars;
  11826. /// List of private copies of the reduction items.
  11827. SmallVector<Expr *, 8> Privates;
  11828. /// LHS expressions for the reduction_op expressions.
  11829. SmallVector<Expr *, 8> LHSs;
  11830. /// RHS expressions for the reduction_op expressions.
  11831. SmallVector<Expr *, 8> RHSs;
  11832. /// Reduction operation expression.
  11833. SmallVector<Expr *, 8> ReductionOps;
  11834. /// Taskgroup descriptors for the corresponding reduction items in
  11835. /// in_reduction clauses.
  11836. SmallVector<Expr *, 8> TaskgroupDescriptors;
  11837. /// List of captures for clause.
  11838. SmallVector<Decl *, 4> ExprCaptures;
  11839. /// List of postupdate expressions.
  11840. SmallVector<Expr *, 4> ExprPostUpdates;
  11841. ReductionData() = delete;
  11842. /// Reserves required memory for the reduction data.
  11843. ReductionData(unsigned Size) {
  11844. Vars.reserve(Size);
  11845. Privates.reserve(Size);
  11846. LHSs.reserve(Size);
  11847. RHSs.reserve(Size);
  11848. ReductionOps.reserve(Size);
  11849. TaskgroupDescriptors.reserve(Size);
  11850. ExprCaptures.reserve(Size);
  11851. ExprPostUpdates.reserve(Size);
  11852. }
  11853. /// Stores reduction item and reduction operation only (required for dependent
  11854. /// reduction item).
  11855. void push(Expr *Item, Expr *ReductionOp) {
  11856. Vars.emplace_back(Item);
  11857. Privates.emplace_back(nullptr);
  11858. LHSs.emplace_back(nullptr);
  11859. RHSs.emplace_back(nullptr);
  11860. ReductionOps.emplace_back(ReductionOp);
  11861. TaskgroupDescriptors.emplace_back(nullptr);
  11862. }
  11863. /// Stores reduction data.
  11864. void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS, Expr *ReductionOp,
  11865. Expr *TaskgroupDescriptor) {
  11866. Vars.emplace_back(Item);
  11867. Privates.emplace_back(Private);
  11868. LHSs.emplace_back(LHS);
  11869. RHSs.emplace_back(RHS);
  11870. ReductionOps.emplace_back(ReductionOp);
  11871. TaskgroupDescriptors.emplace_back(TaskgroupDescriptor);
  11872. }
  11873. };
  11874. } // namespace
  11875. static bool checkOMPArraySectionConstantForReduction(
  11876. ASTContext &Context, const OMPArraySectionExpr *OASE, bool &SingleElement,
  11877. SmallVectorImpl<llvm::APSInt> &ArraySizes) {
  11878. const Expr *Length = OASE->getLength();
  11879. if (Length == nullptr) {
  11880. // For array sections of the form [1:] or [:], we would need to analyze
  11881. // the lower bound...
  11882. if (OASE->getColonLoc().isValid())
  11883. return false;
  11884. // This is an array subscript which has implicit length 1!
  11885. SingleElement = true;
  11886. ArraySizes.push_back(llvm::APSInt::get(1));
  11887. } else {
  11888. Expr::EvalResult Result;
  11889. if (!Length->EvaluateAsInt(Result, Context))
  11890. return false;
  11891. llvm::APSInt ConstantLengthValue = Result.Val.getInt();
  11892. SingleElement = (ConstantLengthValue.getSExtValue() == 1);
  11893. ArraySizes.push_back(ConstantLengthValue);
  11894. }
  11895. // Get the base of this array section and walk up from there.
  11896. const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
  11897. // We require length = 1 for all array sections except the right-most to
  11898. // guarantee that the memory region is contiguous and has no holes in it.
  11899. while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) {
  11900. Length = TempOASE->getLength();
  11901. if (Length == nullptr) {
  11902. // For array sections of the form [1:] or [:], we would need to analyze
  11903. // the lower bound...
  11904. if (OASE->getColonLoc().isValid())
  11905. return false;
  11906. // This is an array subscript which has implicit length 1!
  11907. ArraySizes.push_back(llvm::APSInt::get(1));
  11908. } else {
  11909. Expr::EvalResult Result;
  11910. if (!Length->EvaluateAsInt(Result, Context))
  11911. return false;
  11912. llvm::APSInt ConstantLengthValue = Result.Val.getInt();
  11913. if (ConstantLengthValue.getSExtValue() != 1)
  11914. return false;
  11915. ArraySizes.push_back(ConstantLengthValue);
  11916. }
  11917. Base = TempOASE->getBase()->IgnoreParenImpCasts();
  11918. }
  11919. // If we have a single element, we don't need to add the implicit lengths.
  11920. if (!SingleElement) {
  11921. while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) {
  11922. // Has implicit length 1!
  11923. ArraySizes.push_back(llvm::APSInt::get(1));
  11924. Base = TempASE->getBase()->IgnoreParenImpCasts();
  11925. }
  11926. }
  11927. // This array section can be privatized as a single value or as a constant
  11928. // sized array.
  11929. return true;
  11930. }
  11931. static bool actOnOMPReductionKindClause(
  11932. Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind,
  11933. ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
  11934. SourceLocation ColonLoc, SourceLocation EndLoc,
  11935. CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
  11936. ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) {
  11937. DeclarationName DN = ReductionId.getName();
  11938. OverloadedOperatorKind OOK = DN.getCXXOverloadedOperator();
  11939. BinaryOperatorKind BOK = BO_Comma;
  11940. ASTContext &Context = S.Context;
  11941. // OpenMP [2.14.3.6, reduction clause]
  11942. // C
  11943. // reduction-identifier is either an identifier or one of the following
  11944. // operators: +, -, *, &, |, ^, && and ||
  11945. // C++
  11946. // reduction-identifier is either an id-expression or one of the following
  11947. // operators: +, -, *, &, |, ^, && and ||
  11948. switch (OOK) {
  11949. case OO_Plus:
  11950. case OO_Minus:
  11951. BOK = BO_Add;
  11952. break;
  11953. case OO_Star:
  11954. BOK = BO_Mul;
  11955. break;
  11956. case OO_Amp:
  11957. BOK = BO_And;
  11958. break;
  11959. case OO_Pipe:
  11960. BOK = BO_Or;
  11961. break;
  11962. case OO_Caret:
  11963. BOK = BO_Xor;
  11964. break;
  11965. case OO_AmpAmp:
  11966. BOK = BO_LAnd;
  11967. break;
  11968. case OO_PipePipe:
  11969. BOK = BO_LOr;
  11970. break;
  11971. case OO_New:
  11972. case OO_Delete:
  11973. case OO_Array_New:
  11974. case OO_Array_Delete:
  11975. case OO_Slash:
  11976. case OO_Percent:
  11977. case OO_Tilde:
  11978. case OO_Exclaim:
  11979. case OO_Equal:
  11980. case OO_Less:
  11981. case OO_Greater:
  11982. case OO_LessEqual:
  11983. case OO_GreaterEqual:
  11984. case OO_PlusEqual:
  11985. case OO_MinusEqual:
  11986. case OO_StarEqual:
  11987. case OO_SlashEqual:
  11988. case OO_PercentEqual:
  11989. case OO_CaretEqual:
  11990. case OO_AmpEqual:
  11991. case OO_PipeEqual:
  11992. case OO_LessLess:
  11993. case OO_GreaterGreater:
  11994. case OO_LessLessEqual:
  11995. case OO_GreaterGreaterEqual:
  11996. case OO_EqualEqual:
  11997. case OO_ExclaimEqual:
  11998. case OO_Spaceship:
  11999. case OO_PlusPlus:
  12000. case OO_MinusMinus:
  12001. case OO_Comma:
  12002. case OO_ArrowStar:
  12003. case OO_Arrow:
  12004. case OO_Call:
  12005. case OO_Subscript:
  12006. case OO_Conditional:
  12007. case OO_Coawait:
  12008. case NUM_OVERLOADED_OPERATORS:
  12009. llvm_unreachable("Unexpected reduction identifier");
  12010. case OO_None:
  12011. if (IdentifierInfo *II = DN.getAsIdentifierInfo()) {
  12012. if (II->isStr("max"))
  12013. BOK = BO_GT;
  12014. else if (II->isStr("min"))
  12015. BOK = BO_LT;
  12016. }
  12017. break;
  12018. }
  12019. SourceRange ReductionIdRange;
  12020. if (ReductionIdScopeSpec.isValid())
  12021. ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
  12022. else
  12023. ReductionIdRange.setBegin(ReductionId.getBeginLoc());
  12024. ReductionIdRange.setEnd(ReductionId.getEndLoc());
  12025. auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
  12026. bool FirstIter = true;
  12027. for (Expr *RefExpr : VarList) {
  12028. assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
  12029. // OpenMP [2.1, C/C++]
  12030. // A list item is a variable or array section, subject to the restrictions
  12031. // specified in Section 2.4 on page 42 and in each of the sections
  12032. // describing clauses and directives for which a list appears.
  12033. // OpenMP [2.14.3.3, Restrictions, p.1]
  12034. // A variable that is part of another variable (as an array or
  12035. // structure element) cannot appear in a private clause.
  12036. if (!FirstIter && IR != ER)
  12037. ++IR;
  12038. FirstIter = false;
  12039. SourceLocation ELoc;
  12040. SourceRange ERange;
  12041. Expr *SimpleRefExpr = RefExpr;
  12042. auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
  12043. /*AllowArraySection=*/true);
  12044. if (Res.second) {
  12045. // Try to find 'declare reduction' corresponding construct before using
  12046. // builtin/overloaded operators.
  12047. QualType Type = Context.DependentTy;
  12048. CXXCastPath BasePath;
  12049. ExprResult DeclareReductionRef = buildDeclareReductionRef(
  12050. S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
  12051. ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
  12052. Expr *ReductionOp = nullptr;
  12053. if (S.CurContext->isDependentContext() &&
  12054. (DeclareReductionRef.isUnset() ||
  12055. isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
  12056. ReductionOp = DeclareReductionRef.get();
  12057. // It will be analyzed later.
  12058. RD.push(RefExpr, ReductionOp);
  12059. }
  12060. ValueDecl *D = Res.first;
  12061. if (!D)
  12062. continue;
  12063. Expr *TaskgroupDescriptor = nullptr;
  12064. QualType Type;
  12065. auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
  12066. auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
  12067. if (ASE) {
  12068. Type = ASE->getType().getNonReferenceType();
  12069. } else if (OASE) {
  12070. QualType BaseType =
  12071. OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
  12072. if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
  12073. Type = ATy->getElementType();
  12074. else
  12075. Type = BaseType->getPointeeType();
  12076. Type = Type.getNonReferenceType();
  12077. } else {
  12078. Type = Context.getBaseElementType(D->getType().getNonReferenceType());
  12079. }
  12080. auto *VD = dyn_cast<VarDecl>(D);
  12081. // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
  12082. // A variable that appears in a private clause must not have an incomplete
  12083. // type or a reference type.
  12084. if (S.RequireCompleteType(ELoc, D->getType(),
  12085. diag::err_omp_reduction_incomplete_type))
  12086. continue;
  12087. // OpenMP [2.14.3.6, reduction clause, Restrictions]
  12088. // A list item that appears in a reduction clause must not be
  12089. // const-qualified.
  12090. if (rejectConstNotMutableType(S, D, Type, ClauseKind, ELoc,
  12091. /*AcceptIfMutable*/ false, ASE || OASE))
  12092. continue;
  12093. OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective();
  12094. // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
  12095. // If a list-item is a reference type then it must bind to the same object
  12096. // for all threads of the team.
  12097. if (!ASE && !OASE) {
  12098. if (VD) {
  12099. VarDecl *VDDef = VD->getDefinition();
  12100. if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
  12101. DSARefChecker Check(Stack);
  12102. if (Check.Visit(VDDef->getInit())) {
  12103. S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg)
  12104. << getOpenMPClauseName(ClauseKind) << ERange;
  12105. S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
  12106. continue;
  12107. }
  12108. }
  12109. }
  12110. // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
  12111. // in a Construct]
  12112. // Variables with the predetermined data-sharing attributes may not be
  12113. // listed in data-sharing attributes clauses, except for the cases
  12114. // listed below. For these exceptions only, listing a predetermined
  12115. // variable in a data-sharing attribute clause is allowed and overrides
  12116. // the variable's predetermined data-sharing attributes.
  12117. // OpenMP [2.14.3.6, Restrictions, p.3]
  12118. // Any number of reduction clauses can be specified on the directive,
  12119. // but a list item can appear only once in the reduction clauses for that
  12120. // directive.
  12121. DSAStackTy::DSAVarData DVar = Stack->getTopDSA(D, /*FromParent=*/false);
  12122. if (DVar.CKind == OMPC_reduction) {
  12123. S.Diag(ELoc, diag::err_omp_once_referenced)
  12124. << getOpenMPClauseName(ClauseKind);
  12125. if (DVar.RefExpr)
  12126. S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
  12127. continue;
  12128. }
  12129. if (DVar.CKind != OMPC_unknown) {
  12130. S.Diag(ELoc, diag::err_omp_wrong_dsa)
  12131. << getOpenMPClauseName(DVar.CKind)
  12132. << getOpenMPClauseName(OMPC_reduction);
  12133. reportOriginalDsa(S, Stack, D, DVar);
  12134. continue;
  12135. }
  12136. // OpenMP [2.14.3.6, Restrictions, p.1]
  12137. // A list item that appears in a reduction clause of a worksharing
  12138. // construct must be shared in the parallel regions to which any of the
  12139. // worksharing regions arising from the worksharing construct bind.
  12140. if (isOpenMPWorksharingDirective(CurrDir) &&
  12141. !isOpenMPParallelDirective(CurrDir) &&
  12142. !isOpenMPTeamsDirective(CurrDir)) {
  12143. DVar = Stack->getImplicitDSA(D, true);
  12144. if (DVar.CKind != OMPC_shared) {
  12145. S.Diag(ELoc, diag::err_omp_required_access)
  12146. << getOpenMPClauseName(OMPC_reduction)
  12147. << getOpenMPClauseName(OMPC_shared);
  12148. reportOriginalDsa(S, Stack, D, DVar);
  12149. continue;
  12150. }
  12151. }
  12152. }
  12153. // Try to find 'declare reduction' corresponding construct before using
  12154. // builtin/overloaded operators.
  12155. CXXCastPath BasePath;
  12156. ExprResult DeclareReductionRef = buildDeclareReductionRef(
  12157. S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
  12158. ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
  12159. if (DeclareReductionRef.isInvalid())
  12160. continue;
  12161. if (S.CurContext->isDependentContext() &&
  12162. (DeclareReductionRef.isUnset() ||
  12163. isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
  12164. RD.push(RefExpr, DeclareReductionRef.get());
  12165. continue;
  12166. }
  12167. if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
  12168. // Not allowed reduction identifier is found.
  12169. S.Diag(ReductionId.getBeginLoc(),
  12170. diag::err_omp_unknown_reduction_identifier)
  12171. << Type << ReductionIdRange;
  12172. continue;
  12173. }
  12174. // OpenMP [2.14.3.6, reduction clause, Restrictions]
  12175. // The type of a list item that appears in a reduction clause must be valid
  12176. // for the reduction-identifier. For a max or min reduction in C, the type
  12177. // of the list item must be an allowed arithmetic data type: char, int,
  12178. // float, double, or _Bool, possibly modified with long, short, signed, or
  12179. // unsigned. For a max or min reduction in C++, the type of the list item
  12180. // must be an allowed arithmetic data type: char, wchar_t, int, float,
  12181. // double, or bool, possibly modified with long, short, signed, or unsigned.
  12182. if (DeclareReductionRef.isUnset()) {
  12183. if ((BOK == BO_GT || BOK == BO_LT) &&
  12184. !(Type->isScalarType() ||
  12185. (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
  12186. S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
  12187. << getOpenMPClauseName(ClauseKind) << S.getLangOpts().CPlusPlus;
  12188. if (!ASE && !OASE) {
  12189. bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
  12190. VarDecl::DeclarationOnly;
  12191. S.Diag(D->getLocation(),
  12192. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  12193. << D;
  12194. }
  12195. continue;
  12196. }
  12197. if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
  12198. !S.getLangOpts().CPlusPlus && Type->isFloatingType()) {
  12199. S.Diag(ELoc, diag::err_omp_clause_floating_type_arg)
  12200. << getOpenMPClauseName(ClauseKind);
  12201. if (!ASE && !OASE) {
  12202. bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
  12203. VarDecl::DeclarationOnly;
  12204. S.Diag(D->getLocation(),
  12205. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  12206. << D;
  12207. }
  12208. continue;
  12209. }
  12210. }
  12211. Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
  12212. VarDecl *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs",
  12213. D->hasAttrs() ? &D->getAttrs() : nullptr);
  12214. VarDecl *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(),
  12215. D->hasAttrs() ? &D->getAttrs() : nullptr);
  12216. QualType PrivateTy = Type;
  12217. // Try if we can determine constant lengths for all array sections and avoid
  12218. // the VLA.
  12219. bool ConstantLengthOASE = false;
  12220. if (OASE) {
  12221. bool SingleElement;
  12222. llvm::SmallVector<llvm::APSInt, 4> ArraySizes;
  12223. ConstantLengthOASE = checkOMPArraySectionConstantForReduction(
  12224. Context, OASE, SingleElement, ArraySizes);
  12225. // If we don't have a single element, we must emit a constant array type.
  12226. if (ConstantLengthOASE && !SingleElement) {
  12227. for (llvm::APSInt &Size : ArraySizes)
  12228. PrivateTy = Context.getConstantArrayType(PrivateTy, Size, nullptr,
  12229. ArrayType::Normal,
  12230. /*IndexTypeQuals=*/0);
  12231. }
  12232. }
  12233. if ((OASE && !ConstantLengthOASE) ||
  12234. (!OASE && !ASE &&
  12235. D->getType().getNonReferenceType()->isVariablyModifiedType())) {
  12236. if (!Context.getTargetInfo().isVLASupported()) {
  12237. if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective())) {
  12238. S.Diag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
  12239. S.Diag(ELoc, diag::note_vla_unsupported);
  12240. } else {
  12241. S.targetDiag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
  12242. S.targetDiag(ELoc, diag::note_vla_unsupported);
  12243. }
  12244. continue;
  12245. }
  12246. // For arrays/array sections only:
  12247. // Create pseudo array type for private copy. The size for this array will
  12248. // be generated during codegen.
  12249. // For array subscripts or single variables Private Ty is the same as Type
  12250. // (type of the variable or single array element).
  12251. PrivateTy = Context.getVariableArrayType(
  12252. Type,
  12253. new (Context) OpaqueValueExpr(ELoc, Context.getSizeType(), VK_RValue),
  12254. ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
  12255. } else if (!ASE && !OASE &&
  12256. Context.getAsArrayType(D->getType().getNonReferenceType())) {
  12257. PrivateTy = D->getType().getNonReferenceType();
  12258. }
  12259. // Private copy.
  12260. VarDecl *PrivateVD =
  12261. buildVarDecl(S, ELoc, PrivateTy, D->getName(),
  12262. D->hasAttrs() ? &D->getAttrs() : nullptr,
  12263. VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
  12264. // Add initializer for private variable.
  12265. Expr *Init = nullptr;
  12266. DeclRefExpr *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc);
  12267. DeclRefExpr *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc);
  12268. if (DeclareReductionRef.isUsable()) {
  12269. auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
  12270. auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
  12271. if (DRD->getInitializer()) {
  12272. Init = DRDRef;
  12273. RHSVD->setInit(DRDRef);
  12274. RHSVD->setInitStyle(VarDecl::CallInit);
  12275. }
  12276. } else {
  12277. switch (BOK) {
  12278. case BO_Add:
  12279. case BO_Xor:
  12280. case BO_Or:
  12281. case BO_LOr:
  12282. // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
  12283. if (Type->isScalarType() || Type->isAnyComplexType())
  12284. Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get();
  12285. break;
  12286. case BO_Mul:
  12287. case BO_LAnd:
  12288. if (Type->isScalarType() || Type->isAnyComplexType()) {
  12289. // '*' and '&&' reduction ops - initializer is '1'.
  12290. Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get();
  12291. }
  12292. break;
  12293. case BO_And: {
  12294. // '&' reduction op - initializer is '~0'.
  12295. QualType OrigType = Type;
  12296. if (auto *ComplexTy = OrigType->getAs<ComplexType>())
  12297. Type = ComplexTy->getElementType();
  12298. if (Type->isRealFloatingType()) {
  12299. llvm::APFloat InitValue =
  12300. llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
  12301. /*isIEEE=*/true);
  12302. Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
  12303. Type, ELoc);
  12304. } else if (Type->isScalarType()) {
  12305. uint64_t Size = Context.getTypeSize(Type);
  12306. QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
  12307. llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
  12308. Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
  12309. }
  12310. if (Init && OrigType->isAnyComplexType()) {
  12311. // Init = 0xFFFF + 0xFFFFi;
  12312. auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
  12313. Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
  12314. }
  12315. Type = OrigType;
  12316. break;
  12317. }
  12318. case BO_LT:
  12319. case BO_GT: {
  12320. // 'min' reduction op - initializer is 'Largest representable number in
  12321. // the reduction list item type'.
  12322. // 'max' reduction op - initializer is 'Least representable number in
  12323. // the reduction list item type'.
  12324. if (Type->isIntegerType() || Type->isPointerType()) {
  12325. bool IsSigned = Type->hasSignedIntegerRepresentation();
  12326. uint64_t Size = Context.getTypeSize(Type);
  12327. QualType IntTy =
  12328. Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
  12329. llvm::APInt InitValue =
  12330. (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
  12331. : llvm::APInt::getMinValue(Size)
  12332. : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
  12333. : llvm::APInt::getMaxValue(Size);
  12334. Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
  12335. if (Type->isPointerType()) {
  12336. // Cast to pointer type.
  12337. ExprResult CastExpr = S.BuildCStyleCastExpr(
  12338. ELoc, Context.getTrivialTypeSourceInfo(Type, ELoc), ELoc, Init);
  12339. if (CastExpr.isInvalid())
  12340. continue;
  12341. Init = CastExpr.get();
  12342. }
  12343. } else if (Type->isRealFloatingType()) {
  12344. llvm::APFloat InitValue = llvm::APFloat::getLargest(
  12345. Context.getFloatTypeSemantics(Type), BOK != BO_LT);
  12346. Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
  12347. Type, ELoc);
  12348. }
  12349. break;
  12350. }
  12351. case BO_PtrMemD:
  12352. case BO_PtrMemI:
  12353. case BO_MulAssign:
  12354. case BO_Div:
  12355. case BO_Rem:
  12356. case BO_Sub:
  12357. case BO_Shl:
  12358. case BO_Shr:
  12359. case BO_LE:
  12360. case BO_GE:
  12361. case BO_EQ:
  12362. case BO_NE:
  12363. case BO_Cmp:
  12364. case BO_AndAssign:
  12365. case BO_XorAssign:
  12366. case BO_OrAssign:
  12367. case BO_Assign:
  12368. case BO_AddAssign:
  12369. case BO_SubAssign:
  12370. case BO_DivAssign:
  12371. case BO_RemAssign:
  12372. case BO_ShlAssign:
  12373. case BO_ShrAssign:
  12374. case BO_Comma:
  12375. llvm_unreachable("Unexpected reduction operation");
  12376. }
  12377. }
  12378. if (Init && DeclareReductionRef.isUnset())
  12379. S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false);
  12380. else if (!Init)
  12381. S.ActOnUninitializedDecl(RHSVD);
  12382. if (RHSVD->isInvalidDecl())
  12383. continue;
  12384. if (!RHSVD->hasInit() &&
  12385. (DeclareReductionRef.isUnset() || !S.LangOpts.CPlusPlus)) {
  12386. S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible)
  12387. << Type << ReductionIdRange;
  12388. bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
  12389. VarDecl::DeclarationOnly;
  12390. S.Diag(D->getLocation(),
  12391. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  12392. << D;
  12393. continue;
  12394. }
  12395. // Store initializer for single element in private copy. Will be used during
  12396. // codegen.
  12397. PrivateVD->setInit(RHSVD->getInit());
  12398. PrivateVD->setInitStyle(RHSVD->getInitStyle());
  12399. DeclRefExpr *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc);
  12400. ExprResult ReductionOp;
  12401. if (DeclareReductionRef.isUsable()) {
  12402. QualType RedTy = DeclareReductionRef.get()->getType();
  12403. QualType PtrRedTy = Context.getPointerType(RedTy);
  12404. ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
  12405. ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
  12406. if (!BasePath.empty()) {
  12407. LHS = S.DefaultLvalueConversion(LHS.get());
  12408. RHS = S.DefaultLvalueConversion(RHS.get());
  12409. LHS = ImplicitCastExpr::Create(Context, PtrRedTy,
  12410. CK_UncheckedDerivedToBase, LHS.get(),
  12411. &BasePath, LHS.get()->getValueKind());
  12412. RHS = ImplicitCastExpr::Create(Context, PtrRedTy,
  12413. CK_UncheckedDerivedToBase, RHS.get(),
  12414. &BasePath, RHS.get()->getValueKind());
  12415. }
  12416. FunctionProtoType::ExtProtoInfo EPI;
  12417. QualType Params[] = {PtrRedTy, PtrRedTy};
  12418. QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
  12419. auto *OVE = new (Context) OpaqueValueExpr(
  12420. ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary,
  12421. S.DefaultLvalueConversion(DeclareReductionRef.get()).get());
  12422. Expr *Args[] = {LHS.get(), RHS.get()};
  12423. ReductionOp =
  12424. CallExpr::Create(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc);
  12425. } else {
  12426. ReductionOp = S.BuildBinOp(
  12427. Stack->getCurScope(), ReductionId.getBeginLoc(), BOK, LHSDRE, RHSDRE);
  12428. if (ReductionOp.isUsable()) {
  12429. if (BOK != BO_LT && BOK != BO_GT) {
  12430. ReductionOp =
  12431. S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
  12432. BO_Assign, LHSDRE, ReductionOp.get());
  12433. } else {
  12434. auto *ConditionalOp = new (Context)
  12435. ConditionalOperator(ReductionOp.get(), ELoc, LHSDRE, ELoc, RHSDRE,
  12436. Type, VK_LValue, OK_Ordinary);
  12437. ReductionOp =
  12438. S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
  12439. BO_Assign, LHSDRE, ConditionalOp);
  12440. }
  12441. if (ReductionOp.isUsable())
  12442. ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get(),
  12443. /*DiscardedValue*/ false);
  12444. }
  12445. if (!ReductionOp.isUsable())
  12446. continue;
  12447. }
  12448. // OpenMP [2.15.4.6, Restrictions, p.2]
  12449. // A list item that appears in an in_reduction clause of a task construct
  12450. // must appear in a task_reduction clause of a construct associated with a
  12451. // taskgroup region that includes the participating task in its taskgroup
  12452. // set. The construct associated with the innermost region that meets this
  12453. // condition must specify the same reduction-identifier as the in_reduction
  12454. // clause.
  12455. if (ClauseKind == OMPC_in_reduction) {
  12456. SourceRange ParentSR;
  12457. BinaryOperatorKind ParentBOK;
  12458. const Expr *ParentReductionOp;
  12459. Expr *ParentBOKTD, *ParentReductionOpTD;
  12460. DSAStackTy::DSAVarData ParentBOKDSA =
  12461. Stack->getTopMostTaskgroupReductionData(D, ParentSR, ParentBOK,
  12462. ParentBOKTD);
  12463. DSAStackTy::DSAVarData ParentReductionOpDSA =
  12464. Stack->getTopMostTaskgroupReductionData(
  12465. D, ParentSR, ParentReductionOp, ParentReductionOpTD);
  12466. bool IsParentBOK = ParentBOKDSA.DKind != OMPD_unknown;
  12467. bool IsParentReductionOp = ParentReductionOpDSA.DKind != OMPD_unknown;
  12468. if (!IsParentBOK && !IsParentReductionOp) {
  12469. S.Diag(ELoc, diag::err_omp_in_reduction_not_task_reduction);
  12470. continue;
  12471. }
  12472. if ((DeclareReductionRef.isUnset() && IsParentReductionOp) ||
  12473. (DeclareReductionRef.isUsable() && IsParentBOK) || BOK != ParentBOK ||
  12474. IsParentReductionOp) {
  12475. bool EmitError = true;
  12476. if (IsParentReductionOp && DeclareReductionRef.isUsable()) {
  12477. llvm::FoldingSetNodeID RedId, ParentRedId;
  12478. ParentReductionOp->Profile(ParentRedId, Context, /*Canonical=*/true);
  12479. DeclareReductionRef.get()->Profile(RedId, Context,
  12480. /*Canonical=*/true);
  12481. EmitError = RedId != ParentRedId;
  12482. }
  12483. if (EmitError) {
  12484. S.Diag(ReductionId.getBeginLoc(),
  12485. diag::err_omp_reduction_identifier_mismatch)
  12486. << ReductionIdRange << RefExpr->getSourceRange();
  12487. S.Diag(ParentSR.getBegin(),
  12488. diag::note_omp_previous_reduction_identifier)
  12489. << ParentSR
  12490. << (IsParentBOK ? ParentBOKDSA.RefExpr
  12491. : ParentReductionOpDSA.RefExpr)
  12492. ->getSourceRange();
  12493. continue;
  12494. }
  12495. }
  12496. TaskgroupDescriptor = IsParentBOK ? ParentBOKTD : ParentReductionOpTD;
  12497. assert(TaskgroupDescriptor && "Taskgroup descriptor must be defined.");
  12498. }
  12499. DeclRefExpr *Ref = nullptr;
  12500. Expr *VarsExpr = RefExpr->IgnoreParens();
  12501. if (!VD && !S.CurContext->isDependentContext()) {
  12502. if (ASE || OASE) {
  12503. TransformExprToCaptures RebuildToCapture(S, D);
  12504. VarsExpr =
  12505. RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
  12506. Ref = RebuildToCapture.getCapturedExpr();
  12507. } else {
  12508. VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false);
  12509. }
  12510. if (!S.isOpenMPCapturedDecl(D)) {
  12511. RD.ExprCaptures.emplace_back(Ref->getDecl());
  12512. if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
  12513. ExprResult RefRes = S.DefaultLvalueConversion(Ref);
  12514. if (!RefRes.isUsable())
  12515. continue;
  12516. ExprResult PostUpdateRes =
  12517. S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
  12518. RefRes.get());
  12519. if (!PostUpdateRes.isUsable())
  12520. continue;
  12521. if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
  12522. Stack->getCurrentDirective() == OMPD_taskgroup) {
  12523. S.Diag(RefExpr->getExprLoc(),
  12524. diag::err_omp_reduction_non_addressable_expression)
  12525. << RefExpr->getSourceRange();
  12526. continue;
  12527. }
  12528. RD.ExprPostUpdates.emplace_back(
  12529. S.IgnoredValueConversions(PostUpdateRes.get()).get());
  12530. }
  12531. }
  12532. }
  12533. // All reduction items are still marked as reduction (to do not increase
  12534. // code base size).
  12535. Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref);
  12536. if (CurrDir == OMPD_taskgroup) {
  12537. if (DeclareReductionRef.isUsable())
  12538. Stack->addTaskgroupReductionData(D, ReductionIdRange,
  12539. DeclareReductionRef.get());
  12540. else
  12541. Stack->addTaskgroupReductionData(D, ReductionIdRange, BOK);
  12542. }
  12543. RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get(),
  12544. TaskgroupDescriptor);
  12545. }
  12546. return RD.Vars.empty();
  12547. }
  12548. OMPClause *Sema::ActOnOpenMPReductionClause(
  12549. ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
  12550. SourceLocation ColonLoc, SourceLocation EndLoc,
  12551. CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
  12552. ArrayRef<Expr *> UnresolvedReductions) {
  12553. ReductionData RD(VarList.size());
  12554. if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_reduction, VarList,
  12555. StartLoc, LParenLoc, ColonLoc, EndLoc,
  12556. ReductionIdScopeSpec, ReductionId,
  12557. UnresolvedReductions, RD))
  12558. return nullptr;
  12559. return OMPReductionClause::Create(
  12560. Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
  12561. ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
  12562. RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
  12563. buildPreInits(Context, RD.ExprCaptures),
  12564. buildPostUpdate(*this, RD.ExprPostUpdates));
  12565. }
  12566. OMPClause *Sema::ActOnOpenMPTaskReductionClause(
  12567. ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
  12568. SourceLocation ColonLoc, SourceLocation EndLoc,
  12569. CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
  12570. ArrayRef<Expr *> UnresolvedReductions) {
  12571. ReductionData RD(VarList.size());
  12572. if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_task_reduction, VarList,
  12573. StartLoc, LParenLoc, ColonLoc, EndLoc,
  12574. ReductionIdScopeSpec, ReductionId,
  12575. UnresolvedReductions, RD))
  12576. return nullptr;
  12577. return OMPTaskReductionClause::Create(
  12578. Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
  12579. ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
  12580. RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
  12581. buildPreInits(Context, RD.ExprCaptures),
  12582. buildPostUpdate(*this, RD.ExprPostUpdates));
  12583. }
  12584. OMPClause *Sema::ActOnOpenMPInReductionClause(
  12585. ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
  12586. SourceLocation ColonLoc, SourceLocation EndLoc,
  12587. CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
  12588. ArrayRef<Expr *> UnresolvedReductions) {
  12589. ReductionData RD(VarList.size());
  12590. if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_in_reduction, VarList,
  12591. StartLoc, LParenLoc, ColonLoc, EndLoc,
  12592. ReductionIdScopeSpec, ReductionId,
  12593. UnresolvedReductions, RD))
  12594. return nullptr;
  12595. return OMPInReductionClause::Create(
  12596. Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
  12597. ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
  12598. RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.TaskgroupDescriptors,
  12599. buildPreInits(Context, RD.ExprCaptures),
  12600. buildPostUpdate(*this, RD.ExprPostUpdates));
  12601. }
  12602. bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
  12603. SourceLocation LinLoc) {
  12604. if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
  12605. LinKind == OMPC_LINEAR_unknown) {
  12606. Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
  12607. return true;
  12608. }
  12609. return false;
  12610. }
  12611. bool Sema::CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc,
  12612. OpenMPLinearClauseKind LinKind,
  12613. QualType Type) {
  12614. const auto *VD = dyn_cast_or_null<VarDecl>(D);
  12615. // A variable must not have an incomplete type or a reference type.
  12616. if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
  12617. return true;
  12618. if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
  12619. !Type->isReferenceType()) {
  12620. Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
  12621. << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
  12622. return true;
  12623. }
  12624. Type = Type.getNonReferenceType();
  12625. // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
  12626. // A variable that is privatized must not have a const-qualified type
  12627. // unless it is of class type with a mutable member. This restriction does
  12628. // not apply to the firstprivate clause.
  12629. if (rejectConstNotMutableType(*this, D, Type, OMPC_linear, ELoc))
  12630. return true;
  12631. // A list item must be of integral or pointer type.
  12632. Type = Type.getUnqualifiedType().getCanonicalType();
  12633. const auto *Ty = Type.getTypePtrOrNull();
  12634. if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
  12635. !Ty->isPointerType())) {
  12636. Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
  12637. if (D) {
  12638. bool IsDecl =
  12639. !VD ||
  12640. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  12641. Diag(D->getLocation(),
  12642. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  12643. << D;
  12644. }
  12645. return true;
  12646. }
  12647. return false;
  12648. }
  12649. OMPClause *Sema::ActOnOpenMPLinearClause(
  12650. ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
  12651. SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
  12652. SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
  12653. SmallVector<Expr *, 8> Vars;
  12654. SmallVector<Expr *, 8> Privates;
  12655. SmallVector<Expr *, 8> Inits;
  12656. SmallVector<Decl *, 4> ExprCaptures;
  12657. SmallVector<Expr *, 4> ExprPostUpdates;
  12658. if (CheckOpenMPLinearModifier(LinKind, LinLoc))
  12659. LinKind = OMPC_LINEAR_val;
  12660. for (Expr *RefExpr : VarList) {
  12661. assert(RefExpr && "NULL expr in OpenMP linear clause.");
  12662. SourceLocation ELoc;
  12663. SourceRange ERange;
  12664. Expr *SimpleRefExpr = RefExpr;
  12665. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  12666. if (Res.second) {
  12667. // It will be analyzed later.
  12668. Vars.push_back(RefExpr);
  12669. Privates.push_back(nullptr);
  12670. Inits.push_back(nullptr);
  12671. }
  12672. ValueDecl *D = Res.first;
  12673. if (!D)
  12674. continue;
  12675. QualType Type = D->getType();
  12676. auto *VD = dyn_cast<VarDecl>(D);
  12677. // OpenMP [2.14.3.7, linear clause]
  12678. // A list-item cannot appear in more than one linear clause.
  12679. // A list-item that appears in a linear clause cannot appear in any
  12680. // other data-sharing attribute clause.
  12681. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
  12682. if (DVar.RefExpr) {
  12683. Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
  12684. << getOpenMPClauseName(OMPC_linear);
  12685. reportOriginalDsa(*this, DSAStack, D, DVar);
  12686. continue;
  12687. }
  12688. if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
  12689. continue;
  12690. Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
  12691. // Build private copy of original var.
  12692. VarDecl *Private =
  12693. buildVarDecl(*this, ELoc, Type, D->getName(),
  12694. D->hasAttrs() ? &D->getAttrs() : nullptr,
  12695. VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
  12696. DeclRefExpr *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
  12697. // Build var to save initial value.
  12698. VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
  12699. Expr *InitExpr;
  12700. DeclRefExpr *Ref = nullptr;
  12701. if (!VD && !CurContext->isDependentContext()) {
  12702. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
  12703. if (!isOpenMPCapturedDecl(D)) {
  12704. ExprCaptures.push_back(Ref->getDecl());
  12705. if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
  12706. ExprResult RefRes = DefaultLvalueConversion(Ref);
  12707. if (!RefRes.isUsable())
  12708. continue;
  12709. ExprResult PostUpdateRes =
  12710. BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
  12711. SimpleRefExpr, RefRes.get());
  12712. if (!PostUpdateRes.isUsable())
  12713. continue;
  12714. ExprPostUpdates.push_back(
  12715. IgnoredValueConversions(PostUpdateRes.get()).get());
  12716. }
  12717. }
  12718. }
  12719. if (LinKind == OMPC_LINEAR_uval)
  12720. InitExpr = VD ? VD->getInit() : SimpleRefExpr;
  12721. else
  12722. InitExpr = VD ? SimpleRefExpr : Ref;
  12723. AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
  12724. /*DirectInit=*/false);
  12725. DeclRefExpr *InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
  12726. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
  12727. Vars.push_back((VD || CurContext->isDependentContext())
  12728. ? RefExpr->IgnoreParens()
  12729. : Ref);
  12730. Privates.push_back(PrivateRef);
  12731. Inits.push_back(InitRef);
  12732. }
  12733. if (Vars.empty())
  12734. return nullptr;
  12735. Expr *StepExpr = Step;
  12736. Expr *CalcStepExpr = nullptr;
  12737. if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
  12738. !Step->isInstantiationDependent() &&
  12739. !Step->containsUnexpandedParameterPack()) {
  12740. SourceLocation StepLoc = Step->getBeginLoc();
  12741. ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
  12742. if (Val.isInvalid())
  12743. return nullptr;
  12744. StepExpr = Val.get();
  12745. // Build var to save the step value.
  12746. VarDecl *SaveVar =
  12747. buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
  12748. ExprResult SaveRef =
  12749. buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
  12750. ExprResult CalcStep =
  12751. BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
  12752. CalcStep = ActOnFinishFullExpr(CalcStep.get(), /*DiscardedValue*/ false);
  12753. // Warn about zero linear step (it would be probably better specified as
  12754. // making corresponding variables 'const').
  12755. llvm::APSInt Result;
  12756. bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
  12757. if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
  12758. Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
  12759. << (Vars.size() > 1);
  12760. if (!IsConstant && CalcStep.isUsable()) {
  12761. // Calculate the step beforehand instead of doing this on each iteration.
  12762. // (This is not used if the number of iterations may be kfold-ed).
  12763. CalcStepExpr = CalcStep.get();
  12764. }
  12765. }
  12766. return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
  12767. ColonLoc, EndLoc, Vars, Privates, Inits,
  12768. StepExpr, CalcStepExpr,
  12769. buildPreInits(Context, ExprCaptures),
  12770. buildPostUpdate(*this, ExprPostUpdates));
  12771. }
  12772. static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
  12773. Expr *NumIterations, Sema &SemaRef,
  12774. Scope *S, DSAStackTy *Stack) {
  12775. // Walk the vars and build update/final expressions for the CodeGen.
  12776. SmallVector<Expr *, 8> Updates;
  12777. SmallVector<Expr *, 8> Finals;
  12778. SmallVector<Expr *, 8> UsedExprs;
  12779. Expr *Step = Clause.getStep();
  12780. Expr *CalcStep = Clause.getCalcStep();
  12781. // OpenMP [2.14.3.7, linear clause]
  12782. // If linear-step is not specified it is assumed to be 1.
  12783. if (!Step)
  12784. Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
  12785. else if (CalcStep)
  12786. Step = cast<BinaryOperator>(CalcStep)->getLHS();
  12787. bool HasErrors = false;
  12788. auto CurInit = Clause.inits().begin();
  12789. auto CurPrivate = Clause.privates().begin();
  12790. OpenMPLinearClauseKind LinKind = Clause.getModifier();
  12791. for (Expr *RefExpr : Clause.varlists()) {
  12792. SourceLocation ELoc;
  12793. SourceRange ERange;
  12794. Expr *SimpleRefExpr = RefExpr;
  12795. auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange);
  12796. ValueDecl *D = Res.first;
  12797. if (Res.second || !D) {
  12798. Updates.push_back(nullptr);
  12799. Finals.push_back(nullptr);
  12800. HasErrors = true;
  12801. continue;
  12802. }
  12803. auto &&Info = Stack->isLoopControlVariable(D);
  12804. // OpenMP [2.15.11, distribute simd Construct]
  12805. // A list item may not appear in a linear clause, unless it is the loop
  12806. // iteration variable.
  12807. if (isOpenMPDistributeDirective(Stack->getCurrentDirective()) &&
  12808. isOpenMPSimdDirective(Stack->getCurrentDirective()) && !Info.first) {
  12809. SemaRef.Diag(ELoc,
  12810. diag::err_omp_linear_distribute_var_non_loop_iteration);
  12811. Updates.push_back(nullptr);
  12812. Finals.push_back(nullptr);
  12813. HasErrors = true;
  12814. continue;
  12815. }
  12816. Expr *InitExpr = *CurInit;
  12817. // Build privatized reference to the current linear var.
  12818. auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
  12819. Expr *CapturedRef;
  12820. if (LinKind == OMPC_LINEAR_uval)
  12821. CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
  12822. else
  12823. CapturedRef =
  12824. buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
  12825. DE->getType().getUnqualifiedType(), DE->getExprLoc(),
  12826. /*RefersToCapture=*/true);
  12827. // Build update: Var = InitExpr + IV * Step
  12828. ExprResult Update;
  12829. if (!Info.first)
  12830. Update = buildCounterUpdate(
  12831. SemaRef, S, RefExpr->getExprLoc(), *CurPrivate, InitExpr, IV, Step,
  12832. /*Subtract=*/false, /*IsNonRectangularLB=*/false);
  12833. else
  12834. Update = *CurPrivate;
  12835. Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getBeginLoc(),
  12836. /*DiscardedValue*/ false);
  12837. // Build final: Var = InitExpr + NumIterations * Step
  12838. ExprResult Final;
  12839. if (!Info.first)
  12840. Final =
  12841. buildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
  12842. InitExpr, NumIterations, Step, /*Subtract=*/false,
  12843. /*IsNonRectangularLB=*/false);
  12844. else
  12845. Final = *CurPrivate;
  12846. Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getBeginLoc(),
  12847. /*DiscardedValue*/ false);
  12848. if (!Update.isUsable() || !Final.isUsable()) {
  12849. Updates.push_back(nullptr);
  12850. Finals.push_back(nullptr);
  12851. UsedExprs.push_back(nullptr);
  12852. HasErrors = true;
  12853. } else {
  12854. Updates.push_back(Update.get());
  12855. Finals.push_back(Final.get());
  12856. if (!Info.first)
  12857. UsedExprs.push_back(SimpleRefExpr);
  12858. }
  12859. ++CurInit;
  12860. ++CurPrivate;
  12861. }
  12862. if (Expr *S = Clause.getStep())
  12863. UsedExprs.push_back(S);
  12864. // Fill the remaining part with the nullptr.
  12865. UsedExprs.append(Clause.varlist_size() + 1 - UsedExprs.size(), nullptr);
  12866. Clause.setUpdates(Updates);
  12867. Clause.setFinals(Finals);
  12868. Clause.setUsedExprs(UsedExprs);
  12869. return HasErrors;
  12870. }
  12871. OMPClause *Sema::ActOnOpenMPAlignedClause(
  12872. ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
  12873. SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
  12874. SmallVector<Expr *, 8> Vars;
  12875. for (Expr *RefExpr : VarList) {
  12876. assert(RefExpr && "NULL expr in OpenMP linear clause.");
  12877. SourceLocation ELoc;
  12878. SourceRange ERange;
  12879. Expr *SimpleRefExpr = RefExpr;
  12880. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  12881. if (Res.second) {
  12882. // It will be analyzed later.
  12883. Vars.push_back(RefExpr);
  12884. }
  12885. ValueDecl *D = Res.first;
  12886. if (!D)
  12887. continue;
  12888. QualType QType = D->getType();
  12889. auto *VD = dyn_cast<VarDecl>(D);
  12890. // OpenMP [2.8.1, simd construct, Restrictions]
  12891. // The type of list items appearing in the aligned clause must be
  12892. // array, pointer, reference to array, or reference to pointer.
  12893. QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
  12894. const Type *Ty = QType.getTypePtrOrNull();
  12895. if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
  12896. Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
  12897. << QType << getLangOpts().CPlusPlus << ERange;
  12898. bool IsDecl =
  12899. !VD ||
  12900. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  12901. Diag(D->getLocation(),
  12902. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  12903. << D;
  12904. continue;
  12905. }
  12906. // OpenMP [2.8.1, simd construct, Restrictions]
  12907. // A list-item cannot appear in more than one aligned clause.
  12908. if (const Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
  12909. Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange;
  12910. Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
  12911. << getOpenMPClauseName(OMPC_aligned);
  12912. continue;
  12913. }
  12914. DeclRefExpr *Ref = nullptr;
  12915. if (!VD && isOpenMPCapturedDecl(D))
  12916. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
  12917. Vars.push_back(DefaultFunctionArrayConversion(
  12918. (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
  12919. .get());
  12920. }
  12921. // OpenMP [2.8.1, simd construct, Description]
  12922. // The parameter of the aligned clause, alignment, must be a constant
  12923. // positive integer expression.
  12924. // If no optional parameter is specified, implementation-defined default
  12925. // alignments for SIMD instructions on the target platforms are assumed.
  12926. if (Alignment != nullptr) {
  12927. ExprResult AlignResult =
  12928. VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
  12929. if (AlignResult.isInvalid())
  12930. return nullptr;
  12931. Alignment = AlignResult.get();
  12932. }
  12933. if (Vars.empty())
  12934. return nullptr;
  12935. return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
  12936. EndLoc, Vars, Alignment);
  12937. }
  12938. OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
  12939. SourceLocation StartLoc,
  12940. SourceLocation LParenLoc,
  12941. SourceLocation EndLoc) {
  12942. SmallVector<Expr *, 8> Vars;
  12943. SmallVector<Expr *, 8> SrcExprs;
  12944. SmallVector<Expr *, 8> DstExprs;
  12945. SmallVector<Expr *, 8> AssignmentOps;
  12946. for (Expr *RefExpr : VarList) {
  12947. assert(RefExpr && "NULL expr in OpenMP copyin clause.");
  12948. if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
  12949. // It will be analyzed later.
  12950. Vars.push_back(RefExpr);
  12951. SrcExprs.push_back(nullptr);
  12952. DstExprs.push_back(nullptr);
  12953. AssignmentOps.push_back(nullptr);
  12954. continue;
  12955. }
  12956. SourceLocation ELoc = RefExpr->getExprLoc();
  12957. // OpenMP [2.1, C/C++]
  12958. // A list item is a variable name.
  12959. // OpenMP [2.14.4.1, Restrictions, p.1]
  12960. // A list item that appears in a copyin clause must be threadprivate.
  12961. auto *DE = dyn_cast<DeclRefExpr>(RefExpr);
  12962. if (!DE || !isa<VarDecl>(DE->getDecl())) {
  12963. Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
  12964. << 0 << RefExpr->getSourceRange();
  12965. continue;
  12966. }
  12967. Decl *D = DE->getDecl();
  12968. auto *VD = cast<VarDecl>(D);
  12969. QualType Type = VD->getType();
  12970. if (Type->isDependentType() || Type->isInstantiationDependentType()) {
  12971. // It will be analyzed later.
  12972. Vars.push_back(DE);
  12973. SrcExprs.push_back(nullptr);
  12974. DstExprs.push_back(nullptr);
  12975. AssignmentOps.push_back(nullptr);
  12976. continue;
  12977. }
  12978. // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
  12979. // A list item that appears in a copyin clause must be threadprivate.
  12980. if (!DSAStack->isThreadPrivate(VD)) {
  12981. Diag(ELoc, diag::err_omp_required_access)
  12982. << getOpenMPClauseName(OMPC_copyin)
  12983. << getOpenMPDirectiveName(OMPD_threadprivate);
  12984. continue;
  12985. }
  12986. // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
  12987. // A variable of class type (or array thereof) that appears in a
  12988. // copyin clause requires an accessible, unambiguous copy assignment
  12989. // operator for the class type.
  12990. QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
  12991. VarDecl *SrcVD =
  12992. buildVarDecl(*this, DE->getBeginLoc(), ElemType.getUnqualifiedType(),
  12993. ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
  12994. DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(
  12995. *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
  12996. VarDecl *DstVD =
  12997. buildVarDecl(*this, DE->getBeginLoc(), ElemType, ".copyin.dst",
  12998. VD->hasAttrs() ? &VD->getAttrs() : nullptr);
  12999. DeclRefExpr *PseudoDstExpr =
  13000. buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
  13001. // For arrays generate assignment operation for single element and replace
  13002. // it by the original array element in CodeGen.
  13003. ExprResult AssignmentOp =
  13004. BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign, PseudoDstExpr,
  13005. PseudoSrcExpr);
  13006. if (AssignmentOp.isInvalid())
  13007. continue;
  13008. AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
  13009. /*DiscardedValue*/ false);
  13010. if (AssignmentOp.isInvalid())
  13011. continue;
  13012. DSAStack->addDSA(VD, DE, OMPC_copyin);
  13013. Vars.push_back(DE);
  13014. SrcExprs.push_back(PseudoSrcExpr);
  13015. DstExprs.push_back(PseudoDstExpr);
  13016. AssignmentOps.push_back(AssignmentOp.get());
  13017. }
  13018. if (Vars.empty())
  13019. return nullptr;
  13020. return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
  13021. SrcExprs, DstExprs, AssignmentOps);
  13022. }
  13023. OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
  13024. SourceLocation StartLoc,
  13025. SourceLocation LParenLoc,
  13026. SourceLocation EndLoc) {
  13027. SmallVector<Expr *, 8> Vars;
  13028. SmallVector<Expr *, 8> SrcExprs;
  13029. SmallVector<Expr *, 8> DstExprs;
  13030. SmallVector<Expr *, 8> AssignmentOps;
  13031. for (Expr *RefExpr : VarList) {
  13032. assert(RefExpr && "NULL expr in OpenMP linear clause.");
  13033. SourceLocation ELoc;
  13034. SourceRange ERange;
  13035. Expr *SimpleRefExpr = RefExpr;
  13036. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  13037. if (Res.second) {
  13038. // It will be analyzed later.
  13039. Vars.push_back(RefExpr);
  13040. SrcExprs.push_back(nullptr);
  13041. DstExprs.push_back(nullptr);
  13042. AssignmentOps.push_back(nullptr);
  13043. }
  13044. ValueDecl *D = Res.first;
  13045. if (!D)
  13046. continue;
  13047. QualType Type = D->getType();
  13048. auto *VD = dyn_cast<VarDecl>(D);
  13049. // OpenMP [2.14.4.2, Restrictions, p.2]
  13050. // A list item that appears in a copyprivate clause may not appear in a
  13051. // private or firstprivate clause on the single construct.
  13052. if (!VD || !DSAStack->isThreadPrivate(VD)) {
  13053. DSAStackTy::DSAVarData DVar =
  13054. DSAStack->getTopDSA(D, /*FromParent=*/false);
  13055. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
  13056. DVar.RefExpr) {
  13057. Diag(ELoc, diag::err_omp_wrong_dsa)
  13058. << getOpenMPClauseName(DVar.CKind)
  13059. << getOpenMPClauseName(OMPC_copyprivate);
  13060. reportOriginalDsa(*this, DSAStack, D, DVar);
  13061. continue;
  13062. }
  13063. // OpenMP [2.11.4.2, Restrictions, p.1]
  13064. // All list items that appear in a copyprivate clause must be either
  13065. // threadprivate or private in the enclosing context.
  13066. if (DVar.CKind == OMPC_unknown) {
  13067. DVar = DSAStack->getImplicitDSA(D, false);
  13068. if (DVar.CKind == OMPC_shared) {
  13069. Diag(ELoc, diag::err_omp_required_access)
  13070. << getOpenMPClauseName(OMPC_copyprivate)
  13071. << "threadprivate or private in the enclosing context";
  13072. reportOriginalDsa(*this, DSAStack, D, DVar);
  13073. continue;
  13074. }
  13075. }
  13076. }
  13077. // Variably modified types are not supported.
  13078. if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
  13079. Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
  13080. << getOpenMPClauseName(OMPC_copyprivate) << Type
  13081. << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
  13082. bool IsDecl =
  13083. !VD ||
  13084. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  13085. Diag(D->getLocation(),
  13086. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  13087. << D;
  13088. continue;
  13089. }
  13090. // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
  13091. // A variable of class type (or array thereof) that appears in a
  13092. // copyin clause requires an accessible, unambiguous copy assignment
  13093. // operator for the class type.
  13094. Type = Context.getBaseElementType(Type.getNonReferenceType())
  13095. .getUnqualifiedType();
  13096. VarDecl *SrcVD =
  13097. buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.src",
  13098. D->hasAttrs() ? &D->getAttrs() : nullptr);
  13099. DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
  13100. VarDecl *DstVD =
  13101. buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.dst",
  13102. D->hasAttrs() ? &D->getAttrs() : nullptr);
  13103. DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
  13104. ExprResult AssignmentOp = BuildBinOp(
  13105. DSAStack->getCurScope(), ELoc, BO_Assign, PseudoDstExpr, PseudoSrcExpr);
  13106. if (AssignmentOp.isInvalid())
  13107. continue;
  13108. AssignmentOp =
  13109. ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
  13110. if (AssignmentOp.isInvalid())
  13111. continue;
  13112. // No need to mark vars as copyprivate, they are already threadprivate or
  13113. // implicitly private.
  13114. assert(VD || isOpenMPCapturedDecl(D));
  13115. Vars.push_back(
  13116. VD ? RefExpr->IgnoreParens()
  13117. : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
  13118. SrcExprs.push_back(PseudoSrcExpr);
  13119. DstExprs.push_back(PseudoDstExpr);
  13120. AssignmentOps.push_back(AssignmentOp.get());
  13121. }
  13122. if (Vars.empty())
  13123. return nullptr;
  13124. return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  13125. Vars, SrcExprs, DstExprs, AssignmentOps);
  13126. }
  13127. OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
  13128. SourceLocation StartLoc,
  13129. SourceLocation LParenLoc,
  13130. SourceLocation EndLoc) {
  13131. if (VarList.empty())
  13132. return nullptr;
  13133. return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
  13134. }
  13135. OMPClause *
  13136. Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
  13137. SourceLocation DepLoc, SourceLocation ColonLoc,
  13138. ArrayRef<Expr *> VarList, SourceLocation StartLoc,
  13139. SourceLocation LParenLoc, SourceLocation EndLoc) {
  13140. if (DSAStack->getCurrentDirective() == OMPD_ordered &&
  13141. DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
  13142. Diag(DepLoc, diag::err_omp_unexpected_clause_value)
  13143. << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
  13144. return nullptr;
  13145. }
  13146. if (DSAStack->getCurrentDirective() != OMPD_ordered &&
  13147. (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
  13148. DepKind == OMPC_DEPEND_sink)) {
  13149. unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink};
  13150. Diag(DepLoc, diag::err_omp_unexpected_clause_value)
  13151. << getListOfPossibleValues(OMPC_depend, /*First=*/0,
  13152. /*Last=*/OMPC_DEPEND_unknown, Except)
  13153. << getOpenMPClauseName(OMPC_depend);
  13154. return nullptr;
  13155. }
  13156. SmallVector<Expr *, 8> Vars;
  13157. DSAStackTy::OperatorOffsetTy OpsOffs;
  13158. llvm::APSInt DepCounter(/*BitWidth=*/32);
  13159. llvm::APSInt TotalDepCount(/*BitWidth=*/32);
  13160. if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) {
  13161. if (const Expr *OrderedCountExpr =
  13162. DSAStack->getParentOrderedRegionParam().first) {
  13163. TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
  13164. TotalDepCount.setIsUnsigned(/*Val=*/true);
  13165. }
  13166. }
  13167. for (Expr *RefExpr : VarList) {
  13168. assert(RefExpr && "NULL expr in OpenMP shared clause.");
  13169. if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
  13170. // It will be analyzed later.
  13171. Vars.push_back(RefExpr);
  13172. continue;
  13173. }
  13174. SourceLocation ELoc = RefExpr->getExprLoc();
  13175. Expr *SimpleExpr = RefExpr->IgnoreParenCasts();
  13176. if (DepKind == OMPC_DEPEND_sink) {
  13177. if (DSAStack->getParentOrderedRegionParam().first &&
  13178. DepCounter >= TotalDepCount) {
  13179. Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
  13180. continue;
  13181. }
  13182. ++DepCounter;
  13183. // OpenMP [2.13.9, Summary]
  13184. // depend(dependence-type : vec), where dependence-type is:
  13185. // 'sink' and where vec is the iteration vector, which has the form:
  13186. // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
  13187. // where n is the value specified by the ordered clause in the loop
  13188. // directive, xi denotes the loop iteration variable of the i-th nested
  13189. // loop associated with the loop directive, and di is a constant
  13190. // non-negative integer.
  13191. if (CurContext->isDependentContext()) {
  13192. // It will be analyzed later.
  13193. Vars.push_back(RefExpr);
  13194. continue;
  13195. }
  13196. SimpleExpr = SimpleExpr->IgnoreImplicit();
  13197. OverloadedOperatorKind OOK = OO_None;
  13198. SourceLocation OOLoc;
  13199. Expr *LHS = SimpleExpr;
  13200. Expr *RHS = nullptr;
  13201. if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
  13202. OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
  13203. OOLoc = BO->getOperatorLoc();
  13204. LHS = BO->getLHS()->IgnoreParenImpCasts();
  13205. RHS = BO->getRHS()->IgnoreParenImpCasts();
  13206. } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
  13207. OOK = OCE->getOperator();
  13208. OOLoc = OCE->getOperatorLoc();
  13209. LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
  13210. RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
  13211. } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
  13212. OOK = MCE->getMethodDecl()
  13213. ->getNameInfo()
  13214. .getName()
  13215. .getCXXOverloadedOperator();
  13216. OOLoc = MCE->getCallee()->getExprLoc();
  13217. LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
  13218. RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
  13219. }
  13220. SourceLocation ELoc;
  13221. SourceRange ERange;
  13222. auto Res = getPrivateItem(*this, LHS, ELoc, ERange);
  13223. if (Res.second) {
  13224. // It will be analyzed later.
  13225. Vars.push_back(RefExpr);
  13226. }
  13227. ValueDecl *D = Res.first;
  13228. if (!D)
  13229. continue;
  13230. if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
  13231. Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
  13232. continue;
  13233. }
  13234. if (RHS) {
  13235. ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
  13236. RHS, OMPC_depend, /*StrictlyPositive=*/false);
  13237. if (RHSRes.isInvalid())
  13238. continue;
  13239. }
  13240. if (!CurContext->isDependentContext() &&
  13241. DSAStack->getParentOrderedRegionParam().first &&
  13242. DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
  13243. const ValueDecl *VD =
  13244. DSAStack->getParentLoopControlVariable(DepCounter.getZExtValue());
  13245. if (VD)
  13246. Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
  13247. << 1 << VD;
  13248. else
  13249. Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) << 0;
  13250. continue;
  13251. }
  13252. OpsOffs.emplace_back(RHS, OOK);
  13253. } else {
  13254. auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
  13255. if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
  13256. (ASE &&
  13257. !ASE->getBase()->getType().getNonReferenceType()->isPointerType() &&
  13258. !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
  13259. Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
  13260. << RefExpr->getSourceRange();
  13261. continue;
  13262. }
  13263. ExprResult Res;
  13264. {
  13265. Sema::TentativeAnalysisScope Trap(*this);
  13266. Res = CreateBuiltinUnaryOp(ELoc, UO_AddrOf,
  13267. RefExpr->IgnoreParenImpCasts());
  13268. }
  13269. if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr)) {
  13270. Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
  13271. << RefExpr->getSourceRange();
  13272. continue;
  13273. }
  13274. }
  13275. Vars.push_back(RefExpr->IgnoreParenImpCasts());
  13276. }
  13277. if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
  13278. TotalDepCount > VarList.size() &&
  13279. DSAStack->getParentOrderedRegionParam().first &&
  13280. DSAStack->getParentLoopControlVariable(VarList.size() + 1)) {
  13281. Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration)
  13282. << 1 << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
  13283. }
  13284. if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
  13285. Vars.empty())
  13286. return nullptr;
  13287. auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  13288. DepKind, DepLoc, ColonLoc, Vars,
  13289. TotalDepCount.getZExtValue());
  13290. if ((DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) &&
  13291. DSAStack->isParentOrderedRegion())
  13292. DSAStack->addDoacrossDependClause(C, OpsOffs);
  13293. return C;
  13294. }
  13295. OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
  13296. SourceLocation LParenLoc,
  13297. SourceLocation EndLoc) {
  13298. Expr *ValExpr = Device;
  13299. Stmt *HelperValStmt = nullptr;
  13300. // OpenMP [2.9.1, Restrictions]
  13301. // The device expression must evaluate to a non-negative integer value.
  13302. if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
  13303. /*StrictlyPositive=*/false))
  13304. return nullptr;
  13305. OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
  13306. OpenMPDirectiveKind CaptureRegion =
  13307. getOpenMPCaptureRegionForClause(DKind, OMPC_device);
  13308. if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
  13309. ValExpr = MakeFullExpr(ValExpr).get();
  13310. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  13311. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  13312. HelperValStmt = buildPreInits(Context, Captures);
  13313. }
  13314. return new (Context) OMPDeviceClause(ValExpr, HelperValStmt, CaptureRegion,
  13315. StartLoc, LParenLoc, EndLoc);
  13316. }
  13317. static bool checkTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
  13318. DSAStackTy *Stack, QualType QTy,
  13319. bool FullCheck = true) {
  13320. NamedDecl *ND;
  13321. if (QTy->isIncompleteType(&ND)) {
  13322. SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
  13323. return false;
  13324. }
  13325. if (FullCheck && !SemaRef.CurContext->isDependentContext() &&
  13326. !QTy.isTrivialType(SemaRef.Context))
  13327. SemaRef.Diag(SL, diag::warn_omp_non_trivial_type_mapped) << QTy << SR;
  13328. return true;
  13329. }
  13330. /// Return true if it can be proven that the provided array expression
  13331. /// (array section or array subscript) does NOT specify the whole size of the
  13332. /// array whose base type is \a BaseQTy.
  13333. static bool checkArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
  13334. const Expr *E,
  13335. QualType BaseQTy) {
  13336. const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
  13337. // If this is an array subscript, it refers to the whole size if the size of
  13338. // the dimension is constant and equals 1. Also, an array section assumes the
  13339. // format of an array subscript if no colon is used.
  13340. if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) {
  13341. if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
  13342. return ATy->getSize().getSExtValue() != 1;
  13343. // Size can't be evaluated statically.
  13344. return false;
  13345. }
  13346. assert(OASE && "Expecting array section if not an array subscript.");
  13347. const Expr *LowerBound = OASE->getLowerBound();
  13348. const Expr *Length = OASE->getLength();
  13349. // If there is a lower bound that does not evaluates to zero, we are not
  13350. // covering the whole dimension.
  13351. if (LowerBound) {
  13352. Expr::EvalResult Result;
  13353. if (!LowerBound->EvaluateAsInt(Result, SemaRef.getASTContext()))
  13354. return false; // Can't get the integer value as a constant.
  13355. llvm::APSInt ConstLowerBound = Result.Val.getInt();
  13356. if (ConstLowerBound.getSExtValue())
  13357. return true;
  13358. }
  13359. // If we don't have a length we covering the whole dimension.
  13360. if (!Length)
  13361. return false;
  13362. // If the base is a pointer, we don't have a way to get the size of the
  13363. // pointee.
  13364. if (BaseQTy->isPointerType())
  13365. return false;
  13366. // We can only check if the length is the same as the size of the dimension
  13367. // if we have a constant array.
  13368. const auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
  13369. if (!CATy)
  13370. return false;
  13371. Expr::EvalResult Result;
  13372. if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
  13373. return false; // Can't get the integer value as a constant.
  13374. llvm::APSInt ConstLength = Result.Val.getInt();
  13375. return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
  13376. }
  13377. // Return true if it can be proven that the provided array expression (array
  13378. // section or array subscript) does NOT specify a single element of the array
  13379. // whose base type is \a BaseQTy.
  13380. static bool checkArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
  13381. const Expr *E,
  13382. QualType BaseQTy) {
  13383. const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
  13384. // An array subscript always refer to a single element. Also, an array section
  13385. // assumes the format of an array subscript if no colon is used.
  13386. if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid()))
  13387. return false;
  13388. assert(OASE && "Expecting array section if not an array subscript.");
  13389. const Expr *Length = OASE->getLength();
  13390. // If we don't have a length we have to check if the array has unitary size
  13391. // for this dimension. Also, we should always expect a length if the base type
  13392. // is pointer.
  13393. if (!Length) {
  13394. if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
  13395. return ATy->getSize().getSExtValue() != 1;
  13396. // We cannot assume anything.
  13397. return false;
  13398. }
  13399. // Check if the length evaluates to 1.
  13400. Expr::EvalResult Result;
  13401. if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
  13402. return false; // Can't get the integer value as a constant.
  13403. llvm::APSInt ConstLength = Result.Val.getInt();
  13404. return ConstLength.getSExtValue() != 1;
  13405. }
  13406. // Return the expression of the base of the mappable expression or null if it
  13407. // cannot be determined and do all the necessary checks to see if the expression
  13408. // is valid as a standalone mappable expression. In the process, record all the
  13409. // components of the expression.
  13410. static const Expr *checkMapClauseExpressionBase(
  13411. Sema &SemaRef, Expr *E,
  13412. OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
  13413. OpenMPClauseKind CKind, bool NoDiagnose) {
  13414. SourceLocation ELoc = E->getExprLoc();
  13415. SourceRange ERange = E->getSourceRange();
  13416. // The base of elements of list in a map clause have to be either:
  13417. // - a reference to variable or field.
  13418. // - a member expression.
  13419. // - an array expression.
  13420. //
  13421. // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
  13422. // reference to 'r'.
  13423. //
  13424. // If we have:
  13425. //
  13426. // struct SS {
  13427. // Bla S;
  13428. // foo() {
  13429. // #pragma omp target map (S.Arr[:12]);
  13430. // }
  13431. // }
  13432. //
  13433. // We want to retrieve the member expression 'this->S';
  13434. const Expr *RelevantExpr = nullptr;
  13435. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2]
  13436. // If a list item is an array section, it must specify contiguous storage.
  13437. //
  13438. // For this restriction it is sufficient that we make sure only references
  13439. // to variables or fields and array expressions, and that no array sections
  13440. // exist except in the rightmost expression (unless they cover the whole
  13441. // dimension of the array). E.g. these would be invalid:
  13442. //
  13443. // r.ArrS[3:5].Arr[6:7]
  13444. //
  13445. // r.ArrS[3:5].x
  13446. //
  13447. // but these would be valid:
  13448. // r.ArrS[3].Arr[6:7]
  13449. //
  13450. // r.ArrS[3].x
  13451. bool AllowUnitySizeArraySection = true;
  13452. bool AllowWholeSizeArraySection = true;
  13453. while (!RelevantExpr) {
  13454. E = E->IgnoreParenImpCasts();
  13455. if (auto *CurE = dyn_cast<DeclRefExpr>(E)) {
  13456. if (!isa<VarDecl>(CurE->getDecl()))
  13457. return nullptr;
  13458. RelevantExpr = CurE;
  13459. // If we got a reference to a declaration, we should not expect any array
  13460. // section before that.
  13461. AllowUnitySizeArraySection = false;
  13462. AllowWholeSizeArraySection = false;
  13463. // Record the component.
  13464. CurComponents.emplace_back(CurE, CurE->getDecl());
  13465. } else if (auto *CurE = dyn_cast<MemberExpr>(E)) {
  13466. Expr *BaseE = CurE->getBase()->IgnoreParenImpCasts();
  13467. if (isa<CXXThisExpr>(BaseE))
  13468. // We found a base expression: this->Val.
  13469. RelevantExpr = CurE;
  13470. else
  13471. E = BaseE;
  13472. if (!isa<FieldDecl>(CurE->getMemberDecl())) {
  13473. if (!NoDiagnose) {
  13474. SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
  13475. << CurE->getSourceRange();
  13476. return nullptr;
  13477. }
  13478. if (RelevantExpr)
  13479. return nullptr;
  13480. continue;
  13481. }
  13482. auto *FD = cast<FieldDecl>(CurE->getMemberDecl());
  13483. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
  13484. // A bit-field cannot appear in a map clause.
  13485. //
  13486. if (FD->isBitField()) {
  13487. if (!NoDiagnose) {
  13488. SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
  13489. << CurE->getSourceRange() << getOpenMPClauseName(CKind);
  13490. return nullptr;
  13491. }
  13492. if (RelevantExpr)
  13493. return nullptr;
  13494. continue;
  13495. }
  13496. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
  13497. // If the type of a list item is a reference to a type T then the type
  13498. // will be considered to be T for all purposes of this clause.
  13499. QualType CurType = BaseE->getType().getNonReferenceType();
  13500. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
  13501. // A list item cannot be a variable that is a member of a structure with
  13502. // a union type.
  13503. //
  13504. if (CurType->isUnionType()) {
  13505. if (!NoDiagnose) {
  13506. SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
  13507. << CurE->getSourceRange();
  13508. return nullptr;
  13509. }
  13510. continue;
  13511. }
  13512. // If we got a member expression, we should not expect any array section
  13513. // before that:
  13514. //
  13515. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
  13516. // If a list item is an element of a structure, only the rightmost symbol
  13517. // of the variable reference can be an array section.
  13518. //
  13519. AllowUnitySizeArraySection = false;
  13520. AllowWholeSizeArraySection = false;
  13521. // Record the component.
  13522. CurComponents.emplace_back(CurE, FD);
  13523. } else if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) {
  13524. E = CurE->getBase()->IgnoreParenImpCasts();
  13525. if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
  13526. if (!NoDiagnose) {
  13527. SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
  13528. << 0 << CurE->getSourceRange();
  13529. return nullptr;
  13530. }
  13531. continue;
  13532. }
  13533. // If we got an array subscript that express the whole dimension we
  13534. // can have any array expressions before. If it only expressing part of
  13535. // the dimension, we can only have unitary-size array expressions.
  13536. if (checkArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE,
  13537. E->getType()))
  13538. AllowWholeSizeArraySection = false;
  13539. if (const auto *TE = dyn_cast<CXXThisExpr>(E)) {
  13540. Expr::EvalResult Result;
  13541. if (CurE->getIdx()->EvaluateAsInt(Result, SemaRef.getASTContext())) {
  13542. if (!Result.Val.getInt().isNullValue()) {
  13543. SemaRef.Diag(CurE->getIdx()->getExprLoc(),
  13544. diag::err_omp_invalid_map_this_expr);
  13545. SemaRef.Diag(CurE->getIdx()->getExprLoc(),
  13546. diag::note_omp_invalid_subscript_on_this_ptr_map);
  13547. }
  13548. }
  13549. RelevantExpr = TE;
  13550. }
  13551. // Record the component - we don't have any declaration associated.
  13552. CurComponents.emplace_back(CurE, nullptr);
  13553. } else if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) {
  13554. assert(!NoDiagnose && "Array sections cannot be implicitly mapped.");
  13555. E = CurE->getBase()->IgnoreParenImpCasts();
  13556. QualType CurType =
  13557. OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
  13558. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
  13559. // If the type of a list item is a reference to a type T then the type
  13560. // will be considered to be T for all purposes of this clause.
  13561. if (CurType->isReferenceType())
  13562. CurType = CurType->getPointeeType();
  13563. bool IsPointer = CurType->isAnyPointerType();
  13564. if (!IsPointer && !CurType->isArrayType()) {
  13565. SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
  13566. << 0 << CurE->getSourceRange();
  13567. return nullptr;
  13568. }
  13569. bool NotWhole =
  13570. checkArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType);
  13571. bool NotUnity =
  13572. checkArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType);
  13573. if (AllowWholeSizeArraySection) {
  13574. // Any array section is currently allowed. Allowing a whole size array
  13575. // section implies allowing a unity array section as well.
  13576. //
  13577. // If this array section refers to the whole dimension we can still
  13578. // accept other array sections before this one, except if the base is a
  13579. // pointer. Otherwise, only unitary sections are accepted.
  13580. if (NotWhole || IsPointer)
  13581. AllowWholeSizeArraySection = false;
  13582. } else if (AllowUnitySizeArraySection && NotUnity) {
  13583. // A unity or whole array section is not allowed and that is not
  13584. // compatible with the properties of the current array section.
  13585. SemaRef.Diag(
  13586. ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
  13587. << CurE->getSourceRange();
  13588. return nullptr;
  13589. }
  13590. if (const auto *TE = dyn_cast<CXXThisExpr>(E)) {
  13591. Expr::EvalResult ResultR;
  13592. Expr::EvalResult ResultL;
  13593. if (CurE->getLength()->EvaluateAsInt(ResultR,
  13594. SemaRef.getASTContext())) {
  13595. if (!ResultR.Val.getInt().isOneValue()) {
  13596. SemaRef.Diag(CurE->getLength()->getExprLoc(),
  13597. diag::err_omp_invalid_map_this_expr);
  13598. SemaRef.Diag(CurE->getLength()->getExprLoc(),
  13599. diag::note_omp_invalid_length_on_this_ptr_mapping);
  13600. }
  13601. }
  13602. if (CurE->getLowerBound() && CurE->getLowerBound()->EvaluateAsInt(
  13603. ResultL, SemaRef.getASTContext())) {
  13604. if (!ResultL.Val.getInt().isNullValue()) {
  13605. SemaRef.Diag(CurE->getLowerBound()->getExprLoc(),
  13606. diag::err_omp_invalid_map_this_expr);
  13607. SemaRef.Diag(CurE->getLowerBound()->getExprLoc(),
  13608. diag::note_omp_invalid_lower_bound_on_this_ptr_mapping);
  13609. }
  13610. }
  13611. RelevantExpr = TE;
  13612. }
  13613. // Record the component - we don't have any declaration associated.
  13614. CurComponents.emplace_back(CurE, nullptr);
  13615. } else {
  13616. if (!NoDiagnose) {
  13617. // If nothing else worked, this is not a valid map clause expression.
  13618. SemaRef.Diag(
  13619. ELoc, diag::err_omp_expected_named_var_member_or_array_expression)
  13620. << ERange;
  13621. }
  13622. return nullptr;
  13623. }
  13624. }
  13625. return RelevantExpr;
  13626. }
  13627. // Return true if expression E associated with value VD has conflicts with other
  13628. // map information.
  13629. static bool checkMapConflicts(
  13630. Sema &SemaRef, DSAStackTy *DSAS, const ValueDecl *VD, const Expr *E,
  13631. bool CurrentRegionOnly,
  13632. OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
  13633. OpenMPClauseKind CKind) {
  13634. assert(VD && E);
  13635. SourceLocation ELoc = E->getExprLoc();
  13636. SourceRange ERange = E->getSourceRange();
  13637. // In order to easily check the conflicts we need to match each component of
  13638. // the expression under test with the components of the expressions that are
  13639. // already in the stack.
  13640. assert(!CurComponents.empty() && "Map clause expression with no components!");
  13641. assert(CurComponents.back().getAssociatedDeclaration() == VD &&
  13642. "Map clause expression with unexpected base!");
  13643. // Variables to help detecting enclosing problems in data environment nests.
  13644. bool IsEnclosedByDataEnvironmentExpr = false;
  13645. const Expr *EnclosingExpr = nullptr;
  13646. bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
  13647. VD, CurrentRegionOnly,
  13648. [&IsEnclosedByDataEnvironmentExpr, &SemaRef, VD, CurrentRegionOnly, ELoc,
  13649. ERange, CKind, &EnclosingExpr,
  13650. CurComponents](OMPClauseMappableExprCommon::MappableExprComponentListRef
  13651. StackComponents,
  13652. OpenMPClauseKind) {
  13653. assert(!StackComponents.empty() &&
  13654. "Map clause expression with no components!");
  13655. assert(StackComponents.back().getAssociatedDeclaration() == VD &&
  13656. "Map clause expression with unexpected base!");
  13657. (void)VD;
  13658. // The whole expression in the stack.
  13659. const Expr *RE = StackComponents.front().getAssociatedExpression();
  13660. // Expressions must start from the same base. Here we detect at which
  13661. // point both expressions diverge from each other and see if we can
  13662. // detect if the memory referred to both expressions is contiguous and
  13663. // do not overlap.
  13664. auto CI = CurComponents.rbegin();
  13665. auto CE = CurComponents.rend();
  13666. auto SI = StackComponents.rbegin();
  13667. auto SE = StackComponents.rend();
  13668. for (; CI != CE && SI != SE; ++CI, ++SI) {
  13669. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
  13670. // At most one list item can be an array item derived from a given
  13671. // variable in map clauses of the same construct.
  13672. if (CurrentRegionOnly &&
  13673. (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
  13674. isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) &&
  13675. (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
  13676. isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) {
  13677. SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
  13678. diag::err_omp_multiple_array_items_in_map_clause)
  13679. << CI->getAssociatedExpression()->getSourceRange();
  13680. SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
  13681. diag::note_used_here)
  13682. << SI->getAssociatedExpression()->getSourceRange();
  13683. return true;
  13684. }
  13685. // Do both expressions have the same kind?
  13686. if (CI->getAssociatedExpression()->getStmtClass() !=
  13687. SI->getAssociatedExpression()->getStmtClass())
  13688. break;
  13689. // Are we dealing with different variables/fields?
  13690. if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
  13691. break;
  13692. }
  13693. // Check if the extra components of the expressions in the enclosing
  13694. // data environment are redundant for the current base declaration.
  13695. // If they are, the maps completely overlap, which is legal.
  13696. for (; SI != SE; ++SI) {
  13697. QualType Type;
  13698. if (const auto *ASE =
  13699. dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
  13700. Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
  13701. } else if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(
  13702. SI->getAssociatedExpression())) {
  13703. const Expr *E = OASE->getBase()->IgnoreParenImpCasts();
  13704. Type =
  13705. OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
  13706. }
  13707. if (Type.isNull() || Type->isAnyPointerType() ||
  13708. checkArrayExpressionDoesNotReferToWholeSize(
  13709. SemaRef, SI->getAssociatedExpression(), Type))
  13710. break;
  13711. }
  13712. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
  13713. // List items of map clauses in the same construct must not share
  13714. // original storage.
  13715. //
  13716. // If the expressions are exactly the same or one is a subset of the
  13717. // other, it means they are sharing storage.
  13718. if (CI == CE && SI == SE) {
  13719. if (CurrentRegionOnly) {
  13720. if (CKind == OMPC_map) {
  13721. SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
  13722. } else {
  13723. assert(CKind == OMPC_to || CKind == OMPC_from);
  13724. SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
  13725. << ERange;
  13726. }
  13727. SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
  13728. << RE->getSourceRange();
  13729. return true;
  13730. }
  13731. // If we find the same expression in the enclosing data environment,
  13732. // that is legal.
  13733. IsEnclosedByDataEnvironmentExpr = true;
  13734. return false;
  13735. }
  13736. QualType DerivedType =
  13737. std::prev(CI)->getAssociatedDeclaration()->getType();
  13738. SourceLocation DerivedLoc =
  13739. std::prev(CI)->getAssociatedExpression()->getExprLoc();
  13740. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
  13741. // If the type of a list item is a reference to a type T then the type
  13742. // will be considered to be T for all purposes of this clause.
  13743. DerivedType = DerivedType.getNonReferenceType();
  13744. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
  13745. // A variable for which the type is pointer and an array section
  13746. // derived from that variable must not appear as list items of map
  13747. // clauses of the same construct.
  13748. //
  13749. // Also, cover one of the cases in:
  13750. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
  13751. // If any part of the original storage of a list item has corresponding
  13752. // storage in the device data environment, all of the original storage
  13753. // must have corresponding storage in the device data environment.
  13754. //
  13755. if (DerivedType->isAnyPointerType()) {
  13756. if (CI == CE || SI == SE) {
  13757. SemaRef.Diag(
  13758. DerivedLoc,
  13759. diag::err_omp_pointer_mapped_along_with_derived_section)
  13760. << DerivedLoc;
  13761. SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
  13762. << RE->getSourceRange();
  13763. return true;
  13764. }
  13765. if (CI->getAssociatedExpression()->getStmtClass() !=
  13766. SI->getAssociatedExpression()->getStmtClass() ||
  13767. CI->getAssociatedDeclaration()->getCanonicalDecl() ==
  13768. SI->getAssociatedDeclaration()->getCanonicalDecl()) {
  13769. assert(CI != CE && SI != SE);
  13770. SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_dereferenced)
  13771. << DerivedLoc;
  13772. SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
  13773. << RE->getSourceRange();
  13774. return true;
  13775. }
  13776. }
  13777. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
  13778. // List items of map clauses in the same construct must not share
  13779. // original storage.
  13780. //
  13781. // An expression is a subset of the other.
  13782. if (CurrentRegionOnly && (CI == CE || SI == SE)) {
  13783. if (CKind == OMPC_map) {
  13784. if (CI != CE || SI != SE) {
  13785. // Allow constructs like this: map(s, s.ptr[0:1]), where s.ptr is
  13786. // a pointer.
  13787. auto Begin =
  13788. CI != CE ? CurComponents.begin() : StackComponents.begin();
  13789. auto End = CI != CE ? CurComponents.end() : StackComponents.end();
  13790. auto It = Begin;
  13791. while (It != End && !It->getAssociatedDeclaration())
  13792. std::advance(It, 1);
  13793. assert(It != End &&
  13794. "Expected at least one component with the declaration.");
  13795. if (It != Begin && It->getAssociatedDeclaration()
  13796. ->getType()
  13797. .getCanonicalType()
  13798. ->isAnyPointerType()) {
  13799. IsEnclosedByDataEnvironmentExpr = false;
  13800. EnclosingExpr = nullptr;
  13801. return false;
  13802. }
  13803. }
  13804. SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
  13805. } else {
  13806. assert(CKind == OMPC_to || CKind == OMPC_from);
  13807. SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
  13808. << ERange;
  13809. }
  13810. SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
  13811. << RE->getSourceRange();
  13812. return true;
  13813. }
  13814. // The current expression uses the same base as other expression in the
  13815. // data environment but does not contain it completely.
  13816. if (!CurrentRegionOnly && SI != SE)
  13817. EnclosingExpr = RE;
  13818. // The current expression is a subset of the expression in the data
  13819. // environment.
  13820. IsEnclosedByDataEnvironmentExpr |=
  13821. (!CurrentRegionOnly && CI != CE && SI == SE);
  13822. return false;
  13823. });
  13824. if (CurrentRegionOnly)
  13825. return FoundError;
  13826. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
  13827. // If any part of the original storage of a list item has corresponding
  13828. // storage in the device data environment, all of the original storage must
  13829. // have corresponding storage in the device data environment.
  13830. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
  13831. // If a list item is an element of a structure, and a different element of
  13832. // the structure has a corresponding list item in the device data environment
  13833. // prior to a task encountering the construct associated with the map clause,
  13834. // then the list item must also have a corresponding list item in the device
  13835. // data environment prior to the task encountering the construct.
  13836. //
  13837. if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
  13838. SemaRef.Diag(ELoc,
  13839. diag::err_omp_original_storage_is_shared_and_does_not_contain)
  13840. << ERange;
  13841. SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
  13842. << EnclosingExpr->getSourceRange();
  13843. return true;
  13844. }
  13845. return FoundError;
  13846. }
  13847. // Look up the user-defined mapper given the mapper name and mapped type, and
  13848. // build a reference to it.
  13849. static ExprResult buildUserDefinedMapperRef(Sema &SemaRef, Scope *S,
  13850. CXXScopeSpec &MapperIdScopeSpec,
  13851. const DeclarationNameInfo &MapperId,
  13852. QualType Type,
  13853. Expr *UnresolvedMapper) {
  13854. if (MapperIdScopeSpec.isInvalid())
  13855. return ExprError();
  13856. // Get the actual type for the array type.
  13857. if (Type->isArrayType()) {
  13858. assert(Type->getAsArrayTypeUnsafe() && "Expect to get a valid array type");
  13859. Type = Type->getAsArrayTypeUnsafe()->getElementType().getCanonicalType();
  13860. }
  13861. // Find all user-defined mappers with the given MapperId.
  13862. SmallVector<UnresolvedSet<8>, 4> Lookups;
  13863. LookupResult Lookup(SemaRef, MapperId, Sema::LookupOMPMapperName);
  13864. Lookup.suppressDiagnostics();
  13865. if (S) {
  13866. while (S && SemaRef.LookupParsedName(Lookup, S, &MapperIdScopeSpec)) {
  13867. NamedDecl *D = Lookup.getRepresentativeDecl();
  13868. while (S && !S->isDeclScope(D))
  13869. S = S->getParent();
  13870. if (S)
  13871. S = S->getParent();
  13872. Lookups.emplace_back();
  13873. Lookups.back().append(Lookup.begin(), Lookup.end());
  13874. Lookup.clear();
  13875. }
  13876. } else if (auto *ULE = cast_or_null<UnresolvedLookupExpr>(UnresolvedMapper)) {
  13877. // Extract the user-defined mappers with the given MapperId.
  13878. Lookups.push_back(UnresolvedSet<8>());
  13879. for (NamedDecl *D : ULE->decls()) {
  13880. auto *DMD = cast<OMPDeclareMapperDecl>(D);
  13881. assert(DMD && "Expect valid OMPDeclareMapperDecl during instantiation.");
  13882. Lookups.back().addDecl(DMD);
  13883. }
  13884. }
  13885. // Defer the lookup for dependent types. The results will be passed through
  13886. // UnresolvedMapper on instantiation.
  13887. if (SemaRef.CurContext->isDependentContext() || Type->isDependentType() ||
  13888. Type->isInstantiationDependentType() ||
  13889. Type->containsUnexpandedParameterPack() ||
  13890. filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) {
  13891. return !D->isInvalidDecl() &&
  13892. (D->getType()->isDependentType() ||
  13893. D->getType()->isInstantiationDependentType() ||
  13894. D->getType()->containsUnexpandedParameterPack());
  13895. })) {
  13896. UnresolvedSet<8> URS;
  13897. for (const UnresolvedSet<8> &Set : Lookups) {
  13898. if (Set.empty())
  13899. continue;
  13900. URS.append(Set.begin(), Set.end());
  13901. }
  13902. return UnresolvedLookupExpr::Create(
  13903. SemaRef.Context, /*NamingClass=*/nullptr,
  13904. MapperIdScopeSpec.getWithLocInContext(SemaRef.Context), MapperId,
  13905. /*ADL=*/false, /*Overloaded=*/true, URS.begin(), URS.end());
  13906. }
  13907. SourceLocation Loc = MapperId.getLoc();
  13908. // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
  13909. // The type must be of struct, union or class type in C and C++
  13910. if (!Type->isStructureOrClassType() && !Type->isUnionType() &&
  13911. (MapperIdScopeSpec.isSet() || MapperId.getAsString() != "default")) {
  13912. SemaRef.Diag(Loc, diag::err_omp_mapper_wrong_type);
  13913. return ExprError();
  13914. }
  13915. // Perform argument dependent lookup.
  13916. if (SemaRef.getLangOpts().CPlusPlus && !MapperIdScopeSpec.isSet())
  13917. argumentDependentLookup(SemaRef, MapperId, Loc, Type, Lookups);
  13918. // Return the first user-defined mapper with the desired type.
  13919. if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
  13920. Lookups, [&SemaRef, Type](ValueDecl *D) -> ValueDecl * {
  13921. if (!D->isInvalidDecl() &&
  13922. SemaRef.Context.hasSameType(D->getType(), Type))
  13923. return D;
  13924. return nullptr;
  13925. }))
  13926. return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
  13927. // Find the first user-defined mapper with a type derived from the desired
  13928. // type.
  13929. if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
  13930. Lookups, [&SemaRef, Type, Loc](ValueDecl *D) -> ValueDecl * {
  13931. if (!D->isInvalidDecl() &&
  13932. SemaRef.IsDerivedFrom(Loc, Type, D->getType()) &&
  13933. !Type.isMoreQualifiedThan(D->getType()))
  13934. return D;
  13935. return nullptr;
  13936. })) {
  13937. CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
  13938. /*DetectVirtual=*/false);
  13939. if (SemaRef.IsDerivedFrom(Loc, Type, VD->getType(), Paths)) {
  13940. if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
  13941. VD->getType().getUnqualifiedType()))) {
  13942. if (SemaRef.CheckBaseClassAccess(
  13943. Loc, VD->getType(), Type, Paths.front(),
  13944. /*DiagID=*/0) != Sema::AR_inaccessible) {
  13945. return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
  13946. }
  13947. }
  13948. }
  13949. }
  13950. // Report error if a mapper is specified, but cannot be found.
  13951. if (MapperIdScopeSpec.isSet() || MapperId.getAsString() != "default") {
  13952. SemaRef.Diag(Loc, diag::err_omp_invalid_mapper)
  13953. << Type << MapperId.getName();
  13954. return ExprError();
  13955. }
  13956. return ExprEmpty();
  13957. }
  13958. namespace {
  13959. // Utility struct that gathers all the related lists associated with a mappable
  13960. // expression.
  13961. struct MappableVarListInfo {
  13962. // The list of expressions.
  13963. ArrayRef<Expr *> VarList;
  13964. // The list of processed expressions.
  13965. SmallVector<Expr *, 16> ProcessedVarList;
  13966. // The mappble components for each expression.
  13967. OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
  13968. // The base declaration of the variable.
  13969. SmallVector<ValueDecl *, 16> VarBaseDeclarations;
  13970. // The reference to the user-defined mapper associated with every expression.
  13971. SmallVector<Expr *, 16> UDMapperList;
  13972. MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
  13973. // We have a list of components and base declarations for each entry in the
  13974. // variable list.
  13975. VarComponents.reserve(VarList.size());
  13976. VarBaseDeclarations.reserve(VarList.size());
  13977. }
  13978. };
  13979. }
  13980. // Check the validity of the provided variable list for the provided clause kind
  13981. // \a CKind. In the check process the valid expressions, mappable expression
  13982. // components, variables, and user-defined mappers are extracted and used to
  13983. // fill \a ProcessedVarList, \a VarComponents, \a VarBaseDeclarations, and \a
  13984. // UDMapperList in MVLI. \a MapType, \a IsMapTypeImplicit, \a MapperIdScopeSpec,
  13985. // and \a MapperId are expected to be valid if the clause kind is 'map'.
  13986. static void checkMappableExpressionList(
  13987. Sema &SemaRef, DSAStackTy *DSAS, OpenMPClauseKind CKind,
  13988. MappableVarListInfo &MVLI, SourceLocation StartLoc,
  13989. CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo MapperId,
  13990. ArrayRef<Expr *> UnresolvedMappers,
  13991. OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
  13992. bool IsMapTypeImplicit = false) {
  13993. // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
  13994. assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
  13995. "Unexpected clause kind with mappable expressions!");
  13996. // If the identifier of user-defined mapper is not specified, it is "default".
  13997. // We do not change the actual name in this clause to distinguish whether a
  13998. // mapper is specified explicitly, i.e., it is not explicitly specified when
  13999. // MapperId.getName() is empty.
  14000. if (!MapperId.getName() || MapperId.getName().isEmpty()) {
  14001. auto &DeclNames = SemaRef.getASTContext().DeclarationNames;
  14002. MapperId.setName(DeclNames.getIdentifier(
  14003. &SemaRef.getASTContext().Idents.get("default")));
  14004. }
  14005. // Iterators to find the current unresolved mapper expression.
  14006. auto UMIt = UnresolvedMappers.begin(), UMEnd = UnresolvedMappers.end();
  14007. bool UpdateUMIt = false;
  14008. Expr *UnresolvedMapper = nullptr;
  14009. // Keep track of the mappable components and base declarations in this clause.
  14010. // Each entry in the list is going to have a list of components associated. We
  14011. // record each set of the components so that we can build the clause later on.
  14012. // In the end we should have the same amount of declarations and component
  14013. // lists.
  14014. for (Expr *RE : MVLI.VarList) {
  14015. assert(RE && "Null expr in omp to/from/map clause");
  14016. SourceLocation ELoc = RE->getExprLoc();
  14017. // Find the current unresolved mapper expression.
  14018. if (UpdateUMIt && UMIt != UMEnd) {
  14019. UMIt++;
  14020. assert(
  14021. UMIt != UMEnd &&
  14022. "Expect the size of UnresolvedMappers to match with that of VarList");
  14023. }
  14024. UpdateUMIt = true;
  14025. if (UMIt != UMEnd)
  14026. UnresolvedMapper = *UMIt;
  14027. const Expr *VE = RE->IgnoreParenLValueCasts();
  14028. if (VE->isValueDependent() || VE->isTypeDependent() ||
  14029. VE->isInstantiationDependent() ||
  14030. VE->containsUnexpandedParameterPack()) {
  14031. // Try to find the associated user-defined mapper.
  14032. ExprResult ER = buildUserDefinedMapperRef(
  14033. SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
  14034. VE->getType().getCanonicalType(), UnresolvedMapper);
  14035. if (ER.isInvalid())
  14036. continue;
  14037. MVLI.UDMapperList.push_back(ER.get());
  14038. // We can only analyze this information once the missing information is
  14039. // resolved.
  14040. MVLI.ProcessedVarList.push_back(RE);
  14041. continue;
  14042. }
  14043. Expr *SimpleExpr = RE->IgnoreParenCasts();
  14044. if (!RE->IgnoreParenImpCasts()->isLValue()) {
  14045. SemaRef.Diag(ELoc,
  14046. diag::err_omp_expected_named_var_member_or_array_expression)
  14047. << RE->getSourceRange();
  14048. continue;
  14049. }
  14050. OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
  14051. ValueDecl *CurDeclaration = nullptr;
  14052. // Obtain the array or member expression bases if required. Also, fill the
  14053. // components array with all the components identified in the process.
  14054. const Expr *BE = checkMapClauseExpressionBase(
  14055. SemaRef, SimpleExpr, CurComponents, CKind, /*NoDiagnose=*/false);
  14056. if (!BE)
  14057. continue;
  14058. assert(!CurComponents.empty() &&
  14059. "Invalid mappable expression information.");
  14060. if (const auto *TE = dyn_cast<CXXThisExpr>(BE)) {
  14061. // Add store "this" pointer to class in DSAStackTy for future checking
  14062. DSAS->addMappedClassesQualTypes(TE->getType());
  14063. // Try to find the associated user-defined mapper.
  14064. ExprResult ER = buildUserDefinedMapperRef(
  14065. SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
  14066. VE->getType().getCanonicalType(), UnresolvedMapper);
  14067. if (ER.isInvalid())
  14068. continue;
  14069. MVLI.UDMapperList.push_back(ER.get());
  14070. // Skip restriction checking for variable or field declarations
  14071. MVLI.ProcessedVarList.push_back(RE);
  14072. MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
  14073. MVLI.VarComponents.back().append(CurComponents.begin(),
  14074. CurComponents.end());
  14075. MVLI.VarBaseDeclarations.push_back(nullptr);
  14076. continue;
  14077. }
  14078. // For the following checks, we rely on the base declaration which is
  14079. // expected to be associated with the last component. The declaration is
  14080. // expected to be a variable or a field (if 'this' is being mapped).
  14081. CurDeclaration = CurComponents.back().getAssociatedDeclaration();
  14082. assert(CurDeclaration && "Null decl on map clause.");
  14083. assert(
  14084. CurDeclaration->isCanonicalDecl() &&
  14085. "Expecting components to have associated only canonical declarations.");
  14086. auto *VD = dyn_cast<VarDecl>(CurDeclaration);
  14087. const auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
  14088. assert((VD || FD) && "Only variables or fields are expected here!");
  14089. (void)FD;
  14090. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
  14091. // threadprivate variables cannot appear in a map clause.
  14092. // OpenMP 4.5 [2.10.5, target update Construct]
  14093. // threadprivate variables cannot appear in a from clause.
  14094. if (VD && DSAS->isThreadPrivate(VD)) {
  14095. DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
  14096. SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
  14097. << getOpenMPClauseName(CKind);
  14098. reportOriginalDsa(SemaRef, DSAS, VD, DVar);
  14099. continue;
  14100. }
  14101. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
  14102. // A list item cannot appear in both a map clause and a data-sharing
  14103. // attribute clause on the same construct.
  14104. // Check conflicts with other map clause expressions. We check the conflicts
  14105. // with the current construct separately from the enclosing data
  14106. // environment, because the restrictions are different. We only have to
  14107. // check conflicts across regions for the map clauses.
  14108. if (checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
  14109. /*CurrentRegionOnly=*/true, CurComponents, CKind))
  14110. break;
  14111. if (CKind == OMPC_map &&
  14112. checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
  14113. /*CurrentRegionOnly=*/false, CurComponents, CKind))
  14114. break;
  14115. // OpenMP 4.5 [2.10.5, target update Construct]
  14116. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
  14117. // If the type of a list item is a reference to a type T then the type will
  14118. // be considered to be T for all purposes of this clause.
  14119. auto I = llvm::find_if(
  14120. CurComponents,
  14121. [](const OMPClauseMappableExprCommon::MappableComponent &MC) {
  14122. return MC.getAssociatedDeclaration();
  14123. });
  14124. assert(I != CurComponents.end() && "Null decl on map clause.");
  14125. QualType Type =
  14126. I->getAssociatedDeclaration()->getType().getNonReferenceType();
  14127. // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
  14128. // A list item in a to or from clause must have a mappable type.
  14129. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
  14130. // A list item must have a mappable type.
  14131. if (!checkTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
  14132. DSAS, Type))
  14133. continue;
  14134. if (CKind == OMPC_map) {
  14135. // target enter data
  14136. // OpenMP [2.10.2, Restrictions, p. 99]
  14137. // A map-type must be specified in all map clauses and must be either
  14138. // to or alloc.
  14139. OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
  14140. if (DKind == OMPD_target_enter_data &&
  14141. !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
  14142. SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
  14143. << (IsMapTypeImplicit ? 1 : 0)
  14144. << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
  14145. << getOpenMPDirectiveName(DKind);
  14146. continue;
  14147. }
  14148. // target exit_data
  14149. // OpenMP [2.10.3, Restrictions, p. 102]
  14150. // A map-type must be specified in all map clauses and must be either
  14151. // from, release, or delete.
  14152. if (DKind == OMPD_target_exit_data &&
  14153. !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
  14154. MapType == OMPC_MAP_delete)) {
  14155. SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
  14156. << (IsMapTypeImplicit ? 1 : 0)
  14157. << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
  14158. << getOpenMPDirectiveName(DKind);
  14159. continue;
  14160. }
  14161. // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
  14162. // A list item cannot appear in both a map clause and a data-sharing
  14163. // attribute clause on the same construct
  14164. //
  14165. // OpenMP 5.0 [2.19.7.1, Restrictions, p.7]
  14166. // A list item cannot appear in both a map clause and a data-sharing
  14167. // attribute clause on the same construct unless the construct is a
  14168. // combined construct.
  14169. if (VD && ((SemaRef.LangOpts.OpenMP <= 45 &&
  14170. isOpenMPTargetExecutionDirective(DKind)) ||
  14171. DKind == OMPD_target)) {
  14172. DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
  14173. if (isOpenMPPrivate(DVar.CKind)) {
  14174. SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
  14175. << getOpenMPClauseName(DVar.CKind)
  14176. << getOpenMPClauseName(OMPC_map)
  14177. << getOpenMPDirectiveName(DSAS->getCurrentDirective());
  14178. reportOriginalDsa(SemaRef, DSAS, CurDeclaration, DVar);
  14179. continue;
  14180. }
  14181. }
  14182. }
  14183. // Try to find the associated user-defined mapper.
  14184. ExprResult ER = buildUserDefinedMapperRef(
  14185. SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
  14186. Type.getCanonicalType(), UnresolvedMapper);
  14187. if (ER.isInvalid())
  14188. continue;
  14189. MVLI.UDMapperList.push_back(ER.get());
  14190. // Save the current expression.
  14191. MVLI.ProcessedVarList.push_back(RE);
  14192. // Store the components in the stack so that they can be used to check
  14193. // against other clauses later on.
  14194. DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
  14195. /*WhereFoundClauseKind=*/OMPC_map);
  14196. // Save the components and declaration to create the clause. For purposes of
  14197. // the clause creation, any component list that has has base 'this' uses
  14198. // null as base declaration.
  14199. MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
  14200. MVLI.VarComponents.back().append(CurComponents.begin(),
  14201. CurComponents.end());
  14202. MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
  14203. : CurDeclaration);
  14204. }
  14205. }
  14206. OMPClause *Sema::ActOnOpenMPMapClause(
  14207. ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
  14208. ArrayRef<SourceLocation> MapTypeModifiersLoc,
  14209. CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId,
  14210. OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, SourceLocation MapLoc,
  14211. SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
  14212. const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) {
  14213. OpenMPMapModifierKind Modifiers[] = {OMPC_MAP_MODIFIER_unknown,
  14214. OMPC_MAP_MODIFIER_unknown,
  14215. OMPC_MAP_MODIFIER_unknown};
  14216. SourceLocation ModifiersLoc[OMPMapClause::NumberOfModifiers];
  14217. // Process map-type-modifiers, flag errors for duplicate modifiers.
  14218. unsigned Count = 0;
  14219. for (unsigned I = 0, E = MapTypeModifiers.size(); I < E; ++I) {
  14220. if (MapTypeModifiers[I] != OMPC_MAP_MODIFIER_unknown &&
  14221. llvm::find(Modifiers, MapTypeModifiers[I]) != std::end(Modifiers)) {
  14222. Diag(MapTypeModifiersLoc[I], diag::err_omp_duplicate_map_type_modifier);
  14223. continue;
  14224. }
  14225. assert(Count < OMPMapClause::NumberOfModifiers &&
  14226. "Modifiers exceed the allowed number of map type modifiers");
  14227. Modifiers[Count] = MapTypeModifiers[I];
  14228. ModifiersLoc[Count] = MapTypeModifiersLoc[I];
  14229. ++Count;
  14230. }
  14231. MappableVarListInfo MVLI(VarList);
  14232. checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, Locs.StartLoc,
  14233. MapperIdScopeSpec, MapperId, UnresolvedMappers,
  14234. MapType, IsMapTypeImplicit);
  14235. // We need to produce a map clause even if we don't have variables so that
  14236. // other diagnostics related with non-existing map clauses are accurate.
  14237. return OMPMapClause::Create(Context, Locs, MVLI.ProcessedVarList,
  14238. MVLI.VarBaseDeclarations, MVLI.VarComponents,
  14239. MVLI.UDMapperList, Modifiers, ModifiersLoc,
  14240. MapperIdScopeSpec.getWithLocInContext(Context),
  14241. MapperId, MapType, IsMapTypeImplicit, MapLoc);
  14242. }
  14243. QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
  14244. TypeResult ParsedType) {
  14245. assert(ParsedType.isUsable());
  14246. QualType ReductionType = GetTypeFromParser(ParsedType.get());
  14247. if (ReductionType.isNull())
  14248. return QualType();
  14249. // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
  14250. // A type name in a declare reduction directive cannot be a function type, an
  14251. // array type, a reference type, or a type qualified with const, volatile or
  14252. // restrict.
  14253. if (ReductionType.hasQualifiers()) {
  14254. Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
  14255. return QualType();
  14256. }
  14257. if (ReductionType->isFunctionType()) {
  14258. Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
  14259. return QualType();
  14260. }
  14261. if (ReductionType->isReferenceType()) {
  14262. Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
  14263. return QualType();
  14264. }
  14265. if (ReductionType->isArrayType()) {
  14266. Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
  14267. return QualType();
  14268. }
  14269. return ReductionType;
  14270. }
  14271. Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
  14272. Scope *S, DeclContext *DC, DeclarationName Name,
  14273. ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
  14274. AccessSpecifier AS, Decl *PrevDeclInScope) {
  14275. SmallVector<Decl *, 8> Decls;
  14276. Decls.reserve(ReductionTypes.size());
  14277. LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
  14278. forRedeclarationInCurContext());
  14279. // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
  14280. // A reduction-identifier may not be re-declared in the current scope for the
  14281. // same type or for a type that is compatible according to the base language
  14282. // rules.
  14283. llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
  14284. OMPDeclareReductionDecl *PrevDRD = nullptr;
  14285. bool InCompoundScope = true;
  14286. if (S != nullptr) {
  14287. // Find previous declaration with the same name not referenced in other
  14288. // declarations.
  14289. FunctionScopeInfo *ParentFn = getEnclosingFunction();
  14290. InCompoundScope =
  14291. (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
  14292. LookupName(Lookup, S);
  14293. FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
  14294. /*AllowInlineNamespace=*/false);
  14295. llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
  14296. LookupResult::Filter Filter = Lookup.makeFilter();
  14297. while (Filter.hasNext()) {
  14298. auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
  14299. if (InCompoundScope) {
  14300. auto I = UsedAsPrevious.find(PrevDecl);
  14301. if (I == UsedAsPrevious.end())
  14302. UsedAsPrevious[PrevDecl] = false;
  14303. if (OMPDeclareReductionDecl *D = PrevDecl->getPrevDeclInScope())
  14304. UsedAsPrevious[D] = true;
  14305. }
  14306. PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
  14307. PrevDecl->getLocation();
  14308. }
  14309. Filter.done();
  14310. if (InCompoundScope) {
  14311. for (const auto &PrevData : UsedAsPrevious) {
  14312. if (!PrevData.second) {
  14313. PrevDRD = PrevData.first;
  14314. break;
  14315. }
  14316. }
  14317. }
  14318. } else if (PrevDeclInScope != nullptr) {
  14319. auto *PrevDRDInScope = PrevDRD =
  14320. cast<OMPDeclareReductionDecl>(PrevDeclInScope);
  14321. do {
  14322. PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
  14323. PrevDRDInScope->getLocation();
  14324. PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
  14325. } while (PrevDRDInScope != nullptr);
  14326. }
  14327. for (const auto &TyData : ReductionTypes) {
  14328. const auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
  14329. bool Invalid = false;
  14330. if (I != PreviousRedeclTypes.end()) {
  14331. Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
  14332. << TyData.first;
  14333. Diag(I->second, diag::note_previous_definition);
  14334. Invalid = true;
  14335. }
  14336. PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
  14337. auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
  14338. Name, TyData.first, PrevDRD);
  14339. DC->addDecl(DRD);
  14340. DRD->setAccess(AS);
  14341. Decls.push_back(DRD);
  14342. if (Invalid)
  14343. DRD->setInvalidDecl();
  14344. else
  14345. PrevDRD = DRD;
  14346. }
  14347. return DeclGroupPtrTy::make(
  14348. DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
  14349. }
  14350. void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
  14351. auto *DRD = cast<OMPDeclareReductionDecl>(D);
  14352. // Enter new function scope.
  14353. PushFunctionScope();
  14354. setFunctionHasBranchProtectedScope();
  14355. getCurFunction()->setHasOMPDeclareReductionCombiner();
  14356. if (S != nullptr)
  14357. PushDeclContext(S, DRD);
  14358. else
  14359. CurContext = DRD;
  14360. PushExpressionEvaluationContext(
  14361. ExpressionEvaluationContext::PotentiallyEvaluated);
  14362. QualType ReductionType = DRD->getType();
  14363. // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
  14364. // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
  14365. // uses semantics of argument handles by value, but it should be passed by
  14366. // reference. C lang does not support references, so pass all parameters as
  14367. // pointers.
  14368. // Create 'T omp_in;' variable.
  14369. VarDecl *OmpInParm =
  14370. buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
  14371. // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
  14372. // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
  14373. // uses semantics of argument handles by value, but it should be passed by
  14374. // reference. C lang does not support references, so pass all parameters as
  14375. // pointers.
  14376. // Create 'T omp_out;' variable.
  14377. VarDecl *OmpOutParm =
  14378. buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
  14379. if (S != nullptr) {
  14380. PushOnScopeChains(OmpInParm, S);
  14381. PushOnScopeChains(OmpOutParm, S);
  14382. } else {
  14383. DRD->addDecl(OmpInParm);
  14384. DRD->addDecl(OmpOutParm);
  14385. }
  14386. Expr *InE =
  14387. ::buildDeclRefExpr(*this, OmpInParm, ReductionType, D->getLocation());
  14388. Expr *OutE =
  14389. ::buildDeclRefExpr(*this, OmpOutParm, ReductionType, D->getLocation());
  14390. DRD->setCombinerData(InE, OutE);
  14391. }
  14392. void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
  14393. auto *DRD = cast<OMPDeclareReductionDecl>(D);
  14394. DiscardCleanupsInEvaluationContext();
  14395. PopExpressionEvaluationContext();
  14396. PopDeclContext();
  14397. PopFunctionScopeInfo();
  14398. if (Combiner != nullptr)
  14399. DRD->setCombiner(Combiner);
  14400. else
  14401. DRD->setInvalidDecl();
  14402. }
  14403. VarDecl *Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
  14404. auto *DRD = cast<OMPDeclareReductionDecl>(D);
  14405. // Enter new function scope.
  14406. PushFunctionScope();
  14407. setFunctionHasBranchProtectedScope();
  14408. if (S != nullptr)
  14409. PushDeclContext(S, DRD);
  14410. else
  14411. CurContext = DRD;
  14412. PushExpressionEvaluationContext(
  14413. ExpressionEvaluationContext::PotentiallyEvaluated);
  14414. QualType ReductionType = DRD->getType();
  14415. // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
  14416. // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
  14417. // uses semantics of argument handles by value, but it should be passed by
  14418. // reference. C lang does not support references, so pass all parameters as
  14419. // pointers.
  14420. // Create 'T omp_priv;' variable.
  14421. VarDecl *OmpPrivParm =
  14422. buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
  14423. // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
  14424. // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
  14425. // uses semantics of argument handles by value, but it should be passed by
  14426. // reference. C lang does not support references, so pass all parameters as
  14427. // pointers.
  14428. // Create 'T omp_orig;' variable.
  14429. VarDecl *OmpOrigParm =
  14430. buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
  14431. if (S != nullptr) {
  14432. PushOnScopeChains(OmpPrivParm, S);
  14433. PushOnScopeChains(OmpOrigParm, S);
  14434. } else {
  14435. DRD->addDecl(OmpPrivParm);
  14436. DRD->addDecl(OmpOrigParm);
  14437. }
  14438. Expr *OrigE =
  14439. ::buildDeclRefExpr(*this, OmpOrigParm, ReductionType, D->getLocation());
  14440. Expr *PrivE =
  14441. ::buildDeclRefExpr(*this, OmpPrivParm, ReductionType, D->getLocation());
  14442. DRD->setInitializerData(OrigE, PrivE);
  14443. return OmpPrivParm;
  14444. }
  14445. void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
  14446. VarDecl *OmpPrivParm) {
  14447. auto *DRD = cast<OMPDeclareReductionDecl>(D);
  14448. DiscardCleanupsInEvaluationContext();
  14449. PopExpressionEvaluationContext();
  14450. PopDeclContext();
  14451. PopFunctionScopeInfo();
  14452. if (Initializer != nullptr) {
  14453. DRD->setInitializer(Initializer, OMPDeclareReductionDecl::CallInit);
  14454. } else if (OmpPrivParm->hasInit()) {
  14455. DRD->setInitializer(OmpPrivParm->getInit(),
  14456. OmpPrivParm->isDirectInit()
  14457. ? OMPDeclareReductionDecl::DirectInit
  14458. : OMPDeclareReductionDecl::CopyInit);
  14459. } else {
  14460. DRD->setInvalidDecl();
  14461. }
  14462. }
  14463. Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
  14464. Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
  14465. for (Decl *D : DeclReductions.get()) {
  14466. if (IsValid) {
  14467. if (S)
  14468. PushOnScopeChains(cast<OMPDeclareReductionDecl>(D), S,
  14469. /*AddToContext=*/false);
  14470. } else {
  14471. D->setInvalidDecl();
  14472. }
  14473. }
  14474. return DeclReductions;
  14475. }
  14476. TypeResult Sema::ActOnOpenMPDeclareMapperVarDecl(Scope *S, Declarator &D) {
  14477. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  14478. QualType T = TInfo->getType();
  14479. if (D.isInvalidType())
  14480. return true;
  14481. if (getLangOpts().CPlusPlus) {
  14482. // Check that there are no default arguments (C++ only).
  14483. CheckExtraCXXDefaultArguments(D);
  14484. }
  14485. return CreateParsedType(T, TInfo);
  14486. }
  14487. QualType Sema::ActOnOpenMPDeclareMapperType(SourceLocation TyLoc,
  14488. TypeResult ParsedType) {
  14489. assert(ParsedType.isUsable() && "Expect usable parsed mapper type");
  14490. QualType MapperType = GetTypeFromParser(ParsedType.get());
  14491. assert(!MapperType.isNull() && "Expect valid mapper type");
  14492. // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
  14493. // The type must be of struct, union or class type in C and C++
  14494. if (!MapperType->isStructureOrClassType() && !MapperType->isUnionType()) {
  14495. Diag(TyLoc, diag::err_omp_mapper_wrong_type);
  14496. return QualType();
  14497. }
  14498. return MapperType;
  14499. }
  14500. OMPDeclareMapperDecl *Sema::ActOnOpenMPDeclareMapperDirectiveStart(
  14501. Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType,
  14502. SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS,
  14503. Decl *PrevDeclInScope) {
  14504. LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPMapperName,
  14505. forRedeclarationInCurContext());
  14506. // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
  14507. // A mapper-identifier may not be redeclared in the current scope for the
  14508. // same type or for a type that is compatible according to the base language
  14509. // rules.
  14510. llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
  14511. OMPDeclareMapperDecl *PrevDMD = nullptr;
  14512. bool InCompoundScope = true;
  14513. if (S != nullptr) {
  14514. // Find previous declaration with the same name not referenced in other
  14515. // declarations.
  14516. FunctionScopeInfo *ParentFn = getEnclosingFunction();
  14517. InCompoundScope =
  14518. (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
  14519. LookupName(Lookup, S);
  14520. FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
  14521. /*AllowInlineNamespace=*/false);
  14522. llvm::DenseMap<OMPDeclareMapperDecl *, bool> UsedAsPrevious;
  14523. LookupResult::Filter Filter = Lookup.makeFilter();
  14524. while (Filter.hasNext()) {
  14525. auto *PrevDecl = cast<OMPDeclareMapperDecl>(Filter.next());
  14526. if (InCompoundScope) {
  14527. auto I = UsedAsPrevious.find(PrevDecl);
  14528. if (I == UsedAsPrevious.end())
  14529. UsedAsPrevious[PrevDecl] = false;
  14530. if (OMPDeclareMapperDecl *D = PrevDecl->getPrevDeclInScope())
  14531. UsedAsPrevious[D] = true;
  14532. }
  14533. PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
  14534. PrevDecl->getLocation();
  14535. }
  14536. Filter.done();
  14537. if (InCompoundScope) {
  14538. for (const auto &PrevData : UsedAsPrevious) {
  14539. if (!PrevData.second) {
  14540. PrevDMD = PrevData.first;
  14541. break;
  14542. }
  14543. }
  14544. }
  14545. } else if (PrevDeclInScope) {
  14546. auto *PrevDMDInScope = PrevDMD =
  14547. cast<OMPDeclareMapperDecl>(PrevDeclInScope);
  14548. do {
  14549. PreviousRedeclTypes[PrevDMDInScope->getType().getCanonicalType()] =
  14550. PrevDMDInScope->getLocation();
  14551. PrevDMDInScope = PrevDMDInScope->getPrevDeclInScope();
  14552. } while (PrevDMDInScope != nullptr);
  14553. }
  14554. const auto I = PreviousRedeclTypes.find(MapperType.getCanonicalType());
  14555. bool Invalid = false;
  14556. if (I != PreviousRedeclTypes.end()) {
  14557. Diag(StartLoc, diag::err_omp_declare_mapper_redefinition)
  14558. << MapperType << Name;
  14559. Diag(I->second, diag::note_previous_definition);
  14560. Invalid = true;
  14561. }
  14562. auto *DMD = OMPDeclareMapperDecl::Create(Context, DC, StartLoc, Name,
  14563. MapperType, VN, PrevDMD);
  14564. DC->addDecl(DMD);
  14565. DMD->setAccess(AS);
  14566. if (Invalid)
  14567. DMD->setInvalidDecl();
  14568. // Enter new function scope.
  14569. PushFunctionScope();
  14570. setFunctionHasBranchProtectedScope();
  14571. CurContext = DMD;
  14572. return DMD;
  14573. }
  14574. void Sema::ActOnOpenMPDeclareMapperDirectiveVarDecl(OMPDeclareMapperDecl *DMD,
  14575. Scope *S,
  14576. QualType MapperType,
  14577. SourceLocation StartLoc,
  14578. DeclarationName VN) {
  14579. VarDecl *VD = buildVarDecl(*this, StartLoc, MapperType, VN.getAsString());
  14580. if (S)
  14581. PushOnScopeChains(VD, S);
  14582. else
  14583. DMD->addDecl(VD);
  14584. Expr *MapperVarRefExpr = buildDeclRefExpr(*this, VD, MapperType, StartLoc);
  14585. DMD->setMapperVarRef(MapperVarRefExpr);
  14586. }
  14587. Sema::DeclGroupPtrTy
  14588. Sema::ActOnOpenMPDeclareMapperDirectiveEnd(OMPDeclareMapperDecl *D, Scope *S,
  14589. ArrayRef<OMPClause *> ClauseList) {
  14590. PopDeclContext();
  14591. PopFunctionScopeInfo();
  14592. if (D) {
  14593. if (S)
  14594. PushOnScopeChains(D, S, /*AddToContext=*/false);
  14595. D->CreateClauses(Context, ClauseList);
  14596. }
  14597. return DeclGroupPtrTy::make(DeclGroupRef(D));
  14598. }
  14599. OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
  14600. SourceLocation StartLoc,
  14601. SourceLocation LParenLoc,
  14602. SourceLocation EndLoc) {
  14603. Expr *ValExpr = NumTeams;
  14604. Stmt *HelperValStmt = nullptr;
  14605. // OpenMP [teams Constrcut, Restrictions]
  14606. // The num_teams expression must evaluate to a positive integer value.
  14607. if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
  14608. /*StrictlyPositive=*/true))
  14609. return nullptr;
  14610. OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
  14611. OpenMPDirectiveKind CaptureRegion =
  14612. getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams);
  14613. if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
  14614. ValExpr = MakeFullExpr(ValExpr).get();
  14615. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  14616. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  14617. HelperValStmt = buildPreInits(Context, Captures);
  14618. }
  14619. return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion,
  14620. StartLoc, LParenLoc, EndLoc);
  14621. }
  14622. OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
  14623. SourceLocation StartLoc,
  14624. SourceLocation LParenLoc,
  14625. SourceLocation EndLoc) {
  14626. Expr *ValExpr = ThreadLimit;
  14627. Stmt *HelperValStmt = nullptr;
  14628. // OpenMP [teams Constrcut, Restrictions]
  14629. // The thread_limit expression must evaluate to a positive integer value.
  14630. if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
  14631. /*StrictlyPositive=*/true))
  14632. return nullptr;
  14633. OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
  14634. OpenMPDirectiveKind CaptureRegion =
  14635. getOpenMPCaptureRegionForClause(DKind, OMPC_thread_limit);
  14636. if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
  14637. ValExpr = MakeFullExpr(ValExpr).get();
  14638. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  14639. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  14640. HelperValStmt = buildPreInits(Context, Captures);
  14641. }
  14642. return new (Context) OMPThreadLimitClause(
  14643. ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
  14644. }
  14645. OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
  14646. SourceLocation StartLoc,
  14647. SourceLocation LParenLoc,
  14648. SourceLocation EndLoc) {
  14649. Expr *ValExpr = Priority;
  14650. // OpenMP [2.9.1, task Constrcut]
  14651. // The priority-value is a non-negative numerical scalar expression.
  14652. if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_priority,
  14653. /*StrictlyPositive=*/false))
  14654. return nullptr;
  14655. return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc);
  14656. }
  14657. OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
  14658. SourceLocation StartLoc,
  14659. SourceLocation LParenLoc,
  14660. SourceLocation EndLoc) {
  14661. Expr *ValExpr = Grainsize;
  14662. // OpenMP [2.9.2, taskloop Constrcut]
  14663. // The parameter of the grainsize clause must be a positive integer
  14664. // expression.
  14665. if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize,
  14666. /*StrictlyPositive=*/true))
  14667. return nullptr;
  14668. return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc);
  14669. }
  14670. OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
  14671. SourceLocation StartLoc,
  14672. SourceLocation LParenLoc,
  14673. SourceLocation EndLoc) {
  14674. Expr *ValExpr = NumTasks;
  14675. // OpenMP [2.9.2, taskloop Constrcut]
  14676. // The parameter of the num_tasks clause must be a positive integer
  14677. // expression.
  14678. if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks,
  14679. /*StrictlyPositive=*/true))
  14680. return nullptr;
  14681. return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc);
  14682. }
  14683. OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
  14684. SourceLocation LParenLoc,
  14685. SourceLocation EndLoc) {
  14686. // OpenMP [2.13.2, critical construct, Description]
  14687. // ... where hint-expression is an integer constant expression that evaluates
  14688. // to a valid lock hint.
  14689. ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
  14690. if (HintExpr.isInvalid())
  14691. return nullptr;
  14692. return new (Context)
  14693. OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
  14694. }
  14695. OMPClause *Sema::ActOnOpenMPDistScheduleClause(
  14696. OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
  14697. SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
  14698. SourceLocation EndLoc) {
  14699. if (Kind == OMPC_DIST_SCHEDULE_unknown) {
  14700. std::string Values;
  14701. Values += "'";
  14702. Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
  14703. Values += "'";
  14704. Diag(KindLoc, diag::err_omp_unexpected_clause_value)
  14705. << Values << getOpenMPClauseName(OMPC_dist_schedule);
  14706. return nullptr;
  14707. }
  14708. Expr *ValExpr = ChunkSize;
  14709. Stmt *HelperValStmt = nullptr;
  14710. if (ChunkSize) {
  14711. if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
  14712. !ChunkSize->isInstantiationDependent() &&
  14713. !ChunkSize->containsUnexpandedParameterPack()) {
  14714. SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
  14715. ExprResult Val =
  14716. PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
  14717. if (Val.isInvalid())
  14718. return nullptr;
  14719. ValExpr = Val.get();
  14720. // OpenMP [2.7.1, Restrictions]
  14721. // chunk_size must be a loop invariant integer expression with a positive
  14722. // value.
  14723. llvm::APSInt Result;
  14724. if (ValExpr->isIntegerConstantExpr(Result, Context)) {
  14725. if (Result.isSigned() && !Result.isStrictlyPositive()) {
  14726. Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
  14727. << "dist_schedule" << ChunkSize->getSourceRange();
  14728. return nullptr;
  14729. }
  14730. } else if (getOpenMPCaptureRegionForClause(
  14731. DSAStack->getCurrentDirective(), OMPC_dist_schedule) !=
  14732. OMPD_unknown &&
  14733. !CurContext->isDependentContext()) {
  14734. ValExpr = MakeFullExpr(ValExpr).get();
  14735. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  14736. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  14737. HelperValStmt = buildPreInits(Context, Captures);
  14738. }
  14739. }
  14740. }
  14741. return new (Context)
  14742. OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
  14743. Kind, ValExpr, HelperValStmt);
  14744. }
  14745. OMPClause *Sema::ActOnOpenMPDefaultmapClause(
  14746. OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
  14747. SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
  14748. SourceLocation KindLoc, SourceLocation EndLoc) {
  14749. // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)'
  14750. if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || Kind != OMPC_DEFAULTMAP_scalar) {
  14751. std::string Value;
  14752. SourceLocation Loc;
  14753. Value += "'";
  14754. if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
  14755. Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
  14756. OMPC_DEFAULTMAP_MODIFIER_tofrom);
  14757. Loc = MLoc;
  14758. } else {
  14759. Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
  14760. OMPC_DEFAULTMAP_scalar);
  14761. Loc = KindLoc;
  14762. }
  14763. Value += "'";
  14764. Diag(Loc, diag::err_omp_unexpected_clause_value)
  14765. << Value << getOpenMPClauseName(OMPC_defaultmap);
  14766. return nullptr;
  14767. }
  14768. DSAStack->setDefaultDMAToFromScalar(StartLoc);
  14769. return new (Context)
  14770. OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
  14771. }
  14772. bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) {
  14773. DeclContext *CurLexicalContext = getCurLexicalContext();
  14774. if (!CurLexicalContext->isFileContext() &&
  14775. !CurLexicalContext->isExternCContext() &&
  14776. !CurLexicalContext->isExternCXXContext() &&
  14777. !isa<CXXRecordDecl>(CurLexicalContext) &&
  14778. !isa<ClassTemplateDecl>(CurLexicalContext) &&
  14779. !isa<ClassTemplatePartialSpecializationDecl>(CurLexicalContext) &&
  14780. !isa<ClassTemplateSpecializationDecl>(CurLexicalContext)) {
  14781. Diag(Loc, diag::err_omp_region_not_file_context);
  14782. return false;
  14783. }
  14784. ++DeclareTargetNestingLevel;
  14785. return true;
  14786. }
  14787. void Sema::ActOnFinishOpenMPDeclareTargetDirective() {
  14788. assert(DeclareTargetNestingLevel > 0 &&
  14789. "Unexpected ActOnFinishOpenMPDeclareTargetDirective");
  14790. --DeclareTargetNestingLevel;
  14791. }
  14792. NamedDecl *
  14793. Sema::lookupOpenMPDeclareTargetName(Scope *CurScope, CXXScopeSpec &ScopeSpec,
  14794. const DeclarationNameInfo &Id,
  14795. NamedDeclSetType &SameDirectiveDecls) {
  14796. LookupResult Lookup(*this, Id, LookupOrdinaryName);
  14797. LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
  14798. if (Lookup.isAmbiguous())
  14799. return nullptr;
  14800. Lookup.suppressDiagnostics();
  14801. if (!Lookup.isSingleResult()) {
  14802. VarOrFuncDeclFilterCCC CCC(*this);
  14803. if (TypoCorrection Corrected =
  14804. CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, CCC,
  14805. CTK_ErrorRecovery)) {
  14806. diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
  14807. << Id.getName());
  14808. checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
  14809. return nullptr;
  14810. }
  14811. Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
  14812. return nullptr;
  14813. }
  14814. NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
  14815. if (!isa<VarDecl>(ND) && !isa<FunctionDecl>(ND) &&
  14816. !isa<FunctionTemplateDecl>(ND)) {
  14817. Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
  14818. return nullptr;
  14819. }
  14820. if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl())))
  14821. Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName();
  14822. return ND;
  14823. }
  14824. void Sema::ActOnOpenMPDeclareTargetName(
  14825. NamedDecl *ND, SourceLocation Loc, OMPDeclareTargetDeclAttr::MapTypeTy MT,
  14826. OMPDeclareTargetDeclAttr::DevTypeTy DT) {
  14827. assert((isa<VarDecl>(ND) || isa<FunctionDecl>(ND) ||
  14828. isa<FunctionTemplateDecl>(ND)) &&
  14829. "Expected variable, function or function template.");
  14830. // Diagnose marking after use as it may lead to incorrect diagnosis and
  14831. // codegen.
  14832. if (LangOpts.OpenMP >= 50 &&
  14833. (ND->isUsed(/*CheckUsedAttr=*/false) || ND->isReferenced()))
  14834. Diag(Loc, diag::warn_omp_declare_target_after_first_use);
  14835. Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
  14836. OMPDeclareTargetDeclAttr::getDeviceType(cast<ValueDecl>(ND));
  14837. if (DevTy.hasValue() && *DevTy != DT) {
  14838. Diag(Loc, diag::err_omp_device_type_mismatch)
  14839. << OMPDeclareTargetDeclAttr::ConvertDevTypeTyToStr(DT)
  14840. << OMPDeclareTargetDeclAttr::ConvertDevTypeTyToStr(*DevTy);
  14841. return;
  14842. }
  14843. Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
  14844. OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(cast<ValueDecl>(ND));
  14845. if (!Res) {
  14846. auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT, DT,
  14847. SourceRange(Loc, Loc));
  14848. ND->addAttr(A);
  14849. if (ASTMutationListener *ML = Context.getASTMutationListener())
  14850. ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
  14851. checkDeclIsAllowedInOpenMPTarget(nullptr, ND, Loc);
  14852. } else if (*Res != MT) {
  14853. Diag(Loc, diag::err_omp_declare_target_to_and_link) << ND;
  14854. }
  14855. }
  14856. static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
  14857. Sema &SemaRef, Decl *D) {
  14858. if (!D || !isa<VarDecl>(D))
  14859. return;
  14860. auto *VD = cast<VarDecl>(D);
  14861. Optional<OMPDeclareTargetDeclAttr::MapTypeTy> MapTy =
  14862. OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
  14863. if (SemaRef.LangOpts.OpenMP >= 50 &&
  14864. (SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true) ||
  14865. SemaRef.getCurBlock() || SemaRef.getCurCapturedRegion()) &&
  14866. VD->hasGlobalStorage()) {
  14867. llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> MapTy =
  14868. OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
  14869. if (!MapTy || *MapTy != OMPDeclareTargetDeclAttr::MT_To) {
  14870. // OpenMP 5.0, 2.12.7 declare target Directive, Restrictions
  14871. // If a lambda declaration and definition appears between a
  14872. // declare target directive and the matching end declare target
  14873. // directive, all variables that are captured by the lambda
  14874. // expression must also appear in a to clause.
  14875. SemaRef.Diag(VD->getLocation(),
  14876. diag::err_omp_lambda_capture_in_declare_target_not_to);
  14877. SemaRef.Diag(SL, diag::note_var_explicitly_captured_here)
  14878. << VD << 0 << SR;
  14879. return;
  14880. }
  14881. }
  14882. if (MapTy.hasValue())
  14883. return;
  14884. SemaRef.Diag(VD->getLocation(), diag::warn_omp_not_in_target_context);
  14885. SemaRef.Diag(SL, diag::note_used_here) << SR;
  14886. }
  14887. static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
  14888. Sema &SemaRef, DSAStackTy *Stack,
  14889. ValueDecl *VD) {
  14890. return OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD) ||
  14891. checkTypeMappable(SL, SR, SemaRef, Stack, VD->getType(),
  14892. /*FullCheck=*/false);
  14893. }
  14894. void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D,
  14895. SourceLocation IdLoc) {
  14896. if (!D || D->isInvalidDecl())
  14897. return;
  14898. SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
  14899. SourceLocation SL = E ? E->getBeginLoc() : D->getLocation();
  14900. if (auto *VD = dyn_cast<VarDecl>(D)) {
  14901. // Only global variables can be marked as declare target.
  14902. if (!VD->isFileVarDecl() && !VD->isStaticLocal() &&
  14903. !VD->isStaticDataMember())
  14904. return;
  14905. // 2.10.6: threadprivate variable cannot appear in a declare target
  14906. // directive.
  14907. if (DSAStack->isThreadPrivate(VD)) {
  14908. Diag(SL, diag::err_omp_threadprivate_in_target);
  14909. reportOriginalDsa(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
  14910. return;
  14911. }
  14912. }
  14913. if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(D))
  14914. D = FTD->getTemplatedDecl();
  14915. if (auto *FD = dyn_cast<FunctionDecl>(D)) {
  14916. llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
  14917. OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(FD);
  14918. if (IdLoc.isValid() && Res && *Res == OMPDeclareTargetDeclAttr::MT_Link) {
  14919. Diag(IdLoc, diag::err_omp_function_in_link_clause);
  14920. Diag(FD->getLocation(), diag::note_defined_here) << FD;
  14921. return;
  14922. }
  14923. // Mark the function as must be emitted for the device.
  14924. Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
  14925. OMPDeclareTargetDeclAttr::getDeviceType(FD);
  14926. if (LangOpts.OpenMPIsDevice && Res.hasValue() && IdLoc.isValid() &&
  14927. *DevTy != OMPDeclareTargetDeclAttr::DT_Host)
  14928. checkOpenMPDeviceFunction(IdLoc, FD, /*CheckForDelayedContext=*/false);
  14929. if (!LangOpts.OpenMPIsDevice && Res.hasValue() && IdLoc.isValid() &&
  14930. *DevTy != OMPDeclareTargetDeclAttr::DT_NoHost)
  14931. checkOpenMPHostFunction(IdLoc, FD, /*CheckCaller=*/false);
  14932. }
  14933. if (auto *VD = dyn_cast<ValueDecl>(D)) {
  14934. // Problem if any with var declared with incomplete type will be reported
  14935. // as normal, so no need to check it here.
  14936. if ((E || !VD->getType()->isIncompleteType()) &&
  14937. !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD))
  14938. return;
  14939. if (!E && !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
  14940. // Checking declaration inside declare target region.
  14941. if (isa<VarDecl>(D) || isa<FunctionDecl>(D) ||
  14942. isa<FunctionTemplateDecl>(D)) {
  14943. auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(
  14944. Context, OMPDeclareTargetDeclAttr::MT_To,
  14945. OMPDeclareTargetDeclAttr::DT_Any, SourceRange(IdLoc, IdLoc));
  14946. D->addAttr(A);
  14947. if (ASTMutationListener *ML = Context.getASTMutationListener())
  14948. ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
  14949. }
  14950. return;
  14951. }
  14952. }
  14953. if (!E)
  14954. return;
  14955. checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
  14956. }
  14957. OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
  14958. CXXScopeSpec &MapperIdScopeSpec,
  14959. DeclarationNameInfo &MapperId,
  14960. const OMPVarListLocTy &Locs,
  14961. ArrayRef<Expr *> UnresolvedMappers) {
  14962. MappableVarListInfo MVLI(VarList);
  14963. checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, Locs.StartLoc,
  14964. MapperIdScopeSpec, MapperId, UnresolvedMappers);
  14965. if (MVLI.ProcessedVarList.empty())
  14966. return nullptr;
  14967. return OMPToClause::Create(
  14968. Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
  14969. MVLI.VarComponents, MVLI.UDMapperList,
  14970. MapperIdScopeSpec.getWithLocInContext(Context), MapperId);
  14971. }
  14972. OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
  14973. CXXScopeSpec &MapperIdScopeSpec,
  14974. DeclarationNameInfo &MapperId,
  14975. const OMPVarListLocTy &Locs,
  14976. ArrayRef<Expr *> UnresolvedMappers) {
  14977. MappableVarListInfo MVLI(VarList);
  14978. checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, Locs.StartLoc,
  14979. MapperIdScopeSpec, MapperId, UnresolvedMappers);
  14980. if (MVLI.ProcessedVarList.empty())
  14981. return nullptr;
  14982. return OMPFromClause::Create(
  14983. Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
  14984. MVLI.VarComponents, MVLI.UDMapperList,
  14985. MapperIdScopeSpec.getWithLocInContext(Context), MapperId);
  14986. }
  14987. OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
  14988. const OMPVarListLocTy &Locs) {
  14989. MappableVarListInfo MVLI(VarList);
  14990. SmallVector<Expr *, 8> PrivateCopies;
  14991. SmallVector<Expr *, 8> Inits;
  14992. for (Expr *RefExpr : VarList) {
  14993. assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
  14994. SourceLocation ELoc;
  14995. SourceRange ERange;
  14996. Expr *SimpleRefExpr = RefExpr;
  14997. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  14998. if (Res.second) {
  14999. // It will be analyzed later.
  15000. MVLI.ProcessedVarList.push_back(RefExpr);
  15001. PrivateCopies.push_back(nullptr);
  15002. Inits.push_back(nullptr);
  15003. }
  15004. ValueDecl *D = Res.first;
  15005. if (!D)
  15006. continue;
  15007. QualType Type = D->getType();
  15008. Type = Type.getNonReferenceType().getUnqualifiedType();
  15009. auto *VD = dyn_cast<VarDecl>(D);
  15010. // Item should be a pointer or reference to pointer.
  15011. if (!Type->isPointerType()) {
  15012. Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
  15013. << 0 << RefExpr->getSourceRange();
  15014. continue;
  15015. }
  15016. // Build the private variable and the expression that refers to it.
  15017. auto VDPrivate =
  15018. buildVarDecl(*this, ELoc, Type, D->getName(),
  15019. D->hasAttrs() ? &D->getAttrs() : nullptr,
  15020. VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
  15021. if (VDPrivate->isInvalidDecl())
  15022. continue;
  15023. CurContext->addDecl(VDPrivate);
  15024. DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
  15025. *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
  15026. // Add temporary variable to initialize the private copy of the pointer.
  15027. VarDecl *VDInit =
  15028. buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
  15029. DeclRefExpr *VDInitRefExpr = buildDeclRefExpr(
  15030. *this, VDInit, RefExpr->getType(), RefExpr->getExprLoc());
  15031. AddInitializerToDecl(VDPrivate,
  15032. DefaultLvalueConversion(VDInitRefExpr).get(),
  15033. /*DirectInit=*/false);
  15034. // If required, build a capture to implement the privatization initialized
  15035. // with the current list item value.
  15036. DeclRefExpr *Ref = nullptr;
  15037. if (!VD)
  15038. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
  15039. MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
  15040. PrivateCopies.push_back(VDPrivateRefExpr);
  15041. Inits.push_back(VDInitRefExpr);
  15042. // We need to add a data sharing attribute for this variable to make sure it
  15043. // is correctly captured. A variable that shows up in a use_device_ptr has
  15044. // similar properties of a first private variable.
  15045. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
  15046. // Create a mappable component for the list item. List items in this clause
  15047. // only need a component.
  15048. MVLI.VarBaseDeclarations.push_back(D);
  15049. MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
  15050. MVLI.VarComponents.back().push_back(
  15051. OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D));
  15052. }
  15053. if (MVLI.ProcessedVarList.empty())
  15054. return nullptr;
  15055. return OMPUseDevicePtrClause::Create(
  15056. Context, Locs, MVLI.ProcessedVarList, PrivateCopies, Inits,
  15057. MVLI.VarBaseDeclarations, MVLI.VarComponents);
  15058. }
  15059. OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
  15060. const OMPVarListLocTy &Locs) {
  15061. MappableVarListInfo MVLI(VarList);
  15062. for (Expr *RefExpr : VarList) {
  15063. assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
  15064. SourceLocation ELoc;
  15065. SourceRange ERange;
  15066. Expr *SimpleRefExpr = RefExpr;
  15067. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  15068. if (Res.second) {
  15069. // It will be analyzed later.
  15070. MVLI.ProcessedVarList.push_back(RefExpr);
  15071. }
  15072. ValueDecl *D = Res.first;
  15073. if (!D)
  15074. continue;
  15075. QualType Type = D->getType();
  15076. // item should be a pointer or array or reference to pointer or array
  15077. if (!Type.getNonReferenceType()->isPointerType() &&
  15078. !Type.getNonReferenceType()->isArrayType()) {
  15079. Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
  15080. << 0 << RefExpr->getSourceRange();
  15081. continue;
  15082. }
  15083. // Check if the declaration in the clause does not show up in any data
  15084. // sharing attribute.
  15085. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
  15086. if (isOpenMPPrivate(DVar.CKind)) {
  15087. Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
  15088. << getOpenMPClauseName(DVar.CKind)
  15089. << getOpenMPClauseName(OMPC_is_device_ptr)
  15090. << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
  15091. reportOriginalDsa(*this, DSAStack, D, DVar);
  15092. continue;
  15093. }
  15094. const Expr *ConflictExpr;
  15095. if (DSAStack->checkMappableExprComponentListsForDecl(
  15096. D, /*CurrentRegionOnly=*/true,
  15097. [&ConflictExpr](
  15098. OMPClauseMappableExprCommon::MappableExprComponentListRef R,
  15099. OpenMPClauseKind) -> bool {
  15100. ConflictExpr = R.front().getAssociatedExpression();
  15101. return true;
  15102. })) {
  15103. Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
  15104. Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
  15105. << ConflictExpr->getSourceRange();
  15106. continue;
  15107. }
  15108. // Store the components in the stack so that they can be used to check
  15109. // against other clauses later on.
  15110. OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D);
  15111. DSAStack->addMappableExpressionComponents(
  15112. D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
  15113. // Record the expression we've just processed.
  15114. MVLI.ProcessedVarList.push_back(SimpleRefExpr);
  15115. // Create a mappable component for the list item. List items in this clause
  15116. // only need a component. We use a null declaration to signal fields in
  15117. // 'this'.
  15118. assert((isa<DeclRefExpr>(SimpleRefExpr) ||
  15119. isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
  15120. "Unexpected device pointer expression!");
  15121. MVLI.VarBaseDeclarations.push_back(
  15122. isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
  15123. MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
  15124. MVLI.VarComponents.back().push_back(MC);
  15125. }
  15126. if (MVLI.ProcessedVarList.empty())
  15127. return nullptr;
  15128. return OMPIsDevicePtrClause::Create(Context, Locs, MVLI.ProcessedVarList,
  15129. MVLI.VarBaseDeclarations,
  15130. MVLI.VarComponents);
  15131. }
  15132. OMPClause *Sema::ActOnOpenMPAllocateClause(
  15133. Expr *Allocator, ArrayRef<Expr *> VarList, SourceLocation StartLoc,
  15134. SourceLocation ColonLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
  15135. if (Allocator) {
  15136. // OpenMP [2.11.4 allocate Clause, Description]
  15137. // allocator is an expression of omp_allocator_handle_t type.
  15138. if (!findOMPAllocatorHandleT(*this, Allocator->getExprLoc(), DSAStack))
  15139. return nullptr;
  15140. ExprResult AllocatorRes = DefaultLvalueConversion(Allocator);
  15141. if (AllocatorRes.isInvalid())
  15142. return nullptr;
  15143. AllocatorRes = PerformImplicitConversion(AllocatorRes.get(),
  15144. DSAStack->getOMPAllocatorHandleT(),
  15145. Sema::AA_Initializing,
  15146. /*AllowExplicit=*/true);
  15147. if (AllocatorRes.isInvalid())
  15148. return nullptr;
  15149. Allocator = AllocatorRes.get();
  15150. } else {
  15151. // OpenMP 5.0, 2.11.4 allocate Clause, Restrictions.
  15152. // allocate clauses that appear on a target construct or on constructs in a
  15153. // target region must specify an allocator expression unless a requires
  15154. // directive with the dynamic_allocators clause is present in the same
  15155. // compilation unit.
  15156. if (LangOpts.OpenMPIsDevice &&
  15157. !DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())
  15158. targetDiag(StartLoc, diag::err_expected_allocator_expression);
  15159. }
  15160. // Analyze and build list of variables.
  15161. SmallVector<Expr *, 8> Vars;
  15162. for (Expr *RefExpr : VarList) {
  15163. assert(RefExpr && "NULL expr in OpenMP private clause.");
  15164. SourceLocation ELoc;
  15165. SourceRange ERange;
  15166. Expr *SimpleRefExpr = RefExpr;
  15167. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  15168. if (Res.second) {
  15169. // It will be analyzed later.
  15170. Vars.push_back(RefExpr);
  15171. }
  15172. ValueDecl *D = Res.first;
  15173. if (!D)
  15174. continue;
  15175. auto *VD = dyn_cast<VarDecl>(D);
  15176. DeclRefExpr *Ref = nullptr;
  15177. if (!VD && !CurContext->isDependentContext())
  15178. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
  15179. Vars.push_back((VD || CurContext->isDependentContext())
  15180. ? RefExpr->IgnoreParens()
  15181. : Ref);
  15182. }
  15183. if (Vars.empty())
  15184. return nullptr;
  15185. return OMPAllocateClause::Create(Context, StartLoc, LParenLoc, Allocator,
  15186. ColonLoc, EndLoc, Vars);
  15187. }