SemaOpenMP.cpp 644 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254
  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. Sema::DeviceDiagBuilder Sema::diagIfOpenMPDeviceCode(SourceLocation Loc,
  1453. unsigned DiagID) {
  1454. assert(LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
  1455. "Expected OpenMP device compilation.");
  1456. FunctionEmissionStatus FES = getEmissionStatus(getCurFunctionDecl());
  1457. DeviceDiagBuilder::Kind Kind = DeviceDiagBuilder::K_Nop;
  1458. switch (FES) {
  1459. case FunctionEmissionStatus::Emitted:
  1460. Kind = DeviceDiagBuilder::K_Immediate;
  1461. break;
  1462. case FunctionEmissionStatus::Unknown:
  1463. Kind = isOpenMPDeviceDelayedContext(*this) ? DeviceDiagBuilder::K_Deferred
  1464. : DeviceDiagBuilder::K_Immediate;
  1465. break;
  1466. case FunctionEmissionStatus::TemplateDiscarded:
  1467. case FunctionEmissionStatus::OMPDiscarded:
  1468. Kind = DeviceDiagBuilder::K_Nop;
  1469. break;
  1470. case FunctionEmissionStatus::CUDADiscarded:
  1471. llvm_unreachable("CUDADiscarded unexpected in OpenMP device compilation");
  1472. break;
  1473. }
  1474. return DeviceDiagBuilder(Kind, Loc, DiagID, getCurFunctionDecl(), *this);
  1475. }
  1476. Sema::DeviceDiagBuilder Sema::diagIfOpenMPHostCode(SourceLocation Loc,
  1477. unsigned DiagID) {
  1478. assert(LangOpts.OpenMP && !LangOpts.OpenMPIsDevice &&
  1479. "Expected OpenMP host compilation.");
  1480. FunctionEmissionStatus FES = getEmissionStatus(getCurFunctionDecl());
  1481. DeviceDiagBuilder::Kind Kind = DeviceDiagBuilder::K_Nop;
  1482. switch (FES) {
  1483. case FunctionEmissionStatus::Emitted:
  1484. Kind = DeviceDiagBuilder::K_Immediate;
  1485. break;
  1486. case FunctionEmissionStatus::Unknown:
  1487. Kind = DeviceDiagBuilder::K_Deferred;
  1488. break;
  1489. case FunctionEmissionStatus::TemplateDiscarded:
  1490. case FunctionEmissionStatus::OMPDiscarded:
  1491. case FunctionEmissionStatus::CUDADiscarded:
  1492. Kind = DeviceDiagBuilder::K_Nop;
  1493. break;
  1494. }
  1495. return DeviceDiagBuilder(Kind, Loc, DiagID, getCurFunctionDecl(), *this);
  1496. }
  1497. void Sema::checkOpenMPDeviceFunction(SourceLocation Loc, FunctionDecl *Callee,
  1498. bool CheckForDelayedContext) {
  1499. assert(LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
  1500. "Expected OpenMP device compilation.");
  1501. assert(Callee && "Callee may not be null.");
  1502. Callee = Callee->getMostRecentDecl();
  1503. FunctionDecl *Caller = getCurFunctionDecl();
  1504. // host only function are not available on the device.
  1505. if (Caller) {
  1506. FunctionEmissionStatus CallerS = getEmissionStatus(Caller);
  1507. FunctionEmissionStatus CalleeS = getEmissionStatus(Callee);
  1508. assert(CallerS != FunctionEmissionStatus::CUDADiscarded &&
  1509. CalleeS != FunctionEmissionStatus::CUDADiscarded &&
  1510. "CUDADiscarded unexpected in OpenMP device function check");
  1511. if ((CallerS == FunctionEmissionStatus::Emitted ||
  1512. (!isOpenMPDeviceDelayedContext(*this) &&
  1513. CallerS == FunctionEmissionStatus::Unknown)) &&
  1514. CalleeS == FunctionEmissionStatus::OMPDiscarded) {
  1515. StringRef HostDevTy = getOpenMPSimpleClauseTypeName(
  1516. OMPC_device_type, OMPC_DEVICE_TYPE_host);
  1517. Diag(Loc, diag::err_omp_wrong_device_function_call) << HostDevTy << 0;
  1518. Diag(Callee->getAttr<OMPDeclareTargetDeclAttr>()->getLocation(),
  1519. diag::note_omp_marked_device_type_here)
  1520. << HostDevTy;
  1521. return;
  1522. }
  1523. }
  1524. // If the caller is known-emitted, mark the callee as known-emitted.
  1525. // Otherwise, mark the call in our call graph so we can traverse it later.
  1526. if ((CheckForDelayedContext && !isOpenMPDeviceDelayedContext(*this)) ||
  1527. (!Caller && !CheckForDelayedContext) ||
  1528. (Caller && getEmissionStatus(Caller) == FunctionEmissionStatus::Emitted))
  1529. markKnownEmitted(*this, Caller, Callee, Loc,
  1530. [CheckForDelayedContext](Sema &S, FunctionDecl *FD) {
  1531. return CheckForDelayedContext &&
  1532. S.getEmissionStatus(FD) ==
  1533. FunctionEmissionStatus::Emitted;
  1534. });
  1535. else if (Caller)
  1536. DeviceCallGraph[Caller].insert({Callee, Loc});
  1537. }
  1538. void Sema::checkOpenMPHostFunction(SourceLocation Loc, FunctionDecl *Callee,
  1539. bool CheckCaller) {
  1540. assert(LangOpts.OpenMP && !LangOpts.OpenMPIsDevice &&
  1541. "Expected OpenMP host compilation.");
  1542. assert(Callee && "Callee may not be null.");
  1543. Callee = Callee->getMostRecentDecl();
  1544. FunctionDecl *Caller = getCurFunctionDecl();
  1545. // device only function are not available on the host.
  1546. if (Caller) {
  1547. FunctionEmissionStatus CallerS = getEmissionStatus(Caller);
  1548. FunctionEmissionStatus CalleeS = getEmissionStatus(Callee);
  1549. assert(
  1550. (LangOpts.CUDA || (CallerS != FunctionEmissionStatus::CUDADiscarded &&
  1551. CalleeS != FunctionEmissionStatus::CUDADiscarded)) &&
  1552. "CUDADiscarded unexpected in OpenMP host function check");
  1553. if (CallerS == FunctionEmissionStatus::Emitted &&
  1554. CalleeS == FunctionEmissionStatus::OMPDiscarded) {
  1555. StringRef NoHostDevTy = getOpenMPSimpleClauseTypeName(
  1556. OMPC_device_type, OMPC_DEVICE_TYPE_nohost);
  1557. Diag(Loc, diag::err_omp_wrong_device_function_call) << NoHostDevTy << 1;
  1558. Diag(Callee->getAttr<OMPDeclareTargetDeclAttr>()->getLocation(),
  1559. diag::note_omp_marked_device_type_here)
  1560. << NoHostDevTy;
  1561. return;
  1562. }
  1563. }
  1564. // If the caller is known-emitted, mark the callee as known-emitted.
  1565. // Otherwise, mark the call in our call graph so we can traverse it later.
  1566. if (!shouldIgnoreInHostDeviceCheck(Callee)) {
  1567. if ((!CheckCaller && !Caller) ||
  1568. (Caller &&
  1569. getEmissionStatus(Caller) == FunctionEmissionStatus::Emitted))
  1570. markKnownEmitted(
  1571. *this, Caller, Callee, Loc, [CheckCaller](Sema &S, FunctionDecl *FD) {
  1572. return CheckCaller &&
  1573. S.getEmissionStatus(FD) == FunctionEmissionStatus::Emitted;
  1574. });
  1575. else if (Caller)
  1576. DeviceCallGraph[Caller].insert({Callee, Loc});
  1577. }
  1578. }
  1579. void Sema::checkOpenMPDeviceExpr(const Expr *E) {
  1580. assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
  1581. "OpenMP device compilation mode is expected.");
  1582. QualType Ty = E->getType();
  1583. if ((Ty->isFloat16Type() && !Context.getTargetInfo().hasFloat16Type()) ||
  1584. ((Ty->isFloat128Type() ||
  1585. (Ty->isRealFloatingType() && Context.getTypeSize(Ty) == 128)) &&
  1586. !Context.getTargetInfo().hasFloat128Type()) ||
  1587. (Ty->isIntegerType() && Context.getTypeSize(Ty) == 128 &&
  1588. !Context.getTargetInfo().hasInt128Type()))
  1589. targetDiag(E->getExprLoc(), diag::err_omp_unsupported_type)
  1590. << static_cast<unsigned>(Context.getTypeSize(Ty)) << Ty
  1591. << Context.getTargetInfo().getTriple().str() << E->getSourceRange();
  1592. }
  1593. bool Sema::isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level,
  1594. unsigned OpenMPCaptureLevel) const {
  1595. assert(LangOpts.OpenMP && "OpenMP is not allowed");
  1596. ASTContext &Ctx = getASTContext();
  1597. bool IsByRef = true;
  1598. // Find the directive that is associated with the provided scope.
  1599. D = cast<ValueDecl>(D->getCanonicalDecl());
  1600. QualType Ty = D->getType();
  1601. bool IsVariableUsedInMapClause = false;
  1602. if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) {
  1603. // This table summarizes how a given variable should be passed to the device
  1604. // given its type and the clauses where it appears. This table is based on
  1605. // the description in OpenMP 4.5 [2.10.4, target Construct] and
  1606. // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses].
  1607. //
  1608. // =========================================================================
  1609. // | type | defaultmap | pvt | first | is_device_ptr | map | res. |
  1610. // | |(tofrom:scalar)| | pvt | | | |
  1611. // =========================================================================
  1612. // | scl | | | | - | | bycopy|
  1613. // | scl | | - | x | - | - | bycopy|
  1614. // | scl | | x | - | - | - | null |
  1615. // | scl | x | | | - | | byref |
  1616. // | scl | x | - | x | - | - | bycopy|
  1617. // | scl | x | x | - | - | - | null |
  1618. // | scl | | - | - | - | x | byref |
  1619. // | scl | x | - | - | - | x | byref |
  1620. //
  1621. // | agg | n.a. | | | - | | byref |
  1622. // | agg | n.a. | - | x | - | - | byref |
  1623. // | agg | n.a. | x | - | - | - | null |
  1624. // | agg | n.a. | - | - | - | x | byref |
  1625. // | agg | n.a. | - | - | - | x[] | byref |
  1626. //
  1627. // | ptr | n.a. | | | - | | bycopy|
  1628. // | ptr | n.a. | - | x | - | - | bycopy|
  1629. // | ptr | n.a. | x | - | - | - | null |
  1630. // | ptr | n.a. | - | - | - | x | byref |
  1631. // | ptr | n.a. | - | - | - | x[] | bycopy|
  1632. // | ptr | n.a. | - | - | x | | bycopy|
  1633. // | ptr | n.a. | - | - | x | x | bycopy|
  1634. // | ptr | n.a. | - | - | x | x[] | bycopy|
  1635. // =========================================================================
  1636. // Legend:
  1637. // scl - scalar
  1638. // ptr - pointer
  1639. // agg - aggregate
  1640. // x - applies
  1641. // - - invalid in this combination
  1642. // [] - mapped with an array section
  1643. // byref - should be mapped by reference
  1644. // byval - should be mapped by value
  1645. // null - initialize a local variable to null on the device
  1646. //
  1647. // Observations:
  1648. // - All scalar declarations that show up in a map clause have to be passed
  1649. // by reference, because they may have been mapped in the enclosing data
  1650. // environment.
  1651. // - If the scalar value does not fit the size of uintptr, it has to be
  1652. // passed by reference, regardless the result in the table above.
  1653. // - For pointers mapped by value that have either an implicit map or an
  1654. // array section, the runtime library may pass the NULL value to the
  1655. // device instead of the value passed to it by the compiler.
  1656. if (Ty->isReferenceType())
  1657. Ty = Ty->castAs<ReferenceType>()->getPointeeType();
  1658. // Locate map clauses and see if the variable being captured is referred to
  1659. // in any of those clauses. Here we only care about variables, not fields,
  1660. // because fields are part of aggregates.
  1661. bool IsVariableAssociatedWithSection = false;
  1662. DSAStack->checkMappableExprComponentListsForDeclAtLevel(
  1663. D, Level,
  1664. [&IsVariableUsedInMapClause, &IsVariableAssociatedWithSection, D](
  1665. OMPClauseMappableExprCommon::MappableExprComponentListRef
  1666. MapExprComponents,
  1667. OpenMPClauseKind WhereFoundClauseKind) {
  1668. // Only the map clause information influences how a variable is
  1669. // captured. E.g. is_device_ptr does not require changing the default
  1670. // behavior.
  1671. if (WhereFoundClauseKind != OMPC_map)
  1672. return false;
  1673. auto EI = MapExprComponents.rbegin();
  1674. auto EE = MapExprComponents.rend();
  1675. assert(EI != EE && "Invalid map expression!");
  1676. if (isa<DeclRefExpr>(EI->getAssociatedExpression()))
  1677. IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D;
  1678. ++EI;
  1679. if (EI == EE)
  1680. return false;
  1681. if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) ||
  1682. isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) ||
  1683. isa<MemberExpr>(EI->getAssociatedExpression())) {
  1684. IsVariableAssociatedWithSection = true;
  1685. // There is nothing more we need to know about this variable.
  1686. return true;
  1687. }
  1688. // Keep looking for more map info.
  1689. return false;
  1690. });
  1691. if (IsVariableUsedInMapClause) {
  1692. // If variable is identified in a map clause it is always captured by
  1693. // reference except if it is a pointer that is dereferenced somehow.
  1694. IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection);
  1695. } else {
  1696. // By default, all the data that has a scalar type is mapped by copy
  1697. // (except for reduction variables).
  1698. IsByRef =
  1699. (DSAStack->isForceCaptureByReferenceInTargetExecutable() &&
  1700. !Ty->isAnyPointerType()) ||
  1701. !Ty->isScalarType() ||
  1702. DSAStack->getDefaultDMAAtLevel(Level) == DMA_tofrom_scalar ||
  1703. DSAStack->hasExplicitDSA(
  1704. D, [](OpenMPClauseKind K) { return K == OMPC_reduction; }, Level);
  1705. }
  1706. }
  1707. if (IsByRef && Ty.getNonReferenceType()->isScalarType()) {
  1708. IsByRef =
  1709. ((IsVariableUsedInMapClause &&
  1710. DSAStack->getCaptureRegion(Level, OpenMPCaptureLevel) ==
  1711. OMPD_target) ||
  1712. !DSAStack->hasExplicitDSA(
  1713. D,
  1714. [](OpenMPClauseKind K) -> bool { return K == OMPC_firstprivate; },
  1715. Level, /*NotLastprivate=*/true)) &&
  1716. // If the variable is artificial and must be captured by value - try to
  1717. // capture by value.
  1718. !(isa<OMPCapturedExprDecl>(D) && !D->hasAttr<OMPCaptureNoInitAttr>() &&
  1719. !cast<OMPCapturedExprDecl>(D)->getInit()->isGLValue());
  1720. }
  1721. // When passing data by copy, we need to make sure it fits the uintptr size
  1722. // and alignment, because the runtime library only deals with uintptr types.
  1723. // If it does not fit the uintptr size, we need to pass the data by reference
  1724. // instead.
  1725. if (!IsByRef &&
  1726. (Ctx.getTypeSizeInChars(Ty) >
  1727. Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) ||
  1728. Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) {
  1729. IsByRef = true;
  1730. }
  1731. return IsByRef;
  1732. }
  1733. unsigned Sema::getOpenMPNestingLevel() const {
  1734. assert(getLangOpts().OpenMP);
  1735. return DSAStack->getNestingLevel();
  1736. }
  1737. bool Sema::isInOpenMPTargetExecutionDirective() const {
  1738. return (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) &&
  1739. !DSAStack->isClauseParsingMode()) ||
  1740. DSAStack->hasDirective(
  1741. [](OpenMPDirectiveKind K, const DeclarationNameInfo &,
  1742. SourceLocation) -> bool {
  1743. return isOpenMPTargetExecutionDirective(K);
  1744. },
  1745. false);
  1746. }
  1747. VarDecl *Sema::isOpenMPCapturedDecl(ValueDecl *D, bool CheckScopeInfo,
  1748. unsigned StopAt) {
  1749. assert(LangOpts.OpenMP && "OpenMP is not allowed");
  1750. D = getCanonicalDecl(D);
  1751. // If we want to determine whether the variable should be captured from the
  1752. // perspective of the current capturing scope, and we've already left all the
  1753. // capturing scopes of the top directive on the stack, check from the
  1754. // perspective of its parent directive (if any) instead.
  1755. DSAStackTy::ParentDirectiveScope InParentDirectiveRAII(
  1756. *DSAStack, CheckScopeInfo && DSAStack->isBodyComplete());
  1757. // If we are attempting to capture a global variable in a directive with
  1758. // 'target' we return true so that this global is also mapped to the device.
  1759. //
  1760. auto *VD = dyn_cast<VarDecl>(D);
  1761. if (VD && !VD->hasLocalStorage() &&
  1762. (getCurCapturedRegion() || getCurBlock() || getCurLambda())) {
  1763. if (isInOpenMPDeclareTargetContext()) {
  1764. // Try to mark variable as declare target if it is used in capturing
  1765. // regions.
  1766. if (LangOpts.OpenMP <= 45 &&
  1767. !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
  1768. checkDeclIsAllowedInOpenMPTarget(nullptr, VD);
  1769. return nullptr;
  1770. } else if (isInOpenMPTargetExecutionDirective()) {
  1771. // If the declaration is enclosed in a 'declare target' directive,
  1772. // then it should not be captured.
  1773. //
  1774. if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
  1775. return nullptr;
  1776. return VD;
  1777. }
  1778. }
  1779. if (CheckScopeInfo) {
  1780. bool OpenMPFound = false;
  1781. for (unsigned I = StopAt + 1; I > 0; --I) {
  1782. FunctionScopeInfo *FSI = FunctionScopes[I - 1];
  1783. if(!isa<CapturingScopeInfo>(FSI))
  1784. return nullptr;
  1785. if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(FSI))
  1786. if (RSI->CapRegionKind == CR_OpenMP) {
  1787. OpenMPFound = true;
  1788. break;
  1789. }
  1790. }
  1791. if (!OpenMPFound)
  1792. return nullptr;
  1793. }
  1794. if (DSAStack->getCurrentDirective() != OMPD_unknown &&
  1795. (!DSAStack->isClauseParsingMode() ||
  1796. DSAStack->getParentDirective() != OMPD_unknown)) {
  1797. auto &&Info = DSAStack->isLoopControlVariable(D);
  1798. if (Info.first ||
  1799. (VD && VD->hasLocalStorage() &&
  1800. isImplicitOrExplicitTaskingRegion(DSAStack->getCurrentDirective())) ||
  1801. (VD && DSAStack->isForceVarCapturing()))
  1802. return VD ? VD : Info.second;
  1803. DSAStackTy::DSAVarData DVarPrivate =
  1804. DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
  1805. if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
  1806. return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
  1807. // Threadprivate variables must not be captured.
  1808. if (isOpenMPThreadPrivate(DVarPrivate.CKind))
  1809. return nullptr;
  1810. // The variable is not private or it is the variable in the directive with
  1811. // default(none) clause and not used in any clause.
  1812. DVarPrivate = DSAStack->hasDSA(D, isOpenMPPrivate,
  1813. [](OpenMPDirectiveKind) { return true; },
  1814. DSAStack->isClauseParsingMode());
  1815. if (DVarPrivate.CKind != OMPC_unknown ||
  1816. (VD && DSAStack->getDefaultDSA() == DSA_none))
  1817. return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
  1818. }
  1819. return nullptr;
  1820. }
  1821. void Sema::adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex,
  1822. unsigned Level) const {
  1823. SmallVector<OpenMPDirectiveKind, 4> Regions;
  1824. getOpenMPCaptureRegions(Regions, DSAStack->getDirective(Level));
  1825. FunctionScopesIndex -= Regions.size();
  1826. }
  1827. void Sema::startOpenMPLoop() {
  1828. assert(LangOpts.OpenMP && "OpenMP must be enabled.");
  1829. if (isOpenMPLoopDirective(DSAStack->getCurrentDirective()))
  1830. DSAStack->loopInit();
  1831. }
  1832. void Sema::startOpenMPCXXRangeFor() {
  1833. assert(LangOpts.OpenMP && "OpenMP must be enabled.");
  1834. if (isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
  1835. DSAStack->resetPossibleLoopCounter();
  1836. DSAStack->loopStart();
  1837. }
  1838. }
  1839. bool Sema::isOpenMPPrivateDecl(const ValueDecl *D, unsigned Level) const {
  1840. assert(LangOpts.OpenMP && "OpenMP is not allowed");
  1841. if (isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
  1842. if (DSAStack->getAssociatedLoops() > 0 &&
  1843. !DSAStack->isLoopStarted()) {
  1844. DSAStack->resetPossibleLoopCounter(D);
  1845. DSAStack->loopStart();
  1846. return true;
  1847. }
  1848. if ((DSAStack->getPossiblyLoopCunter() == D->getCanonicalDecl() ||
  1849. DSAStack->isLoopControlVariable(D).first) &&
  1850. !DSAStack->hasExplicitDSA(
  1851. D, [](OpenMPClauseKind K) { return K != OMPC_private; }, Level) &&
  1852. !isOpenMPSimdDirective(DSAStack->getCurrentDirective()))
  1853. return true;
  1854. }
  1855. if (const auto *VD = dyn_cast<VarDecl>(D)) {
  1856. if (DSAStack->isThreadPrivate(const_cast<VarDecl *>(VD)) &&
  1857. DSAStack->isForceVarCapturing() &&
  1858. !DSAStack->hasExplicitDSA(
  1859. D, [](OpenMPClauseKind K) { return K == OMPC_copyin; }, Level))
  1860. return true;
  1861. }
  1862. return DSAStack->hasExplicitDSA(
  1863. D, [](OpenMPClauseKind K) { return K == OMPC_private; }, Level) ||
  1864. (DSAStack->isClauseParsingMode() &&
  1865. DSAStack->getClauseParsingMode() == OMPC_private) ||
  1866. // Consider taskgroup reduction descriptor variable a private to avoid
  1867. // possible capture in the region.
  1868. (DSAStack->hasExplicitDirective(
  1869. [](OpenMPDirectiveKind K) { return K == OMPD_taskgroup; },
  1870. Level) &&
  1871. DSAStack->isTaskgroupReductionRef(D, Level));
  1872. }
  1873. void Sema::setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D,
  1874. unsigned Level) {
  1875. assert(LangOpts.OpenMP && "OpenMP is not allowed");
  1876. D = getCanonicalDecl(D);
  1877. OpenMPClauseKind OMPC = OMPC_unknown;
  1878. for (unsigned I = DSAStack->getNestingLevel() + 1; I > Level; --I) {
  1879. const unsigned NewLevel = I - 1;
  1880. if (DSAStack->hasExplicitDSA(D,
  1881. [&OMPC](const OpenMPClauseKind K) {
  1882. if (isOpenMPPrivate(K)) {
  1883. OMPC = K;
  1884. return true;
  1885. }
  1886. return false;
  1887. },
  1888. NewLevel))
  1889. break;
  1890. if (DSAStack->checkMappableExprComponentListsForDeclAtLevel(
  1891. D, NewLevel,
  1892. [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
  1893. OpenMPClauseKind) { return true; })) {
  1894. OMPC = OMPC_map;
  1895. break;
  1896. }
  1897. if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
  1898. NewLevel)) {
  1899. OMPC = OMPC_map;
  1900. if (D->getType()->isScalarType() &&
  1901. DSAStack->getDefaultDMAAtLevel(NewLevel) !=
  1902. DefaultMapAttributes::DMA_tofrom_scalar)
  1903. OMPC = OMPC_firstprivate;
  1904. break;
  1905. }
  1906. }
  1907. if (OMPC != OMPC_unknown)
  1908. FD->addAttr(OMPCaptureKindAttr::CreateImplicit(Context, OMPC));
  1909. }
  1910. bool Sema::isOpenMPTargetCapturedDecl(const ValueDecl *D,
  1911. unsigned Level) const {
  1912. assert(LangOpts.OpenMP && "OpenMP is not allowed");
  1913. // Return true if the current level is no longer enclosed in a target region.
  1914. const auto *VD = dyn_cast<VarDecl>(D);
  1915. return VD && !VD->hasLocalStorage() &&
  1916. DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
  1917. Level);
  1918. }
  1919. void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
  1920. void Sema::finalizeOpenMPDelayedAnalysis() {
  1921. assert(LangOpts.OpenMP && "Expected OpenMP compilation mode.");
  1922. // Diagnose implicit declare target functions and their callees.
  1923. for (const auto &CallerCallees : DeviceCallGraph) {
  1924. Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
  1925. OMPDeclareTargetDeclAttr::getDeviceType(
  1926. CallerCallees.getFirst()->getMostRecentDecl());
  1927. // Ignore host functions during device analyzis.
  1928. if (LangOpts.OpenMPIsDevice && DevTy &&
  1929. *DevTy == OMPDeclareTargetDeclAttr::DT_Host)
  1930. continue;
  1931. // Ignore nohost functions during host analyzis.
  1932. if (!LangOpts.OpenMPIsDevice && DevTy &&
  1933. *DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
  1934. continue;
  1935. for (const std::pair<CanonicalDeclPtr<FunctionDecl>, SourceLocation>
  1936. &Callee : CallerCallees.getSecond()) {
  1937. const FunctionDecl *FD = Callee.first->getMostRecentDecl();
  1938. Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
  1939. OMPDeclareTargetDeclAttr::getDeviceType(FD);
  1940. if (LangOpts.OpenMPIsDevice && DevTy &&
  1941. *DevTy == OMPDeclareTargetDeclAttr::DT_Host) {
  1942. // Diagnose host function called during device codegen.
  1943. StringRef HostDevTy = getOpenMPSimpleClauseTypeName(
  1944. OMPC_device_type, OMPC_DEVICE_TYPE_host);
  1945. Diag(Callee.second, diag::err_omp_wrong_device_function_call)
  1946. << HostDevTy << 0;
  1947. Diag(FD->getAttr<OMPDeclareTargetDeclAttr>()->getLocation(),
  1948. diag::note_omp_marked_device_type_here)
  1949. << HostDevTy;
  1950. continue;
  1951. }
  1952. if (!LangOpts.OpenMPIsDevice && DevTy &&
  1953. *DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) {
  1954. // Diagnose nohost function called during host codegen.
  1955. StringRef NoHostDevTy = getOpenMPSimpleClauseTypeName(
  1956. OMPC_device_type, OMPC_DEVICE_TYPE_nohost);
  1957. Diag(Callee.second, diag::err_omp_wrong_device_function_call)
  1958. << NoHostDevTy << 1;
  1959. Diag(FD->getAttr<OMPDeclareTargetDeclAttr>()->getLocation(),
  1960. diag::note_omp_marked_device_type_here)
  1961. << NoHostDevTy;
  1962. continue;
  1963. }
  1964. }
  1965. }
  1966. }
  1967. void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
  1968. const DeclarationNameInfo &DirName,
  1969. Scope *CurScope, SourceLocation Loc) {
  1970. DSAStack->push(DKind, DirName, CurScope, Loc);
  1971. PushExpressionEvaluationContext(
  1972. ExpressionEvaluationContext::PotentiallyEvaluated);
  1973. }
  1974. void Sema::StartOpenMPClause(OpenMPClauseKind K) {
  1975. DSAStack->setClauseParsingMode(K);
  1976. }
  1977. void Sema::EndOpenMPClause() {
  1978. DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
  1979. }
  1980. static void checkAllocateClauses(Sema &S, DSAStackTy *Stack,
  1981. ArrayRef<OMPClause *> Clauses);
  1982. void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
  1983. // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
  1984. // A variable of class type (or array thereof) that appears in a lastprivate
  1985. // clause requires an accessible, unambiguous default constructor for the
  1986. // class type, unless the list item is also specified in a firstprivate
  1987. // clause.
  1988. if (const auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
  1989. for (OMPClause *C : D->clauses()) {
  1990. if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
  1991. SmallVector<Expr *, 8> PrivateCopies;
  1992. for (Expr *DE : Clause->varlists()) {
  1993. if (DE->isValueDependent() || DE->isTypeDependent()) {
  1994. PrivateCopies.push_back(nullptr);
  1995. continue;
  1996. }
  1997. auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens());
  1998. auto *VD = cast<VarDecl>(DRE->getDecl());
  1999. QualType Type = VD->getType().getNonReferenceType();
  2000. const DSAStackTy::DSAVarData DVar =
  2001. DSAStack->getTopDSA(VD, /*FromParent=*/false);
  2002. if (DVar.CKind == OMPC_lastprivate) {
  2003. // Generate helper private variable and initialize it with the
  2004. // default value. The address of the original variable is replaced
  2005. // by the address of the new private variable in CodeGen. This new
  2006. // variable is not added to IdResolver, so the code in the OpenMP
  2007. // region uses original variable for proper diagnostics.
  2008. VarDecl *VDPrivate = buildVarDecl(
  2009. *this, DE->getExprLoc(), Type.getUnqualifiedType(),
  2010. VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr, DRE);
  2011. ActOnUninitializedDecl(VDPrivate);
  2012. if (VDPrivate->isInvalidDecl()) {
  2013. PrivateCopies.push_back(nullptr);
  2014. continue;
  2015. }
  2016. PrivateCopies.push_back(buildDeclRefExpr(
  2017. *this, VDPrivate, DE->getType(), DE->getExprLoc()));
  2018. } else {
  2019. // The variable is also a firstprivate, so initialization sequence
  2020. // for private copy is generated already.
  2021. PrivateCopies.push_back(nullptr);
  2022. }
  2023. }
  2024. Clause->setPrivateCopies(PrivateCopies);
  2025. }
  2026. }
  2027. // Check allocate clauses.
  2028. if (!CurContext->isDependentContext())
  2029. checkAllocateClauses(*this, DSAStack, D->clauses());
  2030. }
  2031. DSAStack->pop();
  2032. DiscardCleanupsInEvaluationContext();
  2033. PopExpressionEvaluationContext();
  2034. }
  2035. static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
  2036. Expr *NumIterations, Sema &SemaRef,
  2037. Scope *S, DSAStackTy *Stack);
  2038. namespace {
  2039. class VarDeclFilterCCC final : public CorrectionCandidateCallback {
  2040. private:
  2041. Sema &SemaRef;
  2042. public:
  2043. explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
  2044. bool ValidateCandidate(const TypoCorrection &Candidate) override {
  2045. NamedDecl *ND = Candidate.getCorrectionDecl();
  2046. if (const auto *VD = dyn_cast_or_null<VarDecl>(ND)) {
  2047. return VD->hasGlobalStorage() &&
  2048. SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
  2049. SemaRef.getCurScope());
  2050. }
  2051. return false;
  2052. }
  2053. std::unique_ptr<CorrectionCandidateCallback> clone() override {
  2054. return std::make_unique<VarDeclFilterCCC>(*this);
  2055. }
  2056. };
  2057. class VarOrFuncDeclFilterCCC final : public CorrectionCandidateCallback {
  2058. private:
  2059. Sema &SemaRef;
  2060. public:
  2061. explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {}
  2062. bool ValidateCandidate(const TypoCorrection &Candidate) override {
  2063. NamedDecl *ND = Candidate.getCorrectionDecl();
  2064. if (ND && ((isa<VarDecl>(ND) && ND->getKind() == Decl::Var) ||
  2065. isa<FunctionDecl>(ND))) {
  2066. return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
  2067. SemaRef.getCurScope());
  2068. }
  2069. return false;
  2070. }
  2071. std::unique_ptr<CorrectionCandidateCallback> clone() override {
  2072. return std::make_unique<VarOrFuncDeclFilterCCC>(*this);
  2073. }
  2074. };
  2075. } // namespace
  2076. ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
  2077. CXXScopeSpec &ScopeSpec,
  2078. const DeclarationNameInfo &Id,
  2079. OpenMPDirectiveKind Kind) {
  2080. LookupResult Lookup(*this, Id, LookupOrdinaryName);
  2081. LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
  2082. if (Lookup.isAmbiguous())
  2083. return ExprError();
  2084. VarDecl *VD;
  2085. if (!Lookup.isSingleResult()) {
  2086. VarDeclFilterCCC CCC(*this);
  2087. if (TypoCorrection Corrected =
  2088. CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, CCC,
  2089. CTK_ErrorRecovery)) {
  2090. diagnoseTypo(Corrected,
  2091. PDiag(Lookup.empty()
  2092. ? diag::err_undeclared_var_use_suggest
  2093. : diag::err_omp_expected_var_arg_suggest)
  2094. << Id.getName());
  2095. VD = Corrected.getCorrectionDeclAs<VarDecl>();
  2096. } else {
  2097. Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
  2098. : diag::err_omp_expected_var_arg)
  2099. << Id.getName();
  2100. return ExprError();
  2101. }
  2102. } else if (!(VD = Lookup.getAsSingle<VarDecl>())) {
  2103. Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
  2104. Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
  2105. return ExprError();
  2106. }
  2107. Lookup.suppressDiagnostics();
  2108. // OpenMP [2.9.2, Syntax, C/C++]
  2109. // Variables must be file-scope, namespace-scope, or static block-scope.
  2110. if (Kind == OMPD_threadprivate && !VD->hasGlobalStorage()) {
  2111. Diag(Id.getLoc(), diag::err_omp_global_var_arg)
  2112. << getOpenMPDirectiveName(Kind) << !VD->isStaticLocal();
  2113. bool IsDecl =
  2114. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  2115. Diag(VD->getLocation(),
  2116. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  2117. << VD;
  2118. return ExprError();
  2119. }
  2120. VarDecl *CanonicalVD = VD->getCanonicalDecl();
  2121. NamedDecl *ND = CanonicalVD;
  2122. // OpenMP [2.9.2, Restrictions, C/C++, p.2]
  2123. // A threadprivate directive for file-scope variables must appear outside
  2124. // any definition or declaration.
  2125. if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
  2126. !getCurLexicalContext()->isTranslationUnit()) {
  2127. Diag(Id.getLoc(), diag::err_omp_var_scope)
  2128. << getOpenMPDirectiveName(Kind) << VD;
  2129. bool IsDecl =
  2130. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  2131. Diag(VD->getLocation(),
  2132. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  2133. << VD;
  2134. return ExprError();
  2135. }
  2136. // OpenMP [2.9.2, Restrictions, C/C++, p.3]
  2137. // A threadprivate directive for static class member variables must appear
  2138. // in the class definition, in the same scope in which the member
  2139. // variables are declared.
  2140. if (CanonicalVD->isStaticDataMember() &&
  2141. !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
  2142. Diag(Id.getLoc(), diag::err_omp_var_scope)
  2143. << getOpenMPDirectiveName(Kind) << VD;
  2144. bool IsDecl =
  2145. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  2146. Diag(VD->getLocation(),
  2147. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  2148. << VD;
  2149. return ExprError();
  2150. }
  2151. // OpenMP [2.9.2, Restrictions, C/C++, p.4]
  2152. // A threadprivate directive for namespace-scope variables must appear
  2153. // outside any definition or declaration other than the namespace
  2154. // definition itself.
  2155. if (CanonicalVD->getDeclContext()->isNamespace() &&
  2156. (!getCurLexicalContext()->isFileContext() ||
  2157. !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
  2158. Diag(Id.getLoc(), diag::err_omp_var_scope)
  2159. << getOpenMPDirectiveName(Kind) << VD;
  2160. bool IsDecl =
  2161. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  2162. Diag(VD->getLocation(),
  2163. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  2164. << VD;
  2165. return ExprError();
  2166. }
  2167. // OpenMP [2.9.2, Restrictions, C/C++, p.6]
  2168. // A threadprivate directive for static block-scope variables must appear
  2169. // in the scope of the variable and not in a nested scope.
  2170. if (CanonicalVD->isLocalVarDecl() && CurScope &&
  2171. !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
  2172. Diag(Id.getLoc(), diag::err_omp_var_scope)
  2173. << getOpenMPDirectiveName(Kind) << VD;
  2174. bool IsDecl =
  2175. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  2176. Diag(VD->getLocation(),
  2177. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  2178. << VD;
  2179. return ExprError();
  2180. }
  2181. // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
  2182. // A threadprivate directive must lexically precede all references to any
  2183. // of the variables in its list.
  2184. if (Kind == OMPD_threadprivate && VD->isUsed() &&
  2185. !DSAStack->isThreadPrivate(VD)) {
  2186. Diag(Id.getLoc(), diag::err_omp_var_used)
  2187. << getOpenMPDirectiveName(Kind) << VD;
  2188. return ExprError();
  2189. }
  2190. QualType ExprType = VD->getType().getNonReferenceType();
  2191. return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
  2192. SourceLocation(), VD,
  2193. /*RefersToEnclosingVariableOrCapture=*/false,
  2194. Id.getLoc(), ExprType, VK_LValue);
  2195. }
  2196. Sema::DeclGroupPtrTy
  2197. Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
  2198. ArrayRef<Expr *> VarList) {
  2199. if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
  2200. CurContext->addDecl(D);
  2201. return DeclGroupPtrTy::make(DeclGroupRef(D));
  2202. }
  2203. return nullptr;
  2204. }
  2205. namespace {
  2206. class LocalVarRefChecker final
  2207. : public ConstStmtVisitor<LocalVarRefChecker, bool> {
  2208. Sema &SemaRef;
  2209. public:
  2210. bool VisitDeclRefExpr(const DeclRefExpr *E) {
  2211. if (const auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
  2212. if (VD->hasLocalStorage()) {
  2213. SemaRef.Diag(E->getBeginLoc(),
  2214. diag::err_omp_local_var_in_threadprivate_init)
  2215. << E->getSourceRange();
  2216. SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
  2217. << VD << VD->getSourceRange();
  2218. return true;
  2219. }
  2220. }
  2221. return false;
  2222. }
  2223. bool VisitStmt(const Stmt *S) {
  2224. for (const Stmt *Child : S->children()) {
  2225. if (Child && Visit(Child))
  2226. return true;
  2227. }
  2228. return false;
  2229. }
  2230. explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
  2231. };
  2232. } // namespace
  2233. OMPThreadPrivateDecl *
  2234. Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
  2235. SmallVector<Expr *, 8> Vars;
  2236. for (Expr *RefExpr : VarList) {
  2237. auto *DE = cast<DeclRefExpr>(RefExpr);
  2238. auto *VD = cast<VarDecl>(DE->getDecl());
  2239. SourceLocation ILoc = DE->getExprLoc();
  2240. // Mark variable as used.
  2241. VD->setReferenced();
  2242. VD->markUsed(Context);
  2243. QualType QType = VD->getType();
  2244. if (QType->isDependentType() || QType->isInstantiationDependentType()) {
  2245. // It will be analyzed later.
  2246. Vars.push_back(DE);
  2247. continue;
  2248. }
  2249. // OpenMP [2.9.2, Restrictions, C/C++, p.10]
  2250. // A threadprivate variable must not have an incomplete type.
  2251. if (RequireCompleteType(ILoc, VD->getType(),
  2252. diag::err_omp_threadprivate_incomplete_type)) {
  2253. continue;
  2254. }
  2255. // OpenMP [2.9.2, Restrictions, C/C++, p.10]
  2256. // A threadprivate variable must not have a reference type.
  2257. if (VD->getType()->isReferenceType()) {
  2258. Diag(ILoc, diag::err_omp_ref_type_arg)
  2259. << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
  2260. bool IsDecl =
  2261. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  2262. Diag(VD->getLocation(),
  2263. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  2264. << VD;
  2265. continue;
  2266. }
  2267. // Check if this is a TLS variable. If TLS is not being supported, produce
  2268. // the corresponding diagnostic.
  2269. if ((VD->getTLSKind() != VarDecl::TLS_None &&
  2270. !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
  2271. getLangOpts().OpenMPUseTLS &&
  2272. getASTContext().getTargetInfo().isTLSSupported())) ||
  2273. (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
  2274. !VD->isLocalVarDecl())) {
  2275. Diag(ILoc, diag::err_omp_var_thread_local)
  2276. << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
  2277. bool IsDecl =
  2278. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  2279. Diag(VD->getLocation(),
  2280. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  2281. << VD;
  2282. continue;
  2283. }
  2284. // Check if initial value of threadprivate variable reference variable with
  2285. // local storage (it is not supported by runtime).
  2286. if (const Expr *Init = VD->getAnyInitializer()) {
  2287. LocalVarRefChecker Checker(*this);
  2288. if (Checker.Visit(Init))
  2289. continue;
  2290. }
  2291. Vars.push_back(RefExpr);
  2292. DSAStack->addDSA(VD, DE, OMPC_threadprivate);
  2293. VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
  2294. Context, SourceRange(Loc, Loc)));
  2295. if (ASTMutationListener *ML = Context.getASTMutationListener())
  2296. ML->DeclarationMarkedOpenMPThreadPrivate(VD);
  2297. }
  2298. OMPThreadPrivateDecl *D = nullptr;
  2299. if (!Vars.empty()) {
  2300. D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
  2301. Vars);
  2302. D->setAccess(AS_public);
  2303. }
  2304. return D;
  2305. }
  2306. static OMPAllocateDeclAttr::AllocatorTypeTy
  2307. getAllocatorKind(Sema &S, DSAStackTy *Stack, Expr *Allocator) {
  2308. if (!Allocator)
  2309. return OMPAllocateDeclAttr::OMPDefaultMemAlloc;
  2310. if (Allocator->isTypeDependent() || Allocator->isValueDependent() ||
  2311. Allocator->isInstantiationDependent() ||
  2312. Allocator->containsUnexpandedParameterPack())
  2313. return OMPAllocateDeclAttr::OMPUserDefinedMemAlloc;
  2314. auto AllocatorKindRes = OMPAllocateDeclAttr::OMPUserDefinedMemAlloc;
  2315. const Expr *AE = Allocator->IgnoreParenImpCasts();
  2316. for (int I = OMPAllocateDeclAttr::OMPDefaultMemAlloc;
  2317. I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) {
  2318. auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I);
  2319. const Expr *DefAllocator = Stack->getAllocator(AllocatorKind);
  2320. llvm::FoldingSetNodeID AEId, DAEId;
  2321. AE->Profile(AEId, S.getASTContext(), /*Canonical=*/true);
  2322. DefAllocator->Profile(DAEId, S.getASTContext(), /*Canonical=*/true);
  2323. if (AEId == DAEId) {
  2324. AllocatorKindRes = AllocatorKind;
  2325. break;
  2326. }
  2327. }
  2328. return AllocatorKindRes;
  2329. }
  2330. static bool checkPreviousOMPAllocateAttribute(
  2331. Sema &S, DSAStackTy *Stack, Expr *RefExpr, VarDecl *VD,
  2332. OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind, Expr *Allocator) {
  2333. if (!VD->hasAttr<OMPAllocateDeclAttr>())
  2334. return false;
  2335. const auto *A = VD->getAttr<OMPAllocateDeclAttr>();
  2336. Expr *PrevAllocator = A->getAllocator();
  2337. OMPAllocateDeclAttr::AllocatorTypeTy PrevAllocatorKind =
  2338. getAllocatorKind(S, Stack, PrevAllocator);
  2339. bool AllocatorsMatch = AllocatorKind == PrevAllocatorKind;
  2340. if (AllocatorsMatch &&
  2341. AllocatorKind == OMPAllocateDeclAttr::OMPUserDefinedMemAlloc &&
  2342. Allocator && PrevAllocator) {
  2343. const Expr *AE = Allocator->IgnoreParenImpCasts();
  2344. const Expr *PAE = PrevAllocator->IgnoreParenImpCasts();
  2345. llvm::FoldingSetNodeID AEId, PAEId;
  2346. AE->Profile(AEId, S.Context, /*Canonical=*/true);
  2347. PAE->Profile(PAEId, S.Context, /*Canonical=*/true);
  2348. AllocatorsMatch = AEId == PAEId;
  2349. }
  2350. if (!AllocatorsMatch) {
  2351. SmallString<256> AllocatorBuffer;
  2352. llvm::raw_svector_ostream AllocatorStream(AllocatorBuffer);
  2353. if (Allocator)
  2354. Allocator->printPretty(AllocatorStream, nullptr, S.getPrintingPolicy());
  2355. SmallString<256> PrevAllocatorBuffer;
  2356. llvm::raw_svector_ostream PrevAllocatorStream(PrevAllocatorBuffer);
  2357. if (PrevAllocator)
  2358. PrevAllocator->printPretty(PrevAllocatorStream, nullptr,
  2359. S.getPrintingPolicy());
  2360. SourceLocation AllocatorLoc =
  2361. Allocator ? Allocator->getExprLoc() : RefExpr->getExprLoc();
  2362. SourceRange AllocatorRange =
  2363. Allocator ? Allocator->getSourceRange() : RefExpr->getSourceRange();
  2364. SourceLocation PrevAllocatorLoc =
  2365. PrevAllocator ? PrevAllocator->getExprLoc() : A->getLocation();
  2366. SourceRange PrevAllocatorRange =
  2367. PrevAllocator ? PrevAllocator->getSourceRange() : A->getRange();
  2368. S.Diag(AllocatorLoc, diag::warn_omp_used_different_allocator)
  2369. << (Allocator ? 1 : 0) << AllocatorStream.str()
  2370. << (PrevAllocator ? 1 : 0) << PrevAllocatorStream.str()
  2371. << AllocatorRange;
  2372. S.Diag(PrevAllocatorLoc, diag::note_omp_previous_allocator)
  2373. << PrevAllocatorRange;
  2374. return true;
  2375. }
  2376. return false;
  2377. }
  2378. static void
  2379. applyOMPAllocateAttribute(Sema &S, VarDecl *VD,
  2380. OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind,
  2381. Expr *Allocator, SourceRange SR) {
  2382. if (VD->hasAttr<OMPAllocateDeclAttr>())
  2383. return;
  2384. if (Allocator &&
  2385. (Allocator->isTypeDependent() || Allocator->isValueDependent() ||
  2386. Allocator->isInstantiationDependent() ||
  2387. Allocator->containsUnexpandedParameterPack()))
  2388. return;
  2389. auto *A = OMPAllocateDeclAttr::CreateImplicit(S.Context, AllocatorKind,
  2390. Allocator, SR);
  2391. VD->addAttr(A);
  2392. if (ASTMutationListener *ML = S.Context.getASTMutationListener())
  2393. ML->DeclarationMarkedOpenMPAllocate(VD, A);
  2394. }
  2395. Sema::DeclGroupPtrTy Sema::ActOnOpenMPAllocateDirective(
  2396. SourceLocation Loc, ArrayRef<Expr *> VarList,
  2397. ArrayRef<OMPClause *> Clauses, DeclContext *Owner) {
  2398. assert(Clauses.size() <= 1 && "Expected at most one clause.");
  2399. Expr *Allocator = nullptr;
  2400. if (Clauses.empty()) {
  2401. // OpenMP 5.0, 2.11.3 allocate Directive, Restrictions.
  2402. // allocate directives that appear in a target region must specify an
  2403. // allocator clause unless a requires directive with the dynamic_allocators
  2404. // clause is present in the same compilation unit.
  2405. if (LangOpts.OpenMPIsDevice &&
  2406. !DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())
  2407. targetDiag(Loc, diag::err_expected_allocator_clause);
  2408. } else {
  2409. Allocator = cast<OMPAllocatorClause>(Clauses.back())->getAllocator();
  2410. }
  2411. OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind =
  2412. getAllocatorKind(*this, DSAStack, Allocator);
  2413. SmallVector<Expr *, 8> Vars;
  2414. for (Expr *RefExpr : VarList) {
  2415. auto *DE = cast<DeclRefExpr>(RefExpr);
  2416. auto *VD = cast<VarDecl>(DE->getDecl());
  2417. // Check if this is a TLS variable or global register.
  2418. if (VD->getTLSKind() != VarDecl::TLS_None ||
  2419. VD->hasAttr<OMPThreadPrivateDeclAttr>() ||
  2420. (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
  2421. !VD->isLocalVarDecl()))
  2422. continue;
  2423. // If the used several times in the allocate directive, the same allocator
  2424. // must be used.
  2425. if (checkPreviousOMPAllocateAttribute(*this, DSAStack, RefExpr, VD,
  2426. AllocatorKind, Allocator))
  2427. continue;
  2428. // OpenMP, 2.11.3 allocate Directive, Restrictions, C / C++
  2429. // If a list item has a static storage type, the allocator expression in the
  2430. // allocator clause must be a constant expression that evaluates to one of
  2431. // the predefined memory allocator values.
  2432. if (Allocator && VD->hasGlobalStorage()) {
  2433. if (AllocatorKind == OMPAllocateDeclAttr::OMPUserDefinedMemAlloc) {
  2434. Diag(Allocator->getExprLoc(),
  2435. diag::err_omp_expected_predefined_allocator)
  2436. << Allocator->getSourceRange();
  2437. bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
  2438. VarDecl::DeclarationOnly;
  2439. Diag(VD->getLocation(),
  2440. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  2441. << VD;
  2442. continue;
  2443. }
  2444. }
  2445. Vars.push_back(RefExpr);
  2446. applyOMPAllocateAttribute(*this, VD, AllocatorKind, Allocator,
  2447. DE->getSourceRange());
  2448. }
  2449. if (Vars.empty())
  2450. return nullptr;
  2451. if (!Owner)
  2452. Owner = getCurLexicalContext();
  2453. auto *D = OMPAllocateDecl::Create(Context, Owner, Loc, Vars, Clauses);
  2454. D->setAccess(AS_public);
  2455. Owner->addDecl(D);
  2456. return DeclGroupPtrTy::make(DeclGroupRef(D));
  2457. }
  2458. Sema::DeclGroupPtrTy
  2459. Sema::ActOnOpenMPRequiresDirective(SourceLocation Loc,
  2460. ArrayRef<OMPClause *> ClauseList) {
  2461. OMPRequiresDecl *D = nullptr;
  2462. if (!CurContext->isFileContext()) {
  2463. Diag(Loc, diag::err_omp_invalid_scope) << "requires";
  2464. } else {
  2465. D = CheckOMPRequiresDecl(Loc, ClauseList);
  2466. if (D) {
  2467. CurContext->addDecl(D);
  2468. DSAStack->addRequiresDecl(D);
  2469. }
  2470. }
  2471. return DeclGroupPtrTy::make(DeclGroupRef(D));
  2472. }
  2473. OMPRequiresDecl *Sema::CheckOMPRequiresDecl(SourceLocation Loc,
  2474. ArrayRef<OMPClause *> ClauseList) {
  2475. /// For target specific clauses, the requires directive cannot be
  2476. /// specified after the handling of any of the target regions in the
  2477. /// current compilation unit.
  2478. ArrayRef<SourceLocation> TargetLocations =
  2479. DSAStack->getEncounteredTargetLocs();
  2480. if (!TargetLocations.empty()) {
  2481. for (const OMPClause *CNew : ClauseList) {
  2482. // Check if any of the requires clauses affect target regions.
  2483. if (isa<OMPUnifiedSharedMemoryClause>(CNew) ||
  2484. isa<OMPUnifiedAddressClause>(CNew) ||
  2485. isa<OMPReverseOffloadClause>(CNew) ||
  2486. isa<OMPDynamicAllocatorsClause>(CNew)) {
  2487. Diag(Loc, diag::err_omp_target_before_requires)
  2488. << getOpenMPClauseName(CNew->getClauseKind());
  2489. for (SourceLocation TargetLoc : TargetLocations) {
  2490. Diag(TargetLoc, diag::note_omp_requires_encountered_target);
  2491. }
  2492. }
  2493. }
  2494. }
  2495. if (!DSAStack->hasDuplicateRequiresClause(ClauseList))
  2496. return OMPRequiresDecl::Create(Context, getCurLexicalContext(), Loc,
  2497. ClauseList);
  2498. return nullptr;
  2499. }
  2500. static void reportOriginalDsa(Sema &SemaRef, const DSAStackTy *Stack,
  2501. const ValueDecl *D,
  2502. const DSAStackTy::DSAVarData &DVar,
  2503. bool IsLoopIterVar = false) {
  2504. if (DVar.RefExpr) {
  2505. SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
  2506. << getOpenMPClauseName(DVar.CKind);
  2507. return;
  2508. }
  2509. enum {
  2510. PDSA_StaticMemberShared,
  2511. PDSA_StaticLocalVarShared,
  2512. PDSA_LoopIterVarPrivate,
  2513. PDSA_LoopIterVarLinear,
  2514. PDSA_LoopIterVarLastprivate,
  2515. PDSA_ConstVarShared,
  2516. PDSA_GlobalVarShared,
  2517. PDSA_TaskVarFirstprivate,
  2518. PDSA_LocalVarPrivate,
  2519. PDSA_Implicit
  2520. } Reason = PDSA_Implicit;
  2521. bool ReportHint = false;
  2522. auto ReportLoc = D->getLocation();
  2523. auto *VD = dyn_cast<VarDecl>(D);
  2524. if (IsLoopIterVar) {
  2525. if (DVar.CKind == OMPC_private)
  2526. Reason = PDSA_LoopIterVarPrivate;
  2527. else if (DVar.CKind == OMPC_lastprivate)
  2528. Reason = PDSA_LoopIterVarLastprivate;
  2529. else
  2530. Reason = PDSA_LoopIterVarLinear;
  2531. } else if (isOpenMPTaskingDirective(DVar.DKind) &&
  2532. DVar.CKind == OMPC_firstprivate) {
  2533. Reason = PDSA_TaskVarFirstprivate;
  2534. ReportLoc = DVar.ImplicitDSALoc;
  2535. } else if (VD && VD->isStaticLocal())
  2536. Reason = PDSA_StaticLocalVarShared;
  2537. else if (VD && VD->isStaticDataMember())
  2538. Reason = PDSA_StaticMemberShared;
  2539. else if (VD && VD->isFileVarDecl())
  2540. Reason = PDSA_GlobalVarShared;
  2541. else if (D->getType().isConstant(SemaRef.getASTContext()))
  2542. Reason = PDSA_ConstVarShared;
  2543. else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
  2544. ReportHint = true;
  2545. Reason = PDSA_LocalVarPrivate;
  2546. }
  2547. if (Reason != PDSA_Implicit) {
  2548. SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
  2549. << Reason << ReportHint
  2550. << getOpenMPDirectiveName(Stack->getCurrentDirective());
  2551. } else if (DVar.ImplicitDSALoc.isValid()) {
  2552. SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
  2553. << getOpenMPClauseName(DVar.CKind);
  2554. }
  2555. }
  2556. namespace {
  2557. class DSAAttrChecker final : public StmtVisitor<DSAAttrChecker, void> {
  2558. DSAStackTy *Stack;
  2559. Sema &SemaRef;
  2560. bool ErrorFound = false;
  2561. CapturedStmt *CS = nullptr;
  2562. llvm::SmallVector<Expr *, 4> ImplicitFirstprivate;
  2563. llvm::SmallVector<Expr *, 4> ImplicitMap;
  2564. Sema::VarsWithInheritedDSAType VarsWithInheritedDSA;
  2565. llvm::SmallDenseSet<const ValueDecl *, 4> ImplicitDeclarations;
  2566. void VisitSubCaptures(OMPExecutableDirective *S) {
  2567. // Check implicitly captured variables.
  2568. if (!S->hasAssociatedStmt() || !S->getAssociatedStmt())
  2569. return;
  2570. visitSubCaptures(S->getInnermostCapturedStmt());
  2571. }
  2572. public:
  2573. void VisitDeclRefExpr(DeclRefExpr *E) {
  2574. if (E->isTypeDependent() || E->isValueDependent() ||
  2575. E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
  2576. return;
  2577. if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
  2578. // Check the datasharing rules for the expressions in the clauses.
  2579. if (!CS) {
  2580. if (auto *CED = dyn_cast<OMPCapturedExprDecl>(VD))
  2581. if (!CED->hasAttr<OMPCaptureNoInitAttr>()) {
  2582. Visit(CED->getInit());
  2583. return;
  2584. }
  2585. } else if (VD->isImplicit() || isa<OMPCapturedExprDecl>(VD))
  2586. // Do not analyze internal variables and do not enclose them into
  2587. // implicit clauses.
  2588. return;
  2589. VD = VD->getCanonicalDecl();
  2590. // Skip internally declared variables.
  2591. if (VD->hasLocalStorage() && CS && !CS->capturesVariable(VD))
  2592. return;
  2593. DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
  2594. // Check if the variable has explicit DSA set and stop analysis if it so.
  2595. if (DVar.RefExpr || !ImplicitDeclarations.insert(VD).second)
  2596. return;
  2597. // Skip internally declared static variables.
  2598. llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
  2599. OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
  2600. if (VD->hasGlobalStorage() && CS && !CS->capturesVariable(VD) &&
  2601. (Stack->hasRequiresDeclWithClause<OMPUnifiedSharedMemoryClause>() ||
  2602. !Res || *Res != OMPDeclareTargetDeclAttr::MT_Link))
  2603. return;
  2604. SourceLocation ELoc = E->getExprLoc();
  2605. OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
  2606. // The default(none) clause requires that each variable that is referenced
  2607. // in the construct, and does not have a predetermined data-sharing
  2608. // attribute, must have its data-sharing attribute explicitly determined
  2609. // by being listed in a data-sharing attribute clause.
  2610. if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
  2611. isImplicitOrExplicitTaskingRegion(DKind) &&
  2612. VarsWithInheritedDSA.count(VD) == 0) {
  2613. VarsWithInheritedDSA[VD] = E;
  2614. return;
  2615. }
  2616. if (isOpenMPTargetExecutionDirective(DKind) &&
  2617. !Stack->isLoopControlVariable(VD).first) {
  2618. if (!Stack->checkMappableExprComponentListsForDecl(
  2619. VD, /*CurrentRegionOnly=*/true,
  2620. [](OMPClauseMappableExprCommon::MappableExprComponentListRef
  2621. StackComponents,
  2622. OpenMPClauseKind) {
  2623. // Variable is used if it has been marked as an array, array
  2624. // section or the variable iself.
  2625. return StackComponents.size() == 1 ||
  2626. std::all_of(
  2627. std::next(StackComponents.rbegin()),
  2628. StackComponents.rend(),
  2629. [](const OMPClauseMappableExprCommon::
  2630. MappableComponent &MC) {
  2631. return MC.getAssociatedDeclaration() ==
  2632. nullptr &&
  2633. (isa<OMPArraySectionExpr>(
  2634. MC.getAssociatedExpression()) ||
  2635. isa<ArraySubscriptExpr>(
  2636. MC.getAssociatedExpression()));
  2637. });
  2638. })) {
  2639. bool IsFirstprivate = false;
  2640. // By default lambdas are captured as firstprivates.
  2641. if (const auto *RD =
  2642. VD->getType().getNonReferenceType()->getAsCXXRecordDecl())
  2643. IsFirstprivate = RD->isLambda();
  2644. IsFirstprivate =
  2645. IsFirstprivate ||
  2646. (VD->getType().getNonReferenceType()->isScalarType() &&
  2647. Stack->getDefaultDMA() != DMA_tofrom_scalar && !Res);
  2648. if (IsFirstprivate)
  2649. ImplicitFirstprivate.emplace_back(E);
  2650. else
  2651. ImplicitMap.emplace_back(E);
  2652. return;
  2653. }
  2654. }
  2655. // OpenMP [2.9.3.6, Restrictions, p.2]
  2656. // A list item that appears in a reduction clause of the innermost
  2657. // enclosing worksharing or parallel construct may not be accessed in an
  2658. // explicit task.
  2659. DVar = Stack->hasInnermostDSA(
  2660. VD, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
  2661. [](OpenMPDirectiveKind K) {
  2662. return isOpenMPParallelDirective(K) ||
  2663. isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
  2664. },
  2665. /*FromParent=*/true);
  2666. if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
  2667. ErrorFound = true;
  2668. SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
  2669. reportOriginalDsa(SemaRef, Stack, VD, DVar);
  2670. return;
  2671. }
  2672. // Define implicit data-sharing attributes for task.
  2673. DVar = Stack->getImplicitDSA(VD, /*FromParent=*/false);
  2674. if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
  2675. !Stack->isLoopControlVariable(VD).first) {
  2676. ImplicitFirstprivate.push_back(E);
  2677. return;
  2678. }
  2679. // Store implicitly used globals with declare target link for parent
  2680. // target.
  2681. if (!isOpenMPTargetExecutionDirective(DKind) && Res &&
  2682. *Res == OMPDeclareTargetDeclAttr::MT_Link) {
  2683. Stack->addToParentTargetRegionLinkGlobals(E);
  2684. return;
  2685. }
  2686. }
  2687. }
  2688. void VisitMemberExpr(MemberExpr *E) {
  2689. if (E->isTypeDependent() || E->isValueDependent() ||
  2690. E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
  2691. return;
  2692. auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
  2693. OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
  2694. if (auto *TE = dyn_cast<CXXThisExpr>(E->getBase()->IgnoreParens())) {
  2695. if (!FD)
  2696. return;
  2697. DSAStackTy::DSAVarData DVar = Stack->getTopDSA(FD, /*FromParent=*/false);
  2698. // Check if the variable has explicit DSA set and stop analysis if it
  2699. // so.
  2700. if (DVar.RefExpr || !ImplicitDeclarations.insert(FD).second)
  2701. return;
  2702. if (isOpenMPTargetExecutionDirective(DKind) &&
  2703. !Stack->isLoopControlVariable(FD).first &&
  2704. !Stack->checkMappableExprComponentListsForDecl(
  2705. FD, /*CurrentRegionOnly=*/true,
  2706. [](OMPClauseMappableExprCommon::MappableExprComponentListRef
  2707. StackComponents,
  2708. OpenMPClauseKind) {
  2709. return isa<CXXThisExpr>(
  2710. cast<MemberExpr>(
  2711. StackComponents.back().getAssociatedExpression())
  2712. ->getBase()
  2713. ->IgnoreParens());
  2714. })) {
  2715. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
  2716. // A bit-field cannot appear in a map clause.
  2717. //
  2718. if (FD->isBitField())
  2719. return;
  2720. // Check to see if the member expression is referencing a class that
  2721. // has already been explicitly mapped
  2722. if (Stack->isClassPreviouslyMapped(TE->getType()))
  2723. return;
  2724. ImplicitMap.emplace_back(E);
  2725. return;
  2726. }
  2727. SourceLocation ELoc = E->getExprLoc();
  2728. // OpenMP [2.9.3.6, Restrictions, p.2]
  2729. // A list item that appears in a reduction clause of the innermost
  2730. // enclosing worksharing or parallel construct may not be accessed in
  2731. // an explicit task.
  2732. DVar = Stack->hasInnermostDSA(
  2733. FD, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
  2734. [](OpenMPDirectiveKind K) {
  2735. return isOpenMPParallelDirective(K) ||
  2736. isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
  2737. },
  2738. /*FromParent=*/true);
  2739. if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
  2740. ErrorFound = true;
  2741. SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
  2742. reportOriginalDsa(SemaRef, Stack, FD, DVar);
  2743. return;
  2744. }
  2745. // Define implicit data-sharing attributes for task.
  2746. DVar = Stack->getImplicitDSA(FD, /*FromParent=*/false);
  2747. if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
  2748. !Stack->isLoopControlVariable(FD).first) {
  2749. // Check if there is a captured expression for the current field in the
  2750. // region. Do not mark it as firstprivate unless there is no captured
  2751. // expression.
  2752. // TODO: try to make it firstprivate.
  2753. if (DVar.CKind != OMPC_unknown)
  2754. ImplicitFirstprivate.push_back(E);
  2755. }
  2756. return;
  2757. }
  2758. if (isOpenMPTargetExecutionDirective(DKind)) {
  2759. OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
  2760. if (!checkMapClauseExpressionBase(SemaRef, E, CurComponents, OMPC_map,
  2761. /*NoDiagnose=*/true))
  2762. return;
  2763. const auto *VD = cast<ValueDecl>(
  2764. CurComponents.back().getAssociatedDeclaration()->getCanonicalDecl());
  2765. if (!Stack->checkMappableExprComponentListsForDecl(
  2766. VD, /*CurrentRegionOnly=*/true,
  2767. [&CurComponents](
  2768. OMPClauseMappableExprCommon::MappableExprComponentListRef
  2769. StackComponents,
  2770. OpenMPClauseKind) {
  2771. auto CCI = CurComponents.rbegin();
  2772. auto CCE = CurComponents.rend();
  2773. for (const auto &SC : llvm::reverse(StackComponents)) {
  2774. // Do both expressions have the same kind?
  2775. if (CCI->getAssociatedExpression()->getStmtClass() !=
  2776. SC.getAssociatedExpression()->getStmtClass())
  2777. if (!(isa<OMPArraySectionExpr>(
  2778. SC.getAssociatedExpression()) &&
  2779. isa<ArraySubscriptExpr>(
  2780. CCI->getAssociatedExpression())))
  2781. return false;
  2782. const Decl *CCD = CCI->getAssociatedDeclaration();
  2783. const Decl *SCD = SC.getAssociatedDeclaration();
  2784. CCD = CCD ? CCD->getCanonicalDecl() : nullptr;
  2785. SCD = SCD ? SCD->getCanonicalDecl() : nullptr;
  2786. if (SCD != CCD)
  2787. return false;
  2788. std::advance(CCI, 1);
  2789. if (CCI == CCE)
  2790. break;
  2791. }
  2792. return true;
  2793. })) {
  2794. Visit(E->getBase());
  2795. }
  2796. } else {
  2797. Visit(E->getBase());
  2798. }
  2799. }
  2800. void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
  2801. for (OMPClause *C : S->clauses()) {
  2802. // Skip analysis of arguments of implicitly defined firstprivate clause
  2803. // for task|target directives.
  2804. // Skip analysis of arguments of implicitly defined map clause for target
  2805. // directives.
  2806. if (C && !((isa<OMPFirstprivateClause>(C) || isa<OMPMapClause>(C)) &&
  2807. C->isImplicit())) {
  2808. for (Stmt *CC : C->children()) {
  2809. if (CC)
  2810. Visit(CC);
  2811. }
  2812. }
  2813. }
  2814. // Check implicitly captured variables.
  2815. VisitSubCaptures(S);
  2816. }
  2817. void VisitStmt(Stmt *S) {
  2818. for (Stmt *C : S->children()) {
  2819. if (C) {
  2820. // Check implicitly captured variables in the task-based directives to
  2821. // check if they must be firstprivatized.
  2822. Visit(C);
  2823. }
  2824. }
  2825. }
  2826. void visitSubCaptures(CapturedStmt *S) {
  2827. for (const CapturedStmt::Capture &Cap : S->captures()) {
  2828. if (!Cap.capturesVariable() && !Cap.capturesVariableByCopy())
  2829. continue;
  2830. VarDecl *VD = Cap.getCapturedVar();
  2831. // Do not try to map the variable if it or its sub-component was mapped
  2832. // already.
  2833. if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) &&
  2834. Stack->checkMappableExprComponentListsForDecl(
  2835. VD, /*CurrentRegionOnly=*/true,
  2836. [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
  2837. OpenMPClauseKind) { return true; }))
  2838. continue;
  2839. DeclRefExpr *DRE = buildDeclRefExpr(
  2840. SemaRef, VD, VD->getType().getNonLValueExprType(SemaRef.Context),
  2841. Cap.getLocation(), /*RefersToCapture=*/true);
  2842. Visit(DRE);
  2843. }
  2844. }
  2845. bool isErrorFound() const { return ErrorFound; }
  2846. ArrayRef<Expr *> getImplicitFirstprivate() const {
  2847. return ImplicitFirstprivate;
  2848. }
  2849. ArrayRef<Expr *> getImplicitMap() const { return ImplicitMap; }
  2850. const Sema::VarsWithInheritedDSAType &getVarsWithInheritedDSA() const {
  2851. return VarsWithInheritedDSA;
  2852. }
  2853. DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
  2854. : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {
  2855. // Process declare target link variables for the target directives.
  2856. if (isOpenMPTargetExecutionDirective(S->getCurrentDirective())) {
  2857. for (DeclRefExpr *E : Stack->getLinkGlobals())
  2858. Visit(E);
  2859. }
  2860. }
  2861. };
  2862. } // namespace
  2863. void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
  2864. switch (DKind) {
  2865. case OMPD_parallel:
  2866. case OMPD_parallel_for:
  2867. case OMPD_parallel_for_simd:
  2868. case OMPD_parallel_sections:
  2869. case OMPD_teams:
  2870. case OMPD_teams_distribute:
  2871. case OMPD_teams_distribute_simd: {
  2872. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
  2873. QualType KmpInt32PtrTy =
  2874. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  2875. Sema::CapturedParamNameType Params[] = {
  2876. std::make_pair(".global_tid.", KmpInt32PtrTy),
  2877. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  2878. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2879. };
  2880. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2881. Params);
  2882. break;
  2883. }
  2884. case OMPD_target_teams:
  2885. case OMPD_target_parallel:
  2886. case OMPD_target_parallel_for:
  2887. case OMPD_target_parallel_for_simd:
  2888. case OMPD_target_teams_distribute:
  2889. case OMPD_target_teams_distribute_simd: {
  2890. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
  2891. QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
  2892. QualType KmpInt32PtrTy =
  2893. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  2894. QualType Args[] = {VoidPtrTy};
  2895. FunctionProtoType::ExtProtoInfo EPI;
  2896. EPI.Variadic = true;
  2897. QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
  2898. Sema::CapturedParamNameType Params[] = {
  2899. std::make_pair(".global_tid.", KmpInt32Ty),
  2900. std::make_pair(".part_id.", KmpInt32PtrTy),
  2901. std::make_pair(".privates.", VoidPtrTy),
  2902. std::make_pair(
  2903. ".copy_fn.",
  2904. Context.getPointerType(CopyFnType).withConst().withRestrict()),
  2905. std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
  2906. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2907. };
  2908. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2909. Params, /*OpenMPCaptureLevel=*/0);
  2910. // Mark this captured region as inlined, because we don't use outlined
  2911. // function directly.
  2912. getCurCapturedRegion()->TheCapturedDecl->addAttr(
  2913. AlwaysInlineAttr::CreateImplicit(
  2914. Context, {}, AttributeCommonInfo::AS_Keyword,
  2915. AlwaysInlineAttr::Keyword_forceinline));
  2916. Sema::CapturedParamNameType ParamsTarget[] = {
  2917. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2918. };
  2919. // Start a captured region for 'target' with no implicit parameters.
  2920. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2921. ParamsTarget, /*OpenMPCaptureLevel=*/1);
  2922. Sema::CapturedParamNameType ParamsTeamsOrParallel[] = {
  2923. std::make_pair(".global_tid.", KmpInt32PtrTy),
  2924. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  2925. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2926. };
  2927. // Start a captured region for 'teams' or 'parallel'. Both regions have
  2928. // the same implicit parameters.
  2929. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2930. ParamsTeamsOrParallel, /*OpenMPCaptureLevel=*/2);
  2931. break;
  2932. }
  2933. case OMPD_target:
  2934. case OMPD_target_simd: {
  2935. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
  2936. QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
  2937. QualType KmpInt32PtrTy =
  2938. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  2939. QualType Args[] = {VoidPtrTy};
  2940. FunctionProtoType::ExtProtoInfo EPI;
  2941. EPI.Variadic = true;
  2942. QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
  2943. Sema::CapturedParamNameType Params[] = {
  2944. std::make_pair(".global_tid.", KmpInt32Ty),
  2945. std::make_pair(".part_id.", KmpInt32PtrTy),
  2946. std::make_pair(".privates.", VoidPtrTy),
  2947. std::make_pair(
  2948. ".copy_fn.",
  2949. Context.getPointerType(CopyFnType).withConst().withRestrict()),
  2950. std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
  2951. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2952. };
  2953. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2954. Params, /*OpenMPCaptureLevel=*/0);
  2955. // Mark this captured region as inlined, because we don't use outlined
  2956. // function directly.
  2957. getCurCapturedRegion()->TheCapturedDecl->addAttr(
  2958. AlwaysInlineAttr::CreateImplicit(
  2959. Context, {}, AttributeCommonInfo::AS_Keyword,
  2960. AlwaysInlineAttr::Keyword_forceinline));
  2961. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2962. std::make_pair(StringRef(), QualType()),
  2963. /*OpenMPCaptureLevel=*/1);
  2964. break;
  2965. }
  2966. case OMPD_simd:
  2967. case OMPD_for:
  2968. case OMPD_for_simd:
  2969. case OMPD_sections:
  2970. case OMPD_section:
  2971. case OMPD_single:
  2972. case OMPD_master:
  2973. case OMPD_critical:
  2974. case OMPD_taskgroup:
  2975. case OMPD_distribute:
  2976. case OMPD_distribute_simd:
  2977. case OMPD_ordered:
  2978. case OMPD_atomic:
  2979. case OMPD_target_data: {
  2980. Sema::CapturedParamNameType Params[] = {
  2981. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2982. };
  2983. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2984. Params);
  2985. break;
  2986. }
  2987. case OMPD_task: {
  2988. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
  2989. QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
  2990. QualType KmpInt32PtrTy =
  2991. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  2992. QualType Args[] = {VoidPtrTy};
  2993. FunctionProtoType::ExtProtoInfo EPI;
  2994. EPI.Variadic = true;
  2995. QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
  2996. Sema::CapturedParamNameType Params[] = {
  2997. std::make_pair(".global_tid.", KmpInt32Ty),
  2998. std::make_pair(".part_id.", KmpInt32PtrTy),
  2999. std::make_pair(".privates.", VoidPtrTy),
  3000. std::make_pair(
  3001. ".copy_fn.",
  3002. Context.getPointerType(CopyFnType).withConst().withRestrict()),
  3003. std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
  3004. std::make_pair(StringRef(), QualType()) // __context with shared vars
  3005. };
  3006. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  3007. Params);
  3008. // Mark this captured region as inlined, because we don't use outlined
  3009. // function directly.
  3010. getCurCapturedRegion()->TheCapturedDecl->addAttr(
  3011. AlwaysInlineAttr::CreateImplicit(
  3012. Context, {}, AttributeCommonInfo::AS_Keyword,
  3013. AlwaysInlineAttr::Keyword_forceinline));
  3014. break;
  3015. }
  3016. case OMPD_taskloop:
  3017. case OMPD_taskloop_simd: {
  3018. QualType KmpInt32Ty =
  3019. Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1)
  3020. .withConst();
  3021. QualType KmpUInt64Ty =
  3022. Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0)
  3023. .withConst();
  3024. QualType KmpInt64Ty =
  3025. Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1)
  3026. .withConst();
  3027. QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
  3028. QualType KmpInt32PtrTy =
  3029. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  3030. QualType Args[] = {VoidPtrTy};
  3031. FunctionProtoType::ExtProtoInfo EPI;
  3032. EPI.Variadic = true;
  3033. QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
  3034. Sema::CapturedParamNameType Params[] = {
  3035. std::make_pair(".global_tid.", KmpInt32Ty),
  3036. std::make_pair(".part_id.", KmpInt32PtrTy),
  3037. std::make_pair(".privates.", VoidPtrTy),
  3038. std::make_pair(
  3039. ".copy_fn.",
  3040. Context.getPointerType(CopyFnType).withConst().withRestrict()),
  3041. std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
  3042. std::make_pair(".lb.", KmpUInt64Ty),
  3043. std::make_pair(".ub.", KmpUInt64Ty),
  3044. std::make_pair(".st.", KmpInt64Ty),
  3045. std::make_pair(".liter.", KmpInt32Ty),
  3046. std::make_pair(".reductions.", VoidPtrTy),
  3047. std::make_pair(StringRef(), QualType()) // __context with shared vars
  3048. };
  3049. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  3050. Params);
  3051. // Mark this captured region as inlined, because we don't use outlined
  3052. // function directly.
  3053. getCurCapturedRegion()->TheCapturedDecl->addAttr(
  3054. AlwaysInlineAttr::CreateImplicit(
  3055. Context, {}, AttributeCommonInfo::AS_Keyword,
  3056. AlwaysInlineAttr::Keyword_forceinline));
  3057. break;
  3058. }
  3059. case OMPD_distribute_parallel_for_simd:
  3060. case OMPD_distribute_parallel_for: {
  3061. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
  3062. QualType KmpInt32PtrTy =
  3063. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  3064. Sema::CapturedParamNameType Params[] = {
  3065. std::make_pair(".global_tid.", KmpInt32PtrTy),
  3066. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  3067. std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
  3068. std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
  3069. std::make_pair(StringRef(), QualType()) // __context with shared vars
  3070. };
  3071. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  3072. Params);
  3073. break;
  3074. }
  3075. case OMPD_target_teams_distribute_parallel_for:
  3076. case OMPD_target_teams_distribute_parallel_for_simd: {
  3077. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
  3078. QualType KmpInt32PtrTy =
  3079. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  3080. QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
  3081. QualType Args[] = {VoidPtrTy};
  3082. FunctionProtoType::ExtProtoInfo EPI;
  3083. EPI.Variadic = true;
  3084. QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
  3085. Sema::CapturedParamNameType Params[] = {
  3086. std::make_pair(".global_tid.", KmpInt32Ty),
  3087. std::make_pair(".part_id.", KmpInt32PtrTy),
  3088. std::make_pair(".privates.", VoidPtrTy),
  3089. std::make_pair(
  3090. ".copy_fn.",
  3091. Context.getPointerType(CopyFnType).withConst().withRestrict()),
  3092. std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
  3093. std::make_pair(StringRef(), QualType()) // __context with shared vars
  3094. };
  3095. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  3096. Params, /*OpenMPCaptureLevel=*/0);
  3097. // Mark this captured region as inlined, because we don't use outlined
  3098. // function directly.
  3099. getCurCapturedRegion()->TheCapturedDecl->addAttr(
  3100. AlwaysInlineAttr::CreateImplicit(
  3101. Context, {}, AttributeCommonInfo::AS_Keyword,
  3102. AlwaysInlineAttr::Keyword_forceinline));
  3103. Sema::CapturedParamNameType ParamsTarget[] = {
  3104. std::make_pair(StringRef(), QualType()) // __context with shared vars
  3105. };
  3106. // Start a captured region for 'target' with no implicit parameters.
  3107. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  3108. ParamsTarget, /*OpenMPCaptureLevel=*/1);
  3109. Sema::CapturedParamNameType ParamsTeams[] = {
  3110. std::make_pair(".global_tid.", KmpInt32PtrTy),
  3111. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  3112. std::make_pair(StringRef(), QualType()) // __context with shared vars
  3113. };
  3114. // Start a captured region for 'target' with no implicit parameters.
  3115. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  3116. ParamsTeams, /*OpenMPCaptureLevel=*/2);
  3117. Sema::CapturedParamNameType ParamsParallel[] = {
  3118. std::make_pair(".global_tid.", KmpInt32PtrTy),
  3119. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  3120. std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
  3121. std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
  3122. std::make_pair(StringRef(), QualType()) // __context with shared vars
  3123. };
  3124. // Start a captured region for 'teams' or 'parallel'. Both regions have
  3125. // the same implicit parameters.
  3126. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  3127. ParamsParallel, /*OpenMPCaptureLevel=*/3);
  3128. break;
  3129. }
  3130. case OMPD_teams_distribute_parallel_for:
  3131. case OMPD_teams_distribute_parallel_for_simd: {
  3132. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
  3133. QualType KmpInt32PtrTy =
  3134. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  3135. Sema::CapturedParamNameType ParamsTeams[] = {
  3136. std::make_pair(".global_tid.", KmpInt32PtrTy),
  3137. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  3138. std::make_pair(StringRef(), QualType()) // __context with shared vars
  3139. };
  3140. // Start a captured region for 'target' with no implicit parameters.
  3141. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  3142. ParamsTeams, /*OpenMPCaptureLevel=*/0);
  3143. Sema::CapturedParamNameType ParamsParallel[] = {
  3144. std::make_pair(".global_tid.", KmpInt32PtrTy),
  3145. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  3146. std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
  3147. std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
  3148. std::make_pair(StringRef(), QualType()) // __context with shared vars
  3149. };
  3150. // Start a captured region for 'teams' or 'parallel'. Both regions have
  3151. // the same implicit parameters.
  3152. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  3153. ParamsParallel, /*OpenMPCaptureLevel=*/1);
  3154. break;
  3155. }
  3156. case OMPD_target_update:
  3157. case OMPD_target_enter_data:
  3158. case OMPD_target_exit_data: {
  3159. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
  3160. QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
  3161. QualType KmpInt32PtrTy =
  3162. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  3163. QualType Args[] = {VoidPtrTy};
  3164. FunctionProtoType::ExtProtoInfo EPI;
  3165. EPI.Variadic = true;
  3166. QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
  3167. Sema::CapturedParamNameType Params[] = {
  3168. std::make_pair(".global_tid.", KmpInt32Ty),
  3169. std::make_pair(".part_id.", KmpInt32PtrTy),
  3170. std::make_pair(".privates.", VoidPtrTy),
  3171. std::make_pair(
  3172. ".copy_fn.",
  3173. Context.getPointerType(CopyFnType).withConst().withRestrict()),
  3174. std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
  3175. std::make_pair(StringRef(), QualType()) // __context with shared vars
  3176. };
  3177. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  3178. Params);
  3179. // Mark this captured region as inlined, because we don't use outlined
  3180. // function directly.
  3181. getCurCapturedRegion()->TheCapturedDecl->addAttr(
  3182. AlwaysInlineAttr::CreateImplicit(
  3183. Context, {}, AttributeCommonInfo::AS_Keyword,
  3184. AlwaysInlineAttr::Keyword_forceinline));
  3185. break;
  3186. }
  3187. case OMPD_threadprivate:
  3188. case OMPD_allocate:
  3189. case OMPD_taskyield:
  3190. case OMPD_barrier:
  3191. case OMPD_taskwait:
  3192. case OMPD_cancellation_point:
  3193. case OMPD_cancel:
  3194. case OMPD_flush:
  3195. case OMPD_declare_reduction:
  3196. case OMPD_declare_mapper:
  3197. case OMPD_declare_simd:
  3198. case OMPD_declare_target:
  3199. case OMPD_end_declare_target:
  3200. case OMPD_requires:
  3201. case OMPD_declare_variant:
  3202. llvm_unreachable("OpenMP Directive is not allowed");
  3203. case OMPD_unknown:
  3204. llvm_unreachable("Unknown OpenMP directive");
  3205. }
  3206. }
  3207. int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) {
  3208. SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
  3209. getOpenMPCaptureRegions(CaptureRegions, DKind);
  3210. return CaptureRegions.size();
  3211. }
  3212. static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
  3213. Expr *CaptureExpr, bool WithInit,
  3214. bool AsExpression) {
  3215. assert(CaptureExpr);
  3216. ASTContext &C = S.getASTContext();
  3217. Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
  3218. QualType Ty = Init->getType();
  3219. if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
  3220. if (S.getLangOpts().CPlusPlus) {
  3221. Ty = C.getLValueReferenceType(Ty);
  3222. } else {
  3223. Ty = C.getPointerType(Ty);
  3224. ExprResult Res =
  3225. S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
  3226. if (!Res.isUsable())
  3227. return nullptr;
  3228. Init = Res.get();
  3229. }
  3230. WithInit = true;
  3231. }
  3232. auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty,
  3233. CaptureExpr->getBeginLoc());
  3234. if (!WithInit)
  3235. CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C));
  3236. S.CurContext->addHiddenDecl(CED);
  3237. S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false);
  3238. return CED;
  3239. }
  3240. static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
  3241. bool WithInit) {
  3242. OMPCapturedExprDecl *CD;
  3243. if (VarDecl *VD = S.isOpenMPCapturedDecl(D))
  3244. CD = cast<OMPCapturedExprDecl>(VD);
  3245. else
  3246. CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
  3247. /*AsExpression=*/false);
  3248. return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
  3249. CaptureExpr->getExprLoc());
  3250. }
  3251. static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
  3252. CaptureExpr = S.DefaultLvalueConversion(CaptureExpr).get();
  3253. if (!Ref) {
  3254. OMPCapturedExprDecl *CD = buildCaptureDecl(
  3255. S, &S.getASTContext().Idents.get(".capture_expr."), CaptureExpr,
  3256. /*WithInit=*/true, /*AsExpression=*/true);
  3257. Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
  3258. CaptureExpr->getExprLoc());
  3259. }
  3260. ExprResult Res = Ref;
  3261. if (!S.getLangOpts().CPlusPlus &&
  3262. CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
  3263. Ref->getType()->isPointerType()) {
  3264. Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
  3265. if (!Res.isUsable())
  3266. return ExprError();
  3267. }
  3268. return S.DefaultLvalueConversion(Res.get());
  3269. }
  3270. namespace {
  3271. // OpenMP directives parsed in this section are represented as a
  3272. // CapturedStatement with an associated statement. If a syntax error
  3273. // is detected during the parsing of the associated statement, the
  3274. // compiler must abort processing and close the CapturedStatement.
  3275. //
  3276. // Combined directives such as 'target parallel' have more than one
  3277. // nested CapturedStatements. This RAII ensures that we unwind out
  3278. // of all the nested CapturedStatements when an error is found.
  3279. class CaptureRegionUnwinderRAII {
  3280. private:
  3281. Sema &S;
  3282. bool &ErrorFound;
  3283. OpenMPDirectiveKind DKind = OMPD_unknown;
  3284. public:
  3285. CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound,
  3286. OpenMPDirectiveKind DKind)
  3287. : S(S), ErrorFound(ErrorFound), DKind(DKind) {}
  3288. ~CaptureRegionUnwinderRAII() {
  3289. if (ErrorFound) {
  3290. int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind);
  3291. while (--ThisCaptureLevel >= 0)
  3292. S.ActOnCapturedRegionError();
  3293. }
  3294. }
  3295. };
  3296. } // namespace
  3297. void Sema::tryCaptureOpenMPLambdas(ValueDecl *V) {
  3298. // Capture variables captured by reference in lambdas for target-based
  3299. // directives.
  3300. if (!CurContext->isDependentContext() &&
  3301. (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) ||
  3302. isOpenMPTargetDataManagementDirective(
  3303. DSAStack->getCurrentDirective()))) {
  3304. QualType Type = V->getType();
  3305. if (const auto *RD = Type.getCanonicalType()
  3306. .getNonReferenceType()
  3307. ->getAsCXXRecordDecl()) {
  3308. bool SavedForceCaptureByReferenceInTargetExecutable =
  3309. DSAStack->isForceCaptureByReferenceInTargetExecutable();
  3310. DSAStack->setForceCaptureByReferenceInTargetExecutable(
  3311. /*V=*/true);
  3312. if (RD->isLambda()) {
  3313. llvm::DenseMap<const VarDecl *, FieldDecl *> Captures;
  3314. FieldDecl *ThisCapture;
  3315. RD->getCaptureFields(Captures, ThisCapture);
  3316. for (const LambdaCapture &LC : RD->captures()) {
  3317. if (LC.getCaptureKind() == LCK_ByRef) {
  3318. VarDecl *VD = LC.getCapturedVar();
  3319. DeclContext *VDC = VD->getDeclContext();
  3320. if (!VDC->Encloses(CurContext))
  3321. continue;
  3322. MarkVariableReferenced(LC.getLocation(), VD);
  3323. } else if (LC.getCaptureKind() == LCK_This) {
  3324. QualType ThisTy = getCurrentThisType();
  3325. if (!ThisTy.isNull() &&
  3326. Context.typesAreCompatible(ThisTy, ThisCapture->getType()))
  3327. CheckCXXThisCapture(LC.getLocation());
  3328. }
  3329. }
  3330. }
  3331. DSAStack->setForceCaptureByReferenceInTargetExecutable(
  3332. SavedForceCaptureByReferenceInTargetExecutable);
  3333. }
  3334. }
  3335. }
  3336. StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
  3337. ArrayRef<OMPClause *> Clauses) {
  3338. bool ErrorFound = false;
  3339. CaptureRegionUnwinderRAII CaptureRegionUnwinder(
  3340. *this, ErrorFound, DSAStack->getCurrentDirective());
  3341. if (!S.isUsable()) {
  3342. ErrorFound = true;
  3343. return StmtError();
  3344. }
  3345. SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
  3346. getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective());
  3347. OMPOrderedClause *OC = nullptr;
  3348. OMPScheduleClause *SC = nullptr;
  3349. SmallVector<const OMPLinearClause *, 4> LCs;
  3350. SmallVector<const OMPClauseWithPreInit *, 4> PICs;
  3351. // This is required for proper codegen.
  3352. for (OMPClause *Clause : Clauses) {
  3353. if (isOpenMPTaskingDirective(DSAStack->getCurrentDirective()) &&
  3354. Clause->getClauseKind() == OMPC_in_reduction) {
  3355. // Capture taskgroup task_reduction descriptors inside the tasking regions
  3356. // with the corresponding in_reduction items.
  3357. auto *IRC = cast<OMPInReductionClause>(Clause);
  3358. for (Expr *E : IRC->taskgroup_descriptors())
  3359. if (E)
  3360. MarkDeclarationsReferencedInExpr(E);
  3361. }
  3362. if (isOpenMPPrivate(Clause->getClauseKind()) ||
  3363. Clause->getClauseKind() == OMPC_copyprivate ||
  3364. (getLangOpts().OpenMPUseTLS &&
  3365. getASTContext().getTargetInfo().isTLSSupported() &&
  3366. Clause->getClauseKind() == OMPC_copyin)) {
  3367. DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
  3368. // Mark all variables in private list clauses as used in inner region.
  3369. for (Stmt *VarRef : Clause->children()) {
  3370. if (auto *E = cast_or_null<Expr>(VarRef)) {
  3371. MarkDeclarationsReferencedInExpr(E);
  3372. }
  3373. }
  3374. DSAStack->setForceVarCapturing(/*V=*/false);
  3375. } else if (CaptureRegions.size() > 1 ||
  3376. CaptureRegions.back() != OMPD_unknown) {
  3377. if (auto *C = OMPClauseWithPreInit::get(Clause))
  3378. PICs.push_back(C);
  3379. if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
  3380. if (Expr *E = C->getPostUpdateExpr())
  3381. MarkDeclarationsReferencedInExpr(E);
  3382. }
  3383. }
  3384. if (Clause->getClauseKind() == OMPC_schedule)
  3385. SC = cast<OMPScheduleClause>(Clause);
  3386. else if (Clause->getClauseKind() == OMPC_ordered)
  3387. OC = cast<OMPOrderedClause>(Clause);
  3388. else if (Clause->getClauseKind() == OMPC_linear)
  3389. LCs.push_back(cast<OMPLinearClause>(Clause));
  3390. }
  3391. // OpenMP, 2.7.1 Loop Construct, Restrictions
  3392. // The nonmonotonic modifier cannot be specified if an ordered clause is
  3393. // specified.
  3394. if (SC &&
  3395. (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
  3396. SC->getSecondScheduleModifier() ==
  3397. OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
  3398. OC) {
  3399. Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
  3400. ? SC->getFirstScheduleModifierLoc()
  3401. : SC->getSecondScheduleModifierLoc(),
  3402. diag::err_omp_schedule_nonmonotonic_ordered)
  3403. << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
  3404. ErrorFound = true;
  3405. }
  3406. if (!LCs.empty() && OC && OC->getNumForLoops()) {
  3407. for (const OMPLinearClause *C : LCs) {
  3408. Diag(C->getBeginLoc(), diag::err_omp_linear_ordered)
  3409. << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
  3410. }
  3411. ErrorFound = true;
  3412. }
  3413. if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
  3414. isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
  3415. OC->getNumForLoops()) {
  3416. Diag(OC->getBeginLoc(), diag::err_omp_ordered_simd)
  3417. << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
  3418. ErrorFound = true;
  3419. }
  3420. if (ErrorFound) {
  3421. return StmtError();
  3422. }
  3423. StmtResult SR = S;
  3424. unsigned CompletedRegions = 0;
  3425. for (OpenMPDirectiveKind ThisCaptureRegion : llvm::reverse(CaptureRegions)) {
  3426. // Mark all variables in private list clauses as used in inner region.
  3427. // Required for proper codegen of combined directives.
  3428. // TODO: add processing for other clauses.
  3429. if (ThisCaptureRegion != OMPD_unknown) {
  3430. for (const clang::OMPClauseWithPreInit *C : PICs) {
  3431. OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion();
  3432. // Find the particular capture region for the clause if the
  3433. // directive is a combined one with multiple capture regions.
  3434. // If the directive is not a combined one, the capture region
  3435. // associated with the clause is OMPD_unknown and is generated
  3436. // only once.
  3437. if (CaptureRegion == ThisCaptureRegion ||
  3438. CaptureRegion == OMPD_unknown) {
  3439. if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
  3440. for (Decl *D : DS->decls())
  3441. MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
  3442. }
  3443. }
  3444. }
  3445. }
  3446. if (++CompletedRegions == CaptureRegions.size())
  3447. DSAStack->setBodyComplete();
  3448. SR = ActOnCapturedRegionEnd(SR.get());
  3449. }
  3450. return SR;
  3451. }
  3452. static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion,
  3453. OpenMPDirectiveKind CancelRegion,
  3454. SourceLocation StartLoc) {
  3455. // CancelRegion is only needed for cancel and cancellation_point.
  3456. if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point)
  3457. return false;
  3458. if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for ||
  3459. CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup)
  3460. return false;
  3461. SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region)
  3462. << getOpenMPDirectiveName(CancelRegion);
  3463. return true;
  3464. }
  3465. static bool checkNestingOfRegions(Sema &SemaRef, const DSAStackTy *Stack,
  3466. OpenMPDirectiveKind CurrentRegion,
  3467. const DeclarationNameInfo &CurrentName,
  3468. OpenMPDirectiveKind CancelRegion,
  3469. SourceLocation StartLoc) {
  3470. if (Stack->getCurScope()) {
  3471. OpenMPDirectiveKind ParentRegion = Stack->getParentDirective();
  3472. OpenMPDirectiveKind OffendingRegion = ParentRegion;
  3473. bool NestingProhibited = false;
  3474. bool CloseNesting = true;
  3475. bool OrphanSeen = false;
  3476. enum {
  3477. NoRecommend,
  3478. ShouldBeInParallelRegion,
  3479. ShouldBeInOrderedRegion,
  3480. ShouldBeInTargetRegion,
  3481. ShouldBeInTeamsRegion
  3482. } Recommend = NoRecommend;
  3483. if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) {
  3484. // OpenMP [2.16, Nesting of Regions]
  3485. // OpenMP constructs may not be nested inside a simd region.
  3486. // OpenMP [2.8.1,simd Construct, Restrictions]
  3487. // An ordered construct with the simd clause is the only OpenMP
  3488. // construct that can appear in the simd region.
  3489. // Allowing a SIMD construct nested in another SIMD construct is an
  3490. // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
  3491. // message.
  3492. SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
  3493. ? diag::err_omp_prohibited_region_simd
  3494. : diag::warn_omp_nesting_simd);
  3495. return CurrentRegion != OMPD_simd;
  3496. }
  3497. if (ParentRegion == OMPD_atomic) {
  3498. // OpenMP [2.16, Nesting of Regions]
  3499. // OpenMP constructs may not be nested inside an atomic region.
  3500. SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
  3501. return true;
  3502. }
  3503. if (CurrentRegion == OMPD_section) {
  3504. // OpenMP [2.7.2, sections Construct, Restrictions]
  3505. // Orphaned section directives are prohibited. That is, the section
  3506. // directives must appear within the sections construct and must not be
  3507. // encountered elsewhere in the sections region.
  3508. if (ParentRegion != OMPD_sections &&
  3509. ParentRegion != OMPD_parallel_sections) {
  3510. SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
  3511. << (ParentRegion != OMPD_unknown)
  3512. << getOpenMPDirectiveName(ParentRegion);
  3513. return true;
  3514. }
  3515. return false;
  3516. }
  3517. // Allow some constructs (except teams and cancellation constructs) to be
  3518. // orphaned (they could be used in functions, called from OpenMP regions
  3519. // with the required preconditions).
  3520. if (ParentRegion == OMPD_unknown &&
  3521. !isOpenMPNestingTeamsDirective(CurrentRegion) &&
  3522. CurrentRegion != OMPD_cancellation_point &&
  3523. CurrentRegion != OMPD_cancel)
  3524. return false;
  3525. if (CurrentRegion == OMPD_cancellation_point ||
  3526. CurrentRegion == OMPD_cancel) {
  3527. // OpenMP [2.16, Nesting of Regions]
  3528. // A cancellation point construct for which construct-type-clause is
  3529. // taskgroup must be nested inside a task construct. A cancellation
  3530. // point construct for which construct-type-clause is not taskgroup must
  3531. // be closely nested inside an OpenMP construct that matches the type
  3532. // specified in construct-type-clause.
  3533. // A cancel construct for which construct-type-clause is taskgroup must be
  3534. // nested inside a task construct. A cancel construct for which
  3535. // construct-type-clause is not taskgroup must be closely nested inside an
  3536. // OpenMP construct that matches the type specified in
  3537. // construct-type-clause.
  3538. NestingProhibited =
  3539. !((CancelRegion == OMPD_parallel &&
  3540. (ParentRegion == OMPD_parallel ||
  3541. ParentRegion == OMPD_target_parallel)) ||
  3542. (CancelRegion == OMPD_for &&
  3543. (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
  3544. ParentRegion == OMPD_target_parallel_for ||
  3545. ParentRegion == OMPD_distribute_parallel_for ||
  3546. ParentRegion == OMPD_teams_distribute_parallel_for ||
  3547. ParentRegion == OMPD_target_teams_distribute_parallel_for)) ||
  3548. (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
  3549. (CancelRegion == OMPD_sections &&
  3550. (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
  3551. ParentRegion == OMPD_parallel_sections)));
  3552. OrphanSeen = ParentRegion == OMPD_unknown;
  3553. } else if (CurrentRegion == OMPD_master) {
  3554. // OpenMP [2.16, Nesting of Regions]
  3555. // A master region may not be closely nested inside a worksharing,
  3556. // atomic, or explicit task region.
  3557. NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
  3558. isOpenMPTaskingDirective(ParentRegion);
  3559. } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
  3560. // OpenMP [2.16, Nesting of Regions]
  3561. // A critical region may not be nested (closely or otherwise) inside a
  3562. // critical region with the same name. Note that this restriction is not
  3563. // sufficient to prevent deadlock.
  3564. SourceLocation PreviousCriticalLoc;
  3565. bool DeadLock = Stack->hasDirective(
  3566. [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
  3567. const DeclarationNameInfo &DNI,
  3568. SourceLocation Loc) {
  3569. if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
  3570. PreviousCriticalLoc = Loc;
  3571. return true;
  3572. }
  3573. return false;
  3574. },
  3575. false /* skip top directive */);
  3576. if (DeadLock) {
  3577. SemaRef.Diag(StartLoc,
  3578. diag::err_omp_prohibited_region_critical_same_name)
  3579. << CurrentName.getName();
  3580. if (PreviousCriticalLoc.isValid())
  3581. SemaRef.Diag(PreviousCriticalLoc,
  3582. diag::note_omp_previous_critical_region);
  3583. return true;
  3584. }
  3585. } else if (CurrentRegion == OMPD_barrier) {
  3586. // OpenMP [2.16, Nesting of Regions]
  3587. // A barrier region may not be closely nested inside a worksharing,
  3588. // explicit task, critical, ordered, atomic, or master region.
  3589. NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
  3590. isOpenMPTaskingDirective(ParentRegion) ||
  3591. ParentRegion == OMPD_master ||
  3592. ParentRegion == OMPD_critical ||
  3593. ParentRegion == OMPD_ordered;
  3594. } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
  3595. !isOpenMPParallelDirective(CurrentRegion) &&
  3596. !isOpenMPTeamsDirective(CurrentRegion)) {
  3597. // OpenMP [2.16, Nesting of Regions]
  3598. // A worksharing region may not be closely nested inside a worksharing,
  3599. // explicit task, critical, ordered, atomic, or master region.
  3600. NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
  3601. isOpenMPTaskingDirective(ParentRegion) ||
  3602. ParentRegion == OMPD_master ||
  3603. ParentRegion == OMPD_critical ||
  3604. ParentRegion == OMPD_ordered;
  3605. Recommend = ShouldBeInParallelRegion;
  3606. } else if (CurrentRegion == OMPD_ordered) {
  3607. // OpenMP [2.16, Nesting of Regions]
  3608. // An ordered region may not be closely nested inside a critical,
  3609. // atomic, or explicit task region.
  3610. // An ordered region must be closely nested inside a loop region (or
  3611. // parallel loop region) with an ordered clause.
  3612. // OpenMP [2.8.1,simd Construct, Restrictions]
  3613. // An ordered construct with the simd clause is the only OpenMP construct
  3614. // that can appear in the simd region.
  3615. NestingProhibited = ParentRegion == OMPD_critical ||
  3616. isOpenMPTaskingDirective(ParentRegion) ||
  3617. !(isOpenMPSimdDirective(ParentRegion) ||
  3618. Stack->isParentOrderedRegion());
  3619. Recommend = ShouldBeInOrderedRegion;
  3620. } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
  3621. // OpenMP [2.16, Nesting of Regions]
  3622. // If specified, a teams construct must be contained within a target
  3623. // construct.
  3624. NestingProhibited =
  3625. (SemaRef.LangOpts.OpenMP <= 45 && ParentRegion != OMPD_target) ||
  3626. (SemaRef.LangOpts.OpenMP >= 50 && ParentRegion != OMPD_unknown &&
  3627. ParentRegion != OMPD_target);
  3628. OrphanSeen = ParentRegion == OMPD_unknown;
  3629. Recommend = ShouldBeInTargetRegion;
  3630. }
  3631. if (!NestingProhibited &&
  3632. !isOpenMPTargetExecutionDirective(CurrentRegion) &&
  3633. !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
  3634. (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
  3635. // OpenMP [2.16, Nesting of Regions]
  3636. // distribute, parallel, parallel sections, parallel workshare, and the
  3637. // parallel loop and parallel loop SIMD constructs are the only OpenMP
  3638. // constructs that can be closely nested in the teams region.
  3639. NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
  3640. !isOpenMPDistributeDirective(CurrentRegion);
  3641. Recommend = ShouldBeInParallelRegion;
  3642. }
  3643. if (!NestingProhibited &&
  3644. isOpenMPNestingDistributeDirective(CurrentRegion)) {
  3645. // OpenMP 4.5 [2.17 Nesting of Regions]
  3646. // The region associated with the distribute construct must be strictly
  3647. // nested inside a teams region
  3648. NestingProhibited =
  3649. (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
  3650. Recommend = ShouldBeInTeamsRegion;
  3651. }
  3652. if (!NestingProhibited &&
  3653. (isOpenMPTargetExecutionDirective(CurrentRegion) ||
  3654. isOpenMPTargetDataManagementDirective(CurrentRegion))) {
  3655. // OpenMP 4.5 [2.17 Nesting of Regions]
  3656. // If a target, target update, target data, target enter data, or
  3657. // target exit data construct is encountered during execution of a
  3658. // target region, the behavior is unspecified.
  3659. NestingProhibited = Stack->hasDirective(
  3660. [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
  3661. SourceLocation) {
  3662. if (isOpenMPTargetExecutionDirective(K)) {
  3663. OffendingRegion = K;
  3664. return true;
  3665. }
  3666. return false;
  3667. },
  3668. false /* don't skip top directive */);
  3669. CloseNesting = false;
  3670. }
  3671. if (NestingProhibited) {
  3672. if (OrphanSeen) {
  3673. SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
  3674. << getOpenMPDirectiveName(CurrentRegion) << Recommend;
  3675. } else {
  3676. SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
  3677. << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
  3678. << Recommend << getOpenMPDirectiveName(CurrentRegion);
  3679. }
  3680. return true;
  3681. }
  3682. }
  3683. return false;
  3684. }
  3685. static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
  3686. ArrayRef<OMPClause *> Clauses,
  3687. ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
  3688. bool ErrorFound = false;
  3689. unsigned NamedModifiersNumber = 0;
  3690. SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers(
  3691. OMPD_unknown + 1);
  3692. SmallVector<SourceLocation, 4> NameModifierLoc;
  3693. for (const OMPClause *C : Clauses) {
  3694. if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
  3695. // At most one if clause without a directive-name-modifier can appear on
  3696. // the directive.
  3697. OpenMPDirectiveKind CurNM = IC->getNameModifier();
  3698. if (FoundNameModifiers[CurNM]) {
  3699. S.Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
  3700. << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
  3701. << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
  3702. ErrorFound = true;
  3703. } else if (CurNM != OMPD_unknown) {
  3704. NameModifierLoc.push_back(IC->getNameModifierLoc());
  3705. ++NamedModifiersNumber;
  3706. }
  3707. FoundNameModifiers[CurNM] = IC;
  3708. if (CurNM == OMPD_unknown)
  3709. continue;
  3710. // Check if the specified name modifier is allowed for the current
  3711. // directive.
  3712. // At most one if clause with the particular directive-name-modifier can
  3713. // appear on the directive.
  3714. bool MatchFound = false;
  3715. for (auto NM : AllowedNameModifiers) {
  3716. if (CurNM == NM) {
  3717. MatchFound = true;
  3718. break;
  3719. }
  3720. }
  3721. if (!MatchFound) {
  3722. S.Diag(IC->getNameModifierLoc(),
  3723. diag::err_omp_wrong_if_directive_name_modifier)
  3724. << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
  3725. ErrorFound = true;
  3726. }
  3727. }
  3728. }
  3729. // If any if clause on the directive includes a directive-name-modifier then
  3730. // all if clauses on the directive must include a directive-name-modifier.
  3731. if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
  3732. if (NamedModifiersNumber == AllowedNameModifiers.size()) {
  3733. S.Diag(FoundNameModifiers[OMPD_unknown]->getBeginLoc(),
  3734. diag::err_omp_no_more_if_clause);
  3735. } else {
  3736. std::string Values;
  3737. std::string Sep(", ");
  3738. unsigned AllowedCnt = 0;
  3739. unsigned TotalAllowedNum =
  3740. AllowedNameModifiers.size() - NamedModifiersNumber;
  3741. for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
  3742. ++Cnt) {
  3743. OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
  3744. if (!FoundNameModifiers[NM]) {
  3745. Values += "'";
  3746. Values += getOpenMPDirectiveName(NM);
  3747. Values += "'";
  3748. if (AllowedCnt + 2 == TotalAllowedNum)
  3749. Values += " or ";
  3750. else if (AllowedCnt + 1 != TotalAllowedNum)
  3751. Values += Sep;
  3752. ++AllowedCnt;
  3753. }
  3754. }
  3755. S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getBeginLoc(),
  3756. diag::err_omp_unnamed_if_clause)
  3757. << (TotalAllowedNum > 1) << Values;
  3758. }
  3759. for (SourceLocation Loc : NameModifierLoc) {
  3760. S.Diag(Loc, diag::note_omp_previous_named_if_clause);
  3761. }
  3762. ErrorFound = true;
  3763. }
  3764. return ErrorFound;
  3765. }
  3766. static std::pair<ValueDecl *, bool>
  3767. getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
  3768. SourceRange &ERange, bool AllowArraySection = false) {
  3769. if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
  3770. RefExpr->containsUnexpandedParameterPack())
  3771. return std::make_pair(nullptr, true);
  3772. // OpenMP [3.1, C/C++]
  3773. // A list item is a variable name.
  3774. // OpenMP [2.9.3.3, Restrictions, p.1]
  3775. // A variable that is part of another variable (as an array or
  3776. // structure element) cannot appear in a private clause.
  3777. RefExpr = RefExpr->IgnoreParens();
  3778. enum {
  3779. NoArrayExpr = -1,
  3780. ArraySubscript = 0,
  3781. OMPArraySection = 1
  3782. } IsArrayExpr = NoArrayExpr;
  3783. if (AllowArraySection) {
  3784. if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
  3785. Expr *Base = ASE->getBase()->IgnoreParenImpCasts();
  3786. while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
  3787. Base = TempASE->getBase()->IgnoreParenImpCasts();
  3788. RefExpr = Base;
  3789. IsArrayExpr = ArraySubscript;
  3790. } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
  3791. Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
  3792. while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
  3793. Base = TempOASE->getBase()->IgnoreParenImpCasts();
  3794. while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
  3795. Base = TempASE->getBase()->IgnoreParenImpCasts();
  3796. RefExpr = Base;
  3797. IsArrayExpr = OMPArraySection;
  3798. }
  3799. }
  3800. ELoc = RefExpr->getExprLoc();
  3801. ERange = RefExpr->getSourceRange();
  3802. RefExpr = RefExpr->IgnoreParenImpCasts();
  3803. auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
  3804. auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
  3805. if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
  3806. (S.getCurrentThisType().isNull() || !ME ||
  3807. !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
  3808. !isa<FieldDecl>(ME->getMemberDecl()))) {
  3809. if (IsArrayExpr != NoArrayExpr) {
  3810. S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr
  3811. << ERange;
  3812. } else {
  3813. S.Diag(ELoc,
  3814. AllowArraySection
  3815. ? diag::err_omp_expected_var_name_member_expr_or_array_item
  3816. : diag::err_omp_expected_var_name_member_expr)
  3817. << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
  3818. }
  3819. return std::make_pair(nullptr, false);
  3820. }
  3821. return std::make_pair(
  3822. getCanonicalDecl(DE ? DE->getDecl() : ME->getMemberDecl()), false);
  3823. }
  3824. static void checkAllocateClauses(Sema &S, DSAStackTy *Stack,
  3825. ArrayRef<OMPClause *> Clauses) {
  3826. assert(!S.CurContext->isDependentContext() &&
  3827. "Expected non-dependent context.");
  3828. auto AllocateRange =
  3829. llvm::make_filter_range(Clauses, OMPAllocateClause::classof);
  3830. llvm::DenseMap<CanonicalDeclPtr<Decl>, CanonicalDeclPtr<VarDecl>>
  3831. DeclToCopy;
  3832. auto PrivateRange = llvm::make_filter_range(Clauses, [](const OMPClause *C) {
  3833. return isOpenMPPrivate(C->getClauseKind());
  3834. });
  3835. for (OMPClause *Cl : PrivateRange) {
  3836. MutableArrayRef<Expr *>::iterator I, It, Et;
  3837. if (Cl->getClauseKind() == OMPC_private) {
  3838. auto *PC = cast<OMPPrivateClause>(Cl);
  3839. I = PC->private_copies().begin();
  3840. It = PC->varlist_begin();
  3841. Et = PC->varlist_end();
  3842. } else if (Cl->getClauseKind() == OMPC_firstprivate) {
  3843. auto *PC = cast<OMPFirstprivateClause>(Cl);
  3844. I = PC->private_copies().begin();
  3845. It = PC->varlist_begin();
  3846. Et = PC->varlist_end();
  3847. } else if (Cl->getClauseKind() == OMPC_lastprivate) {
  3848. auto *PC = cast<OMPLastprivateClause>(Cl);
  3849. I = PC->private_copies().begin();
  3850. It = PC->varlist_begin();
  3851. Et = PC->varlist_end();
  3852. } else if (Cl->getClauseKind() == OMPC_linear) {
  3853. auto *PC = cast<OMPLinearClause>(Cl);
  3854. I = PC->privates().begin();
  3855. It = PC->varlist_begin();
  3856. Et = PC->varlist_end();
  3857. } else if (Cl->getClauseKind() == OMPC_reduction) {
  3858. auto *PC = cast<OMPReductionClause>(Cl);
  3859. I = PC->privates().begin();
  3860. It = PC->varlist_begin();
  3861. Et = PC->varlist_end();
  3862. } else if (Cl->getClauseKind() == OMPC_task_reduction) {
  3863. auto *PC = cast<OMPTaskReductionClause>(Cl);
  3864. I = PC->privates().begin();
  3865. It = PC->varlist_begin();
  3866. Et = PC->varlist_end();
  3867. } else if (Cl->getClauseKind() == OMPC_in_reduction) {
  3868. auto *PC = cast<OMPInReductionClause>(Cl);
  3869. I = PC->privates().begin();
  3870. It = PC->varlist_begin();
  3871. Et = PC->varlist_end();
  3872. } else {
  3873. llvm_unreachable("Expected private clause.");
  3874. }
  3875. for (Expr *E : llvm::make_range(It, Et)) {
  3876. if (!*I) {
  3877. ++I;
  3878. continue;
  3879. }
  3880. SourceLocation ELoc;
  3881. SourceRange ERange;
  3882. Expr *SimpleRefExpr = E;
  3883. auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
  3884. /*AllowArraySection=*/true);
  3885. DeclToCopy.try_emplace(Res.first,
  3886. cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()));
  3887. ++I;
  3888. }
  3889. }
  3890. for (OMPClause *C : AllocateRange) {
  3891. auto *AC = cast<OMPAllocateClause>(C);
  3892. OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind =
  3893. getAllocatorKind(S, Stack, AC->getAllocator());
  3894. // OpenMP, 2.11.4 allocate Clause, Restrictions.
  3895. // For task, taskloop or target directives, allocation requests to memory
  3896. // allocators with the trait access set to thread result in unspecified
  3897. // behavior.
  3898. if (AllocatorKind == OMPAllocateDeclAttr::OMPThreadMemAlloc &&
  3899. (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
  3900. isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()))) {
  3901. S.Diag(AC->getAllocator()->getExprLoc(),
  3902. diag::warn_omp_allocate_thread_on_task_target_directive)
  3903. << getOpenMPDirectiveName(Stack->getCurrentDirective());
  3904. }
  3905. for (Expr *E : AC->varlists()) {
  3906. SourceLocation ELoc;
  3907. SourceRange ERange;
  3908. Expr *SimpleRefExpr = E;
  3909. auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange);
  3910. ValueDecl *VD = Res.first;
  3911. DSAStackTy::DSAVarData Data = Stack->getTopDSA(VD, /*FromParent=*/false);
  3912. if (!isOpenMPPrivate(Data.CKind)) {
  3913. S.Diag(E->getExprLoc(),
  3914. diag::err_omp_expected_private_copy_for_allocate);
  3915. continue;
  3916. }
  3917. VarDecl *PrivateVD = DeclToCopy[VD];
  3918. if (checkPreviousOMPAllocateAttribute(S, Stack, E, PrivateVD,
  3919. AllocatorKind, AC->getAllocator()))
  3920. continue;
  3921. applyOMPAllocateAttribute(S, PrivateVD, AllocatorKind, AC->getAllocator(),
  3922. E->getSourceRange());
  3923. }
  3924. }
  3925. }
  3926. StmtResult Sema::ActOnOpenMPExecutableDirective(
  3927. OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
  3928. OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
  3929. Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
  3930. StmtResult Res = StmtError();
  3931. // First check CancelRegion which is then used in checkNestingOfRegions.
  3932. if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) ||
  3933. checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
  3934. StartLoc))
  3935. return StmtError();
  3936. llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
  3937. VarsWithInheritedDSAType VarsWithInheritedDSA;
  3938. bool ErrorFound = false;
  3939. ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
  3940. if (AStmt && !CurContext->isDependentContext()) {
  3941. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  3942. // Check default data sharing attributes for referenced variables.
  3943. DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
  3944. int ThisCaptureLevel = getOpenMPCaptureLevels(Kind);
  3945. Stmt *S = AStmt;
  3946. while (--ThisCaptureLevel >= 0)
  3947. S = cast<CapturedStmt>(S)->getCapturedStmt();
  3948. DSAChecker.Visit(S);
  3949. if (!isOpenMPTargetDataManagementDirective(Kind) &&
  3950. !isOpenMPTaskingDirective(Kind)) {
  3951. // Visit subcaptures to generate implicit clauses for captured vars.
  3952. auto *CS = cast<CapturedStmt>(AStmt);
  3953. SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
  3954. getOpenMPCaptureRegions(CaptureRegions, Kind);
  3955. // Ignore outer tasking regions for target directives.
  3956. if (CaptureRegions.size() > 1 && CaptureRegions.front() == OMPD_task)
  3957. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  3958. DSAChecker.visitSubCaptures(CS);
  3959. }
  3960. if (DSAChecker.isErrorFound())
  3961. return StmtError();
  3962. // Generate list of implicitly defined firstprivate variables.
  3963. VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
  3964. SmallVector<Expr *, 4> ImplicitFirstprivates(
  3965. DSAChecker.getImplicitFirstprivate().begin(),
  3966. DSAChecker.getImplicitFirstprivate().end());
  3967. SmallVector<Expr *, 4> ImplicitMaps(DSAChecker.getImplicitMap().begin(),
  3968. DSAChecker.getImplicitMap().end());
  3969. // Mark taskgroup task_reduction descriptors as implicitly firstprivate.
  3970. for (OMPClause *C : Clauses) {
  3971. if (auto *IRC = dyn_cast<OMPInReductionClause>(C)) {
  3972. for (Expr *E : IRC->taskgroup_descriptors())
  3973. if (E)
  3974. ImplicitFirstprivates.emplace_back(E);
  3975. }
  3976. }
  3977. if (!ImplicitFirstprivates.empty()) {
  3978. if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
  3979. ImplicitFirstprivates, SourceLocation(), SourceLocation(),
  3980. SourceLocation())) {
  3981. ClausesWithImplicit.push_back(Implicit);
  3982. ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
  3983. ImplicitFirstprivates.size();
  3984. } else {
  3985. ErrorFound = true;
  3986. }
  3987. }
  3988. if (!ImplicitMaps.empty()) {
  3989. CXXScopeSpec MapperIdScopeSpec;
  3990. DeclarationNameInfo MapperId;
  3991. if (OMPClause *Implicit = ActOnOpenMPMapClause(
  3992. llvm::None, llvm::None, MapperIdScopeSpec, MapperId,
  3993. OMPC_MAP_tofrom, /*IsMapTypeImplicit=*/true, SourceLocation(),
  3994. SourceLocation(), ImplicitMaps, OMPVarListLocTy())) {
  3995. ClausesWithImplicit.emplace_back(Implicit);
  3996. ErrorFound |=
  3997. cast<OMPMapClause>(Implicit)->varlist_size() != ImplicitMaps.size();
  3998. } else {
  3999. ErrorFound = true;
  4000. }
  4001. }
  4002. }
  4003. llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
  4004. switch (Kind) {
  4005. case OMPD_parallel:
  4006. Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
  4007. EndLoc);
  4008. AllowedNameModifiers.push_back(OMPD_parallel);
  4009. break;
  4010. case OMPD_simd:
  4011. Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
  4012. VarsWithInheritedDSA);
  4013. break;
  4014. case OMPD_for:
  4015. Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
  4016. VarsWithInheritedDSA);
  4017. break;
  4018. case OMPD_for_simd:
  4019. Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
  4020. EndLoc, VarsWithInheritedDSA);
  4021. break;
  4022. case OMPD_sections:
  4023. Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
  4024. EndLoc);
  4025. break;
  4026. case OMPD_section:
  4027. assert(ClausesWithImplicit.empty() &&
  4028. "No clauses are allowed for 'omp section' directive");
  4029. Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
  4030. break;
  4031. case OMPD_single:
  4032. Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
  4033. EndLoc);
  4034. break;
  4035. case OMPD_master:
  4036. assert(ClausesWithImplicit.empty() &&
  4037. "No clauses are allowed for 'omp master' directive");
  4038. Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
  4039. break;
  4040. case OMPD_critical:
  4041. Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
  4042. StartLoc, EndLoc);
  4043. break;
  4044. case OMPD_parallel_for:
  4045. Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
  4046. EndLoc, VarsWithInheritedDSA);
  4047. AllowedNameModifiers.push_back(OMPD_parallel);
  4048. break;
  4049. case OMPD_parallel_for_simd:
  4050. Res = ActOnOpenMPParallelForSimdDirective(
  4051. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  4052. AllowedNameModifiers.push_back(OMPD_parallel);
  4053. break;
  4054. case OMPD_parallel_sections:
  4055. Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
  4056. StartLoc, EndLoc);
  4057. AllowedNameModifiers.push_back(OMPD_parallel);
  4058. break;
  4059. case OMPD_task:
  4060. Res =
  4061. ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
  4062. AllowedNameModifiers.push_back(OMPD_task);
  4063. break;
  4064. case OMPD_taskyield:
  4065. assert(ClausesWithImplicit.empty() &&
  4066. "No clauses are allowed for 'omp taskyield' directive");
  4067. assert(AStmt == nullptr &&
  4068. "No associated statement allowed for 'omp taskyield' directive");
  4069. Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
  4070. break;
  4071. case OMPD_barrier:
  4072. assert(ClausesWithImplicit.empty() &&
  4073. "No clauses are allowed for 'omp barrier' directive");
  4074. assert(AStmt == nullptr &&
  4075. "No associated statement allowed for 'omp barrier' directive");
  4076. Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
  4077. break;
  4078. case OMPD_taskwait:
  4079. assert(ClausesWithImplicit.empty() &&
  4080. "No clauses are allowed for 'omp taskwait' directive");
  4081. assert(AStmt == nullptr &&
  4082. "No associated statement allowed for 'omp taskwait' directive");
  4083. Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
  4084. break;
  4085. case OMPD_taskgroup:
  4086. Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc,
  4087. EndLoc);
  4088. break;
  4089. case OMPD_flush:
  4090. assert(AStmt == nullptr &&
  4091. "No associated statement allowed for 'omp flush' directive");
  4092. Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
  4093. break;
  4094. case OMPD_ordered:
  4095. Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
  4096. EndLoc);
  4097. break;
  4098. case OMPD_atomic:
  4099. Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
  4100. EndLoc);
  4101. break;
  4102. case OMPD_teams:
  4103. Res =
  4104. ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
  4105. break;
  4106. case OMPD_target:
  4107. Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
  4108. EndLoc);
  4109. AllowedNameModifiers.push_back(OMPD_target);
  4110. break;
  4111. case OMPD_target_parallel:
  4112. Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
  4113. StartLoc, EndLoc);
  4114. AllowedNameModifiers.push_back(OMPD_target);
  4115. AllowedNameModifiers.push_back(OMPD_parallel);
  4116. break;
  4117. case OMPD_target_parallel_for:
  4118. Res = ActOnOpenMPTargetParallelForDirective(
  4119. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  4120. AllowedNameModifiers.push_back(OMPD_target);
  4121. AllowedNameModifiers.push_back(OMPD_parallel);
  4122. break;
  4123. case OMPD_cancellation_point:
  4124. assert(ClausesWithImplicit.empty() &&
  4125. "No clauses are allowed for 'omp cancellation point' directive");
  4126. assert(AStmt == nullptr && "No associated statement allowed for 'omp "
  4127. "cancellation point' directive");
  4128. Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
  4129. break;
  4130. case OMPD_cancel:
  4131. assert(AStmt == nullptr &&
  4132. "No associated statement allowed for 'omp cancel' directive");
  4133. Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
  4134. CancelRegion);
  4135. AllowedNameModifiers.push_back(OMPD_cancel);
  4136. break;
  4137. case OMPD_target_data:
  4138. Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
  4139. EndLoc);
  4140. AllowedNameModifiers.push_back(OMPD_target_data);
  4141. break;
  4142. case OMPD_target_enter_data:
  4143. Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
  4144. EndLoc, AStmt);
  4145. AllowedNameModifiers.push_back(OMPD_target_enter_data);
  4146. break;
  4147. case OMPD_target_exit_data:
  4148. Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
  4149. EndLoc, AStmt);
  4150. AllowedNameModifiers.push_back(OMPD_target_exit_data);
  4151. break;
  4152. case OMPD_taskloop:
  4153. Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
  4154. EndLoc, VarsWithInheritedDSA);
  4155. AllowedNameModifiers.push_back(OMPD_taskloop);
  4156. break;
  4157. case OMPD_taskloop_simd:
  4158. Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
  4159. EndLoc, VarsWithInheritedDSA);
  4160. AllowedNameModifiers.push_back(OMPD_taskloop);
  4161. break;
  4162. case OMPD_distribute:
  4163. Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
  4164. EndLoc, VarsWithInheritedDSA);
  4165. break;
  4166. case OMPD_target_update:
  4167. Res = ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc,
  4168. EndLoc, AStmt);
  4169. AllowedNameModifiers.push_back(OMPD_target_update);
  4170. break;
  4171. case OMPD_distribute_parallel_for:
  4172. Res = ActOnOpenMPDistributeParallelForDirective(
  4173. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  4174. AllowedNameModifiers.push_back(OMPD_parallel);
  4175. break;
  4176. case OMPD_distribute_parallel_for_simd:
  4177. Res = ActOnOpenMPDistributeParallelForSimdDirective(
  4178. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  4179. AllowedNameModifiers.push_back(OMPD_parallel);
  4180. break;
  4181. case OMPD_distribute_simd:
  4182. Res = ActOnOpenMPDistributeSimdDirective(
  4183. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  4184. break;
  4185. case OMPD_target_parallel_for_simd:
  4186. Res = ActOnOpenMPTargetParallelForSimdDirective(
  4187. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  4188. AllowedNameModifiers.push_back(OMPD_target);
  4189. AllowedNameModifiers.push_back(OMPD_parallel);
  4190. break;
  4191. case OMPD_target_simd:
  4192. Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
  4193. EndLoc, VarsWithInheritedDSA);
  4194. AllowedNameModifiers.push_back(OMPD_target);
  4195. break;
  4196. case OMPD_teams_distribute:
  4197. Res = ActOnOpenMPTeamsDistributeDirective(
  4198. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  4199. break;
  4200. case OMPD_teams_distribute_simd:
  4201. Res = ActOnOpenMPTeamsDistributeSimdDirective(
  4202. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  4203. break;
  4204. case OMPD_teams_distribute_parallel_for_simd:
  4205. Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
  4206. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  4207. AllowedNameModifiers.push_back(OMPD_parallel);
  4208. break;
  4209. case OMPD_teams_distribute_parallel_for:
  4210. Res = ActOnOpenMPTeamsDistributeParallelForDirective(
  4211. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  4212. AllowedNameModifiers.push_back(OMPD_parallel);
  4213. break;
  4214. case OMPD_target_teams:
  4215. Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
  4216. EndLoc);
  4217. AllowedNameModifiers.push_back(OMPD_target);
  4218. break;
  4219. case OMPD_target_teams_distribute:
  4220. Res = ActOnOpenMPTargetTeamsDistributeDirective(
  4221. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  4222. AllowedNameModifiers.push_back(OMPD_target);
  4223. break;
  4224. case OMPD_target_teams_distribute_parallel_for:
  4225. Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective(
  4226. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  4227. AllowedNameModifiers.push_back(OMPD_target);
  4228. AllowedNameModifiers.push_back(OMPD_parallel);
  4229. break;
  4230. case OMPD_target_teams_distribute_parallel_for_simd:
  4231. Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
  4232. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  4233. AllowedNameModifiers.push_back(OMPD_target);
  4234. AllowedNameModifiers.push_back(OMPD_parallel);
  4235. break;
  4236. case OMPD_target_teams_distribute_simd:
  4237. Res = ActOnOpenMPTargetTeamsDistributeSimdDirective(
  4238. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  4239. AllowedNameModifiers.push_back(OMPD_target);
  4240. break;
  4241. case OMPD_declare_target:
  4242. case OMPD_end_declare_target:
  4243. case OMPD_threadprivate:
  4244. case OMPD_allocate:
  4245. case OMPD_declare_reduction:
  4246. case OMPD_declare_mapper:
  4247. case OMPD_declare_simd:
  4248. case OMPD_requires:
  4249. case OMPD_declare_variant:
  4250. llvm_unreachable("OpenMP Directive is not allowed");
  4251. case OMPD_unknown:
  4252. llvm_unreachable("Unknown OpenMP directive");
  4253. }
  4254. ErrorFound = Res.isInvalid() || ErrorFound;
  4255. // Check variables in the clauses if default(none) was specified.
  4256. if (DSAStack->getDefaultDSA() == DSA_none) {
  4257. DSAAttrChecker DSAChecker(DSAStack, *this, nullptr);
  4258. for (OMPClause *C : Clauses) {
  4259. switch (C->getClauseKind()) {
  4260. case OMPC_num_threads:
  4261. case OMPC_dist_schedule:
  4262. // Do not analyse if no parent teams directive.
  4263. if (isOpenMPTeamsDirective(DSAStack->getCurrentDirective()))
  4264. break;
  4265. continue;
  4266. case OMPC_if:
  4267. if (isOpenMPTeamsDirective(DSAStack->getCurrentDirective()) &&
  4268. cast<OMPIfClause>(C)->getNameModifier() != OMPD_target)
  4269. break;
  4270. continue;
  4271. case OMPC_schedule:
  4272. break;
  4273. case OMPC_ordered:
  4274. case OMPC_device:
  4275. case OMPC_num_teams:
  4276. case OMPC_thread_limit:
  4277. case OMPC_priority:
  4278. case OMPC_grainsize:
  4279. case OMPC_num_tasks:
  4280. case OMPC_hint:
  4281. case OMPC_collapse:
  4282. case OMPC_safelen:
  4283. case OMPC_simdlen:
  4284. case OMPC_final:
  4285. case OMPC_default:
  4286. case OMPC_proc_bind:
  4287. case OMPC_private:
  4288. case OMPC_firstprivate:
  4289. case OMPC_lastprivate:
  4290. case OMPC_shared:
  4291. case OMPC_reduction:
  4292. case OMPC_task_reduction:
  4293. case OMPC_in_reduction:
  4294. case OMPC_linear:
  4295. case OMPC_aligned:
  4296. case OMPC_copyin:
  4297. case OMPC_copyprivate:
  4298. case OMPC_nowait:
  4299. case OMPC_untied:
  4300. case OMPC_mergeable:
  4301. case OMPC_allocate:
  4302. case OMPC_read:
  4303. case OMPC_write:
  4304. case OMPC_update:
  4305. case OMPC_capture:
  4306. case OMPC_seq_cst:
  4307. case OMPC_depend:
  4308. case OMPC_threads:
  4309. case OMPC_simd:
  4310. case OMPC_map:
  4311. case OMPC_nogroup:
  4312. case OMPC_defaultmap:
  4313. case OMPC_to:
  4314. case OMPC_from:
  4315. case OMPC_use_device_ptr:
  4316. case OMPC_is_device_ptr:
  4317. continue;
  4318. case OMPC_allocator:
  4319. case OMPC_flush:
  4320. case OMPC_threadprivate:
  4321. case OMPC_uniform:
  4322. case OMPC_unknown:
  4323. case OMPC_unified_address:
  4324. case OMPC_unified_shared_memory:
  4325. case OMPC_reverse_offload:
  4326. case OMPC_dynamic_allocators:
  4327. case OMPC_atomic_default_mem_order:
  4328. case OMPC_device_type:
  4329. case OMPC_match:
  4330. llvm_unreachable("Unexpected clause");
  4331. }
  4332. for (Stmt *CC : C->children()) {
  4333. if (CC)
  4334. DSAChecker.Visit(CC);
  4335. }
  4336. }
  4337. for (auto &P : DSAChecker.getVarsWithInheritedDSA())
  4338. VarsWithInheritedDSA[P.getFirst()] = P.getSecond();
  4339. }
  4340. for (const auto &P : VarsWithInheritedDSA) {
  4341. if (P.getFirst()->isImplicit() || isa<OMPCapturedExprDecl>(P.getFirst()))
  4342. continue;
  4343. ErrorFound = true;
  4344. Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
  4345. << P.first << P.second->getSourceRange();
  4346. Diag(DSAStack->getDefaultDSALocation(), diag::note_omp_default_dsa_none);
  4347. }
  4348. if (!AllowedNameModifiers.empty())
  4349. ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
  4350. ErrorFound;
  4351. if (ErrorFound)
  4352. return StmtError();
  4353. if (!(Res.getAs<OMPExecutableDirective>()->isStandaloneDirective())) {
  4354. Res.getAs<OMPExecutableDirective>()
  4355. ->getStructuredBlock()
  4356. ->setIsOMPStructuredBlock(true);
  4357. }
  4358. if (!CurContext->isDependentContext() &&
  4359. isOpenMPTargetExecutionDirective(Kind) &&
  4360. !(DSAStack->hasRequiresDeclWithClause<OMPUnifiedSharedMemoryClause>() ||
  4361. DSAStack->hasRequiresDeclWithClause<OMPUnifiedAddressClause>() ||
  4362. DSAStack->hasRequiresDeclWithClause<OMPReverseOffloadClause>() ||
  4363. DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())) {
  4364. // Register target to DSA Stack.
  4365. DSAStack->addTargetDirLocation(StartLoc);
  4366. }
  4367. return Res;
  4368. }
  4369. Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
  4370. DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
  4371. ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
  4372. ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
  4373. ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
  4374. assert(Aligneds.size() == Alignments.size());
  4375. assert(Linears.size() == LinModifiers.size());
  4376. assert(Linears.size() == Steps.size());
  4377. if (!DG || DG.get().isNull())
  4378. return DeclGroupPtrTy();
  4379. const int SimdId = 0;
  4380. if (!DG.get().isSingleDecl()) {
  4381. Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd_variant)
  4382. << SimdId;
  4383. return DG;
  4384. }
  4385. Decl *ADecl = DG.get().getSingleDecl();
  4386. if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
  4387. ADecl = FTD->getTemplatedDecl();
  4388. auto *FD = dyn_cast<FunctionDecl>(ADecl);
  4389. if (!FD) {
  4390. Diag(ADecl->getLocation(), diag::err_omp_function_expected) << SimdId;
  4391. return DeclGroupPtrTy();
  4392. }
  4393. // OpenMP [2.8.2, declare simd construct, Description]
  4394. // The parameter of the simdlen clause must be a constant positive integer
  4395. // expression.
  4396. ExprResult SL;
  4397. if (Simdlen)
  4398. SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
  4399. // OpenMP [2.8.2, declare simd construct, Description]
  4400. // The special this pointer can be used as if was one of the arguments to the
  4401. // function in any of the linear, aligned, or uniform clauses.
  4402. // The uniform clause declares one or more arguments to have an invariant
  4403. // value for all concurrent invocations of the function in the execution of a
  4404. // single SIMD loop.
  4405. llvm::DenseMap<const Decl *, const Expr *> UniformedArgs;
  4406. const Expr *UniformedLinearThis = nullptr;
  4407. for (const Expr *E : Uniforms) {
  4408. E = E->IgnoreParenImpCasts();
  4409. if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
  4410. if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
  4411. if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
  4412. FD->getParamDecl(PVD->getFunctionScopeIndex())
  4413. ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
  4414. UniformedArgs.try_emplace(PVD->getCanonicalDecl(), E);
  4415. continue;
  4416. }
  4417. if (isa<CXXThisExpr>(E)) {
  4418. UniformedLinearThis = E;
  4419. continue;
  4420. }
  4421. Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
  4422. << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
  4423. }
  4424. // OpenMP [2.8.2, declare simd construct, Description]
  4425. // The aligned clause declares that the object to which each list item points
  4426. // is aligned to the number of bytes expressed in the optional parameter of
  4427. // the aligned clause.
  4428. // The special this pointer can be used as if was one of the arguments to the
  4429. // function in any of the linear, aligned, or uniform clauses.
  4430. // The type of list items appearing in the aligned clause must be array,
  4431. // pointer, reference to array, or reference to pointer.
  4432. llvm::DenseMap<const Decl *, const Expr *> AlignedArgs;
  4433. const Expr *AlignedThis = nullptr;
  4434. for (const Expr *E : Aligneds) {
  4435. E = E->IgnoreParenImpCasts();
  4436. if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
  4437. if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
  4438. const VarDecl *CanonPVD = PVD->getCanonicalDecl();
  4439. if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
  4440. FD->getParamDecl(PVD->getFunctionScopeIndex())
  4441. ->getCanonicalDecl() == CanonPVD) {
  4442. // OpenMP [2.8.1, simd construct, Restrictions]
  4443. // A list-item cannot appear in more than one aligned clause.
  4444. if (AlignedArgs.count(CanonPVD) > 0) {
  4445. Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
  4446. << 1 << E->getSourceRange();
  4447. Diag(AlignedArgs[CanonPVD]->getExprLoc(),
  4448. diag::note_omp_explicit_dsa)
  4449. << getOpenMPClauseName(OMPC_aligned);
  4450. continue;
  4451. }
  4452. AlignedArgs[CanonPVD] = E;
  4453. QualType QTy = PVD->getType()
  4454. .getNonReferenceType()
  4455. .getUnqualifiedType()
  4456. .getCanonicalType();
  4457. const Type *Ty = QTy.getTypePtrOrNull();
  4458. if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
  4459. Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
  4460. << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
  4461. Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
  4462. }
  4463. continue;
  4464. }
  4465. }
  4466. if (isa<CXXThisExpr>(E)) {
  4467. if (AlignedThis) {
  4468. Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
  4469. << 2 << E->getSourceRange();
  4470. Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
  4471. << getOpenMPClauseName(OMPC_aligned);
  4472. }
  4473. AlignedThis = E;
  4474. continue;
  4475. }
  4476. Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
  4477. << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
  4478. }
  4479. // The optional parameter of the aligned clause, alignment, must be a constant
  4480. // positive integer expression. If no optional parameter is specified,
  4481. // implementation-defined default alignments for SIMD instructions on the
  4482. // target platforms are assumed.
  4483. SmallVector<const Expr *, 4> NewAligns;
  4484. for (Expr *E : Alignments) {
  4485. ExprResult Align;
  4486. if (E)
  4487. Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
  4488. NewAligns.push_back(Align.get());
  4489. }
  4490. // OpenMP [2.8.2, declare simd construct, Description]
  4491. // The linear clause declares one or more list items to be private to a SIMD
  4492. // lane and to have a linear relationship with respect to the iteration space
  4493. // of a loop.
  4494. // The special this pointer can be used as if was one of the arguments to the
  4495. // function in any of the linear, aligned, or uniform clauses.
  4496. // When a linear-step expression is specified in a linear clause it must be
  4497. // either a constant integer expression or an integer-typed parameter that is
  4498. // specified in a uniform clause on the directive.
  4499. llvm::DenseMap<const Decl *, const Expr *> LinearArgs;
  4500. const bool IsUniformedThis = UniformedLinearThis != nullptr;
  4501. auto MI = LinModifiers.begin();
  4502. for (const Expr *E : Linears) {
  4503. auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
  4504. ++MI;
  4505. E = E->IgnoreParenImpCasts();
  4506. if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
  4507. if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
  4508. const VarDecl *CanonPVD = PVD->getCanonicalDecl();
  4509. if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
  4510. FD->getParamDecl(PVD->getFunctionScopeIndex())
  4511. ->getCanonicalDecl() == CanonPVD) {
  4512. // OpenMP [2.15.3.7, linear Clause, Restrictions]
  4513. // A list-item cannot appear in more than one linear clause.
  4514. if (LinearArgs.count(CanonPVD) > 0) {
  4515. Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
  4516. << getOpenMPClauseName(OMPC_linear)
  4517. << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
  4518. Diag(LinearArgs[CanonPVD]->getExprLoc(),
  4519. diag::note_omp_explicit_dsa)
  4520. << getOpenMPClauseName(OMPC_linear);
  4521. continue;
  4522. }
  4523. // Each argument can appear in at most one uniform or linear clause.
  4524. if (UniformedArgs.count(CanonPVD) > 0) {
  4525. Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
  4526. << getOpenMPClauseName(OMPC_linear)
  4527. << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
  4528. Diag(UniformedArgs[CanonPVD]->getExprLoc(),
  4529. diag::note_omp_explicit_dsa)
  4530. << getOpenMPClauseName(OMPC_uniform);
  4531. continue;
  4532. }
  4533. LinearArgs[CanonPVD] = E;
  4534. if (E->isValueDependent() || E->isTypeDependent() ||
  4535. E->isInstantiationDependent() ||
  4536. E->containsUnexpandedParameterPack())
  4537. continue;
  4538. (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
  4539. PVD->getOriginalType());
  4540. continue;
  4541. }
  4542. }
  4543. if (isa<CXXThisExpr>(E)) {
  4544. if (UniformedLinearThis) {
  4545. Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
  4546. << getOpenMPClauseName(OMPC_linear)
  4547. << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
  4548. << E->getSourceRange();
  4549. Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
  4550. << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
  4551. : OMPC_linear);
  4552. continue;
  4553. }
  4554. UniformedLinearThis = E;
  4555. if (E->isValueDependent() || E->isTypeDependent() ||
  4556. E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
  4557. continue;
  4558. (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
  4559. E->getType());
  4560. continue;
  4561. }
  4562. Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
  4563. << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
  4564. }
  4565. Expr *Step = nullptr;
  4566. Expr *NewStep = nullptr;
  4567. SmallVector<Expr *, 4> NewSteps;
  4568. for (Expr *E : Steps) {
  4569. // Skip the same step expression, it was checked already.
  4570. if (Step == E || !E) {
  4571. NewSteps.push_back(E ? NewStep : nullptr);
  4572. continue;
  4573. }
  4574. Step = E;
  4575. if (const auto *DRE = dyn_cast<DeclRefExpr>(Step))
  4576. if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
  4577. const VarDecl *CanonPVD = PVD->getCanonicalDecl();
  4578. if (UniformedArgs.count(CanonPVD) == 0) {
  4579. Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
  4580. << Step->getSourceRange();
  4581. } else if (E->isValueDependent() || E->isTypeDependent() ||
  4582. E->isInstantiationDependent() ||
  4583. E->containsUnexpandedParameterPack() ||
  4584. CanonPVD->getType()->hasIntegerRepresentation()) {
  4585. NewSteps.push_back(Step);
  4586. } else {
  4587. Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
  4588. << Step->getSourceRange();
  4589. }
  4590. continue;
  4591. }
  4592. NewStep = Step;
  4593. if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
  4594. !Step->isInstantiationDependent() &&
  4595. !Step->containsUnexpandedParameterPack()) {
  4596. NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
  4597. .get();
  4598. if (NewStep)
  4599. NewStep = VerifyIntegerConstantExpression(NewStep).get();
  4600. }
  4601. NewSteps.push_back(NewStep);
  4602. }
  4603. auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
  4604. Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
  4605. Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
  4606. const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
  4607. const_cast<Expr **>(Linears.data()), Linears.size(),
  4608. const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
  4609. NewSteps.data(), NewSteps.size(), SR);
  4610. ADecl->addAttr(NewAttr);
  4611. return DG;
  4612. }
  4613. Optional<std::pair<FunctionDecl *, Expr *>>
  4614. Sema::checkOpenMPDeclareVariantFunction(Sema::DeclGroupPtrTy DG,
  4615. Expr *VariantRef, SourceRange SR) {
  4616. if (!DG || DG.get().isNull())
  4617. return None;
  4618. const int VariantId = 1;
  4619. // Must be applied only to single decl.
  4620. if (!DG.get().isSingleDecl()) {
  4621. Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd_variant)
  4622. << VariantId << SR;
  4623. return None;
  4624. }
  4625. Decl *ADecl = DG.get().getSingleDecl();
  4626. if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
  4627. ADecl = FTD->getTemplatedDecl();
  4628. // Decl must be a function.
  4629. auto *FD = dyn_cast<FunctionDecl>(ADecl);
  4630. if (!FD) {
  4631. Diag(ADecl->getLocation(), diag::err_omp_function_expected)
  4632. << VariantId << SR;
  4633. return None;
  4634. }
  4635. auto &&HasMultiVersionAttributes = [](const FunctionDecl *FD) {
  4636. return FD->hasAttrs() &&
  4637. (FD->hasAttr<CPUDispatchAttr>() || FD->hasAttr<CPUSpecificAttr>() ||
  4638. FD->hasAttr<TargetAttr>());
  4639. };
  4640. // OpenMP is not compatible with CPU-specific attributes.
  4641. if (HasMultiVersionAttributes(FD)) {
  4642. Diag(FD->getLocation(), diag::err_omp_declare_variant_incompat_attributes)
  4643. << SR;
  4644. return None;
  4645. }
  4646. // Allow #pragma omp declare variant only if the function is not used.
  4647. if (FD->isUsed(false))
  4648. Diag(SR.getBegin(), diag::warn_omp_declare_variant_after_used)
  4649. << FD->getLocation();
  4650. // Check if the function was emitted already.
  4651. const FunctionDecl *Definition;
  4652. if (!FD->isThisDeclarationADefinition() && FD->isDefined(Definition) &&
  4653. (LangOpts.EmitAllDecls || Context.DeclMustBeEmitted(Definition)))
  4654. Diag(SR.getBegin(), diag::warn_omp_declare_variant_after_emitted)
  4655. << FD->getLocation();
  4656. // The VariantRef must point to function.
  4657. if (!VariantRef) {
  4658. Diag(SR.getBegin(), diag::err_omp_function_expected) << VariantId;
  4659. return None;
  4660. }
  4661. // Do not check templates, wait until instantiation.
  4662. if (VariantRef->isTypeDependent() || VariantRef->isValueDependent() ||
  4663. VariantRef->containsUnexpandedParameterPack() ||
  4664. VariantRef->isInstantiationDependent() || FD->isDependentContext())
  4665. return std::make_pair(FD, VariantRef);
  4666. // Convert VariantRef expression to the type of the original function to
  4667. // resolve possible conflicts.
  4668. ExprResult VariantRefCast;
  4669. if (LangOpts.CPlusPlus) {
  4670. QualType FnPtrType;
  4671. auto *Method = dyn_cast<CXXMethodDecl>(FD);
  4672. if (Method && !Method->isStatic()) {
  4673. const Type *ClassType =
  4674. Context.getTypeDeclType(Method->getParent()).getTypePtr();
  4675. FnPtrType = Context.getMemberPointerType(FD->getType(), ClassType);
  4676. ExprResult ER;
  4677. {
  4678. // Build adrr_of unary op to correctly handle type checks for member
  4679. // functions.
  4680. Sema::TentativeAnalysisScope Trap(*this);
  4681. ER = CreateBuiltinUnaryOp(VariantRef->getBeginLoc(), UO_AddrOf,
  4682. VariantRef);
  4683. }
  4684. if (!ER.isUsable()) {
  4685. Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
  4686. << VariantId << VariantRef->getSourceRange();
  4687. return None;
  4688. }
  4689. VariantRef = ER.get();
  4690. } else {
  4691. FnPtrType = Context.getPointerType(FD->getType());
  4692. }
  4693. ImplicitConversionSequence ICS =
  4694. TryImplicitConversion(VariantRef, FnPtrType.getUnqualifiedType(),
  4695. /*SuppressUserConversions=*/false,
  4696. /*AllowExplicit=*/false,
  4697. /*InOverloadResolution=*/false,
  4698. /*CStyle=*/false,
  4699. /*AllowObjCWritebackConversion=*/false);
  4700. if (ICS.isFailure()) {
  4701. Diag(VariantRef->getExprLoc(),
  4702. diag::err_omp_declare_variant_incompat_types)
  4703. << VariantRef->getType() << FnPtrType << VariantRef->getSourceRange();
  4704. return None;
  4705. }
  4706. VariantRefCast = PerformImplicitConversion(
  4707. VariantRef, FnPtrType.getUnqualifiedType(), AA_Converting);
  4708. if (!VariantRefCast.isUsable())
  4709. return None;
  4710. // Drop previously built artificial addr_of unary op for member functions.
  4711. if (Method && !Method->isStatic()) {
  4712. Expr *PossibleAddrOfVariantRef = VariantRefCast.get();
  4713. if (auto *UO = dyn_cast<UnaryOperator>(
  4714. PossibleAddrOfVariantRef->IgnoreImplicit()))
  4715. VariantRefCast = UO->getSubExpr();
  4716. }
  4717. } else {
  4718. VariantRefCast = VariantRef;
  4719. }
  4720. ExprResult ER = CheckPlaceholderExpr(VariantRefCast.get());
  4721. if (!ER.isUsable() ||
  4722. !ER.get()->IgnoreParenImpCasts()->getType()->isFunctionType()) {
  4723. Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
  4724. << VariantId << VariantRef->getSourceRange();
  4725. return None;
  4726. }
  4727. // The VariantRef must point to function.
  4728. auto *DRE = dyn_cast<DeclRefExpr>(ER.get()->IgnoreParenImpCasts());
  4729. if (!DRE) {
  4730. Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
  4731. << VariantId << VariantRef->getSourceRange();
  4732. return None;
  4733. }
  4734. auto *NewFD = dyn_cast_or_null<FunctionDecl>(DRE->getDecl());
  4735. if (!NewFD) {
  4736. Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
  4737. << VariantId << VariantRef->getSourceRange();
  4738. return None;
  4739. }
  4740. // Check if variant function is not marked with declare variant directive.
  4741. if (NewFD->hasAttrs() && NewFD->hasAttr<OMPDeclareVariantAttr>()) {
  4742. Diag(VariantRef->getExprLoc(),
  4743. diag::warn_omp_declare_variant_marked_as_declare_variant)
  4744. << VariantRef->getSourceRange();
  4745. SourceRange SR =
  4746. NewFD->specific_attr_begin<OMPDeclareVariantAttr>()->getRange();
  4747. Diag(SR.getBegin(), diag::note_omp_marked_declare_variant_here) << SR;
  4748. return None;
  4749. }
  4750. enum DoesntSupport {
  4751. VirtFuncs = 1,
  4752. Constructors = 3,
  4753. Destructors = 4,
  4754. DeletedFuncs = 5,
  4755. DefaultedFuncs = 6,
  4756. ConstexprFuncs = 7,
  4757. ConstevalFuncs = 8,
  4758. };
  4759. if (const auto *CXXFD = dyn_cast<CXXMethodDecl>(FD)) {
  4760. if (CXXFD->isVirtual()) {
  4761. Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
  4762. << VirtFuncs;
  4763. return None;
  4764. }
  4765. if (isa<CXXConstructorDecl>(FD)) {
  4766. Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
  4767. << Constructors;
  4768. return None;
  4769. }
  4770. if (isa<CXXDestructorDecl>(FD)) {
  4771. Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
  4772. << Destructors;
  4773. return None;
  4774. }
  4775. }
  4776. if (FD->isDeleted()) {
  4777. Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
  4778. << DeletedFuncs;
  4779. return None;
  4780. }
  4781. if (FD->isDefaulted()) {
  4782. Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
  4783. << DefaultedFuncs;
  4784. return None;
  4785. }
  4786. if (FD->isConstexpr()) {
  4787. Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
  4788. << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
  4789. return None;
  4790. }
  4791. // Check general compatibility.
  4792. if (areMultiversionVariantFunctionsCompatible(
  4793. FD, NewFD, PDiag(diag::err_omp_declare_variant_noproto),
  4794. PartialDiagnosticAt(
  4795. SR.getBegin(),
  4796. PDiag(diag::note_omp_declare_variant_specified_here) << SR),
  4797. PartialDiagnosticAt(
  4798. VariantRef->getExprLoc(),
  4799. PDiag(diag::err_omp_declare_variant_doesnt_support)),
  4800. PartialDiagnosticAt(VariantRef->getExprLoc(),
  4801. PDiag(diag::err_omp_declare_variant_diff)
  4802. << FD->getLocation()),
  4803. /*TemplatesSupported=*/true, /*ConstexprSupported=*/false,
  4804. /*CLinkageMayDiffer=*/true))
  4805. return None;
  4806. return std::make_pair(FD, cast<Expr>(DRE));
  4807. }
  4808. void Sema::ActOnOpenMPDeclareVariantDirective(
  4809. FunctionDecl *FD, Expr *VariantRef, SourceRange SR,
  4810. const Sema::OpenMPDeclareVariantCtsSelectorData &Data) {
  4811. if (Data.CtxSet == OMPDeclareVariantAttr::CtxSetUnknown ||
  4812. Data.Ctx == OMPDeclareVariantAttr::CtxUnknown)
  4813. return;
  4814. Expr *Score = nullptr;
  4815. OMPDeclareVariantAttr::ScoreType ST = OMPDeclareVariantAttr::ScoreUnknown;
  4816. if (Data.CtxScore.isUsable()) {
  4817. ST = OMPDeclareVariantAttr::ScoreSpecified;
  4818. Score = Data.CtxScore.get();
  4819. if (!Score->isTypeDependent() && !Score->isValueDependent() &&
  4820. !Score->isInstantiationDependent() &&
  4821. !Score->containsUnexpandedParameterPack()) {
  4822. llvm::APSInt Result;
  4823. ExprResult ICE = VerifyIntegerConstantExpression(Score, &Result);
  4824. if (ICE.isInvalid())
  4825. return;
  4826. }
  4827. }
  4828. auto *NewAttr = OMPDeclareVariantAttr::CreateImplicit(
  4829. Context, VariantRef, Score, Data.CtxSet, ST, Data.Ctx,
  4830. Data.ImplVendors.begin(), Data.ImplVendors.size(), SR);
  4831. FD->addAttr(NewAttr);
  4832. }
  4833. void Sema::markOpenMPDeclareVariantFuncsReferenced(SourceLocation Loc,
  4834. FunctionDecl *Func,
  4835. bool MightBeOdrUse) {
  4836. assert(LangOpts.OpenMP && "Expected OpenMP mode.");
  4837. if (!Func->isDependentContext() && Func->hasAttrs()) {
  4838. for (OMPDeclareVariantAttr *A :
  4839. Func->specific_attrs<OMPDeclareVariantAttr>()) {
  4840. // TODO: add checks for active OpenMP context where possible.
  4841. Expr *VariantRef = A->getVariantFuncRef();
  4842. auto *DRE = dyn_cast<DeclRefExpr>(VariantRef->IgnoreParenImpCasts());
  4843. auto *F = cast<FunctionDecl>(DRE->getDecl());
  4844. if (!F->isDefined() && F->isTemplateInstantiation())
  4845. InstantiateFunctionDefinition(Loc, F->getFirstDecl());
  4846. MarkFunctionReferenced(Loc, F, MightBeOdrUse);
  4847. }
  4848. }
  4849. }
  4850. StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
  4851. Stmt *AStmt,
  4852. SourceLocation StartLoc,
  4853. SourceLocation EndLoc) {
  4854. if (!AStmt)
  4855. return StmtError();
  4856. auto *CS = cast<CapturedStmt>(AStmt);
  4857. // 1.2.2 OpenMP Language Terminology
  4858. // Structured block - An executable statement with a single entry at the
  4859. // top and a single exit at the bottom.
  4860. // The point of exit cannot be a branch out of the structured block.
  4861. // longjmp() and throw() must not violate the entry/exit criteria.
  4862. CS->getCapturedDecl()->setNothrow();
  4863. setFunctionHasBranchProtectedScope();
  4864. return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
  4865. DSAStack->isCancelRegion());
  4866. }
  4867. namespace {
  4868. /// Iteration space of a single for loop.
  4869. struct LoopIterationSpace final {
  4870. /// True if the condition operator is the strict compare operator (<, > or
  4871. /// !=).
  4872. bool IsStrictCompare = false;
  4873. /// Condition of the loop.
  4874. Expr *PreCond = nullptr;
  4875. /// This expression calculates the number of iterations in the loop.
  4876. /// It is always possible to calculate it before starting the loop.
  4877. Expr *NumIterations = nullptr;
  4878. /// The loop counter variable.
  4879. Expr *CounterVar = nullptr;
  4880. /// Private loop counter variable.
  4881. Expr *PrivateCounterVar = nullptr;
  4882. /// This is initializer for the initial value of #CounterVar.
  4883. Expr *CounterInit = nullptr;
  4884. /// This is step for the #CounterVar used to generate its update:
  4885. /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
  4886. Expr *CounterStep = nullptr;
  4887. /// Should step be subtracted?
  4888. bool Subtract = false;
  4889. /// Source range of the loop init.
  4890. SourceRange InitSrcRange;
  4891. /// Source range of the loop condition.
  4892. SourceRange CondSrcRange;
  4893. /// Source range of the loop increment.
  4894. SourceRange IncSrcRange;
  4895. /// Minimum value that can have the loop control variable. Used to support
  4896. /// non-rectangular loops. Applied only for LCV with the non-iterator types,
  4897. /// since only such variables can be used in non-loop invariant expressions.
  4898. Expr *MinValue = nullptr;
  4899. /// Maximum value that can have the loop control variable. Used to support
  4900. /// non-rectangular loops. Applied only for LCV with the non-iterator type,
  4901. /// since only such variables can be used in non-loop invariant expressions.
  4902. Expr *MaxValue = nullptr;
  4903. /// true, if the lower bound depends on the outer loop control var.
  4904. bool IsNonRectangularLB = false;
  4905. /// true, if the upper bound depends on the outer loop control var.
  4906. bool IsNonRectangularUB = false;
  4907. /// Index of the loop this loop depends on and forms non-rectangular loop
  4908. /// nest.
  4909. unsigned LoopDependentIdx = 0;
  4910. /// Final condition for the non-rectangular loop nest support. It is used to
  4911. /// check that the number of iterations for this particular counter must be
  4912. /// finished.
  4913. Expr *FinalCondition = nullptr;
  4914. };
  4915. /// Helper class for checking canonical form of the OpenMP loops and
  4916. /// extracting iteration space of each loop in the loop nest, that will be used
  4917. /// for IR generation.
  4918. class OpenMPIterationSpaceChecker {
  4919. /// Reference to Sema.
  4920. Sema &SemaRef;
  4921. /// Data-sharing stack.
  4922. DSAStackTy &Stack;
  4923. /// A location for diagnostics (when there is no some better location).
  4924. SourceLocation DefaultLoc;
  4925. /// A location for diagnostics (when increment is not compatible).
  4926. SourceLocation ConditionLoc;
  4927. /// A source location for referring to loop init later.
  4928. SourceRange InitSrcRange;
  4929. /// A source location for referring to condition later.
  4930. SourceRange ConditionSrcRange;
  4931. /// A source location for referring to increment later.
  4932. SourceRange IncrementSrcRange;
  4933. /// Loop variable.
  4934. ValueDecl *LCDecl = nullptr;
  4935. /// Reference to loop variable.
  4936. Expr *LCRef = nullptr;
  4937. /// Lower bound (initializer for the var).
  4938. Expr *LB = nullptr;
  4939. /// Upper bound.
  4940. Expr *UB = nullptr;
  4941. /// Loop step (increment).
  4942. Expr *Step = nullptr;
  4943. /// This flag is true when condition is one of:
  4944. /// Var < UB
  4945. /// Var <= UB
  4946. /// UB > Var
  4947. /// UB >= Var
  4948. /// This will have no value when the condition is !=
  4949. llvm::Optional<bool> TestIsLessOp;
  4950. /// This flag is true when condition is strict ( < or > ).
  4951. bool TestIsStrictOp = false;
  4952. /// This flag is true when step is subtracted on each iteration.
  4953. bool SubtractStep = false;
  4954. /// The outer loop counter this loop depends on (if any).
  4955. const ValueDecl *DepDecl = nullptr;
  4956. /// Contains number of loop (starts from 1) on which loop counter init
  4957. /// expression of this loop depends on.
  4958. Optional<unsigned> InitDependOnLC;
  4959. /// Contains number of loop (starts from 1) on which loop counter condition
  4960. /// expression of this loop depends on.
  4961. Optional<unsigned> CondDependOnLC;
  4962. /// Checks if the provide statement depends on the loop counter.
  4963. Optional<unsigned> doesDependOnLoopCounter(const Stmt *S, bool IsInitializer);
  4964. /// Original condition required for checking of the exit condition for
  4965. /// non-rectangular loop.
  4966. Expr *Condition = nullptr;
  4967. public:
  4968. OpenMPIterationSpaceChecker(Sema &SemaRef, DSAStackTy &Stack,
  4969. SourceLocation DefaultLoc)
  4970. : SemaRef(SemaRef), Stack(Stack), DefaultLoc(DefaultLoc),
  4971. ConditionLoc(DefaultLoc) {}
  4972. /// Check init-expr for canonical loop form and save loop counter
  4973. /// variable - #Var and its initialization value - #LB.
  4974. bool checkAndSetInit(Stmt *S, bool EmitDiags = true);
  4975. /// Check test-expr for canonical form, save upper-bound (#UB), flags
  4976. /// for less/greater and for strict/non-strict comparison.
  4977. bool checkAndSetCond(Expr *S);
  4978. /// Check incr-expr for canonical loop form and return true if it
  4979. /// does not conform, otherwise save loop step (#Step).
  4980. bool checkAndSetInc(Expr *S);
  4981. /// Return the loop counter variable.
  4982. ValueDecl *getLoopDecl() const { return LCDecl; }
  4983. /// Return the reference expression to loop counter variable.
  4984. Expr *getLoopDeclRefExpr() const { return LCRef; }
  4985. /// Source range of the loop init.
  4986. SourceRange getInitSrcRange() const { return InitSrcRange; }
  4987. /// Source range of the loop condition.
  4988. SourceRange getConditionSrcRange() const { return ConditionSrcRange; }
  4989. /// Source range of the loop increment.
  4990. SourceRange getIncrementSrcRange() const { return IncrementSrcRange; }
  4991. /// True if the step should be subtracted.
  4992. bool shouldSubtractStep() const { return SubtractStep; }
  4993. /// True, if the compare operator is strict (<, > or !=).
  4994. bool isStrictTestOp() const { return TestIsStrictOp; }
  4995. /// Build the expression to calculate the number of iterations.
  4996. Expr *buildNumIterations(
  4997. Scope *S, ArrayRef<LoopIterationSpace> ResultIterSpaces, bool LimitedType,
  4998. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
  4999. /// Build the precondition expression for the loops.
  5000. Expr *
  5001. buildPreCond(Scope *S, Expr *Cond,
  5002. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
  5003. /// Build reference expression to the counter be used for codegen.
  5004. DeclRefExpr *
  5005. buildCounterVar(llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
  5006. DSAStackTy &DSA) const;
  5007. /// Build reference expression to the private counter be used for
  5008. /// codegen.
  5009. Expr *buildPrivateCounterVar() const;
  5010. /// Build initialization of the counter be used for codegen.
  5011. Expr *buildCounterInit() const;
  5012. /// Build step of the counter be used for codegen.
  5013. Expr *buildCounterStep() const;
  5014. /// Build loop data with counter value for depend clauses in ordered
  5015. /// directives.
  5016. Expr *
  5017. buildOrderedLoopData(Scope *S, Expr *Counter,
  5018. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
  5019. SourceLocation Loc, Expr *Inc = nullptr,
  5020. OverloadedOperatorKind OOK = OO_Amp);
  5021. /// Builds the minimum value for the loop counter.
  5022. std::pair<Expr *, Expr *> buildMinMaxValues(
  5023. Scope *S, llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
  5024. /// Builds final condition for the non-rectangular loops.
  5025. Expr *buildFinalCondition(Scope *S) const;
  5026. /// Return true if any expression is dependent.
  5027. bool dependent() const;
  5028. /// Returns true if the initializer forms non-rectangular loop.
  5029. bool doesInitDependOnLC() const { return InitDependOnLC.hasValue(); }
  5030. /// Returns true if the condition forms non-rectangular loop.
  5031. bool doesCondDependOnLC() const { return CondDependOnLC.hasValue(); }
  5032. /// Returns index of the loop we depend on (starting from 1), or 0 otherwise.
  5033. unsigned getLoopDependentIdx() const {
  5034. return InitDependOnLC.getValueOr(CondDependOnLC.getValueOr(0));
  5035. }
  5036. private:
  5037. /// Check the right-hand side of an assignment in the increment
  5038. /// expression.
  5039. bool checkAndSetIncRHS(Expr *RHS);
  5040. /// Helper to set loop counter variable and its initializer.
  5041. bool setLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB,
  5042. bool EmitDiags);
  5043. /// Helper to set upper bound.
  5044. bool setUB(Expr *NewUB, llvm::Optional<bool> LessOp, bool StrictOp,
  5045. SourceRange SR, SourceLocation SL);
  5046. /// Helper to set loop increment.
  5047. bool setStep(Expr *NewStep, bool Subtract);
  5048. };
  5049. bool OpenMPIterationSpaceChecker::dependent() const {
  5050. if (!LCDecl) {
  5051. assert(!LB && !UB && !Step);
  5052. return false;
  5053. }
  5054. return LCDecl->getType()->isDependentType() ||
  5055. (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
  5056. (Step && Step->isValueDependent());
  5057. }
  5058. bool OpenMPIterationSpaceChecker::setLCDeclAndLB(ValueDecl *NewLCDecl,
  5059. Expr *NewLCRefExpr,
  5060. Expr *NewLB, bool EmitDiags) {
  5061. // State consistency checking to ensure correct usage.
  5062. assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
  5063. UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
  5064. if (!NewLCDecl || !NewLB)
  5065. return true;
  5066. LCDecl = getCanonicalDecl(NewLCDecl);
  5067. LCRef = NewLCRefExpr;
  5068. if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
  5069. if (const CXXConstructorDecl *Ctor = CE->getConstructor())
  5070. if ((Ctor->isCopyOrMoveConstructor() ||
  5071. Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
  5072. CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
  5073. NewLB = CE->getArg(0)->IgnoreParenImpCasts();
  5074. LB = NewLB;
  5075. if (EmitDiags)
  5076. InitDependOnLC = doesDependOnLoopCounter(LB, /*IsInitializer=*/true);
  5077. return false;
  5078. }
  5079. bool OpenMPIterationSpaceChecker::setUB(Expr *NewUB,
  5080. llvm::Optional<bool> LessOp,
  5081. bool StrictOp, SourceRange SR,
  5082. SourceLocation SL) {
  5083. // State consistency checking to ensure correct usage.
  5084. assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
  5085. Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
  5086. if (!NewUB)
  5087. return true;
  5088. UB = NewUB;
  5089. if (LessOp)
  5090. TestIsLessOp = LessOp;
  5091. TestIsStrictOp = StrictOp;
  5092. ConditionSrcRange = SR;
  5093. ConditionLoc = SL;
  5094. CondDependOnLC = doesDependOnLoopCounter(UB, /*IsInitializer=*/false);
  5095. return false;
  5096. }
  5097. bool OpenMPIterationSpaceChecker::setStep(Expr *NewStep, bool Subtract) {
  5098. // State consistency checking to ensure correct usage.
  5099. assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
  5100. if (!NewStep)
  5101. return true;
  5102. if (!NewStep->isValueDependent()) {
  5103. // Check that the step is integer expression.
  5104. SourceLocation StepLoc = NewStep->getBeginLoc();
  5105. ExprResult Val = SemaRef.PerformOpenMPImplicitIntegerConversion(
  5106. StepLoc, getExprAsWritten(NewStep));
  5107. if (Val.isInvalid())
  5108. return true;
  5109. NewStep = Val.get();
  5110. // OpenMP [2.6, Canonical Loop Form, Restrictions]
  5111. // If test-expr is of form var relational-op b and relational-op is < or
  5112. // <= then incr-expr must cause var to increase on each iteration of the
  5113. // loop. If test-expr is of form var relational-op b and relational-op is
  5114. // > or >= then incr-expr must cause var to decrease on each iteration of
  5115. // the loop.
  5116. // If test-expr is of form b relational-op var and relational-op is < or
  5117. // <= then incr-expr must cause var to decrease on each iteration of the
  5118. // loop. If test-expr is of form b relational-op var and relational-op is
  5119. // > or >= then incr-expr must cause var to increase on each iteration of
  5120. // the loop.
  5121. llvm::APSInt Result;
  5122. bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
  5123. bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
  5124. bool IsConstNeg =
  5125. IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
  5126. bool IsConstPos =
  5127. IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
  5128. bool IsConstZero = IsConstant && !Result.getBoolValue();
  5129. // != with increment is treated as <; != with decrement is treated as >
  5130. if (!TestIsLessOp.hasValue())
  5131. TestIsLessOp = IsConstPos || (IsUnsigned && !Subtract);
  5132. if (UB && (IsConstZero ||
  5133. (TestIsLessOp.getValue() ?
  5134. (IsConstNeg || (IsUnsigned && Subtract)) :
  5135. (IsConstPos || (IsUnsigned && !Subtract))))) {
  5136. SemaRef.Diag(NewStep->getExprLoc(),
  5137. diag::err_omp_loop_incr_not_compatible)
  5138. << LCDecl << TestIsLessOp.getValue() << NewStep->getSourceRange();
  5139. SemaRef.Diag(ConditionLoc,
  5140. diag::note_omp_loop_cond_requres_compatible_incr)
  5141. << TestIsLessOp.getValue() << ConditionSrcRange;
  5142. return true;
  5143. }
  5144. if (TestIsLessOp.getValue() == Subtract) {
  5145. NewStep =
  5146. SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
  5147. .get();
  5148. Subtract = !Subtract;
  5149. }
  5150. }
  5151. Step = NewStep;
  5152. SubtractStep = Subtract;
  5153. return false;
  5154. }
  5155. namespace {
  5156. /// Checker for the non-rectangular loops. Checks if the initializer or
  5157. /// condition expression references loop counter variable.
  5158. class LoopCounterRefChecker final
  5159. : public ConstStmtVisitor<LoopCounterRefChecker, bool> {
  5160. Sema &SemaRef;
  5161. DSAStackTy &Stack;
  5162. const ValueDecl *CurLCDecl = nullptr;
  5163. const ValueDecl *DepDecl = nullptr;
  5164. const ValueDecl *PrevDepDecl = nullptr;
  5165. bool IsInitializer = true;
  5166. unsigned BaseLoopId = 0;
  5167. bool checkDecl(const Expr *E, const ValueDecl *VD) {
  5168. if (getCanonicalDecl(VD) == getCanonicalDecl(CurLCDecl)) {
  5169. SemaRef.Diag(E->getExprLoc(), diag::err_omp_stmt_depends_on_loop_counter)
  5170. << (IsInitializer ? 0 : 1);
  5171. return false;
  5172. }
  5173. const auto &&Data = Stack.isLoopControlVariable(VD);
  5174. // OpenMP, 2.9.1 Canonical Loop Form, Restrictions.
  5175. // The type of the loop iterator on which we depend may not have a random
  5176. // access iterator type.
  5177. if (Data.first && VD->getType()->isRecordType()) {
  5178. SmallString<128> Name;
  5179. llvm::raw_svector_ostream OS(Name);
  5180. VD->getNameForDiagnostic(OS, SemaRef.getPrintingPolicy(),
  5181. /*Qualified=*/true);
  5182. SemaRef.Diag(E->getExprLoc(),
  5183. diag::err_omp_wrong_dependency_iterator_type)
  5184. << OS.str();
  5185. SemaRef.Diag(VD->getLocation(), diag::note_previous_decl) << VD;
  5186. return false;
  5187. }
  5188. if (Data.first &&
  5189. (DepDecl || (PrevDepDecl &&
  5190. getCanonicalDecl(VD) != getCanonicalDecl(PrevDepDecl)))) {
  5191. if (!DepDecl && PrevDepDecl)
  5192. DepDecl = PrevDepDecl;
  5193. SmallString<128> Name;
  5194. llvm::raw_svector_ostream OS(Name);
  5195. DepDecl->getNameForDiagnostic(OS, SemaRef.getPrintingPolicy(),
  5196. /*Qualified=*/true);
  5197. SemaRef.Diag(E->getExprLoc(),
  5198. diag::err_omp_invariant_or_linear_dependency)
  5199. << OS.str();
  5200. return false;
  5201. }
  5202. if (Data.first) {
  5203. DepDecl = VD;
  5204. BaseLoopId = Data.first;
  5205. }
  5206. return Data.first;
  5207. }
  5208. public:
  5209. bool VisitDeclRefExpr(const DeclRefExpr *E) {
  5210. const ValueDecl *VD = E->getDecl();
  5211. if (isa<VarDecl>(VD))
  5212. return checkDecl(E, VD);
  5213. return false;
  5214. }
  5215. bool VisitMemberExpr(const MemberExpr *E) {
  5216. if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) {
  5217. const ValueDecl *VD = E->getMemberDecl();
  5218. if (isa<VarDecl>(VD) || isa<FieldDecl>(VD))
  5219. return checkDecl(E, VD);
  5220. }
  5221. return false;
  5222. }
  5223. bool VisitStmt(const Stmt *S) {
  5224. bool Res = false;
  5225. for (const Stmt *Child : S->children())
  5226. Res = (Child && Visit(Child)) || Res;
  5227. return Res;
  5228. }
  5229. explicit LoopCounterRefChecker(Sema &SemaRef, DSAStackTy &Stack,
  5230. const ValueDecl *CurLCDecl, bool IsInitializer,
  5231. const ValueDecl *PrevDepDecl = nullptr)
  5232. : SemaRef(SemaRef), Stack(Stack), CurLCDecl(CurLCDecl),
  5233. PrevDepDecl(PrevDepDecl), IsInitializer(IsInitializer) {}
  5234. unsigned getBaseLoopId() const {
  5235. assert(CurLCDecl && "Expected loop dependency.");
  5236. return BaseLoopId;
  5237. }
  5238. const ValueDecl *getDepDecl() const {
  5239. assert(CurLCDecl && "Expected loop dependency.");
  5240. return DepDecl;
  5241. }
  5242. };
  5243. } // namespace
  5244. Optional<unsigned>
  5245. OpenMPIterationSpaceChecker::doesDependOnLoopCounter(const Stmt *S,
  5246. bool IsInitializer) {
  5247. // Check for the non-rectangular loops.
  5248. LoopCounterRefChecker LoopStmtChecker(SemaRef, Stack, LCDecl, IsInitializer,
  5249. DepDecl);
  5250. if (LoopStmtChecker.Visit(S)) {
  5251. DepDecl = LoopStmtChecker.getDepDecl();
  5252. return LoopStmtChecker.getBaseLoopId();
  5253. }
  5254. return llvm::None;
  5255. }
  5256. bool OpenMPIterationSpaceChecker::checkAndSetInit(Stmt *S, bool EmitDiags) {
  5257. // Check init-expr for canonical loop form and save loop counter
  5258. // variable - #Var and its initialization value - #LB.
  5259. // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
  5260. // var = lb
  5261. // integer-type var = lb
  5262. // random-access-iterator-type var = lb
  5263. // pointer-type var = lb
  5264. //
  5265. if (!S) {
  5266. if (EmitDiags) {
  5267. SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
  5268. }
  5269. return true;
  5270. }
  5271. if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
  5272. if (!ExprTemp->cleanupsHaveSideEffects())
  5273. S = ExprTemp->getSubExpr();
  5274. InitSrcRange = S->getSourceRange();
  5275. if (Expr *E = dyn_cast<Expr>(S))
  5276. S = E->IgnoreParens();
  5277. if (auto *BO = dyn_cast<BinaryOperator>(S)) {
  5278. if (BO->getOpcode() == BO_Assign) {
  5279. Expr *LHS = BO->getLHS()->IgnoreParens();
  5280. if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
  5281. if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
  5282. if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
  5283. return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
  5284. EmitDiags);
  5285. return setLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS(), EmitDiags);
  5286. }
  5287. if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
  5288. if (ME->isArrow() &&
  5289. isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
  5290. return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
  5291. EmitDiags);
  5292. }
  5293. }
  5294. } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
  5295. if (DS->isSingleDecl()) {
  5296. if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
  5297. if (Var->hasInit() && !Var->getType()->isReferenceType()) {
  5298. // Accept non-canonical init form here but emit ext. warning.
  5299. if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
  5300. SemaRef.Diag(S->getBeginLoc(),
  5301. diag::ext_omp_loop_not_canonical_init)
  5302. << S->getSourceRange();
  5303. return setLCDeclAndLB(
  5304. Var,
  5305. buildDeclRefExpr(SemaRef, Var,
  5306. Var->getType().getNonReferenceType(),
  5307. DS->getBeginLoc()),
  5308. Var->getInit(), EmitDiags);
  5309. }
  5310. }
  5311. }
  5312. } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
  5313. if (CE->getOperator() == OO_Equal) {
  5314. Expr *LHS = CE->getArg(0);
  5315. if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
  5316. if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
  5317. if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
  5318. return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
  5319. EmitDiags);
  5320. return setLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1), EmitDiags);
  5321. }
  5322. if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
  5323. if (ME->isArrow() &&
  5324. isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
  5325. return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
  5326. EmitDiags);
  5327. }
  5328. }
  5329. }
  5330. if (dependent() || SemaRef.CurContext->isDependentContext())
  5331. return false;
  5332. if (EmitDiags) {
  5333. SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_init)
  5334. << S->getSourceRange();
  5335. }
  5336. return true;
  5337. }
  5338. /// Ignore parenthesizes, implicit casts, copy constructor and return the
  5339. /// variable (which may be the loop variable) if possible.
  5340. static const ValueDecl *getInitLCDecl(const Expr *E) {
  5341. if (!E)
  5342. return nullptr;
  5343. E = getExprAsWritten(E);
  5344. if (const auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
  5345. if (const CXXConstructorDecl *Ctor = CE->getConstructor())
  5346. if ((Ctor->isCopyOrMoveConstructor() ||
  5347. Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
  5348. CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
  5349. E = CE->getArg(0)->IgnoreParenImpCasts();
  5350. if (const auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
  5351. if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
  5352. return getCanonicalDecl(VD);
  5353. }
  5354. if (const auto *ME = dyn_cast_or_null<MemberExpr>(E))
  5355. if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
  5356. return getCanonicalDecl(ME->getMemberDecl());
  5357. return nullptr;
  5358. }
  5359. bool OpenMPIterationSpaceChecker::checkAndSetCond(Expr *S) {
  5360. // Check test-expr for canonical form, save upper-bound UB, flags for
  5361. // less/greater and for strict/non-strict comparison.
  5362. // OpenMP [2.9] Canonical loop form. Test-expr may be one of the following:
  5363. // var relational-op b
  5364. // b relational-op var
  5365. //
  5366. bool IneqCondIsCanonical = SemaRef.getLangOpts().OpenMP >= 50;
  5367. if (!S) {
  5368. SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond)
  5369. << (IneqCondIsCanonical ? 1 : 0) << LCDecl;
  5370. return true;
  5371. }
  5372. Condition = S;
  5373. S = getExprAsWritten(S);
  5374. SourceLocation CondLoc = S->getBeginLoc();
  5375. if (auto *BO = dyn_cast<BinaryOperator>(S)) {
  5376. if (BO->isRelationalOp()) {
  5377. if (getInitLCDecl(BO->getLHS()) == LCDecl)
  5378. return setUB(BO->getRHS(),
  5379. (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
  5380. (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
  5381. BO->getSourceRange(), BO->getOperatorLoc());
  5382. if (getInitLCDecl(BO->getRHS()) == LCDecl)
  5383. return setUB(BO->getLHS(),
  5384. (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
  5385. (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
  5386. BO->getSourceRange(), BO->getOperatorLoc());
  5387. } else if (IneqCondIsCanonical && BO->getOpcode() == BO_NE)
  5388. return setUB(
  5389. getInitLCDecl(BO->getLHS()) == LCDecl ? BO->getRHS() : BO->getLHS(),
  5390. /*LessOp=*/llvm::None,
  5391. /*StrictOp=*/true, BO->getSourceRange(), BO->getOperatorLoc());
  5392. } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
  5393. if (CE->getNumArgs() == 2) {
  5394. auto Op = CE->getOperator();
  5395. switch (Op) {
  5396. case OO_Greater:
  5397. case OO_GreaterEqual:
  5398. case OO_Less:
  5399. case OO_LessEqual:
  5400. if (getInitLCDecl(CE->getArg(0)) == LCDecl)
  5401. return setUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
  5402. Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
  5403. CE->getOperatorLoc());
  5404. if (getInitLCDecl(CE->getArg(1)) == LCDecl)
  5405. return setUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
  5406. Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
  5407. CE->getOperatorLoc());
  5408. break;
  5409. case OO_ExclaimEqual:
  5410. if (IneqCondIsCanonical)
  5411. return setUB(getInitLCDecl(CE->getArg(0)) == LCDecl ? CE->getArg(1)
  5412. : CE->getArg(0),
  5413. /*LessOp=*/llvm::None,
  5414. /*StrictOp=*/true, CE->getSourceRange(),
  5415. CE->getOperatorLoc());
  5416. break;
  5417. default:
  5418. break;
  5419. }
  5420. }
  5421. }
  5422. if (dependent() || SemaRef.CurContext->isDependentContext())
  5423. return false;
  5424. SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
  5425. << (IneqCondIsCanonical ? 1 : 0) << S->getSourceRange() << LCDecl;
  5426. return true;
  5427. }
  5428. bool OpenMPIterationSpaceChecker::checkAndSetIncRHS(Expr *RHS) {
  5429. // RHS of canonical loop form increment can be:
  5430. // var + incr
  5431. // incr + var
  5432. // var - incr
  5433. //
  5434. RHS = RHS->IgnoreParenImpCasts();
  5435. if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
  5436. if (BO->isAdditiveOp()) {
  5437. bool IsAdd = BO->getOpcode() == BO_Add;
  5438. if (getInitLCDecl(BO->getLHS()) == LCDecl)
  5439. return setStep(BO->getRHS(), !IsAdd);
  5440. if (IsAdd && getInitLCDecl(BO->getRHS()) == LCDecl)
  5441. return setStep(BO->getLHS(), /*Subtract=*/false);
  5442. }
  5443. } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
  5444. bool IsAdd = CE->getOperator() == OO_Plus;
  5445. if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
  5446. if (getInitLCDecl(CE->getArg(0)) == LCDecl)
  5447. return setStep(CE->getArg(1), !IsAdd);
  5448. if (IsAdd && getInitLCDecl(CE->getArg(1)) == LCDecl)
  5449. return setStep(CE->getArg(0), /*Subtract=*/false);
  5450. }
  5451. }
  5452. if (dependent() || SemaRef.CurContext->isDependentContext())
  5453. return false;
  5454. SemaRef.Diag(RHS->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
  5455. << RHS->getSourceRange() << LCDecl;
  5456. return true;
  5457. }
  5458. bool OpenMPIterationSpaceChecker::checkAndSetInc(Expr *S) {
  5459. // Check incr-expr for canonical loop form and return true if it
  5460. // does not conform.
  5461. // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
  5462. // ++var
  5463. // var++
  5464. // --var
  5465. // var--
  5466. // var += incr
  5467. // var -= incr
  5468. // var = var + incr
  5469. // var = incr + var
  5470. // var = var - incr
  5471. //
  5472. if (!S) {
  5473. SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
  5474. return true;
  5475. }
  5476. if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
  5477. if (!ExprTemp->cleanupsHaveSideEffects())
  5478. S = ExprTemp->getSubExpr();
  5479. IncrementSrcRange = S->getSourceRange();
  5480. S = S->IgnoreParens();
  5481. if (auto *UO = dyn_cast<UnaryOperator>(S)) {
  5482. if (UO->isIncrementDecrementOp() &&
  5483. getInitLCDecl(UO->getSubExpr()) == LCDecl)
  5484. return setStep(SemaRef
  5485. .ActOnIntegerConstant(UO->getBeginLoc(),
  5486. (UO->isDecrementOp() ? -1 : 1))
  5487. .get(),
  5488. /*Subtract=*/false);
  5489. } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
  5490. switch (BO->getOpcode()) {
  5491. case BO_AddAssign:
  5492. case BO_SubAssign:
  5493. if (getInitLCDecl(BO->getLHS()) == LCDecl)
  5494. return setStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
  5495. break;
  5496. case BO_Assign:
  5497. if (getInitLCDecl(BO->getLHS()) == LCDecl)
  5498. return checkAndSetIncRHS(BO->getRHS());
  5499. break;
  5500. default:
  5501. break;
  5502. }
  5503. } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
  5504. switch (CE->getOperator()) {
  5505. case OO_PlusPlus:
  5506. case OO_MinusMinus:
  5507. if (getInitLCDecl(CE->getArg(0)) == LCDecl)
  5508. return setStep(SemaRef
  5509. .ActOnIntegerConstant(
  5510. CE->getBeginLoc(),
  5511. ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
  5512. .get(),
  5513. /*Subtract=*/false);
  5514. break;
  5515. case OO_PlusEqual:
  5516. case OO_MinusEqual:
  5517. if (getInitLCDecl(CE->getArg(0)) == LCDecl)
  5518. return setStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
  5519. break;
  5520. case OO_Equal:
  5521. if (getInitLCDecl(CE->getArg(0)) == LCDecl)
  5522. return checkAndSetIncRHS(CE->getArg(1));
  5523. break;
  5524. default:
  5525. break;
  5526. }
  5527. }
  5528. if (dependent() || SemaRef.CurContext->isDependentContext())
  5529. return false;
  5530. SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
  5531. << S->getSourceRange() << LCDecl;
  5532. return true;
  5533. }
  5534. static ExprResult
  5535. tryBuildCapture(Sema &SemaRef, Expr *Capture,
  5536. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
  5537. if (SemaRef.CurContext->isDependentContext())
  5538. return ExprResult(Capture);
  5539. if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
  5540. return SemaRef.PerformImplicitConversion(
  5541. Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
  5542. /*AllowExplicit=*/true);
  5543. auto I = Captures.find(Capture);
  5544. if (I != Captures.end())
  5545. return buildCapture(SemaRef, Capture, I->second);
  5546. DeclRefExpr *Ref = nullptr;
  5547. ExprResult Res = buildCapture(SemaRef, Capture, Ref);
  5548. Captures[Capture] = Ref;
  5549. return Res;
  5550. }
  5551. /// Build the expression to calculate the number of iterations.
  5552. Expr *OpenMPIterationSpaceChecker::buildNumIterations(
  5553. Scope *S, ArrayRef<LoopIterationSpace> ResultIterSpaces, bool LimitedType,
  5554. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
  5555. ExprResult Diff;
  5556. QualType VarType = LCDecl->getType().getNonReferenceType();
  5557. if (VarType->isIntegerType() || VarType->isPointerType() ||
  5558. SemaRef.getLangOpts().CPlusPlus) {
  5559. Expr *LBVal = LB;
  5560. Expr *UBVal = UB;
  5561. // LB = TestIsLessOp.getValue() ? min(LB(MinVal), LB(MaxVal)) :
  5562. // max(LB(MinVal), LB(MaxVal))
  5563. if (InitDependOnLC) {
  5564. const LoopIterationSpace &IS =
  5565. ResultIterSpaces[ResultIterSpaces.size() - 1 -
  5566. InitDependOnLC.getValueOr(
  5567. CondDependOnLC.getValueOr(0))];
  5568. if (!IS.MinValue || !IS.MaxValue)
  5569. return nullptr;
  5570. // OuterVar = Min
  5571. ExprResult MinValue =
  5572. SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MinValue);
  5573. if (!MinValue.isUsable())
  5574. return nullptr;
  5575. ExprResult LBMinVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
  5576. IS.CounterVar, MinValue.get());
  5577. if (!LBMinVal.isUsable())
  5578. return nullptr;
  5579. // OuterVar = Min, LBVal
  5580. LBMinVal =
  5581. SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, LBMinVal.get(), LBVal);
  5582. if (!LBMinVal.isUsable())
  5583. return nullptr;
  5584. // (OuterVar = Min, LBVal)
  5585. LBMinVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, LBMinVal.get());
  5586. if (!LBMinVal.isUsable())
  5587. return nullptr;
  5588. // OuterVar = Max
  5589. ExprResult MaxValue =
  5590. SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MaxValue);
  5591. if (!MaxValue.isUsable())
  5592. return nullptr;
  5593. ExprResult LBMaxVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
  5594. IS.CounterVar, MaxValue.get());
  5595. if (!LBMaxVal.isUsable())
  5596. return nullptr;
  5597. // OuterVar = Max, LBVal
  5598. LBMaxVal =
  5599. SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, LBMaxVal.get(), LBVal);
  5600. if (!LBMaxVal.isUsable())
  5601. return nullptr;
  5602. // (OuterVar = Max, LBVal)
  5603. LBMaxVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, LBMaxVal.get());
  5604. if (!LBMaxVal.isUsable())
  5605. return nullptr;
  5606. Expr *LBMin = tryBuildCapture(SemaRef, LBMinVal.get(), Captures).get();
  5607. Expr *LBMax = tryBuildCapture(SemaRef, LBMaxVal.get(), Captures).get();
  5608. if (!LBMin || !LBMax)
  5609. return nullptr;
  5610. // LB(MinVal) < LB(MaxVal)
  5611. ExprResult MinLessMaxRes =
  5612. SemaRef.BuildBinOp(S, DefaultLoc, BO_LT, LBMin, LBMax);
  5613. if (!MinLessMaxRes.isUsable())
  5614. return nullptr;
  5615. Expr *MinLessMax =
  5616. tryBuildCapture(SemaRef, MinLessMaxRes.get(), Captures).get();
  5617. if (!MinLessMax)
  5618. return nullptr;
  5619. if (TestIsLessOp.getValue()) {
  5620. // LB(MinVal) < LB(MaxVal) ? LB(MinVal) : LB(MaxVal) - min(LB(MinVal),
  5621. // LB(MaxVal))
  5622. ExprResult MinLB = SemaRef.ActOnConditionalOp(DefaultLoc, DefaultLoc,
  5623. MinLessMax, LBMin, LBMax);
  5624. if (!MinLB.isUsable())
  5625. return nullptr;
  5626. LBVal = MinLB.get();
  5627. } else {
  5628. // LB(MinVal) < LB(MaxVal) ? LB(MaxVal) : LB(MinVal) - max(LB(MinVal),
  5629. // LB(MaxVal))
  5630. ExprResult MaxLB = SemaRef.ActOnConditionalOp(DefaultLoc, DefaultLoc,
  5631. MinLessMax, LBMax, LBMin);
  5632. if (!MaxLB.isUsable())
  5633. return nullptr;
  5634. LBVal = MaxLB.get();
  5635. }
  5636. }
  5637. // UB = TestIsLessOp.getValue() ? max(UB(MinVal), UB(MaxVal)) :
  5638. // min(UB(MinVal), UB(MaxVal))
  5639. if (CondDependOnLC) {
  5640. const LoopIterationSpace &IS =
  5641. ResultIterSpaces[ResultIterSpaces.size() - 1 -
  5642. InitDependOnLC.getValueOr(
  5643. CondDependOnLC.getValueOr(0))];
  5644. if (!IS.MinValue || !IS.MaxValue)
  5645. return nullptr;
  5646. // OuterVar = Min
  5647. ExprResult MinValue =
  5648. SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MinValue);
  5649. if (!MinValue.isUsable())
  5650. return nullptr;
  5651. ExprResult UBMinVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
  5652. IS.CounterVar, MinValue.get());
  5653. if (!UBMinVal.isUsable())
  5654. return nullptr;
  5655. // OuterVar = Min, UBVal
  5656. UBMinVal =
  5657. SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, UBMinVal.get(), UBVal);
  5658. if (!UBMinVal.isUsable())
  5659. return nullptr;
  5660. // (OuterVar = Min, UBVal)
  5661. UBMinVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, UBMinVal.get());
  5662. if (!UBMinVal.isUsable())
  5663. return nullptr;
  5664. // OuterVar = Max
  5665. ExprResult MaxValue =
  5666. SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MaxValue);
  5667. if (!MaxValue.isUsable())
  5668. return nullptr;
  5669. ExprResult UBMaxVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
  5670. IS.CounterVar, MaxValue.get());
  5671. if (!UBMaxVal.isUsable())
  5672. return nullptr;
  5673. // OuterVar = Max, UBVal
  5674. UBMaxVal =
  5675. SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, UBMaxVal.get(), UBVal);
  5676. if (!UBMaxVal.isUsable())
  5677. return nullptr;
  5678. // (OuterVar = Max, UBVal)
  5679. UBMaxVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, UBMaxVal.get());
  5680. if (!UBMaxVal.isUsable())
  5681. return nullptr;
  5682. Expr *UBMin = tryBuildCapture(SemaRef, UBMinVal.get(), Captures).get();
  5683. Expr *UBMax = tryBuildCapture(SemaRef, UBMaxVal.get(), Captures).get();
  5684. if (!UBMin || !UBMax)
  5685. return nullptr;
  5686. // UB(MinVal) > UB(MaxVal)
  5687. ExprResult MinGreaterMaxRes =
  5688. SemaRef.BuildBinOp(S, DefaultLoc, BO_GT, UBMin, UBMax);
  5689. if (!MinGreaterMaxRes.isUsable())
  5690. return nullptr;
  5691. Expr *MinGreaterMax =
  5692. tryBuildCapture(SemaRef, MinGreaterMaxRes.get(), Captures).get();
  5693. if (!MinGreaterMax)
  5694. return nullptr;
  5695. if (TestIsLessOp.getValue()) {
  5696. // UB(MinVal) > UB(MaxVal) ? UB(MinVal) : UB(MaxVal) - max(UB(MinVal),
  5697. // UB(MaxVal))
  5698. ExprResult MaxUB = SemaRef.ActOnConditionalOp(
  5699. DefaultLoc, DefaultLoc, MinGreaterMax, UBMin, UBMax);
  5700. if (!MaxUB.isUsable())
  5701. return nullptr;
  5702. UBVal = MaxUB.get();
  5703. } else {
  5704. // UB(MinVal) > UB(MaxVal) ? UB(MaxVal) : UB(MinVal) - min(UB(MinVal),
  5705. // UB(MaxVal))
  5706. ExprResult MinUB = SemaRef.ActOnConditionalOp(
  5707. DefaultLoc, DefaultLoc, MinGreaterMax, UBMax, UBMin);
  5708. if (!MinUB.isUsable())
  5709. return nullptr;
  5710. UBVal = MinUB.get();
  5711. }
  5712. }
  5713. // Upper - Lower
  5714. Expr *UBExpr = TestIsLessOp.getValue() ? UBVal : LBVal;
  5715. Expr *LBExpr = TestIsLessOp.getValue() ? LBVal : UBVal;
  5716. Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
  5717. Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
  5718. if (!Upper || !Lower)
  5719. return nullptr;
  5720. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
  5721. if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
  5722. // BuildBinOp already emitted error, this one is to point user to upper
  5723. // and lower bound, and to tell what is passed to 'operator-'.
  5724. SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx)
  5725. << Upper->getSourceRange() << Lower->getSourceRange();
  5726. return nullptr;
  5727. }
  5728. }
  5729. if (!Diff.isUsable())
  5730. return nullptr;
  5731. // Upper - Lower [- 1]
  5732. if (TestIsStrictOp)
  5733. Diff = SemaRef.BuildBinOp(
  5734. S, DefaultLoc, BO_Sub, Diff.get(),
  5735. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
  5736. if (!Diff.isUsable())
  5737. return nullptr;
  5738. // Upper - Lower [- 1] + Step
  5739. ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
  5740. if (!NewStep.isUsable())
  5741. return nullptr;
  5742. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
  5743. if (!Diff.isUsable())
  5744. return nullptr;
  5745. // Parentheses (for dumping/debugging purposes only).
  5746. Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
  5747. if (!Diff.isUsable())
  5748. return nullptr;
  5749. // (Upper - Lower [- 1] + Step) / Step
  5750. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
  5751. if (!Diff.isUsable())
  5752. return nullptr;
  5753. // OpenMP runtime requires 32-bit or 64-bit loop variables.
  5754. QualType Type = Diff.get()->getType();
  5755. ASTContext &C = SemaRef.Context;
  5756. bool UseVarType = VarType->hasIntegerRepresentation() &&
  5757. C.getTypeSize(Type) > C.getTypeSize(VarType);
  5758. if (!Type->isIntegerType() || UseVarType) {
  5759. unsigned NewSize =
  5760. UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
  5761. bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
  5762. : Type->hasSignedIntegerRepresentation();
  5763. Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
  5764. if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
  5765. Diff = SemaRef.PerformImplicitConversion(
  5766. Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
  5767. if (!Diff.isUsable())
  5768. return nullptr;
  5769. }
  5770. }
  5771. if (LimitedType) {
  5772. unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
  5773. if (NewSize != C.getTypeSize(Type)) {
  5774. if (NewSize < C.getTypeSize(Type)) {
  5775. assert(NewSize == 64 && "incorrect loop var size");
  5776. SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
  5777. << InitSrcRange << ConditionSrcRange;
  5778. }
  5779. QualType NewType = C.getIntTypeForBitwidth(
  5780. NewSize, Type->hasSignedIntegerRepresentation() ||
  5781. C.getTypeSize(Type) < NewSize);
  5782. if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
  5783. Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
  5784. Sema::AA_Converting, true);
  5785. if (!Diff.isUsable())
  5786. return nullptr;
  5787. }
  5788. }
  5789. }
  5790. return Diff.get();
  5791. }
  5792. std::pair<Expr *, Expr *> OpenMPIterationSpaceChecker::buildMinMaxValues(
  5793. Scope *S, llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
  5794. // Do not build for iterators, they cannot be used in non-rectangular loop
  5795. // nests.
  5796. if (LCDecl->getType()->isRecordType())
  5797. return std::make_pair(nullptr, nullptr);
  5798. // If we subtract, the min is in the condition, otherwise the min is in the
  5799. // init value.
  5800. Expr *MinExpr = nullptr;
  5801. Expr *MaxExpr = nullptr;
  5802. Expr *LBExpr = TestIsLessOp.getValue() ? LB : UB;
  5803. Expr *UBExpr = TestIsLessOp.getValue() ? UB : LB;
  5804. bool LBNonRect = TestIsLessOp.getValue() ? InitDependOnLC.hasValue()
  5805. : CondDependOnLC.hasValue();
  5806. bool UBNonRect = TestIsLessOp.getValue() ? CondDependOnLC.hasValue()
  5807. : InitDependOnLC.hasValue();
  5808. Expr *Lower =
  5809. LBNonRect ? LBExpr : tryBuildCapture(SemaRef, LBExpr, Captures).get();
  5810. Expr *Upper =
  5811. UBNonRect ? UBExpr : tryBuildCapture(SemaRef, UBExpr, Captures).get();
  5812. if (!Upper || !Lower)
  5813. return std::make_pair(nullptr, nullptr);
  5814. if (TestIsLessOp.getValue())
  5815. MinExpr = Lower;
  5816. else
  5817. MaxExpr = Upper;
  5818. // Build minimum/maximum value based on number of iterations.
  5819. ExprResult Diff;
  5820. QualType VarType = LCDecl->getType().getNonReferenceType();
  5821. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
  5822. if (!Diff.isUsable())
  5823. return std::make_pair(nullptr, nullptr);
  5824. // Upper - Lower [- 1]
  5825. if (TestIsStrictOp)
  5826. Diff = SemaRef.BuildBinOp(
  5827. S, DefaultLoc, BO_Sub, Diff.get(),
  5828. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
  5829. if (!Diff.isUsable())
  5830. return std::make_pair(nullptr, nullptr);
  5831. // Upper - Lower [- 1] + Step
  5832. ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
  5833. if (!NewStep.isUsable())
  5834. return std::make_pair(nullptr, nullptr);
  5835. // Parentheses (for dumping/debugging purposes only).
  5836. Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
  5837. if (!Diff.isUsable())
  5838. return std::make_pair(nullptr, nullptr);
  5839. // (Upper - Lower [- 1]) / Step
  5840. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
  5841. if (!Diff.isUsable())
  5842. return std::make_pair(nullptr, nullptr);
  5843. // ((Upper - Lower [- 1]) / Step) * Step
  5844. // Parentheses (for dumping/debugging purposes only).
  5845. Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
  5846. if (!Diff.isUsable())
  5847. return std::make_pair(nullptr, nullptr);
  5848. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Mul, Diff.get(), NewStep.get());
  5849. if (!Diff.isUsable())
  5850. return std::make_pair(nullptr, nullptr);
  5851. // Convert to the original type or ptrdiff_t, if original type is pointer.
  5852. if (!VarType->isAnyPointerType() &&
  5853. !SemaRef.Context.hasSameType(Diff.get()->getType(), VarType)) {
  5854. Diff = SemaRef.PerformImplicitConversion(
  5855. Diff.get(), VarType, Sema::AA_Converting, /*AllowExplicit=*/true);
  5856. } else if (VarType->isAnyPointerType() &&
  5857. !SemaRef.Context.hasSameType(
  5858. Diff.get()->getType(),
  5859. SemaRef.Context.getUnsignedPointerDiffType())) {
  5860. Diff = SemaRef.PerformImplicitConversion(
  5861. Diff.get(), SemaRef.Context.getUnsignedPointerDiffType(),
  5862. Sema::AA_Converting, /*AllowExplicit=*/true);
  5863. }
  5864. if (!Diff.isUsable())
  5865. return std::make_pair(nullptr, nullptr);
  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. if (TestIsLessOp.getValue()) {
  5871. // MinExpr = Lower;
  5872. // MaxExpr = Lower + (((Upper - Lower [- 1]) / Step) * Step)
  5873. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Lower, Diff.get());
  5874. if (!Diff.isUsable())
  5875. return std::make_pair(nullptr, nullptr);
  5876. Diff = SemaRef.ActOnFinishFullExpr(Diff.get(), /*DiscardedValue*/ false);
  5877. if (!Diff.isUsable())
  5878. return std::make_pair(nullptr, nullptr);
  5879. MaxExpr = Diff.get();
  5880. } else {
  5881. // MaxExpr = Upper;
  5882. // MinExpr = Upper - (((Upper - Lower [- 1]) / Step) * Step)
  5883. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Diff.get());
  5884. if (!Diff.isUsable())
  5885. return std::make_pair(nullptr, nullptr);
  5886. Diff = SemaRef.ActOnFinishFullExpr(Diff.get(), /*DiscardedValue*/ false);
  5887. if (!Diff.isUsable())
  5888. return std::make_pair(nullptr, nullptr);
  5889. MinExpr = Diff.get();
  5890. }
  5891. return std::make_pair(MinExpr, MaxExpr);
  5892. }
  5893. Expr *OpenMPIterationSpaceChecker::buildFinalCondition(Scope *S) const {
  5894. if (InitDependOnLC || CondDependOnLC)
  5895. return Condition;
  5896. return nullptr;
  5897. }
  5898. Expr *OpenMPIterationSpaceChecker::buildPreCond(
  5899. Scope *S, Expr *Cond,
  5900. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
  5901. // Do not build a precondition when the condition/initialization is dependent
  5902. // to prevent pessimistic early loop exit.
  5903. // TODO: this can be improved by calculating min/max values but not sure that
  5904. // it will be very effective.
  5905. if (CondDependOnLC || InitDependOnLC)
  5906. return SemaRef.PerformImplicitConversion(
  5907. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get(),
  5908. SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
  5909. /*AllowExplicit=*/true).get();
  5910. // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
  5911. Sema::TentativeAnalysisScope Trap(SemaRef);
  5912. ExprResult NewLB = tryBuildCapture(SemaRef, LB, Captures);
  5913. ExprResult NewUB = tryBuildCapture(SemaRef, UB, Captures);
  5914. if (!NewLB.isUsable() || !NewUB.isUsable())
  5915. return nullptr;
  5916. ExprResult CondExpr =
  5917. SemaRef.BuildBinOp(S, DefaultLoc,
  5918. TestIsLessOp.getValue() ?
  5919. (TestIsStrictOp ? BO_LT : BO_LE) :
  5920. (TestIsStrictOp ? BO_GT : BO_GE),
  5921. NewLB.get(), NewUB.get());
  5922. if (CondExpr.isUsable()) {
  5923. if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
  5924. SemaRef.Context.BoolTy))
  5925. CondExpr = SemaRef.PerformImplicitConversion(
  5926. CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
  5927. /*AllowExplicit=*/true);
  5928. }
  5929. // Otherwise use original loop condition and evaluate it in runtime.
  5930. return CondExpr.isUsable() ? CondExpr.get() : Cond;
  5931. }
  5932. /// Build reference expression to the counter be used for codegen.
  5933. DeclRefExpr *OpenMPIterationSpaceChecker::buildCounterVar(
  5934. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
  5935. DSAStackTy &DSA) const {
  5936. auto *VD = dyn_cast<VarDecl>(LCDecl);
  5937. if (!VD) {
  5938. VD = SemaRef.isOpenMPCapturedDecl(LCDecl);
  5939. DeclRefExpr *Ref = buildDeclRefExpr(
  5940. SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
  5941. const DSAStackTy::DSAVarData Data =
  5942. DSA.getTopDSA(LCDecl, /*FromParent=*/false);
  5943. // If the loop control decl is explicitly marked as private, do not mark it
  5944. // as captured again.
  5945. if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
  5946. Captures.insert(std::make_pair(LCRef, Ref));
  5947. return Ref;
  5948. }
  5949. return cast<DeclRefExpr>(LCRef);
  5950. }
  5951. Expr *OpenMPIterationSpaceChecker::buildPrivateCounterVar() const {
  5952. if (LCDecl && !LCDecl->isInvalidDecl()) {
  5953. QualType Type = LCDecl->getType().getNonReferenceType();
  5954. VarDecl *PrivateVar = buildVarDecl(
  5955. SemaRef, DefaultLoc, Type, LCDecl->getName(),
  5956. LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr,
  5957. isa<VarDecl>(LCDecl)
  5958. ? buildDeclRefExpr(SemaRef, cast<VarDecl>(LCDecl), Type, DefaultLoc)
  5959. : nullptr);
  5960. if (PrivateVar->isInvalidDecl())
  5961. return nullptr;
  5962. return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
  5963. }
  5964. return nullptr;
  5965. }
  5966. /// Build initialization of the counter to be used for codegen.
  5967. Expr *OpenMPIterationSpaceChecker::buildCounterInit() const { return LB; }
  5968. /// Build step of the counter be used for codegen.
  5969. Expr *OpenMPIterationSpaceChecker::buildCounterStep() const { return Step; }
  5970. Expr *OpenMPIterationSpaceChecker::buildOrderedLoopData(
  5971. Scope *S, Expr *Counter,
  5972. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, SourceLocation Loc,
  5973. Expr *Inc, OverloadedOperatorKind OOK) {
  5974. Expr *Cnt = SemaRef.DefaultLvalueConversion(Counter).get();
  5975. if (!Cnt)
  5976. return nullptr;
  5977. if (Inc) {
  5978. assert((OOK == OO_Plus || OOK == OO_Minus) &&
  5979. "Expected only + or - operations for depend clauses.");
  5980. BinaryOperatorKind BOK = (OOK == OO_Plus) ? BO_Add : BO_Sub;
  5981. Cnt = SemaRef.BuildBinOp(S, Loc, BOK, Cnt, Inc).get();
  5982. if (!Cnt)
  5983. return nullptr;
  5984. }
  5985. ExprResult Diff;
  5986. QualType VarType = LCDecl->getType().getNonReferenceType();
  5987. if (VarType->isIntegerType() || VarType->isPointerType() ||
  5988. SemaRef.getLangOpts().CPlusPlus) {
  5989. // Upper - Lower
  5990. Expr *Upper = TestIsLessOp.getValue()
  5991. ? Cnt
  5992. : tryBuildCapture(SemaRef, UB, Captures).get();
  5993. Expr *Lower = TestIsLessOp.getValue()
  5994. ? tryBuildCapture(SemaRef, LB, Captures).get()
  5995. : Cnt;
  5996. if (!Upper || !Lower)
  5997. return nullptr;
  5998. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
  5999. if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
  6000. // BuildBinOp already emitted error, this one is to point user to upper
  6001. // and lower bound, and to tell what is passed to 'operator-'.
  6002. SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx)
  6003. << Upper->getSourceRange() << Lower->getSourceRange();
  6004. return nullptr;
  6005. }
  6006. }
  6007. if (!Diff.isUsable())
  6008. return nullptr;
  6009. // Parentheses (for dumping/debugging purposes only).
  6010. Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
  6011. if (!Diff.isUsable())
  6012. return nullptr;
  6013. ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
  6014. if (!NewStep.isUsable())
  6015. return nullptr;
  6016. // (Upper - Lower) / Step
  6017. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
  6018. if (!Diff.isUsable())
  6019. return nullptr;
  6020. return Diff.get();
  6021. }
  6022. } // namespace
  6023. void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
  6024. assert(getLangOpts().OpenMP && "OpenMP is not active.");
  6025. assert(Init && "Expected loop in canonical form.");
  6026. unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
  6027. if (AssociatedLoops > 0 &&
  6028. isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
  6029. DSAStack->loopStart();
  6030. OpenMPIterationSpaceChecker ISC(*this, *DSAStack, ForLoc);
  6031. if (!ISC.checkAndSetInit(Init, /*EmitDiags=*/false)) {
  6032. if (ValueDecl *D = ISC.getLoopDecl()) {
  6033. auto *VD = dyn_cast<VarDecl>(D);
  6034. DeclRefExpr *PrivateRef = nullptr;
  6035. if (!VD) {
  6036. if (VarDecl *Private = isOpenMPCapturedDecl(D)) {
  6037. VD = Private;
  6038. } else {
  6039. PrivateRef = buildCapture(*this, D, ISC.getLoopDeclRefExpr(),
  6040. /*WithInit=*/false);
  6041. VD = cast<VarDecl>(PrivateRef->getDecl());
  6042. }
  6043. }
  6044. DSAStack->addLoopControlVariable(D, VD);
  6045. const Decl *LD = DSAStack->getPossiblyLoopCunter();
  6046. if (LD != D->getCanonicalDecl()) {
  6047. DSAStack->resetPossibleLoopCounter();
  6048. if (auto *Var = dyn_cast_or_null<VarDecl>(LD))
  6049. MarkDeclarationsReferencedInExpr(
  6050. buildDeclRefExpr(*this, const_cast<VarDecl *>(Var),
  6051. Var->getType().getNonLValueExprType(Context),
  6052. ForLoc, /*RefersToCapture=*/true));
  6053. }
  6054. OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
  6055. // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables
  6056. // Referenced in a Construct, C/C++]. The loop iteration variable in the
  6057. // associated for-loop of a simd construct with just one associated
  6058. // for-loop may be listed in a linear clause with a constant-linear-step
  6059. // that is the increment of the associated for-loop. The loop iteration
  6060. // variable(s) in the associated for-loop(s) of a for or parallel for
  6061. // construct may be listed in a private or lastprivate clause.
  6062. DSAStackTy::DSAVarData DVar =
  6063. DSAStack->getTopDSA(D, /*FromParent=*/false);
  6064. // If LoopVarRefExpr is nullptr it means the corresponding loop variable
  6065. // is declared in the loop and it is predetermined as a private.
  6066. Expr *LoopDeclRefExpr = ISC.getLoopDeclRefExpr();
  6067. OpenMPClauseKind PredeterminedCKind =
  6068. isOpenMPSimdDirective(DKind)
  6069. ? (DSAStack->hasMutipleLoops() ? OMPC_lastprivate : OMPC_linear)
  6070. : OMPC_private;
  6071. if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
  6072. DVar.CKind != PredeterminedCKind && DVar.RefExpr &&
  6073. (LangOpts.OpenMP <= 45 || (DVar.CKind != OMPC_lastprivate &&
  6074. DVar.CKind != OMPC_private))) ||
  6075. ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
  6076. isOpenMPDistributeDirective(DKind)) &&
  6077. !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
  6078. DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
  6079. (DVar.CKind != OMPC_private || DVar.RefExpr)) {
  6080. Diag(Init->getBeginLoc(), diag::err_omp_loop_var_dsa)
  6081. << getOpenMPClauseName(DVar.CKind)
  6082. << getOpenMPDirectiveName(DKind)
  6083. << getOpenMPClauseName(PredeterminedCKind);
  6084. if (DVar.RefExpr == nullptr)
  6085. DVar.CKind = PredeterminedCKind;
  6086. reportOriginalDsa(*this, DSAStack, D, DVar,
  6087. /*IsLoopIterVar=*/true);
  6088. } else if (LoopDeclRefExpr) {
  6089. // Make the loop iteration variable private (for worksharing
  6090. // constructs), linear (for simd directives with the only one
  6091. // associated loop) or lastprivate (for simd directives with several
  6092. // collapsed or ordered loops).
  6093. if (DVar.CKind == OMPC_unknown)
  6094. DSAStack->addDSA(D, LoopDeclRefExpr, PredeterminedCKind,
  6095. PrivateRef);
  6096. }
  6097. }
  6098. }
  6099. DSAStack->setAssociatedLoops(AssociatedLoops - 1);
  6100. }
  6101. }
  6102. /// Called on a for stmt to check and extract its iteration space
  6103. /// for further processing (such as collapsing).
  6104. static bool checkOpenMPIterationSpace(
  6105. OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
  6106. unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
  6107. unsigned TotalNestedLoopCount, Expr *CollapseLoopCountExpr,
  6108. Expr *OrderedLoopCountExpr,
  6109. Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
  6110. llvm::MutableArrayRef<LoopIterationSpace> ResultIterSpaces,
  6111. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
  6112. // OpenMP [2.9.1, Canonical Loop Form]
  6113. // for (init-expr; test-expr; incr-expr) structured-block
  6114. // for (range-decl: range-expr) structured-block
  6115. auto *For = dyn_cast_or_null<ForStmt>(S);
  6116. auto *CXXFor = dyn_cast_or_null<CXXForRangeStmt>(S);
  6117. // Ranged for is supported only in OpenMP 5.0.
  6118. if (!For && (SemaRef.LangOpts.OpenMP <= 45 || !CXXFor)) {
  6119. SemaRef.Diag(S->getBeginLoc(), diag::err_omp_not_for)
  6120. << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
  6121. << getOpenMPDirectiveName(DKind) << TotalNestedLoopCount
  6122. << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
  6123. if (TotalNestedLoopCount > 1) {
  6124. if (CollapseLoopCountExpr && OrderedLoopCountExpr)
  6125. SemaRef.Diag(DSA.getConstructLoc(),
  6126. diag::note_omp_collapse_ordered_expr)
  6127. << 2 << CollapseLoopCountExpr->getSourceRange()
  6128. << OrderedLoopCountExpr->getSourceRange();
  6129. else if (CollapseLoopCountExpr)
  6130. SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
  6131. diag::note_omp_collapse_ordered_expr)
  6132. << 0 << CollapseLoopCountExpr->getSourceRange();
  6133. else
  6134. SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
  6135. diag::note_omp_collapse_ordered_expr)
  6136. << 1 << OrderedLoopCountExpr->getSourceRange();
  6137. }
  6138. return true;
  6139. }
  6140. assert(((For && For->getBody()) || (CXXFor && CXXFor->getBody())) &&
  6141. "No loop body.");
  6142. OpenMPIterationSpaceChecker ISC(SemaRef, DSA,
  6143. For ? For->getForLoc() : CXXFor->getForLoc());
  6144. // Check init.
  6145. Stmt *Init = For ? For->getInit() : CXXFor->getBeginStmt();
  6146. if (ISC.checkAndSetInit(Init))
  6147. return true;
  6148. bool HasErrors = false;
  6149. // Check loop variable's type.
  6150. if (ValueDecl *LCDecl = ISC.getLoopDecl()) {
  6151. // OpenMP [2.6, Canonical Loop Form]
  6152. // Var is one of the following:
  6153. // A variable of signed or unsigned integer type.
  6154. // For C++, a variable of a random access iterator type.
  6155. // For C, a variable of a pointer type.
  6156. QualType VarType = LCDecl->getType().getNonReferenceType();
  6157. if (!VarType->isDependentType() && !VarType->isIntegerType() &&
  6158. !VarType->isPointerType() &&
  6159. !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
  6160. SemaRef.Diag(Init->getBeginLoc(), diag::err_omp_loop_variable_type)
  6161. << SemaRef.getLangOpts().CPlusPlus;
  6162. HasErrors = true;
  6163. }
  6164. // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
  6165. // a Construct
  6166. // The loop iteration variable(s) in the associated for-loop(s) of a for or
  6167. // parallel for construct is (are) private.
  6168. // The loop iteration variable in the associated for-loop of a simd
  6169. // construct with just one associated for-loop is linear with a
  6170. // constant-linear-step that is the increment of the associated for-loop.
  6171. // Exclude loop var from the list of variables with implicitly defined data
  6172. // sharing attributes.
  6173. VarsWithImplicitDSA.erase(LCDecl);
  6174. assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
  6175. // Check test-expr.
  6176. HasErrors |= ISC.checkAndSetCond(For ? For->getCond() : CXXFor->getCond());
  6177. // Check incr-expr.
  6178. HasErrors |= ISC.checkAndSetInc(For ? For->getInc() : CXXFor->getInc());
  6179. }
  6180. if (ISC.dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
  6181. return HasErrors;
  6182. // Build the loop's iteration space representation.
  6183. ResultIterSpaces[CurrentNestedLoopCount].PreCond = ISC.buildPreCond(
  6184. DSA.getCurScope(), For ? For->getCond() : CXXFor->getCond(), Captures);
  6185. ResultIterSpaces[CurrentNestedLoopCount].NumIterations =
  6186. ISC.buildNumIterations(DSA.getCurScope(), ResultIterSpaces,
  6187. (isOpenMPWorksharingDirective(DKind) ||
  6188. isOpenMPTaskLoopDirective(DKind) ||
  6189. isOpenMPDistributeDirective(DKind)),
  6190. Captures);
  6191. ResultIterSpaces[CurrentNestedLoopCount].CounterVar =
  6192. ISC.buildCounterVar(Captures, DSA);
  6193. ResultIterSpaces[CurrentNestedLoopCount].PrivateCounterVar =
  6194. ISC.buildPrivateCounterVar();
  6195. ResultIterSpaces[CurrentNestedLoopCount].CounterInit = ISC.buildCounterInit();
  6196. ResultIterSpaces[CurrentNestedLoopCount].CounterStep = ISC.buildCounterStep();
  6197. ResultIterSpaces[CurrentNestedLoopCount].InitSrcRange = ISC.getInitSrcRange();
  6198. ResultIterSpaces[CurrentNestedLoopCount].CondSrcRange =
  6199. ISC.getConditionSrcRange();
  6200. ResultIterSpaces[CurrentNestedLoopCount].IncSrcRange =
  6201. ISC.getIncrementSrcRange();
  6202. ResultIterSpaces[CurrentNestedLoopCount].Subtract = ISC.shouldSubtractStep();
  6203. ResultIterSpaces[CurrentNestedLoopCount].IsStrictCompare =
  6204. ISC.isStrictTestOp();
  6205. std::tie(ResultIterSpaces[CurrentNestedLoopCount].MinValue,
  6206. ResultIterSpaces[CurrentNestedLoopCount].MaxValue) =
  6207. ISC.buildMinMaxValues(DSA.getCurScope(), Captures);
  6208. ResultIterSpaces[CurrentNestedLoopCount].FinalCondition =
  6209. ISC.buildFinalCondition(DSA.getCurScope());
  6210. ResultIterSpaces[CurrentNestedLoopCount].IsNonRectangularLB =
  6211. ISC.doesInitDependOnLC();
  6212. ResultIterSpaces[CurrentNestedLoopCount].IsNonRectangularUB =
  6213. ISC.doesCondDependOnLC();
  6214. ResultIterSpaces[CurrentNestedLoopCount].LoopDependentIdx =
  6215. ISC.getLoopDependentIdx();
  6216. HasErrors |=
  6217. (ResultIterSpaces[CurrentNestedLoopCount].PreCond == nullptr ||
  6218. ResultIterSpaces[CurrentNestedLoopCount].NumIterations == nullptr ||
  6219. ResultIterSpaces[CurrentNestedLoopCount].CounterVar == nullptr ||
  6220. ResultIterSpaces[CurrentNestedLoopCount].PrivateCounterVar == nullptr ||
  6221. ResultIterSpaces[CurrentNestedLoopCount].CounterInit == nullptr ||
  6222. ResultIterSpaces[CurrentNestedLoopCount].CounterStep == nullptr);
  6223. if (!HasErrors && DSA.isOrderedRegion()) {
  6224. if (DSA.getOrderedRegionParam().second->getNumForLoops()) {
  6225. if (CurrentNestedLoopCount <
  6226. DSA.getOrderedRegionParam().second->getLoopNumIterations().size()) {
  6227. DSA.getOrderedRegionParam().second->setLoopNumIterations(
  6228. CurrentNestedLoopCount,
  6229. ResultIterSpaces[CurrentNestedLoopCount].NumIterations);
  6230. DSA.getOrderedRegionParam().second->setLoopCounter(
  6231. CurrentNestedLoopCount,
  6232. ResultIterSpaces[CurrentNestedLoopCount].CounterVar);
  6233. }
  6234. }
  6235. for (auto &Pair : DSA.getDoacrossDependClauses()) {
  6236. if (CurrentNestedLoopCount >= Pair.first->getNumLoops()) {
  6237. // Erroneous case - clause has some problems.
  6238. continue;
  6239. }
  6240. if (Pair.first->getDependencyKind() == OMPC_DEPEND_sink &&
  6241. Pair.second.size() <= CurrentNestedLoopCount) {
  6242. // Erroneous case - clause has some problems.
  6243. Pair.first->setLoopData(CurrentNestedLoopCount, nullptr);
  6244. continue;
  6245. }
  6246. Expr *CntValue;
  6247. if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
  6248. CntValue = ISC.buildOrderedLoopData(
  6249. DSA.getCurScope(),
  6250. ResultIterSpaces[CurrentNestedLoopCount].CounterVar, Captures,
  6251. Pair.first->getDependencyLoc());
  6252. else
  6253. CntValue = ISC.buildOrderedLoopData(
  6254. DSA.getCurScope(),
  6255. ResultIterSpaces[CurrentNestedLoopCount].CounterVar, Captures,
  6256. Pair.first->getDependencyLoc(),
  6257. Pair.second[CurrentNestedLoopCount].first,
  6258. Pair.second[CurrentNestedLoopCount].second);
  6259. Pair.first->setLoopData(CurrentNestedLoopCount, CntValue);
  6260. }
  6261. }
  6262. return HasErrors;
  6263. }
  6264. /// Build 'VarRef = Start.
  6265. static ExprResult
  6266. buildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
  6267. ExprResult Start, bool IsNonRectangularLB,
  6268. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
  6269. // Build 'VarRef = Start.
  6270. ExprResult NewStart = IsNonRectangularLB
  6271. ? Start.get()
  6272. : tryBuildCapture(SemaRef, Start.get(), Captures);
  6273. if (!NewStart.isUsable())
  6274. return ExprError();
  6275. if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
  6276. VarRef.get()->getType())) {
  6277. NewStart = SemaRef.PerformImplicitConversion(
  6278. NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
  6279. /*AllowExplicit=*/true);
  6280. if (!NewStart.isUsable())
  6281. return ExprError();
  6282. }
  6283. ExprResult Init =
  6284. SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
  6285. return Init;
  6286. }
  6287. /// Build 'VarRef = Start + Iter * Step'.
  6288. static ExprResult buildCounterUpdate(
  6289. Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
  6290. ExprResult Start, ExprResult Iter, ExprResult Step, bool Subtract,
  6291. bool IsNonRectangularLB,
  6292. llvm::MapVector<const Expr *, DeclRefExpr *> *Captures = nullptr) {
  6293. // Add parentheses (for debugging purposes only).
  6294. Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
  6295. if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
  6296. !Step.isUsable())
  6297. return ExprError();
  6298. ExprResult NewStep = Step;
  6299. if (Captures)
  6300. NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
  6301. if (NewStep.isInvalid())
  6302. return ExprError();
  6303. ExprResult Update =
  6304. SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
  6305. if (!Update.isUsable())
  6306. return ExprError();
  6307. // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
  6308. // 'VarRef = Start (+|-) Iter * Step'.
  6309. if (!Start.isUsable())
  6310. return ExprError();
  6311. ExprResult NewStart = SemaRef.ActOnParenExpr(Loc, Loc, Start.get());
  6312. if (!NewStart.isUsable())
  6313. return ExprError();
  6314. if (Captures && !IsNonRectangularLB)
  6315. NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
  6316. if (NewStart.isInvalid())
  6317. return ExprError();
  6318. // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
  6319. ExprResult SavedUpdate = Update;
  6320. ExprResult UpdateVal;
  6321. if (VarRef.get()->getType()->isOverloadableType() ||
  6322. NewStart.get()->getType()->isOverloadableType() ||
  6323. Update.get()->getType()->isOverloadableType()) {
  6324. Sema::TentativeAnalysisScope Trap(SemaRef);
  6325. Update =
  6326. SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
  6327. if (Update.isUsable()) {
  6328. UpdateVal =
  6329. SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
  6330. VarRef.get(), SavedUpdate.get());
  6331. if (UpdateVal.isUsable()) {
  6332. Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
  6333. UpdateVal.get());
  6334. }
  6335. }
  6336. }
  6337. // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
  6338. if (!Update.isUsable() || !UpdateVal.isUsable()) {
  6339. Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
  6340. NewStart.get(), SavedUpdate.get());
  6341. if (!Update.isUsable())
  6342. return ExprError();
  6343. if (!SemaRef.Context.hasSameType(Update.get()->getType(),
  6344. VarRef.get()->getType())) {
  6345. Update = SemaRef.PerformImplicitConversion(
  6346. Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
  6347. if (!Update.isUsable())
  6348. return ExprError();
  6349. }
  6350. Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
  6351. }
  6352. return Update;
  6353. }
  6354. /// Convert integer expression \a E to make it have at least \a Bits
  6355. /// bits.
  6356. static ExprResult widenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
  6357. if (E == nullptr)
  6358. return ExprError();
  6359. ASTContext &C = SemaRef.Context;
  6360. QualType OldType = E->getType();
  6361. unsigned HasBits = C.getTypeSize(OldType);
  6362. if (HasBits >= Bits)
  6363. return ExprResult(E);
  6364. // OK to convert to signed, because new type has more bits than old.
  6365. QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
  6366. return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
  6367. true);
  6368. }
  6369. /// Check if the given expression \a E is a constant integer that fits
  6370. /// into \a Bits bits.
  6371. static bool fitsInto(unsigned Bits, bool Signed, const Expr *E, Sema &SemaRef) {
  6372. if (E == nullptr)
  6373. return false;
  6374. llvm::APSInt Result;
  6375. if (E->isIntegerConstantExpr(Result, SemaRef.Context))
  6376. return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
  6377. return false;
  6378. }
  6379. /// Build preinits statement for the given declarations.
  6380. static Stmt *buildPreInits(ASTContext &Context,
  6381. MutableArrayRef<Decl *> PreInits) {
  6382. if (!PreInits.empty()) {
  6383. return new (Context) DeclStmt(
  6384. DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
  6385. SourceLocation(), SourceLocation());
  6386. }
  6387. return nullptr;
  6388. }
  6389. /// Build preinits statement for the given declarations.
  6390. static Stmt *
  6391. buildPreInits(ASTContext &Context,
  6392. const llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
  6393. if (!Captures.empty()) {
  6394. SmallVector<Decl *, 16> PreInits;
  6395. for (const auto &Pair : Captures)
  6396. PreInits.push_back(Pair.second->getDecl());
  6397. return buildPreInits(Context, PreInits);
  6398. }
  6399. return nullptr;
  6400. }
  6401. /// Build postupdate expression for the given list of postupdates expressions.
  6402. static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
  6403. Expr *PostUpdate = nullptr;
  6404. if (!PostUpdates.empty()) {
  6405. for (Expr *E : PostUpdates) {
  6406. Expr *ConvE = S.BuildCStyleCastExpr(
  6407. E->getExprLoc(),
  6408. S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
  6409. E->getExprLoc(), E)
  6410. .get();
  6411. PostUpdate = PostUpdate
  6412. ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
  6413. PostUpdate, ConvE)
  6414. .get()
  6415. : ConvE;
  6416. }
  6417. }
  6418. return PostUpdate;
  6419. }
  6420. /// Called on a for stmt to check itself and nested loops (if any).
  6421. /// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
  6422. /// number of collapsed loops otherwise.
  6423. static unsigned
  6424. checkOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
  6425. Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
  6426. DSAStackTy &DSA,
  6427. Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
  6428. OMPLoopDirective::HelperExprs &Built) {
  6429. unsigned NestedLoopCount = 1;
  6430. if (CollapseLoopCountExpr) {
  6431. // Found 'collapse' clause - calculate collapse number.
  6432. Expr::EvalResult Result;
  6433. if (!CollapseLoopCountExpr->isValueDependent() &&
  6434. CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) {
  6435. NestedLoopCount = Result.Val.getInt().getLimitedValue();
  6436. } else {
  6437. Built.clear(/*Size=*/1);
  6438. return 1;
  6439. }
  6440. }
  6441. unsigned OrderedLoopCount = 1;
  6442. if (OrderedLoopCountExpr) {
  6443. // Found 'ordered' clause - calculate collapse number.
  6444. Expr::EvalResult EVResult;
  6445. if (!OrderedLoopCountExpr->isValueDependent() &&
  6446. OrderedLoopCountExpr->EvaluateAsInt(EVResult,
  6447. SemaRef.getASTContext())) {
  6448. llvm::APSInt Result = EVResult.Val.getInt();
  6449. if (Result.getLimitedValue() < NestedLoopCount) {
  6450. SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
  6451. diag::err_omp_wrong_ordered_loop_count)
  6452. << OrderedLoopCountExpr->getSourceRange();
  6453. SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
  6454. diag::note_collapse_loop_count)
  6455. << CollapseLoopCountExpr->getSourceRange();
  6456. }
  6457. OrderedLoopCount = Result.getLimitedValue();
  6458. } else {
  6459. Built.clear(/*Size=*/1);
  6460. return 1;
  6461. }
  6462. }
  6463. // This is helper routine for loop directives (e.g., 'for', 'simd',
  6464. // 'for simd', etc.).
  6465. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  6466. SmallVector<LoopIterationSpace, 4> IterSpaces(
  6467. std::max(OrderedLoopCount, NestedLoopCount));
  6468. Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
  6469. for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
  6470. if (checkOpenMPIterationSpace(
  6471. DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
  6472. std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr,
  6473. OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces, Captures))
  6474. return 0;
  6475. // Move on to the next nested for loop, or to the loop body.
  6476. // OpenMP [2.8.1, simd construct, Restrictions]
  6477. // All loops associated with the construct must be perfectly nested; that
  6478. // is, there must be no intervening code nor any OpenMP directive between
  6479. // any two loops.
  6480. if (auto *For = dyn_cast<ForStmt>(CurStmt)) {
  6481. CurStmt = For->getBody();
  6482. } else {
  6483. assert(isa<CXXForRangeStmt>(CurStmt) &&
  6484. "Expected canonical for or range-based for loops.");
  6485. CurStmt = cast<CXXForRangeStmt>(CurStmt)->getBody();
  6486. }
  6487. CurStmt = CurStmt->IgnoreContainers();
  6488. }
  6489. for (unsigned Cnt = NestedLoopCount; Cnt < OrderedLoopCount; ++Cnt) {
  6490. if (checkOpenMPIterationSpace(
  6491. DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
  6492. std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr,
  6493. OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces, Captures))
  6494. return 0;
  6495. if (Cnt > 0 && IterSpaces[Cnt].CounterVar) {
  6496. // Handle initialization of captured loop iterator variables.
  6497. auto *DRE = cast<DeclRefExpr>(IterSpaces[Cnt].CounterVar);
  6498. if (isa<OMPCapturedExprDecl>(DRE->getDecl())) {
  6499. Captures[DRE] = DRE;
  6500. }
  6501. }
  6502. // Move on to the next nested for loop, or to the loop body.
  6503. // OpenMP [2.8.1, simd construct, Restrictions]
  6504. // All loops associated with the construct must be perfectly nested; that
  6505. // is, there must be no intervening code nor any OpenMP directive between
  6506. // any two loops.
  6507. if (auto *For = dyn_cast<ForStmt>(CurStmt)) {
  6508. CurStmt = For->getBody();
  6509. } else {
  6510. assert(isa<CXXForRangeStmt>(CurStmt) &&
  6511. "Expected canonical for or range-based for loops.");
  6512. CurStmt = cast<CXXForRangeStmt>(CurStmt)->getBody();
  6513. }
  6514. CurStmt = CurStmt->IgnoreContainers();
  6515. }
  6516. Built.clear(/* size */ NestedLoopCount);
  6517. if (SemaRef.CurContext->isDependentContext())
  6518. return NestedLoopCount;
  6519. // An example of what is generated for the following code:
  6520. //
  6521. // #pragma omp simd collapse(2) ordered(2)
  6522. // for (i = 0; i < NI; ++i)
  6523. // for (k = 0; k < NK; ++k)
  6524. // for (j = J0; j < NJ; j+=2) {
  6525. // <loop body>
  6526. // }
  6527. //
  6528. // We generate the code below.
  6529. // Note: the loop body may be outlined in CodeGen.
  6530. // Note: some counters may be C++ classes, operator- is used to find number of
  6531. // iterations and operator+= to calculate counter value.
  6532. // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
  6533. // or i64 is currently supported).
  6534. //
  6535. // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
  6536. // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
  6537. // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
  6538. // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
  6539. // // similar updates for vars in clauses (e.g. 'linear')
  6540. // <loop body (using local i and j)>
  6541. // }
  6542. // i = NI; // assign final values of counters
  6543. // j = NJ;
  6544. //
  6545. // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
  6546. // the iteration counts of the collapsed for loops.
  6547. // Precondition tests if there is at least one iteration (all conditions are
  6548. // true).
  6549. auto PreCond = ExprResult(IterSpaces[0].PreCond);
  6550. Expr *N0 = IterSpaces[0].NumIterations;
  6551. ExprResult LastIteration32 =
  6552. widenIterationCount(/*Bits=*/32,
  6553. SemaRef
  6554. .PerformImplicitConversion(
  6555. N0->IgnoreImpCasts(), N0->getType(),
  6556. Sema::AA_Converting, /*AllowExplicit=*/true)
  6557. .get(),
  6558. SemaRef);
  6559. ExprResult LastIteration64 = widenIterationCount(
  6560. /*Bits=*/64,
  6561. SemaRef
  6562. .PerformImplicitConversion(N0->IgnoreImpCasts(), N0->getType(),
  6563. Sema::AA_Converting,
  6564. /*AllowExplicit=*/true)
  6565. .get(),
  6566. SemaRef);
  6567. if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
  6568. return NestedLoopCount;
  6569. ASTContext &C = SemaRef.Context;
  6570. bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
  6571. Scope *CurScope = DSA.getCurScope();
  6572. for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
  6573. if (PreCond.isUsable()) {
  6574. PreCond =
  6575. SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
  6576. PreCond.get(), IterSpaces[Cnt].PreCond);
  6577. }
  6578. Expr *N = IterSpaces[Cnt].NumIterations;
  6579. SourceLocation Loc = N->getExprLoc();
  6580. AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
  6581. if (LastIteration32.isUsable())
  6582. LastIteration32 = SemaRef.BuildBinOp(
  6583. CurScope, Loc, BO_Mul, LastIteration32.get(),
  6584. SemaRef
  6585. .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
  6586. Sema::AA_Converting,
  6587. /*AllowExplicit=*/true)
  6588. .get());
  6589. if (LastIteration64.isUsable())
  6590. LastIteration64 = SemaRef.BuildBinOp(
  6591. CurScope, Loc, BO_Mul, LastIteration64.get(),
  6592. SemaRef
  6593. .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
  6594. Sema::AA_Converting,
  6595. /*AllowExplicit=*/true)
  6596. .get());
  6597. }
  6598. // Choose either the 32-bit or 64-bit version.
  6599. ExprResult LastIteration = LastIteration64;
  6600. if (SemaRef.getLangOpts().OpenMPOptimisticCollapse ||
  6601. (LastIteration32.isUsable() &&
  6602. C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
  6603. (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
  6604. fitsInto(
  6605. /*Bits=*/32,
  6606. LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
  6607. LastIteration64.get(), SemaRef))))
  6608. LastIteration = LastIteration32;
  6609. QualType VType = LastIteration.get()->getType();
  6610. QualType RealVType = VType;
  6611. QualType StrideVType = VType;
  6612. if (isOpenMPTaskLoopDirective(DKind)) {
  6613. VType =
  6614. SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
  6615. StrideVType =
  6616. SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
  6617. }
  6618. if (!LastIteration.isUsable())
  6619. return 0;
  6620. // Save the number of iterations.
  6621. ExprResult NumIterations = LastIteration;
  6622. {
  6623. LastIteration = SemaRef.BuildBinOp(
  6624. CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
  6625. LastIteration.get(),
  6626. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
  6627. if (!LastIteration.isUsable())
  6628. return 0;
  6629. }
  6630. // Calculate the last iteration number beforehand instead of doing this on
  6631. // each iteration. Do not do this if the number of iterations may be kfold-ed.
  6632. llvm::APSInt Result;
  6633. bool IsConstant =
  6634. LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
  6635. ExprResult CalcLastIteration;
  6636. if (!IsConstant) {
  6637. ExprResult SaveRef =
  6638. tryBuildCapture(SemaRef, LastIteration.get(), Captures);
  6639. LastIteration = SaveRef;
  6640. // Prepare SaveRef + 1.
  6641. NumIterations = SemaRef.BuildBinOp(
  6642. CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
  6643. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
  6644. if (!NumIterations.isUsable())
  6645. return 0;
  6646. }
  6647. SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
  6648. // Build variables passed into runtime, necessary for worksharing directives.
  6649. ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB;
  6650. if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
  6651. isOpenMPDistributeDirective(DKind)) {
  6652. // Lower bound variable, initialized with zero.
  6653. VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
  6654. LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
  6655. SemaRef.AddInitializerToDecl(LBDecl,
  6656. SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
  6657. /*DirectInit*/ false);
  6658. // Upper bound variable, initialized with last iteration number.
  6659. VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
  6660. UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
  6661. SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
  6662. /*DirectInit*/ false);
  6663. // A 32-bit variable-flag where runtime returns 1 for the last iteration.
  6664. // This will be used to implement clause 'lastprivate'.
  6665. QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
  6666. VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
  6667. IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
  6668. SemaRef.AddInitializerToDecl(ILDecl,
  6669. SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
  6670. /*DirectInit*/ false);
  6671. // Stride variable returned by runtime (we initialize it to 1 by default).
  6672. VarDecl *STDecl =
  6673. buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
  6674. ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
  6675. SemaRef.AddInitializerToDecl(STDecl,
  6676. SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
  6677. /*DirectInit*/ false);
  6678. // Build expression: UB = min(UB, LastIteration)
  6679. // It is necessary for CodeGen of directives with static scheduling.
  6680. ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
  6681. UB.get(), LastIteration.get());
  6682. ExprResult CondOp = SemaRef.ActOnConditionalOp(
  6683. LastIteration.get()->getExprLoc(), InitLoc, IsUBGreater.get(),
  6684. LastIteration.get(), UB.get());
  6685. EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
  6686. CondOp.get());
  6687. EUB = SemaRef.ActOnFinishFullExpr(EUB.get(), /*DiscardedValue*/ false);
  6688. // If we have a combined directive that combines 'distribute', 'for' or
  6689. // 'simd' we need to be able to access the bounds of the schedule of the
  6690. // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
  6691. // by scheduling 'distribute' have to be passed to the schedule of 'for'.
  6692. if (isOpenMPLoopBoundSharingDirective(DKind)) {
  6693. // Lower bound variable, initialized with zero.
  6694. VarDecl *CombLBDecl =
  6695. buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb");
  6696. CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc);
  6697. SemaRef.AddInitializerToDecl(
  6698. CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
  6699. /*DirectInit*/ false);
  6700. // Upper bound variable, initialized with last iteration number.
  6701. VarDecl *CombUBDecl =
  6702. buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub");
  6703. CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc);
  6704. SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(),
  6705. /*DirectInit*/ false);
  6706. ExprResult CombIsUBGreater = SemaRef.BuildBinOp(
  6707. CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get());
  6708. ExprResult CombCondOp =
  6709. SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(),
  6710. LastIteration.get(), CombUB.get());
  6711. CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(),
  6712. CombCondOp.get());
  6713. CombEUB =
  6714. SemaRef.ActOnFinishFullExpr(CombEUB.get(), /*DiscardedValue*/ false);
  6715. const CapturedDecl *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
  6716. // We expect to have at least 2 more parameters than the 'parallel'
  6717. // directive does - the lower and upper bounds of the previous schedule.
  6718. assert(CD->getNumParams() >= 4 &&
  6719. "Unexpected number of parameters in loop combined directive");
  6720. // Set the proper type for the bounds given what we learned from the
  6721. // enclosed loops.
  6722. ImplicitParamDecl *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
  6723. ImplicitParamDecl *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
  6724. // Previous lower and upper bounds are obtained from the region
  6725. // parameters.
  6726. PrevLB =
  6727. buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
  6728. PrevUB =
  6729. buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
  6730. }
  6731. }
  6732. // Build the iteration variable and its initialization before loop.
  6733. ExprResult IV;
  6734. ExprResult Init, CombInit;
  6735. {
  6736. VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
  6737. IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
  6738. Expr *RHS =
  6739. (isOpenMPWorksharingDirective(DKind) ||
  6740. isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
  6741. ? LB.get()
  6742. : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
  6743. Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
  6744. Init = SemaRef.ActOnFinishFullExpr(Init.get(), /*DiscardedValue*/ false);
  6745. if (isOpenMPLoopBoundSharingDirective(DKind)) {
  6746. Expr *CombRHS =
  6747. (isOpenMPWorksharingDirective(DKind) ||
  6748. isOpenMPTaskLoopDirective(DKind) ||
  6749. isOpenMPDistributeDirective(DKind))
  6750. ? CombLB.get()
  6751. : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
  6752. CombInit =
  6753. SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS);
  6754. CombInit =
  6755. SemaRef.ActOnFinishFullExpr(CombInit.get(), /*DiscardedValue*/ false);
  6756. }
  6757. }
  6758. bool UseStrictCompare =
  6759. RealVType->hasUnsignedIntegerRepresentation() &&
  6760. llvm::all_of(IterSpaces, [](const LoopIterationSpace &LIS) {
  6761. return LIS.IsStrictCompare;
  6762. });
  6763. // Loop condition (IV < NumIterations) or (IV <= UB or IV < UB + 1 (for
  6764. // unsigned IV)) for worksharing loops.
  6765. SourceLocation CondLoc = AStmt->getBeginLoc();
  6766. Expr *BoundUB = UB.get();
  6767. if (UseStrictCompare) {
  6768. BoundUB =
  6769. SemaRef
  6770. .BuildBinOp(CurScope, CondLoc, BO_Add, BoundUB,
  6771. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
  6772. .get();
  6773. BoundUB =
  6774. SemaRef.ActOnFinishFullExpr(BoundUB, /*DiscardedValue*/ false).get();
  6775. }
  6776. ExprResult Cond =
  6777. (isOpenMPWorksharingDirective(DKind) ||
  6778. isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
  6779. ? SemaRef.BuildBinOp(CurScope, CondLoc,
  6780. UseStrictCompare ? BO_LT : BO_LE, IV.get(),
  6781. BoundUB)
  6782. : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
  6783. NumIterations.get());
  6784. ExprResult CombDistCond;
  6785. if (isOpenMPLoopBoundSharingDirective(DKind)) {
  6786. CombDistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
  6787. NumIterations.get());
  6788. }
  6789. ExprResult CombCond;
  6790. if (isOpenMPLoopBoundSharingDirective(DKind)) {
  6791. Expr *BoundCombUB = CombUB.get();
  6792. if (UseStrictCompare) {
  6793. BoundCombUB =
  6794. SemaRef
  6795. .BuildBinOp(
  6796. CurScope, CondLoc, BO_Add, BoundCombUB,
  6797. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
  6798. .get();
  6799. BoundCombUB =
  6800. SemaRef.ActOnFinishFullExpr(BoundCombUB, /*DiscardedValue*/ false)
  6801. .get();
  6802. }
  6803. CombCond =
  6804. SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
  6805. IV.get(), BoundCombUB);
  6806. }
  6807. // Loop increment (IV = IV + 1)
  6808. SourceLocation IncLoc = AStmt->getBeginLoc();
  6809. ExprResult Inc =
  6810. SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
  6811. SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
  6812. if (!Inc.isUsable())
  6813. return 0;
  6814. Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
  6815. Inc = SemaRef.ActOnFinishFullExpr(Inc.get(), /*DiscardedValue*/ false);
  6816. if (!Inc.isUsable())
  6817. return 0;
  6818. // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
  6819. // Used for directives with static scheduling.
  6820. // In combined construct, add combined version that use CombLB and CombUB
  6821. // base variables for the update
  6822. ExprResult NextLB, NextUB, CombNextLB, CombNextUB;
  6823. if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
  6824. isOpenMPDistributeDirective(DKind)) {
  6825. // LB + ST
  6826. NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
  6827. if (!NextLB.isUsable())
  6828. return 0;
  6829. // LB = LB + ST
  6830. NextLB =
  6831. SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
  6832. NextLB =
  6833. SemaRef.ActOnFinishFullExpr(NextLB.get(), /*DiscardedValue*/ false);
  6834. if (!NextLB.isUsable())
  6835. return 0;
  6836. // UB + ST
  6837. NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
  6838. if (!NextUB.isUsable())
  6839. return 0;
  6840. // UB = UB + ST
  6841. NextUB =
  6842. SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
  6843. NextUB =
  6844. SemaRef.ActOnFinishFullExpr(NextUB.get(), /*DiscardedValue*/ false);
  6845. if (!NextUB.isUsable())
  6846. return 0;
  6847. if (isOpenMPLoopBoundSharingDirective(DKind)) {
  6848. CombNextLB =
  6849. SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get());
  6850. if (!NextLB.isUsable())
  6851. return 0;
  6852. // LB = LB + ST
  6853. CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(),
  6854. CombNextLB.get());
  6855. CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get(),
  6856. /*DiscardedValue*/ false);
  6857. if (!CombNextLB.isUsable())
  6858. return 0;
  6859. // UB + ST
  6860. CombNextUB =
  6861. SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get());
  6862. if (!CombNextUB.isUsable())
  6863. return 0;
  6864. // UB = UB + ST
  6865. CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(),
  6866. CombNextUB.get());
  6867. CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get(),
  6868. /*DiscardedValue*/ false);
  6869. if (!CombNextUB.isUsable())
  6870. return 0;
  6871. }
  6872. }
  6873. // Create increment expression for distribute loop when combined in a same
  6874. // directive with for as IV = IV + ST; ensure upper bound expression based
  6875. // on PrevUB instead of NumIterations - used to implement 'for' when found
  6876. // in combination with 'distribute', like in 'distribute parallel for'
  6877. SourceLocation DistIncLoc = AStmt->getBeginLoc();
  6878. ExprResult DistCond, DistInc, PrevEUB, ParForInDistCond;
  6879. if (isOpenMPLoopBoundSharingDirective(DKind)) {
  6880. DistCond = SemaRef.BuildBinOp(
  6881. CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE, IV.get(), BoundUB);
  6882. assert(DistCond.isUsable() && "distribute cond expr was not built");
  6883. DistInc =
  6884. SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get());
  6885. assert(DistInc.isUsable() && "distribute inc expr was not built");
  6886. DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(),
  6887. DistInc.get());
  6888. DistInc =
  6889. SemaRef.ActOnFinishFullExpr(DistInc.get(), /*DiscardedValue*/ false);
  6890. assert(DistInc.isUsable() && "distribute inc expr was not built");
  6891. // Build expression: UB = min(UB, prevUB) for #for in composite or combined
  6892. // construct
  6893. SourceLocation DistEUBLoc = AStmt->getBeginLoc();
  6894. ExprResult IsUBGreater =
  6895. SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, UB.get(), PrevUB.get());
  6896. ExprResult CondOp = SemaRef.ActOnConditionalOp(
  6897. DistEUBLoc, DistEUBLoc, IsUBGreater.get(), PrevUB.get(), UB.get());
  6898. PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(),
  6899. CondOp.get());
  6900. PrevEUB =
  6901. SemaRef.ActOnFinishFullExpr(PrevEUB.get(), /*DiscardedValue*/ false);
  6902. // Build IV <= PrevUB or IV < PrevUB + 1 for unsigned IV to be used in
  6903. // parallel for is in combination with a distribute directive with
  6904. // schedule(static, 1)
  6905. Expr *BoundPrevUB = PrevUB.get();
  6906. if (UseStrictCompare) {
  6907. BoundPrevUB =
  6908. SemaRef
  6909. .BuildBinOp(
  6910. CurScope, CondLoc, BO_Add, BoundPrevUB,
  6911. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
  6912. .get();
  6913. BoundPrevUB =
  6914. SemaRef.ActOnFinishFullExpr(BoundPrevUB, /*DiscardedValue*/ false)
  6915. .get();
  6916. }
  6917. ParForInDistCond =
  6918. SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
  6919. IV.get(), BoundPrevUB);
  6920. }
  6921. // Build updates and final values of the loop counters.
  6922. bool HasErrors = false;
  6923. Built.Counters.resize(NestedLoopCount);
  6924. Built.Inits.resize(NestedLoopCount);
  6925. Built.Updates.resize(NestedLoopCount);
  6926. Built.Finals.resize(NestedLoopCount);
  6927. Built.DependentCounters.resize(NestedLoopCount);
  6928. Built.DependentInits.resize(NestedLoopCount);
  6929. Built.FinalsConditions.resize(NestedLoopCount);
  6930. {
  6931. // We implement the following algorithm for obtaining the
  6932. // original loop iteration variable values based on the
  6933. // value of the collapsed loop iteration variable IV.
  6934. //
  6935. // Let n+1 be the number of collapsed loops in the nest.
  6936. // Iteration variables (I0, I1, .... In)
  6937. // Iteration counts (N0, N1, ... Nn)
  6938. //
  6939. // Acc = IV;
  6940. //
  6941. // To compute Ik for loop k, 0 <= k <= n, generate:
  6942. // Prod = N(k+1) * N(k+2) * ... * Nn;
  6943. // Ik = Acc / Prod;
  6944. // Acc -= Ik * Prod;
  6945. //
  6946. ExprResult Acc = IV;
  6947. for (unsigned int Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
  6948. LoopIterationSpace &IS = IterSpaces[Cnt];
  6949. SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
  6950. ExprResult Iter;
  6951. // Compute prod
  6952. ExprResult Prod =
  6953. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
  6954. for (unsigned int K = Cnt+1; K < NestedLoopCount; ++K)
  6955. Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Prod.get(),
  6956. IterSpaces[K].NumIterations);
  6957. // Iter = Acc / Prod
  6958. // If there is at least one more inner loop to avoid
  6959. // multiplication by 1.
  6960. if (Cnt + 1 < NestedLoopCount)
  6961. Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div,
  6962. Acc.get(), Prod.get());
  6963. else
  6964. Iter = Acc;
  6965. if (!Iter.isUsable()) {
  6966. HasErrors = true;
  6967. break;
  6968. }
  6969. // Update Acc:
  6970. // Acc -= Iter * Prod
  6971. // Check if there is at least one more inner loop to avoid
  6972. // multiplication by 1.
  6973. if (Cnt + 1 < NestedLoopCount)
  6974. Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul,
  6975. Iter.get(), Prod.get());
  6976. else
  6977. Prod = Iter;
  6978. Acc = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Sub,
  6979. Acc.get(), Prod.get());
  6980. // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
  6981. auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
  6982. DeclRefExpr *CounterVar = buildDeclRefExpr(
  6983. SemaRef, VD, IS.CounterVar->getType(), IS.CounterVar->getExprLoc(),
  6984. /*RefersToCapture=*/true);
  6985. ExprResult Init =
  6986. buildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
  6987. IS.CounterInit, IS.IsNonRectangularLB, Captures);
  6988. if (!Init.isUsable()) {
  6989. HasErrors = true;
  6990. break;
  6991. }
  6992. ExprResult Update = buildCounterUpdate(
  6993. SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
  6994. IS.CounterStep, IS.Subtract, IS.IsNonRectangularLB, &Captures);
  6995. if (!Update.isUsable()) {
  6996. HasErrors = true;
  6997. break;
  6998. }
  6999. // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
  7000. ExprResult Final =
  7001. buildCounterUpdate(SemaRef, CurScope, UpdLoc, CounterVar,
  7002. IS.CounterInit, IS.NumIterations, IS.CounterStep,
  7003. IS.Subtract, IS.IsNonRectangularLB, &Captures);
  7004. if (!Final.isUsable()) {
  7005. HasErrors = true;
  7006. break;
  7007. }
  7008. if (!Update.isUsable() || !Final.isUsable()) {
  7009. HasErrors = true;
  7010. break;
  7011. }
  7012. // Save results
  7013. Built.Counters[Cnt] = IS.CounterVar;
  7014. Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
  7015. Built.Inits[Cnt] = Init.get();
  7016. Built.Updates[Cnt] = Update.get();
  7017. Built.Finals[Cnt] = Final.get();
  7018. Built.DependentCounters[Cnt] = nullptr;
  7019. Built.DependentInits[Cnt] = nullptr;
  7020. Built.FinalsConditions[Cnt] = nullptr;
  7021. if (IS.IsNonRectangularLB || IS.IsNonRectangularUB) {
  7022. Built.DependentCounters[Cnt] =
  7023. Built.Counters[NestedLoopCount - 1 - IS.LoopDependentIdx];
  7024. Built.DependentInits[Cnt] =
  7025. Built.Inits[NestedLoopCount - 1 - IS.LoopDependentIdx];
  7026. Built.FinalsConditions[Cnt] = IS.FinalCondition;
  7027. }
  7028. }
  7029. }
  7030. if (HasErrors)
  7031. return 0;
  7032. // Save results
  7033. Built.IterationVarRef = IV.get();
  7034. Built.LastIteration = LastIteration.get();
  7035. Built.NumIterations = NumIterations.get();
  7036. Built.CalcLastIteration = SemaRef
  7037. .ActOnFinishFullExpr(CalcLastIteration.get(),
  7038. /*DiscardedValue=*/false)
  7039. .get();
  7040. Built.PreCond = PreCond.get();
  7041. Built.PreInits = buildPreInits(C, Captures);
  7042. Built.Cond = Cond.get();
  7043. Built.Init = Init.get();
  7044. Built.Inc = Inc.get();
  7045. Built.LB = LB.get();
  7046. Built.UB = UB.get();
  7047. Built.IL = IL.get();
  7048. Built.ST = ST.get();
  7049. Built.EUB = EUB.get();
  7050. Built.NLB = NextLB.get();
  7051. Built.NUB = NextUB.get();
  7052. Built.PrevLB = PrevLB.get();
  7053. Built.PrevUB = PrevUB.get();
  7054. Built.DistInc = DistInc.get();
  7055. Built.PrevEUB = PrevEUB.get();
  7056. Built.DistCombinedFields.LB = CombLB.get();
  7057. Built.DistCombinedFields.UB = CombUB.get();
  7058. Built.DistCombinedFields.EUB = CombEUB.get();
  7059. Built.DistCombinedFields.Init = CombInit.get();
  7060. Built.DistCombinedFields.Cond = CombCond.get();
  7061. Built.DistCombinedFields.NLB = CombNextLB.get();
  7062. Built.DistCombinedFields.NUB = CombNextUB.get();
  7063. Built.DistCombinedFields.DistCond = CombDistCond.get();
  7064. Built.DistCombinedFields.ParForInDistCond = ParForInDistCond.get();
  7065. return NestedLoopCount;
  7066. }
  7067. static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
  7068. auto CollapseClauses =
  7069. OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
  7070. if (CollapseClauses.begin() != CollapseClauses.end())
  7071. return (*CollapseClauses.begin())->getNumForLoops();
  7072. return nullptr;
  7073. }
  7074. static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
  7075. auto OrderedClauses =
  7076. OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
  7077. if (OrderedClauses.begin() != OrderedClauses.end())
  7078. return (*OrderedClauses.begin())->getNumForLoops();
  7079. return nullptr;
  7080. }
  7081. static bool checkSimdlenSafelenSpecified(Sema &S,
  7082. const ArrayRef<OMPClause *> Clauses) {
  7083. const OMPSafelenClause *Safelen = nullptr;
  7084. const OMPSimdlenClause *Simdlen = nullptr;
  7085. for (const OMPClause *Clause : Clauses) {
  7086. if (Clause->getClauseKind() == OMPC_safelen)
  7087. Safelen = cast<OMPSafelenClause>(Clause);
  7088. else if (Clause->getClauseKind() == OMPC_simdlen)
  7089. Simdlen = cast<OMPSimdlenClause>(Clause);
  7090. if (Safelen && Simdlen)
  7091. break;
  7092. }
  7093. if (Simdlen && Safelen) {
  7094. const Expr *SimdlenLength = Simdlen->getSimdlen();
  7095. const Expr *SafelenLength = Safelen->getSafelen();
  7096. if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
  7097. SimdlenLength->isInstantiationDependent() ||
  7098. SimdlenLength->containsUnexpandedParameterPack())
  7099. return false;
  7100. if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
  7101. SafelenLength->isInstantiationDependent() ||
  7102. SafelenLength->containsUnexpandedParameterPack())
  7103. return false;
  7104. Expr::EvalResult SimdlenResult, SafelenResult;
  7105. SimdlenLength->EvaluateAsInt(SimdlenResult, S.Context);
  7106. SafelenLength->EvaluateAsInt(SafelenResult, S.Context);
  7107. llvm::APSInt SimdlenRes = SimdlenResult.Val.getInt();
  7108. llvm::APSInt SafelenRes = SafelenResult.Val.getInt();
  7109. // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
  7110. // If both simdlen and safelen clauses are specified, the value of the
  7111. // simdlen parameter must be less than or equal to the value of the safelen
  7112. // parameter.
  7113. if (SimdlenRes > SafelenRes) {
  7114. S.Diag(SimdlenLength->getExprLoc(),
  7115. diag::err_omp_wrong_simdlen_safelen_values)
  7116. << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
  7117. return true;
  7118. }
  7119. }
  7120. return false;
  7121. }
  7122. StmtResult
  7123. Sema::ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
  7124. SourceLocation StartLoc, SourceLocation EndLoc,
  7125. VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  7126. if (!AStmt)
  7127. return StmtError();
  7128. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  7129. OMPLoopDirective::HelperExprs B;
  7130. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  7131. // define the nested loops number.
  7132. unsigned NestedLoopCount = checkOpenMPLoop(
  7133. OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
  7134. AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
  7135. if (NestedLoopCount == 0)
  7136. return StmtError();
  7137. assert((CurContext->isDependentContext() || B.builtAll()) &&
  7138. "omp simd loop exprs were not built");
  7139. if (!CurContext->isDependentContext()) {
  7140. // Finalize the clauses that need pre-built expressions for CodeGen.
  7141. for (OMPClause *C : Clauses) {
  7142. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  7143. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  7144. B.NumIterations, *this, CurScope,
  7145. DSAStack))
  7146. return StmtError();
  7147. }
  7148. }
  7149. if (checkSimdlenSafelenSpecified(*this, Clauses))
  7150. return StmtError();
  7151. setFunctionHasBranchProtectedScope();
  7152. return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
  7153. Clauses, AStmt, B);
  7154. }
  7155. StmtResult
  7156. Sema::ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
  7157. SourceLocation StartLoc, SourceLocation EndLoc,
  7158. VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  7159. if (!AStmt)
  7160. return StmtError();
  7161. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  7162. OMPLoopDirective::HelperExprs B;
  7163. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  7164. // define the nested loops number.
  7165. unsigned NestedLoopCount = checkOpenMPLoop(
  7166. OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
  7167. AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
  7168. if (NestedLoopCount == 0)
  7169. return StmtError();
  7170. assert((CurContext->isDependentContext() || B.builtAll()) &&
  7171. "omp for loop exprs were not built");
  7172. if (!CurContext->isDependentContext()) {
  7173. // Finalize the clauses that need pre-built expressions for CodeGen.
  7174. for (OMPClause *C : Clauses) {
  7175. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  7176. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  7177. B.NumIterations, *this, CurScope,
  7178. DSAStack))
  7179. return StmtError();
  7180. }
  7181. }
  7182. setFunctionHasBranchProtectedScope();
  7183. return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
  7184. Clauses, AStmt, B, DSAStack->isCancelRegion());
  7185. }
  7186. StmtResult Sema::ActOnOpenMPForSimdDirective(
  7187. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  7188. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  7189. if (!AStmt)
  7190. return StmtError();
  7191. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  7192. OMPLoopDirective::HelperExprs B;
  7193. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  7194. // define the nested loops number.
  7195. unsigned NestedLoopCount =
  7196. checkOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
  7197. getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
  7198. VarsWithImplicitDSA, B);
  7199. if (NestedLoopCount == 0)
  7200. return StmtError();
  7201. assert((CurContext->isDependentContext() || B.builtAll()) &&
  7202. "omp for simd loop exprs were not built");
  7203. if (!CurContext->isDependentContext()) {
  7204. // Finalize the clauses that need pre-built expressions for CodeGen.
  7205. for (OMPClause *C : Clauses) {
  7206. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  7207. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  7208. B.NumIterations, *this, CurScope,
  7209. DSAStack))
  7210. return StmtError();
  7211. }
  7212. }
  7213. if (checkSimdlenSafelenSpecified(*this, Clauses))
  7214. return StmtError();
  7215. setFunctionHasBranchProtectedScope();
  7216. return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
  7217. Clauses, AStmt, B);
  7218. }
  7219. StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
  7220. Stmt *AStmt,
  7221. SourceLocation StartLoc,
  7222. SourceLocation EndLoc) {
  7223. if (!AStmt)
  7224. return StmtError();
  7225. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  7226. auto BaseStmt = AStmt;
  7227. while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
  7228. BaseStmt = CS->getCapturedStmt();
  7229. if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
  7230. auto S = C->children();
  7231. if (S.begin() == S.end())
  7232. return StmtError();
  7233. // All associated statements must be '#pragma omp section' except for
  7234. // the first one.
  7235. for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
  7236. if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
  7237. if (SectionStmt)
  7238. Diag(SectionStmt->getBeginLoc(),
  7239. diag::err_omp_sections_substmt_not_section);
  7240. return StmtError();
  7241. }
  7242. cast<OMPSectionDirective>(SectionStmt)
  7243. ->setHasCancel(DSAStack->isCancelRegion());
  7244. }
  7245. } else {
  7246. Diag(AStmt->getBeginLoc(), diag::err_omp_sections_not_compound_stmt);
  7247. return StmtError();
  7248. }
  7249. setFunctionHasBranchProtectedScope();
  7250. return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
  7251. DSAStack->isCancelRegion());
  7252. }
  7253. StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
  7254. SourceLocation StartLoc,
  7255. SourceLocation EndLoc) {
  7256. if (!AStmt)
  7257. return StmtError();
  7258. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  7259. setFunctionHasBranchProtectedScope();
  7260. DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
  7261. return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
  7262. DSAStack->isCancelRegion());
  7263. }
  7264. StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
  7265. Stmt *AStmt,
  7266. SourceLocation StartLoc,
  7267. SourceLocation EndLoc) {
  7268. if (!AStmt)
  7269. return StmtError();
  7270. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  7271. setFunctionHasBranchProtectedScope();
  7272. // OpenMP [2.7.3, single Construct, Restrictions]
  7273. // The copyprivate clause must not be used with the nowait clause.
  7274. const OMPClause *Nowait = nullptr;
  7275. const OMPClause *Copyprivate = nullptr;
  7276. for (const OMPClause *Clause : Clauses) {
  7277. if (Clause->getClauseKind() == OMPC_nowait)
  7278. Nowait = Clause;
  7279. else if (Clause->getClauseKind() == OMPC_copyprivate)
  7280. Copyprivate = Clause;
  7281. if (Copyprivate && Nowait) {
  7282. Diag(Copyprivate->getBeginLoc(),
  7283. diag::err_omp_single_copyprivate_with_nowait);
  7284. Diag(Nowait->getBeginLoc(), diag::note_omp_nowait_clause_here);
  7285. return StmtError();
  7286. }
  7287. }
  7288. return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
  7289. }
  7290. StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
  7291. SourceLocation StartLoc,
  7292. SourceLocation EndLoc) {
  7293. if (!AStmt)
  7294. return StmtError();
  7295. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  7296. setFunctionHasBranchProtectedScope();
  7297. return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
  7298. }
  7299. StmtResult Sema::ActOnOpenMPCriticalDirective(
  7300. const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
  7301. Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
  7302. if (!AStmt)
  7303. return StmtError();
  7304. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  7305. bool ErrorFound = false;
  7306. llvm::APSInt Hint;
  7307. SourceLocation HintLoc;
  7308. bool DependentHint = false;
  7309. for (const OMPClause *C : Clauses) {
  7310. if (C->getClauseKind() == OMPC_hint) {
  7311. if (!DirName.getName()) {
  7312. Diag(C->getBeginLoc(), diag::err_omp_hint_clause_no_name);
  7313. ErrorFound = true;
  7314. }
  7315. Expr *E = cast<OMPHintClause>(C)->getHint();
  7316. if (E->isTypeDependent() || E->isValueDependent() ||
  7317. E->isInstantiationDependent()) {
  7318. DependentHint = true;
  7319. } else {
  7320. Hint = E->EvaluateKnownConstInt(Context);
  7321. HintLoc = C->getBeginLoc();
  7322. }
  7323. }
  7324. }
  7325. if (ErrorFound)
  7326. return StmtError();
  7327. const auto Pair = DSAStack->getCriticalWithHint(DirName);
  7328. if (Pair.first && DirName.getName() && !DependentHint) {
  7329. if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
  7330. Diag(StartLoc, diag::err_omp_critical_with_hint);
  7331. if (HintLoc.isValid())
  7332. Diag(HintLoc, diag::note_omp_critical_hint_here)
  7333. << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
  7334. else
  7335. Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
  7336. if (const auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
  7337. Diag(C->getBeginLoc(), diag::note_omp_critical_hint_here)
  7338. << 1
  7339. << C->getHint()->EvaluateKnownConstInt(Context).toString(
  7340. /*Radix=*/10, /*Signed=*/false);
  7341. } else {
  7342. Diag(Pair.first->getBeginLoc(), diag::note_omp_critical_no_hint) << 1;
  7343. }
  7344. }
  7345. }
  7346. setFunctionHasBranchProtectedScope();
  7347. auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
  7348. Clauses, AStmt);
  7349. if (!Pair.first && DirName.getName() && !DependentHint)
  7350. DSAStack->addCriticalWithHint(Dir, Hint);
  7351. return Dir;
  7352. }
  7353. StmtResult Sema::ActOnOpenMPParallelForDirective(
  7354. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  7355. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  7356. if (!AStmt)
  7357. return StmtError();
  7358. auto *CS = cast<CapturedStmt>(AStmt);
  7359. // 1.2.2 OpenMP Language Terminology
  7360. // Structured block - An executable statement with a single entry at the
  7361. // top and a single exit at the bottom.
  7362. // The point of exit cannot be a branch out of the structured block.
  7363. // longjmp() and throw() must not violate the entry/exit criteria.
  7364. CS->getCapturedDecl()->setNothrow();
  7365. OMPLoopDirective::HelperExprs B;
  7366. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  7367. // define the nested loops number.
  7368. unsigned NestedLoopCount =
  7369. checkOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
  7370. getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
  7371. VarsWithImplicitDSA, B);
  7372. if (NestedLoopCount == 0)
  7373. return StmtError();
  7374. assert((CurContext->isDependentContext() || B.builtAll()) &&
  7375. "omp parallel for loop exprs were not built");
  7376. if (!CurContext->isDependentContext()) {
  7377. // Finalize the clauses that need pre-built expressions for CodeGen.
  7378. for (OMPClause *C : Clauses) {
  7379. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  7380. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  7381. B.NumIterations, *this, CurScope,
  7382. DSAStack))
  7383. return StmtError();
  7384. }
  7385. }
  7386. setFunctionHasBranchProtectedScope();
  7387. return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
  7388. NestedLoopCount, Clauses, AStmt, B,
  7389. DSAStack->isCancelRegion());
  7390. }
  7391. StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
  7392. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  7393. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  7394. if (!AStmt)
  7395. return StmtError();
  7396. auto *CS = cast<CapturedStmt>(AStmt);
  7397. // 1.2.2 OpenMP Language Terminology
  7398. // Structured block - An executable statement with a single entry at the
  7399. // top and a single exit at the bottom.
  7400. // The point of exit cannot be a branch out of the structured block.
  7401. // longjmp() and throw() must not violate the entry/exit criteria.
  7402. CS->getCapturedDecl()->setNothrow();
  7403. OMPLoopDirective::HelperExprs B;
  7404. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  7405. // define the nested loops number.
  7406. unsigned NestedLoopCount =
  7407. checkOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
  7408. getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
  7409. VarsWithImplicitDSA, B);
  7410. if (NestedLoopCount == 0)
  7411. return StmtError();
  7412. if (!CurContext->isDependentContext()) {
  7413. // Finalize the clauses that need pre-built expressions for CodeGen.
  7414. for (OMPClause *C : Clauses) {
  7415. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  7416. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  7417. B.NumIterations, *this, CurScope,
  7418. DSAStack))
  7419. return StmtError();
  7420. }
  7421. }
  7422. if (checkSimdlenSafelenSpecified(*this, Clauses))
  7423. return StmtError();
  7424. setFunctionHasBranchProtectedScope();
  7425. return OMPParallelForSimdDirective::Create(
  7426. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  7427. }
  7428. StmtResult
  7429. Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
  7430. Stmt *AStmt, SourceLocation StartLoc,
  7431. SourceLocation EndLoc) {
  7432. if (!AStmt)
  7433. return StmtError();
  7434. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  7435. auto BaseStmt = AStmt;
  7436. while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
  7437. BaseStmt = CS->getCapturedStmt();
  7438. if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
  7439. auto S = C->children();
  7440. if (S.begin() == S.end())
  7441. return StmtError();
  7442. // All associated statements must be '#pragma omp section' except for
  7443. // the first one.
  7444. for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
  7445. if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
  7446. if (SectionStmt)
  7447. Diag(SectionStmt->getBeginLoc(),
  7448. diag::err_omp_parallel_sections_substmt_not_section);
  7449. return StmtError();
  7450. }
  7451. cast<OMPSectionDirective>(SectionStmt)
  7452. ->setHasCancel(DSAStack->isCancelRegion());
  7453. }
  7454. } else {
  7455. Diag(AStmt->getBeginLoc(),
  7456. diag::err_omp_parallel_sections_not_compound_stmt);
  7457. return StmtError();
  7458. }
  7459. setFunctionHasBranchProtectedScope();
  7460. return OMPParallelSectionsDirective::Create(
  7461. Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
  7462. }
  7463. StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
  7464. Stmt *AStmt, SourceLocation StartLoc,
  7465. SourceLocation EndLoc) {
  7466. if (!AStmt)
  7467. return StmtError();
  7468. auto *CS = cast<CapturedStmt>(AStmt);
  7469. // 1.2.2 OpenMP Language Terminology
  7470. // Structured block - An executable statement with a single entry at the
  7471. // top and a single exit at the bottom.
  7472. // The point of exit cannot be a branch out of the structured block.
  7473. // longjmp() and throw() must not violate the entry/exit criteria.
  7474. CS->getCapturedDecl()->setNothrow();
  7475. setFunctionHasBranchProtectedScope();
  7476. return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
  7477. DSAStack->isCancelRegion());
  7478. }
  7479. StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
  7480. SourceLocation EndLoc) {
  7481. return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
  7482. }
  7483. StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
  7484. SourceLocation EndLoc) {
  7485. return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
  7486. }
  7487. StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
  7488. SourceLocation EndLoc) {
  7489. return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
  7490. }
  7491. StmtResult Sema::ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
  7492. Stmt *AStmt,
  7493. SourceLocation StartLoc,
  7494. SourceLocation EndLoc) {
  7495. if (!AStmt)
  7496. return StmtError();
  7497. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  7498. setFunctionHasBranchProtectedScope();
  7499. return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, Clauses,
  7500. AStmt,
  7501. DSAStack->getTaskgroupReductionRef());
  7502. }
  7503. StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
  7504. SourceLocation StartLoc,
  7505. SourceLocation EndLoc) {
  7506. assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
  7507. return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
  7508. }
  7509. StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
  7510. Stmt *AStmt,
  7511. SourceLocation StartLoc,
  7512. SourceLocation EndLoc) {
  7513. const OMPClause *DependFound = nullptr;
  7514. const OMPClause *DependSourceClause = nullptr;
  7515. const OMPClause *DependSinkClause = nullptr;
  7516. bool ErrorFound = false;
  7517. const OMPThreadsClause *TC = nullptr;
  7518. const OMPSIMDClause *SC = nullptr;
  7519. for (const OMPClause *C : Clauses) {
  7520. if (auto *DC = dyn_cast<OMPDependClause>(C)) {
  7521. DependFound = C;
  7522. if (DC->getDependencyKind() == OMPC_DEPEND_source) {
  7523. if (DependSourceClause) {
  7524. Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
  7525. << getOpenMPDirectiveName(OMPD_ordered)
  7526. << getOpenMPClauseName(OMPC_depend) << 2;
  7527. ErrorFound = true;
  7528. } else {
  7529. DependSourceClause = C;
  7530. }
  7531. if (DependSinkClause) {
  7532. Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
  7533. << 0;
  7534. ErrorFound = true;
  7535. }
  7536. } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
  7537. if (DependSourceClause) {
  7538. Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
  7539. << 1;
  7540. ErrorFound = true;
  7541. }
  7542. DependSinkClause = C;
  7543. }
  7544. } else if (C->getClauseKind() == OMPC_threads) {
  7545. TC = cast<OMPThreadsClause>(C);
  7546. } else if (C->getClauseKind() == OMPC_simd) {
  7547. SC = cast<OMPSIMDClause>(C);
  7548. }
  7549. }
  7550. if (!ErrorFound && !SC &&
  7551. isOpenMPSimdDirective(DSAStack->getParentDirective())) {
  7552. // OpenMP [2.8.1,simd Construct, Restrictions]
  7553. // An ordered construct with the simd clause is the only OpenMP construct
  7554. // that can appear in the simd region.
  7555. Diag(StartLoc, diag::err_omp_prohibited_region_simd);
  7556. ErrorFound = true;
  7557. } else if (DependFound && (TC || SC)) {
  7558. Diag(DependFound->getBeginLoc(), diag::err_omp_depend_clause_thread_simd)
  7559. << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
  7560. ErrorFound = true;
  7561. } else if (DependFound && !DSAStack->getParentOrderedRegionParam().first) {
  7562. Diag(DependFound->getBeginLoc(),
  7563. diag::err_omp_ordered_directive_without_param);
  7564. ErrorFound = true;
  7565. } else if (TC || Clauses.empty()) {
  7566. if (const Expr *Param = DSAStack->getParentOrderedRegionParam().first) {
  7567. SourceLocation ErrLoc = TC ? TC->getBeginLoc() : StartLoc;
  7568. Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
  7569. << (TC != nullptr);
  7570. Diag(Param->getBeginLoc(), diag::note_omp_ordered_param);
  7571. ErrorFound = true;
  7572. }
  7573. }
  7574. if ((!AStmt && !DependFound) || ErrorFound)
  7575. return StmtError();
  7576. if (AStmt) {
  7577. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  7578. setFunctionHasBranchProtectedScope();
  7579. }
  7580. return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
  7581. }
  7582. namespace {
  7583. /// Helper class for checking expression in 'omp atomic [update]'
  7584. /// construct.
  7585. class OpenMPAtomicUpdateChecker {
  7586. /// Error results for atomic update expressions.
  7587. enum ExprAnalysisErrorCode {
  7588. /// A statement is not an expression statement.
  7589. NotAnExpression,
  7590. /// Expression is not builtin binary or unary operation.
  7591. NotABinaryOrUnaryExpression,
  7592. /// Unary operation is not post-/pre- increment/decrement operation.
  7593. NotAnUnaryIncDecExpression,
  7594. /// An expression is not of scalar type.
  7595. NotAScalarType,
  7596. /// A binary operation is not an assignment operation.
  7597. NotAnAssignmentOp,
  7598. /// RHS part of the binary operation is not a binary expression.
  7599. NotABinaryExpression,
  7600. /// RHS part is not additive/multiplicative/shift/biwise binary
  7601. /// expression.
  7602. NotABinaryOperator,
  7603. /// RHS binary operation does not have reference to the updated LHS
  7604. /// part.
  7605. NotAnUpdateExpression,
  7606. /// No errors is found.
  7607. NoError
  7608. };
  7609. /// Reference to Sema.
  7610. Sema &SemaRef;
  7611. /// A location for note diagnostics (when error is found).
  7612. SourceLocation NoteLoc;
  7613. /// 'x' lvalue part of the source atomic expression.
  7614. Expr *X;
  7615. /// 'expr' rvalue part of the source atomic expression.
  7616. Expr *E;
  7617. /// Helper expression of the form
  7618. /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
  7619. /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
  7620. Expr *UpdateExpr;
  7621. /// Is 'x' a LHS in a RHS part of full update expression. It is
  7622. /// important for non-associative operations.
  7623. bool IsXLHSInRHSPart;
  7624. BinaryOperatorKind Op;
  7625. SourceLocation OpLoc;
  7626. /// true if the source expression is a postfix unary operation, false
  7627. /// if it is a prefix unary operation.
  7628. bool IsPostfixUpdate;
  7629. public:
  7630. OpenMPAtomicUpdateChecker(Sema &SemaRef)
  7631. : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
  7632. IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
  7633. /// Check specified statement that it is suitable for 'atomic update'
  7634. /// constructs and extract 'x', 'expr' and Operation from the original
  7635. /// expression. If DiagId and NoteId == 0, then only check is performed
  7636. /// without error notification.
  7637. /// \param DiagId Diagnostic which should be emitted if error is found.
  7638. /// \param NoteId Diagnostic note for the main error message.
  7639. /// \return true if statement is not an update expression, false otherwise.
  7640. bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
  7641. /// Return the 'x' lvalue part of the source atomic expression.
  7642. Expr *getX() const { return X; }
  7643. /// Return the 'expr' rvalue part of the source atomic expression.
  7644. Expr *getExpr() const { return E; }
  7645. /// Return the update expression used in calculation of the updated
  7646. /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
  7647. /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
  7648. Expr *getUpdateExpr() const { return UpdateExpr; }
  7649. /// Return true if 'x' is LHS in RHS part of full update expression,
  7650. /// false otherwise.
  7651. bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
  7652. /// true if the source expression is a postfix unary operation, false
  7653. /// if it is a prefix unary operation.
  7654. bool isPostfixUpdate() const { return IsPostfixUpdate; }
  7655. private:
  7656. bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
  7657. unsigned NoteId = 0);
  7658. };
  7659. } // namespace
  7660. bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
  7661. BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
  7662. ExprAnalysisErrorCode ErrorFound = NoError;
  7663. SourceLocation ErrorLoc, NoteLoc;
  7664. SourceRange ErrorRange, NoteRange;
  7665. // Allowed constructs are:
  7666. // x = x binop expr;
  7667. // x = expr binop x;
  7668. if (AtomicBinOp->getOpcode() == BO_Assign) {
  7669. X = AtomicBinOp->getLHS();
  7670. if (const auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
  7671. AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
  7672. if (AtomicInnerBinOp->isMultiplicativeOp() ||
  7673. AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
  7674. AtomicInnerBinOp->isBitwiseOp()) {
  7675. Op = AtomicInnerBinOp->getOpcode();
  7676. OpLoc = AtomicInnerBinOp->getOperatorLoc();
  7677. Expr *LHS = AtomicInnerBinOp->getLHS();
  7678. Expr *RHS = AtomicInnerBinOp->getRHS();
  7679. llvm::FoldingSetNodeID XId, LHSId, RHSId;
  7680. X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
  7681. /*Canonical=*/true);
  7682. LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
  7683. /*Canonical=*/true);
  7684. RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
  7685. /*Canonical=*/true);
  7686. if (XId == LHSId) {
  7687. E = RHS;
  7688. IsXLHSInRHSPart = true;
  7689. } else if (XId == RHSId) {
  7690. E = LHS;
  7691. IsXLHSInRHSPart = false;
  7692. } else {
  7693. ErrorLoc = AtomicInnerBinOp->getExprLoc();
  7694. ErrorRange = AtomicInnerBinOp->getSourceRange();
  7695. NoteLoc = X->getExprLoc();
  7696. NoteRange = X->getSourceRange();
  7697. ErrorFound = NotAnUpdateExpression;
  7698. }
  7699. } else {
  7700. ErrorLoc = AtomicInnerBinOp->getExprLoc();
  7701. ErrorRange = AtomicInnerBinOp->getSourceRange();
  7702. NoteLoc = AtomicInnerBinOp->getOperatorLoc();
  7703. NoteRange = SourceRange(NoteLoc, NoteLoc);
  7704. ErrorFound = NotABinaryOperator;
  7705. }
  7706. } else {
  7707. NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
  7708. NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
  7709. ErrorFound = NotABinaryExpression;
  7710. }
  7711. } else {
  7712. ErrorLoc = AtomicBinOp->getExprLoc();
  7713. ErrorRange = AtomicBinOp->getSourceRange();
  7714. NoteLoc = AtomicBinOp->getOperatorLoc();
  7715. NoteRange = SourceRange(NoteLoc, NoteLoc);
  7716. ErrorFound = NotAnAssignmentOp;
  7717. }
  7718. if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
  7719. SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
  7720. SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
  7721. return true;
  7722. }
  7723. if (SemaRef.CurContext->isDependentContext())
  7724. E = X = UpdateExpr = nullptr;
  7725. return ErrorFound != NoError;
  7726. }
  7727. bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
  7728. unsigned NoteId) {
  7729. ExprAnalysisErrorCode ErrorFound = NoError;
  7730. SourceLocation ErrorLoc, NoteLoc;
  7731. SourceRange ErrorRange, NoteRange;
  7732. // Allowed constructs are:
  7733. // x++;
  7734. // x--;
  7735. // ++x;
  7736. // --x;
  7737. // x binop= expr;
  7738. // x = x binop expr;
  7739. // x = expr binop x;
  7740. if (auto *AtomicBody = dyn_cast<Expr>(S)) {
  7741. AtomicBody = AtomicBody->IgnoreParenImpCasts();
  7742. if (AtomicBody->getType()->isScalarType() ||
  7743. AtomicBody->isInstantiationDependent()) {
  7744. if (const auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
  7745. AtomicBody->IgnoreParenImpCasts())) {
  7746. // Check for Compound Assignment Operation
  7747. Op = BinaryOperator::getOpForCompoundAssignment(
  7748. AtomicCompAssignOp->getOpcode());
  7749. OpLoc = AtomicCompAssignOp->getOperatorLoc();
  7750. E = AtomicCompAssignOp->getRHS();
  7751. X = AtomicCompAssignOp->getLHS()->IgnoreParens();
  7752. IsXLHSInRHSPart = true;
  7753. } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
  7754. AtomicBody->IgnoreParenImpCasts())) {
  7755. // Check for Binary Operation
  7756. if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
  7757. return true;
  7758. } else if (const auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
  7759. AtomicBody->IgnoreParenImpCasts())) {
  7760. // Check for Unary Operation
  7761. if (AtomicUnaryOp->isIncrementDecrementOp()) {
  7762. IsPostfixUpdate = AtomicUnaryOp->isPostfix();
  7763. Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
  7764. OpLoc = AtomicUnaryOp->getOperatorLoc();
  7765. X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
  7766. E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
  7767. IsXLHSInRHSPart = true;
  7768. } else {
  7769. ErrorFound = NotAnUnaryIncDecExpression;
  7770. ErrorLoc = AtomicUnaryOp->getExprLoc();
  7771. ErrorRange = AtomicUnaryOp->getSourceRange();
  7772. NoteLoc = AtomicUnaryOp->getOperatorLoc();
  7773. NoteRange = SourceRange(NoteLoc, NoteLoc);
  7774. }
  7775. } else if (!AtomicBody->isInstantiationDependent()) {
  7776. ErrorFound = NotABinaryOrUnaryExpression;
  7777. NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
  7778. NoteRange = ErrorRange = AtomicBody->getSourceRange();
  7779. }
  7780. } else {
  7781. ErrorFound = NotAScalarType;
  7782. NoteLoc = ErrorLoc = AtomicBody->getBeginLoc();
  7783. NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
  7784. }
  7785. } else {
  7786. ErrorFound = NotAnExpression;
  7787. NoteLoc = ErrorLoc = S->getBeginLoc();
  7788. NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
  7789. }
  7790. if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
  7791. SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
  7792. SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
  7793. return true;
  7794. }
  7795. if (SemaRef.CurContext->isDependentContext())
  7796. E = X = UpdateExpr = nullptr;
  7797. if (ErrorFound == NoError && E && X) {
  7798. // Build an update expression of form 'OpaqueValueExpr(x) binop
  7799. // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
  7800. // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
  7801. auto *OVEX = new (SemaRef.getASTContext())
  7802. OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
  7803. auto *OVEExpr = new (SemaRef.getASTContext())
  7804. OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
  7805. ExprResult Update =
  7806. SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
  7807. IsXLHSInRHSPart ? OVEExpr : OVEX);
  7808. if (Update.isInvalid())
  7809. return true;
  7810. Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
  7811. Sema::AA_Casting);
  7812. if (Update.isInvalid())
  7813. return true;
  7814. UpdateExpr = Update.get();
  7815. }
  7816. return ErrorFound != NoError;
  7817. }
  7818. StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
  7819. Stmt *AStmt,
  7820. SourceLocation StartLoc,
  7821. SourceLocation EndLoc) {
  7822. if (!AStmt)
  7823. return StmtError();
  7824. auto *CS = cast<CapturedStmt>(AStmt);
  7825. // 1.2.2 OpenMP Language Terminology
  7826. // Structured block - An executable statement with a single entry at the
  7827. // top and a single exit at the bottom.
  7828. // The point of exit cannot be a branch out of the structured block.
  7829. // longjmp() and throw() must not violate the entry/exit criteria.
  7830. OpenMPClauseKind AtomicKind = OMPC_unknown;
  7831. SourceLocation AtomicKindLoc;
  7832. for (const OMPClause *C : Clauses) {
  7833. if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
  7834. C->getClauseKind() == OMPC_update ||
  7835. C->getClauseKind() == OMPC_capture) {
  7836. if (AtomicKind != OMPC_unknown) {
  7837. Diag(C->getBeginLoc(), diag::err_omp_atomic_several_clauses)
  7838. << SourceRange(C->getBeginLoc(), C->getEndLoc());
  7839. Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
  7840. << getOpenMPClauseName(AtomicKind);
  7841. } else {
  7842. AtomicKind = C->getClauseKind();
  7843. AtomicKindLoc = C->getBeginLoc();
  7844. }
  7845. }
  7846. }
  7847. Stmt *Body = CS->getCapturedStmt();
  7848. if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
  7849. Body = EWC->getSubExpr();
  7850. Expr *X = nullptr;
  7851. Expr *V = nullptr;
  7852. Expr *E = nullptr;
  7853. Expr *UE = nullptr;
  7854. bool IsXLHSInRHSPart = false;
  7855. bool IsPostfixUpdate = false;
  7856. // OpenMP [2.12.6, atomic Construct]
  7857. // In the next expressions:
  7858. // * x and v (as applicable) are both l-value expressions with scalar type.
  7859. // * During the execution of an atomic region, multiple syntactic
  7860. // occurrences of x must designate the same storage location.
  7861. // * Neither of v and expr (as applicable) may access the storage location
  7862. // designated by x.
  7863. // * Neither of x and expr (as applicable) may access the storage location
  7864. // designated by v.
  7865. // * expr is an expression with scalar type.
  7866. // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
  7867. // * binop, binop=, ++, and -- are not overloaded operators.
  7868. // * The expression x binop expr must be numerically equivalent to x binop
  7869. // (expr). This requirement is satisfied if the operators in expr have
  7870. // precedence greater than binop, or by using parentheses around expr or
  7871. // subexpressions of expr.
  7872. // * The expression expr binop x must be numerically equivalent to (expr)
  7873. // binop x. This requirement is satisfied if the operators in expr have
  7874. // precedence equal to or greater than binop, or by using parentheses around
  7875. // expr or subexpressions of expr.
  7876. // * For forms that allow multiple occurrences of x, the number of times
  7877. // that x is evaluated is unspecified.
  7878. if (AtomicKind == OMPC_read) {
  7879. enum {
  7880. NotAnExpression,
  7881. NotAnAssignmentOp,
  7882. NotAScalarType,
  7883. NotAnLValue,
  7884. NoError
  7885. } ErrorFound = NoError;
  7886. SourceLocation ErrorLoc, NoteLoc;
  7887. SourceRange ErrorRange, NoteRange;
  7888. // If clause is read:
  7889. // v = x;
  7890. if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
  7891. const auto *AtomicBinOp =
  7892. dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
  7893. if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
  7894. X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
  7895. V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
  7896. if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
  7897. (V->isInstantiationDependent() || V->getType()->isScalarType())) {
  7898. if (!X->isLValue() || !V->isLValue()) {
  7899. const Expr *NotLValueExpr = X->isLValue() ? V : X;
  7900. ErrorFound = NotAnLValue;
  7901. ErrorLoc = AtomicBinOp->getExprLoc();
  7902. ErrorRange = AtomicBinOp->getSourceRange();
  7903. NoteLoc = NotLValueExpr->getExprLoc();
  7904. NoteRange = NotLValueExpr->getSourceRange();
  7905. }
  7906. } else if (!X->isInstantiationDependent() ||
  7907. !V->isInstantiationDependent()) {
  7908. const Expr *NotScalarExpr =
  7909. (X->isInstantiationDependent() || X->getType()->isScalarType())
  7910. ? V
  7911. : X;
  7912. ErrorFound = NotAScalarType;
  7913. ErrorLoc = AtomicBinOp->getExprLoc();
  7914. ErrorRange = AtomicBinOp->getSourceRange();
  7915. NoteLoc = NotScalarExpr->getExprLoc();
  7916. NoteRange = NotScalarExpr->getSourceRange();
  7917. }
  7918. } else if (!AtomicBody->isInstantiationDependent()) {
  7919. ErrorFound = NotAnAssignmentOp;
  7920. ErrorLoc = AtomicBody->getExprLoc();
  7921. ErrorRange = AtomicBody->getSourceRange();
  7922. NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
  7923. : AtomicBody->getExprLoc();
  7924. NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
  7925. : AtomicBody->getSourceRange();
  7926. }
  7927. } else {
  7928. ErrorFound = NotAnExpression;
  7929. NoteLoc = ErrorLoc = Body->getBeginLoc();
  7930. NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
  7931. }
  7932. if (ErrorFound != NoError) {
  7933. Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
  7934. << ErrorRange;
  7935. Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
  7936. << NoteRange;
  7937. return StmtError();
  7938. }
  7939. if (CurContext->isDependentContext())
  7940. V = X = nullptr;
  7941. } else if (AtomicKind == OMPC_write) {
  7942. enum {
  7943. NotAnExpression,
  7944. NotAnAssignmentOp,
  7945. NotAScalarType,
  7946. NotAnLValue,
  7947. NoError
  7948. } ErrorFound = NoError;
  7949. SourceLocation ErrorLoc, NoteLoc;
  7950. SourceRange ErrorRange, NoteRange;
  7951. // If clause is write:
  7952. // x = expr;
  7953. if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
  7954. const auto *AtomicBinOp =
  7955. dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
  7956. if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
  7957. X = AtomicBinOp->getLHS();
  7958. E = AtomicBinOp->getRHS();
  7959. if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
  7960. (E->isInstantiationDependent() || E->getType()->isScalarType())) {
  7961. if (!X->isLValue()) {
  7962. ErrorFound = NotAnLValue;
  7963. ErrorLoc = AtomicBinOp->getExprLoc();
  7964. ErrorRange = AtomicBinOp->getSourceRange();
  7965. NoteLoc = X->getExprLoc();
  7966. NoteRange = X->getSourceRange();
  7967. }
  7968. } else if (!X->isInstantiationDependent() ||
  7969. !E->isInstantiationDependent()) {
  7970. const Expr *NotScalarExpr =
  7971. (X->isInstantiationDependent() || X->getType()->isScalarType())
  7972. ? E
  7973. : X;
  7974. ErrorFound = NotAScalarType;
  7975. ErrorLoc = AtomicBinOp->getExprLoc();
  7976. ErrorRange = AtomicBinOp->getSourceRange();
  7977. NoteLoc = NotScalarExpr->getExprLoc();
  7978. NoteRange = NotScalarExpr->getSourceRange();
  7979. }
  7980. } else if (!AtomicBody->isInstantiationDependent()) {
  7981. ErrorFound = NotAnAssignmentOp;
  7982. ErrorLoc = AtomicBody->getExprLoc();
  7983. ErrorRange = AtomicBody->getSourceRange();
  7984. NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
  7985. : AtomicBody->getExprLoc();
  7986. NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
  7987. : AtomicBody->getSourceRange();
  7988. }
  7989. } else {
  7990. ErrorFound = NotAnExpression;
  7991. NoteLoc = ErrorLoc = Body->getBeginLoc();
  7992. NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
  7993. }
  7994. if (ErrorFound != NoError) {
  7995. Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
  7996. << ErrorRange;
  7997. Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
  7998. << NoteRange;
  7999. return StmtError();
  8000. }
  8001. if (CurContext->isDependentContext())
  8002. E = X = nullptr;
  8003. } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
  8004. // If clause is update:
  8005. // x++;
  8006. // x--;
  8007. // ++x;
  8008. // --x;
  8009. // x binop= expr;
  8010. // x = x binop expr;
  8011. // x = expr binop x;
  8012. OpenMPAtomicUpdateChecker Checker(*this);
  8013. if (Checker.checkStatement(
  8014. Body, (AtomicKind == OMPC_update)
  8015. ? diag::err_omp_atomic_update_not_expression_statement
  8016. : diag::err_omp_atomic_not_expression_statement,
  8017. diag::note_omp_atomic_update))
  8018. return StmtError();
  8019. if (!CurContext->isDependentContext()) {
  8020. E = Checker.getExpr();
  8021. X = Checker.getX();
  8022. UE = Checker.getUpdateExpr();
  8023. IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
  8024. }
  8025. } else if (AtomicKind == OMPC_capture) {
  8026. enum {
  8027. NotAnAssignmentOp,
  8028. NotACompoundStatement,
  8029. NotTwoSubstatements,
  8030. NotASpecificExpression,
  8031. NoError
  8032. } ErrorFound = NoError;
  8033. SourceLocation ErrorLoc, NoteLoc;
  8034. SourceRange ErrorRange, NoteRange;
  8035. if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
  8036. // If clause is a capture:
  8037. // v = x++;
  8038. // v = x--;
  8039. // v = ++x;
  8040. // v = --x;
  8041. // v = x binop= expr;
  8042. // v = x = x binop expr;
  8043. // v = x = expr binop x;
  8044. const auto *AtomicBinOp =
  8045. dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
  8046. if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
  8047. V = AtomicBinOp->getLHS();
  8048. Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
  8049. OpenMPAtomicUpdateChecker Checker(*this);
  8050. if (Checker.checkStatement(
  8051. Body, diag::err_omp_atomic_capture_not_expression_statement,
  8052. diag::note_omp_atomic_update))
  8053. return StmtError();
  8054. E = Checker.getExpr();
  8055. X = Checker.getX();
  8056. UE = Checker.getUpdateExpr();
  8057. IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
  8058. IsPostfixUpdate = Checker.isPostfixUpdate();
  8059. } else if (!AtomicBody->isInstantiationDependent()) {
  8060. ErrorLoc = AtomicBody->getExprLoc();
  8061. ErrorRange = AtomicBody->getSourceRange();
  8062. NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
  8063. : AtomicBody->getExprLoc();
  8064. NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
  8065. : AtomicBody->getSourceRange();
  8066. ErrorFound = NotAnAssignmentOp;
  8067. }
  8068. if (ErrorFound != NoError) {
  8069. Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
  8070. << ErrorRange;
  8071. Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
  8072. return StmtError();
  8073. }
  8074. if (CurContext->isDependentContext())
  8075. UE = V = E = X = nullptr;
  8076. } else {
  8077. // If clause is a capture:
  8078. // { v = x; x = expr; }
  8079. // { v = x; x++; }
  8080. // { v = x; x--; }
  8081. // { v = x; ++x; }
  8082. // { v = x; --x; }
  8083. // { v = x; x binop= expr; }
  8084. // { v = x; x = x binop expr; }
  8085. // { v = x; x = expr binop x; }
  8086. // { x++; v = x; }
  8087. // { x--; v = x; }
  8088. // { ++x; v = x; }
  8089. // { --x; v = x; }
  8090. // { x binop= expr; v = x; }
  8091. // { x = x binop expr; v = x; }
  8092. // { x = expr binop x; v = x; }
  8093. if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
  8094. // Check that this is { expr1; expr2; }
  8095. if (CS->size() == 2) {
  8096. Stmt *First = CS->body_front();
  8097. Stmt *Second = CS->body_back();
  8098. if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
  8099. First = EWC->getSubExpr()->IgnoreParenImpCasts();
  8100. if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
  8101. Second = EWC->getSubExpr()->IgnoreParenImpCasts();
  8102. // Need to find what subexpression is 'v' and what is 'x'.
  8103. OpenMPAtomicUpdateChecker Checker(*this);
  8104. bool IsUpdateExprFound = !Checker.checkStatement(Second);
  8105. BinaryOperator *BinOp = nullptr;
  8106. if (IsUpdateExprFound) {
  8107. BinOp = dyn_cast<BinaryOperator>(First);
  8108. IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
  8109. }
  8110. if (IsUpdateExprFound && !CurContext->isDependentContext()) {
  8111. // { v = x; x++; }
  8112. // { v = x; x--; }
  8113. // { v = x; ++x; }
  8114. // { v = x; --x; }
  8115. // { v = x; x binop= expr; }
  8116. // { v = x; x = x binop expr; }
  8117. // { v = x; x = expr binop x; }
  8118. // Check that the first expression has form v = x.
  8119. Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
  8120. llvm::FoldingSetNodeID XId, PossibleXId;
  8121. Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
  8122. PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
  8123. IsUpdateExprFound = XId == PossibleXId;
  8124. if (IsUpdateExprFound) {
  8125. V = BinOp->getLHS();
  8126. X = Checker.getX();
  8127. E = Checker.getExpr();
  8128. UE = Checker.getUpdateExpr();
  8129. IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
  8130. IsPostfixUpdate = true;
  8131. }
  8132. }
  8133. if (!IsUpdateExprFound) {
  8134. IsUpdateExprFound = !Checker.checkStatement(First);
  8135. BinOp = nullptr;
  8136. if (IsUpdateExprFound) {
  8137. BinOp = dyn_cast<BinaryOperator>(Second);
  8138. IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
  8139. }
  8140. if (IsUpdateExprFound && !CurContext->isDependentContext()) {
  8141. // { x++; v = x; }
  8142. // { x--; v = x; }
  8143. // { ++x; v = x; }
  8144. // { --x; v = x; }
  8145. // { x binop= expr; v = x; }
  8146. // { x = x binop expr; v = x; }
  8147. // { x = expr binop x; v = x; }
  8148. // Check that the second expression has form v = x.
  8149. Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
  8150. llvm::FoldingSetNodeID XId, PossibleXId;
  8151. Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
  8152. PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
  8153. IsUpdateExprFound = XId == PossibleXId;
  8154. if (IsUpdateExprFound) {
  8155. V = BinOp->getLHS();
  8156. X = Checker.getX();
  8157. E = Checker.getExpr();
  8158. UE = Checker.getUpdateExpr();
  8159. IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
  8160. IsPostfixUpdate = false;
  8161. }
  8162. }
  8163. }
  8164. if (!IsUpdateExprFound) {
  8165. // { v = x; x = expr; }
  8166. auto *FirstExpr = dyn_cast<Expr>(First);
  8167. auto *SecondExpr = dyn_cast<Expr>(Second);
  8168. if (!FirstExpr || !SecondExpr ||
  8169. !(FirstExpr->isInstantiationDependent() ||
  8170. SecondExpr->isInstantiationDependent())) {
  8171. auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
  8172. if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
  8173. ErrorFound = NotAnAssignmentOp;
  8174. NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
  8175. : First->getBeginLoc();
  8176. NoteRange = ErrorRange = FirstBinOp
  8177. ? FirstBinOp->getSourceRange()
  8178. : SourceRange(ErrorLoc, ErrorLoc);
  8179. } else {
  8180. auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
  8181. if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
  8182. ErrorFound = NotAnAssignmentOp;
  8183. NoteLoc = ErrorLoc = SecondBinOp
  8184. ? SecondBinOp->getOperatorLoc()
  8185. : Second->getBeginLoc();
  8186. NoteRange = ErrorRange =
  8187. SecondBinOp ? SecondBinOp->getSourceRange()
  8188. : SourceRange(ErrorLoc, ErrorLoc);
  8189. } else {
  8190. Expr *PossibleXRHSInFirst =
  8191. FirstBinOp->getRHS()->IgnoreParenImpCasts();
  8192. Expr *PossibleXLHSInSecond =
  8193. SecondBinOp->getLHS()->IgnoreParenImpCasts();
  8194. llvm::FoldingSetNodeID X1Id, X2Id;
  8195. PossibleXRHSInFirst->Profile(X1Id, Context,
  8196. /*Canonical=*/true);
  8197. PossibleXLHSInSecond->Profile(X2Id, Context,
  8198. /*Canonical=*/true);
  8199. IsUpdateExprFound = X1Id == X2Id;
  8200. if (IsUpdateExprFound) {
  8201. V = FirstBinOp->getLHS();
  8202. X = SecondBinOp->getLHS();
  8203. E = SecondBinOp->getRHS();
  8204. UE = nullptr;
  8205. IsXLHSInRHSPart = false;
  8206. IsPostfixUpdate = true;
  8207. } else {
  8208. ErrorFound = NotASpecificExpression;
  8209. ErrorLoc = FirstBinOp->getExprLoc();
  8210. ErrorRange = FirstBinOp->getSourceRange();
  8211. NoteLoc = SecondBinOp->getLHS()->getExprLoc();
  8212. NoteRange = SecondBinOp->getRHS()->getSourceRange();
  8213. }
  8214. }
  8215. }
  8216. }
  8217. }
  8218. } else {
  8219. NoteLoc = ErrorLoc = Body->getBeginLoc();
  8220. NoteRange = ErrorRange =
  8221. SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
  8222. ErrorFound = NotTwoSubstatements;
  8223. }
  8224. } else {
  8225. NoteLoc = ErrorLoc = Body->getBeginLoc();
  8226. NoteRange = ErrorRange =
  8227. SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
  8228. ErrorFound = NotACompoundStatement;
  8229. }
  8230. if (ErrorFound != NoError) {
  8231. Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
  8232. << ErrorRange;
  8233. Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
  8234. return StmtError();
  8235. }
  8236. if (CurContext->isDependentContext())
  8237. UE = V = E = X = nullptr;
  8238. }
  8239. }
  8240. setFunctionHasBranchProtectedScope();
  8241. return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
  8242. X, V, E, UE, IsXLHSInRHSPart,
  8243. IsPostfixUpdate);
  8244. }
  8245. StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
  8246. Stmt *AStmt,
  8247. SourceLocation StartLoc,
  8248. SourceLocation EndLoc) {
  8249. if (!AStmt)
  8250. return StmtError();
  8251. auto *CS = cast<CapturedStmt>(AStmt);
  8252. // 1.2.2 OpenMP Language Terminology
  8253. // Structured block - An executable statement with a single entry at the
  8254. // top and a single exit at the bottom.
  8255. // The point of exit cannot be a branch out of the structured block.
  8256. // longjmp() and throw() must not violate the entry/exit criteria.
  8257. CS->getCapturedDecl()->setNothrow();
  8258. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target);
  8259. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  8260. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  8261. // 1.2.2 OpenMP Language Terminology
  8262. // Structured block - An executable statement with a single entry at the
  8263. // top and a single exit at the bottom.
  8264. // The point of exit cannot be a branch out of the structured block.
  8265. // longjmp() and throw() must not violate the entry/exit criteria.
  8266. CS->getCapturedDecl()->setNothrow();
  8267. }
  8268. // OpenMP [2.16, Nesting of Regions]
  8269. // If specified, a teams construct must be contained within a target
  8270. // construct. That target construct must contain no statements or directives
  8271. // outside of the teams construct.
  8272. if (DSAStack->hasInnerTeamsRegion()) {
  8273. const Stmt *S = CS->IgnoreContainers(/*IgnoreCaptured=*/true);
  8274. bool OMPTeamsFound = true;
  8275. if (const auto *CS = dyn_cast<CompoundStmt>(S)) {
  8276. auto I = CS->body_begin();
  8277. while (I != CS->body_end()) {
  8278. const auto *OED = dyn_cast<OMPExecutableDirective>(*I);
  8279. if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind()) ||
  8280. OMPTeamsFound) {
  8281. OMPTeamsFound = false;
  8282. break;
  8283. }
  8284. ++I;
  8285. }
  8286. assert(I != CS->body_end() && "Not found statement");
  8287. S = *I;
  8288. } else {
  8289. const auto *OED = dyn_cast<OMPExecutableDirective>(S);
  8290. OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
  8291. }
  8292. if (!OMPTeamsFound) {
  8293. Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
  8294. Diag(DSAStack->getInnerTeamsRegionLoc(),
  8295. diag::note_omp_nested_teams_construct_here);
  8296. Diag(S->getBeginLoc(), diag::note_omp_nested_statement_here)
  8297. << isa<OMPExecutableDirective>(S);
  8298. return StmtError();
  8299. }
  8300. }
  8301. setFunctionHasBranchProtectedScope();
  8302. return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
  8303. }
  8304. StmtResult
  8305. Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
  8306. Stmt *AStmt, SourceLocation StartLoc,
  8307. SourceLocation EndLoc) {
  8308. if (!AStmt)
  8309. return StmtError();
  8310. auto *CS = cast<CapturedStmt>(AStmt);
  8311. // 1.2.2 OpenMP Language Terminology
  8312. // Structured block - An executable statement with a single entry at the
  8313. // top and a single exit at the bottom.
  8314. // The point of exit cannot be a branch out of the structured block.
  8315. // longjmp() and throw() must not violate the entry/exit criteria.
  8316. CS->getCapturedDecl()->setNothrow();
  8317. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel);
  8318. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  8319. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  8320. // 1.2.2 OpenMP Language Terminology
  8321. // Structured block - An executable statement with a single entry at the
  8322. // top and a single exit at the bottom.
  8323. // The point of exit cannot be a branch out of the structured block.
  8324. // longjmp() and throw() must not violate the entry/exit criteria.
  8325. CS->getCapturedDecl()->setNothrow();
  8326. }
  8327. setFunctionHasBranchProtectedScope();
  8328. return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
  8329. AStmt);
  8330. }
  8331. StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
  8332. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  8333. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  8334. if (!AStmt)
  8335. return StmtError();
  8336. auto *CS = cast<CapturedStmt>(AStmt);
  8337. // 1.2.2 OpenMP Language Terminology
  8338. // Structured block - An executable statement with a single entry at the
  8339. // top and a single exit at the bottom.
  8340. // The point of exit cannot be a branch out of the structured block.
  8341. // longjmp() and throw() must not violate the entry/exit criteria.
  8342. CS->getCapturedDecl()->setNothrow();
  8343. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
  8344. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  8345. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  8346. // 1.2.2 OpenMP Language Terminology
  8347. // Structured block - An executable statement with a single entry at the
  8348. // top and a single exit at the bottom.
  8349. // The point of exit cannot be a branch out of the structured block.
  8350. // longjmp() and throw() must not violate the entry/exit criteria.
  8351. CS->getCapturedDecl()->setNothrow();
  8352. }
  8353. OMPLoopDirective::HelperExprs B;
  8354. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  8355. // define the nested loops number.
  8356. unsigned NestedLoopCount =
  8357. checkOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
  8358. getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
  8359. VarsWithImplicitDSA, B);
  8360. if (NestedLoopCount == 0)
  8361. return StmtError();
  8362. assert((CurContext->isDependentContext() || B.builtAll()) &&
  8363. "omp target parallel for loop exprs were not built");
  8364. if (!CurContext->isDependentContext()) {
  8365. // Finalize the clauses that need pre-built expressions for CodeGen.
  8366. for (OMPClause *C : Clauses) {
  8367. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  8368. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  8369. B.NumIterations, *this, CurScope,
  8370. DSAStack))
  8371. return StmtError();
  8372. }
  8373. }
  8374. setFunctionHasBranchProtectedScope();
  8375. return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc,
  8376. NestedLoopCount, Clauses, AStmt,
  8377. B, DSAStack->isCancelRegion());
  8378. }
  8379. /// Check for existence of a map clause in the list of clauses.
  8380. static bool hasClauses(ArrayRef<OMPClause *> Clauses,
  8381. const OpenMPClauseKind K) {
  8382. return llvm::any_of(
  8383. Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; });
  8384. }
  8385. template <typename... Params>
  8386. static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K,
  8387. const Params... ClauseTypes) {
  8388. return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...);
  8389. }
  8390. StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
  8391. Stmt *AStmt,
  8392. SourceLocation StartLoc,
  8393. SourceLocation EndLoc) {
  8394. if (!AStmt)
  8395. return StmtError();
  8396. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  8397. // OpenMP [2.10.1, Restrictions, p. 97]
  8398. // At least one map clause must appear on the directive.
  8399. if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr)) {
  8400. Diag(StartLoc, diag::err_omp_no_clause_for_directive)
  8401. << "'map' or 'use_device_ptr'"
  8402. << getOpenMPDirectiveName(OMPD_target_data);
  8403. return StmtError();
  8404. }
  8405. setFunctionHasBranchProtectedScope();
  8406. return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
  8407. AStmt);
  8408. }
  8409. StmtResult
  8410. Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
  8411. SourceLocation StartLoc,
  8412. SourceLocation EndLoc, Stmt *AStmt) {
  8413. if (!AStmt)
  8414. return StmtError();
  8415. auto *CS = cast<CapturedStmt>(AStmt);
  8416. // 1.2.2 OpenMP Language Terminology
  8417. // Structured block - An executable statement with a single entry at the
  8418. // top and a single exit at the bottom.
  8419. // The point of exit cannot be a branch out of the structured block.
  8420. // longjmp() and throw() must not violate the entry/exit criteria.
  8421. CS->getCapturedDecl()->setNothrow();
  8422. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_enter_data);
  8423. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  8424. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  8425. // 1.2.2 OpenMP Language Terminology
  8426. // Structured block - An executable statement with a single entry at the
  8427. // top and a single exit at the bottom.
  8428. // The point of exit cannot be a branch out of the structured block.
  8429. // longjmp() and throw() must not violate the entry/exit criteria.
  8430. CS->getCapturedDecl()->setNothrow();
  8431. }
  8432. // OpenMP [2.10.2, Restrictions, p. 99]
  8433. // At least one map clause must appear on the directive.
  8434. if (!hasClauses(Clauses, OMPC_map)) {
  8435. Diag(StartLoc, diag::err_omp_no_clause_for_directive)
  8436. << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data);
  8437. return StmtError();
  8438. }
  8439. return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
  8440. AStmt);
  8441. }
  8442. StmtResult
  8443. Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
  8444. SourceLocation StartLoc,
  8445. SourceLocation EndLoc, Stmt *AStmt) {
  8446. if (!AStmt)
  8447. return StmtError();
  8448. auto *CS = cast<CapturedStmt>(AStmt);
  8449. // 1.2.2 OpenMP Language Terminology
  8450. // Structured block - An executable statement with a single entry at the
  8451. // top and a single exit at the bottom.
  8452. // The point of exit cannot be a branch out of the structured block.
  8453. // longjmp() and throw() must not violate the entry/exit criteria.
  8454. CS->getCapturedDecl()->setNothrow();
  8455. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_exit_data);
  8456. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  8457. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  8458. // 1.2.2 OpenMP Language Terminology
  8459. // Structured block - An executable statement with a single entry at the
  8460. // top and a single exit at the bottom.
  8461. // The point of exit cannot be a branch out of the structured block.
  8462. // longjmp() and throw() must not violate the entry/exit criteria.
  8463. CS->getCapturedDecl()->setNothrow();
  8464. }
  8465. // OpenMP [2.10.3, Restrictions, p. 102]
  8466. // At least one map clause must appear on the directive.
  8467. if (!hasClauses(Clauses, OMPC_map)) {
  8468. Diag(StartLoc, diag::err_omp_no_clause_for_directive)
  8469. << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data);
  8470. return StmtError();
  8471. }
  8472. return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
  8473. AStmt);
  8474. }
  8475. StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
  8476. SourceLocation StartLoc,
  8477. SourceLocation EndLoc,
  8478. Stmt *AStmt) {
  8479. if (!AStmt)
  8480. return StmtError();
  8481. auto *CS = cast<CapturedStmt>(AStmt);
  8482. // 1.2.2 OpenMP Language Terminology
  8483. // Structured block - An executable statement with a single entry at the
  8484. // top and a single exit at the bottom.
  8485. // The point of exit cannot be a branch out of the structured block.
  8486. // longjmp() and throw() must not violate the entry/exit criteria.
  8487. CS->getCapturedDecl()->setNothrow();
  8488. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_update);
  8489. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  8490. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  8491. // 1.2.2 OpenMP Language Terminology
  8492. // Structured block - An executable statement with a single entry at the
  8493. // top and a single exit at the bottom.
  8494. // The point of exit cannot be a branch out of the structured block.
  8495. // longjmp() and throw() must not violate the entry/exit criteria.
  8496. CS->getCapturedDecl()->setNothrow();
  8497. }
  8498. if (!hasClauses(Clauses, OMPC_to, OMPC_from)) {
  8499. Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
  8500. return StmtError();
  8501. }
  8502. return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses,
  8503. AStmt);
  8504. }
  8505. StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
  8506. Stmt *AStmt, SourceLocation StartLoc,
  8507. SourceLocation EndLoc) {
  8508. if (!AStmt)
  8509. return StmtError();
  8510. auto *CS = cast<CapturedStmt>(AStmt);
  8511. // 1.2.2 OpenMP Language Terminology
  8512. // Structured block - An executable statement with a single entry at the
  8513. // top and a single exit at the bottom.
  8514. // The point of exit cannot be a branch out of the structured block.
  8515. // longjmp() and throw() must not violate the entry/exit criteria.
  8516. CS->getCapturedDecl()->setNothrow();
  8517. setFunctionHasBranchProtectedScope();
  8518. DSAStack->setParentTeamsRegionLoc(StartLoc);
  8519. return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
  8520. }
  8521. StmtResult
  8522. Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
  8523. SourceLocation EndLoc,
  8524. OpenMPDirectiveKind CancelRegion) {
  8525. if (DSAStack->isParentNowaitRegion()) {
  8526. Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
  8527. return StmtError();
  8528. }
  8529. if (DSAStack->isParentOrderedRegion()) {
  8530. Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
  8531. return StmtError();
  8532. }
  8533. return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
  8534. CancelRegion);
  8535. }
  8536. StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
  8537. SourceLocation StartLoc,
  8538. SourceLocation EndLoc,
  8539. OpenMPDirectiveKind CancelRegion) {
  8540. if (DSAStack->isParentNowaitRegion()) {
  8541. Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
  8542. return StmtError();
  8543. }
  8544. if (DSAStack->isParentOrderedRegion()) {
  8545. Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
  8546. return StmtError();
  8547. }
  8548. DSAStack->setParentCancelRegion(/*Cancel=*/true);
  8549. return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
  8550. CancelRegion);
  8551. }
  8552. static bool checkGrainsizeNumTasksClauses(Sema &S,
  8553. ArrayRef<OMPClause *> Clauses) {
  8554. const OMPClause *PrevClause = nullptr;
  8555. bool ErrorFound = false;
  8556. for (const OMPClause *C : Clauses) {
  8557. if (C->getClauseKind() == OMPC_grainsize ||
  8558. C->getClauseKind() == OMPC_num_tasks) {
  8559. if (!PrevClause)
  8560. PrevClause = C;
  8561. else if (PrevClause->getClauseKind() != C->getClauseKind()) {
  8562. S.Diag(C->getBeginLoc(),
  8563. diag::err_omp_grainsize_num_tasks_mutually_exclusive)
  8564. << getOpenMPClauseName(C->getClauseKind())
  8565. << getOpenMPClauseName(PrevClause->getClauseKind());
  8566. S.Diag(PrevClause->getBeginLoc(),
  8567. diag::note_omp_previous_grainsize_num_tasks)
  8568. << getOpenMPClauseName(PrevClause->getClauseKind());
  8569. ErrorFound = true;
  8570. }
  8571. }
  8572. }
  8573. return ErrorFound;
  8574. }
  8575. static bool checkReductionClauseWithNogroup(Sema &S,
  8576. ArrayRef<OMPClause *> Clauses) {
  8577. const OMPClause *ReductionClause = nullptr;
  8578. const OMPClause *NogroupClause = nullptr;
  8579. for (const OMPClause *C : Clauses) {
  8580. if (C->getClauseKind() == OMPC_reduction) {
  8581. ReductionClause = C;
  8582. if (NogroupClause)
  8583. break;
  8584. continue;
  8585. }
  8586. if (C->getClauseKind() == OMPC_nogroup) {
  8587. NogroupClause = C;
  8588. if (ReductionClause)
  8589. break;
  8590. continue;
  8591. }
  8592. }
  8593. if (ReductionClause && NogroupClause) {
  8594. S.Diag(ReductionClause->getBeginLoc(), diag::err_omp_reduction_with_nogroup)
  8595. << SourceRange(NogroupClause->getBeginLoc(),
  8596. NogroupClause->getEndLoc());
  8597. return true;
  8598. }
  8599. return false;
  8600. }
  8601. StmtResult Sema::ActOnOpenMPTaskLoopDirective(
  8602. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  8603. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  8604. if (!AStmt)
  8605. return StmtError();
  8606. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  8607. OMPLoopDirective::HelperExprs B;
  8608. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  8609. // define the nested loops number.
  8610. unsigned NestedLoopCount =
  8611. checkOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
  8612. /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
  8613. VarsWithImplicitDSA, B);
  8614. if (NestedLoopCount == 0)
  8615. return StmtError();
  8616. assert((CurContext->isDependentContext() || B.builtAll()) &&
  8617. "omp for loop exprs were not built");
  8618. // OpenMP, [2.9.2 taskloop Construct, Restrictions]
  8619. // The grainsize clause and num_tasks clause are mutually exclusive and may
  8620. // not appear on the same taskloop directive.
  8621. if (checkGrainsizeNumTasksClauses(*this, Clauses))
  8622. return StmtError();
  8623. // OpenMP, [2.9.2 taskloop Construct, Restrictions]
  8624. // If a reduction clause is present on the taskloop directive, the nogroup
  8625. // clause must not be specified.
  8626. if (checkReductionClauseWithNogroup(*this, Clauses))
  8627. return StmtError();
  8628. setFunctionHasBranchProtectedScope();
  8629. return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
  8630. NestedLoopCount, Clauses, AStmt, B);
  8631. }
  8632. StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
  8633. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  8634. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  8635. if (!AStmt)
  8636. return StmtError();
  8637. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  8638. OMPLoopDirective::HelperExprs B;
  8639. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  8640. // define the nested loops number.
  8641. unsigned NestedLoopCount =
  8642. checkOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
  8643. /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
  8644. VarsWithImplicitDSA, B);
  8645. if (NestedLoopCount == 0)
  8646. return StmtError();
  8647. assert((CurContext->isDependentContext() || B.builtAll()) &&
  8648. "omp for loop exprs were not built");
  8649. if (!CurContext->isDependentContext()) {
  8650. // Finalize the clauses that need pre-built expressions for CodeGen.
  8651. for (OMPClause *C : Clauses) {
  8652. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  8653. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  8654. B.NumIterations, *this, CurScope,
  8655. DSAStack))
  8656. return StmtError();
  8657. }
  8658. }
  8659. // OpenMP, [2.9.2 taskloop Construct, Restrictions]
  8660. // The grainsize clause and num_tasks clause are mutually exclusive and may
  8661. // not appear on the same taskloop directive.
  8662. if (checkGrainsizeNumTasksClauses(*this, Clauses))
  8663. return StmtError();
  8664. // OpenMP, [2.9.2 taskloop Construct, Restrictions]
  8665. // If a reduction clause is present on the taskloop directive, the nogroup
  8666. // clause must not be specified.
  8667. if (checkReductionClauseWithNogroup(*this, Clauses))
  8668. return StmtError();
  8669. if (checkSimdlenSafelenSpecified(*this, Clauses))
  8670. return StmtError();
  8671. setFunctionHasBranchProtectedScope();
  8672. return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
  8673. NestedLoopCount, Clauses, AStmt, B);
  8674. }
  8675. StmtResult Sema::ActOnOpenMPDistributeDirective(
  8676. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  8677. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  8678. if (!AStmt)
  8679. return StmtError();
  8680. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  8681. OMPLoopDirective::HelperExprs B;
  8682. // In presence of clause 'collapse' with number of loops, it will
  8683. // define the nested loops number.
  8684. unsigned NestedLoopCount =
  8685. checkOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
  8686. nullptr /*ordered not a clause on distribute*/, AStmt,
  8687. *this, *DSAStack, VarsWithImplicitDSA, B);
  8688. if (NestedLoopCount == 0)
  8689. return StmtError();
  8690. assert((CurContext->isDependentContext() || B.builtAll()) &&
  8691. "omp for loop exprs were not built");
  8692. setFunctionHasBranchProtectedScope();
  8693. return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
  8694. NestedLoopCount, Clauses, AStmt, B);
  8695. }
  8696. StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
  8697. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  8698. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  8699. if (!AStmt)
  8700. return StmtError();
  8701. auto *CS = cast<CapturedStmt>(AStmt);
  8702. // 1.2.2 OpenMP Language Terminology
  8703. // Structured block - An executable statement with a single entry at the
  8704. // top and a single exit at the bottom.
  8705. // The point of exit cannot be a branch out of the structured block.
  8706. // longjmp() and throw() must not violate the entry/exit criteria.
  8707. CS->getCapturedDecl()->setNothrow();
  8708. for (int ThisCaptureLevel =
  8709. getOpenMPCaptureLevels(OMPD_distribute_parallel_for);
  8710. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  8711. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  8712. // 1.2.2 OpenMP Language Terminology
  8713. // Structured block - An executable statement with a single entry at the
  8714. // top and a single exit at the bottom.
  8715. // The point of exit cannot be a branch out of the structured block.
  8716. // longjmp() and throw() must not violate the entry/exit criteria.
  8717. CS->getCapturedDecl()->setNothrow();
  8718. }
  8719. OMPLoopDirective::HelperExprs B;
  8720. // In presence of clause 'collapse' with number of loops, it will
  8721. // define the nested loops number.
  8722. unsigned NestedLoopCount = checkOpenMPLoop(
  8723. OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
  8724. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  8725. VarsWithImplicitDSA, B);
  8726. if (NestedLoopCount == 0)
  8727. return StmtError();
  8728. assert((CurContext->isDependentContext() || B.builtAll()) &&
  8729. "omp for loop exprs were not built");
  8730. setFunctionHasBranchProtectedScope();
  8731. return OMPDistributeParallelForDirective::Create(
  8732. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
  8733. DSAStack->isCancelRegion());
  8734. }
  8735. StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
  8736. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  8737. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  8738. if (!AStmt)
  8739. return StmtError();
  8740. auto *CS = cast<CapturedStmt>(AStmt);
  8741. // 1.2.2 OpenMP Language Terminology
  8742. // Structured block - An executable statement with a single entry at the
  8743. // top and a single exit at the bottom.
  8744. // The point of exit cannot be a branch out of the structured block.
  8745. // longjmp() and throw() must not violate the entry/exit criteria.
  8746. CS->getCapturedDecl()->setNothrow();
  8747. for (int ThisCaptureLevel =
  8748. getOpenMPCaptureLevels(OMPD_distribute_parallel_for_simd);
  8749. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  8750. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  8751. // 1.2.2 OpenMP Language Terminology
  8752. // Structured block - An executable statement with a single entry at the
  8753. // top and a single exit at the bottom.
  8754. // The point of exit cannot be a branch out of the structured block.
  8755. // longjmp() and throw() must not violate the entry/exit criteria.
  8756. CS->getCapturedDecl()->setNothrow();
  8757. }
  8758. OMPLoopDirective::HelperExprs B;
  8759. // In presence of clause 'collapse' with number of loops, it will
  8760. // define the nested loops number.
  8761. unsigned NestedLoopCount = checkOpenMPLoop(
  8762. OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
  8763. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  8764. VarsWithImplicitDSA, B);
  8765. if (NestedLoopCount == 0)
  8766. return StmtError();
  8767. assert((CurContext->isDependentContext() || B.builtAll()) &&
  8768. "omp for loop exprs were not built");
  8769. if (!CurContext->isDependentContext()) {
  8770. // Finalize the clauses that need pre-built expressions for CodeGen.
  8771. for (OMPClause *C : Clauses) {
  8772. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  8773. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  8774. B.NumIterations, *this, CurScope,
  8775. DSAStack))
  8776. return StmtError();
  8777. }
  8778. }
  8779. if (checkSimdlenSafelenSpecified(*this, Clauses))
  8780. return StmtError();
  8781. setFunctionHasBranchProtectedScope();
  8782. return OMPDistributeParallelForSimdDirective::Create(
  8783. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  8784. }
  8785. StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
  8786. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  8787. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  8788. if (!AStmt)
  8789. return StmtError();
  8790. auto *CS = cast<CapturedStmt>(AStmt);
  8791. // 1.2.2 OpenMP Language Terminology
  8792. // Structured block - An executable statement with a single entry at the
  8793. // top and a single exit at the bottom.
  8794. // The point of exit cannot be a branch out of the structured block.
  8795. // longjmp() and throw() must not violate the entry/exit criteria.
  8796. CS->getCapturedDecl()->setNothrow();
  8797. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_distribute_simd);
  8798. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  8799. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  8800. // 1.2.2 OpenMP Language Terminology
  8801. // Structured block - An executable statement with a single entry at the
  8802. // top and a single exit at the bottom.
  8803. // The point of exit cannot be a branch out of the structured block.
  8804. // longjmp() and throw() must not violate the entry/exit criteria.
  8805. CS->getCapturedDecl()->setNothrow();
  8806. }
  8807. OMPLoopDirective::HelperExprs B;
  8808. // In presence of clause 'collapse' with number of loops, it will
  8809. // define the nested loops number.
  8810. unsigned NestedLoopCount =
  8811. checkOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
  8812. nullptr /*ordered not a clause on distribute*/, CS, *this,
  8813. *DSAStack, VarsWithImplicitDSA, B);
  8814. if (NestedLoopCount == 0)
  8815. return StmtError();
  8816. assert((CurContext->isDependentContext() || B.builtAll()) &&
  8817. "omp for loop exprs were not built");
  8818. if (!CurContext->isDependentContext()) {
  8819. // Finalize the clauses that need pre-built expressions for CodeGen.
  8820. for (OMPClause *C : Clauses) {
  8821. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  8822. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  8823. B.NumIterations, *this, CurScope,
  8824. DSAStack))
  8825. return StmtError();
  8826. }
  8827. }
  8828. if (checkSimdlenSafelenSpecified(*this, Clauses))
  8829. return StmtError();
  8830. setFunctionHasBranchProtectedScope();
  8831. return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
  8832. NestedLoopCount, Clauses, AStmt, B);
  8833. }
  8834. StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
  8835. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  8836. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  8837. if (!AStmt)
  8838. return StmtError();
  8839. auto *CS = cast<CapturedStmt>(AStmt);
  8840. // 1.2.2 OpenMP Language Terminology
  8841. // Structured block - An executable statement with a single entry at the
  8842. // top and a single exit at the bottom.
  8843. // The point of exit cannot be a branch out of the structured block.
  8844. // longjmp() and throw() must not violate the entry/exit criteria.
  8845. CS->getCapturedDecl()->setNothrow();
  8846. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
  8847. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  8848. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  8849. // 1.2.2 OpenMP Language Terminology
  8850. // Structured block - An executable statement with a single entry at the
  8851. // top and a single exit at the bottom.
  8852. // The point of exit cannot be a branch out of the structured block.
  8853. // longjmp() and throw() must not violate the entry/exit criteria.
  8854. CS->getCapturedDecl()->setNothrow();
  8855. }
  8856. OMPLoopDirective::HelperExprs B;
  8857. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  8858. // define the nested loops number.
  8859. unsigned NestedLoopCount = checkOpenMPLoop(
  8860. OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
  8861. getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
  8862. VarsWithImplicitDSA, B);
  8863. if (NestedLoopCount == 0)
  8864. return StmtError();
  8865. assert((CurContext->isDependentContext() || B.builtAll()) &&
  8866. "omp target parallel for simd loop exprs were not built");
  8867. if (!CurContext->isDependentContext()) {
  8868. // Finalize the clauses that need pre-built expressions for CodeGen.
  8869. for (OMPClause *C : Clauses) {
  8870. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  8871. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  8872. B.NumIterations, *this, CurScope,
  8873. DSAStack))
  8874. return StmtError();
  8875. }
  8876. }
  8877. if (checkSimdlenSafelenSpecified(*this, Clauses))
  8878. return StmtError();
  8879. setFunctionHasBranchProtectedScope();
  8880. return OMPTargetParallelForSimdDirective::Create(
  8881. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  8882. }
  8883. StmtResult Sema::ActOnOpenMPTargetSimdDirective(
  8884. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  8885. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  8886. if (!AStmt)
  8887. return StmtError();
  8888. auto *CS = cast<CapturedStmt>(AStmt);
  8889. // 1.2.2 OpenMP Language Terminology
  8890. // Structured block - An executable statement with a single entry at the
  8891. // top and a single exit at the bottom.
  8892. // The point of exit cannot be a branch out of the structured block.
  8893. // longjmp() and throw() must not violate the entry/exit criteria.
  8894. CS->getCapturedDecl()->setNothrow();
  8895. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_simd);
  8896. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  8897. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  8898. // 1.2.2 OpenMP Language Terminology
  8899. // Structured block - An executable statement with a single entry at the
  8900. // top and a single exit at the bottom.
  8901. // The point of exit cannot be a branch out of the structured block.
  8902. // longjmp() and throw() must not violate the entry/exit criteria.
  8903. CS->getCapturedDecl()->setNothrow();
  8904. }
  8905. OMPLoopDirective::HelperExprs B;
  8906. // In presence of clause 'collapse' with number of loops, it will define the
  8907. // nested loops number.
  8908. unsigned NestedLoopCount =
  8909. checkOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
  8910. getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
  8911. VarsWithImplicitDSA, B);
  8912. if (NestedLoopCount == 0)
  8913. return StmtError();
  8914. assert((CurContext->isDependentContext() || B.builtAll()) &&
  8915. "omp target simd loop exprs were not built");
  8916. if (!CurContext->isDependentContext()) {
  8917. // Finalize the clauses that need pre-built expressions for CodeGen.
  8918. for (OMPClause *C : Clauses) {
  8919. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  8920. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  8921. B.NumIterations, *this, CurScope,
  8922. DSAStack))
  8923. return StmtError();
  8924. }
  8925. }
  8926. if (checkSimdlenSafelenSpecified(*this, Clauses))
  8927. return StmtError();
  8928. setFunctionHasBranchProtectedScope();
  8929. return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
  8930. NestedLoopCount, Clauses, AStmt, B);
  8931. }
  8932. StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
  8933. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  8934. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  8935. if (!AStmt)
  8936. return StmtError();
  8937. auto *CS = cast<CapturedStmt>(AStmt);
  8938. // 1.2.2 OpenMP Language Terminology
  8939. // Structured block - An executable statement with a single entry at the
  8940. // top and a single exit at the bottom.
  8941. // The point of exit cannot be a branch out of the structured block.
  8942. // longjmp() and throw() must not violate the entry/exit criteria.
  8943. CS->getCapturedDecl()->setNothrow();
  8944. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_teams_distribute);
  8945. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  8946. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  8947. // 1.2.2 OpenMP Language Terminology
  8948. // Structured block - An executable statement with a single entry at the
  8949. // top and a single exit at the bottom.
  8950. // The point of exit cannot be a branch out of the structured block.
  8951. // longjmp() and throw() must not violate the entry/exit criteria.
  8952. CS->getCapturedDecl()->setNothrow();
  8953. }
  8954. OMPLoopDirective::HelperExprs B;
  8955. // In presence of clause 'collapse' with number of loops, it will
  8956. // define the nested loops number.
  8957. unsigned NestedLoopCount =
  8958. checkOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
  8959. nullptr /*ordered not a clause on distribute*/, CS, *this,
  8960. *DSAStack, VarsWithImplicitDSA, B);
  8961. if (NestedLoopCount == 0)
  8962. return StmtError();
  8963. assert((CurContext->isDependentContext() || B.builtAll()) &&
  8964. "omp teams distribute loop exprs were not built");
  8965. setFunctionHasBranchProtectedScope();
  8966. DSAStack->setParentTeamsRegionLoc(StartLoc);
  8967. return OMPTeamsDistributeDirective::Create(
  8968. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  8969. }
  8970. StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
  8971. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  8972. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  8973. if (!AStmt)
  8974. return StmtError();
  8975. auto *CS = cast<CapturedStmt>(AStmt);
  8976. // 1.2.2 OpenMP Language Terminology
  8977. // Structured block - An executable statement with a single entry at the
  8978. // top and a single exit at the bottom.
  8979. // The point of exit cannot be a branch out of the structured block.
  8980. // longjmp() and throw() must not violate the entry/exit criteria.
  8981. CS->getCapturedDecl()->setNothrow();
  8982. for (int ThisCaptureLevel =
  8983. getOpenMPCaptureLevels(OMPD_teams_distribute_simd);
  8984. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  8985. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  8986. // 1.2.2 OpenMP Language Terminology
  8987. // Structured block - An executable statement with a single entry at the
  8988. // top and a single exit at the bottom.
  8989. // The point of exit cannot be a branch out of the structured block.
  8990. // longjmp() and throw() must not violate the entry/exit criteria.
  8991. CS->getCapturedDecl()->setNothrow();
  8992. }
  8993. OMPLoopDirective::HelperExprs B;
  8994. // In presence of clause 'collapse' with number of loops, it will
  8995. // define the nested loops number.
  8996. unsigned NestedLoopCount = checkOpenMPLoop(
  8997. OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
  8998. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  8999. VarsWithImplicitDSA, B);
  9000. if (NestedLoopCount == 0)
  9001. return StmtError();
  9002. assert((CurContext->isDependentContext() || B.builtAll()) &&
  9003. "omp teams distribute simd loop exprs were not built");
  9004. if (!CurContext->isDependentContext()) {
  9005. // Finalize the clauses that need pre-built expressions for CodeGen.
  9006. for (OMPClause *C : Clauses) {
  9007. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  9008. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  9009. B.NumIterations, *this, CurScope,
  9010. DSAStack))
  9011. return StmtError();
  9012. }
  9013. }
  9014. if (checkSimdlenSafelenSpecified(*this, Clauses))
  9015. return StmtError();
  9016. setFunctionHasBranchProtectedScope();
  9017. DSAStack->setParentTeamsRegionLoc(StartLoc);
  9018. return OMPTeamsDistributeSimdDirective::Create(
  9019. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  9020. }
  9021. StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
  9022. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  9023. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  9024. if (!AStmt)
  9025. return StmtError();
  9026. auto *CS = cast<CapturedStmt>(AStmt);
  9027. // 1.2.2 OpenMP Language Terminology
  9028. // Structured block - An executable statement with a single entry at the
  9029. // top and a single exit at the bottom.
  9030. // The point of exit cannot be a branch out of the structured block.
  9031. // longjmp() and throw() must not violate the entry/exit criteria.
  9032. CS->getCapturedDecl()->setNothrow();
  9033. for (int ThisCaptureLevel =
  9034. getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for_simd);
  9035. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  9036. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  9037. // 1.2.2 OpenMP Language Terminology
  9038. // Structured block - An executable statement with a single entry at the
  9039. // top and a single exit at the bottom.
  9040. // The point of exit cannot be a branch out of the structured block.
  9041. // longjmp() and throw() must not violate the entry/exit criteria.
  9042. CS->getCapturedDecl()->setNothrow();
  9043. }
  9044. OMPLoopDirective::HelperExprs B;
  9045. // In presence of clause 'collapse' with number of loops, it will
  9046. // define the nested loops number.
  9047. unsigned NestedLoopCount = checkOpenMPLoop(
  9048. OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
  9049. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  9050. VarsWithImplicitDSA, B);
  9051. if (NestedLoopCount == 0)
  9052. return StmtError();
  9053. assert((CurContext->isDependentContext() || B.builtAll()) &&
  9054. "omp for loop exprs were not built");
  9055. if (!CurContext->isDependentContext()) {
  9056. // Finalize the clauses that need pre-built expressions for CodeGen.
  9057. for (OMPClause *C : Clauses) {
  9058. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  9059. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  9060. B.NumIterations, *this, CurScope,
  9061. DSAStack))
  9062. return StmtError();
  9063. }
  9064. }
  9065. if (checkSimdlenSafelenSpecified(*this, Clauses))
  9066. return StmtError();
  9067. setFunctionHasBranchProtectedScope();
  9068. DSAStack->setParentTeamsRegionLoc(StartLoc);
  9069. return OMPTeamsDistributeParallelForSimdDirective::Create(
  9070. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  9071. }
  9072. StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
  9073. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  9074. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  9075. if (!AStmt)
  9076. return StmtError();
  9077. auto *CS = cast<CapturedStmt>(AStmt);
  9078. // 1.2.2 OpenMP Language Terminology
  9079. // Structured block - An executable statement with a single entry at the
  9080. // top and a single exit at the bottom.
  9081. // The point of exit cannot be a branch out of the structured block.
  9082. // longjmp() and throw() must not violate the entry/exit criteria.
  9083. CS->getCapturedDecl()->setNothrow();
  9084. for (int ThisCaptureLevel =
  9085. getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for);
  9086. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  9087. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  9088. // 1.2.2 OpenMP Language Terminology
  9089. // Structured block - An executable statement with a single entry at the
  9090. // top and a single exit at the bottom.
  9091. // The point of exit cannot be a branch out of the structured block.
  9092. // longjmp() and throw() must not violate the entry/exit criteria.
  9093. CS->getCapturedDecl()->setNothrow();
  9094. }
  9095. OMPLoopDirective::HelperExprs B;
  9096. // In presence of clause 'collapse' with number of loops, it will
  9097. // define the nested loops number.
  9098. unsigned NestedLoopCount = checkOpenMPLoop(
  9099. OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
  9100. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  9101. VarsWithImplicitDSA, B);
  9102. if (NestedLoopCount == 0)
  9103. return StmtError();
  9104. assert((CurContext->isDependentContext() || B.builtAll()) &&
  9105. "omp for loop exprs were not built");
  9106. setFunctionHasBranchProtectedScope();
  9107. DSAStack->setParentTeamsRegionLoc(StartLoc);
  9108. return OMPTeamsDistributeParallelForDirective::Create(
  9109. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
  9110. DSAStack->isCancelRegion());
  9111. }
  9112. StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
  9113. Stmt *AStmt,
  9114. SourceLocation StartLoc,
  9115. SourceLocation EndLoc) {
  9116. if (!AStmt)
  9117. return StmtError();
  9118. auto *CS = cast<CapturedStmt>(AStmt);
  9119. // 1.2.2 OpenMP Language Terminology
  9120. // Structured block - An executable statement with a single entry at the
  9121. // top and a single exit at the bottom.
  9122. // The point of exit cannot be a branch out of the structured block.
  9123. // longjmp() and throw() must not violate the entry/exit criteria.
  9124. CS->getCapturedDecl()->setNothrow();
  9125. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_teams);
  9126. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  9127. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  9128. // 1.2.2 OpenMP Language Terminology
  9129. // Structured block - An executable statement with a single entry at the
  9130. // top and a single exit at the bottom.
  9131. // The point of exit cannot be a branch out of the structured block.
  9132. // longjmp() and throw() must not violate the entry/exit criteria.
  9133. CS->getCapturedDecl()->setNothrow();
  9134. }
  9135. setFunctionHasBranchProtectedScope();
  9136. return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
  9137. AStmt);
  9138. }
  9139. StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective(
  9140. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  9141. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  9142. if (!AStmt)
  9143. return StmtError();
  9144. auto *CS = cast<CapturedStmt>(AStmt);
  9145. // 1.2.2 OpenMP Language Terminology
  9146. // Structured block - An executable statement with a single entry at the
  9147. // top and a single exit at the bottom.
  9148. // The point of exit cannot be a branch out of the structured block.
  9149. // longjmp() and throw() must not violate the entry/exit criteria.
  9150. CS->getCapturedDecl()->setNothrow();
  9151. for (int ThisCaptureLevel =
  9152. getOpenMPCaptureLevels(OMPD_target_teams_distribute);
  9153. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  9154. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  9155. // 1.2.2 OpenMP Language Terminology
  9156. // Structured block - An executable statement with a single entry at the
  9157. // top and a single exit at the bottom.
  9158. // The point of exit cannot be a branch out of the structured block.
  9159. // longjmp() and throw() must not violate the entry/exit criteria.
  9160. CS->getCapturedDecl()->setNothrow();
  9161. }
  9162. OMPLoopDirective::HelperExprs B;
  9163. // In presence of clause 'collapse' with number of loops, it will
  9164. // define the nested loops number.
  9165. unsigned NestedLoopCount = checkOpenMPLoop(
  9166. OMPD_target_teams_distribute, getCollapseNumberExpr(Clauses),
  9167. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  9168. VarsWithImplicitDSA, B);
  9169. if (NestedLoopCount == 0)
  9170. return StmtError();
  9171. assert((CurContext->isDependentContext() || B.builtAll()) &&
  9172. "omp target teams distribute loop exprs were not built");
  9173. setFunctionHasBranchProtectedScope();
  9174. return OMPTargetTeamsDistributeDirective::Create(
  9175. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  9176. }
  9177. StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective(
  9178. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  9179. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  9180. if (!AStmt)
  9181. return StmtError();
  9182. auto *CS = cast<CapturedStmt>(AStmt);
  9183. // 1.2.2 OpenMP Language Terminology
  9184. // Structured block - An executable statement with a single entry at the
  9185. // top and a single exit at the bottom.
  9186. // The point of exit cannot be a branch out of the structured block.
  9187. // longjmp() and throw() must not violate the entry/exit criteria.
  9188. CS->getCapturedDecl()->setNothrow();
  9189. for (int ThisCaptureLevel =
  9190. getOpenMPCaptureLevels(OMPD_target_teams_distribute_parallel_for);
  9191. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  9192. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  9193. // 1.2.2 OpenMP Language Terminology
  9194. // Structured block - An executable statement with a single entry at the
  9195. // top and a single exit at the bottom.
  9196. // The point of exit cannot be a branch out of the structured block.
  9197. // longjmp() and throw() must not violate the entry/exit criteria.
  9198. CS->getCapturedDecl()->setNothrow();
  9199. }
  9200. OMPLoopDirective::HelperExprs B;
  9201. // In presence of clause 'collapse' with number of loops, it will
  9202. // define the nested loops number.
  9203. unsigned NestedLoopCount = checkOpenMPLoop(
  9204. OMPD_target_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
  9205. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  9206. VarsWithImplicitDSA, B);
  9207. if (NestedLoopCount == 0)
  9208. return StmtError();
  9209. assert((CurContext->isDependentContext() || B.builtAll()) &&
  9210. "omp target teams distribute parallel for loop exprs were not built");
  9211. if (!CurContext->isDependentContext()) {
  9212. // Finalize the clauses that need pre-built expressions for CodeGen.
  9213. for (OMPClause *C : Clauses) {
  9214. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  9215. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  9216. B.NumIterations, *this, CurScope,
  9217. DSAStack))
  9218. return StmtError();
  9219. }
  9220. }
  9221. setFunctionHasBranchProtectedScope();
  9222. return OMPTargetTeamsDistributeParallelForDirective::Create(
  9223. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
  9224. DSAStack->isCancelRegion());
  9225. }
  9226. StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
  9227. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  9228. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  9229. if (!AStmt)
  9230. return StmtError();
  9231. auto *CS = cast<CapturedStmt>(AStmt);
  9232. // 1.2.2 OpenMP Language Terminology
  9233. // Structured block - An executable statement with a single entry at the
  9234. // top and a single exit at the bottom.
  9235. // The point of exit cannot be a branch out of the structured block.
  9236. // longjmp() and throw() must not violate the entry/exit criteria.
  9237. CS->getCapturedDecl()->setNothrow();
  9238. for (int ThisCaptureLevel = getOpenMPCaptureLevels(
  9239. OMPD_target_teams_distribute_parallel_for_simd);
  9240. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  9241. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  9242. // 1.2.2 OpenMP Language Terminology
  9243. // Structured block - An executable statement with a single entry at the
  9244. // top and a single exit at the bottom.
  9245. // The point of exit cannot be a branch out of the structured block.
  9246. // longjmp() and throw() must not violate the entry/exit criteria.
  9247. CS->getCapturedDecl()->setNothrow();
  9248. }
  9249. OMPLoopDirective::HelperExprs B;
  9250. // In presence of clause 'collapse' with number of loops, it will
  9251. // define the nested loops number.
  9252. unsigned NestedLoopCount =
  9253. checkOpenMPLoop(OMPD_target_teams_distribute_parallel_for_simd,
  9254. getCollapseNumberExpr(Clauses),
  9255. nullptr /*ordered not a clause on distribute*/, CS, *this,
  9256. *DSAStack, VarsWithImplicitDSA, B);
  9257. if (NestedLoopCount == 0)
  9258. return StmtError();
  9259. assert((CurContext->isDependentContext() || B.builtAll()) &&
  9260. "omp target teams distribute parallel for simd loop exprs were not "
  9261. "built");
  9262. if (!CurContext->isDependentContext()) {
  9263. // Finalize the clauses that need pre-built expressions for CodeGen.
  9264. for (OMPClause *C : Clauses) {
  9265. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  9266. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  9267. B.NumIterations, *this, CurScope,
  9268. DSAStack))
  9269. return StmtError();
  9270. }
  9271. }
  9272. if (checkSimdlenSafelenSpecified(*this, Clauses))
  9273. return StmtError();
  9274. setFunctionHasBranchProtectedScope();
  9275. return OMPTargetTeamsDistributeParallelForSimdDirective::Create(
  9276. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  9277. }
  9278. StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective(
  9279. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  9280. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  9281. if (!AStmt)
  9282. return StmtError();
  9283. auto *CS = cast<CapturedStmt>(AStmt);
  9284. // 1.2.2 OpenMP Language Terminology
  9285. // Structured block - An executable statement with a single entry at the
  9286. // top and a single exit at the bottom.
  9287. // The point of exit cannot be a branch out of the structured block.
  9288. // longjmp() and throw() must not violate the entry/exit criteria.
  9289. CS->getCapturedDecl()->setNothrow();
  9290. for (int ThisCaptureLevel =
  9291. getOpenMPCaptureLevels(OMPD_target_teams_distribute_simd);
  9292. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  9293. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  9294. // 1.2.2 OpenMP Language Terminology
  9295. // Structured block - An executable statement with a single entry at the
  9296. // top and a single exit at the bottom.
  9297. // The point of exit cannot be a branch out of the structured block.
  9298. // longjmp() and throw() must not violate the entry/exit criteria.
  9299. CS->getCapturedDecl()->setNothrow();
  9300. }
  9301. OMPLoopDirective::HelperExprs B;
  9302. // In presence of clause 'collapse' with number of loops, it will
  9303. // define the nested loops number.
  9304. unsigned NestedLoopCount = checkOpenMPLoop(
  9305. OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses),
  9306. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  9307. VarsWithImplicitDSA, B);
  9308. if (NestedLoopCount == 0)
  9309. return StmtError();
  9310. assert((CurContext->isDependentContext() || B.builtAll()) &&
  9311. "omp target teams distribute simd loop exprs were not built");
  9312. if (!CurContext->isDependentContext()) {
  9313. // Finalize the clauses that need pre-built expressions for CodeGen.
  9314. for (OMPClause *C : Clauses) {
  9315. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  9316. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  9317. B.NumIterations, *this, CurScope,
  9318. DSAStack))
  9319. return StmtError();
  9320. }
  9321. }
  9322. if (checkSimdlenSafelenSpecified(*this, Clauses))
  9323. return StmtError();
  9324. setFunctionHasBranchProtectedScope();
  9325. return OMPTargetTeamsDistributeSimdDirective::Create(
  9326. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  9327. }
  9328. OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
  9329. SourceLocation StartLoc,
  9330. SourceLocation LParenLoc,
  9331. SourceLocation EndLoc) {
  9332. OMPClause *Res = nullptr;
  9333. switch (Kind) {
  9334. case OMPC_final:
  9335. Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
  9336. break;
  9337. case OMPC_num_threads:
  9338. Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
  9339. break;
  9340. case OMPC_safelen:
  9341. Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
  9342. break;
  9343. case OMPC_simdlen:
  9344. Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
  9345. break;
  9346. case OMPC_allocator:
  9347. Res = ActOnOpenMPAllocatorClause(Expr, StartLoc, LParenLoc, EndLoc);
  9348. break;
  9349. case OMPC_collapse:
  9350. Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
  9351. break;
  9352. case OMPC_ordered:
  9353. Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
  9354. break;
  9355. case OMPC_device:
  9356. Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
  9357. break;
  9358. case OMPC_num_teams:
  9359. Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
  9360. break;
  9361. case OMPC_thread_limit:
  9362. Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
  9363. break;
  9364. case OMPC_priority:
  9365. Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
  9366. break;
  9367. case OMPC_grainsize:
  9368. Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
  9369. break;
  9370. case OMPC_num_tasks:
  9371. Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
  9372. break;
  9373. case OMPC_hint:
  9374. Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
  9375. break;
  9376. case OMPC_if:
  9377. case OMPC_default:
  9378. case OMPC_proc_bind:
  9379. case OMPC_schedule:
  9380. case OMPC_private:
  9381. case OMPC_firstprivate:
  9382. case OMPC_lastprivate:
  9383. case OMPC_shared:
  9384. case OMPC_reduction:
  9385. case OMPC_task_reduction:
  9386. case OMPC_in_reduction:
  9387. case OMPC_linear:
  9388. case OMPC_aligned:
  9389. case OMPC_copyin:
  9390. case OMPC_copyprivate:
  9391. case OMPC_nowait:
  9392. case OMPC_untied:
  9393. case OMPC_mergeable:
  9394. case OMPC_threadprivate:
  9395. case OMPC_allocate:
  9396. case OMPC_flush:
  9397. case OMPC_read:
  9398. case OMPC_write:
  9399. case OMPC_update:
  9400. case OMPC_capture:
  9401. case OMPC_seq_cst:
  9402. case OMPC_depend:
  9403. case OMPC_threads:
  9404. case OMPC_simd:
  9405. case OMPC_map:
  9406. case OMPC_nogroup:
  9407. case OMPC_dist_schedule:
  9408. case OMPC_defaultmap:
  9409. case OMPC_unknown:
  9410. case OMPC_uniform:
  9411. case OMPC_to:
  9412. case OMPC_from:
  9413. case OMPC_use_device_ptr:
  9414. case OMPC_is_device_ptr:
  9415. case OMPC_unified_address:
  9416. case OMPC_unified_shared_memory:
  9417. case OMPC_reverse_offload:
  9418. case OMPC_dynamic_allocators:
  9419. case OMPC_atomic_default_mem_order:
  9420. case OMPC_device_type:
  9421. case OMPC_match:
  9422. llvm_unreachable("Clause is not allowed.");
  9423. }
  9424. return Res;
  9425. }
  9426. // An OpenMP directive such as 'target parallel' has two captured regions:
  9427. // for the 'target' and 'parallel' respectively. This function returns
  9428. // the region in which to capture expressions associated with a clause.
  9429. // A return value of OMPD_unknown signifies that the expression should not
  9430. // be captured.
  9431. static OpenMPDirectiveKind getOpenMPCaptureRegionForClause(
  9432. OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
  9433. OpenMPDirectiveKind NameModifier = OMPD_unknown) {
  9434. OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
  9435. switch (CKind) {
  9436. case OMPC_if:
  9437. switch (DKind) {
  9438. case OMPD_target_parallel:
  9439. case OMPD_target_parallel_for:
  9440. case OMPD_target_parallel_for_simd:
  9441. // If this clause applies to the nested 'parallel' region, capture within
  9442. // the 'target' region, otherwise do not capture.
  9443. if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
  9444. CaptureRegion = OMPD_target;
  9445. break;
  9446. case OMPD_target_teams_distribute_parallel_for:
  9447. case OMPD_target_teams_distribute_parallel_for_simd:
  9448. // If this clause applies to the nested 'parallel' region, capture within
  9449. // the 'teams' region, otherwise do not capture.
  9450. if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
  9451. CaptureRegion = OMPD_teams;
  9452. break;
  9453. case OMPD_teams_distribute_parallel_for:
  9454. case OMPD_teams_distribute_parallel_for_simd:
  9455. CaptureRegion = OMPD_teams;
  9456. break;
  9457. case OMPD_target_update:
  9458. case OMPD_target_enter_data:
  9459. case OMPD_target_exit_data:
  9460. CaptureRegion = OMPD_task;
  9461. break;
  9462. case OMPD_cancel:
  9463. case OMPD_parallel:
  9464. case OMPD_parallel_sections:
  9465. case OMPD_parallel_for:
  9466. case OMPD_parallel_for_simd:
  9467. case OMPD_target:
  9468. case OMPD_target_simd:
  9469. case OMPD_target_teams:
  9470. case OMPD_target_teams_distribute:
  9471. case OMPD_target_teams_distribute_simd:
  9472. case OMPD_distribute_parallel_for:
  9473. case OMPD_distribute_parallel_for_simd:
  9474. case OMPD_task:
  9475. case OMPD_taskloop:
  9476. case OMPD_taskloop_simd:
  9477. case OMPD_target_data:
  9478. // Do not capture if-clause expressions.
  9479. break;
  9480. case OMPD_threadprivate:
  9481. case OMPD_allocate:
  9482. case OMPD_taskyield:
  9483. case OMPD_barrier:
  9484. case OMPD_taskwait:
  9485. case OMPD_cancellation_point:
  9486. case OMPD_flush:
  9487. case OMPD_declare_reduction:
  9488. case OMPD_declare_mapper:
  9489. case OMPD_declare_simd:
  9490. case OMPD_declare_variant:
  9491. case OMPD_declare_target:
  9492. case OMPD_end_declare_target:
  9493. case OMPD_teams:
  9494. case OMPD_simd:
  9495. case OMPD_for:
  9496. case OMPD_for_simd:
  9497. case OMPD_sections:
  9498. case OMPD_section:
  9499. case OMPD_single:
  9500. case OMPD_master:
  9501. case OMPD_critical:
  9502. case OMPD_taskgroup:
  9503. case OMPD_distribute:
  9504. case OMPD_ordered:
  9505. case OMPD_atomic:
  9506. case OMPD_distribute_simd:
  9507. case OMPD_teams_distribute:
  9508. case OMPD_teams_distribute_simd:
  9509. case OMPD_requires:
  9510. llvm_unreachable("Unexpected OpenMP directive with if-clause");
  9511. case OMPD_unknown:
  9512. llvm_unreachable("Unknown OpenMP directive");
  9513. }
  9514. break;
  9515. case OMPC_num_threads:
  9516. switch (DKind) {
  9517. case OMPD_target_parallel:
  9518. case OMPD_target_parallel_for:
  9519. case OMPD_target_parallel_for_simd:
  9520. CaptureRegion = OMPD_target;
  9521. break;
  9522. case OMPD_teams_distribute_parallel_for:
  9523. case OMPD_teams_distribute_parallel_for_simd:
  9524. case OMPD_target_teams_distribute_parallel_for:
  9525. case OMPD_target_teams_distribute_parallel_for_simd:
  9526. CaptureRegion = OMPD_teams;
  9527. break;
  9528. case OMPD_parallel:
  9529. case OMPD_parallel_sections:
  9530. case OMPD_parallel_for:
  9531. case OMPD_parallel_for_simd:
  9532. case OMPD_distribute_parallel_for:
  9533. case OMPD_distribute_parallel_for_simd:
  9534. // Do not capture num_threads-clause expressions.
  9535. break;
  9536. case OMPD_target_data:
  9537. case OMPD_target_enter_data:
  9538. case OMPD_target_exit_data:
  9539. case OMPD_target_update:
  9540. case OMPD_target:
  9541. case OMPD_target_simd:
  9542. case OMPD_target_teams:
  9543. case OMPD_target_teams_distribute:
  9544. case OMPD_target_teams_distribute_simd:
  9545. case OMPD_cancel:
  9546. case OMPD_task:
  9547. case OMPD_taskloop:
  9548. case OMPD_taskloop_simd:
  9549. case OMPD_threadprivate:
  9550. case OMPD_allocate:
  9551. case OMPD_taskyield:
  9552. case OMPD_barrier:
  9553. case OMPD_taskwait:
  9554. case OMPD_cancellation_point:
  9555. case OMPD_flush:
  9556. case OMPD_declare_reduction:
  9557. case OMPD_declare_mapper:
  9558. case OMPD_declare_simd:
  9559. case OMPD_declare_variant:
  9560. case OMPD_declare_target:
  9561. case OMPD_end_declare_target:
  9562. case OMPD_teams:
  9563. case OMPD_simd:
  9564. case OMPD_for:
  9565. case OMPD_for_simd:
  9566. case OMPD_sections:
  9567. case OMPD_section:
  9568. case OMPD_single:
  9569. case OMPD_master:
  9570. case OMPD_critical:
  9571. case OMPD_taskgroup:
  9572. case OMPD_distribute:
  9573. case OMPD_ordered:
  9574. case OMPD_atomic:
  9575. case OMPD_distribute_simd:
  9576. case OMPD_teams_distribute:
  9577. case OMPD_teams_distribute_simd:
  9578. case OMPD_requires:
  9579. llvm_unreachable("Unexpected OpenMP directive with num_threads-clause");
  9580. case OMPD_unknown:
  9581. llvm_unreachable("Unknown OpenMP directive");
  9582. }
  9583. break;
  9584. case OMPC_num_teams:
  9585. switch (DKind) {
  9586. case OMPD_target_teams:
  9587. case OMPD_target_teams_distribute:
  9588. case OMPD_target_teams_distribute_simd:
  9589. case OMPD_target_teams_distribute_parallel_for:
  9590. case OMPD_target_teams_distribute_parallel_for_simd:
  9591. CaptureRegion = OMPD_target;
  9592. break;
  9593. case OMPD_teams_distribute_parallel_for:
  9594. case OMPD_teams_distribute_parallel_for_simd:
  9595. case OMPD_teams:
  9596. case OMPD_teams_distribute:
  9597. case OMPD_teams_distribute_simd:
  9598. // Do not capture num_teams-clause expressions.
  9599. break;
  9600. case OMPD_distribute_parallel_for:
  9601. case OMPD_distribute_parallel_for_simd:
  9602. case OMPD_task:
  9603. case OMPD_taskloop:
  9604. case OMPD_taskloop_simd:
  9605. case OMPD_target_data:
  9606. case OMPD_target_enter_data:
  9607. case OMPD_target_exit_data:
  9608. case OMPD_target_update:
  9609. case OMPD_cancel:
  9610. case OMPD_parallel:
  9611. case OMPD_parallel_sections:
  9612. case OMPD_parallel_for:
  9613. case OMPD_parallel_for_simd:
  9614. case OMPD_target:
  9615. case OMPD_target_simd:
  9616. case OMPD_target_parallel:
  9617. case OMPD_target_parallel_for:
  9618. case OMPD_target_parallel_for_simd:
  9619. case OMPD_threadprivate:
  9620. case OMPD_allocate:
  9621. case OMPD_taskyield:
  9622. case OMPD_barrier:
  9623. case OMPD_taskwait:
  9624. case OMPD_cancellation_point:
  9625. case OMPD_flush:
  9626. case OMPD_declare_reduction:
  9627. case OMPD_declare_mapper:
  9628. case OMPD_declare_simd:
  9629. case OMPD_declare_variant:
  9630. case OMPD_declare_target:
  9631. case OMPD_end_declare_target:
  9632. case OMPD_simd:
  9633. case OMPD_for:
  9634. case OMPD_for_simd:
  9635. case OMPD_sections:
  9636. case OMPD_section:
  9637. case OMPD_single:
  9638. case OMPD_master:
  9639. case OMPD_critical:
  9640. case OMPD_taskgroup:
  9641. case OMPD_distribute:
  9642. case OMPD_ordered:
  9643. case OMPD_atomic:
  9644. case OMPD_distribute_simd:
  9645. case OMPD_requires:
  9646. llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
  9647. case OMPD_unknown:
  9648. llvm_unreachable("Unknown OpenMP directive");
  9649. }
  9650. break;
  9651. case OMPC_thread_limit:
  9652. switch (DKind) {
  9653. case OMPD_target_teams:
  9654. case OMPD_target_teams_distribute:
  9655. case OMPD_target_teams_distribute_simd:
  9656. case OMPD_target_teams_distribute_parallel_for:
  9657. case OMPD_target_teams_distribute_parallel_for_simd:
  9658. CaptureRegion = OMPD_target;
  9659. break;
  9660. case OMPD_teams_distribute_parallel_for:
  9661. case OMPD_teams_distribute_parallel_for_simd:
  9662. case OMPD_teams:
  9663. case OMPD_teams_distribute:
  9664. case OMPD_teams_distribute_simd:
  9665. // Do not capture thread_limit-clause expressions.
  9666. break;
  9667. case OMPD_distribute_parallel_for:
  9668. case OMPD_distribute_parallel_for_simd:
  9669. case OMPD_task:
  9670. case OMPD_taskloop:
  9671. case OMPD_taskloop_simd:
  9672. case OMPD_target_data:
  9673. case OMPD_target_enter_data:
  9674. case OMPD_target_exit_data:
  9675. case OMPD_target_update:
  9676. case OMPD_cancel:
  9677. case OMPD_parallel:
  9678. case OMPD_parallel_sections:
  9679. case OMPD_parallel_for:
  9680. case OMPD_parallel_for_simd:
  9681. case OMPD_target:
  9682. case OMPD_target_simd:
  9683. case OMPD_target_parallel:
  9684. case OMPD_target_parallel_for:
  9685. case OMPD_target_parallel_for_simd:
  9686. case OMPD_threadprivate:
  9687. case OMPD_allocate:
  9688. case OMPD_taskyield:
  9689. case OMPD_barrier:
  9690. case OMPD_taskwait:
  9691. case OMPD_cancellation_point:
  9692. case OMPD_flush:
  9693. case OMPD_declare_reduction:
  9694. case OMPD_declare_mapper:
  9695. case OMPD_declare_simd:
  9696. case OMPD_declare_variant:
  9697. case OMPD_declare_target:
  9698. case OMPD_end_declare_target:
  9699. case OMPD_simd:
  9700. case OMPD_for:
  9701. case OMPD_for_simd:
  9702. case OMPD_sections:
  9703. case OMPD_section:
  9704. case OMPD_single:
  9705. case OMPD_master:
  9706. case OMPD_critical:
  9707. case OMPD_taskgroup:
  9708. case OMPD_distribute:
  9709. case OMPD_ordered:
  9710. case OMPD_atomic:
  9711. case OMPD_distribute_simd:
  9712. case OMPD_requires:
  9713. llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause");
  9714. case OMPD_unknown:
  9715. llvm_unreachable("Unknown OpenMP directive");
  9716. }
  9717. break;
  9718. case OMPC_schedule:
  9719. switch (DKind) {
  9720. case OMPD_parallel_for:
  9721. case OMPD_parallel_for_simd:
  9722. case OMPD_distribute_parallel_for:
  9723. case OMPD_distribute_parallel_for_simd:
  9724. case OMPD_teams_distribute_parallel_for:
  9725. case OMPD_teams_distribute_parallel_for_simd:
  9726. case OMPD_target_parallel_for:
  9727. case OMPD_target_parallel_for_simd:
  9728. case OMPD_target_teams_distribute_parallel_for:
  9729. case OMPD_target_teams_distribute_parallel_for_simd:
  9730. CaptureRegion = OMPD_parallel;
  9731. break;
  9732. case OMPD_for:
  9733. case OMPD_for_simd:
  9734. // Do not capture schedule-clause expressions.
  9735. break;
  9736. case OMPD_task:
  9737. case OMPD_taskloop:
  9738. case OMPD_taskloop_simd:
  9739. case OMPD_target_data:
  9740. case OMPD_target_enter_data:
  9741. case OMPD_target_exit_data:
  9742. case OMPD_target_update:
  9743. case OMPD_teams:
  9744. case OMPD_teams_distribute:
  9745. case OMPD_teams_distribute_simd:
  9746. case OMPD_target_teams_distribute:
  9747. case OMPD_target_teams_distribute_simd:
  9748. case OMPD_target:
  9749. case OMPD_target_simd:
  9750. case OMPD_target_parallel:
  9751. case OMPD_cancel:
  9752. case OMPD_parallel:
  9753. case OMPD_parallel_sections:
  9754. case OMPD_threadprivate:
  9755. case OMPD_allocate:
  9756. case OMPD_taskyield:
  9757. case OMPD_barrier:
  9758. case OMPD_taskwait:
  9759. case OMPD_cancellation_point:
  9760. case OMPD_flush:
  9761. case OMPD_declare_reduction:
  9762. case OMPD_declare_mapper:
  9763. case OMPD_declare_simd:
  9764. case OMPD_declare_variant:
  9765. case OMPD_declare_target:
  9766. case OMPD_end_declare_target:
  9767. case OMPD_simd:
  9768. case OMPD_sections:
  9769. case OMPD_section:
  9770. case OMPD_single:
  9771. case OMPD_master:
  9772. case OMPD_critical:
  9773. case OMPD_taskgroup:
  9774. case OMPD_distribute:
  9775. case OMPD_ordered:
  9776. case OMPD_atomic:
  9777. case OMPD_distribute_simd:
  9778. case OMPD_target_teams:
  9779. case OMPD_requires:
  9780. llvm_unreachable("Unexpected OpenMP directive with schedule clause");
  9781. case OMPD_unknown:
  9782. llvm_unreachable("Unknown OpenMP directive");
  9783. }
  9784. break;
  9785. case OMPC_dist_schedule:
  9786. switch (DKind) {
  9787. case OMPD_teams_distribute_parallel_for:
  9788. case OMPD_teams_distribute_parallel_for_simd:
  9789. case OMPD_teams_distribute:
  9790. case OMPD_teams_distribute_simd:
  9791. case OMPD_target_teams_distribute_parallel_for:
  9792. case OMPD_target_teams_distribute_parallel_for_simd:
  9793. case OMPD_target_teams_distribute:
  9794. case OMPD_target_teams_distribute_simd:
  9795. CaptureRegion = OMPD_teams;
  9796. break;
  9797. case OMPD_distribute_parallel_for:
  9798. case OMPD_distribute_parallel_for_simd:
  9799. case OMPD_distribute:
  9800. case OMPD_distribute_simd:
  9801. // Do not capture thread_limit-clause expressions.
  9802. break;
  9803. case OMPD_parallel_for:
  9804. case OMPD_parallel_for_simd:
  9805. case OMPD_target_parallel_for_simd:
  9806. case OMPD_target_parallel_for:
  9807. case OMPD_task:
  9808. case OMPD_taskloop:
  9809. case OMPD_taskloop_simd:
  9810. case OMPD_target_data:
  9811. case OMPD_target_enter_data:
  9812. case OMPD_target_exit_data:
  9813. case OMPD_target_update:
  9814. case OMPD_teams:
  9815. case OMPD_target:
  9816. case OMPD_target_simd:
  9817. case OMPD_target_parallel:
  9818. case OMPD_cancel:
  9819. case OMPD_parallel:
  9820. case OMPD_parallel_sections:
  9821. case OMPD_threadprivate:
  9822. case OMPD_allocate:
  9823. case OMPD_taskyield:
  9824. case OMPD_barrier:
  9825. case OMPD_taskwait:
  9826. case OMPD_cancellation_point:
  9827. case OMPD_flush:
  9828. case OMPD_declare_reduction:
  9829. case OMPD_declare_mapper:
  9830. case OMPD_declare_simd:
  9831. case OMPD_declare_variant:
  9832. case OMPD_declare_target:
  9833. case OMPD_end_declare_target:
  9834. case OMPD_simd:
  9835. case OMPD_for:
  9836. case OMPD_for_simd:
  9837. case OMPD_sections:
  9838. case OMPD_section:
  9839. case OMPD_single:
  9840. case OMPD_master:
  9841. case OMPD_critical:
  9842. case OMPD_taskgroup:
  9843. case OMPD_ordered:
  9844. case OMPD_atomic:
  9845. case OMPD_target_teams:
  9846. case OMPD_requires:
  9847. llvm_unreachable("Unexpected OpenMP directive with schedule clause");
  9848. case OMPD_unknown:
  9849. llvm_unreachable("Unknown OpenMP directive");
  9850. }
  9851. break;
  9852. case OMPC_device:
  9853. switch (DKind) {
  9854. case OMPD_target_update:
  9855. case OMPD_target_enter_data:
  9856. case OMPD_target_exit_data:
  9857. case OMPD_target:
  9858. case OMPD_target_simd:
  9859. case OMPD_target_teams:
  9860. case OMPD_target_parallel:
  9861. case OMPD_target_teams_distribute:
  9862. case OMPD_target_teams_distribute_simd:
  9863. case OMPD_target_parallel_for:
  9864. case OMPD_target_parallel_for_simd:
  9865. case OMPD_target_teams_distribute_parallel_for:
  9866. case OMPD_target_teams_distribute_parallel_for_simd:
  9867. CaptureRegion = OMPD_task;
  9868. break;
  9869. case OMPD_target_data:
  9870. // Do not capture device-clause expressions.
  9871. break;
  9872. case OMPD_teams_distribute_parallel_for:
  9873. case OMPD_teams_distribute_parallel_for_simd:
  9874. case OMPD_teams:
  9875. case OMPD_teams_distribute:
  9876. case OMPD_teams_distribute_simd:
  9877. case OMPD_distribute_parallel_for:
  9878. case OMPD_distribute_parallel_for_simd:
  9879. case OMPD_task:
  9880. case OMPD_taskloop:
  9881. case OMPD_taskloop_simd:
  9882. case OMPD_cancel:
  9883. case OMPD_parallel:
  9884. case OMPD_parallel_sections:
  9885. case OMPD_parallel_for:
  9886. case OMPD_parallel_for_simd:
  9887. case OMPD_threadprivate:
  9888. case OMPD_allocate:
  9889. case OMPD_taskyield:
  9890. case OMPD_barrier:
  9891. case OMPD_taskwait:
  9892. case OMPD_cancellation_point:
  9893. case OMPD_flush:
  9894. case OMPD_declare_reduction:
  9895. case OMPD_declare_mapper:
  9896. case OMPD_declare_simd:
  9897. case OMPD_declare_variant:
  9898. case OMPD_declare_target:
  9899. case OMPD_end_declare_target:
  9900. case OMPD_simd:
  9901. case OMPD_for:
  9902. case OMPD_for_simd:
  9903. case OMPD_sections:
  9904. case OMPD_section:
  9905. case OMPD_single:
  9906. case OMPD_master:
  9907. case OMPD_critical:
  9908. case OMPD_taskgroup:
  9909. case OMPD_distribute:
  9910. case OMPD_ordered:
  9911. case OMPD_atomic:
  9912. case OMPD_distribute_simd:
  9913. case OMPD_requires:
  9914. llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
  9915. case OMPD_unknown:
  9916. llvm_unreachable("Unknown OpenMP directive");
  9917. }
  9918. break;
  9919. case OMPC_firstprivate:
  9920. case OMPC_lastprivate:
  9921. case OMPC_reduction:
  9922. case OMPC_task_reduction:
  9923. case OMPC_in_reduction:
  9924. case OMPC_linear:
  9925. case OMPC_default:
  9926. case OMPC_proc_bind:
  9927. case OMPC_final:
  9928. case OMPC_safelen:
  9929. case OMPC_simdlen:
  9930. case OMPC_allocator:
  9931. case OMPC_collapse:
  9932. case OMPC_private:
  9933. case OMPC_shared:
  9934. case OMPC_aligned:
  9935. case OMPC_copyin:
  9936. case OMPC_copyprivate:
  9937. case OMPC_ordered:
  9938. case OMPC_nowait:
  9939. case OMPC_untied:
  9940. case OMPC_mergeable:
  9941. case OMPC_threadprivate:
  9942. case OMPC_allocate:
  9943. case OMPC_flush:
  9944. case OMPC_read:
  9945. case OMPC_write:
  9946. case OMPC_update:
  9947. case OMPC_capture:
  9948. case OMPC_seq_cst:
  9949. case OMPC_depend:
  9950. case OMPC_threads:
  9951. case OMPC_simd:
  9952. case OMPC_map:
  9953. case OMPC_priority:
  9954. case OMPC_grainsize:
  9955. case OMPC_nogroup:
  9956. case OMPC_num_tasks:
  9957. case OMPC_hint:
  9958. case OMPC_defaultmap:
  9959. case OMPC_unknown:
  9960. case OMPC_uniform:
  9961. case OMPC_to:
  9962. case OMPC_from:
  9963. case OMPC_use_device_ptr:
  9964. case OMPC_is_device_ptr:
  9965. case OMPC_unified_address:
  9966. case OMPC_unified_shared_memory:
  9967. case OMPC_reverse_offload:
  9968. case OMPC_dynamic_allocators:
  9969. case OMPC_atomic_default_mem_order:
  9970. case OMPC_device_type:
  9971. case OMPC_match:
  9972. llvm_unreachable("Unexpected OpenMP clause.");
  9973. }
  9974. return CaptureRegion;
  9975. }
  9976. OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
  9977. Expr *Condition, SourceLocation StartLoc,
  9978. SourceLocation LParenLoc,
  9979. SourceLocation NameModifierLoc,
  9980. SourceLocation ColonLoc,
  9981. SourceLocation EndLoc) {
  9982. Expr *ValExpr = Condition;
  9983. Stmt *HelperValStmt = nullptr;
  9984. OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
  9985. if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
  9986. !Condition->isInstantiationDependent() &&
  9987. !Condition->containsUnexpandedParameterPack()) {
  9988. ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
  9989. if (Val.isInvalid())
  9990. return nullptr;
  9991. ValExpr = Val.get();
  9992. OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
  9993. CaptureRegion =
  9994. getOpenMPCaptureRegionForClause(DKind, OMPC_if, NameModifier);
  9995. if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
  9996. ValExpr = MakeFullExpr(ValExpr).get();
  9997. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  9998. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  9999. HelperValStmt = buildPreInits(Context, Captures);
  10000. }
  10001. }
  10002. return new (Context)
  10003. OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
  10004. LParenLoc, NameModifierLoc, ColonLoc, EndLoc);
  10005. }
  10006. OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
  10007. SourceLocation StartLoc,
  10008. SourceLocation LParenLoc,
  10009. SourceLocation EndLoc) {
  10010. Expr *ValExpr = Condition;
  10011. if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
  10012. !Condition->isInstantiationDependent() &&
  10013. !Condition->containsUnexpandedParameterPack()) {
  10014. ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
  10015. if (Val.isInvalid())
  10016. return nullptr;
  10017. ValExpr = MakeFullExpr(Val.get()).get();
  10018. }
  10019. return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
  10020. }
  10021. ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
  10022. Expr *Op) {
  10023. if (!Op)
  10024. return ExprError();
  10025. class IntConvertDiagnoser : public ICEConvertDiagnoser {
  10026. public:
  10027. IntConvertDiagnoser()
  10028. : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
  10029. SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
  10030. QualType T) override {
  10031. return S.Diag(Loc, diag::err_omp_not_integral) << T;
  10032. }
  10033. SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
  10034. QualType T) override {
  10035. return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
  10036. }
  10037. SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
  10038. QualType T,
  10039. QualType ConvTy) override {
  10040. return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
  10041. }
  10042. SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
  10043. QualType ConvTy) override {
  10044. return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
  10045. << ConvTy->isEnumeralType() << ConvTy;
  10046. }
  10047. SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
  10048. QualType T) override {
  10049. return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
  10050. }
  10051. SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
  10052. QualType ConvTy) override {
  10053. return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
  10054. << ConvTy->isEnumeralType() << ConvTy;
  10055. }
  10056. SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
  10057. QualType) override {
  10058. llvm_unreachable("conversion functions are permitted");
  10059. }
  10060. } ConvertDiagnoser;
  10061. return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
  10062. }
  10063. static bool isNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef,
  10064. OpenMPClauseKind CKind,
  10065. bool StrictlyPositive) {
  10066. if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
  10067. !ValExpr->isInstantiationDependent()) {
  10068. SourceLocation Loc = ValExpr->getExprLoc();
  10069. ExprResult Value =
  10070. SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
  10071. if (Value.isInvalid())
  10072. return false;
  10073. ValExpr = Value.get();
  10074. // The expression must evaluate to a non-negative integer value.
  10075. llvm::APSInt Result;
  10076. if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
  10077. Result.isSigned() &&
  10078. !((!StrictlyPositive && Result.isNonNegative()) ||
  10079. (StrictlyPositive && Result.isStrictlyPositive()))) {
  10080. SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
  10081. << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
  10082. << ValExpr->getSourceRange();
  10083. return false;
  10084. }
  10085. }
  10086. return true;
  10087. }
  10088. OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
  10089. SourceLocation StartLoc,
  10090. SourceLocation LParenLoc,
  10091. SourceLocation EndLoc) {
  10092. Expr *ValExpr = NumThreads;
  10093. Stmt *HelperValStmt = nullptr;
  10094. // OpenMP [2.5, Restrictions]
  10095. // The num_threads expression must evaluate to a positive integer value.
  10096. if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
  10097. /*StrictlyPositive=*/true))
  10098. return nullptr;
  10099. OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
  10100. OpenMPDirectiveKind CaptureRegion =
  10101. getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads);
  10102. if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
  10103. ValExpr = MakeFullExpr(ValExpr).get();
  10104. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  10105. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  10106. HelperValStmt = buildPreInits(Context, Captures);
  10107. }
  10108. return new (Context) OMPNumThreadsClause(
  10109. ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
  10110. }
  10111. ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
  10112. OpenMPClauseKind CKind,
  10113. bool StrictlyPositive) {
  10114. if (!E)
  10115. return ExprError();
  10116. if (E->isValueDependent() || E->isTypeDependent() ||
  10117. E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
  10118. return E;
  10119. llvm::APSInt Result;
  10120. ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
  10121. if (ICE.isInvalid())
  10122. return ExprError();
  10123. if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
  10124. (!StrictlyPositive && !Result.isNonNegative())) {
  10125. Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
  10126. << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
  10127. << E->getSourceRange();
  10128. return ExprError();
  10129. }
  10130. if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
  10131. Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
  10132. << E->getSourceRange();
  10133. return ExprError();
  10134. }
  10135. if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
  10136. DSAStack->setAssociatedLoops(Result.getExtValue());
  10137. else if (CKind == OMPC_ordered)
  10138. DSAStack->setAssociatedLoops(Result.getExtValue());
  10139. return ICE;
  10140. }
  10141. OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
  10142. SourceLocation LParenLoc,
  10143. SourceLocation EndLoc) {
  10144. // OpenMP [2.8.1, simd construct, Description]
  10145. // The parameter of the safelen clause must be a constant
  10146. // positive integer expression.
  10147. ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
  10148. if (Safelen.isInvalid())
  10149. return nullptr;
  10150. return new (Context)
  10151. OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
  10152. }
  10153. OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
  10154. SourceLocation LParenLoc,
  10155. SourceLocation EndLoc) {
  10156. // OpenMP [2.8.1, simd construct, Description]
  10157. // The parameter of the simdlen clause must be a constant
  10158. // positive integer expression.
  10159. ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
  10160. if (Simdlen.isInvalid())
  10161. return nullptr;
  10162. return new (Context)
  10163. OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
  10164. }
  10165. /// Tries to find omp_allocator_handle_t type.
  10166. static bool findOMPAllocatorHandleT(Sema &S, SourceLocation Loc,
  10167. DSAStackTy *Stack) {
  10168. QualType OMPAllocatorHandleT = Stack->getOMPAllocatorHandleT();
  10169. if (!OMPAllocatorHandleT.isNull())
  10170. return true;
  10171. // Build the predefined allocator expressions.
  10172. bool ErrorFound = false;
  10173. for (int I = OMPAllocateDeclAttr::OMPDefaultMemAlloc;
  10174. I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) {
  10175. auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I);
  10176. StringRef Allocator =
  10177. OMPAllocateDeclAttr::ConvertAllocatorTypeTyToStr(AllocatorKind);
  10178. DeclarationName AllocatorName = &S.getASTContext().Idents.get(Allocator);
  10179. auto *VD = dyn_cast_or_null<ValueDecl>(
  10180. S.LookupSingleName(S.TUScope, AllocatorName, Loc, Sema::LookupAnyName));
  10181. if (!VD) {
  10182. ErrorFound = true;
  10183. break;
  10184. }
  10185. QualType AllocatorType =
  10186. VD->getType().getNonLValueExprType(S.getASTContext());
  10187. ExprResult Res = S.BuildDeclRefExpr(VD, AllocatorType, VK_LValue, Loc);
  10188. if (!Res.isUsable()) {
  10189. ErrorFound = true;
  10190. break;
  10191. }
  10192. if (OMPAllocatorHandleT.isNull())
  10193. OMPAllocatorHandleT = AllocatorType;
  10194. if (!S.getASTContext().hasSameType(OMPAllocatorHandleT, AllocatorType)) {
  10195. ErrorFound = true;
  10196. break;
  10197. }
  10198. Stack->setAllocator(AllocatorKind, Res.get());
  10199. }
  10200. if (ErrorFound) {
  10201. S.Diag(Loc, diag::err_implied_omp_allocator_handle_t_not_found);
  10202. return false;
  10203. }
  10204. OMPAllocatorHandleT.addConst();
  10205. Stack->setOMPAllocatorHandleT(OMPAllocatorHandleT);
  10206. return true;
  10207. }
  10208. OMPClause *Sema::ActOnOpenMPAllocatorClause(Expr *A, SourceLocation StartLoc,
  10209. SourceLocation LParenLoc,
  10210. SourceLocation EndLoc) {
  10211. // OpenMP [2.11.3, allocate Directive, Description]
  10212. // allocator is an expression of omp_allocator_handle_t type.
  10213. if (!findOMPAllocatorHandleT(*this, A->getExprLoc(), DSAStack))
  10214. return nullptr;
  10215. ExprResult Allocator = DefaultLvalueConversion(A);
  10216. if (Allocator.isInvalid())
  10217. return nullptr;
  10218. Allocator = PerformImplicitConversion(Allocator.get(),
  10219. DSAStack->getOMPAllocatorHandleT(),
  10220. Sema::AA_Initializing,
  10221. /*AllowExplicit=*/true);
  10222. if (Allocator.isInvalid())
  10223. return nullptr;
  10224. return new (Context)
  10225. OMPAllocatorClause(Allocator.get(), StartLoc, LParenLoc, EndLoc);
  10226. }
  10227. OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
  10228. SourceLocation StartLoc,
  10229. SourceLocation LParenLoc,
  10230. SourceLocation EndLoc) {
  10231. // OpenMP [2.7.1, loop construct, Description]
  10232. // OpenMP [2.8.1, simd construct, Description]
  10233. // OpenMP [2.9.6, distribute construct, Description]
  10234. // The parameter of the collapse clause must be a constant
  10235. // positive integer expression.
  10236. ExprResult NumForLoopsResult =
  10237. VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
  10238. if (NumForLoopsResult.isInvalid())
  10239. return nullptr;
  10240. return new (Context)
  10241. OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
  10242. }
  10243. OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
  10244. SourceLocation EndLoc,
  10245. SourceLocation LParenLoc,
  10246. Expr *NumForLoops) {
  10247. // OpenMP [2.7.1, loop construct, Description]
  10248. // OpenMP [2.8.1, simd construct, Description]
  10249. // OpenMP [2.9.6, distribute construct, Description]
  10250. // The parameter of the ordered clause must be a constant
  10251. // positive integer expression if any.
  10252. if (NumForLoops && LParenLoc.isValid()) {
  10253. ExprResult NumForLoopsResult =
  10254. VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
  10255. if (NumForLoopsResult.isInvalid())
  10256. return nullptr;
  10257. NumForLoops = NumForLoopsResult.get();
  10258. } else {
  10259. NumForLoops = nullptr;
  10260. }
  10261. auto *Clause = OMPOrderedClause::Create(
  10262. Context, NumForLoops, NumForLoops ? DSAStack->getAssociatedLoops() : 0,
  10263. StartLoc, LParenLoc, EndLoc);
  10264. DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops, Clause);
  10265. return Clause;
  10266. }
  10267. OMPClause *Sema::ActOnOpenMPSimpleClause(
  10268. OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
  10269. SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
  10270. OMPClause *Res = nullptr;
  10271. switch (Kind) {
  10272. case OMPC_default:
  10273. Res =
  10274. ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
  10275. ArgumentLoc, StartLoc, LParenLoc, EndLoc);
  10276. break;
  10277. case OMPC_proc_bind:
  10278. Res = ActOnOpenMPProcBindClause(
  10279. static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
  10280. LParenLoc, EndLoc);
  10281. break;
  10282. case OMPC_atomic_default_mem_order:
  10283. Res = ActOnOpenMPAtomicDefaultMemOrderClause(
  10284. static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Argument),
  10285. ArgumentLoc, StartLoc, LParenLoc, EndLoc);
  10286. break;
  10287. case OMPC_if:
  10288. case OMPC_final:
  10289. case OMPC_num_threads:
  10290. case OMPC_safelen:
  10291. case OMPC_simdlen:
  10292. case OMPC_allocator:
  10293. case OMPC_collapse:
  10294. case OMPC_schedule:
  10295. case OMPC_private:
  10296. case OMPC_firstprivate:
  10297. case OMPC_lastprivate:
  10298. case OMPC_shared:
  10299. case OMPC_reduction:
  10300. case OMPC_task_reduction:
  10301. case OMPC_in_reduction:
  10302. case OMPC_linear:
  10303. case OMPC_aligned:
  10304. case OMPC_copyin:
  10305. case OMPC_copyprivate:
  10306. case OMPC_ordered:
  10307. case OMPC_nowait:
  10308. case OMPC_untied:
  10309. case OMPC_mergeable:
  10310. case OMPC_threadprivate:
  10311. case OMPC_allocate:
  10312. case OMPC_flush:
  10313. case OMPC_read:
  10314. case OMPC_write:
  10315. case OMPC_update:
  10316. case OMPC_capture:
  10317. case OMPC_seq_cst:
  10318. case OMPC_depend:
  10319. case OMPC_device:
  10320. case OMPC_threads:
  10321. case OMPC_simd:
  10322. case OMPC_map:
  10323. case OMPC_num_teams:
  10324. case OMPC_thread_limit:
  10325. case OMPC_priority:
  10326. case OMPC_grainsize:
  10327. case OMPC_nogroup:
  10328. case OMPC_num_tasks:
  10329. case OMPC_hint:
  10330. case OMPC_dist_schedule:
  10331. case OMPC_defaultmap:
  10332. case OMPC_unknown:
  10333. case OMPC_uniform:
  10334. case OMPC_to:
  10335. case OMPC_from:
  10336. case OMPC_use_device_ptr:
  10337. case OMPC_is_device_ptr:
  10338. case OMPC_unified_address:
  10339. case OMPC_unified_shared_memory:
  10340. case OMPC_reverse_offload:
  10341. case OMPC_dynamic_allocators:
  10342. case OMPC_device_type:
  10343. case OMPC_match:
  10344. llvm_unreachable("Clause is not allowed.");
  10345. }
  10346. return Res;
  10347. }
  10348. static std::string
  10349. getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
  10350. ArrayRef<unsigned> Exclude = llvm::None) {
  10351. SmallString<256> Buffer;
  10352. llvm::raw_svector_ostream Out(Buffer);
  10353. unsigned Bound = Last >= 2 ? Last - 2 : 0;
  10354. unsigned Skipped = Exclude.size();
  10355. auto S = Exclude.begin(), E = Exclude.end();
  10356. for (unsigned I = First; I < Last; ++I) {
  10357. if (std::find(S, E, I) != E) {
  10358. --Skipped;
  10359. continue;
  10360. }
  10361. Out << "'" << getOpenMPSimpleClauseTypeName(K, I) << "'";
  10362. if (I == Bound - Skipped)
  10363. Out << " or ";
  10364. else if (I != Bound + 1 - Skipped)
  10365. Out << ", ";
  10366. }
  10367. return Out.str();
  10368. }
  10369. OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
  10370. SourceLocation KindKwLoc,
  10371. SourceLocation StartLoc,
  10372. SourceLocation LParenLoc,
  10373. SourceLocation EndLoc) {
  10374. if (Kind == OMPC_DEFAULT_unknown) {
  10375. static_assert(OMPC_DEFAULT_unknown > 0,
  10376. "OMPC_DEFAULT_unknown not greater than 0");
  10377. Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
  10378. << getListOfPossibleValues(OMPC_default, /*First=*/0,
  10379. /*Last=*/OMPC_DEFAULT_unknown)
  10380. << getOpenMPClauseName(OMPC_default);
  10381. return nullptr;
  10382. }
  10383. switch (Kind) {
  10384. case OMPC_DEFAULT_none:
  10385. DSAStack->setDefaultDSANone(KindKwLoc);
  10386. break;
  10387. case OMPC_DEFAULT_shared:
  10388. DSAStack->setDefaultDSAShared(KindKwLoc);
  10389. break;
  10390. case OMPC_DEFAULT_unknown:
  10391. llvm_unreachable("Clause kind is not allowed.");
  10392. break;
  10393. }
  10394. return new (Context)
  10395. OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
  10396. }
  10397. OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
  10398. SourceLocation KindKwLoc,
  10399. SourceLocation StartLoc,
  10400. SourceLocation LParenLoc,
  10401. SourceLocation EndLoc) {
  10402. if (Kind == OMPC_PROC_BIND_unknown) {
  10403. Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
  10404. << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0,
  10405. /*Last=*/OMPC_PROC_BIND_unknown)
  10406. << getOpenMPClauseName(OMPC_proc_bind);
  10407. return nullptr;
  10408. }
  10409. return new (Context)
  10410. OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
  10411. }
  10412. OMPClause *Sema::ActOnOpenMPAtomicDefaultMemOrderClause(
  10413. OpenMPAtomicDefaultMemOrderClauseKind Kind, SourceLocation KindKwLoc,
  10414. SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
  10415. if (Kind == OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown) {
  10416. Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
  10417. << getListOfPossibleValues(
  10418. OMPC_atomic_default_mem_order, /*First=*/0,
  10419. /*Last=*/OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown)
  10420. << getOpenMPClauseName(OMPC_atomic_default_mem_order);
  10421. return nullptr;
  10422. }
  10423. return new (Context) OMPAtomicDefaultMemOrderClause(Kind, KindKwLoc, StartLoc,
  10424. LParenLoc, EndLoc);
  10425. }
  10426. OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
  10427. OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
  10428. SourceLocation StartLoc, SourceLocation LParenLoc,
  10429. ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
  10430. SourceLocation EndLoc) {
  10431. OMPClause *Res = nullptr;
  10432. switch (Kind) {
  10433. case OMPC_schedule:
  10434. enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
  10435. assert(Argument.size() == NumberOfElements &&
  10436. ArgumentLoc.size() == NumberOfElements);
  10437. Res = ActOnOpenMPScheduleClause(
  10438. static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
  10439. static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
  10440. static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
  10441. StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
  10442. ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
  10443. break;
  10444. case OMPC_if:
  10445. assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
  10446. Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
  10447. Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
  10448. DelimLoc, EndLoc);
  10449. break;
  10450. case OMPC_dist_schedule:
  10451. Res = ActOnOpenMPDistScheduleClause(
  10452. static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
  10453. StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
  10454. break;
  10455. case OMPC_defaultmap:
  10456. enum { Modifier, DefaultmapKind };
  10457. Res = ActOnOpenMPDefaultmapClause(
  10458. static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
  10459. static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
  10460. StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
  10461. EndLoc);
  10462. break;
  10463. case OMPC_final:
  10464. case OMPC_num_threads:
  10465. case OMPC_safelen:
  10466. case OMPC_simdlen:
  10467. case OMPC_allocator:
  10468. case OMPC_collapse:
  10469. case OMPC_default:
  10470. case OMPC_proc_bind:
  10471. case OMPC_private:
  10472. case OMPC_firstprivate:
  10473. case OMPC_lastprivate:
  10474. case OMPC_shared:
  10475. case OMPC_reduction:
  10476. case OMPC_task_reduction:
  10477. case OMPC_in_reduction:
  10478. case OMPC_linear:
  10479. case OMPC_aligned:
  10480. case OMPC_copyin:
  10481. case OMPC_copyprivate:
  10482. case OMPC_ordered:
  10483. case OMPC_nowait:
  10484. case OMPC_untied:
  10485. case OMPC_mergeable:
  10486. case OMPC_threadprivate:
  10487. case OMPC_allocate:
  10488. case OMPC_flush:
  10489. case OMPC_read:
  10490. case OMPC_write:
  10491. case OMPC_update:
  10492. case OMPC_capture:
  10493. case OMPC_seq_cst:
  10494. case OMPC_depend:
  10495. case OMPC_device:
  10496. case OMPC_threads:
  10497. case OMPC_simd:
  10498. case OMPC_map:
  10499. case OMPC_num_teams:
  10500. case OMPC_thread_limit:
  10501. case OMPC_priority:
  10502. case OMPC_grainsize:
  10503. case OMPC_nogroup:
  10504. case OMPC_num_tasks:
  10505. case OMPC_hint:
  10506. case OMPC_unknown:
  10507. case OMPC_uniform:
  10508. case OMPC_to:
  10509. case OMPC_from:
  10510. case OMPC_use_device_ptr:
  10511. case OMPC_is_device_ptr:
  10512. case OMPC_unified_address:
  10513. case OMPC_unified_shared_memory:
  10514. case OMPC_reverse_offload:
  10515. case OMPC_dynamic_allocators:
  10516. case OMPC_atomic_default_mem_order:
  10517. case OMPC_device_type:
  10518. case OMPC_match:
  10519. llvm_unreachable("Clause is not allowed.");
  10520. }
  10521. return Res;
  10522. }
  10523. static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
  10524. OpenMPScheduleClauseModifier M2,
  10525. SourceLocation M1Loc, SourceLocation M2Loc) {
  10526. if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
  10527. SmallVector<unsigned, 2> Excluded;
  10528. if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
  10529. Excluded.push_back(M2);
  10530. if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
  10531. Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
  10532. if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
  10533. Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
  10534. S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
  10535. << getListOfPossibleValues(OMPC_schedule,
  10536. /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
  10537. /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
  10538. Excluded)
  10539. << getOpenMPClauseName(OMPC_schedule);
  10540. return true;
  10541. }
  10542. return false;
  10543. }
  10544. OMPClause *Sema::ActOnOpenMPScheduleClause(
  10545. OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
  10546. OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
  10547. SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
  10548. SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
  10549. if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
  10550. checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
  10551. return nullptr;
  10552. // OpenMP, 2.7.1, Loop Construct, Restrictions
  10553. // Either the monotonic modifier or the nonmonotonic modifier can be specified
  10554. // but not both.
  10555. if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
  10556. (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
  10557. M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
  10558. (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
  10559. M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
  10560. Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
  10561. << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
  10562. << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
  10563. return nullptr;
  10564. }
  10565. if (Kind == OMPC_SCHEDULE_unknown) {
  10566. std::string Values;
  10567. if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
  10568. unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
  10569. Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
  10570. /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
  10571. Exclude);
  10572. } else {
  10573. Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
  10574. /*Last=*/OMPC_SCHEDULE_unknown);
  10575. }
  10576. Diag(KindLoc, diag::err_omp_unexpected_clause_value)
  10577. << Values << getOpenMPClauseName(OMPC_schedule);
  10578. return nullptr;
  10579. }
  10580. // OpenMP, 2.7.1, Loop Construct, Restrictions
  10581. // The nonmonotonic modifier can only be specified with schedule(dynamic) or
  10582. // schedule(guided).
  10583. if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
  10584. M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
  10585. Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
  10586. Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
  10587. diag::err_omp_schedule_nonmonotonic_static);
  10588. return nullptr;
  10589. }
  10590. Expr *ValExpr = ChunkSize;
  10591. Stmt *HelperValStmt = nullptr;
  10592. if (ChunkSize) {
  10593. if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
  10594. !ChunkSize->isInstantiationDependent() &&
  10595. !ChunkSize->containsUnexpandedParameterPack()) {
  10596. SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
  10597. ExprResult Val =
  10598. PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
  10599. if (Val.isInvalid())
  10600. return nullptr;
  10601. ValExpr = Val.get();
  10602. // OpenMP [2.7.1, Restrictions]
  10603. // chunk_size must be a loop invariant integer expression with a positive
  10604. // value.
  10605. llvm::APSInt Result;
  10606. if (ValExpr->isIntegerConstantExpr(Result, Context)) {
  10607. if (Result.isSigned() && !Result.isStrictlyPositive()) {
  10608. Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
  10609. << "schedule" << 1 << ChunkSize->getSourceRange();
  10610. return nullptr;
  10611. }
  10612. } else if (getOpenMPCaptureRegionForClause(
  10613. DSAStack->getCurrentDirective(), OMPC_schedule) !=
  10614. OMPD_unknown &&
  10615. !CurContext->isDependentContext()) {
  10616. ValExpr = MakeFullExpr(ValExpr).get();
  10617. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  10618. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  10619. HelperValStmt = buildPreInits(Context, Captures);
  10620. }
  10621. }
  10622. }
  10623. return new (Context)
  10624. OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
  10625. ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
  10626. }
  10627. OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
  10628. SourceLocation StartLoc,
  10629. SourceLocation EndLoc) {
  10630. OMPClause *Res = nullptr;
  10631. switch (Kind) {
  10632. case OMPC_ordered:
  10633. Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
  10634. break;
  10635. case OMPC_nowait:
  10636. Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
  10637. break;
  10638. case OMPC_untied:
  10639. Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
  10640. break;
  10641. case OMPC_mergeable:
  10642. Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
  10643. break;
  10644. case OMPC_read:
  10645. Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
  10646. break;
  10647. case OMPC_write:
  10648. Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
  10649. break;
  10650. case OMPC_update:
  10651. Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
  10652. break;
  10653. case OMPC_capture:
  10654. Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
  10655. break;
  10656. case OMPC_seq_cst:
  10657. Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
  10658. break;
  10659. case OMPC_threads:
  10660. Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
  10661. break;
  10662. case OMPC_simd:
  10663. Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
  10664. break;
  10665. case OMPC_nogroup:
  10666. Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
  10667. break;
  10668. case OMPC_unified_address:
  10669. Res = ActOnOpenMPUnifiedAddressClause(StartLoc, EndLoc);
  10670. break;
  10671. case OMPC_unified_shared_memory:
  10672. Res = ActOnOpenMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
  10673. break;
  10674. case OMPC_reverse_offload:
  10675. Res = ActOnOpenMPReverseOffloadClause(StartLoc, EndLoc);
  10676. break;
  10677. case OMPC_dynamic_allocators:
  10678. Res = ActOnOpenMPDynamicAllocatorsClause(StartLoc, EndLoc);
  10679. break;
  10680. case OMPC_if:
  10681. case OMPC_final:
  10682. case OMPC_num_threads:
  10683. case OMPC_safelen:
  10684. case OMPC_simdlen:
  10685. case OMPC_allocator:
  10686. case OMPC_collapse:
  10687. case OMPC_schedule:
  10688. case OMPC_private:
  10689. case OMPC_firstprivate:
  10690. case OMPC_lastprivate:
  10691. case OMPC_shared:
  10692. case OMPC_reduction:
  10693. case OMPC_task_reduction:
  10694. case OMPC_in_reduction:
  10695. case OMPC_linear:
  10696. case OMPC_aligned:
  10697. case OMPC_copyin:
  10698. case OMPC_copyprivate:
  10699. case OMPC_default:
  10700. case OMPC_proc_bind:
  10701. case OMPC_threadprivate:
  10702. case OMPC_allocate:
  10703. case OMPC_flush:
  10704. case OMPC_depend:
  10705. case OMPC_device:
  10706. case OMPC_map:
  10707. case OMPC_num_teams:
  10708. case OMPC_thread_limit:
  10709. case OMPC_priority:
  10710. case OMPC_grainsize:
  10711. case OMPC_num_tasks:
  10712. case OMPC_hint:
  10713. case OMPC_dist_schedule:
  10714. case OMPC_defaultmap:
  10715. case OMPC_unknown:
  10716. case OMPC_uniform:
  10717. case OMPC_to:
  10718. case OMPC_from:
  10719. case OMPC_use_device_ptr:
  10720. case OMPC_is_device_ptr:
  10721. case OMPC_atomic_default_mem_order:
  10722. case OMPC_device_type:
  10723. case OMPC_match:
  10724. llvm_unreachable("Clause is not allowed.");
  10725. }
  10726. return Res;
  10727. }
  10728. OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
  10729. SourceLocation EndLoc) {
  10730. DSAStack->setNowaitRegion();
  10731. return new (Context) OMPNowaitClause(StartLoc, EndLoc);
  10732. }
  10733. OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
  10734. SourceLocation EndLoc) {
  10735. return new (Context) OMPUntiedClause(StartLoc, EndLoc);
  10736. }
  10737. OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
  10738. SourceLocation EndLoc) {
  10739. return new (Context) OMPMergeableClause(StartLoc, EndLoc);
  10740. }
  10741. OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
  10742. SourceLocation EndLoc) {
  10743. return new (Context) OMPReadClause(StartLoc, EndLoc);
  10744. }
  10745. OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
  10746. SourceLocation EndLoc) {
  10747. return new (Context) OMPWriteClause(StartLoc, EndLoc);
  10748. }
  10749. OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
  10750. SourceLocation EndLoc) {
  10751. return new (Context) OMPUpdateClause(StartLoc, EndLoc);
  10752. }
  10753. OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
  10754. SourceLocation EndLoc) {
  10755. return new (Context) OMPCaptureClause(StartLoc, EndLoc);
  10756. }
  10757. OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
  10758. SourceLocation EndLoc) {
  10759. return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
  10760. }
  10761. OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
  10762. SourceLocation EndLoc) {
  10763. return new (Context) OMPThreadsClause(StartLoc, EndLoc);
  10764. }
  10765. OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
  10766. SourceLocation EndLoc) {
  10767. return new (Context) OMPSIMDClause(StartLoc, EndLoc);
  10768. }
  10769. OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
  10770. SourceLocation EndLoc) {
  10771. return new (Context) OMPNogroupClause(StartLoc, EndLoc);
  10772. }
  10773. OMPClause *Sema::ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc,
  10774. SourceLocation EndLoc) {
  10775. return new (Context) OMPUnifiedAddressClause(StartLoc, EndLoc);
  10776. }
  10777. OMPClause *Sema::ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc,
  10778. SourceLocation EndLoc) {
  10779. return new (Context) OMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
  10780. }
  10781. OMPClause *Sema::ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc,
  10782. SourceLocation EndLoc) {
  10783. return new (Context) OMPReverseOffloadClause(StartLoc, EndLoc);
  10784. }
  10785. OMPClause *Sema::ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc,
  10786. SourceLocation EndLoc) {
  10787. return new (Context) OMPDynamicAllocatorsClause(StartLoc, EndLoc);
  10788. }
  10789. OMPClause *Sema::ActOnOpenMPVarListClause(
  10790. OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
  10791. const OMPVarListLocTy &Locs, SourceLocation ColonLoc,
  10792. CXXScopeSpec &ReductionOrMapperIdScopeSpec,
  10793. DeclarationNameInfo &ReductionOrMapperId, OpenMPDependClauseKind DepKind,
  10794. OpenMPLinearClauseKind LinKind,
  10795. ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
  10796. ArrayRef<SourceLocation> MapTypeModifiersLoc, OpenMPMapClauseKind MapType,
  10797. bool IsMapTypeImplicit, SourceLocation DepLinMapLoc) {
  10798. SourceLocation StartLoc = Locs.StartLoc;
  10799. SourceLocation LParenLoc = Locs.LParenLoc;
  10800. SourceLocation EndLoc = Locs.EndLoc;
  10801. OMPClause *Res = nullptr;
  10802. switch (Kind) {
  10803. case OMPC_private:
  10804. Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
  10805. break;
  10806. case OMPC_firstprivate:
  10807. Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
  10808. break;
  10809. case OMPC_lastprivate:
  10810. Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
  10811. break;
  10812. case OMPC_shared:
  10813. Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
  10814. break;
  10815. case OMPC_reduction:
  10816. Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
  10817. EndLoc, ReductionOrMapperIdScopeSpec,
  10818. ReductionOrMapperId);
  10819. break;
  10820. case OMPC_task_reduction:
  10821. Res = ActOnOpenMPTaskReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
  10822. EndLoc, ReductionOrMapperIdScopeSpec,
  10823. ReductionOrMapperId);
  10824. break;
  10825. case OMPC_in_reduction:
  10826. Res = ActOnOpenMPInReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
  10827. EndLoc, ReductionOrMapperIdScopeSpec,
  10828. ReductionOrMapperId);
  10829. break;
  10830. case OMPC_linear:
  10831. Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
  10832. LinKind, DepLinMapLoc, ColonLoc, EndLoc);
  10833. break;
  10834. case OMPC_aligned:
  10835. Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
  10836. ColonLoc, EndLoc);
  10837. break;
  10838. case OMPC_copyin:
  10839. Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
  10840. break;
  10841. case OMPC_copyprivate:
  10842. Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
  10843. break;
  10844. case OMPC_flush:
  10845. Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
  10846. break;
  10847. case OMPC_depend:
  10848. Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList,
  10849. StartLoc, LParenLoc, EndLoc);
  10850. break;
  10851. case OMPC_map:
  10852. Res = ActOnOpenMPMapClause(MapTypeModifiers, MapTypeModifiersLoc,
  10853. ReductionOrMapperIdScopeSpec,
  10854. ReductionOrMapperId, MapType, IsMapTypeImplicit,
  10855. DepLinMapLoc, ColonLoc, VarList, Locs);
  10856. break;
  10857. case OMPC_to:
  10858. Res = ActOnOpenMPToClause(VarList, ReductionOrMapperIdScopeSpec,
  10859. ReductionOrMapperId, Locs);
  10860. break;
  10861. case OMPC_from:
  10862. Res = ActOnOpenMPFromClause(VarList, ReductionOrMapperIdScopeSpec,
  10863. ReductionOrMapperId, Locs);
  10864. break;
  10865. case OMPC_use_device_ptr:
  10866. Res = ActOnOpenMPUseDevicePtrClause(VarList, Locs);
  10867. break;
  10868. case OMPC_is_device_ptr:
  10869. Res = ActOnOpenMPIsDevicePtrClause(VarList, Locs);
  10870. break;
  10871. case OMPC_allocate:
  10872. Res = ActOnOpenMPAllocateClause(TailExpr, VarList, StartLoc, LParenLoc,
  10873. ColonLoc, EndLoc);
  10874. break;
  10875. case OMPC_if:
  10876. case OMPC_final:
  10877. case OMPC_num_threads:
  10878. case OMPC_safelen:
  10879. case OMPC_simdlen:
  10880. case OMPC_allocator:
  10881. case OMPC_collapse:
  10882. case OMPC_default:
  10883. case OMPC_proc_bind:
  10884. case OMPC_schedule:
  10885. case OMPC_ordered:
  10886. case OMPC_nowait:
  10887. case OMPC_untied:
  10888. case OMPC_mergeable:
  10889. case OMPC_threadprivate:
  10890. case OMPC_read:
  10891. case OMPC_write:
  10892. case OMPC_update:
  10893. case OMPC_capture:
  10894. case OMPC_seq_cst:
  10895. case OMPC_device:
  10896. case OMPC_threads:
  10897. case OMPC_simd:
  10898. case OMPC_num_teams:
  10899. case OMPC_thread_limit:
  10900. case OMPC_priority:
  10901. case OMPC_grainsize:
  10902. case OMPC_nogroup:
  10903. case OMPC_num_tasks:
  10904. case OMPC_hint:
  10905. case OMPC_dist_schedule:
  10906. case OMPC_defaultmap:
  10907. case OMPC_unknown:
  10908. case OMPC_uniform:
  10909. case OMPC_unified_address:
  10910. case OMPC_unified_shared_memory:
  10911. case OMPC_reverse_offload:
  10912. case OMPC_dynamic_allocators:
  10913. case OMPC_atomic_default_mem_order:
  10914. case OMPC_device_type:
  10915. case OMPC_match:
  10916. llvm_unreachable("Clause is not allowed.");
  10917. }
  10918. return Res;
  10919. }
  10920. ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
  10921. ExprObjectKind OK, SourceLocation Loc) {
  10922. ExprResult Res = BuildDeclRefExpr(
  10923. Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
  10924. if (!Res.isUsable())
  10925. return ExprError();
  10926. if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
  10927. Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
  10928. if (!Res.isUsable())
  10929. return ExprError();
  10930. }
  10931. if (VK != VK_LValue && Res.get()->isGLValue()) {
  10932. Res = DefaultLvalueConversion(Res.get());
  10933. if (!Res.isUsable())
  10934. return ExprError();
  10935. }
  10936. return Res;
  10937. }
  10938. OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
  10939. SourceLocation StartLoc,
  10940. SourceLocation LParenLoc,
  10941. SourceLocation EndLoc) {
  10942. SmallVector<Expr *, 8> Vars;
  10943. SmallVector<Expr *, 8> PrivateCopies;
  10944. for (Expr *RefExpr : VarList) {
  10945. assert(RefExpr && "NULL expr in OpenMP private clause.");
  10946. SourceLocation ELoc;
  10947. SourceRange ERange;
  10948. Expr *SimpleRefExpr = RefExpr;
  10949. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  10950. if (Res.second) {
  10951. // It will be analyzed later.
  10952. Vars.push_back(RefExpr);
  10953. PrivateCopies.push_back(nullptr);
  10954. }
  10955. ValueDecl *D = Res.first;
  10956. if (!D)
  10957. continue;
  10958. QualType Type = D->getType();
  10959. auto *VD = dyn_cast<VarDecl>(D);
  10960. // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
  10961. // A variable that appears in a private clause must not have an incomplete
  10962. // type or a reference type.
  10963. if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
  10964. continue;
  10965. Type = Type.getNonReferenceType();
  10966. // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
  10967. // A variable that is privatized must not have a const-qualified type
  10968. // unless it is of class type with a mutable member. This restriction does
  10969. // not apply to the firstprivate clause.
  10970. //
  10971. // OpenMP 3.1 [2.9.3.3, private clause, Restrictions]
  10972. // A variable that appears in a private clause must not have a
  10973. // const-qualified type unless it is of class type with a mutable member.
  10974. if (rejectConstNotMutableType(*this, D, Type, OMPC_private, ELoc))
  10975. continue;
  10976. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  10977. // in a Construct]
  10978. // Variables with the predetermined data-sharing attributes may not be
  10979. // listed in data-sharing attributes clauses, except for the cases
  10980. // listed below. For these exceptions only, listing a predetermined
  10981. // variable in a data-sharing attribute clause is allowed and overrides
  10982. // the variable's predetermined data-sharing attributes.
  10983. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
  10984. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
  10985. Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
  10986. << getOpenMPClauseName(OMPC_private);
  10987. reportOriginalDsa(*this, DSAStack, D, DVar);
  10988. continue;
  10989. }
  10990. OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
  10991. // Variably modified types are not supported for tasks.
  10992. if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
  10993. isOpenMPTaskingDirective(CurrDir)) {
  10994. Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
  10995. << getOpenMPClauseName(OMPC_private) << Type
  10996. << getOpenMPDirectiveName(CurrDir);
  10997. bool IsDecl =
  10998. !VD ||
  10999. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  11000. Diag(D->getLocation(),
  11001. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  11002. << D;
  11003. continue;
  11004. }
  11005. // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
  11006. // A list item cannot appear in both a map clause and a data-sharing
  11007. // attribute clause on the same construct
  11008. //
  11009. // OpenMP 5.0 [2.19.7.1, Restrictions, p.7]
  11010. // A list item cannot appear in both a map clause and a data-sharing
  11011. // attribute clause on the same construct unless the construct is a
  11012. // combined construct.
  11013. if ((LangOpts.OpenMP <= 45 && isOpenMPTargetExecutionDirective(CurrDir)) ||
  11014. CurrDir == OMPD_target) {
  11015. OpenMPClauseKind ConflictKind;
  11016. if (DSAStack->checkMappableExprComponentListsForDecl(
  11017. VD, /*CurrentRegionOnly=*/true,
  11018. [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
  11019. OpenMPClauseKind WhereFoundClauseKind) -> bool {
  11020. ConflictKind = WhereFoundClauseKind;
  11021. return true;
  11022. })) {
  11023. Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
  11024. << getOpenMPClauseName(OMPC_private)
  11025. << getOpenMPClauseName(ConflictKind)
  11026. << getOpenMPDirectiveName(CurrDir);
  11027. reportOriginalDsa(*this, DSAStack, D, DVar);
  11028. continue;
  11029. }
  11030. }
  11031. // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
  11032. // A variable of class type (or array thereof) that appears in a private
  11033. // clause requires an accessible, unambiguous default constructor for the
  11034. // class type.
  11035. // Generate helper private variable and initialize it with the default
  11036. // value. The address of the original variable is replaced by the address of
  11037. // the new private variable in CodeGen. This new variable is not added to
  11038. // IdResolver, so the code in the OpenMP region uses original variable for
  11039. // proper diagnostics.
  11040. Type = Type.getUnqualifiedType();
  11041. VarDecl *VDPrivate =
  11042. buildVarDecl(*this, ELoc, Type, D->getName(),
  11043. D->hasAttrs() ? &D->getAttrs() : nullptr,
  11044. VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
  11045. ActOnUninitializedDecl(VDPrivate);
  11046. if (VDPrivate->isInvalidDecl())
  11047. continue;
  11048. DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
  11049. *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
  11050. DeclRefExpr *Ref = nullptr;
  11051. if (!VD && !CurContext->isDependentContext())
  11052. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
  11053. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
  11054. Vars.push_back((VD || CurContext->isDependentContext())
  11055. ? RefExpr->IgnoreParens()
  11056. : Ref);
  11057. PrivateCopies.push_back(VDPrivateRefExpr);
  11058. }
  11059. if (Vars.empty())
  11060. return nullptr;
  11061. return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
  11062. PrivateCopies);
  11063. }
  11064. namespace {
  11065. class DiagsUninitializedSeveretyRAII {
  11066. private:
  11067. DiagnosticsEngine &Diags;
  11068. SourceLocation SavedLoc;
  11069. bool IsIgnored = false;
  11070. public:
  11071. DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
  11072. bool IsIgnored)
  11073. : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
  11074. if (!IsIgnored) {
  11075. Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
  11076. /*Map*/ diag::Severity::Ignored, Loc);
  11077. }
  11078. }
  11079. ~DiagsUninitializedSeveretyRAII() {
  11080. if (!IsIgnored)
  11081. Diags.popMappings(SavedLoc);
  11082. }
  11083. };
  11084. }
  11085. OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
  11086. SourceLocation StartLoc,
  11087. SourceLocation LParenLoc,
  11088. SourceLocation EndLoc) {
  11089. SmallVector<Expr *, 8> Vars;
  11090. SmallVector<Expr *, 8> PrivateCopies;
  11091. SmallVector<Expr *, 8> Inits;
  11092. SmallVector<Decl *, 4> ExprCaptures;
  11093. bool IsImplicitClause =
  11094. StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
  11095. SourceLocation ImplicitClauseLoc = DSAStack->getConstructLoc();
  11096. for (Expr *RefExpr : VarList) {
  11097. assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
  11098. SourceLocation ELoc;
  11099. SourceRange ERange;
  11100. Expr *SimpleRefExpr = RefExpr;
  11101. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  11102. if (Res.second) {
  11103. // It will be analyzed later.
  11104. Vars.push_back(RefExpr);
  11105. PrivateCopies.push_back(nullptr);
  11106. Inits.push_back(nullptr);
  11107. }
  11108. ValueDecl *D = Res.first;
  11109. if (!D)
  11110. continue;
  11111. ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
  11112. QualType Type = D->getType();
  11113. auto *VD = dyn_cast<VarDecl>(D);
  11114. // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
  11115. // A variable that appears in a private clause must not have an incomplete
  11116. // type or a reference type.
  11117. if (RequireCompleteType(ELoc, Type,
  11118. diag::err_omp_firstprivate_incomplete_type))
  11119. continue;
  11120. Type = Type.getNonReferenceType();
  11121. // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
  11122. // A variable of class type (or array thereof) that appears in a private
  11123. // clause requires an accessible, unambiguous copy constructor for the
  11124. // class type.
  11125. QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
  11126. // If an implicit firstprivate variable found it was checked already.
  11127. DSAStackTy::DSAVarData TopDVar;
  11128. if (!IsImplicitClause) {
  11129. DSAStackTy::DSAVarData DVar =
  11130. DSAStack->getTopDSA(D, /*FromParent=*/false);
  11131. TopDVar = DVar;
  11132. OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
  11133. bool IsConstant = ElemType.isConstant(Context);
  11134. // OpenMP [2.4.13, Data-sharing Attribute Clauses]
  11135. // A list item that specifies a given variable may not appear in more
  11136. // than one clause on the same directive, except that a variable may be
  11137. // specified in both firstprivate and lastprivate clauses.
  11138. // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
  11139. // A list item may appear in a firstprivate or lastprivate clause but not
  11140. // both.
  11141. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
  11142. (isOpenMPDistributeDirective(CurrDir) ||
  11143. DVar.CKind != OMPC_lastprivate) &&
  11144. DVar.RefExpr) {
  11145. Diag(ELoc, diag::err_omp_wrong_dsa)
  11146. << getOpenMPClauseName(DVar.CKind)
  11147. << getOpenMPClauseName(OMPC_firstprivate);
  11148. reportOriginalDsa(*this, DSAStack, D, DVar);
  11149. continue;
  11150. }
  11151. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  11152. // in a Construct]
  11153. // Variables with the predetermined data-sharing attributes may not be
  11154. // listed in data-sharing attributes clauses, except for the cases
  11155. // listed below. For these exceptions only, listing a predetermined
  11156. // variable in a data-sharing attribute clause is allowed and overrides
  11157. // the variable's predetermined data-sharing attributes.
  11158. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  11159. // in a Construct, C/C++, p.2]
  11160. // Variables with const-qualified type having no mutable member may be
  11161. // listed in a firstprivate clause, even if they are static data members.
  11162. if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
  11163. DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
  11164. Diag(ELoc, diag::err_omp_wrong_dsa)
  11165. << getOpenMPClauseName(DVar.CKind)
  11166. << getOpenMPClauseName(OMPC_firstprivate);
  11167. reportOriginalDsa(*this, DSAStack, D, DVar);
  11168. continue;
  11169. }
  11170. // OpenMP [2.9.3.4, Restrictions, p.2]
  11171. // A list item that is private within a parallel region must not appear
  11172. // in a firstprivate clause on a worksharing construct if any of the
  11173. // worksharing regions arising from the worksharing construct ever bind
  11174. // to any of the parallel regions arising from the parallel construct.
  11175. // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
  11176. // A list item that is private within a teams region must not appear in a
  11177. // firstprivate clause on a distribute construct if any of the distribute
  11178. // regions arising from the distribute construct ever bind to any of the
  11179. // teams regions arising from the teams construct.
  11180. // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
  11181. // A list item that appears in a reduction clause of a teams construct
  11182. // must not appear in a firstprivate clause on a distribute construct if
  11183. // any of the distribute regions arising from the distribute construct
  11184. // ever bind to any of the teams regions arising from the teams construct.
  11185. if ((isOpenMPWorksharingDirective(CurrDir) ||
  11186. isOpenMPDistributeDirective(CurrDir)) &&
  11187. !isOpenMPParallelDirective(CurrDir) &&
  11188. !isOpenMPTeamsDirective(CurrDir)) {
  11189. DVar = DSAStack->getImplicitDSA(D, true);
  11190. if (DVar.CKind != OMPC_shared &&
  11191. (isOpenMPParallelDirective(DVar.DKind) ||
  11192. isOpenMPTeamsDirective(DVar.DKind) ||
  11193. DVar.DKind == OMPD_unknown)) {
  11194. Diag(ELoc, diag::err_omp_required_access)
  11195. << getOpenMPClauseName(OMPC_firstprivate)
  11196. << getOpenMPClauseName(OMPC_shared);
  11197. reportOriginalDsa(*this, DSAStack, D, DVar);
  11198. continue;
  11199. }
  11200. }
  11201. // OpenMP [2.9.3.4, Restrictions, p.3]
  11202. // A list item that appears in a reduction clause of a parallel construct
  11203. // must not appear in a firstprivate clause on a worksharing or task
  11204. // construct if any of the worksharing or task regions arising from the
  11205. // worksharing or task construct ever bind to any of the parallel regions
  11206. // arising from the parallel construct.
  11207. // OpenMP [2.9.3.4, Restrictions, p.4]
  11208. // A list item that appears in a reduction clause in worksharing
  11209. // construct must not appear in a firstprivate clause in a task construct
  11210. // encountered during execution of any of the worksharing regions arising
  11211. // from the worksharing construct.
  11212. if (isOpenMPTaskingDirective(CurrDir)) {
  11213. DVar = DSAStack->hasInnermostDSA(
  11214. D, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
  11215. [](OpenMPDirectiveKind K) {
  11216. return isOpenMPParallelDirective(K) ||
  11217. isOpenMPWorksharingDirective(K) ||
  11218. isOpenMPTeamsDirective(K);
  11219. },
  11220. /*FromParent=*/true);
  11221. if (DVar.CKind == OMPC_reduction &&
  11222. (isOpenMPParallelDirective(DVar.DKind) ||
  11223. isOpenMPWorksharingDirective(DVar.DKind) ||
  11224. isOpenMPTeamsDirective(DVar.DKind))) {
  11225. Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
  11226. << getOpenMPDirectiveName(DVar.DKind);
  11227. reportOriginalDsa(*this, DSAStack, D, DVar);
  11228. continue;
  11229. }
  11230. }
  11231. // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
  11232. // A list item cannot appear in both a map clause and a data-sharing
  11233. // attribute clause on the same construct
  11234. //
  11235. // OpenMP 5.0 [2.19.7.1, Restrictions, p.7]
  11236. // A list item cannot appear in both a map clause and a data-sharing
  11237. // attribute clause on the same construct unless the construct is a
  11238. // combined construct.
  11239. if ((LangOpts.OpenMP <= 45 &&
  11240. isOpenMPTargetExecutionDirective(CurrDir)) ||
  11241. CurrDir == OMPD_target) {
  11242. OpenMPClauseKind ConflictKind;
  11243. if (DSAStack->checkMappableExprComponentListsForDecl(
  11244. VD, /*CurrentRegionOnly=*/true,
  11245. [&ConflictKind](
  11246. OMPClauseMappableExprCommon::MappableExprComponentListRef,
  11247. OpenMPClauseKind WhereFoundClauseKind) {
  11248. ConflictKind = WhereFoundClauseKind;
  11249. return true;
  11250. })) {
  11251. Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
  11252. << getOpenMPClauseName(OMPC_firstprivate)
  11253. << getOpenMPClauseName(ConflictKind)
  11254. << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
  11255. reportOriginalDsa(*this, DSAStack, D, DVar);
  11256. continue;
  11257. }
  11258. }
  11259. }
  11260. // Variably modified types are not supported for tasks.
  11261. if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
  11262. isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
  11263. Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
  11264. << getOpenMPClauseName(OMPC_firstprivate) << Type
  11265. << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
  11266. bool IsDecl =
  11267. !VD ||
  11268. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  11269. Diag(D->getLocation(),
  11270. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  11271. << D;
  11272. continue;
  11273. }
  11274. Type = Type.getUnqualifiedType();
  11275. VarDecl *VDPrivate =
  11276. buildVarDecl(*this, ELoc, Type, D->getName(),
  11277. D->hasAttrs() ? &D->getAttrs() : nullptr,
  11278. VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
  11279. // Generate helper private variable and initialize it with the value of the
  11280. // original variable. The address of the original variable is replaced by
  11281. // the address of the new private variable in the CodeGen. This new variable
  11282. // is not added to IdResolver, so the code in the OpenMP region uses
  11283. // original variable for proper diagnostics and variable capturing.
  11284. Expr *VDInitRefExpr = nullptr;
  11285. // For arrays generate initializer for single element and replace it by the
  11286. // original array element in CodeGen.
  11287. if (Type->isArrayType()) {
  11288. VarDecl *VDInit =
  11289. buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
  11290. VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
  11291. Expr *Init = DefaultLvalueConversion(VDInitRefExpr).get();
  11292. ElemType = ElemType.getUnqualifiedType();
  11293. VarDecl *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
  11294. ".firstprivate.temp");
  11295. InitializedEntity Entity =
  11296. InitializedEntity::InitializeVariable(VDInitTemp);
  11297. InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
  11298. InitializationSequence InitSeq(*this, Entity, Kind, Init);
  11299. ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
  11300. if (Result.isInvalid())
  11301. VDPrivate->setInvalidDecl();
  11302. else
  11303. VDPrivate->setInit(Result.getAs<Expr>());
  11304. // Remove temp variable declaration.
  11305. Context.Deallocate(VDInitTemp);
  11306. } else {
  11307. VarDecl *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
  11308. ".firstprivate.temp");
  11309. VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
  11310. RefExpr->getExprLoc());
  11311. AddInitializerToDecl(VDPrivate,
  11312. DefaultLvalueConversion(VDInitRefExpr).get(),
  11313. /*DirectInit=*/false);
  11314. }
  11315. if (VDPrivate->isInvalidDecl()) {
  11316. if (IsImplicitClause) {
  11317. Diag(RefExpr->getExprLoc(),
  11318. diag::note_omp_task_predetermined_firstprivate_here);
  11319. }
  11320. continue;
  11321. }
  11322. CurContext->addDecl(VDPrivate);
  11323. DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
  11324. *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
  11325. RefExpr->getExprLoc());
  11326. DeclRefExpr *Ref = nullptr;
  11327. if (!VD && !CurContext->isDependentContext()) {
  11328. if (TopDVar.CKind == OMPC_lastprivate) {
  11329. Ref = TopDVar.PrivateCopy;
  11330. } else {
  11331. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
  11332. if (!isOpenMPCapturedDecl(D))
  11333. ExprCaptures.push_back(Ref->getDecl());
  11334. }
  11335. }
  11336. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
  11337. Vars.push_back((VD || CurContext->isDependentContext())
  11338. ? RefExpr->IgnoreParens()
  11339. : Ref);
  11340. PrivateCopies.push_back(VDPrivateRefExpr);
  11341. Inits.push_back(VDInitRefExpr);
  11342. }
  11343. if (Vars.empty())
  11344. return nullptr;
  11345. return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  11346. Vars, PrivateCopies, Inits,
  11347. buildPreInits(Context, ExprCaptures));
  11348. }
  11349. OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
  11350. SourceLocation StartLoc,
  11351. SourceLocation LParenLoc,
  11352. SourceLocation EndLoc) {
  11353. SmallVector<Expr *, 8> Vars;
  11354. SmallVector<Expr *, 8> SrcExprs;
  11355. SmallVector<Expr *, 8> DstExprs;
  11356. SmallVector<Expr *, 8> AssignmentOps;
  11357. SmallVector<Decl *, 4> ExprCaptures;
  11358. SmallVector<Expr *, 4> ExprPostUpdates;
  11359. for (Expr *RefExpr : VarList) {
  11360. assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
  11361. SourceLocation ELoc;
  11362. SourceRange ERange;
  11363. Expr *SimpleRefExpr = RefExpr;
  11364. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  11365. if (Res.second) {
  11366. // It will be analyzed later.
  11367. Vars.push_back(RefExpr);
  11368. SrcExprs.push_back(nullptr);
  11369. DstExprs.push_back(nullptr);
  11370. AssignmentOps.push_back(nullptr);
  11371. }
  11372. ValueDecl *D = Res.first;
  11373. if (!D)
  11374. continue;
  11375. QualType Type = D->getType();
  11376. auto *VD = dyn_cast<VarDecl>(D);
  11377. // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
  11378. // A variable that appears in a lastprivate clause must not have an
  11379. // incomplete type or a reference type.
  11380. if (RequireCompleteType(ELoc, Type,
  11381. diag::err_omp_lastprivate_incomplete_type))
  11382. continue;
  11383. Type = Type.getNonReferenceType();
  11384. // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
  11385. // A variable that is privatized must not have a const-qualified type
  11386. // unless it is of class type with a mutable member. This restriction does
  11387. // not apply to the firstprivate clause.
  11388. //
  11389. // OpenMP 3.1 [2.9.3.5, lastprivate clause, Restrictions]
  11390. // A variable that appears in a lastprivate clause must not have a
  11391. // const-qualified type unless it is of class type with a mutable member.
  11392. if (rejectConstNotMutableType(*this, D, Type, OMPC_lastprivate, ELoc))
  11393. continue;
  11394. OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
  11395. // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
  11396. // in a Construct]
  11397. // Variables with the predetermined data-sharing attributes may not be
  11398. // listed in data-sharing attributes clauses, except for the cases
  11399. // listed below.
  11400. // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
  11401. // A list item may appear in a firstprivate or lastprivate clause but not
  11402. // both.
  11403. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
  11404. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
  11405. (isOpenMPDistributeDirective(CurrDir) ||
  11406. DVar.CKind != OMPC_firstprivate) &&
  11407. (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
  11408. Diag(ELoc, diag::err_omp_wrong_dsa)
  11409. << getOpenMPClauseName(DVar.CKind)
  11410. << getOpenMPClauseName(OMPC_lastprivate);
  11411. reportOriginalDsa(*this, DSAStack, D, DVar);
  11412. continue;
  11413. }
  11414. // OpenMP [2.14.3.5, Restrictions, p.2]
  11415. // A list item that is private within a parallel region, or that appears in
  11416. // the reduction clause of a parallel construct, must not appear in a
  11417. // lastprivate clause on a worksharing construct if any of the corresponding
  11418. // worksharing regions ever binds to any of the corresponding parallel
  11419. // regions.
  11420. DSAStackTy::DSAVarData TopDVar = DVar;
  11421. if (isOpenMPWorksharingDirective(CurrDir) &&
  11422. !isOpenMPParallelDirective(CurrDir) &&
  11423. !isOpenMPTeamsDirective(CurrDir)) {
  11424. DVar = DSAStack->getImplicitDSA(D, true);
  11425. if (DVar.CKind != OMPC_shared) {
  11426. Diag(ELoc, diag::err_omp_required_access)
  11427. << getOpenMPClauseName(OMPC_lastprivate)
  11428. << getOpenMPClauseName(OMPC_shared);
  11429. reportOriginalDsa(*this, DSAStack, D, DVar);
  11430. continue;
  11431. }
  11432. }
  11433. // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
  11434. // A variable of class type (or array thereof) that appears in a
  11435. // lastprivate clause requires an accessible, unambiguous default
  11436. // constructor for the class type, unless the list item is also specified
  11437. // in a firstprivate clause.
  11438. // A variable of class type (or array thereof) that appears in a
  11439. // lastprivate clause requires an accessible, unambiguous copy assignment
  11440. // operator for the class type.
  11441. Type = Context.getBaseElementType(Type).getNonReferenceType();
  11442. VarDecl *SrcVD = buildVarDecl(*this, ERange.getBegin(),
  11443. Type.getUnqualifiedType(), ".lastprivate.src",
  11444. D->hasAttrs() ? &D->getAttrs() : nullptr);
  11445. DeclRefExpr *PseudoSrcExpr =
  11446. buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
  11447. VarDecl *DstVD =
  11448. buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
  11449. D->hasAttrs() ? &D->getAttrs() : nullptr);
  11450. DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
  11451. // For arrays generate assignment operation for single element and replace
  11452. // it by the original array element in CodeGen.
  11453. ExprResult AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
  11454. PseudoDstExpr, PseudoSrcExpr);
  11455. if (AssignmentOp.isInvalid())
  11456. continue;
  11457. AssignmentOp =
  11458. ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
  11459. if (AssignmentOp.isInvalid())
  11460. continue;
  11461. DeclRefExpr *Ref = nullptr;
  11462. if (!VD && !CurContext->isDependentContext()) {
  11463. if (TopDVar.CKind == OMPC_firstprivate) {
  11464. Ref = TopDVar.PrivateCopy;
  11465. } else {
  11466. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
  11467. if (!isOpenMPCapturedDecl(D))
  11468. ExprCaptures.push_back(Ref->getDecl());
  11469. }
  11470. if (TopDVar.CKind == OMPC_firstprivate ||
  11471. (!isOpenMPCapturedDecl(D) &&
  11472. Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
  11473. ExprResult RefRes = DefaultLvalueConversion(Ref);
  11474. if (!RefRes.isUsable())
  11475. continue;
  11476. ExprResult PostUpdateRes =
  11477. BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
  11478. RefRes.get());
  11479. if (!PostUpdateRes.isUsable())
  11480. continue;
  11481. ExprPostUpdates.push_back(
  11482. IgnoredValueConversions(PostUpdateRes.get()).get());
  11483. }
  11484. }
  11485. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
  11486. Vars.push_back((VD || CurContext->isDependentContext())
  11487. ? RefExpr->IgnoreParens()
  11488. : Ref);
  11489. SrcExprs.push_back(PseudoSrcExpr);
  11490. DstExprs.push_back(PseudoDstExpr);
  11491. AssignmentOps.push_back(AssignmentOp.get());
  11492. }
  11493. if (Vars.empty())
  11494. return nullptr;
  11495. return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  11496. Vars, SrcExprs, DstExprs, AssignmentOps,
  11497. buildPreInits(Context, ExprCaptures),
  11498. buildPostUpdate(*this, ExprPostUpdates));
  11499. }
  11500. OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
  11501. SourceLocation StartLoc,
  11502. SourceLocation LParenLoc,
  11503. SourceLocation EndLoc) {
  11504. SmallVector<Expr *, 8> Vars;
  11505. for (Expr *RefExpr : VarList) {
  11506. assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
  11507. SourceLocation ELoc;
  11508. SourceRange ERange;
  11509. Expr *SimpleRefExpr = RefExpr;
  11510. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  11511. if (Res.second) {
  11512. // It will be analyzed later.
  11513. Vars.push_back(RefExpr);
  11514. }
  11515. ValueDecl *D = Res.first;
  11516. if (!D)
  11517. continue;
  11518. auto *VD = dyn_cast<VarDecl>(D);
  11519. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  11520. // in a Construct]
  11521. // Variables with the predetermined data-sharing attributes may not be
  11522. // listed in data-sharing attributes clauses, except for the cases
  11523. // listed below. For these exceptions only, listing a predetermined
  11524. // variable in a data-sharing attribute clause is allowed and overrides
  11525. // the variable's predetermined data-sharing attributes.
  11526. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
  11527. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
  11528. DVar.RefExpr) {
  11529. Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
  11530. << getOpenMPClauseName(OMPC_shared);
  11531. reportOriginalDsa(*this, DSAStack, D, DVar);
  11532. continue;
  11533. }
  11534. DeclRefExpr *Ref = nullptr;
  11535. if (!VD && isOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
  11536. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
  11537. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
  11538. Vars.push_back((VD || !Ref || CurContext->isDependentContext())
  11539. ? RefExpr->IgnoreParens()
  11540. : Ref);
  11541. }
  11542. if (Vars.empty())
  11543. return nullptr;
  11544. return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
  11545. }
  11546. namespace {
  11547. class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
  11548. DSAStackTy *Stack;
  11549. public:
  11550. bool VisitDeclRefExpr(DeclRefExpr *E) {
  11551. if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
  11552. DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
  11553. if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
  11554. return false;
  11555. if (DVar.CKind != OMPC_unknown)
  11556. return true;
  11557. DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
  11558. VD, isOpenMPPrivate, [](OpenMPDirectiveKind) { return true; },
  11559. /*FromParent=*/true);
  11560. return DVarPrivate.CKind != OMPC_unknown;
  11561. }
  11562. return false;
  11563. }
  11564. bool VisitStmt(Stmt *S) {
  11565. for (Stmt *Child : S->children()) {
  11566. if (Child && Visit(Child))
  11567. return true;
  11568. }
  11569. return false;
  11570. }
  11571. explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
  11572. };
  11573. } // namespace
  11574. namespace {
  11575. // Transform MemberExpression for specified FieldDecl of current class to
  11576. // DeclRefExpr to specified OMPCapturedExprDecl.
  11577. class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
  11578. typedef TreeTransform<TransformExprToCaptures> BaseTransform;
  11579. ValueDecl *Field = nullptr;
  11580. DeclRefExpr *CapturedExpr = nullptr;
  11581. public:
  11582. TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
  11583. : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
  11584. ExprResult TransformMemberExpr(MemberExpr *E) {
  11585. if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
  11586. E->getMemberDecl() == Field) {
  11587. CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
  11588. return CapturedExpr;
  11589. }
  11590. return BaseTransform::TransformMemberExpr(E);
  11591. }
  11592. DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
  11593. };
  11594. } // namespace
  11595. template <typename T, typename U>
  11596. static T filterLookupForUDReductionAndMapper(
  11597. SmallVectorImpl<U> &Lookups, const llvm::function_ref<T(ValueDecl *)> Gen) {
  11598. for (U &Set : Lookups) {
  11599. for (auto *D : Set) {
  11600. if (T Res = Gen(cast<ValueDecl>(D)))
  11601. return Res;
  11602. }
  11603. }
  11604. return T();
  11605. }
  11606. static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D) {
  11607. assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case");
  11608. for (auto RD : D->redecls()) {
  11609. // Don't bother with extra checks if we already know this one isn't visible.
  11610. if (RD == D)
  11611. continue;
  11612. auto ND = cast<NamedDecl>(RD);
  11613. if (LookupResult::isVisible(SemaRef, ND))
  11614. return ND;
  11615. }
  11616. return nullptr;
  11617. }
  11618. static void
  11619. argumentDependentLookup(Sema &SemaRef, const DeclarationNameInfo &Id,
  11620. SourceLocation Loc, QualType Ty,
  11621. SmallVectorImpl<UnresolvedSet<8>> &Lookups) {
  11622. // Find all of the associated namespaces and classes based on the
  11623. // arguments we have.
  11624. Sema::AssociatedNamespaceSet AssociatedNamespaces;
  11625. Sema::AssociatedClassSet AssociatedClasses;
  11626. OpaqueValueExpr OVE(Loc, Ty, VK_LValue);
  11627. SemaRef.FindAssociatedClassesAndNamespaces(Loc, &OVE, AssociatedNamespaces,
  11628. AssociatedClasses);
  11629. // C++ [basic.lookup.argdep]p3:
  11630. // Let X be the lookup set produced by unqualified lookup (3.4.1)
  11631. // and let Y be the lookup set produced by argument dependent
  11632. // lookup (defined as follows). If X contains [...] then Y is
  11633. // empty. Otherwise Y is the set of declarations found in the
  11634. // namespaces associated with the argument types as described
  11635. // below. The set of declarations found by the lookup of the name
  11636. // is the union of X and Y.
  11637. //
  11638. // Here, we compute Y and add its members to the overloaded
  11639. // candidate set.
  11640. for (auto *NS : AssociatedNamespaces) {
  11641. // When considering an associated namespace, the lookup is the
  11642. // same as the lookup performed when the associated namespace is
  11643. // used as a qualifier (3.4.3.2) except that:
  11644. //
  11645. // -- Any using-directives in the associated namespace are
  11646. // ignored.
  11647. //
  11648. // -- Any namespace-scope friend functions declared in
  11649. // associated classes are visible within their respective
  11650. // namespaces even if they are not visible during an ordinary
  11651. // lookup (11.4).
  11652. DeclContext::lookup_result R = NS->lookup(Id.getName());
  11653. for (auto *D : R) {
  11654. auto *Underlying = D;
  11655. if (auto *USD = dyn_cast<UsingShadowDecl>(D))
  11656. Underlying = USD->getTargetDecl();
  11657. if (!isa<OMPDeclareReductionDecl>(Underlying) &&
  11658. !isa<OMPDeclareMapperDecl>(Underlying))
  11659. continue;
  11660. if (!SemaRef.isVisible(D)) {
  11661. D = findAcceptableDecl(SemaRef, D);
  11662. if (!D)
  11663. continue;
  11664. if (auto *USD = dyn_cast<UsingShadowDecl>(D))
  11665. Underlying = USD->getTargetDecl();
  11666. }
  11667. Lookups.emplace_back();
  11668. Lookups.back().addDecl(Underlying);
  11669. }
  11670. }
  11671. }
  11672. static ExprResult
  11673. buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
  11674. Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
  11675. const DeclarationNameInfo &ReductionId, QualType Ty,
  11676. CXXCastPath &BasePath, Expr *UnresolvedReduction) {
  11677. if (ReductionIdScopeSpec.isInvalid())
  11678. return ExprError();
  11679. SmallVector<UnresolvedSet<8>, 4> Lookups;
  11680. if (S) {
  11681. LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
  11682. Lookup.suppressDiagnostics();
  11683. while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
  11684. NamedDecl *D = Lookup.getRepresentativeDecl();
  11685. do {
  11686. S = S->getParent();
  11687. } while (S && !S->isDeclScope(D));
  11688. if (S)
  11689. S = S->getParent();
  11690. Lookups.emplace_back();
  11691. Lookups.back().append(Lookup.begin(), Lookup.end());
  11692. Lookup.clear();
  11693. }
  11694. } else if (auto *ULE =
  11695. cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
  11696. Lookups.push_back(UnresolvedSet<8>());
  11697. Decl *PrevD = nullptr;
  11698. for (NamedDecl *D : ULE->decls()) {
  11699. if (D == PrevD)
  11700. Lookups.push_back(UnresolvedSet<8>());
  11701. else if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(D))
  11702. Lookups.back().addDecl(DRD);
  11703. PrevD = D;
  11704. }
  11705. }
  11706. if (SemaRef.CurContext->isDependentContext() || Ty->isDependentType() ||
  11707. Ty->isInstantiationDependentType() ||
  11708. Ty->containsUnexpandedParameterPack() ||
  11709. filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) {
  11710. return !D->isInvalidDecl() &&
  11711. (D->getType()->isDependentType() ||
  11712. D->getType()->isInstantiationDependentType() ||
  11713. D->getType()->containsUnexpandedParameterPack());
  11714. })) {
  11715. UnresolvedSet<8> ResSet;
  11716. for (const UnresolvedSet<8> &Set : Lookups) {
  11717. if (Set.empty())
  11718. continue;
  11719. ResSet.append(Set.begin(), Set.end());
  11720. // The last item marks the end of all declarations at the specified scope.
  11721. ResSet.addDecl(Set[Set.size() - 1]);
  11722. }
  11723. return UnresolvedLookupExpr::Create(
  11724. SemaRef.Context, /*NamingClass=*/nullptr,
  11725. ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
  11726. /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
  11727. }
  11728. // Lookup inside the classes.
  11729. // C++ [over.match.oper]p3:
  11730. // For a unary operator @ with an operand of a type whose
  11731. // cv-unqualified version is T1, and for a binary operator @ with
  11732. // a left operand of a type whose cv-unqualified version is T1 and
  11733. // a right operand of a type whose cv-unqualified version is T2,
  11734. // three sets of candidate functions, designated member
  11735. // candidates, non-member candidates and built-in candidates, are
  11736. // constructed as follows:
  11737. // -- If T1 is a complete class type or a class currently being
  11738. // defined, the set of member candidates is the result of the
  11739. // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
  11740. // the set of member candidates is empty.
  11741. LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
  11742. Lookup.suppressDiagnostics();
  11743. if (const auto *TyRec = Ty->getAs<RecordType>()) {
  11744. // Complete the type if it can be completed.
  11745. // If the type is neither complete nor being defined, bail out now.
  11746. if (SemaRef.isCompleteType(Loc, Ty) || TyRec->isBeingDefined() ||
  11747. TyRec->getDecl()->getDefinition()) {
  11748. Lookup.clear();
  11749. SemaRef.LookupQualifiedName(Lookup, TyRec->getDecl());
  11750. if (Lookup.empty()) {
  11751. Lookups.emplace_back();
  11752. Lookups.back().append(Lookup.begin(), Lookup.end());
  11753. }
  11754. }
  11755. }
  11756. // Perform ADL.
  11757. if (SemaRef.getLangOpts().CPlusPlus)
  11758. argumentDependentLookup(SemaRef, ReductionId, Loc, Ty, Lookups);
  11759. if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
  11760. Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
  11761. if (!D->isInvalidDecl() &&
  11762. SemaRef.Context.hasSameType(D->getType(), Ty))
  11763. return D;
  11764. return nullptr;
  11765. }))
  11766. return SemaRef.BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(),
  11767. VK_LValue, Loc);
  11768. if (SemaRef.getLangOpts().CPlusPlus) {
  11769. if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
  11770. Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
  11771. if (!D->isInvalidDecl() &&
  11772. SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
  11773. !Ty.isMoreQualifiedThan(D->getType()))
  11774. return D;
  11775. return nullptr;
  11776. })) {
  11777. CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
  11778. /*DetectVirtual=*/false);
  11779. if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
  11780. if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
  11781. VD->getType().getUnqualifiedType()))) {
  11782. if (SemaRef.CheckBaseClassAccess(
  11783. Loc, VD->getType(), Ty, Paths.front(),
  11784. /*DiagID=*/0) != Sema::AR_inaccessible) {
  11785. SemaRef.BuildBasePathArray(Paths, BasePath);
  11786. return SemaRef.BuildDeclRefExpr(
  11787. VD, VD->getType().getNonReferenceType(), VK_LValue, Loc);
  11788. }
  11789. }
  11790. }
  11791. }
  11792. }
  11793. if (ReductionIdScopeSpec.isSet()) {
  11794. SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range;
  11795. return ExprError();
  11796. }
  11797. return ExprEmpty();
  11798. }
  11799. namespace {
  11800. /// Data for the reduction-based clauses.
  11801. struct ReductionData {
  11802. /// List of original reduction items.
  11803. SmallVector<Expr *, 8> Vars;
  11804. /// List of private copies of the reduction items.
  11805. SmallVector<Expr *, 8> Privates;
  11806. /// LHS expressions for the reduction_op expressions.
  11807. SmallVector<Expr *, 8> LHSs;
  11808. /// RHS expressions for the reduction_op expressions.
  11809. SmallVector<Expr *, 8> RHSs;
  11810. /// Reduction operation expression.
  11811. SmallVector<Expr *, 8> ReductionOps;
  11812. /// Taskgroup descriptors for the corresponding reduction items in
  11813. /// in_reduction clauses.
  11814. SmallVector<Expr *, 8> TaskgroupDescriptors;
  11815. /// List of captures for clause.
  11816. SmallVector<Decl *, 4> ExprCaptures;
  11817. /// List of postupdate expressions.
  11818. SmallVector<Expr *, 4> ExprPostUpdates;
  11819. ReductionData() = delete;
  11820. /// Reserves required memory for the reduction data.
  11821. ReductionData(unsigned Size) {
  11822. Vars.reserve(Size);
  11823. Privates.reserve(Size);
  11824. LHSs.reserve(Size);
  11825. RHSs.reserve(Size);
  11826. ReductionOps.reserve(Size);
  11827. TaskgroupDescriptors.reserve(Size);
  11828. ExprCaptures.reserve(Size);
  11829. ExprPostUpdates.reserve(Size);
  11830. }
  11831. /// Stores reduction item and reduction operation only (required for dependent
  11832. /// reduction item).
  11833. void push(Expr *Item, Expr *ReductionOp) {
  11834. Vars.emplace_back(Item);
  11835. Privates.emplace_back(nullptr);
  11836. LHSs.emplace_back(nullptr);
  11837. RHSs.emplace_back(nullptr);
  11838. ReductionOps.emplace_back(ReductionOp);
  11839. TaskgroupDescriptors.emplace_back(nullptr);
  11840. }
  11841. /// Stores reduction data.
  11842. void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS, Expr *ReductionOp,
  11843. Expr *TaskgroupDescriptor) {
  11844. Vars.emplace_back(Item);
  11845. Privates.emplace_back(Private);
  11846. LHSs.emplace_back(LHS);
  11847. RHSs.emplace_back(RHS);
  11848. ReductionOps.emplace_back(ReductionOp);
  11849. TaskgroupDescriptors.emplace_back(TaskgroupDescriptor);
  11850. }
  11851. };
  11852. } // namespace
  11853. static bool checkOMPArraySectionConstantForReduction(
  11854. ASTContext &Context, const OMPArraySectionExpr *OASE, bool &SingleElement,
  11855. SmallVectorImpl<llvm::APSInt> &ArraySizes) {
  11856. const Expr *Length = OASE->getLength();
  11857. if (Length == nullptr) {
  11858. // For array sections of the form [1:] or [:], we would need to analyze
  11859. // the lower bound...
  11860. if (OASE->getColonLoc().isValid())
  11861. return false;
  11862. // This is an array subscript which has implicit length 1!
  11863. SingleElement = true;
  11864. ArraySizes.push_back(llvm::APSInt::get(1));
  11865. } else {
  11866. Expr::EvalResult Result;
  11867. if (!Length->EvaluateAsInt(Result, Context))
  11868. return false;
  11869. llvm::APSInt ConstantLengthValue = Result.Val.getInt();
  11870. SingleElement = (ConstantLengthValue.getSExtValue() == 1);
  11871. ArraySizes.push_back(ConstantLengthValue);
  11872. }
  11873. // Get the base of this array section and walk up from there.
  11874. const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
  11875. // We require length = 1 for all array sections except the right-most to
  11876. // guarantee that the memory region is contiguous and has no holes in it.
  11877. while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) {
  11878. Length = TempOASE->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. ArraySizes.push_back(llvm::APSInt::get(1));
  11886. } else {
  11887. Expr::EvalResult Result;
  11888. if (!Length->EvaluateAsInt(Result, Context))
  11889. return false;
  11890. llvm::APSInt ConstantLengthValue = Result.Val.getInt();
  11891. if (ConstantLengthValue.getSExtValue() != 1)
  11892. return false;
  11893. ArraySizes.push_back(ConstantLengthValue);
  11894. }
  11895. Base = TempOASE->getBase()->IgnoreParenImpCasts();
  11896. }
  11897. // If we have a single element, we don't need to add the implicit lengths.
  11898. if (!SingleElement) {
  11899. while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) {
  11900. // Has implicit length 1!
  11901. ArraySizes.push_back(llvm::APSInt::get(1));
  11902. Base = TempASE->getBase()->IgnoreParenImpCasts();
  11903. }
  11904. }
  11905. // This array section can be privatized as a single value or as a constant
  11906. // sized array.
  11907. return true;
  11908. }
  11909. static bool actOnOMPReductionKindClause(
  11910. Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind,
  11911. ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
  11912. SourceLocation ColonLoc, SourceLocation EndLoc,
  11913. CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
  11914. ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) {
  11915. DeclarationName DN = ReductionId.getName();
  11916. OverloadedOperatorKind OOK = DN.getCXXOverloadedOperator();
  11917. BinaryOperatorKind BOK = BO_Comma;
  11918. ASTContext &Context = S.Context;
  11919. // OpenMP [2.14.3.6, reduction clause]
  11920. // C
  11921. // reduction-identifier is either an identifier or one of the following
  11922. // operators: +, -, *, &, |, ^, && and ||
  11923. // C++
  11924. // reduction-identifier is either an id-expression or one of the following
  11925. // operators: +, -, *, &, |, ^, && and ||
  11926. switch (OOK) {
  11927. case OO_Plus:
  11928. case OO_Minus:
  11929. BOK = BO_Add;
  11930. break;
  11931. case OO_Star:
  11932. BOK = BO_Mul;
  11933. break;
  11934. case OO_Amp:
  11935. BOK = BO_And;
  11936. break;
  11937. case OO_Pipe:
  11938. BOK = BO_Or;
  11939. break;
  11940. case OO_Caret:
  11941. BOK = BO_Xor;
  11942. break;
  11943. case OO_AmpAmp:
  11944. BOK = BO_LAnd;
  11945. break;
  11946. case OO_PipePipe:
  11947. BOK = BO_LOr;
  11948. break;
  11949. case OO_New:
  11950. case OO_Delete:
  11951. case OO_Array_New:
  11952. case OO_Array_Delete:
  11953. case OO_Slash:
  11954. case OO_Percent:
  11955. case OO_Tilde:
  11956. case OO_Exclaim:
  11957. case OO_Equal:
  11958. case OO_Less:
  11959. case OO_Greater:
  11960. case OO_LessEqual:
  11961. case OO_GreaterEqual:
  11962. case OO_PlusEqual:
  11963. case OO_MinusEqual:
  11964. case OO_StarEqual:
  11965. case OO_SlashEqual:
  11966. case OO_PercentEqual:
  11967. case OO_CaretEqual:
  11968. case OO_AmpEqual:
  11969. case OO_PipeEqual:
  11970. case OO_LessLess:
  11971. case OO_GreaterGreater:
  11972. case OO_LessLessEqual:
  11973. case OO_GreaterGreaterEqual:
  11974. case OO_EqualEqual:
  11975. case OO_ExclaimEqual:
  11976. case OO_Spaceship:
  11977. case OO_PlusPlus:
  11978. case OO_MinusMinus:
  11979. case OO_Comma:
  11980. case OO_ArrowStar:
  11981. case OO_Arrow:
  11982. case OO_Call:
  11983. case OO_Subscript:
  11984. case OO_Conditional:
  11985. case OO_Coawait:
  11986. case NUM_OVERLOADED_OPERATORS:
  11987. llvm_unreachable("Unexpected reduction identifier");
  11988. case OO_None:
  11989. if (IdentifierInfo *II = DN.getAsIdentifierInfo()) {
  11990. if (II->isStr("max"))
  11991. BOK = BO_GT;
  11992. else if (II->isStr("min"))
  11993. BOK = BO_LT;
  11994. }
  11995. break;
  11996. }
  11997. SourceRange ReductionIdRange;
  11998. if (ReductionIdScopeSpec.isValid())
  11999. ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
  12000. else
  12001. ReductionIdRange.setBegin(ReductionId.getBeginLoc());
  12002. ReductionIdRange.setEnd(ReductionId.getEndLoc());
  12003. auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
  12004. bool FirstIter = true;
  12005. for (Expr *RefExpr : VarList) {
  12006. assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
  12007. // OpenMP [2.1, C/C++]
  12008. // A list item is a variable or array section, subject to the restrictions
  12009. // specified in Section 2.4 on page 42 and in each of the sections
  12010. // describing clauses and directives for which a list appears.
  12011. // OpenMP [2.14.3.3, Restrictions, p.1]
  12012. // A variable that is part of another variable (as an array or
  12013. // structure element) cannot appear in a private clause.
  12014. if (!FirstIter && IR != ER)
  12015. ++IR;
  12016. FirstIter = false;
  12017. SourceLocation ELoc;
  12018. SourceRange ERange;
  12019. Expr *SimpleRefExpr = RefExpr;
  12020. auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
  12021. /*AllowArraySection=*/true);
  12022. if (Res.second) {
  12023. // Try to find 'declare reduction' corresponding construct before using
  12024. // builtin/overloaded operators.
  12025. QualType Type = Context.DependentTy;
  12026. CXXCastPath BasePath;
  12027. ExprResult DeclareReductionRef = buildDeclareReductionRef(
  12028. S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
  12029. ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
  12030. Expr *ReductionOp = nullptr;
  12031. if (S.CurContext->isDependentContext() &&
  12032. (DeclareReductionRef.isUnset() ||
  12033. isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
  12034. ReductionOp = DeclareReductionRef.get();
  12035. // It will be analyzed later.
  12036. RD.push(RefExpr, ReductionOp);
  12037. }
  12038. ValueDecl *D = Res.first;
  12039. if (!D)
  12040. continue;
  12041. Expr *TaskgroupDescriptor = nullptr;
  12042. QualType Type;
  12043. auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
  12044. auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
  12045. if (ASE) {
  12046. Type = ASE->getType().getNonReferenceType();
  12047. } else if (OASE) {
  12048. QualType BaseType =
  12049. OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
  12050. if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
  12051. Type = ATy->getElementType();
  12052. else
  12053. Type = BaseType->getPointeeType();
  12054. Type = Type.getNonReferenceType();
  12055. } else {
  12056. Type = Context.getBaseElementType(D->getType().getNonReferenceType());
  12057. }
  12058. auto *VD = dyn_cast<VarDecl>(D);
  12059. // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
  12060. // A variable that appears in a private clause must not have an incomplete
  12061. // type or a reference type.
  12062. if (S.RequireCompleteType(ELoc, D->getType(),
  12063. diag::err_omp_reduction_incomplete_type))
  12064. continue;
  12065. // OpenMP [2.14.3.6, reduction clause, Restrictions]
  12066. // A list item that appears in a reduction clause must not be
  12067. // const-qualified.
  12068. if (rejectConstNotMutableType(S, D, Type, ClauseKind, ELoc,
  12069. /*AcceptIfMutable*/ false, ASE || OASE))
  12070. continue;
  12071. OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective();
  12072. // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
  12073. // If a list-item is a reference type then it must bind to the same object
  12074. // for all threads of the team.
  12075. if (!ASE && !OASE) {
  12076. if (VD) {
  12077. VarDecl *VDDef = VD->getDefinition();
  12078. if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
  12079. DSARefChecker Check(Stack);
  12080. if (Check.Visit(VDDef->getInit())) {
  12081. S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg)
  12082. << getOpenMPClauseName(ClauseKind) << ERange;
  12083. S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
  12084. continue;
  12085. }
  12086. }
  12087. }
  12088. // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
  12089. // in a Construct]
  12090. // Variables with the predetermined data-sharing attributes may not be
  12091. // listed in data-sharing attributes clauses, except for the cases
  12092. // listed below. For these exceptions only, listing a predetermined
  12093. // variable in a data-sharing attribute clause is allowed and overrides
  12094. // the variable's predetermined data-sharing attributes.
  12095. // OpenMP [2.14.3.6, Restrictions, p.3]
  12096. // Any number of reduction clauses can be specified on the directive,
  12097. // but a list item can appear only once in the reduction clauses for that
  12098. // directive.
  12099. DSAStackTy::DSAVarData DVar = Stack->getTopDSA(D, /*FromParent=*/false);
  12100. if (DVar.CKind == OMPC_reduction) {
  12101. S.Diag(ELoc, diag::err_omp_once_referenced)
  12102. << getOpenMPClauseName(ClauseKind);
  12103. if (DVar.RefExpr)
  12104. S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
  12105. continue;
  12106. }
  12107. if (DVar.CKind != OMPC_unknown) {
  12108. S.Diag(ELoc, diag::err_omp_wrong_dsa)
  12109. << getOpenMPClauseName(DVar.CKind)
  12110. << getOpenMPClauseName(OMPC_reduction);
  12111. reportOriginalDsa(S, Stack, D, DVar);
  12112. continue;
  12113. }
  12114. // OpenMP [2.14.3.6, Restrictions, p.1]
  12115. // A list item that appears in a reduction clause of a worksharing
  12116. // construct must be shared in the parallel regions to which any of the
  12117. // worksharing regions arising from the worksharing construct bind.
  12118. if (isOpenMPWorksharingDirective(CurrDir) &&
  12119. !isOpenMPParallelDirective(CurrDir) &&
  12120. !isOpenMPTeamsDirective(CurrDir)) {
  12121. DVar = Stack->getImplicitDSA(D, true);
  12122. if (DVar.CKind != OMPC_shared) {
  12123. S.Diag(ELoc, diag::err_omp_required_access)
  12124. << getOpenMPClauseName(OMPC_reduction)
  12125. << getOpenMPClauseName(OMPC_shared);
  12126. reportOriginalDsa(S, Stack, D, DVar);
  12127. continue;
  12128. }
  12129. }
  12130. }
  12131. // Try to find 'declare reduction' corresponding construct before using
  12132. // builtin/overloaded operators.
  12133. CXXCastPath BasePath;
  12134. ExprResult DeclareReductionRef = buildDeclareReductionRef(
  12135. S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
  12136. ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
  12137. if (DeclareReductionRef.isInvalid())
  12138. continue;
  12139. if (S.CurContext->isDependentContext() &&
  12140. (DeclareReductionRef.isUnset() ||
  12141. isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
  12142. RD.push(RefExpr, DeclareReductionRef.get());
  12143. continue;
  12144. }
  12145. if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
  12146. // Not allowed reduction identifier is found.
  12147. S.Diag(ReductionId.getBeginLoc(),
  12148. diag::err_omp_unknown_reduction_identifier)
  12149. << Type << ReductionIdRange;
  12150. continue;
  12151. }
  12152. // OpenMP [2.14.3.6, reduction clause, Restrictions]
  12153. // The type of a list item that appears in a reduction clause must be valid
  12154. // for the reduction-identifier. For a max or min reduction in C, the type
  12155. // of the list item must be an allowed arithmetic data type: char, int,
  12156. // float, double, or _Bool, possibly modified with long, short, signed, or
  12157. // unsigned. For a max or min reduction in C++, the type of the list item
  12158. // must be an allowed arithmetic data type: char, wchar_t, int, float,
  12159. // double, or bool, possibly modified with long, short, signed, or unsigned.
  12160. if (DeclareReductionRef.isUnset()) {
  12161. if ((BOK == BO_GT || BOK == BO_LT) &&
  12162. !(Type->isScalarType() ||
  12163. (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
  12164. S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
  12165. << getOpenMPClauseName(ClauseKind) << S.getLangOpts().CPlusPlus;
  12166. if (!ASE && !OASE) {
  12167. bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
  12168. VarDecl::DeclarationOnly;
  12169. S.Diag(D->getLocation(),
  12170. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  12171. << D;
  12172. }
  12173. continue;
  12174. }
  12175. if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
  12176. !S.getLangOpts().CPlusPlus && Type->isFloatingType()) {
  12177. S.Diag(ELoc, diag::err_omp_clause_floating_type_arg)
  12178. << getOpenMPClauseName(ClauseKind);
  12179. if (!ASE && !OASE) {
  12180. bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
  12181. VarDecl::DeclarationOnly;
  12182. S.Diag(D->getLocation(),
  12183. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  12184. << D;
  12185. }
  12186. continue;
  12187. }
  12188. }
  12189. Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
  12190. VarDecl *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs",
  12191. D->hasAttrs() ? &D->getAttrs() : nullptr);
  12192. VarDecl *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(),
  12193. D->hasAttrs() ? &D->getAttrs() : nullptr);
  12194. QualType PrivateTy = Type;
  12195. // Try if we can determine constant lengths for all array sections and avoid
  12196. // the VLA.
  12197. bool ConstantLengthOASE = false;
  12198. if (OASE) {
  12199. bool SingleElement;
  12200. llvm::SmallVector<llvm::APSInt, 4> ArraySizes;
  12201. ConstantLengthOASE = checkOMPArraySectionConstantForReduction(
  12202. Context, OASE, SingleElement, ArraySizes);
  12203. // If we don't have a single element, we must emit a constant array type.
  12204. if (ConstantLengthOASE && !SingleElement) {
  12205. for (llvm::APSInt &Size : ArraySizes)
  12206. PrivateTy = Context.getConstantArrayType(PrivateTy, Size, nullptr,
  12207. ArrayType::Normal,
  12208. /*IndexTypeQuals=*/0);
  12209. }
  12210. }
  12211. if ((OASE && !ConstantLengthOASE) ||
  12212. (!OASE && !ASE &&
  12213. D->getType().getNonReferenceType()->isVariablyModifiedType())) {
  12214. if (!Context.getTargetInfo().isVLASupported()) {
  12215. if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective())) {
  12216. S.Diag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
  12217. S.Diag(ELoc, diag::note_vla_unsupported);
  12218. } else {
  12219. S.targetDiag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
  12220. S.targetDiag(ELoc, diag::note_vla_unsupported);
  12221. }
  12222. continue;
  12223. }
  12224. // For arrays/array sections only:
  12225. // Create pseudo array type for private copy. The size for this array will
  12226. // be generated during codegen.
  12227. // For array subscripts or single variables Private Ty is the same as Type
  12228. // (type of the variable or single array element).
  12229. PrivateTy = Context.getVariableArrayType(
  12230. Type,
  12231. new (Context) OpaqueValueExpr(ELoc, Context.getSizeType(), VK_RValue),
  12232. ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
  12233. } else if (!ASE && !OASE &&
  12234. Context.getAsArrayType(D->getType().getNonReferenceType())) {
  12235. PrivateTy = D->getType().getNonReferenceType();
  12236. }
  12237. // Private copy.
  12238. VarDecl *PrivateVD =
  12239. buildVarDecl(S, ELoc, PrivateTy, D->getName(),
  12240. D->hasAttrs() ? &D->getAttrs() : nullptr,
  12241. VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
  12242. // Add initializer for private variable.
  12243. Expr *Init = nullptr;
  12244. DeclRefExpr *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc);
  12245. DeclRefExpr *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc);
  12246. if (DeclareReductionRef.isUsable()) {
  12247. auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
  12248. auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
  12249. if (DRD->getInitializer()) {
  12250. Init = DRDRef;
  12251. RHSVD->setInit(DRDRef);
  12252. RHSVD->setInitStyle(VarDecl::CallInit);
  12253. }
  12254. } else {
  12255. switch (BOK) {
  12256. case BO_Add:
  12257. case BO_Xor:
  12258. case BO_Or:
  12259. case BO_LOr:
  12260. // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
  12261. if (Type->isScalarType() || Type->isAnyComplexType())
  12262. Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get();
  12263. break;
  12264. case BO_Mul:
  12265. case BO_LAnd:
  12266. if (Type->isScalarType() || Type->isAnyComplexType()) {
  12267. // '*' and '&&' reduction ops - initializer is '1'.
  12268. Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get();
  12269. }
  12270. break;
  12271. case BO_And: {
  12272. // '&' reduction op - initializer is '~0'.
  12273. QualType OrigType = Type;
  12274. if (auto *ComplexTy = OrigType->getAs<ComplexType>())
  12275. Type = ComplexTy->getElementType();
  12276. if (Type->isRealFloatingType()) {
  12277. llvm::APFloat InitValue =
  12278. llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
  12279. /*isIEEE=*/true);
  12280. Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
  12281. Type, ELoc);
  12282. } else if (Type->isScalarType()) {
  12283. uint64_t Size = Context.getTypeSize(Type);
  12284. QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
  12285. llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
  12286. Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
  12287. }
  12288. if (Init && OrigType->isAnyComplexType()) {
  12289. // Init = 0xFFFF + 0xFFFFi;
  12290. auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
  12291. Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
  12292. }
  12293. Type = OrigType;
  12294. break;
  12295. }
  12296. case BO_LT:
  12297. case BO_GT: {
  12298. // 'min' reduction op - initializer is 'Largest representable number in
  12299. // the reduction list item type'.
  12300. // 'max' reduction op - initializer is 'Least representable number in
  12301. // the reduction list item type'.
  12302. if (Type->isIntegerType() || Type->isPointerType()) {
  12303. bool IsSigned = Type->hasSignedIntegerRepresentation();
  12304. uint64_t Size = Context.getTypeSize(Type);
  12305. QualType IntTy =
  12306. Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
  12307. llvm::APInt InitValue =
  12308. (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
  12309. : llvm::APInt::getMinValue(Size)
  12310. : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
  12311. : llvm::APInt::getMaxValue(Size);
  12312. Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
  12313. if (Type->isPointerType()) {
  12314. // Cast to pointer type.
  12315. ExprResult CastExpr = S.BuildCStyleCastExpr(
  12316. ELoc, Context.getTrivialTypeSourceInfo(Type, ELoc), ELoc, Init);
  12317. if (CastExpr.isInvalid())
  12318. continue;
  12319. Init = CastExpr.get();
  12320. }
  12321. } else if (Type->isRealFloatingType()) {
  12322. llvm::APFloat InitValue = llvm::APFloat::getLargest(
  12323. Context.getFloatTypeSemantics(Type), BOK != BO_LT);
  12324. Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
  12325. Type, ELoc);
  12326. }
  12327. break;
  12328. }
  12329. case BO_PtrMemD:
  12330. case BO_PtrMemI:
  12331. case BO_MulAssign:
  12332. case BO_Div:
  12333. case BO_Rem:
  12334. case BO_Sub:
  12335. case BO_Shl:
  12336. case BO_Shr:
  12337. case BO_LE:
  12338. case BO_GE:
  12339. case BO_EQ:
  12340. case BO_NE:
  12341. case BO_Cmp:
  12342. case BO_AndAssign:
  12343. case BO_XorAssign:
  12344. case BO_OrAssign:
  12345. case BO_Assign:
  12346. case BO_AddAssign:
  12347. case BO_SubAssign:
  12348. case BO_DivAssign:
  12349. case BO_RemAssign:
  12350. case BO_ShlAssign:
  12351. case BO_ShrAssign:
  12352. case BO_Comma:
  12353. llvm_unreachable("Unexpected reduction operation");
  12354. }
  12355. }
  12356. if (Init && DeclareReductionRef.isUnset())
  12357. S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false);
  12358. else if (!Init)
  12359. S.ActOnUninitializedDecl(RHSVD);
  12360. if (RHSVD->isInvalidDecl())
  12361. continue;
  12362. if (!RHSVD->hasInit() &&
  12363. (DeclareReductionRef.isUnset() || !S.LangOpts.CPlusPlus)) {
  12364. S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible)
  12365. << Type << ReductionIdRange;
  12366. bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
  12367. VarDecl::DeclarationOnly;
  12368. S.Diag(D->getLocation(),
  12369. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  12370. << D;
  12371. continue;
  12372. }
  12373. // Store initializer for single element in private copy. Will be used during
  12374. // codegen.
  12375. PrivateVD->setInit(RHSVD->getInit());
  12376. PrivateVD->setInitStyle(RHSVD->getInitStyle());
  12377. DeclRefExpr *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc);
  12378. ExprResult ReductionOp;
  12379. if (DeclareReductionRef.isUsable()) {
  12380. QualType RedTy = DeclareReductionRef.get()->getType();
  12381. QualType PtrRedTy = Context.getPointerType(RedTy);
  12382. ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
  12383. ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
  12384. if (!BasePath.empty()) {
  12385. LHS = S.DefaultLvalueConversion(LHS.get());
  12386. RHS = S.DefaultLvalueConversion(RHS.get());
  12387. LHS = ImplicitCastExpr::Create(Context, PtrRedTy,
  12388. CK_UncheckedDerivedToBase, LHS.get(),
  12389. &BasePath, LHS.get()->getValueKind());
  12390. RHS = ImplicitCastExpr::Create(Context, PtrRedTy,
  12391. CK_UncheckedDerivedToBase, RHS.get(),
  12392. &BasePath, RHS.get()->getValueKind());
  12393. }
  12394. FunctionProtoType::ExtProtoInfo EPI;
  12395. QualType Params[] = {PtrRedTy, PtrRedTy};
  12396. QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
  12397. auto *OVE = new (Context) OpaqueValueExpr(
  12398. ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary,
  12399. S.DefaultLvalueConversion(DeclareReductionRef.get()).get());
  12400. Expr *Args[] = {LHS.get(), RHS.get()};
  12401. ReductionOp =
  12402. CallExpr::Create(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc);
  12403. } else {
  12404. ReductionOp = S.BuildBinOp(
  12405. Stack->getCurScope(), ReductionId.getBeginLoc(), BOK, LHSDRE, RHSDRE);
  12406. if (ReductionOp.isUsable()) {
  12407. if (BOK != BO_LT && BOK != BO_GT) {
  12408. ReductionOp =
  12409. S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
  12410. BO_Assign, LHSDRE, ReductionOp.get());
  12411. } else {
  12412. auto *ConditionalOp = new (Context)
  12413. ConditionalOperator(ReductionOp.get(), ELoc, LHSDRE, ELoc, RHSDRE,
  12414. Type, VK_LValue, OK_Ordinary);
  12415. ReductionOp =
  12416. S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
  12417. BO_Assign, LHSDRE, ConditionalOp);
  12418. }
  12419. if (ReductionOp.isUsable())
  12420. ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get(),
  12421. /*DiscardedValue*/ false);
  12422. }
  12423. if (!ReductionOp.isUsable())
  12424. continue;
  12425. }
  12426. // OpenMP [2.15.4.6, Restrictions, p.2]
  12427. // A list item that appears in an in_reduction clause of a task construct
  12428. // must appear in a task_reduction clause of a construct associated with a
  12429. // taskgroup region that includes the participating task in its taskgroup
  12430. // set. The construct associated with the innermost region that meets this
  12431. // condition must specify the same reduction-identifier as the in_reduction
  12432. // clause.
  12433. if (ClauseKind == OMPC_in_reduction) {
  12434. SourceRange ParentSR;
  12435. BinaryOperatorKind ParentBOK;
  12436. const Expr *ParentReductionOp;
  12437. Expr *ParentBOKTD, *ParentReductionOpTD;
  12438. DSAStackTy::DSAVarData ParentBOKDSA =
  12439. Stack->getTopMostTaskgroupReductionData(D, ParentSR, ParentBOK,
  12440. ParentBOKTD);
  12441. DSAStackTy::DSAVarData ParentReductionOpDSA =
  12442. Stack->getTopMostTaskgroupReductionData(
  12443. D, ParentSR, ParentReductionOp, ParentReductionOpTD);
  12444. bool IsParentBOK = ParentBOKDSA.DKind != OMPD_unknown;
  12445. bool IsParentReductionOp = ParentReductionOpDSA.DKind != OMPD_unknown;
  12446. if (!IsParentBOK && !IsParentReductionOp) {
  12447. S.Diag(ELoc, diag::err_omp_in_reduction_not_task_reduction);
  12448. continue;
  12449. }
  12450. if ((DeclareReductionRef.isUnset() && IsParentReductionOp) ||
  12451. (DeclareReductionRef.isUsable() && IsParentBOK) || BOK != ParentBOK ||
  12452. IsParentReductionOp) {
  12453. bool EmitError = true;
  12454. if (IsParentReductionOp && DeclareReductionRef.isUsable()) {
  12455. llvm::FoldingSetNodeID RedId, ParentRedId;
  12456. ParentReductionOp->Profile(ParentRedId, Context, /*Canonical=*/true);
  12457. DeclareReductionRef.get()->Profile(RedId, Context,
  12458. /*Canonical=*/true);
  12459. EmitError = RedId != ParentRedId;
  12460. }
  12461. if (EmitError) {
  12462. S.Diag(ReductionId.getBeginLoc(),
  12463. diag::err_omp_reduction_identifier_mismatch)
  12464. << ReductionIdRange << RefExpr->getSourceRange();
  12465. S.Diag(ParentSR.getBegin(),
  12466. diag::note_omp_previous_reduction_identifier)
  12467. << ParentSR
  12468. << (IsParentBOK ? ParentBOKDSA.RefExpr
  12469. : ParentReductionOpDSA.RefExpr)
  12470. ->getSourceRange();
  12471. continue;
  12472. }
  12473. }
  12474. TaskgroupDescriptor = IsParentBOK ? ParentBOKTD : ParentReductionOpTD;
  12475. assert(TaskgroupDescriptor && "Taskgroup descriptor must be defined.");
  12476. }
  12477. DeclRefExpr *Ref = nullptr;
  12478. Expr *VarsExpr = RefExpr->IgnoreParens();
  12479. if (!VD && !S.CurContext->isDependentContext()) {
  12480. if (ASE || OASE) {
  12481. TransformExprToCaptures RebuildToCapture(S, D);
  12482. VarsExpr =
  12483. RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
  12484. Ref = RebuildToCapture.getCapturedExpr();
  12485. } else {
  12486. VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false);
  12487. }
  12488. if (!S.isOpenMPCapturedDecl(D)) {
  12489. RD.ExprCaptures.emplace_back(Ref->getDecl());
  12490. if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
  12491. ExprResult RefRes = S.DefaultLvalueConversion(Ref);
  12492. if (!RefRes.isUsable())
  12493. continue;
  12494. ExprResult PostUpdateRes =
  12495. S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
  12496. RefRes.get());
  12497. if (!PostUpdateRes.isUsable())
  12498. continue;
  12499. if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
  12500. Stack->getCurrentDirective() == OMPD_taskgroup) {
  12501. S.Diag(RefExpr->getExprLoc(),
  12502. diag::err_omp_reduction_non_addressable_expression)
  12503. << RefExpr->getSourceRange();
  12504. continue;
  12505. }
  12506. RD.ExprPostUpdates.emplace_back(
  12507. S.IgnoredValueConversions(PostUpdateRes.get()).get());
  12508. }
  12509. }
  12510. }
  12511. // All reduction items are still marked as reduction (to do not increase
  12512. // code base size).
  12513. Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref);
  12514. if (CurrDir == OMPD_taskgroup) {
  12515. if (DeclareReductionRef.isUsable())
  12516. Stack->addTaskgroupReductionData(D, ReductionIdRange,
  12517. DeclareReductionRef.get());
  12518. else
  12519. Stack->addTaskgroupReductionData(D, ReductionIdRange, BOK);
  12520. }
  12521. RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get(),
  12522. TaskgroupDescriptor);
  12523. }
  12524. return RD.Vars.empty();
  12525. }
  12526. OMPClause *Sema::ActOnOpenMPReductionClause(
  12527. ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
  12528. SourceLocation ColonLoc, SourceLocation EndLoc,
  12529. CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
  12530. ArrayRef<Expr *> UnresolvedReductions) {
  12531. ReductionData RD(VarList.size());
  12532. if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_reduction, VarList,
  12533. StartLoc, LParenLoc, ColonLoc, EndLoc,
  12534. ReductionIdScopeSpec, ReductionId,
  12535. UnresolvedReductions, RD))
  12536. return nullptr;
  12537. return OMPReductionClause::Create(
  12538. Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
  12539. ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
  12540. RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
  12541. buildPreInits(Context, RD.ExprCaptures),
  12542. buildPostUpdate(*this, RD.ExprPostUpdates));
  12543. }
  12544. OMPClause *Sema::ActOnOpenMPTaskReductionClause(
  12545. ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
  12546. SourceLocation ColonLoc, SourceLocation EndLoc,
  12547. CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
  12548. ArrayRef<Expr *> UnresolvedReductions) {
  12549. ReductionData RD(VarList.size());
  12550. if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_task_reduction, VarList,
  12551. StartLoc, LParenLoc, ColonLoc, EndLoc,
  12552. ReductionIdScopeSpec, ReductionId,
  12553. UnresolvedReductions, RD))
  12554. return nullptr;
  12555. return OMPTaskReductionClause::Create(
  12556. Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
  12557. ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
  12558. RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
  12559. buildPreInits(Context, RD.ExprCaptures),
  12560. buildPostUpdate(*this, RD.ExprPostUpdates));
  12561. }
  12562. OMPClause *Sema::ActOnOpenMPInReductionClause(
  12563. ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
  12564. SourceLocation ColonLoc, SourceLocation EndLoc,
  12565. CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
  12566. ArrayRef<Expr *> UnresolvedReductions) {
  12567. ReductionData RD(VarList.size());
  12568. if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_in_reduction, VarList,
  12569. StartLoc, LParenLoc, ColonLoc, EndLoc,
  12570. ReductionIdScopeSpec, ReductionId,
  12571. UnresolvedReductions, RD))
  12572. return nullptr;
  12573. return OMPInReductionClause::Create(
  12574. Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
  12575. ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
  12576. RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.TaskgroupDescriptors,
  12577. buildPreInits(Context, RD.ExprCaptures),
  12578. buildPostUpdate(*this, RD.ExprPostUpdates));
  12579. }
  12580. bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
  12581. SourceLocation LinLoc) {
  12582. if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
  12583. LinKind == OMPC_LINEAR_unknown) {
  12584. Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
  12585. return true;
  12586. }
  12587. return false;
  12588. }
  12589. bool Sema::CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc,
  12590. OpenMPLinearClauseKind LinKind,
  12591. QualType Type) {
  12592. const auto *VD = dyn_cast_or_null<VarDecl>(D);
  12593. // A variable must not have an incomplete type or a reference type.
  12594. if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
  12595. return true;
  12596. if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
  12597. !Type->isReferenceType()) {
  12598. Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
  12599. << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
  12600. return true;
  12601. }
  12602. Type = Type.getNonReferenceType();
  12603. // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
  12604. // A variable that is privatized must not have a const-qualified type
  12605. // unless it is of class type with a mutable member. This restriction does
  12606. // not apply to the firstprivate clause.
  12607. if (rejectConstNotMutableType(*this, D, Type, OMPC_linear, ELoc))
  12608. return true;
  12609. // A list item must be of integral or pointer type.
  12610. Type = Type.getUnqualifiedType().getCanonicalType();
  12611. const auto *Ty = Type.getTypePtrOrNull();
  12612. if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
  12613. !Ty->isPointerType())) {
  12614. Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
  12615. if (D) {
  12616. bool IsDecl =
  12617. !VD ||
  12618. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  12619. Diag(D->getLocation(),
  12620. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  12621. << D;
  12622. }
  12623. return true;
  12624. }
  12625. return false;
  12626. }
  12627. OMPClause *Sema::ActOnOpenMPLinearClause(
  12628. ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
  12629. SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
  12630. SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
  12631. SmallVector<Expr *, 8> Vars;
  12632. SmallVector<Expr *, 8> Privates;
  12633. SmallVector<Expr *, 8> Inits;
  12634. SmallVector<Decl *, 4> ExprCaptures;
  12635. SmallVector<Expr *, 4> ExprPostUpdates;
  12636. if (CheckOpenMPLinearModifier(LinKind, LinLoc))
  12637. LinKind = OMPC_LINEAR_val;
  12638. for (Expr *RefExpr : VarList) {
  12639. assert(RefExpr && "NULL expr in OpenMP linear clause.");
  12640. SourceLocation ELoc;
  12641. SourceRange ERange;
  12642. Expr *SimpleRefExpr = RefExpr;
  12643. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  12644. if (Res.second) {
  12645. // It will be analyzed later.
  12646. Vars.push_back(RefExpr);
  12647. Privates.push_back(nullptr);
  12648. Inits.push_back(nullptr);
  12649. }
  12650. ValueDecl *D = Res.first;
  12651. if (!D)
  12652. continue;
  12653. QualType Type = D->getType();
  12654. auto *VD = dyn_cast<VarDecl>(D);
  12655. // OpenMP [2.14.3.7, linear clause]
  12656. // A list-item cannot appear in more than one linear clause.
  12657. // A list-item that appears in a linear clause cannot appear in any
  12658. // other data-sharing attribute clause.
  12659. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
  12660. if (DVar.RefExpr) {
  12661. Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
  12662. << getOpenMPClauseName(OMPC_linear);
  12663. reportOriginalDsa(*this, DSAStack, D, DVar);
  12664. continue;
  12665. }
  12666. if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
  12667. continue;
  12668. Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
  12669. // Build private copy of original var.
  12670. VarDecl *Private =
  12671. buildVarDecl(*this, ELoc, Type, D->getName(),
  12672. D->hasAttrs() ? &D->getAttrs() : nullptr,
  12673. VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
  12674. DeclRefExpr *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
  12675. // Build var to save initial value.
  12676. VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
  12677. Expr *InitExpr;
  12678. DeclRefExpr *Ref = nullptr;
  12679. if (!VD && !CurContext->isDependentContext()) {
  12680. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
  12681. if (!isOpenMPCapturedDecl(D)) {
  12682. ExprCaptures.push_back(Ref->getDecl());
  12683. if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
  12684. ExprResult RefRes = DefaultLvalueConversion(Ref);
  12685. if (!RefRes.isUsable())
  12686. continue;
  12687. ExprResult PostUpdateRes =
  12688. BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
  12689. SimpleRefExpr, RefRes.get());
  12690. if (!PostUpdateRes.isUsable())
  12691. continue;
  12692. ExprPostUpdates.push_back(
  12693. IgnoredValueConversions(PostUpdateRes.get()).get());
  12694. }
  12695. }
  12696. }
  12697. if (LinKind == OMPC_LINEAR_uval)
  12698. InitExpr = VD ? VD->getInit() : SimpleRefExpr;
  12699. else
  12700. InitExpr = VD ? SimpleRefExpr : Ref;
  12701. AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
  12702. /*DirectInit=*/false);
  12703. DeclRefExpr *InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
  12704. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
  12705. Vars.push_back((VD || CurContext->isDependentContext())
  12706. ? RefExpr->IgnoreParens()
  12707. : Ref);
  12708. Privates.push_back(PrivateRef);
  12709. Inits.push_back(InitRef);
  12710. }
  12711. if (Vars.empty())
  12712. return nullptr;
  12713. Expr *StepExpr = Step;
  12714. Expr *CalcStepExpr = nullptr;
  12715. if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
  12716. !Step->isInstantiationDependent() &&
  12717. !Step->containsUnexpandedParameterPack()) {
  12718. SourceLocation StepLoc = Step->getBeginLoc();
  12719. ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
  12720. if (Val.isInvalid())
  12721. return nullptr;
  12722. StepExpr = Val.get();
  12723. // Build var to save the step value.
  12724. VarDecl *SaveVar =
  12725. buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
  12726. ExprResult SaveRef =
  12727. buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
  12728. ExprResult CalcStep =
  12729. BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
  12730. CalcStep = ActOnFinishFullExpr(CalcStep.get(), /*DiscardedValue*/ false);
  12731. // Warn about zero linear step (it would be probably better specified as
  12732. // making corresponding variables 'const').
  12733. llvm::APSInt Result;
  12734. bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
  12735. if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
  12736. Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
  12737. << (Vars.size() > 1);
  12738. if (!IsConstant && CalcStep.isUsable()) {
  12739. // Calculate the step beforehand instead of doing this on each iteration.
  12740. // (This is not used if the number of iterations may be kfold-ed).
  12741. CalcStepExpr = CalcStep.get();
  12742. }
  12743. }
  12744. return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
  12745. ColonLoc, EndLoc, Vars, Privates, Inits,
  12746. StepExpr, CalcStepExpr,
  12747. buildPreInits(Context, ExprCaptures),
  12748. buildPostUpdate(*this, ExprPostUpdates));
  12749. }
  12750. static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
  12751. Expr *NumIterations, Sema &SemaRef,
  12752. Scope *S, DSAStackTy *Stack) {
  12753. // Walk the vars and build update/final expressions for the CodeGen.
  12754. SmallVector<Expr *, 8> Updates;
  12755. SmallVector<Expr *, 8> Finals;
  12756. SmallVector<Expr *, 8> UsedExprs;
  12757. Expr *Step = Clause.getStep();
  12758. Expr *CalcStep = Clause.getCalcStep();
  12759. // OpenMP [2.14.3.7, linear clause]
  12760. // If linear-step is not specified it is assumed to be 1.
  12761. if (!Step)
  12762. Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
  12763. else if (CalcStep)
  12764. Step = cast<BinaryOperator>(CalcStep)->getLHS();
  12765. bool HasErrors = false;
  12766. auto CurInit = Clause.inits().begin();
  12767. auto CurPrivate = Clause.privates().begin();
  12768. OpenMPLinearClauseKind LinKind = Clause.getModifier();
  12769. for (Expr *RefExpr : Clause.varlists()) {
  12770. SourceLocation ELoc;
  12771. SourceRange ERange;
  12772. Expr *SimpleRefExpr = RefExpr;
  12773. auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange);
  12774. ValueDecl *D = Res.first;
  12775. if (Res.second || !D) {
  12776. Updates.push_back(nullptr);
  12777. Finals.push_back(nullptr);
  12778. HasErrors = true;
  12779. continue;
  12780. }
  12781. auto &&Info = Stack->isLoopControlVariable(D);
  12782. // OpenMP [2.15.11, distribute simd Construct]
  12783. // A list item may not appear in a linear clause, unless it is the loop
  12784. // iteration variable.
  12785. if (isOpenMPDistributeDirective(Stack->getCurrentDirective()) &&
  12786. isOpenMPSimdDirective(Stack->getCurrentDirective()) && !Info.first) {
  12787. SemaRef.Diag(ELoc,
  12788. diag::err_omp_linear_distribute_var_non_loop_iteration);
  12789. Updates.push_back(nullptr);
  12790. Finals.push_back(nullptr);
  12791. HasErrors = true;
  12792. continue;
  12793. }
  12794. Expr *InitExpr = *CurInit;
  12795. // Build privatized reference to the current linear var.
  12796. auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
  12797. Expr *CapturedRef;
  12798. if (LinKind == OMPC_LINEAR_uval)
  12799. CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
  12800. else
  12801. CapturedRef =
  12802. buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
  12803. DE->getType().getUnqualifiedType(), DE->getExprLoc(),
  12804. /*RefersToCapture=*/true);
  12805. // Build update: Var = InitExpr + IV * Step
  12806. ExprResult Update;
  12807. if (!Info.first)
  12808. Update = buildCounterUpdate(
  12809. SemaRef, S, RefExpr->getExprLoc(), *CurPrivate, InitExpr, IV, Step,
  12810. /*Subtract=*/false, /*IsNonRectangularLB=*/false);
  12811. else
  12812. Update = *CurPrivate;
  12813. Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getBeginLoc(),
  12814. /*DiscardedValue*/ false);
  12815. // Build final: Var = InitExpr + NumIterations * Step
  12816. ExprResult Final;
  12817. if (!Info.first)
  12818. Final =
  12819. buildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
  12820. InitExpr, NumIterations, Step, /*Subtract=*/false,
  12821. /*IsNonRectangularLB=*/false);
  12822. else
  12823. Final = *CurPrivate;
  12824. Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getBeginLoc(),
  12825. /*DiscardedValue*/ false);
  12826. if (!Update.isUsable() || !Final.isUsable()) {
  12827. Updates.push_back(nullptr);
  12828. Finals.push_back(nullptr);
  12829. UsedExprs.push_back(nullptr);
  12830. HasErrors = true;
  12831. } else {
  12832. Updates.push_back(Update.get());
  12833. Finals.push_back(Final.get());
  12834. if (!Info.first)
  12835. UsedExprs.push_back(SimpleRefExpr);
  12836. }
  12837. ++CurInit;
  12838. ++CurPrivate;
  12839. }
  12840. if (Expr *S = Clause.getStep())
  12841. UsedExprs.push_back(S);
  12842. // Fill the remaining part with the nullptr.
  12843. UsedExprs.append(Clause.varlist_size() + 1 - UsedExprs.size(), nullptr);
  12844. Clause.setUpdates(Updates);
  12845. Clause.setFinals(Finals);
  12846. Clause.setUsedExprs(UsedExprs);
  12847. return HasErrors;
  12848. }
  12849. OMPClause *Sema::ActOnOpenMPAlignedClause(
  12850. ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
  12851. SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
  12852. SmallVector<Expr *, 8> Vars;
  12853. for (Expr *RefExpr : VarList) {
  12854. assert(RefExpr && "NULL expr in OpenMP linear clause.");
  12855. SourceLocation ELoc;
  12856. SourceRange ERange;
  12857. Expr *SimpleRefExpr = RefExpr;
  12858. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  12859. if (Res.second) {
  12860. // It will be analyzed later.
  12861. Vars.push_back(RefExpr);
  12862. }
  12863. ValueDecl *D = Res.first;
  12864. if (!D)
  12865. continue;
  12866. QualType QType = D->getType();
  12867. auto *VD = dyn_cast<VarDecl>(D);
  12868. // OpenMP [2.8.1, simd construct, Restrictions]
  12869. // The type of list items appearing in the aligned clause must be
  12870. // array, pointer, reference to array, or reference to pointer.
  12871. QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
  12872. const Type *Ty = QType.getTypePtrOrNull();
  12873. if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
  12874. Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
  12875. << QType << getLangOpts().CPlusPlus << ERange;
  12876. bool IsDecl =
  12877. !VD ||
  12878. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  12879. Diag(D->getLocation(),
  12880. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  12881. << D;
  12882. continue;
  12883. }
  12884. // OpenMP [2.8.1, simd construct, Restrictions]
  12885. // A list-item cannot appear in more than one aligned clause.
  12886. if (const Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
  12887. Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange;
  12888. Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
  12889. << getOpenMPClauseName(OMPC_aligned);
  12890. continue;
  12891. }
  12892. DeclRefExpr *Ref = nullptr;
  12893. if (!VD && isOpenMPCapturedDecl(D))
  12894. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
  12895. Vars.push_back(DefaultFunctionArrayConversion(
  12896. (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
  12897. .get());
  12898. }
  12899. // OpenMP [2.8.1, simd construct, Description]
  12900. // The parameter of the aligned clause, alignment, must be a constant
  12901. // positive integer expression.
  12902. // If no optional parameter is specified, implementation-defined default
  12903. // alignments for SIMD instructions on the target platforms are assumed.
  12904. if (Alignment != nullptr) {
  12905. ExprResult AlignResult =
  12906. VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
  12907. if (AlignResult.isInvalid())
  12908. return nullptr;
  12909. Alignment = AlignResult.get();
  12910. }
  12911. if (Vars.empty())
  12912. return nullptr;
  12913. return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
  12914. EndLoc, Vars, Alignment);
  12915. }
  12916. OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
  12917. SourceLocation StartLoc,
  12918. SourceLocation LParenLoc,
  12919. SourceLocation EndLoc) {
  12920. SmallVector<Expr *, 8> Vars;
  12921. SmallVector<Expr *, 8> SrcExprs;
  12922. SmallVector<Expr *, 8> DstExprs;
  12923. SmallVector<Expr *, 8> AssignmentOps;
  12924. for (Expr *RefExpr : VarList) {
  12925. assert(RefExpr && "NULL expr in OpenMP copyin clause.");
  12926. if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
  12927. // It will be analyzed later.
  12928. Vars.push_back(RefExpr);
  12929. SrcExprs.push_back(nullptr);
  12930. DstExprs.push_back(nullptr);
  12931. AssignmentOps.push_back(nullptr);
  12932. continue;
  12933. }
  12934. SourceLocation ELoc = RefExpr->getExprLoc();
  12935. // OpenMP [2.1, C/C++]
  12936. // A list item is a variable name.
  12937. // OpenMP [2.14.4.1, Restrictions, p.1]
  12938. // A list item that appears in a copyin clause must be threadprivate.
  12939. auto *DE = dyn_cast<DeclRefExpr>(RefExpr);
  12940. if (!DE || !isa<VarDecl>(DE->getDecl())) {
  12941. Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
  12942. << 0 << RefExpr->getSourceRange();
  12943. continue;
  12944. }
  12945. Decl *D = DE->getDecl();
  12946. auto *VD = cast<VarDecl>(D);
  12947. QualType Type = VD->getType();
  12948. if (Type->isDependentType() || Type->isInstantiationDependentType()) {
  12949. // It will be analyzed later.
  12950. Vars.push_back(DE);
  12951. SrcExprs.push_back(nullptr);
  12952. DstExprs.push_back(nullptr);
  12953. AssignmentOps.push_back(nullptr);
  12954. continue;
  12955. }
  12956. // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
  12957. // A list item that appears in a copyin clause must be threadprivate.
  12958. if (!DSAStack->isThreadPrivate(VD)) {
  12959. Diag(ELoc, diag::err_omp_required_access)
  12960. << getOpenMPClauseName(OMPC_copyin)
  12961. << getOpenMPDirectiveName(OMPD_threadprivate);
  12962. continue;
  12963. }
  12964. // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
  12965. // A variable of class type (or array thereof) that appears in a
  12966. // copyin clause requires an accessible, unambiguous copy assignment
  12967. // operator for the class type.
  12968. QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
  12969. VarDecl *SrcVD =
  12970. buildVarDecl(*this, DE->getBeginLoc(), ElemType.getUnqualifiedType(),
  12971. ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
  12972. DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(
  12973. *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
  12974. VarDecl *DstVD =
  12975. buildVarDecl(*this, DE->getBeginLoc(), ElemType, ".copyin.dst",
  12976. VD->hasAttrs() ? &VD->getAttrs() : nullptr);
  12977. DeclRefExpr *PseudoDstExpr =
  12978. buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
  12979. // For arrays generate assignment operation for single element and replace
  12980. // it by the original array element in CodeGen.
  12981. ExprResult AssignmentOp =
  12982. BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign, PseudoDstExpr,
  12983. PseudoSrcExpr);
  12984. if (AssignmentOp.isInvalid())
  12985. continue;
  12986. AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
  12987. /*DiscardedValue*/ false);
  12988. if (AssignmentOp.isInvalid())
  12989. continue;
  12990. DSAStack->addDSA(VD, DE, OMPC_copyin);
  12991. Vars.push_back(DE);
  12992. SrcExprs.push_back(PseudoSrcExpr);
  12993. DstExprs.push_back(PseudoDstExpr);
  12994. AssignmentOps.push_back(AssignmentOp.get());
  12995. }
  12996. if (Vars.empty())
  12997. return nullptr;
  12998. return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
  12999. SrcExprs, DstExprs, AssignmentOps);
  13000. }
  13001. OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
  13002. SourceLocation StartLoc,
  13003. SourceLocation LParenLoc,
  13004. SourceLocation EndLoc) {
  13005. SmallVector<Expr *, 8> Vars;
  13006. SmallVector<Expr *, 8> SrcExprs;
  13007. SmallVector<Expr *, 8> DstExprs;
  13008. SmallVector<Expr *, 8> AssignmentOps;
  13009. for (Expr *RefExpr : VarList) {
  13010. assert(RefExpr && "NULL expr in OpenMP linear clause.");
  13011. SourceLocation ELoc;
  13012. SourceRange ERange;
  13013. Expr *SimpleRefExpr = RefExpr;
  13014. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  13015. if (Res.second) {
  13016. // It will be analyzed later.
  13017. Vars.push_back(RefExpr);
  13018. SrcExprs.push_back(nullptr);
  13019. DstExprs.push_back(nullptr);
  13020. AssignmentOps.push_back(nullptr);
  13021. }
  13022. ValueDecl *D = Res.first;
  13023. if (!D)
  13024. continue;
  13025. QualType Type = D->getType();
  13026. auto *VD = dyn_cast<VarDecl>(D);
  13027. // OpenMP [2.14.4.2, Restrictions, p.2]
  13028. // A list item that appears in a copyprivate clause may not appear in a
  13029. // private or firstprivate clause on the single construct.
  13030. if (!VD || !DSAStack->isThreadPrivate(VD)) {
  13031. DSAStackTy::DSAVarData DVar =
  13032. DSAStack->getTopDSA(D, /*FromParent=*/false);
  13033. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
  13034. DVar.RefExpr) {
  13035. Diag(ELoc, diag::err_omp_wrong_dsa)
  13036. << getOpenMPClauseName(DVar.CKind)
  13037. << getOpenMPClauseName(OMPC_copyprivate);
  13038. reportOriginalDsa(*this, DSAStack, D, DVar);
  13039. continue;
  13040. }
  13041. // OpenMP [2.11.4.2, Restrictions, p.1]
  13042. // All list items that appear in a copyprivate clause must be either
  13043. // threadprivate or private in the enclosing context.
  13044. if (DVar.CKind == OMPC_unknown) {
  13045. DVar = DSAStack->getImplicitDSA(D, false);
  13046. if (DVar.CKind == OMPC_shared) {
  13047. Diag(ELoc, diag::err_omp_required_access)
  13048. << getOpenMPClauseName(OMPC_copyprivate)
  13049. << "threadprivate or private in the enclosing context";
  13050. reportOriginalDsa(*this, DSAStack, D, DVar);
  13051. continue;
  13052. }
  13053. }
  13054. }
  13055. // Variably modified types are not supported.
  13056. if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
  13057. Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
  13058. << getOpenMPClauseName(OMPC_copyprivate) << Type
  13059. << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
  13060. bool IsDecl =
  13061. !VD ||
  13062. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  13063. Diag(D->getLocation(),
  13064. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  13065. << D;
  13066. continue;
  13067. }
  13068. // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
  13069. // A variable of class type (or array thereof) that appears in a
  13070. // copyin clause requires an accessible, unambiguous copy assignment
  13071. // operator for the class type.
  13072. Type = Context.getBaseElementType(Type.getNonReferenceType())
  13073. .getUnqualifiedType();
  13074. VarDecl *SrcVD =
  13075. buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.src",
  13076. D->hasAttrs() ? &D->getAttrs() : nullptr);
  13077. DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
  13078. VarDecl *DstVD =
  13079. buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.dst",
  13080. D->hasAttrs() ? &D->getAttrs() : nullptr);
  13081. DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
  13082. ExprResult AssignmentOp = BuildBinOp(
  13083. DSAStack->getCurScope(), ELoc, BO_Assign, PseudoDstExpr, PseudoSrcExpr);
  13084. if (AssignmentOp.isInvalid())
  13085. continue;
  13086. AssignmentOp =
  13087. ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
  13088. if (AssignmentOp.isInvalid())
  13089. continue;
  13090. // No need to mark vars as copyprivate, they are already threadprivate or
  13091. // implicitly private.
  13092. assert(VD || isOpenMPCapturedDecl(D));
  13093. Vars.push_back(
  13094. VD ? RefExpr->IgnoreParens()
  13095. : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
  13096. SrcExprs.push_back(PseudoSrcExpr);
  13097. DstExprs.push_back(PseudoDstExpr);
  13098. AssignmentOps.push_back(AssignmentOp.get());
  13099. }
  13100. if (Vars.empty())
  13101. return nullptr;
  13102. return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  13103. Vars, SrcExprs, DstExprs, AssignmentOps);
  13104. }
  13105. OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
  13106. SourceLocation StartLoc,
  13107. SourceLocation LParenLoc,
  13108. SourceLocation EndLoc) {
  13109. if (VarList.empty())
  13110. return nullptr;
  13111. return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
  13112. }
  13113. OMPClause *
  13114. Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
  13115. SourceLocation DepLoc, SourceLocation ColonLoc,
  13116. ArrayRef<Expr *> VarList, SourceLocation StartLoc,
  13117. SourceLocation LParenLoc, SourceLocation EndLoc) {
  13118. if (DSAStack->getCurrentDirective() == OMPD_ordered &&
  13119. DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
  13120. Diag(DepLoc, diag::err_omp_unexpected_clause_value)
  13121. << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
  13122. return nullptr;
  13123. }
  13124. if (DSAStack->getCurrentDirective() != OMPD_ordered &&
  13125. (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
  13126. DepKind == OMPC_DEPEND_sink)) {
  13127. unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink};
  13128. Diag(DepLoc, diag::err_omp_unexpected_clause_value)
  13129. << getListOfPossibleValues(OMPC_depend, /*First=*/0,
  13130. /*Last=*/OMPC_DEPEND_unknown, Except)
  13131. << getOpenMPClauseName(OMPC_depend);
  13132. return nullptr;
  13133. }
  13134. SmallVector<Expr *, 8> Vars;
  13135. DSAStackTy::OperatorOffsetTy OpsOffs;
  13136. llvm::APSInt DepCounter(/*BitWidth=*/32);
  13137. llvm::APSInt TotalDepCount(/*BitWidth=*/32);
  13138. if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) {
  13139. if (const Expr *OrderedCountExpr =
  13140. DSAStack->getParentOrderedRegionParam().first) {
  13141. TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
  13142. TotalDepCount.setIsUnsigned(/*Val=*/true);
  13143. }
  13144. }
  13145. for (Expr *RefExpr : VarList) {
  13146. assert(RefExpr && "NULL expr in OpenMP shared clause.");
  13147. if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
  13148. // It will be analyzed later.
  13149. Vars.push_back(RefExpr);
  13150. continue;
  13151. }
  13152. SourceLocation ELoc = RefExpr->getExprLoc();
  13153. Expr *SimpleExpr = RefExpr->IgnoreParenCasts();
  13154. if (DepKind == OMPC_DEPEND_sink) {
  13155. if (DSAStack->getParentOrderedRegionParam().first &&
  13156. DepCounter >= TotalDepCount) {
  13157. Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
  13158. continue;
  13159. }
  13160. ++DepCounter;
  13161. // OpenMP [2.13.9, Summary]
  13162. // depend(dependence-type : vec), where dependence-type is:
  13163. // 'sink' and where vec is the iteration vector, which has the form:
  13164. // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
  13165. // where n is the value specified by the ordered clause in the loop
  13166. // directive, xi denotes the loop iteration variable of the i-th nested
  13167. // loop associated with the loop directive, and di is a constant
  13168. // non-negative integer.
  13169. if (CurContext->isDependentContext()) {
  13170. // It will be analyzed later.
  13171. Vars.push_back(RefExpr);
  13172. continue;
  13173. }
  13174. SimpleExpr = SimpleExpr->IgnoreImplicit();
  13175. OverloadedOperatorKind OOK = OO_None;
  13176. SourceLocation OOLoc;
  13177. Expr *LHS = SimpleExpr;
  13178. Expr *RHS = nullptr;
  13179. if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
  13180. OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
  13181. OOLoc = BO->getOperatorLoc();
  13182. LHS = BO->getLHS()->IgnoreParenImpCasts();
  13183. RHS = BO->getRHS()->IgnoreParenImpCasts();
  13184. } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
  13185. OOK = OCE->getOperator();
  13186. OOLoc = OCE->getOperatorLoc();
  13187. LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
  13188. RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
  13189. } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
  13190. OOK = MCE->getMethodDecl()
  13191. ->getNameInfo()
  13192. .getName()
  13193. .getCXXOverloadedOperator();
  13194. OOLoc = MCE->getCallee()->getExprLoc();
  13195. LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
  13196. RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
  13197. }
  13198. SourceLocation ELoc;
  13199. SourceRange ERange;
  13200. auto Res = getPrivateItem(*this, LHS, ELoc, ERange);
  13201. if (Res.second) {
  13202. // It will be analyzed later.
  13203. Vars.push_back(RefExpr);
  13204. }
  13205. ValueDecl *D = Res.first;
  13206. if (!D)
  13207. continue;
  13208. if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
  13209. Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
  13210. continue;
  13211. }
  13212. if (RHS) {
  13213. ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
  13214. RHS, OMPC_depend, /*StrictlyPositive=*/false);
  13215. if (RHSRes.isInvalid())
  13216. continue;
  13217. }
  13218. if (!CurContext->isDependentContext() &&
  13219. DSAStack->getParentOrderedRegionParam().first &&
  13220. DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
  13221. const ValueDecl *VD =
  13222. DSAStack->getParentLoopControlVariable(DepCounter.getZExtValue());
  13223. if (VD)
  13224. Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
  13225. << 1 << VD;
  13226. else
  13227. Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) << 0;
  13228. continue;
  13229. }
  13230. OpsOffs.emplace_back(RHS, OOK);
  13231. } else {
  13232. auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
  13233. if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
  13234. (ASE &&
  13235. !ASE->getBase()->getType().getNonReferenceType()->isPointerType() &&
  13236. !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
  13237. Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
  13238. << RefExpr->getSourceRange();
  13239. continue;
  13240. }
  13241. ExprResult Res;
  13242. {
  13243. Sema::TentativeAnalysisScope Trap(*this);
  13244. Res = CreateBuiltinUnaryOp(ELoc, UO_AddrOf,
  13245. RefExpr->IgnoreParenImpCasts());
  13246. }
  13247. if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr)) {
  13248. Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
  13249. << RefExpr->getSourceRange();
  13250. continue;
  13251. }
  13252. }
  13253. Vars.push_back(RefExpr->IgnoreParenImpCasts());
  13254. }
  13255. if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
  13256. TotalDepCount > VarList.size() &&
  13257. DSAStack->getParentOrderedRegionParam().first &&
  13258. DSAStack->getParentLoopControlVariable(VarList.size() + 1)) {
  13259. Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration)
  13260. << 1 << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
  13261. }
  13262. if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
  13263. Vars.empty())
  13264. return nullptr;
  13265. auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  13266. DepKind, DepLoc, ColonLoc, Vars,
  13267. TotalDepCount.getZExtValue());
  13268. if ((DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) &&
  13269. DSAStack->isParentOrderedRegion())
  13270. DSAStack->addDoacrossDependClause(C, OpsOffs);
  13271. return C;
  13272. }
  13273. OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
  13274. SourceLocation LParenLoc,
  13275. SourceLocation EndLoc) {
  13276. Expr *ValExpr = Device;
  13277. Stmt *HelperValStmt = nullptr;
  13278. // OpenMP [2.9.1, Restrictions]
  13279. // The device expression must evaluate to a non-negative integer value.
  13280. if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
  13281. /*StrictlyPositive=*/false))
  13282. return nullptr;
  13283. OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
  13284. OpenMPDirectiveKind CaptureRegion =
  13285. getOpenMPCaptureRegionForClause(DKind, OMPC_device);
  13286. if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
  13287. ValExpr = MakeFullExpr(ValExpr).get();
  13288. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  13289. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  13290. HelperValStmt = buildPreInits(Context, Captures);
  13291. }
  13292. return new (Context) OMPDeviceClause(ValExpr, HelperValStmt, CaptureRegion,
  13293. StartLoc, LParenLoc, EndLoc);
  13294. }
  13295. static bool checkTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
  13296. DSAStackTy *Stack, QualType QTy,
  13297. bool FullCheck = true) {
  13298. NamedDecl *ND;
  13299. if (QTy->isIncompleteType(&ND)) {
  13300. SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
  13301. return false;
  13302. }
  13303. if (FullCheck && !SemaRef.CurContext->isDependentContext() &&
  13304. !QTy.isTrivialType(SemaRef.Context))
  13305. SemaRef.Diag(SL, diag::warn_omp_non_trivial_type_mapped) << QTy << SR;
  13306. return true;
  13307. }
  13308. /// Return true if it can be proven that the provided array expression
  13309. /// (array section or array subscript) does NOT specify the whole size of the
  13310. /// array whose base type is \a BaseQTy.
  13311. static bool checkArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
  13312. const Expr *E,
  13313. QualType BaseQTy) {
  13314. const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
  13315. // If this is an array subscript, it refers to the whole size if the size of
  13316. // the dimension is constant and equals 1. Also, an array section assumes the
  13317. // format of an array subscript if no colon is used.
  13318. if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) {
  13319. if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
  13320. return ATy->getSize().getSExtValue() != 1;
  13321. // Size can't be evaluated statically.
  13322. return false;
  13323. }
  13324. assert(OASE && "Expecting array section if not an array subscript.");
  13325. const Expr *LowerBound = OASE->getLowerBound();
  13326. const Expr *Length = OASE->getLength();
  13327. // If there is a lower bound that does not evaluates to zero, we are not
  13328. // covering the whole dimension.
  13329. if (LowerBound) {
  13330. Expr::EvalResult Result;
  13331. if (!LowerBound->EvaluateAsInt(Result, SemaRef.getASTContext()))
  13332. return false; // Can't get the integer value as a constant.
  13333. llvm::APSInt ConstLowerBound = Result.Val.getInt();
  13334. if (ConstLowerBound.getSExtValue())
  13335. return true;
  13336. }
  13337. // If we don't have a length we covering the whole dimension.
  13338. if (!Length)
  13339. return false;
  13340. // If the base is a pointer, we don't have a way to get the size of the
  13341. // pointee.
  13342. if (BaseQTy->isPointerType())
  13343. return false;
  13344. // We can only check if the length is the same as the size of the dimension
  13345. // if we have a constant array.
  13346. const auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
  13347. if (!CATy)
  13348. return false;
  13349. Expr::EvalResult Result;
  13350. if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
  13351. return false; // Can't get the integer value as a constant.
  13352. llvm::APSInt ConstLength = Result.Val.getInt();
  13353. return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
  13354. }
  13355. // Return true if it can be proven that the provided array expression (array
  13356. // section or array subscript) does NOT specify a single element of the array
  13357. // whose base type is \a BaseQTy.
  13358. static bool checkArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
  13359. const Expr *E,
  13360. QualType BaseQTy) {
  13361. const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
  13362. // An array subscript always refer to a single element. Also, an array section
  13363. // assumes the format of an array subscript if no colon is used.
  13364. if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid()))
  13365. return false;
  13366. assert(OASE && "Expecting array section if not an array subscript.");
  13367. const Expr *Length = OASE->getLength();
  13368. // If we don't have a length we have to check if the array has unitary size
  13369. // for this dimension. Also, we should always expect a length if the base type
  13370. // is pointer.
  13371. if (!Length) {
  13372. if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
  13373. return ATy->getSize().getSExtValue() != 1;
  13374. // We cannot assume anything.
  13375. return false;
  13376. }
  13377. // Check if the length evaluates to 1.
  13378. Expr::EvalResult Result;
  13379. if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
  13380. return false; // Can't get the integer value as a constant.
  13381. llvm::APSInt ConstLength = Result.Val.getInt();
  13382. return ConstLength.getSExtValue() != 1;
  13383. }
  13384. // Return the expression of the base of the mappable expression or null if it
  13385. // cannot be determined and do all the necessary checks to see if the expression
  13386. // is valid as a standalone mappable expression. In the process, record all the
  13387. // components of the expression.
  13388. static const Expr *checkMapClauseExpressionBase(
  13389. Sema &SemaRef, Expr *E,
  13390. OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
  13391. OpenMPClauseKind CKind, bool NoDiagnose) {
  13392. SourceLocation ELoc = E->getExprLoc();
  13393. SourceRange ERange = E->getSourceRange();
  13394. // The base of elements of list in a map clause have to be either:
  13395. // - a reference to variable or field.
  13396. // - a member expression.
  13397. // - an array expression.
  13398. //
  13399. // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
  13400. // reference to 'r'.
  13401. //
  13402. // If we have:
  13403. //
  13404. // struct SS {
  13405. // Bla S;
  13406. // foo() {
  13407. // #pragma omp target map (S.Arr[:12]);
  13408. // }
  13409. // }
  13410. //
  13411. // We want to retrieve the member expression 'this->S';
  13412. const Expr *RelevantExpr = nullptr;
  13413. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2]
  13414. // If a list item is an array section, it must specify contiguous storage.
  13415. //
  13416. // For this restriction it is sufficient that we make sure only references
  13417. // to variables or fields and array expressions, and that no array sections
  13418. // exist except in the rightmost expression (unless they cover the whole
  13419. // dimension of the array). E.g. these would be invalid:
  13420. //
  13421. // r.ArrS[3:5].Arr[6:7]
  13422. //
  13423. // r.ArrS[3:5].x
  13424. //
  13425. // but these would be valid:
  13426. // r.ArrS[3].Arr[6:7]
  13427. //
  13428. // r.ArrS[3].x
  13429. bool AllowUnitySizeArraySection = true;
  13430. bool AllowWholeSizeArraySection = true;
  13431. while (!RelevantExpr) {
  13432. E = E->IgnoreParenImpCasts();
  13433. if (auto *CurE = dyn_cast<DeclRefExpr>(E)) {
  13434. if (!isa<VarDecl>(CurE->getDecl()))
  13435. return nullptr;
  13436. RelevantExpr = CurE;
  13437. // If we got a reference to a declaration, we should not expect any array
  13438. // section before that.
  13439. AllowUnitySizeArraySection = false;
  13440. AllowWholeSizeArraySection = false;
  13441. // Record the component.
  13442. CurComponents.emplace_back(CurE, CurE->getDecl());
  13443. } else if (auto *CurE = dyn_cast<MemberExpr>(E)) {
  13444. Expr *BaseE = CurE->getBase()->IgnoreParenImpCasts();
  13445. if (isa<CXXThisExpr>(BaseE))
  13446. // We found a base expression: this->Val.
  13447. RelevantExpr = CurE;
  13448. else
  13449. E = BaseE;
  13450. if (!isa<FieldDecl>(CurE->getMemberDecl())) {
  13451. if (!NoDiagnose) {
  13452. SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
  13453. << CurE->getSourceRange();
  13454. return nullptr;
  13455. }
  13456. if (RelevantExpr)
  13457. return nullptr;
  13458. continue;
  13459. }
  13460. auto *FD = cast<FieldDecl>(CurE->getMemberDecl());
  13461. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
  13462. // A bit-field cannot appear in a map clause.
  13463. //
  13464. if (FD->isBitField()) {
  13465. if (!NoDiagnose) {
  13466. SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
  13467. << CurE->getSourceRange() << getOpenMPClauseName(CKind);
  13468. return nullptr;
  13469. }
  13470. if (RelevantExpr)
  13471. return nullptr;
  13472. continue;
  13473. }
  13474. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
  13475. // If the type of a list item is a reference to a type T then the type
  13476. // will be considered to be T for all purposes of this clause.
  13477. QualType CurType = BaseE->getType().getNonReferenceType();
  13478. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
  13479. // A list item cannot be a variable that is a member of a structure with
  13480. // a union type.
  13481. //
  13482. if (CurType->isUnionType()) {
  13483. if (!NoDiagnose) {
  13484. SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
  13485. << CurE->getSourceRange();
  13486. return nullptr;
  13487. }
  13488. continue;
  13489. }
  13490. // If we got a member expression, we should not expect any array section
  13491. // before that:
  13492. //
  13493. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
  13494. // If a list item is an element of a structure, only the rightmost symbol
  13495. // of the variable reference can be an array section.
  13496. //
  13497. AllowUnitySizeArraySection = false;
  13498. AllowWholeSizeArraySection = false;
  13499. // Record the component.
  13500. CurComponents.emplace_back(CurE, FD);
  13501. } else if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) {
  13502. E = CurE->getBase()->IgnoreParenImpCasts();
  13503. if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
  13504. if (!NoDiagnose) {
  13505. SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
  13506. << 0 << CurE->getSourceRange();
  13507. return nullptr;
  13508. }
  13509. continue;
  13510. }
  13511. // If we got an array subscript that express the whole dimension we
  13512. // can have any array expressions before. If it only expressing part of
  13513. // the dimension, we can only have unitary-size array expressions.
  13514. if (checkArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE,
  13515. E->getType()))
  13516. AllowWholeSizeArraySection = false;
  13517. if (const auto *TE = dyn_cast<CXXThisExpr>(E)) {
  13518. Expr::EvalResult Result;
  13519. if (CurE->getIdx()->EvaluateAsInt(Result, SemaRef.getASTContext())) {
  13520. if (!Result.Val.getInt().isNullValue()) {
  13521. SemaRef.Diag(CurE->getIdx()->getExprLoc(),
  13522. diag::err_omp_invalid_map_this_expr);
  13523. SemaRef.Diag(CurE->getIdx()->getExprLoc(),
  13524. diag::note_omp_invalid_subscript_on_this_ptr_map);
  13525. }
  13526. }
  13527. RelevantExpr = TE;
  13528. }
  13529. // Record the component - we don't have any declaration associated.
  13530. CurComponents.emplace_back(CurE, nullptr);
  13531. } else if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) {
  13532. assert(!NoDiagnose && "Array sections cannot be implicitly mapped.");
  13533. E = CurE->getBase()->IgnoreParenImpCasts();
  13534. QualType CurType =
  13535. OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
  13536. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
  13537. // If the type of a list item is a reference to a type T then the type
  13538. // will be considered to be T for all purposes of this clause.
  13539. if (CurType->isReferenceType())
  13540. CurType = CurType->getPointeeType();
  13541. bool IsPointer = CurType->isAnyPointerType();
  13542. if (!IsPointer && !CurType->isArrayType()) {
  13543. SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
  13544. << 0 << CurE->getSourceRange();
  13545. return nullptr;
  13546. }
  13547. bool NotWhole =
  13548. checkArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType);
  13549. bool NotUnity =
  13550. checkArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType);
  13551. if (AllowWholeSizeArraySection) {
  13552. // Any array section is currently allowed. Allowing a whole size array
  13553. // section implies allowing a unity array section as well.
  13554. //
  13555. // If this array section refers to the whole dimension we can still
  13556. // accept other array sections before this one, except if the base is a
  13557. // pointer. Otherwise, only unitary sections are accepted.
  13558. if (NotWhole || IsPointer)
  13559. AllowWholeSizeArraySection = false;
  13560. } else if (AllowUnitySizeArraySection && NotUnity) {
  13561. // A unity or whole array section is not allowed and that is not
  13562. // compatible with the properties of the current array section.
  13563. SemaRef.Diag(
  13564. ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
  13565. << CurE->getSourceRange();
  13566. return nullptr;
  13567. }
  13568. if (const auto *TE = dyn_cast<CXXThisExpr>(E)) {
  13569. Expr::EvalResult ResultR;
  13570. Expr::EvalResult ResultL;
  13571. if (CurE->getLength()->EvaluateAsInt(ResultR,
  13572. SemaRef.getASTContext())) {
  13573. if (!ResultR.Val.getInt().isOneValue()) {
  13574. SemaRef.Diag(CurE->getLength()->getExprLoc(),
  13575. diag::err_omp_invalid_map_this_expr);
  13576. SemaRef.Diag(CurE->getLength()->getExprLoc(),
  13577. diag::note_omp_invalid_length_on_this_ptr_mapping);
  13578. }
  13579. }
  13580. if (CurE->getLowerBound() && CurE->getLowerBound()->EvaluateAsInt(
  13581. ResultL, SemaRef.getASTContext())) {
  13582. if (!ResultL.Val.getInt().isNullValue()) {
  13583. SemaRef.Diag(CurE->getLowerBound()->getExprLoc(),
  13584. diag::err_omp_invalid_map_this_expr);
  13585. SemaRef.Diag(CurE->getLowerBound()->getExprLoc(),
  13586. diag::note_omp_invalid_lower_bound_on_this_ptr_mapping);
  13587. }
  13588. }
  13589. RelevantExpr = TE;
  13590. }
  13591. // Record the component - we don't have any declaration associated.
  13592. CurComponents.emplace_back(CurE, nullptr);
  13593. } else {
  13594. if (!NoDiagnose) {
  13595. // If nothing else worked, this is not a valid map clause expression.
  13596. SemaRef.Diag(
  13597. ELoc, diag::err_omp_expected_named_var_member_or_array_expression)
  13598. << ERange;
  13599. }
  13600. return nullptr;
  13601. }
  13602. }
  13603. return RelevantExpr;
  13604. }
  13605. // Return true if expression E associated with value VD has conflicts with other
  13606. // map information.
  13607. static bool checkMapConflicts(
  13608. Sema &SemaRef, DSAStackTy *DSAS, const ValueDecl *VD, const Expr *E,
  13609. bool CurrentRegionOnly,
  13610. OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
  13611. OpenMPClauseKind CKind) {
  13612. assert(VD && E);
  13613. SourceLocation ELoc = E->getExprLoc();
  13614. SourceRange ERange = E->getSourceRange();
  13615. // In order to easily check the conflicts we need to match each component of
  13616. // the expression under test with the components of the expressions that are
  13617. // already in the stack.
  13618. assert(!CurComponents.empty() && "Map clause expression with no components!");
  13619. assert(CurComponents.back().getAssociatedDeclaration() == VD &&
  13620. "Map clause expression with unexpected base!");
  13621. // Variables to help detecting enclosing problems in data environment nests.
  13622. bool IsEnclosedByDataEnvironmentExpr = false;
  13623. const Expr *EnclosingExpr = nullptr;
  13624. bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
  13625. VD, CurrentRegionOnly,
  13626. [&IsEnclosedByDataEnvironmentExpr, &SemaRef, VD, CurrentRegionOnly, ELoc,
  13627. ERange, CKind, &EnclosingExpr,
  13628. CurComponents](OMPClauseMappableExprCommon::MappableExprComponentListRef
  13629. StackComponents,
  13630. OpenMPClauseKind) {
  13631. assert(!StackComponents.empty() &&
  13632. "Map clause expression with no components!");
  13633. assert(StackComponents.back().getAssociatedDeclaration() == VD &&
  13634. "Map clause expression with unexpected base!");
  13635. (void)VD;
  13636. // The whole expression in the stack.
  13637. const Expr *RE = StackComponents.front().getAssociatedExpression();
  13638. // Expressions must start from the same base. Here we detect at which
  13639. // point both expressions diverge from each other and see if we can
  13640. // detect if the memory referred to both expressions is contiguous and
  13641. // do not overlap.
  13642. auto CI = CurComponents.rbegin();
  13643. auto CE = CurComponents.rend();
  13644. auto SI = StackComponents.rbegin();
  13645. auto SE = StackComponents.rend();
  13646. for (; CI != CE && SI != SE; ++CI, ++SI) {
  13647. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
  13648. // At most one list item can be an array item derived from a given
  13649. // variable in map clauses of the same construct.
  13650. if (CurrentRegionOnly &&
  13651. (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
  13652. isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) &&
  13653. (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
  13654. isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) {
  13655. SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
  13656. diag::err_omp_multiple_array_items_in_map_clause)
  13657. << CI->getAssociatedExpression()->getSourceRange();
  13658. SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
  13659. diag::note_used_here)
  13660. << SI->getAssociatedExpression()->getSourceRange();
  13661. return true;
  13662. }
  13663. // Do both expressions have the same kind?
  13664. if (CI->getAssociatedExpression()->getStmtClass() !=
  13665. SI->getAssociatedExpression()->getStmtClass())
  13666. break;
  13667. // Are we dealing with different variables/fields?
  13668. if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
  13669. break;
  13670. }
  13671. // Check if the extra components of the expressions in the enclosing
  13672. // data environment are redundant for the current base declaration.
  13673. // If they are, the maps completely overlap, which is legal.
  13674. for (; SI != SE; ++SI) {
  13675. QualType Type;
  13676. if (const auto *ASE =
  13677. dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
  13678. Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
  13679. } else if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(
  13680. SI->getAssociatedExpression())) {
  13681. const Expr *E = OASE->getBase()->IgnoreParenImpCasts();
  13682. Type =
  13683. OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
  13684. }
  13685. if (Type.isNull() || Type->isAnyPointerType() ||
  13686. checkArrayExpressionDoesNotReferToWholeSize(
  13687. SemaRef, SI->getAssociatedExpression(), Type))
  13688. break;
  13689. }
  13690. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
  13691. // List items of map clauses in the same construct must not share
  13692. // original storage.
  13693. //
  13694. // If the expressions are exactly the same or one is a subset of the
  13695. // other, it means they are sharing storage.
  13696. if (CI == CE && SI == SE) {
  13697. if (CurrentRegionOnly) {
  13698. if (CKind == OMPC_map) {
  13699. SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
  13700. } else {
  13701. assert(CKind == OMPC_to || CKind == OMPC_from);
  13702. SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
  13703. << ERange;
  13704. }
  13705. SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
  13706. << RE->getSourceRange();
  13707. return true;
  13708. }
  13709. // If we find the same expression in the enclosing data environment,
  13710. // that is legal.
  13711. IsEnclosedByDataEnvironmentExpr = true;
  13712. return false;
  13713. }
  13714. QualType DerivedType =
  13715. std::prev(CI)->getAssociatedDeclaration()->getType();
  13716. SourceLocation DerivedLoc =
  13717. std::prev(CI)->getAssociatedExpression()->getExprLoc();
  13718. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
  13719. // If the type of a list item is a reference to a type T then the type
  13720. // will be considered to be T for all purposes of this clause.
  13721. DerivedType = DerivedType.getNonReferenceType();
  13722. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
  13723. // A variable for which the type is pointer and an array section
  13724. // derived from that variable must not appear as list items of map
  13725. // clauses of the same construct.
  13726. //
  13727. // Also, cover one of the cases in:
  13728. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
  13729. // If any part of the original storage of a list item has corresponding
  13730. // storage in the device data environment, all of the original storage
  13731. // must have corresponding storage in the device data environment.
  13732. //
  13733. if (DerivedType->isAnyPointerType()) {
  13734. if (CI == CE || SI == SE) {
  13735. SemaRef.Diag(
  13736. DerivedLoc,
  13737. diag::err_omp_pointer_mapped_along_with_derived_section)
  13738. << DerivedLoc;
  13739. SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
  13740. << RE->getSourceRange();
  13741. return true;
  13742. }
  13743. if (CI->getAssociatedExpression()->getStmtClass() !=
  13744. SI->getAssociatedExpression()->getStmtClass() ||
  13745. CI->getAssociatedDeclaration()->getCanonicalDecl() ==
  13746. SI->getAssociatedDeclaration()->getCanonicalDecl()) {
  13747. assert(CI != CE && SI != SE);
  13748. SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_dereferenced)
  13749. << DerivedLoc;
  13750. SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
  13751. << RE->getSourceRange();
  13752. return true;
  13753. }
  13754. }
  13755. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
  13756. // List items of map clauses in the same construct must not share
  13757. // original storage.
  13758. //
  13759. // An expression is a subset of the other.
  13760. if (CurrentRegionOnly && (CI == CE || SI == SE)) {
  13761. if (CKind == OMPC_map) {
  13762. if (CI != CE || SI != SE) {
  13763. // Allow constructs like this: map(s, s.ptr[0:1]), where s.ptr is
  13764. // a pointer.
  13765. auto Begin =
  13766. CI != CE ? CurComponents.begin() : StackComponents.begin();
  13767. auto End = CI != CE ? CurComponents.end() : StackComponents.end();
  13768. auto It = Begin;
  13769. while (It != End && !It->getAssociatedDeclaration())
  13770. std::advance(It, 1);
  13771. assert(It != End &&
  13772. "Expected at least one component with the declaration.");
  13773. if (It != Begin && It->getAssociatedDeclaration()
  13774. ->getType()
  13775. .getCanonicalType()
  13776. ->isAnyPointerType()) {
  13777. IsEnclosedByDataEnvironmentExpr = false;
  13778. EnclosingExpr = nullptr;
  13779. return false;
  13780. }
  13781. }
  13782. SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
  13783. } else {
  13784. assert(CKind == OMPC_to || CKind == OMPC_from);
  13785. SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
  13786. << ERange;
  13787. }
  13788. SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
  13789. << RE->getSourceRange();
  13790. return true;
  13791. }
  13792. // The current expression uses the same base as other expression in the
  13793. // data environment but does not contain it completely.
  13794. if (!CurrentRegionOnly && SI != SE)
  13795. EnclosingExpr = RE;
  13796. // The current expression is a subset of the expression in the data
  13797. // environment.
  13798. IsEnclosedByDataEnvironmentExpr |=
  13799. (!CurrentRegionOnly && CI != CE && SI == SE);
  13800. return false;
  13801. });
  13802. if (CurrentRegionOnly)
  13803. return FoundError;
  13804. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
  13805. // If any part of the original storage of a list item has corresponding
  13806. // storage in the device data environment, all of the original storage must
  13807. // have corresponding storage in the device data environment.
  13808. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
  13809. // If a list item is an element of a structure, and a different element of
  13810. // the structure has a corresponding list item in the device data environment
  13811. // prior to a task encountering the construct associated with the map clause,
  13812. // then the list item must also have a corresponding list item in the device
  13813. // data environment prior to the task encountering the construct.
  13814. //
  13815. if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
  13816. SemaRef.Diag(ELoc,
  13817. diag::err_omp_original_storage_is_shared_and_does_not_contain)
  13818. << ERange;
  13819. SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
  13820. << EnclosingExpr->getSourceRange();
  13821. return true;
  13822. }
  13823. return FoundError;
  13824. }
  13825. // Look up the user-defined mapper given the mapper name and mapped type, and
  13826. // build a reference to it.
  13827. static ExprResult buildUserDefinedMapperRef(Sema &SemaRef, Scope *S,
  13828. CXXScopeSpec &MapperIdScopeSpec,
  13829. const DeclarationNameInfo &MapperId,
  13830. QualType Type,
  13831. Expr *UnresolvedMapper) {
  13832. if (MapperIdScopeSpec.isInvalid())
  13833. return ExprError();
  13834. // Get the actual type for the array type.
  13835. if (Type->isArrayType()) {
  13836. assert(Type->getAsArrayTypeUnsafe() && "Expect to get a valid array type");
  13837. Type = Type->getAsArrayTypeUnsafe()->getElementType().getCanonicalType();
  13838. }
  13839. // Find all user-defined mappers with the given MapperId.
  13840. SmallVector<UnresolvedSet<8>, 4> Lookups;
  13841. LookupResult Lookup(SemaRef, MapperId, Sema::LookupOMPMapperName);
  13842. Lookup.suppressDiagnostics();
  13843. if (S) {
  13844. while (S && SemaRef.LookupParsedName(Lookup, S, &MapperIdScopeSpec)) {
  13845. NamedDecl *D = Lookup.getRepresentativeDecl();
  13846. while (S && !S->isDeclScope(D))
  13847. S = S->getParent();
  13848. if (S)
  13849. S = S->getParent();
  13850. Lookups.emplace_back();
  13851. Lookups.back().append(Lookup.begin(), Lookup.end());
  13852. Lookup.clear();
  13853. }
  13854. } else if (auto *ULE = cast_or_null<UnresolvedLookupExpr>(UnresolvedMapper)) {
  13855. // Extract the user-defined mappers with the given MapperId.
  13856. Lookups.push_back(UnresolvedSet<8>());
  13857. for (NamedDecl *D : ULE->decls()) {
  13858. auto *DMD = cast<OMPDeclareMapperDecl>(D);
  13859. assert(DMD && "Expect valid OMPDeclareMapperDecl during instantiation.");
  13860. Lookups.back().addDecl(DMD);
  13861. }
  13862. }
  13863. // Defer the lookup for dependent types. The results will be passed through
  13864. // UnresolvedMapper on instantiation.
  13865. if (SemaRef.CurContext->isDependentContext() || Type->isDependentType() ||
  13866. Type->isInstantiationDependentType() ||
  13867. Type->containsUnexpandedParameterPack() ||
  13868. filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) {
  13869. return !D->isInvalidDecl() &&
  13870. (D->getType()->isDependentType() ||
  13871. D->getType()->isInstantiationDependentType() ||
  13872. D->getType()->containsUnexpandedParameterPack());
  13873. })) {
  13874. UnresolvedSet<8> URS;
  13875. for (const UnresolvedSet<8> &Set : Lookups) {
  13876. if (Set.empty())
  13877. continue;
  13878. URS.append(Set.begin(), Set.end());
  13879. }
  13880. return UnresolvedLookupExpr::Create(
  13881. SemaRef.Context, /*NamingClass=*/nullptr,
  13882. MapperIdScopeSpec.getWithLocInContext(SemaRef.Context), MapperId,
  13883. /*ADL=*/false, /*Overloaded=*/true, URS.begin(), URS.end());
  13884. }
  13885. SourceLocation Loc = MapperId.getLoc();
  13886. // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
  13887. // The type must be of struct, union or class type in C and C++
  13888. if (!Type->isStructureOrClassType() && !Type->isUnionType() &&
  13889. (MapperIdScopeSpec.isSet() || MapperId.getAsString() != "default")) {
  13890. SemaRef.Diag(Loc, diag::err_omp_mapper_wrong_type);
  13891. return ExprError();
  13892. }
  13893. // Perform argument dependent lookup.
  13894. if (SemaRef.getLangOpts().CPlusPlus && !MapperIdScopeSpec.isSet())
  13895. argumentDependentLookup(SemaRef, MapperId, Loc, Type, Lookups);
  13896. // Return the first user-defined mapper with the desired type.
  13897. if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
  13898. Lookups, [&SemaRef, Type](ValueDecl *D) -> ValueDecl * {
  13899. if (!D->isInvalidDecl() &&
  13900. SemaRef.Context.hasSameType(D->getType(), Type))
  13901. return D;
  13902. return nullptr;
  13903. }))
  13904. return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
  13905. // Find the first user-defined mapper with a type derived from the desired
  13906. // type.
  13907. if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
  13908. Lookups, [&SemaRef, Type, Loc](ValueDecl *D) -> ValueDecl * {
  13909. if (!D->isInvalidDecl() &&
  13910. SemaRef.IsDerivedFrom(Loc, Type, D->getType()) &&
  13911. !Type.isMoreQualifiedThan(D->getType()))
  13912. return D;
  13913. return nullptr;
  13914. })) {
  13915. CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
  13916. /*DetectVirtual=*/false);
  13917. if (SemaRef.IsDerivedFrom(Loc, Type, VD->getType(), Paths)) {
  13918. if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
  13919. VD->getType().getUnqualifiedType()))) {
  13920. if (SemaRef.CheckBaseClassAccess(
  13921. Loc, VD->getType(), Type, Paths.front(),
  13922. /*DiagID=*/0) != Sema::AR_inaccessible) {
  13923. return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
  13924. }
  13925. }
  13926. }
  13927. }
  13928. // Report error if a mapper is specified, but cannot be found.
  13929. if (MapperIdScopeSpec.isSet() || MapperId.getAsString() != "default") {
  13930. SemaRef.Diag(Loc, diag::err_omp_invalid_mapper)
  13931. << Type << MapperId.getName();
  13932. return ExprError();
  13933. }
  13934. return ExprEmpty();
  13935. }
  13936. namespace {
  13937. // Utility struct that gathers all the related lists associated with a mappable
  13938. // expression.
  13939. struct MappableVarListInfo {
  13940. // The list of expressions.
  13941. ArrayRef<Expr *> VarList;
  13942. // The list of processed expressions.
  13943. SmallVector<Expr *, 16> ProcessedVarList;
  13944. // The mappble components for each expression.
  13945. OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
  13946. // The base declaration of the variable.
  13947. SmallVector<ValueDecl *, 16> VarBaseDeclarations;
  13948. // The reference to the user-defined mapper associated with every expression.
  13949. SmallVector<Expr *, 16> UDMapperList;
  13950. MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
  13951. // We have a list of components and base declarations for each entry in the
  13952. // variable list.
  13953. VarComponents.reserve(VarList.size());
  13954. VarBaseDeclarations.reserve(VarList.size());
  13955. }
  13956. };
  13957. }
  13958. // Check the validity of the provided variable list for the provided clause kind
  13959. // \a CKind. In the check process the valid expressions, mappable expression
  13960. // components, variables, and user-defined mappers are extracted and used to
  13961. // fill \a ProcessedVarList, \a VarComponents, \a VarBaseDeclarations, and \a
  13962. // UDMapperList in MVLI. \a MapType, \a IsMapTypeImplicit, \a MapperIdScopeSpec,
  13963. // and \a MapperId are expected to be valid if the clause kind is 'map'.
  13964. static void checkMappableExpressionList(
  13965. Sema &SemaRef, DSAStackTy *DSAS, OpenMPClauseKind CKind,
  13966. MappableVarListInfo &MVLI, SourceLocation StartLoc,
  13967. CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo MapperId,
  13968. ArrayRef<Expr *> UnresolvedMappers,
  13969. OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
  13970. bool IsMapTypeImplicit = false) {
  13971. // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
  13972. assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
  13973. "Unexpected clause kind with mappable expressions!");
  13974. // If the identifier of user-defined mapper is not specified, it is "default".
  13975. // We do not change the actual name in this clause to distinguish whether a
  13976. // mapper is specified explicitly, i.e., it is not explicitly specified when
  13977. // MapperId.getName() is empty.
  13978. if (!MapperId.getName() || MapperId.getName().isEmpty()) {
  13979. auto &DeclNames = SemaRef.getASTContext().DeclarationNames;
  13980. MapperId.setName(DeclNames.getIdentifier(
  13981. &SemaRef.getASTContext().Idents.get("default")));
  13982. }
  13983. // Iterators to find the current unresolved mapper expression.
  13984. auto UMIt = UnresolvedMappers.begin(), UMEnd = UnresolvedMappers.end();
  13985. bool UpdateUMIt = false;
  13986. Expr *UnresolvedMapper = nullptr;
  13987. // Keep track of the mappable components and base declarations in this clause.
  13988. // Each entry in the list is going to have a list of components associated. We
  13989. // record each set of the components so that we can build the clause later on.
  13990. // In the end we should have the same amount of declarations and component
  13991. // lists.
  13992. for (Expr *RE : MVLI.VarList) {
  13993. assert(RE && "Null expr in omp to/from/map clause");
  13994. SourceLocation ELoc = RE->getExprLoc();
  13995. // Find the current unresolved mapper expression.
  13996. if (UpdateUMIt && UMIt != UMEnd) {
  13997. UMIt++;
  13998. assert(
  13999. UMIt != UMEnd &&
  14000. "Expect the size of UnresolvedMappers to match with that of VarList");
  14001. }
  14002. UpdateUMIt = true;
  14003. if (UMIt != UMEnd)
  14004. UnresolvedMapper = *UMIt;
  14005. const Expr *VE = RE->IgnoreParenLValueCasts();
  14006. if (VE->isValueDependent() || VE->isTypeDependent() ||
  14007. VE->isInstantiationDependent() ||
  14008. VE->containsUnexpandedParameterPack()) {
  14009. // Try to find the associated user-defined mapper.
  14010. ExprResult ER = buildUserDefinedMapperRef(
  14011. SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
  14012. VE->getType().getCanonicalType(), UnresolvedMapper);
  14013. if (ER.isInvalid())
  14014. continue;
  14015. MVLI.UDMapperList.push_back(ER.get());
  14016. // We can only analyze this information once the missing information is
  14017. // resolved.
  14018. MVLI.ProcessedVarList.push_back(RE);
  14019. continue;
  14020. }
  14021. Expr *SimpleExpr = RE->IgnoreParenCasts();
  14022. if (!RE->IgnoreParenImpCasts()->isLValue()) {
  14023. SemaRef.Diag(ELoc,
  14024. diag::err_omp_expected_named_var_member_or_array_expression)
  14025. << RE->getSourceRange();
  14026. continue;
  14027. }
  14028. OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
  14029. ValueDecl *CurDeclaration = nullptr;
  14030. // Obtain the array or member expression bases if required. Also, fill the
  14031. // components array with all the components identified in the process.
  14032. const Expr *BE = checkMapClauseExpressionBase(
  14033. SemaRef, SimpleExpr, CurComponents, CKind, /*NoDiagnose=*/false);
  14034. if (!BE)
  14035. continue;
  14036. assert(!CurComponents.empty() &&
  14037. "Invalid mappable expression information.");
  14038. if (const auto *TE = dyn_cast<CXXThisExpr>(BE)) {
  14039. // Add store "this" pointer to class in DSAStackTy for future checking
  14040. DSAS->addMappedClassesQualTypes(TE->getType());
  14041. // Try to find the associated user-defined mapper.
  14042. ExprResult ER = buildUserDefinedMapperRef(
  14043. SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
  14044. VE->getType().getCanonicalType(), UnresolvedMapper);
  14045. if (ER.isInvalid())
  14046. continue;
  14047. MVLI.UDMapperList.push_back(ER.get());
  14048. // Skip restriction checking for variable or field declarations
  14049. MVLI.ProcessedVarList.push_back(RE);
  14050. MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
  14051. MVLI.VarComponents.back().append(CurComponents.begin(),
  14052. CurComponents.end());
  14053. MVLI.VarBaseDeclarations.push_back(nullptr);
  14054. continue;
  14055. }
  14056. // For the following checks, we rely on the base declaration which is
  14057. // expected to be associated with the last component. The declaration is
  14058. // expected to be a variable or a field (if 'this' is being mapped).
  14059. CurDeclaration = CurComponents.back().getAssociatedDeclaration();
  14060. assert(CurDeclaration && "Null decl on map clause.");
  14061. assert(
  14062. CurDeclaration->isCanonicalDecl() &&
  14063. "Expecting components to have associated only canonical declarations.");
  14064. auto *VD = dyn_cast<VarDecl>(CurDeclaration);
  14065. const auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
  14066. assert((VD || FD) && "Only variables or fields are expected here!");
  14067. (void)FD;
  14068. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
  14069. // threadprivate variables cannot appear in a map clause.
  14070. // OpenMP 4.5 [2.10.5, target update Construct]
  14071. // threadprivate variables cannot appear in a from clause.
  14072. if (VD && DSAS->isThreadPrivate(VD)) {
  14073. DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
  14074. SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
  14075. << getOpenMPClauseName(CKind);
  14076. reportOriginalDsa(SemaRef, DSAS, VD, DVar);
  14077. continue;
  14078. }
  14079. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
  14080. // A list item cannot appear in both a map clause and a data-sharing
  14081. // attribute clause on the same construct.
  14082. // Check conflicts with other map clause expressions. We check the conflicts
  14083. // with the current construct separately from the enclosing data
  14084. // environment, because the restrictions are different. We only have to
  14085. // check conflicts across regions for the map clauses.
  14086. if (checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
  14087. /*CurrentRegionOnly=*/true, CurComponents, CKind))
  14088. break;
  14089. if (CKind == OMPC_map &&
  14090. checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
  14091. /*CurrentRegionOnly=*/false, CurComponents, CKind))
  14092. break;
  14093. // OpenMP 4.5 [2.10.5, target update Construct]
  14094. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
  14095. // If the type of a list item is a reference to a type T then the type will
  14096. // be considered to be T for all purposes of this clause.
  14097. auto I = llvm::find_if(
  14098. CurComponents,
  14099. [](const OMPClauseMappableExprCommon::MappableComponent &MC) {
  14100. return MC.getAssociatedDeclaration();
  14101. });
  14102. assert(I != CurComponents.end() && "Null decl on map clause.");
  14103. QualType Type =
  14104. I->getAssociatedDeclaration()->getType().getNonReferenceType();
  14105. // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
  14106. // A list item in a to or from clause must have a mappable type.
  14107. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
  14108. // A list item must have a mappable type.
  14109. if (!checkTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
  14110. DSAS, Type))
  14111. continue;
  14112. if (CKind == OMPC_map) {
  14113. // target enter data
  14114. // OpenMP [2.10.2, Restrictions, p. 99]
  14115. // A map-type must be specified in all map clauses and must be either
  14116. // to or alloc.
  14117. OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
  14118. if (DKind == OMPD_target_enter_data &&
  14119. !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
  14120. SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
  14121. << (IsMapTypeImplicit ? 1 : 0)
  14122. << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
  14123. << getOpenMPDirectiveName(DKind);
  14124. continue;
  14125. }
  14126. // target exit_data
  14127. // OpenMP [2.10.3, Restrictions, p. 102]
  14128. // A map-type must be specified in all map clauses and must be either
  14129. // from, release, or delete.
  14130. if (DKind == OMPD_target_exit_data &&
  14131. !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
  14132. MapType == OMPC_MAP_delete)) {
  14133. SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
  14134. << (IsMapTypeImplicit ? 1 : 0)
  14135. << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
  14136. << getOpenMPDirectiveName(DKind);
  14137. continue;
  14138. }
  14139. // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
  14140. // A list item cannot appear in both a map clause and a data-sharing
  14141. // attribute clause on the same construct
  14142. //
  14143. // OpenMP 5.0 [2.19.7.1, Restrictions, p.7]
  14144. // A list item cannot appear in both a map clause and a data-sharing
  14145. // attribute clause on the same construct unless the construct is a
  14146. // combined construct.
  14147. if (VD && ((SemaRef.LangOpts.OpenMP <= 45 &&
  14148. isOpenMPTargetExecutionDirective(DKind)) ||
  14149. DKind == OMPD_target)) {
  14150. DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
  14151. if (isOpenMPPrivate(DVar.CKind)) {
  14152. SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
  14153. << getOpenMPClauseName(DVar.CKind)
  14154. << getOpenMPClauseName(OMPC_map)
  14155. << getOpenMPDirectiveName(DSAS->getCurrentDirective());
  14156. reportOriginalDsa(SemaRef, DSAS, CurDeclaration, DVar);
  14157. continue;
  14158. }
  14159. }
  14160. }
  14161. // Try to find the associated user-defined mapper.
  14162. ExprResult ER = buildUserDefinedMapperRef(
  14163. SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
  14164. Type.getCanonicalType(), UnresolvedMapper);
  14165. if (ER.isInvalid())
  14166. continue;
  14167. MVLI.UDMapperList.push_back(ER.get());
  14168. // Save the current expression.
  14169. MVLI.ProcessedVarList.push_back(RE);
  14170. // Store the components in the stack so that they can be used to check
  14171. // against other clauses later on.
  14172. DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
  14173. /*WhereFoundClauseKind=*/OMPC_map);
  14174. // Save the components and declaration to create the clause. For purposes of
  14175. // the clause creation, any component list that has has base 'this' uses
  14176. // null as base declaration.
  14177. MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
  14178. MVLI.VarComponents.back().append(CurComponents.begin(),
  14179. CurComponents.end());
  14180. MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
  14181. : CurDeclaration);
  14182. }
  14183. }
  14184. OMPClause *Sema::ActOnOpenMPMapClause(
  14185. ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
  14186. ArrayRef<SourceLocation> MapTypeModifiersLoc,
  14187. CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId,
  14188. OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, SourceLocation MapLoc,
  14189. SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
  14190. const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) {
  14191. OpenMPMapModifierKind Modifiers[] = {OMPC_MAP_MODIFIER_unknown,
  14192. OMPC_MAP_MODIFIER_unknown,
  14193. OMPC_MAP_MODIFIER_unknown};
  14194. SourceLocation ModifiersLoc[OMPMapClause::NumberOfModifiers];
  14195. // Process map-type-modifiers, flag errors for duplicate modifiers.
  14196. unsigned Count = 0;
  14197. for (unsigned I = 0, E = MapTypeModifiers.size(); I < E; ++I) {
  14198. if (MapTypeModifiers[I] != OMPC_MAP_MODIFIER_unknown &&
  14199. llvm::find(Modifiers, MapTypeModifiers[I]) != std::end(Modifiers)) {
  14200. Diag(MapTypeModifiersLoc[I], diag::err_omp_duplicate_map_type_modifier);
  14201. continue;
  14202. }
  14203. assert(Count < OMPMapClause::NumberOfModifiers &&
  14204. "Modifiers exceed the allowed number of map type modifiers");
  14205. Modifiers[Count] = MapTypeModifiers[I];
  14206. ModifiersLoc[Count] = MapTypeModifiersLoc[I];
  14207. ++Count;
  14208. }
  14209. MappableVarListInfo MVLI(VarList);
  14210. checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, Locs.StartLoc,
  14211. MapperIdScopeSpec, MapperId, UnresolvedMappers,
  14212. MapType, IsMapTypeImplicit);
  14213. // We need to produce a map clause even if we don't have variables so that
  14214. // other diagnostics related with non-existing map clauses are accurate.
  14215. return OMPMapClause::Create(Context, Locs, MVLI.ProcessedVarList,
  14216. MVLI.VarBaseDeclarations, MVLI.VarComponents,
  14217. MVLI.UDMapperList, Modifiers, ModifiersLoc,
  14218. MapperIdScopeSpec.getWithLocInContext(Context),
  14219. MapperId, MapType, IsMapTypeImplicit, MapLoc);
  14220. }
  14221. QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
  14222. TypeResult ParsedType) {
  14223. assert(ParsedType.isUsable());
  14224. QualType ReductionType = GetTypeFromParser(ParsedType.get());
  14225. if (ReductionType.isNull())
  14226. return QualType();
  14227. // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
  14228. // A type name in a declare reduction directive cannot be a function type, an
  14229. // array type, a reference type, or a type qualified with const, volatile or
  14230. // restrict.
  14231. if (ReductionType.hasQualifiers()) {
  14232. Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
  14233. return QualType();
  14234. }
  14235. if (ReductionType->isFunctionType()) {
  14236. Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
  14237. return QualType();
  14238. }
  14239. if (ReductionType->isReferenceType()) {
  14240. Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
  14241. return QualType();
  14242. }
  14243. if (ReductionType->isArrayType()) {
  14244. Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
  14245. return QualType();
  14246. }
  14247. return ReductionType;
  14248. }
  14249. Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
  14250. Scope *S, DeclContext *DC, DeclarationName Name,
  14251. ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
  14252. AccessSpecifier AS, Decl *PrevDeclInScope) {
  14253. SmallVector<Decl *, 8> Decls;
  14254. Decls.reserve(ReductionTypes.size());
  14255. LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
  14256. forRedeclarationInCurContext());
  14257. // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
  14258. // A reduction-identifier may not be re-declared in the current scope for the
  14259. // same type or for a type that is compatible according to the base language
  14260. // rules.
  14261. llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
  14262. OMPDeclareReductionDecl *PrevDRD = nullptr;
  14263. bool InCompoundScope = true;
  14264. if (S != nullptr) {
  14265. // Find previous declaration with the same name not referenced in other
  14266. // declarations.
  14267. FunctionScopeInfo *ParentFn = getEnclosingFunction();
  14268. InCompoundScope =
  14269. (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
  14270. LookupName(Lookup, S);
  14271. FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
  14272. /*AllowInlineNamespace=*/false);
  14273. llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
  14274. LookupResult::Filter Filter = Lookup.makeFilter();
  14275. while (Filter.hasNext()) {
  14276. auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
  14277. if (InCompoundScope) {
  14278. auto I = UsedAsPrevious.find(PrevDecl);
  14279. if (I == UsedAsPrevious.end())
  14280. UsedAsPrevious[PrevDecl] = false;
  14281. if (OMPDeclareReductionDecl *D = PrevDecl->getPrevDeclInScope())
  14282. UsedAsPrevious[D] = true;
  14283. }
  14284. PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
  14285. PrevDecl->getLocation();
  14286. }
  14287. Filter.done();
  14288. if (InCompoundScope) {
  14289. for (const auto &PrevData : UsedAsPrevious) {
  14290. if (!PrevData.second) {
  14291. PrevDRD = PrevData.first;
  14292. break;
  14293. }
  14294. }
  14295. }
  14296. } else if (PrevDeclInScope != nullptr) {
  14297. auto *PrevDRDInScope = PrevDRD =
  14298. cast<OMPDeclareReductionDecl>(PrevDeclInScope);
  14299. do {
  14300. PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
  14301. PrevDRDInScope->getLocation();
  14302. PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
  14303. } while (PrevDRDInScope != nullptr);
  14304. }
  14305. for (const auto &TyData : ReductionTypes) {
  14306. const auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
  14307. bool Invalid = false;
  14308. if (I != PreviousRedeclTypes.end()) {
  14309. Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
  14310. << TyData.first;
  14311. Diag(I->second, diag::note_previous_definition);
  14312. Invalid = true;
  14313. }
  14314. PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
  14315. auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
  14316. Name, TyData.first, PrevDRD);
  14317. DC->addDecl(DRD);
  14318. DRD->setAccess(AS);
  14319. Decls.push_back(DRD);
  14320. if (Invalid)
  14321. DRD->setInvalidDecl();
  14322. else
  14323. PrevDRD = DRD;
  14324. }
  14325. return DeclGroupPtrTy::make(
  14326. DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
  14327. }
  14328. void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
  14329. auto *DRD = cast<OMPDeclareReductionDecl>(D);
  14330. // Enter new function scope.
  14331. PushFunctionScope();
  14332. setFunctionHasBranchProtectedScope();
  14333. getCurFunction()->setHasOMPDeclareReductionCombiner();
  14334. if (S != nullptr)
  14335. PushDeclContext(S, DRD);
  14336. else
  14337. CurContext = DRD;
  14338. PushExpressionEvaluationContext(
  14339. ExpressionEvaluationContext::PotentiallyEvaluated);
  14340. QualType ReductionType = DRD->getType();
  14341. // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
  14342. // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
  14343. // uses semantics of argument handles by value, but it should be passed by
  14344. // reference. C lang does not support references, so pass all parameters as
  14345. // pointers.
  14346. // Create 'T omp_in;' variable.
  14347. VarDecl *OmpInParm =
  14348. buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
  14349. // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
  14350. // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
  14351. // uses semantics of argument handles by value, but it should be passed by
  14352. // reference. C lang does not support references, so pass all parameters as
  14353. // pointers.
  14354. // Create 'T omp_out;' variable.
  14355. VarDecl *OmpOutParm =
  14356. buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
  14357. if (S != nullptr) {
  14358. PushOnScopeChains(OmpInParm, S);
  14359. PushOnScopeChains(OmpOutParm, S);
  14360. } else {
  14361. DRD->addDecl(OmpInParm);
  14362. DRD->addDecl(OmpOutParm);
  14363. }
  14364. Expr *InE =
  14365. ::buildDeclRefExpr(*this, OmpInParm, ReductionType, D->getLocation());
  14366. Expr *OutE =
  14367. ::buildDeclRefExpr(*this, OmpOutParm, ReductionType, D->getLocation());
  14368. DRD->setCombinerData(InE, OutE);
  14369. }
  14370. void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
  14371. auto *DRD = cast<OMPDeclareReductionDecl>(D);
  14372. DiscardCleanupsInEvaluationContext();
  14373. PopExpressionEvaluationContext();
  14374. PopDeclContext();
  14375. PopFunctionScopeInfo();
  14376. if (Combiner != nullptr)
  14377. DRD->setCombiner(Combiner);
  14378. else
  14379. DRD->setInvalidDecl();
  14380. }
  14381. VarDecl *Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
  14382. auto *DRD = cast<OMPDeclareReductionDecl>(D);
  14383. // Enter new function scope.
  14384. PushFunctionScope();
  14385. setFunctionHasBranchProtectedScope();
  14386. if (S != nullptr)
  14387. PushDeclContext(S, DRD);
  14388. else
  14389. CurContext = DRD;
  14390. PushExpressionEvaluationContext(
  14391. ExpressionEvaluationContext::PotentiallyEvaluated);
  14392. QualType ReductionType = DRD->getType();
  14393. // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
  14394. // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
  14395. // uses semantics of argument handles by value, but it should be passed by
  14396. // reference. C lang does not support references, so pass all parameters as
  14397. // pointers.
  14398. // Create 'T omp_priv;' variable.
  14399. VarDecl *OmpPrivParm =
  14400. buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
  14401. // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
  14402. // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
  14403. // uses semantics of argument handles by value, but it should be passed by
  14404. // reference. C lang does not support references, so pass all parameters as
  14405. // pointers.
  14406. // Create 'T omp_orig;' variable.
  14407. VarDecl *OmpOrigParm =
  14408. buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
  14409. if (S != nullptr) {
  14410. PushOnScopeChains(OmpPrivParm, S);
  14411. PushOnScopeChains(OmpOrigParm, S);
  14412. } else {
  14413. DRD->addDecl(OmpPrivParm);
  14414. DRD->addDecl(OmpOrigParm);
  14415. }
  14416. Expr *OrigE =
  14417. ::buildDeclRefExpr(*this, OmpOrigParm, ReductionType, D->getLocation());
  14418. Expr *PrivE =
  14419. ::buildDeclRefExpr(*this, OmpPrivParm, ReductionType, D->getLocation());
  14420. DRD->setInitializerData(OrigE, PrivE);
  14421. return OmpPrivParm;
  14422. }
  14423. void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
  14424. VarDecl *OmpPrivParm) {
  14425. auto *DRD = cast<OMPDeclareReductionDecl>(D);
  14426. DiscardCleanupsInEvaluationContext();
  14427. PopExpressionEvaluationContext();
  14428. PopDeclContext();
  14429. PopFunctionScopeInfo();
  14430. if (Initializer != nullptr) {
  14431. DRD->setInitializer(Initializer, OMPDeclareReductionDecl::CallInit);
  14432. } else if (OmpPrivParm->hasInit()) {
  14433. DRD->setInitializer(OmpPrivParm->getInit(),
  14434. OmpPrivParm->isDirectInit()
  14435. ? OMPDeclareReductionDecl::DirectInit
  14436. : OMPDeclareReductionDecl::CopyInit);
  14437. } else {
  14438. DRD->setInvalidDecl();
  14439. }
  14440. }
  14441. Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
  14442. Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
  14443. for (Decl *D : DeclReductions.get()) {
  14444. if (IsValid) {
  14445. if (S)
  14446. PushOnScopeChains(cast<OMPDeclareReductionDecl>(D), S,
  14447. /*AddToContext=*/false);
  14448. } else {
  14449. D->setInvalidDecl();
  14450. }
  14451. }
  14452. return DeclReductions;
  14453. }
  14454. TypeResult Sema::ActOnOpenMPDeclareMapperVarDecl(Scope *S, Declarator &D) {
  14455. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  14456. QualType T = TInfo->getType();
  14457. if (D.isInvalidType())
  14458. return true;
  14459. if (getLangOpts().CPlusPlus) {
  14460. // Check that there are no default arguments (C++ only).
  14461. CheckExtraCXXDefaultArguments(D);
  14462. }
  14463. return CreateParsedType(T, TInfo);
  14464. }
  14465. QualType Sema::ActOnOpenMPDeclareMapperType(SourceLocation TyLoc,
  14466. TypeResult ParsedType) {
  14467. assert(ParsedType.isUsable() && "Expect usable parsed mapper type");
  14468. QualType MapperType = GetTypeFromParser(ParsedType.get());
  14469. assert(!MapperType.isNull() && "Expect valid mapper type");
  14470. // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
  14471. // The type must be of struct, union or class type in C and C++
  14472. if (!MapperType->isStructureOrClassType() && !MapperType->isUnionType()) {
  14473. Diag(TyLoc, diag::err_omp_mapper_wrong_type);
  14474. return QualType();
  14475. }
  14476. return MapperType;
  14477. }
  14478. OMPDeclareMapperDecl *Sema::ActOnOpenMPDeclareMapperDirectiveStart(
  14479. Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType,
  14480. SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS,
  14481. Decl *PrevDeclInScope) {
  14482. LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPMapperName,
  14483. forRedeclarationInCurContext());
  14484. // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
  14485. // A mapper-identifier may not be redeclared in the current scope for the
  14486. // same type or for a type that is compatible according to the base language
  14487. // rules.
  14488. llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
  14489. OMPDeclareMapperDecl *PrevDMD = nullptr;
  14490. bool InCompoundScope = true;
  14491. if (S != nullptr) {
  14492. // Find previous declaration with the same name not referenced in other
  14493. // declarations.
  14494. FunctionScopeInfo *ParentFn = getEnclosingFunction();
  14495. InCompoundScope =
  14496. (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
  14497. LookupName(Lookup, S);
  14498. FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
  14499. /*AllowInlineNamespace=*/false);
  14500. llvm::DenseMap<OMPDeclareMapperDecl *, bool> UsedAsPrevious;
  14501. LookupResult::Filter Filter = Lookup.makeFilter();
  14502. while (Filter.hasNext()) {
  14503. auto *PrevDecl = cast<OMPDeclareMapperDecl>(Filter.next());
  14504. if (InCompoundScope) {
  14505. auto I = UsedAsPrevious.find(PrevDecl);
  14506. if (I == UsedAsPrevious.end())
  14507. UsedAsPrevious[PrevDecl] = false;
  14508. if (OMPDeclareMapperDecl *D = PrevDecl->getPrevDeclInScope())
  14509. UsedAsPrevious[D] = true;
  14510. }
  14511. PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
  14512. PrevDecl->getLocation();
  14513. }
  14514. Filter.done();
  14515. if (InCompoundScope) {
  14516. for (const auto &PrevData : UsedAsPrevious) {
  14517. if (!PrevData.second) {
  14518. PrevDMD = PrevData.first;
  14519. break;
  14520. }
  14521. }
  14522. }
  14523. } else if (PrevDeclInScope) {
  14524. auto *PrevDMDInScope = PrevDMD =
  14525. cast<OMPDeclareMapperDecl>(PrevDeclInScope);
  14526. do {
  14527. PreviousRedeclTypes[PrevDMDInScope->getType().getCanonicalType()] =
  14528. PrevDMDInScope->getLocation();
  14529. PrevDMDInScope = PrevDMDInScope->getPrevDeclInScope();
  14530. } while (PrevDMDInScope != nullptr);
  14531. }
  14532. const auto I = PreviousRedeclTypes.find(MapperType.getCanonicalType());
  14533. bool Invalid = false;
  14534. if (I != PreviousRedeclTypes.end()) {
  14535. Diag(StartLoc, diag::err_omp_declare_mapper_redefinition)
  14536. << MapperType << Name;
  14537. Diag(I->second, diag::note_previous_definition);
  14538. Invalid = true;
  14539. }
  14540. auto *DMD = OMPDeclareMapperDecl::Create(Context, DC, StartLoc, Name,
  14541. MapperType, VN, PrevDMD);
  14542. DC->addDecl(DMD);
  14543. DMD->setAccess(AS);
  14544. if (Invalid)
  14545. DMD->setInvalidDecl();
  14546. // Enter new function scope.
  14547. PushFunctionScope();
  14548. setFunctionHasBranchProtectedScope();
  14549. CurContext = DMD;
  14550. return DMD;
  14551. }
  14552. void Sema::ActOnOpenMPDeclareMapperDirectiveVarDecl(OMPDeclareMapperDecl *DMD,
  14553. Scope *S,
  14554. QualType MapperType,
  14555. SourceLocation StartLoc,
  14556. DeclarationName VN) {
  14557. VarDecl *VD = buildVarDecl(*this, StartLoc, MapperType, VN.getAsString());
  14558. if (S)
  14559. PushOnScopeChains(VD, S);
  14560. else
  14561. DMD->addDecl(VD);
  14562. Expr *MapperVarRefExpr = buildDeclRefExpr(*this, VD, MapperType, StartLoc);
  14563. DMD->setMapperVarRef(MapperVarRefExpr);
  14564. }
  14565. Sema::DeclGroupPtrTy
  14566. Sema::ActOnOpenMPDeclareMapperDirectiveEnd(OMPDeclareMapperDecl *D, Scope *S,
  14567. ArrayRef<OMPClause *> ClauseList) {
  14568. PopDeclContext();
  14569. PopFunctionScopeInfo();
  14570. if (D) {
  14571. if (S)
  14572. PushOnScopeChains(D, S, /*AddToContext=*/false);
  14573. D->CreateClauses(Context, ClauseList);
  14574. }
  14575. return DeclGroupPtrTy::make(DeclGroupRef(D));
  14576. }
  14577. OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
  14578. SourceLocation StartLoc,
  14579. SourceLocation LParenLoc,
  14580. SourceLocation EndLoc) {
  14581. Expr *ValExpr = NumTeams;
  14582. Stmt *HelperValStmt = nullptr;
  14583. // OpenMP [teams Constrcut, Restrictions]
  14584. // The num_teams expression must evaluate to a positive integer value.
  14585. if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
  14586. /*StrictlyPositive=*/true))
  14587. return nullptr;
  14588. OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
  14589. OpenMPDirectiveKind CaptureRegion =
  14590. getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams);
  14591. if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
  14592. ValExpr = MakeFullExpr(ValExpr).get();
  14593. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  14594. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  14595. HelperValStmt = buildPreInits(Context, Captures);
  14596. }
  14597. return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion,
  14598. StartLoc, LParenLoc, EndLoc);
  14599. }
  14600. OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
  14601. SourceLocation StartLoc,
  14602. SourceLocation LParenLoc,
  14603. SourceLocation EndLoc) {
  14604. Expr *ValExpr = ThreadLimit;
  14605. Stmt *HelperValStmt = nullptr;
  14606. // OpenMP [teams Constrcut, Restrictions]
  14607. // The thread_limit expression must evaluate to a positive integer value.
  14608. if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
  14609. /*StrictlyPositive=*/true))
  14610. return nullptr;
  14611. OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
  14612. OpenMPDirectiveKind CaptureRegion =
  14613. getOpenMPCaptureRegionForClause(DKind, OMPC_thread_limit);
  14614. if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
  14615. ValExpr = MakeFullExpr(ValExpr).get();
  14616. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  14617. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  14618. HelperValStmt = buildPreInits(Context, Captures);
  14619. }
  14620. return new (Context) OMPThreadLimitClause(
  14621. ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
  14622. }
  14623. OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
  14624. SourceLocation StartLoc,
  14625. SourceLocation LParenLoc,
  14626. SourceLocation EndLoc) {
  14627. Expr *ValExpr = Priority;
  14628. // OpenMP [2.9.1, task Constrcut]
  14629. // The priority-value is a non-negative numerical scalar expression.
  14630. if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_priority,
  14631. /*StrictlyPositive=*/false))
  14632. return nullptr;
  14633. return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc);
  14634. }
  14635. OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
  14636. SourceLocation StartLoc,
  14637. SourceLocation LParenLoc,
  14638. SourceLocation EndLoc) {
  14639. Expr *ValExpr = Grainsize;
  14640. // OpenMP [2.9.2, taskloop Constrcut]
  14641. // The parameter of the grainsize clause must be a positive integer
  14642. // expression.
  14643. if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize,
  14644. /*StrictlyPositive=*/true))
  14645. return nullptr;
  14646. return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc);
  14647. }
  14648. OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
  14649. SourceLocation StartLoc,
  14650. SourceLocation LParenLoc,
  14651. SourceLocation EndLoc) {
  14652. Expr *ValExpr = NumTasks;
  14653. // OpenMP [2.9.2, taskloop Constrcut]
  14654. // The parameter of the num_tasks clause must be a positive integer
  14655. // expression.
  14656. if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks,
  14657. /*StrictlyPositive=*/true))
  14658. return nullptr;
  14659. return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc);
  14660. }
  14661. OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
  14662. SourceLocation LParenLoc,
  14663. SourceLocation EndLoc) {
  14664. // OpenMP [2.13.2, critical construct, Description]
  14665. // ... where hint-expression is an integer constant expression that evaluates
  14666. // to a valid lock hint.
  14667. ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
  14668. if (HintExpr.isInvalid())
  14669. return nullptr;
  14670. return new (Context)
  14671. OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
  14672. }
  14673. OMPClause *Sema::ActOnOpenMPDistScheduleClause(
  14674. OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
  14675. SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
  14676. SourceLocation EndLoc) {
  14677. if (Kind == OMPC_DIST_SCHEDULE_unknown) {
  14678. std::string Values;
  14679. Values += "'";
  14680. Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
  14681. Values += "'";
  14682. Diag(KindLoc, diag::err_omp_unexpected_clause_value)
  14683. << Values << getOpenMPClauseName(OMPC_dist_schedule);
  14684. return nullptr;
  14685. }
  14686. Expr *ValExpr = ChunkSize;
  14687. Stmt *HelperValStmt = nullptr;
  14688. if (ChunkSize) {
  14689. if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
  14690. !ChunkSize->isInstantiationDependent() &&
  14691. !ChunkSize->containsUnexpandedParameterPack()) {
  14692. SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
  14693. ExprResult Val =
  14694. PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
  14695. if (Val.isInvalid())
  14696. return nullptr;
  14697. ValExpr = Val.get();
  14698. // OpenMP [2.7.1, Restrictions]
  14699. // chunk_size must be a loop invariant integer expression with a positive
  14700. // value.
  14701. llvm::APSInt Result;
  14702. if (ValExpr->isIntegerConstantExpr(Result, Context)) {
  14703. if (Result.isSigned() && !Result.isStrictlyPositive()) {
  14704. Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
  14705. << "dist_schedule" << ChunkSize->getSourceRange();
  14706. return nullptr;
  14707. }
  14708. } else if (getOpenMPCaptureRegionForClause(
  14709. DSAStack->getCurrentDirective(), OMPC_dist_schedule) !=
  14710. OMPD_unknown &&
  14711. !CurContext->isDependentContext()) {
  14712. ValExpr = MakeFullExpr(ValExpr).get();
  14713. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  14714. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  14715. HelperValStmt = buildPreInits(Context, Captures);
  14716. }
  14717. }
  14718. }
  14719. return new (Context)
  14720. OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
  14721. Kind, ValExpr, HelperValStmt);
  14722. }
  14723. OMPClause *Sema::ActOnOpenMPDefaultmapClause(
  14724. OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
  14725. SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
  14726. SourceLocation KindLoc, SourceLocation EndLoc) {
  14727. // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)'
  14728. if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || Kind != OMPC_DEFAULTMAP_scalar) {
  14729. std::string Value;
  14730. SourceLocation Loc;
  14731. Value += "'";
  14732. if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
  14733. Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
  14734. OMPC_DEFAULTMAP_MODIFIER_tofrom);
  14735. Loc = MLoc;
  14736. } else {
  14737. Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
  14738. OMPC_DEFAULTMAP_scalar);
  14739. Loc = KindLoc;
  14740. }
  14741. Value += "'";
  14742. Diag(Loc, diag::err_omp_unexpected_clause_value)
  14743. << Value << getOpenMPClauseName(OMPC_defaultmap);
  14744. return nullptr;
  14745. }
  14746. DSAStack->setDefaultDMAToFromScalar(StartLoc);
  14747. return new (Context)
  14748. OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
  14749. }
  14750. bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) {
  14751. DeclContext *CurLexicalContext = getCurLexicalContext();
  14752. if (!CurLexicalContext->isFileContext() &&
  14753. !CurLexicalContext->isExternCContext() &&
  14754. !CurLexicalContext->isExternCXXContext() &&
  14755. !isa<CXXRecordDecl>(CurLexicalContext) &&
  14756. !isa<ClassTemplateDecl>(CurLexicalContext) &&
  14757. !isa<ClassTemplatePartialSpecializationDecl>(CurLexicalContext) &&
  14758. !isa<ClassTemplateSpecializationDecl>(CurLexicalContext)) {
  14759. Diag(Loc, diag::err_omp_region_not_file_context);
  14760. return false;
  14761. }
  14762. ++DeclareTargetNestingLevel;
  14763. return true;
  14764. }
  14765. void Sema::ActOnFinishOpenMPDeclareTargetDirective() {
  14766. assert(DeclareTargetNestingLevel > 0 &&
  14767. "Unexpected ActOnFinishOpenMPDeclareTargetDirective");
  14768. --DeclareTargetNestingLevel;
  14769. }
  14770. NamedDecl *
  14771. Sema::lookupOpenMPDeclareTargetName(Scope *CurScope, CXXScopeSpec &ScopeSpec,
  14772. const DeclarationNameInfo &Id,
  14773. NamedDeclSetType &SameDirectiveDecls) {
  14774. LookupResult Lookup(*this, Id, LookupOrdinaryName);
  14775. LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
  14776. if (Lookup.isAmbiguous())
  14777. return nullptr;
  14778. Lookup.suppressDiagnostics();
  14779. if (!Lookup.isSingleResult()) {
  14780. VarOrFuncDeclFilterCCC CCC(*this);
  14781. if (TypoCorrection Corrected =
  14782. CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, CCC,
  14783. CTK_ErrorRecovery)) {
  14784. diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
  14785. << Id.getName());
  14786. checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
  14787. return nullptr;
  14788. }
  14789. Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
  14790. return nullptr;
  14791. }
  14792. NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
  14793. if (!isa<VarDecl>(ND) && !isa<FunctionDecl>(ND) &&
  14794. !isa<FunctionTemplateDecl>(ND)) {
  14795. Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
  14796. return nullptr;
  14797. }
  14798. if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl())))
  14799. Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName();
  14800. return ND;
  14801. }
  14802. void Sema::ActOnOpenMPDeclareTargetName(
  14803. NamedDecl *ND, SourceLocation Loc, OMPDeclareTargetDeclAttr::MapTypeTy MT,
  14804. OMPDeclareTargetDeclAttr::DevTypeTy DT) {
  14805. assert((isa<VarDecl>(ND) || isa<FunctionDecl>(ND) ||
  14806. isa<FunctionTemplateDecl>(ND)) &&
  14807. "Expected variable, function or function template.");
  14808. // Diagnose marking after use as it may lead to incorrect diagnosis and
  14809. // codegen.
  14810. if (LangOpts.OpenMP >= 50 &&
  14811. (ND->isUsed(/*CheckUsedAttr=*/false) || ND->isReferenced()))
  14812. Diag(Loc, diag::warn_omp_declare_target_after_first_use);
  14813. Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
  14814. OMPDeclareTargetDeclAttr::getDeviceType(cast<ValueDecl>(ND));
  14815. if (DevTy.hasValue() && *DevTy != DT) {
  14816. Diag(Loc, diag::err_omp_device_type_mismatch)
  14817. << OMPDeclareTargetDeclAttr::ConvertDevTypeTyToStr(DT)
  14818. << OMPDeclareTargetDeclAttr::ConvertDevTypeTyToStr(*DevTy);
  14819. return;
  14820. }
  14821. Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
  14822. OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(cast<ValueDecl>(ND));
  14823. if (!Res) {
  14824. auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT, DT,
  14825. SourceRange(Loc, Loc));
  14826. ND->addAttr(A);
  14827. if (ASTMutationListener *ML = Context.getASTMutationListener())
  14828. ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
  14829. checkDeclIsAllowedInOpenMPTarget(nullptr, ND, Loc);
  14830. } else if (*Res != MT) {
  14831. Diag(Loc, diag::err_omp_declare_target_to_and_link) << ND;
  14832. }
  14833. }
  14834. static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
  14835. Sema &SemaRef, Decl *D) {
  14836. if (!D || !isa<VarDecl>(D))
  14837. return;
  14838. auto *VD = cast<VarDecl>(D);
  14839. Optional<OMPDeclareTargetDeclAttr::MapTypeTy> MapTy =
  14840. OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
  14841. if (SemaRef.LangOpts.OpenMP >= 50 &&
  14842. (SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true) ||
  14843. SemaRef.getCurBlock() || SemaRef.getCurCapturedRegion()) &&
  14844. VD->hasGlobalStorage()) {
  14845. llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> MapTy =
  14846. OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
  14847. if (!MapTy || *MapTy != OMPDeclareTargetDeclAttr::MT_To) {
  14848. // OpenMP 5.0, 2.12.7 declare target Directive, Restrictions
  14849. // If a lambda declaration and definition appears between a
  14850. // declare target directive and the matching end declare target
  14851. // directive, all variables that are captured by the lambda
  14852. // expression must also appear in a to clause.
  14853. SemaRef.Diag(VD->getLocation(),
  14854. diag::err_omp_lambda_capture_in_declare_target_not_to);
  14855. SemaRef.Diag(SL, diag::note_var_explicitly_captured_here)
  14856. << VD << 0 << SR;
  14857. return;
  14858. }
  14859. }
  14860. if (MapTy.hasValue())
  14861. return;
  14862. SemaRef.Diag(VD->getLocation(), diag::warn_omp_not_in_target_context);
  14863. SemaRef.Diag(SL, diag::note_used_here) << SR;
  14864. }
  14865. static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
  14866. Sema &SemaRef, DSAStackTy *Stack,
  14867. ValueDecl *VD) {
  14868. return OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD) ||
  14869. checkTypeMappable(SL, SR, SemaRef, Stack, VD->getType(),
  14870. /*FullCheck=*/false);
  14871. }
  14872. void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D,
  14873. SourceLocation IdLoc) {
  14874. if (!D || D->isInvalidDecl())
  14875. return;
  14876. SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
  14877. SourceLocation SL = E ? E->getBeginLoc() : D->getLocation();
  14878. if (auto *VD = dyn_cast<VarDecl>(D)) {
  14879. // Only global variables can be marked as declare target.
  14880. if (!VD->isFileVarDecl() && !VD->isStaticLocal() &&
  14881. !VD->isStaticDataMember())
  14882. return;
  14883. // 2.10.6: threadprivate variable cannot appear in a declare target
  14884. // directive.
  14885. if (DSAStack->isThreadPrivate(VD)) {
  14886. Diag(SL, diag::err_omp_threadprivate_in_target);
  14887. reportOriginalDsa(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
  14888. return;
  14889. }
  14890. }
  14891. if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(D))
  14892. D = FTD->getTemplatedDecl();
  14893. if (auto *FD = dyn_cast<FunctionDecl>(D)) {
  14894. llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
  14895. OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(FD);
  14896. if (IdLoc.isValid() && Res && *Res == OMPDeclareTargetDeclAttr::MT_Link) {
  14897. Diag(IdLoc, diag::err_omp_function_in_link_clause);
  14898. Diag(FD->getLocation(), diag::note_defined_here) << FD;
  14899. return;
  14900. }
  14901. // Mark the function as must be emitted for the device.
  14902. Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
  14903. OMPDeclareTargetDeclAttr::getDeviceType(FD);
  14904. if (LangOpts.OpenMPIsDevice && Res.hasValue() && IdLoc.isValid() &&
  14905. *DevTy != OMPDeclareTargetDeclAttr::DT_Host)
  14906. checkOpenMPDeviceFunction(IdLoc, FD, /*CheckForDelayedContext=*/false);
  14907. if (!LangOpts.OpenMPIsDevice && Res.hasValue() && IdLoc.isValid() &&
  14908. *DevTy != OMPDeclareTargetDeclAttr::DT_NoHost)
  14909. checkOpenMPHostFunction(IdLoc, FD, /*CheckCaller=*/false);
  14910. }
  14911. if (auto *VD = dyn_cast<ValueDecl>(D)) {
  14912. // Problem if any with var declared with incomplete type will be reported
  14913. // as normal, so no need to check it here.
  14914. if ((E || !VD->getType()->isIncompleteType()) &&
  14915. !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD))
  14916. return;
  14917. if (!E && !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
  14918. // Checking declaration inside declare target region.
  14919. if (isa<VarDecl>(D) || isa<FunctionDecl>(D) ||
  14920. isa<FunctionTemplateDecl>(D)) {
  14921. auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(
  14922. Context, OMPDeclareTargetDeclAttr::MT_To,
  14923. OMPDeclareTargetDeclAttr::DT_Any, SourceRange(IdLoc, IdLoc));
  14924. D->addAttr(A);
  14925. if (ASTMutationListener *ML = Context.getASTMutationListener())
  14926. ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
  14927. }
  14928. return;
  14929. }
  14930. }
  14931. if (!E)
  14932. return;
  14933. checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
  14934. }
  14935. OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
  14936. CXXScopeSpec &MapperIdScopeSpec,
  14937. DeclarationNameInfo &MapperId,
  14938. const OMPVarListLocTy &Locs,
  14939. ArrayRef<Expr *> UnresolvedMappers) {
  14940. MappableVarListInfo MVLI(VarList);
  14941. checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, Locs.StartLoc,
  14942. MapperIdScopeSpec, MapperId, UnresolvedMappers);
  14943. if (MVLI.ProcessedVarList.empty())
  14944. return nullptr;
  14945. return OMPToClause::Create(
  14946. Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
  14947. MVLI.VarComponents, MVLI.UDMapperList,
  14948. MapperIdScopeSpec.getWithLocInContext(Context), MapperId);
  14949. }
  14950. OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
  14951. CXXScopeSpec &MapperIdScopeSpec,
  14952. DeclarationNameInfo &MapperId,
  14953. const OMPVarListLocTy &Locs,
  14954. ArrayRef<Expr *> UnresolvedMappers) {
  14955. MappableVarListInfo MVLI(VarList);
  14956. checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, Locs.StartLoc,
  14957. MapperIdScopeSpec, MapperId, UnresolvedMappers);
  14958. if (MVLI.ProcessedVarList.empty())
  14959. return nullptr;
  14960. return OMPFromClause::Create(
  14961. Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
  14962. MVLI.VarComponents, MVLI.UDMapperList,
  14963. MapperIdScopeSpec.getWithLocInContext(Context), MapperId);
  14964. }
  14965. OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
  14966. const OMPVarListLocTy &Locs) {
  14967. MappableVarListInfo MVLI(VarList);
  14968. SmallVector<Expr *, 8> PrivateCopies;
  14969. SmallVector<Expr *, 8> Inits;
  14970. for (Expr *RefExpr : VarList) {
  14971. assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
  14972. SourceLocation ELoc;
  14973. SourceRange ERange;
  14974. Expr *SimpleRefExpr = RefExpr;
  14975. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  14976. if (Res.second) {
  14977. // It will be analyzed later.
  14978. MVLI.ProcessedVarList.push_back(RefExpr);
  14979. PrivateCopies.push_back(nullptr);
  14980. Inits.push_back(nullptr);
  14981. }
  14982. ValueDecl *D = Res.first;
  14983. if (!D)
  14984. continue;
  14985. QualType Type = D->getType();
  14986. Type = Type.getNonReferenceType().getUnqualifiedType();
  14987. auto *VD = dyn_cast<VarDecl>(D);
  14988. // Item should be a pointer or reference to pointer.
  14989. if (!Type->isPointerType()) {
  14990. Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
  14991. << 0 << RefExpr->getSourceRange();
  14992. continue;
  14993. }
  14994. // Build the private variable and the expression that refers to it.
  14995. auto VDPrivate =
  14996. buildVarDecl(*this, ELoc, Type, D->getName(),
  14997. D->hasAttrs() ? &D->getAttrs() : nullptr,
  14998. VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
  14999. if (VDPrivate->isInvalidDecl())
  15000. continue;
  15001. CurContext->addDecl(VDPrivate);
  15002. DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
  15003. *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
  15004. // Add temporary variable to initialize the private copy of the pointer.
  15005. VarDecl *VDInit =
  15006. buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
  15007. DeclRefExpr *VDInitRefExpr = buildDeclRefExpr(
  15008. *this, VDInit, RefExpr->getType(), RefExpr->getExprLoc());
  15009. AddInitializerToDecl(VDPrivate,
  15010. DefaultLvalueConversion(VDInitRefExpr).get(),
  15011. /*DirectInit=*/false);
  15012. // If required, build a capture to implement the privatization initialized
  15013. // with the current list item value.
  15014. DeclRefExpr *Ref = nullptr;
  15015. if (!VD)
  15016. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
  15017. MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
  15018. PrivateCopies.push_back(VDPrivateRefExpr);
  15019. Inits.push_back(VDInitRefExpr);
  15020. // We need to add a data sharing attribute for this variable to make sure it
  15021. // is correctly captured. A variable that shows up in a use_device_ptr has
  15022. // similar properties of a first private variable.
  15023. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
  15024. // Create a mappable component for the list item. List items in this clause
  15025. // only need a component.
  15026. MVLI.VarBaseDeclarations.push_back(D);
  15027. MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
  15028. MVLI.VarComponents.back().push_back(
  15029. OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D));
  15030. }
  15031. if (MVLI.ProcessedVarList.empty())
  15032. return nullptr;
  15033. return OMPUseDevicePtrClause::Create(
  15034. Context, Locs, MVLI.ProcessedVarList, PrivateCopies, Inits,
  15035. MVLI.VarBaseDeclarations, MVLI.VarComponents);
  15036. }
  15037. OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
  15038. const OMPVarListLocTy &Locs) {
  15039. MappableVarListInfo MVLI(VarList);
  15040. for (Expr *RefExpr : VarList) {
  15041. assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
  15042. SourceLocation ELoc;
  15043. SourceRange ERange;
  15044. Expr *SimpleRefExpr = RefExpr;
  15045. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  15046. if (Res.second) {
  15047. // It will be analyzed later.
  15048. MVLI.ProcessedVarList.push_back(RefExpr);
  15049. }
  15050. ValueDecl *D = Res.first;
  15051. if (!D)
  15052. continue;
  15053. QualType Type = D->getType();
  15054. // item should be a pointer or array or reference to pointer or array
  15055. if (!Type.getNonReferenceType()->isPointerType() &&
  15056. !Type.getNonReferenceType()->isArrayType()) {
  15057. Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
  15058. << 0 << RefExpr->getSourceRange();
  15059. continue;
  15060. }
  15061. // Check if the declaration in the clause does not show up in any data
  15062. // sharing attribute.
  15063. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
  15064. if (isOpenMPPrivate(DVar.CKind)) {
  15065. Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
  15066. << getOpenMPClauseName(DVar.CKind)
  15067. << getOpenMPClauseName(OMPC_is_device_ptr)
  15068. << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
  15069. reportOriginalDsa(*this, DSAStack, D, DVar);
  15070. continue;
  15071. }
  15072. const Expr *ConflictExpr;
  15073. if (DSAStack->checkMappableExprComponentListsForDecl(
  15074. D, /*CurrentRegionOnly=*/true,
  15075. [&ConflictExpr](
  15076. OMPClauseMappableExprCommon::MappableExprComponentListRef R,
  15077. OpenMPClauseKind) -> bool {
  15078. ConflictExpr = R.front().getAssociatedExpression();
  15079. return true;
  15080. })) {
  15081. Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
  15082. Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
  15083. << ConflictExpr->getSourceRange();
  15084. continue;
  15085. }
  15086. // Store the components in the stack so that they can be used to check
  15087. // against other clauses later on.
  15088. OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D);
  15089. DSAStack->addMappableExpressionComponents(
  15090. D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
  15091. // Record the expression we've just processed.
  15092. MVLI.ProcessedVarList.push_back(SimpleRefExpr);
  15093. // Create a mappable component for the list item. List items in this clause
  15094. // only need a component. We use a null declaration to signal fields in
  15095. // 'this'.
  15096. assert((isa<DeclRefExpr>(SimpleRefExpr) ||
  15097. isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
  15098. "Unexpected device pointer expression!");
  15099. MVLI.VarBaseDeclarations.push_back(
  15100. isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
  15101. MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
  15102. MVLI.VarComponents.back().push_back(MC);
  15103. }
  15104. if (MVLI.ProcessedVarList.empty())
  15105. return nullptr;
  15106. return OMPIsDevicePtrClause::Create(Context, Locs, MVLI.ProcessedVarList,
  15107. MVLI.VarBaseDeclarations,
  15108. MVLI.VarComponents);
  15109. }
  15110. OMPClause *Sema::ActOnOpenMPAllocateClause(
  15111. Expr *Allocator, ArrayRef<Expr *> VarList, SourceLocation StartLoc,
  15112. SourceLocation ColonLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
  15113. if (Allocator) {
  15114. // OpenMP [2.11.4 allocate Clause, Description]
  15115. // allocator is an expression of omp_allocator_handle_t type.
  15116. if (!findOMPAllocatorHandleT(*this, Allocator->getExprLoc(), DSAStack))
  15117. return nullptr;
  15118. ExprResult AllocatorRes = DefaultLvalueConversion(Allocator);
  15119. if (AllocatorRes.isInvalid())
  15120. return nullptr;
  15121. AllocatorRes = PerformImplicitConversion(AllocatorRes.get(),
  15122. DSAStack->getOMPAllocatorHandleT(),
  15123. Sema::AA_Initializing,
  15124. /*AllowExplicit=*/true);
  15125. if (AllocatorRes.isInvalid())
  15126. return nullptr;
  15127. Allocator = AllocatorRes.get();
  15128. } else {
  15129. // OpenMP 5.0, 2.11.4 allocate Clause, Restrictions.
  15130. // allocate clauses that appear on a target construct or on constructs in a
  15131. // target region must specify an allocator expression unless a requires
  15132. // directive with the dynamic_allocators clause is present in the same
  15133. // compilation unit.
  15134. if (LangOpts.OpenMPIsDevice &&
  15135. !DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())
  15136. targetDiag(StartLoc, diag::err_expected_allocator_expression);
  15137. }
  15138. // Analyze and build list of variables.
  15139. SmallVector<Expr *, 8> Vars;
  15140. for (Expr *RefExpr : VarList) {
  15141. assert(RefExpr && "NULL expr in OpenMP private clause.");
  15142. SourceLocation ELoc;
  15143. SourceRange ERange;
  15144. Expr *SimpleRefExpr = RefExpr;
  15145. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  15146. if (Res.second) {
  15147. // It will be analyzed later.
  15148. Vars.push_back(RefExpr);
  15149. }
  15150. ValueDecl *D = Res.first;
  15151. if (!D)
  15152. continue;
  15153. auto *VD = dyn_cast<VarDecl>(D);
  15154. DeclRefExpr *Ref = nullptr;
  15155. if (!VD && !CurContext->isDependentContext())
  15156. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
  15157. Vars.push_back((VD || CurContext->isDependentContext())
  15158. ? RefExpr->IgnoreParens()
  15159. : Ref);
  15160. }
  15161. if (Vars.empty())
  15162. return nullptr;
  15163. return OMPAllocateClause::Create(Context, StartLoc, LParenLoc, Allocator,
  15164. ColonLoc, EndLoc, Vars);
  15165. }