SemaOpenMP.cpp 577 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521
  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. const Decl *PossiblyLoopCounter = nullptr;
  135. bool NowaitRegion = false;
  136. bool CancelRegion = false;
  137. bool LoopStart = false;
  138. SourceLocation InnerTeamsRegionLoc;
  139. /// Reference to the taskgroup task_reduction reference expression.
  140. Expr *TaskgroupReductionRef = nullptr;
  141. llvm::DenseSet<QualType> MappedClassesQualTypes;
  142. /// List of globals marked as declare target link in this target region
  143. /// (isOpenMPTargetExecutionDirective(Directive) == true).
  144. llvm::SmallVector<DeclRefExpr *, 4> DeclareTargetLinkVarDecls;
  145. SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name,
  146. Scope *CurScope, SourceLocation Loc)
  147. : Directive(DKind), DirectiveName(Name), CurScope(CurScope),
  148. ConstructLoc(Loc) {}
  149. SharingMapTy() = default;
  150. };
  151. using StackTy = SmallVector<SharingMapTy, 4>;
  152. /// Stack of used declaration and their data-sharing attributes.
  153. DeclSAMapTy Threadprivates;
  154. const FunctionScopeInfo *CurrentNonCapturingFunctionScope = nullptr;
  155. SmallVector<std::pair<StackTy, const FunctionScopeInfo *>, 4> Stack;
  156. /// true, if check for DSA must be from parent directive, false, if
  157. /// from current directive.
  158. OpenMPClauseKind ClauseKindMode = OMPC_unknown;
  159. Sema &SemaRef;
  160. bool ForceCapturing = false;
  161. /// true if all the vaiables in the target executable directives must be
  162. /// captured by reference.
  163. bool ForceCaptureByReferenceInTargetExecutable = false;
  164. CriticalsWithHintsTy Criticals;
  165. using iterator = StackTy::const_reverse_iterator;
  166. DSAVarData getDSA(iterator &Iter, ValueDecl *D) const;
  167. /// Checks if the variable is a local for OpenMP region.
  168. bool isOpenMPLocal(VarDecl *D, iterator Iter) const;
  169. bool isStackEmpty() const {
  170. return Stack.empty() ||
  171. Stack.back().second != CurrentNonCapturingFunctionScope ||
  172. Stack.back().first.empty();
  173. }
  174. /// Vector of previously declared requires directives
  175. SmallVector<const OMPRequiresDecl *, 2> RequiresDecls;
  176. public:
  177. explicit DSAStackTy(Sema &S) : SemaRef(S) {}
  178. bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; }
  179. OpenMPClauseKind getClauseParsingMode() const {
  180. assert(isClauseParsingMode() && "Must be in clause parsing mode.");
  181. return ClauseKindMode;
  182. }
  183. void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; }
  184. bool isForceVarCapturing() const { return ForceCapturing; }
  185. void setForceVarCapturing(bool V) { ForceCapturing = V; }
  186. void setForceCaptureByReferenceInTargetExecutable(bool V) {
  187. ForceCaptureByReferenceInTargetExecutable = V;
  188. }
  189. bool isForceCaptureByReferenceInTargetExecutable() const {
  190. return ForceCaptureByReferenceInTargetExecutable;
  191. }
  192. void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
  193. Scope *CurScope, SourceLocation Loc) {
  194. if (Stack.empty() ||
  195. Stack.back().second != CurrentNonCapturingFunctionScope)
  196. Stack.emplace_back(StackTy(), CurrentNonCapturingFunctionScope);
  197. Stack.back().first.emplace_back(DKind, DirName, CurScope, Loc);
  198. Stack.back().first.back().DefaultAttrLoc = Loc;
  199. }
  200. void pop() {
  201. assert(!Stack.back().first.empty() &&
  202. "Data-sharing attributes stack is empty!");
  203. Stack.back().first.pop_back();
  204. }
  205. /// Marks that we're started loop parsing.
  206. void loopInit() {
  207. assert(isOpenMPLoopDirective(getCurrentDirective()) &&
  208. "Expected loop-based directive.");
  209. Stack.back().first.back().LoopStart = true;
  210. }
  211. /// Start capturing of the variables in the loop context.
  212. void loopStart() {
  213. assert(isOpenMPLoopDirective(getCurrentDirective()) &&
  214. "Expected loop-based directive.");
  215. Stack.back().first.back().LoopStart = false;
  216. }
  217. /// true, if variables are captured, false otherwise.
  218. bool isLoopStarted() const {
  219. assert(isOpenMPLoopDirective(getCurrentDirective()) &&
  220. "Expected loop-based directive.");
  221. return !Stack.back().first.back().LoopStart;
  222. }
  223. /// Marks (or clears) declaration as possibly loop counter.
  224. void resetPossibleLoopCounter(const Decl *D = nullptr) {
  225. Stack.back().first.back().PossiblyLoopCounter =
  226. D ? D->getCanonicalDecl() : D;
  227. }
  228. /// Gets the possible loop counter decl.
  229. const Decl *getPossiblyLoopCunter() const {
  230. return Stack.back().first.back().PossiblyLoopCounter;
  231. }
  232. /// Start new OpenMP region stack in new non-capturing function.
  233. void pushFunction() {
  234. const FunctionScopeInfo *CurFnScope = SemaRef.getCurFunction();
  235. assert(!isa<CapturingScopeInfo>(CurFnScope));
  236. CurrentNonCapturingFunctionScope = CurFnScope;
  237. }
  238. /// Pop region stack for non-capturing function.
  239. void popFunction(const FunctionScopeInfo *OldFSI) {
  240. if (!Stack.empty() && Stack.back().second == OldFSI) {
  241. assert(Stack.back().first.empty());
  242. Stack.pop_back();
  243. }
  244. CurrentNonCapturingFunctionScope = nullptr;
  245. for (const FunctionScopeInfo *FSI : llvm::reverse(SemaRef.FunctionScopes)) {
  246. if (!isa<CapturingScopeInfo>(FSI)) {
  247. CurrentNonCapturingFunctionScope = FSI;
  248. break;
  249. }
  250. }
  251. }
  252. void addCriticalWithHint(const OMPCriticalDirective *D, llvm::APSInt Hint) {
  253. Criticals.try_emplace(D->getDirectiveName().getAsString(), D, Hint);
  254. }
  255. const std::pair<const OMPCriticalDirective *, llvm::APSInt>
  256. getCriticalWithHint(const DeclarationNameInfo &Name) const {
  257. auto I = Criticals.find(Name.getAsString());
  258. if (I != Criticals.end())
  259. return I->second;
  260. return std::make_pair(nullptr, llvm::APSInt());
  261. }
  262. /// If 'aligned' declaration for given variable \a D was not seen yet,
  263. /// add it and return NULL; otherwise return previous occurrence's expression
  264. /// for diagnostics.
  265. const Expr *addUniqueAligned(const ValueDecl *D, const Expr *NewDE);
  266. /// Register specified variable as loop control variable.
  267. void addLoopControlVariable(const ValueDecl *D, VarDecl *Capture);
  268. /// Check if the specified variable is a loop control variable for
  269. /// current region.
  270. /// \return The index of the loop control variable in the list of associated
  271. /// for-loops (from outer to inner).
  272. const LCDeclInfo isLoopControlVariable(const ValueDecl *D) const;
  273. /// Check if the specified variable is a loop control variable for
  274. /// parent region.
  275. /// \return The index of the loop control variable in the list of associated
  276. /// for-loops (from outer to inner).
  277. const LCDeclInfo isParentLoopControlVariable(const ValueDecl *D) const;
  278. /// Get the loop control variable for the I-th loop (or nullptr) in
  279. /// parent directive.
  280. const ValueDecl *getParentLoopControlVariable(unsigned I) const;
  281. /// Adds explicit data sharing attribute to the specified declaration.
  282. void addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A,
  283. DeclRefExpr *PrivateCopy = nullptr);
  284. /// Adds additional information for the reduction items with the reduction id
  285. /// represented as an operator.
  286. void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
  287. BinaryOperatorKind BOK);
  288. /// Adds additional information for the reduction items with the reduction id
  289. /// represented as reduction identifier.
  290. void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
  291. const Expr *ReductionRef);
  292. /// Returns the location and reduction operation from the innermost parent
  293. /// region for the given \p D.
  294. const DSAVarData
  295. getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR,
  296. BinaryOperatorKind &BOK,
  297. Expr *&TaskgroupDescriptor) const;
  298. /// Returns the location and reduction operation from the innermost parent
  299. /// region for the given \p D.
  300. const DSAVarData
  301. getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR,
  302. const Expr *&ReductionRef,
  303. Expr *&TaskgroupDescriptor) const;
  304. /// Return reduction reference expression for the current taskgroup.
  305. Expr *getTaskgroupReductionRef() const {
  306. assert(Stack.back().first.back().Directive == OMPD_taskgroup &&
  307. "taskgroup reference expression requested for non taskgroup "
  308. "directive.");
  309. return Stack.back().first.back().TaskgroupReductionRef;
  310. }
  311. /// Checks if the given \p VD declaration is actually a taskgroup reduction
  312. /// descriptor variable at the \p Level of OpenMP regions.
  313. bool isTaskgroupReductionRef(const ValueDecl *VD, unsigned Level) const {
  314. return Stack.back().first[Level].TaskgroupReductionRef &&
  315. cast<DeclRefExpr>(Stack.back().first[Level].TaskgroupReductionRef)
  316. ->getDecl() == VD;
  317. }
  318. /// Returns data sharing attributes from top of the stack for the
  319. /// specified declaration.
  320. const DSAVarData getTopDSA(ValueDecl *D, bool FromParent);
  321. /// Returns data-sharing attributes for the specified declaration.
  322. const DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent) const;
  323. /// Checks if the specified variables has data-sharing attributes which
  324. /// match specified \a CPred predicate in any directive which matches \a DPred
  325. /// predicate.
  326. const DSAVarData
  327. hasDSA(ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
  328. const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
  329. bool FromParent) const;
  330. /// Checks if the specified variables has data-sharing attributes which
  331. /// match specified \a CPred predicate in any innermost directive which
  332. /// matches \a DPred predicate.
  333. const DSAVarData
  334. hasInnermostDSA(ValueDecl *D,
  335. const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
  336. const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
  337. bool FromParent) const;
  338. /// Checks if the specified variables has explicit data-sharing
  339. /// attributes which match specified \a CPred predicate at the specified
  340. /// OpenMP region.
  341. bool hasExplicitDSA(const ValueDecl *D,
  342. const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
  343. unsigned Level, bool NotLastprivate = false) const;
  344. /// Returns true if the directive at level \Level matches in the
  345. /// specified \a DPred predicate.
  346. bool hasExplicitDirective(
  347. const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
  348. unsigned Level) const;
  349. /// Finds a directive which matches specified \a DPred predicate.
  350. bool hasDirective(
  351. const llvm::function_ref<bool(
  352. OpenMPDirectiveKind, const DeclarationNameInfo &, SourceLocation)>
  353. DPred,
  354. bool FromParent) const;
  355. /// Returns currently analyzed directive.
  356. OpenMPDirectiveKind getCurrentDirective() const {
  357. return isStackEmpty() ? OMPD_unknown : Stack.back().first.back().Directive;
  358. }
  359. /// Returns directive kind at specified level.
  360. OpenMPDirectiveKind getDirective(unsigned Level) const {
  361. assert(!isStackEmpty() && "No directive at specified level.");
  362. return Stack.back().first[Level].Directive;
  363. }
  364. /// Returns parent directive.
  365. OpenMPDirectiveKind getParentDirective() const {
  366. if (isStackEmpty() || Stack.back().first.size() == 1)
  367. return OMPD_unknown;
  368. return std::next(Stack.back().first.rbegin())->Directive;
  369. }
  370. /// Add requires decl to internal vector
  371. void addRequiresDecl(OMPRequiresDecl *RD) {
  372. RequiresDecls.push_back(RD);
  373. }
  374. /// Checks for a duplicate clause amongst previously declared requires
  375. /// directives
  376. bool hasDuplicateRequiresClause(ArrayRef<OMPClause *> ClauseList) const {
  377. bool IsDuplicate = false;
  378. for (OMPClause *CNew : ClauseList) {
  379. for (const OMPRequiresDecl *D : RequiresDecls) {
  380. for (const OMPClause *CPrev : D->clauselists()) {
  381. if (CNew->getClauseKind() == CPrev->getClauseKind()) {
  382. SemaRef.Diag(CNew->getBeginLoc(),
  383. diag::err_omp_requires_clause_redeclaration)
  384. << getOpenMPClauseName(CNew->getClauseKind());
  385. SemaRef.Diag(CPrev->getBeginLoc(),
  386. diag::note_omp_requires_previous_clause)
  387. << getOpenMPClauseName(CPrev->getClauseKind());
  388. IsDuplicate = true;
  389. }
  390. }
  391. }
  392. }
  393. return IsDuplicate;
  394. }
  395. /// Set default data sharing attribute to none.
  396. void setDefaultDSANone(SourceLocation Loc) {
  397. assert(!isStackEmpty());
  398. Stack.back().first.back().DefaultAttr = DSA_none;
  399. Stack.back().first.back().DefaultAttrLoc = Loc;
  400. }
  401. /// Set default data sharing attribute to shared.
  402. void setDefaultDSAShared(SourceLocation Loc) {
  403. assert(!isStackEmpty());
  404. Stack.back().first.back().DefaultAttr = DSA_shared;
  405. Stack.back().first.back().DefaultAttrLoc = Loc;
  406. }
  407. /// Set default data mapping attribute to 'tofrom:scalar'.
  408. void setDefaultDMAToFromScalar(SourceLocation Loc) {
  409. assert(!isStackEmpty());
  410. Stack.back().first.back().DefaultMapAttr = DMA_tofrom_scalar;
  411. Stack.back().first.back().DefaultMapAttrLoc = Loc;
  412. }
  413. DefaultDataSharingAttributes getDefaultDSA() const {
  414. return isStackEmpty() ? DSA_unspecified
  415. : Stack.back().first.back().DefaultAttr;
  416. }
  417. SourceLocation getDefaultDSALocation() const {
  418. return isStackEmpty() ? SourceLocation()
  419. : Stack.back().first.back().DefaultAttrLoc;
  420. }
  421. DefaultMapAttributes getDefaultDMA() const {
  422. return isStackEmpty() ? DMA_unspecified
  423. : Stack.back().first.back().DefaultMapAttr;
  424. }
  425. DefaultMapAttributes getDefaultDMAAtLevel(unsigned Level) const {
  426. return Stack.back().first[Level].DefaultMapAttr;
  427. }
  428. SourceLocation getDefaultDMALocation() const {
  429. return isStackEmpty() ? SourceLocation()
  430. : Stack.back().first.back().DefaultMapAttrLoc;
  431. }
  432. /// Checks if the specified variable is a threadprivate.
  433. bool isThreadPrivate(VarDecl *D) {
  434. const DSAVarData DVar = getTopDSA(D, false);
  435. return isOpenMPThreadPrivate(DVar.CKind);
  436. }
  437. /// Marks current region as ordered (it has an 'ordered' clause).
  438. void setOrderedRegion(bool IsOrdered, const Expr *Param,
  439. OMPOrderedClause *Clause) {
  440. assert(!isStackEmpty());
  441. if (IsOrdered)
  442. Stack.back().first.back().OrderedRegion.emplace(Param, Clause);
  443. else
  444. Stack.back().first.back().OrderedRegion.reset();
  445. }
  446. /// Returns true, if region is ordered (has associated 'ordered' clause),
  447. /// false - otherwise.
  448. bool isOrderedRegion() const {
  449. if (isStackEmpty())
  450. return false;
  451. return Stack.back().first.rbegin()->OrderedRegion.hasValue();
  452. }
  453. /// Returns optional parameter for the ordered region.
  454. std::pair<const Expr *, OMPOrderedClause *> getOrderedRegionParam() const {
  455. if (isStackEmpty() ||
  456. !Stack.back().first.rbegin()->OrderedRegion.hasValue())
  457. return std::make_pair(nullptr, nullptr);
  458. return Stack.back().first.rbegin()->OrderedRegion.getValue();
  459. }
  460. /// Returns true, if parent region is ordered (has associated
  461. /// 'ordered' clause), false - otherwise.
  462. bool isParentOrderedRegion() const {
  463. if (isStackEmpty() || Stack.back().first.size() == 1)
  464. return false;
  465. return std::next(Stack.back().first.rbegin())->OrderedRegion.hasValue();
  466. }
  467. /// Returns optional parameter for the ordered region.
  468. std::pair<const Expr *, OMPOrderedClause *>
  469. getParentOrderedRegionParam() const {
  470. if (isStackEmpty() || Stack.back().first.size() == 1 ||
  471. !std::next(Stack.back().first.rbegin())->OrderedRegion.hasValue())
  472. return std::make_pair(nullptr, nullptr);
  473. return std::next(Stack.back().first.rbegin())->OrderedRegion.getValue();
  474. }
  475. /// Marks current region as nowait (it has a 'nowait' clause).
  476. void setNowaitRegion(bool IsNowait = true) {
  477. assert(!isStackEmpty());
  478. Stack.back().first.back().NowaitRegion = IsNowait;
  479. }
  480. /// Returns true, if parent region is nowait (has associated
  481. /// 'nowait' clause), false - otherwise.
  482. bool isParentNowaitRegion() const {
  483. if (isStackEmpty() || Stack.back().first.size() == 1)
  484. return false;
  485. return std::next(Stack.back().first.rbegin())->NowaitRegion;
  486. }
  487. /// Marks parent region as cancel region.
  488. void setParentCancelRegion(bool Cancel = true) {
  489. if (!isStackEmpty() && Stack.back().first.size() > 1) {
  490. auto &StackElemRef = *std::next(Stack.back().first.rbegin());
  491. StackElemRef.CancelRegion |= StackElemRef.CancelRegion || Cancel;
  492. }
  493. }
  494. /// Return true if current region has inner cancel construct.
  495. bool isCancelRegion() const {
  496. return isStackEmpty() ? false : Stack.back().first.back().CancelRegion;
  497. }
  498. /// Set collapse value for the region.
  499. void setAssociatedLoops(unsigned Val) {
  500. assert(!isStackEmpty());
  501. Stack.back().first.back().AssociatedLoops = Val;
  502. }
  503. /// Return collapse value for region.
  504. unsigned getAssociatedLoops() const {
  505. return isStackEmpty() ? 0 : Stack.back().first.back().AssociatedLoops;
  506. }
  507. /// Marks current target region as one with closely nested teams
  508. /// region.
  509. void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
  510. if (!isStackEmpty() && Stack.back().first.size() > 1) {
  511. std::next(Stack.back().first.rbegin())->InnerTeamsRegionLoc =
  512. TeamsRegionLoc;
  513. }
  514. }
  515. /// Returns true, if current region has closely nested teams region.
  516. bool hasInnerTeamsRegion() const {
  517. return getInnerTeamsRegionLoc().isValid();
  518. }
  519. /// Returns location of the nested teams region (if any).
  520. SourceLocation getInnerTeamsRegionLoc() const {
  521. return isStackEmpty() ? SourceLocation()
  522. : Stack.back().first.back().InnerTeamsRegionLoc;
  523. }
  524. Scope *getCurScope() const {
  525. return isStackEmpty() ? nullptr : Stack.back().first.back().CurScope;
  526. }
  527. SourceLocation getConstructLoc() const {
  528. return isStackEmpty() ? SourceLocation()
  529. : Stack.back().first.back().ConstructLoc;
  530. }
  531. /// Do the check specified in \a Check to all component lists and return true
  532. /// if any issue is found.
  533. bool checkMappableExprComponentListsForDecl(
  534. const ValueDecl *VD, bool CurrentRegionOnly,
  535. const llvm::function_ref<
  536. bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
  537. OpenMPClauseKind)>
  538. Check) const {
  539. if (isStackEmpty())
  540. return false;
  541. auto SI = Stack.back().first.rbegin();
  542. auto SE = Stack.back().first.rend();
  543. if (SI == SE)
  544. return false;
  545. if (CurrentRegionOnly)
  546. SE = std::next(SI);
  547. else
  548. std::advance(SI, 1);
  549. for (; SI != SE; ++SI) {
  550. auto MI = SI->MappedExprComponents.find(VD);
  551. if (MI != SI->MappedExprComponents.end())
  552. for (OMPClauseMappableExprCommon::MappableExprComponentListRef L :
  553. MI->second.Components)
  554. if (Check(L, MI->second.Kind))
  555. return true;
  556. }
  557. return false;
  558. }
  559. /// Do the check specified in \a Check to all component lists at a given level
  560. /// and return true if any issue is found.
  561. bool checkMappableExprComponentListsForDeclAtLevel(
  562. const ValueDecl *VD, unsigned Level,
  563. const llvm::function_ref<
  564. bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
  565. OpenMPClauseKind)>
  566. Check) const {
  567. if (isStackEmpty())
  568. return false;
  569. auto StartI = Stack.back().first.begin();
  570. auto EndI = Stack.back().first.end();
  571. if (std::distance(StartI, EndI) <= (int)Level)
  572. return false;
  573. std::advance(StartI, Level);
  574. auto MI = StartI->MappedExprComponents.find(VD);
  575. if (MI != StartI->MappedExprComponents.end())
  576. for (OMPClauseMappableExprCommon::MappableExprComponentListRef L :
  577. MI->second.Components)
  578. if (Check(L, MI->second.Kind))
  579. return true;
  580. return false;
  581. }
  582. /// Create a new mappable expression component list associated with a given
  583. /// declaration and initialize it with the provided list of components.
  584. void addMappableExpressionComponents(
  585. const ValueDecl *VD,
  586. OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
  587. OpenMPClauseKind WhereFoundClauseKind) {
  588. assert(!isStackEmpty() &&
  589. "Not expecting to retrieve components from a empty stack!");
  590. MappedExprComponentTy &MEC =
  591. Stack.back().first.back().MappedExprComponents[VD];
  592. // Create new entry and append the new components there.
  593. MEC.Components.resize(MEC.Components.size() + 1);
  594. MEC.Components.back().append(Components.begin(), Components.end());
  595. MEC.Kind = WhereFoundClauseKind;
  596. }
  597. unsigned getNestingLevel() const {
  598. assert(!isStackEmpty());
  599. return Stack.back().first.size() - 1;
  600. }
  601. void addDoacrossDependClause(OMPDependClause *C,
  602. const OperatorOffsetTy &OpsOffs) {
  603. assert(!isStackEmpty() && Stack.back().first.size() > 1);
  604. SharingMapTy &StackElem = *std::next(Stack.back().first.rbegin());
  605. assert(isOpenMPWorksharingDirective(StackElem.Directive));
  606. StackElem.DoacrossDepends.try_emplace(C, OpsOffs);
  607. }
  608. llvm::iterator_range<DoacrossDependMapTy::const_iterator>
  609. getDoacrossDependClauses() const {
  610. assert(!isStackEmpty());
  611. const SharingMapTy &StackElem = Stack.back().first.back();
  612. if (isOpenMPWorksharingDirective(StackElem.Directive)) {
  613. const DoacrossDependMapTy &Ref = StackElem.DoacrossDepends;
  614. return llvm::make_range(Ref.begin(), Ref.end());
  615. }
  616. return llvm::make_range(StackElem.DoacrossDepends.end(),
  617. StackElem.DoacrossDepends.end());
  618. }
  619. // Store types of classes which have been explicitly mapped
  620. void addMappedClassesQualTypes(QualType QT) {
  621. SharingMapTy &StackElem = Stack.back().first.back();
  622. StackElem.MappedClassesQualTypes.insert(QT);
  623. }
  624. // Return set of mapped classes types
  625. bool isClassPreviouslyMapped(QualType QT) const {
  626. const SharingMapTy &StackElem = Stack.back().first.back();
  627. return StackElem.MappedClassesQualTypes.count(QT) != 0;
  628. }
  629. /// Adds global declare target to the parent target region.
  630. void addToParentTargetRegionLinkGlobals(DeclRefExpr *E) {
  631. assert(*OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(
  632. E->getDecl()) == OMPDeclareTargetDeclAttr::MT_Link &&
  633. "Expected declare target link global.");
  634. if (isStackEmpty())
  635. return;
  636. auto It = Stack.back().first.rbegin();
  637. while (It != Stack.back().first.rend() &&
  638. !isOpenMPTargetExecutionDirective(It->Directive))
  639. ++It;
  640. if (It != Stack.back().first.rend()) {
  641. assert(isOpenMPTargetExecutionDirective(It->Directive) &&
  642. "Expected target executable directive.");
  643. It->DeclareTargetLinkVarDecls.push_back(E);
  644. }
  645. }
  646. /// Returns the list of globals with declare target link if current directive
  647. /// is target.
  648. ArrayRef<DeclRefExpr *> getLinkGlobals() const {
  649. assert(isOpenMPTargetExecutionDirective(getCurrentDirective()) &&
  650. "Expected target executable directive.");
  651. return Stack.back().first.back().DeclareTargetLinkVarDecls;
  652. }
  653. };
  654. bool isImplicitTaskingRegion(OpenMPDirectiveKind DKind) {
  655. return isOpenMPParallelDirective(DKind) || isOpenMPTeamsDirective(DKind);
  656. }
  657. bool isImplicitOrExplicitTaskingRegion(OpenMPDirectiveKind DKind) {
  658. return isImplicitTaskingRegion(DKind) || isOpenMPTaskingDirective(DKind) || DKind == OMPD_unknown;
  659. }
  660. } // namespace
  661. static const Expr *getExprAsWritten(const Expr *E) {
  662. if (const auto *FE = dyn_cast<FullExpr>(E))
  663. E = FE->getSubExpr();
  664. if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
  665. E = MTE->GetTemporaryExpr();
  666. while (const auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
  667. E = Binder->getSubExpr();
  668. if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
  669. E = ICE->getSubExprAsWritten();
  670. return E->IgnoreParens();
  671. }
  672. static Expr *getExprAsWritten(Expr *E) {
  673. return const_cast<Expr *>(getExprAsWritten(const_cast<const Expr *>(E)));
  674. }
  675. static const ValueDecl *getCanonicalDecl(const ValueDecl *D) {
  676. if (const auto *CED = dyn_cast<OMPCapturedExprDecl>(D))
  677. if (const auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
  678. D = ME->getMemberDecl();
  679. const auto *VD = dyn_cast<VarDecl>(D);
  680. const auto *FD = dyn_cast<FieldDecl>(D);
  681. if (VD != nullptr) {
  682. VD = VD->getCanonicalDecl();
  683. D = VD;
  684. } else {
  685. assert(FD);
  686. FD = FD->getCanonicalDecl();
  687. D = FD;
  688. }
  689. return D;
  690. }
  691. static ValueDecl *getCanonicalDecl(ValueDecl *D) {
  692. return const_cast<ValueDecl *>(
  693. getCanonicalDecl(const_cast<const ValueDecl *>(D)));
  694. }
  695. DSAStackTy::DSAVarData DSAStackTy::getDSA(iterator &Iter,
  696. ValueDecl *D) const {
  697. D = getCanonicalDecl(D);
  698. auto *VD = dyn_cast<VarDecl>(D);
  699. const auto *FD = dyn_cast<FieldDecl>(D);
  700. DSAVarData DVar;
  701. if (isStackEmpty() || Iter == Stack.back().first.rend()) {
  702. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  703. // in a region but not in construct]
  704. // File-scope or namespace-scope variables referenced in called routines
  705. // in the region are shared unless they appear in a threadprivate
  706. // directive.
  707. if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(VD))
  708. DVar.CKind = OMPC_shared;
  709. // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
  710. // in a region but not in construct]
  711. // Variables with static storage duration that are declared in called
  712. // routines in the region are shared.
  713. if (VD && VD->hasGlobalStorage())
  714. DVar.CKind = OMPC_shared;
  715. // Non-static data members are shared by default.
  716. if (FD)
  717. DVar.CKind = OMPC_shared;
  718. return DVar;
  719. }
  720. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  721. // in a Construct, C/C++, predetermined, p.1]
  722. // Variables with automatic storage duration that are declared in a scope
  723. // inside the construct are private.
  724. if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() &&
  725. (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) {
  726. DVar.CKind = OMPC_private;
  727. return DVar;
  728. }
  729. DVar.DKind = Iter->Directive;
  730. // Explicitly specified attributes and local variables with predetermined
  731. // attributes.
  732. if (Iter->SharingMap.count(D)) {
  733. const DSAInfo &Data = Iter->SharingMap.lookup(D);
  734. DVar.RefExpr = Data.RefExpr.getPointer();
  735. DVar.PrivateCopy = Data.PrivateCopy;
  736. DVar.CKind = Data.Attributes;
  737. DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
  738. return DVar;
  739. }
  740. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  741. // in a Construct, C/C++, implicitly determined, p.1]
  742. // In a parallel or task construct, the data-sharing attributes of these
  743. // variables are determined by the default clause, if present.
  744. switch (Iter->DefaultAttr) {
  745. case DSA_shared:
  746. DVar.CKind = OMPC_shared;
  747. DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
  748. return DVar;
  749. case DSA_none:
  750. return DVar;
  751. case DSA_unspecified:
  752. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  753. // in a Construct, implicitly determined, p.2]
  754. // In a parallel construct, if no default clause is present, these
  755. // variables are shared.
  756. DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
  757. if (isOpenMPParallelDirective(DVar.DKind) ||
  758. isOpenMPTeamsDirective(DVar.DKind)) {
  759. DVar.CKind = OMPC_shared;
  760. return DVar;
  761. }
  762. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  763. // in a Construct, implicitly determined, p.4]
  764. // In a task construct, if no default clause is present, a variable that in
  765. // the enclosing context is determined to be shared by all implicit tasks
  766. // bound to the current team is shared.
  767. if (isOpenMPTaskingDirective(DVar.DKind)) {
  768. DSAVarData DVarTemp;
  769. iterator I = Iter, E = Stack.back().first.rend();
  770. do {
  771. ++I;
  772. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
  773. // Referenced in a Construct, implicitly determined, p.6]
  774. // In a task construct, if no default clause is present, a variable
  775. // whose data-sharing attribute is not determined by the rules above is
  776. // firstprivate.
  777. DVarTemp = getDSA(I, D);
  778. if (DVarTemp.CKind != OMPC_shared) {
  779. DVar.RefExpr = nullptr;
  780. DVar.CKind = OMPC_firstprivate;
  781. return DVar;
  782. }
  783. } while (I != E && !isImplicitTaskingRegion(I->Directive));
  784. DVar.CKind =
  785. (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
  786. return DVar;
  787. }
  788. }
  789. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  790. // in a Construct, implicitly determined, p.3]
  791. // For constructs other than task, if no default clause is present, these
  792. // variables inherit their data-sharing attributes from the enclosing
  793. // context.
  794. return getDSA(++Iter, D);
  795. }
  796. const Expr *DSAStackTy::addUniqueAligned(const ValueDecl *D,
  797. const Expr *NewDE) {
  798. assert(!isStackEmpty() && "Data sharing attributes stack is empty");
  799. D = getCanonicalDecl(D);
  800. SharingMapTy &StackElem = Stack.back().first.back();
  801. auto It = StackElem.AlignedMap.find(D);
  802. if (It == StackElem.AlignedMap.end()) {
  803. assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
  804. StackElem.AlignedMap[D] = NewDE;
  805. return nullptr;
  806. }
  807. assert(It->second && "Unexpected nullptr expr in the aligned map");
  808. return It->second;
  809. }
  810. void DSAStackTy::addLoopControlVariable(const ValueDecl *D, VarDecl *Capture) {
  811. assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
  812. D = getCanonicalDecl(D);
  813. SharingMapTy &StackElem = Stack.back().first.back();
  814. StackElem.LCVMap.try_emplace(
  815. D, LCDeclInfo(StackElem.LCVMap.size() + 1, Capture));
  816. }
  817. const DSAStackTy::LCDeclInfo
  818. DSAStackTy::isLoopControlVariable(const ValueDecl *D) const {
  819. assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
  820. D = getCanonicalDecl(D);
  821. const SharingMapTy &StackElem = Stack.back().first.back();
  822. auto It = StackElem.LCVMap.find(D);
  823. if (It != StackElem.LCVMap.end())
  824. return It->second;
  825. return {0, nullptr};
  826. }
  827. const DSAStackTy::LCDeclInfo
  828. DSAStackTy::isParentLoopControlVariable(const ValueDecl *D) const {
  829. assert(!isStackEmpty() && Stack.back().first.size() > 1 &&
  830. "Data-sharing attributes stack is empty");
  831. D = getCanonicalDecl(D);
  832. const SharingMapTy &StackElem = *std::next(Stack.back().first.rbegin());
  833. auto It = StackElem.LCVMap.find(D);
  834. if (It != StackElem.LCVMap.end())
  835. return It->second;
  836. return {0, nullptr};
  837. }
  838. const ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) const {
  839. assert(!isStackEmpty() && Stack.back().first.size() > 1 &&
  840. "Data-sharing attributes stack is empty");
  841. const SharingMapTy &StackElem = *std::next(Stack.back().first.rbegin());
  842. if (StackElem.LCVMap.size() < I)
  843. return nullptr;
  844. for (const auto &Pair : StackElem.LCVMap)
  845. if (Pair.second.first == I)
  846. return Pair.first;
  847. return nullptr;
  848. }
  849. void DSAStackTy::addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A,
  850. DeclRefExpr *PrivateCopy) {
  851. D = getCanonicalDecl(D);
  852. if (A == OMPC_threadprivate) {
  853. DSAInfo &Data = Threadprivates[D];
  854. Data.Attributes = A;
  855. Data.RefExpr.setPointer(E);
  856. Data.PrivateCopy = nullptr;
  857. } else {
  858. assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
  859. DSAInfo &Data = Stack.back().first.back().SharingMap[D];
  860. assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) ||
  861. (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) ||
  862. (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) ||
  863. (isLoopControlVariable(D).first && A == OMPC_private));
  864. if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) {
  865. Data.RefExpr.setInt(/*IntVal=*/true);
  866. return;
  867. }
  868. const bool IsLastprivate =
  869. A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate;
  870. Data.Attributes = A;
  871. Data.RefExpr.setPointerAndInt(E, IsLastprivate);
  872. Data.PrivateCopy = PrivateCopy;
  873. if (PrivateCopy) {
  874. DSAInfo &Data =
  875. Stack.back().first.back().SharingMap[PrivateCopy->getDecl()];
  876. Data.Attributes = A;
  877. Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate);
  878. Data.PrivateCopy = nullptr;
  879. }
  880. }
  881. }
  882. /// Build a variable declaration for OpenMP loop iteration variable.
  883. static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
  884. StringRef Name, const AttrVec *Attrs = nullptr,
  885. DeclRefExpr *OrigRef = nullptr) {
  886. DeclContext *DC = SemaRef.CurContext;
  887. IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
  888. TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
  889. auto *Decl =
  890. VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
  891. if (Attrs) {
  892. for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end());
  893. I != E; ++I)
  894. Decl->addAttr(*I);
  895. }
  896. Decl->setImplicit();
  897. if (OrigRef) {
  898. Decl->addAttr(
  899. OMPReferencedVarAttr::CreateImplicit(SemaRef.Context, OrigRef));
  900. }
  901. return Decl;
  902. }
  903. static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
  904. SourceLocation Loc,
  905. bool RefersToCapture = false) {
  906. D->setReferenced();
  907. D->markUsed(S.Context);
  908. return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
  909. SourceLocation(), D, RefersToCapture, Loc, Ty,
  910. VK_LValue);
  911. }
  912. void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
  913. BinaryOperatorKind BOK) {
  914. D = getCanonicalDecl(D);
  915. assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
  916. assert(
  917. Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction &&
  918. "Additional reduction info may be specified only for reduction items.");
  919. ReductionData &ReductionData = Stack.back().first.back().ReductionMap[D];
  920. assert(ReductionData.ReductionRange.isInvalid() &&
  921. Stack.back().first.back().Directive == OMPD_taskgroup &&
  922. "Additional reduction info may be specified only once for reduction "
  923. "items.");
  924. ReductionData.set(BOK, SR);
  925. Expr *&TaskgroupReductionRef =
  926. Stack.back().first.back().TaskgroupReductionRef;
  927. if (!TaskgroupReductionRef) {
  928. VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(),
  929. SemaRef.Context.VoidPtrTy, ".task_red.");
  930. TaskgroupReductionRef =
  931. buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
  932. }
  933. }
  934. void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
  935. const Expr *ReductionRef) {
  936. D = getCanonicalDecl(D);
  937. assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
  938. assert(
  939. Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction &&
  940. "Additional reduction info may be specified only for reduction items.");
  941. ReductionData &ReductionData = Stack.back().first.back().ReductionMap[D];
  942. assert(ReductionData.ReductionRange.isInvalid() &&
  943. Stack.back().first.back().Directive == OMPD_taskgroup &&
  944. "Additional reduction info may be specified only once for reduction "
  945. "items.");
  946. ReductionData.set(ReductionRef, SR);
  947. Expr *&TaskgroupReductionRef =
  948. Stack.back().first.back().TaskgroupReductionRef;
  949. if (!TaskgroupReductionRef) {
  950. VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(),
  951. SemaRef.Context.VoidPtrTy, ".task_red.");
  952. TaskgroupReductionRef =
  953. buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
  954. }
  955. }
  956. const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData(
  957. const ValueDecl *D, SourceRange &SR, BinaryOperatorKind &BOK,
  958. Expr *&TaskgroupDescriptor) const {
  959. D = getCanonicalDecl(D);
  960. assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
  961. if (Stack.back().first.empty())
  962. return DSAVarData();
  963. for (iterator I = std::next(Stack.back().first.rbegin(), 1),
  964. E = Stack.back().first.rend();
  965. I != E; std::advance(I, 1)) {
  966. const DSAInfo &Data = I->SharingMap.lookup(D);
  967. if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
  968. continue;
  969. const ReductionData &ReductionData = I->ReductionMap.lookup(D);
  970. if (!ReductionData.ReductionOp ||
  971. ReductionData.ReductionOp.is<const Expr *>())
  972. return DSAVarData();
  973. SR = ReductionData.ReductionRange;
  974. BOK = ReductionData.ReductionOp.get<ReductionData::BOKPtrType>();
  975. assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
  976. "expression for the descriptor is not "
  977. "set.");
  978. TaskgroupDescriptor = I->TaskgroupReductionRef;
  979. return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
  980. Data.PrivateCopy, I->DefaultAttrLoc);
  981. }
  982. return DSAVarData();
  983. }
  984. const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData(
  985. const ValueDecl *D, SourceRange &SR, const Expr *&ReductionRef,
  986. Expr *&TaskgroupDescriptor) const {
  987. D = getCanonicalDecl(D);
  988. assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
  989. if (Stack.back().first.empty())
  990. return DSAVarData();
  991. for (iterator I = std::next(Stack.back().first.rbegin(), 1),
  992. E = Stack.back().first.rend();
  993. I != E; std::advance(I, 1)) {
  994. const DSAInfo &Data = I->SharingMap.lookup(D);
  995. if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
  996. continue;
  997. const ReductionData &ReductionData = I->ReductionMap.lookup(D);
  998. if (!ReductionData.ReductionOp ||
  999. !ReductionData.ReductionOp.is<const Expr *>())
  1000. return DSAVarData();
  1001. SR = ReductionData.ReductionRange;
  1002. ReductionRef = ReductionData.ReductionOp.get<const Expr *>();
  1003. assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
  1004. "expression for the descriptor is not "
  1005. "set.");
  1006. TaskgroupDescriptor = I->TaskgroupReductionRef;
  1007. return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
  1008. Data.PrivateCopy, I->DefaultAttrLoc);
  1009. }
  1010. return DSAVarData();
  1011. }
  1012. bool DSAStackTy::isOpenMPLocal(VarDecl *D, iterator Iter) const {
  1013. D = D->getCanonicalDecl();
  1014. if (!isStackEmpty()) {
  1015. iterator I = Iter, E = Stack.back().first.rend();
  1016. Scope *TopScope = nullptr;
  1017. while (I != E && !isImplicitOrExplicitTaskingRegion(I->Directive) &&
  1018. !isOpenMPTargetExecutionDirective(I->Directive))
  1019. ++I;
  1020. if (I == E)
  1021. return false;
  1022. TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
  1023. Scope *CurScope = getCurScope();
  1024. while (CurScope != TopScope && !CurScope->isDeclScope(D))
  1025. CurScope = CurScope->getParent();
  1026. return CurScope != TopScope;
  1027. }
  1028. return false;
  1029. }
  1030. static bool isConstNotMutableType(Sema &SemaRef, QualType Type,
  1031. bool AcceptIfMutable = true,
  1032. bool *IsClassType = nullptr) {
  1033. ASTContext &Context = SemaRef.getASTContext();
  1034. Type = Type.getNonReferenceType().getCanonicalType();
  1035. bool IsConstant = Type.isConstant(Context);
  1036. Type = Context.getBaseElementType(Type);
  1037. const CXXRecordDecl *RD = AcceptIfMutable && SemaRef.getLangOpts().CPlusPlus
  1038. ? Type->getAsCXXRecordDecl()
  1039. : nullptr;
  1040. if (const auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD))
  1041. if (const ClassTemplateDecl *CTD = CTSD->getSpecializedTemplate())
  1042. RD = CTD->getTemplatedDecl();
  1043. if (IsClassType)
  1044. *IsClassType = RD;
  1045. return IsConstant && !(SemaRef.getLangOpts().CPlusPlus && RD &&
  1046. RD->hasDefinition() && RD->hasMutableFields());
  1047. }
  1048. static bool rejectConstNotMutableType(Sema &SemaRef, const ValueDecl *D,
  1049. QualType Type, OpenMPClauseKind CKind,
  1050. SourceLocation ELoc,
  1051. bool AcceptIfMutable = true,
  1052. bool ListItemNotVar = false) {
  1053. ASTContext &Context = SemaRef.getASTContext();
  1054. bool IsClassType;
  1055. if (isConstNotMutableType(SemaRef, Type, AcceptIfMutable, &IsClassType)) {
  1056. unsigned Diag = ListItemNotVar
  1057. ? diag::err_omp_const_list_item
  1058. : IsClassType ? diag::err_omp_const_not_mutable_variable
  1059. : diag::err_omp_const_variable;
  1060. SemaRef.Diag(ELoc, Diag) << getOpenMPClauseName(CKind);
  1061. if (!ListItemNotVar && D) {
  1062. const VarDecl *VD = dyn_cast<VarDecl>(D);
  1063. bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
  1064. VarDecl::DeclarationOnly;
  1065. SemaRef.Diag(D->getLocation(),
  1066. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  1067. << D;
  1068. }
  1069. return true;
  1070. }
  1071. return false;
  1072. }
  1073. const DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D,
  1074. bool FromParent) {
  1075. D = getCanonicalDecl(D);
  1076. DSAVarData DVar;
  1077. auto *VD = dyn_cast<VarDecl>(D);
  1078. auto TI = Threadprivates.find(D);
  1079. if (TI != Threadprivates.end()) {
  1080. DVar.RefExpr = TI->getSecond().RefExpr.getPointer();
  1081. DVar.CKind = OMPC_threadprivate;
  1082. return DVar;
  1083. }
  1084. if (VD && VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
  1085. DVar.RefExpr = buildDeclRefExpr(
  1086. SemaRef, VD, D->getType().getNonReferenceType(),
  1087. VD->getAttr<OMPThreadPrivateDeclAttr>()->getLocation());
  1088. DVar.CKind = OMPC_threadprivate;
  1089. addDSA(D, DVar.RefExpr, OMPC_threadprivate);
  1090. return DVar;
  1091. }
  1092. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  1093. // in a Construct, C/C++, predetermined, p.1]
  1094. // Variables appearing in threadprivate directives are threadprivate.
  1095. if ((VD && VD->getTLSKind() != VarDecl::TLS_None &&
  1096. !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
  1097. SemaRef.getLangOpts().OpenMPUseTLS &&
  1098. SemaRef.getASTContext().getTargetInfo().isTLSSupported())) ||
  1099. (VD && VD->getStorageClass() == SC_Register &&
  1100. VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) {
  1101. DVar.RefExpr = buildDeclRefExpr(
  1102. SemaRef, VD, D->getType().getNonReferenceType(), D->getLocation());
  1103. DVar.CKind = OMPC_threadprivate;
  1104. addDSA(D, DVar.RefExpr, OMPC_threadprivate);
  1105. return DVar;
  1106. }
  1107. if (SemaRef.getLangOpts().OpenMPCUDAMode && VD &&
  1108. VD->isLocalVarDeclOrParm() && !isStackEmpty() &&
  1109. !isLoopControlVariable(D).first) {
  1110. iterator IterTarget =
  1111. std::find_if(Stack.back().first.rbegin(), Stack.back().first.rend(),
  1112. [](const SharingMapTy &Data) {
  1113. return isOpenMPTargetExecutionDirective(Data.Directive);
  1114. });
  1115. if (IterTarget != Stack.back().first.rend()) {
  1116. iterator ParentIterTarget = std::next(IterTarget, 1);
  1117. for (iterator Iter = Stack.back().first.rbegin();
  1118. Iter != ParentIterTarget; std::advance(Iter, 1)) {
  1119. if (isOpenMPLocal(VD, Iter)) {
  1120. DVar.RefExpr =
  1121. buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
  1122. D->getLocation());
  1123. DVar.CKind = OMPC_threadprivate;
  1124. return DVar;
  1125. }
  1126. }
  1127. if (!isClauseParsingMode() || IterTarget != Stack.back().first.rbegin()) {
  1128. auto DSAIter = IterTarget->SharingMap.find(D);
  1129. if (DSAIter != IterTarget->SharingMap.end() &&
  1130. isOpenMPPrivate(DSAIter->getSecond().Attributes)) {
  1131. DVar.RefExpr = DSAIter->getSecond().RefExpr.getPointer();
  1132. DVar.CKind = OMPC_threadprivate;
  1133. return DVar;
  1134. }
  1135. iterator End = Stack.back().first.rend();
  1136. if (!SemaRef.isOpenMPCapturedByRef(
  1137. D, std::distance(ParentIterTarget, End))) {
  1138. DVar.RefExpr =
  1139. buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
  1140. IterTarget->ConstructLoc);
  1141. DVar.CKind = OMPC_threadprivate;
  1142. return DVar;
  1143. }
  1144. }
  1145. }
  1146. }
  1147. if (isStackEmpty())
  1148. // Not in OpenMP execution region and top scope was already checked.
  1149. return DVar;
  1150. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  1151. // in a Construct, C/C++, predetermined, p.4]
  1152. // Static data members are shared.
  1153. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  1154. // in a Construct, C/C++, predetermined, p.7]
  1155. // Variables with static storage duration that are declared in a scope
  1156. // inside the construct are shared.
  1157. auto &&MatchesAlways = [](OpenMPDirectiveKind) { return true; };
  1158. if (VD && VD->isStaticDataMember()) {
  1159. DSAVarData DVarTemp = hasDSA(D, isOpenMPPrivate, MatchesAlways, FromParent);
  1160. if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
  1161. return DVar;
  1162. DVar.CKind = OMPC_shared;
  1163. return DVar;
  1164. }
  1165. // The predetermined shared attribute for const-qualified types having no
  1166. // mutable members was removed after OpenMP 3.1.
  1167. if (SemaRef.LangOpts.OpenMP <= 31) {
  1168. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  1169. // in a Construct, C/C++, predetermined, p.6]
  1170. // Variables with const qualified type having no mutable member are
  1171. // shared.
  1172. if (isConstNotMutableType(SemaRef, D->getType())) {
  1173. // Variables with const-qualified type having no mutable member may be
  1174. // listed in a firstprivate clause, even if they are static data members.
  1175. DSAVarData DVarTemp = hasInnermostDSA(
  1176. D,
  1177. [](OpenMPClauseKind C) {
  1178. return C == OMPC_firstprivate || C == OMPC_shared;
  1179. },
  1180. MatchesAlways, FromParent);
  1181. if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
  1182. return DVarTemp;
  1183. DVar.CKind = OMPC_shared;
  1184. return DVar;
  1185. }
  1186. }
  1187. // Explicitly specified attributes and local variables with predetermined
  1188. // attributes.
  1189. iterator I = Stack.back().first.rbegin();
  1190. iterator EndI = Stack.back().first.rend();
  1191. if (FromParent && I != EndI)
  1192. std::advance(I, 1);
  1193. auto It = I->SharingMap.find(D);
  1194. if (It != I->SharingMap.end()) {
  1195. const DSAInfo &Data = It->getSecond();
  1196. DVar.RefExpr = Data.RefExpr.getPointer();
  1197. DVar.PrivateCopy = Data.PrivateCopy;
  1198. DVar.CKind = Data.Attributes;
  1199. DVar.ImplicitDSALoc = I->DefaultAttrLoc;
  1200. DVar.DKind = I->Directive;
  1201. }
  1202. return DVar;
  1203. }
  1204. const DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
  1205. bool FromParent) const {
  1206. if (isStackEmpty()) {
  1207. iterator I;
  1208. return getDSA(I, D);
  1209. }
  1210. D = getCanonicalDecl(D);
  1211. iterator StartI = Stack.back().first.rbegin();
  1212. iterator EndI = Stack.back().first.rend();
  1213. if (FromParent && StartI != EndI)
  1214. std::advance(StartI, 1);
  1215. return getDSA(StartI, D);
  1216. }
  1217. const DSAStackTy::DSAVarData
  1218. DSAStackTy::hasDSA(ValueDecl *D,
  1219. const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
  1220. const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
  1221. bool FromParent) const {
  1222. if (isStackEmpty())
  1223. return {};
  1224. D = getCanonicalDecl(D);
  1225. iterator I = Stack.back().first.rbegin();
  1226. iterator EndI = Stack.back().first.rend();
  1227. if (FromParent && I != EndI)
  1228. std::advance(I, 1);
  1229. for (; I != EndI; std::advance(I, 1)) {
  1230. if (!DPred(I->Directive) && !isImplicitOrExplicitTaskingRegion(I->Directive))
  1231. continue;
  1232. iterator NewI = I;
  1233. DSAVarData DVar = getDSA(NewI, D);
  1234. if (I == NewI && CPred(DVar.CKind))
  1235. return DVar;
  1236. }
  1237. return {};
  1238. }
  1239. const DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA(
  1240. ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
  1241. const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
  1242. bool FromParent) const {
  1243. if (isStackEmpty())
  1244. return {};
  1245. D = getCanonicalDecl(D);
  1246. iterator StartI = Stack.back().first.rbegin();
  1247. iterator EndI = Stack.back().first.rend();
  1248. if (FromParent && StartI != EndI)
  1249. std::advance(StartI, 1);
  1250. if (StartI == EndI || !DPred(StartI->Directive))
  1251. return {};
  1252. iterator NewI = StartI;
  1253. DSAVarData DVar = getDSA(NewI, D);
  1254. return (NewI == StartI && CPred(DVar.CKind)) ? DVar : DSAVarData();
  1255. }
  1256. bool DSAStackTy::hasExplicitDSA(
  1257. const ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
  1258. unsigned Level, bool NotLastprivate) const {
  1259. if (isStackEmpty())
  1260. return false;
  1261. D = getCanonicalDecl(D);
  1262. auto StartI = Stack.back().first.begin();
  1263. auto EndI = Stack.back().first.end();
  1264. if (std::distance(StartI, EndI) <= (int)Level)
  1265. return false;
  1266. std::advance(StartI, Level);
  1267. auto I = StartI->SharingMap.find(D);
  1268. if ((I != StartI->SharingMap.end()) &&
  1269. I->getSecond().RefExpr.getPointer() &&
  1270. CPred(I->getSecond().Attributes) &&
  1271. (!NotLastprivate || !I->getSecond().RefExpr.getInt()))
  1272. return true;
  1273. // Check predetermined rules for the loop control variables.
  1274. auto LI = StartI->LCVMap.find(D);
  1275. if (LI != StartI->LCVMap.end())
  1276. return CPred(OMPC_private);
  1277. return false;
  1278. }
  1279. bool DSAStackTy::hasExplicitDirective(
  1280. const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
  1281. unsigned Level) const {
  1282. if (isStackEmpty())
  1283. return false;
  1284. auto StartI = Stack.back().first.begin();
  1285. auto EndI = Stack.back().first.end();
  1286. if (std::distance(StartI, EndI) <= (int)Level)
  1287. return false;
  1288. std::advance(StartI, Level);
  1289. return DPred(StartI->Directive);
  1290. }
  1291. bool DSAStackTy::hasDirective(
  1292. const llvm::function_ref<bool(OpenMPDirectiveKind,
  1293. const DeclarationNameInfo &, SourceLocation)>
  1294. DPred,
  1295. bool FromParent) const {
  1296. // We look only in the enclosing region.
  1297. if (isStackEmpty())
  1298. return false;
  1299. auto StartI = std::next(Stack.back().first.rbegin());
  1300. auto EndI = Stack.back().first.rend();
  1301. if (FromParent && StartI != EndI)
  1302. StartI = std::next(StartI);
  1303. for (auto I = StartI, EE = EndI; I != EE; ++I) {
  1304. if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
  1305. return true;
  1306. }
  1307. return false;
  1308. }
  1309. void Sema::InitDataSharingAttributesStack() {
  1310. VarDataSharingAttributesStack = new DSAStackTy(*this);
  1311. }
  1312. #define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
  1313. void Sema::pushOpenMPFunctionRegion() {
  1314. DSAStack->pushFunction();
  1315. }
  1316. void Sema::popOpenMPFunctionRegion(const FunctionScopeInfo *OldFSI) {
  1317. DSAStack->popFunction(OldFSI);
  1318. }
  1319. static bool isOpenMPDeviceDelayedContext(Sema &S) {
  1320. assert(S.LangOpts.OpenMP && S.LangOpts.OpenMPIsDevice &&
  1321. "Expected OpenMP device compilation.");
  1322. return !S.isInOpenMPTargetExecutionDirective() &&
  1323. !S.isInOpenMPDeclareTargetContext();
  1324. }
  1325. /// Do we know that we will eventually codegen the given function?
  1326. static bool isKnownEmitted(Sema &S, FunctionDecl *FD) {
  1327. assert(S.LangOpts.OpenMP && S.LangOpts.OpenMPIsDevice &&
  1328. "Expected OpenMP device compilation.");
  1329. // Templates are emitted when they're instantiated.
  1330. if (FD->isDependentContext())
  1331. return false;
  1332. if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(
  1333. FD->getCanonicalDecl()))
  1334. return true;
  1335. // Otherwise, the function is known-emitted if it's in our set of
  1336. // known-emitted functions.
  1337. return S.DeviceKnownEmittedFns.count(FD) > 0;
  1338. }
  1339. Sema::DeviceDiagBuilder Sema::diagIfOpenMPDeviceCode(SourceLocation Loc,
  1340. unsigned DiagID) {
  1341. assert(LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
  1342. "Expected OpenMP device compilation.");
  1343. return DeviceDiagBuilder((isOpenMPDeviceDelayedContext(*this) &&
  1344. !isKnownEmitted(*this, getCurFunctionDecl()))
  1345. ? DeviceDiagBuilder::K_Deferred
  1346. : DeviceDiagBuilder::K_Immediate,
  1347. Loc, DiagID, getCurFunctionDecl(), *this);
  1348. }
  1349. void Sema::checkOpenMPDeviceFunction(SourceLocation Loc, FunctionDecl *Callee) {
  1350. assert(LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
  1351. "Expected OpenMP device compilation.");
  1352. assert(Callee && "Callee may not be null.");
  1353. FunctionDecl *Caller = getCurFunctionDecl();
  1354. // If the caller is known-emitted, mark the callee as known-emitted.
  1355. // Otherwise, mark the call in our call graph so we can traverse it later.
  1356. if (!isOpenMPDeviceDelayedContext(*this) ||
  1357. (Caller && isKnownEmitted(*this, Caller)))
  1358. markKnownEmitted(*this, Caller, Callee, Loc, isKnownEmitted);
  1359. else if (Caller)
  1360. DeviceCallGraph[Caller].insert({Callee, Loc});
  1361. }
  1362. void Sema::checkOpenMPDeviceExpr(const Expr *E) {
  1363. assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
  1364. "OpenMP device compilation mode is expected.");
  1365. QualType Ty = E->getType();
  1366. if ((Ty->isFloat16Type() && !Context.getTargetInfo().hasFloat16Type()) ||
  1367. (Ty->isFloat128Type() && !Context.getTargetInfo().hasFloat128Type()) ||
  1368. (Ty->isIntegerType() && Context.getTypeSize(Ty) == 128 &&
  1369. !Context.getTargetInfo().hasInt128Type()))
  1370. targetDiag(E->getExprLoc(), diag::err_type_unsupported)
  1371. << Ty << E->getSourceRange();
  1372. }
  1373. bool Sema::isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level) const {
  1374. assert(LangOpts.OpenMP && "OpenMP is not allowed");
  1375. ASTContext &Ctx = getASTContext();
  1376. bool IsByRef = true;
  1377. // Find the directive that is associated with the provided scope.
  1378. D = cast<ValueDecl>(D->getCanonicalDecl());
  1379. QualType Ty = D->getType();
  1380. if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) {
  1381. // This table summarizes how a given variable should be passed to the device
  1382. // given its type and the clauses where it appears. This table is based on
  1383. // the description in OpenMP 4.5 [2.10.4, target Construct] and
  1384. // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses].
  1385. //
  1386. // =========================================================================
  1387. // | type | defaultmap | pvt | first | is_device_ptr | map | res. |
  1388. // | |(tofrom:scalar)| | pvt | | | |
  1389. // =========================================================================
  1390. // | scl | | | | - | | bycopy|
  1391. // | scl | | - | x | - | - | bycopy|
  1392. // | scl | | x | - | - | - | null |
  1393. // | scl | x | | | - | | byref |
  1394. // | scl | x | - | x | - | - | bycopy|
  1395. // | scl | x | x | - | - | - | null |
  1396. // | scl | | - | - | - | x | byref |
  1397. // | scl | x | - | - | - | x | byref |
  1398. //
  1399. // | agg | n.a. | | | - | | byref |
  1400. // | agg | n.a. | - | x | - | - | byref |
  1401. // | agg | n.a. | x | - | - | - | null |
  1402. // | agg | n.a. | - | - | - | x | byref |
  1403. // | agg | n.a. | - | - | - | x[] | byref |
  1404. //
  1405. // | ptr | n.a. | | | - | | bycopy|
  1406. // | ptr | n.a. | - | x | - | - | bycopy|
  1407. // | ptr | n.a. | x | - | - | - | null |
  1408. // | ptr | n.a. | - | - | - | x | byref |
  1409. // | ptr | n.a. | - | - | - | x[] | bycopy|
  1410. // | ptr | n.a. | - | - | x | | bycopy|
  1411. // | ptr | n.a. | - | - | x | x | bycopy|
  1412. // | ptr | n.a. | - | - | x | x[] | bycopy|
  1413. // =========================================================================
  1414. // Legend:
  1415. // scl - scalar
  1416. // ptr - pointer
  1417. // agg - aggregate
  1418. // x - applies
  1419. // - - invalid in this combination
  1420. // [] - mapped with an array section
  1421. // byref - should be mapped by reference
  1422. // byval - should be mapped by value
  1423. // null - initialize a local variable to null on the device
  1424. //
  1425. // Observations:
  1426. // - All scalar declarations that show up in a map clause have to be passed
  1427. // by reference, because they may have been mapped in the enclosing data
  1428. // environment.
  1429. // - If the scalar value does not fit the size of uintptr, it has to be
  1430. // passed by reference, regardless the result in the table above.
  1431. // - For pointers mapped by value that have either an implicit map or an
  1432. // array section, the runtime library may pass the NULL value to the
  1433. // device instead of the value passed to it by the compiler.
  1434. if (Ty->isReferenceType())
  1435. Ty = Ty->castAs<ReferenceType>()->getPointeeType();
  1436. // Locate map clauses and see if the variable being captured is referred to
  1437. // in any of those clauses. Here we only care about variables, not fields,
  1438. // because fields are part of aggregates.
  1439. bool IsVariableUsedInMapClause = false;
  1440. bool IsVariableAssociatedWithSection = false;
  1441. DSAStack->checkMappableExprComponentListsForDeclAtLevel(
  1442. D, Level,
  1443. [&IsVariableUsedInMapClause, &IsVariableAssociatedWithSection, D](
  1444. OMPClauseMappableExprCommon::MappableExprComponentListRef
  1445. MapExprComponents,
  1446. OpenMPClauseKind WhereFoundClauseKind) {
  1447. // Only the map clause information influences how a variable is
  1448. // captured. E.g. is_device_ptr does not require changing the default
  1449. // behavior.
  1450. if (WhereFoundClauseKind != OMPC_map)
  1451. return false;
  1452. auto EI = MapExprComponents.rbegin();
  1453. auto EE = MapExprComponents.rend();
  1454. assert(EI != EE && "Invalid map expression!");
  1455. if (isa<DeclRefExpr>(EI->getAssociatedExpression()))
  1456. IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D;
  1457. ++EI;
  1458. if (EI == EE)
  1459. return false;
  1460. if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) ||
  1461. isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) ||
  1462. isa<MemberExpr>(EI->getAssociatedExpression())) {
  1463. IsVariableAssociatedWithSection = true;
  1464. // There is nothing more we need to know about this variable.
  1465. return true;
  1466. }
  1467. // Keep looking for more map info.
  1468. return false;
  1469. });
  1470. if (IsVariableUsedInMapClause) {
  1471. // If variable is identified in a map clause it is always captured by
  1472. // reference except if it is a pointer that is dereferenced somehow.
  1473. IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection);
  1474. } else {
  1475. // By default, all the data that has a scalar type is mapped by copy
  1476. // (except for reduction variables).
  1477. IsByRef =
  1478. (DSAStack->isForceCaptureByReferenceInTargetExecutable() &&
  1479. !Ty->isAnyPointerType()) ||
  1480. !Ty->isScalarType() ||
  1481. DSAStack->getDefaultDMAAtLevel(Level) == DMA_tofrom_scalar ||
  1482. DSAStack->hasExplicitDSA(
  1483. D, [](OpenMPClauseKind K) { return K == OMPC_reduction; }, Level);
  1484. }
  1485. }
  1486. if (IsByRef && Ty.getNonReferenceType()->isScalarType()) {
  1487. IsByRef =
  1488. ((DSAStack->isForceCaptureByReferenceInTargetExecutable() &&
  1489. !Ty->isAnyPointerType()) ||
  1490. !DSAStack->hasExplicitDSA(
  1491. D,
  1492. [](OpenMPClauseKind K) -> bool { return K == OMPC_firstprivate; },
  1493. Level, /*NotLastprivate=*/true)) &&
  1494. // If the variable is artificial and must be captured by value - try to
  1495. // capture by value.
  1496. !(isa<OMPCapturedExprDecl>(D) && !D->hasAttr<OMPCaptureNoInitAttr>() &&
  1497. !cast<OMPCapturedExprDecl>(D)->getInit()->isGLValue());
  1498. }
  1499. // When passing data by copy, we need to make sure it fits the uintptr size
  1500. // and alignment, because the runtime library only deals with uintptr types.
  1501. // If it does not fit the uintptr size, we need to pass the data by reference
  1502. // instead.
  1503. if (!IsByRef &&
  1504. (Ctx.getTypeSizeInChars(Ty) >
  1505. Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) ||
  1506. Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) {
  1507. IsByRef = true;
  1508. }
  1509. return IsByRef;
  1510. }
  1511. unsigned Sema::getOpenMPNestingLevel() const {
  1512. assert(getLangOpts().OpenMP);
  1513. return DSAStack->getNestingLevel();
  1514. }
  1515. bool Sema::isInOpenMPTargetExecutionDirective() const {
  1516. return (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) &&
  1517. !DSAStack->isClauseParsingMode()) ||
  1518. DSAStack->hasDirective(
  1519. [](OpenMPDirectiveKind K, const DeclarationNameInfo &,
  1520. SourceLocation) -> bool {
  1521. return isOpenMPTargetExecutionDirective(K);
  1522. },
  1523. false);
  1524. }
  1525. VarDecl *Sema::isOpenMPCapturedDecl(ValueDecl *D) {
  1526. assert(LangOpts.OpenMP && "OpenMP is not allowed");
  1527. D = getCanonicalDecl(D);
  1528. // If we are attempting to capture a global variable in a directive with
  1529. // 'target' we return true so that this global is also mapped to the device.
  1530. //
  1531. auto *VD = dyn_cast<VarDecl>(D);
  1532. if (VD && !VD->hasLocalStorage()) {
  1533. if (isInOpenMPDeclareTargetContext() &&
  1534. (getCurCapturedRegion() || getCurBlock() || getCurLambda())) {
  1535. // Try to mark variable as declare target if it is used in capturing
  1536. // regions.
  1537. if (!OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
  1538. checkDeclIsAllowedInOpenMPTarget(nullptr, VD);
  1539. return nullptr;
  1540. } else if (isInOpenMPTargetExecutionDirective()) {
  1541. // If the declaration is enclosed in a 'declare target' directive,
  1542. // then it should not be captured.
  1543. //
  1544. if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
  1545. return nullptr;
  1546. return VD;
  1547. }
  1548. }
  1549. // Capture variables captured by reference in lambdas for target-based
  1550. // directives.
  1551. if (VD && !DSAStack->isClauseParsingMode()) {
  1552. if (const auto *RD = VD->getType()
  1553. .getCanonicalType()
  1554. .getNonReferenceType()
  1555. ->getAsCXXRecordDecl()) {
  1556. bool SavedForceCaptureByReferenceInTargetExecutable =
  1557. DSAStack->isForceCaptureByReferenceInTargetExecutable();
  1558. DSAStack->setForceCaptureByReferenceInTargetExecutable(/*V=*/true);
  1559. if (RD->isLambda()) {
  1560. llvm::DenseMap<const VarDecl *, FieldDecl *> Captures;
  1561. FieldDecl *ThisCapture;
  1562. RD->getCaptureFields(Captures, ThisCapture);
  1563. for (const LambdaCapture &LC : RD->captures()) {
  1564. if (LC.getCaptureKind() == LCK_ByRef) {
  1565. VarDecl *VD = LC.getCapturedVar();
  1566. DeclContext *VDC = VD->getDeclContext();
  1567. if (!VDC->Encloses(CurContext))
  1568. continue;
  1569. DSAStackTy::DSAVarData DVarPrivate =
  1570. DSAStack->getTopDSA(VD, /*FromParent=*/false);
  1571. // Do not capture already captured variables.
  1572. if (!OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD) &&
  1573. DVarPrivate.CKind == OMPC_unknown &&
  1574. !DSAStack->checkMappableExprComponentListsForDecl(
  1575. D, /*CurrentRegionOnly=*/true,
  1576. [](OMPClauseMappableExprCommon::
  1577. MappableExprComponentListRef,
  1578. OpenMPClauseKind) { return true; }))
  1579. MarkVariableReferenced(LC.getLocation(), LC.getCapturedVar());
  1580. } else if (LC.getCaptureKind() == LCK_This) {
  1581. QualType ThisTy = getCurrentThisType();
  1582. if (!ThisTy.isNull() &&
  1583. Context.typesAreCompatible(ThisTy, ThisCapture->getType()))
  1584. CheckCXXThisCapture(LC.getLocation());
  1585. }
  1586. }
  1587. }
  1588. DSAStack->setForceCaptureByReferenceInTargetExecutable(
  1589. SavedForceCaptureByReferenceInTargetExecutable);
  1590. }
  1591. }
  1592. if (DSAStack->getCurrentDirective() != OMPD_unknown &&
  1593. (!DSAStack->isClauseParsingMode() ||
  1594. DSAStack->getParentDirective() != OMPD_unknown)) {
  1595. auto &&Info = DSAStack->isLoopControlVariable(D);
  1596. if (Info.first ||
  1597. (VD && VD->hasLocalStorage() &&
  1598. isImplicitOrExplicitTaskingRegion(DSAStack->getCurrentDirective())) ||
  1599. (VD && DSAStack->isForceVarCapturing()))
  1600. return VD ? VD : Info.second;
  1601. DSAStackTy::DSAVarData DVarPrivate =
  1602. DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
  1603. if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
  1604. return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
  1605. DVarPrivate = DSAStack->hasDSA(D, isOpenMPPrivate,
  1606. [](OpenMPDirectiveKind) { return true; },
  1607. DSAStack->isClauseParsingMode());
  1608. if (DVarPrivate.CKind != OMPC_unknown)
  1609. return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
  1610. }
  1611. return nullptr;
  1612. }
  1613. void Sema::adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex,
  1614. unsigned Level) const {
  1615. SmallVector<OpenMPDirectiveKind, 4> Regions;
  1616. getOpenMPCaptureRegions(Regions, DSAStack->getDirective(Level));
  1617. FunctionScopesIndex -= Regions.size();
  1618. }
  1619. void Sema::startOpenMPLoop() {
  1620. assert(LangOpts.OpenMP && "OpenMP must be enabled.");
  1621. if (isOpenMPLoopDirective(DSAStack->getCurrentDirective()))
  1622. DSAStack->loopInit();
  1623. }
  1624. bool Sema::isOpenMPPrivateDecl(const ValueDecl *D, unsigned Level) const {
  1625. assert(LangOpts.OpenMP && "OpenMP is not allowed");
  1626. if (isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
  1627. if (DSAStack->getAssociatedLoops() > 0 &&
  1628. !DSAStack->isLoopStarted()) {
  1629. DSAStack->resetPossibleLoopCounter(D);
  1630. DSAStack->loopStart();
  1631. return true;
  1632. }
  1633. if ((DSAStack->getPossiblyLoopCunter() == D->getCanonicalDecl() ||
  1634. DSAStack->isLoopControlVariable(D).first) &&
  1635. !DSAStack->hasExplicitDSA(
  1636. D, [](OpenMPClauseKind K) { return K != OMPC_private; }, Level) &&
  1637. !isOpenMPSimdDirective(DSAStack->getCurrentDirective()))
  1638. return true;
  1639. }
  1640. return DSAStack->hasExplicitDSA(
  1641. D, [](OpenMPClauseKind K) { return K == OMPC_private; }, Level) ||
  1642. (DSAStack->isClauseParsingMode() &&
  1643. DSAStack->getClauseParsingMode() == OMPC_private) ||
  1644. // Consider taskgroup reduction descriptor variable a private to avoid
  1645. // possible capture in the region.
  1646. (DSAStack->hasExplicitDirective(
  1647. [](OpenMPDirectiveKind K) { return K == OMPD_taskgroup; },
  1648. Level) &&
  1649. DSAStack->isTaskgroupReductionRef(D, Level));
  1650. }
  1651. void Sema::setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D,
  1652. unsigned Level) {
  1653. assert(LangOpts.OpenMP && "OpenMP is not allowed");
  1654. D = getCanonicalDecl(D);
  1655. OpenMPClauseKind OMPC = OMPC_unknown;
  1656. for (unsigned I = DSAStack->getNestingLevel() + 1; I > Level; --I) {
  1657. const unsigned NewLevel = I - 1;
  1658. if (DSAStack->hasExplicitDSA(D,
  1659. [&OMPC](const OpenMPClauseKind K) {
  1660. if (isOpenMPPrivate(K)) {
  1661. OMPC = K;
  1662. return true;
  1663. }
  1664. return false;
  1665. },
  1666. NewLevel))
  1667. break;
  1668. if (DSAStack->checkMappableExprComponentListsForDeclAtLevel(
  1669. D, NewLevel,
  1670. [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
  1671. OpenMPClauseKind) { return true; })) {
  1672. OMPC = OMPC_map;
  1673. break;
  1674. }
  1675. if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
  1676. NewLevel)) {
  1677. OMPC = OMPC_map;
  1678. if (D->getType()->isScalarType() &&
  1679. DSAStack->getDefaultDMAAtLevel(NewLevel) !=
  1680. DefaultMapAttributes::DMA_tofrom_scalar)
  1681. OMPC = OMPC_firstprivate;
  1682. break;
  1683. }
  1684. }
  1685. if (OMPC != OMPC_unknown)
  1686. FD->addAttr(OMPCaptureKindAttr::CreateImplicit(Context, OMPC));
  1687. }
  1688. bool Sema::isOpenMPTargetCapturedDecl(const ValueDecl *D,
  1689. unsigned Level) const {
  1690. assert(LangOpts.OpenMP && "OpenMP is not allowed");
  1691. // Return true if the current level is no longer enclosed in a target region.
  1692. const auto *VD = dyn_cast<VarDecl>(D);
  1693. return VD && !VD->hasLocalStorage() &&
  1694. DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
  1695. Level);
  1696. }
  1697. void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
  1698. void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
  1699. const DeclarationNameInfo &DirName,
  1700. Scope *CurScope, SourceLocation Loc) {
  1701. DSAStack->push(DKind, DirName, CurScope, Loc);
  1702. PushExpressionEvaluationContext(
  1703. ExpressionEvaluationContext::PotentiallyEvaluated);
  1704. }
  1705. void Sema::StartOpenMPClause(OpenMPClauseKind K) {
  1706. DSAStack->setClauseParsingMode(K);
  1707. }
  1708. void Sema::EndOpenMPClause() {
  1709. DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
  1710. }
  1711. void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
  1712. // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
  1713. // A variable of class type (or array thereof) that appears in a lastprivate
  1714. // clause requires an accessible, unambiguous default constructor for the
  1715. // class type, unless the list item is also specified in a firstprivate
  1716. // clause.
  1717. if (const auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
  1718. for (OMPClause *C : D->clauses()) {
  1719. if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
  1720. SmallVector<Expr *, 8> PrivateCopies;
  1721. for (Expr *DE : Clause->varlists()) {
  1722. if (DE->isValueDependent() || DE->isTypeDependent()) {
  1723. PrivateCopies.push_back(nullptr);
  1724. continue;
  1725. }
  1726. auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens());
  1727. auto *VD = cast<VarDecl>(DRE->getDecl());
  1728. QualType Type = VD->getType().getNonReferenceType();
  1729. const DSAStackTy::DSAVarData DVar =
  1730. DSAStack->getTopDSA(VD, /*FromParent=*/false);
  1731. if (DVar.CKind == OMPC_lastprivate) {
  1732. // Generate helper private variable and initialize it with the
  1733. // default value. The address of the original variable is replaced
  1734. // by the address of the new private variable in CodeGen. This new
  1735. // variable is not added to IdResolver, so the code in the OpenMP
  1736. // region uses original variable for proper diagnostics.
  1737. VarDecl *VDPrivate = buildVarDecl(
  1738. *this, DE->getExprLoc(), Type.getUnqualifiedType(),
  1739. VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr, DRE);
  1740. ActOnUninitializedDecl(VDPrivate);
  1741. if (VDPrivate->isInvalidDecl())
  1742. continue;
  1743. PrivateCopies.push_back(buildDeclRefExpr(
  1744. *this, VDPrivate, DE->getType(), DE->getExprLoc()));
  1745. } else {
  1746. // The variable is also a firstprivate, so initialization sequence
  1747. // for private copy is generated already.
  1748. PrivateCopies.push_back(nullptr);
  1749. }
  1750. }
  1751. // Set initializers to private copies if no errors were found.
  1752. if (PrivateCopies.size() == Clause->varlist_size())
  1753. Clause->setPrivateCopies(PrivateCopies);
  1754. }
  1755. }
  1756. }
  1757. DSAStack->pop();
  1758. DiscardCleanupsInEvaluationContext();
  1759. PopExpressionEvaluationContext();
  1760. }
  1761. static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
  1762. Expr *NumIterations, Sema &SemaRef,
  1763. Scope *S, DSAStackTy *Stack);
  1764. namespace {
  1765. class VarDeclFilterCCC final : public CorrectionCandidateCallback {
  1766. private:
  1767. Sema &SemaRef;
  1768. public:
  1769. explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
  1770. bool ValidateCandidate(const TypoCorrection &Candidate) override {
  1771. NamedDecl *ND = Candidate.getCorrectionDecl();
  1772. if (const auto *VD = dyn_cast_or_null<VarDecl>(ND)) {
  1773. return VD->hasGlobalStorage() &&
  1774. SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
  1775. SemaRef.getCurScope());
  1776. }
  1777. return false;
  1778. }
  1779. };
  1780. class VarOrFuncDeclFilterCCC final : public CorrectionCandidateCallback {
  1781. private:
  1782. Sema &SemaRef;
  1783. public:
  1784. explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {}
  1785. bool ValidateCandidate(const TypoCorrection &Candidate) override {
  1786. NamedDecl *ND = Candidate.getCorrectionDecl();
  1787. if (ND && ((isa<VarDecl>(ND) && ND->getKind() == Decl::Var) ||
  1788. isa<FunctionDecl>(ND))) {
  1789. return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
  1790. SemaRef.getCurScope());
  1791. }
  1792. return false;
  1793. }
  1794. };
  1795. } // namespace
  1796. ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
  1797. CXXScopeSpec &ScopeSpec,
  1798. const DeclarationNameInfo &Id,
  1799. OpenMPDirectiveKind Kind) {
  1800. LookupResult Lookup(*this, Id, LookupOrdinaryName);
  1801. LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
  1802. if (Lookup.isAmbiguous())
  1803. return ExprError();
  1804. VarDecl *VD;
  1805. if (!Lookup.isSingleResult()) {
  1806. if (TypoCorrection Corrected = CorrectTypo(
  1807. Id, LookupOrdinaryName, CurScope, nullptr,
  1808. llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) {
  1809. diagnoseTypo(Corrected,
  1810. PDiag(Lookup.empty()
  1811. ? diag::err_undeclared_var_use_suggest
  1812. : diag::err_omp_expected_var_arg_suggest)
  1813. << Id.getName());
  1814. VD = Corrected.getCorrectionDeclAs<VarDecl>();
  1815. } else {
  1816. Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
  1817. : diag::err_omp_expected_var_arg)
  1818. << Id.getName();
  1819. return ExprError();
  1820. }
  1821. } else if (!(VD = Lookup.getAsSingle<VarDecl>())) {
  1822. Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
  1823. Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
  1824. return ExprError();
  1825. }
  1826. Lookup.suppressDiagnostics();
  1827. // OpenMP [2.9.2, Syntax, C/C++]
  1828. // Variables must be file-scope, namespace-scope, or static block-scope.
  1829. if (Kind == OMPD_threadprivate && !VD->hasGlobalStorage()) {
  1830. Diag(Id.getLoc(), diag::err_omp_global_var_arg)
  1831. << getOpenMPDirectiveName(Kind) << !VD->isStaticLocal();
  1832. bool IsDecl =
  1833. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  1834. Diag(VD->getLocation(),
  1835. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  1836. << VD;
  1837. return ExprError();
  1838. }
  1839. VarDecl *CanonicalVD = VD->getCanonicalDecl();
  1840. NamedDecl *ND = CanonicalVD;
  1841. // OpenMP [2.9.2, Restrictions, C/C++, p.2]
  1842. // A threadprivate directive for file-scope variables must appear outside
  1843. // any definition or declaration.
  1844. if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
  1845. !getCurLexicalContext()->isTranslationUnit()) {
  1846. Diag(Id.getLoc(), diag::err_omp_var_scope)
  1847. << getOpenMPDirectiveName(Kind) << VD;
  1848. bool IsDecl =
  1849. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  1850. Diag(VD->getLocation(),
  1851. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  1852. << VD;
  1853. return ExprError();
  1854. }
  1855. // OpenMP [2.9.2, Restrictions, C/C++, p.3]
  1856. // A threadprivate directive for static class member variables must appear
  1857. // in the class definition, in the same scope in which the member
  1858. // variables are declared.
  1859. if (CanonicalVD->isStaticDataMember() &&
  1860. !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
  1861. Diag(Id.getLoc(), diag::err_omp_var_scope)
  1862. << getOpenMPDirectiveName(Kind) << VD;
  1863. bool IsDecl =
  1864. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  1865. Diag(VD->getLocation(),
  1866. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  1867. << VD;
  1868. return ExprError();
  1869. }
  1870. // OpenMP [2.9.2, Restrictions, C/C++, p.4]
  1871. // A threadprivate directive for namespace-scope variables must appear
  1872. // outside any definition or declaration other than the namespace
  1873. // definition itself.
  1874. if (CanonicalVD->getDeclContext()->isNamespace() &&
  1875. (!getCurLexicalContext()->isFileContext() ||
  1876. !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
  1877. Diag(Id.getLoc(), diag::err_omp_var_scope)
  1878. << getOpenMPDirectiveName(Kind) << VD;
  1879. bool IsDecl =
  1880. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  1881. Diag(VD->getLocation(),
  1882. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  1883. << VD;
  1884. return ExprError();
  1885. }
  1886. // OpenMP [2.9.2, Restrictions, C/C++, p.6]
  1887. // A threadprivate directive for static block-scope variables must appear
  1888. // in the scope of the variable and not in a nested scope.
  1889. if (CanonicalVD->isLocalVarDecl() && CurScope &&
  1890. !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
  1891. Diag(Id.getLoc(), diag::err_omp_var_scope)
  1892. << getOpenMPDirectiveName(Kind) << VD;
  1893. bool IsDecl =
  1894. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  1895. Diag(VD->getLocation(),
  1896. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  1897. << VD;
  1898. return ExprError();
  1899. }
  1900. // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
  1901. // A threadprivate directive must lexically precede all references to any
  1902. // of the variables in its list.
  1903. if (Kind == OMPD_threadprivate && VD->isUsed() &&
  1904. !DSAStack->isThreadPrivate(VD)) {
  1905. Diag(Id.getLoc(), diag::err_omp_var_used)
  1906. << getOpenMPDirectiveName(Kind) << VD;
  1907. return ExprError();
  1908. }
  1909. QualType ExprType = VD->getType().getNonReferenceType();
  1910. return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
  1911. SourceLocation(), VD,
  1912. /*RefersToEnclosingVariableOrCapture=*/false,
  1913. Id.getLoc(), ExprType, VK_LValue);
  1914. }
  1915. Sema::DeclGroupPtrTy
  1916. Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
  1917. ArrayRef<Expr *> VarList) {
  1918. if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
  1919. CurContext->addDecl(D);
  1920. return DeclGroupPtrTy::make(DeclGroupRef(D));
  1921. }
  1922. return nullptr;
  1923. }
  1924. namespace {
  1925. class LocalVarRefChecker final
  1926. : public ConstStmtVisitor<LocalVarRefChecker, bool> {
  1927. Sema &SemaRef;
  1928. public:
  1929. bool VisitDeclRefExpr(const DeclRefExpr *E) {
  1930. if (const auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
  1931. if (VD->hasLocalStorage()) {
  1932. SemaRef.Diag(E->getBeginLoc(),
  1933. diag::err_omp_local_var_in_threadprivate_init)
  1934. << E->getSourceRange();
  1935. SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
  1936. << VD << VD->getSourceRange();
  1937. return true;
  1938. }
  1939. }
  1940. return false;
  1941. }
  1942. bool VisitStmt(const Stmt *S) {
  1943. for (const Stmt *Child : S->children()) {
  1944. if (Child && Visit(Child))
  1945. return true;
  1946. }
  1947. return false;
  1948. }
  1949. explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
  1950. };
  1951. } // namespace
  1952. OMPThreadPrivateDecl *
  1953. Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
  1954. SmallVector<Expr *, 8> Vars;
  1955. for (Expr *RefExpr : VarList) {
  1956. auto *DE = cast<DeclRefExpr>(RefExpr);
  1957. auto *VD = cast<VarDecl>(DE->getDecl());
  1958. SourceLocation ILoc = DE->getExprLoc();
  1959. // Mark variable as used.
  1960. VD->setReferenced();
  1961. VD->markUsed(Context);
  1962. QualType QType = VD->getType();
  1963. if (QType->isDependentType() || QType->isInstantiationDependentType()) {
  1964. // It will be analyzed later.
  1965. Vars.push_back(DE);
  1966. continue;
  1967. }
  1968. // OpenMP [2.9.2, Restrictions, C/C++, p.10]
  1969. // A threadprivate variable must not have an incomplete type.
  1970. if (RequireCompleteType(ILoc, VD->getType(),
  1971. diag::err_omp_threadprivate_incomplete_type)) {
  1972. continue;
  1973. }
  1974. // OpenMP [2.9.2, Restrictions, C/C++, p.10]
  1975. // A threadprivate variable must not have a reference type.
  1976. if (VD->getType()->isReferenceType()) {
  1977. Diag(ILoc, diag::err_omp_ref_type_arg)
  1978. << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
  1979. bool IsDecl =
  1980. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  1981. Diag(VD->getLocation(),
  1982. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  1983. << VD;
  1984. continue;
  1985. }
  1986. // Check if this is a TLS variable. If TLS is not being supported, produce
  1987. // the corresponding diagnostic.
  1988. if ((VD->getTLSKind() != VarDecl::TLS_None &&
  1989. !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
  1990. getLangOpts().OpenMPUseTLS &&
  1991. getASTContext().getTargetInfo().isTLSSupported())) ||
  1992. (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
  1993. !VD->isLocalVarDecl())) {
  1994. Diag(ILoc, diag::err_omp_var_thread_local)
  1995. << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
  1996. bool IsDecl =
  1997. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  1998. Diag(VD->getLocation(),
  1999. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  2000. << VD;
  2001. continue;
  2002. }
  2003. // Check if initial value of threadprivate variable reference variable with
  2004. // local storage (it is not supported by runtime).
  2005. if (const Expr *Init = VD->getAnyInitializer()) {
  2006. LocalVarRefChecker Checker(*this);
  2007. if (Checker.Visit(Init))
  2008. continue;
  2009. }
  2010. Vars.push_back(RefExpr);
  2011. DSAStack->addDSA(VD, DE, OMPC_threadprivate);
  2012. VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
  2013. Context, SourceRange(Loc, Loc)));
  2014. if (ASTMutationListener *ML = Context.getASTMutationListener())
  2015. ML->DeclarationMarkedOpenMPThreadPrivate(VD);
  2016. }
  2017. OMPThreadPrivateDecl *D = nullptr;
  2018. if (!Vars.empty()) {
  2019. D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
  2020. Vars);
  2021. D->setAccess(AS_public);
  2022. }
  2023. return D;
  2024. }
  2025. Sema::DeclGroupPtrTy Sema::ActOnOpenMPAllocateDirective(
  2026. SourceLocation Loc, ArrayRef<Expr *> VarList,
  2027. ArrayRef<OMPClause *> Clauses, DeclContext *Owner) {
  2028. assert(Clauses.size() <= 1 && "Expected at most one clause.");
  2029. Expr *Allocator = nullptr;
  2030. if (!Clauses.empty())
  2031. Allocator = cast<OMPAllocatorClause>(Clauses.back())->getAllocator();
  2032. SmallVector<Expr *, 8> Vars;
  2033. for (Expr *RefExpr : VarList) {
  2034. auto *DE = cast<DeclRefExpr>(RefExpr);
  2035. auto *VD = cast<VarDecl>(DE->getDecl());
  2036. // Check if this is a TLS variable or global register.
  2037. if (VD->getTLSKind() != VarDecl::TLS_None ||
  2038. VD->hasAttr<OMPThreadPrivateDeclAttr>() ||
  2039. (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
  2040. !VD->isLocalVarDecl()))
  2041. continue;
  2042. // Do not apply for parameters.
  2043. if (isa<ParmVarDecl>(VD))
  2044. continue;
  2045. Vars.push_back(RefExpr);
  2046. Attr *A = OMPAllocateDeclAttr::CreateImplicit(Context, Allocator,
  2047. DE->getSourceRange());
  2048. VD->addAttr(A);
  2049. if (ASTMutationListener *ML = Context.getASTMutationListener())
  2050. ML->DeclarationMarkedOpenMPAllocate(VD, A);
  2051. }
  2052. if (Vars.empty())
  2053. return nullptr;
  2054. if (!Owner)
  2055. Owner = getCurLexicalContext();
  2056. OMPAllocateDecl *D =
  2057. OMPAllocateDecl::Create(Context, Owner, Loc, Vars, Clauses);
  2058. D->setAccess(AS_public);
  2059. Owner->addDecl(D);
  2060. return DeclGroupPtrTy::make(DeclGroupRef(D));
  2061. }
  2062. Sema::DeclGroupPtrTy
  2063. Sema::ActOnOpenMPRequiresDirective(SourceLocation Loc,
  2064. ArrayRef<OMPClause *> ClauseList) {
  2065. OMPRequiresDecl *D = nullptr;
  2066. if (!CurContext->isFileContext()) {
  2067. Diag(Loc, diag::err_omp_invalid_scope) << "requires";
  2068. } else {
  2069. D = CheckOMPRequiresDecl(Loc, ClauseList);
  2070. if (D) {
  2071. CurContext->addDecl(D);
  2072. DSAStack->addRequiresDecl(D);
  2073. }
  2074. }
  2075. return DeclGroupPtrTy::make(DeclGroupRef(D));
  2076. }
  2077. OMPRequiresDecl *Sema::CheckOMPRequiresDecl(SourceLocation Loc,
  2078. ArrayRef<OMPClause *> ClauseList) {
  2079. if (!DSAStack->hasDuplicateRequiresClause(ClauseList))
  2080. return OMPRequiresDecl::Create(Context, getCurLexicalContext(), Loc,
  2081. ClauseList);
  2082. return nullptr;
  2083. }
  2084. static void reportOriginalDsa(Sema &SemaRef, const DSAStackTy *Stack,
  2085. const ValueDecl *D,
  2086. const DSAStackTy::DSAVarData &DVar,
  2087. bool IsLoopIterVar = false) {
  2088. if (DVar.RefExpr) {
  2089. SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
  2090. << getOpenMPClauseName(DVar.CKind);
  2091. return;
  2092. }
  2093. enum {
  2094. PDSA_StaticMemberShared,
  2095. PDSA_StaticLocalVarShared,
  2096. PDSA_LoopIterVarPrivate,
  2097. PDSA_LoopIterVarLinear,
  2098. PDSA_LoopIterVarLastprivate,
  2099. PDSA_ConstVarShared,
  2100. PDSA_GlobalVarShared,
  2101. PDSA_TaskVarFirstprivate,
  2102. PDSA_LocalVarPrivate,
  2103. PDSA_Implicit
  2104. } Reason = PDSA_Implicit;
  2105. bool ReportHint = false;
  2106. auto ReportLoc = D->getLocation();
  2107. auto *VD = dyn_cast<VarDecl>(D);
  2108. if (IsLoopIterVar) {
  2109. if (DVar.CKind == OMPC_private)
  2110. Reason = PDSA_LoopIterVarPrivate;
  2111. else if (DVar.CKind == OMPC_lastprivate)
  2112. Reason = PDSA_LoopIterVarLastprivate;
  2113. else
  2114. Reason = PDSA_LoopIterVarLinear;
  2115. } else if (isOpenMPTaskingDirective(DVar.DKind) &&
  2116. DVar.CKind == OMPC_firstprivate) {
  2117. Reason = PDSA_TaskVarFirstprivate;
  2118. ReportLoc = DVar.ImplicitDSALoc;
  2119. } else if (VD && VD->isStaticLocal())
  2120. Reason = PDSA_StaticLocalVarShared;
  2121. else if (VD && VD->isStaticDataMember())
  2122. Reason = PDSA_StaticMemberShared;
  2123. else if (VD && VD->isFileVarDecl())
  2124. Reason = PDSA_GlobalVarShared;
  2125. else if (D->getType().isConstant(SemaRef.getASTContext()))
  2126. Reason = PDSA_ConstVarShared;
  2127. else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
  2128. ReportHint = true;
  2129. Reason = PDSA_LocalVarPrivate;
  2130. }
  2131. if (Reason != PDSA_Implicit) {
  2132. SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
  2133. << Reason << ReportHint
  2134. << getOpenMPDirectiveName(Stack->getCurrentDirective());
  2135. } else if (DVar.ImplicitDSALoc.isValid()) {
  2136. SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
  2137. << getOpenMPClauseName(DVar.CKind);
  2138. }
  2139. }
  2140. namespace {
  2141. class DSAAttrChecker final : public StmtVisitor<DSAAttrChecker, void> {
  2142. DSAStackTy *Stack;
  2143. Sema &SemaRef;
  2144. bool ErrorFound = false;
  2145. CapturedStmt *CS = nullptr;
  2146. llvm::SmallVector<Expr *, 4> ImplicitFirstprivate;
  2147. llvm::SmallVector<Expr *, 4> ImplicitMap;
  2148. Sema::VarsWithInheritedDSAType VarsWithInheritedDSA;
  2149. llvm::SmallDenseSet<const ValueDecl *, 4> ImplicitDeclarations;
  2150. void VisitSubCaptures(OMPExecutableDirective *S) {
  2151. // Check implicitly captured variables.
  2152. if (!S->hasAssociatedStmt() || !S->getAssociatedStmt())
  2153. return;
  2154. for (const CapturedStmt::Capture &Cap :
  2155. S->getInnermostCapturedStmt()->captures()) {
  2156. if (!Cap.capturesVariable())
  2157. continue;
  2158. VarDecl *VD = Cap.getCapturedVar();
  2159. // Do not try to map the variable if it or its sub-component was mapped
  2160. // already.
  2161. if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) &&
  2162. Stack->checkMappableExprComponentListsForDecl(
  2163. VD, /*CurrentRegionOnly=*/true,
  2164. [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
  2165. OpenMPClauseKind) { return true; }))
  2166. continue;
  2167. DeclRefExpr *DRE = buildDeclRefExpr(
  2168. SemaRef, VD, VD->getType().getNonLValueExprType(SemaRef.Context),
  2169. Cap.getLocation(), /*RefersToCapture=*/true);
  2170. Visit(DRE);
  2171. }
  2172. }
  2173. public:
  2174. void VisitDeclRefExpr(DeclRefExpr *E) {
  2175. if (E->isTypeDependent() || E->isValueDependent() ||
  2176. E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
  2177. return;
  2178. if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
  2179. VD = VD->getCanonicalDecl();
  2180. // Skip internally declared variables.
  2181. if (VD->hasLocalStorage() && !CS->capturesVariable(VD))
  2182. return;
  2183. DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
  2184. // Check if the variable has explicit DSA set and stop analysis if it so.
  2185. if (DVar.RefExpr || !ImplicitDeclarations.insert(VD).second)
  2186. return;
  2187. // Skip internally declared static variables.
  2188. llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
  2189. OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
  2190. if (VD->hasGlobalStorage() && !CS->capturesVariable(VD) &&
  2191. (!Res || *Res != OMPDeclareTargetDeclAttr::MT_Link))
  2192. return;
  2193. SourceLocation ELoc = E->getExprLoc();
  2194. OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
  2195. // The default(none) clause requires that each variable that is referenced
  2196. // in the construct, and does not have a predetermined data-sharing
  2197. // attribute, must have its data-sharing attribute explicitly determined
  2198. // by being listed in a data-sharing attribute clause.
  2199. if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
  2200. isImplicitOrExplicitTaskingRegion(DKind) &&
  2201. VarsWithInheritedDSA.count(VD) == 0) {
  2202. VarsWithInheritedDSA[VD] = E;
  2203. return;
  2204. }
  2205. if (isOpenMPTargetExecutionDirective(DKind) &&
  2206. !Stack->isLoopControlVariable(VD).first) {
  2207. if (!Stack->checkMappableExprComponentListsForDecl(
  2208. VD, /*CurrentRegionOnly=*/true,
  2209. [](OMPClauseMappableExprCommon::MappableExprComponentListRef
  2210. StackComponents,
  2211. OpenMPClauseKind) {
  2212. // Variable is used if it has been marked as an array, array
  2213. // section or the variable iself.
  2214. return StackComponents.size() == 1 ||
  2215. std::all_of(
  2216. std::next(StackComponents.rbegin()),
  2217. StackComponents.rend(),
  2218. [](const OMPClauseMappableExprCommon::
  2219. MappableComponent &MC) {
  2220. return MC.getAssociatedDeclaration() ==
  2221. nullptr &&
  2222. (isa<OMPArraySectionExpr>(
  2223. MC.getAssociatedExpression()) ||
  2224. isa<ArraySubscriptExpr>(
  2225. MC.getAssociatedExpression()));
  2226. });
  2227. })) {
  2228. bool IsFirstprivate = false;
  2229. // By default lambdas are captured as firstprivates.
  2230. if (const auto *RD =
  2231. VD->getType().getNonReferenceType()->getAsCXXRecordDecl())
  2232. IsFirstprivate = RD->isLambda();
  2233. IsFirstprivate =
  2234. IsFirstprivate ||
  2235. (VD->getType().getNonReferenceType()->isScalarType() &&
  2236. Stack->getDefaultDMA() != DMA_tofrom_scalar && !Res);
  2237. if (IsFirstprivate)
  2238. ImplicitFirstprivate.emplace_back(E);
  2239. else
  2240. ImplicitMap.emplace_back(E);
  2241. return;
  2242. }
  2243. }
  2244. // OpenMP [2.9.3.6, Restrictions, p.2]
  2245. // A list item that appears in a reduction clause of the innermost
  2246. // enclosing worksharing or parallel construct may not be accessed in an
  2247. // explicit task.
  2248. DVar = Stack->hasInnermostDSA(
  2249. VD, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
  2250. [](OpenMPDirectiveKind K) {
  2251. return isOpenMPParallelDirective(K) ||
  2252. isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
  2253. },
  2254. /*FromParent=*/true);
  2255. if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
  2256. ErrorFound = true;
  2257. SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
  2258. reportOriginalDsa(SemaRef, Stack, VD, DVar);
  2259. return;
  2260. }
  2261. // Define implicit data-sharing attributes for task.
  2262. DVar = Stack->getImplicitDSA(VD, /*FromParent=*/false);
  2263. if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
  2264. !Stack->isLoopControlVariable(VD).first) {
  2265. ImplicitFirstprivate.push_back(E);
  2266. return;
  2267. }
  2268. // Store implicitly used globals with declare target link for parent
  2269. // target.
  2270. if (!isOpenMPTargetExecutionDirective(DKind) && Res &&
  2271. *Res == OMPDeclareTargetDeclAttr::MT_Link) {
  2272. Stack->addToParentTargetRegionLinkGlobals(E);
  2273. return;
  2274. }
  2275. }
  2276. }
  2277. void VisitMemberExpr(MemberExpr *E) {
  2278. if (E->isTypeDependent() || E->isValueDependent() ||
  2279. E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
  2280. return;
  2281. auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
  2282. OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
  2283. if (auto *TE = dyn_cast<CXXThisExpr>(E->getBase()->IgnoreParens())) {
  2284. if (!FD)
  2285. return;
  2286. DSAStackTy::DSAVarData DVar = Stack->getTopDSA(FD, /*FromParent=*/false);
  2287. // Check if the variable has explicit DSA set and stop analysis if it
  2288. // so.
  2289. if (DVar.RefExpr || !ImplicitDeclarations.insert(FD).second)
  2290. return;
  2291. if (isOpenMPTargetExecutionDirective(DKind) &&
  2292. !Stack->isLoopControlVariable(FD).first &&
  2293. !Stack->checkMappableExprComponentListsForDecl(
  2294. FD, /*CurrentRegionOnly=*/true,
  2295. [](OMPClauseMappableExprCommon::MappableExprComponentListRef
  2296. StackComponents,
  2297. OpenMPClauseKind) {
  2298. return isa<CXXThisExpr>(
  2299. cast<MemberExpr>(
  2300. StackComponents.back().getAssociatedExpression())
  2301. ->getBase()
  2302. ->IgnoreParens());
  2303. })) {
  2304. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
  2305. // A bit-field cannot appear in a map clause.
  2306. //
  2307. if (FD->isBitField())
  2308. return;
  2309. // Check to see if the member expression is referencing a class that
  2310. // has already been explicitly mapped
  2311. if (Stack->isClassPreviouslyMapped(TE->getType()))
  2312. return;
  2313. ImplicitMap.emplace_back(E);
  2314. return;
  2315. }
  2316. SourceLocation ELoc = E->getExprLoc();
  2317. // OpenMP [2.9.3.6, Restrictions, p.2]
  2318. // A list item that appears in a reduction clause of the innermost
  2319. // enclosing worksharing or parallel construct may not be accessed in
  2320. // an explicit task.
  2321. DVar = Stack->hasInnermostDSA(
  2322. FD, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
  2323. [](OpenMPDirectiveKind K) {
  2324. return isOpenMPParallelDirective(K) ||
  2325. isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
  2326. },
  2327. /*FromParent=*/true);
  2328. if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
  2329. ErrorFound = true;
  2330. SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
  2331. reportOriginalDsa(SemaRef, Stack, FD, DVar);
  2332. return;
  2333. }
  2334. // Define implicit data-sharing attributes for task.
  2335. DVar = Stack->getImplicitDSA(FD, /*FromParent=*/false);
  2336. if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
  2337. !Stack->isLoopControlVariable(FD).first) {
  2338. // Check if there is a captured expression for the current field in the
  2339. // region. Do not mark it as firstprivate unless there is no captured
  2340. // expression.
  2341. // TODO: try to make it firstprivate.
  2342. if (DVar.CKind != OMPC_unknown)
  2343. ImplicitFirstprivate.push_back(E);
  2344. }
  2345. return;
  2346. }
  2347. if (isOpenMPTargetExecutionDirective(DKind)) {
  2348. OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
  2349. if (!checkMapClauseExpressionBase(SemaRef, E, CurComponents, OMPC_map,
  2350. /*NoDiagnose=*/true))
  2351. return;
  2352. const auto *VD = cast<ValueDecl>(
  2353. CurComponents.back().getAssociatedDeclaration()->getCanonicalDecl());
  2354. if (!Stack->checkMappableExprComponentListsForDecl(
  2355. VD, /*CurrentRegionOnly=*/true,
  2356. [&CurComponents](
  2357. OMPClauseMappableExprCommon::MappableExprComponentListRef
  2358. StackComponents,
  2359. OpenMPClauseKind) {
  2360. auto CCI = CurComponents.rbegin();
  2361. auto CCE = CurComponents.rend();
  2362. for (const auto &SC : llvm::reverse(StackComponents)) {
  2363. // Do both expressions have the same kind?
  2364. if (CCI->getAssociatedExpression()->getStmtClass() !=
  2365. SC.getAssociatedExpression()->getStmtClass())
  2366. if (!(isa<OMPArraySectionExpr>(
  2367. SC.getAssociatedExpression()) &&
  2368. isa<ArraySubscriptExpr>(
  2369. CCI->getAssociatedExpression())))
  2370. return false;
  2371. const Decl *CCD = CCI->getAssociatedDeclaration();
  2372. const Decl *SCD = SC.getAssociatedDeclaration();
  2373. CCD = CCD ? CCD->getCanonicalDecl() : nullptr;
  2374. SCD = SCD ? SCD->getCanonicalDecl() : nullptr;
  2375. if (SCD != CCD)
  2376. return false;
  2377. std::advance(CCI, 1);
  2378. if (CCI == CCE)
  2379. break;
  2380. }
  2381. return true;
  2382. })) {
  2383. Visit(E->getBase());
  2384. }
  2385. } else {
  2386. Visit(E->getBase());
  2387. }
  2388. }
  2389. void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
  2390. for (OMPClause *C : S->clauses()) {
  2391. // Skip analysis of arguments of implicitly defined firstprivate clause
  2392. // for task|target directives.
  2393. // Skip analysis of arguments of implicitly defined map clause for target
  2394. // directives.
  2395. if (C && !((isa<OMPFirstprivateClause>(C) || isa<OMPMapClause>(C)) &&
  2396. C->isImplicit())) {
  2397. for (Stmt *CC : C->children()) {
  2398. if (CC)
  2399. Visit(CC);
  2400. }
  2401. }
  2402. }
  2403. // Check implicitly captured variables.
  2404. VisitSubCaptures(S);
  2405. }
  2406. void VisitStmt(Stmt *S) {
  2407. for (Stmt *C : S->children()) {
  2408. if (C) {
  2409. // Check implicitly captured variables in the task-based directives to
  2410. // check if they must be firstprivatized.
  2411. Visit(C);
  2412. }
  2413. }
  2414. }
  2415. bool isErrorFound() const { return ErrorFound; }
  2416. ArrayRef<Expr *> getImplicitFirstprivate() const {
  2417. return ImplicitFirstprivate;
  2418. }
  2419. ArrayRef<Expr *> getImplicitMap() const { return ImplicitMap; }
  2420. const Sema::VarsWithInheritedDSAType &getVarsWithInheritedDSA() const {
  2421. return VarsWithInheritedDSA;
  2422. }
  2423. DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
  2424. : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {
  2425. // Process declare target link variables for the target directives.
  2426. if (isOpenMPTargetExecutionDirective(S->getCurrentDirective())) {
  2427. for (DeclRefExpr *E : Stack->getLinkGlobals())
  2428. Visit(E);
  2429. }
  2430. }
  2431. };
  2432. } // namespace
  2433. void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
  2434. switch (DKind) {
  2435. case OMPD_parallel:
  2436. case OMPD_parallel_for:
  2437. case OMPD_parallel_for_simd:
  2438. case OMPD_parallel_sections:
  2439. case OMPD_teams:
  2440. case OMPD_teams_distribute:
  2441. case OMPD_teams_distribute_simd: {
  2442. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
  2443. QualType KmpInt32PtrTy =
  2444. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  2445. Sema::CapturedParamNameType Params[] = {
  2446. std::make_pair(".global_tid.", KmpInt32PtrTy),
  2447. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  2448. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2449. };
  2450. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2451. Params);
  2452. break;
  2453. }
  2454. case OMPD_target_teams:
  2455. case OMPD_target_parallel:
  2456. case OMPD_target_parallel_for:
  2457. case OMPD_target_parallel_for_simd:
  2458. case OMPD_target_teams_distribute:
  2459. case OMPD_target_teams_distribute_simd: {
  2460. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
  2461. QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
  2462. QualType KmpInt32PtrTy =
  2463. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  2464. QualType Args[] = {VoidPtrTy};
  2465. FunctionProtoType::ExtProtoInfo EPI;
  2466. EPI.Variadic = true;
  2467. QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
  2468. Sema::CapturedParamNameType Params[] = {
  2469. std::make_pair(".global_tid.", KmpInt32Ty),
  2470. std::make_pair(".part_id.", KmpInt32PtrTy),
  2471. std::make_pair(".privates.", VoidPtrTy),
  2472. std::make_pair(
  2473. ".copy_fn.",
  2474. Context.getPointerType(CopyFnType).withConst().withRestrict()),
  2475. std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
  2476. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2477. };
  2478. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2479. Params);
  2480. // Mark this captured region as inlined, because we don't use outlined
  2481. // function directly.
  2482. getCurCapturedRegion()->TheCapturedDecl->addAttr(
  2483. AlwaysInlineAttr::CreateImplicit(
  2484. Context, AlwaysInlineAttr::Keyword_forceinline));
  2485. Sema::CapturedParamNameType ParamsTarget[] = {
  2486. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2487. };
  2488. // Start a captured region for 'target' with no implicit parameters.
  2489. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2490. ParamsTarget);
  2491. Sema::CapturedParamNameType ParamsTeamsOrParallel[] = {
  2492. std::make_pair(".global_tid.", KmpInt32PtrTy),
  2493. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  2494. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2495. };
  2496. // Start a captured region for 'teams' or 'parallel'. Both regions have
  2497. // the same implicit parameters.
  2498. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2499. ParamsTeamsOrParallel);
  2500. break;
  2501. }
  2502. case OMPD_target:
  2503. case OMPD_target_simd: {
  2504. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
  2505. QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
  2506. QualType KmpInt32PtrTy =
  2507. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  2508. QualType Args[] = {VoidPtrTy};
  2509. FunctionProtoType::ExtProtoInfo EPI;
  2510. EPI.Variadic = true;
  2511. QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
  2512. Sema::CapturedParamNameType Params[] = {
  2513. std::make_pair(".global_tid.", KmpInt32Ty),
  2514. std::make_pair(".part_id.", KmpInt32PtrTy),
  2515. std::make_pair(".privates.", VoidPtrTy),
  2516. std::make_pair(
  2517. ".copy_fn.",
  2518. Context.getPointerType(CopyFnType).withConst().withRestrict()),
  2519. std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
  2520. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2521. };
  2522. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2523. Params);
  2524. // Mark this captured region as inlined, because we don't use outlined
  2525. // function directly.
  2526. getCurCapturedRegion()->TheCapturedDecl->addAttr(
  2527. AlwaysInlineAttr::CreateImplicit(
  2528. Context, AlwaysInlineAttr::Keyword_forceinline));
  2529. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2530. std::make_pair(StringRef(), QualType()));
  2531. break;
  2532. }
  2533. case OMPD_simd:
  2534. case OMPD_for:
  2535. case OMPD_for_simd:
  2536. case OMPD_sections:
  2537. case OMPD_section:
  2538. case OMPD_single:
  2539. case OMPD_master:
  2540. case OMPD_critical:
  2541. case OMPD_taskgroup:
  2542. case OMPD_distribute:
  2543. case OMPD_distribute_simd:
  2544. case OMPD_ordered:
  2545. case OMPD_atomic:
  2546. case OMPD_target_data: {
  2547. Sema::CapturedParamNameType Params[] = {
  2548. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2549. };
  2550. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2551. Params);
  2552. break;
  2553. }
  2554. case OMPD_task: {
  2555. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
  2556. QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
  2557. QualType KmpInt32PtrTy =
  2558. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  2559. QualType Args[] = {VoidPtrTy};
  2560. FunctionProtoType::ExtProtoInfo EPI;
  2561. EPI.Variadic = true;
  2562. QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
  2563. Sema::CapturedParamNameType Params[] = {
  2564. std::make_pair(".global_tid.", KmpInt32Ty),
  2565. std::make_pair(".part_id.", KmpInt32PtrTy),
  2566. std::make_pair(".privates.", VoidPtrTy),
  2567. std::make_pair(
  2568. ".copy_fn.",
  2569. Context.getPointerType(CopyFnType).withConst().withRestrict()),
  2570. std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
  2571. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2572. };
  2573. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2574. Params);
  2575. // Mark this captured region as inlined, because we don't use outlined
  2576. // function directly.
  2577. getCurCapturedRegion()->TheCapturedDecl->addAttr(
  2578. AlwaysInlineAttr::CreateImplicit(
  2579. Context, AlwaysInlineAttr::Keyword_forceinline));
  2580. break;
  2581. }
  2582. case OMPD_taskloop:
  2583. case OMPD_taskloop_simd: {
  2584. QualType KmpInt32Ty =
  2585. Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1)
  2586. .withConst();
  2587. QualType KmpUInt64Ty =
  2588. Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0)
  2589. .withConst();
  2590. QualType KmpInt64Ty =
  2591. Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1)
  2592. .withConst();
  2593. QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
  2594. QualType KmpInt32PtrTy =
  2595. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  2596. QualType Args[] = {VoidPtrTy};
  2597. FunctionProtoType::ExtProtoInfo EPI;
  2598. EPI.Variadic = true;
  2599. QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
  2600. Sema::CapturedParamNameType Params[] = {
  2601. std::make_pair(".global_tid.", KmpInt32Ty),
  2602. std::make_pair(".part_id.", KmpInt32PtrTy),
  2603. std::make_pair(".privates.", VoidPtrTy),
  2604. std::make_pair(
  2605. ".copy_fn.",
  2606. Context.getPointerType(CopyFnType).withConst().withRestrict()),
  2607. std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
  2608. std::make_pair(".lb.", KmpUInt64Ty),
  2609. std::make_pair(".ub.", KmpUInt64Ty),
  2610. std::make_pair(".st.", KmpInt64Ty),
  2611. std::make_pair(".liter.", KmpInt32Ty),
  2612. std::make_pair(".reductions.", VoidPtrTy),
  2613. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2614. };
  2615. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2616. Params);
  2617. // Mark this captured region as inlined, because we don't use outlined
  2618. // function directly.
  2619. getCurCapturedRegion()->TheCapturedDecl->addAttr(
  2620. AlwaysInlineAttr::CreateImplicit(
  2621. Context, AlwaysInlineAttr::Keyword_forceinline));
  2622. break;
  2623. }
  2624. case OMPD_distribute_parallel_for_simd:
  2625. case OMPD_distribute_parallel_for: {
  2626. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
  2627. QualType KmpInt32PtrTy =
  2628. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  2629. Sema::CapturedParamNameType Params[] = {
  2630. std::make_pair(".global_tid.", KmpInt32PtrTy),
  2631. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  2632. std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
  2633. std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
  2634. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2635. };
  2636. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2637. Params);
  2638. break;
  2639. }
  2640. case OMPD_target_teams_distribute_parallel_for:
  2641. case OMPD_target_teams_distribute_parallel_for_simd: {
  2642. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
  2643. QualType KmpInt32PtrTy =
  2644. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  2645. QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
  2646. QualType Args[] = {VoidPtrTy};
  2647. FunctionProtoType::ExtProtoInfo EPI;
  2648. EPI.Variadic = true;
  2649. QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
  2650. Sema::CapturedParamNameType Params[] = {
  2651. std::make_pair(".global_tid.", KmpInt32Ty),
  2652. std::make_pair(".part_id.", KmpInt32PtrTy),
  2653. std::make_pair(".privates.", VoidPtrTy),
  2654. std::make_pair(
  2655. ".copy_fn.",
  2656. Context.getPointerType(CopyFnType).withConst().withRestrict()),
  2657. std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
  2658. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2659. };
  2660. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2661. Params);
  2662. // Mark this captured region as inlined, because we don't use outlined
  2663. // function directly.
  2664. getCurCapturedRegion()->TheCapturedDecl->addAttr(
  2665. AlwaysInlineAttr::CreateImplicit(
  2666. Context, AlwaysInlineAttr::Keyword_forceinline));
  2667. Sema::CapturedParamNameType ParamsTarget[] = {
  2668. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2669. };
  2670. // Start a captured region for 'target' with no implicit parameters.
  2671. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2672. ParamsTarget);
  2673. Sema::CapturedParamNameType ParamsTeams[] = {
  2674. std::make_pair(".global_tid.", KmpInt32PtrTy),
  2675. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  2676. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2677. };
  2678. // Start a captured region for 'target' with no implicit parameters.
  2679. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2680. ParamsTeams);
  2681. Sema::CapturedParamNameType ParamsParallel[] = {
  2682. std::make_pair(".global_tid.", KmpInt32PtrTy),
  2683. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  2684. std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
  2685. std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
  2686. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2687. };
  2688. // Start a captured region for 'teams' or 'parallel'. Both regions have
  2689. // the same implicit parameters.
  2690. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2691. ParamsParallel);
  2692. break;
  2693. }
  2694. case OMPD_teams_distribute_parallel_for:
  2695. case OMPD_teams_distribute_parallel_for_simd: {
  2696. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
  2697. QualType KmpInt32PtrTy =
  2698. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  2699. Sema::CapturedParamNameType ParamsTeams[] = {
  2700. std::make_pair(".global_tid.", KmpInt32PtrTy),
  2701. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  2702. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2703. };
  2704. // Start a captured region for 'target' with no implicit parameters.
  2705. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2706. ParamsTeams);
  2707. Sema::CapturedParamNameType ParamsParallel[] = {
  2708. std::make_pair(".global_tid.", KmpInt32PtrTy),
  2709. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  2710. std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
  2711. std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
  2712. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2713. };
  2714. // Start a captured region for 'teams' or 'parallel'. Both regions have
  2715. // the same implicit parameters.
  2716. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2717. ParamsParallel);
  2718. break;
  2719. }
  2720. case OMPD_target_update:
  2721. case OMPD_target_enter_data:
  2722. case OMPD_target_exit_data: {
  2723. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
  2724. QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
  2725. QualType KmpInt32PtrTy =
  2726. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  2727. QualType Args[] = {VoidPtrTy};
  2728. FunctionProtoType::ExtProtoInfo EPI;
  2729. EPI.Variadic = true;
  2730. QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
  2731. Sema::CapturedParamNameType Params[] = {
  2732. std::make_pair(".global_tid.", KmpInt32Ty),
  2733. std::make_pair(".part_id.", KmpInt32PtrTy),
  2734. std::make_pair(".privates.", VoidPtrTy),
  2735. std::make_pair(
  2736. ".copy_fn.",
  2737. Context.getPointerType(CopyFnType).withConst().withRestrict()),
  2738. std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
  2739. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2740. };
  2741. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2742. Params);
  2743. // Mark this captured region as inlined, because we don't use outlined
  2744. // function directly.
  2745. getCurCapturedRegion()->TheCapturedDecl->addAttr(
  2746. AlwaysInlineAttr::CreateImplicit(
  2747. Context, AlwaysInlineAttr::Keyword_forceinline));
  2748. break;
  2749. }
  2750. case OMPD_threadprivate:
  2751. case OMPD_allocate:
  2752. case OMPD_taskyield:
  2753. case OMPD_barrier:
  2754. case OMPD_taskwait:
  2755. case OMPD_cancellation_point:
  2756. case OMPD_cancel:
  2757. case OMPD_flush:
  2758. case OMPD_declare_reduction:
  2759. case OMPD_declare_mapper:
  2760. case OMPD_declare_simd:
  2761. case OMPD_declare_target:
  2762. case OMPD_end_declare_target:
  2763. case OMPD_requires:
  2764. llvm_unreachable("OpenMP Directive is not allowed");
  2765. case OMPD_unknown:
  2766. llvm_unreachable("Unknown OpenMP directive");
  2767. }
  2768. }
  2769. int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) {
  2770. SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
  2771. getOpenMPCaptureRegions(CaptureRegions, DKind);
  2772. return CaptureRegions.size();
  2773. }
  2774. static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
  2775. Expr *CaptureExpr, bool WithInit,
  2776. bool AsExpression) {
  2777. assert(CaptureExpr);
  2778. ASTContext &C = S.getASTContext();
  2779. Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
  2780. QualType Ty = Init->getType();
  2781. if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
  2782. if (S.getLangOpts().CPlusPlus) {
  2783. Ty = C.getLValueReferenceType(Ty);
  2784. } else {
  2785. Ty = C.getPointerType(Ty);
  2786. ExprResult Res =
  2787. S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
  2788. if (!Res.isUsable())
  2789. return nullptr;
  2790. Init = Res.get();
  2791. }
  2792. WithInit = true;
  2793. }
  2794. auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty,
  2795. CaptureExpr->getBeginLoc());
  2796. if (!WithInit)
  2797. CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C));
  2798. S.CurContext->addHiddenDecl(CED);
  2799. S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false);
  2800. return CED;
  2801. }
  2802. static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
  2803. bool WithInit) {
  2804. OMPCapturedExprDecl *CD;
  2805. if (VarDecl *VD = S.isOpenMPCapturedDecl(D))
  2806. CD = cast<OMPCapturedExprDecl>(VD);
  2807. else
  2808. CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
  2809. /*AsExpression=*/false);
  2810. return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
  2811. CaptureExpr->getExprLoc());
  2812. }
  2813. static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
  2814. CaptureExpr = S.DefaultLvalueConversion(CaptureExpr).get();
  2815. if (!Ref) {
  2816. OMPCapturedExprDecl *CD = buildCaptureDecl(
  2817. S, &S.getASTContext().Idents.get(".capture_expr."), CaptureExpr,
  2818. /*WithInit=*/true, /*AsExpression=*/true);
  2819. Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
  2820. CaptureExpr->getExprLoc());
  2821. }
  2822. ExprResult Res = Ref;
  2823. if (!S.getLangOpts().CPlusPlus &&
  2824. CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
  2825. Ref->getType()->isPointerType()) {
  2826. Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
  2827. if (!Res.isUsable())
  2828. return ExprError();
  2829. }
  2830. return S.DefaultLvalueConversion(Res.get());
  2831. }
  2832. namespace {
  2833. // OpenMP directives parsed in this section are represented as a
  2834. // CapturedStatement with an associated statement. If a syntax error
  2835. // is detected during the parsing of the associated statement, the
  2836. // compiler must abort processing and close the CapturedStatement.
  2837. //
  2838. // Combined directives such as 'target parallel' have more than one
  2839. // nested CapturedStatements. This RAII ensures that we unwind out
  2840. // of all the nested CapturedStatements when an error is found.
  2841. class CaptureRegionUnwinderRAII {
  2842. private:
  2843. Sema &S;
  2844. bool &ErrorFound;
  2845. OpenMPDirectiveKind DKind = OMPD_unknown;
  2846. public:
  2847. CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound,
  2848. OpenMPDirectiveKind DKind)
  2849. : S(S), ErrorFound(ErrorFound), DKind(DKind) {}
  2850. ~CaptureRegionUnwinderRAII() {
  2851. if (ErrorFound) {
  2852. int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind);
  2853. while (--ThisCaptureLevel >= 0)
  2854. S.ActOnCapturedRegionError();
  2855. }
  2856. }
  2857. };
  2858. } // namespace
  2859. StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
  2860. ArrayRef<OMPClause *> Clauses) {
  2861. bool ErrorFound = false;
  2862. CaptureRegionUnwinderRAII CaptureRegionUnwinder(
  2863. *this, ErrorFound, DSAStack->getCurrentDirective());
  2864. if (!S.isUsable()) {
  2865. ErrorFound = true;
  2866. return StmtError();
  2867. }
  2868. SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
  2869. getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective());
  2870. OMPOrderedClause *OC = nullptr;
  2871. OMPScheduleClause *SC = nullptr;
  2872. SmallVector<const OMPLinearClause *, 4> LCs;
  2873. SmallVector<const OMPClauseWithPreInit *, 4> PICs;
  2874. // This is required for proper codegen.
  2875. for (OMPClause *Clause : Clauses) {
  2876. if (isOpenMPTaskingDirective(DSAStack->getCurrentDirective()) &&
  2877. Clause->getClauseKind() == OMPC_in_reduction) {
  2878. // Capture taskgroup task_reduction descriptors inside the tasking regions
  2879. // with the corresponding in_reduction items.
  2880. auto *IRC = cast<OMPInReductionClause>(Clause);
  2881. for (Expr *E : IRC->taskgroup_descriptors())
  2882. if (E)
  2883. MarkDeclarationsReferencedInExpr(E);
  2884. }
  2885. if (isOpenMPPrivate(Clause->getClauseKind()) ||
  2886. Clause->getClauseKind() == OMPC_copyprivate ||
  2887. (getLangOpts().OpenMPUseTLS &&
  2888. getASTContext().getTargetInfo().isTLSSupported() &&
  2889. Clause->getClauseKind() == OMPC_copyin)) {
  2890. DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
  2891. // Mark all variables in private list clauses as used in inner region.
  2892. for (Stmt *VarRef : Clause->children()) {
  2893. if (auto *E = cast_or_null<Expr>(VarRef)) {
  2894. MarkDeclarationsReferencedInExpr(E);
  2895. }
  2896. }
  2897. DSAStack->setForceVarCapturing(/*V=*/false);
  2898. } else if (CaptureRegions.size() > 1 ||
  2899. CaptureRegions.back() != OMPD_unknown) {
  2900. if (auto *C = OMPClauseWithPreInit::get(Clause))
  2901. PICs.push_back(C);
  2902. if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
  2903. if (Expr *E = C->getPostUpdateExpr())
  2904. MarkDeclarationsReferencedInExpr(E);
  2905. }
  2906. }
  2907. if (Clause->getClauseKind() == OMPC_schedule)
  2908. SC = cast<OMPScheduleClause>(Clause);
  2909. else if (Clause->getClauseKind() == OMPC_ordered)
  2910. OC = cast<OMPOrderedClause>(Clause);
  2911. else if (Clause->getClauseKind() == OMPC_linear)
  2912. LCs.push_back(cast<OMPLinearClause>(Clause));
  2913. }
  2914. // OpenMP, 2.7.1 Loop Construct, Restrictions
  2915. // The nonmonotonic modifier cannot be specified if an ordered clause is
  2916. // specified.
  2917. if (SC &&
  2918. (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
  2919. SC->getSecondScheduleModifier() ==
  2920. OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
  2921. OC) {
  2922. Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
  2923. ? SC->getFirstScheduleModifierLoc()
  2924. : SC->getSecondScheduleModifierLoc(),
  2925. diag::err_omp_schedule_nonmonotonic_ordered)
  2926. << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
  2927. ErrorFound = true;
  2928. }
  2929. if (!LCs.empty() && OC && OC->getNumForLoops()) {
  2930. for (const OMPLinearClause *C : LCs) {
  2931. Diag(C->getBeginLoc(), diag::err_omp_linear_ordered)
  2932. << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
  2933. }
  2934. ErrorFound = true;
  2935. }
  2936. if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
  2937. isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
  2938. OC->getNumForLoops()) {
  2939. Diag(OC->getBeginLoc(), diag::err_omp_ordered_simd)
  2940. << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
  2941. ErrorFound = true;
  2942. }
  2943. if (ErrorFound) {
  2944. return StmtError();
  2945. }
  2946. StmtResult SR = S;
  2947. for (OpenMPDirectiveKind ThisCaptureRegion : llvm::reverse(CaptureRegions)) {
  2948. // Mark all variables in private list clauses as used in inner region.
  2949. // Required for proper codegen of combined directives.
  2950. // TODO: add processing for other clauses.
  2951. if (ThisCaptureRegion != OMPD_unknown) {
  2952. for (const clang::OMPClauseWithPreInit *C : PICs) {
  2953. OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion();
  2954. // Find the particular capture region for the clause if the
  2955. // directive is a combined one with multiple capture regions.
  2956. // If the directive is not a combined one, the capture region
  2957. // associated with the clause is OMPD_unknown and is generated
  2958. // only once.
  2959. if (CaptureRegion == ThisCaptureRegion ||
  2960. CaptureRegion == OMPD_unknown) {
  2961. if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
  2962. for (Decl *D : DS->decls())
  2963. MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
  2964. }
  2965. }
  2966. }
  2967. }
  2968. SR = ActOnCapturedRegionEnd(SR.get());
  2969. }
  2970. return SR;
  2971. }
  2972. static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion,
  2973. OpenMPDirectiveKind CancelRegion,
  2974. SourceLocation StartLoc) {
  2975. // CancelRegion is only needed for cancel and cancellation_point.
  2976. if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point)
  2977. return false;
  2978. if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for ||
  2979. CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup)
  2980. return false;
  2981. SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region)
  2982. << getOpenMPDirectiveName(CancelRegion);
  2983. return true;
  2984. }
  2985. static bool checkNestingOfRegions(Sema &SemaRef, const DSAStackTy *Stack,
  2986. OpenMPDirectiveKind CurrentRegion,
  2987. const DeclarationNameInfo &CurrentName,
  2988. OpenMPDirectiveKind CancelRegion,
  2989. SourceLocation StartLoc) {
  2990. if (Stack->getCurScope()) {
  2991. OpenMPDirectiveKind ParentRegion = Stack->getParentDirective();
  2992. OpenMPDirectiveKind OffendingRegion = ParentRegion;
  2993. bool NestingProhibited = false;
  2994. bool CloseNesting = true;
  2995. bool OrphanSeen = false;
  2996. enum {
  2997. NoRecommend,
  2998. ShouldBeInParallelRegion,
  2999. ShouldBeInOrderedRegion,
  3000. ShouldBeInTargetRegion,
  3001. ShouldBeInTeamsRegion
  3002. } Recommend = NoRecommend;
  3003. if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) {
  3004. // OpenMP [2.16, Nesting of Regions]
  3005. // OpenMP constructs may not be nested inside a simd region.
  3006. // OpenMP [2.8.1,simd Construct, Restrictions]
  3007. // An ordered construct with the simd clause is the only OpenMP
  3008. // construct that can appear in the simd region.
  3009. // Allowing a SIMD construct nested in another SIMD construct is an
  3010. // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
  3011. // message.
  3012. SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
  3013. ? diag::err_omp_prohibited_region_simd
  3014. : diag::warn_omp_nesting_simd);
  3015. return CurrentRegion != OMPD_simd;
  3016. }
  3017. if (ParentRegion == OMPD_atomic) {
  3018. // OpenMP [2.16, Nesting of Regions]
  3019. // OpenMP constructs may not be nested inside an atomic region.
  3020. SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
  3021. return true;
  3022. }
  3023. if (CurrentRegion == OMPD_section) {
  3024. // OpenMP [2.7.2, sections Construct, Restrictions]
  3025. // Orphaned section directives are prohibited. That is, the section
  3026. // directives must appear within the sections construct and must not be
  3027. // encountered elsewhere in the sections region.
  3028. if (ParentRegion != OMPD_sections &&
  3029. ParentRegion != OMPD_parallel_sections) {
  3030. SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
  3031. << (ParentRegion != OMPD_unknown)
  3032. << getOpenMPDirectiveName(ParentRegion);
  3033. return true;
  3034. }
  3035. return false;
  3036. }
  3037. // Allow some constructs (except teams and cancellation constructs) to be
  3038. // orphaned (they could be used in functions, called from OpenMP regions
  3039. // with the required preconditions).
  3040. if (ParentRegion == OMPD_unknown &&
  3041. !isOpenMPNestingTeamsDirective(CurrentRegion) &&
  3042. CurrentRegion != OMPD_cancellation_point &&
  3043. CurrentRegion != OMPD_cancel)
  3044. return false;
  3045. if (CurrentRegion == OMPD_cancellation_point ||
  3046. CurrentRegion == OMPD_cancel) {
  3047. // OpenMP [2.16, Nesting of Regions]
  3048. // A cancellation point construct for which construct-type-clause is
  3049. // taskgroup must be nested inside a task construct. A cancellation
  3050. // point construct for which construct-type-clause is not taskgroup must
  3051. // be closely nested inside an OpenMP construct that matches the type
  3052. // specified in construct-type-clause.
  3053. // A cancel construct for which construct-type-clause is taskgroup must be
  3054. // nested inside a task construct. A cancel construct for which
  3055. // construct-type-clause is not taskgroup must be closely nested inside an
  3056. // OpenMP construct that matches the type specified in
  3057. // construct-type-clause.
  3058. NestingProhibited =
  3059. !((CancelRegion == OMPD_parallel &&
  3060. (ParentRegion == OMPD_parallel ||
  3061. ParentRegion == OMPD_target_parallel)) ||
  3062. (CancelRegion == OMPD_for &&
  3063. (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
  3064. ParentRegion == OMPD_target_parallel_for ||
  3065. ParentRegion == OMPD_distribute_parallel_for ||
  3066. ParentRegion == OMPD_teams_distribute_parallel_for ||
  3067. ParentRegion == OMPD_target_teams_distribute_parallel_for)) ||
  3068. (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
  3069. (CancelRegion == OMPD_sections &&
  3070. (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
  3071. ParentRegion == OMPD_parallel_sections)));
  3072. OrphanSeen = ParentRegion == OMPD_unknown;
  3073. } else if (CurrentRegion == OMPD_master) {
  3074. // OpenMP [2.16, Nesting of Regions]
  3075. // A master region may not be closely nested inside a worksharing,
  3076. // atomic, or explicit task region.
  3077. NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
  3078. isOpenMPTaskingDirective(ParentRegion);
  3079. } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
  3080. // OpenMP [2.16, Nesting of Regions]
  3081. // A critical region may not be nested (closely or otherwise) inside a
  3082. // critical region with the same name. Note that this restriction is not
  3083. // sufficient to prevent deadlock.
  3084. SourceLocation PreviousCriticalLoc;
  3085. bool DeadLock = Stack->hasDirective(
  3086. [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
  3087. const DeclarationNameInfo &DNI,
  3088. SourceLocation Loc) {
  3089. if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
  3090. PreviousCriticalLoc = Loc;
  3091. return true;
  3092. }
  3093. return false;
  3094. },
  3095. false /* skip top directive */);
  3096. if (DeadLock) {
  3097. SemaRef.Diag(StartLoc,
  3098. diag::err_omp_prohibited_region_critical_same_name)
  3099. << CurrentName.getName();
  3100. if (PreviousCriticalLoc.isValid())
  3101. SemaRef.Diag(PreviousCriticalLoc,
  3102. diag::note_omp_previous_critical_region);
  3103. return true;
  3104. }
  3105. } else if (CurrentRegion == OMPD_barrier) {
  3106. // OpenMP [2.16, Nesting of Regions]
  3107. // A barrier region may not be closely nested inside a worksharing,
  3108. // explicit task, critical, ordered, atomic, or master region.
  3109. NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
  3110. isOpenMPTaskingDirective(ParentRegion) ||
  3111. ParentRegion == OMPD_master ||
  3112. ParentRegion == OMPD_critical ||
  3113. ParentRegion == OMPD_ordered;
  3114. } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
  3115. !isOpenMPParallelDirective(CurrentRegion) &&
  3116. !isOpenMPTeamsDirective(CurrentRegion)) {
  3117. // OpenMP [2.16, Nesting of Regions]
  3118. // A worksharing region may not be closely nested inside a worksharing,
  3119. // explicit task, critical, ordered, atomic, or master region.
  3120. NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
  3121. isOpenMPTaskingDirective(ParentRegion) ||
  3122. ParentRegion == OMPD_master ||
  3123. ParentRegion == OMPD_critical ||
  3124. ParentRegion == OMPD_ordered;
  3125. Recommend = ShouldBeInParallelRegion;
  3126. } else if (CurrentRegion == OMPD_ordered) {
  3127. // OpenMP [2.16, Nesting of Regions]
  3128. // An ordered region may not be closely nested inside a critical,
  3129. // atomic, or explicit task region.
  3130. // An ordered region must be closely nested inside a loop region (or
  3131. // parallel loop region) with an ordered clause.
  3132. // OpenMP [2.8.1,simd Construct, Restrictions]
  3133. // An ordered construct with the simd clause is the only OpenMP construct
  3134. // that can appear in the simd region.
  3135. NestingProhibited = ParentRegion == OMPD_critical ||
  3136. isOpenMPTaskingDirective(ParentRegion) ||
  3137. !(isOpenMPSimdDirective(ParentRegion) ||
  3138. Stack->isParentOrderedRegion());
  3139. Recommend = ShouldBeInOrderedRegion;
  3140. } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
  3141. // OpenMP [2.16, Nesting of Regions]
  3142. // If specified, a teams construct must be contained within a target
  3143. // construct.
  3144. NestingProhibited = ParentRegion != OMPD_target;
  3145. OrphanSeen = ParentRegion == OMPD_unknown;
  3146. Recommend = ShouldBeInTargetRegion;
  3147. }
  3148. if (!NestingProhibited &&
  3149. !isOpenMPTargetExecutionDirective(CurrentRegion) &&
  3150. !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
  3151. (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
  3152. // OpenMP [2.16, Nesting of Regions]
  3153. // distribute, parallel, parallel sections, parallel workshare, and the
  3154. // parallel loop and parallel loop SIMD constructs are the only OpenMP
  3155. // constructs that can be closely nested in the teams region.
  3156. NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
  3157. !isOpenMPDistributeDirective(CurrentRegion);
  3158. Recommend = ShouldBeInParallelRegion;
  3159. }
  3160. if (!NestingProhibited &&
  3161. isOpenMPNestingDistributeDirective(CurrentRegion)) {
  3162. // OpenMP 4.5 [2.17 Nesting of Regions]
  3163. // The region associated with the distribute construct must be strictly
  3164. // nested inside a teams region
  3165. NestingProhibited =
  3166. (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
  3167. Recommend = ShouldBeInTeamsRegion;
  3168. }
  3169. if (!NestingProhibited &&
  3170. (isOpenMPTargetExecutionDirective(CurrentRegion) ||
  3171. isOpenMPTargetDataManagementDirective(CurrentRegion))) {
  3172. // OpenMP 4.5 [2.17 Nesting of Regions]
  3173. // If a target, target update, target data, target enter data, or
  3174. // target exit data construct is encountered during execution of a
  3175. // target region, the behavior is unspecified.
  3176. NestingProhibited = Stack->hasDirective(
  3177. [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
  3178. SourceLocation) {
  3179. if (isOpenMPTargetExecutionDirective(K)) {
  3180. OffendingRegion = K;
  3181. return true;
  3182. }
  3183. return false;
  3184. },
  3185. false /* don't skip top directive */);
  3186. CloseNesting = false;
  3187. }
  3188. if (NestingProhibited) {
  3189. if (OrphanSeen) {
  3190. SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
  3191. << getOpenMPDirectiveName(CurrentRegion) << Recommend;
  3192. } else {
  3193. SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
  3194. << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
  3195. << Recommend << getOpenMPDirectiveName(CurrentRegion);
  3196. }
  3197. return true;
  3198. }
  3199. }
  3200. return false;
  3201. }
  3202. static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
  3203. ArrayRef<OMPClause *> Clauses,
  3204. ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
  3205. bool ErrorFound = false;
  3206. unsigned NamedModifiersNumber = 0;
  3207. SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers(
  3208. OMPD_unknown + 1);
  3209. SmallVector<SourceLocation, 4> NameModifierLoc;
  3210. for (const OMPClause *C : Clauses) {
  3211. if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
  3212. // At most one if clause without a directive-name-modifier can appear on
  3213. // the directive.
  3214. OpenMPDirectiveKind CurNM = IC->getNameModifier();
  3215. if (FoundNameModifiers[CurNM]) {
  3216. S.Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
  3217. << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
  3218. << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
  3219. ErrorFound = true;
  3220. } else if (CurNM != OMPD_unknown) {
  3221. NameModifierLoc.push_back(IC->getNameModifierLoc());
  3222. ++NamedModifiersNumber;
  3223. }
  3224. FoundNameModifiers[CurNM] = IC;
  3225. if (CurNM == OMPD_unknown)
  3226. continue;
  3227. // Check if the specified name modifier is allowed for the current
  3228. // directive.
  3229. // At most one if clause with the particular directive-name-modifier can
  3230. // appear on the directive.
  3231. bool MatchFound = false;
  3232. for (auto NM : AllowedNameModifiers) {
  3233. if (CurNM == NM) {
  3234. MatchFound = true;
  3235. break;
  3236. }
  3237. }
  3238. if (!MatchFound) {
  3239. S.Diag(IC->getNameModifierLoc(),
  3240. diag::err_omp_wrong_if_directive_name_modifier)
  3241. << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
  3242. ErrorFound = true;
  3243. }
  3244. }
  3245. }
  3246. // If any if clause on the directive includes a directive-name-modifier then
  3247. // all if clauses on the directive must include a directive-name-modifier.
  3248. if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
  3249. if (NamedModifiersNumber == AllowedNameModifiers.size()) {
  3250. S.Diag(FoundNameModifiers[OMPD_unknown]->getBeginLoc(),
  3251. diag::err_omp_no_more_if_clause);
  3252. } else {
  3253. std::string Values;
  3254. std::string Sep(", ");
  3255. unsigned AllowedCnt = 0;
  3256. unsigned TotalAllowedNum =
  3257. AllowedNameModifiers.size() - NamedModifiersNumber;
  3258. for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
  3259. ++Cnt) {
  3260. OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
  3261. if (!FoundNameModifiers[NM]) {
  3262. Values += "'";
  3263. Values += getOpenMPDirectiveName(NM);
  3264. Values += "'";
  3265. if (AllowedCnt + 2 == TotalAllowedNum)
  3266. Values += " or ";
  3267. else if (AllowedCnt + 1 != TotalAllowedNum)
  3268. Values += Sep;
  3269. ++AllowedCnt;
  3270. }
  3271. }
  3272. S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getBeginLoc(),
  3273. diag::err_omp_unnamed_if_clause)
  3274. << (TotalAllowedNum > 1) << Values;
  3275. }
  3276. for (SourceLocation Loc : NameModifierLoc) {
  3277. S.Diag(Loc, diag::note_omp_previous_named_if_clause);
  3278. }
  3279. ErrorFound = true;
  3280. }
  3281. return ErrorFound;
  3282. }
  3283. StmtResult Sema::ActOnOpenMPExecutableDirective(
  3284. OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
  3285. OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
  3286. Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
  3287. StmtResult Res = StmtError();
  3288. // First check CancelRegion which is then used in checkNestingOfRegions.
  3289. if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) ||
  3290. checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
  3291. StartLoc))
  3292. return StmtError();
  3293. llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
  3294. VarsWithInheritedDSAType VarsWithInheritedDSA;
  3295. bool ErrorFound = false;
  3296. ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
  3297. if (AStmt && !CurContext->isDependentContext()) {
  3298. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  3299. // Check default data sharing attributes for referenced variables.
  3300. DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
  3301. int ThisCaptureLevel = getOpenMPCaptureLevels(Kind);
  3302. Stmt *S = AStmt;
  3303. while (--ThisCaptureLevel >= 0)
  3304. S = cast<CapturedStmt>(S)->getCapturedStmt();
  3305. DSAChecker.Visit(S);
  3306. if (DSAChecker.isErrorFound())
  3307. return StmtError();
  3308. // Generate list of implicitly defined firstprivate variables.
  3309. VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
  3310. SmallVector<Expr *, 4> ImplicitFirstprivates(
  3311. DSAChecker.getImplicitFirstprivate().begin(),
  3312. DSAChecker.getImplicitFirstprivate().end());
  3313. SmallVector<Expr *, 4> ImplicitMaps(DSAChecker.getImplicitMap().begin(),
  3314. DSAChecker.getImplicitMap().end());
  3315. // Mark taskgroup task_reduction descriptors as implicitly firstprivate.
  3316. for (OMPClause *C : Clauses) {
  3317. if (auto *IRC = dyn_cast<OMPInReductionClause>(C)) {
  3318. for (Expr *E : IRC->taskgroup_descriptors())
  3319. if (E)
  3320. ImplicitFirstprivates.emplace_back(E);
  3321. }
  3322. }
  3323. if (!ImplicitFirstprivates.empty()) {
  3324. if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
  3325. ImplicitFirstprivates, SourceLocation(), SourceLocation(),
  3326. SourceLocation())) {
  3327. ClausesWithImplicit.push_back(Implicit);
  3328. ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
  3329. ImplicitFirstprivates.size();
  3330. } else {
  3331. ErrorFound = true;
  3332. }
  3333. }
  3334. if (!ImplicitMaps.empty()) {
  3335. CXXScopeSpec MapperIdScopeSpec;
  3336. DeclarationNameInfo MapperId;
  3337. if (OMPClause *Implicit = ActOnOpenMPMapClause(
  3338. llvm::None, llvm::None, MapperIdScopeSpec, MapperId,
  3339. OMPC_MAP_tofrom, /*IsMapTypeImplicit=*/true, SourceLocation(),
  3340. SourceLocation(), ImplicitMaps, OMPVarListLocTy())) {
  3341. ClausesWithImplicit.emplace_back(Implicit);
  3342. ErrorFound |=
  3343. cast<OMPMapClause>(Implicit)->varlist_size() != ImplicitMaps.size();
  3344. } else {
  3345. ErrorFound = true;
  3346. }
  3347. }
  3348. }
  3349. llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
  3350. switch (Kind) {
  3351. case OMPD_parallel:
  3352. Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
  3353. EndLoc);
  3354. AllowedNameModifiers.push_back(OMPD_parallel);
  3355. break;
  3356. case OMPD_simd:
  3357. Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
  3358. VarsWithInheritedDSA);
  3359. break;
  3360. case OMPD_for:
  3361. Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
  3362. VarsWithInheritedDSA);
  3363. break;
  3364. case OMPD_for_simd:
  3365. Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
  3366. EndLoc, VarsWithInheritedDSA);
  3367. break;
  3368. case OMPD_sections:
  3369. Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
  3370. EndLoc);
  3371. break;
  3372. case OMPD_section:
  3373. assert(ClausesWithImplicit.empty() &&
  3374. "No clauses are allowed for 'omp section' directive");
  3375. Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
  3376. break;
  3377. case OMPD_single:
  3378. Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
  3379. EndLoc);
  3380. break;
  3381. case OMPD_master:
  3382. assert(ClausesWithImplicit.empty() &&
  3383. "No clauses are allowed for 'omp master' directive");
  3384. Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
  3385. break;
  3386. case OMPD_critical:
  3387. Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
  3388. StartLoc, EndLoc);
  3389. break;
  3390. case OMPD_parallel_for:
  3391. Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
  3392. EndLoc, VarsWithInheritedDSA);
  3393. AllowedNameModifiers.push_back(OMPD_parallel);
  3394. break;
  3395. case OMPD_parallel_for_simd:
  3396. Res = ActOnOpenMPParallelForSimdDirective(
  3397. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  3398. AllowedNameModifiers.push_back(OMPD_parallel);
  3399. break;
  3400. case OMPD_parallel_sections:
  3401. Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
  3402. StartLoc, EndLoc);
  3403. AllowedNameModifiers.push_back(OMPD_parallel);
  3404. break;
  3405. case OMPD_task:
  3406. Res =
  3407. ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
  3408. AllowedNameModifiers.push_back(OMPD_task);
  3409. break;
  3410. case OMPD_taskyield:
  3411. assert(ClausesWithImplicit.empty() &&
  3412. "No clauses are allowed for 'omp taskyield' directive");
  3413. assert(AStmt == nullptr &&
  3414. "No associated statement allowed for 'omp taskyield' directive");
  3415. Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
  3416. break;
  3417. case OMPD_barrier:
  3418. assert(ClausesWithImplicit.empty() &&
  3419. "No clauses are allowed for 'omp barrier' directive");
  3420. assert(AStmt == nullptr &&
  3421. "No associated statement allowed for 'omp barrier' directive");
  3422. Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
  3423. break;
  3424. case OMPD_taskwait:
  3425. assert(ClausesWithImplicit.empty() &&
  3426. "No clauses are allowed for 'omp taskwait' directive");
  3427. assert(AStmt == nullptr &&
  3428. "No associated statement allowed for 'omp taskwait' directive");
  3429. Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
  3430. break;
  3431. case OMPD_taskgroup:
  3432. Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc,
  3433. EndLoc);
  3434. break;
  3435. case OMPD_flush:
  3436. assert(AStmt == nullptr &&
  3437. "No associated statement allowed for 'omp flush' directive");
  3438. Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
  3439. break;
  3440. case OMPD_ordered:
  3441. Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
  3442. EndLoc);
  3443. break;
  3444. case OMPD_atomic:
  3445. Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
  3446. EndLoc);
  3447. break;
  3448. case OMPD_teams:
  3449. Res =
  3450. ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
  3451. break;
  3452. case OMPD_target:
  3453. Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
  3454. EndLoc);
  3455. AllowedNameModifiers.push_back(OMPD_target);
  3456. break;
  3457. case OMPD_target_parallel:
  3458. Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
  3459. StartLoc, EndLoc);
  3460. AllowedNameModifiers.push_back(OMPD_target);
  3461. AllowedNameModifiers.push_back(OMPD_parallel);
  3462. break;
  3463. case OMPD_target_parallel_for:
  3464. Res = ActOnOpenMPTargetParallelForDirective(
  3465. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  3466. AllowedNameModifiers.push_back(OMPD_target);
  3467. AllowedNameModifiers.push_back(OMPD_parallel);
  3468. break;
  3469. case OMPD_cancellation_point:
  3470. assert(ClausesWithImplicit.empty() &&
  3471. "No clauses are allowed for 'omp cancellation point' directive");
  3472. assert(AStmt == nullptr && "No associated statement allowed for 'omp "
  3473. "cancellation point' directive");
  3474. Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
  3475. break;
  3476. case OMPD_cancel:
  3477. assert(AStmt == nullptr &&
  3478. "No associated statement allowed for 'omp cancel' directive");
  3479. Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
  3480. CancelRegion);
  3481. AllowedNameModifiers.push_back(OMPD_cancel);
  3482. break;
  3483. case OMPD_target_data:
  3484. Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
  3485. EndLoc);
  3486. AllowedNameModifiers.push_back(OMPD_target_data);
  3487. break;
  3488. case OMPD_target_enter_data:
  3489. Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
  3490. EndLoc, AStmt);
  3491. AllowedNameModifiers.push_back(OMPD_target_enter_data);
  3492. break;
  3493. case OMPD_target_exit_data:
  3494. Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
  3495. EndLoc, AStmt);
  3496. AllowedNameModifiers.push_back(OMPD_target_exit_data);
  3497. break;
  3498. case OMPD_taskloop:
  3499. Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
  3500. EndLoc, VarsWithInheritedDSA);
  3501. AllowedNameModifiers.push_back(OMPD_taskloop);
  3502. break;
  3503. case OMPD_taskloop_simd:
  3504. Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
  3505. EndLoc, VarsWithInheritedDSA);
  3506. AllowedNameModifiers.push_back(OMPD_taskloop);
  3507. break;
  3508. case OMPD_distribute:
  3509. Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
  3510. EndLoc, VarsWithInheritedDSA);
  3511. break;
  3512. case OMPD_target_update:
  3513. Res = ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc,
  3514. EndLoc, AStmt);
  3515. AllowedNameModifiers.push_back(OMPD_target_update);
  3516. break;
  3517. case OMPD_distribute_parallel_for:
  3518. Res = ActOnOpenMPDistributeParallelForDirective(
  3519. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  3520. AllowedNameModifiers.push_back(OMPD_parallel);
  3521. break;
  3522. case OMPD_distribute_parallel_for_simd:
  3523. Res = ActOnOpenMPDistributeParallelForSimdDirective(
  3524. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  3525. AllowedNameModifiers.push_back(OMPD_parallel);
  3526. break;
  3527. case OMPD_distribute_simd:
  3528. Res = ActOnOpenMPDistributeSimdDirective(
  3529. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  3530. break;
  3531. case OMPD_target_parallel_for_simd:
  3532. Res = ActOnOpenMPTargetParallelForSimdDirective(
  3533. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  3534. AllowedNameModifiers.push_back(OMPD_target);
  3535. AllowedNameModifiers.push_back(OMPD_parallel);
  3536. break;
  3537. case OMPD_target_simd:
  3538. Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
  3539. EndLoc, VarsWithInheritedDSA);
  3540. AllowedNameModifiers.push_back(OMPD_target);
  3541. break;
  3542. case OMPD_teams_distribute:
  3543. Res = ActOnOpenMPTeamsDistributeDirective(
  3544. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  3545. break;
  3546. case OMPD_teams_distribute_simd:
  3547. Res = ActOnOpenMPTeamsDistributeSimdDirective(
  3548. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  3549. break;
  3550. case OMPD_teams_distribute_parallel_for_simd:
  3551. Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
  3552. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  3553. AllowedNameModifiers.push_back(OMPD_parallel);
  3554. break;
  3555. case OMPD_teams_distribute_parallel_for:
  3556. Res = ActOnOpenMPTeamsDistributeParallelForDirective(
  3557. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  3558. AllowedNameModifiers.push_back(OMPD_parallel);
  3559. break;
  3560. case OMPD_target_teams:
  3561. Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
  3562. EndLoc);
  3563. AllowedNameModifiers.push_back(OMPD_target);
  3564. break;
  3565. case OMPD_target_teams_distribute:
  3566. Res = ActOnOpenMPTargetTeamsDistributeDirective(
  3567. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  3568. AllowedNameModifiers.push_back(OMPD_target);
  3569. break;
  3570. case OMPD_target_teams_distribute_parallel_for:
  3571. Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective(
  3572. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  3573. AllowedNameModifiers.push_back(OMPD_target);
  3574. AllowedNameModifiers.push_back(OMPD_parallel);
  3575. break;
  3576. case OMPD_target_teams_distribute_parallel_for_simd:
  3577. Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
  3578. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  3579. AllowedNameModifiers.push_back(OMPD_target);
  3580. AllowedNameModifiers.push_back(OMPD_parallel);
  3581. break;
  3582. case OMPD_target_teams_distribute_simd:
  3583. Res = ActOnOpenMPTargetTeamsDistributeSimdDirective(
  3584. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  3585. AllowedNameModifiers.push_back(OMPD_target);
  3586. break;
  3587. case OMPD_declare_target:
  3588. case OMPD_end_declare_target:
  3589. case OMPD_threadprivate:
  3590. case OMPD_allocate:
  3591. case OMPD_declare_reduction:
  3592. case OMPD_declare_mapper:
  3593. case OMPD_declare_simd:
  3594. case OMPD_requires:
  3595. llvm_unreachable("OpenMP Directive is not allowed");
  3596. case OMPD_unknown:
  3597. llvm_unreachable("Unknown OpenMP directive");
  3598. }
  3599. for (const auto &P : VarsWithInheritedDSA) {
  3600. Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
  3601. << P.first << P.second->getSourceRange();
  3602. }
  3603. ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound;
  3604. if (!AllowedNameModifiers.empty())
  3605. ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
  3606. ErrorFound;
  3607. if (ErrorFound)
  3608. return StmtError();
  3609. return Res;
  3610. }
  3611. Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
  3612. DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
  3613. ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
  3614. ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
  3615. ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
  3616. assert(Aligneds.size() == Alignments.size());
  3617. assert(Linears.size() == LinModifiers.size());
  3618. assert(Linears.size() == Steps.size());
  3619. if (!DG || DG.get().isNull())
  3620. return DeclGroupPtrTy();
  3621. if (!DG.get().isSingleDecl()) {
  3622. Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd);
  3623. return DG;
  3624. }
  3625. Decl *ADecl = DG.get().getSingleDecl();
  3626. if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
  3627. ADecl = FTD->getTemplatedDecl();
  3628. auto *FD = dyn_cast<FunctionDecl>(ADecl);
  3629. if (!FD) {
  3630. Diag(ADecl->getLocation(), diag::err_omp_function_expected);
  3631. return DeclGroupPtrTy();
  3632. }
  3633. // OpenMP [2.8.2, declare simd construct, Description]
  3634. // The parameter of the simdlen clause must be a constant positive integer
  3635. // expression.
  3636. ExprResult SL;
  3637. if (Simdlen)
  3638. SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
  3639. // OpenMP [2.8.2, declare simd construct, Description]
  3640. // The special this pointer can be used as if was one of the arguments to the
  3641. // function in any of the linear, aligned, or uniform clauses.
  3642. // The uniform clause declares one or more arguments to have an invariant
  3643. // value for all concurrent invocations of the function in the execution of a
  3644. // single SIMD loop.
  3645. llvm::DenseMap<const Decl *, const Expr *> UniformedArgs;
  3646. const Expr *UniformedLinearThis = nullptr;
  3647. for (const Expr *E : Uniforms) {
  3648. E = E->IgnoreParenImpCasts();
  3649. if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
  3650. if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
  3651. if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
  3652. FD->getParamDecl(PVD->getFunctionScopeIndex())
  3653. ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
  3654. UniformedArgs.try_emplace(PVD->getCanonicalDecl(), E);
  3655. continue;
  3656. }
  3657. if (isa<CXXThisExpr>(E)) {
  3658. UniformedLinearThis = E;
  3659. continue;
  3660. }
  3661. Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
  3662. << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
  3663. }
  3664. // OpenMP [2.8.2, declare simd construct, Description]
  3665. // The aligned clause declares that the object to which each list item points
  3666. // is aligned to the number of bytes expressed in the optional parameter of
  3667. // the aligned clause.
  3668. // The special this pointer can be used as if was one of the arguments to the
  3669. // function in any of the linear, aligned, or uniform clauses.
  3670. // The type of list items appearing in the aligned clause must be array,
  3671. // pointer, reference to array, or reference to pointer.
  3672. llvm::DenseMap<const Decl *, const Expr *> AlignedArgs;
  3673. const Expr *AlignedThis = nullptr;
  3674. for (const Expr *E : Aligneds) {
  3675. E = E->IgnoreParenImpCasts();
  3676. if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
  3677. if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
  3678. const VarDecl *CanonPVD = PVD->getCanonicalDecl();
  3679. if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
  3680. FD->getParamDecl(PVD->getFunctionScopeIndex())
  3681. ->getCanonicalDecl() == CanonPVD) {
  3682. // OpenMP [2.8.1, simd construct, Restrictions]
  3683. // A list-item cannot appear in more than one aligned clause.
  3684. if (AlignedArgs.count(CanonPVD) > 0) {
  3685. Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
  3686. << 1 << E->getSourceRange();
  3687. Diag(AlignedArgs[CanonPVD]->getExprLoc(),
  3688. diag::note_omp_explicit_dsa)
  3689. << getOpenMPClauseName(OMPC_aligned);
  3690. continue;
  3691. }
  3692. AlignedArgs[CanonPVD] = E;
  3693. QualType QTy = PVD->getType()
  3694. .getNonReferenceType()
  3695. .getUnqualifiedType()
  3696. .getCanonicalType();
  3697. const Type *Ty = QTy.getTypePtrOrNull();
  3698. if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
  3699. Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
  3700. << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
  3701. Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
  3702. }
  3703. continue;
  3704. }
  3705. }
  3706. if (isa<CXXThisExpr>(E)) {
  3707. if (AlignedThis) {
  3708. Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
  3709. << 2 << E->getSourceRange();
  3710. Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
  3711. << getOpenMPClauseName(OMPC_aligned);
  3712. }
  3713. AlignedThis = E;
  3714. continue;
  3715. }
  3716. Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
  3717. << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
  3718. }
  3719. // The optional parameter of the aligned clause, alignment, must be a constant
  3720. // positive integer expression. If no optional parameter is specified,
  3721. // implementation-defined default alignments for SIMD instructions on the
  3722. // target platforms are assumed.
  3723. SmallVector<const Expr *, 4> NewAligns;
  3724. for (Expr *E : Alignments) {
  3725. ExprResult Align;
  3726. if (E)
  3727. Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
  3728. NewAligns.push_back(Align.get());
  3729. }
  3730. // OpenMP [2.8.2, declare simd construct, Description]
  3731. // The linear clause declares one or more list items to be private to a SIMD
  3732. // lane and to have a linear relationship with respect to the iteration space
  3733. // of a loop.
  3734. // The special this pointer can be used as if was one of the arguments to the
  3735. // function in any of the linear, aligned, or uniform clauses.
  3736. // When a linear-step expression is specified in a linear clause it must be
  3737. // either a constant integer expression or an integer-typed parameter that is
  3738. // specified in a uniform clause on the directive.
  3739. llvm::DenseMap<const Decl *, const Expr *> LinearArgs;
  3740. const bool IsUniformedThis = UniformedLinearThis != nullptr;
  3741. auto MI = LinModifiers.begin();
  3742. for (const Expr *E : Linears) {
  3743. auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
  3744. ++MI;
  3745. E = E->IgnoreParenImpCasts();
  3746. if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
  3747. if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
  3748. const VarDecl *CanonPVD = PVD->getCanonicalDecl();
  3749. if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
  3750. FD->getParamDecl(PVD->getFunctionScopeIndex())
  3751. ->getCanonicalDecl() == CanonPVD) {
  3752. // OpenMP [2.15.3.7, linear Clause, Restrictions]
  3753. // A list-item cannot appear in more than one linear clause.
  3754. if (LinearArgs.count(CanonPVD) > 0) {
  3755. Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
  3756. << getOpenMPClauseName(OMPC_linear)
  3757. << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
  3758. Diag(LinearArgs[CanonPVD]->getExprLoc(),
  3759. diag::note_omp_explicit_dsa)
  3760. << getOpenMPClauseName(OMPC_linear);
  3761. continue;
  3762. }
  3763. // Each argument can appear in at most one uniform or linear clause.
  3764. if (UniformedArgs.count(CanonPVD) > 0) {
  3765. Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
  3766. << getOpenMPClauseName(OMPC_linear)
  3767. << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
  3768. Diag(UniformedArgs[CanonPVD]->getExprLoc(),
  3769. diag::note_omp_explicit_dsa)
  3770. << getOpenMPClauseName(OMPC_uniform);
  3771. continue;
  3772. }
  3773. LinearArgs[CanonPVD] = E;
  3774. if (E->isValueDependent() || E->isTypeDependent() ||
  3775. E->isInstantiationDependent() ||
  3776. E->containsUnexpandedParameterPack())
  3777. continue;
  3778. (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
  3779. PVD->getOriginalType());
  3780. continue;
  3781. }
  3782. }
  3783. if (isa<CXXThisExpr>(E)) {
  3784. if (UniformedLinearThis) {
  3785. Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
  3786. << getOpenMPClauseName(OMPC_linear)
  3787. << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
  3788. << E->getSourceRange();
  3789. Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
  3790. << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
  3791. : OMPC_linear);
  3792. continue;
  3793. }
  3794. UniformedLinearThis = E;
  3795. if (E->isValueDependent() || E->isTypeDependent() ||
  3796. E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
  3797. continue;
  3798. (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
  3799. E->getType());
  3800. continue;
  3801. }
  3802. Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
  3803. << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
  3804. }
  3805. Expr *Step = nullptr;
  3806. Expr *NewStep = nullptr;
  3807. SmallVector<Expr *, 4> NewSteps;
  3808. for (Expr *E : Steps) {
  3809. // Skip the same step expression, it was checked already.
  3810. if (Step == E || !E) {
  3811. NewSteps.push_back(E ? NewStep : nullptr);
  3812. continue;
  3813. }
  3814. Step = E;
  3815. if (const auto *DRE = dyn_cast<DeclRefExpr>(Step))
  3816. if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
  3817. const VarDecl *CanonPVD = PVD->getCanonicalDecl();
  3818. if (UniformedArgs.count(CanonPVD) == 0) {
  3819. Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
  3820. << Step->getSourceRange();
  3821. } else if (E->isValueDependent() || E->isTypeDependent() ||
  3822. E->isInstantiationDependent() ||
  3823. E->containsUnexpandedParameterPack() ||
  3824. CanonPVD->getType()->hasIntegerRepresentation()) {
  3825. NewSteps.push_back(Step);
  3826. } else {
  3827. Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
  3828. << Step->getSourceRange();
  3829. }
  3830. continue;
  3831. }
  3832. NewStep = Step;
  3833. if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
  3834. !Step->isInstantiationDependent() &&
  3835. !Step->containsUnexpandedParameterPack()) {
  3836. NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
  3837. .get();
  3838. if (NewStep)
  3839. NewStep = VerifyIntegerConstantExpression(NewStep).get();
  3840. }
  3841. NewSteps.push_back(NewStep);
  3842. }
  3843. auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
  3844. Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
  3845. Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
  3846. const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
  3847. const_cast<Expr **>(Linears.data()), Linears.size(),
  3848. const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
  3849. NewSteps.data(), NewSteps.size(), SR);
  3850. ADecl->addAttr(NewAttr);
  3851. return ConvertDeclToDeclGroup(ADecl);
  3852. }
  3853. StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
  3854. Stmt *AStmt,
  3855. SourceLocation StartLoc,
  3856. SourceLocation EndLoc) {
  3857. if (!AStmt)
  3858. return StmtError();
  3859. auto *CS = cast<CapturedStmt>(AStmt);
  3860. // 1.2.2 OpenMP Language Terminology
  3861. // Structured block - An executable statement with a single entry at the
  3862. // top and a single exit at the bottom.
  3863. // The point of exit cannot be a branch out of the structured block.
  3864. // longjmp() and throw() must not violate the entry/exit criteria.
  3865. CS->getCapturedDecl()->setNothrow();
  3866. setFunctionHasBranchProtectedScope();
  3867. return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
  3868. DSAStack->isCancelRegion());
  3869. }
  3870. namespace {
  3871. /// Helper class for checking canonical form of the OpenMP loops and
  3872. /// extracting iteration space of each loop in the loop nest, that will be used
  3873. /// for IR generation.
  3874. class OpenMPIterationSpaceChecker {
  3875. /// Reference to Sema.
  3876. Sema &SemaRef;
  3877. /// A location for diagnostics (when there is no some better location).
  3878. SourceLocation DefaultLoc;
  3879. /// A location for diagnostics (when increment is not compatible).
  3880. SourceLocation ConditionLoc;
  3881. /// A source location for referring to loop init later.
  3882. SourceRange InitSrcRange;
  3883. /// A source location for referring to condition later.
  3884. SourceRange ConditionSrcRange;
  3885. /// A source location for referring to increment later.
  3886. SourceRange IncrementSrcRange;
  3887. /// Loop variable.
  3888. ValueDecl *LCDecl = nullptr;
  3889. /// Reference to loop variable.
  3890. Expr *LCRef = nullptr;
  3891. /// Lower bound (initializer for the var).
  3892. Expr *LB = nullptr;
  3893. /// Upper bound.
  3894. Expr *UB = nullptr;
  3895. /// Loop step (increment).
  3896. Expr *Step = nullptr;
  3897. /// This flag is true when condition is one of:
  3898. /// Var < UB
  3899. /// Var <= UB
  3900. /// UB > Var
  3901. /// UB >= Var
  3902. /// This will have no value when the condition is !=
  3903. llvm::Optional<bool> TestIsLessOp;
  3904. /// This flag is true when condition is strict ( < or > ).
  3905. bool TestIsStrictOp = false;
  3906. /// This flag is true when step is subtracted on each iteration.
  3907. bool SubtractStep = false;
  3908. public:
  3909. OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
  3910. : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {}
  3911. /// Check init-expr for canonical loop form and save loop counter
  3912. /// variable - #Var and its initialization value - #LB.
  3913. bool checkAndSetInit(Stmt *S, bool EmitDiags = true);
  3914. /// Check test-expr for canonical form, save upper-bound (#UB), flags
  3915. /// for less/greater and for strict/non-strict comparison.
  3916. bool checkAndSetCond(Expr *S);
  3917. /// Check incr-expr for canonical loop form and return true if it
  3918. /// does not conform, otherwise save loop step (#Step).
  3919. bool checkAndSetInc(Expr *S);
  3920. /// Return the loop counter variable.
  3921. ValueDecl *getLoopDecl() const { return LCDecl; }
  3922. /// Return the reference expression to loop counter variable.
  3923. Expr *getLoopDeclRefExpr() const { return LCRef; }
  3924. /// Source range of the loop init.
  3925. SourceRange getInitSrcRange() const { return InitSrcRange; }
  3926. /// Source range of the loop condition.
  3927. SourceRange getConditionSrcRange() const { return ConditionSrcRange; }
  3928. /// Source range of the loop increment.
  3929. SourceRange getIncrementSrcRange() const { return IncrementSrcRange; }
  3930. /// True if the step should be subtracted.
  3931. bool shouldSubtractStep() const { return SubtractStep; }
  3932. /// True, if the compare operator is strict (<, > or !=).
  3933. bool isStrictTestOp() const { return TestIsStrictOp; }
  3934. /// Build the expression to calculate the number of iterations.
  3935. Expr *buildNumIterations(
  3936. Scope *S, const bool LimitedType,
  3937. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
  3938. /// Build the precondition expression for the loops.
  3939. Expr *
  3940. buildPreCond(Scope *S, Expr *Cond,
  3941. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
  3942. /// Build reference expression to the counter be used for codegen.
  3943. DeclRefExpr *
  3944. buildCounterVar(llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
  3945. DSAStackTy &DSA) const;
  3946. /// Build reference expression to the private counter be used for
  3947. /// codegen.
  3948. Expr *buildPrivateCounterVar() const;
  3949. /// Build initialization of the counter be used for codegen.
  3950. Expr *buildCounterInit() const;
  3951. /// Build step of the counter be used for codegen.
  3952. Expr *buildCounterStep() const;
  3953. /// Build loop data with counter value for depend clauses in ordered
  3954. /// directives.
  3955. Expr *
  3956. buildOrderedLoopData(Scope *S, Expr *Counter,
  3957. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
  3958. SourceLocation Loc, Expr *Inc = nullptr,
  3959. OverloadedOperatorKind OOK = OO_Amp);
  3960. /// Return true if any expression is dependent.
  3961. bool dependent() const;
  3962. private:
  3963. /// Check the right-hand side of an assignment in the increment
  3964. /// expression.
  3965. bool checkAndSetIncRHS(Expr *RHS);
  3966. /// Helper to set loop counter variable and its initializer.
  3967. bool setLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB);
  3968. /// Helper to set upper bound.
  3969. bool setUB(Expr *NewUB, llvm::Optional<bool> LessOp, bool StrictOp,
  3970. SourceRange SR, SourceLocation SL);
  3971. /// Helper to set loop increment.
  3972. bool setStep(Expr *NewStep, bool Subtract);
  3973. };
  3974. bool OpenMPIterationSpaceChecker::dependent() const {
  3975. if (!LCDecl) {
  3976. assert(!LB && !UB && !Step);
  3977. return false;
  3978. }
  3979. return LCDecl->getType()->isDependentType() ||
  3980. (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
  3981. (Step && Step->isValueDependent());
  3982. }
  3983. bool OpenMPIterationSpaceChecker::setLCDeclAndLB(ValueDecl *NewLCDecl,
  3984. Expr *NewLCRefExpr,
  3985. Expr *NewLB) {
  3986. // State consistency checking to ensure correct usage.
  3987. assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
  3988. UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
  3989. if (!NewLCDecl || !NewLB)
  3990. return true;
  3991. LCDecl = getCanonicalDecl(NewLCDecl);
  3992. LCRef = NewLCRefExpr;
  3993. if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
  3994. if (const CXXConstructorDecl *Ctor = CE->getConstructor())
  3995. if ((Ctor->isCopyOrMoveConstructor() ||
  3996. Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
  3997. CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
  3998. NewLB = CE->getArg(0)->IgnoreParenImpCasts();
  3999. LB = NewLB;
  4000. return false;
  4001. }
  4002. bool OpenMPIterationSpaceChecker::setUB(Expr *NewUB,
  4003. llvm::Optional<bool> LessOp,
  4004. bool StrictOp, SourceRange SR,
  4005. SourceLocation SL) {
  4006. // State consistency checking to ensure correct usage.
  4007. assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
  4008. Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
  4009. if (!NewUB)
  4010. return true;
  4011. UB = NewUB;
  4012. if (LessOp)
  4013. TestIsLessOp = LessOp;
  4014. TestIsStrictOp = StrictOp;
  4015. ConditionSrcRange = SR;
  4016. ConditionLoc = SL;
  4017. return false;
  4018. }
  4019. bool OpenMPIterationSpaceChecker::setStep(Expr *NewStep, bool Subtract) {
  4020. // State consistency checking to ensure correct usage.
  4021. assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
  4022. if (!NewStep)
  4023. return true;
  4024. if (!NewStep->isValueDependent()) {
  4025. // Check that the step is integer expression.
  4026. SourceLocation StepLoc = NewStep->getBeginLoc();
  4027. ExprResult Val = SemaRef.PerformOpenMPImplicitIntegerConversion(
  4028. StepLoc, getExprAsWritten(NewStep));
  4029. if (Val.isInvalid())
  4030. return true;
  4031. NewStep = Val.get();
  4032. // OpenMP [2.6, Canonical Loop Form, Restrictions]
  4033. // If test-expr is of form var relational-op b and relational-op is < or
  4034. // <= then incr-expr must cause var to increase on each iteration of the
  4035. // loop. If test-expr is of form var relational-op b and relational-op is
  4036. // > or >= then incr-expr must cause var to decrease on each iteration of
  4037. // the loop.
  4038. // If test-expr is of form b relational-op var and relational-op is < or
  4039. // <= then incr-expr must cause var to decrease on each iteration of the
  4040. // loop. If test-expr is of form b relational-op var and relational-op is
  4041. // > or >= then incr-expr must cause var to increase on each iteration of
  4042. // the loop.
  4043. llvm::APSInt Result;
  4044. bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
  4045. bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
  4046. bool IsConstNeg =
  4047. IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
  4048. bool IsConstPos =
  4049. IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
  4050. bool IsConstZero = IsConstant && !Result.getBoolValue();
  4051. // != with increment is treated as <; != with decrement is treated as >
  4052. if (!TestIsLessOp.hasValue())
  4053. TestIsLessOp = IsConstPos || (IsUnsigned && !Subtract);
  4054. if (UB && (IsConstZero ||
  4055. (TestIsLessOp.getValue() ?
  4056. (IsConstNeg || (IsUnsigned && Subtract)) :
  4057. (IsConstPos || (IsUnsigned && !Subtract))))) {
  4058. SemaRef.Diag(NewStep->getExprLoc(),
  4059. diag::err_omp_loop_incr_not_compatible)
  4060. << LCDecl << TestIsLessOp.getValue() << NewStep->getSourceRange();
  4061. SemaRef.Diag(ConditionLoc,
  4062. diag::note_omp_loop_cond_requres_compatible_incr)
  4063. << TestIsLessOp.getValue() << ConditionSrcRange;
  4064. return true;
  4065. }
  4066. if (TestIsLessOp.getValue() == Subtract) {
  4067. NewStep =
  4068. SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
  4069. .get();
  4070. Subtract = !Subtract;
  4071. }
  4072. }
  4073. Step = NewStep;
  4074. SubtractStep = Subtract;
  4075. return false;
  4076. }
  4077. bool OpenMPIterationSpaceChecker::checkAndSetInit(Stmt *S, bool EmitDiags) {
  4078. // Check init-expr for canonical loop form and save loop counter
  4079. // variable - #Var and its initialization value - #LB.
  4080. // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
  4081. // var = lb
  4082. // integer-type var = lb
  4083. // random-access-iterator-type var = lb
  4084. // pointer-type var = lb
  4085. //
  4086. if (!S) {
  4087. if (EmitDiags) {
  4088. SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
  4089. }
  4090. return true;
  4091. }
  4092. if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
  4093. if (!ExprTemp->cleanupsHaveSideEffects())
  4094. S = ExprTemp->getSubExpr();
  4095. InitSrcRange = S->getSourceRange();
  4096. if (Expr *E = dyn_cast<Expr>(S))
  4097. S = E->IgnoreParens();
  4098. if (auto *BO = dyn_cast<BinaryOperator>(S)) {
  4099. if (BO->getOpcode() == BO_Assign) {
  4100. Expr *LHS = BO->getLHS()->IgnoreParens();
  4101. if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
  4102. if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
  4103. if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
  4104. return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
  4105. return setLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS());
  4106. }
  4107. if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
  4108. if (ME->isArrow() &&
  4109. isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
  4110. return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
  4111. }
  4112. }
  4113. } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
  4114. if (DS->isSingleDecl()) {
  4115. if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
  4116. if (Var->hasInit() && !Var->getType()->isReferenceType()) {
  4117. // Accept non-canonical init form here but emit ext. warning.
  4118. if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
  4119. SemaRef.Diag(S->getBeginLoc(),
  4120. diag::ext_omp_loop_not_canonical_init)
  4121. << S->getSourceRange();
  4122. return setLCDeclAndLB(
  4123. Var,
  4124. buildDeclRefExpr(SemaRef, Var,
  4125. Var->getType().getNonReferenceType(),
  4126. DS->getBeginLoc()),
  4127. Var->getInit());
  4128. }
  4129. }
  4130. }
  4131. } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
  4132. if (CE->getOperator() == OO_Equal) {
  4133. Expr *LHS = CE->getArg(0);
  4134. if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
  4135. if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
  4136. if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
  4137. return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
  4138. return setLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1));
  4139. }
  4140. if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
  4141. if (ME->isArrow() &&
  4142. isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
  4143. return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
  4144. }
  4145. }
  4146. }
  4147. if (dependent() || SemaRef.CurContext->isDependentContext())
  4148. return false;
  4149. if (EmitDiags) {
  4150. SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_init)
  4151. << S->getSourceRange();
  4152. }
  4153. return true;
  4154. }
  4155. /// Ignore parenthesizes, implicit casts, copy constructor and return the
  4156. /// variable (which may be the loop variable) if possible.
  4157. static const ValueDecl *getInitLCDecl(const Expr *E) {
  4158. if (!E)
  4159. return nullptr;
  4160. E = getExprAsWritten(E);
  4161. if (const auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
  4162. if (const CXXConstructorDecl *Ctor = CE->getConstructor())
  4163. if ((Ctor->isCopyOrMoveConstructor() ||
  4164. Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
  4165. CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
  4166. E = CE->getArg(0)->IgnoreParenImpCasts();
  4167. if (const auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
  4168. if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
  4169. return getCanonicalDecl(VD);
  4170. }
  4171. if (const auto *ME = dyn_cast_or_null<MemberExpr>(E))
  4172. if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
  4173. return getCanonicalDecl(ME->getMemberDecl());
  4174. return nullptr;
  4175. }
  4176. bool OpenMPIterationSpaceChecker::checkAndSetCond(Expr *S) {
  4177. // Check test-expr for canonical form, save upper-bound UB, flags for
  4178. // less/greater and for strict/non-strict comparison.
  4179. // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
  4180. // var relational-op b
  4181. // b relational-op var
  4182. //
  4183. if (!S) {
  4184. SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << LCDecl;
  4185. return true;
  4186. }
  4187. S = getExprAsWritten(S);
  4188. SourceLocation CondLoc = S->getBeginLoc();
  4189. if (auto *BO = dyn_cast<BinaryOperator>(S)) {
  4190. if (BO->isRelationalOp()) {
  4191. if (getInitLCDecl(BO->getLHS()) == LCDecl)
  4192. return setUB(BO->getRHS(),
  4193. (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
  4194. (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
  4195. BO->getSourceRange(), BO->getOperatorLoc());
  4196. if (getInitLCDecl(BO->getRHS()) == LCDecl)
  4197. return setUB(BO->getLHS(),
  4198. (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
  4199. (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
  4200. BO->getSourceRange(), BO->getOperatorLoc());
  4201. } else if (BO->getOpcode() == BO_NE)
  4202. return setUB(getInitLCDecl(BO->getLHS()) == LCDecl ?
  4203. BO->getRHS() : BO->getLHS(),
  4204. /*LessOp=*/llvm::None,
  4205. /*StrictOp=*/true,
  4206. BO->getSourceRange(), BO->getOperatorLoc());
  4207. } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
  4208. if (CE->getNumArgs() == 2) {
  4209. auto Op = CE->getOperator();
  4210. switch (Op) {
  4211. case OO_Greater:
  4212. case OO_GreaterEqual:
  4213. case OO_Less:
  4214. case OO_LessEqual:
  4215. if (getInitLCDecl(CE->getArg(0)) == LCDecl)
  4216. return setUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
  4217. Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
  4218. CE->getOperatorLoc());
  4219. if (getInitLCDecl(CE->getArg(1)) == LCDecl)
  4220. return setUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
  4221. Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
  4222. CE->getOperatorLoc());
  4223. break;
  4224. case OO_ExclaimEqual:
  4225. return setUB(getInitLCDecl(CE->getArg(0)) == LCDecl ?
  4226. CE->getArg(1) : CE->getArg(0),
  4227. /*LessOp=*/llvm::None,
  4228. /*StrictOp=*/true,
  4229. CE->getSourceRange(),
  4230. CE->getOperatorLoc());
  4231. break;
  4232. default:
  4233. break;
  4234. }
  4235. }
  4236. }
  4237. if (dependent() || SemaRef.CurContext->isDependentContext())
  4238. return false;
  4239. SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
  4240. << S->getSourceRange() << LCDecl;
  4241. return true;
  4242. }
  4243. bool OpenMPIterationSpaceChecker::checkAndSetIncRHS(Expr *RHS) {
  4244. // RHS of canonical loop form increment can be:
  4245. // var + incr
  4246. // incr + var
  4247. // var - incr
  4248. //
  4249. RHS = RHS->IgnoreParenImpCasts();
  4250. if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
  4251. if (BO->isAdditiveOp()) {
  4252. bool IsAdd = BO->getOpcode() == BO_Add;
  4253. if (getInitLCDecl(BO->getLHS()) == LCDecl)
  4254. return setStep(BO->getRHS(), !IsAdd);
  4255. if (IsAdd && getInitLCDecl(BO->getRHS()) == LCDecl)
  4256. return setStep(BO->getLHS(), /*Subtract=*/false);
  4257. }
  4258. } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
  4259. bool IsAdd = CE->getOperator() == OO_Plus;
  4260. if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
  4261. if (getInitLCDecl(CE->getArg(0)) == LCDecl)
  4262. return setStep(CE->getArg(1), !IsAdd);
  4263. if (IsAdd && getInitLCDecl(CE->getArg(1)) == LCDecl)
  4264. return setStep(CE->getArg(0), /*Subtract=*/false);
  4265. }
  4266. }
  4267. if (dependent() || SemaRef.CurContext->isDependentContext())
  4268. return false;
  4269. SemaRef.Diag(RHS->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
  4270. << RHS->getSourceRange() << LCDecl;
  4271. return true;
  4272. }
  4273. bool OpenMPIterationSpaceChecker::checkAndSetInc(Expr *S) {
  4274. // Check incr-expr for canonical loop form and return true if it
  4275. // does not conform.
  4276. // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
  4277. // ++var
  4278. // var++
  4279. // --var
  4280. // var--
  4281. // var += incr
  4282. // var -= incr
  4283. // var = var + incr
  4284. // var = incr + var
  4285. // var = var - incr
  4286. //
  4287. if (!S) {
  4288. SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
  4289. return true;
  4290. }
  4291. if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
  4292. if (!ExprTemp->cleanupsHaveSideEffects())
  4293. S = ExprTemp->getSubExpr();
  4294. IncrementSrcRange = S->getSourceRange();
  4295. S = S->IgnoreParens();
  4296. if (auto *UO = dyn_cast<UnaryOperator>(S)) {
  4297. if (UO->isIncrementDecrementOp() &&
  4298. getInitLCDecl(UO->getSubExpr()) == LCDecl)
  4299. return setStep(SemaRef
  4300. .ActOnIntegerConstant(UO->getBeginLoc(),
  4301. (UO->isDecrementOp() ? -1 : 1))
  4302. .get(),
  4303. /*Subtract=*/false);
  4304. } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
  4305. switch (BO->getOpcode()) {
  4306. case BO_AddAssign:
  4307. case BO_SubAssign:
  4308. if (getInitLCDecl(BO->getLHS()) == LCDecl)
  4309. return setStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
  4310. break;
  4311. case BO_Assign:
  4312. if (getInitLCDecl(BO->getLHS()) == LCDecl)
  4313. return checkAndSetIncRHS(BO->getRHS());
  4314. break;
  4315. default:
  4316. break;
  4317. }
  4318. } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
  4319. switch (CE->getOperator()) {
  4320. case OO_PlusPlus:
  4321. case OO_MinusMinus:
  4322. if (getInitLCDecl(CE->getArg(0)) == LCDecl)
  4323. return setStep(SemaRef
  4324. .ActOnIntegerConstant(
  4325. CE->getBeginLoc(),
  4326. ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
  4327. .get(),
  4328. /*Subtract=*/false);
  4329. break;
  4330. case OO_PlusEqual:
  4331. case OO_MinusEqual:
  4332. if (getInitLCDecl(CE->getArg(0)) == LCDecl)
  4333. return setStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
  4334. break;
  4335. case OO_Equal:
  4336. if (getInitLCDecl(CE->getArg(0)) == LCDecl)
  4337. return checkAndSetIncRHS(CE->getArg(1));
  4338. break;
  4339. default:
  4340. break;
  4341. }
  4342. }
  4343. if (dependent() || SemaRef.CurContext->isDependentContext())
  4344. return false;
  4345. SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
  4346. << S->getSourceRange() << LCDecl;
  4347. return true;
  4348. }
  4349. static ExprResult
  4350. tryBuildCapture(Sema &SemaRef, Expr *Capture,
  4351. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
  4352. if (SemaRef.CurContext->isDependentContext())
  4353. return ExprResult(Capture);
  4354. if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
  4355. return SemaRef.PerformImplicitConversion(
  4356. Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
  4357. /*AllowExplicit=*/true);
  4358. auto I = Captures.find(Capture);
  4359. if (I != Captures.end())
  4360. return buildCapture(SemaRef, Capture, I->second);
  4361. DeclRefExpr *Ref = nullptr;
  4362. ExprResult Res = buildCapture(SemaRef, Capture, Ref);
  4363. Captures[Capture] = Ref;
  4364. return Res;
  4365. }
  4366. /// Build the expression to calculate the number of iterations.
  4367. Expr *OpenMPIterationSpaceChecker::buildNumIterations(
  4368. Scope *S, const bool LimitedType,
  4369. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
  4370. ExprResult Diff;
  4371. QualType VarType = LCDecl->getType().getNonReferenceType();
  4372. if (VarType->isIntegerType() || VarType->isPointerType() ||
  4373. SemaRef.getLangOpts().CPlusPlus) {
  4374. // Upper - Lower
  4375. Expr *UBExpr = TestIsLessOp.getValue() ? UB : LB;
  4376. Expr *LBExpr = TestIsLessOp.getValue() ? LB : UB;
  4377. Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
  4378. Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
  4379. if (!Upper || !Lower)
  4380. return nullptr;
  4381. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
  4382. if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
  4383. // BuildBinOp already emitted error, this one is to point user to upper
  4384. // and lower bound, and to tell what is passed to 'operator-'.
  4385. SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx)
  4386. << Upper->getSourceRange() << Lower->getSourceRange();
  4387. return nullptr;
  4388. }
  4389. }
  4390. if (!Diff.isUsable())
  4391. return nullptr;
  4392. // Upper - Lower [- 1]
  4393. if (TestIsStrictOp)
  4394. Diff = SemaRef.BuildBinOp(
  4395. S, DefaultLoc, BO_Sub, Diff.get(),
  4396. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
  4397. if (!Diff.isUsable())
  4398. return nullptr;
  4399. // Upper - Lower [- 1] + Step
  4400. ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
  4401. if (!NewStep.isUsable())
  4402. return nullptr;
  4403. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
  4404. if (!Diff.isUsable())
  4405. return nullptr;
  4406. // Parentheses (for dumping/debugging purposes only).
  4407. Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
  4408. if (!Diff.isUsable())
  4409. return nullptr;
  4410. // (Upper - Lower [- 1] + Step) / Step
  4411. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
  4412. if (!Diff.isUsable())
  4413. return nullptr;
  4414. // OpenMP runtime requires 32-bit or 64-bit loop variables.
  4415. QualType Type = Diff.get()->getType();
  4416. ASTContext &C = SemaRef.Context;
  4417. bool UseVarType = VarType->hasIntegerRepresentation() &&
  4418. C.getTypeSize(Type) > C.getTypeSize(VarType);
  4419. if (!Type->isIntegerType() || UseVarType) {
  4420. unsigned NewSize =
  4421. UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
  4422. bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
  4423. : Type->hasSignedIntegerRepresentation();
  4424. Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
  4425. if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
  4426. Diff = SemaRef.PerformImplicitConversion(
  4427. Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
  4428. if (!Diff.isUsable())
  4429. return nullptr;
  4430. }
  4431. }
  4432. if (LimitedType) {
  4433. unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
  4434. if (NewSize != C.getTypeSize(Type)) {
  4435. if (NewSize < C.getTypeSize(Type)) {
  4436. assert(NewSize == 64 && "incorrect loop var size");
  4437. SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
  4438. << InitSrcRange << ConditionSrcRange;
  4439. }
  4440. QualType NewType = C.getIntTypeForBitwidth(
  4441. NewSize, Type->hasSignedIntegerRepresentation() ||
  4442. C.getTypeSize(Type) < NewSize);
  4443. if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
  4444. Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
  4445. Sema::AA_Converting, true);
  4446. if (!Diff.isUsable())
  4447. return nullptr;
  4448. }
  4449. }
  4450. }
  4451. return Diff.get();
  4452. }
  4453. Expr *OpenMPIterationSpaceChecker::buildPreCond(
  4454. Scope *S, Expr *Cond,
  4455. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
  4456. // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
  4457. bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
  4458. SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
  4459. ExprResult NewLB = tryBuildCapture(SemaRef, LB, Captures);
  4460. ExprResult NewUB = tryBuildCapture(SemaRef, UB, Captures);
  4461. if (!NewLB.isUsable() || !NewUB.isUsable())
  4462. return nullptr;
  4463. ExprResult CondExpr =
  4464. SemaRef.BuildBinOp(S, DefaultLoc,
  4465. TestIsLessOp.getValue() ?
  4466. (TestIsStrictOp ? BO_LT : BO_LE) :
  4467. (TestIsStrictOp ? BO_GT : BO_GE),
  4468. NewLB.get(), NewUB.get());
  4469. if (CondExpr.isUsable()) {
  4470. if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
  4471. SemaRef.Context.BoolTy))
  4472. CondExpr = SemaRef.PerformImplicitConversion(
  4473. CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
  4474. /*AllowExplicit=*/true);
  4475. }
  4476. SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
  4477. // Otherwise use original loop condition and evaluate it in runtime.
  4478. return CondExpr.isUsable() ? CondExpr.get() : Cond;
  4479. }
  4480. /// Build reference expression to the counter be used for codegen.
  4481. DeclRefExpr *OpenMPIterationSpaceChecker::buildCounterVar(
  4482. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
  4483. DSAStackTy &DSA) const {
  4484. auto *VD = dyn_cast<VarDecl>(LCDecl);
  4485. if (!VD) {
  4486. VD = SemaRef.isOpenMPCapturedDecl(LCDecl);
  4487. DeclRefExpr *Ref = buildDeclRefExpr(
  4488. SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
  4489. const DSAStackTy::DSAVarData Data =
  4490. DSA.getTopDSA(LCDecl, /*FromParent=*/false);
  4491. // If the loop control decl is explicitly marked as private, do not mark it
  4492. // as captured again.
  4493. if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
  4494. Captures.insert(std::make_pair(LCRef, Ref));
  4495. return Ref;
  4496. }
  4497. return cast<DeclRefExpr>(LCRef);
  4498. }
  4499. Expr *OpenMPIterationSpaceChecker::buildPrivateCounterVar() const {
  4500. if (LCDecl && !LCDecl->isInvalidDecl()) {
  4501. QualType Type = LCDecl->getType().getNonReferenceType();
  4502. VarDecl *PrivateVar = buildVarDecl(
  4503. SemaRef, DefaultLoc, Type, LCDecl->getName(),
  4504. LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr,
  4505. isa<VarDecl>(LCDecl)
  4506. ? buildDeclRefExpr(SemaRef, cast<VarDecl>(LCDecl), Type, DefaultLoc)
  4507. : nullptr);
  4508. if (PrivateVar->isInvalidDecl())
  4509. return nullptr;
  4510. return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
  4511. }
  4512. return nullptr;
  4513. }
  4514. /// Build initialization of the counter to be used for codegen.
  4515. Expr *OpenMPIterationSpaceChecker::buildCounterInit() const { return LB; }
  4516. /// Build step of the counter be used for codegen.
  4517. Expr *OpenMPIterationSpaceChecker::buildCounterStep() const { return Step; }
  4518. Expr *OpenMPIterationSpaceChecker::buildOrderedLoopData(
  4519. Scope *S, Expr *Counter,
  4520. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, SourceLocation Loc,
  4521. Expr *Inc, OverloadedOperatorKind OOK) {
  4522. Expr *Cnt = SemaRef.DefaultLvalueConversion(Counter).get();
  4523. if (!Cnt)
  4524. return nullptr;
  4525. if (Inc) {
  4526. assert((OOK == OO_Plus || OOK == OO_Minus) &&
  4527. "Expected only + or - operations for depend clauses.");
  4528. BinaryOperatorKind BOK = (OOK == OO_Plus) ? BO_Add : BO_Sub;
  4529. Cnt = SemaRef.BuildBinOp(S, Loc, BOK, Cnt, Inc).get();
  4530. if (!Cnt)
  4531. return nullptr;
  4532. }
  4533. ExprResult Diff;
  4534. QualType VarType = LCDecl->getType().getNonReferenceType();
  4535. if (VarType->isIntegerType() || VarType->isPointerType() ||
  4536. SemaRef.getLangOpts().CPlusPlus) {
  4537. // Upper - Lower
  4538. Expr *Upper = TestIsLessOp.getValue()
  4539. ? Cnt
  4540. : tryBuildCapture(SemaRef, UB, Captures).get();
  4541. Expr *Lower = TestIsLessOp.getValue()
  4542. ? tryBuildCapture(SemaRef, LB, Captures).get()
  4543. : Cnt;
  4544. if (!Upper || !Lower)
  4545. return nullptr;
  4546. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
  4547. if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
  4548. // BuildBinOp already emitted error, this one is to point user to upper
  4549. // and lower bound, and to tell what is passed to 'operator-'.
  4550. SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx)
  4551. << Upper->getSourceRange() << Lower->getSourceRange();
  4552. return nullptr;
  4553. }
  4554. }
  4555. if (!Diff.isUsable())
  4556. return nullptr;
  4557. // Parentheses (for dumping/debugging purposes only).
  4558. Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
  4559. if (!Diff.isUsable())
  4560. return nullptr;
  4561. ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
  4562. if (!NewStep.isUsable())
  4563. return nullptr;
  4564. // (Upper - Lower) / Step
  4565. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
  4566. if (!Diff.isUsable())
  4567. return nullptr;
  4568. return Diff.get();
  4569. }
  4570. /// Iteration space of a single for loop.
  4571. struct LoopIterationSpace final {
  4572. /// True if the condition operator is the strict compare operator (<, > or
  4573. /// !=).
  4574. bool IsStrictCompare = false;
  4575. /// Condition of the loop.
  4576. Expr *PreCond = nullptr;
  4577. /// This expression calculates the number of iterations in the loop.
  4578. /// It is always possible to calculate it before starting the loop.
  4579. Expr *NumIterations = nullptr;
  4580. /// The loop counter variable.
  4581. Expr *CounterVar = nullptr;
  4582. /// Private loop counter variable.
  4583. Expr *PrivateCounterVar = nullptr;
  4584. /// This is initializer for the initial value of #CounterVar.
  4585. Expr *CounterInit = nullptr;
  4586. /// This is step for the #CounterVar used to generate its update:
  4587. /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
  4588. Expr *CounterStep = nullptr;
  4589. /// Should step be subtracted?
  4590. bool Subtract = false;
  4591. /// Source range of the loop init.
  4592. SourceRange InitSrcRange;
  4593. /// Source range of the loop condition.
  4594. SourceRange CondSrcRange;
  4595. /// Source range of the loop increment.
  4596. SourceRange IncSrcRange;
  4597. };
  4598. } // namespace
  4599. void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
  4600. assert(getLangOpts().OpenMP && "OpenMP is not active.");
  4601. assert(Init && "Expected loop in canonical form.");
  4602. unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
  4603. if (AssociatedLoops > 0 &&
  4604. isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
  4605. DSAStack->loopStart();
  4606. OpenMPIterationSpaceChecker ISC(*this, ForLoc);
  4607. if (!ISC.checkAndSetInit(Init, /*EmitDiags=*/false)) {
  4608. if (ValueDecl *D = ISC.getLoopDecl()) {
  4609. auto *VD = dyn_cast<VarDecl>(D);
  4610. if (!VD) {
  4611. if (VarDecl *Private = isOpenMPCapturedDecl(D)) {
  4612. VD = Private;
  4613. } else {
  4614. DeclRefExpr *Ref = buildCapture(*this, D, ISC.getLoopDeclRefExpr(),
  4615. /*WithInit=*/false);
  4616. VD = cast<VarDecl>(Ref->getDecl());
  4617. }
  4618. }
  4619. DSAStack->addLoopControlVariable(D, VD);
  4620. const Decl *LD = DSAStack->getPossiblyLoopCunter();
  4621. if (LD != D->getCanonicalDecl()) {
  4622. DSAStack->resetPossibleLoopCounter();
  4623. if (auto *Var = dyn_cast_or_null<VarDecl>(LD))
  4624. MarkDeclarationsReferencedInExpr(
  4625. buildDeclRefExpr(*this, const_cast<VarDecl *>(Var),
  4626. Var->getType().getNonLValueExprType(Context),
  4627. ForLoc, /*RefersToCapture=*/true));
  4628. }
  4629. }
  4630. }
  4631. DSAStack->setAssociatedLoops(AssociatedLoops - 1);
  4632. }
  4633. }
  4634. /// Called on a for stmt to check and extract its iteration space
  4635. /// for further processing (such as collapsing).
  4636. static bool checkOpenMPIterationSpace(
  4637. OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
  4638. unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
  4639. unsigned TotalNestedLoopCount, Expr *CollapseLoopCountExpr,
  4640. Expr *OrderedLoopCountExpr,
  4641. Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
  4642. LoopIterationSpace &ResultIterSpace,
  4643. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
  4644. // OpenMP [2.6, Canonical Loop Form]
  4645. // for (init-expr; test-expr; incr-expr) structured-block
  4646. auto *For = dyn_cast_or_null<ForStmt>(S);
  4647. if (!For) {
  4648. SemaRef.Diag(S->getBeginLoc(), diag::err_omp_not_for)
  4649. << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
  4650. << getOpenMPDirectiveName(DKind) << TotalNestedLoopCount
  4651. << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
  4652. if (TotalNestedLoopCount > 1) {
  4653. if (CollapseLoopCountExpr && OrderedLoopCountExpr)
  4654. SemaRef.Diag(DSA.getConstructLoc(),
  4655. diag::note_omp_collapse_ordered_expr)
  4656. << 2 << CollapseLoopCountExpr->getSourceRange()
  4657. << OrderedLoopCountExpr->getSourceRange();
  4658. else if (CollapseLoopCountExpr)
  4659. SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
  4660. diag::note_omp_collapse_ordered_expr)
  4661. << 0 << CollapseLoopCountExpr->getSourceRange();
  4662. else
  4663. SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
  4664. diag::note_omp_collapse_ordered_expr)
  4665. << 1 << OrderedLoopCountExpr->getSourceRange();
  4666. }
  4667. return true;
  4668. }
  4669. assert(For->getBody());
  4670. OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
  4671. // Check init.
  4672. Stmt *Init = For->getInit();
  4673. if (ISC.checkAndSetInit(Init))
  4674. return true;
  4675. bool HasErrors = false;
  4676. // Check loop variable's type.
  4677. if (ValueDecl *LCDecl = ISC.getLoopDecl()) {
  4678. Expr *LoopDeclRefExpr = ISC.getLoopDeclRefExpr();
  4679. // OpenMP [2.6, Canonical Loop Form]
  4680. // Var is one of the following:
  4681. // A variable of signed or unsigned integer type.
  4682. // For C++, a variable of a random access iterator type.
  4683. // For C, a variable of a pointer type.
  4684. QualType VarType = LCDecl->getType().getNonReferenceType();
  4685. if (!VarType->isDependentType() && !VarType->isIntegerType() &&
  4686. !VarType->isPointerType() &&
  4687. !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
  4688. SemaRef.Diag(Init->getBeginLoc(), diag::err_omp_loop_variable_type)
  4689. << SemaRef.getLangOpts().CPlusPlus;
  4690. HasErrors = true;
  4691. }
  4692. // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
  4693. // a Construct
  4694. // The loop iteration variable(s) in the associated for-loop(s) of a for or
  4695. // parallel for construct is (are) private.
  4696. // The loop iteration variable in the associated for-loop of a simd
  4697. // construct with just one associated for-loop is linear with a
  4698. // constant-linear-step that is the increment of the associated for-loop.
  4699. // Exclude loop var from the list of variables with implicitly defined data
  4700. // sharing attributes.
  4701. VarsWithImplicitDSA.erase(LCDecl);
  4702. // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
  4703. // in a Construct, C/C++].
  4704. // The loop iteration variable in the associated for-loop of a simd
  4705. // construct with just one associated for-loop may be listed in a linear
  4706. // clause with a constant-linear-step that is the increment of the
  4707. // associated for-loop.
  4708. // The loop iteration variable(s) in the associated for-loop(s) of a for or
  4709. // parallel for construct may be listed in a private or lastprivate clause.
  4710. DSAStackTy::DSAVarData DVar = DSA.getTopDSA(LCDecl, false);
  4711. // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
  4712. // declared in the loop and it is predetermined as a private.
  4713. OpenMPClauseKind PredeterminedCKind =
  4714. isOpenMPSimdDirective(DKind)
  4715. ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
  4716. : OMPC_private;
  4717. if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
  4718. DVar.CKind != PredeterminedCKind) ||
  4719. ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
  4720. isOpenMPDistributeDirective(DKind)) &&
  4721. !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
  4722. DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
  4723. (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
  4724. SemaRef.Diag(Init->getBeginLoc(), diag::err_omp_loop_var_dsa)
  4725. << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
  4726. << getOpenMPClauseName(PredeterminedCKind);
  4727. if (DVar.RefExpr == nullptr)
  4728. DVar.CKind = PredeterminedCKind;
  4729. reportOriginalDsa(SemaRef, &DSA, LCDecl, DVar, /*IsLoopIterVar=*/true);
  4730. HasErrors = true;
  4731. } else if (LoopDeclRefExpr != nullptr) {
  4732. // Make the loop iteration variable private (for worksharing constructs),
  4733. // linear (for simd directives with the only one associated loop) or
  4734. // lastprivate (for simd directives with several collapsed or ordered
  4735. // loops).
  4736. if (DVar.CKind == OMPC_unknown)
  4737. DSA.addDSA(LCDecl, LoopDeclRefExpr, PredeterminedCKind);
  4738. }
  4739. assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
  4740. // Check test-expr.
  4741. HasErrors |= ISC.checkAndSetCond(For->getCond());
  4742. // Check incr-expr.
  4743. HasErrors |= ISC.checkAndSetInc(For->getInc());
  4744. }
  4745. if (ISC.dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
  4746. return HasErrors;
  4747. // Build the loop's iteration space representation.
  4748. ResultIterSpace.PreCond =
  4749. ISC.buildPreCond(DSA.getCurScope(), For->getCond(), Captures);
  4750. ResultIterSpace.NumIterations = ISC.buildNumIterations(
  4751. DSA.getCurScope(),
  4752. (isOpenMPWorksharingDirective(DKind) ||
  4753. isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)),
  4754. Captures);
  4755. ResultIterSpace.CounterVar = ISC.buildCounterVar(Captures, DSA);
  4756. ResultIterSpace.PrivateCounterVar = ISC.buildPrivateCounterVar();
  4757. ResultIterSpace.CounterInit = ISC.buildCounterInit();
  4758. ResultIterSpace.CounterStep = ISC.buildCounterStep();
  4759. ResultIterSpace.InitSrcRange = ISC.getInitSrcRange();
  4760. ResultIterSpace.CondSrcRange = ISC.getConditionSrcRange();
  4761. ResultIterSpace.IncSrcRange = ISC.getIncrementSrcRange();
  4762. ResultIterSpace.Subtract = ISC.shouldSubtractStep();
  4763. ResultIterSpace.IsStrictCompare = ISC.isStrictTestOp();
  4764. HasErrors |= (ResultIterSpace.PreCond == nullptr ||
  4765. ResultIterSpace.NumIterations == nullptr ||
  4766. ResultIterSpace.CounterVar == nullptr ||
  4767. ResultIterSpace.PrivateCounterVar == nullptr ||
  4768. ResultIterSpace.CounterInit == nullptr ||
  4769. ResultIterSpace.CounterStep == nullptr);
  4770. if (!HasErrors && DSA.isOrderedRegion()) {
  4771. if (DSA.getOrderedRegionParam().second->getNumForLoops()) {
  4772. if (CurrentNestedLoopCount <
  4773. DSA.getOrderedRegionParam().second->getLoopNumIterations().size()) {
  4774. DSA.getOrderedRegionParam().second->setLoopNumIterations(
  4775. CurrentNestedLoopCount, ResultIterSpace.NumIterations);
  4776. DSA.getOrderedRegionParam().second->setLoopCounter(
  4777. CurrentNestedLoopCount, ResultIterSpace.CounterVar);
  4778. }
  4779. }
  4780. for (auto &Pair : DSA.getDoacrossDependClauses()) {
  4781. if (CurrentNestedLoopCount >= Pair.first->getNumLoops()) {
  4782. // Erroneous case - clause has some problems.
  4783. continue;
  4784. }
  4785. if (Pair.first->getDependencyKind() == OMPC_DEPEND_sink &&
  4786. Pair.second.size() <= CurrentNestedLoopCount) {
  4787. // Erroneous case - clause has some problems.
  4788. Pair.first->setLoopData(CurrentNestedLoopCount, nullptr);
  4789. continue;
  4790. }
  4791. Expr *CntValue;
  4792. if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
  4793. CntValue = ISC.buildOrderedLoopData(
  4794. DSA.getCurScope(), ResultIterSpace.CounterVar, Captures,
  4795. Pair.first->getDependencyLoc());
  4796. else
  4797. CntValue = ISC.buildOrderedLoopData(
  4798. DSA.getCurScope(), ResultIterSpace.CounterVar, Captures,
  4799. Pair.first->getDependencyLoc(),
  4800. Pair.second[CurrentNestedLoopCount].first,
  4801. Pair.second[CurrentNestedLoopCount].second);
  4802. Pair.first->setLoopData(CurrentNestedLoopCount, CntValue);
  4803. }
  4804. }
  4805. return HasErrors;
  4806. }
  4807. /// Build 'VarRef = Start.
  4808. static ExprResult
  4809. buildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
  4810. ExprResult Start,
  4811. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
  4812. // Build 'VarRef = Start.
  4813. ExprResult NewStart = tryBuildCapture(SemaRef, Start.get(), Captures);
  4814. if (!NewStart.isUsable())
  4815. return ExprError();
  4816. if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
  4817. VarRef.get()->getType())) {
  4818. NewStart = SemaRef.PerformImplicitConversion(
  4819. NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
  4820. /*AllowExplicit=*/true);
  4821. if (!NewStart.isUsable())
  4822. return ExprError();
  4823. }
  4824. ExprResult Init =
  4825. SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
  4826. return Init;
  4827. }
  4828. /// Build 'VarRef = Start + Iter * Step'.
  4829. static ExprResult buildCounterUpdate(
  4830. Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
  4831. ExprResult Start, ExprResult Iter, ExprResult Step, bool Subtract,
  4832. llvm::MapVector<const Expr *, DeclRefExpr *> *Captures = nullptr) {
  4833. // Add parentheses (for debugging purposes only).
  4834. Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
  4835. if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
  4836. !Step.isUsable())
  4837. return ExprError();
  4838. ExprResult NewStep = Step;
  4839. if (Captures)
  4840. NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
  4841. if (NewStep.isInvalid())
  4842. return ExprError();
  4843. ExprResult Update =
  4844. SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
  4845. if (!Update.isUsable())
  4846. return ExprError();
  4847. // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
  4848. // 'VarRef = Start (+|-) Iter * Step'.
  4849. ExprResult NewStart = Start;
  4850. if (Captures)
  4851. NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
  4852. if (NewStart.isInvalid())
  4853. return ExprError();
  4854. // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
  4855. ExprResult SavedUpdate = Update;
  4856. ExprResult UpdateVal;
  4857. if (VarRef.get()->getType()->isOverloadableType() ||
  4858. NewStart.get()->getType()->isOverloadableType() ||
  4859. Update.get()->getType()->isOverloadableType()) {
  4860. bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
  4861. SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
  4862. Update =
  4863. SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
  4864. if (Update.isUsable()) {
  4865. UpdateVal =
  4866. SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
  4867. VarRef.get(), SavedUpdate.get());
  4868. if (UpdateVal.isUsable()) {
  4869. Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
  4870. UpdateVal.get());
  4871. }
  4872. }
  4873. SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
  4874. }
  4875. // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
  4876. if (!Update.isUsable() || !UpdateVal.isUsable()) {
  4877. Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
  4878. NewStart.get(), SavedUpdate.get());
  4879. if (!Update.isUsable())
  4880. return ExprError();
  4881. if (!SemaRef.Context.hasSameType(Update.get()->getType(),
  4882. VarRef.get()->getType())) {
  4883. Update = SemaRef.PerformImplicitConversion(
  4884. Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
  4885. if (!Update.isUsable())
  4886. return ExprError();
  4887. }
  4888. Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
  4889. }
  4890. return Update;
  4891. }
  4892. /// Convert integer expression \a E to make it have at least \a Bits
  4893. /// bits.
  4894. static ExprResult widenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
  4895. if (E == nullptr)
  4896. return ExprError();
  4897. ASTContext &C = SemaRef.Context;
  4898. QualType OldType = E->getType();
  4899. unsigned HasBits = C.getTypeSize(OldType);
  4900. if (HasBits >= Bits)
  4901. return ExprResult(E);
  4902. // OK to convert to signed, because new type has more bits than old.
  4903. QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
  4904. return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
  4905. true);
  4906. }
  4907. /// Check if the given expression \a E is a constant integer that fits
  4908. /// into \a Bits bits.
  4909. static bool fitsInto(unsigned Bits, bool Signed, const Expr *E, Sema &SemaRef) {
  4910. if (E == nullptr)
  4911. return false;
  4912. llvm::APSInt Result;
  4913. if (E->isIntegerConstantExpr(Result, SemaRef.Context))
  4914. return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
  4915. return false;
  4916. }
  4917. /// Build preinits statement for the given declarations.
  4918. static Stmt *buildPreInits(ASTContext &Context,
  4919. MutableArrayRef<Decl *> PreInits) {
  4920. if (!PreInits.empty()) {
  4921. return new (Context) DeclStmt(
  4922. DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
  4923. SourceLocation(), SourceLocation());
  4924. }
  4925. return nullptr;
  4926. }
  4927. /// Build preinits statement for the given declarations.
  4928. static Stmt *
  4929. buildPreInits(ASTContext &Context,
  4930. const llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
  4931. if (!Captures.empty()) {
  4932. SmallVector<Decl *, 16> PreInits;
  4933. for (const auto &Pair : Captures)
  4934. PreInits.push_back(Pair.second->getDecl());
  4935. return buildPreInits(Context, PreInits);
  4936. }
  4937. return nullptr;
  4938. }
  4939. /// Build postupdate expression for the given list of postupdates expressions.
  4940. static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
  4941. Expr *PostUpdate = nullptr;
  4942. if (!PostUpdates.empty()) {
  4943. for (Expr *E : PostUpdates) {
  4944. Expr *ConvE = S.BuildCStyleCastExpr(
  4945. E->getExprLoc(),
  4946. S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
  4947. E->getExprLoc(), E)
  4948. .get();
  4949. PostUpdate = PostUpdate
  4950. ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
  4951. PostUpdate, ConvE)
  4952. .get()
  4953. : ConvE;
  4954. }
  4955. }
  4956. return PostUpdate;
  4957. }
  4958. /// Called on a for stmt to check itself and nested loops (if any).
  4959. /// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
  4960. /// number of collapsed loops otherwise.
  4961. static unsigned
  4962. checkOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
  4963. Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
  4964. DSAStackTy &DSA,
  4965. Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
  4966. OMPLoopDirective::HelperExprs &Built) {
  4967. unsigned NestedLoopCount = 1;
  4968. if (CollapseLoopCountExpr) {
  4969. // Found 'collapse' clause - calculate collapse number.
  4970. Expr::EvalResult Result;
  4971. if (CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
  4972. NestedLoopCount = Result.Val.getInt().getLimitedValue();
  4973. }
  4974. unsigned OrderedLoopCount = 1;
  4975. if (OrderedLoopCountExpr) {
  4976. // Found 'ordered' clause - calculate collapse number.
  4977. Expr::EvalResult EVResult;
  4978. if (OrderedLoopCountExpr->EvaluateAsInt(EVResult, SemaRef.getASTContext())) {
  4979. llvm::APSInt Result = EVResult.Val.getInt();
  4980. if (Result.getLimitedValue() < NestedLoopCount) {
  4981. SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
  4982. diag::err_omp_wrong_ordered_loop_count)
  4983. << OrderedLoopCountExpr->getSourceRange();
  4984. SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
  4985. diag::note_collapse_loop_count)
  4986. << CollapseLoopCountExpr->getSourceRange();
  4987. }
  4988. OrderedLoopCount = Result.getLimitedValue();
  4989. }
  4990. }
  4991. // This is helper routine for loop directives (e.g., 'for', 'simd',
  4992. // 'for simd', etc.).
  4993. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  4994. SmallVector<LoopIterationSpace, 4> IterSpaces(
  4995. std::max(OrderedLoopCount, NestedLoopCount));
  4996. Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
  4997. for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
  4998. if (checkOpenMPIterationSpace(
  4999. DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
  5000. std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr,
  5001. OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces[Cnt],
  5002. Captures))
  5003. return 0;
  5004. // Move on to the next nested for loop, or to the loop body.
  5005. // OpenMP [2.8.1, simd construct, Restrictions]
  5006. // All loops associated with the construct must be perfectly nested; that
  5007. // is, there must be no intervening code nor any OpenMP directive between
  5008. // any two loops.
  5009. CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
  5010. }
  5011. for (unsigned Cnt = NestedLoopCount; Cnt < OrderedLoopCount; ++Cnt) {
  5012. if (checkOpenMPIterationSpace(
  5013. DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
  5014. std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr,
  5015. OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces[Cnt],
  5016. Captures))
  5017. return 0;
  5018. if (Cnt > 0 && IterSpaces[Cnt].CounterVar) {
  5019. // Handle initialization of captured loop iterator variables.
  5020. auto *DRE = cast<DeclRefExpr>(IterSpaces[Cnt].CounterVar);
  5021. if (isa<OMPCapturedExprDecl>(DRE->getDecl())) {
  5022. Captures[DRE] = DRE;
  5023. }
  5024. }
  5025. // Move on to the next nested for loop, or to the loop body.
  5026. // OpenMP [2.8.1, simd construct, Restrictions]
  5027. // All loops associated with the construct must be perfectly nested; that
  5028. // is, there must be no intervening code nor any OpenMP directive between
  5029. // any two loops.
  5030. CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
  5031. }
  5032. Built.clear(/* size */ NestedLoopCount);
  5033. if (SemaRef.CurContext->isDependentContext())
  5034. return NestedLoopCount;
  5035. // An example of what is generated for the following code:
  5036. //
  5037. // #pragma omp simd collapse(2) ordered(2)
  5038. // for (i = 0; i < NI; ++i)
  5039. // for (k = 0; k < NK; ++k)
  5040. // for (j = J0; j < NJ; j+=2) {
  5041. // <loop body>
  5042. // }
  5043. //
  5044. // We generate the code below.
  5045. // Note: the loop body may be outlined in CodeGen.
  5046. // Note: some counters may be C++ classes, operator- is used to find number of
  5047. // iterations and operator+= to calculate counter value.
  5048. // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
  5049. // or i64 is currently supported).
  5050. //
  5051. // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
  5052. // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
  5053. // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
  5054. // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
  5055. // // similar updates for vars in clauses (e.g. 'linear')
  5056. // <loop body (using local i and j)>
  5057. // }
  5058. // i = NI; // assign final values of counters
  5059. // j = NJ;
  5060. //
  5061. // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
  5062. // the iteration counts of the collapsed for loops.
  5063. // Precondition tests if there is at least one iteration (all conditions are
  5064. // true).
  5065. auto PreCond = ExprResult(IterSpaces[0].PreCond);
  5066. Expr *N0 = IterSpaces[0].NumIterations;
  5067. ExprResult LastIteration32 =
  5068. widenIterationCount(/*Bits=*/32,
  5069. SemaRef
  5070. .PerformImplicitConversion(
  5071. N0->IgnoreImpCasts(), N0->getType(),
  5072. Sema::AA_Converting, /*AllowExplicit=*/true)
  5073. .get(),
  5074. SemaRef);
  5075. ExprResult LastIteration64 = widenIterationCount(
  5076. /*Bits=*/64,
  5077. SemaRef
  5078. .PerformImplicitConversion(N0->IgnoreImpCasts(), N0->getType(),
  5079. Sema::AA_Converting,
  5080. /*AllowExplicit=*/true)
  5081. .get(),
  5082. SemaRef);
  5083. if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
  5084. return NestedLoopCount;
  5085. ASTContext &C = SemaRef.Context;
  5086. bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
  5087. Scope *CurScope = DSA.getCurScope();
  5088. for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
  5089. if (PreCond.isUsable()) {
  5090. PreCond =
  5091. SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
  5092. PreCond.get(), IterSpaces[Cnt].PreCond);
  5093. }
  5094. Expr *N = IterSpaces[Cnt].NumIterations;
  5095. SourceLocation Loc = N->getExprLoc();
  5096. AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
  5097. if (LastIteration32.isUsable())
  5098. LastIteration32 = SemaRef.BuildBinOp(
  5099. CurScope, Loc, BO_Mul, LastIteration32.get(),
  5100. SemaRef
  5101. .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
  5102. Sema::AA_Converting,
  5103. /*AllowExplicit=*/true)
  5104. .get());
  5105. if (LastIteration64.isUsable())
  5106. LastIteration64 = SemaRef.BuildBinOp(
  5107. CurScope, Loc, BO_Mul, LastIteration64.get(),
  5108. SemaRef
  5109. .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
  5110. Sema::AA_Converting,
  5111. /*AllowExplicit=*/true)
  5112. .get());
  5113. }
  5114. // Choose either the 32-bit or 64-bit version.
  5115. ExprResult LastIteration = LastIteration64;
  5116. if (SemaRef.getLangOpts().OpenMPOptimisticCollapse ||
  5117. (LastIteration32.isUsable() &&
  5118. C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
  5119. (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
  5120. fitsInto(
  5121. /*Bits=*/32,
  5122. LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
  5123. LastIteration64.get(), SemaRef))))
  5124. LastIteration = LastIteration32;
  5125. QualType VType = LastIteration.get()->getType();
  5126. QualType RealVType = VType;
  5127. QualType StrideVType = VType;
  5128. if (isOpenMPTaskLoopDirective(DKind)) {
  5129. VType =
  5130. SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
  5131. StrideVType =
  5132. SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
  5133. }
  5134. if (!LastIteration.isUsable())
  5135. return 0;
  5136. // Save the number of iterations.
  5137. ExprResult NumIterations = LastIteration;
  5138. {
  5139. LastIteration = SemaRef.BuildBinOp(
  5140. CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
  5141. LastIteration.get(),
  5142. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
  5143. if (!LastIteration.isUsable())
  5144. return 0;
  5145. }
  5146. // Calculate the last iteration number beforehand instead of doing this on
  5147. // each iteration. Do not do this if the number of iterations may be kfold-ed.
  5148. llvm::APSInt Result;
  5149. bool IsConstant =
  5150. LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
  5151. ExprResult CalcLastIteration;
  5152. if (!IsConstant) {
  5153. ExprResult SaveRef =
  5154. tryBuildCapture(SemaRef, LastIteration.get(), Captures);
  5155. LastIteration = SaveRef;
  5156. // Prepare SaveRef + 1.
  5157. NumIterations = SemaRef.BuildBinOp(
  5158. CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
  5159. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
  5160. if (!NumIterations.isUsable())
  5161. return 0;
  5162. }
  5163. SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
  5164. // Build variables passed into runtime, necessary for worksharing directives.
  5165. ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB;
  5166. if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
  5167. isOpenMPDistributeDirective(DKind)) {
  5168. // Lower bound variable, initialized with zero.
  5169. VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
  5170. LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
  5171. SemaRef.AddInitializerToDecl(LBDecl,
  5172. SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
  5173. /*DirectInit*/ false);
  5174. // Upper bound variable, initialized with last iteration number.
  5175. VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
  5176. UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
  5177. SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
  5178. /*DirectInit*/ false);
  5179. // A 32-bit variable-flag where runtime returns 1 for the last iteration.
  5180. // This will be used to implement clause 'lastprivate'.
  5181. QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
  5182. VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
  5183. IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
  5184. SemaRef.AddInitializerToDecl(ILDecl,
  5185. SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
  5186. /*DirectInit*/ false);
  5187. // Stride variable returned by runtime (we initialize it to 1 by default).
  5188. VarDecl *STDecl =
  5189. buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
  5190. ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
  5191. SemaRef.AddInitializerToDecl(STDecl,
  5192. SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
  5193. /*DirectInit*/ false);
  5194. // Build expression: UB = min(UB, LastIteration)
  5195. // It is necessary for CodeGen of directives with static scheduling.
  5196. ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
  5197. UB.get(), LastIteration.get());
  5198. ExprResult CondOp = SemaRef.ActOnConditionalOp(
  5199. LastIteration.get()->getExprLoc(), InitLoc, IsUBGreater.get(),
  5200. LastIteration.get(), UB.get());
  5201. EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
  5202. CondOp.get());
  5203. EUB = SemaRef.ActOnFinishFullExpr(EUB.get(), /*DiscardedValue*/ false);
  5204. // If we have a combined directive that combines 'distribute', 'for' or
  5205. // 'simd' we need to be able to access the bounds of the schedule of the
  5206. // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
  5207. // by scheduling 'distribute' have to be passed to the schedule of 'for'.
  5208. if (isOpenMPLoopBoundSharingDirective(DKind)) {
  5209. // Lower bound variable, initialized with zero.
  5210. VarDecl *CombLBDecl =
  5211. buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb");
  5212. CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc);
  5213. SemaRef.AddInitializerToDecl(
  5214. CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
  5215. /*DirectInit*/ false);
  5216. // Upper bound variable, initialized with last iteration number.
  5217. VarDecl *CombUBDecl =
  5218. buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub");
  5219. CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc);
  5220. SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(),
  5221. /*DirectInit*/ false);
  5222. ExprResult CombIsUBGreater = SemaRef.BuildBinOp(
  5223. CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get());
  5224. ExprResult CombCondOp =
  5225. SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(),
  5226. LastIteration.get(), CombUB.get());
  5227. CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(),
  5228. CombCondOp.get());
  5229. CombEUB =
  5230. SemaRef.ActOnFinishFullExpr(CombEUB.get(), /*DiscardedValue*/ false);
  5231. const CapturedDecl *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
  5232. // We expect to have at least 2 more parameters than the 'parallel'
  5233. // directive does - the lower and upper bounds of the previous schedule.
  5234. assert(CD->getNumParams() >= 4 &&
  5235. "Unexpected number of parameters in loop combined directive");
  5236. // Set the proper type for the bounds given what we learned from the
  5237. // enclosed loops.
  5238. ImplicitParamDecl *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
  5239. ImplicitParamDecl *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
  5240. // Previous lower and upper bounds are obtained from the region
  5241. // parameters.
  5242. PrevLB =
  5243. buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
  5244. PrevUB =
  5245. buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
  5246. }
  5247. }
  5248. // Build the iteration variable and its initialization before loop.
  5249. ExprResult IV;
  5250. ExprResult Init, CombInit;
  5251. {
  5252. VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
  5253. IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
  5254. Expr *RHS =
  5255. (isOpenMPWorksharingDirective(DKind) ||
  5256. isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
  5257. ? LB.get()
  5258. : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
  5259. Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
  5260. Init = SemaRef.ActOnFinishFullExpr(Init.get(), /*DiscardedValue*/ false);
  5261. if (isOpenMPLoopBoundSharingDirective(DKind)) {
  5262. Expr *CombRHS =
  5263. (isOpenMPWorksharingDirective(DKind) ||
  5264. isOpenMPTaskLoopDirective(DKind) ||
  5265. isOpenMPDistributeDirective(DKind))
  5266. ? CombLB.get()
  5267. : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
  5268. CombInit =
  5269. SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS);
  5270. CombInit =
  5271. SemaRef.ActOnFinishFullExpr(CombInit.get(), /*DiscardedValue*/ false);
  5272. }
  5273. }
  5274. bool UseStrictCompare =
  5275. RealVType->hasUnsignedIntegerRepresentation() &&
  5276. llvm::all_of(IterSpaces, [](const LoopIterationSpace &LIS) {
  5277. return LIS.IsStrictCompare;
  5278. });
  5279. // Loop condition (IV < NumIterations) or (IV <= UB or IV < UB + 1 (for
  5280. // unsigned IV)) for worksharing loops.
  5281. SourceLocation CondLoc = AStmt->getBeginLoc();
  5282. Expr *BoundUB = UB.get();
  5283. if (UseStrictCompare) {
  5284. BoundUB =
  5285. SemaRef
  5286. .BuildBinOp(CurScope, CondLoc, BO_Add, BoundUB,
  5287. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
  5288. .get();
  5289. BoundUB =
  5290. SemaRef.ActOnFinishFullExpr(BoundUB, /*DiscardedValue*/ false).get();
  5291. }
  5292. ExprResult Cond =
  5293. (isOpenMPWorksharingDirective(DKind) ||
  5294. isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
  5295. ? SemaRef.BuildBinOp(CurScope, CondLoc,
  5296. UseStrictCompare ? BO_LT : BO_LE, IV.get(),
  5297. BoundUB)
  5298. : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
  5299. NumIterations.get());
  5300. ExprResult CombDistCond;
  5301. if (isOpenMPLoopBoundSharingDirective(DKind)) {
  5302. CombDistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
  5303. NumIterations.get());
  5304. }
  5305. ExprResult CombCond;
  5306. if (isOpenMPLoopBoundSharingDirective(DKind)) {
  5307. Expr *BoundCombUB = CombUB.get();
  5308. if (UseStrictCompare) {
  5309. BoundCombUB =
  5310. SemaRef
  5311. .BuildBinOp(
  5312. CurScope, CondLoc, BO_Add, BoundCombUB,
  5313. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
  5314. .get();
  5315. BoundCombUB =
  5316. SemaRef.ActOnFinishFullExpr(BoundCombUB, /*DiscardedValue*/ false)
  5317. .get();
  5318. }
  5319. CombCond =
  5320. SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
  5321. IV.get(), BoundCombUB);
  5322. }
  5323. // Loop increment (IV = IV + 1)
  5324. SourceLocation IncLoc = AStmt->getBeginLoc();
  5325. ExprResult Inc =
  5326. SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
  5327. SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
  5328. if (!Inc.isUsable())
  5329. return 0;
  5330. Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
  5331. Inc = SemaRef.ActOnFinishFullExpr(Inc.get(), /*DiscardedValue*/ false);
  5332. if (!Inc.isUsable())
  5333. return 0;
  5334. // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
  5335. // Used for directives with static scheduling.
  5336. // In combined construct, add combined version that use CombLB and CombUB
  5337. // base variables for the update
  5338. ExprResult NextLB, NextUB, CombNextLB, CombNextUB;
  5339. if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
  5340. isOpenMPDistributeDirective(DKind)) {
  5341. // LB + ST
  5342. NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
  5343. if (!NextLB.isUsable())
  5344. return 0;
  5345. // LB = LB + ST
  5346. NextLB =
  5347. SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
  5348. NextLB =
  5349. SemaRef.ActOnFinishFullExpr(NextLB.get(), /*DiscardedValue*/ false);
  5350. if (!NextLB.isUsable())
  5351. return 0;
  5352. // UB + ST
  5353. NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
  5354. if (!NextUB.isUsable())
  5355. return 0;
  5356. // UB = UB + ST
  5357. NextUB =
  5358. SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
  5359. NextUB =
  5360. SemaRef.ActOnFinishFullExpr(NextUB.get(), /*DiscardedValue*/ false);
  5361. if (!NextUB.isUsable())
  5362. return 0;
  5363. if (isOpenMPLoopBoundSharingDirective(DKind)) {
  5364. CombNextLB =
  5365. SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get());
  5366. if (!NextLB.isUsable())
  5367. return 0;
  5368. // LB = LB + ST
  5369. CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(),
  5370. CombNextLB.get());
  5371. CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get(),
  5372. /*DiscardedValue*/ false);
  5373. if (!CombNextLB.isUsable())
  5374. return 0;
  5375. // UB + ST
  5376. CombNextUB =
  5377. SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get());
  5378. if (!CombNextUB.isUsable())
  5379. return 0;
  5380. // UB = UB + ST
  5381. CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(),
  5382. CombNextUB.get());
  5383. CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get(),
  5384. /*DiscardedValue*/ false);
  5385. if (!CombNextUB.isUsable())
  5386. return 0;
  5387. }
  5388. }
  5389. // Create increment expression for distribute loop when combined in a same
  5390. // directive with for as IV = IV + ST; ensure upper bound expression based
  5391. // on PrevUB instead of NumIterations - used to implement 'for' when found
  5392. // in combination with 'distribute', like in 'distribute parallel for'
  5393. SourceLocation DistIncLoc = AStmt->getBeginLoc();
  5394. ExprResult DistCond, DistInc, PrevEUB, ParForInDistCond;
  5395. if (isOpenMPLoopBoundSharingDirective(DKind)) {
  5396. DistCond = SemaRef.BuildBinOp(
  5397. CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE, IV.get(), BoundUB);
  5398. assert(DistCond.isUsable() && "distribute cond expr was not built");
  5399. DistInc =
  5400. SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get());
  5401. assert(DistInc.isUsable() && "distribute inc expr was not built");
  5402. DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(),
  5403. DistInc.get());
  5404. DistInc =
  5405. SemaRef.ActOnFinishFullExpr(DistInc.get(), /*DiscardedValue*/ false);
  5406. assert(DistInc.isUsable() && "distribute inc expr was not built");
  5407. // Build expression: UB = min(UB, prevUB) for #for in composite or combined
  5408. // construct
  5409. SourceLocation DistEUBLoc = AStmt->getBeginLoc();
  5410. ExprResult IsUBGreater =
  5411. SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, UB.get(), PrevUB.get());
  5412. ExprResult CondOp = SemaRef.ActOnConditionalOp(
  5413. DistEUBLoc, DistEUBLoc, IsUBGreater.get(), PrevUB.get(), UB.get());
  5414. PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(),
  5415. CondOp.get());
  5416. PrevEUB =
  5417. SemaRef.ActOnFinishFullExpr(PrevEUB.get(), /*DiscardedValue*/ false);
  5418. // Build IV <= PrevUB or IV < PrevUB + 1 for unsigned IV to be used in
  5419. // parallel for is in combination with a distribute directive with
  5420. // schedule(static, 1)
  5421. Expr *BoundPrevUB = PrevUB.get();
  5422. if (UseStrictCompare) {
  5423. BoundPrevUB =
  5424. SemaRef
  5425. .BuildBinOp(
  5426. CurScope, CondLoc, BO_Add, BoundPrevUB,
  5427. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
  5428. .get();
  5429. BoundPrevUB =
  5430. SemaRef.ActOnFinishFullExpr(BoundPrevUB, /*DiscardedValue*/ false)
  5431. .get();
  5432. }
  5433. ParForInDistCond =
  5434. SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
  5435. IV.get(), BoundPrevUB);
  5436. }
  5437. // Build updates and final values of the loop counters.
  5438. bool HasErrors = false;
  5439. Built.Counters.resize(NestedLoopCount);
  5440. Built.Inits.resize(NestedLoopCount);
  5441. Built.Updates.resize(NestedLoopCount);
  5442. Built.Finals.resize(NestedLoopCount);
  5443. {
  5444. // We implement the following algorithm for obtaining the
  5445. // original loop iteration variable values based on the
  5446. // value of the collapsed loop iteration variable IV.
  5447. //
  5448. // Let n+1 be the number of collapsed loops in the nest.
  5449. // Iteration variables (I0, I1, .... In)
  5450. // Iteration counts (N0, N1, ... Nn)
  5451. //
  5452. // Acc = IV;
  5453. //
  5454. // To compute Ik for loop k, 0 <= k <= n, generate:
  5455. // Prod = N(k+1) * N(k+2) * ... * Nn;
  5456. // Ik = Acc / Prod;
  5457. // Acc -= Ik * Prod;
  5458. //
  5459. ExprResult Acc = IV;
  5460. for (unsigned int Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
  5461. LoopIterationSpace &IS = IterSpaces[Cnt];
  5462. SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
  5463. ExprResult Iter;
  5464. // Compute prod
  5465. ExprResult Prod =
  5466. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
  5467. for (unsigned int K = Cnt+1; K < NestedLoopCount; ++K)
  5468. Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Prod.get(),
  5469. IterSpaces[K].NumIterations);
  5470. // Iter = Acc / Prod
  5471. // If there is at least one more inner loop to avoid
  5472. // multiplication by 1.
  5473. if (Cnt + 1 < NestedLoopCount)
  5474. Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div,
  5475. Acc.get(), Prod.get());
  5476. else
  5477. Iter = Acc;
  5478. if (!Iter.isUsable()) {
  5479. HasErrors = true;
  5480. break;
  5481. }
  5482. // Update Acc:
  5483. // Acc -= Iter * Prod
  5484. // Check if there is at least one more inner loop to avoid
  5485. // multiplication by 1.
  5486. if (Cnt + 1 < NestedLoopCount)
  5487. Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul,
  5488. Iter.get(), Prod.get());
  5489. else
  5490. Prod = Iter;
  5491. Acc = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Sub,
  5492. Acc.get(), Prod.get());
  5493. // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
  5494. auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
  5495. DeclRefExpr *CounterVar = buildDeclRefExpr(
  5496. SemaRef, VD, IS.CounterVar->getType(), IS.CounterVar->getExprLoc(),
  5497. /*RefersToCapture=*/true);
  5498. ExprResult Init = buildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
  5499. IS.CounterInit, Captures);
  5500. if (!Init.isUsable()) {
  5501. HasErrors = true;
  5502. break;
  5503. }
  5504. ExprResult Update = buildCounterUpdate(
  5505. SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
  5506. IS.CounterStep, IS.Subtract, &Captures);
  5507. if (!Update.isUsable()) {
  5508. HasErrors = true;
  5509. break;
  5510. }
  5511. // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
  5512. ExprResult Final = buildCounterUpdate(
  5513. SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit,
  5514. IS.NumIterations, IS.CounterStep, IS.Subtract, &Captures);
  5515. if (!Final.isUsable()) {
  5516. HasErrors = true;
  5517. break;
  5518. }
  5519. if (!Update.isUsable() || !Final.isUsable()) {
  5520. HasErrors = true;
  5521. break;
  5522. }
  5523. // Save results
  5524. Built.Counters[Cnt] = IS.CounterVar;
  5525. Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
  5526. Built.Inits[Cnt] = Init.get();
  5527. Built.Updates[Cnt] = Update.get();
  5528. Built.Finals[Cnt] = Final.get();
  5529. }
  5530. }
  5531. if (HasErrors)
  5532. return 0;
  5533. // Save results
  5534. Built.IterationVarRef = IV.get();
  5535. Built.LastIteration = LastIteration.get();
  5536. Built.NumIterations = NumIterations.get();
  5537. Built.CalcLastIteration = SemaRef
  5538. .ActOnFinishFullExpr(CalcLastIteration.get(),
  5539. /*DiscardedValue*/ false)
  5540. .get();
  5541. Built.PreCond = PreCond.get();
  5542. Built.PreInits = buildPreInits(C, Captures);
  5543. Built.Cond = Cond.get();
  5544. Built.Init = Init.get();
  5545. Built.Inc = Inc.get();
  5546. Built.LB = LB.get();
  5547. Built.UB = UB.get();
  5548. Built.IL = IL.get();
  5549. Built.ST = ST.get();
  5550. Built.EUB = EUB.get();
  5551. Built.NLB = NextLB.get();
  5552. Built.NUB = NextUB.get();
  5553. Built.PrevLB = PrevLB.get();
  5554. Built.PrevUB = PrevUB.get();
  5555. Built.DistInc = DistInc.get();
  5556. Built.PrevEUB = PrevEUB.get();
  5557. Built.DistCombinedFields.LB = CombLB.get();
  5558. Built.DistCombinedFields.UB = CombUB.get();
  5559. Built.DistCombinedFields.EUB = CombEUB.get();
  5560. Built.DistCombinedFields.Init = CombInit.get();
  5561. Built.DistCombinedFields.Cond = CombCond.get();
  5562. Built.DistCombinedFields.NLB = CombNextLB.get();
  5563. Built.DistCombinedFields.NUB = CombNextUB.get();
  5564. Built.DistCombinedFields.DistCond = CombDistCond.get();
  5565. Built.DistCombinedFields.ParForInDistCond = ParForInDistCond.get();
  5566. return NestedLoopCount;
  5567. }
  5568. static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
  5569. auto CollapseClauses =
  5570. OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
  5571. if (CollapseClauses.begin() != CollapseClauses.end())
  5572. return (*CollapseClauses.begin())->getNumForLoops();
  5573. return nullptr;
  5574. }
  5575. static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
  5576. auto OrderedClauses =
  5577. OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
  5578. if (OrderedClauses.begin() != OrderedClauses.end())
  5579. return (*OrderedClauses.begin())->getNumForLoops();
  5580. return nullptr;
  5581. }
  5582. static bool checkSimdlenSafelenSpecified(Sema &S,
  5583. const ArrayRef<OMPClause *> Clauses) {
  5584. const OMPSafelenClause *Safelen = nullptr;
  5585. const OMPSimdlenClause *Simdlen = nullptr;
  5586. for (const OMPClause *Clause : Clauses) {
  5587. if (Clause->getClauseKind() == OMPC_safelen)
  5588. Safelen = cast<OMPSafelenClause>(Clause);
  5589. else if (Clause->getClauseKind() == OMPC_simdlen)
  5590. Simdlen = cast<OMPSimdlenClause>(Clause);
  5591. if (Safelen && Simdlen)
  5592. break;
  5593. }
  5594. if (Simdlen && Safelen) {
  5595. const Expr *SimdlenLength = Simdlen->getSimdlen();
  5596. const Expr *SafelenLength = Safelen->getSafelen();
  5597. if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
  5598. SimdlenLength->isInstantiationDependent() ||
  5599. SimdlenLength->containsUnexpandedParameterPack())
  5600. return false;
  5601. if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
  5602. SafelenLength->isInstantiationDependent() ||
  5603. SafelenLength->containsUnexpandedParameterPack())
  5604. return false;
  5605. Expr::EvalResult SimdlenResult, SafelenResult;
  5606. SimdlenLength->EvaluateAsInt(SimdlenResult, S.Context);
  5607. SafelenLength->EvaluateAsInt(SafelenResult, S.Context);
  5608. llvm::APSInt SimdlenRes = SimdlenResult.Val.getInt();
  5609. llvm::APSInt SafelenRes = SafelenResult.Val.getInt();
  5610. // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
  5611. // If both simdlen and safelen clauses are specified, the value of the
  5612. // simdlen parameter must be less than or equal to the value of the safelen
  5613. // parameter.
  5614. if (SimdlenRes > SafelenRes) {
  5615. S.Diag(SimdlenLength->getExprLoc(),
  5616. diag::err_omp_wrong_simdlen_safelen_values)
  5617. << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
  5618. return true;
  5619. }
  5620. }
  5621. return false;
  5622. }
  5623. StmtResult
  5624. Sema::ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
  5625. SourceLocation StartLoc, SourceLocation EndLoc,
  5626. VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  5627. if (!AStmt)
  5628. return StmtError();
  5629. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  5630. OMPLoopDirective::HelperExprs B;
  5631. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  5632. // define the nested loops number.
  5633. unsigned NestedLoopCount = checkOpenMPLoop(
  5634. OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
  5635. AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
  5636. if (NestedLoopCount == 0)
  5637. return StmtError();
  5638. assert((CurContext->isDependentContext() || B.builtAll()) &&
  5639. "omp simd loop exprs were not built");
  5640. if (!CurContext->isDependentContext()) {
  5641. // Finalize the clauses that need pre-built expressions for CodeGen.
  5642. for (OMPClause *C : Clauses) {
  5643. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  5644. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  5645. B.NumIterations, *this, CurScope,
  5646. DSAStack))
  5647. return StmtError();
  5648. }
  5649. }
  5650. if (checkSimdlenSafelenSpecified(*this, Clauses))
  5651. return StmtError();
  5652. setFunctionHasBranchProtectedScope();
  5653. return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
  5654. Clauses, AStmt, B);
  5655. }
  5656. StmtResult
  5657. Sema::ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
  5658. SourceLocation StartLoc, SourceLocation EndLoc,
  5659. VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  5660. if (!AStmt)
  5661. return StmtError();
  5662. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  5663. OMPLoopDirective::HelperExprs B;
  5664. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  5665. // define the nested loops number.
  5666. unsigned NestedLoopCount = checkOpenMPLoop(
  5667. OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
  5668. AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
  5669. if (NestedLoopCount == 0)
  5670. return StmtError();
  5671. assert((CurContext->isDependentContext() || B.builtAll()) &&
  5672. "omp for loop exprs were not built");
  5673. if (!CurContext->isDependentContext()) {
  5674. // Finalize the clauses that need pre-built expressions for CodeGen.
  5675. for (OMPClause *C : Clauses) {
  5676. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  5677. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  5678. B.NumIterations, *this, CurScope,
  5679. DSAStack))
  5680. return StmtError();
  5681. }
  5682. }
  5683. setFunctionHasBranchProtectedScope();
  5684. return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
  5685. Clauses, AStmt, B, DSAStack->isCancelRegion());
  5686. }
  5687. StmtResult Sema::ActOnOpenMPForSimdDirective(
  5688. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  5689. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  5690. if (!AStmt)
  5691. return StmtError();
  5692. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  5693. OMPLoopDirective::HelperExprs B;
  5694. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  5695. // define the nested loops number.
  5696. unsigned NestedLoopCount =
  5697. checkOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
  5698. getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
  5699. VarsWithImplicitDSA, B);
  5700. if (NestedLoopCount == 0)
  5701. return StmtError();
  5702. assert((CurContext->isDependentContext() || B.builtAll()) &&
  5703. "omp for simd loop exprs were not built");
  5704. if (!CurContext->isDependentContext()) {
  5705. // Finalize the clauses that need pre-built expressions for CodeGen.
  5706. for (OMPClause *C : Clauses) {
  5707. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  5708. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  5709. B.NumIterations, *this, CurScope,
  5710. DSAStack))
  5711. return StmtError();
  5712. }
  5713. }
  5714. if (checkSimdlenSafelenSpecified(*this, Clauses))
  5715. return StmtError();
  5716. setFunctionHasBranchProtectedScope();
  5717. return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
  5718. Clauses, AStmt, B);
  5719. }
  5720. StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
  5721. Stmt *AStmt,
  5722. SourceLocation StartLoc,
  5723. SourceLocation EndLoc) {
  5724. if (!AStmt)
  5725. return StmtError();
  5726. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  5727. auto BaseStmt = AStmt;
  5728. while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
  5729. BaseStmt = CS->getCapturedStmt();
  5730. if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
  5731. auto S = C->children();
  5732. if (S.begin() == S.end())
  5733. return StmtError();
  5734. // All associated statements must be '#pragma omp section' except for
  5735. // the first one.
  5736. for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
  5737. if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
  5738. if (SectionStmt)
  5739. Diag(SectionStmt->getBeginLoc(),
  5740. diag::err_omp_sections_substmt_not_section);
  5741. return StmtError();
  5742. }
  5743. cast<OMPSectionDirective>(SectionStmt)
  5744. ->setHasCancel(DSAStack->isCancelRegion());
  5745. }
  5746. } else {
  5747. Diag(AStmt->getBeginLoc(), diag::err_omp_sections_not_compound_stmt);
  5748. return StmtError();
  5749. }
  5750. setFunctionHasBranchProtectedScope();
  5751. return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
  5752. DSAStack->isCancelRegion());
  5753. }
  5754. StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
  5755. SourceLocation StartLoc,
  5756. SourceLocation EndLoc) {
  5757. if (!AStmt)
  5758. return StmtError();
  5759. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  5760. setFunctionHasBranchProtectedScope();
  5761. DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
  5762. return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
  5763. DSAStack->isCancelRegion());
  5764. }
  5765. StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
  5766. Stmt *AStmt,
  5767. SourceLocation StartLoc,
  5768. SourceLocation EndLoc) {
  5769. if (!AStmt)
  5770. return StmtError();
  5771. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  5772. setFunctionHasBranchProtectedScope();
  5773. // OpenMP [2.7.3, single Construct, Restrictions]
  5774. // The copyprivate clause must not be used with the nowait clause.
  5775. const OMPClause *Nowait = nullptr;
  5776. const OMPClause *Copyprivate = nullptr;
  5777. for (const OMPClause *Clause : Clauses) {
  5778. if (Clause->getClauseKind() == OMPC_nowait)
  5779. Nowait = Clause;
  5780. else if (Clause->getClauseKind() == OMPC_copyprivate)
  5781. Copyprivate = Clause;
  5782. if (Copyprivate && Nowait) {
  5783. Diag(Copyprivate->getBeginLoc(),
  5784. diag::err_omp_single_copyprivate_with_nowait);
  5785. Diag(Nowait->getBeginLoc(), diag::note_omp_nowait_clause_here);
  5786. return StmtError();
  5787. }
  5788. }
  5789. return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
  5790. }
  5791. StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
  5792. SourceLocation StartLoc,
  5793. SourceLocation EndLoc) {
  5794. if (!AStmt)
  5795. return StmtError();
  5796. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  5797. setFunctionHasBranchProtectedScope();
  5798. return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
  5799. }
  5800. StmtResult Sema::ActOnOpenMPCriticalDirective(
  5801. const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
  5802. Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
  5803. if (!AStmt)
  5804. return StmtError();
  5805. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  5806. bool ErrorFound = false;
  5807. llvm::APSInt Hint;
  5808. SourceLocation HintLoc;
  5809. bool DependentHint = false;
  5810. for (const OMPClause *C : Clauses) {
  5811. if (C->getClauseKind() == OMPC_hint) {
  5812. if (!DirName.getName()) {
  5813. Diag(C->getBeginLoc(), diag::err_omp_hint_clause_no_name);
  5814. ErrorFound = true;
  5815. }
  5816. Expr *E = cast<OMPHintClause>(C)->getHint();
  5817. if (E->isTypeDependent() || E->isValueDependent() ||
  5818. E->isInstantiationDependent()) {
  5819. DependentHint = true;
  5820. } else {
  5821. Hint = E->EvaluateKnownConstInt(Context);
  5822. HintLoc = C->getBeginLoc();
  5823. }
  5824. }
  5825. }
  5826. if (ErrorFound)
  5827. return StmtError();
  5828. const auto Pair = DSAStack->getCriticalWithHint(DirName);
  5829. if (Pair.first && DirName.getName() && !DependentHint) {
  5830. if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
  5831. Diag(StartLoc, diag::err_omp_critical_with_hint);
  5832. if (HintLoc.isValid())
  5833. Diag(HintLoc, diag::note_omp_critical_hint_here)
  5834. << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
  5835. else
  5836. Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
  5837. if (const auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
  5838. Diag(C->getBeginLoc(), diag::note_omp_critical_hint_here)
  5839. << 1
  5840. << C->getHint()->EvaluateKnownConstInt(Context).toString(
  5841. /*Radix=*/10, /*Signed=*/false);
  5842. } else {
  5843. Diag(Pair.first->getBeginLoc(), diag::note_omp_critical_no_hint) << 1;
  5844. }
  5845. }
  5846. }
  5847. setFunctionHasBranchProtectedScope();
  5848. auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
  5849. Clauses, AStmt);
  5850. if (!Pair.first && DirName.getName() && !DependentHint)
  5851. DSAStack->addCriticalWithHint(Dir, Hint);
  5852. return Dir;
  5853. }
  5854. StmtResult Sema::ActOnOpenMPParallelForDirective(
  5855. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  5856. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  5857. if (!AStmt)
  5858. return StmtError();
  5859. auto *CS = cast<CapturedStmt>(AStmt);
  5860. // 1.2.2 OpenMP Language Terminology
  5861. // Structured block - An executable statement with a single entry at the
  5862. // top and a single exit at the bottom.
  5863. // The point of exit cannot be a branch out of the structured block.
  5864. // longjmp() and throw() must not violate the entry/exit criteria.
  5865. CS->getCapturedDecl()->setNothrow();
  5866. OMPLoopDirective::HelperExprs B;
  5867. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  5868. // define the nested loops number.
  5869. unsigned NestedLoopCount =
  5870. checkOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
  5871. getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
  5872. VarsWithImplicitDSA, B);
  5873. if (NestedLoopCount == 0)
  5874. return StmtError();
  5875. assert((CurContext->isDependentContext() || B.builtAll()) &&
  5876. "omp parallel for loop exprs were not built");
  5877. if (!CurContext->isDependentContext()) {
  5878. // Finalize the clauses that need pre-built expressions for CodeGen.
  5879. for (OMPClause *C : Clauses) {
  5880. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  5881. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  5882. B.NumIterations, *this, CurScope,
  5883. DSAStack))
  5884. return StmtError();
  5885. }
  5886. }
  5887. setFunctionHasBranchProtectedScope();
  5888. return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
  5889. NestedLoopCount, Clauses, AStmt, B,
  5890. DSAStack->isCancelRegion());
  5891. }
  5892. StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
  5893. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  5894. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  5895. if (!AStmt)
  5896. return StmtError();
  5897. auto *CS = cast<CapturedStmt>(AStmt);
  5898. // 1.2.2 OpenMP Language Terminology
  5899. // Structured block - An executable statement with a single entry at the
  5900. // top and a single exit at the bottom.
  5901. // The point of exit cannot be a branch out of the structured block.
  5902. // longjmp() and throw() must not violate the entry/exit criteria.
  5903. CS->getCapturedDecl()->setNothrow();
  5904. OMPLoopDirective::HelperExprs B;
  5905. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  5906. // define the nested loops number.
  5907. unsigned NestedLoopCount =
  5908. checkOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
  5909. getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
  5910. VarsWithImplicitDSA, B);
  5911. if (NestedLoopCount == 0)
  5912. return StmtError();
  5913. if (!CurContext->isDependentContext()) {
  5914. // Finalize the clauses that need pre-built expressions for CodeGen.
  5915. for (OMPClause *C : Clauses) {
  5916. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  5917. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  5918. B.NumIterations, *this, CurScope,
  5919. DSAStack))
  5920. return StmtError();
  5921. }
  5922. }
  5923. if (checkSimdlenSafelenSpecified(*this, Clauses))
  5924. return StmtError();
  5925. setFunctionHasBranchProtectedScope();
  5926. return OMPParallelForSimdDirective::Create(
  5927. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  5928. }
  5929. StmtResult
  5930. Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
  5931. Stmt *AStmt, SourceLocation StartLoc,
  5932. SourceLocation EndLoc) {
  5933. if (!AStmt)
  5934. return StmtError();
  5935. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  5936. auto BaseStmt = AStmt;
  5937. while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
  5938. BaseStmt = CS->getCapturedStmt();
  5939. if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
  5940. auto S = C->children();
  5941. if (S.begin() == S.end())
  5942. return StmtError();
  5943. // All associated statements must be '#pragma omp section' except for
  5944. // the first one.
  5945. for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
  5946. if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
  5947. if (SectionStmt)
  5948. Diag(SectionStmt->getBeginLoc(),
  5949. diag::err_omp_parallel_sections_substmt_not_section);
  5950. return StmtError();
  5951. }
  5952. cast<OMPSectionDirective>(SectionStmt)
  5953. ->setHasCancel(DSAStack->isCancelRegion());
  5954. }
  5955. } else {
  5956. Diag(AStmt->getBeginLoc(),
  5957. diag::err_omp_parallel_sections_not_compound_stmt);
  5958. return StmtError();
  5959. }
  5960. setFunctionHasBranchProtectedScope();
  5961. return OMPParallelSectionsDirective::Create(
  5962. Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
  5963. }
  5964. StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
  5965. Stmt *AStmt, SourceLocation StartLoc,
  5966. SourceLocation EndLoc) {
  5967. if (!AStmt)
  5968. return StmtError();
  5969. auto *CS = cast<CapturedStmt>(AStmt);
  5970. // 1.2.2 OpenMP Language Terminology
  5971. // Structured block - An executable statement with a single entry at the
  5972. // top and a single exit at the bottom.
  5973. // The point of exit cannot be a branch out of the structured block.
  5974. // longjmp() and throw() must not violate the entry/exit criteria.
  5975. CS->getCapturedDecl()->setNothrow();
  5976. setFunctionHasBranchProtectedScope();
  5977. return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
  5978. DSAStack->isCancelRegion());
  5979. }
  5980. StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
  5981. SourceLocation EndLoc) {
  5982. return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
  5983. }
  5984. StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
  5985. SourceLocation EndLoc) {
  5986. return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
  5987. }
  5988. StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
  5989. SourceLocation EndLoc) {
  5990. return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
  5991. }
  5992. StmtResult Sema::ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
  5993. Stmt *AStmt,
  5994. SourceLocation StartLoc,
  5995. SourceLocation EndLoc) {
  5996. if (!AStmt)
  5997. return StmtError();
  5998. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  5999. setFunctionHasBranchProtectedScope();
  6000. return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, Clauses,
  6001. AStmt,
  6002. DSAStack->getTaskgroupReductionRef());
  6003. }
  6004. StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
  6005. SourceLocation StartLoc,
  6006. SourceLocation EndLoc) {
  6007. assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
  6008. return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
  6009. }
  6010. StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
  6011. Stmt *AStmt,
  6012. SourceLocation StartLoc,
  6013. SourceLocation EndLoc) {
  6014. const OMPClause *DependFound = nullptr;
  6015. const OMPClause *DependSourceClause = nullptr;
  6016. const OMPClause *DependSinkClause = nullptr;
  6017. bool ErrorFound = false;
  6018. const OMPThreadsClause *TC = nullptr;
  6019. const OMPSIMDClause *SC = nullptr;
  6020. for (const OMPClause *C : Clauses) {
  6021. if (auto *DC = dyn_cast<OMPDependClause>(C)) {
  6022. DependFound = C;
  6023. if (DC->getDependencyKind() == OMPC_DEPEND_source) {
  6024. if (DependSourceClause) {
  6025. Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
  6026. << getOpenMPDirectiveName(OMPD_ordered)
  6027. << getOpenMPClauseName(OMPC_depend) << 2;
  6028. ErrorFound = true;
  6029. } else {
  6030. DependSourceClause = C;
  6031. }
  6032. if (DependSinkClause) {
  6033. Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
  6034. << 0;
  6035. ErrorFound = true;
  6036. }
  6037. } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
  6038. if (DependSourceClause) {
  6039. Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
  6040. << 1;
  6041. ErrorFound = true;
  6042. }
  6043. DependSinkClause = C;
  6044. }
  6045. } else if (C->getClauseKind() == OMPC_threads) {
  6046. TC = cast<OMPThreadsClause>(C);
  6047. } else if (C->getClauseKind() == OMPC_simd) {
  6048. SC = cast<OMPSIMDClause>(C);
  6049. }
  6050. }
  6051. if (!ErrorFound && !SC &&
  6052. isOpenMPSimdDirective(DSAStack->getParentDirective())) {
  6053. // OpenMP [2.8.1,simd Construct, Restrictions]
  6054. // An ordered construct with the simd clause is the only OpenMP construct
  6055. // that can appear in the simd region.
  6056. Diag(StartLoc, diag::err_omp_prohibited_region_simd);
  6057. ErrorFound = true;
  6058. } else if (DependFound && (TC || SC)) {
  6059. Diag(DependFound->getBeginLoc(), diag::err_omp_depend_clause_thread_simd)
  6060. << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
  6061. ErrorFound = true;
  6062. } else if (DependFound && !DSAStack->getParentOrderedRegionParam().first) {
  6063. Diag(DependFound->getBeginLoc(),
  6064. diag::err_omp_ordered_directive_without_param);
  6065. ErrorFound = true;
  6066. } else if (TC || Clauses.empty()) {
  6067. if (const Expr *Param = DSAStack->getParentOrderedRegionParam().first) {
  6068. SourceLocation ErrLoc = TC ? TC->getBeginLoc() : StartLoc;
  6069. Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
  6070. << (TC != nullptr);
  6071. Diag(Param->getBeginLoc(), diag::note_omp_ordered_param);
  6072. ErrorFound = true;
  6073. }
  6074. }
  6075. if ((!AStmt && !DependFound) || ErrorFound)
  6076. return StmtError();
  6077. if (AStmt) {
  6078. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  6079. setFunctionHasBranchProtectedScope();
  6080. }
  6081. return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
  6082. }
  6083. namespace {
  6084. /// Helper class for checking expression in 'omp atomic [update]'
  6085. /// construct.
  6086. class OpenMPAtomicUpdateChecker {
  6087. /// Error results for atomic update expressions.
  6088. enum ExprAnalysisErrorCode {
  6089. /// A statement is not an expression statement.
  6090. NotAnExpression,
  6091. /// Expression is not builtin binary or unary operation.
  6092. NotABinaryOrUnaryExpression,
  6093. /// Unary operation is not post-/pre- increment/decrement operation.
  6094. NotAnUnaryIncDecExpression,
  6095. /// An expression is not of scalar type.
  6096. NotAScalarType,
  6097. /// A binary operation is not an assignment operation.
  6098. NotAnAssignmentOp,
  6099. /// RHS part of the binary operation is not a binary expression.
  6100. NotABinaryExpression,
  6101. /// RHS part is not additive/multiplicative/shift/biwise binary
  6102. /// expression.
  6103. NotABinaryOperator,
  6104. /// RHS binary operation does not have reference to the updated LHS
  6105. /// part.
  6106. NotAnUpdateExpression,
  6107. /// No errors is found.
  6108. NoError
  6109. };
  6110. /// Reference to Sema.
  6111. Sema &SemaRef;
  6112. /// A location for note diagnostics (when error is found).
  6113. SourceLocation NoteLoc;
  6114. /// 'x' lvalue part of the source atomic expression.
  6115. Expr *X;
  6116. /// 'expr' rvalue part of the source atomic expression.
  6117. Expr *E;
  6118. /// Helper expression of the form
  6119. /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
  6120. /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
  6121. Expr *UpdateExpr;
  6122. /// Is 'x' a LHS in a RHS part of full update expression. It is
  6123. /// important for non-associative operations.
  6124. bool IsXLHSInRHSPart;
  6125. BinaryOperatorKind Op;
  6126. SourceLocation OpLoc;
  6127. /// true if the source expression is a postfix unary operation, false
  6128. /// if it is a prefix unary operation.
  6129. bool IsPostfixUpdate;
  6130. public:
  6131. OpenMPAtomicUpdateChecker(Sema &SemaRef)
  6132. : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
  6133. IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
  6134. /// Check specified statement that it is suitable for 'atomic update'
  6135. /// constructs and extract 'x', 'expr' and Operation from the original
  6136. /// expression. If DiagId and NoteId == 0, then only check is performed
  6137. /// without error notification.
  6138. /// \param DiagId Diagnostic which should be emitted if error is found.
  6139. /// \param NoteId Diagnostic note for the main error message.
  6140. /// \return true if statement is not an update expression, false otherwise.
  6141. bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
  6142. /// Return the 'x' lvalue part of the source atomic expression.
  6143. Expr *getX() const { return X; }
  6144. /// Return the 'expr' rvalue part of the source atomic expression.
  6145. Expr *getExpr() const { return E; }
  6146. /// Return the update expression used in calculation of the updated
  6147. /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
  6148. /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
  6149. Expr *getUpdateExpr() const { return UpdateExpr; }
  6150. /// Return true if 'x' is LHS in RHS part of full update expression,
  6151. /// false otherwise.
  6152. bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
  6153. /// true if the source expression is a postfix unary operation, false
  6154. /// if it is a prefix unary operation.
  6155. bool isPostfixUpdate() const { return IsPostfixUpdate; }
  6156. private:
  6157. bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
  6158. unsigned NoteId = 0);
  6159. };
  6160. } // namespace
  6161. bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
  6162. BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
  6163. ExprAnalysisErrorCode ErrorFound = NoError;
  6164. SourceLocation ErrorLoc, NoteLoc;
  6165. SourceRange ErrorRange, NoteRange;
  6166. // Allowed constructs are:
  6167. // x = x binop expr;
  6168. // x = expr binop x;
  6169. if (AtomicBinOp->getOpcode() == BO_Assign) {
  6170. X = AtomicBinOp->getLHS();
  6171. if (const auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
  6172. AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
  6173. if (AtomicInnerBinOp->isMultiplicativeOp() ||
  6174. AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
  6175. AtomicInnerBinOp->isBitwiseOp()) {
  6176. Op = AtomicInnerBinOp->getOpcode();
  6177. OpLoc = AtomicInnerBinOp->getOperatorLoc();
  6178. Expr *LHS = AtomicInnerBinOp->getLHS();
  6179. Expr *RHS = AtomicInnerBinOp->getRHS();
  6180. llvm::FoldingSetNodeID XId, LHSId, RHSId;
  6181. X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
  6182. /*Canonical=*/true);
  6183. LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
  6184. /*Canonical=*/true);
  6185. RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
  6186. /*Canonical=*/true);
  6187. if (XId == LHSId) {
  6188. E = RHS;
  6189. IsXLHSInRHSPart = true;
  6190. } else if (XId == RHSId) {
  6191. E = LHS;
  6192. IsXLHSInRHSPart = false;
  6193. } else {
  6194. ErrorLoc = AtomicInnerBinOp->getExprLoc();
  6195. ErrorRange = AtomicInnerBinOp->getSourceRange();
  6196. NoteLoc = X->getExprLoc();
  6197. NoteRange = X->getSourceRange();
  6198. ErrorFound = NotAnUpdateExpression;
  6199. }
  6200. } else {
  6201. ErrorLoc = AtomicInnerBinOp->getExprLoc();
  6202. ErrorRange = AtomicInnerBinOp->getSourceRange();
  6203. NoteLoc = AtomicInnerBinOp->getOperatorLoc();
  6204. NoteRange = SourceRange(NoteLoc, NoteLoc);
  6205. ErrorFound = NotABinaryOperator;
  6206. }
  6207. } else {
  6208. NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
  6209. NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
  6210. ErrorFound = NotABinaryExpression;
  6211. }
  6212. } else {
  6213. ErrorLoc = AtomicBinOp->getExprLoc();
  6214. ErrorRange = AtomicBinOp->getSourceRange();
  6215. NoteLoc = AtomicBinOp->getOperatorLoc();
  6216. NoteRange = SourceRange(NoteLoc, NoteLoc);
  6217. ErrorFound = NotAnAssignmentOp;
  6218. }
  6219. if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
  6220. SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
  6221. SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
  6222. return true;
  6223. }
  6224. if (SemaRef.CurContext->isDependentContext())
  6225. E = X = UpdateExpr = nullptr;
  6226. return ErrorFound != NoError;
  6227. }
  6228. bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
  6229. unsigned NoteId) {
  6230. ExprAnalysisErrorCode ErrorFound = NoError;
  6231. SourceLocation ErrorLoc, NoteLoc;
  6232. SourceRange ErrorRange, NoteRange;
  6233. // Allowed constructs are:
  6234. // x++;
  6235. // x--;
  6236. // ++x;
  6237. // --x;
  6238. // x binop= expr;
  6239. // x = x binop expr;
  6240. // x = expr binop x;
  6241. if (auto *AtomicBody = dyn_cast<Expr>(S)) {
  6242. AtomicBody = AtomicBody->IgnoreParenImpCasts();
  6243. if (AtomicBody->getType()->isScalarType() ||
  6244. AtomicBody->isInstantiationDependent()) {
  6245. if (const auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
  6246. AtomicBody->IgnoreParenImpCasts())) {
  6247. // Check for Compound Assignment Operation
  6248. Op = BinaryOperator::getOpForCompoundAssignment(
  6249. AtomicCompAssignOp->getOpcode());
  6250. OpLoc = AtomicCompAssignOp->getOperatorLoc();
  6251. E = AtomicCompAssignOp->getRHS();
  6252. X = AtomicCompAssignOp->getLHS()->IgnoreParens();
  6253. IsXLHSInRHSPart = true;
  6254. } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
  6255. AtomicBody->IgnoreParenImpCasts())) {
  6256. // Check for Binary Operation
  6257. if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
  6258. return true;
  6259. } else if (const auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
  6260. AtomicBody->IgnoreParenImpCasts())) {
  6261. // Check for Unary Operation
  6262. if (AtomicUnaryOp->isIncrementDecrementOp()) {
  6263. IsPostfixUpdate = AtomicUnaryOp->isPostfix();
  6264. Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
  6265. OpLoc = AtomicUnaryOp->getOperatorLoc();
  6266. X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
  6267. E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
  6268. IsXLHSInRHSPart = true;
  6269. } else {
  6270. ErrorFound = NotAnUnaryIncDecExpression;
  6271. ErrorLoc = AtomicUnaryOp->getExprLoc();
  6272. ErrorRange = AtomicUnaryOp->getSourceRange();
  6273. NoteLoc = AtomicUnaryOp->getOperatorLoc();
  6274. NoteRange = SourceRange(NoteLoc, NoteLoc);
  6275. }
  6276. } else if (!AtomicBody->isInstantiationDependent()) {
  6277. ErrorFound = NotABinaryOrUnaryExpression;
  6278. NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
  6279. NoteRange = ErrorRange = AtomicBody->getSourceRange();
  6280. }
  6281. } else {
  6282. ErrorFound = NotAScalarType;
  6283. NoteLoc = ErrorLoc = AtomicBody->getBeginLoc();
  6284. NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
  6285. }
  6286. } else {
  6287. ErrorFound = NotAnExpression;
  6288. NoteLoc = ErrorLoc = S->getBeginLoc();
  6289. NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
  6290. }
  6291. if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
  6292. SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
  6293. SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
  6294. return true;
  6295. }
  6296. if (SemaRef.CurContext->isDependentContext())
  6297. E = X = UpdateExpr = nullptr;
  6298. if (ErrorFound == NoError && E && X) {
  6299. // Build an update expression of form 'OpaqueValueExpr(x) binop
  6300. // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
  6301. // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
  6302. auto *OVEX = new (SemaRef.getASTContext())
  6303. OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
  6304. auto *OVEExpr = new (SemaRef.getASTContext())
  6305. OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
  6306. ExprResult Update =
  6307. SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
  6308. IsXLHSInRHSPart ? OVEExpr : OVEX);
  6309. if (Update.isInvalid())
  6310. return true;
  6311. Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
  6312. Sema::AA_Casting);
  6313. if (Update.isInvalid())
  6314. return true;
  6315. UpdateExpr = Update.get();
  6316. }
  6317. return ErrorFound != NoError;
  6318. }
  6319. StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
  6320. Stmt *AStmt,
  6321. SourceLocation StartLoc,
  6322. SourceLocation EndLoc) {
  6323. if (!AStmt)
  6324. return StmtError();
  6325. auto *CS = cast<CapturedStmt>(AStmt);
  6326. // 1.2.2 OpenMP Language Terminology
  6327. // Structured block - An executable statement with a single entry at the
  6328. // top and a single exit at the bottom.
  6329. // The point of exit cannot be a branch out of the structured block.
  6330. // longjmp() and throw() must not violate the entry/exit criteria.
  6331. OpenMPClauseKind AtomicKind = OMPC_unknown;
  6332. SourceLocation AtomicKindLoc;
  6333. for (const OMPClause *C : Clauses) {
  6334. if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
  6335. C->getClauseKind() == OMPC_update ||
  6336. C->getClauseKind() == OMPC_capture) {
  6337. if (AtomicKind != OMPC_unknown) {
  6338. Diag(C->getBeginLoc(), diag::err_omp_atomic_several_clauses)
  6339. << SourceRange(C->getBeginLoc(), C->getEndLoc());
  6340. Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
  6341. << getOpenMPClauseName(AtomicKind);
  6342. } else {
  6343. AtomicKind = C->getClauseKind();
  6344. AtomicKindLoc = C->getBeginLoc();
  6345. }
  6346. }
  6347. }
  6348. Stmt *Body = CS->getCapturedStmt();
  6349. if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
  6350. Body = EWC->getSubExpr();
  6351. Expr *X = nullptr;
  6352. Expr *V = nullptr;
  6353. Expr *E = nullptr;
  6354. Expr *UE = nullptr;
  6355. bool IsXLHSInRHSPart = false;
  6356. bool IsPostfixUpdate = false;
  6357. // OpenMP [2.12.6, atomic Construct]
  6358. // In the next expressions:
  6359. // * x and v (as applicable) are both l-value expressions with scalar type.
  6360. // * During the execution of an atomic region, multiple syntactic
  6361. // occurrences of x must designate the same storage location.
  6362. // * Neither of v and expr (as applicable) may access the storage location
  6363. // designated by x.
  6364. // * Neither of x and expr (as applicable) may access the storage location
  6365. // designated by v.
  6366. // * expr is an expression with scalar type.
  6367. // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
  6368. // * binop, binop=, ++, and -- are not overloaded operators.
  6369. // * The expression x binop expr must be numerically equivalent to x binop
  6370. // (expr). This requirement is satisfied if the operators in expr have
  6371. // precedence greater than binop, or by using parentheses around expr or
  6372. // subexpressions of expr.
  6373. // * The expression expr binop x must be numerically equivalent to (expr)
  6374. // binop x. This requirement is satisfied if the operators in expr have
  6375. // precedence equal to or greater than binop, or by using parentheses around
  6376. // expr or subexpressions of expr.
  6377. // * For forms that allow multiple occurrences of x, the number of times
  6378. // that x is evaluated is unspecified.
  6379. if (AtomicKind == OMPC_read) {
  6380. enum {
  6381. NotAnExpression,
  6382. NotAnAssignmentOp,
  6383. NotAScalarType,
  6384. NotAnLValue,
  6385. NoError
  6386. } ErrorFound = NoError;
  6387. SourceLocation ErrorLoc, NoteLoc;
  6388. SourceRange ErrorRange, NoteRange;
  6389. // If clause is read:
  6390. // v = x;
  6391. if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
  6392. const auto *AtomicBinOp =
  6393. dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
  6394. if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
  6395. X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
  6396. V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
  6397. if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
  6398. (V->isInstantiationDependent() || V->getType()->isScalarType())) {
  6399. if (!X->isLValue() || !V->isLValue()) {
  6400. const Expr *NotLValueExpr = X->isLValue() ? V : X;
  6401. ErrorFound = NotAnLValue;
  6402. ErrorLoc = AtomicBinOp->getExprLoc();
  6403. ErrorRange = AtomicBinOp->getSourceRange();
  6404. NoteLoc = NotLValueExpr->getExprLoc();
  6405. NoteRange = NotLValueExpr->getSourceRange();
  6406. }
  6407. } else if (!X->isInstantiationDependent() ||
  6408. !V->isInstantiationDependent()) {
  6409. const Expr *NotScalarExpr =
  6410. (X->isInstantiationDependent() || X->getType()->isScalarType())
  6411. ? V
  6412. : X;
  6413. ErrorFound = NotAScalarType;
  6414. ErrorLoc = AtomicBinOp->getExprLoc();
  6415. ErrorRange = AtomicBinOp->getSourceRange();
  6416. NoteLoc = NotScalarExpr->getExprLoc();
  6417. NoteRange = NotScalarExpr->getSourceRange();
  6418. }
  6419. } else if (!AtomicBody->isInstantiationDependent()) {
  6420. ErrorFound = NotAnAssignmentOp;
  6421. ErrorLoc = AtomicBody->getExprLoc();
  6422. ErrorRange = AtomicBody->getSourceRange();
  6423. NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
  6424. : AtomicBody->getExprLoc();
  6425. NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
  6426. : AtomicBody->getSourceRange();
  6427. }
  6428. } else {
  6429. ErrorFound = NotAnExpression;
  6430. NoteLoc = ErrorLoc = Body->getBeginLoc();
  6431. NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
  6432. }
  6433. if (ErrorFound != NoError) {
  6434. Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
  6435. << ErrorRange;
  6436. Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
  6437. << NoteRange;
  6438. return StmtError();
  6439. }
  6440. if (CurContext->isDependentContext())
  6441. V = X = nullptr;
  6442. } else if (AtomicKind == OMPC_write) {
  6443. enum {
  6444. NotAnExpression,
  6445. NotAnAssignmentOp,
  6446. NotAScalarType,
  6447. NotAnLValue,
  6448. NoError
  6449. } ErrorFound = NoError;
  6450. SourceLocation ErrorLoc, NoteLoc;
  6451. SourceRange ErrorRange, NoteRange;
  6452. // If clause is write:
  6453. // x = expr;
  6454. if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
  6455. const auto *AtomicBinOp =
  6456. dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
  6457. if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
  6458. X = AtomicBinOp->getLHS();
  6459. E = AtomicBinOp->getRHS();
  6460. if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
  6461. (E->isInstantiationDependent() || E->getType()->isScalarType())) {
  6462. if (!X->isLValue()) {
  6463. ErrorFound = NotAnLValue;
  6464. ErrorLoc = AtomicBinOp->getExprLoc();
  6465. ErrorRange = AtomicBinOp->getSourceRange();
  6466. NoteLoc = X->getExprLoc();
  6467. NoteRange = X->getSourceRange();
  6468. }
  6469. } else if (!X->isInstantiationDependent() ||
  6470. !E->isInstantiationDependent()) {
  6471. const Expr *NotScalarExpr =
  6472. (X->isInstantiationDependent() || X->getType()->isScalarType())
  6473. ? E
  6474. : X;
  6475. ErrorFound = NotAScalarType;
  6476. ErrorLoc = AtomicBinOp->getExprLoc();
  6477. ErrorRange = AtomicBinOp->getSourceRange();
  6478. NoteLoc = NotScalarExpr->getExprLoc();
  6479. NoteRange = NotScalarExpr->getSourceRange();
  6480. }
  6481. } else if (!AtomicBody->isInstantiationDependent()) {
  6482. ErrorFound = NotAnAssignmentOp;
  6483. ErrorLoc = AtomicBody->getExprLoc();
  6484. ErrorRange = AtomicBody->getSourceRange();
  6485. NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
  6486. : AtomicBody->getExprLoc();
  6487. NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
  6488. : AtomicBody->getSourceRange();
  6489. }
  6490. } else {
  6491. ErrorFound = NotAnExpression;
  6492. NoteLoc = ErrorLoc = Body->getBeginLoc();
  6493. NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
  6494. }
  6495. if (ErrorFound != NoError) {
  6496. Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
  6497. << ErrorRange;
  6498. Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
  6499. << NoteRange;
  6500. return StmtError();
  6501. }
  6502. if (CurContext->isDependentContext())
  6503. E = X = nullptr;
  6504. } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
  6505. // If clause is update:
  6506. // x++;
  6507. // x--;
  6508. // ++x;
  6509. // --x;
  6510. // x binop= expr;
  6511. // x = x binop expr;
  6512. // x = expr binop x;
  6513. OpenMPAtomicUpdateChecker Checker(*this);
  6514. if (Checker.checkStatement(
  6515. Body, (AtomicKind == OMPC_update)
  6516. ? diag::err_omp_atomic_update_not_expression_statement
  6517. : diag::err_omp_atomic_not_expression_statement,
  6518. diag::note_omp_atomic_update))
  6519. return StmtError();
  6520. if (!CurContext->isDependentContext()) {
  6521. E = Checker.getExpr();
  6522. X = Checker.getX();
  6523. UE = Checker.getUpdateExpr();
  6524. IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
  6525. }
  6526. } else if (AtomicKind == OMPC_capture) {
  6527. enum {
  6528. NotAnAssignmentOp,
  6529. NotACompoundStatement,
  6530. NotTwoSubstatements,
  6531. NotASpecificExpression,
  6532. NoError
  6533. } ErrorFound = NoError;
  6534. SourceLocation ErrorLoc, NoteLoc;
  6535. SourceRange ErrorRange, NoteRange;
  6536. if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
  6537. // If clause is a capture:
  6538. // v = x++;
  6539. // v = x--;
  6540. // v = ++x;
  6541. // v = --x;
  6542. // v = x binop= expr;
  6543. // v = x = x binop expr;
  6544. // v = x = expr binop x;
  6545. const auto *AtomicBinOp =
  6546. dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
  6547. if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
  6548. V = AtomicBinOp->getLHS();
  6549. Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
  6550. OpenMPAtomicUpdateChecker Checker(*this);
  6551. if (Checker.checkStatement(
  6552. Body, diag::err_omp_atomic_capture_not_expression_statement,
  6553. diag::note_omp_atomic_update))
  6554. return StmtError();
  6555. E = Checker.getExpr();
  6556. X = Checker.getX();
  6557. UE = Checker.getUpdateExpr();
  6558. IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
  6559. IsPostfixUpdate = Checker.isPostfixUpdate();
  6560. } else if (!AtomicBody->isInstantiationDependent()) {
  6561. ErrorLoc = AtomicBody->getExprLoc();
  6562. ErrorRange = AtomicBody->getSourceRange();
  6563. NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
  6564. : AtomicBody->getExprLoc();
  6565. NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
  6566. : AtomicBody->getSourceRange();
  6567. ErrorFound = NotAnAssignmentOp;
  6568. }
  6569. if (ErrorFound != NoError) {
  6570. Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
  6571. << ErrorRange;
  6572. Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
  6573. return StmtError();
  6574. }
  6575. if (CurContext->isDependentContext())
  6576. UE = V = E = X = nullptr;
  6577. } else {
  6578. // If clause is a capture:
  6579. // { v = x; x = expr; }
  6580. // { v = x; x++; }
  6581. // { v = x; x--; }
  6582. // { v = x; ++x; }
  6583. // { v = x; --x; }
  6584. // { v = x; x binop= expr; }
  6585. // { v = x; x = x binop expr; }
  6586. // { v = x; x = expr binop x; }
  6587. // { x++; v = x; }
  6588. // { x--; v = x; }
  6589. // { ++x; v = x; }
  6590. // { --x; v = x; }
  6591. // { x binop= expr; v = x; }
  6592. // { x = x binop expr; v = x; }
  6593. // { x = expr binop x; v = x; }
  6594. if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
  6595. // Check that this is { expr1; expr2; }
  6596. if (CS->size() == 2) {
  6597. Stmt *First = CS->body_front();
  6598. Stmt *Second = CS->body_back();
  6599. if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
  6600. First = EWC->getSubExpr()->IgnoreParenImpCasts();
  6601. if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
  6602. Second = EWC->getSubExpr()->IgnoreParenImpCasts();
  6603. // Need to find what subexpression is 'v' and what is 'x'.
  6604. OpenMPAtomicUpdateChecker Checker(*this);
  6605. bool IsUpdateExprFound = !Checker.checkStatement(Second);
  6606. BinaryOperator *BinOp = nullptr;
  6607. if (IsUpdateExprFound) {
  6608. BinOp = dyn_cast<BinaryOperator>(First);
  6609. IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
  6610. }
  6611. if (IsUpdateExprFound && !CurContext->isDependentContext()) {
  6612. // { v = x; x++; }
  6613. // { v = x; x--; }
  6614. // { v = x; ++x; }
  6615. // { v = x; --x; }
  6616. // { v = x; x binop= expr; }
  6617. // { v = x; x = x binop expr; }
  6618. // { v = x; x = expr binop x; }
  6619. // Check that the first expression has form v = x.
  6620. Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
  6621. llvm::FoldingSetNodeID XId, PossibleXId;
  6622. Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
  6623. PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
  6624. IsUpdateExprFound = XId == PossibleXId;
  6625. if (IsUpdateExprFound) {
  6626. V = BinOp->getLHS();
  6627. X = Checker.getX();
  6628. E = Checker.getExpr();
  6629. UE = Checker.getUpdateExpr();
  6630. IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
  6631. IsPostfixUpdate = true;
  6632. }
  6633. }
  6634. if (!IsUpdateExprFound) {
  6635. IsUpdateExprFound = !Checker.checkStatement(First);
  6636. BinOp = nullptr;
  6637. if (IsUpdateExprFound) {
  6638. BinOp = dyn_cast<BinaryOperator>(Second);
  6639. IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
  6640. }
  6641. if (IsUpdateExprFound && !CurContext->isDependentContext()) {
  6642. // { x++; v = x; }
  6643. // { x--; v = x; }
  6644. // { ++x; v = x; }
  6645. // { --x; v = x; }
  6646. // { x binop= expr; v = x; }
  6647. // { x = x binop expr; v = x; }
  6648. // { x = expr binop x; v = x; }
  6649. // Check that the second expression has form v = x.
  6650. Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
  6651. llvm::FoldingSetNodeID XId, PossibleXId;
  6652. Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
  6653. PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
  6654. IsUpdateExprFound = XId == PossibleXId;
  6655. if (IsUpdateExprFound) {
  6656. V = BinOp->getLHS();
  6657. X = Checker.getX();
  6658. E = Checker.getExpr();
  6659. UE = Checker.getUpdateExpr();
  6660. IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
  6661. IsPostfixUpdate = false;
  6662. }
  6663. }
  6664. }
  6665. if (!IsUpdateExprFound) {
  6666. // { v = x; x = expr; }
  6667. auto *FirstExpr = dyn_cast<Expr>(First);
  6668. auto *SecondExpr = dyn_cast<Expr>(Second);
  6669. if (!FirstExpr || !SecondExpr ||
  6670. !(FirstExpr->isInstantiationDependent() ||
  6671. SecondExpr->isInstantiationDependent())) {
  6672. auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
  6673. if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
  6674. ErrorFound = NotAnAssignmentOp;
  6675. NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
  6676. : First->getBeginLoc();
  6677. NoteRange = ErrorRange = FirstBinOp
  6678. ? FirstBinOp->getSourceRange()
  6679. : SourceRange(ErrorLoc, ErrorLoc);
  6680. } else {
  6681. auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
  6682. if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
  6683. ErrorFound = NotAnAssignmentOp;
  6684. NoteLoc = ErrorLoc = SecondBinOp
  6685. ? SecondBinOp->getOperatorLoc()
  6686. : Second->getBeginLoc();
  6687. NoteRange = ErrorRange =
  6688. SecondBinOp ? SecondBinOp->getSourceRange()
  6689. : SourceRange(ErrorLoc, ErrorLoc);
  6690. } else {
  6691. Expr *PossibleXRHSInFirst =
  6692. FirstBinOp->getRHS()->IgnoreParenImpCasts();
  6693. Expr *PossibleXLHSInSecond =
  6694. SecondBinOp->getLHS()->IgnoreParenImpCasts();
  6695. llvm::FoldingSetNodeID X1Id, X2Id;
  6696. PossibleXRHSInFirst->Profile(X1Id, Context,
  6697. /*Canonical=*/true);
  6698. PossibleXLHSInSecond->Profile(X2Id, Context,
  6699. /*Canonical=*/true);
  6700. IsUpdateExprFound = X1Id == X2Id;
  6701. if (IsUpdateExprFound) {
  6702. V = FirstBinOp->getLHS();
  6703. X = SecondBinOp->getLHS();
  6704. E = SecondBinOp->getRHS();
  6705. UE = nullptr;
  6706. IsXLHSInRHSPart = false;
  6707. IsPostfixUpdate = true;
  6708. } else {
  6709. ErrorFound = NotASpecificExpression;
  6710. ErrorLoc = FirstBinOp->getExprLoc();
  6711. ErrorRange = FirstBinOp->getSourceRange();
  6712. NoteLoc = SecondBinOp->getLHS()->getExprLoc();
  6713. NoteRange = SecondBinOp->getRHS()->getSourceRange();
  6714. }
  6715. }
  6716. }
  6717. }
  6718. }
  6719. } else {
  6720. NoteLoc = ErrorLoc = Body->getBeginLoc();
  6721. NoteRange = ErrorRange =
  6722. SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
  6723. ErrorFound = NotTwoSubstatements;
  6724. }
  6725. } else {
  6726. NoteLoc = ErrorLoc = Body->getBeginLoc();
  6727. NoteRange = ErrorRange =
  6728. SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
  6729. ErrorFound = NotACompoundStatement;
  6730. }
  6731. if (ErrorFound != NoError) {
  6732. Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
  6733. << ErrorRange;
  6734. Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
  6735. return StmtError();
  6736. }
  6737. if (CurContext->isDependentContext())
  6738. UE = V = E = X = nullptr;
  6739. }
  6740. }
  6741. setFunctionHasBranchProtectedScope();
  6742. return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
  6743. X, V, E, UE, IsXLHSInRHSPart,
  6744. IsPostfixUpdate);
  6745. }
  6746. StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
  6747. Stmt *AStmt,
  6748. SourceLocation StartLoc,
  6749. SourceLocation EndLoc) {
  6750. if (!AStmt)
  6751. return StmtError();
  6752. auto *CS = cast<CapturedStmt>(AStmt);
  6753. // 1.2.2 OpenMP Language Terminology
  6754. // Structured block - An executable statement with a single entry at the
  6755. // top and a single exit at the bottom.
  6756. // The point of exit cannot be a branch out of the structured block.
  6757. // longjmp() and throw() must not violate the entry/exit criteria.
  6758. CS->getCapturedDecl()->setNothrow();
  6759. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target);
  6760. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  6761. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  6762. // 1.2.2 OpenMP Language Terminology
  6763. // Structured block - An executable statement with a single entry at the
  6764. // top and a single exit at the bottom.
  6765. // The point of exit cannot be a branch out of the structured block.
  6766. // longjmp() and throw() must not violate the entry/exit criteria.
  6767. CS->getCapturedDecl()->setNothrow();
  6768. }
  6769. // OpenMP [2.16, Nesting of Regions]
  6770. // If specified, a teams construct must be contained within a target
  6771. // construct. That target construct must contain no statements or directives
  6772. // outside of the teams construct.
  6773. if (DSAStack->hasInnerTeamsRegion()) {
  6774. const Stmt *S = CS->IgnoreContainers(/*IgnoreCaptured=*/true);
  6775. bool OMPTeamsFound = true;
  6776. if (const auto *CS = dyn_cast<CompoundStmt>(S)) {
  6777. auto I = CS->body_begin();
  6778. while (I != CS->body_end()) {
  6779. const auto *OED = dyn_cast<OMPExecutableDirective>(*I);
  6780. if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind()) ||
  6781. OMPTeamsFound) {
  6782. OMPTeamsFound = false;
  6783. break;
  6784. }
  6785. ++I;
  6786. }
  6787. assert(I != CS->body_end() && "Not found statement");
  6788. S = *I;
  6789. } else {
  6790. const auto *OED = dyn_cast<OMPExecutableDirective>(S);
  6791. OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
  6792. }
  6793. if (!OMPTeamsFound) {
  6794. Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
  6795. Diag(DSAStack->getInnerTeamsRegionLoc(),
  6796. diag::note_omp_nested_teams_construct_here);
  6797. Diag(S->getBeginLoc(), diag::note_omp_nested_statement_here)
  6798. << isa<OMPExecutableDirective>(S);
  6799. return StmtError();
  6800. }
  6801. }
  6802. setFunctionHasBranchProtectedScope();
  6803. return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
  6804. }
  6805. StmtResult
  6806. Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
  6807. Stmt *AStmt, SourceLocation StartLoc,
  6808. SourceLocation EndLoc) {
  6809. if (!AStmt)
  6810. return StmtError();
  6811. auto *CS = cast<CapturedStmt>(AStmt);
  6812. // 1.2.2 OpenMP Language Terminology
  6813. // Structured block - An executable statement with a single entry at the
  6814. // top and a single exit at the bottom.
  6815. // The point of exit cannot be a branch out of the structured block.
  6816. // longjmp() and throw() must not violate the entry/exit criteria.
  6817. CS->getCapturedDecl()->setNothrow();
  6818. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel);
  6819. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  6820. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  6821. // 1.2.2 OpenMP Language Terminology
  6822. // Structured block - An executable statement with a single entry at the
  6823. // top and a single exit at the bottom.
  6824. // The point of exit cannot be a branch out of the structured block.
  6825. // longjmp() and throw() must not violate the entry/exit criteria.
  6826. CS->getCapturedDecl()->setNothrow();
  6827. }
  6828. setFunctionHasBranchProtectedScope();
  6829. return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
  6830. AStmt);
  6831. }
  6832. StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
  6833. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  6834. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  6835. if (!AStmt)
  6836. return StmtError();
  6837. auto *CS = cast<CapturedStmt>(AStmt);
  6838. // 1.2.2 OpenMP Language Terminology
  6839. // Structured block - An executable statement with a single entry at the
  6840. // top and a single exit at the bottom.
  6841. // The point of exit cannot be a branch out of the structured block.
  6842. // longjmp() and throw() must not violate the entry/exit criteria.
  6843. CS->getCapturedDecl()->setNothrow();
  6844. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
  6845. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  6846. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  6847. // 1.2.2 OpenMP Language Terminology
  6848. // Structured block - An executable statement with a single entry at the
  6849. // top and a single exit at the bottom.
  6850. // The point of exit cannot be a branch out of the structured block.
  6851. // longjmp() and throw() must not violate the entry/exit criteria.
  6852. CS->getCapturedDecl()->setNothrow();
  6853. }
  6854. OMPLoopDirective::HelperExprs B;
  6855. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  6856. // define the nested loops number.
  6857. unsigned NestedLoopCount =
  6858. checkOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
  6859. getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
  6860. VarsWithImplicitDSA, B);
  6861. if (NestedLoopCount == 0)
  6862. return StmtError();
  6863. assert((CurContext->isDependentContext() || B.builtAll()) &&
  6864. "omp target parallel for loop exprs were not built");
  6865. if (!CurContext->isDependentContext()) {
  6866. // Finalize the clauses that need pre-built expressions for CodeGen.
  6867. for (OMPClause *C : Clauses) {
  6868. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  6869. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  6870. B.NumIterations, *this, CurScope,
  6871. DSAStack))
  6872. return StmtError();
  6873. }
  6874. }
  6875. setFunctionHasBranchProtectedScope();
  6876. return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc,
  6877. NestedLoopCount, Clauses, AStmt,
  6878. B, DSAStack->isCancelRegion());
  6879. }
  6880. /// Check for existence of a map clause in the list of clauses.
  6881. static bool hasClauses(ArrayRef<OMPClause *> Clauses,
  6882. const OpenMPClauseKind K) {
  6883. return llvm::any_of(
  6884. Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; });
  6885. }
  6886. template <typename... Params>
  6887. static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K,
  6888. const Params... ClauseTypes) {
  6889. return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...);
  6890. }
  6891. StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
  6892. Stmt *AStmt,
  6893. SourceLocation StartLoc,
  6894. SourceLocation EndLoc) {
  6895. if (!AStmt)
  6896. return StmtError();
  6897. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  6898. // OpenMP [2.10.1, Restrictions, p. 97]
  6899. // At least one map clause must appear on the directive.
  6900. if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr)) {
  6901. Diag(StartLoc, diag::err_omp_no_clause_for_directive)
  6902. << "'map' or 'use_device_ptr'"
  6903. << getOpenMPDirectiveName(OMPD_target_data);
  6904. return StmtError();
  6905. }
  6906. setFunctionHasBranchProtectedScope();
  6907. return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
  6908. AStmt);
  6909. }
  6910. StmtResult
  6911. Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
  6912. SourceLocation StartLoc,
  6913. SourceLocation EndLoc, Stmt *AStmt) {
  6914. if (!AStmt)
  6915. return StmtError();
  6916. auto *CS = cast<CapturedStmt>(AStmt);
  6917. // 1.2.2 OpenMP Language Terminology
  6918. // Structured block - An executable statement with a single entry at the
  6919. // top and a single exit at the bottom.
  6920. // The point of exit cannot be a branch out of the structured block.
  6921. // longjmp() and throw() must not violate the entry/exit criteria.
  6922. CS->getCapturedDecl()->setNothrow();
  6923. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_enter_data);
  6924. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  6925. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  6926. // 1.2.2 OpenMP Language Terminology
  6927. // Structured block - An executable statement with a single entry at the
  6928. // top and a single exit at the bottom.
  6929. // The point of exit cannot be a branch out of the structured block.
  6930. // longjmp() and throw() must not violate the entry/exit criteria.
  6931. CS->getCapturedDecl()->setNothrow();
  6932. }
  6933. // OpenMP [2.10.2, Restrictions, p. 99]
  6934. // At least one map clause must appear on the directive.
  6935. if (!hasClauses(Clauses, OMPC_map)) {
  6936. Diag(StartLoc, diag::err_omp_no_clause_for_directive)
  6937. << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data);
  6938. return StmtError();
  6939. }
  6940. return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
  6941. AStmt);
  6942. }
  6943. StmtResult
  6944. Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
  6945. SourceLocation StartLoc,
  6946. SourceLocation EndLoc, Stmt *AStmt) {
  6947. if (!AStmt)
  6948. return StmtError();
  6949. auto *CS = cast<CapturedStmt>(AStmt);
  6950. // 1.2.2 OpenMP Language Terminology
  6951. // Structured block - An executable statement with a single entry at the
  6952. // top and a single exit at the bottom.
  6953. // The point of exit cannot be a branch out of the structured block.
  6954. // longjmp() and throw() must not violate the entry/exit criteria.
  6955. CS->getCapturedDecl()->setNothrow();
  6956. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_exit_data);
  6957. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  6958. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  6959. // 1.2.2 OpenMP Language Terminology
  6960. // Structured block - An executable statement with a single entry at the
  6961. // top and a single exit at the bottom.
  6962. // The point of exit cannot be a branch out of the structured block.
  6963. // longjmp() and throw() must not violate the entry/exit criteria.
  6964. CS->getCapturedDecl()->setNothrow();
  6965. }
  6966. // OpenMP [2.10.3, Restrictions, p. 102]
  6967. // At least one map clause must appear on the directive.
  6968. if (!hasClauses(Clauses, OMPC_map)) {
  6969. Diag(StartLoc, diag::err_omp_no_clause_for_directive)
  6970. << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data);
  6971. return StmtError();
  6972. }
  6973. return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
  6974. AStmt);
  6975. }
  6976. StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
  6977. SourceLocation StartLoc,
  6978. SourceLocation EndLoc,
  6979. Stmt *AStmt) {
  6980. if (!AStmt)
  6981. return StmtError();
  6982. auto *CS = cast<CapturedStmt>(AStmt);
  6983. // 1.2.2 OpenMP Language Terminology
  6984. // Structured block - An executable statement with a single entry at the
  6985. // top and a single exit at the bottom.
  6986. // The point of exit cannot be a branch out of the structured block.
  6987. // longjmp() and throw() must not violate the entry/exit criteria.
  6988. CS->getCapturedDecl()->setNothrow();
  6989. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_update);
  6990. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  6991. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  6992. // 1.2.2 OpenMP Language Terminology
  6993. // Structured block - An executable statement with a single entry at the
  6994. // top and a single exit at the bottom.
  6995. // The point of exit cannot be a branch out of the structured block.
  6996. // longjmp() and throw() must not violate the entry/exit criteria.
  6997. CS->getCapturedDecl()->setNothrow();
  6998. }
  6999. if (!hasClauses(Clauses, OMPC_to, OMPC_from)) {
  7000. Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
  7001. return StmtError();
  7002. }
  7003. return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses,
  7004. AStmt);
  7005. }
  7006. StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
  7007. Stmt *AStmt, SourceLocation StartLoc,
  7008. SourceLocation EndLoc) {
  7009. if (!AStmt)
  7010. return StmtError();
  7011. auto *CS = cast<CapturedStmt>(AStmt);
  7012. // 1.2.2 OpenMP Language Terminology
  7013. // Structured block - An executable statement with a single entry at the
  7014. // top and a single exit at the bottom.
  7015. // The point of exit cannot be a branch out of the structured block.
  7016. // longjmp() and throw() must not violate the entry/exit criteria.
  7017. CS->getCapturedDecl()->setNothrow();
  7018. setFunctionHasBranchProtectedScope();
  7019. DSAStack->setParentTeamsRegionLoc(StartLoc);
  7020. return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
  7021. }
  7022. StmtResult
  7023. Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
  7024. SourceLocation EndLoc,
  7025. OpenMPDirectiveKind CancelRegion) {
  7026. if (DSAStack->isParentNowaitRegion()) {
  7027. Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
  7028. return StmtError();
  7029. }
  7030. if (DSAStack->isParentOrderedRegion()) {
  7031. Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
  7032. return StmtError();
  7033. }
  7034. return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
  7035. CancelRegion);
  7036. }
  7037. StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
  7038. SourceLocation StartLoc,
  7039. SourceLocation EndLoc,
  7040. OpenMPDirectiveKind CancelRegion) {
  7041. if (DSAStack->isParentNowaitRegion()) {
  7042. Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
  7043. return StmtError();
  7044. }
  7045. if (DSAStack->isParentOrderedRegion()) {
  7046. Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
  7047. return StmtError();
  7048. }
  7049. DSAStack->setParentCancelRegion(/*Cancel=*/true);
  7050. return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
  7051. CancelRegion);
  7052. }
  7053. static bool checkGrainsizeNumTasksClauses(Sema &S,
  7054. ArrayRef<OMPClause *> Clauses) {
  7055. const OMPClause *PrevClause = nullptr;
  7056. bool ErrorFound = false;
  7057. for (const OMPClause *C : Clauses) {
  7058. if (C->getClauseKind() == OMPC_grainsize ||
  7059. C->getClauseKind() == OMPC_num_tasks) {
  7060. if (!PrevClause)
  7061. PrevClause = C;
  7062. else if (PrevClause->getClauseKind() != C->getClauseKind()) {
  7063. S.Diag(C->getBeginLoc(),
  7064. diag::err_omp_grainsize_num_tasks_mutually_exclusive)
  7065. << getOpenMPClauseName(C->getClauseKind())
  7066. << getOpenMPClauseName(PrevClause->getClauseKind());
  7067. S.Diag(PrevClause->getBeginLoc(),
  7068. diag::note_omp_previous_grainsize_num_tasks)
  7069. << getOpenMPClauseName(PrevClause->getClauseKind());
  7070. ErrorFound = true;
  7071. }
  7072. }
  7073. }
  7074. return ErrorFound;
  7075. }
  7076. static bool checkReductionClauseWithNogroup(Sema &S,
  7077. ArrayRef<OMPClause *> Clauses) {
  7078. const OMPClause *ReductionClause = nullptr;
  7079. const OMPClause *NogroupClause = nullptr;
  7080. for (const OMPClause *C : Clauses) {
  7081. if (C->getClauseKind() == OMPC_reduction) {
  7082. ReductionClause = C;
  7083. if (NogroupClause)
  7084. break;
  7085. continue;
  7086. }
  7087. if (C->getClauseKind() == OMPC_nogroup) {
  7088. NogroupClause = C;
  7089. if (ReductionClause)
  7090. break;
  7091. continue;
  7092. }
  7093. }
  7094. if (ReductionClause && NogroupClause) {
  7095. S.Diag(ReductionClause->getBeginLoc(), diag::err_omp_reduction_with_nogroup)
  7096. << SourceRange(NogroupClause->getBeginLoc(),
  7097. NogroupClause->getEndLoc());
  7098. return true;
  7099. }
  7100. return false;
  7101. }
  7102. StmtResult Sema::ActOnOpenMPTaskLoopDirective(
  7103. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  7104. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  7105. if (!AStmt)
  7106. return StmtError();
  7107. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  7108. OMPLoopDirective::HelperExprs B;
  7109. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  7110. // define the nested loops number.
  7111. unsigned NestedLoopCount =
  7112. checkOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
  7113. /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
  7114. VarsWithImplicitDSA, B);
  7115. if (NestedLoopCount == 0)
  7116. return StmtError();
  7117. assert((CurContext->isDependentContext() || B.builtAll()) &&
  7118. "omp for loop exprs were not built");
  7119. // OpenMP, [2.9.2 taskloop Construct, Restrictions]
  7120. // The grainsize clause and num_tasks clause are mutually exclusive and may
  7121. // not appear on the same taskloop directive.
  7122. if (checkGrainsizeNumTasksClauses(*this, Clauses))
  7123. return StmtError();
  7124. // OpenMP, [2.9.2 taskloop Construct, Restrictions]
  7125. // If a reduction clause is present on the taskloop directive, the nogroup
  7126. // clause must not be specified.
  7127. if (checkReductionClauseWithNogroup(*this, Clauses))
  7128. return StmtError();
  7129. setFunctionHasBranchProtectedScope();
  7130. return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
  7131. NestedLoopCount, Clauses, AStmt, B);
  7132. }
  7133. StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
  7134. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  7135. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  7136. if (!AStmt)
  7137. return StmtError();
  7138. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  7139. OMPLoopDirective::HelperExprs B;
  7140. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  7141. // define the nested loops number.
  7142. unsigned NestedLoopCount =
  7143. checkOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
  7144. /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
  7145. VarsWithImplicitDSA, B);
  7146. if (NestedLoopCount == 0)
  7147. return StmtError();
  7148. assert((CurContext->isDependentContext() || B.builtAll()) &&
  7149. "omp for loop exprs were not built");
  7150. if (!CurContext->isDependentContext()) {
  7151. // Finalize the clauses that need pre-built expressions for CodeGen.
  7152. for (OMPClause *C : Clauses) {
  7153. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  7154. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  7155. B.NumIterations, *this, CurScope,
  7156. DSAStack))
  7157. return StmtError();
  7158. }
  7159. }
  7160. // OpenMP, [2.9.2 taskloop Construct, Restrictions]
  7161. // The grainsize clause and num_tasks clause are mutually exclusive and may
  7162. // not appear on the same taskloop directive.
  7163. if (checkGrainsizeNumTasksClauses(*this, Clauses))
  7164. return StmtError();
  7165. // OpenMP, [2.9.2 taskloop Construct, Restrictions]
  7166. // If a reduction clause is present on the taskloop directive, the nogroup
  7167. // clause must not be specified.
  7168. if (checkReductionClauseWithNogroup(*this, Clauses))
  7169. return StmtError();
  7170. if (checkSimdlenSafelenSpecified(*this, Clauses))
  7171. return StmtError();
  7172. setFunctionHasBranchProtectedScope();
  7173. return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
  7174. NestedLoopCount, Clauses, AStmt, B);
  7175. }
  7176. StmtResult Sema::ActOnOpenMPDistributeDirective(
  7177. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  7178. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  7179. if (!AStmt)
  7180. return StmtError();
  7181. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  7182. OMPLoopDirective::HelperExprs B;
  7183. // In presence of clause 'collapse' with number of loops, it will
  7184. // define the nested loops number.
  7185. unsigned NestedLoopCount =
  7186. checkOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
  7187. nullptr /*ordered not a clause on distribute*/, AStmt,
  7188. *this, *DSAStack, VarsWithImplicitDSA, B);
  7189. if (NestedLoopCount == 0)
  7190. return StmtError();
  7191. assert((CurContext->isDependentContext() || B.builtAll()) &&
  7192. "omp for loop exprs were not built");
  7193. setFunctionHasBranchProtectedScope();
  7194. return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
  7195. NestedLoopCount, Clauses, AStmt, B);
  7196. }
  7197. StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
  7198. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  7199. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  7200. if (!AStmt)
  7201. return StmtError();
  7202. auto *CS = cast<CapturedStmt>(AStmt);
  7203. // 1.2.2 OpenMP Language Terminology
  7204. // Structured block - An executable statement with a single entry at the
  7205. // top and a single exit at the bottom.
  7206. // The point of exit cannot be a branch out of the structured block.
  7207. // longjmp() and throw() must not violate the entry/exit criteria.
  7208. CS->getCapturedDecl()->setNothrow();
  7209. for (int ThisCaptureLevel =
  7210. getOpenMPCaptureLevels(OMPD_distribute_parallel_for);
  7211. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  7212. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  7213. // 1.2.2 OpenMP Language Terminology
  7214. // Structured block - An executable statement with a single entry at the
  7215. // top and a single exit at the bottom.
  7216. // The point of exit cannot be a branch out of the structured block.
  7217. // longjmp() and throw() must not violate the entry/exit criteria.
  7218. CS->getCapturedDecl()->setNothrow();
  7219. }
  7220. OMPLoopDirective::HelperExprs B;
  7221. // In presence of clause 'collapse' with number of loops, it will
  7222. // define the nested loops number.
  7223. unsigned NestedLoopCount = checkOpenMPLoop(
  7224. OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
  7225. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  7226. VarsWithImplicitDSA, B);
  7227. if (NestedLoopCount == 0)
  7228. return StmtError();
  7229. assert((CurContext->isDependentContext() || B.builtAll()) &&
  7230. "omp for loop exprs were not built");
  7231. setFunctionHasBranchProtectedScope();
  7232. return OMPDistributeParallelForDirective::Create(
  7233. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
  7234. DSAStack->isCancelRegion());
  7235. }
  7236. StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
  7237. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  7238. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  7239. if (!AStmt)
  7240. return StmtError();
  7241. auto *CS = cast<CapturedStmt>(AStmt);
  7242. // 1.2.2 OpenMP Language Terminology
  7243. // Structured block - An executable statement with a single entry at the
  7244. // top and a single exit at the bottom.
  7245. // The point of exit cannot be a branch out of the structured block.
  7246. // longjmp() and throw() must not violate the entry/exit criteria.
  7247. CS->getCapturedDecl()->setNothrow();
  7248. for (int ThisCaptureLevel =
  7249. getOpenMPCaptureLevels(OMPD_distribute_parallel_for_simd);
  7250. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  7251. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  7252. // 1.2.2 OpenMP Language Terminology
  7253. // Structured block - An executable statement with a single entry at the
  7254. // top and a single exit at the bottom.
  7255. // The point of exit cannot be a branch out of the structured block.
  7256. // longjmp() and throw() must not violate the entry/exit criteria.
  7257. CS->getCapturedDecl()->setNothrow();
  7258. }
  7259. OMPLoopDirective::HelperExprs B;
  7260. // In presence of clause 'collapse' with number of loops, it will
  7261. // define the nested loops number.
  7262. unsigned NestedLoopCount = checkOpenMPLoop(
  7263. OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
  7264. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  7265. VarsWithImplicitDSA, B);
  7266. if (NestedLoopCount == 0)
  7267. return StmtError();
  7268. assert((CurContext->isDependentContext() || B.builtAll()) &&
  7269. "omp for loop exprs were not built");
  7270. if (!CurContext->isDependentContext()) {
  7271. // Finalize the clauses that need pre-built expressions for CodeGen.
  7272. for (OMPClause *C : Clauses) {
  7273. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  7274. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  7275. B.NumIterations, *this, CurScope,
  7276. DSAStack))
  7277. return StmtError();
  7278. }
  7279. }
  7280. if (checkSimdlenSafelenSpecified(*this, Clauses))
  7281. return StmtError();
  7282. setFunctionHasBranchProtectedScope();
  7283. return OMPDistributeParallelForSimdDirective::Create(
  7284. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  7285. }
  7286. StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
  7287. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  7288. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  7289. if (!AStmt)
  7290. return StmtError();
  7291. auto *CS = cast<CapturedStmt>(AStmt);
  7292. // 1.2.2 OpenMP Language Terminology
  7293. // Structured block - An executable statement with a single entry at the
  7294. // top and a single exit at the bottom.
  7295. // The point of exit cannot be a branch out of the structured block.
  7296. // longjmp() and throw() must not violate the entry/exit criteria.
  7297. CS->getCapturedDecl()->setNothrow();
  7298. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_distribute_simd);
  7299. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  7300. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  7301. // 1.2.2 OpenMP Language Terminology
  7302. // Structured block - An executable statement with a single entry at the
  7303. // top and a single exit at the bottom.
  7304. // The point of exit cannot be a branch out of the structured block.
  7305. // longjmp() and throw() must not violate the entry/exit criteria.
  7306. CS->getCapturedDecl()->setNothrow();
  7307. }
  7308. OMPLoopDirective::HelperExprs B;
  7309. // In presence of clause 'collapse' with number of loops, it will
  7310. // define the nested loops number.
  7311. unsigned NestedLoopCount =
  7312. checkOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
  7313. nullptr /*ordered not a clause on distribute*/, CS, *this,
  7314. *DSAStack, VarsWithImplicitDSA, B);
  7315. if (NestedLoopCount == 0)
  7316. return StmtError();
  7317. assert((CurContext->isDependentContext() || B.builtAll()) &&
  7318. "omp for loop exprs were not built");
  7319. if (!CurContext->isDependentContext()) {
  7320. // Finalize the clauses that need pre-built expressions for CodeGen.
  7321. for (OMPClause *C : Clauses) {
  7322. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  7323. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  7324. B.NumIterations, *this, CurScope,
  7325. DSAStack))
  7326. return StmtError();
  7327. }
  7328. }
  7329. if (checkSimdlenSafelenSpecified(*this, Clauses))
  7330. return StmtError();
  7331. setFunctionHasBranchProtectedScope();
  7332. return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
  7333. NestedLoopCount, Clauses, AStmt, B);
  7334. }
  7335. StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
  7336. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  7337. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  7338. if (!AStmt)
  7339. return StmtError();
  7340. auto *CS = cast<CapturedStmt>(AStmt);
  7341. // 1.2.2 OpenMP Language Terminology
  7342. // Structured block - An executable statement with a single entry at the
  7343. // top and a single exit at the bottom.
  7344. // The point of exit cannot be a branch out of the structured block.
  7345. // longjmp() and throw() must not violate the entry/exit criteria.
  7346. CS->getCapturedDecl()->setNothrow();
  7347. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
  7348. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  7349. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  7350. // 1.2.2 OpenMP Language Terminology
  7351. // Structured block - An executable statement with a single entry at the
  7352. // top and a single exit at the bottom.
  7353. // The point of exit cannot be a branch out of the structured block.
  7354. // longjmp() and throw() must not violate the entry/exit criteria.
  7355. CS->getCapturedDecl()->setNothrow();
  7356. }
  7357. OMPLoopDirective::HelperExprs B;
  7358. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  7359. // define the nested loops number.
  7360. unsigned NestedLoopCount = checkOpenMPLoop(
  7361. OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
  7362. getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
  7363. VarsWithImplicitDSA, B);
  7364. if (NestedLoopCount == 0)
  7365. return StmtError();
  7366. assert((CurContext->isDependentContext() || B.builtAll()) &&
  7367. "omp target parallel for simd loop exprs were not built");
  7368. if (!CurContext->isDependentContext()) {
  7369. // Finalize the clauses that need pre-built expressions for CodeGen.
  7370. for (OMPClause *C : Clauses) {
  7371. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  7372. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  7373. B.NumIterations, *this, CurScope,
  7374. DSAStack))
  7375. return StmtError();
  7376. }
  7377. }
  7378. if (checkSimdlenSafelenSpecified(*this, Clauses))
  7379. return StmtError();
  7380. setFunctionHasBranchProtectedScope();
  7381. return OMPTargetParallelForSimdDirective::Create(
  7382. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  7383. }
  7384. StmtResult Sema::ActOnOpenMPTargetSimdDirective(
  7385. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  7386. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  7387. if (!AStmt)
  7388. return StmtError();
  7389. auto *CS = cast<CapturedStmt>(AStmt);
  7390. // 1.2.2 OpenMP Language Terminology
  7391. // Structured block - An executable statement with a single entry at the
  7392. // top and a single exit at the bottom.
  7393. // The point of exit cannot be a branch out of the structured block.
  7394. // longjmp() and throw() must not violate the entry/exit criteria.
  7395. CS->getCapturedDecl()->setNothrow();
  7396. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_simd);
  7397. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  7398. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  7399. // 1.2.2 OpenMP Language Terminology
  7400. // Structured block - An executable statement with a single entry at the
  7401. // top and a single exit at the bottom.
  7402. // The point of exit cannot be a branch out of the structured block.
  7403. // longjmp() and throw() must not violate the entry/exit criteria.
  7404. CS->getCapturedDecl()->setNothrow();
  7405. }
  7406. OMPLoopDirective::HelperExprs B;
  7407. // In presence of clause 'collapse' with number of loops, it will define the
  7408. // nested loops number.
  7409. unsigned NestedLoopCount =
  7410. checkOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
  7411. getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
  7412. VarsWithImplicitDSA, B);
  7413. if (NestedLoopCount == 0)
  7414. return StmtError();
  7415. assert((CurContext->isDependentContext() || B.builtAll()) &&
  7416. "omp target simd loop exprs were not built");
  7417. if (!CurContext->isDependentContext()) {
  7418. // Finalize the clauses that need pre-built expressions for CodeGen.
  7419. for (OMPClause *C : Clauses) {
  7420. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  7421. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  7422. B.NumIterations, *this, CurScope,
  7423. DSAStack))
  7424. return StmtError();
  7425. }
  7426. }
  7427. if (checkSimdlenSafelenSpecified(*this, Clauses))
  7428. return StmtError();
  7429. setFunctionHasBranchProtectedScope();
  7430. return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
  7431. NestedLoopCount, Clauses, AStmt, B);
  7432. }
  7433. StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
  7434. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  7435. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  7436. if (!AStmt)
  7437. return StmtError();
  7438. auto *CS = cast<CapturedStmt>(AStmt);
  7439. // 1.2.2 OpenMP Language Terminology
  7440. // Structured block - An executable statement with a single entry at the
  7441. // top and a single exit at the bottom.
  7442. // The point of exit cannot be a branch out of the structured block.
  7443. // longjmp() and throw() must not violate the entry/exit criteria.
  7444. CS->getCapturedDecl()->setNothrow();
  7445. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_teams_distribute);
  7446. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  7447. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  7448. // 1.2.2 OpenMP Language Terminology
  7449. // Structured block - An executable statement with a single entry at the
  7450. // top and a single exit at the bottom.
  7451. // The point of exit cannot be a branch out of the structured block.
  7452. // longjmp() and throw() must not violate the entry/exit criteria.
  7453. CS->getCapturedDecl()->setNothrow();
  7454. }
  7455. OMPLoopDirective::HelperExprs B;
  7456. // In presence of clause 'collapse' with number of loops, it will
  7457. // define the nested loops number.
  7458. unsigned NestedLoopCount =
  7459. checkOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
  7460. nullptr /*ordered not a clause on distribute*/, CS, *this,
  7461. *DSAStack, VarsWithImplicitDSA, B);
  7462. if (NestedLoopCount == 0)
  7463. return StmtError();
  7464. assert((CurContext->isDependentContext() || B.builtAll()) &&
  7465. "omp teams distribute loop exprs were not built");
  7466. setFunctionHasBranchProtectedScope();
  7467. DSAStack->setParentTeamsRegionLoc(StartLoc);
  7468. return OMPTeamsDistributeDirective::Create(
  7469. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  7470. }
  7471. StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
  7472. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  7473. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  7474. if (!AStmt)
  7475. return StmtError();
  7476. auto *CS = cast<CapturedStmt>(AStmt);
  7477. // 1.2.2 OpenMP Language Terminology
  7478. // Structured block - An executable statement with a single entry at the
  7479. // top and a single exit at the bottom.
  7480. // The point of exit cannot be a branch out of the structured block.
  7481. // longjmp() and throw() must not violate the entry/exit criteria.
  7482. CS->getCapturedDecl()->setNothrow();
  7483. for (int ThisCaptureLevel =
  7484. getOpenMPCaptureLevels(OMPD_teams_distribute_simd);
  7485. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  7486. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  7487. // 1.2.2 OpenMP Language Terminology
  7488. // Structured block - An executable statement with a single entry at the
  7489. // top and a single exit at the bottom.
  7490. // The point of exit cannot be a branch out of the structured block.
  7491. // longjmp() and throw() must not violate the entry/exit criteria.
  7492. CS->getCapturedDecl()->setNothrow();
  7493. }
  7494. OMPLoopDirective::HelperExprs B;
  7495. // In presence of clause 'collapse' with number of loops, it will
  7496. // define the nested loops number.
  7497. unsigned NestedLoopCount = checkOpenMPLoop(
  7498. OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
  7499. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  7500. VarsWithImplicitDSA, B);
  7501. if (NestedLoopCount == 0)
  7502. return StmtError();
  7503. assert((CurContext->isDependentContext() || B.builtAll()) &&
  7504. "omp teams distribute simd loop exprs were not built");
  7505. if (!CurContext->isDependentContext()) {
  7506. // Finalize the clauses that need pre-built expressions for CodeGen.
  7507. for (OMPClause *C : Clauses) {
  7508. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  7509. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  7510. B.NumIterations, *this, CurScope,
  7511. DSAStack))
  7512. return StmtError();
  7513. }
  7514. }
  7515. if (checkSimdlenSafelenSpecified(*this, Clauses))
  7516. return StmtError();
  7517. setFunctionHasBranchProtectedScope();
  7518. DSAStack->setParentTeamsRegionLoc(StartLoc);
  7519. return OMPTeamsDistributeSimdDirective::Create(
  7520. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  7521. }
  7522. StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
  7523. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  7524. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  7525. if (!AStmt)
  7526. return StmtError();
  7527. auto *CS = cast<CapturedStmt>(AStmt);
  7528. // 1.2.2 OpenMP Language Terminology
  7529. // Structured block - An executable statement with a single entry at the
  7530. // top and a single exit at the bottom.
  7531. // The point of exit cannot be a branch out of the structured block.
  7532. // longjmp() and throw() must not violate the entry/exit criteria.
  7533. CS->getCapturedDecl()->setNothrow();
  7534. for (int ThisCaptureLevel =
  7535. getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for_simd);
  7536. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  7537. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  7538. // 1.2.2 OpenMP Language Terminology
  7539. // Structured block - An executable statement with a single entry at the
  7540. // top and a single exit at the bottom.
  7541. // The point of exit cannot be a branch out of the structured block.
  7542. // longjmp() and throw() must not violate the entry/exit criteria.
  7543. CS->getCapturedDecl()->setNothrow();
  7544. }
  7545. OMPLoopDirective::HelperExprs B;
  7546. // In presence of clause 'collapse' with number of loops, it will
  7547. // define the nested loops number.
  7548. unsigned NestedLoopCount = checkOpenMPLoop(
  7549. OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
  7550. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  7551. VarsWithImplicitDSA, B);
  7552. if (NestedLoopCount == 0)
  7553. return StmtError();
  7554. assert((CurContext->isDependentContext() || B.builtAll()) &&
  7555. "omp for loop exprs were not built");
  7556. if (!CurContext->isDependentContext()) {
  7557. // Finalize the clauses that need pre-built expressions for CodeGen.
  7558. for (OMPClause *C : Clauses) {
  7559. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  7560. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  7561. B.NumIterations, *this, CurScope,
  7562. DSAStack))
  7563. return StmtError();
  7564. }
  7565. }
  7566. if (checkSimdlenSafelenSpecified(*this, Clauses))
  7567. return StmtError();
  7568. setFunctionHasBranchProtectedScope();
  7569. DSAStack->setParentTeamsRegionLoc(StartLoc);
  7570. return OMPTeamsDistributeParallelForSimdDirective::Create(
  7571. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  7572. }
  7573. StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
  7574. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  7575. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  7576. if (!AStmt)
  7577. return StmtError();
  7578. auto *CS = cast<CapturedStmt>(AStmt);
  7579. // 1.2.2 OpenMP Language Terminology
  7580. // Structured block - An executable statement with a single entry at the
  7581. // top and a single exit at the bottom.
  7582. // The point of exit cannot be a branch out of the structured block.
  7583. // longjmp() and throw() must not violate the entry/exit criteria.
  7584. CS->getCapturedDecl()->setNothrow();
  7585. for (int ThisCaptureLevel =
  7586. getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for);
  7587. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  7588. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  7589. // 1.2.2 OpenMP Language Terminology
  7590. // Structured block - An executable statement with a single entry at the
  7591. // top and a single exit at the bottom.
  7592. // The point of exit cannot be a branch out of the structured block.
  7593. // longjmp() and throw() must not violate the entry/exit criteria.
  7594. CS->getCapturedDecl()->setNothrow();
  7595. }
  7596. OMPLoopDirective::HelperExprs B;
  7597. // In presence of clause 'collapse' with number of loops, it will
  7598. // define the nested loops number.
  7599. unsigned NestedLoopCount = checkOpenMPLoop(
  7600. OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
  7601. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  7602. VarsWithImplicitDSA, B);
  7603. if (NestedLoopCount == 0)
  7604. return StmtError();
  7605. assert((CurContext->isDependentContext() || B.builtAll()) &&
  7606. "omp for loop exprs were not built");
  7607. setFunctionHasBranchProtectedScope();
  7608. DSAStack->setParentTeamsRegionLoc(StartLoc);
  7609. return OMPTeamsDistributeParallelForDirective::Create(
  7610. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
  7611. DSAStack->isCancelRegion());
  7612. }
  7613. StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
  7614. Stmt *AStmt,
  7615. SourceLocation StartLoc,
  7616. SourceLocation EndLoc) {
  7617. if (!AStmt)
  7618. return StmtError();
  7619. auto *CS = cast<CapturedStmt>(AStmt);
  7620. // 1.2.2 OpenMP Language Terminology
  7621. // Structured block - An executable statement with a single entry at the
  7622. // top and a single exit at the bottom.
  7623. // The point of exit cannot be a branch out of the structured block.
  7624. // longjmp() and throw() must not violate the entry/exit criteria.
  7625. CS->getCapturedDecl()->setNothrow();
  7626. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_teams);
  7627. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  7628. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  7629. // 1.2.2 OpenMP Language Terminology
  7630. // Structured block - An executable statement with a single entry at the
  7631. // top and a single exit at the bottom.
  7632. // The point of exit cannot be a branch out of the structured block.
  7633. // longjmp() and throw() must not violate the entry/exit criteria.
  7634. CS->getCapturedDecl()->setNothrow();
  7635. }
  7636. setFunctionHasBranchProtectedScope();
  7637. return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
  7638. AStmt);
  7639. }
  7640. StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective(
  7641. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  7642. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  7643. if (!AStmt)
  7644. return StmtError();
  7645. auto *CS = cast<CapturedStmt>(AStmt);
  7646. // 1.2.2 OpenMP Language Terminology
  7647. // Structured block - An executable statement with a single entry at the
  7648. // top and a single exit at the bottom.
  7649. // The point of exit cannot be a branch out of the structured block.
  7650. // longjmp() and throw() must not violate the entry/exit criteria.
  7651. CS->getCapturedDecl()->setNothrow();
  7652. for (int ThisCaptureLevel =
  7653. getOpenMPCaptureLevels(OMPD_target_teams_distribute);
  7654. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  7655. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  7656. // 1.2.2 OpenMP Language Terminology
  7657. // Structured block - An executable statement with a single entry at the
  7658. // top and a single exit at the bottom.
  7659. // The point of exit cannot be a branch out of the structured block.
  7660. // longjmp() and throw() must not violate the entry/exit criteria.
  7661. CS->getCapturedDecl()->setNothrow();
  7662. }
  7663. OMPLoopDirective::HelperExprs B;
  7664. // In presence of clause 'collapse' with number of loops, it will
  7665. // define the nested loops number.
  7666. unsigned NestedLoopCount = checkOpenMPLoop(
  7667. OMPD_target_teams_distribute, getCollapseNumberExpr(Clauses),
  7668. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  7669. VarsWithImplicitDSA, B);
  7670. if (NestedLoopCount == 0)
  7671. return StmtError();
  7672. assert((CurContext->isDependentContext() || B.builtAll()) &&
  7673. "omp target teams distribute loop exprs were not built");
  7674. setFunctionHasBranchProtectedScope();
  7675. return OMPTargetTeamsDistributeDirective::Create(
  7676. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  7677. }
  7678. StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective(
  7679. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  7680. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  7681. if (!AStmt)
  7682. return StmtError();
  7683. auto *CS = cast<CapturedStmt>(AStmt);
  7684. // 1.2.2 OpenMP Language Terminology
  7685. // Structured block - An executable statement with a single entry at the
  7686. // top and a single exit at the bottom.
  7687. // The point of exit cannot be a branch out of the structured block.
  7688. // longjmp() and throw() must not violate the entry/exit criteria.
  7689. CS->getCapturedDecl()->setNothrow();
  7690. for (int ThisCaptureLevel =
  7691. getOpenMPCaptureLevels(OMPD_target_teams_distribute_parallel_for);
  7692. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  7693. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  7694. // 1.2.2 OpenMP Language Terminology
  7695. // Structured block - An executable statement with a single entry at the
  7696. // top and a single exit at the bottom.
  7697. // The point of exit cannot be a branch out of the structured block.
  7698. // longjmp() and throw() must not violate the entry/exit criteria.
  7699. CS->getCapturedDecl()->setNothrow();
  7700. }
  7701. OMPLoopDirective::HelperExprs B;
  7702. // In presence of clause 'collapse' with number of loops, it will
  7703. // define the nested loops number.
  7704. unsigned NestedLoopCount = checkOpenMPLoop(
  7705. OMPD_target_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
  7706. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  7707. VarsWithImplicitDSA, B);
  7708. if (NestedLoopCount == 0)
  7709. return StmtError();
  7710. assert((CurContext->isDependentContext() || B.builtAll()) &&
  7711. "omp target teams distribute parallel for loop exprs were not built");
  7712. if (!CurContext->isDependentContext()) {
  7713. // Finalize the clauses that need pre-built expressions for CodeGen.
  7714. for (OMPClause *C : Clauses) {
  7715. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  7716. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  7717. B.NumIterations, *this, CurScope,
  7718. DSAStack))
  7719. return StmtError();
  7720. }
  7721. }
  7722. setFunctionHasBranchProtectedScope();
  7723. return OMPTargetTeamsDistributeParallelForDirective::Create(
  7724. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
  7725. DSAStack->isCancelRegion());
  7726. }
  7727. StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
  7728. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  7729. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  7730. if (!AStmt)
  7731. return StmtError();
  7732. auto *CS = cast<CapturedStmt>(AStmt);
  7733. // 1.2.2 OpenMP Language Terminology
  7734. // Structured block - An executable statement with a single entry at the
  7735. // top and a single exit at the bottom.
  7736. // The point of exit cannot be a branch out of the structured block.
  7737. // longjmp() and throw() must not violate the entry/exit criteria.
  7738. CS->getCapturedDecl()->setNothrow();
  7739. for (int ThisCaptureLevel = getOpenMPCaptureLevels(
  7740. OMPD_target_teams_distribute_parallel_for_simd);
  7741. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  7742. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  7743. // 1.2.2 OpenMP Language Terminology
  7744. // Structured block - An executable statement with a single entry at the
  7745. // top and a single exit at the bottom.
  7746. // The point of exit cannot be a branch out of the structured block.
  7747. // longjmp() and throw() must not violate the entry/exit criteria.
  7748. CS->getCapturedDecl()->setNothrow();
  7749. }
  7750. OMPLoopDirective::HelperExprs B;
  7751. // In presence of clause 'collapse' with number of loops, it will
  7752. // define the nested loops number.
  7753. unsigned NestedLoopCount =
  7754. checkOpenMPLoop(OMPD_target_teams_distribute_parallel_for_simd,
  7755. getCollapseNumberExpr(Clauses),
  7756. nullptr /*ordered not a clause on distribute*/, CS, *this,
  7757. *DSAStack, VarsWithImplicitDSA, B);
  7758. if (NestedLoopCount == 0)
  7759. return StmtError();
  7760. assert((CurContext->isDependentContext() || B.builtAll()) &&
  7761. "omp target teams distribute parallel for simd loop exprs were not "
  7762. "built");
  7763. if (!CurContext->isDependentContext()) {
  7764. // Finalize the clauses that need pre-built expressions for CodeGen.
  7765. for (OMPClause *C : Clauses) {
  7766. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  7767. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  7768. B.NumIterations, *this, CurScope,
  7769. DSAStack))
  7770. return StmtError();
  7771. }
  7772. }
  7773. if (checkSimdlenSafelenSpecified(*this, Clauses))
  7774. return StmtError();
  7775. setFunctionHasBranchProtectedScope();
  7776. return OMPTargetTeamsDistributeParallelForSimdDirective::Create(
  7777. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  7778. }
  7779. StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective(
  7780. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  7781. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  7782. if (!AStmt)
  7783. return StmtError();
  7784. auto *CS = cast<CapturedStmt>(AStmt);
  7785. // 1.2.2 OpenMP Language Terminology
  7786. // Structured block - An executable statement with a single entry at the
  7787. // top and a single exit at the bottom.
  7788. // The point of exit cannot be a branch out of the structured block.
  7789. // longjmp() and throw() must not violate the entry/exit criteria.
  7790. CS->getCapturedDecl()->setNothrow();
  7791. for (int ThisCaptureLevel =
  7792. getOpenMPCaptureLevels(OMPD_target_teams_distribute_simd);
  7793. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  7794. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  7795. // 1.2.2 OpenMP Language Terminology
  7796. // Structured block - An executable statement with a single entry at the
  7797. // top and a single exit at the bottom.
  7798. // The point of exit cannot be a branch out of the structured block.
  7799. // longjmp() and throw() must not violate the entry/exit criteria.
  7800. CS->getCapturedDecl()->setNothrow();
  7801. }
  7802. OMPLoopDirective::HelperExprs B;
  7803. // In presence of clause 'collapse' with number of loops, it will
  7804. // define the nested loops number.
  7805. unsigned NestedLoopCount = checkOpenMPLoop(
  7806. OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses),
  7807. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  7808. VarsWithImplicitDSA, B);
  7809. if (NestedLoopCount == 0)
  7810. return StmtError();
  7811. assert((CurContext->isDependentContext() || B.builtAll()) &&
  7812. "omp target teams distribute simd loop exprs were not built");
  7813. if (!CurContext->isDependentContext()) {
  7814. // Finalize the clauses that need pre-built expressions for CodeGen.
  7815. for (OMPClause *C : Clauses) {
  7816. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  7817. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  7818. B.NumIterations, *this, CurScope,
  7819. DSAStack))
  7820. return StmtError();
  7821. }
  7822. }
  7823. if (checkSimdlenSafelenSpecified(*this, Clauses))
  7824. return StmtError();
  7825. setFunctionHasBranchProtectedScope();
  7826. return OMPTargetTeamsDistributeSimdDirective::Create(
  7827. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  7828. }
  7829. OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
  7830. SourceLocation StartLoc,
  7831. SourceLocation LParenLoc,
  7832. SourceLocation EndLoc) {
  7833. OMPClause *Res = nullptr;
  7834. switch (Kind) {
  7835. case OMPC_final:
  7836. Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
  7837. break;
  7838. case OMPC_num_threads:
  7839. Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
  7840. break;
  7841. case OMPC_safelen:
  7842. Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
  7843. break;
  7844. case OMPC_simdlen:
  7845. Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
  7846. break;
  7847. case OMPC_allocator:
  7848. Res = ActOnOpenMPAllocatorClause(Expr, StartLoc, LParenLoc, EndLoc);
  7849. break;
  7850. case OMPC_collapse:
  7851. Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
  7852. break;
  7853. case OMPC_ordered:
  7854. Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
  7855. break;
  7856. case OMPC_device:
  7857. Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
  7858. break;
  7859. case OMPC_num_teams:
  7860. Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
  7861. break;
  7862. case OMPC_thread_limit:
  7863. Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
  7864. break;
  7865. case OMPC_priority:
  7866. Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
  7867. break;
  7868. case OMPC_grainsize:
  7869. Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
  7870. break;
  7871. case OMPC_num_tasks:
  7872. Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
  7873. break;
  7874. case OMPC_hint:
  7875. Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
  7876. break;
  7877. case OMPC_if:
  7878. case OMPC_default:
  7879. case OMPC_proc_bind:
  7880. case OMPC_schedule:
  7881. case OMPC_private:
  7882. case OMPC_firstprivate:
  7883. case OMPC_lastprivate:
  7884. case OMPC_shared:
  7885. case OMPC_reduction:
  7886. case OMPC_task_reduction:
  7887. case OMPC_in_reduction:
  7888. case OMPC_linear:
  7889. case OMPC_aligned:
  7890. case OMPC_copyin:
  7891. case OMPC_copyprivate:
  7892. case OMPC_nowait:
  7893. case OMPC_untied:
  7894. case OMPC_mergeable:
  7895. case OMPC_threadprivate:
  7896. case OMPC_allocate:
  7897. case OMPC_flush:
  7898. case OMPC_read:
  7899. case OMPC_write:
  7900. case OMPC_update:
  7901. case OMPC_capture:
  7902. case OMPC_seq_cst:
  7903. case OMPC_depend:
  7904. case OMPC_threads:
  7905. case OMPC_simd:
  7906. case OMPC_map:
  7907. case OMPC_nogroup:
  7908. case OMPC_dist_schedule:
  7909. case OMPC_defaultmap:
  7910. case OMPC_unknown:
  7911. case OMPC_uniform:
  7912. case OMPC_to:
  7913. case OMPC_from:
  7914. case OMPC_use_device_ptr:
  7915. case OMPC_is_device_ptr:
  7916. case OMPC_unified_address:
  7917. case OMPC_unified_shared_memory:
  7918. case OMPC_reverse_offload:
  7919. case OMPC_dynamic_allocators:
  7920. case OMPC_atomic_default_mem_order:
  7921. llvm_unreachable("Clause is not allowed.");
  7922. }
  7923. return Res;
  7924. }
  7925. // An OpenMP directive such as 'target parallel' has two captured regions:
  7926. // for the 'target' and 'parallel' respectively. This function returns
  7927. // the region in which to capture expressions associated with a clause.
  7928. // A return value of OMPD_unknown signifies that the expression should not
  7929. // be captured.
  7930. static OpenMPDirectiveKind getOpenMPCaptureRegionForClause(
  7931. OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
  7932. OpenMPDirectiveKind NameModifier = OMPD_unknown) {
  7933. OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
  7934. switch (CKind) {
  7935. case OMPC_if:
  7936. switch (DKind) {
  7937. case OMPD_target_parallel:
  7938. case OMPD_target_parallel_for:
  7939. case OMPD_target_parallel_for_simd:
  7940. // If this clause applies to the nested 'parallel' region, capture within
  7941. // the 'target' region, otherwise do not capture.
  7942. if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
  7943. CaptureRegion = OMPD_target;
  7944. break;
  7945. case OMPD_target_teams_distribute_parallel_for:
  7946. case OMPD_target_teams_distribute_parallel_for_simd:
  7947. // If this clause applies to the nested 'parallel' region, capture within
  7948. // the 'teams' region, otherwise do not capture.
  7949. if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
  7950. CaptureRegion = OMPD_teams;
  7951. break;
  7952. case OMPD_teams_distribute_parallel_for:
  7953. case OMPD_teams_distribute_parallel_for_simd:
  7954. CaptureRegion = OMPD_teams;
  7955. break;
  7956. case OMPD_target_update:
  7957. case OMPD_target_enter_data:
  7958. case OMPD_target_exit_data:
  7959. CaptureRegion = OMPD_task;
  7960. break;
  7961. case OMPD_cancel:
  7962. case OMPD_parallel:
  7963. case OMPD_parallel_sections:
  7964. case OMPD_parallel_for:
  7965. case OMPD_parallel_for_simd:
  7966. case OMPD_target:
  7967. case OMPD_target_simd:
  7968. case OMPD_target_teams:
  7969. case OMPD_target_teams_distribute:
  7970. case OMPD_target_teams_distribute_simd:
  7971. case OMPD_distribute_parallel_for:
  7972. case OMPD_distribute_parallel_for_simd:
  7973. case OMPD_task:
  7974. case OMPD_taskloop:
  7975. case OMPD_taskloop_simd:
  7976. case OMPD_target_data:
  7977. // Do not capture if-clause expressions.
  7978. break;
  7979. case OMPD_threadprivate:
  7980. case OMPD_allocate:
  7981. case OMPD_taskyield:
  7982. case OMPD_barrier:
  7983. case OMPD_taskwait:
  7984. case OMPD_cancellation_point:
  7985. case OMPD_flush:
  7986. case OMPD_declare_reduction:
  7987. case OMPD_declare_mapper:
  7988. case OMPD_declare_simd:
  7989. case OMPD_declare_target:
  7990. case OMPD_end_declare_target:
  7991. case OMPD_teams:
  7992. case OMPD_simd:
  7993. case OMPD_for:
  7994. case OMPD_for_simd:
  7995. case OMPD_sections:
  7996. case OMPD_section:
  7997. case OMPD_single:
  7998. case OMPD_master:
  7999. case OMPD_critical:
  8000. case OMPD_taskgroup:
  8001. case OMPD_distribute:
  8002. case OMPD_ordered:
  8003. case OMPD_atomic:
  8004. case OMPD_distribute_simd:
  8005. case OMPD_teams_distribute:
  8006. case OMPD_teams_distribute_simd:
  8007. case OMPD_requires:
  8008. llvm_unreachable("Unexpected OpenMP directive with if-clause");
  8009. case OMPD_unknown:
  8010. llvm_unreachable("Unknown OpenMP directive");
  8011. }
  8012. break;
  8013. case OMPC_num_threads:
  8014. switch (DKind) {
  8015. case OMPD_target_parallel:
  8016. case OMPD_target_parallel_for:
  8017. case OMPD_target_parallel_for_simd:
  8018. CaptureRegion = OMPD_target;
  8019. break;
  8020. case OMPD_teams_distribute_parallel_for:
  8021. case OMPD_teams_distribute_parallel_for_simd:
  8022. case OMPD_target_teams_distribute_parallel_for:
  8023. case OMPD_target_teams_distribute_parallel_for_simd:
  8024. CaptureRegion = OMPD_teams;
  8025. break;
  8026. case OMPD_parallel:
  8027. case OMPD_parallel_sections:
  8028. case OMPD_parallel_for:
  8029. case OMPD_parallel_for_simd:
  8030. case OMPD_distribute_parallel_for:
  8031. case OMPD_distribute_parallel_for_simd:
  8032. // Do not capture num_threads-clause expressions.
  8033. break;
  8034. case OMPD_target_data:
  8035. case OMPD_target_enter_data:
  8036. case OMPD_target_exit_data:
  8037. case OMPD_target_update:
  8038. case OMPD_target:
  8039. case OMPD_target_simd:
  8040. case OMPD_target_teams:
  8041. case OMPD_target_teams_distribute:
  8042. case OMPD_target_teams_distribute_simd:
  8043. case OMPD_cancel:
  8044. case OMPD_task:
  8045. case OMPD_taskloop:
  8046. case OMPD_taskloop_simd:
  8047. case OMPD_threadprivate:
  8048. case OMPD_allocate:
  8049. case OMPD_taskyield:
  8050. case OMPD_barrier:
  8051. case OMPD_taskwait:
  8052. case OMPD_cancellation_point:
  8053. case OMPD_flush:
  8054. case OMPD_declare_reduction:
  8055. case OMPD_declare_mapper:
  8056. case OMPD_declare_simd:
  8057. case OMPD_declare_target:
  8058. case OMPD_end_declare_target:
  8059. case OMPD_teams:
  8060. case OMPD_simd:
  8061. case OMPD_for:
  8062. case OMPD_for_simd:
  8063. case OMPD_sections:
  8064. case OMPD_section:
  8065. case OMPD_single:
  8066. case OMPD_master:
  8067. case OMPD_critical:
  8068. case OMPD_taskgroup:
  8069. case OMPD_distribute:
  8070. case OMPD_ordered:
  8071. case OMPD_atomic:
  8072. case OMPD_distribute_simd:
  8073. case OMPD_teams_distribute:
  8074. case OMPD_teams_distribute_simd:
  8075. case OMPD_requires:
  8076. llvm_unreachable("Unexpected OpenMP directive with num_threads-clause");
  8077. case OMPD_unknown:
  8078. llvm_unreachable("Unknown OpenMP directive");
  8079. }
  8080. break;
  8081. case OMPC_num_teams:
  8082. switch (DKind) {
  8083. case OMPD_target_teams:
  8084. case OMPD_target_teams_distribute:
  8085. case OMPD_target_teams_distribute_simd:
  8086. case OMPD_target_teams_distribute_parallel_for:
  8087. case OMPD_target_teams_distribute_parallel_for_simd:
  8088. CaptureRegion = OMPD_target;
  8089. break;
  8090. case OMPD_teams_distribute_parallel_for:
  8091. case OMPD_teams_distribute_parallel_for_simd:
  8092. case OMPD_teams:
  8093. case OMPD_teams_distribute:
  8094. case OMPD_teams_distribute_simd:
  8095. // Do not capture num_teams-clause expressions.
  8096. break;
  8097. case OMPD_distribute_parallel_for:
  8098. case OMPD_distribute_parallel_for_simd:
  8099. case OMPD_task:
  8100. case OMPD_taskloop:
  8101. case OMPD_taskloop_simd:
  8102. case OMPD_target_data:
  8103. case OMPD_target_enter_data:
  8104. case OMPD_target_exit_data:
  8105. case OMPD_target_update:
  8106. case OMPD_cancel:
  8107. case OMPD_parallel:
  8108. case OMPD_parallel_sections:
  8109. case OMPD_parallel_for:
  8110. case OMPD_parallel_for_simd:
  8111. case OMPD_target:
  8112. case OMPD_target_simd:
  8113. case OMPD_target_parallel:
  8114. case OMPD_target_parallel_for:
  8115. case OMPD_target_parallel_for_simd:
  8116. case OMPD_threadprivate:
  8117. case OMPD_allocate:
  8118. case OMPD_taskyield:
  8119. case OMPD_barrier:
  8120. case OMPD_taskwait:
  8121. case OMPD_cancellation_point:
  8122. case OMPD_flush:
  8123. case OMPD_declare_reduction:
  8124. case OMPD_declare_mapper:
  8125. case OMPD_declare_simd:
  8126. case OMPD_declare_target:
  8127. case OMPD_end_declare_target:
  8128. case OMPD_simd:
  8129. case OMPD_for:
  8130. case OMPD_for_simd:
  8131. case OMPD_sections:
  8132. case OMPD_section:
  8133. case OMPD_single:
  8134. case OMPD_master:
  8135. case OMPD_critical:
  8136. case OMPD_taskgroup:
  8137. case OMPD_distribute:
  8138. case OMPD_ordered:
  8139. case OMPD_atomic:
  8140. case OMPD_distribute_simd:
  8141. case OMPD_requires:
  8142. llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
  8143. case OMPD_unknown:
  8144. llvm_unreachable("Unknown OpenMP directive");
  8145. }
  8146. break;
  8147. case OMPC_thread_limit:
  8148. switch (DKind) {
  8149. case OMPD_target_teams:
  8150. case OMPD_target_teams_distribute:
  8151. case OMPD_target_teams_distribute_simd:
  8152. case OMPD_target_teams_distribute_parallel_for:
  8153. case OMPD_target_teams_distribute_parallel_for_simd:
  8154. CaptureRegion = OMPD_target;
  8155. break;
  8156. case OMPD_teams_distribute_parallel_for:
  8157. case OMPD_teams_distribute_parallel_for_simd:
  8158. case OMPD_teams:
  8159. case OMPD_teams_distribute:
  8160. case OMPD_teams_distribute_simd:
  8161. // Do not capture thread_limit-clause expressions.
  8162. break;
  8163. case OMPD_distribute_parallel_for:
  8164. case OMPD_distribute_parallel_for_simd:
  8165. case OMPD_task:
  8166. case OMPD_taskloop:
  8167. case OMPD_taskloop_simd:
  8168. case OMPD_target_data:
  8169. case OMPD_target_enter_data:
  8170. case OMPD_target_exit_data:
  8171. case OMPD_target_update:
  8172. case OMPD_cancel:
  8173. case OMPD_parallel:
  8174. case OMPD_parallel_sections:
  8175. case OMPD_parallel_for:
  8176. case OMPD_parallel_for_simd:
  8177. case OMPD_target:
  8178. case OMPD_target_simd:
  8179. case OMPD_target_parallel:
  8180. case OMPD_target_parallel_for:
  8181. case OMPD_target_parallel_for_simd:
  8182. case OMPD_threadprivate:
  8183. case OMPD_allocate:
  8184. case OMPD_taskyield:
  8185. case OMPD_barrier:
  8186. case OMPD_taskwait:
  8187. case OMPD_cancellation_point:
  8188. case OMPD_flush:
  8189. case OMPD_declare_reduction:
  8190. case OMPD_declare_mapper:
  8191. case OMPD_declare_simd:
  8192. case OMPD_declare_target:
  8193. case OMPD_end_declare_target:
  8194. case OMPD_simd:
  8195. case OMPD_for:
  8196. case OMPD_for_simd:
  8197. case OMPD_sections:
  8198. case OMPD_section:
  8199. case OMPD_single:
  8200. case OMPD_master:
  8201. case OMPD_critical:
  8202. case OMPD_taskgroup:
  8203. case OMPD_distribute:
  8204. case OMPD_ordered:
  8205. case OMPD_atomic:
  8206. case OMPD_distribute_simd:
  8207. case OMPD_requires:
  8208. llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause");
  8209. case OMPD_unknown:
  8210. llvm_unreachable("Unknown OpenMP directive");
  8211. }
  8212. break;
  8213. case OMPC_schedule:
  8214. switch (DKind) {
  8215. case OMPD_parallel_for:
  8216. case OMPD_parallel_for_simd:
  8217. case OMPD_distribute_parallel_for:
  8218. case OMPD_distribute_parallel_for_simd:
  8219. case OMPD_teams_distribute_parallel_for:
  8220. case OMPD_teams_distribute_parallel_for_simd:
  8221. case OMPD_target_parallel_for:
  8222. case OMPD_target_parallel_for_simd:
  8223. case OMPD_target_teams_distribute_parallel_for:
  8224. case OMPD_target_teams_distribute_parallel_for_simd:
  8225. CaptureRegion = OMPD_parallel;
  8226. break;
  8227. case OMPD_for:
  8228. case OMPD_for_simd:
  8229. // Do not capture schedule-clause expressions.
  8230. break;
  8231. case OMPD_task:
  8232. case OMPD_taskloop:
  8233. case OMPD_taskloop_simd:
  8234. case OMPD_target_data:
  8235. case OMPD_target_enter_data:
  8236. case OMPD_target_exit_data:
  8237. case OMPD_target_update:
  8238. case OMPD_teams:
  8239. case OMPD_teams_distribute:
  8240. case OMPD_teams_distribute_simd:
  8241. case OMPD_target_teams_distribute:
  8242. case OMPD_target_teams_distribute_simd:
  8243. case OMPD_target:
  8244. case OMPD_target_simd:
  8245. case OMPD_target_parallel:
  8246. case OMPD_cancel:
  8247. case OMPD_parallel:
  8248. case OMPD_parallel_sections:
  8249. case OMPD_threadprivate:
  8250. case OMPD_allocate:
  8251. case OMPD_taskyield:
  8252. case OMPD_barrier:
  8253. case OMPD_taskwait:
  8254. case OMPD_cancellation_point:
  8255. case OMPD_flush:
  8256. case OMPD_declare_reduction:
  8257. case OMPD_declare_mapper:
  8258. case OMPD_declare_simd:
  8259. case OMPD_declare_target:
  8260. case OMPD_end_declare_target:
  8261. case OMPD_simd:
  8262. case OMPD_sections:
  8263. case OMPD_section:
  8264. case OMPD_single:
  8265. case OMPD_master:
  8266. case OMPD_critical:
  8267. case OMPD_taskgroup:
  8268. case OMPD_distribute:
  8269. case OMPD_ordered:
  8270. case OMPD_atomic:
  8271. case OMPD_distribute_simd:
  8272. case OMPD_target_teams:
  8273. case OMPD_requires:
  8274. llvm_unreachable("Unexpected OpenMP directive with schedule clause");
  8275. case OMPD_unknown:
  8276. llvm_unreachable("Unknown OpenMP directive");
  8277. }
  8278. break;
  8279. case OMPC_dist_schedule:
  8280. switch (DKind) {
  8281. case OMPD_teams_distribute_parallel_for:
  8282. case OMPD_teams_distribute_parallel_for_simd:
  8283. case OMPD_teams_distribute:
  8284. case OMPD_teams_distribute_simd:
  8285. case OMPD_target_teams_distribute_parallel_for:
  8286. case OMPD_target_teams_distribute_parallel_for_simd:
  8287. case OMPD_target_teams_distribute:
  8288. case OMPD_target_teams_distribute_simd:
  8289. CaptureRegion = OMPD_teams;
  8290. break;
  8291. case OMPD_distribute_parallel_for:
  8292. case OMPD_distribute_parallel_for_simd:
  8293. case OMPD_distribute:
  8294. case OMPD_distribute_simd:
  8295. // Do not capture thread_limit-clause expressions.
  8296. break;
  8297. case OMPD_parallel_for:
  8298. case OMPD_parallel_for_simd:
  8299. case OMPD_target_parallel_for_simd:
  8300. case OMPD_target_parallel_for:
  8301. case OMPD_task:
  8302. case OMPD_taskloop:
  8303. case OMPD_taskloop_simd:
  8304. case OMPD_target_data:
  8305. case OMPD_target_enter_data:
  8306. case OMPD_target_exit_data:
  8307. case OMPD_target_update:
  8308. case OMPD_teams:
  8309. case OMPD_target:
  8310. case OMPD_target_simd:
  8311. case OMPD_target_parallel:
  8312. case OMPD_cancel:
  8313. case OMPD_parallel:
  8314. case OMPD_parallel_sections:
  8315. case OMPD_threadprivate:
  8316. case OMPD_allocate:
  8317. case OMPD_taskyield:
  8318. case OMPD_barrier:
  8319. case OMPD_taskwait:
  8320. case OMPD_cancellation_point:
  8321. case OMPD_flush:
  8322. case OMPD_declare_reduction:
  8323. case OMPD_declare_mapper:
  8324. case OMPD_declare_simd:
  8325. case OMPD_declare_target:
  8326. case OMPD_end_declare_target:
  8327. case OMPD_simd:
  8328. case OMPD_for:
  8329. case OMPD_for_simd:
  8330. case OMPD_sections:
  8331. case OMPD_section:
  8332. case OMPD_single:
  8333. case OMPD_master:
  8334. case OMPD_critical:
  8335. case OMPD_taskgroup:
  8336. case OMPD_ordered:
  8337. case OMPD_atomic:
  8338. case OMPD_target_teams:
  8339. case OMPD_requires:
  8340. llvm_unreachable("Unexpected OpenMP directive with schedule clause");
  8341. case OMPD_unknown:
  8342. llvm_unreachable("Unknown OpenMP directive");
  8343. }
  8344. break;
  8345. case OMPC_device:
  8346. switch (DKind) {
  8347. case OMPD_target_update:
  8348. case OMPD_target_enter_data:
  8349. case OMPD_target_exit_data:
  8350. case OMPD_target:
  8351. case OMPD_target_simd:
  8352. case OMPD_target_teams:
  8353. case OMPD_target_parallel:
  8354. case OMPD_target_teams_distribute:
  8355. case OMPD_target_teams_distribute_simd:
  8356. case OMPD_target_parallel_for:
  8357. case OMPD_target_parallel_for_simd:
  8358. case OMPD_target_teams_distribute_parallel_for:
  8359. case OMPD_target_teams_distribute_parallel_for_simd:
  8360. CaptureRegion = OMPD_task;
  8361. break;
  8362. case OMPD_target_data:
  8363. // Do not capture device-clause expressions.
  8364. break;
  8365. case OMPD_teams_distribute_parallel_for:
  8366. case OMPD_teams_distribute_parallel_for_simd:
  8367. case OMPD_teams:
  8368. case OMPD_teams_distribute:
  8369. case OMPD_teams_distribute_simd:
  8370. case OMPD_distribute_parallel_for:
  8371. case OMPD_distribute_parallel_for_simd:
  8372. case OMPD_task:
  8373. case OMPD_taskloop:
  8374. case OMPD_taskloop_simd:
  8375. case OMPD_cancel:
  8376. case OMPD_parallel:
  8377. case OMPD_parallel_sections:
  8378. case OMPD_parallel_for:
  8379. case OMPD_parallel_for_simd:
  8380. case OMPD_threadprivate:
  8381. case OMPD_allocate:
  8382. case OMPD_taskyield:
  8383. case OMPD_barrier:
  8384. case OMPD_taskwait:
  8385. case OMPD_cancellation_point:
  8386. case OMPD_flush:
  8387. case OMPD_declare_reduction:
  8388. case OMPD_declare_mapper:
  8389. case OMPD_declare_simd:
  8390. case OMPD_declare_target:
  8391. case OMPD_end_declare_target:
  8392. case OMPD_simd:
  8393. case OMPD_for:
  8394. case OMPD_for_simd:
  8395. case OMPD_sections:
  8396. case OMPD_section:
  8397. case OMPD_single:
  8398. case OMPD_master:
  8399. case OMPD_critical:
  8400. case OMPD_taskgroup:
  8401. case OMPD_distribute:
  8402. case OMPD_ordered:
  8403. case OMPD_atomic:
  8404. case OMPD_distribute_simd:
  8405. case OMPD_requires:
  8406. llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
  8407. case OMPD_unknown:
  8408. llvm_unreachable("Unknown OpenMP directive");
  8409. }
  8410. break;
  8411. case OMPC_firstprivate:
  8412. case OMPC_lastprivate:
  8413. case OMPC_reduction:
  8414. case OMPC_task_reduction:
  8415. case OMPC_in_reduction:
  8416. case OMPC_linear:
  8417. case OMPC_default:
  8418. case OMPC_proc_bind:
  8419. case OMPC_final:
  8420. case OMPC_safelen:
  8421. case OMPC_simdlen:
  8422. case OMPC_allocator:
  8423. case OMPC_collapse:
  8424. case OMPC_private:
  8425. case OMPC_shared:
  8426. case OMPC_aligned:
  8427. case OMPC_copyin:
  8428. case OMPC_copyprivate:
  8429. case OMPC_ordered:
  8430. case OMPC_nowait:
  8431. case OMPC_untied:
  8432. case OMPC_mergeable:
  8433. case OMPC_threadprivate:
  8434. case OMPC_allocate:
  8435. case OMPC_flush:
  8436. case OMPC_read:
  8437. case OMPC_write:
  8438. case OMPC_update:
  8439. case OMPC_capture:
  8440. case OMPC_seq_cst:
  8441. case OMPC_depend:
  8442. case OMPC_threads:
  8443. case OMPC_simd:
  8444. case OMPC_map:
  8445. case OMPC_priority:
  8446. case OMPC_grainsize:
  8447. case OMPC_nogroup:
  8448. case OMPC_num_tasks:
  8449. case OMPC_hint:
  8450. case OMPC_defaultmap:
  8451. case OMPC_unknown:
  8452. case OMPC_uniform:
  8453. case OMPC_to:
  8454. case OMPC_from:
  8455. case OMPC_use_device_ptr:
  8456. case OMPC_is_device_ptr:
  8457. case OMPC_unified_address:
  8458. case OMPC_unified_shared_memory:
  8459. case OMPC_reverse_offload:
  8460. case OMPC_dynamic_allocators:
  8461. case OMPC_atomic_default_mem_order:
  8462. llvm_unreachable("Unexpected OpenMP clause.");
  8463. }
  8464. return CaptureRegion;
  8465. }
  8466. OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
  8467. Expr *Condition, SourceLocation StartLoc,
  8468. SourceLocation LParenLoc,
  8469. SourceLocation NameModifierLoc,
  8470. SourceLocation ColonLoc,
  8471. SourceLocation EndLoc) {
  8472. Expr *ValExpr = Condition;
  8473. Stmt *HelperValStmt = nullptr;
  8474. OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
  8475. if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
  8476. !Condition->isInstantiationDependent() &&
  8477. !Condition->containsUnexpandedParameterPack()) {
  8478. ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
  8479. if (Val.isInvalid())
  8480. return nullptr;
  8481. ValExpr = Val.get();
  8482. OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
  8483. CaptureRegion =
  8484. getOpenMPCaptureRegionForClause(DKind, OMPC_if, NameModifier);
  8485. if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
  8486. ValExpr = MakeFullExpr(ValExpr).get();
  8487. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  8488. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  8489. HelperValStmt = buildPreInits(Context, Captures);
  8490. }
  8491. }
  8492. return new (Context)
  8493. OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
  8494. LParenLoc, NameModifierLoc, ColonLoc, EndLoc);
  8495. }
  8496. OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
  8497. SourceLocation StartLoc,
  8498. SourceLocation LParenLoc,
  8499. SourceLocation EndLoc) {
  8500. Expr *ValExpr = Condition;
  8501. if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
  8502. !Condition->isInstantiationDependent() &&
  8503. !Condition->containsUnexpandedParameterPack()) {
  8504. ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
  8505. if (Val.isInvalid())
  8506. return nullptr;
  8507. ValExpr = MakeFullExpr(Val.get()).get();
  8508. }
  8509. return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
  8510. }
  8511. ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
  8512. Expr *Op) {
  8513. if (!Op)
  8514. return ExprError();
  8515. class IntConvertDiagnoser : public ICEConvertDiagnoser {
  8516. public:
  8517. IntConvertDiagnoser()
  8518. : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
  8519. SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
  8520. QualType T) override {
  8521. return S.Diag(Loc, diag::err_omp_not_integral) << T;
  8522. }
  8523. SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
  8524. QualType T) override {
  8525. return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
  8526. }
  8527. SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
  8528. QualType T,
  8529. QualType ConvTy) override {
  8530. return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
  8531. }
  8532. SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
  8533. QualType ConvTy) override {
  8534. return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
  8535. << ConvTy->isEnumeralType() << ConvTy;
  8536. }
  8537. SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
  8538. QualType T) override {
  8539. return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
  8540. }
  8541. SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
  8542. QualType ConvTy) override {
  8543. return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
  8544. << ConvTy->isEnumeralType() << ConvTy;
  8545. }
  8546. SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
  8547. QualType) override {
  8548. llvm_unreachable("conversion functions are permitted");
  8549. }
  8550. } ConvertDiagnoser;
  8551. return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
  8552. }
  8553. static bool isNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef,
  8554. OpenMPClauseKind CKind,
  8555. bool StrictlyPositive) {
  8556. if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
  8557. !ValExpr->isInstantiationDependent()) {
  8558. SourceLocation Loc = ValExpr->getExprLoc();
  8559. ExprResult Value =
  8560. SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
  8561. if (Value.isInvalid())
  8562. return false;
  8563. ValExpr = Value.get();
  8564. // The expression must evaluate to a non-negative integer value.
  8565. llvm::APSInt Result;
  8566. if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
  8567. Result.isSigned() &&
  8568. !((!StrictlyPositive && Result.isNonNegative()) ||
  8569. (StrictlyPositive && Result.isStrictlyPositive()))) {
  8570. SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
  8571. << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
  8572. << ValExpr->getSourceRange();
  8573. return false;
  8574. }
  8575. }
  8576. return true;
  8577. }
  8578. OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
  8579. SourceLocation StartLoc,
  8580. SourceLocation LParenLoc,
  8581. SourceLocation EndLoc) {
  8582. Expr *ValExpr = NumThreads;
  8583. Stmt *HelperValStmt = nullptr;
  8584. // OpenMP [2.5, Restrictions]
  8585. // The num_threads expression must evaluate to a positive integer value.
  8586. if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
  8587. /*StrictlyPositive=*/true))
  8588. return nullptr;
  8589. OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
  8590. OpenMPDirectiveKind CaptureRegion =
  8591. getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads);
  8592. if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
  8593. ValExpr = MakeFullExpr(ValExpr).get();
  8594. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  8595. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  8596. HelperValStmt = buildPreInits(Context, Captures);
  8597. }
  8598. return new (Context) OMPNumThreadsClause(
  8599. ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
  8600. }
  8601. ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
  8602. OpenMPClauseKind CKind,
  8603. bool StrictlyPositive) {
  8604. if (!E)
  8605. return ExprError();
  8606. if (E->isValueDependent() || E->isTypeDependent() ||
  8607. E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
  8608. return E;
  8609. llvm::APSInt Result;
  8610. ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
  8611. if (ICE.isInvalid())
  8612. return ExprError();
  8613. if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
  8614. (!StrictlyPositive && !Result.isNonNegative())) {
  8615. Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
  8616. << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
  8617. << E->getSourceRange();
  8618. return ExprError();
  8619. }
  8620. if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
  8621. Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
  8622. << E->getSourceRange();
  8623. return ExprError();
  8624. }
  8625. if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
  8626. DSAStack->setAssociatedLoops(Result.getExtValue());
  8627. else if (CKind == OMPC_ordered)
  8628. DSAStack->setAssociatedLoops(Result.getExtValue());
  8629. return ICE;
  8630. }
  8631. OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
  8632. SourceLocation LParenLoc,
  8633. SourceLocation EndLoc) {
  8634. // OpenMP [2.8.1, simd construct, Description]
  8635. // The parameter of the safelen clause must be a constant
  8636. // positive integer expression.
  8637. ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
  8638. if (Safelen.isInvalid())
  8639. return nullptr;
  8640. return new (Context)
  8641. OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
  8642. }
  8643. OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
  8644. SourceLocation LParenLoc,
  8645. SourceLocation EndLoc) {
  8646. // OpenMP [2.8.1, simd construct, Description]
  8647. // The parameter of the simdlen clause must be a constant
  8648. // positive integer expression.
  8649. ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
  8650. if (Simdlen.isInvalid())
  8651. return nullptr;
  8652. return new (Context)
  8653. OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
  8654. }
  8655. /// Tries to find omp_allocator_handle_t type.
  8656. static bool FindOMPAllocatorHandleT(Sema &S, SourceLocation Loc,
  8657. QualType &OMPAllocatorHandleT) {
  8658. if (!OMPAllocatorHandleT.isNull())
  8659. return true;
  8660. DeclarationName OMPAllocatorHandleTName =
  8661. &S.getASTContext().Idents.get("omp_allocator_handle_t");
  8662. auto *TD = dyn_cast_or_null<TypeDecl>(S.LookupSingleName(
  8663. S.TUScope, OMPAllocatorHandleTName, Loc, Sema::LookupAnyName));
  8664. if (!TD) {
  8665. S.Diag(Loc, diag::err_implied_omp_allocator_handle_t_not_found);
  8666. return false;
  8667. }
  8668. OMPAllocatorHandleT = S.getASTContext().getTypeDeclType(TD);
  8669. return true;
  8670. }
  8671. OMPClause *Sema::ActOnOpenMPAllocatorClause(Expr *A, SourceLocation StartLoc,
  8672. SourceLocation LParenLoc,
  8673. SourceLocation EndLoc) {
  8674. // OpenMP [2.11.3, allocate Directive, Description]
  8675. // allocator is an expression of omp_allocator_handle_t type.
  8676. if (!FindOMPAllocatorHandleT(*this, A->getExprLoc(), OMPAllocatorHandleT))
  8677. return nullptr;
  8678. ExprResult Allocator = DefaultLvalueConversion(A);
  8679. if (Allocator.isInvalid())
  8680. return nullptr;
  8681. Allocator = PerformImplicitConversion(Allocator.get(), OMPAllocatorHandleT,
  8682. Sema::AA_Initializing,
  8683. /*AllowExplicit=*/true);
  8684. if (Allocator.isInvalid())
  8685. return nullptr;
  8686. return new (Context)
  8687. OMPAllocatorClause(Allocator.get(), StartLoc, LParenLoc, EndLoc);
  8688. }
  8689. OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
  8690. SourceLocation StartLoc,
  8691. SourceLocation LParenLoc,
  8692. SourceLocation EndLoc) {
  8693. // OpenMP [2.7.1, loop construct, Description]
  8694. // OpenMP [2.8.1, simd construct, Description]
  8695. // OpenMP [2.9.6, distribute construct, Description]
  8696. // The parameter of the collapse clause must be a constant
  8697. // positive integer expression.
  8698. ExprResult NumForLoopsResult =
  8699. VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
  8700. if (NumForLoopsResult.isInvalid())
  8701. return nullptr;
  8702. return new (Context)
  8703. OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
  8704. }
  8705. OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
  8706. SourceLocation EndLoc,
  8707. SourceLocation LParenLoc,
  8708. Expr *NumForLoops) {
  8709. // OpenMP [2.7.1, loop construct, Description]
  8710. // OpenMP [2.8.1, simd construct, Description]
  8711. // OpenMP [2.9.6, distribute construct, Description]
  8712. // The parameter of the ordered clause must be a constant
  8713. // positive integer expression if any.
  8714. if (NumForLoops && LParenLoc.isValid()) {
  8715. ExprResult NumForLoopsResult =
  8716. VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
  8717. if (NumForLoopsResult.isInvalid())
  8718. return nullptr;
  8719. NumForLoops = NumForLoopsResult.get();
  8720. } else {
  8721. NumForLoops = nullptr;
  8722. }
  8723. auto *Clause = OMPOrderedClause::Create(
  8724. Context, NumForLoops, NumForLoops ? DSAStack->getAssociatedLoops() : 0,
  8725. StartLoc, LParenLoc, EndLoc);
  8726. DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops, Clause);
  8727. return Clause;
  8728. }
  8729. OMPClause *Sema::ActOnOpenMPSimpleClause(
  8730. OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
  8731. SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
  8732. OMPClause *Res = nullptr;
  8733. switch (Kind) {
  8734. case OMPC_default:
  8735. Res =
  8736. ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
  8737. ArgumentLoc, StartLoc, LParenLoc, EndLoc);
  8738. break;
  8739. case OMPC_proc_bind:
  8740. Res = ActOnOpenMPProcBindClause(
  8741. static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
  8742. LParenLoc, EndLoc);
  8743. break;
  8744. case OMPC_atomic_default_mem_order:
  8745. Res = ActOnOpenMPAtomicDefaultMemOrderClause(
  8746. static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Argument),
  8747. ArgumentLoc, StartLoc, LParenLoc, EndLoc);
  8748. break;
  8749. case OMPC_if:
  8750. case OMPC_final:
  8751. case OMPC_num_threads:
  8752. case OMPC_safelen:
  8753. case OMPC_simdlen:
  8754. case OMPC_allocator:
  8755. case OMPC_collapse:
  8756. case OMPC_schedule:
  8757. case OMPC_private:
  8758. case OMPC_firstprivate:
  8759. case OMPC_lastprivate:
  8760. case OMPC_shared:
  8761. case OMPC_reduction:
  8762. case OMPC_task_reduction:
  8763. case OMPC_in_reduction:
  8764. case OMPC_linear:
  8765. case OMPC_aligned:
  8766. case OMPC_copyin:
  8767. case OMPC_copyprivate:
  8768. case OMPC_ordered:
  8769. case OMPC_nowait:
  8770. case OMPC_untied:
  8771. case OMPC_mergeable:
  8772. case OMPC_threadprivate:
  8773. case OMPC_allocate:
  8774. case OMPC_flush:
  8775. case OMPC_read:
  8776. case OMPC_write:
  8777. case OMPC_update:
  8778. case OMPC_capture:
  8779. case OMPC_seq_cst:
  8780. case OMPC_depend:
  8781. case OMPC_device:
  8782. case OMPC_threads:
  8783. case OMPC_simd:
  8784. case OMPC_map:
  8785. case OMPC_num_teams:
  8786. case OMPC_thread_limit:
  8787. case OMPC_priority:
  8788. case OMPC_grainsize:
  8789. case OMPC_nogroup:
  8790. case OMPC_num_tasks:
  8791. case OMPC_hint:
  8792. case OMPC_dist_schedule:
  8793. case OMPC_defaultmap:
  8794. case OMPC_unknown:
  8795. case OMPC_uniform:
  8796. case OMPC_to:
  8797. case OMPC_from:
  8798. case OMPC_use_device_ptr:
  8799. case OMPC_is_device_ptr:
  8800. case OMPC_unified_address:
  8801. case OMPC_unified_shared_memory:
  8802. case OMPC_reverse_offload:
  8803. case OMPC_dynamic_allocators:
  8804. llvm_unreachable("Clause is not allowed.");
  8805. }
  8806. return Res;
  8807. }
  8808. static std::string
  8809. getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
  8810. ArrayRef<unsigned> Exclude = llvm::None) {
  8811. SmallString<256> Buffer;
  8812. llvm::raw_svector_ostream Out(Buffer);
  8813. unsigned Bound = Last >= 2 ? Last - 2 : 0;
  8814. unsigned Skipped = Exclude.size();
  8815. auto S = Exclude.begin(), E = Exclude.end();
  8816. for (unsigned I = First; I < Last; ++I) {
  8817. if (std::find(S, E, I) != E) {
  8818. --Skipped;
  8819. continue;
  8820. }
  8821. Out << "'" << getOpenMPSimpleClauseTypeName(K, I) << "'";
  8822. if (I == Bound - Skipped)
  8823. Out << " or ";
  8824. else if (I != Bound + 1 - Skipped)
  8825. Out << ", ";
  8826. }
  8827. return Out.str();
  8828. }
  8829. OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
  8830. SourceLocation KindKwLoc,
  8831. SourceLocation StartLoc,
  8832. SourceLocation LParenLoc,
  8833. SourceLocation EndLoc) {
  8834. if (Kind == OMPC_DEFAULT_unknown) {
  8835. static_assert(OMPC_DEFAULT_unknown > 0,
  8836. "OMPC_DEFAULT_unknown not greater than 0");
  8837. Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
  8838. << getListOfPossibleValues(OMPC_default, /*First=*/0,
  8839. /*Last=*/OMPC_DEFAULT_unknown)
  8840. << getOpenMPClauseName(OMPC_default);
  8841. return nullptr;
  8842. }
  8843. switch (Kind) {
  8844. case OMPC_DEFAULT_none:
  8845. DSAStack->setDefaultDSANone(KindKwLoc);
  8846. break;
  8847. case OMPC_DEFAULT_shared:
  8848. DSAStack->setDefaultDSAShared(KindKwLoc);
  8849. break;
  8850. case OMPC_DEFAULT_unknown:
  8851. llvm_unreachable("Clause kind is not allowed.");
  8852. break;
  8853. }
  8854. return new (Context)
  8855. OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
  8856. }
  8857. OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
  8858. SourceLocation KindKwLoc,
  8859. SourceLocation StartLoc,
  8860. SourceLocation LParenLoc,
  8861. SourceLocation EndLoc) {
  8862. if (Kind == OMPC_PROC_BIND_unknown) {
  8863. Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
  8864. << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0,
  8865. /*Last=*/OMPC_PROC_BIND_unknown)
  8866. << getOpenMPClauseName(OMPC_proc_bind);
  8867. return nullptr;
  8868. }
  8869. return new (Context)
  8870. OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
  8871. }
  8872. OMPClause *Sema::ActOnOpenMPAtomicDefaultMemOrderClause(
  8873. OpenMPAtomicDefaultMemOrderClauseKind Kind, SourceLocation KindKwLoc,
  8874. SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
  8875. if (Kind == OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown) {
  8876. Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
  8877. << getListOfPossibleValues(
  8878. OMPC_atomic_default_mem_order, /*First=*/0,
  8879. /*Last=*/OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown)
  8880. << getOpenMPClauseName(OMPC_atomic_default_mem_order);
  8881. return nullptr;
  8882. }
  8883. return new (Context) OMPAtomicDefaultMemOrderClause(Kind, KindKwLoc, StartLoc,
  8884. LParenLoc, EndLoc);
  8885. }
  8886. OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
  8887. OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
  8888. SourceLocation StartLoc, SourceLocation LParenLoc,
  8889. ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
  8890. SourceLocation EndLoc) {
  8891. OMPClause *Res = nullptr;
  8892. switch (Kind) {
  8893. case OMPC_schedule:
  8894. enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
  8895. assert(Argument.size() == NumberOfElements &&
  8896. ArgumentLoc.size() == NumberOfElements);
  8897. Res = ActOnOpenMPScheduleClause(
  8898. static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
  8899. static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
  8900. static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
  8901. StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
  8902. ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
  8903. break;
  8904. case OMPC_if:
  8905. assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
  8906. Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
  8907. Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
  8908. DelimLoc, EndLoc);
  8909. break;
  8910. case OMPC_dist_schedule:
  8911. Res = ActOnOpenMPDistScheduleClause(
  8912. static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
  8913. StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
  8914. break;
  8915. case OMPC_defaultmap:
  8916. enum { Modifier, DefaultmapKind };
  8917. Res = ActOnOpenMPDefaultmapClause(
  8918. static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
  8919. static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
  8920. StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
  8921. EndLoc);
  8922. break;
  8923. case OMPC_final:
  8924. case OMPC_num_threads:
  8925. case OMPC_safelen:
  8926. case OMPC_simdlen:
  8927. case OMPC_allocator:
  8928. case OMPC_collapse:
  8929. case OMPC_default:
  8930. case OMPC_proc_bind:
  8931. case OMPC_private:
  8932. case OMPC_firstprivate:
  8933. case OMPC_lastprivate:
  8934. case OMPC_shared:
  8935. case OMPC_reduction:
  8936. case OMPC_task_reduction:
  8937. case OMPC_in_reduction:
  8938. case OMPC_linear:
  8939. case OMPC_aligned:
  8940. case OMPC_copyin:
  8941. case OMPC_copyprivate:
  8942. case OMPC_ordered:
  8943. case OMPC_nowait:
  8944. case OMPC_untied:
  8945. case OMPC_mergeable:
  8946. case OMPC_threadprivate:
  8947. case OMPC_allocate:
  8948. case OMPC_flush:
  8949. case OMPC_read:
  8950. case OMPC_write:
  8951. case OMPC_update:
  8952. case OMPC_capture:
  8953. case OMPC_seq_cst:
  8954. case OMPC_depend:
  8955. case OMPC_device:
  8956. case OMPC_threads:
  8957. case OMPC_simd:
  8958. case OMPC_map:
  8959. case OMPC_num_teams:
  8960. case OMPC_thread_limit:
  8961. case OMPC_priority:
  8962. case OMPC_grainsize:
  8963. case OMPC_nogroup:
  8964. case OMPC_num_tasks:
  8965. case OMPC_hint:
  8966. case OMPC_unknown:
  8967. case OMPC_uniform:
  8968. case OMPC_to:
  8969. case OMPC_from:
  8970. case OMPC_use_device_ptr:
  8971. case OMPC_is_device_ptr:
  8972. case OMPC_unified_address:
  8973. case OMPC_unified_shared_memory:
  8974. case OMPC_reverse_offload:
  8975. case OMPC_dynamic_allocators:
  8976. case OMPC_atomic_default_mem_order:
  8977. llvm_unreachable("Clause is not allowed.");
  8978. }
  8979. return Res;
  8980. }
  8981. static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
  8982. OpenMPScheduleClauseModifier M2,
  8983. SourceLocation M1Loc, SourceLocation M2Loc) {
  8984. if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
  8985. SmallVector<unsigned, 2> Excluded;
  8986. if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
  8987. Excluded.push_back(M2);
  8988. if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
  8989. Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
  8990. if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
  8991. Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
  8992. S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
  8993. << getListOfPossibleValues(OMPC_schedule,
  8994. /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
  8995. /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
  8996. Excluded)
  8997. << getOpenMPClauseName(OMPC_schedule);
  8998. return true;
  8999. }
  9000. return false;
  9001. }
  9002. OMPClause *Sema::ActOnOpenMPScheduleClause(
  9003. OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
  9004. OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
  9005. SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
  9006. SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
  9007. if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
  9008. checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
  9009. return nullptr;
  9010. // OpenMP, 2.7.1, Loop Construct, Restrictions
  9011. // Either the monotonic modifier or the nonmonotonic modifier can be specified
  9012. // but not both.
  9013. if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
  9014. (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
  9015. M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
  9016. (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
  9017. M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
  9018. Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
  9019. << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
  9020. << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
  9021. return nullptr;
  9022. }
  9023. if (Kind == OMPC_SCHEDULE_unknown) {
  9024. std::string Values;
  9025. if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
  9026. unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
  9027. Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
  9028. /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
  9029. Exclude);
  9030. } else {
  9031. Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
  9032. /*Last=*/OMPC_SCHEDULE_unknown);
  9033. }
  9034. Diag(KindLoc, diag::err_omp_unexpected_clause_value)
  9035. << Values << getOpenMPClauseName(OMPC_schedule);
  9036. return nullptr;
  9037. }
  9038. // OpenMP, 2.7.1, Loop Construct, Restrictions
  9039. // The nonmonotonic modifier can only be specified with schedule(dynamic) or
  9040. // schedule(guided).
  9041. if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
  9042. M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
  9043. Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
  9044. Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
  9045. diag::err_omp_schedule_nonmonotonic_static);
  9046. return nullptr;
  9047. }
  9048. Expr *ValExpr = ChunkSize;
  9049. Stmt *HelperValStmt = nullptr;
  9050. if (ChunkSize) {
  9051. if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
  9052. !ChunkSize->isInstantiationDependent() &&
  9053. !ChunkSize->containsUnexpandedParameterPack()) {
  9054. SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
  9055. ExprResult Val =
  9056. PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
  9057. if (Val.isInvalid())
  9058. return nullptr;
  9059. ValExpr = Val.get();
  9060. // OpenMP [2.7.1, Restrictions]
  9061. // chunk_size must be a loop invariant integer expression with a positive
  9062. // value.
  9063. llvm::APSInt Result;
  9064. if (ValExpr->isIntegerConstantExpr(Result, Context)) {
  9065. if (Result.isSigned() && !Result.isStrictlyPositive()) {
  9066. Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
  9067. << "schedule" << 1 << ChunkSize->getSourceRange();
  9068. return nullptr;
  9069. }
  9070. } else if (getOpenMPCaptureRegionForClause(
  9071. DSAStack->getCurrentDirective(), OMPC_schedule) !=
  9072. OMPD_unknown &&
  9073. !CurContext->isDependentContext()) {
  9074. ValExpr = MakeFullExpr(ValExpr).get();
  9075. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  9076. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  9077. HelperValStmt = buildPreInits(Context, Captures);
  9078. }
  9079. }
  9080. }
  9081. return new (Context)
  9082. OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
  9083. ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
  9084. }
  9085. OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
  9086. SourceLocation StartLoc,
  9087. SourceLocation EndLoc) {
  9088. OMPClause *Res = nullptr;
  9089. switch (Kind) {
  9090. case OMPC_ordered:
  9091. Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
  9092. break;
  9093. case OMPC_nowait:
  9094. Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
  9095. break;
  9096. case OMPC_untied:
  9097. Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
  9098. break;
  9099. case OMPC_mergeable:
  9100. Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
  9101. break;
  9102. case OMPC_read:
  9103. Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
  9104. break;
  9105. case OMPC_write:
  9106. Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
  9107. break;
  9108. case OMPC_update:
  9109. Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
  9110. break;
  9111. case OMPC_capture:
  9112. Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
  9113. break;
  9114. case OMPC_seq_cst:
  9115. Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
  9116. break;
  9117. case OMPC_threads:
  9118. Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
  9119. break;
  9120. case OMPC_simd:
  9121. Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
  9122. break;
  9123. case OMPC_nogroup:
  9124. Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
  9125. break;
  9126. case OMPC_unified_address:
  9127. Res = ActOnOpenMPUnifiedAddressClause(StartLoc, EndLoc);
  9128. break;
  9129. case OMPC_unified_shared_memory:
  9130. Res = ActOnOpenMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
  9131. break;
  9132. case OMPC_reverse_offload:
  9133. Res = ActOnOpenMPReverseOffloadClause(StartLoc, EndLoc);
  9134. break;
  9135. case OMPC_dynamic_allocators:
  9136. Res = ActOnOpenMPDynamicAllocatorsClause(StartLoc, EndLoc);
  9137. break;
  9138. case OMPC_if:
  9139. case OMPC_final:
  9140. case OMPC_num_threads:
  9141. case OMPC_safelen:
  9142. case OMPC_simdlen:
  9143. case OMPC_allocator:
  9144. case OMPC_collapse:
  9145. case OMPC_schedule:
  9146. case OMPC_private:
  9147. case OMPC_firstprivate:
  9148. case OMPC_lastprivate:
  9149. case OMPC_shared:
  9150. case OMPC_reduction:
  9151. case OMPC_task_reduction:
  9152. case OMPC_in_reduction:
  9153. case OMPC_linear:
  9154. case OMPC_aligned:
  9155. case OMPC_copyin:
  9156. case OMPC_copyprivate:
  9157. case OMPC_default:
  9158. case OMPC_proc_bind:
  9159. case OMPC_threadprivate:
  9160. case OMPC_allocate:
  9161. case OMPC_flush:
  9162. case OMPC_depend:
  9163. case OMPC_device:
  9164. case OMPC_map:
  9165. case OMPC_num_teams:
  9166. case OMPC_thread_limit:
  9167. case OMPC_priority:
  9168. case OMPC_grainsize:
  9169. case OMPC_num_tasks:
  9170. case OMPC_hint:
  9171. case OMPC_dist_schedule:
  9172. case OMPC_defaultmap:
  9173. case OMPC_unknown:
  9174. case OMPC_uniform:
  9175. case OMPC_to:
  9176. case OMPC_from:
  9177. case OMPC_use_device_ptr:
  9178. case OMPC_is_device_ptr:
  9179. case OMPC_atomic_default_mem_order:
  9180. llvm_unreachable("Clause is not allowed.");
  9181. }
  9182. return Res;
  9183. }
  9184. OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
  9185. SourceLocation EndLoc) {
  9186. DSAStack->setNowaitRegion();
  9187. return new (Context) OMPNowaitClause(StartLoc, EndLoc);
  9188. }
  9189. OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
  9190. SourceLocation EndLoc) {
  9191. return new (Context) OMPUntiedClause(StartLoc, EndLoc);
  9192. }
  9193. OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
  9194. SourceLocation EndLoc) {
  9195. return new (Context) OMPMergeableClause(StartLoc, EndLoc);
  9196. }
  9197. OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
  9198. SourceLocation EndLoc) {
  9199. return new (Context) OMPReadClause(StartLoc, EndLoc);
  9200. }
  9201. OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
  9202. SourceLocation EndLoc) {
  9203. return new (Context) OMPWriteClause(StartLoc, EndLoc);
  9204. }
  9205. OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
  9206. SourceLocation EndLoc) {
  9207. return new (Context) OMPUpdateClause(StartLoc, EndLoc);
  9208. }
  9209. OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
  9210. SourceLocation EndLoc) {
  9211. return new (Context) OMPCaptureClause(StartLoc, EndLoc);
  9212. }
  9213. OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
  9214. SourceLocation EndLoc) {
  9215. return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
  9216. }
  9217. OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
  9218. SourceLocation EndLoc) {
  9219. return new (Context) OMPThreadsClause(StartLoc, EndLoc);
  9220. }
  9221. OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
  9222. SourceLocation EndLoc) {
  9223. return new (Context) OMPSIMDClause(StartLoc, EndLoc);
  9224. }
  9225. OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
  9226. SourceLocation EndLoc) {
  9227. return new (Context) OMPNogroupClause(StartLoc, EndLoc);
  9228. }
  9229. OMPClause *Sema::ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc,
  9230. SourceLocation EndLoc) {
  9231. return new (Context) OMPUnifiedAddressClause(StartLoc, EndLoc);
  9232. }
  9233. OMPClause *Sema::ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc,
  9234. SourceLocation EndLoc) {
  9235. return new (Context) OMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
  9236. }
  9237. OMPClause *Sema::ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc,
  9238. SourceLocation EndLoc) {
  9239. return new (Context) OMPReverseOffloadClause(StartLoc, EndLoc);
  9240. }
  9241. OMPClause *Sema::ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc,
  9242. SourceLocation EndLoc) {
  9243. return new (Context) OMPDynamicAllocatorsClause(StartLoc, EndLoc);
  9244. }
  9245. OMPClause *Sema::ActOnOpenMPVarListClause(
  9246. OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
  9247. const OMPVarListLocTy &Locs, SourceLocation ColonLoc,
  9248. CXXScopeSpec &ReductionOrMapperIdScopeSpec,
  9249. DeclarationNameInfo &ReductionOrMapperId, OpenMPDependClauseKind DepKind,
  9250. OpenMPLinearClauseKind LinKind,
  9251. ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
  9252. ArrayRef<SourceLocation> MapTypeModifiersLoc, OpenMPMapClauseKind MapType,
  9253. bool IsMapTypeImplicit, SourceLocation DepLinMapLoc) {
  9254. SourceLocation StartLoc = Locs.StartLoc;
  9255. SourceLocation LParenLoc = Locs.LParenLoc;
  9256. SourceLocation EndLoc = Locs.EndLoc;
  9257. OMPClause *Res = nullptr;
  9258. switch (Kind) {
  9259. case OMPC_private:
  9260. Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
  9261. break;
  9262. case OMPC_firstprivate:
  9263. Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
  9264. break;
  9265. case OMPC_lastprivate:
  9266. Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
  9267. break;
  9268. case OMPC_shared:
  9269. Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
  9270. break;
  9271. case OMPC_reduction:
  9272. Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
  9273. EndLoc, ReductionOrMapperIdScopeSpec,
  9274. ReductionOrMapperId);
  9275. break;
  9276. case OMPC_task_reduction:
  9277. Res = ActOnOpenMPTaskReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
  9278. EndLoc, ReductionOrMapperIdScopeSpec,
  9279. ReductionOrMapperId);
  9280. break;
  9281. case OMPC_in_reduction:
  9282. Res = ActOnOpenMPInReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
  9283. EndLoc, ReductionOrMapperIdScopeSpec,
  9284. ReductionOrMapperId);
  9285. break;
  9286. case OMPC_linear:
  9287. Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
  9288. LinKind, DepLinMapLoc, ColonLoc, EndLoc);
  9289. break;
  9290. case OMPC_aligned:
  9291. Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
  9292. ColonLoc, EndLoc);
  9293. break;
  9294. case OMPC_copyin:
  9295. Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
  9296. break;
  9297. case OMPC_copyprivate:
  9298. Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
  9299. break;
  9300. case OMPC_flush:
  9301. Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
  9302. break;
  9303. case OMPC_depend:
  9304. Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList,
  9305. StartLoc, LParenLoc, EndLoc);
  9306. break;
  9307. case OMPC_map:
  9308. Res = ActOnOpenMPMapClause(MapTypeModifiers, MapTypeModifiersLoc,
  9309. ReductionOrMapperIdScopeSpec,
  9310. ReductionOrMapperId, MapType, IsMapTypeImplicit,
  9311. DepLinMapLoc, ColonLoc, VarList, Locs);
  9312. break;
  9313. case OMPC_to:
  9314. Res = ActOnOpenMPToClause(VarList, ReductionOrMapperIdScopeSpec,
  9315. ReductionOrMapperId, Locs);
  9316. break;
  9317. case OMPC_from:
  9318. Res = ActOnOpenMPFromClause(VarList, ReductionOrMapperIdScopeSpec,
  9319. ReductionOrMapperId, Locs);
  9320. break;
  9321. case OMPC_use_device_ptr:
  9322. Res = ActOnOpenMPUseDevicePtrClause(VarList, Locs);
  9323. break;
  9324. case OMPC_is_device_ptr:
  9325. Res = ActOnOpenMPIsDevicePtrClause(VarList, Locs);
  9326. break;
  9327. case OMPC_if:
  9328. case OMPC_final:
  9329. case OMPC_num_threads:
  9330. case OMPC_safelen:
  9331. case OMPC_simdlen:
  9332. case OMPC_allocator:
  9333. case OMPC_collapse:
  9334. case OMPC_default:
  9335. case OMPC_proc_bind:
  9336. case OMPC_schedule:
  9337. case OMPC_ordered:
  9338. case OMPC_nowait:
  9339. case OMPC_untied:
  9340. case OMPC_mergeable:
  9341. case OMPC_threadprivate:
  9342. case OMPC_allocate:
  9343. case OMPC_read:
  9344. case OMPC_write:
  9345. case OMPC_update:
  9346. case OMPC_capture:
  9347. case OMPC_seq_cst:
  9348. case OMPC_device:
  9349. case OMPC_threads:
  9350. case OMPC_simd:
  9351. case OMPC_num_teams:
  9352. case OMPC_thread_limit:
  9353. case OMPC_priority:
  9354. case OMPC_grainsize:
  9355. case OMPC_nogroup:
  9356. case OMPC_num_tasks:
  9357. case OMPC_hint:
  9358. case OMPC_dist_schedule:
  9359. case OMPC_defaultmap:
  9360. case OMPC_unknown:
  9361. case OMPC_uniform:
  9362. case OMPC_unified_address:
  9363. case OMPC_unified_shared_memory:
  9364. case OMPC_reverse_offload:
  9365. case OMPC_dynamic_allocators:
  9366. case OMPC_atomic_default_mem_order:
  9367. llvm_unreachable("Clause is not allowed.");
  9368. }
  9369. return Res;
  9370. }
  9371. ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
  9372. ExprObjectKind OK, SourceLocation Loc) {
  9373. ExprResult Res = BuildDeclRefExpr(
  9374. Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
  9375. if (!Res.isUsable())
  9376. return ExprError();
  9377. if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
  9378. Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
  9379. if (!Res.isUsable())
  9380. return ExprError();
  9381. }
  9382. if (VK != VK_LValue && Res.get()->isGLValue()) {
  9383. Res = DefaultLvalueConversion(Res.get());
  9384. if (!Res.isUsable())
  9385. return ExprError();
  9386. }
  9387. return Res;
  9388. }
  9389. static std::pair<ValueDecl *, bool>
  9390. getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
  9391. SourceRange &ERange, bool AllowArraySection = false) {
  9392. if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
  9393. RefExpr->containsUnexpandedParameterPack())
  9394. return std::make_pair(nullptr, true);
  9395. // OpenMP [3.1, C/C++]
  9396. // A list item is a variable name.
  9397. // OpenMP [2.9.3.3, Restrictions, p.1]
  9398. // A variable that is part of another variable (as an array or
  9399. // structure element) cannot appear in a private clause.
  9400. RefExpr = RefExpr->IgnoreParens();
  9401. enum {
  9402. NoArrayExpr = -1,
  9403. ArraySubscript = 0,
  9404. OMPArraySection = 1
  9405. } IsArrayExpr = NoArrayExpr;
  9406. if (AllowArraySection) {
  9407. if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
  9408. Expr *Base = ASE->getBase()->IgnoreParenImpCasts();
  9409. while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
  9410. Base = TempASE->getBase()->IgnoreParenImpCasts();
  9411. RefExpr = Base;
  9412. IsArrayExpr = ArraySubscript;
  9413. } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
  9414. Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
  9415. while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
  9416. Base = TempOASE->getBase()->IgnoreParenImpCasts();
  9417. while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
  9418. Base = TempASE->getBase()->IgnoreParenImpCasts();
  9419. RefExpr = Base;
  9420. IsArrayExpr = OMPArraySection;
  9421. }
  9422. }
  9423. ELoc = RefExpr->getExprLoc();
  9424. ERange = RefExpr->getSourceRange();
  9425. RefExpr = RefExpr->IgnoreParenImpCasts();
  9426. auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
  9427. auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
  9428. if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
  9429. (S.getCurrentThisType().isNull() || !ME ||
  9430. !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
  9431. !isa<FieldDecl>(ME->getMemberDecl()))) {
  9432. if (IsArrayExpr != NoArrayExpr) {
  9433. S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr
  9434. << ERange;
  9435. } else {
  9436. S.Diag(ELoc,
  9437. AllowArraySection
  9438. ? diag::err_omp_expected_var_name_member_expr_or_array_item
  9439. : diag::err_omp_expected_var_name_member_expr)
  9440. << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
  9441. }
  9442. return std::make_pair(nullptr, false);
  9443. }
  9444. return std::make_pair(
  9445. getCanonicalDecl(DE ? DE->getDecl() : ME->getMemberDecl()), false);
  9446. }
  9447. OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
  9448. SourceLocation StartLoc,
  9449. SourceLocation LParenLoc,
  9450. SourceLocation EndLoc) {
  9451. SmallVector<Expr *, 8> Vars;
  9452. SmallVector<Expr *, 8> PrivateCopies;
  9453. for (Expr *RefExpr : VarList) {
  9454. assert(RefExpr && "NULL expr in OpenMP private clause.");
  9455. SourceLocation ELoc;
  9456. SourceRange ERange;
  9457. Expr *SimpleRefExpr = RefExpr;
  9458. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  9459. if (Res.second) {
  9460. // It will be analyzed later.
  9461. Vars.push_back(RefExpr);
  9462. PrivateCopies.push_back(nullptr);
  9463. }
  9464. ValueDecl *D = Res.first;
  9465. if (!D)
  9466. continue;
  9467. QualType Type = D->getType();
  9468. auto *VD = dyn_cast<VarDecl>(D);
  9469. // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
  9470. // A variable that appears in a private clause must not have an incomplete
  9471. // type or a reference type.
  9472. if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
  9473. continue;
  9474. Type = Type.getNonReferenceType();
  9475. // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
  9476. // A variable that is privatized must not have a const-qualified type
  9477. // unless it is of class type with a mutable member. This restriction does
  9478. // not apply to the firstprivate clause.
  9479. //
  9480. // OpenMP 3.1 [2.9.3.3, private clause, Restrictions]
  9481. // A variable that appears in a private clause must not have a
  9482. // const-qualified type unless it is of class type with a mutable member.
  9483. if (rejectConstNotMutableType(*this, D, Type, OMPC_private, ELoc))
  9484. continue;
  9485. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  9486. // in a Construct]
  9487. // Variables with the predetermined data-sharing attributes may not be
  9488. // listed in data-sharing attributes clauses, except for the cases
  9489. // listed below. For these exceptions only, listing a predetermined
  9490. // variable in a data-sharing attribute clause is allowed and overrides
  9491. // the variable's predetermined data-sharing attributes.
  9492. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
  9493. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
  9494. Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
  9495. << getOpenMPClauseName(OMPC_private);
  9496. reportOriginalDsa(*this, DSAStack, D, DVar);
  9497. continue;
  9498. }
  9499. OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
  9500. // Variably modified types are not supported for tasks.
  9501. if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
  9502. isOpenMPTaskingDirective(CurrDir)) {
  9503. Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
  9504. << getOpenMPClauseName(OMPC_private) << Type
  9505. << getOpenMPDirectiveName(CurrDir);
  9506. bool IsDecl =
  9507. !VD ||
  9508. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  9509. Diag(D->getLocation(),
  9510. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  9511. << D;
  9512. continue;
  9513. }
  9514. // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
  9515. // A list item cannot appear in both a map clause and a data-sharing
  9516. // attribute clause on the same construct
  9517. if (isOpenMPTargetExecutionDirective(CurrDir)) {
  9518. OpenMPClauseKind ConflictKind;
  9519. if (DSAStack->checkMappableExprComponentListsForDecl(
  9520. VD, /*CurrentRegionOnly=*/true,
  9521. [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
  9522. OpenMPClauseKind WhereFoundClauseKind) -> bool {
  9523. ConflictKind = WhereFoundClauseKind;
  9524. return true;
  9525. })) {
  9526. Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
  9527. << getOpenMPClauseName(OMPC_private)
  9528. << getOpenMPClauseName(ConflictKind)
  9529. << getOpenMPDirectiveName(CurrDir);
  9530. reportOriginalDsa(*this, DSAStack, D, DVar);
  9531. continue;
  9532. }
  9533. }
  9534. // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
  9535. // A variable of class type (or array thereof) that appears in a private
  9536. // clause requires an accessible, unambiguous default constructor for the
  9537. // class type.
  9538. // Generate helper private variable and initialize it with the default
  9539. // value. The address of the original variable is replaced by the address of
  9540. // the new private variable in CodeGen. This new variable is not added to
  9541. // IdResolver, so the code in the OpenMP region uses original variable for
  9542. // proper diagnostics.
  9543. Type = Type.getUnqualifiedType();
  9544. VarDecl *VDPrivate =
  9545. buildVarDecl(*this, ELoc, Type, D->getName(),
  9546. D->hasAttrs() ? &D->getAttrs() : nullptr,
  9547. VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
  9548. ActOnUninitializedDecl(VDPrivate);
  9549. if (VDPrivate->isInvalidDecl())
  9550. continue;
  9551. DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
  9552. *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
  9553. DeclRefExpr *Ref = nullptr;
  9554. if (!VD && !CurContext->isDependentContext())
  9555. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
  9556. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
  9557. Vars.push_back((VD || CurContext->isDependentContext())
  9558. ? RefExpr->IgnoreParens()
  9559. : Ref);
  9560. PrivateCopies.push_back(VDPrivateRefExpr);
  9561. }
  9562. if (Vars.empty())
  9563. return nullptr;
  9564. return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
  9565. PrivateCopies);
  9566. }
  9567. namespace {
  9568. class DiagsUninitializedSeveretyRAII {
  9569. private:
  9570. DiagnosticsEngine &Diags;
  9571. SourceLocation SavedLoc;
  9572. bool IsIgnored = false;
  9573. public:
  9574. DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
  9575. bool IsIgnored)
  9576. : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
  9577. if (!IsIgnored) {
  9578. Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
  9579. /*Map*/ diag::Severity::Ignored, Loc);
  9580. }
  9581. }
  9582. ~DiagsUninitializedSeveretyRAII() {
  9583. if (!IsIgnored)
  9584. Diags.popMappings(SavedLoc);
  9585. }
  9586. };
  9587. }
  9588. OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
  9589. SourceLocation StartLoc,
  9590. SourceLocation LParenLoc,
  9591. SourceLocation EndLoc) {
  9592. SmallVector<Expr *, 8> Vars;
  9593. SmallVector<Expr *, 8> PrivateCopies;
  9594. SmallVector<Expr *, 8> Inits;
  9595. SmallVector<Decl *, 4> ExprCaptures;
  9596. bool IsImplicitClause =
  9597. StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
  9598. SourceLocation ImplicitClauseLoc = DSAStack->getConstructLoc();
  9599. for (Expr *RefExpr : VarList) {
  9600. assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
  9601. SourceLocation ELoc;
  9602. SourceRange ERange;
  9603. Expr *SimpleRefExpr = RefExpr;
  9604. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  9605. if (Res.second) {
  9606. // It will be analyzed later.
  9607. Vars.push_back(RefExpr);
  9608. PrivateCopies.push_back(nullptr);
  9609. Inits.push_back(nullptr);
  9610. }
  9611. ValueDecl *D = Res.first;
  9612. if (!D)
  9613. continue;
  9614. ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
  9615. QualType Type = D->getType();
  9616. auto *VD = dyn_cast<VarDecl>(D);
  9617. // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
  9618. // A variable that appears in a private clause must not have an incomplete
  9619. // type or a reference type.
  9620. if (RequireCompleteType(ELoc, Type,
  9621. diag::err_omp_firstprivate_incomplete_type))
  9622. continue;
  9623. Type = Type.getNonReferenceType();
  9624. // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
  9625. // A variable of class type (or array thereof) that appears in a private
  9626. // clause requires an accessible, unambiguous copy constructor for the
  9627. // class type.
  9628. QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
  9629. // If an implicit firstprivate variable found it was checked already.
  9630. DSAStackTy::DSAVarData TopDVar;
  9631. if (!IsImplicitClause) {
  9632. DSAStackTy::DSAVarData DVar =
  9633. DSAStack->getTopDSA(D, /*FromParent=*/false);
  9634. TopDVar = DVar;
  9635. OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
  9636. bool IsConstant = ElemType.isConstant(Context);
  9637. // OpenMP [2.4.13, Data-sharing Attribute Clauses]
  9638. // A list item that specifies a given variable may not appear in more
  9639. // than one clause on the same directive, except that a variable may be
  9640. // specified in both firstprivate and lastprivate clauses.
  9641. // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
  9642. // A list item may appear in a firstprivate or lastprivate clause but not
  9643. // both.
  9644. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
  9645. (isOpenMPDistributeDirective(CurrDir) ||
  9646. DVar.CKind != OMPC_lastprivate) &&
  9647. DVar.RefExpr) {
  9648. Diag(ELoc, diag::err_omp_wrong_dsa)
  9649. << getOpenMPClauseName(DVar.CKind)
  9650. << getOpenMPClauseName(OMPC_firstprivate);
  9651. reportOriginalDsa(*this, DSAStack, D, DVar);
  9652. continue;
  9653. }
  9654. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  9655. // in a Construct]
  9656. // Variables with the predetermined data-sharing attributes may not be
  9657. // listed in data-sharing attributes clauses, except for the cases
  9658. // listed below. For these exceptions only, listing a predetermined
  9659. // variable in a data-sharing attribute clause is allowed and overrides
  9660. // the variable's predetermined data-sharing attributes.
  9661. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  9662. // in a Construct, C/C++, p.2]
  9663. // Variables with const-qualified type having no mutable member may be
  9664. // listed in a firstprivate clause, even if they are static data members.
  9665. if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
  9666. DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
  9667. Diag(ELoc, diag::err_omp_wrong_dsa)
  9668. << getOpenMPClauseName(DVar.CKind)
  9669. << getOpenMPClauseName(OMPC_firstprivate);
  9670. reportOriginalDsa(*this, DSAStack, D, DVar);
  9671. continue;
  9672. }
  9673. // OpenMP [2.9.3.4, Restrictions, p.2]
  9674. // A list item that is private within a parallel region must not appear
  9675. // in a firstprivate clause on a worksharing construct if any of the
  9676. // worksharing regions arising from the worksharing construct ever bind
  9677. // to any of the parallel regions arising from the parallel construct.
  9678. // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
  9679. // A list item that is private within a teams region must not appear in a
  9680. // firstprivate clause on a distribute construct if any of the distribute
  9681. // regions arising from the distribute construct ever bind to any of the
  9682. // teams regions arising from the teams construct.
  9683. // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
  9684. // A list item that appears in a reduction clause of a teams construct
  9685. // must not appear in a firstprivate clause on a distribute construct if
  9686. // any of the distribute regions arising from the distribute construct
  9687. // ever bind to any of the teams regions arising from the teams construct.
  9688. if ((isOpenMPWorksharingDirective(CurrDir) ||
  9689. isOpenMPDistributeDirective(CurrDir)) &&
  9690. !isOpenMPParallelDirective(CurrDir) &&
  9691. !isOpenMPTeamsDirective(CurrDir)) {
  9692. DVar = DSAStack->getImplicitDSA(D, true);
  9693. if (DVar.CKind != OMPC_shared &&
  9694. (isOpenMPParallelDirective(DVar.DKind) ||
  9695. isOpenMPTeamsDirective(DVar.DKind) ||
  9696. DVar.DKind == OMPD_unknown)) {
  9697. Diag(ELoc, diag::err_omp_required_access)
  9698. << getOpenMPClauseName(OMPC_firstprivate)
  9699. << getOpenMPClauseName(OMPC_shared);
  9700. reportOriginalDsa(*this, DSAStack, D, DVar);
  9701. continue;
  9702. }
  9703. }
  9704. // OpenMP [2.9.3.4, Restrictions, p.3]
  9705. // A list item that appears in a reduction clause of a parallel construct
  9706. // must not appear in a firstprivate clause on a worksharing or task
  9707. // construct if any of the worksharing or task regions arising from the
  9708. // worksharing or task construct ever bind to any of the parallel regions
  9709. // arising from the parallel construct.
  9710. // OpenMP [2.9.3.4, Restrictions, p.4]
  9711. // A list item that appears in a reduction clause in worksharing
  9712. // construct must not appear in a firstprivate clause in a task construct
  9713. // encountered during execution of any of the worksharing regions arising
  9714. // from the worksharing construct.
  9715. if (isOpenMPTaskingDirective(CurrDir)) {
  9716. DVar = DSAStack->hasInnermostDSA(
  9717. D, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
  9718. [](OpenMPDirectiveKind K) {
  9719. return isOpenMPParallelDirective(K) ||
  9720. isOpenMPWorksharingDirective(K) ||
  9721. isOpenMPTeamsDirective(K);
  9722. },
  9723. /*FromParent=*/true);
  9724. if (DVar.CKind == OMPC_reduction &&
  9725. (isOpenMPParallelDirective(DVar.DKind) ||
  9726. isOpenMPWorksharingDirective(DVar.DKind) ||
  9727. isOpenMPTeamsDirective(DVar.DKind))) {
  9728. Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
  9729. << getOpenMPDirectiveName(DVar.DKind);
  9730. reportOriginalDsa(*this, DSAStack, D, DVar);
  9731. continue;
  9732. }
  9733. }
  9734. // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
  9735. // A list item cannot appear in both a map clause and a data-sharing
  9736. // attribute clause on the same construct
  9737. if (isOpenMPTargetExecutionDirective(CurrDir)) {
  9738. OpenMPClauseKind ConflictKind;
  9739. if (DSAStack->checkMappableExprComponentListsForDecl(
  9740. VD, /*CurrentRegionOnly=*/true,
  9741. [&ConflictKind](
  9742. OMPClauseMappableExprCommon::MappableExprComponentListRef,
  9743. OpenMPClauseKind WhereFoundClauseKind) {
  9744. ConflictKind = WhereFoundClauseKind;
  9745. return true;
  9746. })) {
  9747. Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
  9748. << getOpenMPClauseName(OMPC_firstprivate)
  9749. << getOpenMPClauseName(ConflictKind)
  9750. << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
  9751. reportOriginalDsa(*this, DSAStack, D, DVar);
  9752. continue;
  9753. }
  9754. }
  9755. }
  9756. // Variably modified types are not supported for tasks.
  9757. if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
  9758. isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
  9759. Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
  9760. << getOpenMPClauseName(OMPC_firstprivate) << Type
  9761. << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
  9762. bool IsDecl =
  9763. !VD ||
  9764. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  9765. Diag(D->getLocation(),
  9766. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  9767. << D;
  9768. continue;
  9769. }
  9770. Type = Type.getUnqualifiedType();
  9771. VarDecl *VDPrivate =
  9772. buildVarDecl(*this, ELoc, Type, D->getName(),
  9773. D->hasAttrs() ? &D->getAttrs() : nullptr,
  9774. VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
  9775. // Generate helper private variable and initialize it with the value of the
  9776. // original variable. The address of the original variable is replaced by
  9777. // the address of the new private variable in the CodeGen. This new variable
  9778. // is not added to IdResolver, so the code in the OpenMP region uses
  9779. // original variable for proper diagnostics and variable capturing.
  9780. Expr *VDInitRefExpr = nullptr;
  9781. // For arrays generate initializer for single element and replace it by the
  9782. // original array element in CodeGen.
  9783. if (Type->isArrayType()) {
  9784. VarDecl *VDInit =
  9785. buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
  9786. VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
  9787. Expr *Init = DefaultLvalueConversion(VDInitRefExpr).get();
  9788. ElemType = ElemType.getUnqualifiedType();
  9789. VarDecl *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
  9790. ".firstprivate.temp");
  9791. InitializedEntity Entity =
  9792. InitializedEntity::InitializeVariable(VDInitTemp);
  9793. InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
  9794. InitializationSequence InitSeq(*this, Entity, Kind, Init);
  9795. ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
  9796. if (Result.isInvalid())
  9797. VDPrivate->setInvalidDecl();
  9798. else
  9799. VDPrivate->setInit(Result.getAs<Expr>());
  9800. // Remove temp variable declaration.
  9801. Context.Deallocate(VDInitTemp);
  9802. } else {
  9803. VarDecl *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
  9804. ".firstprivate.temp");
  9805. VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
  9806. RefExpr->getExprLoc());
  9807. AddInitializerToDecl(VDPrivate,
  9808. DefaultLvalueConversion(VDInitRefExpr).get(),
  9809. /*DirectInit=*/false);
  9810. }
  9811. if (VDPrivate->isInvalidDecl()) {
  9812. if (IsImplicitClause) {
  9813. Diag(RefExpr->getExprLoc(),
  9814. diag::note_omp_task_predetermined_firstprivate_here);
  9815. }
  9816. continue;
  9817. }
  9818. CurContext->addDecl(VDPrivate);
  9819. DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
  9820. *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
  9821. RefExpr->getExprLoc());
  9822. DeclRefExpr *Ref = nullptr;
  9823. if (!VD && !CurContext->isDependentContext()) {
  9824. if (TopDVar.CKind == OMPC_lastprivate) {
  9825. Ref = TopDVar.PrivateCopy;
  9826. } else {
  9827. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
  9828. if (!isOpenMPCapturedDecl(D))
  9829. ExprCaptures.push_back(Ref->getDecl());
  9830. }
  9831. }
  9832. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
  9833. Vars.push_back((VD || CurContext->isDependentContext())
  9834. ? RefExpr->IgnoreParens()
  9835. : Ref);
  9836. PrivateCopies.push_back(VDPrivateRefExpr);
  9837. Inits.push_back(VDInitRefExpr);
  9838. }
  9839. if (Vars.empty())
  9840. return nullptr;
  9841. return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  9842. Vars, PrivateCopies, Inits,
  9843. buildPreInits(Context, ExprCaptures));
  9844. }
  9845. OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
  9846. SourceLocation StartLoc,
  9847. SourceLocation LParenLoc,
  9848. SourceLocation EndLoc) {
  9849. SmallVector<Expr *, 8> Vars;
  9850. SmallVector<Expr *, 8> SrcExprs;
  9851. SmallVector<Expr *, 8> DstExprs;
  9852. SmallVector<Expr *, 8> AssignmentOps;
  9853. SmallVector<Decl *, 4> ExprCaptures;
  9854. SmallVector<Expr *, 4> ExprPostUpdates;
  9855. for (Expr *RefExpr : VarList) {
  9856. assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
  9857. SourceLocation ELoc;
  9858. SourceRange ERange;
  9859. Expr *SimpleRefExpr = RefExpr;
  9860. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  9861. if (Res.second) {
  9862. // It will be analyzed later.
  9863. Vars.push_back(RefExpr);
  9864. SrcExprs.push_back(nullptr);
  9865. DstExprs.push_back(nullptr);
  9866. AssignmentOps.push_back(nullptr);
  9867. }
  9868. ValueDecl *D = Res.first;
  9869. if (!D)
  9870. continue;
  9871. QualType Type = D->getType();
  9872. auto *VD = dyn_cast<VarDecl>(D);
  9873. // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
  9874. // A variable that appears in a lastprivate clause must not have an
  9875. // incomplete type or a reference type.
  9876. if (RequireCompleteType(ELoc, Type,
  9877. diag::err_omp_lastprivate_incomplete_type))
  9878. continue;
  9879. Type = Type.getNonReferenceType();
  9880. // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
  9881. // A variable that is privatized must not have a const-qualified type
  9882. // unless it is of class type with a mutable member. This restriction does
  9883. // not apply to the firstprivate clause.
  9884. //
  9885. // OpenMP 3.1 [2.9.3.5, lastprivate clause, Restrictions]
  9886. // A variable that appears in a lastprivate clause must not have a
  9887. // const-qualified type unless it is of class type with a mutable member.
  9888. if (rejectConstNotMutableType(*this, D, Type, OMPC_lastprivate, ELoc))
  9889. continue;
  9890. OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
  9891. // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
  9892. // in a Construct]
  9893. // Variables with the predetermined data-sharing attributes may not be
  9894. // listed in data-sharing attributes clauses, except for the cases
  9895. // listed below.
  9896. // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
  9897. // A list item may appear in a firstprivate or lastprivate clause but not
  9898. // both.
  9899. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
  9900. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
  9901. (isOpenMPDistributeDirective(CurrDir) ||
  9902. DVar.CKind != OMPC_firstprivate) &&
  9903. (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
  9904. Diag(ELoc, diag::err_omp_wrong_dsa)
  9905. << getOpenMPClauseName(DVar.CKind)
  9906. << getOpenMPClauseName(OMPC_lastprivate);
  9907. reportOriginalDsa(*this, DSAStack, D, DVar);
  9908. continue;
  9909. }
  9910. // OpenMP [2.14.3.5, Restrictions, p.2]
  9911. // A list item that is private within a parallel region, or that appears in
  9912. // the reduction clause of a parallel construct, must not appear in a
  9913. // lastprivate clause on a worksharing construct if any of the corresponding
  9914. // worksharing regions ever binds to any of the corresponding parallel
  9915. // regions.
  9916. DSAStackTy::DSAVarData TopDVar = DVar;
  9917. if (isOpenMPWorksharingDirective(CurrDir) &&
  9918. !isOpenMPParallelDirective(CurrDir) &&
  9919. !isOpenMPTeamsDirective(CurrDir)) {
  9920. DVar = DSAStack->getImplicitDSA(D, true);
  9921. if (DVar.CKind != OMPC_shared) {
  9922. Diag(ELoc, diag::err_omp_required_access)
  9923. << getOpenMPClauseName(OMPC_lastprivate)
  9924. << getOpenMPClauseName(OMPC_shared);
  9925. reportOriginalDsa(*this, DSAStack, D, DVar);
  9926. continue;
  9927. }
  9928. }
  9929. // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
  9930. // A variable of class type (or array thereof) that appears in a
  9931. // lastprivate clause requires an accessible, unambiguous default
  9932. // constructor for the class type, unless the list item is also specified
  9933. // in a firstprivate clause.
  9934. // A variable of class type (or array thereof) that appears in a
  9935. // lastprivate clause requires an accessible, unambiguous copy assignment
  9936. // operator for the class type.
  9937. Type = Context.getBaseElementType(Type).getNonReferenceType();
  9938. VarDecl *SrcVD = buildVarDecl(*this, ERange.getBegin(),
  9939. Type.getUnqualifiedType(), ".lastprivate.src",
  9940. D->hasAttrs() ? &D->getAttrs() : nullptr);
  9941. DeclRefExpr *PseudoSrcExpr =
  9942. buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
  9943. VarDecl *DstVD =
  9944. buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
  9945. D->hasAttrs() ? &D->getAttrs() : nullptr);
  9946. DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
  9947. // For arrays generate assignment operation for single element and replace
  9948. // it by the original array element in CodeGen.
  9949. ExprResult AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
  9950. PseudoDstExpr, PseudoSrcExpr);
  9951. if (AssignmentOp.isInvalid())
  9952. continue;
  9953. AssignmentOp =
  9954. ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
  9955. if (AssignmentOp.isInvalid())
  9956. continue;
  9957. DeclRefExpr *Ref = nullptr;
  9958. if (!VD && !CurContext->isDependentContext()) {
  9959. if (TopDVar.CKind == OMPC_firstprivate) {
  9960. Ref = TopDVar.PrivateCopy;
  9961. } else {
  9962. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
  9963. if (!isOpenMPCapturedDecl(D))
  9964. ExprCaptures.push_back(Ref->getDecl());
  9965. }
  9966. if (TopDVar.CKind == OMPC_firstprivate ||
  9967. (!isOpenMPCapturedDecl(D) &&
  9968. Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
  9969. ExprResult RefRes = DefaultLvalueConversion(Ref);
  9970. if (!RefRes.isUsable())
  9971. continue;
  9972. ExprResult PostUpdateRes =
  9973. BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
  9974. RefRes.get());
  9975. if (!PostUpdateRes.isUsable())
  9976. continue;
  9977. ExprPostUpdates.push_back(
  9978. IgnoredValueConversions(PostUpdateRes.get()).get());
  9979. }
  9980. }
  9981. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
  9982. Vars.push_back((VD || CurContext->isDependentContext())
  9983. ? RefExpr->IgnoreParens()
  9984. : Ref);
  9985. SrcExprs.push_back(PseudoSrcExpr);
  9986. DstExprs.push_back(PseudoDstExpr);
  9987. AssignmentOps.push_back(AssignmentOp.get());
  9988. }
  9989. if (Vars.empty())
  9990. return nullptr;
  9991. return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  9992. Vars, SrcExprs, DstExprs, AssignmentOps,
  9993. buildPreInits(Context, ExprCaptures),
  9994. buildPostUpdate(*this, ExprPostUpdates));
  9995. }
  9996. OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
  9997. SourceLocation StartLoc,
  9998. SourceLocation LParenLoc,
  9999. SourceLocation EndLoc) {
  10000. SmallVector<Expr *, 8> Vars;
  10001. for (Expr *RefExpr : VarList) {
  10002. assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
  10003. SourceLocation ELoc;
  10004. SourceRange ERange;
  10005. Expr *SimpleRefExpr = RefExpr;
  10006. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  10007. if (Res.second) {
  10008. // It will be analyzed later.
  10009. Vars.push_back(RefExpr);
  10010. }
  10011. ValueDecl *D = Res.first;
  10012. if (!D)
  10013. continue;
  10014. auto *VD = dyn_cast<VarDecl>(D);
  10015. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  10016. // in a Construct]
  10017. // Variables with the predetermined data-sharing attributes may not be
  10018. // listed in data-sharing attributes clauses, except for the cases
  10019. // listed below. For these exceptions only, listing a predetermined
  10020. // variable in a data-sharing attribute clause is allowed and overrides
  10021. // the variable's predetermined data-sharing attributes.
  10022. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
  10023. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
  10024. DVar.RefExpr) {
  10025. Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
  10026. << getOpenMPClauseName(OMPC_shared);
  10027. reportOriginalDsa(*this, DSAStack, D, DVar);
  10028. continue;
  10029. }
  10030. DeclRefExpr *Ref = nullptr;
  10031. if (!VD && isOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
  10032. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
  10033. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
  10034. Vars.push_back((VD || !Ref || CurContext->isDependentContext())
  10035. ? RefExpr->IgnoreParens()
  10036. : Ref);
  10037. }
  10038. if (Vars.empty())
  10039. return nullptr;
  10040. return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
  10041. }
  10042. namespace {
  10043. class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
  10044. DSAStackTy *Stack;
  10045. public:
  10046. bool VisitDeclRefExpr(DeclRefExpr *E) {
  10047. if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
  10048. DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
  10049. if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
  10050. return false;
  10051. if (DVar.CKind != OMPC_unknown)
  10052. return true;
  10053. DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
  10054. VD, isOpenMPPrivate, [](OpenMPDirectiveKind) { return true; },
  10055. /*FromParent=*/true);
  10056. return DVarPrivate.CKind != OMPC_unknown;
  10057. }
  10058. return false;
  10059. }
  10060. bool VisitStmt(Stmt *S) {
  10061. for (Stmt *Child : S->children()) {
  10062. if (Child && Visit(Child))
  10063. return true;
  10064. }
  10065. return false;
  10066. }
  10067. explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
  10068. };
  10069. } // namespace
  10070. namespace {
  10071. // Transform MemberExpression for specified FieldDecl of current class to
  10072. // DeclRefExpr to specified OMPCapturedExprDecl.
  10073. class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
  10074. typedef TreeTransform<TransformExprToCaptures> BaseTransform;
  10075. ValueDecl *Field = nullptr;
  10076. DeclRefExpr *CapturedExpr = nullptr;
  10077. public:
  10078. TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
  10079. : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
  10080. ExprResult TransformMemberExpr(MemberExpr *E) {
  10081. if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
  10082. E->getMemberDecl() == Field) {
  10083. CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
  10084. return CapturedExpr;
  10085. }
  10086. return BaseTransform::TransformMemberExpr(E);
  10087. }
  10088. DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
  10089. };
  10090. } // namespace
  10091. template <typename T, typename U>
  10092. static T filterLookupForUDReductionAndMapper(
  10093. SmallVectorImpl<U> &Lookups, const llvm::function_ref<T(ValueDecl *)> Gen) {
  10094. for (U &Set : Lookups) {
  10095. for (auto *D : Set) {
  10096. if (T Res = Gen(cast<ValueDecl>(D)))
  10097. return Res;
  10098. }
  10099. }
  10100. return T();
  10101. }
  10102. static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D) {
  10103. assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case");
  10104. for (auto RD : D->redecls()) {
  10105. // Don't bother with extra checks if we already know this one isn't visible.
  10106. if (RD == D)
  10107. continue;
  10108. auto ND = cast<NamedDecl>(RD);
  10109. if (LookupResult::isVisible(SemaRef, ND))
  10110. return ND;
  10111. }
  10112. return nullptr;
  10113. }
  10114. static void
  10115. argumentDependentLookup(Sema &SemaRef, const DeclarationNameInfo &Id,
  10116. SourceLocation Loc, QualType Ty,
  10117. SmallVectorImpl<UnresolvedSet<8>> &Lookups) {
  10118. // Find all of the associated namespaces and classes based on the
  10119. // arguments we have.
  10120. Sema::AssociatedNamespaceSet AssociatedNamespaces;
  10121. Sema::AssociatedClassSet AssociatedClasses;
  10122. OpaqueValueExpr OVE(Loc, Ty, VK_LValue);
  10123. SemaRef.FindAssociatedClassesAndNamespaces(Loc, &OVE, AssociatedNamespaces,
  10124. AssociatedClasses);
  10125. // C++ [basic.lookup.argdep]p3:
  10126. // Let X be the lookup set produced by unqualified lookup (3.4.1)
  10127. // and let Y be the lookup set produced by argument dependent
  10128. // lookup (defined as follows). If X contains [...] then Y is
  10129. // empty. Otherwise Y is the set of declarations found in the
  10130. // namespaces associated with the argument types as described
  10131. // below. The set of declarations found by the lookup of the name
  10132. // is the union of X and Y.
  10133. //
  10134. // Here, we compute Y and add its members to the overloaded
  10135. // candidate set.
  10136. for (auto *NS : AssociatedNamespaces) {
  10137. // When considering an associated namespace, the lookup is the
  10138. // same as the lookup performed when the associated namespace is
  10139. // used as a qualifier (3.4.3.2) except that:
  10140. //
  10141. // -- Any using-directives in the associated namespace are
  10142. // ignored.
  10143. //
  10144. // -- Any namespace-scope friend functions declared in
  10145. // associated classes are visible within their respective
  10146. // namespaces even if they are not visible during an ordinary
  10147. // lookup (11.4).
  10148. DeclContext::lookup_result R = NS->lookup(Id.getName());
  10149. for (auto *D : R) {
  10150. auto *Underlying = D;
  10151. if (auto *USD = dyn_cast<UsingShadowDecl>(D))
  10152. Underlying = USD->getTargetDecl();
  10153. if (!isa<OMPDeclareReductionDecl>(Underlying) &&
  10154. !isa<OMPDeclareMapperDecl>(Underlying))
  10155. continue;
  10156. if (!SemaRef.isVisible(D)) {
  10157. D = findAcceptableDecl(SemaRef, D);
  10158. if (!D)
  10159. continue;
  10160. if (auto *USD = dyn_cast<UsingShadowDecl>(D))
  10161. Underlying = USD->getTargetDecl();
  10162. }
  10163. Lookups.emplace_back();
  10164. Lookups.back().addDecl(Underlying);
  10165. }
  10166. }
  10167. }
  10168. static ExprResult
  10169. buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
  10170. Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
  10171. const DeclarationNameInfo &ReductionId, QualType Ty,
  10172. CXXCastPath &BasePath, Expr *UnresolvedReduction) {
  10173. if (ReductionIdScopeSpec.isInvalid())
  10174. return ExprError();
  10175. SmallVector<UnresolvedSet<8>, 4> Lookups;
  10176. if (S) {
  10177. LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
  10178. Lookup.suppressDiagnostics();
  10179. while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
  10180. NamedDecl *D = Lookup.getRepresentativeDecl();
  10181. do {
  10182. S = S->getParent();
  10183. } while (S && !S->isDeclScope(D));
  10184. if (S)
  10185. S = S->getParent();
  10186. Lookups.emplace_back();
  10187. Lookups.back().append(Lookup.begin(), Lookup.end());
  10188. Lookup.clear();
  10189. }
  10190. } else if (auto *ULE =
  10191. cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
  10192. Lookups.push_back(UnresolvedSet<8>());
  10193. Decl *PrevD = nullptr;
  10194. for (NamedDecl *D : ULE->decls()) {
  10195. if (D == PrevD)
  10196. Lookups.push_back(UnresolvedSet<8>());
  10197. else if (auto *DRD = cast<OMPDeclareReductionDecl>(D))
  10198. Lookups.back().addDecl(DRD);
  10199. PrevD = D;
  10200. }
  10201. }
  10202. if (SemaRef.CurContext->isDependentContext() || Ty->isDependentType() ||
  10203. Ty->isInstantiationDependentType() ||
  10204. Ty->containsUnexpandedParameterPack() ||
  10205. filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) {
  10206. return !D->isInvalidDecl() &&
  10207. (D->getType()->isDependentType() ||
  10208. D->getType()->isInstantiationDependentType() ||
  10209. D->getType()->containsUnexpandedParameterPack());
  10210. })) {
  10211. UnresolvedSet<8> ResSet;
  10212. for (const UnresolvedSet<8> &Set : Lookups) {
  10213. if (Set.empty())
  10214. continue;
  10215. ResSet.append(Set.begin(), Set.end());
  10216. // The last item marks the end of all declarations at the specified scope.
  10217. ResSet.addDecl(Set[Set.size() - 1]);
  10218. }
  10219. return UnresolvedLookupExpr::Create(
  10220. SemaRef.Context, /*NamingClass=*/nullptr,
  10221. ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
  10222. /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
  10223. }
  10224. // Lookup inside the classes.
  10225. // C++ [over.match.oper]p3:
  10226. // For a unary operator @ with an operand of a type whose
  10227. // cv-unqualified version is T1, and for a binary operator @ with
  10228. // a left operand of a type whose cv-unqualified version is T1 and
  10229. // a right operand of a type whose cv-unqualified version is T2,
  10230. // three sets of candidate functions, designated member
  10231. // candidates, non-member candidates and built-in candidates, are
  10232. // constructed as follows:
  10233. // -- If T1 is a complete class type or a class currently being
  10234. // defined, the set of member candidates is the result of the
  10235. // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
  10236. // the set of member candidates is empty.
  10237. LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
  10238. Lookup.suppressDiagnostics();
  10239. if (const auto *TyRec = Ty->getAs<RecordType>()) {
  10240. // Complete the type if it can be completed.
  10241. // If the type is neither complete nor being defined, bail out now.
  10242. if (SemaRef.isCompleteType(Loc, Ty) || TyRec->isBeingDefined() ||
  10243. TyRec->getDecl()->getDefinition()) {
  10244. Lookup.clear();
  10245. SemaRef.LookupQualifiedName(Lookup, TyRec->getDecl());
  10246. if (Lookup.empty()) {
  10247. Lookups.emplace_back();
  10248. Lookups.back().append(Lookup.begin(), Lookup.end());
  10249. }
  10250. }
  10251. }
  10252. // Perform ADL.
  10253. if (SemaRef.getLangOpts().CPlusPlus) {
  10254. argumentDependentLookup(SemaRef, ReductionId, Loc, Ty, Lookups);
  10255. if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
  10256. Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
  10257. if (!D->isInvalidDecl() &&
  10258. SemaRef.Context.hasSameType(D->getType(), Ty))
  10259. return D;
  10260. return nullptr;
  10261. }))
  10262. return SemaRef.BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(),
  10263. VK_LValue, Loc);
  10264. if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
  10265. Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
  10266. if (!D->isInvalidDecl() &&
  10267. SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
  10268. !Ty.isMoreQualifiedThan(D->getType()))
  10269. return D;
  10270. return nullptr;
  10271. })) {
  10272. CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
  10273. /*DetectVirtual=*/false);
  10274. if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
  10275. if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
  10276. VD->getType().getUnqualifiedType()))) {
  10277. if (SemaRef.CheckBaseClassAccess(
  10278. Loc, VD->getType(), Ty, Paths.front(),
  10279. /*DiagID=*/0) != Sema::AR_inaccessible) {
  10280. SemaRef.BuildBasePathArray(Paths, BasePath);
  10281. return SemaRef.BuildDeclRefExpr(
  10282. VD, VD->getType().getNonReferenceType(), VK_LValue, Loc);
  10283. }
  10284. }
  10285. }
  10286. }
  10287. }
  10288. if (ReductionIdScopeSpec.isSet()) {
  10289. SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range;
  10290. return ExprError();
  10291. }
  10292. return ExprEmpty();
  10293. }
  10294. namespace {
  10295. /// Data for the reduction-based clauses.
  10296. struct ReductionData {
  10297. /// List of original reduction items.
  10298. SmallVector<Expr *, 8> Vars;
  10299. /// List of private copies of the reduction items.
  10300. SmallVector<Expr *, 8> Privates;
  10301. /// LHS expressions for the reduction_op expressions.
  10302. SmallVector<Expr *, 8> LHSs;
  10303. /// RHS expressions for the reduction_op expressions.
  10304. SmallVector<Expr *, 8> RHSs;
  10305. /// Reduction operation expression.
  10306. SmallVector<Expr *, 8> ReductionOps;
  10307. /// Taskgroup descriptors for the corresponding reduction items in
  10308. /// in_reduction clauses.
  10309. SmallVector<Expr *, 8> TaskgroupDescriptors;
  10310. /// List of captures for clause.
  10311. SmallVector<Decl *, 4> ExprCaptures;
  10312. /// List of postupdate expressions.
  10313. SmallVector<Expr *, 4> ExprPostUpdates;
  10314. ReductionData() = delete;
  10315. /// Reserves required memory for the reduction data.
  10316. ReductionData(unsigned Size) {
  10317. Vars.reserve(Size);
  10318. Privates.reserve(Size);
  10319. LHSs.reserve(Size);
  10320. RHSs.reserve(Size);
  10321. ReductionOps.reserve(Size);
  10322. TaskgroupDescriptors.reserve(Size);
  10323. ExprCaptures.reserve(Size);
  10324. ExprPostUpdates.reserve(Size);
  10325. }
  10326. /// Stores reduction item and reduction operation only (required for dependent
  10327. /// reduction item).
  10328. void push(Expr *Item, Expr *ReductionOp) {
  10329. Vars.emplace_back(Item);
  10330. Privates.emplace_back(nullptr);
  10331. LHSs.emplace_back(nullptr);
  10332. RHSs.emplace_back(nullptr);
  10333. ReductionOps.emplace_back(ReductionOp);
  10334. TaskgroupDescriptors.emplace_back(nullptr);
  10335. }
  10336. /// Stores reduction data.
  10337. void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS, Expr *ReductionOp,
  10338. Expr *TaskgroupDescriptor) {
  10339. Vars.emplace_back(Item);
  10340. Privates.emplace_back(Private);
  10341. LHSs.emplace_back(LHS);
  10342. RHSs.emplace_back(RHS);
  10343. ReductionOps.emplace_back(ReductionOp);
  10344. TaskgroupDescriptors.emplace_back(TaskgroupDescriptor);
  10345. }
  10346. };
  10347. } // namespace
  10348. static bool checkOMPArraySectionConstantForReduction(
  10349. ASTContext &Context, const OMPArraySectionExpr *OASE, bool &SingleElement,
  10350. SmallVectorImpl<llvm::APSInt> &ArraySizes) {
  10351. const Expr *Length = OASE->getLength();
  10352. if (Length == nullptr) {
  10353. // For array sections of the form [1:] or [:], we would need to analyze
  10354. // the lower bound...
  10355. if (OASE->getColonLoc().isValid())
  10356. return false;
  10357. // This is an array subscript which has implicit length 1!
  10358. SingleElement = true;
  10359. ArraySizes.push_back(llvm::APSInt::get(1));
  10360. } else {
  10361. Expr::EvalResult Result;
  10362. if (!Length->EvaluateAsInt(Result, Context))
  10363. return false;
  10364. llvm::APSInt ConstantLengthValue = Result.Val.getInt();
  10365. SingleElement = (ConstantLengthValue.getSExtValue() == 1);
  10366. ArraySizes.push_back(ConstantLengthValue);
  10367. }
  10368. // Get the base of this array section and walk up from there.
  10369. const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
  10370. // We require length = 1 for all array sections except the right-most to
  10371. // guarantee that the memory region is contiguous and has no holes in it.
  10372. while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) {
  10373. Length = TempOASE->getLength();
  10374. if (Length == nullptr) {
  10375. // For array sections of the form [1:] or [:], we would need to analyze
  10376. // the lower bound...
  10377. if (OASE->getColonLoc().isValid())
  10378. return false;
  10379. // This is an array subscript which has implicit length 1!
  10380. ArraySizes.push_back(llvm::APSInt::get(1));
  10381. } else {
  10382. Expr::EvalResult Result;
  10383. if (!Length->EvaluateAsInt(Result, Context))
  10384. return false;
  10385. llvm::APSInt ConstantLengthValue = Result.Val.getInt();
  10386. if (ConstantLengthValue.getSExtValue() != 1)
  10387. return false;
  10388. ArraySizes.push_back(ConstantLengthValue);
  10389. }
  10390. Base = TempOASE->getBase()->IgnoreParenImpCasts();
  10391. }
  10392. // If we have a single element, we don't need to add the implicit lengths.
  10393. if (!SingleElement) {
  10394. while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) {
  10395. // Has implicit length 1!
  10396. ArraySizes.push_back(llvm::APSInt::get(1));
  10397. Base = TempASE->getBase()->IgnoreParenImpCasts();
  10398. }
  10399. }
  10400. // This array section can be privatized as a single value or as a constant
  10401. // sized array.
  10402. return true;
  10403. }
  10404. static bool actOnOMPReductionKindClause(
  10405. Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind,
  10406. ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
  10407. SourceLocation ColonLoc, SourceLocation EndLoc,
  10408. CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
  10409. ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) {
  10410. DeclarationName DN = ReductionId.getName();
  10411. OverloadedOperatorKind OOK = DN.getCXXOverloadedOperator();
  10412. BinaryOperatorKind BOK = BO_Comma;
  10413. ASTContext &Context = S.Context;
  10414. // OpenMP [2.14.3.6, reduction clause]
  10415. // C
  10416. // reduction-identifier is either an identifier or one of the following
  10417. // operators: +, -, *, &, |, ^, && and ||
  10418. // C++
  10419. // reduction-identifier is either an id-expression or one of the following
  10420. // operators: +, -, *, &, |, ^, && and ||
  10421. switch (OOK) {
  10422. case OO_Plus:
  10423. case OO_Minus:
  10424. BOK = BO_Add;
  10425. break;
  10426. case OO_Star:
  10427. BOK = BO_Mul;
  10428. break;
  10429. case OO_Amp:
  10430. BOK = BO_And;
  10431. break;
  10432. case OO_Pipe:
  10433. BOK = BO_Or;
  10434. break;
  10435. case OO_Caret:
  10436. BOK = BO_Xor;
  10437. break;
  10438. case OO_AmpAmp:
  10439. BOK = BO_LAnd;
  10440. break;
  10441. case OO_PipePipe:
  10442. BOK = BO_LOr;
  10443. break;
  10444. case OO_New:
  10445. case OO_Delete:
  10446. case OO_Array_New:
  10447. case OO_Array_Delete:
  10448. case OO_Slash:
  10449. case OO_Percent:
  10450. case OO_Tilde:
  10451. case OO_Exclaim:
  10452. case OO_Equal:
  10453. case OO_Less:
  10454. case OO_Greater:
  10455. case OO_LessEqual:
  10456. case OO_GreaterEqual:
  10457. case OO_PlusEqual:
  10458. case OO_MinusEqual:
  10459. case OO_StarEqual:
  10460. case OO_SlashEqual:
  10461. case OO_PercentEqual:
  10462. case OO_CaretEqual:
  10463. case OO_AmpEqual:
  10464. case OO_PipeEqual:
  10465. case OO_LessLess:
  10466. case OO_GreaterGreater:
  10467. case OO_LessLessEqual:
  10468. case OO_GreaterGreaterEqual:
  10469. case OO_EqualEqual:
  10470. case OO_ExclaimEqual:
  10471. case OO_Spaceship:
  10472. case OO_PlusPlus:
  10473. case OO_MinusMinus:
  10474. case OO_Comma:
  10475. case OO_ArrowStar:
  10476. case OO_Arrow:
  10477. case OO_Call:
  10478. case OO_Subscript:
  10479. case OO_Conditional:
  10480. case OO_Coawait:
  10481. case NUM_OVERLOADED_OPERATORS:
  10482. llvm_unreachable("Unexpected reduction identifier");
  10483. case OO_None:
  10484. if (IdentifierInfo *II = DN.getAsIdentifierInfo()) {
  10485. if (II->isStr("max"))
  10486. BOK = BO_GT;
  10487. else if (II->isStr("min"))
  10488. BOK = BO_LT;
  10489. }
  10490. break;
  10491. }
  10492. SourceRange ReductionIdRange;
  10493. if (ReductionIdScopeSpec.isValid())
  10494. ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
  10495. else
  10496. ReductionIdRange.setBegin(ReductionId.getBeginLoc());
  10497. ReductionIdRange.setEnd(ReductionId.getEndLoc());
  10498. auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
  10499. bool FirstIter = true;
  10500. for (Expr *RefExpr : VarList) {
  10501. assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
  10502. // OpenMP [2.1, C/C++]
  10503. // A list item is a variable or array section, subject to the restrictions
  10504. // specified in Section 2.4 on page 42 and in each of the sections
  10505. // describing clauses and directives for which a list appears.
  10506. // OpenMP [2.14.3.3, Restrictions, p.1]
  10507. // A variable that is part of another variable (as an array or
  10508. // structure element) cannot appear in a private clause.
  10509. if (!FirstIter && IR != ER)
  10510. ++IR;
  10511. FirstIter = false;
  10512. SourceLocation ELoc;
  10513. SourceRange ERange;
  10514. Expr *SimpleRefExpr = RefExpr;
  10515. auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
  10516. /*AllowArraySection=*/true);
  10517. if (Res.second) {
  10518. // Try to find 'declare reduction' corresponding construct before using
  10519. // builtin/overloaded operators.
  10520. QualType Type = Context.DependentTy;
  10521. CXXCastPath BasePath;
  10522. ExprResult DeclareReductionRef = buildDeclareReductionRef(
  10523. S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
  10524. ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
  10525. Expr *ReductionOp = nullptr;
  10526. if (S.CurContext->isDependentContext() &&
  10527. (DeclareReductionRef.isUnset() ||
  10528. isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
  10529. ReductionOp = DeclareReductionRef.get();
  10530. // It will be analyzed later.
  10531. RD.push(RefExpr, ReductionOp);
  10532. }
  10533. ValueDecl *D = Res.first;
  10534. if (!D)
  10535. continue;
  10536. Expr *TaskgroupDescriptor = nullptr;
  10537. QualType Type;
  10538. auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
  10539. auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
  10540. if (ASE) {
  10541. Type = ASE->getType().getNonReferenceType();
  10542. } else if (OASE) {
  10543. QualType BaseType =
  10544. OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
  10545. if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
  10546. Type = ATy->getElementType();
  10547. else
  10548. Type = BaseType->getPointeeType();
  10549. Type = Type.getNonReferenceType();
  10550. } else {
  10551. Type = Context.getBaseElementType(D->getType().getNonReferenceType());
  10552. }
  10553. auto *VD = dyn_cast<VarDecl>(D);
  10554. // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
  10555. // A variable that appears in a private clause must not have an incomplete
  10556. // type or a reference type.
  10557. if (S.RequireCompleteType(ELoc, D->getType(),
  10558. diag::err_omp_reduction_incomplete_type))
  10559. continue;
  10560. // OpenMP [2.14.3.6, reduction clause, Restrictions]
  10561. // A list item that appears in a reduction clause must not be
  10562. // const-qualified.
  10563. if (rejectConstNotMutableType(S, D, Type, ClauseKind, ELoc,
  10564. /*AcceptIfMutable*/ false, ASE || OASE))
  10565. continue;
  10566. OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective();
  10567. // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
  10568. // If a list-item is a reference type then it must bind to the same object
  10569. // for all threads of the team.
  10570. if (!ASE && !OASE) {
  10571. if (VD) {
  10572. VarDecl *VDDef = VD->getDefinition();
  10573. if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
  10574. DSARefChecker Check(Stack);
  10575. if (Check.Visit(VDDef->getInit())) {
  10576. S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg)
  10577. << getOpenMPClauseName(ClauseKind) << ERange;
  10578. S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
  10579. continue;
  10580. }
  10581. }
  10582. }
  10583. // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
  10584. // in a Construct]
  10585. // Variables with the predetermined data-sharing attributes may not be
  10586. // listed in data-sharing attributes clauses, except for the cases
  10587. // listed below. For these exceptions only, listing a predetermined
  10588. // variable in a data-sharing attribute clause is allowed and overrides
  10589. // the variable's predetermined data-sharing attributes.
  10590. // OpenMP [2.14.3.6, Restrictions, p.3]
  10591. // Any number of reduction clauses can be specified on the directive,
  10592. // but a list item can appear only once in the reduction clauses for that
  10593. // directive.
  10594. DSAStackTy::DSAVarData DVar = Stack->getTopDSA(D, /*FromParent=*/false);
  10595. if (DVar.CKind == OMPC_reduction) {
  10596. S.Diag(ELoc, diag::err_omp_once_referenced)
  10597. << getOpenMPClauseName(ClauseKind);
  10598. if (DVar.RefExpr)
  10599. S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
  10600. continue;
  10601. }
  10602. if (DVar.CKind != OMPC_unknown) {
  10603. S.Diag(ELoc, diag::err_omp_wrong_dsa)
  10604. << getOpenMPClauseName(DVar.CKind)
  10605. << getOpenMPClauseName(OMPC_reduction);
  10606. reportOriginalDsa(S, Stack, D, DVar);
  10607. continue;
  10608. }
  10609. // OpenMP [2.14.3.6, Restrictions, p.1]
  10610. // A list item that appears in a reduction clause of a worksharing
  10611. // construct must be shared in the parallel regions to which any of the
  10612. // worksharing regions arising from the worksharing construct bind.
  10613. if (isOpenMPWorksharingDirective(CurrDir) &&
  10614. !isOpenMPParallelDirective(CurrDir) &&
  10615. !isOpenMPTeamsDirective(CurrDir)) {
  10616. DVar = Stack->getImplicitDSA(D, true);
  10617. if (DVar.CKind != OMPC_shared) {
  10618. S.Diag(ELoc, diag::err_omp_required_access)
  10619. << getOpenMPClauseName(OMPC_reduction)
  10620. << getOpenMPClauseName(OMPC_shared);
  10621. reportOriginalDsa(S, Stack, D, DVar);
  10622. continue;
  10623. }
  10624. }
  10625. }
  10626. // Try to find 'declare reduction' corresponding construct before using
  10627. // builtin/overloaded operators.
  10628. CXXCastPath BasePath;
  10629. ExprResult DeclareReductionRef = buildDeclareReductionRef(
  10630. S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
  10631. ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
  10632. if (DeclareReductionRef.isInvalid())
  10633. continue;
  10634. if (S.CurContext->isDependentContext() &&
  10635. (DeclareReductionRef.isUnset() ||
  10636. isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
  10637. RD.push(RefExpr, DeclareReductionRef.get());
  10638. continue;
  10639. }
  10640. if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
  10641. // Not allowed reduction identifier is found.
  10642. S.Diag(ReductionId.getBeginLoc(),
  10643. diag::err_omp_unknown_reduction_identifier)
  10644. << Type << ReductionIdRange;
  10645. continue;
  10646. }
  10647. // OpenMP [2.14.3.6, reduction clause, Restrictions]
  10648. // The type of a list item that appears in a reduction clause must be valid
  10649. // for the reduction-identifier. For a max or min reduction in C, the type
  10650. // of the list item must be an allowed arithmetic data type: char, int,
  10651. // float, double, or _Bool, possibly modified with long, short, signed, or
  10652. // unsigned. For a max or min reduction in C++, the type of the list item
  10653. // must be an allowed arithmetic data type: char, wchar_t, int, float,
  10654. // double, or bool, possibly modified with long, short, signed, or unsigned.
  10655. if (DeclareReductionRef.isUnset()) {
  10656. if ((BOK == BO_GT || BOK == BO_LT) &&
  10657. !(Type->isScalarType() ||
  10658. (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
  10659. S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
  10660. << getOpenMPClauseName(ClauseKind) << S.getLangOpts().CPlusPlus;
  10661. if (!ASE && !OASE) {
  10662. bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
  10663. VarDecl::DeclarationOnly;
  10664. S.Diag(D->getLocation(),
  10665. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  10666. << D;
  10667. }
  10668. continue;
  10669. }
  10670. if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
  10671. !S.getLangOpts().CPlusPlus && Type->isFloatingType()) {
  10672. S.Diag(ELoc, diag::err_omp_clause_floating_type_arg)
  10673. << getOpenMPClauseName(ClauseKind);
  10674. if (!ASE && !OASE) {
  10675. bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
  10676. VarDecl::DeclarationOnly;
  10677. S.Diag(D->getLocation(),
  10678. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  10679. << D;
  10680. }
  10681. continue;
  10682. }
  10683. }
  10684. Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
  10685. VarDecl *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs",
  10686. D->hasAttrs() ? &D->getAttrs() : nullptr);
  10687. VarDecl *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(),
  10688. D->hasAttrs() ? &D->getAttrs() : nullptr);
  10689. QualType PrivateTy = Type;
  10690. // Try if we can determine constant lengths for all array sections and avoid
  10691. // the VLA.
  10692. bool ConstantLengthOASE = false;
  10693. if (OASE) {
  10694. bool SingleElement;
  10695. llvm::SmallVector<llvm::APSInt, 4> ArraySizes;
  10696. ConstantLengthOASE = checkOMPArraySectionConstantForReduction(
  10697. Context, OASE, SingleElement, ArraySizes);
  10698. // If we don't have a single element, we must emit a constant array type.
  10699. if (ConstantLengthOASE && !SingleElement) {
  10700. for (llvm::APSInt &Size : ArraySizes)
  10701. PrivateTy = Context.getConstantArrayType(
  10702. PrivateTy, Size, ArrayType::Normal, /*IndexTypeQuals=*/0);
  10703. }
  10704. }
  10705. if ((OASE && !ConstantLengthOASE) ||
  10706. (!OASE && !ASE &&
  10707. D->getType().getNonReferenceType()->isVariablyModifiedType())) {
  10708. if (!Context.getTargetInfo().isVLASupported() &&
  10709. S.shouldDiagnoseTargetSupportFromOpenMP()) {
  10710. S.Diag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
  10711. S.Diag(ELoc, diag::note_vla_unsupported);
  10712. continue;
  10713. }
  10714. // For arrays/array sections only:
  10715. // Create pseudo array type for private copy. The size for this array will
  10716. // be generated during codegen.
  10717. // For array subscripts or single variables Private Ty is the same as Type
  10718. // (type of the variable or single array element).
  10719. PrivateTy = Context.getVariableArrayType(
  10720. Type,
  10721. new (Context) OpaqueValueExpr(ELoc, Context.getSizeType(), VK_RValue),
  10722. ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
  10723. } else if (!ASE && !OASE &&
  10724. Context.getAsArrayType(D->getType().getNonReferenceType())) {
  10725. PrivateTy = D->getType().getNonReferenceType();
  10726. }
  10727. // Private copy.
  10728. VarDecl *PrivateVD =
  10729. buildVarDecl(S, ELoc, PrivateTy, D->getName(),
  10730. D->hasAttrs() ? &D->getAttrs() : nullptr,
  10731. VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
  10732. // Add initializer for private variable.
  10733. Expr *Init = nullptr;
  10734. DeclRefExpr *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc);
  10735. DeclRefExpr *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc);
  10736. if (DeclareReductionRef.isUsable()) {
  10737. auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
  10738. auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
  10739. if (DRD->getInitializer()) {
  10740. Init = DRDRef;
  10741. RHSVD->setInit(DRDRef);
  10742. RHSVD->setInitStyle(VarDecl::CallInit);
  10743. }
  10744. } else {
  10745. switch (BOK) {
  10746. case BO_Add:
  10747. case BO_Xor:
  10748. case BO_Or:
  10749. case BO_LOr:
  10750. // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
  10751. if (Type->isScalarType() || Type->isAnyComplexType())
  10752. Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get();
  10753. break;
  10754. case BO_Mul:
  10755. case BO_LAnd:
  10756. if (Type->isScalarType() || Type->isAnyComplexType()) {
  10757. // '*' and '&&' reduction ops - initializer is '1'.
  10758. Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get();
  10759. }
  10760. break;
  10761. case BO_And: {
  10762. // '&' reduction op - initializer is '~0'.
  10763. QualType OrigType = Type;
  10764. if (auto *ComplexTy = OrigType->getAs<ComplexType>())
  10765. Type = ComplexTy->getElementType();
  10766. if (Type->isRealFloatingType()) {
  10767. llvm::APFloat InitValue =
  10768. llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
  10769. /*isIEEE=*/true);
  10770. Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
  10771. Type, ELoc);
  10772. } else if (Type->isScalarType()) {
  10773. uint64_t Size = Context.getTypeSize(Type);
  10774. QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
  10775. llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
  10776. Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
  10777. }
  10778. if (Init && OrigType->isAnyComplexType()) {
  10779. // Init = 0xFFFF + 0xFFFFi;
  10780. auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
  10781. Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
  10782. }
  10783. Type = OrigType;
  10784. break;
  10785. }
  10786. case BO_LT:
  10787. case BO_GT: {
  10788. // 'min' reduction op - initializer is 'Largest representable number in
  10789. // the reduction list item type'.
  10790. // 'max' reduction op - initializer is 'Least representable number in
  10791. // the reduction list item type'.
  10792. if (Type->isIntegerType() || Type->isPointerType()) {
  10793. bool IsSigned = Type->hasSignedIntegerRepresentation();
  10794. uint64_t Size = Context.getTypeSize(Type);
  10795. QualType IntTy =
  10796. Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
  10797. llvm::APInt InitValue =
  10798. (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
  10799. : llvm::APInt::getMinValue(Size)
  10800. : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
  10801. : llvm::APInt::getMaxValue(Size);
  10802. Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
  10803. if (Type->isPointerType()) {
  10804. // Cast to pointer type.
  10805. ExprResult CastExpr = S.BuildCStyleCastExpr(
  10806. ELoc, Context.getTrivialTypeSourceInfo(Type, ELoc), ELoc, Init);
  10807. if (CastExpr.isInvalid())
  10808. continue;
  10809. Init = CastExpr.get();
  10810. }
  10811. } else if (Type->isRealFloatingType()) {
  10812. llvm::APFloat InitValue = llvm::APFloat::getLargest(
  10813. Context.getFloatTypeSemantics(Type), BOK != BO_LT);
  10814. Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
  10815. Type, ELoc);
  10816. }
  10817. break;
  10818. }
  10819. case BO_PtrMemD:
  10820. case BO_PtrMemI:
  10821. case BO_MulAssign:
  10822. case BO_Div:
  10823. case BO_Rem:
  10824. case BO_Sub:
  10825. case BO_Shl:
  10826. case BO_Shr:
  10827. case BO_LE:
  10828. case BO_GE:
  10829. case BO_EQ:
  10830. case BO_NE:
  10831. case BO_Cmp:
  10832. case BO_AndAssign:
  10833. case BO_XorAssign:
  10834. case BO_OrAssign:
  10835. case BO_Assign:
  10836. case BO_AddAssign:
  10837. case BO_SubAssign:
  10838. case BO_DivAssign:
  10839. case BO_RemAssign:
  10840. case BO_ShlAssign:
  10841. case BO_ShrAssign:
  10842. case BO_Comma:
  10843. llvm_unreachable("Unexpected reduction operation");
  10844. }
  10845. }
  10846. if (Init && DeclareReductionRef.isUnset())
  10847. S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false);
  10848. else if (!Init)
  10849. S.ActOnUninitializedDecl(RHSVD);
  10850. if (RHSVD->isInvalidDecl())
  10851. continue;
  10852. if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) {
  10853. S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible)
  10854. << Type << ReductionIdRange;
  10855. bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
  10856. VarDecl::DeclarationOnly;
  10857. S.Diag(D->getLocation(),
  10858. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  10859. << D;
  10860. continue;
  10861. }
  10862. // Store initializer for single element in private copy. Will be used during
  10863. // codegen.
  10864. PrivateVD->setInit(RHSVD->getInit());
  10865. PrivateVD->setInitStyle(RHSVD->getInitStyle());
  10866. DeclRefExpr *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc);
  10867. ExprResult ReductionOp;
  10868. if (DeclareReductionRef.isUsable()) {
  10869. QualType RedTy = DeclareReductionRef.get()->getType();
  10870. QualType PtrRedTy = Context.getPointerType(RedTy);
  10871. ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
  10872. ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
  10873. if (!BasePath.empty()) {
  10874. LHS = S.DefaultLvalueConversion(LHS.get());
  10875. RHS = S.DefaultLvalueConversion(RHS.get());
  10876. LHS = ImplicitCastExpr::Create(Context, PtrRedTy,
  10877. CK_UncheckedDerivedToBase, LHS.get(),
  10878. &BasePath, LHS.get()->getValueKind());
  10879. RHS = ImplicitCastExpr::Create(Context, PtrRedTy,
  10880. CK_UncheckedDerivedToBase, RHS.get(),
  10881. &BasePath, RHS.get()->getValueKind());
  10882. }
  10883. FunctionProtoType::ExtProtoInfo EPI;
  10884. QualType Params[] = {PtrRedTy, PtrRedTy};
  10885. QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
  10886. auto *OVE = new (Context) OpaqueValueExpr(
  10887. ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary,
  10888. S.DefaultLvalueConversion(DeclareReductionRef.get()).get());
  10889. Expr *Args[] = {LHS.get(), RHS.get()};
  10890. ReductionOp =
  10891. CallExpr::Create(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc);
  10892. } else {
  10893. ReductionOp = S.BuildBinOp(
  10894. Stack->getCurScope(), ReductionId.getBeginLoc(), BOK, LHSDRE, RHSDRE);
  10895. if (ReductionOp.isUsable()) {
  10896. if (BOK != BO_LT && BOK != BO_GT) {
  10897. ReductionOp =
  10898. S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
  10899. BO_Assign, LHSDRE, ReductionOp.get());
  10900. } else {
  10901. auto *ConditionalOp = new (Context)
  10902. ConditionalOperator(ReductionOp.get(), ELoc, LHSDRE, ELoc, RHSDRE,
  10903. Type, VK_LValue, OK_Ordinary);
  10904. ReductionOp =
  10905. S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
  10906. BO_Assign, LHSDRE, ConditionalOp);
  10907. }
  10908. if (ReductionOp.isUsable())
  10909. ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get(),
  10910. /*DiscardedValue*/ false);
  10911. }
  10912. if (!ReductionOp.isUsable())
  10913. continue;
  10914. }
  10915. // OpenMP [2.15.4.6, Restrictions, p.2]
  10916. // A list item that appears in an in_reduction clause of a task construct
  10917. // must appear in a task_reduction clause of a construct associated with a
  10918. // taskgroup region that includes the participating task in its taskgroup
  10919. // set. The construct associated with the innermost region that meets this
  10920. // condition must specify the same reduction-identifier as the in_reduction
  10921. // clause.
  10922. if (ClauseKind == OMPC_in_reduction) {
  10923. SourceRange ParentSR;
  10924. BinaryOperatorKind ParentBOK;
  10925. const Expr *ParentReductionOp;
  10926. Expr *ParentBOKTD, *ParentReductionOpTD;
  10927. DSAStackTy::DSAVarData ParentBOKDSA =
  10928. Stack->getTopMostTaskgroupReductionData(D, ParentSR, ParentBOK,
  10929. ParentBOKTD);
  10930. DSAStackTy::DSAVarData ParentReductionOpDSA =
  10931. Stack->getTopMostTaskgroupReductionData(
  10932. D, ParentSR, ParentReductionOp, ParentReductionOpTD);
  10933. bool IsParentBOK = ParentBOKDSA.DKind != OMPD_unknown;
  10934. bool IsParentReductionOp = ParentReductionOpDSA.DKind != OMPD_unknown;
  10935. if (!IsParentBOK && !IsParentReductionOp) {
  10936. S.Diag(ELoc, diag::err_omp_in_reduction_not_task_reduction);
  10937. continue;
  10938. }
  10939. if ((DeclareReductionRef.isUnset() && IsParentReductionOp) ||
  10940. (DeclareReductionRef.isUsable() && IsParentBOK) || BOK != ParentBOK ||
  10941. IsParentReductionOp) {
  10942. bool EmitError = true;
  10943. if (IsParentReductionOp && DeclareReductionRef.isUsable()) {
  10944. llvm::FoldingSetNodeID RedId, ParentRedId;
  10945. ParentReductionOp->Profile(ParentRedId, Context, /*Canonical=*/true);
  10946. DeclareReductionRef.get()->Profile(RedId, Context,
  10947. /*Canonical=*/true);
  10948. EmitError = RedId != ParentRedId;
  10949. }
  10950. if (EmitError) {
  10951. S.Diag(ReductionId.getBeginLoc(),
  10952. diag::err_omp_reduction_identifier_mismatch)
  10953. << ReductionIdRange << RefExpr->getSourceRange();
  10954. S.Diag(ParentSR.getBegin(),
  10955. diag::note_omp_previous_reduction_identifier)
  10956. << ParentSR
  10957. << (IsParentBOK ? ParentBOKDSA.RefExpr
  10958. : ParentReductionOpDSA.RefExpr)
  10959. ->getSourceRange();
  10960. continue;
  10961. }
  10962. }
  10963. TaskgroupDescriptor = IsParentBOK ? ParentBOKTD : ParentReductionOpTD;
  10964. assert(TaskgroupDescriptor && "Taskgroup descriptor must be defined.");
  10965. }
  10966. DeclRefExpr *Ref = nullptr;
  10967. Expr *VarsExpr = RefExpr->IgnoreParens();
  10968. if (!VD && !S.CurContext->isDependentContext()) {
  10969. if (ASE || OASE) {
  10970. TransformExprToCaptures RebuildToCapture(S, D);
  10971. VarsExpr =
  10972. RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
  10973. Ref = RebuildToCapture.getCapturedExpr();
  10974. } else {
  10975. VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false);
  10976. }
  10977. if (!S.isOpenMPCapturedDecl(D)) {
  10978. RD.ExprCaptures.emplace_back(Ref->getDecl());
  10979. if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
  10980. ExprResult RefRes = S.DefaultLvalueConversion(Ref);
  10981. if (!RefRes.isUsable())
  10982. continue;
  10983. ExprResult PostUpdateRes =
  10984. S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
  10985. RefRes.get());
  10986. if (!PostUpdateRes.isUsable())
  10987. continue;
  10988. if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
  10989. Stack->getCurrentDirective() == OMPD_taskgroup) {
  10990. S.Diag(RefExpr->getExprLoc(),
  10991. diag::err_omp_reduction_non_addressable_expression)
  10992. << RefExpr->getSourceRange();
  10993. continue;
  10994. }
  10995. RD.ExprPostUpdates.emplace_back(
  10996. S.IgnoredValueConversions(PostUpdateRes.get()).get());
  10997. }
  10998. }
  10999. }
  11000. // All reduction items are still marked as reduction (to do not increase
  11001. // code base size).
  11002. Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref);
  11003. if (CurrDir == OMPD_taskgroup) {
  11004. if (DeclareReductionRef.isUsable())
  11005. Stack->addTaskgroupReductionData(D, ReductionIdRange,
  11006. DeclareReductionRef.get());
  11007. else
  11008. Stack->addTaskgroupReductionData(D, ReductionIdRange, BOK);
  11009. }
  11010. RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get(),
  11011. TaskgroupDescriptor);
  11012. }
  11013. return RD.Vars.empty();
  11014. }
  11015. OMPClause *Sema::ActOnOpenMPReductionClause(
  11016. ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
  11017. SourceLocation ColonLoc, SourceLocation EndLoc,
  11018. CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
  11019. ArrayRef<Expr *> UnresolvedReductions) {
  11020. ReductionData RD(VarList.size());
  11021. if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_reduction, VarList,
  11022. StartLoc, LParenLoc, ColonLoc, EndLoc,
  11023. ReductionIdScopeSpec, ReductionId,
  11024. UnresolvedReductions, RD))
  11025. return nullptr;
  11026. return OMPReductionClause::Create(
  11027. Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
  11028. ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
  11029. RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
  11030. buildPreInits(Context, RD.ExprCaptures),
  11031. buildPostUpdate(*this, RD.ExprPostUpdates));
  11032. }
  11033. OMPClause *Sema::ActOnOpenMPTaskReductionClause(
  11034. ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
  11035. SourceLocation ColonLoc, SourceLocation EndLoc,
  11036. CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
  11037. ArrayRef<Expr *> UnresolvedReductions) {
  11038. ReductionData RD(VarList.size());
  11039. if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_task_reduction, VarList,
  11040. StartLoc, LParenLoc, ColonLoc, EndLoc,
  11041. ReductionIdScopeSpec, ReductionId,
  11042. UnresolvedReductions, RD))
  11043. return nullptr;
  11044. return OMPTaskReductionClause::Create(
  11045. Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
  11046. ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
  11047. RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
  11048. buildPreInits(Context, RD.ExprCaptures),
  11049. buildPostUpdate(*this, RD.ExprPostUpdates));
  11050. }
  11051. OMPClause *Sema::ActOnOpenMPInReductionClause(
  11052. ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
  11053. SourceLocation ColonLoc, SourceLocation EndLoc,
  11054. CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
  11055. ArrayRef<Expr *> UnresolvedReductions) {
  11056. ReductionData RD(VarList.size());
  11057. if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_in_reduction, VarList,
  11058. StartLoc, LParenLoc, ColonLoc, EndLoc,
  11059. ReductionIdScopeSpec, ReductionId,
  11060. UnresolvedReductions, RD))
  11061. return nullptr;
  11062. return OMPInReductionClause::Create(
  11063. Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
  11064. ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
  11065. RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.TaskgroupDescriptors,
  11066. buildPreInits(Context, RD.ExprCaptures),
  11067. buildPostUpdate(*this, RD.ExprPostUpdates));
  11068. }
  11069. bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
  11070. SourceLocation LinLoc) {
  11071. if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
  11072. LinKind == OMPC_LINEAR_unknown) {
  11073. Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
  11074. return true;
  11075. }
  11076. return false;
  11077. }
  11078. bool Sema::CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc,
  11079. OpenMPLinearClauseKind LinKind,
  11080. QualType Type) {
  11081. const auto *VD = dyn_cast_or_null<VarDecl>(D);
  11082. // A variable must not have an incomplete type or a reference type.
  11083. if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
  11084. return true;
  11085. if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
  11086. !Type->isReferenceType()) {
  11087. Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
  11088. << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
  11089. return true;
  11090. }
  11091. Type = Type.getNonReferenceType();
  11092. // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
  11093. // A variable that is privatized must not have a const-qualified type
  11094. // unless it is of class type with a mutable member. This restriction does
  11095. // not apply to the firstprivate clause.
  11096. if (rejectConstNotMutableType(*this, D, Type, OMPC_linear, ELoc))
  11097. return true;
  11098. // A list item must be of integral or pointer type.
  11099. Type = Type.getUnqualifiedType().getCanonicalType();
  11100. const auto *Ty = Type.getTypePtrOrNull();
  11101. if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
  11102. !Ty->isPointerType())) {
  11103. Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
  11104. if (D) {
  11105. bool IsDecl =
  11106. !VD ||
  11107. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  11108. Diag(D->getLocation(),
  11109. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  11110. << D;
  11111. }
  11112. return true;
  11113. }
  11114. return false;
  11115. }
  11116. OMPClause *Sema::ActOnOpenMPLinearClause(
  11117. ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
  11118. SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
  11119. SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
  11120. SmallVector<Expr *, 8> Vars;
  11121. SmallVector<Expr *, 8> Privates;
  11122. SmallVector<Expr *, 8> Inits;
  11123. SmallVector<Decl *, 4> ExprCaptures;
  11124. SmallVector<Expr *, 4> ExprPostUpdates;
  11125. if (CheckOpenMPLinearModifier(LinKind, LinLoc))
  11126. LinKind = OMPC_LINEAR_val;
  11127. for (Expr *RefExpr : VarList) {
  11128. assert(RefExpr && "NULL expr in OpenMP linear clause.");
  11129. SourceLocation ELoc;
  11130. SourceRange ERange;
  11131. Expr *SimpleRefExpr = RefExpr;
  11132. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  11133. if (Res.second) {
  11134. // It will be analyzed later.
  11135. Vars.push_back(RefExpr);
  11136. Privates.push_back(nullptr);
  11137. Inits.push_back(nullptr);
  11138. }
  11139. ValueDecl *D = Res.first;
  11140. if (!D)
  11141. continue;
  11142. QualType Type = D->getType();
  11143. auto *VD = dyn_cast<VarDecl>(D);
  11144. // OpenMP [2.14.3.7, linear clause]
  11145. // A list-item cannot appear in more than one linear clause.
  11146. // A list-item that appears in a linear clause cannot appear in any
  11147. // other data-sharing attribute clause.
  11148. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
  11149. if (DVar.RefExpr) {
  11150. Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
  11151. << getOpenMPClauseName(OMPC_linear);
  11152. reportOriginalDsa(*this, DSAStack, D, DVar);
  11153. continue;
  11154. }
  11155. if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
  11156. continue;
  11157. Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
  11158. // Build private copy of original var.
  11159. VarDecl *Private =
  11160. buildVarDecl(*this, ELoc, Type, D->getName(),
  11161. D->hasAttrs() ? &D->getAttrs() : nullptr,
  11162. VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
  11163. DeclRefExpr *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
  11164. // Build var to save initial value.
  11165. VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
  11166. Expr *InitExpr;
  11167. DeclRefExpr *Ref = nullptr;
  11168. if (!VD && !CurContext->isDependentContext()) {
  11169. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
  11170. if (!isOpenMPCapturedDecl(D)) {
  11171. ExprCaptures.push_back(Ref->getDecl());
  11172. if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
  11173. ExprResult RefRes = DefaultLvalueConversion(Ref);
  11174. if (!RefRes.isUsable())
  11175. continue;
  11176. ExprResult PostUpdateRes =
  11177. BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
  11178. SimpleRefExpr, RefRes.get());
  11179. if (!PostUpdateRes.isUsable())
  11180. continue;
  11181. ExprPostUpdates.push_back(
  11182. IgnoredValueConversions(PostUpdateRes.get()).get());
  11183. }
  11184. }
  11185. }
  11186. if (LinKind == OMPC_LINEAR_uval)
  11187. InitExpr = VD ? VD->getInit() : SimpleRefExpr;
  11188. else
  11189. InitExpr = VD ? SimpleRefExpr : Ref;
  11190. AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
  11191. /*DirectInit=*/false);
  11192. DeclRefExpr *InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
  11193. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
  11194. Vars.push_back((VD || CurContext->isDependentContext())
  11195. ? RefExpr->IgnoreParens()
  11196. : Ref);
  11197. Privates.push_back(PrivateRef);
  11198. Inits.push_back(InitRef);
  11199. }
  11200. if (Vars.empty())
  11201. return nullptr;
  11202. Expr *StepExpr = Step;
  11203. Expr *CalcStepExpr = nullptr;
  11204. if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
  11205. !Step->isInstantiationDependent() &&
  11206. !Step->containsUnexpandedParameterPack()) {
  11207. SourceLocation StepLoc = Step->getBeginLoc();
  11208. ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
  11209. if (Val.isInvalid())
  11210. return nullptr;
  11211. StepExpr = Val.get();
  11212. // Build var to save the step value.
  11213. VarDecl *SaveVar =
  11214. buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
  11215. ExprResult SaveRef =
  11216. buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
  11217. ExprResult CalcStep =
  11218. BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
  11219. CalcStep = ActOnFinishFullExpr(CalcStep.get(), /*DiscardedValue*/ false);
  11220. // Warn about zero linear step (it would be probably better specified as
  11221. // making corresponding variables 'const').
  11222. llvm::APSInt Result;
  11223. bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
  11224. if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
  11225. Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
  11226. << (Vars.size() > 1);
  11227. if (!IsConstant && CalcStep.isUsable()) {
  11228. // Calculate the step beforehand instead of doing this on each iteration.
  11229. // (This is not used if the number of iterations may be kfold-ed).
  11230. CalcStepExpr = CalcStep.get();
  11231. }
  11232. }
  11233. return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
  11234. ColonLoc, EndLoc, Vars, Privates, Inits,
  11235. StepExpr, CalcStepExpr,
  11236. buildPreInits(Context, ExprCaptures),
  11237. buildPostUpdate(*this, ExprPostUpdates));
  11238. }
  11239. static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
  11240. Expr *NumIterations, Sema &SemaRef,
  11241. Scope *S, DSAStackTy *Stack) {
  11242. // Walk the vars and build update/final expressions for the CodeGen.
  11243. SmallVector<Expr *, 8> Updates;
  11244. SmallVector<Expr *, 8> Finals;
  11245. Expr *Step = Clause.getStep();
  11246. Expr *CalcStep = Clause.getCalcStep();
  11247. // OpenMP [2.14.3.7, linear clause]
  11248. // If linear-step is not specified it is assumed to be 1.
  11249. if (!Step)
  11250. Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
  11251. else if (CalcStep)
  11252. Step = cast<BinaryOperator>(CalcStep)->getLHS();
  11253. bool HasErrors = false;
  11254. auto CurInit = Clause.inits().begin();
  11255. auto CurPrivate = Clause.privates().begin();
  11256. OpenMPLinearClauseKind LinKind = Clause.getModifier();
  11257. for (Expr *RefExpr : Clause.varlists()) {
  11258. SourceLocation ELoc;
  11259. SourceRange ERange;
  11260. Expr *SimpleRefExpr = RefExpr;
  11261. auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange);
  11262. ValueDecl *D = Res.first;
  11263. if (Res.second || !D) {
  11264. Updates.push_back(nullptr);
  11265. Finals.push_back(nullptr);
  11266. HasErrors = true;
  11267. continue;
  11268. }
  11269. auto &&Info = Stack->isLoopControlVariable(D);
  11270. // OpenMP [2.15.11, distribute simd Construct]
  11271. // A list item may not appear in a linear clause, unless it is the loop
  11272. // iteration variable.
  11273. if (isOpenMPDistributeDirective(Stack->getCurrentDirective()) &&
  11274. isOpenMPSimdDirective(Stack->getCurrentDirective()) && !Info.first) {
  11275. SemaRef.Diag(ELoc,
  11276. diag::err_omp_linear_distribute_var_non_loop_iteration);
  11277. Updates.push_back(nullptr);
  11278. Finals.push_back(nullptr);
  11279. HasErrors = true;
  11280. continue;
  11281. }
  11282. Expr *InitExpr = *CurInit;
  11283. // Build privatized reference to the current linear var.
  11284. auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
  11285. Expr *CapturedRef;
  11286. if (LinKind == OMPC_LINEAR_uval)
  11287. CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
  11288. else
  11289. CapturedRef =
  11290. buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
  11291. DE->getType().getUnqualifiedType(), DE->getExprLoc(),
  11292. /*RefersToCapture=*/true);
  11293. // Build update: Var = InitExpr + IV * Step
  11294. ExprResult Update;
  11295. if (!Info.first)
  11296. Update =
  11297. buildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate,
  11298. InitExpr, IV, Step, /* Subtract */ false);
  11299. else
  11300. Update = *CurPrivate;
  11301. Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getBeginLoc(),
  11302. /*DiscardedValue*/ false);
  11303. // Build final: Var = InitExpr + NumIterations * Step
  11304. ExprResult Final;
  11305. if (!Info.first)
  11306. Final =
  11307. buildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
  11308. InitExpr, NumIterations, Step, /*Subtract=*/false);
  11309. else
  11310. Final = *CurPrivate;
  11311. Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getBeginLoc(),
  11312. /*DiscardedValue*/ false);
  11313. if (!Update.isUsable() || !Final.isUsable()) {
  11314. Updates.push_back(nullptr);
  11315. Finals.push_back(nullptr);
  11316. HasErrors = true;
  11317. } else {
  11318. Updates.push_back(Update.get());
  11319. Finals.push_back(Final.get());
  11320. }
  11321. ++CurInit;
  11322. ++CurPrivate;
  11323. }
  11324. Clause.setUpdates(Updates);
  11325. Clause.setFinals(Finals);
  11326. return HasErrors;
  11327. }
  11328. OMPClause *Sema::ActOnOpenMPAlignedClause(
  11329. ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
  11330. SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
  11331. SmallVector<Expr *, 8> Vars;
  11332. for (Expr *RefExpr : VarList) {
  11333. assert(RefExpr && "NULL expr in OpenMP linear clause.");
  11334. SourceLocation ELoc;
  11335. SourceRange ERange;
  11336. Expr *SimpleRefExpr = RefExpr;
  11337. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  11338. if (Res.second) {
  11339. // It will be analyzed later.
  11340. Vars.push_back(RefExpr);
  11341. }
  11342. ValueDecl *D = Res.first;
  11343. if (!D)
  11344. continue;
  11345. QualType QType = D->getType();
  11346. auto *VD = dyn_cast<VarDecl>(D);
  11347. // OpenMP [2.8.1, simd construct, Restrictions]
  11348. // The type of list items appearing in the aligned clause must be
  11349. // array, pointer, reference to array, or reference to pointer.
  11350. QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
  11351. const Type *Ty = QType.getTypePtrOrNull();
  11352. if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
  11353. Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
  11354. << QType << getLangOpts().CPlusPlus << ERange;
  11355. bool IsDecl =
  11356. !VD ||
  11357. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  11358. Diag(D->getLocation(),
  11359. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  11360. << D;
  11361. continue;
  11362. }
  11363. // OpenMP [2.8.1, simd construct, Restrictions]
  11364. // A list-item cannot appear in more than one aligned clause.
  11365. if (const Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
  11366. Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange;
  11367. Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
  11368. << getOpenMPClauseName(OMPC_aligned);
  11369. continue;
  11370. }
  11371. DeclRefExpr *Ref = nullptr;
  11372. if (!VD && isOpenMPCapturedDecl(D))
  11373. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
  11374. Vars.push_back(DefaultFunctionArrayConversion(
  11375. (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
  11376. .get());
  11377. }
  11378. // OpenMP [2.8.1, simd construct, Description]
  11379. // The parameter of the aligned clause, alignment, must be a constant
  11380. // positive integer expression.
  11381. // If no optional parameter is specified, implementation-defined default
  11382. // alignments for SIMD instructions on the target platforms are assumed.
  11383. if (Alignment != nullptr) {
  11384. ExprResult AlignResult =
  11385. VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
  11386. if (AlignResult.isInvalid())
  11387. return nullptr;
  11388. Alignment = AlignResult.get();
  11389. }
  11390. if (Vars.empty())
  11391. return nullptr;
  11392. return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
  11393. EndLoc, Vars, Alignment);
  11394. }
  11395. OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
  11396. SourceLocation StartLoc,
  11397. SourceLocation LParenLoc,
  11398. SourceLocation EndLoc) {
  11399. SmallVector<Expr *, 8> Vars;
  11400. SmallVector<Expr *, 8> SrcExprs;
  11401. SmallVector<Expr *, 8> DstExprs;
  11402. SmallVector<Expr *, 8> AssignmentOps;
  11403. for (Expr *RefExpr : VarList) {
  11404. assert(RefExpr && "NULL expr in OpenMP copyin clause.");
  11405. if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
  11406. // It will be analyzed later.
  11407. Vars.push_back(RefExpr);
  11408. SrcExprs.push_back(nullptr);
  11409. DstExprs.push_back(nullptr);
  11410. AssignmentOps.push_back(nullptr);
  11411. continue;
  11412. }
  11413. SourceLocation ELoc = RefExpr->getExprLoc();
  11414. // OpenMP [2.1, C/C++]
  11415. // A list item is a variable name.
  11416. // OpenMP [2.14.4.1, Restrictions, p.1]
  11417. // A list item that appears in a copyin clause must be threadprivate.
  11418. auto *DE = dyn_cast<DeclRefExpr>(RefExpr);
  11419. if (!DE || !isa<VarDecl>(DE->getDecl())) {
  11420. Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
  11421. << 0 << RefExpr->getSourceRange();
  11422. continue;
  11423. }
  11424. Decl *D = DE->getDecl();
  11425. auto *VD = cast<VarDecl>(D);
  11426. QualType Type = VD->getType();
  11427. if (Type->isDependentType() || Type->isInstantiationDependentType()) {
  11428. // It will be analyzed later.
  11429. Vars.push_back(DE);
  11430. SrcExprs.push_back(nullptr);
  11431. DstExprs.push_back(nullptr);
  11432. AssignmentOps.push_back(nullptr);
  11433. continue;
  11434. }
  11435. // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
  11436. // A list item that appears in a copyin clause must be threadprivate.
  11437. if (!DSAStack->isThreadPrivate(VD)) {
  11438. Diag(ELoc, diag::err_omp_required_access)
  11439. << getOpenMPClauseName(OMPC_copyin)
  11440. << getOpenMPDirectiveName(OMPD_threadprivate);
  11441. continue;
  11442. }
  11443. // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
  11444. // A variable of class type (or array thereof) that appears in a
  11445. // copyin clause requires an accessible, unambiguous copy assignment
  11446. // operator for the class type.
  11447. QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
  11448. VarDecl *SrcVD =
  11449. buildVarDecl(*this, DE->getBeginLoc(), ElemType.getUnqualifiedType(),
  11450. ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
  11451. DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(
  11452. *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
  11453. VarDecl *DstVD =
  11454. buildVarDecl(*this, DE->getBeginLoc(), ElemType, ".copyin.dst",
  11455. VD->hasAttrs() ? &VD->getAttrs() : nullptr);
  11456. DeclRefExpr *PseudoDstExpr =
  11457. buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
  11458. // For arrays generate assignment operation for single element and replace
  11459. // it by the original array element in CodeGen.
  11460. ExprResult AssignmentOp =
  11461. BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign, PseudoDstExpr,
  11462. PseudoSrcExpr);
  11463. if (AssignmentOp.isInvalid())
  11464. continue;
  11465. AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
  11466. /*DiscardedValue*/ false);
  11467. if (AssignmentOp.isInvalid())
  11468. continue;
  11469. DSAStack->addDSA(VD, DE, OMPC_copyin);
  11470. Vars.push_back(DE);
  11471. SrcExprs.push_back(PseudoSrcExpr);
  11472. DstExprs.push_back(PseudoDstExpr);
  11473. AssignmentOps.push_back(AssignmentOp.get());
  11474. }
  11475. if (Vars.empty())
  11476. return nullptr;
  11477. return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
  11478. SrcExprs, DstExprs, AssignmentOps);
  11479. }
  11480. OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
  11481. SourceLocation StartLoc,
  11482. SourceLocation LParenLoc,
  11483. SourceLocation EndLoc) {
  11484. SmallVector<Expr *, 8> Vars;
  11485. SmallVector<Expr *, 8> SrcExprs;
  11486. SmallVector<Expr *, 8> DstExprs;
  11487. SmallVector<Expr *, 8> AssignmentOps;
  11488. for (Expr *RefExpr : VarList) {
  11489. assert(RefExpr && "NULL expr in OpenMP linear clause.");
  11490. SourceLocation ELoc;
  11491. SourceRange ERange;
  11492. Expr *SimpleRefExpr = RefExpr;
  11493. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  11494. if (Res.second) {
  11495. // It will be analyzed later.
  11496. Vars.push_back(RefExpr);
  11497. SrcExprs.push_back(nullptr);
  11498. DstExprs.push_back(nullptr);
  11499. AssignmentOps.push_back(nullptr);
  11500. }
  11501. ValueDecl *D = Res.first;
  11502. if (!D)
  11503. continue;
  11504. QualType Type = D->getType();
  11505. auto *VD = dyn_cast<VarDecl>(D);
  11506. // OpenMP [2.14.4.2, Restrictions, p.2]
  11507. // A list item that appears in a copyprivate clause may not appear in a
  11508. // private or firstprivate clause on the single construct.
  11509. if (!VD || !DSAStack->isThreadPrivate(VD)) {
  11510. DSAStackTy::DSAVarData DVar =
  11511. DSAStack->getTopDSA(D, /*FromParent=*/false);
  11512. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
  11513. DVar.RefExpr) {
  11514. Diag(ELoc, diag::err_omp_wrong_dsa)
  11515. << getOpenMPClauseName(DVar.CKind)
  11516. << getOpenMPClauseName(OMPC_copyprivate);
  11517. reportOriginalDsa(*this, DSAStack, D, DVar);
  11518. continue;
  11519. }
  11520. // OpenMP [2.11.4.2, Restrictions, p.1]
  11521. // All list items that appear in a copyprivate clause must be either
  11522. // threadprivate or private in the enclosing context.
  11523. if (DVar.CKind == OMPC_unknown) {
  11524. DVar = DSAStack->getImplicitDSA(D, false);
  11525. if (DVar.CKind == OMPC_shared) {
  11526. Diag(ELoc, diag::err_omp_required_access)
  11527. << getOpenMPClauseName(OMPC_copyprivate)
  11528. << "threadprivate or private in the enclosing context";
  11529. reportOriginalDsa(*this, DSAStack, D, DVar);
  11530. continue;
  11531. }
  11532. }
  11533. }
  11534. // Variably modified types are not supported.
  11535. if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
  11536. Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
  11537. << getOpenMPClauseName(OMPC_copyprivate) << Type
  11538. << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
  11539. bool IsDecl =
  11540. !VD ||
  11541. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  11542. Diag(D->getLocation(),
  11543. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  11544. << D;
  11545. continue;
  11546. }
  11547. // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
  11548. // A variable of class type (or array thereof) that appears in a
  11549. // copyin clause requires an accessible, unambiguous copy assignment
  11550. // operator for the class type.
  11551. Type = Context.getBaseElementType(Type.getNonReferenceType())
  11552. .getUnqualifiedType();
  11553. VarDecl *SrcVD =
  11554. buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.src",
  11555. D->hasAttrs() ? &D->getAttrs() : nullptr);
  11556. DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
  11557. VarDecl *DstVD =
  11558. buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.dst",
  11559. D->hasAttrs() ? &D->getAttrs() : nullptr);
  11560. DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
  11561. ExprResult AssignmentOp = BuildBinOp(
  11562. DSAStack->getCurScope(), ELoc, BO_Assign, PseudoDstExpr, PseudoSrcExpr);
  11563. if (AssignmentOp.isInvalid())
  11564. continue;
  11565. AssignmentOp =
  11566. ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
  11567. if (AssignmentOp.isInvalid())
  11568. continue;
  11569. // No need to mark vars as copyprivate, they are already threadprivate or
  11570. // implicitly private.
  11571. assert(VD || isOpenMPCapturedDecl(D));
  11572. Vars.push_back(
  11573. VD ? RefExpr->IgnoreParens()
  11574. : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
  11575. SrcExprs.push_back(PseudoSrcExpr);
  11576. DstExprs.push_back(PseudoDstExpr);
  11577. AssignmentOps.push_back(AssignmentOp.get());
  11578. }
  11579. if (Vars.empty())
  11580. return nullptr;
  11581. return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  11582. Vars, SrcExprs, DstExprs, AssignmentOps);
  11583. }
  11584. OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
  11585. SourceLocation StartLoc,
  11586. SourceLocation LParenLoc,
  11587. SourceLocation EndLoc) {
  11588. if (VarList.empty())
  11589. return nullptr;
  11590. return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
  11591. }
  11592. OMPClause *
  11593. Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
  11594. SourceLocation DepLoc, SourceLocation ColonLoc,
  11595. ArrayRef<Expr *> VarList, SourceLocation StartLoc,
  11596. SourceLocation LParenLoc, SourceLocation EndLoc) {
  11597. if (DSAStack->getCurrentDirective() == OMPD_ordered &&
  11598. DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
  11599. Diag(DepLoc, diag::err_omp_unexpected_clause_value)
  11600. << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
  11601. return nullptr;
  11602. }
  11603. if (DSAStack->getCurrentDirective() != OMPD_ordered &&
  11604. (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
  11605. DepKind == OMPC_DEPEND_sink)) {
  11606. unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink};
  11607. Diag(DepLoc, diag::err_omp_unexpected_clause_value)
  11608. << getListOfPossibleValues(OMPC_depend, /*First=*/0,
  11609. /*Last=*/OMPC_DEPEND_unknown, Except)
  11610. << getOpenMPClauseName(OMPC_depend);
  11611. return nullptr;
  11612. }
  11613. SmallVector<Expr *, 8> Vars;
  11614. DSAStackTy::OperatorOffsetTy OpsOffs;
  11615. llvm::APSInt DepCounter(/*BitWidth=*/32);
  11616. llvm::APSInt TotalDepCount(/*BitWidth=*/32);
  11617. if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) {
  11618. if (const Expr *OrderedCountExpr =
  11619. DSAStack->getParentOrderedRegionParam().first) {
  11620. TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
  11621. TotalDepCount.setIsUnsigned(/*Val=*/true);
  11622. }
  11623. }
  11624. for (Expr *RefExpr : VarList) {
  11625. assert(RefExpr && "NULL expr in OpenMP shared clause.");
  11626. if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
  11627. // It will be analyzed later.
  11628. Vars.push_back(RefExpr);
  11629. continue;
  11630. }
  11631. SourceLocation ELoc = RefExpr->getExprLoc();
  11632. Expr *SimpleExpr = RefExpr->IgnoreParenCasts();
  11633. if (DepKind == OMPC_DEPEND_sink) {
  11634. if (DSAStack->getParentOrderedRegionParam().first &&
  11635. DepCounter >= TotalDepCount) {
  11636. Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
  11637. continue;
  11638. }
  11639. ++DepCounter;
  11640. // OpenMP [2.13.9, Summary]
  11641. // depend(dependence-type : vec), where dependence-type is:
  11642. // 'sink' and where vec is the iteration vector, which has the form:
  11643. // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
  11644. // where n is the value specified by the ordered clause in the loop
  11645. // directive, xi denotes the loop iteration variable of the i-th nested
  11646. // loop associated with the loop directive, and di is a constant
  11647. // non-negative integer.
  11648. if (CurContext->isDependentContext()) {
  11649. // It will be analyzed later.
  11650. Vars.push_back(RefExpr);
  11651. continue;
  11652. }
  11653. SimpleExpr = SimpleExpr->IgnoreImplicit();
  11654. OverloadedOperatorKind OOK = OO_None;
  11655. SourceLocation OOLoc;
  11656. Expr *LHS = SimpleExpr;
  11657. Expr *RHS = nullptr;
  11658. if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
  11659. OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
  11660. OOLoc = BO->getOperatorLoc();
  11661. LHS = BO->getLHS()->IgnoreParenImpCasts();
  11662. RHS = BO->getRHS()->IgnoreParenImpCasts();
  11663. } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
  11664. OOK = OCE->getOperator();
  11665. OOLoc = OCE->getOperatorLoc();
  11666. LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
  11667. RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
  11668. } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
  11669. OOK = MCE->getMethodDecl()
  11670. ->getNameInfo()
  11671. .getName()
  11672. .getCXXOverloadedOperator();
  11673. OOLoc = MCE->getCallee()->getExprLoc();
  11674. LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
  11675. RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
  11676. }
  11677. SourceLocation ELoc;
  11678. SourceRange ERange;
  11679. auto Res = getPrivateItem(*this, LHS, ELoc, ERange);
  11680. if (Res.second) {
  11681. // It will be analyzed later.
  11682. Vars.push_back(RefExpr);
  11683. }
  11684. ValueDecl *D = Res.first;
  11685. if (!D)
  11686. continue;
  11687. if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
  11688. Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
  11689. continue;
  11690. }
  11691. if (RHS) {
  11692. ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
  11693. RHS, OMPC_depend, /*StrictlyPositive=*/false);
  11694. if (RHSRes.isInvalid())
  11695. continue;
  11696. }
  11697. if (!CurContext->isDependentContext() &&
  11698. DSAStack->getParentOrderedRegionParam().first &&
  11699. DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
  11700. const ValueDecl *VD =
  11701. DSAStack->getParentLoopControlVariable(DepCounter.getZExtValue());
  11702. if (VD)
  11703. Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
  11704. << 1 << VD;
  11705. else
  11706. Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) << 0;
  11707. continue;
  11708. }
  11709. OpsOffs.emplace_back(RHS, OOK);
  11710. } else {
  11711. auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
  11712. if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
  11713. (ASE &&
  11714. !ASE->getBase()->getType().getNonReferenceType()->isPointerType() &&
  11715. !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
  11716. Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
  11717. << RefExpr->getSourceRange();
  11718. continue;
  11719. }
  11720. bool Suppress = getDiagnostics().getSuppressAllDiagnostics();
  11721. getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
  11722. ExprResult Res =
  11723. CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RefExpr->IgnoreParenImpCasts());
  11724. getDiagnostics().setSuppressAllDiagnostics(Suppress);
  11725. if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr)) {
  11726. Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
  11727. << RefExpr->getSourceRange();
  11728. continue;
  11729. }
  11730. }
  11731. Vars.push_back(RefExpr->IgnoreParenImpCasts());
  11732. }
  11733. if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
  11734. TotalDepCount > VarList.size() &&
  11735. DSAStack->getParentOrderedRegionParam().first &&
  11736. DSAStack->getParentLoopControlVariable(VarList.size() + 1)) {
  11737. Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration)
  11738. << 1 << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
  11739. }
  11740. if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
  11741. Vars.empty())
  11742. return nullptr;
  11743. auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  11744. DepKind, DepLoc, ColonLoc, Vars,
  11745. TotalDepCount.getZExtValue());
  11746. if ((DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) &&
  11747. DSAStack->isParentOrderedRegion())
  11748. DSAStack->addDoacrossDependClause(C, OpsOffs);
  11749. return C;
  11750. }
  11751. OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
  11752. SourceLocation LParenLoc,
  11753. SourceLocation EndLoc) {
  11754. Expr *ValExpr = Device;
  11755. Stmt *HelperValStmt = nullptr;
  11756. // OpenMP [2.9.1, Restrictions]
  11757. // The device expression must evaluate to a non-negative integer value.
  11758. if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
  11759. /*StrictlyPositive=*/false))
  11760. return nullptr;
  11761. OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
  11762. OpenMPDirectiveKind CaptureRegion =
  11763. getOpenMPCaptureRegionForClause(DKind, OMPC_device);
  11764. if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
  11765. ValExpr = MakeFullExpr(ValExpr).get();
  11766. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  11767. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  11768. HelperValStmt = buildPreInits(Context, Captures);
  11769. }
  11770. return new (Context) OMPDeviceClause(ValExpr, HelperValStmt, CaptureRegion,
  11771. StartLoc, LParenLoc, EndLoc);
  11772. }
  11773. static bool checkTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
  11774. DSAStackTy *Stack, QualType QTy,
  11775. bool FullCheck = true) {
  11776. NamedDecl *ND;
  11777. if (QTy->isIncompleteType(&ND)) {
  11778. SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
  11779. return false;
  11780. }
  11781. if (FullCheck && !SemaRef.CurContext->isDependentContext() &&
  11782. !QTy.isTrivialType(SemaRef.Context))
  11783. SemaRef.Diag(SL, diag::warn_omp_non_trivial_type_mapped) << QTy << SR;
  11784. return true;
  11785. }
  11786. /// Return true if it can be proven that the provided array expression
  11787. /// (array section or array subscript) does NOT specify the whole size of the
  11788. /// array whose base type is \a BaseQTy.
  11789. static bool checkArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
  11790. const Expr *E,
  11791. QualType BaseQTy) {
  11792. const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
  11793. // If this is an array subscript, it refers to the whole size if the size of
  11794. // the dimension is constant and equals 1. Also, an array section assumes the
  11795. // format of an array subscript if no colon is used.
  11796. if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) {
  11797. if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
  11798. return ATy->getSize().getSExtValue() != 1;
  11799. // Size can't be evaluated statically.
  11800. return false;
  11801. }
  11802. assert(OASE && "Expecting array section if not an array subscript.");
  11803. const Expr *LowerBound = OASE->getLowerBound();
  11804. const Expr *Length = OASE->getLength();
  11805. // If there is a lower bound that does not evaluates to zero, we are not
  11806. // covering the whole dimension.
  11807. if (LowerBound) {
  11808. Expr::EvalResult Result;
  11809. if (!LowerBound->EvaluateAsInt(Result, SemaRef.getASTContext()))
  11810. return false; // Can't get the integer value as a constant.
  11811. llvm::APSInt ConstLowerBound = Result.Val.getInt();
  11812. if (ConstLowerBound.getSExtValue())
  11813. return true;
  11814. }
  11815. // If we don't have a length we covering the whole dimension.
  11816. if (!Length)
  11817. return false;
  11818. // If the base is a pointer, we don't have a way to get the size of the
  11819. // pointee.
  11820. if (BaseQTy->isPointerType())
  11821. return false;
  11822. // We can only check if the length is the same as the size of the dimension
  11823. // if we have a constant array.
  11824. const auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
  11825. if (!CATy)
  11826. return false;
  11827. Expr::EvalResult Result;
  11828. if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
  11829. return false; // Can't get the integer value as a constant.
  11830. llvm::APSInt ConstLength = Result.Val.getInt();
  11831. return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
  11832. }
  11833. // Return true if it can be proven that the provided array expression (array
  11834. // section or array subscript) does NOT specify a single element of the array
  11835. // whose base type is \a BaseQTy.
  11836. static bool checkArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
  11837. const Expr *E,
  11838. QualType BaseQTy) {
  11839. const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
  11840. // An array subscript always refer to a single element. Also, an array section
  11841. // assumes the format of an array subscript if no colon is used.
  11842. if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid()))
  11843. return false;
  11844. assert(OASE && "Expecting array section if not an array subscript.");
  11845. const Expr *Length = OASE->getLength();
  11846. // If we don't have a length we have to check if the array has unitary size
  11847. // for this dimension. Also, we should always expect a length if the base type
  11848. // is pointer.
  11849. if (!Length) {
  11850. if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
  11851. return ATy->getSize().getSExtValue() != 1;
  11852. // We cannot assume anything.
  11853. return false;
  11854. }
  11855. // Check if the length evaluates to 1.
  11856. Expr::EvalResult Result;
  11857. if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
  11858. return false; // Can't get the integer value as a constant.
  11859. llvm::APSInt ConstLength = Result.Val.getInt();
  11860. return ConstLength.getSExtValue() != 1;
  11861. }
  11862. // Return the expression of the base of the mappable expression or null if it
  11863. // cannot be determined and do all the necessary checks to see if the expression
  11864. // is valid as a standalone mappable expression. In the process, record all the
  11865. // components of the expression.
  11866. static const Expr *checkMapClauseExpressionBase(
  11867. Sema &SemaRef, Expr *E,
  11868. OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
  11869. OpenMPClauseKind CKind, bool NoDiagnose) {
  11870. SourceLocation ELoc = E->getExprLoc();
  11871. SourceRange ERange = E->getSourceRange();
  11872. // The base of elements of list in a map clause have to be either:
  11873. // - a reference to variable or field.
  11874. // - a member expression.
  11875. // - an array expression.
  11876. //
  11877. // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
  11878. // reference to 'r'.
  11879. //
  11880. // If we have:
  11881. //
  11882. // struct SS {
  11883. // Bla S;
  11884. // foo() {
  11885. // #pragma omp target map (S.Arr[:12]);
  11886. // }
  11887. // }
  11888. //
  11889. // We want to retrieve the member expression 'this->S';
  11890. const Expr *RelevantExpr = nullptr;
  11891. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2]
  11892. // If a list item is an array section, it must specify contiguous storage.
  11893. //
  11894. // For this restriction it is sufficient that we make sure only references
  11895. // to variables or fields and array expressions, and that no array sections
  11896. // exist except in the rightmost expression (unless they cover the whole
  11897. // dimension of the array). E.g. these would be invalid:
  11898. //
  11899. // r.ArrS[3:5].Arr[6:7]
  11900. //
  11901. // r.ArrS[3:5].x
  11902. //
  11903. // but these would be valid:
  11904. // r.ArrS[3].Arr[6:7]
  11905. //
  11906. // r.ArrS[3].x
  11907. bool AllowUnitySizeArraySection = true;
  11908. bool AllowWholeSizeArraySection = true;
  11909. while (!RelevantExpr) {
  11910. E = E->IgnoreParenImpCasts();
  11911. if (auto *CurE = dyn_cast<DeclRefExpr>(E)) {
  11912. if (!isa<VarDecl>(CurE->getDecl()))
  11913. return nullptr;
  11914. RelevantExpr = CurE;
  11915. // If we got a reference to a declaration, we should not expect any array
  11916. // section before that.
  11917. AllowUnitySizeArraySection = false;
  11918. AllowWholeSizeArraySection = false;
  11919. // Record the component.
  11920. CurComponents.emplace_back(CurE, CurE->getDecl());
  11921. } else if (auto *CurE = dyn_cast<MemberExpr>(E)) {
  11922. Expr *BaseE = CurE->getBase()->IgnoreParenImpCasts();
  11923. if (isa<CXXThisExpr>(BaseE))
  11924. // We found a base expression: this->Val.
  11925. RelevantExpr = CurE;
  11926. else
  11927. E = BaseE;
  11928. if (!isa<FieldDecl>(CurE->getMemberDecl())) {
  11929. if (!NoDiagnose) {
  11930. SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
  11931. << CurE->getSourceRange();
  11932. return nullptr;
  11933. }
  11934. if (RelevantExpr)
  11935. return nullptr;
  11936. continue;
  11937. }
  11938. auto *FD = cast<FieldDecl>(CurE->getMemberDecl());
  11939. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
  11940. // A bit-field cannot appear in a map clause.
  11941. //
  11942. if (FD->isBitField()) {
  11943. if (!NoDiagnose) {
  11944. SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
  11945. << CurE->getSourceRange() << getOpenMPClauseName(CKind);
  11946. return nullptr;
  11947. }
  11948. if (RelevantExpr)
  11949. return nullptr;
  11950. continue;
  11951. }
  11952. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
  11953. // If the type of a list item is a reference to a type T then the type
  11954. // will be considered to be T for all purposes of this clause.
  11955. QualType CurType = BaseE->getType().getNonReferenceType();
  11956. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
  11957. // A list item cannot be a variable that is a member of a structure with
  11958. // a union type.
  11959. //
  11960. if (CurType->isUnionType()) {
  11961. if (!NoDiagnose) {
  11962. SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
  11963. << CurE->getSourceRange();
  11964. return nullptr;
  11965. }
  11966. continue;
  11967. }
  11968. // If we got a member expression, we should not expect any array section
  11969. // before that:
  11970. //
  11971. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
  11972. // If a list item is an element of a structure, only the rightmost symbol
  11973. // of the variable reference can be an array section.
  11974. //
  11975. AllowUnitySizeArraySection = false;
  11976. AllowWholeSizeArraySection = false;
  11977. // Record the component.
  11978. CurComponents.emplace_back(CurE, FD);
  11979. } else if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) {
  11980. E = CurE->getBase()->IgnoreParenImpCasts();
  11981. if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
  11982. if (!NoDiagnose) {
  11983. SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
  11984. << 0 << CurE->getSourceRange();
  11985. return nullptr;
  11986. }
  11987. continue;
  11988. }
  11989. // If we got an array subscript that express the whole dimension we
  11990. // can have any array expressions before. If it only expressing part of
  11991. // the dimension, we can only have unitary-size array expressions.
  11992. if (checkArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE,
  11993. E->getType()))
  11994. AllowWholeSizeArraySection = false;
  11995. if (const auto *TE = dyn_cast<CXXThisExpr>(E)) {
  11996. Expr::EvalResult Result;
  11997. if (CurE->getIdx()->EvaluateAsInt(Result, SemaRef.getASTContext())) {
  11998. if (!Result.Val.getInt().isNullValue()) {
  11999. SemaRef.Diag(CurE->getIdx()->getExprLoc(),
  12000. diag::err_omp_invalid_map_this_expr);
  12001. SemaRef.Diag(CurE->getIdx()->getExprLoc(),
  12002. diag::note_omp_invalid_subscript_on_this_ptr_map);
  12003. }
  12004. }
  12005. RelevantExpr = TE;
  12006. }
  12007. // Record the component - we don't have any declaration associated.
  12008. CurComponents.emplace_back(CurE, nullptr);
  12009. } else if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) {
  12010. assert(!NoDiagnose && "Array sections cannot be implicitly mapped.");
  12011. E = CurE->getBase()->IgnoreParenImpCasts();
  12012. QualType CurType =
  12013. OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
  12014. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
  12015. // If the type of a list item is a reference to a type T then the type
  12016. // will be considered to be T for all purposes of this clause.
  12017. if (CurType->isReferenceType())
  12018. CurType = CurType->getPointeeType();
  12019. bool IsPointer = CurType->isAnyPointerType();
  12020. if (!IsPointer && !CurType->isArrayType()) {
  12021. SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
  12022. << 0 << CurE->getSourceRange();
  12023. return nullptr;
  12024. }
  12025. bool NotWhole =
  12026. checkArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType);
  12027. bool NotUnity =
  12028. checkArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType);
  12029. if (AllowWholeSizeArraySection) {
  12030. // Any array section is currently allowed. Allowing a whole size array
  12031. // section implies allowing a unity array section as well.
  12032. //
  12033. // If this array section refers to the whole dimension we can still
  12034. // accept other array sections before this one, except if the base is a
  12035. // pointer. Otherwise, only unitary sections are accepted.
  12036. if (NotWhole || IsPointer)
  12037. AllowWholeSizeArraySection = false;
  12038. } else if (AllowUnitySizeArraySection && NotUnity) {
  12039. // A unity or whole array section is not allowed and that is not
  12040. // compatible with the properties of the current array section.
  12041. SemaRef.Diag(
  12042. ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
  12043. << CurE->getSourceRange();
  12044. return nullptr;
  12045. }
  12046. if (const auto *TE = dyn_cast<CXXThisExpr>(E)) {
  12047. Expr::EvalResult ResultR;
  12048. Expr::EvalResult ResultL;
  12049. if (CurE->getLength()->EvaluateAsInt(ResultR,
  12050. SemaRef.getASTContext())) {
  12051. if (!ResultR.Val.getInt().isOneValue()) {
  12052. SemaRef.Diag(CurE->getLength()->getExprLoc(),
  12053. diag::err_omp_invalid_map_this_expr);
  12054. SemaRef.Diag(CurE->getLength()->getExprLoc(),
  12055. diag::note_omp_invalid_length_on_this_ptr_mapping);
  12056. }
  12057. }
  12058. if (CurE->getLowerBound() && CurE->getLowerBound()->EvaluateAsInt(
  12059. ResultL, SemaRef.getASTContext())) {
  12060. if (!ResultL.Val.getInt().isNullValue()) {
  12061. SemaRef.Diag(CurE->getLowerBound()->getExprLoc(),
  12062. diag::err_omp_invalid_map_this_expr);
  12063. SemaRef.Diag(CurE->getLowerBound()->getExprLoc(),
  12064. diag::note_omp_invalid_lower_bound_on_this_ptr_mapping);
  12065. }
  12066. }
  12067. RelevantExpr = TE;
  12068. }
  12069. // Record the component - we don't have any declaration associated.
  12070. CurComponents.emplace_back(CurE, nullptr);
  12071. } else {
  12072. if (!NoDiagnose) {
  12073. // If nothing else worked, this is not a valid map clause expression.
  12074. SemaRef.Diag(
  12075. ELoc, diag::err_omp_expected_named_var_member_or_array_expression)
  12076. << ERange;
  12077. }
  12078. return nullptr;
  12079. }
  12080. }
  12081. return RelevantExpr;
  12082. }
  12083. // Return true if expression E associated with value VD has conflicts with other
  12084. // map information.
  12085. static bool checkMapConflicts(
  12086. Sema &SemaRef, DSAStackTy *DSAS, const ValueDecl *VD, const Expr *E,
  12087. bool CurrentRegionOnly,
  12088. OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
  12089. OpenMPClauseKind CKind) {
  12090. assert(VD && E);
  12091. SourceLocation ELoc = E->getExprLoc();
  12092. SourceRange ERange = E->getSourceRange();
  12093. // In order to easily check the conflicts we need to match each component of
  12094. // the expression under test with the components of the expressions that are
  12095. // already in the stack.
  12096. assert(!CurComponents.empty() && "Map clause expression with no components!");
  12097. assert(CurComponents.back().getAssociatedDeclaration() == VD &&
  12098. "Map clause expression with unexpected base!");
  12099. // Variables to help detecting enclosing problems in data environment nests.
  12100. bool IsEnclosedByDataEnvironmentExpr = false;
  12101. const Expr *EnclosingExpr = nullptr;
  12102. bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
  12103. VD, CurrentRegionOnly,
  12104. [&IsEnclosedByDataEnvironmentExpr, &SemaRef, VD, CurrentRegionOnly, ELoc,
  12105. ERange, CKind, &EnclosingExpr,
  12106. CurComponents](OMPClauseMappableExprCommon::MappableExprComponentListRef
  12107. StackComponents,
  12108. OpenMPClauseKind) {
  12109. assert(!StackComponents.empty() &&
  12110. "Map clause expression with no components!");
  12111. assert(StackComponents.back().getAssociatedDeclaration() == VD &&
  12112. "Map clause expression with unexpected base!");
  12113. (void)VD;
  12114. // The whole expression in the stack.
  12115. const Expr *RE = StackComponents.front().getAssociatedExpression();
  12116. // Expressions must start from the same base. Here we detect at which
  12117. // point both expressions diverge from each other and see if we can
  12118. // detect if the memory referred to both expressions is contiguous and
  12119. // do not overlap.
  12120. auto CI = CurComponents.rbegin();
  12121. auto CE = CurComponents.rend();
  12122. auto SI = StackComponents.rbegin();
  12123. auto SE = StackComponents.rend();
  12124. for (; CI != CE && SI != SE; ++CI, ++SI) {
  12125. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
  12126. // At most one list item can be an array item derived from a given
  12127. // variable in map clauses of the same construct.
  12128. if (CurrentRegionOnly &&
  12129. (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
  12130. isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) &&
  12131. (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
  12132. isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) {
  12133. SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
  12134. diag::err_omp_multiple_array_items_in_map_clause)
  12135. << CI->getAssociatedExpression()->getSourceRange();
  12136. SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
  12137. diag::note_used_here)
  12138. << SI->getAssociatedExpression()->getSourceRange();
  12139. return true;
  12140. }
  12141. // Do both expressions have the same kind?
  12142. if (CI->getAssociatedExpression()->getStmtClass() !=
  12143. SI->getAssociatedExpression()->getStmtClass())
  12144. break;
  12145. // Are we dealing with different variables/fields?
  12146. if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
  12147. break;
  12148. }
  12149. // Check if the extra components of the expressions in the enclosing
  12150. // data environment are redundant for the current base declaration.
  12151. // If they are, the maps completely overlap, which is legal.
  12152. for (; SI != SE; ++SI) {
  12153. QualType Type;
  12154. if (const auto *ASE =
  12155. dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
  12156. Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
  12157. } else if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(
  12158. SI->getAssociatedExpression())) {
  12159. const Expr *E = OASE->getBase()->IgnoreParenImpCasts();
  12160. Type =
  12161. OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
  12162. }
  12163. if (Type.isNull() || Type->isAnyPointerType() ||
  12164. checkArrayExpressionDoesNotReferToWholeSize(
  12165. SemaRef, SI->getAssociatedExpression(), Type))
  12166. break;
  12167. }
  12168. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
  12169. // List items of map clauses in the same construct must not share
  12170. // original storage.
  12171. //
  12172. // If the expressions are exactly the same or one is a subset of the
  12173. // other, it means they are sharing storage.
  12174. if (CI == CE && SI == SE) {
  12175. if (CurrentRegionOnly) {
  12176. if (CKind == OMPC_map) {
  12177. SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
  12178. } else {
  12179. assert(CKind == OMPC_to || CKind == OMPC_from);
  12180. SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
  12181. << ERange;
  12182. }
  12183. SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
  12184. << RE->getSourceRange();
  12185. return true;
  12186. }
  12187. // If we find the same expression in the enclosing data environment,
  12188. // that is legal.
  12189. IsEnclosedByDataEnvironmentExpr = true;
  12190. return false;
  12191. }
  12192. QualType DerivedType =
  12193. std::prev(CI)->getAssociatedDeclaration()->getType();
  12194. SourceLocation DerivedLoc =
  12195. std::prev(CI)->getAssociatedExpression()->getExprLoc();
  12196. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
  12197. // If the type of a list item is a reference to a type T then the type
  12198. // will be considered to be T for all purposes of this clause.
  12199. DerivedType = DerivedType.getNonReferenceType();
  12200. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
  12201. // A variable for which the type is pointer and an array section
  12202. // derived from that variable must not appear as list items of map
  12203. // clauses of the same construct.
  12204. //
  12205. // Also, cover one of the cases in:
  12206. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
  12207. // If any part of the original storage of a list item has corresponding
  12208. // storage in the device data environment, all of the original storage
  12209. // must have corresponding storage in the device data environment.
  12210. //
  12211. if (DerivedType->isAnyPointerType()) {
  12212. if (CI == CE || SI == SE) {
  12213. SemaRef.Diag(
  12214. DerivedLoc,
  12215. diag::err_omp_pointer_mapped_along_with_derived_section)
  12216. << DerivedLoc;
  12217. SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
  12218. << RE->getSourceRange();
  12219. return true;
  12220. }
  12221. if (CI->getAssociatedExpression()->getStmtClass() !=
  12222. SI->getAssociatedExpression()->getStmtClass() ||
  12223. CI->getAssociatedDeclaration()->getCanonicalDecl() ==
  12224. SI->getAssociatedDeclaration()->getCanonicalDecl()) {
  12225. assert(CI != CE && SI != SE);
  12226. SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_dereferenced)
  12227. << DerivedLoc;
  12228. SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
  12229. << RE->getSourceRange();
  12230. return true;
  12231. }
  12232. }
  12233. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
  12234. // List items of map clauses in the same construct must not share
  12235. // original storage.
  12236. //
  12237. // An expression is a subset of the other.
  12238. if (CurrentRegionOnly && (CI == CE || SI == SE)) {
  12239. if (CKind == OMPC_map) {
  12240. if (CI != CE || SI != SE) {
  12241. // Allow constructs like this: map(s, s.ptr[0:1]), where s.ptr is
  12242. // a pointer.
  12243. auto Begin =
  12244. CI != CE ? CurComponents.begin() : StackComponents.begin();
  12245. auto End = CI != CE ? CurComponents.end() : StackComponents.end();
  12246. auto It = Begin;
  12247. while (It != End && !It->getAssociatedDeclaration())
  12248. std::advance(It, 1);
  12249. assert(It != End &&
  12250. "Expected at least one component with the declaration.");
  12251. if (It != Begin && It->getAssociatedDeclaration()
  12252. ->getType()
  12253. .getCanonicalType()
  12254. ->isAnyPointerType()) {
  12255. IsEnclosedByDataEnvironmentExpr = false;
  12256. EnclosingExpr = nullptr;
  12257. return false;
  12258. }
  12259. }
  12260. SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
  12261. } else {
  12262. assert(CKind == OMPC_to || CKind == OMPC_from);
  12263. SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
  12264. << ERange;
  12265. }
  12266. SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
  12267. << RE->getSourceRange();
  12268. return true;
  12269. }
  12270. // The current expression uses the same base as other expression in the
  12271. // data environment but does not contain it completely.
  12272. if (!CurrentRegionOnly && SI != SE)
  12273. EnclosingExpr = RE;
  12274. // The current expression is a subset of the expression in the data
  12275. // environment.
  12276. IsEnclosedByDataEnvironmentExpr |=
  12277. (!CurrentRegionOnly && CI != CE && SI == SE);
  12278. return false;
  12279. });
  12280. if (CurrentRegionOnly)
  12281. return FoundError;
  12282. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
  12283. // If any part of the original storage of a list item has corresponding
  12284. // storage in the device data environment, all of the original storage must
  12285. // have corresponding storage in the device data environment.
  12286. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
  12287. // If a list item is an element of a structure, and a different element of
  12288. // the structure has a corresponding list item in the device data environment
  12289. // prior to a task encountering the construct associated with the map clause,
  12290. // then the list item must also have a corresponding list item in the device
  12291. // data environment prior to the task encountering the construct.
  12292. //
  12293. if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
  12294. SemaRef.Diag(ELoc,
  12295. diag::err_omp_original_storage_is_shared_and_does_not_contain)
  12296. << ERange;
  12297. SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
  12298. << EnclosingExpr->getSourceRange();
  12299. return true;
  12300. }
  12301. return FoundError;
  12302. }
  12303. // Look up the user-defined mapper given the mapper name and mapped type, and
  12304. // build a reference to it.
  12305. ExprResult buildUserDefinedMapperRef(Sema &SemaRef, Scope *S,
  12306. CXXScopeSpec &MapperIdScopeSpec,
  12307. const DeclarationNameInfo &MapperId,
  12308. QualType Type, Expr *UnresolvedMapper) {
  12309. if (MapperIdScopeSpec.isInvalid())
  12310. return ExprError();
  12311. // Find all user-defined mappers with the given MapperId.
  12312. SmallVector<UnresolvedSet<8>, 4> Lookups;
  12313. LookupResult Lookup(SemaRef, MapperId, Sema::LookupOMPMapperName);
  12314. Lookup.suppressDiagnostics();
  12315. if (S) {
  12316. while (S && SemaRef.LookupParsedName(Lookup, S, &MapperIdScopeSpec)) {
  12317. NamedDecl *D = Lookup.getRepresentativeDecl();
  12318. while (S && !S->isDeclScope(D))
  12319. S = S->getParent();
  12320. if (S)
  12321. S = S->getParent();
  12322. Lookups.emplace_back();
  12323. Lookups.back().append(Lookup.begin(), Lookup.end());
  12324. Lookup.clear();
  12325. }
  12326. } else if (auto *ULE = cast_or_null<UnresolvedLookupExpr>(UnresolvedMapper)) {
  12327. // Extract the user-defined mappers with the given MapperId.
  12328. Lookups.push_back(UnresolvedSet<8>());
  12329. for (NamedDecl *D : ULE->decls()) {
  12330. auto *DMD = cast<OMPDeclareMapperDecl>(D);
  12331. assert(DMD && "Expect valid OMPDeclareMapperDecl during instantiation.");
  12332. Lookups.back().addDecl(DMD);
  12333. }
  12334. }
  12335. // Defer the lookup for dependent types. The results will be passed through
  12336. // UnresolvedMapper on instantiation.
  12337. if (SemaRef.CurContext->isDependentContext() || Type->isDependentType() ||
  12338. Type->isInstantiationDependentType() ||
  12339. Type->containsUnexpandedParameterPack() ||
  12340. filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) {
  12341. return !D->isInvalidDecl() &&
  12342. (D->getType()->isDependentType() ||
  12343. D->getType()->isInstantiationDependentType() ||
  12344. D->getType()->containsUnexpandedParameterPack());
  12345. })) {
  12346. UnresolvedSet<8> URS;
  12347. for (const UnresolvedSet<8> &Set : Lookups) {
  12348. if (Set.empty())
  12349. continue;
  12350. URS.append(Set.begin(), Set.end());
  12351. }
  12352. return UnresolvedLookupExpr::Create(
  12353. SemaRef.Context, /*NamingClass=*/nullptr,
  12354. MapperIdScopeSpec.getWithLocInContext(SemaRef.Context), MapperId,
  12355. /*ADL=*/false, /*Overloaded=*/true, URS.begin(), URS.end());
  12356. }
  12357. // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
  12358. // The type must be of struct, union or class type in C and C++
  12359. if (!Type->isStructureOrClassType() && !Type->isUnionType())
  12360. return ExprEmpty();
  12361. SourceLocation Loc = MapperId.getLoc();
  12362. // Perform argument dependent lookup.
  12363. if (SemaRef.getLangOpts().CPlusPlus && !MapperIdScopeSpec.isSet())
  12364. argumentDependentLookup(SemaRef, MapperId, Loc, Type, Lookups);
  12365. // Return the first user-defined mapper with the desired type.
  12366. if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
  12367. Lookups, [&SemaRef, Type](ValueDecl *D) -> ValueDecl * {
  12368. if (!D->isInvalidDecl() &&
  12369. SemaRef.Context.hasSameType(D->getType(), Type))
  12370. return D;
  12371. return nullptr;
  12372. }))
  12373. return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
  12374. // Find the first user-defined mapper with a type derived from the desired
  12375. // type.
  12376. if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
  12377. Lookups, [&SemaRef, Type, Loc](ValueDecl *D) -> ValueDecl * {
  12378. if (!D->isInvalidDecl() &&
  12379. SemaRef.IsDerivedFrom(Loc, Type, D->getType()) &&
  12380. !Type.isMoreQualifiedThan(D->getType()))
  12381. return D;
  12382. return nullptr;
  12383. })) {
  12384. CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
  12385. /*DetectVirtual=*/false);
  12386. if (SemaRef.IsDerivedFrom(Loc, Type, VD->getType(), Paths)) {
  12387. if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
  12388. VD->getType().getUnqualifiedType()))) {
  12389. if (SemaRef.CheckBaseClassAccess(
  12390. Loc, VD->getType(), Type, Paths.front(),
  12391. /*DiagID=*/0) != Sema::AR_inaccessible) {
  12392. return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
  12393. }
  12394. }
  12395. }
  12396. }
  12397. // Report error if a mapper is specified, but cannot be found.
  12398. if (MapperIdScopeSpec.isSet() || MapperId.getAsString() != "default") {
  12399. SemaRef.Diag(Loc, diag::err_omp_invalid_mapper)
  12400. << Type << MapperId.getName();
  12401. return ExprError();
  12402. }
  12403. return ExprEmpty();
  12404. }
  12405. namespace {
  12406. // Utility struct that gathers all the related lists associated with a mappable
  12407. // expression.
  12408. struct MappableVarListInfo {
  12409. // The list of expressions.
  12410. ArrayRef<Expr *> VarList;
  12411. // The list of processed expressions.
  12412. SmallVector<Expr *, 16> ProcessedVarList;
  12413. // The mappble components for each expression.
  12414. OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
  12415. // The base declaration of the variable.
  12416. SmallVector<ValueDecl *, 16> VarBaseDeclarations;
  12417. // The reference to the user-defined mapper associated with every expression.
  12418. SmallVector<Expr *, 16> UDMapperList;
  12419. MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
  12420. // We have a list of components and base declarations for each entry in the
  12421. // variable list.
  12422. VarComponents.reserve(VarList.size());
  12423. VarBaseDeclarations.reserve(VarList.size());
  12424. }
  12425. };
  12426. }
  12427. // Check the validity of the provided variable list for the provided clause kind
  12428. // \a CKind. In the check process the valid expressions, mappable expression
  12429. // components, variables, and user-defined mappers are extracted and used to
  12430. // fill \a ProcessedVarList, \a VarComponents, \a VarBaseDeclarations, and \a
  12431. // UDMapperList in MVLI. \a MapType, \a IsMapTypeImplicit, \a MapperIdScopeSpec,
  12432. // and \a MapperId are expected to be valid if the clause kind is 'map'.
  12433. static void checkMappableExpressionList(
  12434. Sema &SemaRef, DSAStackTy *DSAS, OpenMPClauseKind CKind,
  12435. MappableVarListInfo &MVLI, SourceLocation StartLoc,
  12436. CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo MapperId,
  12437. ArrayRef<Expr *> UnresolvedMappers,
  12438. OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
  12439. bool IsMapTypeImplicit = false) {
  12440. // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
  12441. assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
  12442. "Unexpected clause kind with mappable expressions!");
  12443. // If the identifier of user-defined mapper is not specified, it is "default".
  12444. // We do not change the actual name in this clause to distinguish whether a
  12445. // mapper is specified explicitly, i.e., it is not explicitly specified when
  12446. // MapperId.getName() is empty.
  12447. if (!MapperId.getName() || MapperId.getName().isEmpty()) {
  12448. auto &DeclNames = SemaRef.getASTContext().DeclarationNames;
  12449. MapperId.setName(DeclNames.getIdentifier(
  12450. &SemaRef.getASTContext().Idents.get("default")));
  12451. }
  12452. // Iterators to find the current unresolved mapper expression.
  12453. auto UMIt = UnresolvedMappers.begin(), UMEnd = UnresolvedMappers.end();
  12454. bool UpdateUMIt = false;
  12455. Expr *UnresolvedMapper = nullptr;
  12456. // Keep track of the mappable components and base declarations in this clause.
  12457. // Each entry in the list is going to have a list of components associated. We
  12458. // record each set of the components so that we can build the clause later on.
  12459. // In the end we should have the same amount of declarations and component
  12460. // lists.
  12461. for (Expr *RE : MVLI.VarList) {
  12462. assert(RE && "Null expr in omp to/from/map clause");
  12463. SourceLocation ELoc = RE->getExprLoc();
  12464. // Find the current unresolved mapper expression.
  12465. if (UpdateUMIt && UMIt != UMEnd) {
  12466. UMIt++;
  12467. assert(
  12468. UMIt != UMEnd &&
  12469. "Expect the size of UnresolvedMappers to match with that of VarList");
  12470. }
  12471. UpdateUMIt = true;
  12472. if (UMIt != UMEnd)
  12473. UnresolvedMapper = *UMIt;
  12474. const Expr *VE = RE->IgnoreParenLValueCasts();
  12475. if (VE->isValueDependent() || VE->isTypeDependent() ||
  12476. VE->isInstantiationDependent() ||
  12477. VE->containsUnexpandedParameterPack()) {
  12478. // Try to find the associated user-defined mapper.
  12479. ExprResult ER = buildUserDefinedMapperRef(
  12480. SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
  12481. VE->getType().getCanonicalType(), UnresolvedMapper);
  12482. if (ER.isInvalid())
  12483. continue;
  12484. MVLI.UDMapperList.push_back(ER.get());
  12485. // We can only analyze this information once the missing information is
  12486. // resolved.
  12487. MVLI.ProcessedVarList.push_back(RE);
  12488. continue;
  12489. }
  12490. Expr *SimpleExpr = RE->IgnoreParenCasts();
  12491. if (!RE->IgnoreParenImpCasts()->isLValue()) {
  12492. SemaRef.Diag(ELoc,
  12493. diag::err_omp_expected_named_var_member_or_array_expression)
  12494. << RE->getSourceRange();
  12495. continue;
  12496. }
  12497. OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
  12498. ValueDecl *CurDeclaration = nullptr;
  12499. // Obtain the array or member expression bases if required. Also, fill the
  12500. // components array with all the components identified in the process.
  12501. const Expr *BE = checkMapClauseExpressionBase(
  12502. SemaRef, SimpleExpr, CurComponents, CKind, /*NoDiagnose=*/false);
  12503. if (!BE)
  12504. continue;
  12505. assert(!CurComponents.empty() &&
  12506. "Invalid mappable expression information.");
  12507. if (const auto *TE = dyn_cast<CXXThisExpr>(BE)) {
  12508. // Add store "this" pointer to class in DSAStackTy for future checking
  12509. DSAS->addMappedClassesQualTypes(TE->getType());
  12510. // Try to find the associated user-defined mapper.
  12511. ExprResult ER = buildUserDefinedMapperRef(
  12512. SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
  12513. VE->getType().getCanonicalType(), UnresolvedMapper);
  12514. if (ER.isInvalid())
  12515. continue;
  12516. MVLI.UDMapperList.push_back(ER.get());
  12517. // Skip restriction checking for variable or field declarations
  12518. MVLI.ProcessedVarList.push_back(RE);
  12519. MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
  12520. MVLI.VarComponents.back().append(CurComponents.begin(),
  12521. CurComponents.end());
  12522. MVLI.VarBaseDeclarations.push_back(nullptr);
  12523. continue;
  12524. }
  12525. // For the following checks, we rely on the base declaration which is
  12526. // expected to be associated with the last component. The declaration is
  12527. // expected to be a variable or a field (if 'this' is being mapped).
  12528. CurDeclaration = CurComponents.back().getAssociatedDeclaration();
  12529. assert(CurDeclaration && "Null decl on map clause.");
  12530. assert(
  12531. CurDeclaration->isCanonicalDecl() &&
  12532. "Expecting components to have associated only canonical declarations.");
  12533. auto *VD = dyn_cast<VarDecl>(CurDeclaration);
  12534. const auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
  12535. assert((VD || FD) && "Only variables or fields are expected here!");
  12536. (void)FD;
  12537. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
  12538. // threadprivate variables cannot appear in a map clause.
  12539. // OpenMP 4.5 [2.10.5, target update Construct]
  12540. // threadprivate variables cannot appear in a from clause.
  12541. if (VD && DSAS->isThreadPrivate(VD)) {
  12542. DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
  12543. SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
  12544. << getOpenMPClauseName(CKind);
  12545. reportOriginalDsa(SemaRef, DSAS, VD, DVar);
  12546. continue;
  12547. }
  12548. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
  12549. // A list item cannot appear in both a map clause and a data-sharing
  12550. // attribute clause on the same construct.
  12551. // Check conflicts with other map clause expressions. We check the conflicts
  12552. // with the current construct separately from the enclosing data
  12553. // environment, because the restrictions are different. We only have to
  12554. // check conflicts across regions for the map clauses.
  12555. if (checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
  12556. /*CurrentRegionOnly=*/true, CurComponents, CKind))
  12557. break;
  12558. if (CKind == OMPC_map &&
  12559. checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
  12560. /*CurrentRegionOnly=*/false, CurComponents, CKind))
  12561. break;
  12562. // OpenMP 4.5 [2.10.5, target update Construct]
  12563. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
  12564. // If the type of a list item is a reference to a type T then the type will
  12565. // be considered to be T for all purposes of this clause.
  12566. auto I = llvm::find_if(
  12567. CurComponents,
  12568. [](const OMPClauseMappableExprCommon::MappableComponent &MC) {
  12569. return MC.getAssociatedDeclaration();
  12570. });
  12571. assert(I != CurComponents.end() && "Null decl on map clause.");
  12572. QualType Type =
  12573. I->getAssociatedDeclaration()->getType().getNonReferenceType();
  12574. // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
  12575. // A list item in a to or from clause must have a mappable type.
  12576. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
  12577. // A list item must have a mappable type.
  12578. if (!checkTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
  12579. DSAS, Type))
  12580. continue;
  12581. if (CKind == OMPC_map) {
  12582. // target enter data
  12583. // OpenMP [2.10.2, Restrictions, p. 99]
  12584. // A map-type must be specified in all map clauses and must be either
  12585. // to or alloc.
  12586. OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
  12587. if (DKind == OMPD_target_enter_data &&
  12588. !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
  12589. SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
  12590. << (IsMapTypeImplicit ? 1 : 0)
  12591. << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
  12592. << getOpenMPDirectiveName(DKind);
  12593. continue;
  12594. }
  12595. // target exit_data
  12596. // OpenMP [2.10.3, Restrictions, p. 102]
  12597. // A map-type must be specified in all map clauses and must be either
  12598. // from, release, or delete.
  12599. if (DKind == OMPD_target_exit_data &&
  12600. !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
  12601. MapType == OMPC_MAP_delete)) {
  12602. SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
  12603. << (IsMapTypeImplicit ? 1 : 0)
  12604. << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
  12605. << getOpenMPDirectiveName(DKind);
  12606. continue;
  12607. }
  12608. // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
  12609. // A list item cannot appear in both a map clause and a data-sharing
  12610. // attribute clause on the same construct
  12611. if (VD && isOpenMPTargetExecutionDirective(DKind)) {
  12612. DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
  12613. if (isOpenMPPrivate(DVar.CKind)) {
  12614. SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
  12615. << getOpenMPClauseName(DVar.CKind)
  12616. << getOpenMPClauseName(OMPC_map)
  12617. << getOpenMPDirectiveName(DSAS->getCurrentDirective());
  12618. reportOriginalDsa(SemaRef, DSAS, CurDeclaration, DVar);
  12619. continue;
  12620. }
  12621. }
  12622. }
  12623. // Try to find the associated user-defined mapper.
  12624. ExprResult ER = buildUserDefinedMapperRef(
  12625. SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
  12626. Type.getCanonicalType(), UnresolvedMapper);
  12627. if (ER.isInvalid())
  12628. continue;
  12629. MVLI.UDMapperList.push_back(ER.get());
  12630. // Save the current expression.
  12631. MVLI.ProcessedVarList.push_back(RE);
  12632. // Store the components in the stack so that they can be used to check
  12633. // against other clauses later on.
  12634. DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
  12635. /*WhereFoundClauseKind=*/OMPC_map);
  12636. // Save the components and declaration to create the clause. For purposes of
  12637. // the clause creation, any component list that has has base 'this' uses
  12638. // null as base declaration.
  12639. MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
  12640. MVLI.VarComponents.back().append(CurComponents.begin(),
  12641. CurComponents.end());
  12642. MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
  12643. : CurDeclaration);
  12644. }
  12645. }
  12646. OMPClause *Sema::ActOnOpenMPMapClause(
  12647. ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
  12648. ArrayRef<SourceLocation> MapTypeModifiersLoc,
  12649. CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId,
  12650. OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, SourceLocation MapLoc,
  12651. SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
  12652. const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) {
  12653. OpenMPMapModifierKind Modifiers[] = {OMPC_MAP_MODIFIER_unknown,
  12654. OMPC_MAP_MODIFIER_unknown,
  12655. OMPC_MAP_MODIFIER_unknown};
  12656. SourceLocation ModifiersLoc[OMPMapClause::NumberOfModifiers];
  12657. // Process map-type-modifiers, flag errors for duplicate modifiers.
  12658. unsigned Count = 0;
  12659. for (unsigned I = 0, E = MapTypeModifiers.size(); I < E; ++I) {
  12660. if (MapTypeModifiers[I] != OMPC_MAP_MODIFIER_unknown &&
  12661. llvm::find(Modifiers, MapTypeModifiers[I]) != std::end(Modifiers)) {
  12662. Diag(MapTypeModifiersLoc[I], diag::err_omp_duplicate_map_type_modifier);
  12663. continue;
  12664. }
  12665. assert(Count < OMPMapClause::NumberOfModifiers &&
  12666. "Modifiers exceed the allowed number of map type modifiers");
  12667. Modifiers[Count] = MapTypeModifiers[I];
  12668. ModifiersLoc[Count] = MapTypeModifiersLoc[I];
  12669. ++Count;
  12670. }
  12671. MappableVarListInfo MVLI(VarList);
  12672. checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, Locs.StartLoc,
  12673. MapperIdScopeSpec, MapperId, UnresolvedMappers,
  12674. MapType, IsMapTypeImplicit);
  12675. // We need to produce a map clause even if we don't have variables so that
  12676. // other diagnostics related with non-existing map clauses are accurate.
  12677. return OMPMapClause::Create(Context, Locs, MVLI.ProcessedVarList,
  12678. MVLI.VarBaseDeclarations, MVLI.VarComponents,
  12679. MVLI.UDMapperList, Modifiers, ModifiersLoc,
  12680. MapperIdScopeSpec.getWithLocInContext(Context),
  12681. MapperId, MapType, IsMapTypeImplicit, MapLoc);
  12682. }
  12683. QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
  12684. TypeResult ParsedType) {
  12685. assert(ParsedType.isUsable());
  12686. QualType ReductionType = GetTypeFromParser(ParsedType.get());
  12687. if (ReductionType.isNull())
  12688. return QualType();
  12689. // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
  12690. // A type name in a declare reduction directive cannot be a function type, an
  12691. // array type, a reference type, or a type qualified with const, volatile or
  12692. // restrict.
  12693. if (ReductionType.hasQualifiers()) {
  12694. Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
  12695. return QualType();
  12696. }
  12697. if (ReductionType->isFunctionType()) {
  12698. Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
  12699. return QualType();
  12700. }
  12701. if (ReductionType->isReferenceType()) {
  12702. Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
  12703. return QualType();
  12704. }
  12705. if (ReductionType->isArrayType()) {
  12706. Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
  12707. return QualType();
  12708. }
  12709. return ReductionType;
  12710. }
  12711. Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
  12712. Scope *S, DeclContext *DC, DeclarationName Name,
  12713. ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
  12714. AccessSpecifier AS, Decl *PrevDeclInScope) {
  12715. SmallVector<Decl *, 8> Decls;
  12716. Decls.reserve(ReductionTypes.size());
  12717. LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
  12718. forRedeclarationInCurContext());
  12719. // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
  12720. // A reduction-identifier may not be re-declared in the current scope for the
  12721. // same type or for a type that is compatible according to the base language
  12722. // rules.
  12723. llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
  12724. OMPDeclareReductionDecl *PrevDRD = nullptr;
  12725. bool InCompoundScope = true;
  12726. if (S != nullptr) {
  12727. // Find previous declaration with the same name not referenced in other
  12728. // declarations.
  12729. FunctionScopeInfo *ParentFn = getEnclosingFunction();
  12730. InCompoundScope =
  12731. (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
  12732. LookupName(Lookup, S);
  12733. FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
  12734. /*AllowInlineNamespace=*/false);
  12735. llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
  12736. LookupResult::Filter Filter = Lookup.makeFilter();
  12737. while (Filter.hasNext()) {
  12738. auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
  12739. if (InCompoundScope) {
  12740. auto I = UsedAsPrevious.find(PrevDecl);
  12741. if (I == UsedAsPrevious.end())
  12742. UsedAsPrevious[PrevDecl] = false;
  12743. if (OMPDeclareReductionDecl *D = PrevDecl->getPrevDeclInScope())
  12744. UsedAsPrevious[D] = true;
  12745. }
  12746. PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
  12747. PrevDecl->getLocation();
  12748. }
  12749. Filter.done();
  12750. if (InCompoundScope) {
  12751. for (const auto &PrevData : UsedAsPrevious) {
  12752. if (!PrevData.second) {
  12753. PrevDRD = PrevData.first;
  12754. break;
  12755. }
  12756. }
  12757. }
  12758. } else if (PrevDeclInScope != nullptr) {
  12759. auto *PrevDRDInScope = PrevDRD =
  12760. cast<OMPDeclareReductionDecl>(PrevDeclInScope);
  12761. do {
  12762. PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
  12763. PrevDRDInScope->getLocation();
  12764. PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
  12765. } while (PrevDRDInScope != nullptr);
  12766. }
  12767. for (const auto &TyData : ReductionTypes) {
  12768. const auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
  12769. bool Invalid = false;
  12770. if (I != PreviousRedeclTypes.end()) {
  12771. Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
  12772. << TyData.first;
  12773. Diag(I->second, diag::note_previous_definition);
  12774. Invalid = true;
  12775. }
  12776. PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
  12777. auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
  12778. Name, TyData.first, PrevDRD);
  12779. DC->addDecl(DRD);
  12780. DRD->setAccess(AS);
  12781. Decls.push_back(DRD);
  12782. if (Invalid)
  12783. DRD->setInvalidDecl();
  12784. else
  12785. PrevDRD = DRD;
  12786. }
  12787. return DeclGroupPtrTy::make(
  12788. DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
  12789. }
  12790. void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
  12791. auto *DRD = cast<OMPDeclareReductionDecl>(D);
  12792. // Enter new function scope.
  12793. PushFunctionScope();
  12794. setFunctionHasBranchProtectedScope();
  12795. getCurFunction()->setHasOMPDeclareReductionCombiner();
  12796. if (S != nullptr)
  12797. PushDeclContext(S, DRD);
  12798. else
  12799. CurContext = DRD;
  12800. PushExpressionEvaluationContext(
  12801. ExpressionEvaluationContext::PotentiallyEvaluated);
  12802. QualType ReductionType = DRD->getType();
  12803. // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
  12804. // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
  12805. // uses semantics of argument handles by value, but it should be passed by
  12806. // reference. C lang does not support references, so pass all parameters as
  12807. // pointers.
  12808. // Create 'T omp_in;' variable.
  12809. VarDecl *OmpInParm =
  12810. buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
  12811. // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
  12812. // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
  12813. // uses semantics of argument handles by value, but it should be passed by
  12814. // reference. C lang does not support references, so pass all parameters as
  12815. // pointers.
  12816. // Create 'T omp_out;' variable.
  12817. VarDecl *OmpOutParm =
  12818. buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
  12819. if (S != nullptr) {
  12820. PushOnScopeChains(OmpInParm, S);
  12821. PushOnScopeChains(OmpOutParm, S);
  12822. } else {
  12823. DRD->addDecl(OmpInParm);
  12824. DRD->addDecl(OmpOutParm);
  12825. }
  12826. Expr *InE =
  12827. ::buildDeclRefExpr(*this, OmpInParm, ReductionType, D->getLocation());
  12828. Expr *OutE =
  12829. ::buildDeclRefExpr(*this, OmpOutParm, ReductionType, D->getLocation());
  12830. DRD->setCombinerData(InE, OutE);
  12831. }
  12832. void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
  12833. auto *DRD = cast<OMPDeclareReductionDecl>(D);
  12834. DiscardCleanupsInEvaluationContext();
  12835. PopExpressionEvaluationContext();
  12836. PopDeclContext();
  12837. PopFunctionScopeInfo();
  12838. if (Combiner != nullptr)
  12839. DRD->setCombiner(Combiner);
  12840. else
  12841. DRD->setInvalidDecl();
  12842. }
  12843. VarDecl *Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
  12844. auto *DRD = cast<OMPDeclareReductionDecl>(D);
  12845. // Enter new function scope.
  12846. PushFunctionScope();
  12847. setFunctionHasBranchProtectedScope();
  12848. if (S != nullptr)
  12849. PushDeclContext(S, DRD);
  12850. else
  12851. CurContext = DRD;
  12852. PushExpressionEvaluationContext(
  12853. ExpressionEvaluationContext::PotentiallyEvaluated);
  12854. QualType ReductionType = DRD->getType();
  12855. // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
  12856. // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
  12857. // uses semantics of argument handles by value, but it should be passed by
  12858. // reference. C lang does not support references, so pass all parameters as
  12859. // pointers.
  12860. // Create 'T omp_priv;' variable.
  12861. VarDecl *OmpPrivParm =
  12862. buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
  12863. // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
  12864. // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
  12865. // uses semantics of argument handles by value, but it should be passed by
  12866. // reference. C lang does not support references, so pass all parameters as
  12867. // pointers.
  12868. // Create 'T omp_orig;' variable.
  12869. VarDecl *OmpOrigParm =
  12870. buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
  12871. if (S != nullptr) {
  12872. PushOnScopeChains(OmpPrivParm, S);
  12873. PushOnScopeChains(OmpOrigParm, S);
  12874. } else {
  12875. DRD->addDecl(OmpPrivParm);
  12876. DRD->addDecl(OmpOrigParm);
  12877. }
  12878. Expr *OrigE =
  12879. ::buildDeclRefExpr(*this, OmpOrigParm, ReductionType, D->getLocation());
  12880. Expr *PrivE =
  12881. ::buildDeclRefExpr(*this, OmpPrivParm, ReductionType, D->getLocation());
  12882. DRD->setInitializerData(OrigE, PrivE);
  12883. return OmpPrivParm;
  12884. }
  12885. void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
  12886. VarDecl *OmpPrivParm) {
  12887. auto *DRD = cast<OMPDeclareReductionDecl>(D);
  12888. DiscardCleanupsInEvaluationContext();
  12889. PopExpressionEvaluationContext();
  12890. PopDeclContext();
  12891. PopFunctionScopeInfo();
  12892. if (Initializer != nullptr) {
  12893. DRD->setInitializer(Initializer, OMPDeclareReductionDecl::CallInit);
  12894. } else if (OmpPrivParm->hasInit()) {
  12895. DRD->setInitializer(OmpPrivParm->getInit(),
  12896. OmpPrivParm->isDirectInit()
  12897. ? OMPDeclareReductionDecl::DirectInit
  12898. : OMPDeclareReductionDecl::CopyInit);
  12899. } else {
  12900. DRD->setInvalidDecl();
  12901. }
  12902. }
  12903. Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
  12904. Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
  12905. for (Decl *D : DeclReductions.get()) {
  12906. if (IsValid) {
  12907. if (S)
  12908. PushOnScopeChains(cast<OMPDeclareReductionDecl>(D), S,
  12909. /*AddToContext=*/false);
  12910. } else {
  12911. D->setInvalidDecl();
  12912. }
  12913. }
  12914. return DeclReductions;
  12915. }
  12916. TypeResult Sema::ActOnOpenMPDeclareMapperVarDecl(Scope *S, Declarator &D) {
  12917. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  12918. QualType T = TInfo->getType();
  12919. if (D.isInvalidType())
  12920. return true;
  12921. if (getLangOpts().CPlusPlus) {
  12922. // Check that there are no default arguments (C++ only).
  12923. CheckExtraCXXDefaultArguments(D);
  12924. }
  12925. return CreateParsedType(T, TInfo);
  12926. }
  12927. QualType Sema::ActOnOpenMPDeclareMapperType(SourceLocation TyLoc,
  12928. TypeResult ParsedType) {
  12929. assert(ParsedType.isUsable() && "Expect usable parsed mapper type");
  12930. QualType MapperType = GetTypeFromParser(ParsedType.get());
  12931. assert(!MapperType.isNull() && "Expect valid mapper type");
  12932. // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
  12933. // The type must be of struct, union or class type in C and C++
  12934. if (!MapperType->isStructureOrClassType() && !MapperType->isUnionType()) {
  12935. Diag(TyLoc, diag::err_omp_mapper_wrong_type);
  12936. return QualType();
  12937. }
  12938. return MapperType;
  12939. }
  12940. OMPDeclareMapperDecl *Sema::ActOnOpenMPDeclareMapperDirectiveStart(
  12941. Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType,
  12942. SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS,
  12943. Decl *PrevDeclInScope) {
  12944. LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPMapperName,
  12945. forRedeclarationInCurContext());
  12946. // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
  12947. // A mapper-identifier may not be redeclared in the current scope for the
  12948. // same type or for a type that is compatible according to the base language
  12949. // rules.
  12950. llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
  12951. OMPDeclareMapperDecl *PrevDMD = nullptr;
  12952. bool InCompoundScope = true;
  12953. if (S != nullptr) {
  12954. // Find previous declaration with the same name not referenced in other
  12955. // declarations.
  12956. FunctionScopeInfo *ParentFn = getEnclosingFunction();
  12957. InCompoundScope =
  12958. (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
  12959. LookupName(Lookup, S);
  12960. FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
  12961. /*AllowInlineNamespace=*/false);
  12962. llvm::DenseMap<OMPDeclareMapperDecl *, bool> UsedAsPrevious;
  12963. LookupResult::Filter Filter = Lookup.makeFilter();
  12964. while (Filter.hasNext()) {
  12965. auto *PrevDecl = cast<OMPDeclareMapperDecl>(Filter.next());
  12966. if (InCompoundScope) {
  12967. auto I = UsedAsPrevious.find(PrevDecl);
  12968. if (I == UsedAsPrevious.end())
  12969. UsedAsPrevious[PrevDecl] = false;
  12970. if (OMPDeclareMapperDecl *D = PrevDecl->getPrevDeclInScope())
  12971. UsedAsPrevious[D] = true;
  12972. }
  12973. PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
  12974. PrevDecl->getLocation();
  12975. }
  12976. Filter.done();
  12977. if (InCompoundScope) {
  12978. for (const auto &PrevData : UsedAsPrevious) {
  12979. if (!PrevData.second) {
  12980. PrevDMD = PrevData.first;
  12981. break;
  12982. }
  12983. }
  12984. }
  12985. } else if (PrevDeclInScope) {
  12986. auto *PrevDMDInScope = PrevDMD =
  12987. cast<OMPDeclareMapperDecl>(PrevDeclInScope);
  12988. do {
  12989. PreviousRedeclTypes[PrevDMDInScope->getType().getCanonicalType()] =
  12990. PrevDMDInScope->getLocation();
  12991. PrevDMDInScope = PrevDMDInScope->getPrevDeclInScope();
  12992. } while (PrevDMDInScope != nullptr);
  12993. }
  12994. const auto I = PreviousRedeclTypes.find(MapperType.getCanonicalType());
  12995. bool Invalid = false;
  12996. if (I != PreviousRedeclTypes.end()) {
  12997. Diag(StartLoc, diag::err_omp_declare_mapper_redefinition)
  12998. << MapperType << Name;
  12999. Diag(I->second, diag::note_previous_definition);
  13000. Invalid = true;
  13001. }
  13002. auto *DMD = OMPDeclareMapperDecl::Create(Context, DC, StartLoc, Name,
  13003. MapperType, VN, PrevDMD);
  13004. DC->addDecl(DMD);
  13005. DMD->setAccess(AS);
  13006. if (Invalid)
  13007. DMD->setInvalidDecl();
  13008. // Enter new function scope.
  13009. PushFunctionScope();
  13010. setFunctionHasBranchProtectedScope();
  13011. CurContext = DMD;
  13012. return DMD;
  13013. }
  13014. void Sema::ActOnOpenMPDeclareMapperDirectiveVarDecl(OMPDeclareMapperDecl *DMD,
  13015. Scope *S,
  13016. QualType MapperType,
  13017. SourceLocation StartLoc,
  13018. DeclarationName VN) {
  13019. VarDecl *VD = buildVarDecl(*this, StartLoc, MapperType, VN.getAsString());
  13020. if (S)
  13021. PushOnScopeChains(VD, S);
  13022. else
  13023. DMD->addDecl(VD);
  13024. Expr *MapperVarRefExpr = buildDeclRefExpr(*this, VD, MapperType, StartLoc);
  13025. DMD->setMapperVarRef(MapperVarRefExpr);
  13026. }
  13027. Sema::DeclGroupPtrTy
  13028. Sema::ActOnOpenMPDeclareMapperDirectiveEnd(OMPDeclareMapperDecl *D, Scope *S,
  13029. ArrayRef<OMPClause *> ClauseList) {
  13030. PopDeclContext();
  13031. PopFunctionScopeInfo();
  13032. if (D) {
  13033. if (S)
  13034. PushOnScopeChains(D, S, /*AddToContext=*/false);
  13035. D->CreateClauses(Context, ClauseList);
  13036. }
  13037. return DeclGroupPtrTy::make(DeclGroupRef(D));
  13038. }
  13039. OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
  13040. SourceLocation StartLoc,
  13041. SourceLocation LParenLoc,
  13042. SourceLocation EndLoc) {
  13043. Expr *ValExpr = NumTeams;
  13044. Stmt *HelperValStmt = nullptr;
  13045. // OpenMP [teams Constrcut, Restrictions]
  13046. // The num_teams expression must evaluate to a positive integer value.
  13047. if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
  13048. /*StrictlyPositive=*/true))
  13049. return nullptr;
  13050. OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
  13051. OpenMPDirectiveKind CaptureRegion =
  13052. getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams);
  13053. if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
  13054. ValExpr = MakeFullExpr(ValExpr).get();
  13055. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  13056. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  13057. HelperValStmt = buildPreInits(Context, Captures);
  13058. }
  13059. return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion,
  13060. StartLoc, LParenLoc, EndLoc);
  13061. }
  13062. OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
  13063. SourceLocation StartLoc,
  13064. SourceLocation LParenLoc,
  13065. SourceLocation EndLoc) {
  13066. Expr *ValExpr = ThreadLimit;
  13067. Stmt *HelperValStmt = nullptr;
  13068. // OpenMP [teams Constrcut, Restrictions]
  13069. // The thread_limit expression must evaluate to a positive integer value.
  13070. if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
  13071. /*StrictlyPositive=*/true))
  13072. return nullptr;
  13073. OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
  13074. OpenMPDirectiveKind CaptureRegion =
  13075. getOpenMPCaptureRegionForClause(DKind, OMPC_thread_limit);
  13076. if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
  13077. ValExpr = MakeFullExpr(ValExpr).get();
  13078. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  13079. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  13080. HelperValStmt = buildPreInits(Context, Captures);
  13081. }
  13082. return new (Context) OMPThreadLimitClause(
  13083. ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
  13084. }
  13085. OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
  13086. SourceLocation StartLoc,
  13087. SourceLocation LParenLoc,
  13088. SourceLocation EndLoc) {
  13089. Expr *ValExpr = Priority;
  13090. // OpenMP [2.9.1, task Constrcut]
  13091. // The priority-value is a non-negative numerical scalar expression.
  13092. if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_priority,
  13093. /*StrictlyPositive=*/false))
  13094. return nullptr;
  13095. return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc);
  13096. }
  13097. OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
  13098. SourceLocation StartLoc,
  13099. SourceLocation LParenLoc,
  13100. SourceLocation EndLoc) {
  13101. Expr *ValExpr = Grainsize;
  13102. // OpenMP [2.9.2, taskloop Constrcut]
  13103. // The parameter of the grainsize clause must be a positive integer
  13104. // expression.
  13105. if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize,
  13106. /*StrictlyPositive=*/true))
  13107. return nullptr;
  13108. return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc);
  13109. }
  13110. OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
  13111. SourceLocation StartLoc,
  13112. SourceLocation LParenLoc,
  13113. SourceLocation EndLoc) {
  13114. Expr *ValExpr = NumTasks;
  13115. // OpenMP [2.9.2, taskloop Constrcut]
  13116. // The parameter of the num_tasks clause must be a positive integer
  13117. // expression.
  13118. if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks,
  13119. /*StrictlyPositive=*/true))
  13120. return nullptr;
  13121. return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc);
  13122. }
  13123. OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
  13124. SourceLocation LParenLoc,
  13125. SourceLocation EndLoc) {
  13126. // OpenMP [2.13.2, critical construct, Description]
  13127. // ... where hint-expression is an integer constant expression that evaluates
  13128. // to a valid lock hint.
  13129. ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
  13130. if (HintExpr.isInvalid())
  13131. return nullptr;
  13132. return new (Context)
  13133. OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
  13134. }
  13135. OMPClause *Sema::ActOnOpenMPDistScheduleClause(
  13136. OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
  13137. SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
  13138. SourceLocation EndLoc) {
  13139. if (Kind == OMPC_DIST_SCHEDULE_unknown) {
  13140. std::string Values;
  13141. Values += "'";
  13142. Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
  13143. Values += "'";
  13144. Diag(KindLoc, diag::err_omp_unexpected_clause_value)
  13145. << Values << getOpenMPClauseName(OMPC_dist_schedule);
  13146. return nullptr;
  13147. }
  13148. Expr *ValExpr = ChunkSize;
  13149. Stmt *HelperValStmt = nullptr;
  13150. if (ChunkSize) {
  13151. if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
  13152. !ChunkSize->isInstantiationDependent() &&
  13153. !ChunkSize->containsUnexpandedParameterPack()) {
  13154. SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
  13155. ExprResult Val =
  13156. PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
  13157. if (Val.isInvalid())
  13158. return nullptr;
  13159. ValExpr = Val.get();
  13160. // OpenMP [2.7.1, Restrictions]
  13161. // chunk_size must be a loop invariant integer expression with a positive
  13162. // value.
  13163. llvm::APSInt Result;
  13164. if (ValExpr->isIntegerConstantExpr(Result, Context)) {
  13165. if (Result.isSigned() && !Result.isStrictlyPositive()) {
  13166. Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
  13167. << "dist_schedule" << ChunkSize->getSourceRange();
  13168. return nullptr;
  13169. }
  13170. } else if (getOpenMPCaptureRegionForClause(
  13171. DSAStack->getCurrentDirective(), OMPC_dist_schedule) !=
  13172. OMPD_unknown &&
  13173. !CurContext->isDependentContext()) {
  13174. ValExpr = MakeFullExpr(ValExpr).get();
  13175. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  13176. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  13177. HelperValStmt = buildPreInits(Context, Captures);
  13178. }
  13179. }
  13180. }
  13181. return new (Context)
  13182. OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
  13183. Kind, ValExpr, HelperValStmt);
  13184. }
  13185. OMPClause *Sema::ActOnOpenMPDefaultmapClause(
  13186. OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
  13187. SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
  13188. SourceLocation KindLoc, SourceLocation EndLoc) {
  13189. // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)'
  13190. if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || Kind != OMPC_DEFAULTMAP_scalar) {
  13191. std::string Value;
  13192. SourceLocation Loc;
  13193. Value += "'";
  13194. if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
  13195. Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
  13196. OMPC_DEFAULTMAP_MODIFIER_tofrom);
  13197. Loc = MLoc;
  13198. } else {
  13199. Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
  13200. OMPC_DEFAULTMAP_scalar);
  13201. Loc = KindLoc;
  13202. }
  13203. Value += "'";
  13204. Diag(Loc, diag::err_omp_unexpected_clause_value)
  13205. << Value << getOpenMPClauseName(OMPC_defaultmap);
  13206. return nullptr;
  13207. }
  13208. DSAStack->setDefaultDMAToFromScalar(StartLoc);
  13209. return new (Context)
  13210. OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
  13211. }
  13212. bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) {
  13213. DeclContext *CurLexicalContext = getCurLexicalContext();
  13214. if (!CurLexicalContext->isFileContext() &&
  13215. !CurLexicalContext->isExternCContext() &&
  13216. !CurLexicalContext->isExternCXXContext() &&
  13217. !isa<CXXRecordDecl>(CurLexicalContext) &&
  13218. !isa<ClassTemplateDecl>(CurLexicalContext) &&
  13219. !isa<ClassTemplatePartialSpecializationDecl>(CurLexicalContext) &&
  13220. !isa<ClassTemplateSpecializationDecl>(CurLexicalContext)) {
  13221. Diag(Loc, diag::err_omp_region_not_file_context);
  13222. return false;
  13223. }
  13224. ++DeclareTargetNestingLevel;
  13225. return true;
  13226. }
  13227. void Sema::ActOnFinishOpenMPDeclareTargetDirective() {
  13228. assert(DeclareTargetNestingLevel > 0 &&
  13229. "Unexpected ActOnFinishOpenMPDeclareTargetDirective");
  13230. --DeclareTargetNestingLevel;
  13231. }
  13232. void Sema::ActOnOpenMPDeclareTargetName(Scope *CurScope,
  13233. CXXScopeSpec &ScopeSpec,
  13234. const DeclarationNameInfo &Id,
  13235. OMPDeclareTargetDeclAttr::MapTypeTy MT,
  13236. NamedDeclSetType &SameDirectiveDecls) {
  13237. LookupResult Lookup(*this, Id, LookupOrdinaryName);
  13238. LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
  13239. if (Lookup.isAmbiguous())
  13240. return;
  13241. Lookup.suppressDiagnostics();
  13242. if (!Lookup.isSingleResult()) {
  13243. if (TypoCorrection Corrected =
  13244. CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr,
  13245. llvm::make_unique<VarOrFuncDeclFilterCCC>(*this),
  13246. CTK_ErrorRecovery)) {
  13247. diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
  13248. << Id.getName());
  13249. checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
  13250. return;
  13251. }
  13252. Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
  13253. return;
  13254. }
  13255. NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
  13256. if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND) ||
  13257. isa<FunctionTemplateDecl>(ND)) {
  13258. if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl())))
  13259. Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName();
  13260. llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
  13261. OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(
  13262. cast<ValueDecl>(ND));
  13263. if (!Res) {
  13264. auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT);
  13265. ND->addAttr(A);
  13266. if (ASTMutationListener *ML = Context.getASTMutationListener())
  13267. ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
  13268. checkDeclIsAllowedInOpenMPTarget(nullptr, ND, Id.getLoc());
  13269. } else if (*Res != MT) {
  13270. Diag(Id.getLoc(), diag::err_omp_declare_target_to_and_link)
  13271. << Id.getName();
  13272. }
  13273. } else {
  13274. Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
  13275. }
  13276. }
  13277. static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
  13278. Sema &SemaRef, Decl *D) {
  13279. if (!D || !isa<VarDecl>(D))
  13280. return;
  13281. auto *VD = cast<VarDecl>(D);
  13282. if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
  13283. return;
  13284. SemaRef.Diag(VD->getLocation(), diag::warn_omp_not_in_target_context);
  13285. SemaRef.Diag(SL, diag::note_used_here) << SR;
  13286. }
  13287. static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
  13288. Sema &SemaRef, DSAStackTy *Stack,
  13289. ValueDecl *VD) {
  13290. return VD->hasAttr<OMPDeclareTargetDeclAttr>() ||
  13291. checkTypeMappable(SL, SR, SemaRef, Stack, VD->getType(),
  13292. /*FullCheck=*/false);
  13293. }
  13294. void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D,
  13295. SourceLocation IdLoc) {
  13296. if (!D || D->isInvalidDecl())
  13297. return;
  13298. SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
  13299. SourceLocation SL = E ? E->getBeginLoc() : D->getLocation();
  13300. if (auto *VD = dyn_cast<VarDecl>(D)) {
  13301. // Only global variables can be marked as declare target.
  13302. if (!VD->isFileVarDecl() && !VD->isStaticLocal() &&
  13303. !VD->isStaticDataMember())
  13304. return;
  13305. // 2.10.6: threadprivate variable cannot appear in a declare target
  13306. // directive.
  13307. if (DSAStack->isThreadPrivate(VD)) {
  13308. Diag(SL, diag::err_omp_threadprivate_in_target);
  13309. reportOriginalDsa(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
  13310. return;
  13311. }
  13312. }
  13313. if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(D))
  13314. D = FTD->getTemplatedDecl();
  13315. if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
  13316. llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
  13317. OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(FD);
  13318. if (Res && *Res == OMPDeclareTargetDeclAttr::MT_Link) {
  13319. assert(IdLoc.isValid() && "Source location is expected");
  13320. Diag(IdLoc, diag::err_omp_function_in_link_clause);
  13321. Diag(FD->getLocation(), diag::note_defined_here) << FD;
  13322. return;
  13323. }
  13324. }
  13325. if (auto *VD = dyn_cast<ValueDecl>(D)) {
  13326. // Problem if any with var declared with incomplete type will be reported
  13327. // as normal, so no need to check it here.
  13328. if ((E || !VD->getType()->isIncompleteType()) &&
  13329. !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD))
  13330. return;
  13331. if (!E && !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
  13332. // Checking declaration inside declare target region.
  13333. if (isa<VarDecl>(D) || isa<FunctionDecl>(D) ||
  13334. isa<FunctionTemplateDecl>(D)) {
  13335. auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(
  13336. Context, OMPDeclareTargetDeclAttr::MT_To);
  13337. D->addAttr(A);
  13338. if (ASTMutationListener *ML = Context.getASTMutationListener())
  13339. ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
  13340. }
  13341. return;
  13342. }
  13343. }
  13344. if (!E)
  13345. return;
  13346. checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
  13347. }
  13348. OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
  13349. CXXScopeSpec &MapperIdScopeSpec,
  13350. DeclarationNameInfo &MapperId,
  13351. const OMPVarListLocTy &Locs,
  13352. ArrayRef<Expr *> UnresolvedMappers) {
  13353. MappableVarListInfo MVLI(VarList);
  13354. checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, Locs.StartLoc,
  13355. MapperIdScopeSpec, MapperId, UnresolvedMappers);
  13356. if (MVLI.ProcessedVarList.empty())
  13357. return nullptr;
  13358. return OMPToClause::Create(
  13359. Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
  13360. MVLI.VarComponents, MVLI.UDMapperList,
  13361. MapperIdScopeSpec.getWithLocInContext(Context), MapperId);
  13362. }
  13363. OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
  13364. CXXScopeSpec &MapperIdScopeSpec,
  13365. DeclarationNameInfo &MapperId,
  13366. const OMPVarListLocTy &Locs,
  13367. ArrayRef<Expr *> UnresolvedMappers) {
  13368. MappableVarListInfo MVLI(VarList);
  13369. checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, Locs.StartLoc,
  13370. MapperIdScopeSpec, MapperId, UnresolvedMappers);
  13371. if (MVLI.ProcessedVarList.empty())
  13372. return nullptr;
  13373. return OMPFromClause::Create(
  13374. Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
  13375. MVLI.VarComponents, MVLI.UDMapperList,
  13376. MapperIdScopeSpec.getWithLocInContext(Context), MapperId);
  13377. }
  13378. OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
  13379. const OMPVarListLocTy &Locs) {
  13380. MappableVarListInfo MVLI(VarList);
  13381. SmallVector<Expr *, 8> PrivateCopies;
  13382. SmallVector<Expr *, 8> Inits;
  13383. for (Expr *RefExpr : VarList) {
  13384. assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
  13385. SourceLocation ELoc;
  13386. SourceRange ERange;
  13387. Expr *SimpleRefExpr = RefExpr;
  13388. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  13389. if (Res.second) {
  13390. // It will be analyzed later.
  13391. MVLI.ProcessedVarList.push_back(RefExpr);
  13392. PrivateCopies.push_back(nullptr);
  13393. Inits.push_back(nullptr);
  13394. }
  13395. ValueDecl *D = Res.first;
  13396. if (!D)
  13397. continue;
  13398. QualType Type = D->getType();
  13399. Type = Type.getNonReferenceType().getUnqualifiedType();
  13400. auto *VD = dyn_cast<VarDecl>(D);
  13401. // Item should be a pointer or reference to pointer.
  13402. if (!Type->isPointerType()) {
  13403. Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
  13404. << 0 << RefExpr->getSourceRange();
  13405. continue;
  13406. }
  13407. // Build the private variable and the expression that refers to it.
  13408. auto VDPrivate =
  13409. buildVarDecl(*this, ELoc, Type, D->getName(),
  13410. D->hasAttrs() ? &D->getAttrs() : nullptr,
  13411. VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
  13412. if (VDPrivate->isInvalidDecl())
  13413. continue;
  13414. CurContext->addDecl(VDPrivate);
  13415. DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
  13416. *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
  13417. // Add temporary variable to initialize the private copy of the pointer.
  13418. VarDecl *VDInit =
  13419. buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
  13420. DeclRefExpr *VDInitRefExpr = buildDeclRefExpr(
  13421. *this, VDInit, RefExpr->getType(), RefExpr->getExprLoc());
  13422. AddInitializerToDecl(VDPrivate,
  13423. DefaultLvalueConversion(VDInitRefExpr).get(),
  13424. /*DirectInit=*/false);
  13425. // If required, build a capture to implement the privatization initialized
  13426. // with the current list item value.
  13427. DeclRefExpr *Ref = nullptr;
  13428. if (!VD)
  13429. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
  13430. MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
  13431. PrivateCopies.push_back(VDPrivateRefExpr);
  13432. Inits.push_back(VDInitRefExpr);
  13433. // We need to add a data sharing attribute for this variable to make sure it
  13434. // is correctly captured. A variable that shows up in a use_device_ptr has
  13435. // similar properties of a first private variable.
  13436. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
  13437. // Create a mappable component for the list item. List items in this clause
  13438. // only need a component.
  13439. MVLI.VarBaseDeclarations.push_back(D);
  13440. MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
  13441. MVLI.VarComponents.back().push_back(
  13442. OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D));
  13443. }
  13444. if (MVLI.ProcessedVarList.empty())
  13445. return nullptr;
  13446. return OMPUseDevicePtrClause::Create(
  13447. Context, Locs, MVLI.ProcessedVarList, PrivateCopies, Inits,
  13448. MVLI.VarBaseDeclarations, MVLI.VarComponents);
  13449. }
  13450. OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
  13451. const OMPVarListLocTy &Locs) {
  13452. MappableVarListInfo MVLI(VarList);
  13453. for (Expr *RefExpr : VarList) {
  13454. assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
  13455. SourceLocation ELoc;
  13456. SourceRange ERange;
  13457. Expr *SimpleRefExpr = RefExpr;
  13458. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  13459. if (Res.second) {
  13460. // It will be analyzed later.
  13461. MVLI.ProcessedVarList.push_back(RefExpr);
  13462. }
  13463. ValueDecl *D = Res.first;
  13464. if (!D)
  13465. continue;
  13466. QualType Type = D->getType();
  13467. // item should be a pointer or array or reference to pointer or array
  13468. if (!Type.getNonReferenceType()->isPointerType() &&
  13469. !Type.getNonReferenceType()->isArrayType()) {
  13470. Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
  13471. << 0 << RefExpr->getSourceRange();
  13472. continue;
  13473. }
  13474. // Check if the declaration in the clause does not show up in any data
  13475. // sharing attribute.
  13476. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
  13477. if (isOpenMPPrivate(DVar.CKind)) {
  13478. Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
  13479. << getOpenMPClauseName(DVar.CKind)
  13480. << getOpenMPClauseName(OMPC_is_device_ptr)
  13481. << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
  13482. reportOriginalDsa(*this, DSAStack, D, DVar);
  13483. continue;
  13484. }
  13485. const Expr *ConflictExpr;
  13486. if (DSAStack->checkMappableExprComponentListsForDecl(
  13487. D, /*CurrentRegionOnly=*/true,
  13488. [&ConflictExpr](
  13489. OMPClauseMappableExprCommon::MappableExprComponentListRef R,
  13490. OpenMPClauseKind) -> bool {
  13491. ConflictExpr = R.front().getAssociatedExpression();
  13492. return true;
  13493. })) {
  13494. Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
  13495. Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
  13496. << ConflictExpr->getSourceRange();
  13497. continue;
  13498. }
  13499. // Store the components in the stack so that they can be used to check
  13500. // against other clauses later on.
  13501. OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D);
  13502. DSAStack->addMappableExpressionComponents(
  13503. D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
  13504. // Record the expression we've just processed.
  13505. MVLI.ProcessedVarList.push_back(SimpleRefExpr);
  13506. // Create a mappable component for the list item. List items in this clause
  13507. // only need a component. We use a null declaration to signal fields in
  13508. // 'this'.
  13509. assert((isa<DeclRefExpr>(SimpleRefExpr) ||
  13510. isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
  13511. "Unexpected device pointer expression!");
  13512. MVLI.VarBaseDeclarations.push_back(
  13513. isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
  13514. MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
  13515. MVLI.VarComponents.back().push_back(MC);
  13516. }
  13517. if (MVLI.ProcessedVarList.empty())
  13518. return nullptr;
  13519. return OMPIsDevicePtrClause::Create(Context, Locs, MVLI.ProcessedVarList,
  13520. MVLI.VarBaseDeclarations,
  13521. MVLI.VarComponents);
  13522. }