SemaOpenMP.cpp 604 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277
  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. bool BodyComplete = false;
  139. SourceLocation InnerTeamsRegionLoc;
  140. /// Reference to the taskgroup task_reduction reference expression.
  141. Expr *TaskgroupReductionRef = nullptr;
  142. llvm::DenseSet<QualType> MappedClassesQualTypes;
  143. /// List of globals marked as declare target link in this target region
  144. /// (isOpenMPTargetExecutionDirective(Directive) == true).
  145. llvm::SmallVector<DeclRefExpr *, 4> DeclareTargetLinkVarDecls;
  146. SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name,
  147. Scope *CurScope, SourceLocation Loc)
  148. : Directive(DKind), DirectiveName(Name), CurScope(CurScope),
  149. ConstructLoc(Loc) {}
  150. SharingMapTy() = default;
  151. };
  152. using StackTy = SmallVector<SharingMapTy, 4>;
  153. /// Stack of used declaration and their data-sharing attributes.
  154. DeclSAMapTy Threadprivates;
  155. const FunctionScopeInfo *CurrentNonCapturingFunctionScope = nullptr;
  156. SmallVector<std::pair<StackTy, const FunctionScopeInfo *>, 4> Stack;
  157. /// true, if check for DSA must be from parent directive, false, if
  158. /// from current directive.
  159. OpenMPClauseKind ClauseKindMode = OMPC_unknown;
  160. Sema &SemaRef;
  161. bool ForceCapturing = false;
  162. /// true if all the vaiables in the target executable directives must be
  163. /// captured by reference.
  164. bool ForceCaptureByReferenceInTargetExecutable = false;
  165. CriticalsWithHintsTy Criticals;
  166. unsigned IgnoredStackElements = 0;
  167. /// Iterators over the stack iterate in order from innermost to outermost
  168. /// directive.
  169. using const_iterator = StackTy::const_reverse_iterator;
  170. const_iterator begin() const {
  171. return Stack.empty() ? const_iterator()
  172. : Stack.back().first.rbegin() + IgnoredStackElements;
  173. }
  174. const_iterator end() const {
  175. return Stack.empty() ? const_iterator() : Stack.back().first.rend();
  176. }
  177. using iterator = StackTy::reverse_iterator;
  178. iterator begin() {
  179. return Stack.empty() ? iterator()
  180. : Stack.back().first.rbegin() + IgnoredStackElements;
  181. }
  182. iterator end() {
  183. return Stack.empty() ? iterator() : Stack.back().first.rend();
  184. }
  185. // Convenience operations to get at the elements of the stack.
  186. bool isStackEmpty() const {
  187. return Stack.empty() ||
  188. Stack.back().second != CurrentNonCapturingFunctionScope ||
  189. Stack.back().first.size() <= IgnoredStackElements;
  190. }
  191. size_t getStackSize() const {
  192. return isStackEmpty() ? 0
  193. : Stack.back().first.size() - IgnoredStackElements;
  194. }
  195. SharingMapTy *getTopOfStackOrNull() {
  196. size_t Size = getStackSize();
  197. if (Size == 0)
  198. return nullptr;
  199. return &Stack.back().first[Size - 1];
  200. }
  201. const SharingMapTy *getTopOfStackOrNull() const {
  202. return const_cast<DSAStackTy&>(*this).getTopOfStackOrNull();
  203. }
  204. SharingMapTy &getTopOfStack() {
  205. assert(!isStackEmpty() && "no current directive");
  206. return *getTopOfStackOrNull();
  207. }
  208. const SharingMapTy &getTopOfStack() const {
  209. return const_cast<DSAStackTy&>(*this).getTopOfStack();
  210. }
  211. SharingMapTy *getSecondOnStackOrNull() {
  212. size_t Size = getStackSize();
  213. if (Size <= 1)
  214. return nullptr;
  215. return &Stack.back().first[Size - 2];
  216. }
  217. const SharingMapTy *getSecondOnStackOrNull() const {
  218. return const_cast<DSAStackTy&>(*this).getSecondOnStackOrNull();
  219. }
  220. /// Get the stack element at a certain level (previously returned by
  221. /// \c getNestingLevel).
  222. ///
  223. /// Note that nesting levels count from outermost to innermost, and this is
  224. /// the reverse of our iteration order where new inner levels are pushed at
  225. /// the front of the stack.
  226. SharingMapTy &getStackElemAtLevel(unsigned Level) {
  227. assert(Level < getStackSize() && "no such stack element");
  228. return Stack.back().first[Level];
  229. }
  230. const SharingMapTy &getStackElemAtLevel(unsigned Level) const {
  231. return const_cast<DSAStackTy&>(*this).getStackElemAtLevel(Level);
  232. }
  233. DSAVarData getDSA(const_iterator &Iter, ValueDecl *D) const;
  234. /// Checks if the variable is a local for OpenMP region.
  235. bool isOpenMPLocal(VarDecl *D, const_iterator Iter) const;
  236. /// Vector of previously declared requires directives
  237. SmallVector<const OMPRequiresDecl *, 2> RequiresDecls;
  238. /// omp_allocator_handle_t type.
  239. QualType OMPAllocatorHandleT;
  240. /// Expression for the predefined allocators.
  241. Expr *OMPPredefinedAllocators[OMPAllocateDeclAttr::OMPUserDefinedMemAlloc] = {
  242. nullptr};
  243. /// Vector of previously encountered target directives
  244. SmallVector<SourceLocation, 2> TargetLocations;
  245. public:
  246. explicit DSAStackTy(Sema &S) : SemaRef(S) {}
  247. /// Sets omp_allocator_handle_t type.
  248. void setOMPAllocatorHandleT(QualType Ty) { OMPAllocatorHandleT = Ty; }
  249. /// Gets omp_allocator_handle_t type.
  250. QualType getOMPAllocatorHandleT() const { return OMPAllocatorHandleT; }
  251. /// Sets the given default allocator.
  252. void setAllocator(OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind,
  253. Expr *Allocator) {
  254. OMPPredefinedAllocators[AllocatorKind] = Allocator;
  255. }
  256. /// Returns the specified default allocator.
  257. Expr *getAllocator(OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind) const {
  258. return OMPPredefinedAllocators[AllocatorKind];
  259. }
  260. bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; }
  261. OpenMPClauseKind getClauseParsingMode() const {
  262. assert(isClauseParsingMode() && "Must be in clause parsing mode.");
  263. return ClauseKindMode;
  264. }
  265. void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; }
  266. bool isBodyComplete() const {
  267. const SharingMapTy *Top = getTopOfStackOrNull();
  268. return Top && Top->BodyComplete;
  269. }
  270. void setBodyComplete() {
  271. getTopOfStack().BodyComplete = true;
  272. }
  273. bool isForceVarCapturing() const { return ForceCapturing; }
  274. void setForceVarCapturing(bool V) { ForceCapturing = V; }
  275. void setForceCaptureByReferenceInTargetExecutable(bool V) {
  276. ForceCaptureByReferenceInTargetExecutable = V;
  277. }
  278. bool isForceCaptureByReferenceInTargetExecutable() const {
  279. return ForceCaptureByReferenceInTargetExecutable;
  280. }
  281. void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
  282. Scope *CurScope, SourceLocation Loc) {
  283. assert(!IgnoredStackElements &&
  284. "cannot change stack while ignoring elements");
  285. if (Stack.empty() ||
  286. Stack.back().second != CurrentNonCapturingFunctionScope)
  287. Stack.emplace_back(StackTy(), CurrentNonCapturingFunctionScope);
  288. Stack.back().first.emplace_back(DKind, DirName, CurScope, Loc);
  289. Stack.back().first.back().DefaultAttrLoc = Loc;
  290. }
  291. void pop() {
  292. assert(!IgnoredStackElements &&
  293. "cannot change stack while ignoring elements");
  294. assert(!Stack.back().first.empty() &&
  295. "Data-sharing attributes stack is empty!");
  296. Stack.back().first.pop_back();
  297. }
  298. /// RAII object to temporarily leave the scope of a directive when we want to
  299. /// logically operate in its parent.
  300. class ParentDirectiveScope {
  301. DSAStackTy &Self;
  302. bool Active;
  303. public:
  304. ParentDirectiveScope(DSAStackTy &Self, bool Activate)
  305. : Self(Self), Active(false) {
  306. if (Activate)
  307. enable();
  308. }
  309. ~ParentDirectiveScope() { disable(); }
  310. void disable() {
  311. if (Active) {
  312. --Self.IgnoredStackElements;
  313. Active = false;
  314. }
  315. }
  316. void enable() {
  317. if (!Active) {
  318. ++Self.IgnoredStackElements;
  319. Active = true;
  320. }
  321. }
  322. };
  323. /// Marks that we're started loop parsing.
  324. void loopInit() {
  325. assert(isOpenMPLoopDirective(getCurrentDirective()) &&
  326. "Expected loop-based directive.");
  327. getTopOfStack().LoopStart = true;
  328. }
  329. /// Start capturing of the variables in the loop context.
  330. void loopStart() {
  331. assert(isOpenMPLoopDirective(getCurrentDirective()) &&
  332. "Expected loop-based directive.");
  333. getTopOfStack().LoopStart = false;
  334. }
  335. /// true, if variables are captured, false otherwise.
  336. bool isLoopStarted() const {
  337. assert(isOpenMPLoopDirective(getCurrentDirective()) &&
  338. "Expected loop-based directive.");
  339. return !getTopOfStack().LoopStart;
  340. }
  341. /// Marks (or clears) declaration as possibly loop counter.
  342. void resetPossibleLoopCounter(const Decl *D = nullptr) {
  343. getTopOfStack().PossiblyLoopCounter =
  344. D ? D->getCanonicalDecl() : D;
  345. }
  346. /// Gets the possible loop counter decl.
  347. const Decl *getPossiblyLoopCunter() const {
  348. return getTopOfStack().PossiblyLoopCounter;
  349. }
  350. /// Start new OpenMP region stack in new non-capturing function.
  351. void pushFunction() {
  352. assert(!IgnoredStackElements &&
  353. "cannot change stack while ignoring elements");
  354. const FunctionScopeInfo *CurFnScope = SemaRef.getCurFunction();
  355. assert(!isa<CapturingScopeInfo>(CurFnScope));
  356. CurrentNonCapturingFunctionScope = CurFnScope;
  357. }
  358. /// Pop region stack for non-capturing function.
  359. void popFunction(const FunctionScopeInfo *OldFSI) {
  360. assert(!IgnoredStackElements &&
  361. "cannot change stack while ignoring elements");
  362. if (!Stack.empty() && Stack.back().second == OldFSI) {
  363. assert(Stack.back().first.empty());
  364. Stack.pop_back();
  365. }
  366. CurrentNonCapturingFunctionScope = nullptr;
  367. for (const FunctionScopeInfo *FSI : llvm::reverse(SemaRef.FunctionScopes)) {
  368. if (!isa<CapturingScopeInfo>(FSI)) {
  369. CurrentNonCapturingFunctionScope = FSI;
  370. break;
  371. }
  372. }
  373. }
  374. void addCriticalWithHint(const OMPCriticalDirective *D, llvm::APSInt Hint) {
  375. Criticals.try_emplace(D->getDirectiveName().getAsString(), D, Hint);
  376. }
  377. const std::pair<const OMPCriticalDirective *, llvm::APSInt>
  378. getCriticalWithHint(const DeclarationNameInfo &Name) const {
  379. auto I = Criticals.find(Name.getAsString());
  380. if (I != Criticals.end())
  381. return I->second;
  382. return std::make_pair(nullptr, llvm::APSInt());
  383. }
  384. /// If 'aligned' declaration for given variable \a D was not seen yet,
  385. /// add it and return NULL; otherwise return previous occurrence's expression
  386. /// for diagnostics.
  387. const Expr *addUniqueAligned(const ValueDecl *D, const Expr *NewDE);
  388. /// Register specified variable as loop control variable.
  389. void addLoopControlVariable(const ValueDecl *D, VarDecl *Capture);
  390. /// Check if the specified variable is a loop control variable for
  391. /// current region.
  392. /// \return The index of the loop control variable in the list of associated
  393. /// for-loops (from outer to inner).
  394. const LCDeclInfo isLoopControlVariable(const ValueDecl *D) const;
  395. /// Check if the specified variable is a loop control variable for
  396. /// parent region.
  397. /// \return The index of the loop control variable in the list of associated
  398. /// for-loops (from outer to inner).
  399. const LCDeclInfo isParentLoopControlVariable(const ValueDecl *D) const;
  400. /// Get the loop control variable for the I-th loop (or nullptr) in
  401. /// parent directive.
  402. const ValueDecl *getParentLoopControlVariable(unsigned I) const;
  403. /// Adds explicit data sharing attribute to the specified declaration.
  404. void addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A,
  405. DeclRefExpr *PrivateCopy = nullptr);
  406. /// Adds additional information for the reduction items with the reduction id
  407. /// represented as an operator.
  408. void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
  409. BinaryOperatorKind BOK);
  410. /// Adds additional information for the reduction items with the reduction id
  411. /// represented as reduction identifier.
  412. void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
  413. const Expr *ReductionRef);
  414. /// Returns the location and reduction operation from the innermost parent
  415. /// region for the given \p D.
  416. const DSAVarData
  417. getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR,
  418. BinaryOperatorKind &BOK,
  419. Expr *&TaskgroupDescriptor) const;
  420. /// Returns the location and reduction operation from the innermost parent
  421. /// region for the given \p D.
  422. const DSAVarData
  423. getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR,
  424. const Expr *&ReductionRef,
  425. Expr *&TaskgroupDescriptor) const;
  426. /// Return reduction reference expression for the current taskgroup.
  427. Expr *getTaskgroupReductionRef() const {
  428. assert(getTopOfStack().Directive == OMPD_taskgroup &&
  429. "taskgroup reference expression requested for non taskgroup "
  430. "directive.");
  431. return getTopOfStack().TaskgroupReductionRef;
  432. }
  433. /// Checks if the given \p VD declaration is actually a taskgroup reduction
  434. /// descriptor variable at the \p Level of OpenMP regions.
  435. bool isTaskgroupReductionRef(const ValueDecl *VD, unsigned Level) const {
  436. return getStackElemAtLevel(Level).TaskgroupReductionRef &&
  437. cast<DeclRefExpr>(getStackElemAtLevel(Level).TaskgroupReductionRef)
  438. ->getDecl() == VD;
  439. }
  440. /// Returns data sharing attributes from top of the stack for the
  441. /// specified declaration.
  442. const DSAVarData getTopDSA(ValueDecl *D, bool FromParent);
  443. /// Returns data-sharing attributes for the specified declaration.
  444. const DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent) const;
  445. /// Checks if the specified variables has data-sharing attributes which
  446. /// match specified \a CPred predicate in any directive which matches \a DPred
  447. /// predicate.
  448. const DSAVarData
  449. hasDSA(ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
  450. const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
  451. bool FromParent) const;
  452. /// Checks if the specified variables has data-sharing attributes which
  453. /// match specified \a CPred predicate in any innermost directive which
  454. /// matches \a DPred predicate.
  455. const DSAVarData
  456. hasInnermostDSA(ValueDecl *D,
  457. const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
  458. const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
  459. bool FromParent) const;
  460. /// Checks if the specified variables has explicit data-sharing
  461. /// attributes which match specified \a CPred predicate at the specified
  462. /// OpenMP region.
  463. bool hasExplicitDSA(const ValueDecl *D,
  464. const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
  465. unsigned Level, bool NotLastprivate = false) const;
  466. /// Returns true if the directive at level \Level matches in the
  467. /// specified \a DPred predicate.
  468. bool hasExplicitDirective(
  469. const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
  470. unsigned Level) const;
  471. /// Finds a directive which matches specified \a DPred predicate.
  472. bool hasDirective(
  473. const llvm::function_ref<bool(
  474. OpenMPDirectiveKind, const DeclarationNameInfo &, SourceLocation)>
  475. DPred,
  476. bool FromParent) const;
  477. /// Returns currently analyzed directive.
  478. OpenMPDirectiveKind getCurrentDirective() const {
  479. const SharingMapTy *Top = getTopOfStackOrNull();
  480. return Top ? Top->Directive : OMPD_unknown;
  481. }
  482. /// Returns directive kind at specified level.
  483. OpenMPDirectiveKind getDirective(unsigned Level) const {
  484. assert(!isStackEmpty() && "No directive at specified level.");
  485. return getStackElemAtLevel(Level).Directive;
  486. }
  487. /// Returns parent directive.
  488. OpenMPDirectiveKind getParentDirective() const {
  489. const SharingMapTy *Parent = getSecondOnStackOrNull();
  490. return Parent ? Parent->Directive : OMPD_unknown;
  491. }
  492. /// Add requires decl to internal vector
  493. void addRequiresDecl(OMPRequiresDecl *RD) {
  494. RequiresDecls.push_back(RD);
  495. }
  496. /// Checks if the defined 'requires' directive has specified type of clause.
  497. template <typename ClauseType>
  498. bool hasRequiresDeclWithClause() {
  499. return llvm::any_of(RequiresDecls, [](const OMPRequiresDecl *D) {
  500. return llvm::any_of(D->clauselists(), [](const OMPClause *C) {
  501. return isa<ClauseType>(C);
  502. });
  503. });
  504. }
  505. /// Checks for a duplicate clause amongst previously declared requires
  506. /// directives
  507. bool hasDuplicateRequiresClause(ArrayRef<OMPClause *> ClauseList) const {
  508. bool IsDuplicate = false;
  509. for (OMPClause *CNew : ClauseList) {
  510. for (const OMPRequiresDecl *D : RequiresDecls) {
  511. for (const OMPClause *CPrev : D->clauselists()) {
  512. if (CNew->getClauseKind() == CPrev->getClauseKind()) {
  513. SemaRef.Diag(CNew->getBeginLoc(),
  514. diag::err_omp_requires_clause_redeclaration)
  515. << getOpenMPClauseName(CNew->getClauseKind());
  516. SemaRef.Diag(CPrev->getBeginLoc(),
  517. diag::note_omp_requires_previous_clause)
  518. << getOpenMPClauseName(CPrev->getClauseKind());
  519. IsDuplicate = true;
  520. }
  521. }
  522. }
  523. }
  524. return IsDuplicate;
  525. }
  526. /// Add location of previously encountered target to internal vector
  527. void addTargetDirLocation(SourceLocation LocStart) {
  528. TargetLocations.push_back(LocStart);
  529. }
  530. // Return previously encountered target region locations.
  531. ArrayRef<SourceLocation> getEncounteredTargetLocs() const {
  532. return TargetLocations;
  533. }
  534. /// Set default data sharing attribute to none.
  535. void setDefaultDSANone(SourceLocation Loc) {
  536. getTopOfStack().DefaultAttr = DSA_none;
  537. getTopOfStack().DefaultAttrLoc = Loc;
  538. }
  539. /// Set default data sharing attribute to shared.
  540. void setDefaultDSAShared(SourceLocation Loc) {
  541. getTopOfStack().DefaultAttr = DSA_shared;
  542. getTopOfStack().DefaultAttrLoc = Loc;
  543. }
  544. /// Set default data mapping attribute to 'tofrom:scalar'.
  545. void setDefaultDMAToFromScalar(SourceLocation Loc) {
  546. getTopOfStack().DefaultMapAttr = DMA_tofrom_scalar;
  547. getTopOfStack().DefaultMapAttrLoc = Loc;
  548. }
  549. DefaultDataSharingAttributes getDefaultDSA() const {
  550. return isStackEmpty() ? DSA_unspecified
  551. : getTopOfStack().DefaultAttr;
  552. }
  553. SourceLocation getDefaultDSALocation() const {
  554. return isStackEmpty() ? SourceLocation()
  555. : getTopOfStack().DefaultAttrLoc;
  556. }
  557. DefaultMapAttributes getDefaultDMA() const {
  558. return isStackEmpty() ? DMA_unspecified
  559. : getTopOfStack().DefaultMapAttr;
  560. }
  561. DefaultMapAttributes getDefaultDMAAtLevel(unsigned Level) const {
  562. return getStackElemAtLevel(Level).DefaultMapAttr;
  563. }
  564. SourceLocation getDefaultDMALocation() const {
  565. return isStackEmpty() ? SourceLocation()
  566. : getTopOfStack().DefaultMapAttrLoc;
  567. }
  568. /// Checks if the specified variable is a threadprivate.
  569. bool isThreadPrivate(VarDecl *D) {
  570. const DSAVarData DVar = getTopDSA(D, false);
  571. return isOpenMPThreadPrivate(DVar.CKind);
  572. }
  573. /// Marks current region as ordered (it has an 'ordered' clause).
  574. void setOrderedRegion(bool IsOrdered, const Expr *Param,
  575. OMPOrderedClause *Clause) {
  576. if (IsOrdered)
  577. getTopOfStack().OrderedRegion.emplace(Param, Clause);
  578. else
  579. getTopOfStack().OrderedRegion.reset();
  580. }
  581. /// Returns true, if region is ordered (has associated 'ordered' clause),
  582. /// false - otherwise.
  583. bool isOrderedRegion() const {
  584. if (const SharingMapTy *Top = getTopOfStackOrNull())
  585. return Top->OrderedRegion.hasValue();
  586. return false;
  587. }
  588. /// Returns optional parameter for the ordered region.
  589. std::pair<const Expr *, OMPOrderedClause *> getOrderedRegionParam() const {
  590. if (const SharingMapTy *Top = getTopOfStackOrNull())
  591. if (Top->OrderedRegion.hasValue())
  592. return Top->OrderedRegion.getValue();
  593. return std::make_pair(nullptr, nullptr);
  594. }
  595. /// Returns true, if parent region is ordered (has associated
  596. /// 'ordered' clause), false - otherwise.
  597. bool isParentOrderedRegion() const {
  598. if (const SharingMapTy *Parent = getSecondOnStackOrNull())
  599. return Parent->OrderedRegion.hasValue();
  600. return false;
  601. }
  602. /// Returns optional parameter for the ordered region.
  603. std::pair<const Expr *, OMPOrderedClause *>
  604. getParentOrderedRegionParam() const {
  605. if (const SharingMapTy *Parent = getSecondOnStackOrNull())
  606. if (Parent->OrderedRegion.hasValue())
  607. return Parent->OrderedRegion.getValue();
  608. return std::make_pair(nullptr, nullptr);
  609. }
  610. /// Marks current region as nowait (it has a 'nowait' clause).
  611. void setNowaitRegion(bool IsNowait = true) {
  612. getTopOfStack().NowaitRegion = IsNowait;
  613. }
  614. /// Returns true, if parent region is nowait (has associated
  615. /// 'nowait' clause), false - otherwise.
  616. bool isParentNowaitRegion() const {
  617. if (const SharingMapTy *Parent = getSecondOnStackOrNull())
  618. return Parent->NowaitRegion;
  619. return false;
  620. }
  621. /// Marks parent region as cancel region.
  622. void setParentCancelRegion(bool Cancel = true) {
  623. if (SharingMapTy *Parent = getSecondOnStackOrNull())
  624. Parent->CancelRegion |= Cancel;
  625. }
  626. /// Return true if current region has inner cancel construct.
  627. bool isCancelRegion() const {
  628. const SharingMapTy *Top = getTopOfStackOrNull();
  629. return Top ? Top->CancelRegion : false;
  630. }
  631. /// Set collapse value for the region.
  632. void setAssociatedLoops(unsigned Val) {
  633. getTopOfStack().AssociatedLoops = Val;
  634. }
  635. /// Return collapse value for region.
  636. unsigned getAssociatedLoops() const {
  637. const SharingMapTy *Top = getTopOfStackOrNull();
  638. return Top ? Top->AssociatedLoops : 0;
  639. }
  640. /// Marks current target region as one with closely nested teams
  641. /// region.
  642. void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
  643. if (SharingMapTy *Parent = getSecondOnStackOrNull())
  644. Parent->InnerTeamsRegionLoc = TeamsRegionLoc;
  645. }
  646. /// Returns true, if current region has closely nested teams region.
  647. bool hasInnerTeamsRegion() const {
  648. return getInnerTeamsRegionLoc().isValid();
  649. }
  650. /// Returns location of the nested teams region (if any).
  651. SourceLocation getInnerTeamsRegionLoc() const {
  652. const SharingMapTy *Top = getTopOfStackOrNull();
  653. return Top ? Top->InnerTeamsRegionLoc : SourceLocation();
  654. }
  655. Scope *getCurScope() const {
  656. const SharingMapTy *Top = getTopOfStackOrNull();
  657. return Top ? Top->CurScope : nullptr;
  658. }
  659. SourceLocation getConstructLoc() const {
  660. const SharingMapTy *Top = getTopOfStackOrNull();
  661. return Top ? Top->ConstructLoc : SourceLocation();
  662. }
  663. /// Do the check specified in \a Check to all component lists and return true
  664. /// if any issue is found.
  665. bool checkMappableExprComponentListsForDecl(
  666. const ValueDecl *VD, bool CurrentRegionOnly,
  667. const llvm::function_ref<
  668. bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
  669. OpenMPClauseKind)>
  670. Check) const {
  671. if (isStackEmpty())
  672. return false;
  673. auto SI = begin();
  674. auto SE = end();
  675. if (SI == SE)
  676. return false;
  677. if (CurrentRegionOnly)
  678. SE = std::next(SI);
  679. else
  680. std::advance(SI, 1);
  681. for (; SI != SE; ++SI) {
  682. auto MI = SI->MappedExprComponents.find(VD);
  683. if (MI != SI->MappedExprComponents.end())
  684. for (OMPClauseMappableExprCommon::MappableExprComponentListRef L :
  685. MI->second.Components)
  686. if (Check(L, MI->second.Kind))
  687. return true;
  688. }
  689. return false;
  690. }
  691. /// Do the check specified in \a Check to all component lists at a given level
  692. /// and return true if any issue is found.
  693. bool checkMappableExprComponentListsForDeclAtLevel(
  694. const ValueDecl *VD, unsigned Level,
  695. const llvm::function_ref<
  696. bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
  697. OpenMPClauseKind)>
  698. Check) const {
  699. if (getStackSize() <= Level)
  700. return false;
  701. const SharingMapTy &StackElem = getStackElemAtLevel(Level);
  702. auto MI = StackElem.MappedExprComponents.find(VD);
  703. if (MI != StackElem.MappedExprComponents.end())
  704. for (OMPClauseMappableExprCommon::MappableExprComponentListRef L :
  705. MI->second.Components)
  706. if (Check(L, MI->second.Kind))
  707. return true;
  708. return false;
  709. }
  710. /// Create a new mappable expression component list associated with a given
  711. /// declaration and initialize it with the provided list of components.
  712. void addMappableExpressionComponents(
  713. const ValueDecl *VD,
  714. OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
  715. OpenMPClauseKind WhereFoundClauseKind) {
  716. MappedExprComponentTy &MEC = getTopOfStack().MappedExprComponents[VD];
  717. // Create new entry and append the new components there.
  718. MEC.Components.resize(MEC.Components.size() + 1);
  719. MEC.Components.back().append(Components.begin(), Components.end());
  720. MEC.Kind = WhereFoundClauseKind;
  721. }
  722. unsigned getNestingLevel() const {
  723. assert(!isStackEmpty());
  724. return getStackSize() - 1;
  725. }
  726. void addDoacrossDependClause(OMPDependClause *C,
  727. const OperatorOffsetTy &OpsOffs) {
  728. SharingMapTy *Parent = getSecondOnStackOrNull();
  729. assert(Parent && isOpenMPWorksharingDirective(Parent->Directive));
  730. Parent->DoacrossDepends.try_emplace(C, OpsOffs);
  731. }
  732. llvm::iterator_range<DoacrossDependMapTy::const_iterator>
  733. getDoacrossDependClauses() const {
  734. const SharingMapTy &StackElem = getTopOfStack();
  735. if (isOpenMPWorksharingDirective(StackElem.Directive)) {
  736. const DoacrossDependMapTy &Ref = StackElem.DoacrossDepends;
  737. return llvm::make_range(Ref.begin(), Ref.end());
  738. }
  739. return llvm::make_range(StackElem.DoacrossDepends.end(),
  740. StackElem.DoacrossDepends.end());
  741. }
  742. // Store types of classes which have been explicitly mapped
  743. void addMappedClassesQualTypes(QualType QT) {
  744. SharingMapTy &StackElem = getTopOfStack();
  745. StackElem.MappedClassesQualTypes.insert(QT);
  746. }
  747. // Return set of mapped classes types
  748. bool isClassPreviouslyMapped(QualType QT) const {
  749. const SharingMapTy &StackElem = getTopOfStack();
  750. return StackElem.MappedClassesQualTypes.count(QT) != 0;
  751. }
  752. /// Adds global declare target to the parent target region.
  753. void addToParentTargetRegionLinkGlobals(DeclRefExpr *E) {
  754. assert(*OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(
  755. E->getDecl()) == OMPDeclareTargetDeclAttr::MT_Link &&
  756. "Expected declare target link global.");
  757. for (auto &Elem : *this) {
  758. if (isOpenMPTargetExecutionDirective(Elem.Directive)) {
  759. Elem.DeclareTargetLinkVarDecls.push_back(E);
  760. return;
  761. }
  762. }
  763. }
  764. /// Returns the list of globals with declare target link if current directive
  765. /// is target.
  766. ArrayRef<DeclRefExpr *> getLinkGlobals() const {
  767. assert(isOpenMPTargetExecutionDirective(getCurrentDirective()) &&
  768. "Expected target executable directive.");
  769. return getTopOfStack().DeclareTargetLinkVarDecls;
  770. }
  771. };
  772. bool isImplicitTaskingRegion(OpenMPDirectiveKind DKind) {
  773. return isOpenMPParallelDirective(DKind) || isOpenMPTeamsDirective(DKind);
  774. }
  775. bool isImplicitOrExplicitTaskingRegion(OpenMPDirectiveKind DKind) {
  776. return isImplicitTaskingRegion(DKind) || isOpenMPTaskingDirective(DKind) ||
  777. DKind == OMPD_unknown;
  778. }
  779. } // namespace
  780. static const Expr *getExprAsWritten(const Expr *E) {
  781. if (const auto *FE = dyn_cast<FullExpr>(E))
  782. E = FE->getSubExpr();
  783. if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
  784. E = MTE->GetTemporaryExpr();
  785. while (const auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
  786. E = Binder->getSubExpr();
  787. if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
  788. E = ICE->getSubExprAsWritten();
  789. return E->IgnoreParens();
  790. }
  791. static Expr *getExprAsWritten(Expr *E) {
  792. return const_cast<Expr *>(getExprAsWritten(const_cast<const Expr *>(E)));
  793. }
  794. static const ValueDecl *getCanonicalDecl(const ValueDecl *D) {
  795. if (const auto *CED = dyn_cast<OMPCapturedExprDecl>(D))
  796. if (const auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
  797. D = ME->getMemberDecl();
  798. const auto *VD = dyn_cast<VarDecl>(D);
  799. const auto *FD = dyn_cast<FieldDecl>(D);
  800. if (VD != nullptr) {
  801. VD = VD->getCanonicalDecl();
  802. D = VD;
  803. } else {
  804. assert(FD);
  805. FD = FD->getCanonicalDecl();
  806. D = FD;
  807. }
  808. return D;
  809. }
  810. static ValueDecl *getCanonicalDecl(ValueDecl *D) {
  811. return const_cast<ValueDecl *>(
  812. getCanonicalDecl(const_cast<const ValueDecl *>(D)));
  813. }
  814. DSAStackTy::DSAVarData DSAStackTy::getDSA(const_iterator &Iter,
  815. ValueDecl *D) const {
  816. D = getCanonicalDecl(D);
  817. auto *VD = dyn_cast<VarDecl>(D);
  818. const auto *FD = dyn_cast<FieldDecl>(D);
  819. DSAVarData DVar;
  820. if (Iter == end()) {
  821. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  822. // in a region but not in construct]
  823. // File-scope or namespace-scope variables referenced in called routines
  824. // in the region are shared unless they appear in a threadprivate
  825. // directive.
  826. if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(VD))
  827. DVar.CKind = OMPC_shared;
  828. // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
  829. // in a region but not in construct]
  830. // Variables with static storage duration that are declared in called
  831. // routines in the region are shared.
  832. if (VD && VD->hasGlobalStorage())
  833. DVar.CKind = OMPC_shared;
  834. // Non-static data members are shared by default.
  835. if (FD)
  836. DVar.CKind = OMPC_shared;
  837. return DVar;
  838. }
  839. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  840. // in a Construct, C/C++, predetermined, p.1]
  841. // Variables with automatic storage duration that are declared in a scope
  842. // inside the construct are private.
  843. if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() &&
  844. (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) {
  845. DVar.CKind = OMPC_private;
  846. return DVar;
  847. }
  848. DVar.DKind = Iter->Directive;
  849. // Explicitly specified attributes and local variables with predetermined
  850. // attributes.
  851. if (Iter->SharingMap.count(D)) {
  852. const DSAInfo &Data = Iter->SharingMap.lookup(D);
  853. DVar.RefExpr = Data.RefExpr.getPointer();
  854. DVar.PrivateCopy = Data.PrivateCopy;
  855. DVar.CKind = Data.Attributes;
  856. DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
  857. return DVar;
  858. }
  859. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  860. // in a Construct, C/C++, implicitly determined, p.1]
  861. // In a parallel or task construct, the data-sharing attributes of these
  862. // variables are determined by the default clause, if present.
  863. switch (Iter->DefaultAttr) {
  864. case DSA_shared:
  865. DVar.CKind = OMPC_shared;
  866. DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
  867. return DVar;
  868. case DSA_none:
  869. return DVar;
  870. case DSA_unspecified:
  871. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  872. // in a Construct, implicitly determined, p.2]
  873. // In a parallel construct, if no default clause is present, these
  874. // variables are shared.
  875. DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
  876. if (isOpenMPParallelDirective(DVar.DKind) ||
  877. isOpenMPTeamsDirective(DVar.DKind)) {
  878. DVar.CKind = OMPC_shared;
  879. return DVar;
  880. }
  881. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  882. // in a Construct, implicitly determined, p.4]
  883. // In a task construct, if no default clause is present, a variable that in
  884. // the enclosing context is determined to be shared by all implicit tasks
  885. // bound to the current team is shared.
  886. if (isOpenMPTaskingDirective(DVar.DKind)) {
  887. DSAVarData DVarTemp;
  888. const_iterator I = Iter, E = end();
  889. do {
  890. ++I;
  891. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
  892. // Referenced in a Construct, implicitly determined, p.6]
  893. // In a task construct, if no default clause is present, a variable
  894. // whose data-sharing attribute is not determined by the rules above is
  895. // firstprivate.
  896. DVarTemp = getDSA(I, D);
  897. if (DVarTemp.CKind != OMPC_shared) {
  898. DVar.RefExpr = nullptr;
  899. DVar.CKind = OMPC_firstprivate;
  900. return DVar;
  901. }
  902. } while (I != E && !isImplicitTaskingRegion(I->Directive));
  903. DVar.CKind =
  904. (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
  905. return DVar;
  906. }
  907. }
  908. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  909. // in a Construct, implicitly determined, p.3]
  910. // For constructs other than task, if no default clause is present, these
  911. // variables inherit their data-sharing attributes from the enclosing
  912. // context.
  913. return getDSA(++Iter, D);
  914. }
  915. const Expr *DSAStackTy::addUniqueAligned(const ValueDecl *D,
  916. const Expr *NewDE) {
  917. assert(!isStackEmpty() && "Data sharing attributes stack is empty");
  918. D = getCanonicalDecl(D);
  919. SharingMapTy &StackElem = getTopOfStack();
  920. auto It = StackElem.AlignedMap.find(D);
  921. if (It == StackElem.AlignedMap.end()) {
  922. assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
  923. StackElem.AlignedMap[D] = NewDE;
  924. return nullptr;
  925. }
  926. assert(It->second && "Unexpected nullptr expr in the aligned map");
  927. return It->second;
  928. }
  929. void DSAStackTy::addLoopControlVariable(const ValueDecl *D, VarDecl *Capture) {
  930. assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
  931. D = getCanonicalDecl(D);
  932. SharingMapTy &StackElem = getTopOfStack();
  933. StackElem.LCVMap.try_emplace(
  934. D, LCDeclInfo(StackElem.LCVMap.size() + 1, Capture));
  935. }
  936. const DSAStackTy::LCDeclInfo
  937. DSAStackTy::isLoopControlVariable(const ValueDecl *D) const {
  938. assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
  939. D = getCanonicalDecl(D);
  940. const SharingMapTy &StackElem = getTopOfStack();
  941. auto It = StackElem.LCVMap.find(D);
  942. if (It != StackElem.LCVMap.end())
  943. return It->second;
  944. return {0, nullptr};
  945. }
  946. const DSAStackTy::LCDeclInfo
  947. DSAStackTy::isParentLoopControlVariable(const ValueDecl *D) const {
  948. const SharingMapTy *Parent = getSecondOnStackOrNull();
  949. assert(Parent && "Data-sharing attributes stack is empty");
  950. D = getCanonicalDecl(D);
  951. auto It = Parent->LCVMap.find(D);
  952. if (It != Parent->LCVMap.end())
  953. return It->second;
  954. return {0, nullptr};
  955. }
  956. const ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) const {
  957. const SharingMapTy *Parent = getSecondOnStackOrNull();
  958. assert(Parent && "Data-sharing attributes stack is empty");
  959. if (Parent->LCVMap.size() < I)
  960. return nullptr;
  961. for (const auto &Pair : Parent->LCVMap)
  962. if (Pair.second.first == I)
  963. return Pair.first;
  964. return nullptr;
  965. }
  966. void DSAStackTy::addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A,
  967. DeclRefExpr *PrivateCopy) {
  968. D = getCanonicalDecl(D);
  969. if (A == OMPC_threadprivate) {
  970. DSAInfo &Data = Threadprivates[D];
  971. Data.Attributes = A;
  972. Data.RefExpr.setPointer(E);
  973. Data.PrivateCopy = nullptr;
  974. } else {
  975. DSAInfo &Data = getTopOfStack().SharingMap[D];
  976. assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) ||
  977. (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) ||
  978. (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) ||
  979. (isLoopControlVariable(D).first && A == OMPC_private));
  980. if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) {
  981. Data.RefExpr.setInt(/*IntVal=*/true);
  982. return;
  983. }
  984. const bool IsLastprivate =
  985. A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate;
  986. Data.Attributes = A;
  987. Data.RefExpr.setPointerAndInt(E, IsLastprivate);
  988. Data.PrivateCopy = PrivateCopy;
  989. if (PrivateCopy) {
  990. DSAInfo &Data = getTopOfStack().SharingMap[PrivateCopy->getDecl()];
  991. Data.Attributes = A;
  992. Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate);
  993. Data.PrivateCopy = nullptr;
  994. }
  995. }
  996. }
  997. /// Build a variable declaration for OpenMP loop iteration variable.
  998. static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
  999. StringRef Name, const AttrVec *Attrs = nullptr,
  1000. DeclRefExpr *OrigRef = nullptr) {
  1001. DeclContext *DC = SemaRef.CurContext;
  1002. IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
  1003. TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
  1004. auto *Decl =
  1005. VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
  1006. if (Attrs) {
  1007. for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end());
  1008. I != E; ++I)
  1009. Decl->addAttr(*I);
  1010. }
  1011. Decl->setImplicit();
  1012. if (OrigRef) {
  1013. Decl->addAttr(
  1014. OMPReferencedVarAttr::CreateImplicit(SemaRef.Context, OrigRef));
  1015. }
  1016. return Decl;
  1017. }
  1018. static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
  1019. SourceLocation Loc,
  1020. bool RefersToCapture = false) {
  1021. D->setReferenced();
  1022. D->markUsed(S.Context);
  1023. return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
  1024. SourceLocation(), D, RefersToCapture, Loc, Ty,
  1025. VK_LValue);
  1026. }
  1027. void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
  1028. BinaryOperatorKind BOK) {
  1029. D = getCanonicalDecl(D);
  1030. assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
  1031. assert(
  1032. getTopOfStack().SharingMap[D].Attributes == OMPC_reduction &&
  1033. "Additional reduction info may be specified only for reduction items.");
  1034. ReductionData &ReductionData = getTopOfStack().ReductionMap[D];
  1035. assert(ReductionData.ReductionRange.isInvalid() &&
  1036. getTopOfStack().Directive == OMPD_taskgroup &&
  1037. "Additional reduction info may be specified only once for reduction "
  1038. "items.");
  1039. ReductionData.set(BOK, SR);
  1040. Expr *&TaskgroupReductionRef =
  1041. getTopOfStack().TaskgroupReductionRef;
  1042. if (!TaskgroupReductionRef) {
  1043. VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(),
  1044. SemaRef.Context.VoidPtrTy, ".task_red.");
  1045. TaskgroupReductionRef =
  1046. buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
  1047. }
  1048. }
  1049. void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
  1050. const Expr *ReductionRef) {
  1051. D = getCanonicalDecl(D);
  1052. assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
  1053. assert(
  1054. getTopOfStack().SharingMap[D].Attributes == OMPC_reduction &&
  1055. "Additional reduction info may be specified only for reduction items.");
  1056. ReductionData &ReductionData = getTopOfStack().ReductionMap[D];
  1057. assert(ReductionData.ReductionRange.isInvalid() &&
  1058. getTopOfStack().Directive == OMPD_taskgroup &&
  1059. "Additional reduction info may be specified only once for reduction "
  1060. "items.");
  1061. ReductionData.set(ReductionRef, SR);
  1062. Expr *&TaskgroupReductionRef =
  1063. getTopOfStack().TaskgroupReductionRef;
  1064. if (!TaskgroupReductionRef) {
  1065. VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(),
  1066. SemaRef.Context.VoidPtrTy, ".task_red.");
  1067. TaskgroupReductionRef =
  1068. buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
  1069. }
  1070. }
  1071. const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData(
  1072. const ValueDecl *D, SourceRange &SR, BinaryOperatorKind &BOK,
  1073. Expr *&TaskgroupDescriptor) const {
  1074. D = getCanonicalDecl(D);
  1075. assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
  1076. for (const_iterator I = begin() + 1, E = end(); I != E; ++I) {
  1077. const DSAInfo &Data = I->SharingMap.lookup(D);
  1078. if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
  1079. continue;
  1080. const ReductionData &ReductionData = I->ReductionMap.lookup(D);
  1081. if (!ReductionData.ReductionOp ||
  1082. ReductionData.ReductionOp.is<const Expr *>())
  1083. return DSAVarData();
  1084. SR = ReductionData.ReductionRange;
  1085. BOK = ReductionData.ReductionOp.get<ReductionData::BOKPtrType>();
  1086. assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
  1087. "expression for the descriptor is not "
  1088. "set.");
  1089. TaskgroupDescriptor = I->TaskgroupReductionRef;
  1090. return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
  1091. Data.PrivateCopy, I->DefaultAttrLoc);
  1092. }
  1093. return DSAVarData();
  1094. }
  1095. const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData(
  1096. const ValueDecl *D, SourceRange &SR, const Expr *&ReductionRef,
  1097. Expr *&TaskgroupDescriptor) const {
  1098. D = getCanonicalDecl(D);
  1099. assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
  1100. for (const_iterator I = begin() + 1, E = end(); I != E; ++I) {
  1101. const DSAInfo &Data = I->SharingMap.lookup(D);
  1102. if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
  1103. continue;
  1104. const ReductionData &ReductionData = I->ReductionMap.lookup(D);
  1105. if (!ReductionData.ReductionOp ||
  1106. !ReductionData.ReductionOp.is<const Expr *>())
  1107. return DSAVarData();
  1108. SR = ReductionData.ReductionRange;
  1109. ReductionRef = ReductionData.ReductionOp.get<const Expr *>();
  1110. assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
  1111. "expression for the descriptor is not "
  1112. "set.");
  1113. TaskgroupDescriptor = I->TaskgroupReductionRef;
  1114. return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
  1115. Data.PrivateCopy, I->DefaultAttrLoc);
  1116. }
  1117. return DSAVarData();
  1118. }
  1119. bool DSAStackTy::isOpenMPLocal(VarDecl *D, const_iterator I) const {
  1120. D = D->getCanonicalDecl();
  1121. for (const_iterator E = end(); I != E; ++I) {
  1122. if (isImplicitOrExplicitTaskingRegion(I->Directive) ||
  1123. isOpenMPTargetExecutionDirective(I->Directive)) {
  1124. Scope *TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
  1125. Scope *CurScope = getCurScope();
  1126. while (CurScope && CurScope != TopScope && !CurScope->isDeclScope(D))
  1127. CurScope = CurScope->getParent();
  1128. return CurScope != TopScope;
  1129. }
  1130. }
  1131. return false;
  1132. }
  1133. static bool isConstNotMutableType(Sema &SemaRef, QualType Type,
  1134. bool AcceptIfMutable = true,
  1135. bool *IsClassType = nullptr) {
  1136. ASTContext &Context = SemaRef.getASTContext();
  1137. Type = Type.getNonReferenceType().getCanonicalType();
  1138. bool IsConstant = Type.isConstant(Context);
  1139. Type = Context.getBaseElementType(Type);
  1140. const CXXRecordDecl *RD = AcceptIfMutable && SemaRef.getLangOpts().CPlusPlus
  1141. ? Type->getAsCXXRecordDecl()
  1142. : nullptr;
  1143. if (const auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD))
  1144. if (const ClassTemplateDecl *CTD = CTSD->getSpecializedTemplate())
  1145. RD = CTD->getTemplatedDecl();
  1146. if (IsClassType)
  1147. *IsClassType = RD;
  1148. return IsConstant && !(SemaRef.getLangOpts().CPlusPlus && RD &&
  1149. RD->hasDefinition() && RD->hasMutableFields());
  1150. }
  1151. static bool rejectConstNotMutableType(Sema &SemaRef, const ValueDecl *D,
  1152. QualType Type, OpenMPClauseKind CKind,
  1153. SourceLocation ELoc,
  1154. bool AcceptIfMutable = true,
  1155. bool ListItemNotVar = false) {
  1156. ASTContext &Context = SemaRef.getASTContext();
  1157. bool IsClassType;
  1158. if (isConstNotMutableType(SemaRef, Type, AcceptIfMutable, &IsClassType)) {
  1159. unsigned Diag = ListItemNotVar
  1160. ? diag::err_omp_const_list_item
  1161. : IsClassType ? diag::err_omp_const_not_mutable_variable
  1162. : diag::err_omp_const_variable;
  1163. SemaRef.Diag(ELoc, Diag) << getOpenMPClauseName(CKind);
  1164. if (!ListItemNotVar && D) {
  1165. const VarDecl *VD = dyn_cast<VarDecl>(D);
  1166. bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
  1167. VarDecl::DeclarationOnly;
  1168. SemaRef.Diag(D->getLocation(),
  1169. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  1170. << D;
  1171. }
  1172. return true;
  1173. }
  1174. return false;
  1175. }
  1176. const DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D,
  1177. bool FromParent) {
  1178. D = getCanonicalDecl(D);
  1179. DSAVarData DVar;
  1180. auto *VD = dyn_cast<VarDecl>(D);
  1181. auto TI = Threadprivates.find(D);
  1182. if (TI != Threadprivates.end()) {
  1183. DVar.RefExpr = TI->getSecond().RefExpr.getPointer();
  1184. DVar.CKind = OMPC_threadprivate;
  1185. return DVar;
  1186. }
  1187. if (VD && VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
  1188. DVar.RefExpr = buildDeclRefExpr(
  1189. SemaRef, VD, D->getType().getNonReferenceType(),
  1190. VD->getAttr<OMPThreadPrivateDeclAttr>()->getLocation());
  1191. DVar.CKind = OMPC_threadprivate;
  1192. addDSA(D, DVar.RefExpr, OMPC_threadprivate);
  1193. return DVar;
  1194. }
  1195. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  1196. // in a Construct, C/C++, predetermined, p.1]
  1197. // Variables appearing in threadprivate directives are threadprivate.
  1198. if ((VD && VD->getTLSKind() != VarDecl::TLS_None &&
  1199. !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
  1200. SemaRef.getLangOpts().OpenMPUseTLS &&
  1201. SemaRef.getASTContext().getTargetInfo().isTLSSupported())) ||
  1202. (VD && VD->getStorageClass() == SC_Register &&
  1203. VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) {
  1204. DVar.RefExpr = buildDeclRefExpr(
  1205. SemaRef, VD, D->getType().getNonReferenceType(), D->getLocation());
  1206. DVar.CKind = OMPC_threadprivate;
  1207. addDSA(D, DVar.RefExpr, OMPC_threadprivate);
  1208. return DVar;
  1209. }
  1210. if (SemaRef.getLangOpts().OpenMPCUDAMode && VD &&
  1211. VD->isLocalVarDeclOrParm() && !isStackEmpty() &&
  1212. !isLoopControlVariable(D).first) {
  1213. const_iterator IterTarget =
  1214. std::find_if(begin(), end(), [](const SharingMapTy &Data) {
  1215. return isOpenMPTargetExecutionDirective(Data.Directive);
  1216. });
  1217. if (IterTarget != end()) {
  1218. const_iterator ParentIterTarget = IterTarget + 1;
  1219. for (const_iterator Iter = begin();
  1220. Iter != ParentIterTarget; ++Iter) {
  1221. if (isOpenMPLocal(VD, Iter)) {
  1222. DVar.RefExpr =
  1223. buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
  1224. D->getLocation());
  1225. DVar.CKind = OMPC_threadprivate;
  1226. return DVar;
  1227. }
  1228. }
  1229. if (!isClauseParsingMode() || IterTarget != begin()) {
  1230. auto DSAIter = IterTarget->SharingMap.find(D);
  1231. if (DSAIter != IterTarget->SharingMap.end() &&
  1232. isOpenMPPrivate(DSAIter->getSecond().Attributes)) {
  1233. DVar.RefExpr = DSAIter->getSecond().RefExpr.getPointer();
  1234. DVar.CKind = OMPC_threadprivate;
  1235. return DVar;
  1236. }
  1237. const_iterator End = end();
  1238. if (!SemaRef.isOpenMPCapturedByRef(
  1239. D, std::distance(ParentIterTarget, End))) {
  1240. DVar.RefExpr =
  1241. buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
  1242. IterTarget->ConstructLoc);
  1243. DVar.CKind = OMPC_threadprivate;
  1244. return DVar;
  1245. }
  1246. }
  1247. }
  1248. }
  1249. if (isStackEmpty())
  1250. // Not in OpenMP execution region and top scope was already checked.
  1251. return DVar;
  1252. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  1253. // in a Construct, C/C++, predetermined, p.4]
  1254. // Static data members are shared.
  1255. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  1256. // in a Construct, C/C++, predetermined, p.7]
  1257. // Variables with static storage duration that are declared in a scope
  1258. // inside the construct are shared.
  1259. if (VD && VD->isStaticDataMember()) {
  1260. // Check for explicitly specified attributes.
  1261. const_iterator I = begin();
  1262. const_iterator EndI = end();
  1263. if (FromParent && I != EndI)
  1264. ++I;
  1265. auto It = I->SharingMap.find(D);
  1266. if (It != I->SharingMap.end()) {
  1267. const DSAInfo &Data = It->getSecond();
  1268. DVar.RefExpr = Data.RefExpr.getPointer();
  1269. DVar.PrivateCopy = Data.PrivateCopy;
  1270. DVar.CKind = Data.Attributes;
  1271. DVar.ImplicitDSALoc = I->DefaultAttrLoc;
  1272. DVar.DKind = I->Directive;
  1273. return DVar;
  1274. }
  1275. DVar.CKind = OMPC_shared;
  1276. return DVar;
  1277. }
  1278. auto &&MatchesAlways = [](OpenMPDirectiveKind) { return true; };
  1279. // The predetermined shared attribute for const-qualified types having no
  1280. // mutable members was removed after OpenMP 3.1.
  1281. if (SemaRef.LangOpts.OpenMP <= 31) {
  1282. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  1283. // in a Construct, C/C++, predetermined, p.6]
  1284. // Variables with const qualified type having no mutable member are
  1285. // shared.
  1286. if (isConstNotMutableType(SemaRef, D->getType())) {
  1287. // Variables with const-qualified type having no mutable member may be
  1288. // listed in a firstprivate clause, even if they are static data members.
  1289. DSAVarData DVarTemp = hasInnermostDSA(
  1290. D,
  1291. [](OpenMPClauseKind C) {
  1292. return C == OMPC_firstprivate || C == OMPC_shared;
  1293. },
  1294. MatchesAlways, FromParent);
  1295. if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
  1296. return DVarTemp;
  1297. DVar.CKind = OMPC_shared;
  1298. return DVar;
  1299. }
  1300. }
  1301. // Explicitly specified attributes and local variables with predetermined
  1302. // attributes.
  1303. const_iterator I = begin();
  1304. const_iterator EndI = end();
  1305. if (FromParent && I != EndI)
  1306. ++I;
  1307. auto It = I->SharingMap.find(D);
  1308. if (It != I->SharingMap.end()) {
  1309. const DSAInfo &Data = It->getSecond();
  1310. DVar.RefExpr = Data.RefExpr.getPointer();
  1311. DVar.PrivateCopy = Data.PrivateCopy;
  1312. DVar.CKind = Data.Attributes;
  1313. DVar.ImplicitDSALoc = I->DefaultAttrLoc;
  1314. DVar.DKind = I->Directive;
  1315. }
  1316. return DVar;
  1317. }
  1318. const DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
  1319. bool FromParent) const {
  1320. if (isStackEmpty()) {
  1321. const_iterator I;
  1322. return getDSA(I, D);
  1323. }
  1324. D = getCanonicalDecl(D);
  1325. const_iterator StartI = begin();
  1326. const_iterator EndI = end();
  1327. if (FromParent && StartI != EndI)
  1328. ++StartI;
  1329. return getDSA(StartI, D);
  1330. }
  1331. const DSAStackTy::DSAVarData
  1332. DSAStackTy::hasDSA(ValueDecl *D,
  1333. const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
  1334. const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
  1335. bool FromParent) const {
  1336. if (isStackEmpty())
  1337. return {};
  1338. D = getCanonicalDecl(D);
  1339. const_iterator I = begin();
  1340. const_iterator EndI = end();
  1341. if (FromParent && I != EndI)
  1342. ++I;
  1343. for (; I != EndI; ++I) {
  1344. if (!DPred(I->Directive) &&
  1345. !isImplicitOrExplicitTaskingRegion(I->Directive))
  1346. continue;
  1347. const_iterator NewI = I;
  1348. DSAVarData DVar = getDSA(NewI, D);
  1349. if (I == NewI && CPred(DVar.CKind))
  1350. return DVar;
  1351. }
  1352. return {};
  1353. }
  1354. const DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA(
  1355. ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
  1356. const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
  1357. bool FromParent) const {
  1358. if (isStackEmpty())
  1359. return {};
  1360. D = getCanonicalDecl(D);
  1361. const_iterator StartI = begin();
  1362. const_iterator EndI = end();
  1363. if (FromParent && StartI != EndI)
  1364. ++StartI;
  1365. if (StartI == EndI || !DPred(StartI->Directive))
  1366. return {};
  1367. const_iterator NewI = StartI;
  1368. DSAVarData DVar = getDSA(NewI, D);
  1369. return (NewI == StartI && CPred(DVar.CKind)) ? DVar : DSAVarData();
  1370. }
  1371. bool DSAStackTy::hasExplicitDSA(
  1372. const ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
  1373. unsigned Level, bool NotLastprivate) const {
  1374. if (getStackSize() <= Level)
  1375. return false;
  1376. D = getCanonicalDecl(D);
  1377. const SharingMapTy &StackElem = getStackElemAtLevel(Level);
  1378. auto I = StackElem.SharingMap.find(D);
  1379. if (I != StackElem.SharingMap.end() &&
  1380. I->getSecond().RefExpr.getPointer() &&
  1381. CPred(I->getSecond().Attributes) &&
  1382. (!NotLastprivate || !I->getSecond().RefExpr.getInt()))
  1383. return true;
  1384. // Check predetermined rules for the loop control variables.
  1385. auto LI = StackElem.LCVMap.find(D);
  1386. if (LI != StackElem.LCVMap.end())
  1387. return CPred(OMPC_private);
  1388. return false;
  1389. }
  1390. bool DSAStackTy::hasExplicitDirective(
  1391. const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
  1392. unsigned Level) const {
  1393. if (getStackSize() <= Level)
  1394. return false;
  1395. const SharingMapTy &StackElem = getStackElemAtLevel(Level);
  1396. return DPred(StackElem.Directive);
  1397. }
  1398. bool DSAStackTy::hasDirective(
  1399. const llvm::function_ref<bool(OpenMPDirectiveKind,
  1400. const DeclarationNameInfo &, SourceLocation)>
  1401. DPred,
  1402. bool FromParent) const {
  1403. // We look only in the enclosing region.
  1404. size_t Skip = FromParent ? 2 : 1;
  1405. for (const_iterator I = begin() + std::min(Skip, getStackSize()), E = end();
  1406. I != E; ++I) {
  1407. if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
  1408. return true;
  1409. }
  1410. return false;
  1411. }
  1412. void Sema::InitDataSharingAttributesStack() {
  1413. VarDataSharingAttributesStack = new DSAStackTy(*this);
  1414. }
  1415. #define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
  1416. void Sema::pushOpenMPFunctionRegion() {
  1417. DSAStack->pushFunction();
  1418. }
  1419. void Sema::popOpenMPFunctionRegion(const FunctionScopeInfo *OldFSI) {
  1420. DSAStack->popFunction(OldFSI);
  1421. }
  1422. static bool isOpenMPDeviceDelayedContext(Sema &S) {
  1423. assert(S.LangOpts.OpenMP && S.LangOpts.OpenMPIsDevice &&
  1424. "Expected OpenMP device compilation.");
  1425. return !S.isInOpenMPTargetExecutionDirective() &&
  1426. !S.isInOpenMPDeclareTargetContext();
  1427. }
  1428. /// Do we know that we will eventually codegen the given function?
  1429. static bool isKnownEmitted(Sema &S, FunctionDecl *FD) {
  1430. assert(S.LangOpts.OpenMP && S.LangOpts.OpenMPIsDevice &&
  1431. "Expected OpenMP device compilation.");
  1432. // Templates are emitted when they're instantiated.
  1433. if (FD->isDependentContext())
  1434. return false;
  1435. if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(
  1436. FD->getCanonicalDecl()))
  1437. return true;
  1438. // Otherwise, the function is known-emitted if it's in our set of
  1439. // known-emitted functions.
  1440. return S.DeviceKnownEmittedFns.count(FD) > 0;
  1441. }
  1442. Sema::DeviceDiagBuilder Sema::diagIfOpenMPDeviceCode(SourceLocation Loc,
  1443. unsigned DiagID) {
  1444. assert(LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
  1445. "Expected OpenMP device compilation.");
  1446. return DeviceDiagBuilder((isOpenMPDeviceDelayedContext(*this) &&
  1447. !isKnownEmitted(*this, getCurFunctionDecl()))
  1448. ? DeviceDiagBuilder::K_Deferred
  1449. : DeviceDiagBuilder::K_Immediate,
  1450. Loc, DiagID, getCurFunctionDecl(), *this);
  1451. }
  1452. void Sema::checkOpenMPDeviceFunction(SourceLocation Loc, FunctionDecl *Callee) {
  1453. assert(LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
  1454. "Expected OpenMP device compilation.");
  1455. assert(Callee && "Callee may not be null.");
  1456. FunctionDecl *Caller = getCurFunctionDecl();
  1457. // If the caller is known-emitted, mark the callee as known-emitted.
  1458. // Otherwise, mark the call in our call graph so we can traverse it later.
  1459. if (!isOpenMPDeviceDelayedContext(*this) ||
  1460. (Caller && isKnownEmitted(*this, Caller)))
  1461. markKnownEmitted(*this, Caller, Callee, Loc, isKnownEmitted);
  1462. else if (Caller)
  1463. DeviceCallGraph[Caller].insert({Callee, Loc});
  1464. }
  1465. void Sema::checkOpenMPDeviceExpr(const Expr *E) {
  1466. assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
  1467. "OpenMP device compilation mode is expected.");
  1468. QualType Ty = E->getType();
  1469. if ((Ty->isFloat16Type() && !Context.getTargetInfo().hasFloat16Type()) ||
  1470. ((Ty->isFloat128Type() ||
  1471. (Ty->isRealFloatingType() && Context.getTypeSize(Ty) == 128)) &&
  1472. !Context.getTargetInfo().hasFloat128Type()) ||
  1473. (Ty->isIntegerType() && Context.getTypeSize(Ty) == 128 &&
  1474. !Context.getTargetInfo().hasInt128Type()))
  1475. targetDiag(E->getExprLoc(), diag::err_type_unsupported)
  1476. << Ty << E->getSourceRange();
  1477. }
  1478. bool Sema::isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level) const {
  1479. assert(LangOpts.OpenMP && "OpenMP is not allowed");
  1480. ASTContext &Ctx = getASTContext();
  1481. bool IsByRef = true;
  1482. // Find the directive that is associated with the provided scope.
  1483. D = cast<ValueDecl>(D->getCanonicalDecl());
  1484. QualType Ty = D->getType();
  1485. if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) {
  1486. // This table summarizes how a given variable should be passed to the device
  1487. // given its type and the clauses where it appears. This table is based on
  1488. // the description in OpenMP 4.5 [2.10.4, target Construct] and
  1489. // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses].
  1490. //
  1491. // =========================================================================
  1492. // | type | defaultmap | pvt | first | is_device_ptr | map | res. |
  1493. // | |(tofrom:scalar)| | pvt | | | |
  1494. // =========================================================================
  1495. // | scl | | | | - | | bycopy|
  1496. // | scl | | - | x | - | - | bycopy|
  1497. // | scl | | x | - | - | - | null |
  1498. // | scl | x | | | - | | byref |
  1499. // | scl | x | - | x | - | - | bycopy|
  1500. // | scl | x | x | - | - | - | null |
  1501. // | scl | | - | - | - | x | byref |
  1502. // | scl | x | - | - | - | x | byref |
  1503. //
  1504. // | agg | n.a. | | | - | | byref |
  1505. // | agg | n.a. | - | x | - | - | byref |
  1506. // | agg | n.a. | x | - | - | - | null |
  1507. // | agg | n.a. | - | - | - | x | byref |
  1508. // | agg | n.a. | - | - | - | x[] | byref |
  1509. //
  1510. // | ptr | n.a. | | | - | | bycopy|
  1511. // | ptr | n.a. | - | x | - | - | bycopy|
  1512. // | ptr | n.a. | x | - | - | - | null |
  1513. // | ptr | n.a. | - | - | - | x | byref |
  1514. // | ptr | n.a. | - | - | - | x[] | bycopy|
  1515. // | ptr | n.a. | - | - | x | | bycopy|
  1516. // | ptr | n.a. | - | - | x | x | bycopy|
  1517. // | ptr | n.a. | - | - | x | x[] | bycopy|
  1518. // =========================================================================
  1519. // Legend:
  1520. // scl - scalar
  1521. // ptr - pointer
  1522. // agg - aggregate
  1523. // x - applies
  1524. // - - invalid in this combination
  1525. // [] - mapped with an array section
  1526. // byref - should be mapped by reference
  1527. // byval - should be mapped by value
  1528. // null - initialize a local variable to null on the device
  1529. //
  1530. // Observations:
  1531. // - All scalar declarations that show up in a map clause have to be passed
  1532. // by reference, because they may have been mapped in the enclosing data
  1533. // environment.
  1534. // - If the scalar value does not fit the size of uintptr, it has to be
  1535. // passed by reference, regardless the result in the table above.
  1536. // - For pointers mapped by value that have either an implicit map or an
  1537. // array section, the runtime library may pass the NULL value to the
  1538. // device instead of the value passed to it by the compiler.
  1539. if (Ty->isReferenceType())
  1540. Ty = Ty->castAs<ReferenceType>()->getPointeeType();
  1541. // Locate map clauses and see if the variable being captured is referred to
  1542. // in any of those clauses. Here we only care about variables, not fields,
  1543. // because fields are part of aggregates.
  1544. bool IsVariableUsedInMapClause = false;
  1545. bool IsVariableAssociatedWithSection = false;
  1546. DSAStack->checkMappableExprComponentListsForDeclAtLevel(
  1547. D, Level,
  1548. [&IsVariableUsedInMapClause, &IsVariableAssociatedWithSection, D](
  1549. OMPClauseMappableExprCommon::MappableExprComponentListRef
  1550. MapExprComponents,
  1551. OpenMPClauseKind WhereFoundClauseKind) {
  1552. // Only the map clause information influences how a variable is
  1553. // captured. E.g. is_device_ptr does not require changing the default
  1554. // behavior.
  1555. if (WhereFoundClauseKind != OMPC_map)
  1556. return false;
  1557. auto EI = MapExprComponents.rbegin();
  1558. auto EE = MapExprComponents.rend();
  1559. assert(EI != EE && "Invalid map expression!");
  1560. if (isa<DeclRefExpr>(EI->getAssociatedExpression()))
  1561. IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D;
  1562. ++EI;
  1563. if (EI == EE)
  1564. return false;
  1565. if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) ||
  1566. isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) ||
  1567. isa<MemberExpr>(EI->getAssociatedExpression())) {
  1568. IsVariableAssociatedWithSection = true;
  1569. // There is nothing more we need to know about this variable.
  1570. return true;
  1571. }
  1572. // Keep looking for more map info.
  1573. return false;
  1574. });
  1575. if (IsVariableUsedInMapClause) {
  1576. // If variable is identified in a map clause it is always captured by
  1577. // reference except if it is a pointer that is dereferenced somehow.
  1578. IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection);
  1579. } else {
  1580. // By default, all the data that has a scalar type is mapped by copy
  1581. // (except for reduction variables).
  1582. IsByRef =
  1583. (DSAStack->isForceCaptureByReferenceInTargetExecutable() &&
  1584. !Ty->isAnyPointerType()) ||
  1585. !Ty->isScalarType() ||
  1586. DSAStack->getDefaultDMAAtLevel(Level) == DMA_tofrom_scalar ||
  1587. DSAStack->hasExplicitDSA(
  1588. D, [](OpenMPClauseKind K) { return K == OMPC_reduction; }, Level);
  1589. }
  1590. }
  1591. if (IsByRef && Ty.getNonReferenceType()->isScalarType()) {
  1592. IsByRef =
  1593. ((DSAStack->isForceCaptureByReferenceInTargetExecutable() &&
  1594. !Ty->isAnyPointerType()) ||
  1595. !DSAStack->hasExplicitDSA(
  1596. D,
  1597. [](OpenMPClauseKind K) -> bool { return K == OMPC_firstprivate; },
  1598. Level, /*NotLastprivate=*/true)) &&
  1599. // If the variable is artificial and must be captured by value - try to
  1600. // capture by value.
  1601. !(isa<OMPCapturedExprDecl>(D) && !D->hasAttr<OMPCaptureNoInitAttr>() &&
  1602. !cast<OMPCapturedExprDecl>(D)->getInit()->isGLValue());
  1603. }
  1604. // When passing data by copy, we need to make sure it fits the uintptr size
  1605. // and alignment, because the runtime library only deals with uintptr types.
  1606. // If it does not fit the uintptr size, we need to pass the data by reference
  1607. // instead.
  1608. if (!IsByRef &&
  1609. (Ctx.getTypeSizeInChars(Ty) >
  1610. Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) ||
  1611. Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) {
  1612. IsByRef = true;
  1613. }
  1614. return IsByRef;
  1615. }
  1616. unsigned Sema::getOpenMPNestingLevel() const {
  1617. assert(getLangOpts().OpenMP);
  1618. return DSAStack->getNestingLevel();
  1619. }
  1620. bool Sema::isInOpenMPTargetExecutionDirective() const {
  1621. return (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) &&
  1622. !DSAStack->isClauseParsingMode()) ||
  1623. DSAStack->hasDirective(
  1624. [](OpenMPDirectiveKind K, const DeclarationNameInfo &,
  1625. SourceLocation) -> bool {
  1626. return isOpenMPTargetExecutionDirective(K);
  1627. },
  1628. false);
  1629. }
  1630. VarDecl *Sema::isOpenMPCapturedDecl(ValueDecl *D, bool CheckScopeInfo,
  1631. unsigned StopAt) {
  1632. assert(LangOpts.OpenMP && "OpenMP is not allowed");
  1633. D = getCanonicalDecl(D);
  1634. // If we want to determine whether the variable should be captured from the
  1635. // perspective of the current capturing scope, and we've already left all the
  1636. // capturing scopes of the top directive on the stack, check from the
  1637. // perspective of its parent directive (if any) instead.
  1638. DSAStackTy::ParentDirectiveScope InParentDirectiveRAII(
  1639. *DSAStack, CheckScopeInfo && DSAStack->isBodyComplete());
  1640. // If we are attempting to capture a global variable in a directive with
  1641. // 'target' we return true so that this global is also mapped to the device.
  1642. //
  1643. auto *VD = dyn_cast<VarDecl>(D);
  1644. if (VD && !VD->hasLocalStorage() &&
  1645. (getCurCapturedRegion() || getCurBlock() || getCurLambda())) {
  1646. if (isInOpenMPDeclareTargetContext()) {
  1647. // Try to mark variable as declare target if it is used in capturing
  1648. // regions.
  1649. if (!OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
  1650. checkDeclIsAllowedInOpenMPTarget(nullptr, VD);
  1651. return nullptr;
  1652. } else if (isInOpenMPTargetExecutionDirective()) {
  1653. // If the declaration is enclosed in a 'declare target' directive,
  1654. // then it should not be captured.
  1655. //
  1656. if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
  1657. return nullptr;
  1658. return VD;
  1659. }
  1660. }
  1661. // Capture variables captured by reference in lambdas for target-based
  1662. // directives.
  1663. // FIXME: Triggering capture from here is completely inappropriate.
  1664. if (VD && !DSAStack->isClauseParsingMode()) {
  1665. if (const auto *RD = VD->getType()
  1666. .getCanonicalType()
  1667. .getNonReferenceType()
  1668. ->getAsCXXRecordDecl()) {
  1669. bool SavedForceCaptureByReferenceInTargetExecutable =
  1670. DSAStack->isForceCaptureByReferenceInTargetExecutable();
  1671. DSAStack->setForceCaptureByReferenceInTargetExecutable(/*V=*/true);
  1672. InParentDirectiveRAII.disable();
  1673. if (RD->isLambda()) {
  1674. llvm::DenseMap<const VarDecl *, FieldDecl *> Captures;
  1675. FieldDecl *ThisCapture;
  1676. RD->getCaptureFields(Captures, ThisCapture);
  1677. for (const LambdaCapture &LC : RD->captures()) {
  1678. if (LC.getCaptureKind() == LCK_ByRef) {
  1679. VarDecl *VD = LC.getCapturedVar();
  1680. DeclContext *VDC = VD->getDeclContext();
  1681. if (!VDC->Encloses(CurContext))
  1682. continue;
  1683. DSAStackTy::DSAVarData DVarPrivate =
  1684. DSAStack->getTopDSA(VD, /*FromParent=*/false);
  1685. // Do not capture already captured variables.
  1686. if (!OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD) &&
  1687. DVarPrivate.CKind == OMPC_unknown &&
  1688. !DSAStack->checkMappableExprComponentListsForDecl(
  1689. D, /*CurrentRegionOnly=*/true,
  1690. [](OMPClauseMappableExprCommon::
  1691. MappableExprComponentListRef,
  1692. OpenMPClauseKind) { return true; }))
  1693. MarkVariableReferenced(LC.getLocation(), LC.getCapturedVar());
  1694. } else if (LC.getCaptureKind() == LCK_This) {
  1695. QualType ThisTy = getCurrentThisType();
  1696. if (!ThisTy.isNull() &&
  1697. Context.typesAreCompatible(ThisTy, ThisCapture->getType()))
  1698. CheckCXXThisCapture(LC.getLocation());
  1699. }
  1700. }
  1701. }
  1702. if (CheckScopeInfo && DSAStack->isBodyComplete())
  1703. InParentDirectiveRAII.enable();
  1704. DSAStack->setForceCaptureByReferenceInTargetExecutable(
  1705. SavedForceCaptureByReferenceInTargetExecutable);
  1706. }
  1707. }
  1708. if (CheckScopeInfo) {
  1709. bool OpenMPFound = false;
  1710. for (unsigned I = StopAt + 1; I > 0; --I) {
  1711. FunctionScopeInfo *FSI = FunctionScopes[I - 1];
  1712. if(!isa<CapturingScopeInfo>(FSI))
  1713. return nullptr;
  1714. if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(FSI))
  1715. if (RSI->CapRegionKind == CR_OpenMP) {
  1716. OpenMPFound = true;
  1717. break;
  1718. }
  1719. }
  1720. if (!OpenMPFound)
  1721. return nullptr;
  1722. }
  1723. if (DSAStack->getCurrentDirective() != OMPD_unknown &&
  1724. (!DSAStack->isClauseParsingMode() ||
  1725. DSAStack->getParentDirective() != OMPD_unknown)) {
  1726. auto &&Info = DSAStack->isLoopControlVariable(D);
  1727. if (Info.first ||
  1728. (VD && VD->hasLocalStorage() &&
  1729. isImplicitOrExplicitTaskingRegion(DSAStack->getCurrentDirective())) ||
  1730. (VD && DSAStack->isForceVarCapturing()))
  1731. return VD ? VD : Info.second;
  1732. DSAStackTy::DSAVarData DVarPrivate =
  1733. DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
  1734. if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
  1735. return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
  1736. // Threadprivate variables must not be captured.
  1737. if (isOpenMPThreadPrivate(DVarPrivate.CKind))
  1738. return nullptr;
  1739. // The variable is not private or it is the variable in the directive with
  1740. // default(none) clause and not used in any clause.
  1741. DVarPrivate = DSAStack->hasDSA(D, isOpenMPPrivate,
  1742. [](OpenMPDirectiveKind) { return true; },
  1743. DSAStack->isClauseParsingMode());
  1744. if (DVarPrivate.CKind != OMPC_unknown ||
  1745. (VD && DSAStack->getDefaultDSA() == DSA_none))
  1746. return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
  1747. }
  1748. return nullptr;
  1749. }
  1750. void Sema::adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex,
  1751. unsigned Level) const {
  1752. SmallVector<OpenMPDirectiveKind, 4> Regions;
  1753. getOpenMPCaptureRegions(Regions, DSAStack->getDirective(Level));
  1754. FunctionScopesIndex -= Regions.size();
  1755. }
  1756. void Sema::startOpenMPLoop() {
  1757. assert(LangOpts.OpenMP && "OpenMP must be enabled.");
  1758. if (isOpenMPLoopDirective(DSAStack->getCurrentDirective()))
  1759. DSAStack->loopInit();
  1760. }
  1761. bool Sema::isOpenMPPrivateDecl(const ValueDecl *D, unsigned Level) const {
  1762. assert(LangOpts.OpenMP && "OpenMP is not allowed");
  1763. if (isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
  1764. if (DSAStack->getAssociatedLoops() > 0 &&
  1765. !DSAStack->isLoopStarted()) {
  1766. DSAStack->resetPossibleLoopCounter(D);
  1767. DSAStack->loopStart();
  1768. return true;
  1769. }
  1770. if ((DSAStack->getPossiblyLoopCunter() == D->getCanonicalDecl() ||
  1771. DSAStack->isLoopControlVariable(D).first) &&
  1772. !DSAStack->hasExplicitDSA(
  1773. D, [](OpenMPClauseKind K) { return K != OMPC_private; }, Level) &&
  1774. !isOpenMPSimdDirective(DSAStack->getCurrentDirective()))
  1775. return true;
  1776. }
  1777. return DSAStack->hasExplicitDSA(
  1778. D, [](OpenMPClauseKind K) { return K == OMPC_private; }, Level) ||
  1779. (DSAStack->isClauseParsingMode() &&
  1780. DSAStack->getClauseParsingMode() == OMPC_private) ||
  1781. // Consider taskgroup reduction descriptor variable a private to avoid
  1782. // possible capture in the region.
  1783. (DSAStack->hasExplicitDirective(
  1784. [](OpenMPDirectiveKind K) { return K == OMPD_taskgroup; },
  1785. Level) &&
  1786. DSAStack->isTaskgroupReductionRef(D, Level));
  1787. }
  1788. void Sema::setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D,
  1789. unsigned Level) {
  1790. assert(LangOpts.OpenMP && "OpenMP is not allowed");
  1791. D = getCanonicalDecl(D);
  1792. OpenMPClauseKind OMPC = OMPC_unknown;
  1793. for (unsigned I = DSAStack->getNestingLevel() + 1; I > Level; --I) {
  1794. const unsigned NewLevel = I - 1;
  1795. if (DSAStack->hasExplicitDSA(D,
  1796. [&OMPC](const OpenMPClauseKind K) {
  1797. if (isOpenMPPrivate(K)) {
  1798. OMPC = K;
  1799. return true;
  1800. }
  1801. return false;
  1802. },
  1803. NewLevel))
  1804. break;
  1805. if (DSAStack->checkMappableExprComponentListsForDeclAtLevel(
  1806. D, NewLevel,
  1807. [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
  1808. OpenMPClauseKind) { return true; })) {
  1809. OMPC = OMPC_map;
  1810. break;
  1811. }
  1812. if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
  1813. NewLevel)) {
  1814. OMPC = OMPC_map;
  1815. if (D->getType()->isScalarType() &&
  1816. DSAStack->getDefaultDMAAtLevel(NewLevel) !=
  1817. DefaultMapAttributes::DMA_tofrom_scalar)
  1818. OMPC = OMPC_firstprivate;
  1819. break;
  1820. }
  1821. }
  1822. if (OMPC != OMPC_unknown)
  1823. FD->addAttr(OMPCaptureKindAttr::CreateImplicit(Context, OMPC));
  1824. }
  1825. bool Sema::isOpenMPTargetCapturedDecl(const ValueDecl *D,
  1826. unsigned Level) const {
  1827. assert(LangOpts.OpenMP && "OpenMP is not allowed");
  1828. // Return true if the current level is no longer enclosed in a target region.
  1829. const auto *VD = dyn_cast<VarDecl>(D);
  1830. return VD && !VD->hasLocalStorage() &&
  1831. DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
  1832. Level);
  1833. }
  1834. void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
  1835. void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
  1836. const DeclarationNameInfo &DirName,
  1837. Scope *CurScope, SourceLocation Loc) {
  1838. DSAStack->push(DKind, DirName, CurScope, Loc);
  1839. PushExpressionEvaluationContext(
  1840. ExpressionEvaluationContext::PotentiallyEvaluated);
  1841. }
  1842. void Sema::StartOpenMPClause(OpenMPClauseKind K) {
  1843. DSAStack->setClauseParsingMode(K);
  1844. }
  1845. void Sema::EndOpenMPClause() {
  1846. DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
  1847. }
  1848. static void checkAllocateClauses(Sema &S, DSAStackTy *Stack,
  1849. ArrayRef<OMPClause *> Clauses);
  1850. void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
  1851. // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
  1852. // A variable of class type (or array thereof) that appears in a lastprivate
  1853. // clause requires an accessible, unambiguous default constructor for the
  1854. // class type, unless the list item is also specified in a firstprivate
  1855. // clause.
  1856. if (const auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
  1857. for (OMPClause *C : D->clauses()) {
  1858. if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
  1859. SmallVector<Expr *, 8> PrivateCopies;
  1860. for (Expr *DE : Clause->varlists()) {
  1861. if (DE->isValueDependent() || DE->isTypeDependent()) {
  1862. PrivateCopies.push_back(nullptr);
  1863. continue;
  1864. }
  1865. auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens());
  1866. auto *VD = cast<VarDecl>(DRE->getDecl());
  1867. QualType Type = VD->getType().getNonReferenceType();
  1868. const DSAStackTy::DSAVarData DVar =
  1869. DSAStack->getTopDSA(VD, /*FromParent=*/false);
  1870. if (DVar.CKind == OMPC_lastprivate) {
  1871. // Generate helper private variable and initialize it with the
  1872. // default value. The address of the original variable is replaced
  1873. // by the address of the new private variable in CodeGen. This new
  1874. // variable is not added to IdResolver, so the code in the OpenMP
  1875. // region uses original variable for proper diagnostics.
  1876. VarDecl *VDPrivate = buildVarDecl(
  1877. *this, DE->getExprLoc(), Type.getUnqualifiedType(),
  1878. VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr, DRE);
  1879. ActOnUninitializedDecl(VDPrivate);
  1880. if (VDPrivate->isInvalidDecl()) {
  1881. PrivateCopies.push_back(nullptr);
  1882. continue;
  1883. }
  1884. PrivateCopies.push_back(buildDeclRefExpr(
  1885. *this, VDPrivate, DE->getType(), DE->getExprLoc()));
  1886. } else {
  1887. // The variable is also a firstprivate, so initialization sequence
  1888. // for private copy is generated already.
  1889. PrivateCopies.push_back(nullptr);
  1890. }
  1891. }
  1892. Clause->setPrivateCopies(PrivateCopies);
  1893. }
  1894. }
  1895. // Check allocate clauses.
  1896. if (!CurContext->isDependentContext())
  1897. checkAllocateClauses(*this, DSAStack, D->clauses());
  1898. }
  1899. DSAStack->pop();
  1900. DiscardCleanupsInEvaluationContext();
  1901. PopExpressionEvaluationContext();
  1902. }
  1903. static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
  1904. Expr *NumIterations, Sema &SemaRef,
  1905. Scope *S, DSAStackTy *Stack);
  1906. namespace {
  1907. class VarDeclFilterCCC final : public CorrectionCandidateCallback {
  1908. private:
  1909. Sema &SemaRef;
  1910. public:
  1911. explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
  1912. bool ValidateCandidate(const TypoCorrection &Candidate) override {
  1913. NamedDecl *ND = Candidate.getCorrectionDecl();
  1914. if (const auto *VD = dyn_cast_or_null<VarDecl>(ND)) {
  1915. return VD->hasGlobalStorage() &&
  1916. SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
  1917. SemaRef.getCurScope());
  1918. }
  1919. return false;
  1920. }
  1921. std::unique_ptr<CorrectionCandidateCallback> clone() override {
  1922. return llvm::make_unique<VarDeclFilterCCC>(*this);
  1923. }
  1924. };
  1925. class VarOrFuncDeclFilterCCC final : public CorrectionCandidateCallback {
  1926. private:
  1927. Sema &SemaRef;
  1928. public:
  1929. explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {}
  1930. bool ValidateCandidate(const TypoCorrection &Candidate) override {
  1931. NamedDecl *ND = Candidate.getCorrectionDecl();
  1932. if (ND && ((isa<VarDecl>(ND) && ND->getKind() == Decl::Var) ||
  1933. isa<FunctionDecl>(ND))) {
  1934. return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
  1935. SemaRef.getCurScope());
  1936. }
  1937. return false;
  1938. }
  1939. std::unique_ptr<CorrectionCandidateCallback> clone() override {
  1940. return llvm::make_unique<VarOrFuncDeclFilterCCC>(*this);
  1941. }
  1942. };
  1943. } // namespace
  1944. ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
  1945. CXXScopeSpec &ScopeSpec,
  1946. const DeclarationNameInfo &Id,
  1947. OpenMPDirectiveKind Kind) {
  1948. LookupResult Lookup(*this, Id, LookupOrdinaryName);
  1949. LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
  1950. if (Lookup.isAmbiguous())
  1951. return ExprError();
  1952. VarDecl *VD;
  1953. if (!Lookup.isSingleResult()) {
  1954. VarDeclFilterCCC CCC(*this);
  1955. if (TypoCorrection Corrected =
  1956. CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, CCC,
  1957. CTK_ErrorRecovery)) {
  1958. diagnoseTypo(Corrected,
  1959. PDiag(Lookup.empty()
  1960. ? diag::err_undeclared_var_use_suggest
  1961. : diag::err_omp_expected_var_arg_suggest)
  1962. << Id.getName());
  1963. VD = Corrected.getCorrectionDeclAs<VarDecl>();
  1964. } else {
  1965. Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
  1966. : diag::err_omp_expected_var_arg)
  1967. << Id.getName();
  1968. return ExprError();
  1969. }
  1970. } else if (!(VD = Lookup.getAsSingle<VarDecl>())) {
  1971. Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
  1972. Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
  1973. return ExprError();
  1974. }
  1975. Lookup.suppressDiagnostics();
  1976. // OpenMP [2.9.2, Syntax, C/C++]
  1977. // Variables must be file-scope, namespace-scope, or static block-scope.
  1978. if (Kind == OMPD_threadprivate && !VD->hasGlobalStorage()) {
  1979. Diag(Id.getLoc(), diag::err_omp_global_var_arg)
  1980. << getOpenMPDirectiveName(Kind) << !VD->isStaticLocal();
  1981. bool IsDecl =
  1982. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  1983. Diag(VD->getLocation(),
  1984. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  1985. << VD;
  1986. return ExprError();
  1987. }
  1988. VarDecl *CanonicalVD = VD->getCanonicalDecl();
  1989. NamedDecl *ND = CanonicalVD;
  1990. // OpenMP [2.9.2, Restrictions, C/C++, p.2]
  1991. // A threadprivate directive for file-scope variables must appear outside
  1992. // any definition or declaration.
  1993. if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
  1994. !getCurLexicalContext()->isTranslationUnit()) {
  1995. Diag(Id.getLoc(), diag::err_omp_var_scope)
  1996. << getOpenMPDirectiveName(Kind) << VD;
  1997. bool IsDecl =
  1998. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  1999. Diag(VD->getLocation(),
  2000. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  2001. << VD;
  2002. return ExprError();
  2003. }
  2004. // OpenMP [2.9.2, Restrictions, C/C++, p.3]
  2005. // A threadprivate directive for static class member variables must appear
  2006. // in the class definition, in the same scope in which the member
  2007. // variables are declared.
  2008. if (CanonicalVD->isStaticDataMember() &&
  2009. !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
  2010. Diag(Id.getLoc(), diag::err_omp_var_scope)
  2011. << getOpenMPDirectiveName(Kind) << VD;
  2012. bool IsDecl =
  2013. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  2014. Diag(VD->getLocation(),
  2015. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  2016. << VD;
  2017. return ExprError();
  2018. }
  2019. // OpenMP [2.9.2, Restrictions, C/C++, p.4]
  2020. // A threadprivate directive for namespace-scope variables must appear
  2021. // outside any definition or declaration other than the namespace
  2022. // definition itself.
  2023. if (CanonicalVD->getDeclContext()->isNamespace() &&
  2024. (!getCurLexicalContext()->isFileContext() ||
  2025. !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
  2026. Diag(Id.getLoc(), diag::err_omp_var_scope)
  2027. << getOpenMPDirectiveName(Kind) << VD;
  2028. bool IsDecl =
  2029. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  2030. Diag(VD->getLocation(),
  2031. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  2032. << VD;
  2033. return ExprError();
  2034. }
  2035. // OpenMP [2.9.2, Restrictions, C/C++, p.6]
  2036. // A threadprivate directive for static block-scope variables must appear
  2037. // in the scope of the variable and not in a nested scope.
  2038. if (CanonicalVD->isLocalVarDecl() && CurScope &&
  2039. !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
  2040. Diag(Id.getLoc(), diag::err_omp_var_scope)
  2041. << getOpenMPDirectiveName(Kind) << VD;
  2042. bool IsDecl =
  2043. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  2044. Diag(VD->getLocation(),
  2045. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  2046. << VD;
  2047. return ExprError();
  2048. }
  2049. // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
  2050. // A threadprivate directive must lexically precede all references to any
  2051. // of the variables in its list.
  2052. if (Kind == OMPD_threadprivate && VD->isUsed() &&
  2053. !DSAStack->isThreadPrivate(VD)) {
  2054. Diag(Id.getLoc(), diag::err_omp_var_used)
  2055. << getOpenMPDirectiveName(Kind) << VD;
  2056. return ExprError();
  2057. }
  2058. QualType ExprType = VD->getType().getNonReferenceType();
  2059. return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
  2060. SourceLocation(), VD,
  2061. /*RefersToEnclosingVariableOrCapture=*/false,
  2062. Id.getLoc(), ExprType, VK_LValue);
  2063. }
  2064. Sema::DeclGroupPtrTy
  2065. Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
  2066. ArrayRef<Expr *> VarList) {
  2067. if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
  2068. CurContext->addDecl(D);
  2069. return DeclGroupPtrTy::make(DeclGroupRef(D));
  2070. }
  2071. return nullptr;
  2072. }
  2073. namespace {
  2074. class LocalVarRefChecker final
  2075. : public ConstStmtVisitor<LocalVarRefChecker, bool> {
  2076. Sema &SemaRef;
  2077. public:
  2078. bool VisitDeclRefExpr(const DeclRefExpr *E) {
  2079. if (const auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
  2080. if (VD->hasLocalStorage()) {
  2081. SemaRef.Diag(E->getBeginLoc(),
  2082. diag::err_omp_local_var_in_threadprivate_init)
  2083. << E->getSourceRange();
  2084. SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
  2085. << VD << VD->getSourceRange();
  2086. return true;
  2087. }
  2088. }
  2089. return false;
  2090. }
  2091. bool VisitStmt(const Stmt *S) {
  2092. for (const Stmt *Child : S->children()) {
  2093. if (Child && Visit(Child))
  2094. return true;
  2095. }
  2096. return false;
  2097. }
  2098. explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
  2099. };
  2100. } // namespace
  2101. OMPThreadPrivateDecl *
  2102. Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
  2103. SmallVector<Expr *, 8> Vars;
  2104. for (Expr *RefExpr : VarList) {
  2105. auto *DE = cast<DeclRefExpr>(RefExpr);
  2106. auto *VD = cast<VarDecl>(DE->getDecl());
  2107. SourceLocation ILoc = DE->getExprLoc();
  2108. // Mark variable as used.
  2109. VD->setReferenced();
  2110. VD->markUsed(Context);
  2111. QualType QType = VD->getType();
  2112. if (QType->isDependentType() || QType->isInstantiationDependentType()) {
  2113. // It will be analyzed later.
  2114. Vars.push_back(DE);
  2115. continue;
  2116. }
  2117. // OpenMP [2.9.2, Restrictions, C/C++, p.10]
  2118. // A threadprivate variable must not have an incomplete type.
  2119. if (RequireCompleteType(ILoc, VD->getType(),
  2120. diag::err_omp_threadprivate_incomplete_type)) {
  2121. continue;
  2122. }
  2123. // OpenMP [2.9.2, Restrictions, C/C++, p.10]
  2124. // A threadprivate variable must not have a reference type.
  2125. if (VD->getType()->isReferenceType()) {
  2126. Diag(ILoc, diag::err_omp_ref_type_arg)
  2127. << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
  2128. bool IsDecl =
  2129. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  2130. Diag(VD->getLocation(),
  2131. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  2132. << VD;
  2133. continue;
  2134. }
  2135. // Check if this is a TLS variable. If TLS is not being supported, produce
  2136. // the corresponding diagnostic.
  2137. if ((VD->getTLSKind() != VarDecl::TLS_None &&
  2138. !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
  2139. getLangOpts().OpenMPUseTLS &&
  2140. getASTContext().getTargetInfo().isTLSSupported())) ||
  2141. (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
  2142. !VD->isLocalVarDecl())) {
  2143. Diag(ILoc, diag::err_omp_var_thread_local)
  2144. << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
  2145. bool IsDecl =
  2146. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  2147. Diag(VD->getLocation(),
  2148. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  2149. << VD;
  2150. continue;
  2151. }
  2152. // Check if initial value of threadprivate variable reference variable with
  2153. // local storage (it is not supported by runtime).
  2154. if (const Expr *Init = VD->getAnyInitializer()) {
  2155. LocalVarRefChecker Checker(*this);
  2156. if (Checker.Visit(Init))
  2157. continue;
  2158. }
  2159. Vars.push_back(RefExpr);
  2160. DSAStack->addDSA(VD, DE, OMPC_threadprivate);
  2161. VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
  2162. Context, SourceRange(Loc, Loc)));
  2163. if (ASTMutationListener *ML = Context.getASTMutationListener())
  2164. ML->DeclarationMarkedOpenMPThreadPrivate(VD);
  2165. }
  2166. OMPThreadPrivateDecl *D = nullptr;
  2167. if (!Vars.empty()) {
  2168. D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
  2169. Vars);
  2170. D->setAccess(AS_public);
  2171. }
  2172. return D;
  2173. }
  2174. static OMPAllocateDeclAttr::AllocatorTypeTy
  2175. getAllocatorKind(Sema &S, DSAStackTy *Stack, Expr *Allocator) {
  2176. if (!Allocator)
  2177. return OMPAllocateDeclAttr::OMPDefaultMemAlloc;
  2178. if (Allocator->isTypeDependent() || Allocator->isValueDependent() ||
  2179. Allocator->isInstantiationDependent() ||
  2180. Allocator->containsUnexpandedParameterPack())
  2181. return OMPAllocateDeclAttr::OMPUserDefinedMemAlloc;
  2182. auto AllocatorKindRes = OMPAllocateDeclAttr::OMPUserDefinedMemAlloc;
  2183. const Expr *AE = Allocator->IgnoreParenImpCasts();
  2184. for (int I = OMPAllocateDeclAttr::OMPDefaultMemAlloc;
  2185. I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) {
  2186. auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I);
  2187. const Expr *DefAllocator = Stack->getAllocator(AllocatorKind);
  2188. llvm::FoldingSetNodeID AEId, DAEId;
  2189. AE->Profile(AEId, S.getASTContext(), /*Canonical=*/true);
  2190. DefAllocator->Profile(DAEId, S.getASTContext(), /*Canonical=*/true);
  2191. if (AEId == DAEId) {
  2192. AllocatorKindRes = AllocatorKind;
  2193. break;
  2194. }
  2195. }
  2196. return AllocatorKindRes;
  2197. }
  2198. static bool checkPreviousOMPAllocateAttribute(
  2199. Sema &S, DSAStackTy *Stack, Expr *RefExpr, VarDecl *VD,
  2200. OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind, Expr *Allocator) {
  2201. if (!VD->hasAttr<OMPAllocateDeclAttr>())
  2202. return false;
  2203. const auto *A = VD->getAttr<OMPAllocateDeclAttr>();
  2204. Expr *PrevAllocator = A->getAllocator();
  2205. OMPAllocateDeclAttr::AllocatorTypeTy PrevAllocatorKind =
  2206. getAllocatorKind(S, Stack, PrevAllocator);
  2207. bool AllocatorsMatch = AllocatorKind == PrevAllocatorKind;
  2208. if (AllocatorsMatch &&
  2209. AllocatorKind == OMPAllocateDeclAttr::OMPUserDefinedMemAlloc &&
  2210. Allocator && PrevAllocator) {
  2211. const Expr *AE = Allocator->IgnoreParenImpCasts();
  2212. const Expr *PAE = PrevAllocator->IgnoreParenImpCasts();
  2213. llvm::FoldingSetNodeID AEId, PAEId;
  2214. AE->Profile(AEId, S.Context, /*Canonical=*/true);
  2215. PAE->Profile(PAEId, S.Context, /*Canonical=*/true);
  2216. AllocatorsMatch = AEId == PAEId;
  2217. }
  2218. if (!AllocatorsMatch) {
  2219. SmallString<256> AllocatorBuffer;
  2220. llvm::raw_svector_ostream AllocatorStream(AllocatorBuffer);
  2221. if (Allocator)
  2222. Allocator->printPretty(AllocatorStream, nullptr, S.getPrintingPolicy());
  2223. SmallString<256> PrevAllocatorBuffer;
  2224. llvm::raw_svector_ostream PrevAllocatorStream(PrevAllocatorBuffer);
  2225. if (PrevAllocator)
  2226. PrevAllocator->printPretty(PrevAllocatorStream, nullptr,
  2227. S.getPrintingPolicy());
  2228. SourceLocation AllocatorLoc =
  2229. Allocator ? Allocator->getExprLoc() : RefExpr->getExprLoc();
  2230. SourceRange AllocatorRange =
  2231. Allocator ? Allocator->getSourceRange() : RefExpr->getSourceRange();
  2232. SourceLocation PrevAllocatorLoc =
  2233. PrevAllocator ? PrevAllocator->getExprLoc() : A->getLocation();
  2234. SourceRange PrevAllocatorRange =
  2235. PrevAllocator ? PrevAllocator->getSourceRange() : A->getRange();
  2236. S.Diag(AllocatorLoc, diag::warn_omp_used_different_allocator)
  2237. << (Allocator ? 1 : 0) << AllocatorStream.str()
  2238. << (PrevAllocator ? 1 : 0) << PrevAllocatorStream.str()
  2239. << AllocatorRange;
  2240. S.Diag(PrevAllocatorLoc, diag::note_omp_previous_allocator)
  2241. << PrevAllocatorRange;
  2242. return true;
  2243. }
  2244. return false;
  2245. }
  2246. static void
  2247. applyOMPAllocateAttribute(Sema &S, VarDecl *VD,
  2248. OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind,
  2249. Expr *Allocator, SourceRange SR) {
  2250. if (VD->hasAttr<OMPAllocateDeclAttr>())
  2251. return;
  2252. if (Allocator &&
  2253. (Allocator->isTypeDependent() || Allocator->isValueDependent() ||
  2254. Allocator->isInstantiationDependent() ||
  2255. Allocator->containsUnexpandedParameterPack()))
  2256. return;
  2257. auto *A = OMPAllocateDeclAttr::CreateImplicit(S.Context, AllocatorKind,
  2258. Allocator, SR);
  2259. VD->addAttr(A);
  2260. if (ASTMutationListener *ML = S.Context.getASTMutationListener())
  2261. ML->DeclarationMarkedOpenMPAllocate(VD, A);
  2262. }
  2263. Sema::DeclGroupPtrTy Sema::ActOnOpenMPAllocateDirective(
  2264. SourceLocation Loc, ArrayRef<Expr *> VarList,
  2265. ArrayRef<OMPClause *> Clauses, DeclContext *Owner) {
  2266. assert(Clauses.size() <= 1 && "Expected at most one clause.");
  2267. Expr *Allocator = nullptr;
  2268. if (Clauses.empty()) {
  2269. // OpenMP 5.0, 2.11.3 allocate Directive, Restrictions.
  2270. // allocate directives that appear in a target region must specify an
  2271. // allocator clause unless a requires directive with the dynamic_allocators
  2272. // clause is present in the same compilation unit.
  2273. if (LangOpts.OpenMPIsDevice &&
  2274. !DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())
  2275. targetDiag(Loc, diag::err_expected_allocator_clause);
  2276. } else {
  2277. Allocator = cast<OMPAllocatorClause>(Clauses.back())->getAllocator();
  2278. }
  2279. OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind =
  2280. getAllocatorKind(*this, DSAStack, Allocator);
  2281. SmallVector<Expr *, 8> Vars;
  2282. for (Expr *RefExpr : VarList) {
  2283. auto *DE = cast<DeclRefExpr>(RefExpr);
  2284. auto *VD = cast<VarDecl>(DE->getDecl());
  2285. // Check if this is a TLS variable or global register.
  2286. if (VD->getTLSKind() != VarDecl::TLS_None ||
  2287. VD->hasAttr<OMPThreadPrivateDeclAttr>() ||
  2288. (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
  2289. !VD->isLocalVarDecl()))
  2290. continue;
  2291. // If the used several times in the allocate directive, the same allocator
  2292. // must be used.
  2293. if (checkPreviousOMPAllocateAttribute(*this, DSAStack, RefExpr, VD,
  2294. AllocatorKind, Allocator))
  2295. continue;
  2296. // OpenMP, 2.11.3 allocate Directive, Restrictions, C / C++
  2297. // If a list item has a static storage type, the allocator expression in the
  2298. // allocator clause must be a constant expression that evaluates to one of
  2299. // the predefined memory allocator values.
  2300. if (Allocator && VD->hasGlobalStorage()) {
  2301. if (AllocatorKind == OMPAllocateDeclAttr::OMPUserDefinedMemAlloc) {
  2302. Diag(Allocator->getExprLoc(),
  2303. diag::err_omp_expected_predefined_allocator)
  2304. << Allocator->getSourceRange();
  2305. bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
  2306. VarDecl::DeclarationOnly;
  2307. Diag(VD->getLocation(),
  2308. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  2309. << VD;
  2310. continue;
  2311. }
  2312. }
  2313. Vars.push_back(RefExpr);
  2314. applyOMPAllocateAttribute(*this, VD, AllocatorKind, Allocator,
  2315. DE->getSourceRange());
  2316. }
  2317. if (Vars.empty())
  2318. return nullptr;
  2319. if (!Owner)
  2320. Owner = getCurLexicalContext();
  2321. auto *D = OMPAllocateDecl::Create(Context, Owner, Loc, Vars, Clauses);
  2322. D->setAccess(AS_public);
  2323. Owner->addDecl(D);
  2324. return DeclGroupPtrTy::make(DeclGroupRef(D));
  2325. }
  2326. Sema::DeclGroupPtrTy
  2327. Sema::ActOnOpenMPRequiresDirective(SourceLocation Loc,
  2328. ArrayRef<OMPClause *> ClauseList) {
  2329. OMPRequiresDecl *D = nullptr;
  2330. if (!CurContext->isFileContext()) {
  2331. Diag(Loc, diag::err_omp_invalid_scope) << "requires";
  2332. } else {
  2333. D = CheckOMPRequiresDecl(Loc, ClauseList);
  2334. if (D) {
  2335. CurContext->addDecl(D);
  2336. DSAStack->addRequiresDecl(D);
  2337. }
  2338. }
  2339. return DeclGroupPtrTy::make(DeclGroupRef(D));
  2340. }
  2341. OMPRequiresDecl *Sema::CheckOMPRequiresDecl(SourceLocation Loc,
  2342. ArrayRef<OMPClause *> ClauseList) {
  2343. /// For target specific clauses, the requires directive cannot be
  2344. /// specified after the handling of any of the target regions in the
  2345. /// current compilation unit.
  2346. ArrayRef<SourceLocation> TargetLocations =
  2347. DSAStack->getEncounteredTargetLocs();
  2348. if (!TargetLocations.empty()) {
  2349. for (const OMPClause *CNew : ClauseList) {
  2350. // Check if any of the requires clauses affect target regions.
  2351. if (isa<OMPUnifiedSharedMemoryClause>(CNew) ||
  2352. isa<OMPUnifiedAddressClause>(CNew) ||
  2353. isa<OMPReverseOffloadClause>(CNew) ||
  2354. isa<OMPDynamicAllocatorsClause>(CNew)) {
  2355. Diag(Loc, diag::err_omp_target_before_requires)
  2356. << getOpenMPClauseName(CNew->getClauseKind());
  2357. for (SourceLocation TargetLoc : TargetLocations) {
  2358. Diag(TargetLoc, diag::note_omp_requires_encountered_target);
  2359. }
  2360. }
  2361. }
  2362. }
  2363. if (!DSAStack->hasDuplicateRequiresClause(ClauseList))
  2364. return OMPRequiresDecl::Create(Context, getCurLexicalContext(), Loc,
  2365. ClauseList);
  2366. return nullptr;
  2367. }
  2368. static void reportOriginalDsa(Sema &SemaRef, const DSAStackTy *Stack,
  2369. const ValueDecl *D,
  2370. const DSAStackTy::DSAVarData &DVar,
  2371. bool IsLoopIterVar = false) {
  2372. if (DVar.RefExpr) {
  2373. SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
  2374. << getOpenMPClauseName(DVar.CKind);
  2375. return;
  2376. }
  2377. enum {
  2378. PDSA_StaticMemberShared,
  2379. PDSA_StaticLocalVarShared,
  2380. PDSA_LoopIterVarPrivate,
  2381. PDSA_LoopIterVarLinear,
  2382. PDSA_LoopIterVarLastprivate,
  2383. PDSA_ConstVarShared,
  2384. PDSA_GlobalVarShared,
  2385. PDSA_TaskVarFirstprivate,
  2386. PDSA_LocalVarPrivate,
  2387. PDSA_Implicit
  2388. } Reason = PDSA_Implicit;
  2389. bool ReportHint = false;
  2390. auto ReportLoc = D->getLocation();
  2391. auto *VD = dyn_cast<VarDecl>(D);
  2392. if (IsLoopIterVar) {
  2393. if (DVar.CKind == OMPC_private)
  2394. Reason = PDSA_LoopIterVarPrivate;
  2395. else if (DVar.CKind == OMPC_lastprivate)
  2396. Reason = PDSA_LoopIterVarLastprivate;
  2397. else
  2398. Reason = PDSA_LoopIterVarLinear;
  2399. } else if (isOpenMPTaskingDirective(DVar.DKind) &&
  2400. DVar.CKind == OMPC_firstprivate) {
  2401. Reason = PDSA_TaskVarFirstprivate;
  2402. ReportLoc = DVar.ImplicitDSALoc;
  2403. } else if (VD && VD->isStaticLocal())
  2404. Reason = PDSA_StaticLocalVarShared;
  2405. else if (VD && VD->isStaticDataMember())
  2406. Reason = PDSA_StaticMemberShared;
  2407. else if (VD && VD->isFileVarDecl())
  2408. Reason = PDSA_GlobalVarShared;
  2409. else if (D->getType().isConstant(SemaRef.getASTContext()))
  2410. Reason = PDSA_ConstVarShared;
  2411. else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
  2412. ReportHint = true;
  2413. Reason = PDSA_LocalVarPrivate;
  2414. }
  2415. if (Reason != PDSA_Implicit) {
  2416. SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
  2417. << Reason << ReportHint
  2418. << getOpenMPDirectiveName(Stack->getCurrentDirective());
  2419. } else if (DVar.ImplicitDSALoc.isValid()) {
  2420. SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
  2421. << getOpenMPClauseName(DVar.CKind);
  2422. }
  2423. }
  2424. namespace {
  2425. class DSAAttrChecker final : public StmtVisitor<DSAAttrChecker, void> {
  2426. DSAStackTy *Stack;
  2427. Sema &SemaRef;
  2428. bool ErrorFound = false;
  2429. CapturedStmt *CS = nullptr;
  2430. llvm::SmallVector<Expr *, 4> ImplicitFirstprivate;
  2431. llvm::SmallVector<Expr *, 4> ImplicitMap;
  2432. Sema::VarsWithInheritedDSAType VarsWithInheritedDSA;
  2433. llvm::SmallDenseSet<const ValueDecl *, 4> ImplicitDeclarations;
  2434. void VisitSubCaptures(OMPExecutableDirective *S) {
  2435. // Check implicitly captured variables.
  2436. if (!S->hasAssociatedStmt() || !S->getAssociatedStmt())
  2437. return;
  2438. for (const CapturedStmt::Capture &Cap :
  2439. S->getInnermostCapturedStmt()->captures()) {
  2440. if (!Cap.capturesVariable())
  2441. continue;
  2442. VarDecl *VD = Cap.getCapturedVar();
  2443. // Do not try to map the variable if it or its sub-component was mapped
  2444. // already.
  2445. if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) &&
  2446. Stack->checkMappableExprComponentListsForDecl(
  2447. VD, /*CurrentRegionOnly=*/true,
  2448. [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
  2449. OpenMPClauseKind) { return true; }))
  2450. continue;
  2451. DeclRefExpr *DRE = buildDeclRefExpr(
  2452. SemaRef, VD, VD->getType().getNonLValueExprType(SemaRef.Context),
  2453. Cap.getLocation(), /*RefersToCapture=*/true);
  2454. Visit(DRE);
  2455. }
  2456. }
  2457. public:
  2458. void VisitDeclRefExpr(DeclRefExpr *E) {
  2459. if (E->isTypeDependent() || E->isValueDependent() ||
  2460. E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
  2461. return;
  2462. if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
  2463. // Check the datasharing rules for the expressions in the clauses.
  2464. if (!CS) {
  2465. if (auto *CED = dyn_cast<OMPCapturedExprDecl>(VD))
  2466. if (!CED->hasAttr<OMPCaptureNoInitAttr>()) {
  2467. Visit(CED->getInit());
  2468. return;
  2469. }
  2470. }
  2471. VD = VD->getCanonicalDecl();
  2472. // Skip internally declared variables.
  2473. if (VD->hasLocalStorage() && CS && !CS->capturesVariable(VD))
  2474. return;
  2475. DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
  2476. // Check if the variable has explicit DSA set and stop analysis if it so.
  2477. if (DVar.RefExpr || !ImplicitDeclarations.insert(VD).second)
  2478. return;
  2479. // Skip internally declared static variables.
  2480. llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
  2481. OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
  2482. if (VD->hasGlobalStorage() && CS && !CS->capturesVariable(VD) &&
  2483. (Stack->hasRequiresDeclWithClause<OMPUnifiedSharedMemoryClause>() ||
  2484. !Res || *Res != OMPDeclareTargetDeclAttr::MT_Link))
  2485. return;
  2486. SourceLocation ELoc = E->getExprLoc();
  2487. OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
  2488. // The default(none) clause requires that each variable that is referenced
  2489. // in the construct, and does not have a predetermined data-sharing
  2490. // attribute, must have its data-sharing attribute explicitly determined
  2491. // by being listed in a data-sharing attribute clause.
  2492. if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
  2493. isImplicitOrExplicitTaskingRegion(DKind) &&
  2494. VarsWithInheritedDSA.count(VD) == 0) {
  2495. VarsWithInheritedDSA[VD] = E;
  2496. return;
  2497. }
  2498. if (isOpenMPTargetExecutionDirective(DKind) &&
  2499. !Stack->isLoopControlVariable(VD).first) {
  2500. if (!Stack->checkMappableExprComponentListsForDecl(
  2501. VD, /*CurrentRegionOnly=*/true,
  2502. [](OMPClauseMappableExprCommon::MappableExprComponentListRef
  2503. StackComponents,
  2504. OpenMPClauseKind) {
  2505. // Variable is used if it has been marked as an array, array
  2506. // section or the variable iself.
  2507. return StackComponents.size() == 1 ||
  2508. std::all_of(
  2509. std::next(StackComponents.rbegin()),
  2510. StackComponents.rend(),
  2511. [](const OMPClauseMappableExprCommon::
  2512. MappableComponent &MC) {
  2513. return MC.getAssociatedDeclaration() ==
  2514. nullptr &&
  2515. (isa<OMPArraySectionExpr>(
  2516. MC.getAssociatedExpression()) ||
  2517. isa<ArraySubscriptExpr>(
  2518. MC.getAssociatedExpression()));
  2519. });
  2520. })) {
  2521. bool IsFirstprivate = false;
  2522. // By default lambdas are captured as firstprivates.
  2523. if (const auto *RD =
  2524. VD->getType().getNonReferenceType()->getAsCXXRecordDecl())
  2525. IsFirstprivate = RD->isLambda();
  2526. IsFirstprivate =
  2527. IsFirstprivate ||
  2528. (VD->getType().getNonReferenceType()->isScalarType() &&
  2529. Stack->getDefaultDMA() != DMA_tofrom_scalar && !Res);
  2530. if (IsFirstprivate)
  2531. ImplicitFirstprivate.emplace_back(E);
  2532. else
  2533. ImplicitMap.emplace_back(E);
  2534. return;
  2535. }
  2536. }
  2537. // OpenMP [2.9.3.6, Restrictions, p.2]
  2538. // A list item that appears in a reduction clause of the innermost
  2539. // enclosing worksharing or parallel construct may not be accessed in an
  2540. // explicit task.
  2541. DVar = Stack->hasInnermostDSA(
  2542. VD, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
  2543. [](OpenMPDirectiveKind K) {
  2544. return isOpenMPParallelDirective(K) ||
  2545. isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
  2546. },
  2547. /*FromParent=*/true);
  2548. if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
  2549. ErrorFound = true;
  2550. SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
  2551. reportOriginalDsa(SemaRef, Stack, VD, DVar);
  2552. return;
  2553. }
  2554. // Define implicit data-sharing attributes for task.
  2555. DVar = Stack->getImplicitDSA(VD, /*FromParent=*/false);
  2556. if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
  2557. !Stack->isLoopControlVariable(VD).first) {
  2558. ImplicitFirstprivate.push_back(E);
  2559. return;
  2560. }
  2561. // Store implicitly used globals with declare target link for parent
  2562. // target.
  2563. if (!isOpenMPTargetExecutionDirective(DKind) && Res &&
  2564. *Res == OMPDeclareTargetDeclAttr::MT_Link) {
  2565. Stack->addToParentTargetRegionLinkGlobals(E);
  2566. return;
  2567. }
  2568. }
  2569. }
  2570. void VisitMemberExpr(MemberExpr *E) {
  2571. if (E->isTypeDependent() || E->isValueDependent() ||
  2572. E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
  2573. return;
  2574. auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
  2575. OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
  2576. if (auto *TE = dyn_cast<CXXThisExpr>(E->getBase()->IgnoreParens())) {
  2577. if (!FD)
  2578. return;
  2579. DSAStackTy::DSAVarData DVar = Stack->getTopDSA(FD, /*FromParent=*/false);
  2580. // Check if the variable has explicit DSA set and stop analysis if it
  2581. // so.
  2582. if (DVar.RefExpr || !ImplicitDeclarations.insert(FD).second)
  2583. return;
  2584. if (isOpenMPTargetExecutionDirective(DKind) &&
  2585. !Stack->isLoopControlVariable(FD).first &&
  2586. !Stack->checkMappableExprComponentListsForDecl(
  2587. FD, /*CurrentRegionOnly=*/true,
  2588. [](OMPClauseMappableExprCommon::MappableExprComponentListRef
  2589. StackComponents,
  2590. OpenMPClauseKind) {
  2591. return isa<CXXThisExpr>(
  2592. cast<MemberExpr>(
  2593. StackComponents.back().getAssociatedExpression())
  2594. ->getBase()
  2595. ->IgnoreParens());
  2596. })) {
  2597. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
  2598. // A bit-field cannot appear in a map clause.
  2599. //
  2600. if (FD->isBitField())
  2601. return;
  2602. // Check to see if the member expression is referencing a class that
  2603. // has already been explicitly mapped
  2604. if (Stack->isClassPreviouslyMapped(TE->getType()))
  2605. return;
  2606. ImplicitMap.emplace_back(E);
  2607. return;
  2608. }
  2609. SourceLocation ELoc = E->getExprLoc();
  2610. // OpenMP [2.9.3.6, Restrictions, p.2]
  2611. // A list item that appears in a reduction clause of the innermost
  2612. // enclosing worksharing or parallel construct may not be accessed in
  2613. // an explicit task.
  2614. DVar = Stack->hasInnermostDSA(
  2615. FD, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
  2616. [](OpenMPDirectiveKind K) {
  2617. return isOpenMPParallelDirective(K) ||
  2618. isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
  2619. },
  2620. /*FromParent=*/true);
  2621. if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
  2622. ErrorFound = true;
  2623. SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
  2624. reportOriginalDsa(SemaRef, Stack, FD, DVar);
  2625. return;
  2626. }
  2627. // Define implicit data-sharing attributes for task.
  2628. DVar = Stack->getImplicitDSA(FD, /*FromParent=*/false);
  2629. if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
  2630. !Stack->isLoopControlVariable(FD).first) {
  2631. // Check if there is a captured expression for the current field in the
  2632. // region. Do not mark it as firstprivate unless there is no captured
  2633. // expression.
  2634. // TODO: try to make it firstprivate.
  2635. if (DVar.CKind != OMPC_unknown)
  2636. ImplicitFirstprivate.push_back(E);
  2637. }
  2638. return;
  2639. }
  2640. if (isOpenMPTargetExecutionDirective(DKind)) {
  2641. OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
  2642. if (!checkMapClauseExpressionBase(SemaRef, E, CurComponents, OMPC_map,
  2643. /*NoDiagnose=*/true))
  2644. return;
  2645. const auto *VD = cast<ValueDecl>(
  2646. CurComponents.back().getAssociatedDeclaration()->getCanonicalDecl());
  2647. if (!Stack->checkMappableExprComponentListsForDecl(
  2648. VD, /*CurrentRegionOnly=*/true,
  2649. [&CurComponents](
  2650. OMPClauseMappableExprCommon::MappableExprComponentListRef
  2651. StackComponents,
  2652. OpenMPClauseKind) {
  2653. auto CCI = CurComponents.rbegin();
  2654. auto CCE = CurComponents.rend();
  2655. for (const auto &SC : llvm::reverse(StackComponents)) {
  2656. // Do both expressions have the same kind?
  2657. if (CCI->getAssociatedExpression()->getStmtClass() !=
  2658. SC.getAssociatedExpression()->getStmtClass())
  2659. if (!(isa<OMPArraySectionExpr>(
  2660. SC.getAssociatedExpression()) &&
  2661. isa<ArraySubscriptExpr>(
  2662. CCI->getAssociatedExpression())))
  2663. return false;
  2664. const Decl *CCD = CCI->getAssociatedDeclaration();
  2665. const Decl *SCD = SC.getAssociatedDeclaration();
  2666. CCD = CCD ? CCD->getCanonicalDecl() : nullptr;
  2667. SCD = SCD ? SCD->getCanonicalDecl() : nullptr;
  2668. if (SCD != CCD)
  2669. return false;
  2670. std::advance(CCI, 1);
  2671. if (CCI == CCE)
  2672. break;
  2673. }
  2674. return true;
  2675. })) {
  2676. Visit(E->getBase());
  2677. }
  2678. } else {
  2679. Visit(E->getBase());
  2680. }
  2681. }
  2682. void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
  2683. for (OMPClause *C : S->clauses()) {
  2684. // Skip analysis of arguments of implicitly defined firstprivate clause
  2685. // for task|target directives.
  2686. // Skip analysis of arguments of implicitly defined map clause for target
  2687. // directives.
  2688. if (C && !((isa<OMPFirstprivateClause>(C) || isa<OMPMapClause>(C)) &&
  2689. C->isImplicit())) {
  2690. for (Stmt *CC : C->children()) {
  2691. if (CC)
  2692. Visit(CC);
  2693. }
  2694. }
  2695. }
  2696. // Check implicitly captured variables.
  2697. VisitSubCaptures(S);
  2698. }
  2699. void VisitStmt(Stmt *S) {
  2700. for (Stmt *C : S->children()) {
  2701. if (C) {
  2702. // Check implicitly captured variables in the task-based directives to
  2703. // check if they must be firstprivatized.
  2704. Visit(C);
  2705. }
  2706. }
  2707. }
  2708. bool isErrorFound() const { return ErrorFound; }
  2709. ArrayRef<Expr *> getImplicitFirstprivate() const {
  2710. return ImplicitFirstprivate;
  2711. }
  2712. ArrayRef<Expr *> getImplicitMap() const { return ImplicitMap; }
  2713. const Sema::VarsWithInheritedDSAType &getVarsWithInheritedDSA() const {
  2714. return VarsWithInheritedDSA;
  2715. }
  2716. DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
  2717. : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {
  2718. // Process declare target link variables for the target directives.
  2719. if (isOpenMPTargetExecutionDirective(S->getCurrentDirective())) {
  2720. for (DeclRefExpr *E : Stack->getLinkGlobals())
  2721. Visit(E);
  2722. }
  2723. }
  2724. };
  2725. } // namespace
  2726. void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
  2727. switch (DKind) {
  2728. case OMPD_parallel:
  2729. case OMPD_parallel_for:
  2730. case OMPD_parallel_for_simd:
  2731. case OMPD_parallel_sections:
  2732. case OMPD_teams:
  2733. case OMPD_teams_distribute:
  2734. case OMPD_teams_distribute_simd: {
  2735. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
  2736. QualType KmpInt32PtrTy =
  2737. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  2738. Sema::CapturedParamNameType Params[] = {
  2739. std::make_pair(".global_tid.", KmpInt32PtrTy),
  2740. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  2741. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2742. };
  2743. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2744. Params);
  2745. break;
  2746. }
  2747. case OMPD_target_teams:
  2748. case OMPD_target_parallel:
  2749. case OMPD_target_parallel_for:
  2750. case OMPD_target_parallel_for_simd:
  2751. case OMPD_target_teams_distribute:
  2752. case OMPD_target_teams_distribute_simd: {
  2753. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
  2754. QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
  2755. QualType KmpInt32PtrTy =
  2756. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  2757. QualType Args[] = {VoidPtrTy};
  2758. FunctionProtoType::ExtProtoInfo EPI;
  2759. EPI.Variadic = true;
  2760. QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
  2761. Sema::CapturedParamNameType Params[] = {
  2762. std::make_pair(".global_tid.", KmpInt32Ty),
  2763. std::make_pair(".part_id.", KmpInt32PtrTy),
  2764. std::make_pair(".privates.", VoidPtrTy),
  2765. std::make_pair(
  2766. ".copy_fn.",
  2767. Context.getPointerType(CopyFnType).withConst().withRestrict()),
  2768. std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
  2769. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2770. };
  2771. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2772. Params);
  2773. // Mark this captured region as inlined, because we don't use outlined
  2774. // function directly.
  2775. getCurCapturedRegion()->TheCapturedDecl->addAttr(
  2776. AlwaysInlineAttr::CreateImplicit(
  2777. Context, AlwaysInlineAttr::Keyword_forceinline));
  2778. Sema::CapturedParamNameType ParamsTarget[] = {
  2779. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2780. };
  2781. // Start a captured region for 'target' with no implicit parameters.
  2782. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2783. ParamsTarget);
  2784. Sema::CapturedParamNameType ParamsTeamsOrParallel[] = {
  2785. std::make_pair(".global_tid.", KmpInt32PtrTy),
  2786. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  2787. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2788. };
  2789. // Start a captured region for 'teams' or 'parallel'. Both regions have
  2790. // the same implicit parameters.
  2791. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2792. ParamsTeamsOrParallel);
  2793. break;
  2794. }
  2795. case OMPD_target:
  2796. case OMPD_target_simd: {
  2797. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
  2798. QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
  2799. QualType KmpInt32PtrTy =
  2800. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  2801. QualType Args[] = {VoidPtrTy};
  2802. FunctionProtoType::ExtProtoInfo EPI;
  2803. EPI.Variadic = true;
  2804. QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
  2805. Sema::CapturedParamNameType Params[] = {
  2806. std::make_pair(".global_tid.", KmpInt32Ty),
  2807. std::make_pair(".part_id.", KmpInt32PtrTy),
  2808. std::make_pair(".privates.", VoidPtrTy),
  2809. std::make_pair(
  2810. ".copy_fn.",
  2811. Context.getPointerType(CopyFnType).withConst().withRestrict()),
  2812. std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
  2813. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2814. };
  2815. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2816. Params);
  2817. // Mark this captured region as inlined, because we don't use outlined
  2818. // function directly.
  2819. getCurCapturedRegion()->TheCapturedDecl->addAttr(
  2820. AlwaysInlineAttr::CreateImplicit(
  2821. Context, AlwaysInlineAttr::Keyword_forceinline));
  2822. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2823. std::make_pair(StringRef(), QualType()));
  2824. break;
  2825. }
  2826. case OMPD_simd:
  2827. case OMPD_for:
  2828. case OMPD_for_simd:
  2829. case OMPD_sections:
  2830. case OMPD_section:
  2831. case OMPD_single:
  2832. case OMPD_master:
  2833. case OMPD_critical:
  2834. case OMPD_taskgroup:
  2835. case OMPD_distribute:
  2836. case OMPD_distribute_simd:
  2837. case OMPD_ordered:
  2838. case OMPD_atomic:
  2839. case OMPD_target_data: {
  2840. Sema::CapturedParamNameType Params[] = {
  2841. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2842. };
  2843. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2844. Params);
  2845. break;
  2846. }
  2847. case OMPD_task: {
  2848. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
  2849. QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
  2850. QualType KmpInt32PtrTy =
  2851. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  2852. QualType Args[] = {VoidPtrTy};
  2853. FunctionProtoType::ExtProtoInfo EPI;
  2854. EPI.Variadic = true;
  2855. QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
  2856. Sema::CapturedParamNameType Params[] = {
  2857. std::make_pair(".global_tid.", KmpInt32Ty),
  2858. std::make_pair(".part_id.", KmpInt32PtrTy),
  2859. std::make_pair(".privates.", VoidPtrTy),
  2860. std::make_pair(
  2861. ".copy_fn.",
  2862. Context.getPointerType(CopyFnType).withConst().withRestrict()),
  2863. std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
  2864. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2865. };
  2866. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2867. Params);
  2868. // Mark this captured region as inlined, because we don't use outlined
  2869. // function directly.
  2870. getCurCapturedRegion()->TheCapturedDecl->addAttr(
  2871. AlwaysInlineAttr::CreateImplicit(
  2872. Context, AlwaysInlineAttr::Keyword_forceinline));
  2873. break;
  2874. }
  2875. case OMPD_taskloop:
  2876. case OMPD_taskloop_simd: {
  2877. QualType KmpInt32Ty =
  2878. Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1)
  2879. .withConst();
  2880. QualType KmpUInt64Ty =
  2881. Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0)
  2882. .withConst();
  2883. QualType KmpInt64Ty =
  2884. Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1)
  2885. .withConst();
  2886. QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
  2887. QualType KmpInt32PtrTy =
  2888. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  2889. QualType Args[] = {VoidPtrTy};
  2890. FunctionProtoType::ExtProtoInfo EPI;
  2891. EPI.Variadic = true;
  2892. QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
  2893. Sema::CapturedParamNameType Params[] = {
  2894. std::make_pair(".global_tid.", KmpInt32Ty),
  2895. std::make_pair(".part_id.", KmpInt32PtrTy),
  2896. std::make_pair(".privates.", VoidPtrTy),
  2897. std::make_pair(
  2898. ".copy_fn.",
  2899. Context.getPointerType(CopyFnType).withConst().withRestrict()),
  2900. std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
  2901. std::make_pair(".lb.", KmpUInt64Ty),
  2902. std::make_pair(".ub.", KmpUInt64Ty),
  2903. std::make_pair(".st.", KmpInt64Ty),
  2904. std::make_pair(".liter.", KmpInt32Ty),
  2905. std::make_pair(".reductions.", VoidPtrTy),
  2906. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2907. };
  2908. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2909. Params);
  2910. // Mark this captured region as inlined, because we don't use outlined
  2911. // function directly.
  2912. getCurCapturedRegion()->TheCapturedDecl->addAttr(
  2913. AlwaysInlineAttr::CreateImplicit(
  2914. Context, AlwaysInlineAttr::Keyword_forceinline));
  2915. break;
  2916. }
  2917. case OMPD_distribute_parallel_for_simd:
  2918. case OMPD_distribute_parallel_for: {
  2919. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
  2920. QualType KmpInt32PtrTy =
  2921. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  2922. Sema::CapturedParamNameType Params[] = {
  2923. std::make_pair(".global_tid.", KmpInt32PtrTy),
  2924. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  2925. std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
  2926. std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
  2927. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2928. };
  2929. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2930. Params);
  2931. break;
  2932. }
  2933. case OMPD_target_teams_distribute_parallel_for:
  2934. case OMPD_target_teams_distribute_parallel_for_simd: {
  2935. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
  2936. QualType KmpInt32PtrTy =
  2937. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  2938. QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
  2939. QualType Args[] = {VoidPtrTy};
  2940. FunctionProtoType::ExtProtoInfo EPI;
  2941. EPI.Variadic = true;
  2942. QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
  2943. Sema::CapturedParamNameType Params[] = {
  2944. std::make_pair(".global_tid.", KmpInt32Ty),
  2945. std::make_pair(".part_id.", KmpInt32PtrTy),
  2946. std::make_pair(".privates.", VoidPtrTy),
  2947. std::make_pair(
  2948. ".copy_fn.",
  2949. Context.getPointerType(CopyFnType).withConst().withRestrict()),
  2950. std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
  2951. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2952. };
  2953. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2954. Params);
  2955. // Mark this captured region as inlined, because we don't use outlined
  2956. // function directly.
  2957. getCurCapturedRegion()->TheCapturedDecl->addAttr(
  2958. AlwaysInlineAttr::CreateImplicit(
  2959. Context, AlwaysInlineAttr::Keyword_forceinline));
  2960. Sema::CapturedParamNameType ParamsTarget[] = {
  2961. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2962. };
  2963. // Start a captured region for 'target' with no implicit parameters.
  2964. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2965. ParamsTarget);
  2966. Sema::CapturedParamNameType ParamsTeams[] = {
  2967. std::make_pair(".global_tid.", KmpInt32PtrTy),
  2968. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  2969. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2970. };
  2971. // Start a captured region for 'target' with no implicit parameters.
  2972. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2973. ParamsTeams);
  2974. Sema::CapturedParamNameType ParamsParallel[] = {
  2975. std::make_pair(".global_tid.", KmpInt32PtrTy),
  2976. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  2977. std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
  2978. std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
  2979. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2980. };
  2981. // Start a captured region for 'teams' or 'parallel'. Both regions have
  2982. // the same implicit parameters.
  2983. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2984. ParamsParallel);
  2985. break;
  2986. }
  2987. case OMPD_teams_distribute_parallel_for:
  2988. case OMPD_teams_distribute_parallel_for_simd: {
  2989. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
  2990. QualType KmpInt32PtrTy =
  2991. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  2992. Sema::CapturedParamNameType ParamsTeams[] = {
  2993. std::make_pair(".global_tid.", KmpInt32PtrTy),
  2994. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  2995. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2996. };
  2997. // Start a captured region for 'target' with no implicit parameters.
  2998. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2999. ParamsTeams);
  3000. Sema::CapturedParamNameType ParamsParallel[] = {
  3001. std::make_pair(".global_tid.", KmpInt32PtrTy),
  3002. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  3003. std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
  3004. std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
  3005. std::make_pair(StringRef(), QualType()) // __context with shared vars
  3006. };
  3007. // Start a captured region for 'teams' or 'parallel'. Both regions have
  3008. // the same implicit parameters.
  3009. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  3010. ParamsParallel);
  3011. break;
  3012. }
  3013. case OMPD_target_update:
  3014. case OMPD_target_enter_data:
  3015. case OMPD_target_exit_data: {
  3016. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
  3017. QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
  3018. QualType KmpInt32PtrTy =
  3019. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  3020. QualType Args[] = {VoidPtrTy};
  3021. FunctionProtoType::ExtProtoInfo EPI;
  3022. EPI.Variadic = true;
  3023. QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
  3024. Sema::CapturedParamNameType Params[] = {
  3025. std::make_pair(".global_tid.", KmpInt32Ty),
  3026. std::make_pair(".part_id.", KmpInt32PtrTy),
  3027. std::make_pair(".privates.", VoidPtrTy),
  3028. std::make_pair(
  3029. ".copy_fn.",
  3030. Context.getPointerType(CopyFnType).withConst().withRestrict()),
  3031. std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
  3032. std::make_pair(StringRef(), QualType()) // __context with shared vars
  3033. };
  3034. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  3035. Params);
  3036. // Mark this captured region as inlined, because we don't use outlined
  3037. // function directly.
  3038. getCurCapturedRegion()->TheCapturedDecl->addAttr(
  3039. AlwaysInlineAttr::CreateImplicit(
  3040. Context, AlwaysInlineAttr::Keyword_forceinline));
  3041. break;
  3042. }
  3043. case OMPD_threadprivate:
  3044. case OMPD_allocate:
  3045. case OMPD_taskyield:
  3046. case OMPD_barrier:
  3047. case OMPD_taskwait:
  3048. case OMPD_cancellation_point:
  3049. case OMPD_cancel:
  3050. case OMPD_flush:
  3051. case OMPD_declare_reduction:
  3052. case OMPD_declare_mapper:
  3053. case OMPD_declare_simd:
  3054. case OMPD_declare_target:
  3055. case OMPD_end_declare_target:
  3056. case OMPD_requires:
  3057. llvm_unreachable("OpenMP Directive is not allowed");
  3058. case OMPD_unknown:
  3059. llvm_unreachable("Unknown OpenMP directive");
  3060. }
  3061. }
  3062. int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) {
  3063. SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
  3064. getOpenMPCaptureRegions(CaptureRegions, DKind);
  3065. return CaptureRegions.size();
  3066. }
  3067. static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
  3068. Expr *CaptureExpr, bool WithInit,
  3069. bool AsExpression) {
  3070. assert(CaptureExpr);
  3071. ASTContext &C = S.getASTContext();
  3072. Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
  3073. QualType Ty = Init->getType();
  3074. if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
  3075. if (S.getLangOpts().CPlusPlus) {
  3076. Ty = C.getLValueReferenceType(Ty);
  3077. } else {
  3078. Ty = C.getPointerType(Ty);
  3079. ExprResult Res =
  3080. S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
  3081. if (!Res.isUsable())
  3082. return nullptr;
  3083. Init = Res.get();
  3084. }
  3085. WithInit = true;
  3086. }
  3087. auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty,
  3088. CaptureExpr->getBeginLoc());
  3089. if (!WithInit)
  3090. CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C));
  3091. S.CurContext->addHiddenDecl(CED);
  3092. S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false);
  3093. return CED;
  3094. }
  3095. static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
  3096. bool WithInit) {
  3097. OMPCapturedExprDecl *CD;
  3098. if (VarDecl *VD = S.isOpenMPCapturedDecl(D))
  3099. CD = cast<OMPCapturedExprDecl>(VD);
  3100. else
  3101. CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
  3102. /*AsExpression=*/false);
  3103. return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
  3104. CaptureExpr->getExprLoc());
  3105. }
  3106. static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
  3107. CaptureExpr = S.DefaultLvalueConversion(CaptureExpr).get();
  3108. if (!Ref) {
  3109. OMPCapturedExprDecl *CD = buildCaptureDecl(
  3110. S, &S.getASTContext().Idents.get(".capture_expr."), CaptureExpr,
  3111. /*WithInit=*/true, /*AsExpression=*/true);
  3112. Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
  3113. CaptureExpr->getExprLoc());
  3114. }
  3115. ExprResult Res = Ref;
  3116. if (!S.getLangOpts().CPlusPlus &&
  3117. CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
  3118. Ref->getType()->isPointerType()) {
  3119. Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
  3120. if (!Res.isUsable())
  3121. return ExprError();
  3122. }
  3123. return S.DefaultLvalueConversion(Res.get());
  3124. }
  3125. namespace {
  3126. // OpenMP directives parsed in this section are represented as a
  3127. // CapturedStatement with an associated statement. If a syntax error
  3128. // is detected during the parsing of the associated statement, the
  3129. // compiler must abort processing and close the CapturedStatement.
  3130. //
  3131. // Combined directives such as 'target parallel' have more than one
  3132. // nested CapturedStatements. This RAII ensures that we unwind out
  3133. // of all the nested CapturedStatements when an error is found.
  3134. class CaptureRegionUnwinderRAII {
  3135. private:
  3136. Sema &S;
  3137. bool &ErrorFound;
  3138. OpenMPDirectiveKind DKind = OMPD_unknown;
  3139. public:
  3140. CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound,
  3141. OpenMPDirectiveKind DKind)
  3142. : S(S), ErrorFound(ErrorFound), DKind(DKind) {}
  3143. ~CaptureRegionUnwinderRAII() {
  3144. if (ErrorFound) {
  3145. int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind);
  3146. while (--ThisCaptureLevel >= 0)
  3147. S.ActOnCapturedRegionError();
  3148. }
  3149. }
  3150. };
  3151. } // namespace
  3152. StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
  3153. ArrayRef<OMPClause *> Clauses) {
  3154. bool ErrorFound = false;
  3155. CaptureRegionUnwinderRAII CaptureRegionUnwinder(
  3156. *this, ErrorFound, DSAStack->getCurrentDirective());
  3157. if (!S.isUsable()) {
  3158. ErrorFound = true;
  3159. return StmtError();
  3160. }
  3161. SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
  3162. getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective());
  3163. OMPOrderedClause *OC = nullptr;
  3164. OMPScheduleClause *SC = nullptr;
  3165. SmallVector<const OMPLinearClause *, 4> LCs;
  3166. SmallVector<const OMPClauseWithPreInit *, 4> PICs;
  3167. // This is required for proper codegen.
  3168. for (OMPClause *Clause : Clauses) {
  3169. if (isOpenMPTaskingDirective(DSAStack->getCurrentDirective()) &&
  3170. Clause->getClauseKind() == OMPC_in_reduction) {
  3171. // Capture taskgroup task_reduction descriptors inside the tasking regions
  3172. // with the corresponding in_reduction items.
  3173. auto *IRC = cast<OMPInReductionClause>(Clause);
  3174. for (Expr *E : IRC->taskgroup_descriptors())
  3175. if (E)
  3176. MarkDeclarationsReferencedInExpr(E);
  3177. }
  3178. if (isOpenMPPrivate(Clause->getClauseKind()) ||
  3179. Clause->getClauseKind() == OMPC_copyprivate ||
  3180. (getLangOpts().OpenMPUseTLS &&
  3181. getASTContext().getTargetInfo().isTLSSupported() &&
  3182. Clause->getClauseKind() == OMPC_copyin)) {
  3183. DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
  3184. // Mark all variables in private list clauses as used in inner region.
  3185. for (Stmt *VarRef : Clause->children()) {
  3186. if (auto *E = cast_or_null<Expr>(VarRef)) {
  3187. MarkDeclarationsReferencedInExpr(E);
  3188. }
  3189. }
  3190. DSAStack->setForceVarCapturing(/*V=*/false);
  3191. } else if (CaptureRegions.size() > 1 ||
  3192. CaptureRegions.back() != OMPD_unknown) {
  3193. if (auto *C = OMPClauseWithPreInit::get(Clause))
  3194. PICs.push_back(C);
  3195. if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
  3196. if (Expr *E = C->getPostUpdateExpr())
  3197. MarkDeclarationsReferencedInExpr(E);
  3198. }
  3199. }
  3200. if (Clause->getClauseKind() == OMPC_schedule)
  3201. SC = cast<OMPScheduleClause>(Clause);
  3202. else if (Clause->getClauseKind() == OMPC_ordered)
  3203. OC = cast<OMPOrderedClause>(Clause);
  3204. else if (Clause->getClauseKind() == OMPC_linear)
  3205. LCs.push_back(cast<OMPLinearClause>(Clause));
  3206. }
  3207. // OpenMP, 2.7.1 Loop Construct, Restrictions
  3208. // The nonmonotonic modifier cannot be specified if an ordered clause is
  3209. // specified.
  3210. if (SC &&
  3211. (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
  3212. SC->getSecondScheduleModifier() ==
  3213. OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
  3214. OC) {
  3215. Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
  3216. ? SC->getFirstScheduleModifierLoc()
  3217. : SC->getSecondScheduleModifierLoc(),
  3218. diag::err_omp_schedule_nonmonotonic_ordered)
  3219. << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
  3220. ErrorFound = true;
  3221. }
  3222. if (!LCs.empty() && OC && OC->getNumForLoops()) {
  3223. for (const OMPLinearClause *C : LCs) {
  3224. Diag(C->getBeginLoc(), diag::err_omp_linear_ordered)
  3225. << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
  3226. }
  3227. ErrorFound = true;
  3228. }
  3229. if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
  3230. isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
  3231. OC->getNumForLoops()) {
  3232. Diag(OC->getBeginLoc(), diag::err_omp_ordered_simd)
  3233. << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
  3234. ErrorFound = true;
  3235. }
  3236. if (ErrorFound) {
  3237. return StmtError();
  3238. }
  3239. StmtResult SR = S;
  3240. unsigned CompletedRegions = 0;
  3241. for (OpenMPDirectiveKind ThisCaptureRegion : llvm::reverse(CaptureRegions)) {
  3242. // Mark all variables in private list clauses as used in inner region.
  3243. // Required for proper codegen of combined directives.
  3244. // TODO: add processing for other clauses.
  3245. if (ThisCaptureRegion != OMPD_unknown) {
  3246. for (const clang::OMPClauseWithPreInit *C : PICs) {
  3247. OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion();
  3248. // Find the particular capture region for the clause if the
  3249. // directive is a combined one with multiple capture regions.
  3250. // If the directive is not a combined one, the capture region
  3251. // associated with the clause is OMPD_unknown and is generated
  3252. // only once.
  3253. if (CaptureRegion == ThisCaptureRegion ||
  3254. CaptureRegion == OMPD_unknown) {
  3255. if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
  3256. for (Decl *D : DS->decls())
  3257. MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
  3258. }
  3259. }
  3260. }
  3261. }
  3262. if (++CompletedRegions == CaptureRegions.size())
  3263. DSAStack->setBodyComplete();
  3264. SR = ActOnCapturedRegionEnd(SR.get());
  3265. }
  3266. return SR;
  3267. }
  3268. static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion,
  3269. OpenMPDirectiveKind CancelRegion,
  3270. SourceLocation StartLoc) {
  3271. // CancelRegion is only needed for cancel and cancellation_point.
  3272. if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point)
  3273. return false;
  3274. if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for ||
  3275. CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup)
  3276. return false;
  3277. SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region)
  3278. << getOpenMPDirectiveName(CancelRegion);
  3279. return true;
  3280. }
  3281. static bool checkNestingOfRegions(Sema &SemaRef, const DSAStackTy *Stack,
  3282. OpenMPDirectiveKind CurrentRegion,
  3283. const DeclarationNameInfo &CurrentName,
  3284. OpenMPDirectiveKind CancelRegion,
  3285. SourceLocation StartLoc) {
  3286. if (Stack->getCurScope()) {
  3287. OpenMPDirectiveKind ParentRegion = Stack->getParentDirective();
  3288. OpenMPDirectiveKind OffendingRegion = ParentRegion;
  3289. bool NestingProhibited = false;
  3290. bool CloseNesting = true;
  3291. bool OrphanSeen = false;
  3292. enum {
  3293. NoRecommend,
  3294. ShouldBeInParallelRegion,
  3295. ShouldBeInOrderedRegion,
  3296. ShouldBeInTargetRegion,
  3297. ShouldBeInTeamsRegion
  3298. } Recommend = NoRecommend;
  3299. if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) {
  3300. // OpenMP [2.16, Nesting of Regions]
  3301. // OpenMP constructs may not be nested inside a simd region.
  3302. // OpenMP [2.8.1,simd Construct, Restrictions]
  3303. // An ordered construct with the simd clause is the only OpenMP
  3304. // construct that can appear in the simd region.
  3305. // Allowing a SIMD construct nested in another SIMD construct is an
  3306. // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
  3307. // message.
  3308. SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
  3309. ? diag::err_omp_prohibited_region_simd
  3310. : diag::warn_omp_nesting_simd);
  3311. return CurrentRegion != OMPD_simd;
  3312. }
  3313. if (ParentRegion == OMPD_atomic) {
  3314. // OpenMP [2.16, Nesting of Regions]
  3315. // OpenMP constructs may not be nested inside an atomic region.
  3316. SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
  3317. return true;
  3318. }
  3319. if (CurrentRegion == OMPD_section) {
  3320. // OpenMP [2.7.2, sections Construct, Restrictions]
  3321. // Orphaned section directives are prohibited. That is, the section
  3322. // directives must appear within the sections construct and must not be
  3323. // encountered elsewhere in the sections region.
  3324. if (ParentRegion != OMPD_sections &&
  3325. ParentRegion != OMPD_parallel_sections) {
  3326. SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
  3327. << (ParentRegion != OMPD_unknown)
  3328. << getOpenMPDirectiveName(ParentRegion);
  3329. return true;
  3330. }
  3331. return false;
  3332. }
  3333. // Allow some constructs (except teams and cancellation constructs) to be
  3334. // orphaned (they could be used in functions, called from OpenMP regions
  3335. // with the required preconditions).
  3336. if (ParentRegion == OMPD_unknown &&
  3337. !isOpenMPNestingTeamsDirective(CurrentRegion) &&
  3338. CurrentRegion != OMPD_cancellation_point &&
  3339. CurrentRegion != OMPD_cancel)
  3340. return false;
  3341. if (CurrentRegion == OMPD_cancellation_point ||
  3342. CurrentRegion == OMPD_cancel) {
  3343. // OpenMP [2.16, Nesting of Regions]
  3344. // A cancellation point construct for which construct-type-clause is
  3345. // taskgroup must be nested inside a task construct. A cancellation
  3346. // point construct for which construct-type-clause is not taskgroup must
  3347. // be closely nested inside an OpenMP construct that matches the type
  3348. // specified in construct-type-clause.
  3349. // A cancel construct for which construct-type-clause is taskgroup must be
  3350. // nested inside a task construct. A cancel construct for which
  3351. // construct-type-clause is not taskgroup must be closely nested inside an
  3352. // OpenMP construct that matches the type specified in
  3353. // construct-type-clause.
  3354. NestingProhibited =
  3355. !((CancelRegion == OMPD_parallel &&
  3356. (ParentRegion == OMPD_parallel ||
  3357. ParentRegion == OMPD_target_parallel)) ||
  3358. (CancelRegion == OMPD_for &&
  3359. (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
  3360. ParentRegion == OMPD_target_parallel_for ||
  3361. ParentRegion == OMPD_distribute_parallel_for ||
  3362. ParentRegion == OMPD_teams_distribute_parallel_for ||
  3363. ParentRegion == OMPD_target_teams_distribute_parallel_for)) ||
  3364. (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
  3365. (CancelRegion == OMPD_sections &&
  3366. (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
  3367. ParentRegion == OMPD_parallel_sections)));
  3368. OrphanSeen = ParentRegion == OMPD_unknown;
  3369. } else if (CurrentRegion == OMPD_master) {
  3370. // OpenMP [2.16, Nesting of Regions]
  3371. // A master region may not be closely nested inside a worksharing,
  3372. // atomic, or explicit task region.
  3373. NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
  3374. isOpenMPTaskingDirective(ParentRegion);
  3375. } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
  3376. // OpenMP [2.16, Nesting of Regions]
  3377. // A critical region may not be nested (closely or otherwise) inside a
  3378. // critical region with the same name. Note that this restriction is not
  3379. // sufficient to prevent deadlock.
  3380. SourceLocation PreviousCriticalLoc;
  3381. bool DeadLock = Stack->hasDirective(
  3382. [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
  3383. const DeclarationNameInfo &DNI,
  3384. SourceLocation Loc) {
  3385. if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
  3386. PreviousCriticalLoc = Loc;
  3387. return true;
  3388. }
  3389. return false;
  3390. },
  3391. false /* skip top directive */);
  3392. if (DeadLock) {
  3393. SemaRef.Diag(StartLoc,
  3394. diag::err_omp_prohibited_region_critical_same_name)
  3395. << CurrentName.getName();
  3396. if (PreviousCriticalLoc.isValid())
  3397. SemaRef.Diag(PreviousCriticalLoc,
  3398. diag::note_omp_previous_critical_region);
  3399. return true;
  3400. }
  3401. } else if (CurrentRegion == OMPD_barrier) {
  3402. // OpenMP [2.16, Nesting of Regions]
  3403. // A barrier region may not be closely nested inside a worksharing,
  3404. // explicit task, critical, ordered, atomic, or master region.
  3405. NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
  3406. isOpenMPTaskingDirective(ParentRegion) ||
  3407. ParentRegion == OMPD_master ||
  3408. ParentRegion == OMPD_critical ||
  3409. ParentRegion == OMPD_ordered;
  3410. } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
  3411. !isOpenMPParallelDirective(CurrentRegion) &&
  3412. !isOpenMPTeamsDirective(CurrentRegion)) {
  3413. // OpenMP [2.16, Nesting of Regions]
  3414. // A worksharing region may not be closely nested inside a worksharing,
  3415. // explicit task, critical, ordered, atomic, or master region.
  3416. NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
  3417. isOpenMPTaskingDirective(ParentRegion) ||
  3418. ParentRegion == OMPD_master ||
  3419. ParentRegion == OMPD_critical ||
  3420. ParentRegion == OMPD_ordered;
  3421. Recommend = ShouldBeInParallelRegion;
  3422. } else if (CurrentRegion == OMPD_ordered) {
  3423. // OpenMP [2.16, Nesting of Regions]
  3424. // An ordered region may not be closely nested inside a critical,
  3425. // atomic, or explicit task region.
  3426. // An ordered region must be closely nested inside a loop region (or
  3427. // parallel loop region) with an ordered clause.
  3428. // OpenMP [2.8.1,simd Construct, Restrictions]
  3429. // An ordered construct with the simd clause is the only OpenMP construct
  3430. // that can appear in the simd region.
  3431. NestingProhibited = ParentRegion == OMPD_critical ||
  3432. isOpenMPTaskingDirective(ParentRegion) ||
  3433. !(isOpenMPSimdDirective(ParentRegion) ||
  3434. Stack->isParentOrderedRegion());
  3435. Recommend = ShouldBeInOrderedRegion;
  3436. } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
  3437. // OpenMP [2.16, Nesting of Regions]
  3438. // If specified, a teams construct must be contained within a target
  3439. // construct.
  3440. NestingProhibited = ParentRegion != OMPD_target;
  3441. OrphanSeen = ParentRegion == OMPD_unknown;
  3442. Recommend = ShouldBeInTargetRegion;
  3443. }
  3444. if (!NestingProhibited &&
  3445. !isOpenMPTargetExecutionDirective(CurrentRegion) &&
  3446. !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
  3447. (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
  3448. // OpenMP [2.16, Nesting of Regions]
  3449. // distribute, parallel, parallel sections, parallel workshare, and the
  3450. // parallel loop and parallel loop SIMD constructs are the only OpenMP
  3451. // constructs that can be closely nested in the teams region.
  3452. NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
  3453. !isOpenMPDistributeDirective(CurrentRegion);
  3454. Recommend = ShouldBeInParallelRegion;
  3455. }
  3456. if (!NestingProhibited &&
  3457. isOpenMPNestingDistributeDirective(CurrentRegion)) {
  3458. // OpenMP 4.5 [2.17 Nesting of Regions]
  3459. // The region associated with the distribute construct must be strictly
  3460. // nested inside a teams region
  3461. NestingProhibited =
  3462. (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
  3463. Recommend = ShouldBeInTeamsRegion;
  3464. }
  3465. if (!NestingProhibited &&
  3466. (isOpenMPTargetExecutionDirective(CurrentRegion) ||
  3467. isOpenMPTargetDataManagementDirective(CurrentRegion))) {
  3468. // OpenMP 4.5 [2.17 Nesting of Regions]
  3469. // If a target, target update, target data, target enter data, or
  3470. // target exit data construct is encountered during execution of a
  3471. // target region, the behavior is unspecified.
  3472. NestingProhibited = Stack->hasDirective(
  3473. [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
  3474. SourceLocation) {
  3475. if (isOpenMPTargetExecutionDirective(K)) {
  3476. OffendingRegion = K;
  3477. return true;
  3478. }
  3479. return false;
  3480. },
  3481. false /* don't skip top directive */);
  3482. CloseNesting = false;
  3483. }
  3484. if (NestingProhibited) {
  3485. if (OrphanSeen) {
  3486. SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
  3487. << getOpenMPDirectiveName(CurrentRegion) << Recommend;
  3488. } else {
  3489. SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
  3490. << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
  3491. << Recommend << getOpenMPDirectiveName(CurrentRegion);
  3492. }
  3493. return true;
  3494. }
  3495. }
  3496. return false;
  3497. }
  3498. static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
  3499. ArrayRef<OMPClause *> Clauses,
  3500. ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
  3501. bool ErrorFound = false;
  3502. unsigned NamedModifiersNumber = 0;
  3503. SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers(
  3504. OMPD_unknown + 1);
  3505. SmallVector<SourceLocation, 4> NameModifierLoc;
  3506. for (const OMPClause *C : Clauses) {
  3507. if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
  3508. // At most one if clause without a directive-name-modifier can appear on
  3509. // the directive.
  3510. OpenMPDirectiveKind CurNM = IC->getNameModifier();
  3511. if (FoundNameModifiers[CurNM]) {
  3512. S.Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
  3513. << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
  3514. << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
  3515. ErrorFound = true;
  3516. } else if (CurNM != OMPD_unknown) {
  3517. NameModifierLoc.push_back(IC->getNameModifierLoc());
  3518. ++NamedModifiersNumber;
  3519. }
  3520. FoundNameModifiers[CurNM] = IC;
  3521. if (CurNM == OMPD_unknown)
  3522. continue;
  3523. // Check if the specified name modifier is allowed for the current
  3524. // directive.
  3525. // At most one if clause with the particular directive-name-modifier can
  3526. // appear on the directive.
  3527. bool MatchFound = false;
  3528. for (auto NM : AllowedNameModifiers) {
  3529. if (CurNM == NM) {
  3530. MatchFound = true;
  3531. break;
  3532. }
  3533. }
  3534. if (!MatchFound) {
  3535. S.Diag(IC->getNameModifierLoc(),
  3536. diag::err_omp_wrong_if_directive_name_modifier)
  3537. << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
  3538. ErrorFound = true;
  3539. }
  3540. }
  3541. }
  3542. // If any if clause on the directive includes a directive-name-modifier then
  3543. // all if clauses on the directive must include a directive-name-modifier.
  3544. if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
  3545. if (NamedModifiersNumber == AllowedNameModifiers.size()) {
  3546. S.Diag(FoundNameModifiers[OMPD_unknown]->getBeginLoc(),
  3547. diag::err_omp_no_more_if_clause);
  3548. } else {
  3549. std::string Values;
  3550. std::string Sep(", ");
  3551. unsigned AllowedCnt = 0;
  3552. unsigned TotalAllowedNum =
  3553. AllowedNameModifiers.size() - NamedModifiersNumber;
  3554. for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
  3555. ++Cnt) {
  3556. OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
  3557. if (!FoundNameModifiers[NM]) {
  3558. Values += "'";
  3559. Values += getOpenMPDirectiveName(NM);
  3560. Values += "'";
  3561. if (AllowedCnt + 2 == TotalAllowedNum)
  3562. Values += " or ";
  3563. else if (AllowedCnt + 1 != TotalAllowedNum)
  3564. Values += Sep;
  3565. ++AllowedCnt;
  3566. }
  3567. }
  3568. S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getBeginLoc(),
  3569. diag::err_omp_unnamed_if_clause)
  3570. << (TotalAllowedNum > 1) << Values;
  3571. }
  3572. for (SourceLocation Loc : NameModifierLoc) {
  3573. S.Diag(Loc, diag::note_omp_previous_named_if_clause);
  3574. }
  3575. ErrorFound = true;
  3576. }
  3577. return ErrorFound;
  3578. }
  3579. static std::pair<ValueDecl *, bool>
  3580. getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
  3581. SourceRange &ERange, bool AllowArraySection = false) {
  3582. if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
  3583. RefExpr->containsUnexpandedParameterPack())
  3584. return std::make_pair(nullptr, true);
  3585. // OpenMP [3.1, C/C++]
  3586. // A list item is a variable name.
  3587. // OpenMP [2.9.3.3, Restrictions, p.1]
  3588. // A variable that is part of another variable (as an array or
  3589. // structure element) cannot appear in a private clause.
  3590. RefExpr = RefExpr->IgnoreParens();
  3591. enum {
  3592. NoArrayExpr = -1,
  3593. ArraySubscript = 0,
  3594. OMPArraySection = 1
  3595. } IsArrayExpr = NoArrayExpr;
  3596. if (AllowArraySection) {
  3597. if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
  3598. Expr *Base = ASE->getBase()->IgnoreParenImpCasts();
  3599. while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
  3600. Base = TempASE->getBase()->IgnoreParenImpCasts();
  3601. RefExpr = Base;
  3602. IsArrayExpr = ArraySubscript;
  3603. } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
  3604. Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
  3605. while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
  3606. Base = TempOASE->getBase()->IgnoreParenImpCasts();
  3607. while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
  3608. Base = TempASE->getBase()->IgnoreParenImpCasts();
  3609. RefExpr = Base;
  3610. IsArrayExpr = OMPArraySection;
  3611. }
  3612. }
  3613. ELoc = RefExpr->getExprLoc();
  3614. ERange = RefExpr->getSourceRange();
  3615. RefExpr = RefExpr->IgnoreParenImpCasts();
  3616. auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
  3617. auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
  3618. if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
  3619. (S.getCurrentThisType().isNull() || !ME ||
  3620. !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
  3621. !isa<FieldDecl>(ME->getMemberDecl()))) {
  3622. if (IsArrayExpr != NoArrayExpr) {
  3623. S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr
  3624. << ERange;
  3625. } else {
  3626. S.Diag(ELoc,
  3627. AllowArraySection
  3628. ? diag::err_omp_expected_var_name_member_expr_or_array_item
  3629. : diag::err_omp_expected_var_name_member_expr)
  3630. << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
  3631. }
  3632. return std::make_pair(nullptr, false);
  3633. }
  3634. return std::make_pair(
  3635. getCanonicalDecl(DE ? DE->getDecl() : ME->getMemberDecl()), false);
  3636. }
  3637. static void checkAllocateClauses(Sema &S, DSAStackTy *Stack,
  3638. ArrayRef<OMPClause *> Clauses) {
  3639. assert(!S.CurContext->isDependentContext() &&
  3640. "Expected non-dependent context.");
  3641. auto AllocateRange =
  3642. llvm::make_filter_range(Clauses, OMPAllocateClause::classof);
  3643. llvm::DenseMap<CanonicalDeclPtr<Decl>, CanonicalDeclPtr<VarDecl>>
  3644. DeclToCopy;
  3645. auto PrivateRange = llvm::make_filter_range(Clauses, [](const OMPClause *C) {
  3646. return isOpenMPPrivate(C->getClauseKind());
  3647. });
  3648. for (OMPClause *Cl : PrivateRange) {
  3649. MutableArrayRef<Expr *>::iterator I, It, Et;
  3650. if (Cl->getClauseKind() == OMPC_private) {
  3651. auto *PC = cast<OMPPrivateClause>(Cl);
  3652. I = PC->private_copies().begin();
  3653. It = PC->varlist_begin();
  3654. Et = PC->varlist_end();
  3655. } else if (Cl->getClauseKind() == OMPC_firstprivate) {
  3656. auto *PC = cast<OMPFirstprivateClause>(Cl);
  3657. I = PC->private_copies().begin();
  3658. It = PC->varlist_begin();
  3659. Et = PC->varlist_end();
  3660. } else if (Cl->getClauseKind() == OMPC_lastprivate) {
  3661. auto *PC = cast<OMPLastprivateClause>(Cl);
  3662. I = PC->private_copies().begin();
  3663. It = PC->varlist_begin();
  3664. Et = PC->varlist_end();
  3665. } else if (Cl->getClauseKind() == OMPC_linear) {
  3666. auto *PC = cast<OMPLinearClause>(Cl);
  3667. I = PC->privates().begin();
  3668. It = PC->varlist_begin();
  3669. Et = PC->varlist_end();
  3670. } else if (Cl->getClauseKind() == OMPC_reduction) {
  3671. auto *PC = cast<OMPReductionClause>(Cl);
  3672. I = PC->privates().begin();
  3673. It = PC->varlist_begin();
  3674. Et = PC->varlist_end();
  3675. } else if (Cl->getClauseKind() == OMPC_task_reduction) {
  3676. auto *PC = cast<OMPTaskReductionClause>(Cl);
  3677. I = PC->privates().begin();
  3678. It = PC->varlist_begin();
  3679. Et = PC->varlist_end();
  3680. } else if (Cl->getClauseKind() == OMPC_in_reduction) {
  3681. auto *PC = cast<OMPInReductionClause>(Cl);
  3682. I = PC->privates().begin();
  3683. It = PC->varlist_begin();
  3684. Et = PC->varlist_end();
  3685. } else {
  3686. llvm_unreachable("Expected private clause.");
  3687. }
  3688. for (Expr *E : llvm::make_range(It, Et)) {
  3689. if (!*I) {
  3690. ++I;
  3691. continue;
  3692. }
  3693. SourceLocation ELoc;
  3694. SourceRange ERange;
  3695. Expr *SimpleRefExpr = E;
  3696. auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
  3697. /*AllowArraySection=*/true);
  3698. DeclToCopy.try_emplace(Res.first,
  3699. cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()));
  3700. ++I;
  3701. }
  3702. }
  3703. for (OMPClause *C : AllocateRange) {
  3704. auto *AC = cast<OMPAllocateClause>(C);
  3705. OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind =
  3706. getAllocatorKind(S, Stack, AC->getAllocator());
  3707. // OpenMP, 2.11.4 allocate Clause, Restrictions.
  3708. // For task, taskloop or target directives, allocation requests to memory
  3709. // allocators with the trait access set to thread result in unspecified
  3710. // behavior.
  3711. if (AllocatorKind == OMPAllocateDeclAttr::OMPThreadMemAlloc &&
  3712. (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
  3713. isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()))) {
  3714. S.Diag(AC->getAllocator()->getExprLoc(),
  3715. diag::warn_omp_allocate_thread_on_task_target_directive)
  3716. << getOpenMPDirectiveName(Stack->getCurrentDirective());
  3717. }
  3718. for (Expr *E : AC->varlists()) {
  3719. SourceLocation ELoc;
  3720. SourceRange ERange;
  3721. Expr *SimpleRefExpr = E;
  3722. auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange);
  3723. ValueDecl *VD = Res.first;
  3724. DSAStackTy::DSAVarData Data = Stack->getTopDSA(VD, /*FromParent=*/false);
  3725. if (!isOpenMPPrivate(Data.CKind)) {
  3726. S.Diag(E->getExprLoc(),
  3727. diag::err_omp_expected_private_copy_for_allocate);
  3728. continue;
  3729. }
  3730. VarDecl *PrivateVD = DeclToCopy[VD];
  3731. if (checkPreviousOMPAllocateAttribute(S, Stack, E, PrivateVD,
  3732. AllocatorKind, AC->getAllocator()))
  3733. continue;
  3734. applyOMPAllocateAttribute(S, PrivateVD, AllocatorKind, AC->getAllocator(),
  3735. E->getSourceRange());
  3736. }
  3737. }
  3738. }
  3739. StmtResult Sema::ActOnOpenMPExecutableDirective(
  3740. OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
  3741. OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
  3742. Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
  3743. StmtResult Res = StmtError();
  3744. // First check CancelRegion which is then used in checkNestingOfRegions.
  3745. if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) ||
  3746. checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
  3747. StartLoc))
  3748. return StmtError();
  3749. llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
  3750. VarsWithInheritedDSAType VarsWithInheritedDSA;
  3751. bool ErrorFound = false;
  3752. ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
  3753. if (AStmt && !CurContext->isDependentContext()) {
  3754. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  3755. // Check default data sharing attributes for referenced variables.
  3756. DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
  3757. int ThisCaptureLevel = getOpenMPCaptureLevels(Kind);
  3758. Stmt *S = AStmt;
  3759. while (--ThisCaptureLevel >= 0)
  3760. S = cast<CapturedStmt>(S)->getCapturedStmt();
  3761. DSAChecker.Visit(S);
  3762. if (DSAChecker.isErrorFound())
  3763. return StmtError();
  3764. // Generate list of implicitly defined firstprivate variables.
  3765. VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
  3766. SmallVector<Expr *, 4> ImplicitFirstprivates(
  3767. DSAChecker.getImplicitFirstprivate().begin(),
  3768. DSAChecker.getImplicitFirstprivate().end());
  3769. SmallVector<Expr *, 4> ImplicitMaps(DSAChecker.getImplicitMap().begin(),
  3770. DSAChecker.getImplicitMap().end());
  3771. // Mark taskgroup task_reduction descriptors as implicitly firstprivate.
  3772. for (OMPClause *C : Clauses) {
  3773. if (auto *IRC = dyn_cast<OMPInReductionClause>(C)) {
  3774. for (Expr *E : IRC->taskgroup_descriptors())
  3775. if (E)
  3776. ImplicitFirstprivates.emplace_back(E);
  3777. }
  3778. }
  3779. if (!ImplicitFirstprivates.empty()) {
  3780. if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
  3781. ImplicitFirstprivates, SourceLocation(), SourceLocation(),
  3782. SourceLocation())) {
  3783. ClausesWithImplicit.push_back(Implicit);
  3784. ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
  3785. ImplicitFirstprivates.size();
  3786. } else {
  3787. ErrorFound = true;
  3788. }
  3789. }
  3790. if (!ImplicitMaps.empty()) {
  3791. CXXScopeSpec MapperIdScopeSpec;
  3792. DeclarationNameInfo MapperId;
  3793. if (OMPClause *Implicit = ActOnOpenMPMapClause(
  3794. llvm::None, llvm::None, MapperIdScopeSpec, MapperId,
  3795. OMPC_MAP_tofrom, /*IsMapTypeImplicit=*/true, SourceLocation(),
  3796. SourceLocation(), ImplicitMaps, OMPVarListLocTy())) {
  3797. ClausesWithImplicit.emplace_back(Implicit);
  3798. ErrorFound |=
  3799. cast<OMPMapClause>(Implicit)->varlist_size() != ImplicitMaps.size();
  3800. } else {
  3801. ErrorFound = true;
  3802. }
  3803. }
  3804. }
  3805. llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
  3806. switch (Kind) {
  3807. case OMPD_parallel:
  3808. Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
  3809. EndLoc);
  3810. AllowedNameModifiers.push_back(OMPD_parallel);
  3811. break;
  3812. case OMPD_simd:
  3813. Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
  3814. VarsWithInheritedDSA);
  3815. break;
  3816. case OMPD_for:
  3817. Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
  3818. VarsWithInheritedDSA);
  3819. break;
  3820. case OMPD_for_simd:
  3821. Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
  3822. EndLoc, VarsWithInheritedDSA);
  3823. break;
  3824. case OMPD_sections:
  3825. Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
  3826. EndLoc);
  3827. break;
  3828. case OMPD_section:
  3829. assert(ClausesWithImplicit.empty() &&
  3830. "No clauses are allowed for 'omp section' directive");
  3831. Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
  3832. break;
  3833. case OMPD_single:
  3834. Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
  3835. EndLoc);
  3836. break;
  3837. case OMPD_master:
  3838. assert(ClausesWithImplicit.empty() &&
  3839. "No clauses are allowed for 'omp master' directive");
  3840. Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
  3841. break;
  3842. case OMPD_critical:
  3843. Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
  3844. StartLoc, EndLoc);
  3845. break;
  3846. case OMPD_parallel_for:
  3847. Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
  3848. EndLoc, VarsWithInheritedDSA);
  3849. AllowedNameModifiers.push_back(OMPD_parallel);
  3850. break;
  3851. case OMPD_parallel_for_simd:
  3852. Res = ActOnOpenMPParallelForSimdDirective(
  3853. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  3854. AllowedNameModifiers.push_back(OMPD_parallel);
  3855. break;
  3856. case OMPD_parallel_sections:
  3857. Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
  3858. StartLoc, EndLoc);
  3859. AllowedNameModifiers.push_back(OMPD_parallel);
  3860. break;
  3861. case OMPD_task:
  3862. Res =
  3863. ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
  3864. AllowedNameModifiers.push_back(OMPD_task);
  3865. break;
  3866. case OMPD_taskyield:
  3867. assert(ClausesWithImplicit.empty() &&
  3868. "No clauses are allowed for 'omp taskyield' directive");
  3869. assert(AStmt == nullptr &&
  3870. "No associated statement allowed for 'omp taskyield' directive");
  3871. Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
  3872. break;
  3873. case OMPD_barrier:
  3874. assert(ClausesWithImplicit.empty() &&
  3875. "No clauses are allowed for 'omp barrier' directive");
  3876. assert(AStmt == nullptr &&
  3877. "No associated statement allowed for 'omp barrier' directive");
  3878. Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
  3879. break;
  3880. case OMPD_taskwait:
  3881. assert(ClausesWithImplicit.empty() &&
  3882. "No clauses are allowed for 'omp taskwait' directive");
  3883. assert(AStmt == nullptr &&
  3884. "No associated statement allowed for 'omp taskwait' directive");
  3885. Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
  3886. break;
  3887. case OMPD_taskgroup:
  3888. Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc,
  3889. EndLoc);
  3890. break;
  3891. case OMPD_flush:
  3892. assert(AStmt == nullptr &&
  3893. "No associated statement allowed for 'omp flush' directive");
  3894. Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
  3895. break;
  3896. case OMPD_ordered:
  3897. Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
  3898. EndLoc);
  3899. break;
  3900. case OMPD_atomic:
  3901. Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
  3902. EndLoc);
  3903. break;
  3904. case OMPD_teams:
  3905. Res =
  3906. ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
  3907. break;
  3908. case OMPD_target:
  3909. Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
  3910. EndLoc);
  3911. AllowedNameModifiers.push_back(OMPD_target);
  3912. break;
  3913. case OMPD_target_parallel:
  3914. Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
  3915. StartLoc, EndLoc);
  3916. AllowedNameModifiers.push_back(OMPD_target);
  3917. AllowedNameModifiers.push_back(OMPD_parallel);
  3918. break;
  3919. case OMPD_target_parallel_for:
  3920. Res = ActOnOpenMPTargetParallelForDirective(
  3921. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  3922. AllowedNameModifiers.push_back(OMPD_target);
  3923. AllowedNameModifiers.push_back(OMPD_parallel);
  3924. break;
  3925. case OMPD_cancellation_point:
  3926. assert(ClausesWithImplicit.empty() &&
  3927. "No clauses are allowed for 'omp cancellation point' directive");
  3928. assert(AStmt == nullptr && "No associated statement allowed for 'omp "
  3929. "cancellation point' directive");
  3930. Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
  3931. break;
  3932. case OMPD_cancel:
  3933. assert(AStmt == nullptr &&
  3934. "No associated statement allowed for 'omp cancel' directive");
  3935. Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
  3936. CancelRegion);
  3937. AllowedNameModifiers.push_back(OMPD_cancel);
  3938. break;
  3939. case OMPD_target_data:
  3940. Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
  3941. EndLoc);
  3942. AllowedNameModifiers.push_back(OMPD_target_data);
  3943. break;
  3944. case OMPD_target_enter_data:
  3945. Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
  3946. EndLoc, AStmt);
  3947. AllowedNameModifiers.push_back(OMPD_target_enter_data);
  3948. break;
  3949. case OMPD_target_exit_data:
  3950. Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
  3951. EndLoc, AStmt);
  3952. AllowedNameModifiers.push_back(OMPD_target_exit_data);
  3953. break;
  3954. case OMPD_taskloop:
  3955. Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
  3956. EndLoc, VarsWithInheritedDSA);
  3957. AllowedNameModifiers.push_back(OMPD_taskloop);
  3958. break;
  3959. case OMPD_taskloop_simd:
  3960. Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
  3961. EndLoc, VarsWithInheritedDSA);
  3962. AllowedNameModifiers.push_back(OMPD_taskloop);
  3963. break;
  3964. case OMPD_distribute:
  3965. Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
  3966. EndLoc, VarsWithInheritedDSA);
  3967. break;
  3968. case OMPD_target_update:
  3969. Res = ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc,
  3970. EndLoc, AStmt);
  3971. AllowedNameModifiers.push_back(OMPD_target_update);
  3972. break;
  3973. case OMPD_distribute_parallel_for:
  3974. Res = ActOnOpenMPDistributeParallelForDirective(
  3975. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  3976. AllowedNameModifiers.push_back(OMPD_parallel);
  3977. break;
  3978. case OMPD_distribute_parallel_for_simd:
  3979. Res = ActOnOpenMPDistributeParallelForSimdDirective(
  3980. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  3981. AllowedNameModifiers.push_back(OMPD_parallel);
  3982. break;
  3983. case OMPD_distribute_simd:
  3984. Res = ActOnOpenMPDistributeSimdDirective(
  3985. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  3986. break;
  3987. case OMPD_target_parallel_for_simd:
  3988. Res = ActOnOpenMPTargetParallelForSimdDirective(
  3989. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  3990. AllowedNameModifiers.push_back(OMPD_target);
  3991. AllowedNameModifiers.push_back(OMPD_parallel);
  3992. break;
  3993. case OMPD_target_simd:
  3994. Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
  3995. EndLoc, VarsWithInheritedDSA);
  3996. AllowedNameModifiers.push_back(OMPD_target);
  3997. break;
  3998. case OMPD_teams_distribute:
  3999. Res = ActOnOpenMPTeamsDistributeDirective(
  4000. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  4001. break;
  4002. case OMPD_teams_distribute_simd:
  4003. Res = ActOnOpenMPTeamsDistributeSimdDirective(
  4004. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  4005. break;
  4006. case OMPD_teams_distribute_parallel_for_simd:
  4007. Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
  4008. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  4009. AllowedNameModifiers.push_back(OMPD_parallel);
  4010. break;
  4011. case OMPD_teams_distribute_parallel_for:
  4012. Res = ActOnOpenMPTeamsDistributeParallelForDirective(
  4013. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  4014. AllowedNameModifiers.push_back(OMPD_parallel);
  4015. break;
  4016. case OMPD_target_teams:
  4017. Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
  4018. EndLoc);
  4019. AllowedNameModifiers.push_back(OMPD_target);
  4020. break;
  4021. case OMPD_target_teams_distribute:
  4022. Res = ActOnOpenMPTargetTeamsDistributeDirective(
  4023. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  4024. AllowedNameModifiers.push_back(OMPD_target);
  4025. break;
  4026. case OMPD_target_teams_distribute_parallel_for:
  4027. Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective(
  4028. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  4029. AllowedNameModifiers.push_back(OMPD_target);
  4030. AllowedNameModifiers.push_back(OMPD_parallel);
  4031. break;
  4032. case OMPD_target_teams_distribute_parallel_for_simd:
  4033. Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
  4034. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  4035. AllowedNameModifiers.push_back(OMPD_target);
  4036. AllowedNameModifiers.push_back(OMPD_parallel);
  4037. break;
  4038. case OMPD_target_teams_distribute_simd:
  4039. Res = ActOnOpenMPTargetTeamsDistributeSimdDirective(
  4040. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  4041. AllowedNameModifiers.push_back(OMPD_target);
  4042. break;
  4043. case OMPD_declare_target:
  4044. case OMPD_end_declare_target:
  4045. case OMPD_threadprivate:
  4046. case OMPD_allocate:
  4047. case OMPD_declare_reduction:
  4048. case OMPD_declare_mapper:
  4049. case OMPD_declare_simd:
  4050. case OMPD_requires:
  4051. llvm_unreachable("OpenMP Directive is not allowed");
  4052. case OMPD_unknown:
  4053. llvm_unreachable("Unknown OpenMP directive");
  4054. }
  4055. ErrorFound = Res.isInvalid() || ErrorFound;
  4056. // Check variables in the clauses if default(none) was specified.
  4057. if (DSAStack->getDefaultDSA() == DSA_none) {
  4058. DSAAttrChecker DSAChecker(DSAStack, *this, nullptr);
  4059. for (OMPClause *C : Clauses) {
  4060. switch (C->getClauseKind()) {
  4061. case OMPC_num_threads:
  4062. case OMPC_dist_schedule:
  4063. // Do not analyse if no parent teams directive.
  4064. if (isOpenMPTeamsDirective(DSAStack->getCurrentDirective()))
  4065. break;
  4066. continue;
  4067. case OMPC_if:
  4068. if (isOpenMPTeamsDirective(DSAStack->getCurrentDirective()) &&
  4069. cast<OMPIfClause>(C)->getNameModifier() != OMPD_target)
  4070. break;
  4071. continue;
  4072. case OMPC_schedule:
  4073. break;
  4074. case OMPC_ordered:
  4075. case OMPC_device:
  4076. case OMPC_num_teams:
  4077. case OMPC_thread_limit:
  4078. case OMPC_priority:
  4079. case OMPC_grainsize:
  4080. case OMPC_num_tasks:
  4081. case OMPC_hint:
  4082. case OMPC_collapse:
  4083. case OMPC_safelen:
  4084. case OMPC_simdlen:
  4085. case OMPC_final:
  4086. case OMPC_default:
  4087. case OMPC_proc_bind:
  4088. case OMPC_private:
  4089. case OMPC_firstprivate:
  4090. case OMPC_lastprivate:
  4091. case OMPC_shared:
  4092. case OMPC_reduction:
  4093. case OMPC_task_reduction:
  4094. case OMPC_in_reduction:
  4095. case OMPC_linear:
  4096. case OMPC_aligned:
  4097. case OMPC_copyin:
  4098. case OMPC_copyprivate:
  4099. case OMPC_nowait:
  4100. case OMPC_untied:
  4101. case OMPC_mergeable:
  4102. case OMPC_allocate:
  4103. case OMPC_read:
  4104. case OMPC_write:
  4105. case OMPC_update:
  4106. case OMPC_capture:
  4107. case OMPC_seq_cst:
  4108. case OMPC_depend:
  4109. case OMPC_threads:
  4110. case OMPC_simd:
  4111. case OMPC_map:
  4112. case OMPC_nogroup:
  4113. case OMPC_defaultmap:
  4114. case OMPC_to:
  4115. case OMPC_from:
  4116. case OMPC_use_device_ptr:
  4117. case OMPC_is_device_ptr:
  4118. continue;
  4119. case OMPC_allocator:
  4120. case OMPC_flush:
  4121. case OMPC_threadprivate:
  4122. case OMPC_uniform:
  4123. case OMPC_unknown:
  4124. case OMPC_unified_address:
  4125. case OMPC_unified_shared_memory:
  4126. case OMPC_reverse_offload:
  4127. case OMPC_dynamic_allocators:
  4128. case OMPC_atomic_default_mem_order:
  4129. llvm_unreachable("Unexpected clause");
  4130. }
  4131. for (Stmt *CC : C->children()) {
  4132. if (CC)
  4133. DSAChecker.Visit(CC);
  4134. }
  4135. }
  4136. for (auto &P : DSAChecker.getVarsWithInheritedDSA())
  4137. VarsWithInheritedDSA[P.getFirst()] = P.getSecond();
  4138. }
  4139. for (const auto &P : VarsWithInheritedDSA) {
  4140. Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
  4141. << P.first << P.second->getSourceRange();
  4142. Diag(DSAStack->getDefaultDSALocation(), diag::note_omp_default_dsa_none);
  4143. }
  4144. ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound;
  4145. if (!AllowedNameModifiers.empty())
  4146. ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
  4147. ErrorFound;
  4148. if (ErrorFound)
  4149. return StmtError();
  4150. if (!(Res.getAs<OMPExecutableDirective>()->isStandaloneDirective())) {
  4151. Res.getAs<OMPExecutableDirective>()
  4152. ->getStructuredBlock()
  4153. ->setIsOMPStructuredBlock(true);
  4154. }
  4155. if (!CurContext->isDependentContext() &&
  4156. isOpenMPTargetExecutionDirective(Kind) &&
  4157. !(DSAStack->hasRequiresDeclWithClause<OMPUnifiedSharedMemoryClause>() ||
  4158. DSAStack->hasRequiresDeclWithClause<OMPUnifiedAddressClause>() ||
  4159. DSAStack->hasRequiresDeclWithClause<OMPReverseOffloadClause>() ||
  4160. DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())) {
  4161. // Register target to DSA Stack.
  4162. DSAStack->addTargetDirLocation(StartLoc);
  4163. }
  4164. return Res;
  4165. }
  4166. Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
  4167. DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
  4168. ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
  4169. ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
  4170. ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
  4171. assert(Aligneds.size() == Alignments.size());
  4172. assert(Linears.size() == LinModifiers.size());
  4173. assert(Linears.size() == Steps.size());
  4174. if (!DG || DG.get().isNull())
  4175. return DeclGroupPtrTy();
  4176. if (!DG.get().isSingleDecl()) {
  4177. Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd);
  4178. return DG;
  4179. }
  4180. Decl *ADecl = DG.get().getSingleDecl();
  4181. if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
  4182. ADecl = FTD->getTemplatedDecl();
  4183. auto *FD = dyn_cast<FunctionDecl>(ADecl);
  4184. if (!FD) {
  4185. Diag(ADecl->getLocation(), diag::err_omp_function_expected);
  4186. return DeclGroupPtrTy();
  4187. }
  4188. // OpenMP [2.8.2, declare simd construct, Description]
  4189. // The parameter of the simdlen clause must be a constant positive integer
  4190. // expression.
  4191. ExprResult SL;
  4192. if (Simdlen)
  4193. SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
  4194. // OpenMP [2.8.2, declare simd construct, Description]
  4195. // The special this pointer can be used as if was one of the arguments to the
  4196. // function in any of the linear, aligned, or uniform clauses.
  4197. // The uniform clause declares one or more arguments to have an invariant
  4198. // value for all concurrent invocations of the function in the execution of a
  4199. // single SIMD loop.
  4200. llvm::DenseMap<const Decl *, const Expr *> UniformedArgs;
  4201. const Expr *UniformedLinearThis = nullptr;
  4202. for (const Expr *E : Uniforms) {
  4203. E = E->IgnoreParenImpCasts();
  4204. if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
  4205. if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
  4206. if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
  4207. FD->getParamDecl(PVD->getFunctionScopeIndex())
  4208. ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
  4209. UniformedArgs.try_emplace(PVD->getCanonicalDecl(), E);
  4210. continue;
  4211. }
  4212. if (isa<CXXThisExpr>(E)) {
  4213. UniformedLinearThis = E;
  4214. continue;
  4215. }
  4216. Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
  4217. << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
  4218. }
  4219. // OpenMP [2.8.2, declare simd construct, Description]
  4220. // The aligned clause declares that the object to which each list item points
  4221. // is aligned to the number of bytes expressed in the optional parameter of
  4222. // the aligned clause.
  4223. // The special this pointer can be used as if was one of the arguments to the
  4224. // function in any of the linear, aligned, or uniform clauses.
  4225. // The type of list items appearing in the aligned clause must be array,
  4226. // pointer, reference to array, or reference to pointer.
  4227. llvm::DenseMap<const Decl *, const Expr *> AlignedArgs;
  4228. const Expr *AlignedThis = nullptr;
  4229. for (const Expr *E : Aligneds) {
  4230. E = E->IgnoreParenImpCasts();
  4231. if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
  4232. if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
  4233. const VarDecl *CanonPVD = PVD->getCanonicalDecl();
  4234. if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
  4235. FD->getParamDecl(PVD->getFunctionScopeIndex())
  4236. ->getCanonicalDecl() == CanonPVD) {
  4237. // OpenMP [2.8.1, simd construct, Restrictions]
  4238. // A list-item cannot appear in more than one aligned clause.
  4239. if (AlignedArgs.count(CanonPVD) > 0) {
  4240. Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
  4241. << 1 << E->getSourceRange();
  4242. Diag(AlignedArgs[CanonPVD]->getExprLoc(),
  4243. diag::note_omp_explicit_dsa)
  4244. << getOpenMPClauseName(OMPC_aligned);
  4245. continue;
  4246. }
  4247. AlignedArgs[CanonPVD] = E;
  4248. QualType QTy = PVD->getType()
  4249. .getNonReferenceType()
  4250. .getUnqualifiedType()
  4251. .getCanonicalType();
  4252. const Type *Ty = QTy.getTypePtrOrNull();
  4253. if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
  4254. Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
  4255. << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
  4256. Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
  4257. }
  4258. continue;
  4259. }
  4260. }
  4261. if (isa<CXXThisExpr>(E)) {
  4262. if (AlignedThis) {
  4263. Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
  4264. << 2 << E->getSourceRange();
  4265. Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
  4266. << getOpenMPClauseName(OMPC_aligned);
  4267. }
  4268. AlignedThis = E;
  4269. continue;
  4270. }
  4271. Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
  4272. << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
  4273. }
  4274. // The optional parameter of the aligned clause, alignment, must be a constant
  4275. // positive integer expression. If no optional parameter is specified,
  4276. // implementation-defined default alignments for SIMD instructions on the
  4277. // target platforms are assumed.
  4278. SmallVector<const Expr *, 4> NewAligns;
  4279. for (Expr *E : Alignments) {
  4280. ExprResult Align;
  4281. if (E)
  4282. Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
  4283. NewAligns.push_back(Align.get());
  4284. }
  4285. // OpenMP [2.8.2, declare simd construct, Description]
  4286. // The linear clause declares one or more list items to be private to a SIMD
  4287. // lane and to have a linear relationship with respect to the iteration space
  4288. // of a loop.
  4289. // The special this pointer can be used as if was one of the arguments to the
  4290. // function in any of the linear, aligned, or uniform clauses.
  4291. // When a linear-step expression is specified in a linear clause it must be
  4292. // either a constant integer expression or an integer-typed parameter that is
  4293. // specified in a uniform clause on the directive.
  4294. llvm::DenseMap<const Decl *, const Expr *> LinearArgs;
  4295. const bool IsUniformedThis = UniformedLinearThis != nullptr;
  4296. auto MI = LinModifiers.begin();
  4297. for (const Expr *E : Linears) {
  4298. auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
  4299. ++MI;
  4300. E = E->IgnoreParenImpCasts();
  4301. if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
  4302. if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
  4303. const VarDecl *CanonPVD = PVD->getCanonicalDecl();
  4304. if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
  4305. FD->getParamDecl(PVD->getFunctionScopeIndex())
  4306. ->getCanonicalDecl() == CanonPVD) {
  4307. // OpenMP [2.15.3.7, linear Clause, Restrictions]
  4308. // A list-item cannot appear in more than one linear clause.
  4309. if (LinearArgs.count(CanonPVD) > 0) {
  4310. Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
  4311. << getOpenMPClauseName(OMPC_linear)
  4312. << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
  4313. Diag(LinearArgs[CanonPVD]->getExprLoc(),
  4314. diag::note_omp_explicit_dsa)
  4315. << getOpenMPClauseName(OMPC_linear);
  4316. continue;
  4317. }
  4318. // Each argument can appear in at most one uniform or linear clause.
  4319. if (UniformedArgs.count(CanonPVD) > 0) {
  4320. Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
  4321. << getOpenMPClauseName(OMPC_linear)
  4322. << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
  4323. Diag(UniformedArgs[CanonPVD]->getExprLoc(),
  4324. diag::note_omp_explicit_dsa)
  4325. << getOpenMPClauseName(OMPC_uniform);
  4326. continue;
  4327. }
  4328. LinearArgs[CanonPVD] = E;
  4329. if (E->isValueDependent() || E->isTypeDependent() ||
  4330. E->isInstantiationDependent() ||
  4331. E->containsUnexpandedParameterPack())
  4332. continue;
  4333. (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
  4334. PVD->getOriginalType());
  4335. continue;
  4336. }
  4337. }
  4338. if (isa<CXXThisExpr>(E)) {
  4339. if (UniformedLinearThis) {
  4340. Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
  4341. << getOpenMPClauseName(OMPC_linear)
  4342. << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
  4343. << E->getSourceRange();
  4344. Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
  4345. << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
  4346. : OMPC_linear);
  4347. continue;
  4348. }
  4349. UniformedLinearThis = E;
  4350. if (E->isValueDependent() || E->isTypeDependent() ||
  4351. E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
  4352. continue;
  4353. (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
  4354. E->getType());
  4355. continue;
  4356. }
  4357. Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
  4358. << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
  4359. }
  4360. Expr *Step = nullptr;
  4361. Expr *NewStep = nullptr;
  4362. SmallVector<Expr *, 4> NewSteps;
  4363. for (Expr *E : Steps) {
  4364. // Skip the same step expression, it was checked already.
  4365. if (Step == E || !E) {
  4366. NewSteps.push_back(E ? NewStep : nullptr);
  4367. continue;
  4368. }
  4369. Step = E;
  4370. if (const auto *DRE = dyn_cast<DeclRefExpr>(Step))
  4371. if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
  4372. const VarDecl *CanonPVD = PVD->getCanonicalDecl();
  4373. if (UniformedArgs.count(CanonPVD) == 0) {
  4374. Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
  4375. << Step->getSourceRange();
  4376. } else if (E->isValueDependent() || E->isTypeDependent() ||
  4377. E->isInstantiationDependent() ||
  4378. E->containsUnexpandedParameterPack() ||
  4379. CanonPVD->getType()->hasIntegerRepresentation()) {
  4380. NewSteps.push_back(Step);
  4381. } else {
  4382. Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
  4383. << Step->getSourceRange();
  4384. }
  4385. continue;
  4386. }
  4387. NewStep = Step;
  4388. if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
  4389. !Step->isInstantiationDependent() &&
  4390. !Step->containsUnexpandedParameterPack()) {
  4391. NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
  4392. .get();
  4393. if (NewStep)
  4394. NewStep = VerifyIntegerConstantExpression(NewStep).get();
  4395. }
  4396. NewSteps.push_back(NewStep);
  4397. }
  4398. auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
  4399. Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
  4400. Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
  4401. const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
  4402. const_cast<Expr **>(Linears.data()), Linears.size(),
  4403. const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
  4404. NewSteps.data(), NewSteps.size(), SR);
  4405. ADecl->addAttr(NewAttr);
  4406. return ConvertDeclToDeclGroup(ADecl);
  4407. }
  4408. StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
  4409. Stmt *AStmt,
  4410. SourceLocation StartLoc,
  4411. SourceLocation EndLoc) {
  4412. if (!AStmt)
  4413. return StmtError();
  4414. auto *CS = cast<CapturedStmt>(AStmt);
  4415. // 1.2.2 OpenMP Language Terminology
  4416. // Structured block - An executable statement with a single entry at the
  4417. // top and a single exit at the bottom.
  4418. // The point of exit cannot be a branch out of the structured block.
  4419. // longjmp() and throw() must not violate the entry/exit criteria.
  4420. CS->getCapturedDecl()->setNothrow();
  4421. setFunctionHasBranchProtectedScope();
  4422. return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
  4423. DSAStack->isCancelRegion());
  4424. }
  4425. namespace {
  4426. /// Helper class for checking canonical form of the OpenMP loops and
  4427. /// extracting iteration space of each loop in the loop nest, that will be used
  4428. /// for IR generation.
  4429. class OpenMPIterationSpaceChecker {
  4430. /// Reference to Sema.
  4431. Sema &SemaRef;
  4432. /// Data-sharing stack.
  4433. DSAStackTy &Stack;
  4434. /// A location for diagnostics (when there is no some better location).
  4435. SourceLocation DefaultLoc;
  4436. /// A location for diagnostics (when increment is not compatible).
  4437. SourceLocation ConditionLoc;
  4438. /// A source location for referring to loop init later.
  4439. SourceRange InitSrcRange;
  4440. /// A source location for referring to condition later.
  4441. SourceRange ConditionSrcRange;
  4442. /// A source location for referring to increment later.
  4443. SourceRange IncrementSrcRange;
  4444. /// Loop variable.
  4445. ValueDecl *LCDecl = nullptr;
  4446. /// Reference to loop variable.
  4447. Expr *LCRef = nullptr;
  4448. /// Lower bound (initializer for the var).
  4449. Expr *LB = nullptr;
  4450. /// Upper bound.
  4451. Expr *UB = nullptr;
  4452. /// Loop step (increment).
  4453. Expr *Step = nullptr;
  4454. /// This flag is true when condition is one of:
  4455. /// Var < UB
  4456. /// Var <= UB
  4457. /// UB > Var
  4458. /// UB >= Var
  4459. /// This will have no value when the condition is !=
  4460. llvm::Optional<bool> TestIsLessOp;
  4461. /// This flag is true when condition is strict ( < or > ).
  4462. bool TestIsStrictOp = false;
  4463. /// This flag is true when step is subtracted on each iteration.
  4464. bool SubtractStep = false;
  4465. /// The outer loop counter this loop depends on (if any).
  4466. const ValueDecl *DepDecl = nullptr;
  4467. /// Contains number of loop (starts from 1) on which loop counter init
  4468. /// expression of this loop depends on.
  4469. Optional<unsigned> InitDependOnLC;
  4470. /// Contains number of loop (starts from 1) on which loop counter condition
  4471. /// expression of this loop depends on.
  4472. Optional<unsigned> CondDependOnLC;
  4473. /// Checks if the provide statement depends on the loop counter.
  4474. Optional<unsigned> doesDependOnLoopCounter(const Stmt *S, bool IsInitializer);
  4475. public:
  4476. OpenMPIterationSpaceChecker(Sema &SemaRef, DSAStackTy &Stack,
  4477. SourceLocation DefaultLoc)
  4478. : SemaRef(SemaRef), Stack(Stack), DefaultLoc(DefaultLoc),
  4479. ConditionLoc(DefaultLoc) {}
  4480. /// Check init-expr for canonical loop form and save loop counter
  4481. /// variable - #Var and its initialization value - #LB.
  4482. bool checkAndSetInit(Stmt *S, bool EmitDiags = true);
  4483. /// Check test-expr for canonical form, save upper-bound (#UB), flags
  4484. /// for less/greater and for strict/non-strict comparison.
  4485. bool checkAndSetCond(Expr *S);
  4486. /// Check incr-expr for canonical loop form and return true if it
  4487. /// does not conform, otherwise save loop step (#Step).
  4488. bool checkAndSetInc(Expr *S);
  4489. /// Return the loop counter variable.
  4490. ValueDecl *getLoopDecl() const { return LCDecl; }
  4491. /// Return the reference expression to loop counter variable.
  4492. Expr *getLoopDeclRefExpr() const { return LCRef; }
  4493. /// Source range of the loop init.
  4494. SourceRange getInitSrcRange() const { return InitSrcRange; }
  4495. /// Source range of the loop condition.
  4496. SourceRange getConditionSrcRange() const { return ConditionSrcRange; }
  4497. /// Source range of the loop increment.
  4498. SourceRange getIncrementSrcRange() const { return IncrementSrcRange; }
  4499. /// True if the step should be subtracted.
  4500. bool shouldSubtractStep() const { return SubtractStep; }
  4501. /// True, if the compare operator is strict (<, > or !=).
  4502. bool isStrictTestOp() const { return TestIsStrictOp; }
  4503. /// Build the expression to calculate the number of iterations.
  4504. Expr *buildNumIterations(
  4505. Scope *S, const bool LimitedType,
  4506. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
  4507. /// Build the precondition expression for the loops.
  4508. Expr *
  4509. buildPreCond(Scope *S, Expr *Cond,
  4510. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
  4511. /// Build reference expression to the counter be used for codegen.
  4512. DeclRefExpr *
  4513. buildCounterVar(llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
  4514. DSAStackTy &DSA) const;
  4515. /// Build reference expression to the private counter be used for
  4516. /// codegen.
  4517. Expr *buildPrivateCounterVar() const;
  4518. /// Build initialization of the counter be used for codegen.
  4519. Expr *buildCounterInit() const;
  4520. /// Build step of the counter be used for codegen.
  4521. Expr *buildCounterStep() const;
  4522. /// Build loop data with counter value for depend clauses in ordered
  4523. /// directives.
  4524. Expr *
  4525. buildOrderedLoopData(Scope *S, Expr *Counter,
  4526. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
  4527. SourceLocation Loc, Expr *Inc = nullptr,
  4528. OverloadedOperatorKind OOK = OO_Amp);
  4529. /// Return true if any expression is dependent.
  4530. bool dependent() const;
  4531. private:
  4532. /// Check the right-hand side of an assignment in the increment
  4533. /// expression.
  4534. bool checkAndSetIncRHS(Expr *RHS);
  4535. /// Helper to set loop counter variable and its initializer.
  4536. bool setLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB,
  4537. bool EmitDiags);
  4538. /// Helper to set upper bound.
  4539. bool setUB(Expr *NewUB, llvm::Optional<bool> LessOp, bool StrictOp,
  4540. SourceRange SR, SourceLocation SL);
  4541. /// Helper to set loop increment.
  4542. bool setStep(Expr *NewStep, bool Subtract);
  4543. };
  4544. bool OpenMPIterationSpaceChecker::dependent() const {
  4545. if (!LCDecl) {
  4546. assert(!LB && !UB && !Step);
  4547. return false;
  4548. }
  4549. return LCDecl->getType()->isDependentType() ||
  4550. (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
  4551. (Step && Step->isValueDependent());
  4552. }
  4553. bool OpenMPIterationSpaceChecker::setLCDeclAndLB(ValueDecl *NewLCDecl,
  4554. Expr *NewLCRefExpr,
  4555. Expr *NewLB, bool EmitDiags) {
  4556. // State consistency checking to ensure correct usage.
  4557. assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
  4558. UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
  4559. if (!NewLCDecl || !NewLB)
  4560. return true;
  4561. LCDecl = getCanonicalDecl(NewLCDecl);
  4562. LCRef = NewLCRefExpr;
  4563. if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
  4564. if (const CXXConstructorDecl *Ctor = CE->getConstructor())
  4565. if ((Ctor->isCopyOrMoveConstructor() ||
  4566. Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
  4567. CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
  4568. NewLB = CE->getArg(0)->IgnoreParenImpCasts();
  4569. LB = NewLB;
  4570. if (EmitDiags)
  4571. InitDependOnLC = doesDependOnLoopCounter(LB, /*IsInitializer=*/true);
  4572. return false;
  4573. }
  4574. bool OpenMPIterationSpaceChecker::setUB(Expr *NewUB,
  4575. llvm::Optional<bool> LessOp,
  4576. bool StrictOp, SourceRange SR,
  4577. SourceLocation SL) {
  4578. // State consistency checking to ensure correct usage.
  4579. assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
  4580. Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
  4581. if (!NewUB)
  4582. return true;
  4583. UB = NewUB;
  4584. if (LessOp)
  4585. TestIsLessOp = LessOp;
  4586. TestIsStrictOp = StrictOp;
  4587. ConditionSrcRange = SR;
  4588. ConditionLoc = SL;
  4589. CondDependOnLC = doesDependOnLoopCounter(UB, /*IsInitializer=*/false);
  4590. return false;
  4591. }
  4592. bool OpenMPIterationSpaceChecker::setStep(Expr *NewStep, bool Subtract) {
  4593. // State consistency checking to ensure correct usage.
  4594. assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
  4595. if (!NewStep)
  4596. return true;
  4597. if (!NewStep->isValueDependent()) {
  4598. // Check that the step is integer expression.
  4599. SourceLocation StepLoc = NewStep->getBeginLoc();
  4600. ExprResult Val = SemaRef.PerformOpenMPImplicitIntegerConversion(
  4601. StepLoc, getExprAsWritten(NewStep));
  4602. if (Val.isInvalid())
  4603. return true;
  4604. NewStep = Val.get();
  4605. // OpenMP [2.6, Canonical Loop Form, Restrictions]
  4606. // If test-expr is of form var relational-op b and relational-op is < or
  4607. // <= then incr-expr must cause var to increase on each iteration of the
  4608. // loop. If test-expr is of form var relational-op b and relational-op is
  4609. // > or >= then incr-expr must cause var to decrease on each iteration of
  4610. // the loop.
  4611. // If test-expr is of form b relational-op var and relational-op is < or
  4612. // <= then incr-expr must cause var to decrease on each iteration of the
  4613. // loop. If test-expr is of form b relational-op var and relational-op is
  4614. // > or >= then incr-expr must cause var to increase on each iteration of
  4615. // the loop.
  4616. llvm::APSInt Result;
  4617. bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
  4618. bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
  4619. bool IsConstNeg =
  4620. IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
  4621. bool IsConstPos =
  4622. IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
  4623. bool IsConstZero = IsConstant && !Result.getBoolValue();
  4624. // != with increment is treated as <; != with decrement is treated as >
  4625. if (!TestIsLessOp.hasValue())
  4626. TestIsLessOp = IsConstPos || (IsUnsigned && !Subtract);
  4627. if (UB && (IsConstZero ||
  4628. (TestIsLessOp.getValue() ?
  4629. (IsConstNeg || (IsUnsigned && Subtract)) :
  4630. (IsConstPos || (IsUnsigned && !Subtract))))) {
  4631. SemaRef.Diag(NewStep->getExprLoc(),
  4632. diag::err_omp_loop_incr_not_compatible)
  4633. << LCDecl << TestIsLessOp.getValue() << NewStep->getSourceRange();
  4634. SemaRef.Diag(ConditionLoc,
  4635. diag::note_omp_loop_cond_requres_compatible_incr)
  4636. << TestIsLessOp.getValue() << ConditionSrcRange;
  4637. return true;
  4638. }
  4639. if (TestIsLessOp.getValue() == Subtract) {
  4640. NewStep =
  4641. SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
  4642. .get();
  4643. Subtract = !Subtract;
  4644. }
  4645. }
  4646. Step = NewStep;
  4647. SubtractStep = Subtract;
  4648. return false;
  4649. }
  4650. namespace {
  4651. /// Checker for the non-rectangular loops. Checks if the initializer or
  4652. /// condition expression references loop counter variable.
  4653. class LoopCounterRefChecker final
  4654. : public ConstStmtVisitor<LoopCounterRefChecker, bool> {
  4655. Sema &SemaRef;
  4656. DSAStackTy &Stack;
  4657. const ValueDecl *CurLCDecl = nullptr;
  4658. const ValueDecl *DepDecl = nullptr;
  4659. const ValueDecl *PrevDepDecl = nullptr;
  4660. bool IsInitializer = true;
  4661. unsigned BaseLoopId = 0;
  4662. bool checkDecl(const Expr *E, const ValueDecl *VD) {
  4663. if (getCanonicalDecl(VD) == getCanonicalDecl(CurLCDecl)) {
  4664. SemaRef.Diag(E->getExprLoc(), diag::err_omp_stmt_depends_on_loop_counter)
  4665. << (IsInitializer ? 0 : 1);
  4666. return false;
  4667. }
  4668. const auto &&Data = Stack.isLoopControlVariable(VD);
  4669. // OpenMP, 2.9.1 Canonical Loop Form, Restrictions.
  4670. // The type of the loop iterator on which we depend may not have a random
  4671. // access iterator type.
  4672. if (Data.first && VD->getType()->isRecordType()) {
  4673. SmallString<128> Name;
  4674. llvm::raw_svector_ostream OS(Name);
  4675. VD->getNameForDiagnostic(OS, SemaRef.getPrintingPolicy(),
  4676. /*Qualified=*/true);
  4677. SemaRef.Diag(E->getExprLoc(),
  4678. diag::err_omp_wrong_dependency_iterator_type)
  4679. << OS.str();
  4680. SemaRef.Diag(VD->getLocation(), diag::note_previous_decl) << VD;
  4681. return false;
  4682. }
  4683. if (Data.first &&
  4684. (DepDecl || (PrevDepDecl &&
  4685. getCanonicalDecl(VD) != getCanonicalDecl(PrevDepDecl)))) {
  4686. if (!DepDecl && PrevDepDecl)
  4687. DepDecl = PrevDepDecl;
  4688. SmallString<128> Name;
  4689. llvm::raw_svector_ostream OS(Name);
  4690. DepDecl->getNameForDiagnostic(OS, SemaRef.getPrintingPolicy(),
  4691. /*Qualified=*/true);
  4692. SemaRef.Diag(E->getExprLoc(),
  4693. diag::err_omp_invariant_or_linear_dependency)
  4694. << OS.str();
  4695. return false;
  4696. }
  4697. if (Data.first) {
  4698. DepDecl = VD;
  4699. BaseLoopId = Data.first;
  4700. }
  4701. return Data.first;
  4702. }
  4703. public:
  4704. bool VisitDeclRefExpr(const DeclRefExpr *E) {
  4705. const ValueDecl *VD = E->getDecl();
  4706. if (isa<VarDecl>(VD))
  4707. return checkDecl(E, VD);
  4708. return false;
  4709. }
  4710. bool VisitMemberExpr(const MemberExpr *E) {
  4711. if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) {
  4712. const ValueDecl *VD = E->getMemberDecl();
  4713. return checkDecl(E, VD);
  4714. }
  4715. return false;
  4716. }
  4717. bool VisitStmt(const Stmt *S) {
  4718. bool Res = true;
  4719. for (const Stmt *Child : S->children())
  4720. Res = Child && Visit(Child) && Res;
  4721. return Res;
  4722. }
  4723. explicit LoopCounterRefChecker(Sema &SemaRef, DSAStackTy &Stack,
  4724. const ValueDecl *CurLCDecl, bool IsInitializer,
  4725. const ValueDecl *PrevDepDecl = nullptr)
  4726. : SemaRef(SemaRef), Stack(Stack), CurLCDecl(CurLCDecl),
  4727. PrevDepDecl(PrevDepDecl), IsInitializer(IsInitializer) {}
  4728. unsigned getBaseLoopId() const {
  4729. assert(CurLCDecl && "Expected loop dependency.");
  4730. return BaseLoopId;
  4731. }
  4732. const ValueDecl *getDepDecl() const {
  4733. assert(CurLCDecl && "Expected loop dependency.");
  4734. return DepDecl;
  4735. }
  4736. };
  4737. } // namespace
  4738. Optional<unsigned>
  4739. OpenMPIterationSpaceChecker::doesDependOnLoopCounter(const Stmt *S,
  4740. bool IsInitializer) {
  4741. // Check for the non-rectangular loops.
  4742. LoopCounterRefChecker LoopStmtChecker(SemaRef, Stack, LCDecl, IsInitializer,
  4743. DepDecl);
  4744. if (LoopStmtChecker.Visit(S)) {
  4745. DepDecl = LoopStmtChecker.getDepDecl();
  4746. return LoopStmtChecker.getBaseLoopId();
  4747. }
  4748. return llvm::None;
  4749. }
  4750. bool OpenMPIterationSpaceChecker::checkAndSetInit(Stmt *S, bool EmitDiags) {
  4751. // Check init-expr for canonical loop form and save loop counter
  4752. // variable - #Var and its initialization value - #LB.
  4753. // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
  4754. // var = lb
  4755. // integer-type var = lb
  4756. // random-access-iterator-type var = lb
  4757. // pointer-type var = lb
  4758. //
  4759. if (!S) {
  4760. if (EmitDiags) {
  4761. SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
  4762. }
  4763. return true;
  4764. }
  4765. if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
  4766. if (!ExprTemp->cleanupsHaveSideEffects())
  4767. S = ExprTemp->getSubExpr();
  4768. InitSrcRange = S->getSourceRange();
  4769. if (Expr *E = dyn_cast<Expr>(S))
  4770. S = E->IgnoreParens();
  4771. if (auto *BO = dyn_cast<BinaryOperator>(S)) {
  4772. if (BO->getOpcode() == BO_Assign) {
  4773. Expr *LHS = BO->getLHS()->IgnoreParens();
  4774. if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
  4775. if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
  4776. if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
  4777. return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
  4778. EmitDiags);
  4779. return setLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS(), EmitDiags);
  4780. }
  4781. if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
  4782. if (ME->isArrow() &&
  4783. isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
  4784. return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
  4785. EmitDiags);
  4786. }
  4787. }
  4788. } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
  4789. if (DS->isSingleDecl()) {
  4790. if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
  4791. if (Var->hasInit() && !Var->getType()->isReferenceType()) {
  4792. // Accept non-canonical init form here but emit ext. warning.
  4793. if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
  4794. SemaRef.Diag(S->getBeginLoc(),
  4795. diag::ext_omp_loop_not_canonical_init)
  4796. << S->getSourceRange();
  4797. return setLCDeclAndLB(
  4798. Var,
  4799. buildDeclRefExpr(SemaRef, Var,
  4800. Var->getType().getNonReferenceType(),
  4801. DS->getBeginLoc()),
  4802. Var->getInit(), EmitDiags);
  4803. }
  4804. }
  4805. }
  4806. } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
  4807. if (CE->getOperator() == OO_Equal) {
  4808. Expr *LHS = CE->getArg(0);
  4809. if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
  4810. if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
  4811. if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
  4812. return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
  4813. EmitDiags);
  4814. return setLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1), EmitDiags);
  4815. }
  4816. if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
  4817. if (ME->isArrow() &&
  4818. isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
  4819. return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
  4820. EmitDiags);
  4821. }
  4822. }
  4823. }
  4824. if (dependent() || SemaRef.CurContext->isDependentContext())
  4825. return false;
  4826. if (EmitDiags) {
  4827. SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_init)
  4828. << S->getSourceRange();
  4829. }
  4830. return true;
  4831. }
  4832. /// Ignore parenthesizes, implicit casts, copy constructor and return the
  4833. /// variable (which may be the loop variable) if possible.
  4834. static const ValueDecl *getInitLCDecl(const Expr *E) {
  4835. if (!E)
  4836. return nullptr;
  4837. E = getExprAsWritten(E);
  4838. if (const auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
  4839. if (const CXXConstructorDecl *Ctor = CE->getConstructor())
  4840. if ((Ctor->isCopyOrMoveConstructor() ||
  4841. Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
  4842. CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
  4843. E = CE->getArg(0)->IgnoreParenImpCasts();
  4844. if (const auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
  4845. if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
  4846. return getCanonicalDecl(VD);
  4847. }
  4848. if (const auto *ME = dyn_cast_or_null<MemberExpr>(E))
  4849. if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
  4850. return getCanonicalDecl(ME->getMemberDecl());
  4851. return nullptr;
  4852. }
  4853. bool OpenMPIterationSpaceChecker::checkAndSetCond(Expr *S) {
  4854. // Check test-expr for canonical form, save upper-bound UB, flags for
  4855. // less/greater and for strict/non-strict comparison.
  4856. // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
  4857. // var relational-op b
  4858. // b relational-op var
  4859. //
  4860. if (!S) {
  4861. SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << LCDecl;
  4862. return true;
  4863. }
  4864. S = getExprAsWritten(S);
  4865. SourceLocation CondLoc = S->getBeginLoc();
  4866. if (auto *BO = dyn_cast<BinaryOperator>(S)) {
  4867. if (BO->isRelationalOp()) {
  4868. if (getInitLCDecl(BO->getLHS()) == LCDecl)
  4869. return setUB(BO->getRHS(),
  4870. (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
  4871. (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
  4872. BO->getSourceRange(), BO->getOperatorLoc());
  4873. if (getInitLCDecl(BO->getRHS()) == LCDecl)
  4874. return setUB(BO->getLHS(),
  4875. (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
  4876. (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
  4877. BO->getSourceRange(), BO->getOperatorLoc());
  4878. } else if (BO->getOpcode() == BO_NE)
  4879. return setUB(getInitLCDecl(BO->getLHS()) == LCDecl ?
  4880. BO->getRHS() : BO->getLHS(),
  4881. /*LessOp=*/llvm::None,
  4882. /*StrictOp=*/true,
  4883. BO->getSourceRange(), BO->getOperatorLoc());
  4884. } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
  4885. if (CE->getNumArgs() == 2) {
  4886. auto Op = CE->getOperator();
  4887. switch (Op) {
  4888. case OO_Greater:
  4889. case OO_GreaterEqual:
  4890. case OO_Less:
  4891. case OO_LessEqual:
  4892. if (getInitLCDecl(CE->getArg(0)) == LCDecl)
  4893. return setUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
  4894. Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
  4895. CE->getOperatorLoc());
  4896. if (getInitLCDecl(CE->getArg(1)) == LCDecl)
  4897. return setUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
  4898. Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
  4899. CE->getOperatorLoc());
  4900. break;
  4901. case OO_ExclaimEqual:
  4902. return setUB(getInitLCDecl(CE->getArg(0)) == LCDecl ?
  4903. CE->getArg(1) : CE->getArg(0),
  4904. /*LessOp=*/llvm::None,
  4905. /*StrictOp=*/true,
  4906. CE->getSourceRange(),
  4907. CE->getOperatorLoc());
  4908. break;
  4909. default:
  4910. break;
  4911. }
  4912. }
  4913. }
  4914. if (dependent() || SemaRef.CurContext->isDependentContext())
  4915. return false;
  4916. SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
  4917. << S->getSourceRange() << LCDecl;
  4918. return true;
  4919. }
  4920. bool OpenMPIterationSpaceChecker::checkAndSetIncRHS(Expr *RHS) {
  4921. // RHS of canonical loop form increment can be:
  4922. // var + incr
  4923. // incr + var
  4924. // var - incr
  4925. //
  4926. RHS = RHS->IgnoreParenImpCasts();
  4927. if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
  4928. if (BO->isAdditiveOp()) {
  4929. bool IsAdd = BO->getOpcode() == BO_Add;
  4930. if (getInitLCDecl(BO->getLHS()) == LCDecl)
  4931. return setStep(BO->getRHS(), !IsAdd);
  4932. if (IsAdd && getInitLCDecl(BO->getRHS()) == LCDecl)
  4933. return setStep(BO->getLHS(), /*Subtract=*/false);
  4934. }
  4935. } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
  4936. bool IsAdd = CE->getOperator() == OO_Plus;
  4937. if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
  4938. if (getInitLCDecl(CE->getArg(0)) == LCDecl)
  4939. return setStep(CE->getArg(1), !IsAdd);
  4940. if (IsAdd && getInitLCDecl(CE->getArg(1)) == LCDecl)
  4941. return setStep(CE->getArg(0), /*Subtract=*/false);
  4942. }
  4943. }
  4944. if (dependent() || SemaRef.CurContext->isDependentContext())
  4945. return false;
  4946. SemaRef.Diag(RHS->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
  4947. << RHS->getSourceRange() << LCDecl;
  4948. return true;
  4949. }
  4950. bool OpenMPIterationSpaceChecker::checkAndSetInc(Expr *S) {
  4951. // Check incr-expr for canonical loop form and return true if it
  4952. // does not conform.
  4953. // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
  4954. // ++var
  4955. // var++
  4956. // --var
  4957. // var--
  4958. // var += incr
  4959. // var -= incr
  4960. // var = var + incr
  4961. // var = incr + var
  4962. // var = var - incr
  4963. //
  4964. if (!S) {
  4965. SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
  4966. return true;
  4967. }
  4968. if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
  4969. if (!ExprTemp->cleanupsHaveSideEffects())
  4970. S = ExprTemp->getSubExpr();
  4971. IncrementSrcRange = S->getSourceRange();
  4972. S = S->IgnoreParens();
  4973. if (auto *UO = dyn_cast<UnaryOperator>(S)) {
  4974. if (UO->isIncrementDecrementOp() &&
  4975. getInitLCDecl(UO->getSubExpr()) == LCDecl)
  4976. return setStep(SemaRef
  4977. .ActOnIntegerConstant(UO->getBeginLoc(),
  4978. (UO->isDecrementOp() ? -1 : 1))
  4979. .get(),
  4980. /*Subtract=*/false);
  4981. } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
  4982. switch (BO->getOpcode()) {
  4983. case BO_AddAssign:
  4984. case BO_SubAssign:
  4985. if (getInitLCDecl(BO->getLHS()) == LCDecl)
  4986. return setStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
  4987. break;
  4988. case BO_Assign:
  4989. if (getInitLCDecl(BO->getLHS()) == LCDecl)
  4990. return checkAndSetIncRHS(BO->getRHS());
  4991. break;
  4992. default:
  4993. break;
  4994. }
  4995. } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
  4996. switch (CE->getOperator()) {
  4997. case OO_PlusPlus:
  4998. case OO_MinusMinus:
  4999. if (getInitLCDecl(CE->getArg(0)) == LCDecl)
  5000. return setStep(SemaRef
  5001. .ActOnIntegerConstant(
  5002. CE->getBeginLoc(),
  5003. ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
  5004. .get(),
  5005. /*Subtract=*/false);
  5006. break;
  5007. case OO_PlusEqual:
  5008. case OO_MinusEqual:
  5009. if (getInitLCDecl(CE->getArg(0)) == LCDecl)
  5010. return setStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
  5011. break;
  5012. case OO_Equal:
  5013. if (getInitLCDecl(CE->getArg(0)) == LCDecl)
  5014. return checkAndSetIncRHS(CE->getArg(1));
  5015. break;
  5016. default:
  5017. break;
  5018. }
  5019. }
  5020. if (dependent() || SemaRef.CurContext->isDependentContext())
  5021. return false;
  5022. SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
  5023. << S->getSourceRange() << LCDecl;
  5024. return true;
  5025. }
  5026. static ExprResult
  5027. tryBuildCapture(Sema &SemaRef, Expr *Capture,
  5028. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
  5029. if (SemaRef.CurContext->isDependentContext())
  5030. return ExprResult(Capture);
  5031. if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
  5032. return SemaRef.PerformImplicitConversion(
  5033. Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
  5034. /*AllowExplicit=*/true);
  5035. auto I = Captures.find(Capture);
  5036. if (I != Captures.end())
  5037. return buildCapture(SemaRef, Capture, I->second);
  5038. DeclRefExpr *Ref = nullptr;
  5039. ExprResult Res = buildCapture(SemaRef, Capture, Ref);
  5040. Captures[Capture] = Ref;
  5041. return Res;
  5042. }
  5043. /// Build the expression to calculate the number of iterations.
  5044. Expr *OpenMPIterationSpaceChecker::buildNumIterations(
  5045. Scope *S, const bool LimitedType,
  5046. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
  5047. ExprResult Diff;
  5048. QualType VarType = LCDecl->getType().getNonReferenceType();
  5049. if (VarType->isIntegerType() || VarType->isPointerType() ||
  5050. SemaRef.getLangOpts().CPlusPlus) {
  5051. // Upper - Lower
  5052. Expr *UBExpr = TestIsLessOp.getValue() ? UB : LB;
  5053. Expr *LBExpr = TestIsLessOp.getValue() ? LB : UB;
  5054. Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
  5055. Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
  5056. if (!Upper || !Lower)
  5057. return nullptr;
  5058. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
  5059. if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
  5060. // BuildBinOp already emitted error, this one is to point user to upper
  5061. // and lower bound, and to tell what is passed to 'operator-'.
  5062. SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx)
  5063. << Upper->getSourceRange() << Lower->getSourceRange();
  5064. return nullptr;
  5065. }
  5066. }
  5067. if (!Diff.isUsable())
  5068. return nullptr;
  5069. // Upper - Lower [- 1]
  5070. if (TestIsStrictOp)
  5071. Diff = SemaRef.BuildBinOp(
  5072. S, DefaultLoc, BO_Sub, Diff.get(),
  5073. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
  5074. if (!Diff.isUsable())
  5075. return nullptr;
  5076. // Upper - Lower [- 1] + Step
  5077. ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
  5078. if (!NewStep.isUsable())
  5079. return nullptr;
  5080. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
  5081. if (!Diff.isUsable())
  5082. return nullptr;
  5083. // Parentheses (for dumping/debugging purposes only).
  5084. Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
  5085. if (!Diff.isUsable())
  5086. return nullptr;
  5087. // (Upper - Lower [- 1] + Step) / Step
  5088. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
  5089. if (!Diff.isUsable())
  5090. return nullptr;
  5091. // OpenMP runtime requires 32-bit or 64-bit loop variables.
  5092. QualType Type = Diff.get()->getType();
  5093. ASTContext &C = SemaRef.Context;
  5094. bool UseVarType = VarType->hasIntegerRepresentation() &&
  5095. C.getTypeSize(Type) > C.getTypeSize(VarType);
  5096. if (!Type->isIntegerType() || UseVarType) {
  5097. unsigned NewSize =
  5098. UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
  5099. bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
  5100. : Type->hasSignedIntegerRepresentation();
  5101. Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
  5102. if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
  5103. Diff = SemaRef.PerformImplicitConversion(
  5104. Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
  5105. if (!Diff.isUsable())
  5106. return nullptr;
  5107. }
  5108. }
  5109. if (LimitedType) {
  5110. unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
  5111. if (NewSize != C.getTypeSize(Type)) {
  5112. if (NewSize < C.getTypeSize(Type)) {
  5113. assert(NewSize == 64 && "incorrect loop var size");
  5114. SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
  5115. << InitSrcRange << ConditionSrcRange;
  5116. }
  5117. QualType NewType = C.getIntTypeForBitwidth(
  5118. NewSize, Type->hasSignedIntegerRepresentation() ||
  5119. C.getTypeSize(Type) < NewSize);
  5120. if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
  5121. Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
  5122. Sema::AA_Converting, true);
  5123. if (!Diff.isUsable())
  5124. return nullptr;
  5125. }
  5126. }
  5127. }
  5128. return Diff.get();
  5129. }
  5130. Expr *OpenMPIterationSpaceChecker::buildPreCond(
  5131. Scope *S, Expr *Cond,
  5132. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
  5133. // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
  5134. bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
  5135. SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
  5136. ExprResult NewLB = tryBuildCapture(SemaRef, LB, Captures);
  5137. ExprResult NewUB = tryBuildCapture(SemaRef, UB, Captures);
  5138. if (!NewLB.isUsable() || !NewUB.isUsable())
  5139. return nullptr;
  5140. ExprResult CondExpr =
  5141. SemaRef.BuildBinOp(S, DefaultLoc,
  5142. TestIsLessOp.getValue() ?
  5143. (TestIsStrictOp ? BO_LT : BO_LE) :
  5144. (TestIsStrictOp ? BO_GT : BO_GE),
  5145. NewLB.get(), NewUB.get());
  5146. if (CondExpr.isUsable()) {
  5147. if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
  5148. SemaRef.Context.BoolTy))
  5149. CondExpr = SemaRef.PerformImplicitConversion(
  5150. CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
  5151. /*AllowExplicit=*/true);
  5152. }
  5153. SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
  5154. // Otherwise use original loop condition and evaluate it in runtime.
  5155. return CondExpr.isUsable() ? CondExpr.get() : Cond;
  5156. }
  5157. /// Build reference expression to the counter be used for codegen.
  5158. DeclRefExpr *OpenMPIterationSpaceChecker::buildCounterVar(
  5159. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
  5160. DSAStackTy &DSA) const {
  5161. auto *VD = dyn_cast<VarDecl>(LCDecl);
  5162. if (!VD) {
  5163. VD = SemaRef.isOpenMPCapturedDecl(LCDecl);
  5164. DeclRefExpr *Ref = buildDeclRefExpr(
  5165. SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
  5166. const DSAStackTy::DSAVarData Data =
  5167. DSA.getTopDSA(LCDecl, /*FromParent=*/false);
  5168. // If the loop control decl is explicitly marked as private, do not mark it
  5169. // as captured again.
  5170. if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
  5171. Captures.insert(std::make_pair(LCRef, Ref));
  5172. return Ref;
  5173. }
  5174. return cast<DeclRefExpr>(LCRef);
  5175. }
  5176. Expr *OpenMPIterationSpaceChecker::buildPrivateCounterVar() const {
  5177. if (LCDecl && !LCDecl->isInvalidDecl()) {
  5178. QualType Type = LCDecl->getType().getNonReferenceType();
  5179. VarDecl *PrivateVar = buildVarDecl(
  5180. SemaRef, DefaultLoc, Type, LCDecl->getName(),
  5181. LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr,
  5182. isa<VarDecl>(LCDecl)
  5183. ? buildDeclRefExpr(SemaRef, cast<VarDecl>(LCDecl), Type, DefaultLoc)
  5184. : nullptr);
  5185. if (PrivateVar->isInvalidDecl())
  5186. return nullptr;
  5187. return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
  5188. }
  5189. return nullptr;
  5190. }
  5191. /// Build initialization of the counter to be used for codegen.
  5192. Expr *OpenMPIterationSpaceChecker::buildCounterInit() const { return LB; }
  5193. /// Build step of the counter be used for codegen.
  5194. Expr *OpenMPIterationSpaceChecker::buildCounterStep() const { return Step; }
  5195. Expr *OpenMPIterationSpaceChecker::buildOrderedLoopData(
  5196. Scope *S, Expr *Counter,
  5197. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, SourceLocation Loc,
  5198. Expr *Inc, OverloadedOperatorKind OOK) {
  5199. Expr *Cnt = SemaRef.DefaultLvalueConversion(Counter).get();
  5200. if (!Cnt)
  5201. return nullptr;
  5202. if (Inc) {
  5203. assert((OOK == OO_Plus || OOK == OO_Minus) &&
  5204. "Expected only + or - operations for depend clauses.");
  5205. BinaryOperatorKind BOK = (OOK == OO_Plus) ? BO_Add : BO_Sub;
  5206. Cnt = SemaRef.BuildBinOp(S, Loc, BOK, Cnt, Inc).get();
  5207. if (!Cnt)
  5208. return nullptr;
  5209. }
  5210. ExprResult Diff;
  5211. QualType VarType = LCDecl->getType().getNonReferenceType();
  5212. if (VarType->isIntegerType() || VarType->isPointerType() ||
  5213. SemaRef.getLangOpts().CPlusPlus) {
  5214. // Upper - Lower
  5215. Expr *Upper = TestIsLessOp.getValue()
  5216. ? Cnt
  5217. : tryBuildCapture(SemaRef, UB, Captures).get();
  5218. Expr *Lower = TestIsLessOp.getValue()
  5219. ? tryBuildCapture(SemaRef, LB, Captures).get()
  5220. : Cnt;
  5221. if (!Upper || !Lower)
  5222. return nullptr;
  5223. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
  5224. if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
  5225. // BuildBinOp already emitted error, this one is to point user to upper
  5226. // and lower bound, and to tell what is passed to 'operator-'.
  5227. SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx)
  5228. << Upper->getSourceRange() << Lower->getSourceRange();
  5229. return nullptr;
  5230. }
  5231. }
  5232. if (!Diff.isUsable())
  5233. return nullptr;
  5234. // Parentheses (for dumping/debugging purposes only).
  5235. Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
  5236. if (!Diff.isUsable())
  5237. return nullptr;
  5238. ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
  5239. if (!NewStep.isUsable())
  5240. return nullptr;
  5241. // (Upper - Lower) / Step
  5242. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
  5243. if (!Diff.isUsable())
  5244. return nullptr;
  5245. return Diff.get();
  5246. }
  5247. /// Iteration space of a single for loop.
  5248. struct LoopIterationSpace final {
  5249. /// True if the condition operator is the strict compare operator (<, > or
  5250. /// !=).
  5251. bool IsStrictCompare = false;
  5252. /// Condition of the loop.
  5253. Expr *PreCond = nullptr;
  5254. /// This expression calculates the number of iterations in the loop.
  5255. /// It is always possible to calculate it before starting the loop.
  5256. Expr *NumIterations = nullptr;
  5257. /// The loop counter variable.
  5258. Expr *CounterVar = nullptr;
  5259. /// Private loop counter variable.
  5260. Expr *PrivateCounterVar = nullptr;
  5261. /// This is initializer for the initial value of #CounterVar.
  5262. Expr *CounterInit = nullptr;
  5263. /// This is step for the #CounterVar used to generate its update:
  5264. /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
  5265. Expr *CounterStep = nullptr;
  5266. /// Should step be subtracted?
  5267. bool Subtract = false;
  5268. /// Source range of the loop init.
  5269. SourceRange InitSrcRange;
  5270. /// Source range of the loop condition.
  5271. SourceRange CondSrcRange;
  5272. /// Source range of the loop increment.
  5273. SourceRange IncSrcRange;
  5274. };
  5275. } // namespace
  5276. void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
  5277. assert(getLangOpts().OpenMP && "OpenMP is not active.");
  5278. assert(Init && "Expected loop in canonical form.");
  5279. unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
  5280. if (AssociatedLoops > 0 &&
  5281. isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
  5282. DSAStack->loopStart();
  5283. OpenMPIterationSpaceChecker ISC(*this, *DSAStack, ForLoc);
  5284. if (!ISC.checkAndSetInit(Init, /*EmitDiags=*/false)) {
  5285. if (ValueDecl *D = ISC.getLoopDecl()) {
  5286. auto *VD = dyn_cast<VarDecl>(D);
  5287. if (!VD) {
  5288. if (VarDecl *Private = isOpenMPCapturedDecl(D)) {
  5289. VD = Private;
  5290. } else {
  5291. DeclRefExpr *Ref = buildCapture(*this, D, ISC.getLoopDeclRefExpr(),
  5292. /*WithInit=*/false);
  5293. VD = cast<VarDecl>(Ref->getDecl());
  5294. }
  5295. }
  5296. DSAStack->addLoopControlVariable(D, VD);
  5297. const Decl *LD = DSAStack->getPossiblyLoopCunter();
  5298. if (LD != D->getCanonicalDecl()) {
  5299. DSAStack->resetPossibleLoopCounter();
  5300. if (auto *Var = dyn_cast_or_null<VarDecl>(LD))
  5301. MarkDeclarationsReferencedInExpr(
  5302. buildDeclRefExpr(*this, const_cast<VarDecl *>(Var),
  5303. Var->getType().getNonLValueExprType(Context),
  5304. ForLoc, /*RefersToCapture=*/true));
  5305. }
  5306. }
  5307. }
  5308. DSAStack->setAssociatedLoops(AssociatedLoops - 1);
  5309. }
  5310. }
  5311. /// Called on a for stmt to check and extract its iteration space
  5312. /// for further processing (such as collapsing).
  5313. static bool checkOpenMPIterationSpace(
  5314. OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
  5315. unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
  5316. unsigned TotalNestedLoopCount, Expr *CollapseLoopCountExpr,
  5317. Expr *OrderedLoopCountExpr,
  5318. Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
  5319. LoopIterationSpace &ResultIterSpace,
  5320. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
  5321. // OpenMP [2.6, Canonical Loop Form]
  5322. // for (init-expr; test-expr; incr-expr) structured-block
  5323. auto *For = dyn_cast_or_null<ForStmt>(S);
  5324. if (!For) {
  5325. SemaRef.Diag(S->getBeginLoc(), diag::err_omp_not_for)
  5326. << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
  5327. << getOpenMPDirectiveName(DKind) << TotalNestedLoopCount
  5328. << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
  5329. if (TotalNestedLoopCount > 1) {
  5330. if (CollapseLoopCountExpr && OrderedLoopCountExpr)
  5331. SemaRef.Diag(DSA.getConstructLoc(),
  5332. diag::note_omp_collapse_ordered_expr)
  5333. << 2 << CollapseLoopCountExpr->getSourceRange()
  5334. << OrderedLoopCountExpr->getSourceRange();
  5335. else if (CollapseLoopCountExpr)
  5336. SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
  5337. diag::note_omp_collapse_ordered_expr)
  5338. << 0 << CollapseLoopCountExpr->getSourceRange();
  5339. else
  5340. SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
  5341. diag::note_omp_collapse_ordered_expr)
  5342. << 1 << OrderedLoopCountExpr->getSourceRange();
  5343. }
  5344. return true;
  5345. }
  5346. assert(For->getBody());
  5347. OpenMPIterationSpaceChecker ISC(SemaRef, DSA, For->getForLoc());
  5348. // Check init.
  5349. Stmt *Init = For->getInit();
  5350. if (ISC.checkAndSetInit(Init))
  5351. return true;
  5352. bool HasErrors = false;
  5353. // Check loop variable's type.
  5354. if (ValueDecl *LCDecl = ISC.getLoopDecl()) {
  5355. Expr *LoopDeclRefExpr = ISC.getLoopDeclRefExpr();
  5356. // OpenMP [2.6, Canonical Loop Form]
  5357. // Var is one of the following:
  5358. // A variable of signed or unsigned integer type.
  5359. // For C++, a variable of a random access iterator type.
  5360. // For C, a variable of a pointer type.
  5361. QualType VarType = LCDecl->getType().getNonReferenceType();
  5362. if (!VarType->isDependentType() && !VarType->isIntegerType() &&
  5363. !VarType->isPointerType() &&
  5364. !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
  5365. SemaRef.Diag(Init->getBeginLoc(), diag::err_omp_loop_variable_type)
  5366. << SemaRef.getLangOpts().CPlusPlus;
  5367. HasErrors = true;
  5368. }
  5369. // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
  5370. // a Construct
  5371. // The loop iteration variable(s) in the associated for-loop(s) of a for or
  5372. // parallel for construct is (are) private.
  5373. // The loop iteration variable in the associated for-loop of a simd
  5374. // construct with just one associated for-loop is linear with a
  5375. // constant-linear-step that is the increment of the associated for-loop.
  5376. // Exclude loop var from the list of variables with implicitly defined data
  5377. // sharing attributes.
  5378. VarsWithImplicitDSA.erase(LCDecl);
  5379. // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
  5380. // in a Construct, C/C++].
  5381. // The loop iteration variable in the associated for-loop of a simd
  5382. // construct with just one associated for-loop may be listed in a linear
  5383. // clause with a constant-linear-step that is the increment of the
  5384. // associated for-loop.
  5385. // The loop iteration variable(s) in the associated for-loop(s) of a for or
  5386. // parallel for construct may be listed in a private or lastprivate clause.
  5387. DSAStackTy::DSAVarData DVar = DSA.getTopDSA(LCDecl, false);
  5388. // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
  5389. // declared in the loop and it is predetermined as a private.
  5390. OpenMPClauseKind PredeterminedCKind =
  5391. isOpenMPSimdDirective(DKind)
  5392. ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
  5393. : OMPC_private;
  5394. if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
  5395. DVar.CKind != PredeterminedCKind && DVar.RefExpr &&
  5396. (SemaRef.getLangOpts().OpenMP <= 45 ||
  5397. (DVar.CKind != OMPC_lastprivate && DVar.CKind != OMPC_private))) ||
  5398. ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
  5399. isOpenMPDistributeDirective(DKind)) &&
  5400. !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
  5401. DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
  5402. (DVar.CKind != OMPC_private || DVar.RefExpr)) {
  5403. SemaRef.Diag(Init->getBeginLoc(), diag::err_omp_loop_var_dsa)
  5404. << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
  5405. << getOpenMPClauseName(PredeterminedCKind);
  5406. if (DVar.RefExpr == nullptr)
  5407. DVar.CKind = PredeterminedCKind;
  5408. reportOriginalDsa(SemaRef, &DSA, LCDecl, DVar, /*IsLoopIterVar=*/true);
  5409. HasErrors = true;
  5410. } else if (LoopDeclRefExpr != nullptr) {
  5411. // Make the loop iteration variable private (for worksharing constructs),
  5412. // linear (for simd directives with the only one associated loop) or
  5413. // lastprivate (for simd directives with several collapsed or ordered
  5414. // loops).
  5415. if (DVar.CKind == OMPC_unknown)
  5416. DSA.addDSA(LCDecl, LoopDeclRefExpr, PredeterminedCKind);
  5417. }
  5418. assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
  5419. // Check test-expr.
  5420. HasErrors |= ISC.checkAndSetCond(For->getCond());
  5421. // Check incr-expr.
  5422. HasErrors |= ISC.checkAndSetInc(For->getInc());
  5423. }
  5424. if (ISC.dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
  5425. return HasErrors;
  5426. // Build the loop's iteration space representation.
  5427. ResultIterSpace.PreCond =
  5428. ISC.buildPreCond(DSA.getCurScope(), For->getCond(), Captures);
  5429. ResultIterSpace.NumIterations = ISC.buildNumIterations(
  5430. DSA.getCurScope(),
  5431. (isOpenMPWorksharingDirective(DKind) ||
  5432. isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)),
  5433. Captures);
  5434. ResultIterSpace.CounterVar = ISC.buildCounterVar(Captures, DSA);
  5435. ResultIterSpace.PrivateCounterVar = ISC.buildPrivateCounterVar();
  5436. ResultIterSpace.CounterInit = ISC.buildCounterInit();
  5437. ResultIterSpace.CounterStep = ISC.buildCounterStep();
  5438. ResultIterSpace.InitSrcRange = ISC.getInitSrcRange();
  5439. ResultIterSpace.CondSrcRange = ISC.getConditionSrcRange();
  5440. ResultIterSpace.IncSrcRange = ISC.getIncrementSrcRange();
  5441. ResultIterSpace.Subtract = ISC.shouldSubtractStep();
  5442. ResultIterSpace.IsStrictCompare = ISC.isStrictTestOp();
  5443. HasErrors |= (ResultIterSpace.PreCond == nullptr ||
  5444. ResultIterSpace.NumIterations == nullptr ||
  5445. ResultIterSpace.CounterVar == nullptr ||
  5446. ResultIterSpace.PrivateCounterVar == nullptr ||
  5447. ResultIterSpace.CounterInit == nullptr ||
  5448. ResultIterSpace.CounterStep == nullptr);
  5449. if (!HasErrors && DSA.isOrderedRegion()) {
  5450. if (DSA.getOrderedRegionParam().second->getNumForLoops()) {
  5451. if (CurrentNestedLoopCount <
  5452. DSA.getOrderedRegionParam().second->getLoopNumIterations().size()) {
  5453. DSA.getOrderedRegionParam().second->setLoopNumIterations(
  5454. CurrentNestedLoopCount, ResultIterSpace.NumIterations);
  5455. DSA.getOrderedRegionParam().second->setLoopCounter(
  5456. CurrentNestedLoopCount, ResultIterSpace.CounterVar);
  5457. }
  5458. }
  5459. for (auto &Pair : DSA.getDoacrossDependClauses()) {
  5460. if (CurrentNestedLoopCount >= Pair.first->getNumLoops()) {
  5461. // Erroneous case - clause has some problems.
  5462. continue;
  5463. }
  5464. if (Pair.first->getDependencyKind() == OMPC_DEPEND_sink &&
  5465. Pair.second.size() <= CurrentNestedLoopCount) {
  5466. // Erroneous case - clause has some problems.
  5467. Pair.first->setLoopData(CurrentNestedLoopCount, nullptr);
  5468. continue;
  5469. }
  5470. Expr *CntValue;
  5471. if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
  5472. CntValue = ISC.buildOrderedLoopData(
  5473. DSA.getCurScope(), ResultIterSpace.CounterVar, Captures,
  5474. Pair.first->getDependencyLoc());
  5475. else
  5476. CntValue = ISC.buildOrderedLoopData(
  5477. DSA.getCurScope(), ResultIterSpace.CounterVar, Captures,
  5478. Pair.first->getDependencyLoc(),
  5479. Pair.second[CurrentNestedLoopCount].first,
  5480. Pair.second[CurrentNestedLoopCount].second);
  5481. Pair.first->setLoopData(CurrentNestedLoopCount, CntValue);
  5482. }
  5483. }
  5484. return HasErrors;
  5485. }
  5486. /// Build 'VarRef = Start.
  5487. static ExprResult
  5488. buildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
  5489. ExprResult Start,
  5490. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
  5491. // Build 'VarRef = Start.
  5492. ExprResult NewStart = tryBuildCapture(SemaRef, Start.get(), Captures);
  5493. if (!NewStart.isUsable())
  5494. return ExprError();
  5495. if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
  5496. VarRef.get()->getType())) {
  5497. NewStart = SemaRef.PerformImplicitConversion(
  5498. NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
  5499. /*AllowExplicit=*/true);
  5500. if (!NewStart.isUsable())
  5501. return ExprError();
  5502. }
  5503. ExprResult Init =
  5504. SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
  5505. return Init;
  5506. }
  5507. /// Build 'VarRef = Start + Iter * Step'.
  5508. static ExprResult buildCounterUpdate(
  5509. Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
  5510. ExprResult Start, ExprResult Iter, ExprResult Step, bool Subtract,
  5511. llvm::MapVector<const Expr *, DeclRefExpr *> *Captures = nullptr) {
  5512. // Add parentheses (for debugging purposes only).
  5513. Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
  5514. if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
  5515. !Step.isUsable())
  5516. return ExprError();
  5517. ExprResult NewStep = Step;
  5518. if (Captures)
  5519. NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
  5520. if (NewStep.isInvalid())
  5521. return ExprError();
  5522. ExprResult Update =
  5523. SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
  5524. if (!Update.isUsable())
  5525. return ExprError();
  5526. // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
  5527. // 'VarRef = Start (+|-) Iter * Step'.
  5528. ExprResult NewStart = Start;
  5529. if (Captures)
  5530. NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
  5531. if (NewStart.isInvalid())
  5532. return ExprError();
  5533. // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
  5534. ExprResult SavedUpdate = Update;
  5535. ExprResult UpdateVal;
  5536. if (VarRef.get()->getType()->isOverloadableType() ||
  5537. NewStart.get()->getType()->isOverloadableType() ||
  5538. Update.get()->getType()->isOverloadableType()) {
  5539. bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
  5540. SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
  5541. Update =
  5542. SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
  5543. if (Update.isUsable()) {
  5544. UpdateVal =
  5545. SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
  5546. VarRef.get(), SavedUpdate.get());
  5547. if (UpdateVal.isUsable()) {
  5548. Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
  5549. UpdateVal.get());
  5550. }
  5551. }
  5552. SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
  5553. }
  5554. // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
  5555. if (!Update.isUsable() || !UpdateVal.isUsable()) {
  5556. Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
  5557. NewStart.get(), SavedUpdate.get());
  5558. if (!Update.isUsable())
  5559. return ExprError();
  5560. if (!SemaRef.Context.hasSameType(Update.get()->getType(),
  5561. VarRef.get()->getType())) {
  5562. Update = SemaRef.PerformImplicitConversion(
  5563. Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
  5564. if (!Update.isUsable())
  5565. return ExprError();
  5566. }
  5567. Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
  5568. }
  5569. return Update;
  5570. }
  5571. /// Convert integer expression \a E to make it have at least \a Bits
  5572. /// bits.
  5573. static ExprResult widenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
  5574. if (E == nullptr)
  5575. return ExprError();
  5576. ASTContext &C = SemaRef.Context;
  5577. QualType OldType = E->getType();
  5578. unsigned HasBits = C.getTypeSize(OldType);
  5579. if (HasBits >= Bits)
  5580. return ExprResult(E);
  5581. // OK to convert to signed, because new type has more bits than old.
  5582. QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
  5583. return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
  5584. true);
  5585. }
  5586. /// Check if the given expression \a E is a constant integer that fits
  5587. /// into \a Bits bits.
  5588. static bool fitsInto(unsigned Bits, bool Signed, const Expr *E, Sema &SemaRef) {
  5589. if (E == nullptr)
  5590. return false;
  5591. llvm::APSInt Result;
  5592. if (E->isIntegerConstantExpr(Result, SemaRef.Context))
  5593. return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
  5594. return false;
  5595. }
  5596. /// Build preinits statement for the given declarations.
  5597. static Stmt *buildPreInits(ASTContext &Context,
  5598. MutableArrayRef<Decl *> PreInits) {
  5599. if (!PreInits.empty()) {
  5600. return new (Context) DeclStmt(
  5601. DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
  5602. SourceLocation(), SourceLocation());
  5603. }
  5604. return nullptr;
  5605. }
  5606. /// Build preinits statement for the given declarations.
  5607. static Stmt *
  5608. buildPreInits(ASTContext &Context,
  5609. const llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
  5610. if (!Captures.empty()) {
  5611. SmallVector<Decl *, 16> PreInits;
  5612. for (const auto &Pair : Captures)
  5613. PreInits.push_back(Pair.second->getDecl());
  5614. return buildPreInits(Context, PreInits);
  5615. }
  5616. return nullptr;
  5617. }
  5618. /// Build postupdate expression for the given list of postupdates expressions.
  5619. static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
  5620. Expr *PostUpdate = nullptr;
  5621. if (!PostUpdates.empty()) {
  5622. for (Expr *E : PostUpdates) {
  5623. Expr *ConvE = S.BuildCStyleCastExpr(
  5624. E->getExprLoc(),
  5625. S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
  5626. E->getExprLoc(), E)
  5627. .get();
  5628. PostUpdate = PostUpdate
  5629. ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
  5630. PostUpdate, ConvE)
  5631. .get()
  5632. : ConvE;
  5633. }
  5634. }
  5635. return PostUpdate;
  5636. }
  5637. /// Called on a for stmt to check itself and nested loops (if any).
  5638. /// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
  5639. /// number of collapsed loops otherwise.
  5640. static unsigned
  5641. checkOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
  5642. Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
  5643. DSAStackTy &DSA,
  5644. Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
  5645. OMPLoopDirective::HelperExprs &Built) {
  5646. unsigned NestedLoopCount = 1;
  5647. if (CollapseLoopCountExpr) {
  5648. // Found 'collapse' clause - calculate collapse number.
  5649. Expr::EvalResult Result;
  5650. if (!CollapseLoopCountExpr->isValueDependent() &&
  5651. CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) {
  5652. NestedLoopCount = Result.Val.getInt().getLimitedValue();
  5653. } else {
  5654. Built.clear(/*size=*/1);
  5655. return 1;
  5656. }
  5657. }
  5658. unsigned OrderedLoopCount = 1;
  5659. if (OrderedLoopCountExpr) {
  5660. // Found 'ordered' clause - calculate collapse number.
  5661. Expr::EvalResult EVResult;
  5662. if (!OrderedLoopCountExpr->isValueDependent() &&
  5663. OrderedLoopCountExpr->EvaluateAsInt(EVResult,
  5664. SemaRef.getASTContext())) {
  5665. llvm::APSInt Result = EVResult.Val.getInt();
  5666. if (Result.getLimitedValue() < NestedLoopCount) {
  5667. SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
  5668. diag::err_omp_wrong_ordered_loop_count)
  5669. << OrderedLoopCountExpr->getSourceRange();
  5670. SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
  5671. diag::note_collapse_loop_count)
  5672. << CollapseLoopCountExpr->getSourceRange();
  5673. }
  5674. OrderedLoopCount = Result.getLimitedValue();
  5675. } else {
  5676. Built.clear(/*size=*/1);
  5677. return 1;
  5678. }
  5679. }
  5680. // This is helper routine for loop directives (e.g., 'for', 'simd',
  5681. // 'for simd', etc.).
  5682. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  5683. SmallVector<LoopIterationSpace, 4> IterSpaces(
  5684. std::max(OrderedLoopCount, NestedLoopCount));
  5685. Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
  5686. for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
  5687. if (checkOpenMPIterationSpace(
  5688. DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
  5689. std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr,
  5690. OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces[Cnt],
  5691. Captures))
  5692. return 0;
  5693. // Move on to the next nested for loop, or to the loop body.
  5694. // OpenMP [2.8.1, simd construct, Restrictions]
  5695. // All loops associated with the construct must be perfectly nested; that
  5696. // is, there must be no intervening code nor any OpenMP directive between
  5697. // any two loops.
  5698. CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
  5699. }
  5700. for (unsigned Cnt = NestedLoopCount; Cnt < OrderedLoopCount; ++Cnt) {
  5701. if (checkOpenMPIterationSpace(
  5702. DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
  5703. std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr,
  5704. OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces[Cnt],
  5705. Captures))
  5706. return 0;
  5707. if (Cnt > 0 && IterSpaces[Cnt].CounterVar) {
  5708. // Handle initialization of captured loop iterator variables.
  5709. auto *DRE = cast<DeclRefExpr>(IterSpaces[Cnt].CounterVar);
  5710. if (isa<OMPCapturedExprDecl>(DRE->getDecl())) {
  5711. Captures[DRE] = DRE;
  5712. }
  5713. }
  5714. // Move on to the next nested for loop, or to the loop body.
  5715. // OpenMP [2.8.1, simd construct, Restrictions]
  5716. // All loops associated with the construct must be perfectly nested; that
  5717. // is, there must be no intervening code nor any OpenMP directive between
  5718. // any two loops.
  5719. CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
  5720. }
  5721. Built.clear(/* size */ NestedLoopCount);
  5722. if (SemaRef.CurContext->isDependentContext())
  5723. return NestedLoopCount;
  5724. // An example of what is generated for the following code:
  5725. //
  5726. // #pragma omp simd collapse(2) ordered(2)
  5727. // for (i = 0; i < NI; ++i)
  5728. // for (k = 0; k < NK; ++k)
  5729. // for (j = J0; j < NJ; j+=2) {
  5730. // <loop body>
  5731. // }
  5732. //
  5733. // We generate the code below.
  5734. // Note: the loop body may be outlined in CodeGen.
  5735. // Note: some counters may be C++ classes, operator- is used to find number of
  5736. // iterations and operator+= to calculate counter value.
  5737. // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
  5738. // or i64 is currently supported).
  5739. //
  5740. // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
  5741. // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
  5742. // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
  5743. // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
  5744. // // similar updates for vars in clauses (e.g. 'linear')
  5745. // <loop body (using local i and j)>
  5746. // }
  5747. // i = NI; // assign final values of counters
  5748. // j = NJ;
  5749. //
  5750. // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
  5751. // the iteration counts of the collapsed for loops.
  5752. // Precondition tests if there is at least one iteration (all conditions are
  5753. // true).
  5754. auto PreCond = ExprResult(IterSpaces[0].PreCond);
  5755. Expr *N0 = IterSpaces[0].NumIterations;
  5756. ExprResult LastIteration32 =
  5757. widenIterationCount(/*Bits=*/32,
  5758. SemaRef
  5759. .PerformImplicitConversion(
  5760. N0->IgnoreImpCasts(), N0->getType(),
  5761. Sema::AA_Converting, /*AllowExplicit=*/true)
  5762. .get(),
  5763. SemaRef);
  5764. ExprResult LastIteration64 = widenIterationCount(
  5765. /*Bits=*/64,
  5766. SemaRef
  5767. .PerformImplicitConversion(N0->IgnoreImpCasts(), N0->getType(),
  5768. Sema::AA_Converting,
  5769. /*AllowExplicit=*/true)
  5770. .get(),
  5771. SemaRef);
  5772. if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
  5773. return NestedLoopCount;
  5774. ASTContext &C = SemaRef.Context;
  5775. bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
  5776. Scope *CurScope = DSA.getCurScope();
  5777. for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
  5778. if (PreCond.isUsable()) {
  5779. PreCond =
  5780. SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
  5781. PreCond.get(), IterSpaces[Cnt].PreCond);
  5782. }
  5783. Expr *N = IterSpaces[Cnt].NumIterations;
  5784. SourceLocation Loc = N->getExprLoc();
  5785. AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
  5786. if (LastIteration32.isUsable())
  5787. LastIteration32 = SemaRef.BuildBinOp(
  5788. CurScope, Loc, BO_Mul, LastIteration32.get(),
  5789. SemaRef
  5790. .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
  5791. Sema::AA_Converting,
  5792. /*AllowExplicit=*/true)
  5793. .get());
  5794. if (LastIteration64.isUsable())
  5795. LastIteration64 = SemaRef.BuildBinOp(
  5796. CurScope, Loc, BO_Mul, LastIteration64.get(),
  5797. SemaRef
  5798. .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
  5799. Sema::AA_Converting,
  5800. /*AllowExplicit=*/true)
  5801. .get());
  5802. }
  5803. // Choose either the 32-bit or 64-bit version.
  5804. ExprResult LastIteration = LastIteration64;
  5805. if (SemaRef.getLangOpts().OpenMPOptimisticCollapse ||
  5806. (LastIteration32.isUsable() &&
  5807. C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
  5808. (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
  5809. fitsInto(
  5810. /*Bits=*/32,
  5811. LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
  5812. LastIteration64.get(), SemaRef))))
  5813. LastIteration = LastIteration32;
  5814. QualType VType = LastIteration.get()->getType();
  5815. QualType RealVType = VType;
  5816. QualType StrideVType = VType;
  5817. if (isOpenMPTaskLoopDirective(DKind)) {
  5818. VType =
  5819. SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
  5820. StrideVType =
  5821. SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
  5822. }
  5823. if (!LastIteration.isUsable())
  5824. return 0;
  5825. // Save the number of iterations.
  5826. ExprResult NumIterations = LastIteration;
  5827. {
  5828. LastIteration = SemaRef.BuildBinOp(
  5829. CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
  5830. LastIteration.get(),
  5831. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
  5832. if (!LastIteration.isUsable())
  5833. return 0;
  5834. }
  5835. // Calculate the last iteration number beforehand instead of doing this on
  5836. // each iteration. Do not do this if the number of iterations may be kfold-ed.
  5837. llvm::APSInt Result;
  5838. bool IsConstant =
  5839. LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
  5840. ExprResult CalcLastIteration;
  5841. if (!IsConstant) {
  5842. ExprResult SaveRef =
  5843. tryBuildCapture(SemaRef, LastIteration.get(), Captures);
  5844. LastIteration = SaveRef;
  5845. // Prepare SaveRef + 1.
  5846. NumIterations = SemaRef.BuildBinOp(
  5847. CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
  5848. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
  5849. if (!NumIterations.isUsable())
  5850. return 0;
  5851. }
  5852. SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
  5853. // Build variables passed into runtime, necessary for worksharing directives.
  5854. ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB;
  5855. if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
  5856. isOpenMPDistributeDirective(DKind)) {
  5857. // Lower bound variable, initialized with zero.
  5858. VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
  5859. LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
  5860. SemaRef.AddInitializerToDecl(LBDecl,
  5861. SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
  5862. /*DirectInit*/ false);
  5863. // Upper bound variable, initialized with last iteration number.
  5864. VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
  5865. UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
  5866. SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
  5867. /*DirectInit*/ false);
  5868. // A 32-bit variable-flag where runtime returns 1 for the last iteration.
  5869. // This will be used to implement clause 'lastprivate'.
  5870. QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
  5871. VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
  5872. IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
  5873. SemaRef.AddInitializerToDecl(ILDecl,
  5874. SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
  5875. /*DirectInit*/ false);
  5876. // Stride variable returned by runtime (we initialize it to 1 by default).
  5877. VarDecl *STDecl =
  5878. buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
  5879. ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
  5880. SemaRef.AddInitializerToDecl(STDecl,
  5881. SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
  5882. /*DirectInit*/ false);
  5883. // Build expression: UB = min(UB, LastIteration)
  5884. // It is necessary for CodeGen of directives with static scheduling.
  5885. ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
  5886. UB.get(), LastIteration.get());
  5887. ExprResult CondOp = SemaRef.ActOnConditionalOp(
  5888. LastIteration.get()->getExprLoc(), InitLoc, IsUBGreater.get(),
  5889. LastIteration.get(), UB.get());
  5890. EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
  5891. CondOp.get());
  5892. EUB = SemaRef.ActOnFinishFullExpr(EUB.get(), /*DiscardedValue*/ false);
  5893. // If we have a combined directive that combines 'distribute', 'for' or
  5894. // 'simd' we need to be able to access the bounds of the schedule of the
  5895. // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
  5896. // by scheduling 'distribute' have to be passed to the schedule of 'for'.
  5897. if (isOpenMPLoopBoundSharingDirective(DKind)) {
  5898. // Lower bound variable, initialized with zero.
  5899. VarDecl *CombLBDecl =
  5900. buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb");
  5901. CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc);
  5902. SemaRef.AddInitializerToDecl(
  5903. CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
  5904. /*DirectInit*/ false);
  5905. // Upper bound variable, initialized with last iteration number.
  5906. VarDecl *CombUBDecl =
  5907. buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub");
  5908. CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc);
  5909. SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(),
  5910. /*DirectInit*/ false);
  5911. ExprResult CombIsUBGreater = SemaRef.BuildBinOp(
  5912. CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get());
  5913. ExprResult CombCondOp =
  5914. SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(),
  5915. LastIteration.get(), CombUB.get());
  5916. CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(),
  5917. CombCondOp.get());
  5918. CombEUB =
  5919. SemaRef.ActOnFinishFullExpr(CombEUB.get(), /*DiscardedValue*/ false);
  5920. const CapturedDecl *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
  5921. // We expect to have at least 2 more parameters than the 'parallel'
  5922. // directive does - the lower and upper bounds of the previous schedule.
  5923. assert(CD->getNumParams() >= 4 &&
  5924. "Unexpected number of parameters in loop combined directive");
  5925. // Set the proper type for the bounds given what we learned from the
  5926. // enclosed loops.
  5927. ImplicitParamDecl *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
  5928. ImplicitParamDecl *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
  5929. // Previous lower and upper bounds are obtained from the region
  5930. // parameters.
  5931. PrevLB =
  5932. buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
  5933. PrevUB =
  5934. buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
  5935. }
  5936. }
  5937. // Build the iteration variable and its initialization before loop.
  5938. ExprResult IV;
  5939. ExprResult Init, CombInit;
  5940. {
  5941. VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
  5942. IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
  5943. Expr *RHS =
  5944. (isOpenMPWorksharingDirective(DKind) ||
  5945. isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
  5946. ? LB.get()
  5947. : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
  5948. Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
  5949. Init = SemaRef.ActOnFinishFullExpr(Init.get(), /*DiscardedValue*/ false);
  5950. if (isOpenMPLoopBoundSharingDirective(DKind)) {
  5951. Expr *CombRHS =
  5952. (isOpenMPWorksharingDirective(DKind) ||
  5953. isOpenMPTaskLoopDirective(DKind) ||
  5954. isOpenMPDistributeDirective(DKind))
  5955. ? CombLB.get()
  5956. : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
  5957. CombInit =
  5958. SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS);
  5959. CombInit =
  5960. SemaRef.ActOnFinishFullExpr(CombInit.get(), /*DiscardedValue*/ false);
  5961. }
  5962. }
  5963. bool UseStrictCompare =
  5964. RealVType->hasUnsignedIntegerRepresentation() &&
  5965. llvm::all_of(IterSpaces, [](const LoopIterationSpace &LIS) {
  5966. return LIS.IsStrictCompare;
  5967. });
  5968. // Loop condition (IV < NumIterations) or (IV <= UB or IV < UB + 1 (for
  5969. // unsigned IV)) for worksharing loops.
  5970. SourceLocation CondLoc = AStmt->getBeginLoc();
  5971. Expr *BoundUB = UB.get();
  5972. if (UseStrictCompare) {
  5973. BoundUB =
  5974. SemaRef
  5975. .BuildBinOp(CurScope, CondLoc, BO_Add, BoundUB,
  5976. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
  5977. .get();
  5978. BoundUB =
  5979. SemaRef.ActOnFinishFullExpr(BoundUB, /*DiscardedValue*/ false).get();
  5980. }
  5981. ExprResult Cond =
  5982. (isOpenMPWorksharingDirective(DKind) ||
  5983. isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
  5984. ? SemaRef.BuildBinOp(CurScope, CondLoc,
  5985. UseStrictCompare ? BO_LT : BO_LE, IV.get(),
  5986. BoundUB)
  5987. : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
  5988. NumIterations.get());
  5989. ExprResult CombDistCond;
  5990. if (isOpenMPLoopBoundSharingDirective(DKind)) {
  5991. CombDistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
  5992. NumIterations.get());
  5993. }
  5994. ExprResult CombCond;
  5995. if (isOpenMPLoopBoundSharingDirective(DKind)) {
  5996. Expr *BoundCombUB = CombUB.get();
  5997. if (UseStrictCompare) {
  5998. BoundCombUB =
  5999. SemaRef
  6000. .BuildBinOp(
  6001. CurScope, CondLoc, BO_Add, BoundCombUB,
  6002. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
  6003. .get();
  6004. BoundCombUB =
  6005. SemaRef.ActOnFinishFullExpr(BoundCombUB, /*DiscardedValue*/ false)
  6006. .get();
  6007. }
  6008. CombCond =
  6009. SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
  6010. IV.get(), BoundCombUB);
  6011. }
  6012. // Loop increment (IV = IV + 1)
  6013. SourceLocation IncLoc = AStmt->getBeginLoc();
  6014. ExprResult Inc =
  6015. SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
  6016. SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
  6017. if (!Inc.isUsable())
  6018. return 0;
  6019. Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
  6020. Inc = SemaRef.ActOnFinishFullExpr(Inc.get(), /*DiscardedValue*/ false);
  6021. if (!Inc.isUsable())
  6022. return 0;
  6023. // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
  6024. // Used for directives with static scheduling.
  6025. // In combined construct, add combined version that use CombLB and CombUB
  6026. // base variables for the update
  6027. ExprResult NextLB, NextUB, CombNextLB, CombNextUB;
  6028. if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
  6029. isOpenMPDistributeDirective(DKind)) {
  6030. // LB + ST
  6031. NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
  6032. if (!NextLB.isUsable())
  6033. return 0;
  6034. // LB = LB + ST
  6035. NextLB =
  6036. SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
  6037. NextLB =
  6038. SemaRef.ActOnFinishFullExpr(NextLB.get(), /*DiscardedValue*/ false);
  6039. if (!NextLB.isUsable())
  6040. return 0;
  6041. // UB + ST
  6042. NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
  6043. if (!NextUB.isUsable())
  6044. return 0;
  6045. // UB = UB + ST
  6046. NextUB =
  6047. SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
  6048. NextUB =
  6049. SemaRef.ActOnFinishFullExpr(NextUB.get(), /*DiscardedValue*/ false);
  6050. if (!NextUB.isUsable())
  6051. return 0;
  6052. if (isOpenMPLoopBoundSharingDirective(DKind)) {
  6053. CombNextLB =
  6054. SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get());
  6055. if (!NextLB.isUsable())
  6056. return 0;
  6057. // LB = LB + ST
  6058. CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(),
  6059. CombNextLB.get());
  6060. CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get(),
  6061. /*DiscardedValue*/ false);
  6062. if (!CombNextLB.isUsable())
  6063. return 0;
  6064. // UB + ST
  6065. CombNextUB =
  6066. SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get());
  6067. if (!CombNextUB.isUsable())
  6068. return 0;
  6069. // UB = UB + ST
  6070. CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(),
  6071. CombNextUB.get());
  6072. CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get(),
  6073. /*DiscardedValue*/ false);
  6074. if (!CombNextUB.isUsable())
  6075. return 0;
  6076. }
  6077. }
  6078. // Create increment expression for distribute loop when combined in a same
  6079. // directive with for as IV = IV + ST; ensure upper bound expression based
  6080. // on PrevUB instead of NumIterations - used to implement 'for' when found
  6081. // in combination with 'distribute', like in 'distribute parallel for'
  6082. SourceLocation DistIncLoc = AStmt->getBeginLoc();
  6083. ExprResult DistCond, DistInc, PrevEUB, ParForInDistCond;
  6084. if (isOpenMPLoopBoundSharingDirective(DKind)) {
  6085. DistCond = SemaRef.BuildBinOp(
  6086. CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE, IV.get(), BoundUB);
  6087. assert(DistCond.isUsable() && "distribute cond expr was not built");
  6088. DistInc =
  6089. SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get());
  6090. assert(DistInc.isUsable() && "distribute inc expr was not built");
  6091. DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(),
  6092. DistInc.get());
  6093. DistInc =
  6094. SemaRef.ActOnFinishFullExpr(DistInc.get(), /*DiscardedValue*/ false);
  6095. assert(DistInc.isUsable() && "distribute inc expr was not built");
  6096. // Build expression: UB = min(UB, prevUB) for #for in composite or combined
  6097. // construct
  6098. SourceLocation DistEUBLoc = AStmt->getBeginLoc();
  6099. ExprResult IsUBGreater =
  6100. SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, UB.get(), PrevUB.get());
  6101. ExprResult CondOp = SemaRef.ActOnConditionalOp(
  6102. DistEUBLoc, DistEUBLoc, IsUBGreater.get(), PrevUB.get(), UB.get());
  6103. PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(),
  6104. CondOp.get());
  6105. PrevEUB =
  6106. SemaRef.ActOnFinishFullExpr(PrevEUB.get(), /*DiscardedValue*/ false);
  6107. // Build IV <= PrevUB or IV < PrevUB + 1 for unsigned IV to be used in
  6108. // parallel for is in combination with a distribute directive with
  6109. // schedule(static, 1)
  6110. Expr *BoundPrevUB = PrevUB.get();
  6111. if (UseStrictCompare) {
  6112. BoundPrevUB =
  6113. SemaRef
  6114. .BuildBinOp(
  6115. CurScope, CondLoc, BO_Add, BoundPrevUB,
  6116. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
  6117. .get();
  6118. BoundPrevUB =
  6119. SemaRef.ActOnFinishFullExpr(BoundPrevUB, /*DiscardedValue*/ false)
  6120. .get();
  6121. }
  6122. ParForInDistCond =
  6123. SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
  6124. IV.get(), BoundPrevUB);
  6125. }
  6126. // Build updates and final values of the loop counters.
  6127. bool HasErrors = false;
  6128. Built.Counters.resize(NestedLoopCount);
  6129. Built.Inits.resize(NestedLoopCount);
  6130. Built.Updates.resize(NestedLoopCount);
  6131. Built.Finals.resize(NestedLoopCount);
  6132. {
  6133. // We implement the following algorithm for obtaining the
  6134. // original loop iteration variable values based on the
  6135. // value of the collapsed loop iteration variable IV.
  6136. //
  6137. // Let n+1 be the number of collapsed loops in the nest.
  6138. // Iteration variables (I0, I1, .... In)
  6139. // Iteration counts (N0, N1, ... Nn)
  6140. //
  6141. // Acc = IV;
  6142. //
  6143. // To compute Ik for loop k, 0 <= k <= n, generate:
  6144. // Prod = N(k+1) * N(k+2) * ... * Nn;
  6145. // Ik = Acc / Prod;
  6146. // Acc -= Ik * Prod;
  6147. //
  6148. ExprResult Acc = IV;
  6149. for (unsigned int Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
  6150. LoopIterationSpace &IS = IterSpaces[Cnt];
  6151. SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
  6152. ExprResult Iter;
  6153. // Compute prod
  6154. ExprResult Prod =
  6155. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
  6156. for (unsigned int K = Cnt+1; K < NestedLoopCount; ++K)
  6157. Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Prod.get(),
  6158. IterSpaces[K].NumIterations);
  6159. // Iter = Acc / Prod
  6160. // If there is at least one more inner loop to avoid
  6161. // multiplication by 1.
  6162. if (Cnt + 1 < NestedLoopCount)
  6163. Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div,
  6164. Acc.get(), Prod.get());
  6165. else
  6166. Iter = Acc;
  6167. if (!Iter.isUsable()) {
  6168. HasErrors = true;
  6169. break;
  6170. }
  6171. // Update Acc:
  6172. // Acc -= Iter * Prod
  6173. // Check if there is at least one more inner loop to avoid
  6174. // multiplication by 1.
  6175. if (Cnt + 1 < NestedLoopCount)
  6176. Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul,
  6177. Iter.get(), Prod.get());
  6178. else
  6179. Prod = Iter;
  6180. Acc = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Sub,
  6181. Acc.get(), Prod.get());
  6182. // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
  6183. auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
  6184. DeclRefExpr *CounterVar = buildDeclRefExpr(
  6185. SemaRef, VD, IS.CounterVar->getType(), IS.CounterVar->getExprLoc(),
  6186. /*RefersToCapture=*/true);
  6187. ExprResult Init = buildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
  6188. IS.CounterInit, Captures);
  6189. if (!Init.isUsable()) {
  6190. HasErrors = true;
  6191. break;
  6192. }
  6193. ExprResult Update = buildCounterUpdate(
  6194. SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
  6195. IS.CounterStep, IS.Subtract, &Captures);
  6196. if (!Update.isUsable()) {
  6197. HasErrors = true;
  6198. break;
  6199. }
  6200. // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
  6201. ExprResult Final = buildCounterUpdate(
  6202. SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit,
  6203. IS.NumIterations, IS.CounterStep, IS.Subtract, &Captures);
  6204. if (!Final.isUsable()) {
  6205. HasErrors = true;
  6206. break;
  6207. }
  6208. if (!Update.isUsable() || !Final.isUsable()) {
  6209. HasErrors = true;
  6210. break;
  6211. }
  6212. // Save results
  6213. Built.Counters[Cnt] = IS.CounterVar;
  6214. Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
  6215. Built.Inits[Cnt] = Init.get();
  6216. Built.Updates[Cnt] = Update.get();
  6217. Built.Finals[Cnt] = Final.get();
  6218. }
  6219. }
  6220. if (HasErrors)
  6221. return 0;
  6222. // Save results
  6223. Built.IterationVarRef = IV.get();
  6224. Built.LastIteration = LastIteration.get();
  6225. Built.NumIterations = NumIterations.get();
  6226. Built.CalcLastIteration = SemaRef
  6227. .ActOnFinishFullExpr(CalcLastIteration.get(),
  6228. /*DiscardedValue*/ false)
  6229. .get();
  6230. Built.PreCond = PreCond.get();
  6231. Built.PreInits = buildPreInits(C, Captures);
  6232. Built.Cond = Cond.get();
  6233. Built.Init = Init.get();
  6234. Built.Inc = Inc.get();
  6235. Built.LB = LB.get();
  6236. Built.UB = UB.get();
  6237. Built.IL = IL.get();
  6238. Built.ST = ST.get();
  6239. Built.EUB = EUB.get();
  6240. Built.NLB = NextLB.get();
  6241. Built.NUB = NextUB.get();
  6242. Built.PrevLB = PrevLB.get();
  6243. Built.PrevUB = PrevUB.get();
  6244. Built.DistInc = DistInc.get();
  6245. Built.PrevEUB = PrevEUB.get();
  6246. Built.DistCombinedFields.LB = CombLB.get();
  6247. Built.DistCombinedFields.UB = CombUB.get();
  6248. Built.DistCombinedFields.EUB = CombEUB.get();
  6249. Built.DistCombinedFields.Init = CombInit.get();
  6250. Built.DistCombinedFields.Cond = CombCond.get();
  6251. Built.DistCombinedFields.NLB = CombNextLB.get();
  6252. Built.DistCombinedFields.NUB = CombNextUB.get();
  6253. Built.DistCombinedFields.DistCond = CombDistCond.get();
  6254. Built.DistCombinedFields.ParForInDistCond = ParForInDistCond.get();
  6255. return NestedLoopCount;
  6256. }
  6257. static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
  6258. auto CollapseClauses =
  6259. OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
  6260. if (CollapseClauses.begin() != CollapseClauses.end())
  6261. return (*CollapseClauses.begin())->getNumForLoops();
  6262. return nullptr;
  6263. }
  6264. static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
  6265. auto OrderedClauses =
  6266. OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
  6267. if (OrderedClauses.begin() != OrderedClauses.end())
  6268. return (*OrderedClauses.begin())->getNumForLoops();
  6269. return nullptr;
  6270. }
  6271. static bool checkSimdlenSafelenSpecified(Sema &S,
  6272. const ArrayRef<OMPClause *> Clauses) {
  6273. const OMPSafelenClause *Safelen = nullptr;
  6274. const OMPSimdlenClause *Simdlen = nullptr;
  6275. for (const OMPClause *Clause : Clauses) {
  6276. if (Clause->getClauseKind() == OMPC_safelen)
  6277. Safelen = cast<OMPSafelenClause>(Clause);
  6278. else if (Clause->getClauseKind() == OMPC_simdlen)
  6279. Simdlen = cast<OMPSimdlenClause>(Clause);
  6280. if (Safelen && Simdlen)
  6281. break;
  6282. }
  6283. if (Simdlen && Safelen) {
  6284. const Expr *SimdlenLength = Simdlen->getSimdlen();
  6285. const Expr *SafelenLength = Safelen->getSafelen();
  6286. if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
  6287. SimdlenLength->isInstantiationDependent() ||
  6288. SimdlenLength->containsUnexpandedParameterPack())
  6289. return false;
  6290. if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
  6291. SafelenLength->isInstantiationDependent() ||
  6292. SafelenLength->containsUnexpandedParameterPack())
  6293. return false;
  6294. Expr::EvalResult SimdlenResult, SafelenResult;
  6295. SimdlenLength->EvaluateAsInt(SimdlenResult, S.Context);
  6296. SafelenLength->EvaluateAsInt(SafelenResult, S.Context);
  6297. llvm::APSInt SimdlenRes = SimdlenResult.Val.getInt();
  6298. llvm::APSInt SafelenRes = SafelenResult.Val.getInt();
  6299. // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
  6300. // If both simdlen and safelen clauses are specified, the value of the
  6301. // simdlen parameter must be less than or equal to the value of the safelen
  6302. // parameter.
  6303. if (SimdlenRes > SafelenRes) {
  6304. S.Diag(SimdlenLength->getExprLoc(),
  6305. diag::err_omp_wrong_simdlen_safelen_values)
  6306. << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
  6307. return true;
  6308. }
  6309. }
  6310. return false;
  6311. }
  6312. StmtResult
  6313. Sema::ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
  6314. SourceLocation StartLoc, SourceLocation EndLoc,
  6315. VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  6316. if (!AStmt)
  6317. return StmtError();
  6318. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  6319. OMPLoopDirective::HelperExprs B;
  6320. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  6321. // define the nested loops number.
  6322. unsigned NestedLoopCount = checkOpenMPLoop(
  6323. OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
  6324. AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
  6325. if (NestedLoopCount == 0)
  6326. return StmtError();
  6327. assert((CurContext->isDependentContext() || B.builtAll()) &&
  6328. "omp simd loop exprs were not built");
  6329. if (!CurContext->isDependentContext()) {
  6330. // Finalize the clauses that need pre-built expressions for CodeGen.
  6331. for (OMPClause *C : Clauses) {
  6332. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  6333. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  6334. B.NumIterations, *this, CurScope,
  6335. DSAStack))
  6336. return StmtError();
  6337. }
  6338. }
  6339. if (checkSimdlenSafelenSpecified(*this, Clauses))
  6340. return StmtError();
  6341. setFunctionHasBranchProtectedScope();
  6342. return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
  6343. Clauses, AStmt, B);
  6344. }
  6345. StmtResult
  6346. Sema::ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
  6347. SourceLocation StartLoc, SourceLocation EndLoc,
  6348. VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  6349. if (!AStmt)
  6350. return StmtError();
  6351. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  6352. OMPLoopDirective::HelperExprs B;
  6353. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  6354. // define the nested loops number.
  6355. unsigned NestedLoopCount = checkOpenMPLoop(
  6356. OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
  6357. AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
  6358. if (NestedLoopCount == 0)
  6359. return StmtError();
  6360. assert((CurContext->isDependentContext() || B.builtAll()) &&
  6361. "omp for loop exprs were not built");
  6362. if (!CurContext->isDependentContext()) {
  6363. // Finalize the clauses that need pre-built expressions for CodeGen.
  6364. for (OMPClause *C : Clauses) {
  6365. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  6366. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  6367. B.NumIterations, *this, CurScope,
  6368. DSAStack))
  6369. return StmtError();
  6370. }
  6371. }
  6372. setFunctionHasBranchProtectedScope();
  6373. return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
  6374. Clauses, AStmt, B, DSAStack->isCancelRegion());
  6375. }
  6376. StmtResult Sema::ActOnOpenMPForSimdDirective(
  6377. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  6378. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  6379. if (!AStmt)
  6380. return StmtError();
  6381. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  6382. OMPLoopDirective::HelperExprs B;
  6383. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  6384. // define the nested loops number.
  6385. unsigned NestedLoopCount =
  6386. checkOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
  6387. getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
  6388. VarsWithImplicitDSA, B);
  6389. if (NestedLoopCount == 0)
  6390. return StmtError();
  6391. assert((CurContext->isDependentContext() || B.builtAll()) &&
  6392. "omp for simd loop exprs were not built");
  6393. if (!CurContext->isDependentContext()) {
  6394. // Finalize the clauses that need pre-built expressions for CodeGen.
  6395. for (OMPClause *C : Clauses) {
  6396. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  6397. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  6398. B.NumIterations, *this, CurScope,
  6399. DSAStack))
  6400. return StmtError();
  6401. }
  6402. }
  6403. if (checkSimdlenSafelenSpecified(*this, Clauses))
  6404. return StmtError();
  6405. setFunctionHasBranchProtectedScope();
  6406. return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
  6407. Clauses, AStmt, B);
  6408. }
  6409. StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
  6410. Stmt *AStmt,
  6411. SourceLocation StartLoc,
  6412. SourceLocation EndLoc) {
  6413. if (!AStmt)
  6414. return StmtError();
  6415. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  6416. auto BaseStmt = AStmt;
  6417. while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
  6418. BaseStmt = CS->getCapturedStmt();
  6419. if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
  6420. auto S = C->children();
  6421. if (S.begin() == S.end())
  6422. return StmtError();
  6423. // All associated statements must be '#pragma omp section' except for
  6424. // the first one.
  6425. for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
  6426. if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
  6427. if (SectionStmt)
  6428. Diag(SectionStmt->getBeginLoc(),
  6429. diag::err_omp_sections_substmt_not_section);
  6430. return StmtError();
  6431. }
  6432. cast<OMPSectionDirective>(SectionStmt)
  6433. ->setHasCancel(DSAStack->isCancelRegion());
  6434. }
  6435. } else {
  6436. Diag(AStmt->getBeginLoc(), diag::err_omp_sections_not_compound_stmt);
  6437. return StmtError();
  6438. }
  6439. setFunctionHasBranchProtectedScope();
  6440. return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
  6441. DSAStack->isCancelRegion());
  6442. }
  6443. StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
  6444. SourceLocation StartLoc,
  6445. SourceLocation EndLoc) {
  6446. if (!AStmt)
  6447. return StmtError();
  6448. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  6449. setFunctionHasBranchProtectedScope();
  6450. DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
  6451. return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
  6452. DSAStack->isCancelRegion());
  6453. }
  6454. StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
  6455. Stmt *AStmt,
  6456. SourceLocation StartLoc,
  6457. SourceLocation EndLoc) {
  6458. if (!AStmt)
  6459. return StmtError();
  6460. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  6461. setFunctionHasBranchProtectedScope();
  6462. // OpenMP [2.7.3, single Construct, Restrictions]
  6463. // The copyprivate clause must not be used with the nowait clause.
  6464. const OMPClause *Nowait = nullptr;
  6465. const OMPClause *Copyprivate = nullptr;
  6466. for (const OMPClause *Clause : Clauses) {
  6467. if (Clause->getClauseKind() == OMPC_nowait)
  6468. Nowait = Clause;
  6469. else if (Clause->getClauseKind() == OMPC_copyprivate)
  6470. Copyprivate = Clause;
  6471. if (Copyprivate && Nowait) {
  6472. Diag(Copyprivate->getBeginLoc(),
  6473. diag::err_omp_single_copyprivate_with_nowait);
  6474. Diag(Nowait->getBeginLoc(), diag::note_omp_nowait_clause_here);
  6475. return StmtError();
  6476. }
  6477. }
  6478. return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
  6479. }
  6480. StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
  6481. SourceLocation StartLoc,
  6482. SourceLocation EndLoc) {
  6483. if (!AStmt)
  6484. return StmtError();
  6485. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  6486. setFunctionHasBranchProtectedScope();
  6487. return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
  6488. }
  6489. StmtResult Sema::ActOnOpenMPCriticalDirective(
  6490. const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
  6491. Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
  6492. if (!AStmt)
  6493. return StmtError();
  6494. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  6495. bool ErrorFound = false;
  6496. llvm::APSInt Hint;
  6497. SourceLocation HintLoc;
  6498. bool DependentHint = false;
  6499. for (const OMPClause *C : Clauses) {
  6500. if (C->getClauseKind() == OMPC_hint) {
  6501. if (!DirName.getName()) {
  6502. Diag(C->getBeginLoc(), diag::err_omp_hint_clause_no_name);
  6503. ErrorFound = true;
  6504. }
  6505. Expr *E = cast<OMPHintClause>(C)->getHint();
  6506. if (E->isTypeDependent() || E->isValueDependent() ||
  6507. E->isInstantiationDependent()) {
  6508. DependentHint = true;
  6509. } else {
  6510. Hint = E->EvaluateKnownConstInt(Context);
  6511. HintLoc = C->getBeginLoc();
  6512. }
  6513. }
  6514. }
  6515. if (ErrorFound)
  6516. return StmtError();
  6517. const auto Pair = DSAStack->getCriticalWithHint(DirName);
  6518. if (Pair.first && DirName.getName() && !DependentHint) {
  6519. if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
  6520. Diag(StartLoc, diag::err_omp_critical_with_hint);
  6521. if (HintLoc.isValid())
  6522. Diag(HintLoc, diag::note_omp_critical_hint_here)
  6523. << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
  6524. else
  6525. Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
  6526. if (const auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
  6527. Diag(C->getBeginLoc(), diag::note_omp_critical_hint_here)
  6528. << 1
  6529. << C->getHint()->EvaluateKnownConstInt(Context).toString(
  6530. /*Radix=*/10, /*Signed=*/false);
  6531. } else {
  6532. Diag(Pair.first->getBeginLoc(), diag::note_omp_critical_no_hint) << 1;
  6533. }
  6534. }
  6535. }
  6536. setFunctionHasBranchProtectedScope();
  6537. auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
  6538. Clauses, AStmt);
  6539. if (!Pair.first && DirName.getName() && !DependentHint)
  6540. DSAStack->addCriticalWithHint(Dir, Hint);
  6541. return Dir;
  6542. }
  6543. StmtResult Sema::ActOnOpenMPParallelForDirective(
  6544. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  6545. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  6546. if (!AStmt)
  6547. return StmtError();
  6548. auto *CS = cast<CapturedStmt>(AStmt);
  6549. // 1.2.2 OpenMP Language Terminology
  6550. // Structured block - An executable statement with a single entry at the
  6551. // top and a single exit at the bottom.
  6552. // The point of exit cannot be a branch out of the structured block.
  6553. // longjmp() and throw() must not violate the entry/exit criteria.
  6554. CS->getCapturedDecl()->setNothrow();
  6555. OMPLoopDirective::HelperExprs B;
  6556. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  6557. // define the nested loops number.
  6558. unsigned NestedLoopCount =
  6559. checkOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
  6560. getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
  6561. VarsWithImplicitDSA, B);
  6562. if (NestedLoopCount == 0)
  6563. return StmtError();
  6564. assert((CurContext->isDependentContext() || B.builtAll()) &&
  6565. "omp parallel for loop exprs were not built");
  6566. if (!CurContext->isDependentContext()) {
  6567. // Finalize the clauses that need pre-built expressions for CodeGen.
  6568. for (OMPClause *C : Clauses) {
  6569. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  6570. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  6571. B.NumIterations, *this, CurScope,
  6572. DSAStack))
  6573. return StmtError();
  6574. }
  6575. }
  6576. setFunctionHasBranchProtectedScope();
  6577. return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
  6578. NestedLoopCount, Clauses, AStmt, B,
  6579. DSAStack->isCancelRegion());
  6580. }
  6581. StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
  6582. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  6583. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  6584. if (!AStmt)
  6585. return StmtError();
  6586. auto *CS = cast<CapturedStmt>(AStmt);
  6587. // 1.2.2 OpenMP Language Terminology
  6588. // Structured block - An executable statement with a single entry at the
  6589. // top and a single exit at the bottom.
  6590. // The point of exit cannot be a branch out of the structured block.
  6591. // longjmp() and throw() must not violate the entry/exit criteria.
  6592. CS->getCapturedDecl()->setNothrow();
  6593. OMPLoopDirective::HelperExprs B;
  6594. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  6595. // define the nested loops number.
  6596. unsigned NestedLoopCount =
  6597. checkOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
  6598. getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
  6599. VarsWithImplicitDSA, B);
  6600. if (NestedLoopCount == 0)
  6601. return StmtError();
  6602. if (!CurContext->isDependentContext()) {
  6603. // Finalize the clauses that need pre-built expressions for CodeGen.
  6604. for (OMPClause *C : Clauses) {
  6605. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  6606. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  6607. B.NumIterations, *this, CurScope,
  6608. DSAStack))
  6609. return StmtError();
  6610. }
  6611. }
  6612. if (checkSimdlenSafelenSpecified(*this, Clauses))
  6613. return StmtError();
  6614. setFunctionHasBranchProtectedScope();
  6615. return OMPParallelForSimdDirective::Create(
  6616. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  6617. }
  6618. StmtResult
  6619. Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
  6620. Stmt *AStmt, SourceLocation StartLoc,
  6621. SourceLocation EndLoc) {
  6622. if (!AStmt)
  6623. return StmtError();
  6624. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  6625. auto BaseStmt = AStmt;
  6626. while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
  6627. BaseStmt = CS->getCapturedStmt();
  6628. if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
  6629. auto S = C->children();
  6630. if (S.begin() == S.end())
  6631. return StmtError();
  6632. // All associated statements must be '#pragma omp section' except for
  6633. // the first one.
  6634. for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
  6635. if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
  6636. if (SectionStmt)
  6637. Diag(SectionStmt->getBeginLoc(),
  6638. diag::err_omp_parallel_sections_substmt_not_section);
  6639. return StmtError();
  6640. }
  6641. cast<OMPSectionDirective>(SectionStmt)
  6642. ->setHasCancel(DSAStack->isCancelRegion());
  6643. }
  6644. } else {
  6645. Diag(AStmt->getBeginLoc(),
  6646. diag::err_omp_parallel_sections_not_compound_stmt);
  6647. return StmtError();
  6648. }
  6649. setFunctionHasBranchProtectedScope();
  6650. return OMPParallelSectionsDirective::Create(
  6651. Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
  6652. }
  6653. StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
  6654. Stmt *AStmt, SourceLocation StartLoc,
  6655. SourceLocation EndLoc) {
  6656. if (!AStmt)
  6657. return StmtError();
  6658. auto *CS = cast<CapturedStmt>(AStmt);
  6659. // 1.2.2 OpenMP Language Terminology
  6660. // Structured block - An executable statement with a single entry at the
  6661. // top and a single exit at the bottom.
  6662. // The point of exit cannot be a branch out of the structured block.
  6663. // longjmp() and throw() must not violate the entry/exit criteria.
  6664. CS->getCapturedDecl()->setNothrow();
  6665. setFunctionHasBranchProtectedScope();
  6666. return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
  6667. DSAStack->isCancelRegion());
  6668. }
  6669. StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
  6670. SourceLocation EndLoc) {
  6671. return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
  6672. }
  6673. StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
  6674. SourceLocation EndLoc) {
  6675. return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
  6676. }
  6677. StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
  6678. SourceLocation EndLoc) {
  6679. return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
  6680. }
  6681. StmtResult Sema::ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
  6682. Stmt *AStmt,
  6683. SourceLocation StartLoc,
  6684. SourceLocation EndLoc) {
  6685. if (!AStmt)
  6686. return StmtError();
  6687. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  6688. setFunctionHasBranchProtectedScope();
  6689. return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, Clauses,
  6690. AStmt,
  6691. DSAStack->getTaskgroupReductionRef());
  6692. }
  6693. StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
  6694. SourceLocation StartLoc,
  6695. SourceLocation EndLoc) {
  6696. assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
  6697. return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
  6698. }
  6699. StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
  6700. Stmt *AStmt,
  6701. SourceLocation StartLoc,
  6702. SourceLocation EndLoc) {
  6703. const OMPClause *DependFound = nullptr;
  6704. const OMPClause *DependSourceClause = nullptr;
  6705. const OMPClause *DependSinkClause = nullptr;
  6706. bool ErrorFound = false;
  6707. const OMPThreadsClause *TC = nullptr;
  6708. const OMPSIMDClause *SC = nullptr;
  6709. for (const OMPClause *C : Clauses) {
  6710. if (auto *DC = dyn_cast<OMPDependClause>(C)) {
  6711. DependFound = C;
  6712. if (DC->getDependencyKind() == OMPC_DEPEND_source) {
  6713. if (DependSourceClause) {
  6714. Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
  6715. << getOpenMPDirectiveName(OMPD_ordered)
  6716. << getOpenMPClauseName(OMPC_depend) << 2;
  6717. ErrorFound = true;
  6718. } else {
  6719. DependSourceClause = C;
  6720. }
  6721. if (DependSinkClause) {
  6722. Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
  6723. << 0;
  6724. ErrorFound = true;
  6725. }
  6726. } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
  6727. if (DependSourceClause) {
  6728. Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
  6729. << 1;
  6730. ErrorFound = true;
  6731. }
  6732. DependSinkClause = C;
  6733. }
  6734. } else if (C->getClauseKind() == OMPC_threads) {
  6735. TC = cast<OMPThreadsClause>(C);
  6736. } else if (C->getClauseKind() == OMPC_simd) {
  6737. SC = cast<OMPSIMDClause>(C);
  6738. }
  6739. }
  6740. if (!ErrorFound && !SC &&
  6741. isOpenMPSimdDirective(DSAStack->getParentDirective())) {
  6742. // OpenMP [2.8.1,simd Construct, Restrictions]
  6743. // An ordered construct with the simd clause is the only OpenMP construct
  6744. // that can appear in the simd region.
  6745. Diag(StartLoc, diag::err_omp_prohibited_region_simd);
  6746. ErrorFound = true;
  6747. } else if (DependFound && (TC || SC)) {
  6748. Diag(DependFound->getBeginLoc(), diag::err_omp_depend_clause_thread_simd)
  6749. << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
  6750. ErrorFound = true;
  6751. } else if (DependFound && !DSAStack->getParentOrderedRegionParam().first) {
  6752. Diag(DependFound->getBeginLoc(),
  6753. diag::err_omp_ordered_directive_without_param);
  6754. ErrorFound = true;
  6755. } else if (TC || Clauses.empty()) {
  6756. if (const Expr *Param = DSAStack->getParentOrderedRegionParam().first) {
  6757. SourceLocation ErrLoc = TC ? TC->getBeginLoc() : StartLoc;
  6758. Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
  6759. << (TC != nullptr);
  6760. Diag(Param->getBeginLoc(), diag::note_omp_ordered_param);
  6761. ErrorFound = true;
  6762. }
  6763. }
  6764. if ((!AStmt && !DependFound) || ErrorFound)
  6765. return StmtError();
  6766. if (AStmt) {
  6767. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  6768. setFunctionHasBranchProtectedScope();
  6769. }
  6770. return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
  6771. }
  6772. namespace {
  6773. /// Helper class for checking expression in 'omp atomic [update]'
  6774. /// construct.
  6775. class OpenMPAtomicUpdateChecker {
  6776. /// Error results for atomic update expressions.
  6777. enum ExprAnalysisErrorCode {
  6778. /// A statement is not an expression statement.
  6779. NotAnExpression,
  6780. /// Expression is not builtin binary or unary operation.
  6781. NotABinaryOrUnaryExpression,
  6782. /// Unary operation is not post-/pre- increment/decrement operation.
  6783. NotAnUnaryIncDecExpression,
  6784. /// An expression is not of scalar type.
  6785. NotAScalarType,
  6786. /// A binary operation is not an assignment operation.
  6787. NotAnAssignmentOp,
  6788. /// RHS part of the binary operation is not a binary expression.
  6789. NotABinaryExpression,
  6790. /// RHS part is not additive/multiplicative/shift/biwise binary
  6791. /// expression.
  6792. NotABinaryOperator,
  6793. /// RHS binary operation does not have reference to the updated LHS
  6794. /// part.
  6795. NotAnUpdateExpression,
  6796. /// No errors is found.
  6797. NoError
  6798. };
  6799. /// Reference to Sema.
  6800. Sema &SemaRef;
  6801. /// A location for note diagnostics (when error is found).
  6802. SourceLocation NoteLoc;
  6803. /// 'x' lvalue part of the source atomic expression.
  6804. Expr *X;
  6805. /// 'expr' rvalue part of the source atomic expression.
  6806. Expr *E;
  6807. /// Helper expression of the form
  6808. /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
  6809. /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
  6810. Expr *UpdateExpr;
  6811. /// Is 'x' a LHS in a RHS part of full update expression. It is
  6812. /// important for non-associative operations.
  6813. bool IsXLHSInRHSPart;
  6814. BinaryOperatorKind Op;
  6815. SourceLocation OpLoc;
  6816. /// true if the source expression is a postfix unary operation, false
  6817. /// if it is a prefix unary operation.
  6818. bool IsPostfixUpdate;
  6819. public:
  6820. OpenMPAtomicUpdateChecker(Sema &SemaRef)
  6821. : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
  6822. IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
  6823. /// Check specified statement that it is suitable for 'atomic update'
  6824. /// constructs and extract 'x', 'expr' and Operation from the original
  6825. /// expression. If DiagId and NoteId == 0, then only check is performed
  6826. /// without error notification.
  6827. /// \param DiagId Diagnostic which should be emitted if error is found.
  6828. /// \param NoteId Diagnostic note for the main error message.
  6829. /// \return true if statement is not an update expression, false otherwise.
  6830. bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
  6831. /// Return the 'x' lvalue part of the source atomic expression.
  6832. Expr *getX() const { return X; }
  6833. /// Return the 'expr' rvalue part of the source atomic expression.
  6834. Expr *getExpr() const { return E; }
  6835. /// Return the update expression used in calculation of the updated
  6836. /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
  6837. /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
  6838. Expr *getUpdateExpr() const { return UpdateExpr; }
  6839. /// Return true if 'x' is LHS in RHS part of full update expression,
  6840. /// false otherwise.
  6841. bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
  6842. /// true if the source expression is a postfix unary operation, false
  6843. /// if it is a prefix unary operation.
  6844. bool isPostfixUpdate() const { return IsPostfixUpdate; }
  6845. private:
  6846. bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
  6847. unsigned NoteId = 0);
  6848. };
  6849. } // namespace
  6850. bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
  6851. BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
  6852. ExprAnalysisErrorCode ErrorFound = NoError;
  6853. SourceLocation ErrorLoc, NoteLoc;
  6854. SourceRange ErrorRange, NoteRange;
  6855. // Allowed constructs are:
  6856. // x = x binop expr;
  6857. // x = expr binop x;
  6858. if (AtomicBinOp->getOpcode() == BO_Assign) {
  6859. X = AtomicBinOp->getLHS();
  6860. if (const auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
  6861. AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
  6862. if (AtomicInnerBinOp->isMultiplicativeOp() ||
  6863. AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
  6864. AtomicInnerBinOp->isBitwiseOp()) {
  6865. Op = AtomicInnerBinOp->getOpcode();
  6866. OpLoc = AtomicInnerBinOp->getOperatorLoc();
  6867. Expr *LHS = AtomicInnerBinOp->getLHS();
  6868. Expr *RHS = AtomicInnerBinOp->getRHS();
  6869. llvm::FoldingSetNodeID XId, LHSId, RHSId;
  6870. X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
  6871. /*Canonical=*/true);
  6872. LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
  6873. /*Canonical=*/true);
  6874. RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
  6875. /*Canonical=*/true);
  6876. if (XId == LHSId) {
  6877. E = RHS;
  6878. IsXLHSInRHSPart = true;
  6879. } else if (XId == RHSId) {
  6880. E = LHS;
  6881. IsXLHSInRHSPart = false;
  6882. } else {
  6883. ErrorLoc = AtomicInnerBinOp->getExprLoc();
  6884. ErrorRange = AtomicInnerBinOp->getSourceRange();
  6885. NoteLoc = X->getExprLoc();
  6886. NoteRange = X->getSourceRange();
  6887. ErrorFound = NotAnUpdateExpression;
  6888. }
  6889. } else {
  6890. ErrorLoc = AtomicInnerBinOp->getExprLoc();
  6891. ErrorRange = AtomicInnerBinOp->getSourceRange();
  6892. NoteLoc = AtomicInnerBinOp->getOperatorLoc();
  6893. NoteRange = SourceRange(NoteLoc, NoteLoc);
  6894. ErrorFound = NotABinaryOperator;
  6895. }
  6896. } else {
  6897. NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
  6898. NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
  6899. ErrorFound = NotABinaryExpression;
  6900. }
  6901. } else {
  6902. ErrorLoc = AtomicBinOp->getExprLoc();
  6903. ErrorRange = AtomicBinOp->getSourceRange();
  6904. NoteLoc = AtomicBinOp->getOperatorLoc();
  6905. NoteRange = SourceRange(NoteLoc, NoteLoc);
  6906. ErrorFound = NotAnAssignmentOp;
  6907. }
  6908. if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
  6909. SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
  6910. SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
  6911. return true;
  6912. }
  6913. if (SemaRef.CurContext->isDependentContext())
  6914. E = X = UpdateExpr = nullptr;
  6915. return ErrorFound != NoError;
  6916. }
  6917. bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
  6918. unsigned NoteId) {
  6919. ExprAnalysisErrorCode ErrorFound = NoError;
  6920. SourceLocation ErrorLoc, NoteLoc;
  6921. SourceRange ErrorRange, NoteRange;
  6922. // Allowed constructs are:
  6923. // x++;
  6924. // x--;
  6925. // ++x;
  6926. // --x;
  6927. // x binop= expr;
  6928. // x = x binop expr;
  6929. // x = expr binop x;
  6930. if (auto *AtomicBody = dyn_cast<Expr>(S)) {
  6931. AtomicBody = AtomicBody->IgnoreParenImpCasts();
  6932. if (AtomicBody->getType()->isScalarType() ||
  6933. AtomicBody->isInstantiationDependent()) {
  6934. if (const auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
  6935. AtomicBody->IgnoreParenImpCasts())) {
  6936. // Check for Compound Assignment Operation
  6937. Op = BinaryOperator::getOpForCompoundAssignment(
  6938. AtomicCompAssignOp->getOpcode());
  6939. OpLoc = AtomicCompAssignOp->getOperatorLoc();
  6940. E = AtomicCompAssignOp->getRHS();
  6941. X = AtomicCompAssignOp->getLHS()->IgnoreParens();
  6942. IsXLHSInRHSPart = true;
  6943. } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
  6944. AtomicBody->IgnoreParenImpCasts())) {
  6945. // Check for Binary Operation
  6946. if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
  6947. return true;
  6948. } else if (const auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
  6949. AtomicBody->IgnoreParenImpCasts())) {
  6950. // Check for Unary Operation
  6951. if (AtomicUnaryOp->isIncrementDecrementOp()) {
  6952. IsPostfixUpdate = AtomicUnaryOp->isPostfix();
  6953. Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
  6954. OpLoc = AtomicUnaryOp->getOperatorLoc();
  6955. X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
  6956. E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
  6957. IsXLHSInRHSPart = true;
  6958. } else {
  6959. ErrorFound = NotAnUnaryIncDecExpression;
  6960. ErrorLoc = AtomicUnaryOp->getExprLoc();
  6961. ErrorRange = AtomicUnaryOp->getSourceRange();
  6962. NoteLoc = AtomicUnaryOp->getOperatorLoc();
  6963. NoteRange = SourceRange(NoteLoc, NoteLoc);
  6964. }
  6965. } else if (!AtomicBody->isInstantiationDependent()) {
  6966. ErrorFound = NotABinaryOrUnaryExpression;
  6967. NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
  6968. NoteRange = ErrorRange = AtomicBody->getSourceRange();
  6969. }
  6970. } else {
  6971. ErrorFound = NotAScalarType;
  6972. NoteLoc = ErrorLoc = AtomicBody->getBeginLoc();
  6973. NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
  6974. }
  6975. } else {
  6976. ErrorFound = NotAnExpression;
  6977. NoteLoc = ErrorLoc = S->getBeginLoc();
  6978. NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
  6979. }
  6980. if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
  6981. SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
  6982. SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
  6983. return true;
  6984. }
  6985. if (SemaRef.CurContext->isDependentContext())
  6986. E = X = UpdateExpr = nullptr;
  6987. if (ErrorFound == NoError && E && X) {
  6988. // Build an update expression of form 'OpaqueValueExpr(x) binop
  6989. // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
  6990. // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
  6991. auto *OVEX = new (SemaRef.getASTContext())
  6992. OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
  6993. auto *OVEExpr = new (SemaRef.getASTContext())
  6994. OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
  6995. ExprResult Update =
  6996. SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
  6997. IsXLHSInRHSPart ? OVEExpr : OVEX);
  6998. if (Update.isInvalid())
  6999. return true;
  7000. Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
  7001. Sema::AA_Casting);
  7002. if (Update.isInvalid())
  7003. return true;
  7004. UpdateExpr = Update.get();
  7005. }
  7006. return ErrorFound != NoError;
  7007. }
  7008. StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
  7009. Stmt *AStmt,
  7010. SourceLocation StartLoc,
  7011. SourceLocation EndLoc) {
  7012. if (!AStmt)
  7013. return StmtError();
  7014. auto *CS = cast<CapturedStmt>(AStmt);
  7015. // 1.2.2 OpenMP Language Terminology
  7016. // Structured block - An executable statement with a single entry at the
  7017. // top and a single exit at the bottom.
  7018. // The point of exit cannot be a branch out of the structured block.
  7019. // longjmp() and throw() must not violate the entry/exit criteria.
  7020. OpenMPClauseKind AtomicKind = OMPC_unknown;
  7021. SourceLocation AtomicKindLoc;
  7022. for (const OMPClause *C : Clauses) {
  7023. if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
  7024. C->getClauseKind() == OMPC_update ||
  7025. C->getClauseKind() == OMPC_capture) {
  7026. if (AtomicKind != OMPC_unknown) {
  7027. Diag(C->getBeginLoc(), diag::err_omp_atomic_several_clauses)
  7028. << SourceRange(C->getBeginLoc(), C->getEndLoc());
  7029. Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
  7030. << getOpenMPClauseName(AtomicKind);
  7031. } else {
  7032. AtomicKind = C->getClauseKind();
  7033. AtomicKindLoc = C->getBeginLoc();
  7034. }
  7035. }
  7036. }
  7037. Stmt *Body = CS->getCapturedStmt();
  7038. if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
  7039. Body = EWC->getSubExpr();
  7040. Expr *X = nullptr;
  7041. Expr *V = nullptr;
  7042. Expr *E = nullptr;
  7043. Expr *UE = nullptr;
  7044. bool IsXLHSInRHSPart = false;
  7045. bool IsPostfixUpdate = false;
  7046. // OpenMP [2.12.6, atomic Construct]
  7047. // In the next expressions:
  7048. // * x and v (as applicable) are both l-value expressions with scalar type.
  7049. // * During the execution of an atomic region, multiple syntactic
  7050. // occurrences of x must designate the same storage location.
  7051. // * Neither of v and expr (as applicable) may access the storage location
  7052. // designated by x.
  7053. // * Neither of x and expr (as applicable) may access the storage location
  7054. // designated by v.
  7055. // * expr is an expression with scalar type.
  7056. // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
  7057. // * binop, binop=, ++, and -- are not overloaded operators.
  7058. // * The expression x binop expr must be numerically equivalent to x binop
  7059. // (expr). This requirement is satisfied if the operators in expr have
  7060. // precedence greater than binop, or by using parentheses around expr or
  7061. // subexpressions of expr.
  7062. // * The expression expr binop x must be numerically equivalent to (expr)
  7063. // binop x. This requirement is satisfied if the operators in expr have
  7064. // precedence equal to or greater than binop, or by using parentheses around
  7065. // expr or subexpressions of expr.
  7066. // * For forms that allow multiple occurrences of x, the number of times
  7067. // that x is evaluated is unspecified.
  7068. if (AtomicKind == OMPC_read) {
  7069. enum {
  7070. NotAnExpression,
  7071. NotAnAssignmentOp,
  7072. NotAScalarType,
  7073. NotAnLValue,
  7074. NoError
  7075. } ErrorFound = NoError;
  7076. SourceLocation ErrorLoc, NoteLoc;
  7077. SourceRange ErrorRange, NoteRange;
  7078. // If clause is read:
  7079. // v = x;
  7080. if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
  7081. const auto *AtomicBinOp =
  7082. dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
  7083. if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
  7084. X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
  7085. V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
  7086. if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
  7087. (V->isInstantiationDependent() || V->getType()->isScalarType())) {
  7088. if (!X->isLValue() || !V->isLValue()) {
  7089. const Expr *NotLValueExpr = X->isLValue() ? V : X;
  7090. ErrorFound = NotAnLValue;
  7091. ErrorLoc = AtomicBinOp->getExprLoc();
  7092. ErrorRange = AtomicBinOp->getSourceRange();
  7093. NoteLoc = NotLValueExpr->getExprLoc();
  7094. NoteRange = NotLValueExpr->getSourceRange();
  7095. }
  7096. } else if (!X->isInstantiationDependent() ||
  7097. !V->isInstantiationDependent()) {
  7098. const Expr *NotScalarExpr =
  7099. (X->isInstantiationDependent() || X->getType()->isScalarType())
  7100. ? V
  7101. : X;
  7102. ErrorFound = NotAScalarType;
  7103. ErrorLoc = AtomicBinOp->getExprLoc();
  7104. ErrorRange = AtomicBinOp->getSourceRange();
  7105. NoteLoc = NotScalarExpr->getExprLoc();
  7106. NoteRange = NotScalarExpr->getSourceRange();
  7107. }
  7108. } else if (!AtomicBody->isInstantiationDependent()) {
  7109. ErrorFound = NotAnAssignmentOp;
  7110. ErrorLoc = AtomicBody->getExprLoc();
  7111. ErrorRange = AtomicBody->getSourceRange();
  7112. NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
  7113. : AtomicBody->getExprLoc();
  7114. NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
  7115. : AtomicBody->getSourceRange();
  7116. }
  7117. } else {
  7118. ErrorFound = NotAnExpression;
  7119. NoteLoc = ErrorLoc = Body->getBeginLoc();
  7120. NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
  7121. }
  7122. if (ErrorFound != NoError) {
  7123. Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
  7124. << ErrorRange;
  7125. Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
  7126. << NoteRange;
  7127. return StmtError();
  7128. }
  7129. if (CurContext->isDependentContext())
  7130. V = X = nullptr;
  7131. } else if (AtomicKind == OMPC_write) {
  7132. enum {
  7133. NotAnExpression,
  7134. NotAnAssignmentOp,
  7135. NotAScalarType,
  7136. NotAnLValue,
  7137. NoError
  7138. } ErrorFound = NoError;
  7139. SourceLocation ErrorLoc, NoteLoc;
  7140. SourceRange ErrorRange, NoteRange;
  7141. // If clause is write:
  7142. // x = expr;
  7143. if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
  7144. const auto *AtomicBinOp =
  7145. dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
  7146. if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
  7147. X = AtomicBinOp->getLHS();
  7148. E = AtomicBinOp->getRHS();
  7149. if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
  7150. (E->isInstantiationDependent() || E->getType()->isScalarType())) {
  7151. if (!X->isLValue()) {
  7152. ErrorFound = NotAnLValue;
  7153. ErrorLoc = AtomicBinOp->getExprLoc();
  7154. ErrorRange = AtomicBinOp->getSourceRange();
  7155. NoteLoc = X->getExprLoc();
  7156. NoteRange = X->getSourceRange();
  7157. }
  7158. } else if (!X->isInstantiationDependent() ||
  7159. !E->isInstantiationDependent()) {
  7160. const Expr *NotScalarExpr =
  7161. (X->isInstantiationDependent() || X->getType()->isScalarType())
  7162. ? E
  7163. : X;
  7164. ErrorFound = NotAScalarType;
  7165. ErrorLoc = AtomicBinOp->getExprLoc();
  7166. ErrorRange = AtomicBinOp->getSourceRange();
  7167. NoteLoc = NotScalarExpr->getExprLoc();
  7168. NoteRange = NotScalarExpr->getSourceRange();
  7169. }
  7170. } else if (!AtomicBody->isInstantiationDependent()) {
  7171. ErrorFound = NotAnAssignmentOp;
  7172. ErrorLoc = AtomicBody->getExprLoc();
  7173. ErrorRange = AtomicBody->getSourceRange();
  7174. NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
  7175. : AtomicBody->getExprLoc();
  7176. NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
  7177. : AtomicBody->getSourceRange();
  7178. }
  7179. } else {
  7180. ErrorFound = NotAnExpression;
  7181. NoteLoc = ErrorLoc = Body->getBeginLoc();
  7182. NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
  7183. }
  7184. if (ErrorFound != NoError) {
  7185. Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
  7186. << ErrorRange;
  7187. Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
  7188. << NoteRange;
  7189. return StmtError();
  7190. }
  7191. if (CurContext->isDependentContext())
  7192. E = X = nullptr;
  7193. } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
  7194. // If clause is update:
  7195. // x++;
  7196. // x--;
  7197. // ++x;
  7198. // --x;
  7199. // x binop= expr;
  7200. // x = x binop expr;
  7201. // x = expr binop x;
  7202. OpenMPAtomicUpdateChecker Checker(*this);
  7203. if (Checker.checkStatement(
  7204. Body, (AtomicKind == OMPC_update)
  7205. ? diag::err_omp_atomic_update_not_expression_statement
  7206. : diag::err_omp_atomic_not_expression_statement,
  7207. diag::note_omp_atomic_update))
  7208. return StmtError();
  7209. if (!CurContext->isDependentContext()) {
  7210. E = Checker.getExpr();
  7211. X = Checker.getX();
  7212. UE = Checker.getUpdateExpr();
  7213. IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
  7214. }
  7215. } else if (AtomicKind == OMPC_capture) {
  7216. enum {
  7217. NotAnAssignmentOp,
  7218. NotACompoundStatement,
  7219. NotTwoSubstatements,
  7220. NotASpecificExpression,
  7221. NoError
  7222. } ErrorFound = NoError;
  7223. SourceLocation ErrorLoc, NoteLoc;
  7224. SourceRange ErrorRange, NoteRange;
  7225. if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
  7226. // If clause is a capture:
  7227. // v = x++;
  7228. // v = x--;
  7229. // v = ++x;
  7230. // v = --x;
  7231. // v = x binop= expr;
  7232. // v = x = x binop expr;
  7233. // v = x = expr binop x;
  7234. const auto *AtomicBinOp =
  7235. dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
  7236. if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
  7237. V = AtomicBinOp->getLHS();
  7238. Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
  7239. OpenMPAtomicUpdateChecker Checker(*this);
  7240. if (Checker.checkStatement(
  7241. Body, diag::err_omp_atomic_capture_not_expression_statement,
  7242. diag::note_omp_atomic_update))
  7243. return StmtError();
  7244. E = Checker.getExpr();
  7245. X = Checker.getX();
  7246. UE = Checker.getUpdateExpr();
  7247. IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
  7248. IsPostfixUpdate = Checker.isPostfixUpdate();
  7249. } else if (!AtomicBody->isInstantiationDependent()) {
  7250. ErrorLoc = AtomicBody->getExprLoc();
  7251. ErrorRange = AtomicBody->getSourceRange();
  7252. NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
  7253. : AtomicBody->getExprLoc();
  7254. NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
  7255. : AtomicBody->getSourceRange();
  7256. ErrorFound = NotAnAssignmentOp;
  7257. }
  7258. if (ErrorFound != NoError) {
  7259. Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
  7260. << ErrorRange;
  7261. Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
  7262. return StmtError();
  7263. }
  7264. if (CurContext->isDependentContext())
  7265. UE = V = E = X = nullptr;
  7266. } else {
  7267. // If clause is a capture:
  7268. // { v = x; x = expr; }
  7269. // { v = x; x++; }
  7270. // { v = x; x--; }
  7271. // { v = x; ++x; }
  7272. // { v = x; --x; }
  7273. // { v = x; x binop= expr; }
  7274. // { v = x; x = x binop expr; }
  7275. // { v = x; x = expr binop x; }
  7276. // { x++; v = x; }
  7277. // { x--; v = x; }
  7278. // { ++x; v = x; }
  7279. // { --x; v = x; }
  7280. // { x binop= expr; v = x; }
  7281. // { x = x binop expr; v = x; }
  7282. // { x = expr binop x; v = x; }
  7283. if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
  7284. // Check that this is { expr1; expr2; }
  7285. if (CS->size() == 2) {
  7286. Stmt *First = CS->body_front();
  7287. Stmt *Second = CS->body_back();
  7288. if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
  7289. First = EWC->getSubExpr()->IgnoreParenImpCasts();
  7290. if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
  7291. Second = EWC->getSubExpr()->IgnoreParenImpCasts();
  7292. // Need to find what subexpression is 'v' and what is 'x'.
  7293. OpenMPAtomicUpdateChecker Checker(*this);
  7294. bool IsUpdateExprFound = !Checker.checkStatement(Second);
  7295. BinaryOperator *BinOp = nullptr;
  7296. if (IsUpdateExprFound) {
  7297. BinOp = dyn_cast<BinaryOperator>(First);
  7298. IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
  7299. }
  7300. if (IsUpdateExprFound && !CurContext->isDependentContext()) {
  7301. // { v = x; x++; }
  7302. // { v = x; x--; }
  7303. // { v = x; ++x; }
  7304. // { v = x; --x; }
  7305. // { v = x; x binop= expr; }
  7306. // { v = x; x = x binop expr; }
  7307. // { v = x; x = expr binop x; }
  7308. // Check that the first expression has form v = x.
  7309. Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
  7310. llvm::FoldingSetNodeID XId, PossibleXId;
  7311. Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
  7312. PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
  7313. IsUpdateExprFound = XId == PossibleXId;
  7314. if (IsUpdateExprFound) {
  7315. V = BinOp->getLHS();
  7316. X = Checker.getX();
  7317. E = Checker.getExpr();
  7318. UE = Checker.getUpdateExpr();
  7319. IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
  7320. IsPostfixUpdate = true;
  7321. }
  7322. }
  7323. if (!IsUpdateExprFound) {
  7324. IsUpdateExprFound = !Checker.checkStatement(First);
  7325. BinOp = nullptr;
  7326. if (IsUpdateExprFound) {
  7327. BinOp = dyn_cast<BinaryOperator>(Second);
  7328. IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
  7329. }
  7330. if (IsUpdateExprFound && !CurContext->isDependentContext()) {
  7331. // { x++; v = x; }
  7332. // { x--; v = x; }
  7333. // { ++x; v = x; }
  7334. // { --x; v = x; }
  7335. // { x binop= expr; v = x; }
  7336. // { x = x binop expr; v = x; }
  7337. // { x = expr binop x; v = x; }
  7338. // Check that the second expression has form v = x.
  7339. Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
  7340. llvm::FoldingSetNodeID XId, PossibleXId;
  7341. Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
  7342. PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
  7343. IsUpdateExprFound = XId == PossibleXId;
  7344. if (IsUpdateExprFound) {
  7345. V = BinOp->getLHS();
  7346. X = Checker.getX();
  7347. E = Checker.getExpr();
  7348. UE = Checker.getUpdateExpr();
  7349. IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
  7350. IsPostfixUpdate = false;
  7351. }
  7352. }
  7353. }
  7354. if (!IsUpdateExprFound) {
  7355. // { v = x; x = expr; }
  7356. auto *FirstExpr = dyn_cast<Expr>(First);
  7357. auto *SecondExpr = dyn_cast<Expr>(Second);
  7358. if (!FirstExpr || !SecondExpr ||
  7359. !(FirstExpr->isInstantiationDependent() ||
  7360. SecondExpr->isInstantiationDependent())) {
  7361. auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
  7362. if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
  7363. ErrorFound = NotAnAssignmentOp;
  7364. NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
  7365. : First->getBeginLoc();
  7366. NoteRange = ErrorRange = FirstBinOp
  7367. ? FirstBinOp->getSourceRange()
  7368. : SourceRange(ErrorLoc, ErrorLoc);
  7369. } else {
  7370. auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
  7371. if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
  7372. ErrorFound = NotAnAssignmentOp;
  7373. NoteLoc = ErrorLoc = SecondBinOp
  7374. ? SecondBinOp->getOperatorLoc()
  7375. : Second->getBeginLoc();
  7376. NoteRange = ErrorRange =
  7377. SecondBinOp ? SecondBinOp->getSourceRange()
  7378. : SourceRange(ErrorLoc, ErrorLoc);
  7379. } else {
  7380. Expr *PossibleXRHSInFirst =
  7381. FirstBinOp->getRHS()->IgnoreParenImpCasts();
  7382. Expr *PossibleXLHSInSecond =
  7383. SecondBinOp->getLHS()->IgnoreParenImpCasts();
  7384. llvm::FoldingSetNodeID X1Id, X2Id;
  7385. PossibleXRHSInFirst->Profile(X1Id, Context,
  7386. /*Canonical=*/true);
  7387. PossibleXLHSInSecond->Profile(X2Id, Context,
  7388. /*Canonical=*/true);
  7389. IsUpdateExprFound = X1Id == X2Id;
  7390. if (IsUpdateExprFound) {
  7391. V = FirstBinOp->getLHS();
  7392. X = SecondBinOp->getLHS();
  7393. E = SecondBinOp->getRHS();
  7394. UE = nullptr;
  7395. IsXLHSInRHSPart = false;
  7396. IsPostfixUpdate = true;
  7397. } else {
  7398. ErrorFound = NotASpecificExpression;
  7399. ErrorLoc = FirstBinOp->getExprLoc();
  7400. ErrorRange = FirstBinOp->getSourceRange();
  7401. NoteLoc = SecondBinOp->getLHS()->getExprLoc();
  7402. NoteRange = SecondBinOp->getRHS()->getSourceRange();
  7403. }
  7404. }
  7405. }
  7406. }
  7407. }
  7408. } else {
  7409. NoteLoc = ErrorLoc = Body->getBeginLoc();
  7410. NoteRange = ErrorRange =
  7411. SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
  7412. ErrorFound = NotTwoSubstatements;
  7413. }
  7414. } else {
  7415. NoteLoc = ErrorLoc = Body->getBeginLoc();
  7416. NoteRange = ErrorRange =
  7417. SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
  7418. ErrorFound = NotACompoundStatement;
  7419. }
  7420. if (ErrorFound != NoError) {
  7421. Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
  7422. << ErrorRange;
  7423. Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
  7424. return StmtError();
  7425. }
  7426. if (CurContext->isDependentContext())
  7427. UE = V = E = X = nullptr;
  7428. }
  7429. }
  7430. setFunctionHasBranchProtectedScope();
  7431. return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
  7432. X, V, E, UE, IsXLHSInRHSPart,
  7433. IsPostfixUpdate);
  7434. }
  7435. StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
  7436. Stmt *AStmt,
  7437. SourceLocation StartLoc,
  7438. SourceLocation EndLoc) {
  7439. if (!AStmt)
  7440. return StmtError();
  7441. auto *CS = cast<CapturedStmt>(AStmt);
  7442. // 1.2.2 OpenMP Language Terminology
  7443. // Structured block - An executable statement with a single entry at the
  7444. // top and a single exit at the bottom.
  7445. // The point of exit cannot be a branch out of the structured block.
  7446. // longjmp() and throw() must not violate the entry/exit criteria.
  7447. CS->getCapturedDecl()->setNothrow();
  7448. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target);
  7449. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  7450. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  7451. // 1.2.2 OpenMP Language Terminology
  7452. // Structured block - An executable statement with a single entry at the
  7453. // top and a single exit at the bottom.
  7454. // The point of exit cannot be a branch out of the structured block.
  7455. // longjmp() and throw() must not violate the entry/exit criteria.
  7456. CS->getCapturedDecl()->setNothrow();
  7457. }
  7458. // OpenMP [2.16, Nesting of Regions]
  7459. // If specified, a teams construct must be contained within a target
  7460. // construct. That target construct must contain no statements or directives
  7461. // outside of the teams construct.
  7462. if (DSAStack->hasInnerTeamsRegion()) {
  7463. const Stmt *S = CS->IgnoreContainers(/*IgnoreCaptured=*/true);
  7464. bool OMPTeamsFound = true;
  7465. if (const auto *CS = dyn_cast<CompoundStmt>(S)) {
  7466. auto I = CS->body_begin();
  7467. while (I != CS->body_end()) {
  7468. const auto *OED = dyn_cast<OMPExecutableDirective>(*I);
  7469. if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind()) ||
  7470. OMPTeamsFound) {
  7471. OMPTeamsFound = false;
  7472. break;
  7473. }
  7474. ++I;
  7475. }
  7476. assert(I != CS->body_end() && "Not found statement");
  7477. S = *I;
  7478. } else {
  7479. const auto *OED = dyn_cast<OMPExecutableDirective>(S);
  7480. OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
  7481. }
  7482. if (!OMPTeamsFound) {
  7483. Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
  7484. Diag(DSAStack->getInnerTeamsRegionLoc(),
  7485. diag::note_omp_nested_teams_construct_here);
  7486. Diag(S->getBeginLoc(), diag::note_omp_nested_statement_here)
  7487. << isa<OMPExecutableDirective>(S);
  7488. return StmtError();
  7489. }
  7490. }
  7491. setFunctionHasBranchProtectedScope();
  7492. return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
  7493. }
  7494. StmtResult
  7495. Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
  7496. Stmt *AStmt, SourceLocation StartLoc,
  7497. SourceLocation EndLoc) {
  7498. if (!AStmt)
  7499. return StmtError();
  7500. auto *CS = cast<CapturedStmt>(AStmt);
  7501. // 1.2.2 OpenMP Language Terminology
  7502. // Structured block - An executable statement with a single entry at the
  7503. // top and a single exit at the bottom.
  7504. // The point of exit cannot be a branch out of the structured block.
  7505. // longjmp() and throw() must not violate the entry/exit criteria.
  7506. CS->getCapturedDecl()->setNothrow();
  7507. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel);
  7508. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  7509. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  7510. // 1.2.2 OpenMP Language Terminology
  7511. // Structured block - An executable statement with a single entry at the
  7512. // top and a single exit at the bottom.
  7513. // The point of exit cannot be a branch out of the structured block.
  7514. // longjmp() and throw() must not violate the entry/exit criteria.
  7515. CS->getCapturedDecl()->setNothrow();
  7516. }
  7517. setFunctionHasBranchProtectedScope();
  7518. return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
  7519. AStmt);
  7520. }
  7521. StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
  7522. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  7523. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  7524. if (!AStmt)
  7525. return StmtError();
  7526. auto *CS = cast<CapturedStmt>(AStmt);
  7527. // 1.2.2 OpenMP Language Terminology
  7528. // Structured block - An executable statement with a single entry at the
  7529. // top and a single exit at the bottom.
  7530. // The point of exit cannot be a branch out of the structured block.
  7531. // longjmp() and throw() must not violate the entry/exit criteria.
  7532. CS->getCapturedDecl()->setNothrow();
  7533. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
  7534. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  7535. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  7536. // 1.2.2 OpenMP Language Terminology
  7537. // Structured block - An executable statement with a single entry at the
  7538. // top and a single exit at the bottom.
  7539. // The point of exit cannot be a branch out of the structured block.
  7540. // longjmp() and throw() must not violate the entry/exit criteria.
  7541. CS->getCapturedDecl()->setNothrow();
  7542. }
  7543. OMPLoopDirective::HelperExprs B;
  7544. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  7545. // define the nested loops number.
  7546. unsigned NestedLoopCount =
  7547. checkOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
  7548. getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
  7549. VarsWithImplicitDSA, B);
  7550. if (NestedLoopCount == 0)
  7551. return StmtError();
  7552. assert((CurContext->isDependentContext() || B.builtAll()) &&
  7553. "omp target parallel for loop exprs were not built");
  7554. if (!CurContext->isDependentContext()) {
  7555. // Finalize the clauses that need pre-built expressions for CodeGen.
  7556. for (OMPClause *C : Clauses) {
  7557. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  7558. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  7559. B.NumIterations, *this, CurScope,
  7560. DSAStack))
  7561. return StmtError();
  7562. }
  7563. }
  7564. setFunctionHasBranchProtectedScope();
  7565. return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc,
  7566. NestedLoopCount, Clauses, AStmt,
  7567. B, DSAStack->isCancelRegion());
  7568. }
  7569. /// Check for existence of a map clause in the list of clauses.
  7570. static bool hasClauses(ArrayRef<OMPClause *> Clauses,
  7571. const OpenMPClauseKind K) {
  7572. return llvm::any_of(
  7573. Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; });
  7574. }
  7575. template <typename... Params>
  7576. static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K,
  7577. const Params... ClauseTypes) {
  7578. return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...);
  7579. }
  7580. StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
  7581. Stmt *AStmt,
  7582. SourceLocation StartLoc,
  7583. SourceLocation EndLoc) {
  7584. if (!AStmt)
  7585. return StmtError();
  7586. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  7587. // OpenMP [2.10.1, Restrictions, p. 97]
  7588. // At least one map clause must appear on the directive.
  7589. if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr)) {
  7590. Diag(StartLoc, diag::err_omp_no_clause_for_directive)
  7591. << "'map' or 'use_device_ptr'"
  7592. << getOpenMPDirectiveName(OMPD_target_data);
  7593. return StmtError();
  7594. }
  7595. setFunctionHasBranchProtectedScope();
  7596. return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
  7597. AStmt);
  7598. }
  7599. StmtResult
  7600. Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
  7601. SourceLocation StartLoc,
  7602. SourceLocation EndLoc, Stmt *AStmt) {
  7603. if (!AStmt)
  7604. return StmtError();
  7605. auto *CS = cast<CapturedStmt>(AStmt);
  7606. // 1.2.2 OpenMP Language Terminology
  7607. // Structured block - An executable statement with a single entry at the
  7608. // top and a single exit at the bottom.
  7609. // The point of exit cannot be a branch out of the structured block.
  7610. // longjmp() and throw() must not violate the entry/exit criteria.
  7611. CS->getCapturedDecl()->setNothrow();
  7612. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_enter_data);
  7613. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  7614. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  7615. // 1.2.2 OpenMP Language Terminology
  7616. // Structured block - An executable statement with a single entry at the
  7617. // top and a single exit at the bottom.
  7618. // The point of exit cannot be a branch out of the structured block.
  7619. // longjmp() and throw() must not violate the entry/exit criteria.
  7620. CS->getCapturedDecl()->setNothrow();
  7621. }
  7622. // OpenMP [2.10.2, Restrictions, p. 99]
  7623. // At least one map clause must appear on the directive.
  7624. if (!hasClauses(Clauses, OMPC_map)) {
  7625. Diag(StartLoc, diag::err_omp_no_clause_for_directive)
  7626. << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data);
  7627. return StmtError();
  7628. }
  7629. return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
  7630. AStmt);
  7631. }
  7632. StmtResult
  7633. Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
  7634. SourceLocation StartLoc,
  7635. SourceLocation EndLoc, Stmt *AStmt) {
  7636. if (!AStmt)
  7637. return StmtError();
  7638. auto *CS = cast<CapturedStmt>(AStmt);
  7639. // 1.2.2 OpenMP Language Terminology
  7640. // Structured block - An executable statement with a single entry at the
  7641. // top and a single exit at the bottom.
  7642. // The point of exit cannot be a branch out of the structured block.
  7643. // longjmp() and throw() must not violate the entry/exit criteria.
  7644. CS->getCapturedDecl()->setNothrow();
  7645. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_exit_data);
  7646. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  7647. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  7648. // 1.2.2 OpenMP Language Terminology
  7649. // Structured block - An executable statement with a single entry at the
  7650. // top and a single exit at the bottom.
  7651. // The point of exit cannot be a branch out of the structured block.
  7652. // longjmp() and throw() must not violate the entry/exit criteria.
  7653. CS->getCapturedDecl()->setNothrow();
  7654. }
  7655. // OpenMP [2.10.3, Restrictions, p. 102]
  7656. // At least one map clause must appear on the directive.
  7657. if (!hasClauses(Clauses, OMPC_map)) {
  7658. Diag(StartLoc, diag::err_omp_no_clause_for_directive)
  7659. << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data);
  7660. return StmtError();
  7661. }
  7662. return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
  7663. AStmt);
  7664. }
  7665. StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
  7666. SourceLocation StartLoc,
  7667. SourceLocation EndLoc,
  7668. Stmt *AStmt) {
  7669. if (!AStmt)
  7670. return StmtError();
  7671. auto *CS = cast<CapturedStmt>(AStmt);
  7672. // 1.2.2 OpenMP Language Terminology
  7673. // Structured block - An executable statement with a single entry at the
  7674. // top and a single exit at the bottom.
  7675. // The point of exit cannot be a branch out of the structured block.
  7676. // longjmp() and throw() must not violate the entry/exit criteria.
  7677. CS->getCapturedDecl()->setNothrow();
  7678. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_update);
  7679. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  7680. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  7681. // 1.2.2 OpenMP Language Terminology
  7682. // Structured block - An executable statement with a single entry at the
  7683. // top and a single exit at the bottom.
  7684. // The point of exit cannot be a branch out of the structured block.
  7685. // longjmp() and throw() must not violate the entry/exit criteria.
  7686. CS->getCapturedDecl()->setNothrow();
  7687. }
  7688. if (!hasClauses(Clauses, OMPC_to, OMPC_from)) {
  7689. Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
  7690. return StmtError();
  7691. }
  7692. return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses,
  7693. AStmt);
  7694. }
  7695. StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
  7696. Stmt *AStmt, SourceLocation StartLoc,
  7697. SourceLocation EndLoc) {
  7698. if (!AStmt)
  7699. return StmtError();
  7700. auto *CS = cast<CapturedStmt>(AStmt);
  7701. // 1.2.2 OpenMP Language Terminology
  7702. // Structured block - An executable statement with a single entry at the
  7703. // top and a single exit at the bottom.
  7704. // The point of exit cannot be a branch out of the structured block.
  7705. // longjmp() and throw() must not violate the entry/exit criteria.
  7706. CS->getCapturedDecl()->setNothrow();
  7707. setFunctionHasBranchProtectedScope();
  7708. DSAStack->setParentTeamsRegionLoc(StartLoc);
  7709. return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
  7710. }
  7711. StmtResult
  7712. Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
  7713. SourceLocation EndLoc,
  7714. OpenMPDirectiveKind CancelRegion) {
  7715. if (DSAStack->isParentNowaitRegion()) {
  7716. Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
  7717. return StmtError();
  7718. }
  7719. if (DSAStack->isParentOrderedRegion()) {
  7720. Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
  7721. return StmtError();
  7722. }
  7723. return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
  7724. CancelRegion);
  7725. }
  7726. StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
  7727. SourceLocation StartLoc,
  7728. SourceLocation EndLoc,
  7729. OpenMPDirectiveKind CancelRegion) {
  7730. if (DSAStack->isParentNowaitRegion()) {
  7731. Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
  7732. return StmtError();
  7733. }
  7734. if (DSAStack->isParentOrderedRegion()) {
  7735. Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
  7736. return StmtError();
  7737. }
  7738. DSAStack->setParentCancelRegion(/*Cancel=*/true);
  7739. return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
  7740. CancelRegion);
  7741. }
  7742. static bool checkGrainsizeNumTasksClauses(Sema &S,
  7743. ArrayRef<OMPClause *> Clauses) {
  7744. const OMPClause *PrevClause = nullptr;
  7745. bool ErrorFound = false;
  7746. for (const OMPClause *C : Clauses) {
  7747. if (C->getClauseKind() == OMPC_grainsize ||
  7748. C->getClauseKind() == OMPC_num_tasks) {
  7749. if (!PrevClause)
  7750. PrevClause = C;
  7751. else if (PrevClause->getClauseKind() != C->getClauseKind()) {
  7752. S.Diag(C->getBeginLoc(),
  7753. diag::err_omp_grainsize_num_tasks_mutually_exclusive)
  7754. << getOpenMPClauseName(C->getClauseKind())
  7755. << getOpenMPClauseName(PrevClause->getClauseKind());
  7756. S.Diag(PrevClause->getBeginLoc(),
  7757. diag::note_omp_previous_grainsize_num_tasks)
  7758. << getOpenMPClauseName(PrevClause->getClauseKind());
  7759. ErrorFound = true;
  7760. }
  7761. }
  7762. }
  7763. return ErrorFound;
  7764. }
  7765. static bool checkReductionClauseWithNogroup(Sema &S,
  7766. ArrayRef<OMPClause *> Clauses) {
  7767. const OMPClause *ReductionClause = nullptr;
  7768. const OMPClause *NogroupClause = nullptr;
  7769. for (const OMPClause *C : Clauses) {
  7770. if (C->getClauseKind() == OMPC_reduction) {
  7771. ReductionClause = C;
  7772. if (NogroupClause)
  7773. break;
  7774. continue;
  7775. }
  7776. if (C->getClauseKind() == OMPC_nogroup) {
  7777. NogroupClause = C;
  7778. if (ReductionClause)
  7779. break;
  7780. continue;
  7781. }
  7782. }
  7783. if (ReductionClause && NogroupClause) {
  7784. S.Diag(ReductionClause->getBeginLoc(), diag::err_omp_reduction_with_nogroup)
  7785. << SourceRange(NogroupClause->getBeginLoc(),
  7786. NogroupClause->getEndLoc());
  7787. return true;
  7788. }
  7789. return false;
  7790. }
  7791. StmtResult Sema::ActOnOpenMPTaskLoopDirective(
  7792. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  7793. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  7794. if (!AStmt)
  7795. return StmtError();
  7796. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  7797. OMPLoopDirective::HelperExprs B;
  7798. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  7799. // define the nested loops number.
  7800. unsigned NestedLoopCount =
  7801. checkOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
  7802. /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
  7803. VarsWithImplicitDSA, B);
  7804. if (NestedLoopCount == 0)
  7805. return StmtError();
  7806. assert((CurContext->isDependentContext() || B.builtAll()) &&
  7807. "omp for loop exprs were not built");
  7808. // OpenMP, [2.9.2 taskloop Construct, Restrictions]
  7809. // The grainsize clause and num_tasks clause are mutually exclusive and may
  7810. // not appear on the same taskloop directive.
  7811. if (checkGrainsizeNumTasksClauses(*this, Clauses))
  7812. return StmtError();
  7813. // OpenMP, [2.9.2 taskloop Construct, Restrictions]
  7814. // If a reduction clause is present on the taskloop directive, the nogroup
  7815. // clause must not be specified.
  7816. if (checkReductionClauseWithNogroup(*this, Clauses))
  7817. return StmtError();
  7818. setFunctionHasBranchProtectedScope();
  7819. return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
  7820. NestedLoopCount, Clauses, AStmt, B);
  7821. }
  7822. StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
  7823. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  7824. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  7825. if (!AStmt)
  7826. return StmtError();
  7827. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  7828. OMPLoopDirective::HelperExprs B;
  7829. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  7830. // define the nested loops number.
  7831. unsigned NestedLoopCount =
  7832. checkOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
  7833. /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
  7834. VarsWithImplicitDSA, B);
  7835. if (NestedLoopCount == 0)
  7836. return StmtError();
  7837. assert((CurContext->isDependentContext() || B.builtAll()) &&
  7838. "omp for loop exprs were not built");
  7839. if (!CurContext->isDependentContext()) {
  7840. // Finalize the clauses that need pre-built expressions for CodeGen.
  7841. for (OMPClause *C : Clauses) {
  7842. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  7843. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  7844. B.NumIterations, *this, CurScope,
  7845. DSAStack))
  7846. return StmtError();
  7847. }
  7848. }
  7849. // OpenMP, [2.9.2 taskloop Construct, Restrictions]
  7850. // The grainsize clause and num_tasks clause are mutually exclusive and may
  7851. // not appear on the same taskloop directive.
  7852. if (checkGrainsizeNumTasksClauses(*this, Clauses))
  7853. return StmtError();
  7854. // OpenMP, [2.9.2 taskloop Construct, Restrictions]
  7855. // If a reduction clause is present on the taskloop directive, the nogroup
  7856. // clause must not be specified.
  7857. if (checkReductionClauseWithNogroup(*this, Clauses))
  7858. return StmtError();
  7859. if (checkSimdlenSafelenSpecified(*this, Clauses))
  7860. return StmtError();
  7861. setFunctionHasBranchProtectedScope();
  7862. return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
  7863. NestedLoopCount, Clauses, AStmt, B);
  7864. }
  7865. StmtResult Sema::ActOnOpenMPDistributeDirective(
  7866. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  7867. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  7868. if (!AStmt)
  7869. return StmtError();
  7870. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  7871. OMPLoopDirective::HelperExprs B;
  7872. // In presence of clause 'collapse' with number of loops, it will
  7873. // define the nested loops number.
  7874. unsigned NestedLoopCount =
  7875. checkOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
  7876. nullptr /*ordered not a clause on distribute*/, AStmt,
  7877. *this, *DSAStack, VarsWithImplicitDSA, B);
  7878. if (NestedLoopCount == 0)
  7879. return StmtError();
  7880. assert((CurContext->isDependentContext() || B.builtAll()) &&
  7881. "omp for loop exprs were not built");
  7882. setFunctionHasBranchProtectedScope();
  7883. return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
  7884. NestedLoopCount, Clauses, AStmt, B);
  7885. }
  7886. StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
  7887. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  7888. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  7889. if (!AStmt)
  7890. return StmtError();
  7891. auto *CS = cast<CapturedStmt>(AStmt);
  7892. // 1.2.2 OpenMP Language Terminology
  7893. // Structured block - An executable statement with a single entry at the
  7894. // top and a single exit at the bottom.
  7895. // The point of exit cannot be a branch out of the structured block.
  7896. // longjmp() and throw() must not violate the entry/exit criteria.
  7897. CS->getCapturedDecl()->setNothrow();
  7898. for (int ThisCaptureLevel =
  7899. getOpenMPCaptureLevels(OMPD_distribute_parallel_for);
  7900. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  7901. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  7902. // 1.2.2 OpenMP Language Terminology
  7903. // Structured block - An executable statement with a single entry at the
  7904. // top and a single exit at the bottom.
  7905. // The point of exit cannot be a branch out of the structured block.
  7906. // longjmp() and throw() must not violate the entry/exit criteria.
  7907. CS->getCapturedDecl()->setNothrow();
  7908. }
  7909. OMPLoopDirective::HelperExprs B;
  7910. // In presence of clause 'collapse' with number of loops, it will
  7911. // define the nested loops number.
  7912. unsigned NestedLoopCount = checkOpenMPLoop(
  7913. OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
  7914. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  7915. VarsWithImplicitDSA, B);
  7916. if (NestedLoopCount == 0)
  7917. return StmtError();
  7918. assert((CurContext->isDependentContext() || B.builtAll()) &&
  7919. "omp for loop exprs were not built");
  7920. setFunctionHasBranchProtectedScope();
  7921. return OMPDistributeParallelForDirective::Create(
  7922. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
  7923. DSAStack->isCancelRegion());
  7924. }
  7925. StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
  7926. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  7927. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  7928. if (!AStmt)
  7929. return StmtError();
  7930. auto *CS = cast<CapturedStmt>(AStmt);
  7931. // 1.2.2 OpenMP Language Terminology
  7932. // Structured block - An executable statement with a single entry at the
  7933. // top and a single exit at the bottom.
  7934. // The point of exit cannot be a branch out of the structured block.
  7935. // longjmp() and throw() must not violate the entry/exit criteria.
  7936. CS->getCapturedDecl()->setNothrow();
  7937. for (int ThisCaptureLevel =
  7938. getOpenMPCaptureLevels(OMPD_distribute_parallel_for_simd);
  7939. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  7940. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  7941. // 1.2.2 OpenMP Language Terminology
  7942. // Structured block - An executable statement with a single entry at the
  7943. // top and a single exit at the bottom.
  7944. // The point of exit cannot be a branch out of the structured block.
  7945. // longjmp() and throw() must not violate the entry/exit criteria.
  7946. CS->getCapturedDecl()->setNothrow();
  7947. }
  7948. OMPLoopDirective::HelperExprs B;
  7949. // In presence of clause 'collapse' with number of loops, it will
  7950. // define the nested loops number.
  7951. unsigned NestedLoopCount = checkOpenMPLoop(
  7952. OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
  7953. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  7954. VarsWithImplicitDSA, B);
  7955. if (NestedLoopCount == 0)
  7956. return StmtError();
  7957. assert((CurContext->isDependentContext() || B.builtAll()) &&
  7958. "omp for loop exprs were not built");
  7959. if (!CurContext->isDependentContext()) {
  7960. // Finalize the clauses that need pre-built expressions for CodeGen.
  7961. for (OMPClause *C : Clauses) {
  7962. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  7963. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  7964. B.NumIterations, *this, CurScope,
  7965. DSAStack))
  7966. return StmtError();
  7967. }
  7968. }
  7969. if (checkSimdlenSafelenSpecified(*this, Clauses))
  7970. return StmtError();
  7971. setFunctionHasBranchProtectedScope();
  7972. return OMPDistributeParallelForSimdDirective::Create(
  7973. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  7974. }
  7975. StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
  7976. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  7977. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  7978. if (!AStmt)
  7979. return StmtError();
  7980. auto *CS = cast<CapturedStmt>(AStmt);
  7981. // 1.2.2 OpenMP Language Terminology
  7982. // Structured block - An executable statement with a single entry at the
  7983. // top and a single exit at the bottom.
  7984. // The point of exit cannot be a branch out of the structured block.
  7985. // longjmp() and throw() must not violate the entry/exit criteria.
  7986. CS->getCapturedDecl()->setNothrow();
  7987. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_distribute_simd);
  7988. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  7989. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  7990. // 1.2.2 OpenMP Language Terminology
  7991. // Structured block - An executable statement with a single entry at the
  7992. // top and a single exit at the bottom.
  7993. // The point of exit cannot be a branch out of the structured block.
  7994. // longjmp() and throw() must not violate the entry/exit criteria.
  7995. CS->getCapturedDecl()->setNothrow();
  7996. }
  7997. OMPLoopDirective::HelperExprs B;
  7998. // In presence of clause 'collapse' with number of loops, it will
  7999. // define the nested loops number.
  8000. unsigned NestedLoopCount =
  8001. checkOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
  8002. nullptr /*ordered not a clause on distribute*/, CS, *this,
  8003. *DSAStack, VarsWithImplicitDSA, B);
  8004. if (NestedLoopCount == 0)
  8005. return StmtError();
  8006. assert((CurContext->isDependentContext() || B.builtAll()) &&
  8007. "omp for loop exprs were not built");
  8008. if (!CurContext->isDependentContext()) {
  8009. // Finalize the clauses that need pre-built expressions for CodeGen.
  8010. for (OMPClause *C : Clauses) {
  8011. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  8012. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  8013. B.NumIterations, *this, CurScope,
  8014. DSAStack))
  8015. return StmtError();
  8016. }
  8017. }
  8018. if (checkSimdlenSafelenSpecified(*this, Clauses))
  8019. return StmtError();
  8020. setFunctionHasBranchProtectedScope();
  8021. return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
  8022. NestedLoopCount, Clauses, AStmt, B);
  8023. }
  8024. StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
  8025. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  8026. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  8027. if (!AStmt)
  8028. return StmtError();
  8029. auto *CS = cast<CapturedStmt>(AStmt);
  8030. // 1.2.2 OpenMP Language Terminology
  8031. // Structured block - An executable statement with a single entry at the
  8032. // top and a single exit at the bottom.
  8033. // The point of exit cannot be a branch out of the structured block.
  8034. // longjmp() and throw() must not violate the entry/exit criteria.
  8035. CS->getCapturedDecl()->setNothrow();
  8036. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
  8037. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  8038. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  8039. // 1.2.2 OpenMP Language Terminology
  8040. // Structured block - An executable statement with a single entry at the
  8041. // top and a single exit at the bottom.
  8042. // The point of exit cannot be a branch out of the structured block.
  8043. // longjmp() and throw() must not violate the entry/exit criteria.
  8044. CS->getCapturedDecl()->setNothrow();
  8045. }
  8046. OMPLoopDirective::HelperExprs B;
  8047. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  8048. // define the nested loops number.
  8049. unsigned NestedLoopCount = checkOpenMPLoop(
  8050. OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
  8051. getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
  8052. VarsWithImplicitDSA, B);
  8053. if (NestedLoopCount == 0)
  8054. return StmtError();
  8055. assert((CurContext->isDependentContext() || B.builtAll()) &&
  8056. "omp target parallel for simd loop exprs were not built");
  8057. if (!CurContext->isDependentContext()) {
  8058. // Finalize the clauses that need pre-built expressions for CodeGen.
  8059. for (OMPClause *C : Clauses) {
  8060. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  8061. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  8062. B.NumIterations, *this, CurScope,
  8063. DSAStack))
  8064. return StmtError();
  8065. }
  8066. }
  8067. if (checkSimdlenSafelenSpecified(*this, Clauses))
  8068. return StmtError();
  8069. setFunctionHasBranchProtectedScope();
  8070. return OMPTargetParallelForSimdDirective::Create(
  8071. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  8072. }
  8073. StmtResult Sema::ActOnOpenMPTargetSimdDirective(
  8074. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  8075. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  8076. if (!AStmt)
  8077. return StmtError();
  8078. auto *CS = cast<CapturedStmt>(AStmt);
  8079. // 1.2.2 OpenMP Language Terminology
  8080. // Structured block - An executable statement with a single entry at the
  8081. // top and a single exit at the bottom.
  8082. // The point of exit cannot be a branch out of the structured block.
  8083. // longjmp() and throw() must not violate the entry/exit criteria.
  8084. CS->getCapturedDecl()->setNothrow();
  8085. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_simd);
  8086. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  8087. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  8088. // 1.2.2 OpenMP Language Terminology
  8089. // Structured block - An executable statement with a single entry at the
  8090. // top and a single exit at the bottom.
  8091. // The point of exit cannot be a branch out of the structured block.
  8092. // longjmp() and throw() must not violate the entry/exit criteria.
  8093. CS->getCapturedDecl()->setNothrow();
  8094. }
  8095. OMPLoopDirective::HelperExprs B;
  8096. // In presence of clause 'collapse' with number of loops, it will define the
  8097. // nested loops number.
  8098. unsigned NestedLoopCount =
  8099. checkOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
  8100. getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
  8101. VarsWithImplicitDSA, B);
  8102. if (NestedLoopCount == 0)
  8103. return StmtError();
  8104. assert((CurContext->isDependentContext() || B.builtAll()) &&
  8105. "omp target simd loop exprs were not built");
  8106. if (!CurContext->isDependentContext()) {
  8107. // Finalize the clauses that need pre-built expressions for CodeGen.
  8108. for (OMPClause *C : Clauses) {
  8109. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  8110. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  8111. B.NumIterations, *this, CurScope,
  8112. DSAStack))
  8113. return StmtError();
  8114. }
  8115. }
  8116. if (checkSimdlenSafelenSpecified(*this, Clauses))
  8117. return StmtError();
  8118. setFunctionHasBranchProtectedScope();
  8119. return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
  8120. NestedLoopCount, Clauses, AStmt, B);
  8121. }
  8122. StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
  8123. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  8124. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  8125. if (!AStmt)
  8126. return StmtError();
  8127. auto *CS = cast<CapturedStmt>(AStmt);
  8128. // 1.2.2 OpenMP Language Terminology
  8129. // Structured block - An executable statement with a single entry at the
  8130. // top and a single exit at the bottom.
  8131. // The point of exit cannot be a branch out of the structured block.
  8132. // longjmp() and throw() must not violate the entry/exit criteria.
  8133. CS->getCapturedDecl()->setNothrow();
  8134. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_teams_distribute);
  8135. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  8136. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  8137. // 1.2.2 OpenMP Language Terminology
  8138. // Structured block - An executable statement with a single entry at the
  8139. // top and a single exit at the bottom.
  8140. // The point of exit cannot be a branch out of the structured block.
  8141. // longjmp() and throw() must not violate the entry/exit criteria.
  8142. CS->getCapturedDecl()->setNothrow();
  8143. }
  8144. OMPLoopDirective::HelperExprs B;
  8145. // In presence of clause 'collapse' with number of loops, it will
  8146. // define the nested loops number.
  8147. unsigned NestedLoopCount =
  8148. checkOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
  8149. nullptr /*ordered not a clause on distribute*/, CS, *this,
  8150. *DSAStack, VarsWithImplicitDSA, B);
  8151. if (NestedLoopCount == 0)
  8152. return StmtError();
  8153. assert((CurContext->isDependentContext() || B.builtAll()) &&
  8154. "omp teams distribute loop exprs were not built");
  8155. setFunctionHasBranchProtectedScope();
  8156. DSAStack->setParentTeamsRegionLoc(StartLoc);
  8157. return OMPTeamsDistributeDirective::Create(
  8158. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  8159. }
  8160. StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
  8161. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  8162. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  8163. if (!AStmt)
  8164. return StmtError();
  8165. auto *CS = cast<CapturedStmt>(AStmt);
  8166. // 1.2.2 OpenMP Language Terminology
  8167. // Structured block - An executable statement with a single entry at the
  8168. // top and a single exit at the bottom.
  8169. // The point of exit cannot be a branch out of the structured block.
  8170. // longjmp() and throw() must not violate the entry/exit criteria.
  8171. CS->getCapturedDecl()->setNothrow();
  8172. for (int ThisCaptureLevel =
  8173. getOpenMPCaptureLevels(OMPD_teams_distribute_simd);
  8174. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  8175. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  8176. // 1.2.2 OpenMP Language Terminology
  8177. // Structured block - An executable statement with a single entry at the
  8178. // top and a single exit at the bottom.
  8179. // The point of exit cannot be a branch out of the structured block.
  8180. // longjmp() and throw() must not violate the entry/exit criteria.
  8181. CS->getCapturedDecl()->setNothrow();
  8182. }
  8183. OMPLoopDirective::HelperExprs B;
  8184. // In presence of clause 'collapse' with number of loops, it will
  8185. // define the nested loops number.
  8186. unsigned NestedLoopCount = checkOpenMPLoop(
  8187. OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
  8188. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  8189. VarsWithImplicitDSA, B);
  8190. if (NestedLoopCount == 0)
  8191. return StmtError();
  8192. assert((CurContext->isDependentContext() || B.builtAll()) &&
  8193. "omp teams distribute simd loop exprs were not built");
  8194. if (!CurContext->isDependentContext()) {
  8195. // Finalize the clauses that need pre-built expressions for CodeGen.
  8196. for (OMPClause *C : Clauses) {
  8197. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  8198. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  8199. B.NumIterations, *this, CurScope,
  8200. DSAStack))
  8201. return StmtError();
  8202. }
  8203. }
  8204. if (checkSimdlenSafelenSpecified(*this, Clauses))
  8205. return StmtError();
  8206. setFunctionHasBranchProtectedScope();
  8207. DSAStack->setParentTeamsRegionLoc(StartLoc);
  8208. return OMPTeamsDistributeSimdDirective::Create(
  8209. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  8210. }
  8211. StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
  8212. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  8213. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  8214. if (!AStmt)
  8215. return StmtError();
  8216. auto *CS = cast<CapturedStmt>(AStmt);
  8217. // 1.2.2 OpenMP Language Terminology
  8218. // Structured block - An executable statement with a single entry at the
  8219. // top and a single exit at the bottom.
  8220. // The point of exit cannot be a branch out of the structured block.
  8221. // longjmp() and throw() must not violate the entry/exit criteria.
  8222. CS->getCapturedDecl()->setNothrow();
  8223. for (int ThisCaptureLevel =
  8224. getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for_simd);
  8225. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  8226. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  8227. // 1.2.2 OpenMP Language Terminology
  8228. // Structured block - An executable statement with a single entry at the
  8229. // top and a single exit at the bottom.
  8230. // The point of exit cannot be a branch out of the structured block.
  8231. // longjmp() and throw() must not violate the entry/exit criteria.
  8232. CS->getCapturedDecl()->setNothrow();
  8233. }
  8234. OMPLoopDirective::HelperExprs B;
  8235. // In presence of clause 'collapse' with number of loops, it will
  8236. // define the nested loops number.
  8237. unsigned NestedLoopCount = checkOpenMPLoop(
  8238. OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
  8239. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  8240. VarsWithImplicitDSA, B);
  8241. if (NestedLoopCount == 0)
  8242. return StmtError();
  8243. assert((CurContext->isDependentContext() || B.builtAll()) &&
  8244. "omp for loop exprs were not built");
  8245. if (!CurContext->isDependentContext()) {
  8246. // Finalize the clauses that need pre-built expressions for CodeGen.
  8247. for (OMPClause *C : Clauses) {
  8248. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  8249. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  8250. B.NumIterations, *this, CurScope,
  8251. DSAStack))
  8252. return StmtError();
  8253. }
  8254. }
  8255. if (checkSimdlenSafelenSpecified(*this, Clauses))
  8256. return StmtError();
  8257. setFunctionHasBranchProtectedScope();
  8258. DSAStack->setParentTeamsRegionLoc(StartLoc);
  8259. return OMPTeamsDistributeParallelForSimdDirective::Create(
  8260. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  8261. }
  8262. StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
  8263. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  8264. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  8265. if (!AStmt)
  8266. return StmtError();
  8267. auto *CS = cast<CapturedStmt>(AStmt);
  8268. // 1.2.2 OpenMP Language Terminology
  8269. // Structured block - An executable statement with a single entry at the
  8270. // top and a single exit at the bottom.
  8271. // The point of exit cannot be a branch out of the structured block.
  8272. // longjmp() and throw() must not violate the entry/exit criteria.
  8273. CS->getCapturedDecl()->setNothrow();
  8274. for (int ThisCaptureLevel =
  8275. getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for);
  8276. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  8277. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  8278. // 1.2.2 OpenMP Language Terminology
  8279. // Structured block - An executable statement with a single entry at the
  8280. // top and a single exit at the bottom.
  8281. // The point of exit cannot be a branch out of the structured block.
  8282. // longjmp() and throw() must not violate the entry/exit criteria.
  8283. CS->getCapturedDecl()->setNothrow();
  8284. }
  8285. OMPLoopDirective::HelperExprs B;
  8286. // In presence of clause 'collapse' with number of loops, it will
  8287. // define the nested loops number.
  8288. unsigned NestedLoopCount = checkOpenMPLoop(
  8289. OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
  8290. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  8291. VarsWithImplicitDSA, B);
  8292. if (NestedLoopCount == 0)
  8293. return StmtError();
  8294. assert((CurContext->isDependentContext() || B.builtAll()) &&
  8295. "omp for loop exprs were not built");
  8296. setFunctionHasBranchProtectedScope();
  8297. DSAStack->setParentTeamsRegionLoc(StartLoc);
  8298. return OMPTeamsDistributeParallelForDirective::Create(
  8299. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
  8300. DSAStack->isCancelRegion());
  8301. }
  8302. StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
  8303. Stmt *AStmt,
  8304. SourceLocation StartLoc,
  8305. SourceLocation EndLoc) {
  8306. if (!AStmt)
  8307. return StmtError();
  8308. auto *CS = cast<CapturedStmt>(AStmt);
  8309. // 1.2.2 OpenMP Language Terminology
  8310. // Structured block - An executable statement with a single entry at the
  8311. // top and a single exit at the bottom.
  8312. // The point of exit cannot be a branch out of the structured block.
  8313. // longjmp() and throw() must not violate the entry/exit criteria.
  8314. CS->getCapturedDecl()->setNothrow();
  8315. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_teams);
  8316. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  8317. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  8318. // 1.2.2 OpenMP Language Terminology
  8319. // Structured block - An executable statement with a single entry at the
  8320. // top and a single exit at the bottom.
  8321. // The point of exit cannot be a branch out of the structured block.
  8322. // longjmp() and throw() must not violate the entry/exit criteria.
  8323. CS->getCapturedDecl()->setNothrow();
  8324. }
  8325. setFunctionHasBranchProtectedScope();
  8326. return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
  8327. AStmt);
  8328. }
  8329. StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective(
  8330. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  8331. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  8332. if (!AStmt)
  8333. return StmtError();
  8334. auto *CS = cast<CapturedStmt>(AStmt);
  8335. // 1.2.2 OpenMP Language Terminology
  8336. // Structured block - An executable statement with a single entry at the
  8337. // top and a single exit at the bottom.
  8338. // The point of exit cannot be a branch out of the structured block.
  8339. // longjmp() and throw() must not violate the entry/exit criteria.
  8340. CS->getCapturedDecl()->setNothrow();
  8341. for (int ThisCaptureLevel =
  8342. getOpenMPCaptureLevels(OMPD_target_teams_distribute);
  8343. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  8344. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  8345. // 1.2.2 OpenMP Language Terminology
  8346. // Structured block - An executable statement with a single entry at the
  8347. // top and a single exit at the bottom.
  8348. // The point of exit cannot be a branch out of the structured block.
  8349. // longjmp() and throw() must not violate the entry/exit criteria.
  8350. CS->getCapturedDecl()->setNothrow();
  8351. }
  8352. OMPLoopDirective::HelperExprs B;
  8353. // In presence of clause 'collapse' with number of loops, it will
  8354. // define the nested loops number.
  8355. unsigned NestedLoopCount = checkOpenMPLoop(
  8356. OMPD_target_teams_distribute, getCollapseNumberExpr(Clauses),
  8357. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  8358. VarsWithImplicitDSA, B);
  8359. if (NestedLoopCount == 0)
  8360. return StmtError();
  8361. assert((CurContext->isDependentContext() || B.builtAll()) &&
  8362. "omp target teams distribute loop exprs were not built");
  8363. setFunctionHasBranchProtectedScope();
  8364. return OMPTargetTeamsDistributeDirective::Create(
  8365. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  8366. }
  8367. StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective(
  8368. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  8369. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  8370. if (!AStmt)
  8371. return StmtError();
  8372. auto *CS = cast<CapturedStmt>(AStmt);
  8373. // 1.2.2 OpenMP Language Terminology
  8374. // Structured block - An executable statement with a single entry at the
  8375. // top and a single exit at the bottom.
  8376. // The point of exit cannot be a branch out of the structured block.
  8377. // longjmp() and throw() must not violate the entry/exit criteria.
  8378. CS->getCapturedDecl()->setNothrow();
  8379. for (int ThisCaptureLevel =
  8380. getOpenMPCaptureLevels(OMPD_target_teams_distribute_parallel_for);
  8381. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  8382. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  8383. // 1.2.2 OpenMP Language Terminology
  8384. // Structured block - An executable statement with a single entry at the
  8385. // top and a single exit at the bottom.
  8386. // The point of exit cannot be a branch out of the structured block.
  8387. // longjmp() and throw() must not violate the entry/exit criteria.
  8388. CS->getCapturedDecl()->setNothrow();
  8389. }
  8390. OMPLoopDirective::HelperExprs B;
  8391. // In presence of clause 'collapse' with number of loops, it will
  8392. // define the nested loops number.
  8393. unsigned NestedLoopCount = checkOpenMPLoop(
  8394. OMPD_target_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
  8395. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  8396. VarsWithImplicitDSA, B);
  8397. if (NestedLoopCount == 0)
  8398. return StmtError();
  8399. assert((CurContext->isDependentContext() || B.builtAll()) &&
  8400. "omp target teams distribute parallel for loop exprs were not built");
  8401. if (!CurContext->isDependentContext()) {
  8402. // Finalize the clauses that need pre-built expressions for CodeGen.
  8403. for (OMPClause *C : Clauses) {
  8404. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  8405. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  8406. B.NumIterations, *this, CurScope,
  8407. DSAStack))
  8408. return StmtError();
  8409. }
  8410. }
  8411. setFunctionHasBranchProtectedScope();
  8412. return OMPTargetTeamsDistributeParallelForDirective::Create(
  8413. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
  8414. DSAStack->isCancelRegion());
  8415. }
  8416. StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
  8417. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  8418. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  8419. if (!AStmt)
  8420. return StmtError();
  8421. auto *CS = cast<CapturedStmt>(AStmt);
  8422. // 1.2.2 OpenMP Language Terminology
  8423. // Structured block - An executable statement with a single entry at the
  8424. // top and a single exit at the bottom.
  8425. // The point of exit cannot be a branch out of the structured block.
  8426. // longjmp() and throw() must not violate the entry/exit criteria.
  8427. CS->getCapturedDecl()->setNothrow();
  8428. for (int ThisCaptureLevel = getOpenMPCaptureLevels(
  8429. OMPD_target_teams_distribute_parallel_for_simd);
  8430. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  8431. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  8432. // 1.2.2 OpenMP Language Terminology
  8433. // Structured block - An executable statement with a single entry at the
  8434. // top and a single exit at the bottom.
  8435. // The point of exit cannot be a branch out of the structured block.
  8436. // longjmp() and throw() must not violate the entry/exit criteria.
  8437. CS->getCapturedDecl()->setNothrow();
  8438. }
  8439. OMPLoopDirective::HelperExprs B;
  8440. // In presence of clause 'collapse' with number of loops, it will
  8441. // define the nested loops number.
  8442. unsigned NestedLoopCount =
  8443. checkOpenMPLoop(OMPD_target_teams_distribute_parallel_for_simd,
  8444. getCollapseNumberExpr(Clauses),
  8445. nullptr /*ordered not a clause on distribute*/, CS, *this,
  8446. *DSAStack, VarsWithImplicitDSA, B);
  8447. if (NestedLoopCount == 0)
  8448. return StmtError();
  8449. assert((CurContext->isDependentContext() || B.builtAll()) &&
  8450. "omp target teams distribute parallel for simd loop exprs were not "
  8451. "built");
  8452. if (!CurContext->isDependentContext()) {
  8453. // Finalize the clauses that need pre-built expressions for CodeGen.
  8454. for (OMPClause *C : Clauses) {
  8455. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  8456. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  8457. B.NumIterations, *this, CurScope,
  8458. DSAStack))
  8459. return StmtError();
  8460. }
  8461. }
  8462. if (checkSimdlenSafelenSpecified(*this, Clauses))
  8463. return StmtError();
  8464. setFunctionHasBranchProtectedScope();
  8465. return OMPTargetTeamsDistributeParallelForSimdDirective::Create(
  8466. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  8467. }
  8468. StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective(
  8469. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  8470. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  8471. if (!AStmt)
  8472. return StmtError();
  8473. auto *CS = cast<CapturedStmt>(AStmt);
  8474. // 1.2.2 OpenMP Language Terminology
  8475. // Structured block - An executable statement with a single entry at the
  8476. // top and a single exit at the bottom.
  8477. // The point of exit cannot be a branch out of the structured block.
  8478. // longjmp() and throw() must not violate the entry/exit criteria.
  8479. CS->getCapturedDecl()->setNothrow();
  8480. for (int ThisCaptureLevel =
  8481. getOpenMPCaptureLevels(OMPD_target_teams_distribute_simd);
  8482. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  8483. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  8484. // 1.2.2 OpenMP Language Terminology
  8485. // Structured block - An executable statement with a single entry at the
  8486. // top and a single exit at the bottom.
  8487. // The point of exit cannot be a branch out of the structured block.
  8488. // longjmp() and throw() must not violate the entry/exit criteria.
  8489. CS->getCapturedDecl()->setNothrow();
  8490. }
  8491. OMPLoopDirective::HelperExprs B;
  8492. // In presence of clause 'collapse' with number of loops, it will
  8493. // define the nested loops number.
  8494. unsigned NestedLoopCount = checkOpenMPLoop(
  8495. OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses),
  8496. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  8497. VarsWithImplicitDSA, B);
  8498. if (NestedLoopCount == 0)
  8499. return StmtError();
  8500. assert((CurContext->isDependentContext() || B.builtAll()) &&
  8501. "omp target teams distribute simd loop exprs were not built");
  8502. if (!CurContext->isDependentContext()) {
  8503. // Finalize the clauses that need pre-built expressions for CodeGen.
  8504. for (OMPClause *C : Clauses) {
  8505. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  8506. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  8507. B.NumIterations, *this, CurScope,
  8508. DSAStack))
  8509. return StmtError();
  8510. }
  8511. }
  8512. if (checkSimdlenSafelenSpecified(*this, Clauses))
  8513. return StmtError();
  8514. setFunctionHasBranchProtectedScope();
  8515. return OMPTargetTeamsDistributeSimdDirective::Create(
  8516. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  8517. }
  8518. OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
  8519. SourceLocation StartLoc,
  8520. SourceLocation LParenLoc,
  8521. SourceLocation EndLoc) {
  8522. OMPClause *Res = nullptr;
  8523. switch (Kind) {
  8524. case OMPC_final:
  8525. Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
  8526. break;
  8527. case OMPC_num_threads:
  8528. Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
  8529. break;
  8530. case OMPC_safelen:
  8531. Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
  8532. break;
  8533. case OMPC_simdlen:
  8534. Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
  8535. break;
  8536. case OMPC_allocator:
  8537. Res = ActOnOpenMPAllocatorClause(Expr, StartLoc, LParenLoc, EndLoc);
  8538. break;
  8539. case OMPC_collapse:
  8540. Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
  8541. break;
  8542. case OMPC_ordered:
  8543. Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
  8544. break;
  8545. case OMPC_device:
  8546. Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
  8547. break;
  8548. case OMPC_num_teams:
  8549. Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
  8550. break;
  8551. case OMPC_thread_limit:
  8552. Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
  8553. break;
  8554. case OMPC_priority:
  8555. Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
  8556. break;
  8557. case OMPC_grainsize:
  8558. Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
  8559. break;
  8560. case OMPC_num_tasks:
  8561. Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
  8562. break;
  8563. case OMPC_hint:
  8564. Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
  8565. break;
  8566. case OMPC_if:
  8567. case OMPC_default:
  8568. case OMPC_proc_bind:
  8569. case OMPC_schedule:
  8570. case OMPC_private:
  8571. case OMPC_firstprivate:
  8572. case OMPC_lastprivate:
  8573. case OMPC_shared:
  8574. case OMPC_reduction:
  8575. case OMPC_task_reduction:
  8576. case OMPC_in_reduction:
  8577. case OMPC_linear:
  8578. case OMPC_aligned:
  8579. case OMPC_copyin:
  8580. case OMPC_copyprivate:
  8581. case OMPC_nowait:
  8582. case OMPC_untied:
  8583. case OMPC_mergeable:
  8584. case OMPC_threadprivate:
  8585. case OMPC_allocate:
  8586. case OMPC_flush:
  8587. case OMPC_read:
  8588. case OMPC_write:
  8589. case OMPC_update:
  8590. case OMPC_capture:
  8591. case OMPC_seq_cst:
  8592. case OMPC_depend:
  8593. case OMPC_threads:
  8594. case OMPC_simd:
  8595. case OMPC_map:
  8596. case OMPC_nogroup:
  8597. case OMPC_dist_schedule:
  8598. case OMPC_defaultmap:
  8599. case OMPC_unknown:
  8600. case OMPC_uniform:
  8601. case OMPC_to:
  8602. case OMPC_from:
  8603. case OMPC_use_device_ptr:
  8604. case OMPC_is_device_ptr:
  8605. case OMPC_unified_address:
  8606. case OMPC_unified_shared_memory:
  8607. case OMPC_reverse_offload:
  8608. case OMPC_dynamic_allocators:
  8609. case OMPC_atomic_default_mem_order:
  8610. llvm_unreachable("Clause is not allowed.");
  8611. }
  8612. return Res;
  8613. }
  8614. // An OpenMP directive such as 'target parallel' has two captured regions:
  8615. // for the 'target' and 'parallel' respectively. This function returns
  8616. // the region in which to capture expressions associated with a clause.
  8617. // A return value of OMPD_unknown signifies that the expression should not
  8618. // be captured.
  8619. static OpenMPDirectiveKind getOpenMPCaptureRegionForClause(
  8620. OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
  8621. OpenMPDirectiveKind NameModifier = OMPD_unknown) {
  8622. OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
  8623. switch (CKind) {
  8624. case OMPC_if:
  8625. switch (DKind) {
  8626. case OMPD_target_parallel:
  8627. case OMPD_target_parallel_for:
  8628. case OMPD_target_parallel_for_simd:
  8629. // If this clause applies to the nested 'parallel' region, capture within
  8630. // the 'target' region, otherwise do not capture.
  8631. if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
  8632. CaptureRegion = OMPD_target;
  8633. break;
  8634. case OMPD_target_teams_distribute_parallel_for:
  8635. case OMPD_target_teams_distribute_parallel_for_simd:
  8636. // If this clause applies to the nested 'parallel' region, capture within
  8637. // the 'teams' region, otherwise do not capture.
  8638. if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
  8639. CaptureRegion = OMPD_teams;
  8640. break;
  8641. case OMPD_teams_distribute_parallel_for:
  8642. case OMPD_teams_distribute_parallel_for_simd:
  8643. CaptureRegion = OMPD_teams;
  8644. break;
  8645. case OMPD_target_update:
  8646. case OMPD_target_enter_data:
  8647. case OMPD_target_exit_data:
  8648. CaptureRegion = OMPD_task;
  8649. break;
  8650. case OMPD_cancel:
  8651. case OMPD_parallel:
  8652. case OMPD_parallel_sections:
  8653. case OMPD_parallel_for:
  8654. case OMPD_parallel_for_simd:
  8655. case OMPD_target:
  8656. case OMPD_target_simd:
  8657. case OMPD_target_teams:
  8658. case OMPD_target_teams_distribute:
  8659. case OMPD_target_teams_distribute_simd:
  8660. case OMPD_distribute_parallel_for:
  8661. case OMPD_distribute_parallel_for_simd:
  8662. case OMPD_task:
  8663. case OMPD_taskloop:
  8664. case OMPD_taskloop_simd:
  8665. case OMPD_target_data:
  8666. // Do not capture if-clause expressions.
  8667. break;
  8668. case OMPD_threadprivate:
  8669. case OMPD_allocate:
  8670. case OMPD_taskyield:
  8671. case OMPD_barrier:
  8672. case OMPD_taskwait:
  8673. case OMPD_cancellation_point:
  8674. case OMPD_flush:
  8675. case OMPD_declare_reduction:
  8676. case OMPD_declare_mapper:
  8677. case OMPD_declare_simd:
  8678. case OMPD_declare_target:
  8679. case OMPD_end_declare_target:
  8680. case OMPD_teams:
  8681. case OMPD_simd:
  8682. case OMPD_for:
  8683. case OMPD_for_simd:
  8684. case OMPD_sections:
  8685. case OMPD_section:
  8686. case OMPD_single:
  8687. case OMPD_master:
  8688. case OMPD_critical:
  8689. case OMPD_taskgroup:
  8690. case OMPD_distribute:
  8691. case OMPD_ordered:
  8692. case OMPD_atomic:
  8693. case OMPD_distribute_simd:
  8694. case OMPD_teams_distribute:
  8695. case OMPD_teams_distribute_simd:
  8696. case OMPD_requires:
  8697. llvm_unreachable("Unexpected OpenMP directive with if-clause");
  8698. case OMPD_unknown:
  8699. llvm_unreachable("Unknown OpenMP directive");
  8700. }
  8701. break;
  8702. case OMPC_num_threads:
  8703. switch (DKind) {
  8704. case OMPD_target_parallel:
  8705. case OMPD_target_parallel_for:
  8706. case OMPD_target_parallel_for_simd:
  8707. CaptureRegion = OMPD_target;
  8708. break;
  8709. case OMPD_teams_distribute_parallel_for:
  8710. case OMPD_teams_distribute_parallel_for_simd:
  8711. case OMPD_target_teams_distribute_parallel_for:
  8712. case OMPD_target_teams_distribute_parallel_for_simd:
  8713. CaptureRegion = OMPD_teams;
  8714. break;
  8715. case OMPD_parallel:
  8716. case OMPD_parallel_sections:
  8717. case OMPD_parallel_for:
  8718. case OMPD_parallel_for_simd:
  8719. case OMPD_distribute_parallel_for:
  8720. case OMPD_distribute_parallel_for_simd:
  8721. // Do not capture num_threads-clause expressions.
  8722. break;
  8723. case OMPD_target_data:
  8724. case OMPD_target_enter_data:
  8725. case OMPD_target_exit_data:
  8726. case OMPD_target_update:
  8727. case OMPD_target:
  8728. case OMPD_target_simd:
  8729. case OMPD_target_teams:
  8730. case OMPD_target_teams_distribute:
  8731. case OMPD_target_teams_distribute_simd:
  8732. case OMPD_cancel:
  8733. case OMPD_task:
  8734. case OMPD_taskloop:
  8735. case OMPD_taskloop_simd:
  8736. case OMPD_threadprivate:
  8737. case OMPD_allocate:
  8738. case OMPD_taskyield:
  8739. case OMPD_barrier:
  8740. case OMPD_taskwait:
  8741. case OMPD_cancellation_point:
  8742. case OMPD_flush:
  8743. case OMPD_declare_reduction:
  8744. case OMPD_declare_mapper:
  8745. case OMPD_declare_simd:
  8746. case OMPD_declare_target:
  8747. case OMPD_end_declare_target:
  8748. case OMPD_teams:
  8749. case OMPD_simd:
  8750. case OMPD_for:
  8751. case OMPD_for_simd:
  8752. case OMPD_sections:
  8753. case OMPD_section:
  8754. case OMPD_single:
  8755. case OMPD_master:
  8756. case OMPD_critical:
  8757. case OMPD_taskgroup:
  8758. case OMPD_distribute:
  8759. case OMPD_ordered:
  8760. case OMPD_atomic:
  8761. case OMPD_distribute_simd:
  8762. case OMPD_teams_distribute:
  8763. case OMPD_teams_distribute_simd:
  8764. case OMPD_requires:
  8765. llvm_unreachable("Unexpected OpenMP directive with num_threads-clause");
  8766. case OMPD_unknown:
  8767. llvm_unreachable("Unknown OpenMP directive");
  8768. }
  8769. break;
  8770. case OMPC_num_teams:
  8771. switch (DKind) {
  8772. case OMPD_target_teams:
  8773. case OMPD_target_teams_distribute:
  8774. case OMPD_target_teams_distribute_simd:
  8775. case OMPD_target_teams_distribute_parallel_for:
  8776. case OMPD_target_teams_distribute_parallel_for_simd:
  8777. CaptureRegion = OMPD_target;
  8778. break;
  8779. case OMPD_teams_distribute_parallel_for:
  8780. case OMPD_teams_distribute_parallel_for_simd:
  8781. case OMPD_teams:
  8782. case OMPD_teams_distribute:
  8783. case OMPD_teams_distribute_simd:
  8784. // Do not capture num_teams-clause expressions.
  8785. break;
  8786. case OMPD_distribute_parallel_for:
  8787. case OMPD_distribute_parallel_for_simd:
  8788. case OMPD_task:
  8789. case OMPD_taskloop:
  8790. case OMPD_taskloop_simd:
  8791. case OMPD_target_data:
  8792. case OMPD_target_enter_data:
  8793. case OMPD_target_exit_data:
  8794. case OMPD_target_update:
  8795. case OMPD_cancel:
  8796. case OMPD_parallel:
  8797. case OMPD_parallel_sections:
  8798. case OMPD_parallel_for:
  8799. case OMPD_parallel_for_simd:
  8800. case OMPD_target:
  8801. case OMPD_target_simd:
  8802. case OMPD_target_parallel:
  8803. case OMPD_target_parallel_for:
  8804. case OMPD_target_parallel_for_simd:
  8805. case OMPD_threadprivate:
  8806. case OMPD_allocate:
  8807. case OMPD_taskyield:
  8808. case OMPD_barrier:
  8809. case OMPD_taskwait:
  8810. case OMPD_cancellation_point:
  8811. case OMPD_flush:
  8812. case OMPD_declare_reduction:
  8813. case OMPD_declare_mapper:
  8814. case OMPD_declare_simd:
  8815. case OMPD_declare_target:
  8816. case OMPD_end_declare_target:
  8817. case OMPD_simd:
  8818. case OMPD_for:
  8819. case OMPD_for_simd:
  8820. case OMPD_sections:
  8821. case OMPD_section:
  8822. case OMPD_single:
  8823. case OMPD_master:
  8824. case OMPD_critical:
  8825. case OMPD_taskgroup:
  8826. case OMPD_distribute:
  8827. case OMPD_ordered:
  8828. case OMPD_atomic:
  8829. case OMPD_distribute_simd:
  8830. case OMPD_requires:
  8831. llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
  8832. case OMPD_unknown:
  8833. llvm_unreachable("Unknown OpenMP directive");
  8834. }
  8835. break;
  8836. case OMPC_thread_limit:
  8837. switch (DKind) {
  8838. case OMPD_target_teams:
  8839. case OMPD_target_teams_distribute:
  8840. case OMPD_target_teams_distribute_simd:
  8841. case OMPD_target_teams_distribute_parallel_for:
  8842. case OMPD_target_teams_distribute_parallel_for_simd:
  8843. CaptureRegion = OMPD_target;
  8844. break;
  8845. case OMPD_teams_distribute_parallel_for:
  8846. case OMPD_teams_distribute_parallel_for_simd:
  8847. case OMPD_teams:
  8848. case OMPD_teams_distribute:
  8849. case OMPD_teams_distribute_simd:
  8850. // Do not capture thread_limit-clause expressions.
  8851. break;
  8852. case OMPD_distribute_parallel_for:
  8853. case OMPD_distribute_parallel_for_simd:
  8854. case OMPD_task:
  8855. case OMPD_taskloop:
  8856. case OMPD_taskloop_simd:
  8857. case OMPD_target_data:
  8858. case OMPD_target_enter_data:
  8859. case OMPD_target_exit_data:
  8860. case OMPD_target_update:
  8861. case OMPD_cancel:
  8862. case OMPD_parallel:
  8863. case OMPD_parallel_sections:
  8864. case OMPD_parallel_for:
  8865. case OMPD_parallel_for_simd:
  8866. case OMPD_target:
  8867. case OMPD_target_simd:
  8868. case OMPD_target_parallel:
  8869. case OMPD_target_parallel_for:
  8870. case OMPD_target_parallel_for_simd:
  8871. case OMPD_threadprivate:
  8872. case OMPD_allocate:
  8873. case OMPD_taskyield:
  8874. case OMPD_barrier:
  8875. case OMPD_taskwait:
  8876. case OMPD_cancellation_point:
  8877. case OMPD_flush:
  8878. case OMPD_declare_reduction:
  8879. case OMPD_declare_mapper:
  8880. case OMPD_declare_simd:
  8881. case OMPD_declare_target:
  8882. case OMPD_end_declare_target:
  8883. case OMPD_simd:
  8884. case OMPD_for:
  8885. case OMPD_for_simd:
  8886. case OMPD_sections:
  8887. case OMPD_section:
  8888. case OMPD_single:
  8889. case OMPD_master:
  8890. case OMPD_critical:
  8891. case OMPD_taskgroup:
  8892. case OMPD_distribute:
  8893. case OMPD_ordered:
  8894. case OMPD_atomic:
  8895. case OMPD_distribute_simd:
  8896. case OMPD_requires:
  8897. llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause");
  8898. case OMPD_unknown:
  8899. llvm_unreachable("Unknown OpenMP directive");
  8900. }
  8901. break;
  8902. case OMPC_schedule:
  8903. switch (DKind) {
  8904. case OMPD_parallel_for:
  8905. case OMPD_parallel_for_simd:
  8906. case OMPD_distribute_parallel_for:
  8907. case OMPD_distribute_parallel_for_simd:
  8908. case OMPD_teams_distribute_parallel_for:
  8909. case OMPD_teams_distribute_parallel_for_simd:
  8910. case OMPD_target_parallel_for:
  8911. case OMPD_target_parallel_for_simd:
  8912. case OMPD_target_teams_distribute_parallel_for:
  8913. case OMPD_target_teams_distribute_parallel_for_simd:
  8914. CaptureRegion = OMPD_parallel;
  8915. break;
  8916. case OMPD_for:
  8917. case OMPD_for_simd:
  8918. // Do not capture schedule-clause expressions.
  8919. break;
  8920. case OMPD_task:
  8921. case OMPD_taskloop:
  8922. case OMPD_taskloop_simd:
  8923. case OMPD_target_data:
  8924. case OMPD_target_enter_data:
  8925. case OMPD_target_exit_data:
  8926. case OMPD_target_update:
  8927. case OMPD_teams:
  8928. case OMPD_teams_distribute:
  8929. case OMPD_teams_distribute_simd:
  8930. case OMPD_target_teams_distribute:
  8931. case OMPD_target_teams_distribute_simd:
  8932. case OMPD_target:
  8933. case OMPD_target_simd:
  8934. case OMPD_target_parallel:
  8935. case OMPD_cancel:
  8936. case OMPD_parallel:
  8937. case OMPD_parallel_sections:
  8938. case OMPD_threadprivate:
  8939. case OMPD_allocate:
  8940. case OMPD_taskyield:
  8941. case OMPD_barrier:
  8942. case OMPD_taskwait:
  8943. case OMPD_cancellation_point:
  8944. case OMPD_flush:
  8945. case OMPD_declare_reduction:
  8946. case OMPD_declare_mapper:
  8947. case OMPD_declare_simd:
  8948. case OMPD_declare_target:
  8949. case OMPD_end_declare_target:
  8950. case OMPD_simd:
  8951. case OMPD_sections:
  8952. case OMPD_section:
  8953. case OMPD_single:
  8954. case OMPD_master:
  8955. case OMPD_critical:
  8956. case OMPD_taskgroup:
  8957. case OMPD_distribute:
  8958. case OMPD_ordered:
  8959. case OMPD_atomic:
  8960. case OMPD_distribute_simd:
  8961. case OMPD_target_teams:
  8962. case OMPD_requires:
  8963. llvm_unreachable("Unexpected OpenMP directive with schedule clause");
  8964. case OMPD_unknown:
  8965. llvm_unreachable("Unknown OpenMP directive");
  8966. }
  8967. break;
  8968. case OMPC_dist_schedule:
  8969. switch (DKind) {
  8970. case OMPD_teams_distribute_parallel_for:
  8971. case OMPD_teams_distribute_parallel_for_simd:
  8972. case OMPD_teams_distribute:
  8973. case OMPD_teams_distribute_simd:
  8974. case OMPD_target_teams_distribute_parallel_for:
  8975. case OMPD_target_teams_distribute_parallel_for_simd:
  8976. case OMPD_target_teams_distribute:
  8977. case OMPD_target_teams_distribute_simd:
  8978. CaptureRegion = OMPD_teams;
  8979. break;
  8980. case OMPD_distribute_parallel_for:
  8981. case OMPD_distribute_parallel_for_simd:
  8982. case OMPD_distribute:
  8983. case OMPD_distribute_simd:
  8984. // Do not capture thread_limit-clause expressions.
  8985. break;
  8986. case OMPD_parallel_for:
  8987. case OMPD_parallel_for_simd:
  8988. case OMPD_target_parallel_for_simd:
  8989. case OMPD_target_parallel_for:
  8990. case OMPD_task:
  8991. case OMPD_taskloop:
  8992. case OMPD_taskloop_simd:
  8993. case OMPD_target_data:
  8994. case OMPD_target_enter_data:
  8995. case OMPD_target_exit_data:
  8996. case OMPD_target_update:
  8997. case OMPD_teams:
  8998. case OMPD_target:
  8999. case OMPD_target_simd:
  9000. case OMPD_target_parallel:
  9001. case OMPD_cancel:
  9002. case OMPD_parallel:
  9003. case OMPD_parallel_sections:
  9004. case OMPD_threadprivate:
  9005. case OMPD_allocate:
  9006. case OMPD_taskyield:
  9007. case OMPD_barrier:
  9008. case OMPD_taskwait:
  9009. case OMPD_cancellation_point:
  9010. case OMPD_flush:
  9011. case OMPD_declare_reduction:
  9012. case OMPD_declare_mapper:
  9013. case OMPD_declare_simd:
  9014. case OMPD_declare_target:
  9015. case OMPD_end_declare_target:
  9016. case OMPD_simd:
  9017. case OMPD_for:
  9018. case OMPD_for_simd:
  9019. case OMPD_sections:
  9020. case OMPD_section:
  9021. case OMPD_single:
  9022. case OMPD_master:
  9023. case OMPD_critical:
  9024. case OMPD_taskgroup:
  9025. case OMPD_ordered:
  9026. case OMPD_atomic:
  9027. case OMPD_target_teams:
  9028. case OMPD_requires:
  9029. llvm_unreachable("Unexpected OpenMP directive with schedule clause");
  9030. case OMPD_unknown:
  9031. llvm_unreachable("Unknown OpenMP directive");
  9032. }
  9033. break;
  9034. case OMPC_device:
  9035. switch (DKind) {
  9036. case OMPD_target_update:
  9037. case OMPD_target_enter_data:
  9038. case OMPD_target_exit_data:
  9039. case OMPD_target:
  9040. case OMPD_target_simd:
  9041. case OMPD_target_teams:
  9042. case OMPD_target_parallel:
  9043. case OMPD_target_teams_distribute:
  9044. case OMPD_target_teams_distribute_simd:
  9045. case OMPD_target_parallel_for:
  9046. case OMPD_target_parallel_for_simd:
  9047. case OMPD_target_teams_distribute_parallel_for:
  9048. case OMPD_target_teams_distribute_parallel_for_simd:
  9049. CaptureRegion = OMPD_task;
  9050. break;
  9051. case OMPD_target_data:
  9052. // Do not capture device-clause expressions.
  9053. break;
  9054. case OMPD_teams_distribute_parallel_for:
  9055. case OMPD_teams_distribute_parallel_for_simd:
  9056. case OMPD_teams:
  9057. case OMPD_teams_distribute:
  9058. case OMPD_teams_distribute_simd:
  9059. case OMPD_distribute_parallel_for:
  9060. case OMPD_distribute_parallel_for_simd:
  9061. case OMPD_task:
  9062. case OMPD_taskloop:
  9063. case OMPD_taskloop_simd:
  9064. case OMPD_cancel:
  9065. case OMPD_parallel:
  9066. case OMPD_parallel_sections:
  9067. case OMPD_parallel_for:
  9068. case OMPD_parallel_for_simd:
  9069. case OMPD_threadprivate:
  9070. case OMPD_allocate:
  9071. case OMPD_taskyield:
  9072. case OMPD_barrier:
  9073. case OMPD_taskwait:
  9074. case OMPD_cancellation_point:
  9075. case OMPD_flush:
  9076. case OMPD_declare_reduction:
  9077. case OMPD_declare_mapper:
  9078. case OMPD_declare_simd:
  9079. case OMPD_declare_target:
  9080. case OMPD_end_declare_target:
  9081. case OMPD_simd:
  9082. case OMPD_for:
  9083. case OMPD_for_simd:
  9084. case OMPD_sections:
  9085. case OMPD_section:
  9086. case OMPD_single:
  9087. case OMPD_master:
  9088. case OMPD_critical:
  9089. case OMPD_taskgroup:
  9090. case OMPD_distribute:
  9091. case OMPD_ordered:
  9092. case OMPD_atomic:
  9093. case OMPD_distribute_simd:
  9094. case OMPD_requires:
  9095. llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
  9096. case OMPD_unknown:
  9097. llvm_unreachable("Unknown OpenMP directive");
  9098. }
  9099. break;
  9100. case OMPC_firstprivate:
  9101. case OMPC_lastprivate:
  9102. case OMPC_reduction:
  9103. case OMPC_task_reduction:
  9104. case OMPC_in_reduction:
  9105. case OMPC_linear:
  9106. case OMPC_default:
  9107. case OMPC_proc_bind:
  9108. case OMPC_final:
  9109. case OMPC_safelen:
  9110. case OMPC_simdlen:
  9111. case OMPC_allocator:
  9112. case OMPC_collapse:
  9113. case OMPC_private:
  9114. case OMPC_shared:
  9115. case OMPC_aligned:
  9116. case OMPC_copyin:
  9117. case OMPC_copyprivate:
  9118. case OMPC_ordered:
  9119. case OMPC_nowait:
  9120. case OMPC_untied:
  9121. case OMPC_mergeable:
  9122. case OMPC_threadprivate:
  9123. case OMPC_allocate:
  9124. case OMPC_flush:
  9125. case OMPC_read:
  9126. case OMPC_write:
  9127. case OMPC_update:
  9128. case OMPC_capture:
  9129. case OMPC_seq_cst:
  9130. case OMPC_depend:
  9131. case OMPC_threads:
  9132. case OMPC_simd:
  9133. case OMPC_map:
  9134. case OMPC_priority:
  9135. case OMPC_grainsize:
  9136. case OMPC_nogroup:
  9137. case OMPC_num_tasks:
  9138. case OMPC_hint:
  9139. case OMPC_defaultmap:
  9140. case OMPC_unknown:
  9141. case OMPC_uniform:
  9142. case OMPC_to:
  9143. case OMPC_from:
  9144. case OMPC_use_device_ptr:
  9145. case OMPC_is_device_ptr:
  9146. case OMPC_unified_address:
  9147. case OMPC_unified_shared_memory:
  9148. case OMPC_reverse_offload:
  9149. case OMPC_dynamic_allocators:
  9150. case OMPC_atomic_default_mem_order:
  9151. llvm_unreachable("Unexpected OpenMP clause.");
  9152. }
  9153. return CaptureRegion;
  9154. }
  9155. OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
  9156. Expr *Condition, SourceLocation StartLoc,
  9157. SourceLocation LParenLoc,
  9158. SourceLocation NameModifierLoc,
  9159. SourceLocation ColonLoc,
  9160. SourceLocation EndLoc) {
  9161. Expr *ValExpr = Condition;
  9162. Stmt *HelperValStmt = nullptr;
  9163. OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
  9164. if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
  9165. !Condition->isInstantiationDependent() &&
  9166. !Condition->containsUnexpandedParameterPack()) {
  9167. ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
  9168. if (Val.isInvalid())
  9169. return nullptr;
  9170. ValExpr = Val.get();
  9171. OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
  9172. CaptureRegion =
  9173. getOpenMPCaptureRegionForClause(DKind, OMPC_if, NameModifier);
  9174. if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
  9175. ValExpr = MakeFullExpr(ValExpr).get();
  9176. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  9177. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  9178. HelperValStmt = buildPreInits(Context, Captures);
  9179. }
  9180. }
  9181. return new (Context)
  9182. OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
  9183. LParenLoc, NameModifierLoc, ColonLoc, EndLoc);
  9184. }
  9185. OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
  9186. SourceLocation StartLoc,
  9187. SourceLocation LParenLoc,
  9188. SourceLocation EndLoc) {
  9189. Expr *ValExpr = Condition;
  9190. if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
  9191. !Condition->isInstantiationDependent() &&
  9192. !Condition->containsUnexpandedParameterPack()) {
  9193. ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
  9194. if (Val.isInvalid())
  9195. return nullptr;
  9196. ValExpr = MakeFullExpr(Val.get()).get();
  9197. }
  9198. return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
  9199. }
  9200. ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
  9201. Expr *Op) {
  9202. if (!Op)
  9203. return ExprError();
  9204. class IntConvertDiagnoser : public ICEConvertDiagnoser {
  9205. public:
  9206. IntConvertDiagnoser()
  9207. : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
  9208. SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
  9209. QualType T) override {
  9210. return S.Diag(Loc, diag::err_omp_not_integral) << T;
  9211. }
  9212. SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
  9213. QualType T) override {
  9214. return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
  9215. }
  9216. SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
  9217. QualType T,
  9218. QualType ConvTy) override {
  9219. return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
  9220. }
  9221. SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
  9222. QualType ConvTy) override {
  9223. return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
  9224. << ConvTy->isEnumeralType() << ConvTy;
  9225. }
  9226. SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
  9227. QualType T) override {
  9228. return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
  9229. }
  9230. SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
  9231. QualType ConvTy) override {
  9232. return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
  9233. << ConvTy->isEnumeralType() << ConvTy;
  9234. }
  9235. SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
  9236. QualType) override {
  9237. llvm_unreachable("conversion functions are permitted");
  9238. }
  9239. } ConvertDiagnoser;
  9240. return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
  9241. }
  9242. static bool isNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef,
  9243. OpenMPClauseKind CKind,
  9244. bool StrictlyPositive) {
  9245. if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
  9246. !ValExpr->isInstantiationDependent()) {
  9247. SourceLocation Loc = ValExpr->getExprLoc();
  9248. ExprResult Value =
  9249. SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
  9250. if (Value.isInvalid())
  9251. return false;
  9252. ValExpr = Value.get();
  9253. // The expression must evaluate to a non-negative integer value.
  9254. llvm::APSInt Result;
  9255. if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
  9256. Result.isSigned() &&
  9257. !((!StrictlyPositive && Result.isNonNegative()) ||
  9258. (StrictlyPositive && Result.isStrictlyPositive()))) {
  9259. SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
  9260. << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
  9261. << ValExpr->getSourceRange();
  9262. return false;
  9263. }
  9264. }
  9265. return true;
  9266. }
  9267. OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
  9268. SourceLocation StartLoc,
  9269. SourceLocation LParenLoc,
  9270. SourceLocation EndLoc) {
  9271. Expr *ValExpr = NumThreads;
  9272. Stmt *HelperValStmt = nullptr;
  9273. // OpenMP [2.5, Restrictions]
  9274. // The num_threads expression must evaluate to a positive integer value.
  9275. if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
  9276. /*StrictlyPositive=*/true))
  9277. return nullptr;
  9278. OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
  9279. OpenMPDirectiveKind CaptureRegion =
  9280. getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads);
  9281. if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
  9282. ValExpr = MakeFullExpr(ValExpr).get();
  9283. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  9284. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  9285. HelperValStmt = buildPreInits(Context, Captures);
  9286. }
  9287. return new (Context) OMPNumThreadsClause(
  9288. ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
  9289. }
  9290. ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
  9291. OpenMPClauseKind CKind,
  9292. bool StrictlyPositive) {
  9293. if (!E)
  9294. return ExprError();
  9295. if (E->isValueDependent() || E->isTypeDependent() ||
  9296. E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
  9297. return E;
  9298. llvm::APSInt Result;
  9299. ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
  9300. if (ICE.isInvalid())
  9301. return ExprError();
  9302. if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
  9303. (!StrictlyPositive && !Result.isNonNegative())) {
  9304. Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
  9305. << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
  9306. << E->getSourceRange();
  9307. return ExprError();
  9308. }
  9309. if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
  9310. Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
  9311. << E->getSourceRange();
  9312. return ExprError();
  9313. }
  9314. if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
  9315. DSAStack->setAssociatedLoops(Result.getExtValue());
  9316. else if (CKind == OMPC_ordered)
  9317. DSAStack->setAssociatedLoops(Result.getExtValue());
  9318. return ICE;
  9319. }
  9320. OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
  9321. SourceLocation LParenLoc,
  9322. SourceLocation EndLoc) {
  9323. // OpenMP [2.8.1, simd construct, Description]
  9324. // The parameter of the safelen clause must be a constant
  9325. // positive integer expression.
  9326. ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
  9327. if (Safelen.isInvalid())
  9328. return nullptr;
  9329. return new (Context)
  9330. OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
  9331. }
  9332. OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
  9333. SourceLocation LParenLoc,
  9334. SourceLocation EndLoc) {
  9335. // OpenMP [2.8.1, simd construct, Description]
  9336. // The parameter of the simdlen clause must be a constant
  9337. // positive integer expression.
  9338. ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
  9339. if (Simdlen.isInvalid())
  9340. return nullptr;
  9341. return new (Context)
  9342. OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
  9343. }
  9344. /// Tries to find omp_allocator_handle_t type.
  9345. static bool findOMPAllocatorHandleT(Sema &S, SourceLocation Loc,
  9346. DSAStackTy *Stack) {
  9347. QualType OMPAllocatorHandleT = Stack->getOMPAllocatorHandleT();
  9348. if (!OMPAllocatorHandleT.isNull())
  9349. return true;
  9350. // Build the predefined allocator expressions.
  9351. bool ErrorFound = false;
  9352. for (int I = OMPAllocateDeclAttr::OMPDefaultMemAlloc;
  9353. I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) {
  9354. auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I);
  9355. StringRef Allocator =
  9356. OMPAllocateDeclAttr::ConvertAllocatorTypeTyToStr(AllocatorKind);
  9357. DeclarationName AllocatorName = &S.getASTContext().Idents.get(Allocator);
  9358. auto *VD = dyn_cast_or_null<ValueDecl>(
  9359. S.LookupSingleName(S.TUScope, AllocatorName, Loc, Sema::LookupAnyName));
  9360. if (!VD) {
  9361. ErrorFound = true;
  9362. break;
  9363. }
  9364. QualType AllocatorType =
  9365. VD->getType().getNonLValueExprType(S.getASTContext());
  9366. ExprResult Res = S.BuildDeclRefExpr(VD, AllocatorType, VK_LValue, Loc);
  9367. if (!Res.isUsable()) {
  9368. ErrorFound = true;
  9369. break;
  9370. }
  9371. if (OMPAllocatorHandleT.isNull())
  9372. OMPAllocatorHandleT = AllocatorType;
  9373. if (!S.getASTContext().hasSameType(OMPAllocatorHandleT, AllocatorType)) {
  9374. ErrorFound = true;
  9375. break;
  9376. }
  9377. Stack->setAllocator(AllocatorKind, Res.get());
  9378. }
  9379. if (ErrorFound) {
  9380. S.Diag(Loc, diag::err_implied_omp_allocator_handle_t_not_found);
  9381. return false;
  9382. }
  9383. OMPAllocatorHandleT.addConst();
  9384. Stack->setOMPAllocatorHandleT(OMPAllocatorHandleT);
  9385. return true;
  9386. }
  9387. OMPClause *Sema::ActOnOpenMPAllocatorClause(Expr *A, SourceLocation StartLoc,
  9388. SourceLocation LParenLoc,
  9389. SourceLocation EndLoc) {
  9390. // OpenMP [2.11.3, allocate Directive, Description]
  9391. // allocator is an expression of omp_allocator_handle_t type.
  9392. if (!findOMPAllocatorHandleT(*this, A->getExprLoc(), DSAStack))
  9393. return nullptr;
  9394. ExprResult Allocator = DefaultLvalueConversion(A);
  9395. if (Allocator.isInvalid())
  9396. return nullptr;
  9397. Allocator = PerformImplicitConversion(Allocator.get(),
  9398. DSAStack->getOMPAllocatorHandleT(),
  9399. Sema::AA_Initializing,
  9400. /*AllowExplicit=*/true);
  9401. if (Allocator.isInvalid())
  9402. return nullptr;
  9403. return new (Context)
  9404. OMPAllocatorClause(Allocator.get(), StartLoc, LParenLoc, EndLoc);
  9405. }
  9406. OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
  9407. SourceLocation StartLoc,
  9408. SourceLocation LParenLoc,
  9409. SourceLocation EndLoc) {
  9410. // OpenMP [2.7.1, loop construct, Description]
  9411. // OpenMP [2.8.1, simd construct, Description]
  9412. // OpenMP [2.9.6, distribute construct, Description]
  9413. // The parameter of the collapse clause must be a constant
  9414. // positive integer expression.
  9415. ExprResult NumForLoopsResult =
  9416. VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
  9417. if (NumForLoopsResult.isInvalid())
  9418. return nullptr;
  9419. return new (Context)
  9420. OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
  9421. }
  9422. OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
  9423. SourceLocation EndLoc,
  9424. SourceLocation LParenLoc,
  9425. Expr *NumForLoops) {
  9426. // OpenMP [2.7.1, loop construct, Description]
  9427. // OpenMP [2.8.1, simd construct, Description]
  9428. // OpenMP [2.9.6, distribute construct, Description]
  9429. // The parameter of the ordered clause must be a constant
  9430. // positive integer expression if any.
  9431. if (NumForLoops && LParenLoc.isValid()) {
  9432. ExprResult NumForLoopsResult =
  9433. VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
  9434. if (NumForLoopsResult.isInvalid())
  9435. return nullptr;
  9436. NumForLoops = NumForLoopsResult.get();
  9437. } else {
  9438. NumForLoops = nullptr;
  9439. }
  9440. auto *Clause = OMPOrderedClause::Create(
  9441. Context, NumForLoops, NumForLoops ? DSAStack->getAssociatedLoops() : 0,
  9442. StartLoc, LParenLoc, EndLoc);
  9443. DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops, Clause);
  9444. return Clause;
  9445. }
  9446. OMPClause *Sema::ActOnOpenMPSimpleClause(
  9447. OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
  9448. SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
  9449. OMPClause *Res = nullptr;
  9450. switch (Kind) {
  9451. case OMPC_default:
  9452. Res =
  9453. ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
  9454. ArgumentLoc, StartLoc, LParenLoc, EndLoc);
  9455. break;
  9456. case OMPC_proc_bind:
  9457. Res = ActOnOpenMPProcBindClause(
  9458. static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
  9459. LParenLoc, EndLoc);
  9460. break;
  9461. case OMPC_atomic_default_mem_order:
  9462. Res = ActOnOpenMPAtomicDefaultMemOrderClause(
  9463. static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Argument),
  9464. ArgumentLoc, StartLoc, LParenLoc, EndLoc);
  9465. break;
  9466. case OMPC_if:
  9467. case OMPC_final:
  9468. case OMPC_num_threads:
  9469. case OMPC_safelen:
  9470. case OMPC_simdlen:
  9471. case OMPC_allocator:
  9472. case OMPC_collapse:
  9473. case OMPC_schedule:
  9474. case OMPC_private:
  9475. case OMPC_firstprivate:
  9476. case OMPC_lastprivate:
  9477. case OMPC_shared:
  9478. case OMPC_reduction:
  9479. case OMPC_task_reduction:
  9480. case OMPC_in_reduction:
  9481. case OMPC_linear:
  9482. case OMPC_aligned:
  9483. case OMPC_copyin:
  9484. case OMPC_copyprivate:
  9485. case OMPC_ordered:
  9486. case OMPC_nowait:
  9487. case OMPC_untied:
  9488. case OMPC_mergeable:
  9489. case OMPC_threadprivate:
  9490. case OMPC_allocate:
  9491. case OMPC_flush:
  9492. case OMPC_read:
  9493. case OMPC_write:
  9494. case OMPC_update:
  9495. case OMPC_capture:
  9496. case OMPC_seq_cst:
  9497. case OMPC_depend:
  9498. case OMPC_device:
  9499. case OMPC_threads:
  9500. case OMPC_simd:
  9501. case OMPC_map:
  9502. case OMPC_num_teams:
  9503. case OMPC_thread_limit:
  9504. case OMPC_priority:
  9505. case OMPC_grainsize:
  9506. case OMPC_nogroup:
  9507. case OMPC_num_tasks:
  9508. case OMPC_hint:
  9509. case OMPC_dist_schedule:
  9510. case OMPC_defaultmap:
  9511. case OMPC_unknown:
  9512. case OMPC_uniform:
  9513. case OMPC_to:
  9514. case OMPC_from:
  9515. case OMPC_use_device_ptr:
  9516. case OMPC_is_device_ptr:
  9517. case OMPC_unified_address:
  9518. case OMPC_unified_shared_memory:
  9519. case OMPC_reverse_offload:
  9520. case OMPC_dynamic_allocators:
  9521. llvm_unreachable("Clause is not allowed.");
  9522. }
  9523. return Res;
  9524. }
  9525. static std::string
  9526. getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
  9527. ArrayRef<unsigned> Exclude = llvm::None) {
  9528. SmallString<256> Buffer;
  9529. llvm::raw_svector_ostream Out(Buffer);
  9530. unsigned Bound = Last >= 2 ? Last - 2 : 0;
  9531. unsigned Skipped = Exclude.size();
  9532. auto S = Exclude.begin(), E = Exclude.end();
  9533. for (unsigned I = First; I < Last; ++I) {
  9534. if (std::find(S, E, I) != E) {
  9535. --Skipped;
  9536. continue;
  9537. }
  9538. Out << "'" << getOpenMPSimpleClauseTypeName(K, I) << "'";
  9539. if (I == Bound - Skipped)
  9540. Out << " or ";
  9541. else if (I != Bound + 1 - Skipped)
  9542. Out << ", ";
  9543. }
  9544. return Out.str();
  9545. }
  9546. OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
  9547. SourceLocation KindKwLoc,
  9548. SourceLocation StartLoc,
  9549. SourceLocation LParenLoc,
  9550. SourceLocation EndLoc) {
  9551. if (Kind == OMPC_DEFAULT_unknown) {
  9552. static_assert(OMPC_DEFAULT_unknown > 0,
  9553. "OMPC_DEFAULT_unknown not greater than 0");
  9554. Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
  9555. << getListOfPossibleValues(OMPC_default, /*First=*/0,
  9556. /*Last=*/OMPC_DEFAULT_unknown)
  9557. << getOpenMPClauseName(OMPC_default);
  9558. return nullptr;
  9559. }
  9560. switch (Kind) {
  9561. case OMPC_DEFAULT_none:
  9562. DSAStack->setDefaultDSANone(KindKwLoc);
  9563. break;
  9564. case OMPC_DEFAULT_shared:
  9565. DSAStack->setDefaultDSAShared(KindKwLoc);
  9566. break;
  9567. case OMPC_DEFAULT_unknown:
  9568. llvm_unreachable("Clause kind is not allowed.");
  9569. break;
  9570. }
  9571. return new (Context)
  9572. OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
  9573. }
  9574. OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
  9575. SourceLocation KindKwLoc,
  9576. SourceLocation StartLoc,
  9577. SourceLocation LParenLoc,
  9578. SourceLocation EndLoc) {
  9579. if (Kind == OMPC_PROC_BIND_unknown) {
  9580. Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
  9581. << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0,
  9582. /*Last=*/OMPC_PROC_BIND_unknown)
  9583. << getOpenMPClauseName(OMPC_proc_bind);
  9584. return nullptr;
  9585. }
  9586. return new (Context)
  9587. OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
  9588. }
  9589. OMPClause *Sema::ActOnOpenMPAtomicDefaultMemOrderClause(
  9590. OpenMPAtomicDefaultMemOrderClauseKind Kind, SourceLocation KindKwLoc,
  9591. SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
  9592. if (Kind == OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown) {
  9593. Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
  9594. << getListOfPossibleValues(
  9595. OMPC_atomic_default_mem_order, /*First=*/0,
  9596. /*Last=*/OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown)
  9597. << getOpenMPClauseName(OMPC_atomic_default_mem_order);
  9598. return nullptr;
  9599. }
  9600. return new (Context) OMPAtomicDefaultMemOrderClause(Kind, KindKwLoc, StartLoc,
  9601. LParenLoc, EndLoc);
  9602. }
  9603. OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
  9604. OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
  9605. SourceLocation StartLoc, SourceLocation LParenLoc,
  9606. ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
  9607. SourceLocation EndLoc) {
  9608. OMPClause *Res = nullptr;
  9609. switch (Kind) {
  9610. case OMPC_schedule:
  9611. enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
  9612. assert(Argument.size() == NumberOfElements &&
  9613. ArgumentLoc.size() == NumberOfElements);
  9614. Res = ActOnOpenMPScheduleClause(
  9615. static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
  9616. static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
  9617. static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
  9618. StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
  9619. ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
  9620. break;
  9621. case OMPC_if:
  9622. assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
  9623. Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
  9624. Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
  9625. DelimLoc, EndLoc);
  9626. break;
  9627. case OMPC_dist_schedule:
  9628. Res = ActOnOpenMPDistScheduleClause(
  9629. static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
  9630. StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
  9631. break;
  9632. case OMPC_defaultmap:
  9633. enum { Modifier, DefaultmapKind };
  9634. Res = ActOnOpenMPDefaultmapClause(
  9635. static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
  9636. static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
  9637. StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
  9638. EndLoc);
  9639. break;
  9640. case OMPC_final:
  9641. case OMPC_num_threads:
  9642. case OMPC_safelen:
  9643. case OMPC_simdlen:
  9644. case OMPC_allocator:
  9645. case OMPC_collapse:
  9646. case OMPC_default:
  9647. case OMPC_proc_bind:
  9648. case OMPC_private:
  9649. case OMPC_firstprivate:
  9650. case OMPC_lastprivate:
  9651. case OMPC_shared:
  9652. case OMPC_reduction:
  9653. case OMPC_task_reduction:
  9654. case OMPC_in_reduction:
  9655. case OMPC_linear:
  9656. case OMPC_aligned:
  9657. case OMPC_copyin:
  9658. case OMPC_copyprivate:
  9659. case OMPC_ordered:
  9660. case OMPC_nowait:
  9661. case OMPC_untied:
  9662. case OMPC_mergeable:
  9663. case OMPC_threadprivate:
  9664. case OMPC_allocate:
  9665. case OMPC_flush:
  9666. case OMPC_read:
  9667. case OMPC_write:
  9668. case OMPC_update:
  9669. case OMPC_capture:
  9670. case OMPC_seq_cst:
  9671. case OMPC_depend:
  9672. case OMPC_device:
  9673. case OMPC_threads:
  9674. case OMPC_simd:
  9675. case OMPC_map:
  9676. case OMPC_num_teams:
  9677. case OMPC_thread_limit:
  9678. case OMPC_priority:
  9679. case OMPC_grainsize:
  9680. case OMPC_nogroup:
  9681. case OMPC_num_tasks:
  9682. case OMPC_hint:
  9683. case OMPC_unknown:
  9684. case OMPC_uniform:
  9685. case OMPC_to:
  9686. case OMPC_from:
  9687. case OMPC_use_device_ptr:
  9688. case OMPC_is_device_ptr:
  9689. case OMPC_unified_address:
  9690. case OMPC_unified_shared_memory:
  9691. case OMPC_reverse_offload:
  9692. case OMPC_dynamic_allocators:
  9693. case OMPC_atomic_default_mem_order:
  9694. llvm_unreachable("Clause is not allowed.");
  9695. }
  9696. return Res;
  9697. }
  9698. static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
  9699. OpenMPScheduleClauseModifier M2,
  9700. SourceLocation M1Loc, SourceLocation M2Loc) {
  9701. if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
  9702. SmallVector<unsigned, 2> Excluded;
  9703. if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
  9704. Excluded.push_back(M2);
  9705. if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
  9706. Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
  9707. if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
  9708. Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
  9709. S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
  9710. << getListOfPossibleValues(OMPC_schedule,
  9711. /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
  9712. /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
  9713. Excluded)
  9714. << getOpenMPClauseName(OMPC_schedule);
  9715. return true;
  9716. }
  9717. return false;
  9718. }
  9719. OMPClause *Sema::ActOnOpenMPScheduleClause(
  9720. OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
  9721. OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
  9722. SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
  9723. SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
  9724. if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
  9725. checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
  9726. return nullptr;
  9727. // OpenMP, 2.7.1, Loop Construct, Restrictions
  9728. // Either the monotonic modifier or the nonmonotonic modifier can be specified
  9729. // but not both.
  9730. if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
  9731. (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
  9732. M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
  9733. (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
  9734. M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
  9735. Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
  9736. << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
  9737. << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
  9738. return nullptr;
  9739. }
  9740. if (Kind == OMPC_SCHEDULE_unknown) {
  9741. std::string Values;
  9742. if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
  9743. unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
  9744. Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
  9745. /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
  9746. Exclude);
  9747. } else {
  9748. Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
  9749. /*Last=*/OMPC_SCHEDULE_unknown);
  9750. }
  9751. Diag(KindLoc, diag::err_omp_unexpected_clause_value)
  9752. << Values << getOpenMPClauseName(OMPC_schedule);
  9753. return nullptr;
  9754. }
  9755. // OpenMP, 2.7.1, Loop Construct, Restrictions
  9756. // The nonmonotonic modifier can only be specified with schedule(dynamic) or
  9757. // schedule(guided).
  9758. if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
  9759. M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
  9760. Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
  9761. Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
  9762. diag::err_omp_schedule_nonmonotonic_static);
  9763. return nullptr;
  9764. }
  9765. Expr *ValExpr = ChunkSize;
  9766. Stmt *HelperValStmt = nullptr;
  9767. if (ChunkSize) {
  9768. if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
  9769. !ChunkSize->isInstantiationDependent() &&
  9770. !ChunkSize->containsUnexpandedParameterPack()) {
  9771. SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
  9772. ExprResult Val =
  9773. PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
  9774. if (Val.isInvalid())
  9775. return nullptr;
  9776. ValExpr = Val.get();
  9777. // OpenMP [2.7.1, Restrictions]
  9778. // chunk_size must be a loop invariant integer expression with a positive
  9779. // value.
  9780. llvm::APSInt Result;
  9781. if (ValExpr->isIntegerConstantExpr(Result, Context)) {
  9782. if (Result.isSigned() && !Result.isStrictlyPositive()) {
  9783. Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
  9784. << "schedule" << 1 << ChunkSize->getSourceRange();
  9785. return nullptr;
  9786. }
  9787. } else if (getOpenMPCaptureRegionForClause(
  9788. DSAStack->getCurrentDirective(), OMPC_schedule) !=
  9789. OMPD_unknown &&
  9790. !CurContext->isDependentContext()) {
  9791. ValExpr = MakeFullExpr(ValExpr).get();
  9792. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  9793. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  9794. HelperValStmt = buildPreInits(Context, Captures);
  9795. }
  9796. }
  9797. }
  9798. return new (Context)
  9799. OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
  9800. ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
  9801. }
  9802. OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
  9803. SourceLocation StartLoc,
  9804. SourceLocation EndLoc) {
  9805. OMPClause *Res = nullptr;
  9806. switch (Kind) {
  9807. case OMPC_ordered:
  9808. Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
  9809. break;
  9810. case OMPC_nowait:
  9811. Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
  9812. break;
  9813. case OMPC_untied:
  9814. Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
  9815. break;
  9816. case OMPC_mergeable:
  9817. Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
  9818. break;
  9819. case OMPC_read:
  9820. Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
  9821. break;
  9822. case OMPC_write:
  9823. Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
  9824. break;
  9825. case OMPC_update:
  9826. Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
  9827. break;
  9828. case OMPC_capture:
  9829. Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
  9830. break;
  9831. case OMPC_seq_cst:
  9832. Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
  9833. break;
  9834. case OMPC_threads:
  9835. Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
  9836. break;
  9837. case OMPC_simd:
  9838. Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
  9839. break;
  9840. case OMPC_nogroup:
  9841. Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
  9842. break;
  9843. case OMPC_unified_address:
  9844. Res = ActOnOpenMPUnifiedAddressClause(StartLoc, EndLoc);
  9845. break;
  9846. case OMPC_unified_shared_memory:
  9847. Res = ActOnOpenMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
  9848. break;
  9849. case OMPC_reverse_offload:
  9850. Res = ActOnOpenMPReverseOffloadClause(StartLoc, EndLoc);
  9851. break;
  9852. case OMPC_dynamic_allocators:
  9853. Res = ActOnOpenMPDynamicAllocatorsClause(StartLoc, EndLoc);
  9854. break;
  9855. case OMPC_if:
  9856. case OMPC_final:
  9857. case OMPC_num_threads:
  9858. case OMPC_safelen:
  9859. case OMPC_simdlen:
  9860. case OMPC_allocator:
  9861. case OMPC_collapse:
  9862. case OMPC_schedule:
  9863. case OMPC_private:
  9864. case OMPC_firstprivate:
  9865. case OMPC_lastprivate:
  9866. case OMPC_shared:
  9867. case OMPC_reduction:
  9868. case OMPC_task_reduction:
  9869. case OMPC_in_reduction:
  9870. case OMPC_linear:
  9871. case OMPC_aligned:
  9872. case OMPC_copyin:
  9873. case OMPC_copyprivate:
  9874. case OMPC_default:
  9875. case OMPC_proc_bind:
  9876. case OMPC_threadprivate:
  9877. case OMPC_allocate:
  9878. case OMPC_flush:
  9879. case OMPC_depend:
  9880. case OMPC_device:
  9881. case OMPC_map:
  9882. case OMPC_num_teams:
  9883. case OMPC_thread_limit:
  9884. case OMPC_priority:
  9885. case OMPC_grainsize:
  9886. case OMPC_num_tasks:
  9887. case OMPC_hint:
  9888. case OMPC_dist_schedule:
  9889. case OMPC_defaultmap:
  9890. case OMPC_unknown:
  9891. case OMPC_uniform:
  9892. case OMPC_to:
  9893. case OMPC_from:
  9894. case OMPC_use_device_ptr:
  9895. case OMPC_is_device_ptr:
  9896. case OMPC_atomic_default_mem_order:
  9897. llvm_unreachable("Clause is not allowed.");
  9898. }
  9899. return Res;
  9900. }
  9901. OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
  9902. SourceLocation EndLoc) {
  9903. DSAStack->setNowaitRegion();
  9904. return new (Context) OMPNowaitClause(StartLoc, EndLoc);
  9905. }
  9906. OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
  9907. SourceLocation EndLoc) {
  9908. return new (Context) OMPUntiedClause(StartLoc, EndLoc);
  9909. }
  9910. OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
  9911. SourceLocation EndLoc) {
  9912. return new (Context) OMPMergeableClause(StartLoc, EndLoc);
  9913. }
  9914. OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
  9915. SourceLocation EndLoc) {
  9916. return new (Context) OMPReadClause(StartLoc, EndLoc);
  9917. }
  9918. OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
  9919. SourceLocation EndLoc) {
  9920. return new (Context) OMPWriteClause(StartLoc, EndLoc);
  9921. }
  9922. OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
  9923. SourceLocation EndLoc) {
  9924. return new (Context) OMPUpdateClause(StartLoc, EndLoc);
  9925. }
  9926. OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
  9927. SourceLocation EndLoc) {
  9928. return new (Context) OMPCaptureClause(StartLoc, EndLoc);
  9929. }
  9930. OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
  9931. SourceLocation EndLoc) {
  9932. return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
  9933. }
  9934. OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
  9935. SourceLocation EndLoc) {
  9936. return new (Context) OMPThreadsClause(StartLoc, EndLoc);
  9937. }
  9938. OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
  9939. SourceLocation EndLoc) {
  9940. return new (Context) OMPSIMDClause(StartLoc, EndLoc);
  9941. }
  9942. OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
  9943. SourceLocation EndLoc) {
  9944. return new (Context) OMPNogroupClause(StartLoc, EndLoc);
  9945. }
  9946. OMPClause *Sema::ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc,
  9947. SourceLocation EndLoc) {
  9948. return new (Context) OMPUnifiedAddressClause(StartLoc, EndLoc);
  9949. }
  9950. OMPClause *Sema::ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc,
  9951. SourceLocation EndLoc) {
  9952. return new (Context) OMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
  9953. }
  9954. OMPClause *Sema::ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc,
  9955. SourceLocation EndLoc) {
  9956. return new (Context) OMPReverseOffloadClause(StartLoc, EndLoc);
  9957. }
  9958. OMPClause *Sema::ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc,
  9959. SourceLocation EndLoc) {
  9960. return new (Context) OMPDynamicAllocatorsClause(StartLoc, EndLoc);
  9961. }
  9962. OMPClause *Sema::ActOnOpenMPVarListClause(
  9963. OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
  9964. const OMPVarListLocTy &Locs, SourceLocation ColonLoc,
  9965. CXXScopeSpec &ReductionOrMapperIdScopeSpec,
  9966. DeclarationNameInfo &ReductionOrMapperId, OpenMPDependClauseKind DepKind,
  9967. OpenMPLinearClauseKind LinKind,
  9968. ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
  9969. ArrayRef<SourceLocation> MapTypeModifiersLoc, OpenMPMapClauseKind MapType,
  9970. bool IsMapTypeImplicit, SourceLocation DepLinMapLoc) {
  9971. SourceLocation StartLoc = Locs.StartLoc;
  9972. SourceLocation LParenLoc = Locs.LParenLoc;
  9973. SourceLocation EndLoc = Locs.EndLoc;
  9974. OMPClause *Res = nullptr;
  9975. switch (Kind) {
  9976. case OMPC_private:
  9977. Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
  9978. break;
  9979. case OMPC_firstprivate:
  9980. Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
  9981. break;
  9982. case OMPC_lastprivate:
  9983. Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
  9984. break;
  9985. case OMPC_shared:
  9986. Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
  9987. break;
  9988. case OMPC_reduction:
  9989. Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
  9990. EndLoc, ReductionOrMapperIdScopeSpec,
  9991. ReductionOrMapperId);
  9992. break;
  9993. case OMPC_task_reduction:
  9994. Res = ActOnOpenMPTaskReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
  9995. EndLoc, ReductionOrMapperIdScopeSpec,
  9996. ReductionOrMapperId);
  9997. break;
  9998. case OMPC_in_reduction:
  9999. Res = ActOnOpenMPInReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
  10000. EndLoc, ReductionOrMapperIdScopeSpec,
  10001. ReductionOrMapperId);
  10002. break;
  10003. case OMPC_linear:
  10004. Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
  10005. LinKind, DepLinMapLoc, ColonLoc, EndLoc);
  10006. break;
  10007. case OMPC_aligned:
  10008. Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
  10009. ColonLoc, EndLoc);
  10010. break;
  10011. case OMPC_copyin:
  10012. Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
  10013. break;
  10014. case OMPC_copyprivate:
  10015. Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
  10016. break;
  10017. case OMPC_flush:
  10018. Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
  10019. break;
  10020. case OMPC_depend:
  10021. Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList,
  10022. StartLoc, LParenLoc, EndLoc);
  10023. break;
  10024. case OMPC_map:
  10025. Res = ActOnOpenMPMapClause(MapTypeModifiers, MapTypeModifiersLoc,
  10026. ReductionOrMapperIdScopeSpec,
  10027. ReductionOrMapperId, MapType, IsMapTypeImplicit,
  10028. DepLinMapLoc, ColonLoc, VarList, Locs);
  10029. break;
  10030. case OMPC_to:
  10031. Res = ActOnOpenMPToClause(VarList, ReductionOrMapperIdScopeSpec,
  10032. ReductionOrMapperId, Locs);
  10033. break;
  10034. case OMPC_from:
  10035. Res = ActOnOpenMPFromClause(VarList, ReductionOrMapperIdScopeSpec,
  10036. ReductionOrMapperId, Locs);
  10037. break;
  10038. case OMPC_use_device_ptr:
  10039. Res = ActOnOpenMPUseDevicePtrClause(VarList, Locs);
  10040. break;
  10041. case OMPC_is_device_ptr:
  10042. Res = ActOnOpenMPIsDevicePtrClause(VarList, Locs);
  10043. break;
  10044. case OMPC_allocate:
  10045. Res = ActOnOpenMPAllocateClause(TailExpr, VarList, StartLoc, LParenLoc,
  10046. ColonLoc, EndLoc);
  10047. break;
  10048. case OMPC_if:
  10049. case OMPC_final:
  10050. case OMPC_num_threads:
  10051. case OMPC_safelen:
  10052. case OMPC_simdlen:
  10053. case OMPC_allocator:
  10054. case OMPC_collapse:
  10055. case OMPC_default:
  10056. case OMPC_proc_bind:
  10057. case OMPC_schedule:
  10058. case OMPC_ordered:
  10059. case OMPC_nowait:
  10060. case OMPC_untied:
  10061. case OMPC_mergeable:
  10062. case OMPC_threadprivate:
  10063. case OMPC_read:
  10064. case OMPC_write:
  10065. case OMPC_update:
  10066. case OMPC_capture:
  10067. case OMPC_seq_cst:
  10068. case OMPC_device:
  10069. case OMPC_threads:
  10070. case OMPC_simd:
  10071. case OMPC_num_teams:
  10072. case OMPC_thread_limit:
  10073. case OMPC_priority:
  10074. case OMPC_grainsize:
  10075. case OMPC_nogroup:
  10076. case OMPC_num_tasks:
  10077. case OMPC_hint:
  10078. case OMPC_dist_schedule:
  10079. case OMPC_defaultmap:
  10080. case OMPC_unknown:
  10081. case OMPC_uniform:
  10082. case OMPC_unified_address:
  10083. case OMPC_unified_shared_memory:
  10084. case OMPC_reverse_offload:
  10085. case OMPC_dynamic_allocators:
  10086. case OMPC_atomic_default_mem_order:
  10087. llvm_unreachable("Clause is not allowed.");
  10088. }
  10089. return Res;
  10090. }
  10091. ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
  10092. ExprObjectKind OK, SourceLocation Loc) {
  10093. ExprResult Res = BuildDeclRefExpr(
  10094. Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
  10095. if (!Res.isUsable())
  10096. return ExprError();
  10097. if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
  10098. Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
  10099. if (!Res.isUsable())
  10100. return ExprError();
  10101. }
  10102. if (VK != VK_LValue && Res.get()->isGLValue()) {
  10103. Res = DefaultLvalueConversion(Res.get());
  10104. if (!Res.isUsable())
  10105. return ExprError();
  10106. }
  10107. return Res;
  10108. }
  10109. OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
  10110. SourceLocation StartLoc,
  10111. SourceLocation LParenLoc,
  10112. SourceLocation EndLoc) {
  10113. SmallVector<Expr *, 8> Vars;
  10114. SmallVector<Expr *, 8> PrivateCopies;
  10115. for (Expr *RefExpr : VarList) {
  10116. assert(RefExpr && "NULL expr in OpenMP private clause.");
  10117. SourceLocation ELoc;
  10118. SourceRange ERange;
  10119. Expr *SimpleRefExpr = RefExpr;
  10120. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  10121. if (Res.second) {
  10122. // It will be analyzed later.
  10123. Vars.push_back(RefExpr);
  10124. PrivateCopies.push_back(nullptr);
  10125. }
  10126. ValueDecl *D = Res.first;
  10127. if (!D)
  10128. continue;
  10129. QualType Type = D->getType();
  10130. auto *VD = dyn_cast<VarDecl>(D);
  10131. // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
  10132. // A variable that appears in a private clause must not have an incomplete
  10133. // type or a reference type.
  10134. if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
  10135. continue;
  10136. Type = Type.getNonReferenceType();
  10137. // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
  10138. // A variable that is privatized must not have a const-qualified type
  10139. // unless it is of class type with a mutable member. This restriction does
  10140. // not apply to the firstprivate clause.
  10141. //
  10142. // OpenMP 3.1 [2.9.3.3, private clause, Restrictions]
  10143. // A variable that appears in a private clause must not have a
  10144. // const-qualified type unless it is of class type with a mutable member.
  10145. if (rejectConstNotMutableType(*this, D, Type, OMPC_private, ELoc))
  10146. continue;
  10147. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  10148. // in a Construct]
  10149. // Variables with the predetermined data-sharing attributes may not be
  10150. // listed in data-sharing attributes clauses, except for the cases
  10151. // listed below. For these exceptions only, listing a predetermined
  10152. // variable in a data-sharing attribute clause is allowed and overrides
  10153. // the variable's predetermined data-sharing attributes.
  10154. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
  10155. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
  10156. Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
  10157. << getOpenMPClauseName(OMPC_private);
  10158. reportOriginalDsa(*this, DSAStack, D, DVar);
  10159. continue;
  10160. }
  10161. OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
  10162. // Variably modified types are not supported for tasks.
  10163. if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
  10164. isOpenMPTaskingDirective(CurrDir)) {
  10165. Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
  10166. << getOpenMPClauseName(OMPC_private) << Type
  10167. << getOpenMPDirectiveName(CurrDir);
  10168. bool IsDecl =
  10169. !VD ||
  10170. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  10171. Diag(D->getLocation(),
  10172. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  10173. << D;
  10174. continue;
  10175. }
  10176. // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
  10177. // A list item cannot appear in both a map clause and a data-sharing
  10178. // attribute clause on the same construct
  10179. if (isOpenMPTargetExecutionDirective(CurrDir)) {
  10180. OpenMPClauseKind ConflictKind;
  10181. if (DSAStack->checkMappableExprComponentListsForDecl(
  10182. VD, /*CurrentRegionOnly=*/true,
  10183. [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
  10184. OpenMPClauseKind WhereFoundClauseKind) -> bool {
  10185. ConflictKind = WhereFoundClauseKind;
  10186. return true;
  10187. })) {
  10188. Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
  10189. << getOpenMPClauseName(OMPC_private)
  10190. << getOpenMPClauseName(ConflictKind)
  10191. << getOpenMPDirectiveName(CurrDir);
  10192. reportOriginalDsa(*this, DSAStack, D, DVar);
  10193. continue;
  10194. }
  10195. }
  10196. // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
  10197. // A variable of class type (or array thereof) that appears in a private
  10198. // clause requires an accessible, unambiguous default constructor for the
  10199. // class type.
  10200. // Generate helper private variable and initialize it with the default
  10201. // value. The address of the original variable is replaced by the address of
  10202. // the new private variable in CodeGen. This new variable is not added to
  10203. // IdResolver, so the code in the OpenMP region uses original variable for
  10204. // proper diagnostics.
  10205. Type = Type.getUnqualifiedType();
  10206. VarDecl *VDPrivate =
  10207. buildVarDecl(*this, ELoc, Type, D->getName(),
  10208. D->hasAttrs() ? &D->getAttrs() : nullptr,
  10209. VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
  10210. ActOnUninitializedDecl(VDPrivate);
  10211. if (VDPrivate->isInvalidDecl())
  10212. continue;
  10213. DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
  10214. *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
  10215. DeclRefExpr *Ref = nullptr;
  10216. if (!VD && !CurContext->isDependentContext())
  10217. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
  10218. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
  10219. Vars.push_back((VD || CurContext->isDependentContext())
  10220. ? RefExpr->IgnoreParens()
  10221. : Ref);
  10222. PrivateCopies.push_back(VDPrivateRefExpr);
  10223. }
  10224. if (Vars.empty())
  10225. return nullptr;
  10226. return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
  10227. PrivateCopies);
  10228. }
  10229. namespace {
  10230. class DiagsUninitializedSeveretyRAII {
  10231. private:
  10232. DiagnosticsEngine &Diags;
  10233. SourceLocation SavedLoc;
  10234. bool IsIgnored = false;
  10235. public:
  10236. DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
  10237. bool IsIgnored)
  10238. : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
  10239. if (!IsIgnored) {
  10240. Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
  10241. /*Map*/ diag::Severity::Ignored, Loc);
  10242. }
  10243. }
  10244. ~DiagsUninitializedSeveretyRAII() {
  10245. if (!IsIgnored)
  10246. Diags.popMappings(SavedLoc);
  10247. }
  10248. };
  10249. }
  10250. OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
  10251. SourceLocation StartLoc,
  10252. SourceLocation LParenLoc,
  10253. SourceLocation EndLoc) {
  10254. SmallVector<Expr *, 8> Vars;
  10255. SmallVector<Expr *, 8> PrivateCopies;
  10256. SmallVector<Expr *, 8> Inits;
  10257. SmallVector<Decl *, 4> ExprCaptures;
  10258. bool IsImplicitClause =
  10259. StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
  10260. SourceLocation ImplicitClauseLoc = DSAStack->getConstructLoc();
  10261. for (Expr *RefExpr : VarList) {
  10262. assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
  10263. SourceLocation ELoc;
  10264. SourceRange ERange;
  10265. Expr *SimpleRefExpr = RefExpr;
  10266. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  10267. if (Res.second) {
  10268. // It will be analyzed later.
  10269. Vars.push_back(RefExpr);
  10270. PrivateCopies.push_back(nullptr);
  10271. Inits.push_back(nullptr);
  10272. }
  10273. ValueDecl *D = Res.first;
  10274. if (!D)
  10275. continue;
  10276. ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
  10277. QualType Type = D->getType();
  10278. auto *VD = dyn_cast<VarDecl>(D);
  10279. // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
  10280. // A variable that appears in a private clause must not have an incomplete
  10281. // type or a reference type.
  10282. if (RequireCompleteType(ELoc, Type,
  10283. diag::err_omp_firstprivate_incomplete_type))
  10284. continue;
  10285. Type = Type.getNonReferenceType();
  10286. // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
  10287. // A variable of class type (or array thereof) that appears in a private
  10288. // clause requires an accessible, unambiguous copy constructor for the
  10289. // class type.
  10290. QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
  10291. // If an implicit firstprivate variable found it was checked already.
  10292. DSAStackTy::DSAVarData TopDVar;
  10293. if (!IsImplicitClause) {
  10294. DSAStackTy::DSAVarData DVar =
  10295. DSAStack->getTopDSA(D, /*FromParent=*/false);
  10296. TopDVar = DVar;
  10297. OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
  10298. bool IsConstant = ElemType.isConstant(Context);
  10299. // OpenMP [2.4.13, Data-sharing Attribute Clauses]
  10300. // A list item that specifies a given variable may not appear in more
  10301. // than one clause on the same directive, except that a variable may be
  10302. // specified in both firstprivate and lastprivate clauses.
  10303. // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
  10304. // A list item may appear in a firstprivate or lastprivate clause but not
  10305. // both.
  10306. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
  10307. (isOpenMPDistributeDirective(CurrDir) ||
  10308. DVar.CKind != OMPC_lastprivate) &&
  10309. DVar.RefExpr) {
  10310. Diag(ELoc, diag::err_omp_wrong_dsa)
  10311. << getOpenMPClauseName(DVar.CKind)
  10312. << getOpenMPClauseName(OMPC_firstprivate);
  10313. reportOriginalDsa(*this, DSAStack, D, DVar);
  10314. continue;
  10315. }
  10316. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  10317. // in a Construct]
  10318. // Variables with the predetermined data-sharing attributes may not be
  10319. // listed in data-sharing attributes clauses, except for the cases
  10320. // listed below. For these exceptions only, listing a predetermined
  10321. // variable in a data-sharing attribute clause is allowed and overrides
  10322. // the variable's predetermined data-sharing attributes.
  10323. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  10324. // in a Construct, C/C++, p.2]
  10325. // Variables with const-qualified type having no mutable member may be
  10326. // listed in a firstprivate clause, even if they are static data members.
  10327. if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
  10328. DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
  10329. Diag(ELoc, diag::err_omp_wrong_dsa)
  10330. << getOpenMPClauseName(DVar.CKind)
  10331. << getOpenMPClauseName(OMPC_firstprivate);
  10332. reportOriginalDsa(*this, DSAStack, D, DVar);
  10333. continue;
  10334. }
  10335. // OpenMP [2.9.3.4, Restrictions, p.2]
  10336. // A list item that is private within a parallel region must not appear
  10337. // in a firstprivate clause on a worksharing construct if any of the
  10338. // worksharing regions arising from the worksharing construct ever bind
  10339. // to any of the parallel regions arising from the parallel construct.
  10340. // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
  10341. // A list item that is private within a teams region must not appear in a
  10342. // firstprivate clause on a distribute construct if any of the distribute
  10343. // regions arising from the distribute construct ever bind to any of the
  10344. // teams regions arising from the teams construct.
  10345. // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
  10346. // A list item that appears in a reduction clause of a teams construct
  10347. // must not appear in a firstprivate clause on a distribute construct if
  10348. // any of the distribute regions arising from the distribute construct
  10349. // ever bind to any of the teams regions arising from the teams construct.
  10350. if ((isOpenMPWorksharingDirective(CurrDir) ||
  10351. isOpenMPDistributeDirective(CurrDir)) &&
  10352. !isOpenMPParallelDirective(CurrDir) &&
  10353. !isOpenMPTeamsDirective(CurrDir)) {
  10354. DVar = DSAStack->getImplicitDSA(D, true);
  10355. if (DVar.CKind != OMPC_shared &&
  10356. (isOpenMPParallelDirective(DVar.DKind) ||
  10357. isOpenMPTeamsDirective(DVar.DKind) ||
  10358. DVar.DKind == OMPD_unknown)) {
  10359. Diag(ELoc, diag::err_omp_required_access)
  10360. << getOpenMPClauseName(OMPC_firstprivate)
  10361. << getOpenMPClauseName(OMPC_shared);
  10362. reportOriginalDsa(*this, DSAStack, D, DVar);
  10363. continue;
  10364. }
  10365. }
  10366. // OpenMP [2.9.3.4, Restrictions, p.3]
  10367. // A list item that appears in a reduction clause of a parallel construct
  10368. // must not appear in a firstprivate clause on a worksharing or task
  10369. // construct if any of the worksharing or task regions arising from the
  10370. // worksharing or task construct ever bind to any of the parallel regions
  10371. // arising from the parallel construct.
  10372. // OpenMP [2.9.3.4, Restrictions, p.4]
  10373. // A list item that appears in a reduction clause in worksharing
  10374. // construct must not appear in a firstprivate clause in a task construct
  10375. // encountered during execution of any of the worksharing regions arising
  10376. // from the worksharing construct.
  10377. if (isOpenMPTaskingDirective(CurrDir)) {
  10378. DVar = DSAStack->hasInnermostDSA(
  10379. D, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
  10380. [](OpenMPDirectiveKind K) {
  10381. return isOpenMPParallelDirective(K) ||
  10382. isOpenMPWorksharingDirective(K) ||
  10383. isOpenMPTeamsDirective(K);
  10384. },
  10385. /*FromParent=*/true);
  10386. if (DVar.CKind == OMPC_reduction &&
  10387. (isOpenMPParallelDirective(DVar.DKind) ||
  10388. isOpenMPWorksharingDirective(DVar.DKind) ||
  10389. isOpenMPTeamsDirective(DVar.DKind))) {
  10390. Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
  10391. << getOpenMPDirectiveName(DVar.DKind);
  10392. reportOriginalDsa(*this, DSAStack, D, DVar);
  10393. continue;
  10394. }
  10395. }
  10396. // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
  10397. // A list item cannot appear in both a map clause and a data-sharing
  10398. // attribute clause on the same construct
  10399. if (isOpenMPTargetExecutionDirective(CurrDir)) {
  10400. OpenMPClauseKind ConflictKind;
  10401. if (DSAStack->checkMappableExprComponentListsForDecl(
  10402. VD, /*CurrentRegionOnly=*/true,
  10403. [&ConflictKind](
  10404. OMPClauseMappableExprCommon::MappableExprComponentListRef,
  10405. OpenMPClauseKind WhereFoundClauseKind) {
  10406. ConflictKind = WhereFoundClauseKind;
  10407. return true;
  10408. })) {
  10409. Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
  10410. << getOpenMPClauseName(OMPC_firstprivate)
  10411. << getOpenMPClauseName(ConflictKind)
  10412. << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
  10413. reportOriginalDsa(*this, DSAStack, D, DVar);
  10414. continue;
  10415. }
  10416. }
  10417. }
  10418. // Variably modified types are not supported for tasks.
  10419. if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
  10420. isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
  10421. Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
  10422. << getOpenMPClauseName(OMPC_firstprivate) << Type
  10423. << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
  10424. bool IsDecl =
  10425. !VD ||
  10426. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  10427. Diag(D->getLocation(),
  10428. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  10429. << D;
  10430. continue;
  10431. }
  10432. Type = Type.getUnqualifiedType();
  10433. VarDecl *VDPrivate =
  10434. buildVarDecl(*this, ELoc, Type, D->getName(),
  10435. D->hasAttrs() ? &D->getAttrs() : nullptr,
  10436. VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
  10437. // Generate helper private variable and initialize it with the value of the
  10438. // original variable. The address of the original variable is replaced by
  10439. // the address of the new private variable in the CodeGen. This new variable
  10440. // is not added to IdResolver, so the code in the OpenMP region uses
  10441. // original variable for proper diagnostics and variable capturing.
  10442. Expr *VDInitRefExpr = nullptr;
  10443. // For arrays generate initializer for single element and replace it by the
  10444. // original array element in CodeGen.
  10445. if (Type->isArrayType()) {
  10446. VarDecl *VDInit =
  10447. buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
  10448. VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
  10449. Expr *Init = DefaultLvalueConversion(VDInitRefExpr).get();
  10450. ElemType = ElemType.getUnqualifiedType();
  10451. VarDecl *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
  10452. ".firstprivate.temp");
  10453. InitializedEntity Entity =
  10454. InitializedEntity::InitializeVariable(VDInitTemp);
  10455. InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
  10456. InitializationSequence InitSeq(*this, Entity, Kind, Init);
  10457. ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
  10458. if (Result.isInvalid())
  10459. VDPrivate->setInvalidDecl();
  10460. else
  10461. VDPrivate->setInit(Result.getAs<Expr>());
  10462. // Remove temp variable declaration.
  10463. Context.Deallocate(VDInitTemp);
  10464. } else {
  10465. VarDecl *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
  10466. ".firstprivate.temp");
  10467. VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
  10468. RefExpr->getExprLoc());
  10469. AddInitializerToDecl(VDPrivate,
  10470. DefaultLvalueConversion(VDInitRefExpr).get(),
  10471. /*DirectInit=*/false);
  10472. }
  10473. if (VDPrivate->isInvalidDecl()) {
  10474. if (IsImplicitClause) {
  10475. Diag(RefExpr->getExprLoc(),
  10476. diag::note_omp_task_predetermined_firstprivate_here);
  10477. }
  10478. continue;
  10479. }
  10480. CurContext->addDecl(VDPrivate);
  10481. DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
  10482. *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
  10483. RefExpr->getExprLoc());
  10484. DeclRefExpr *Ref = nullptr;
  10485. if (!VD && !CurContext->isDependentContext()) {
  10486. if (TopDVar.CKind == OMPC_lastprivate) {
  10487. Ref = TopDVar.PrivateCopy;
  10488. } else {
  10489. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
  10490. if (!isOpenMPCapturedDecl(D))
  10491. ExprCaptures.push_back(Ref->getDecl());
  10492. }
  10493. }
  10494. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
  10495. Vars.push_back((VD || CurContext->isDependentContext())
  10496. ? RefExpr->IgnoreParens()
  10497. : Ref);
  10498. PrivateCopies.push_back(VDPrivateRefExpr);
  10499. Inits.push_back(VDInitRefExpr);
  10500. }
  10501. if (Vars.empty())
  10502. return nullptr;
  10503. return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  10504. Vars, PrivateCopies, Inits,
  10505. buildPreInits(Context, ExprCaptures));
  10506. }
  10507. OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
  10508. SourceLocation StartLoc,
  10509. SourceLocation LParenLoc,
  10510. SourceLocation EndLoc) {
  10511. SmallVector<Expr *, 8> Vars;
  10512. SmallVector<Expr *, 8> SrcExprs;
  10513. SmallVector<Expr *, 8> DstExprs;
  10514. SmallVector<Expr *, 8> AssignmentOps;
  10515. SmallVector<Decl *, 4> ExprCaptures;
  10516. SmallVector<Expr *, 4> ExprPostUpdates;
  10517. for (Expr *RefExpr : VarList) {
  10518. assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
  10519. SourceLocation ELoc;
  10520. SourceRange ERange;
  10521. Expr *SimpleRefExpr = RefExpr;
  10522. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  10523. if (Res.second) {
  10524. // It will be analyzed later.
  10525. Vars.push_back(RefExpr);
  10526. SrcExprs.push_back(nullptr);
  10527. DstExprs.push_back(nullptr);
  10528. AssignmentOps.push_back(nullptr);
  10529. }
  10530. ValueDecl *D = Res.first;
  10531. if (!D)
  10532. continue;
  10533. QualType Type = D->getType();
  10534. auto *VD = dyn_cast<VarDecl>(D);
  10535. // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
  10536. // A variable that appears in a lastprivate clause must not have an
  10537. // incomplete type or a reference type.
  10538. if (RequireCompleteType(ELoc, Type,
  10539. diag::err_omp_lastprivate_incomplete_type))
  10540. continue;
  10541. Type = Type.getNonReferenceType();
  10542. // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
  10543. // A variable that is privatized must not have a const-qualified type
  10544. // unless it is of class type with a mutable member. This restriction does
  10545. // not apply to the firstprivate clause.
  10546. //
  10547. // OpenMP 3.1 [2.9.3.5, lastprivate clause, Restrictions]
  10548. // A variable that appears in a lastprivate clause must not have a
  10549. // const-qualified type unless it is of class type with a mutable member.
  10550. if (rejectConstNotMutableType(*this, D, Type, OMPC_lastprivate, ELoc))
  10551. continue;
  10552. OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
  10553. // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
  10554. // in a Construct]
  10555. // Variables with the predetermined data-sharing attributes may not be
  10556. // listed in data-sharing attributes clauses, except for the cases
  10557. // listed below.
  10558. // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
  10559. // A list item may appear in a firstprivate or lastprivate clause but not
  10560. // both.
  10561. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
  10562. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
  10563. (isOpenMPDistributeDirective(CurrDir) ||
  10564. DVar.CKind != OMPC_firstprivate) &&
  10565. (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
  10566. Diag(ELoc, diag::err_omp_wrong_dsa)
  10567. << getOpenMPClauseName(DVar.CKind)
  10568. << getOpenMPClauseName(OMPC_lastprivate);
  10569. reportOriginalDsa(*this, DSAStack, D, DVar);
  10570. continue;
  10571. }
  10572. // OpenMP [2.14.3.5, Restrictions, p.2]
  10573. // A list item that is private within a parallel region, or that appears in
  10574. // the reduction clause of a parallel construct, must not appear in a
  10575. // lastprivate clause on a worksharing construct if any of the corresponding
  10576. // worksharing regions ever binds to any of the corresponding parallel
  10577. // regions.
  10578. DSAStackTy::DSAVarData TopDVar = DVar;
  10579. if (isOpenMPWorksharingDirective(CurrDir) &&
  10580. !isOpenMPParallelDirective(CurrDir) &&
  10581. !isOpenMPTeamsDirective(CurrDir)) {
  10582. DVar = DSAStack->getImplicitDSA(D, true);
  10583. if (DVar.CKind != OMPC_shared) {
  10584. Diag(ELoc, diag::err_omp_required_access)
  10585. << getOpenMPClauseName(OMPC_lastprivate)
  10586. << getOpenMPClauseName(OMPC_shared);
  10587. reportOriginalDsa(*this, DSAStack, D, DVar);
  10588. continue;
  10589. }
  10590. }
  10591. // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
  10592. // A variable of class type (or array thereof) that appears in a
  10593. // lastprivate clause requires an accessible, unambiguous default
  10594. // constructor for the class type, unless the list item is also specified
  10595. // in a firstprivate clause.
  10596. // A variable of class type (or array thereof) that appears in a
  10597. // lastprivate clause requires an accessible, unambiguous copy assignment
  10598. // operator for the class type.
  10599. Type = Context.getBaseElementType(Type).getNonReferenceType();
  10600. VarDecl *SrcVD = buildVarDecl(*this, ERange.getBegin(),
  10601. Type.getUnqualifiedType(), ".lastprivate.src",
  10602. D->hasAttrs() ? &D->getAttrs() : nullptr);
  10603. DeclRefExpr *PseudoSrcExpr =
  10604. buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
  10605. VarDecl *DstVD =
  10606. buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
  10607. D->hasAttrs() ? &D->getAttrs() : nullptr);
  10608. DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
  10609. // For arrays generate assignment operation for single element and replace
  10610. // it by the original array element in CodeGen.
  10611. ExprResult AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
  10612. PseudoDstExpr, PseudoSrcExpr);
  10613. if (AssignmentOp.isInvalid())
  10614. continue;
  10615. AssignmentOp =
  10616. ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
  10617. if (AssignmentOp.isInvalid())
  10618. continue;
  10619. DeclRefExpr *Ref = nullptr;
  10620. if (!VD && !CurContext->isDependentContext()) {
  10621. if (TopDVar.CKind == OMPC_firstprivate) {
  10622. Ref = TopDVar.PrivateCopy;
  10623. } else {
  10624. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
  10625. if (!isOpenMPCapturedDecl(D))
  10626. ExprCaptures.push_back(Ref->getDecl());
  10627. }
  10628. if (TopDVar.CKind == OMPC_firstprivate ||
  10629. (!isOpenMPCapturedDecl(D) &&
  10630. Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
  10631. ExprResult RefRes = DefaultLvalueConversion(Ref);
  10632. if (!RefRes.isUsable())
  10633. continue;
  10634. ExprResult PostUpdateRes =
  10635. BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
  10636. RefRes.get());
  10637. if (!PostUpdateRes.isUsable())
  10638. continue;
  10639. ExprPostUpdates.push_back(
  10640. IgnoredValueConversions(PostUpdateRes.get()).get());
  10641. }
  10642. }
  10643. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
  10644. Vars.push_back((VD || CurContext->isDependentContext())
  10645. ? RefExpr->IgnoreParens()
  10646. : Ref);
  10647. SrcExprs.push_back(PseudoSrcExpr);
  10648. DstExprs.push_back(PseudoDstExpr);
  10649. AssignmentOps.push_back(AssignmentOp.get());
  10650. }
  10651. if (Vars.empty())
  10652. return nullptr;
  10653. return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  10654. Vars, SrcExprs, DstExprs, AssignmentOps,
  10655. buildPreInits(Context, ExprCaptures),
  10656. buildPostUpdate(*this, ExprPostUpdates));
  10657. }
  10658. OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
  10659. SourceLocation StartLoc,
  10660. SourceLocation LParenLoc,
  10661. SourceLocation EndLoc) {
  10662. SmallVector<Expr *, 8> Vars;
  10663. for (Expr *RefExpr : VarList) {
  10664. assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
  10665. SourceLocation ELoc;
  10666. SourceRange ERange;
  10667. Expr *SimpleRefExpr = RefExpr;
  10668. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  10669. if (Res.second) {
  10670. // It will be analyzed later.
  10671. Vars.push_back(RefExpr);
  10672. }
  10673. ValueDecl *D = Res.first;
  10674. if (!D)
  10675. continue;
  10676. auto *VD = dyn_cast<VarDecl>(D);
  10677. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  10678. // in a Construct]
  10679. // Variables with the predetermined data-sharing attributes may not be
  10680. // listed in data-sharing attributes clauses, except for the cases
  10681. // listed below. For these exceptions only, listing a predetermined
  10682. // variable in a data-sharing attribute clause is allowed and overrides
  10683. // the variable's predetermined data-sharing attributes.
  10684. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
  10685. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
  10686. DVar.RefExpr) {
  10687. Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
  10688. << getOpenMPClauseName(OMPC_shared);
  10689. reportOriginalDsa(*this, DSAStack, D, DVar);
  10690. continue;
  10691. }
  10692. DeclRefExpr *Ref = nullptr;
  10693. if (!VD && isOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
  10694. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
  10695. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
  10696. Vars.push_back((VD || !Ref || CurContext->isDependentContext())
  10697. ? RefExpr->IgnoreParens()
  10698. : Ref);
  10699. }
  10700. if (Vars.empty())
  10701. return nullptr;
  10702. return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
  10703. }
  10704. namespace {
  10705. class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
  10706. DSAStackTy *Stack;
  10707. public:
  10708. bool VisitDeclRefExpr(DeclRefExpr *E) {
  10709. if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
  10710. DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
  10711. if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
  10712. return false;
  10713. if (DVar.CKind != OMPC_unknown)
  10714. return true;
  10715. DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
  10716. VD, isOpenMPPrivate, [](OpenMPDirectiveKind) { return true; },
  10717. /*FromParent=*/true);
  10718. return DVarPrivate.CKind != OMPC_unknown;
  10719. }
  10720. return false;
  10721. }
  10722. bool VisitStmt(Stmt *S) {
  10723. for (Stmt *Child : S->children()) {
  10724. if (Child && Visit(Child))
  10725. return true;
  10726. }
  10727. return false;
  10728. }
  10729. explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
  10730. };
  10731. } // namespace
  10732. namespace {
  10733. // Transform MemberExpression for specified FieldDecl of current class to
  10734. // DeclRefExpr to specified OMPCapturedExprDecl.
  10735. class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
  10736. typedef TreeTransform<TransformExprToCaptures> BaseTransform;
  10737. ValueDecl *Field = nullptr;
  10738. DeclRefExpr *CapturedExpr = nullptr;
  10739. public:
  10740. TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
  10741. : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
  10742. ExprResult TransformMemberExpr(MemberExpr *E) {
  10743. if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
  10744. E->getMemberDecl() == Field) {
  10745. CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
  10746. return CapturedExpr;
  10747. }
  10748. return BaseTransform::TransformMemberExpr(E);
  10749. }
  10750. DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
  10751. };
  10752. } // namespace
  10753. template <typename T, typename U>
  10754. static T filterLookupForUDReductionAndMapper(
  10755. SmallVectorImpl<U> &Lookups, const llvm::function_ref<T(ValueDecl *)> Gen) {
  10756. for (U &Set : Lookups) {
  10757. for (auto *D : Set) {
  10758. if (T Res = Gen(cast<ValueDecl>(D)))
  10759. return Res;
  10760. }
  10761. }
  10762. return T();
  10763. }
  10764. static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D) {
  10765. assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case");
  10766. for (auto RD : D->redecls()) {
  10767. // Don't bother with extra checks if we already know this one isn't visible.
  10768. if (RD == D)
  10769. continue;
  10770. auto ND = cast<NamedDecl>(RD);
  10771. if (LookupResult::isVisible(SemaRef, ND))
  10772. return ND;
  10773. }
  10774. return nullptr;
  10775. }
  10776. static void
  10777. argumentDependentLookup(Sema &SemaRef, const DeclarationNameInfo &Id,
  10778. SourceLocation Loc, QualType Ty,
  10779. SmallVectorImpl<UnresolvedSet<8>> &Lookups) {
  10780. // Find all of the associated namespaces and classes based on the
  10781. // arguments we have.
  10782. Sema::AssociatedNamespaceSet AssociatedNamespaces;
  10783. Sema::AssociatedClassSet AssociatedClasses;
  10784. OpaqueValueExpr OVE(Loc, Ty, VK_LValue);
  10785. SemaRef.FindAssociatedClassesAndNamespaces(Loc, &OVE, AssociatedNamespaces,
  10786. AssociatedClasses);
  10787. // C++ [basic.lookup.argdep]p3:
  10788. // Let X be the lookup set produced by unqualified lookup (3.4.1)
  10789. // and let Y be the lookup set produced by argument dependent
  10790. // lookup (defined as follows). If X contains [...] then Y is
  10791. // empty. Otherwise Y is the set of declarations found in the
  10792. // namespaces associated with the argument types as described
  10793. // below. The set of declarations found by the lookup of the name
  10794. // is the union of X and Y.
  10795. //
  10796. // Here, we compute Y and add its members to the overloaded
  10797. // candidate set.
  10798. for (auto *NS : AssociatedNamespaces) {
  10799. // When considering an associated namespace, the lookup is the
  10800. // same as the lookup performed when the associated namespace is
  10801. // used as a qualifier (3.4.3.2) except that:
  10802. //
  10803. // -- Any using-directives in the associated namespace are
  10804. // ignored.
  10805. //
  10806. // -- Any namespace-scope friend functions declared in
  10807. // associated classes are visible within their respective
  10808. // namespaces even if they are not visible during an ordinary
  10809. // lookup (11.4).
  10810. DeclContext::lookup_result R = NS->lookup(Id.getName());
  10811. for (auto *D : R) {
  10812. auto *Underlying = D;
  10813. if (auto *USD = dyn_cast<UsingShadowDecl>(D))
  10814. Underlying = USD->getTargetDecl();
  10815. if (!isa<OMPDeclareReductionDecl>(Underlying) &&
  10816. !isa<OMPDeclareMapperDecl>(Underlying))
  10817. continue;
  10818. if (!SemaRef.isVisible(D)) {
  10819. D = findAcceptableDecl(SemaRef, D);
  10820. if (!D)
  10821. continue;
  10822. if (auto *USD = dyn_cast<UsingShadowDecl>(D))
  10823. Underlying = USD->getTargetDecl();
  10824. }
  10825. Lookups.emplace_back();
  10826. Lookups.back().addDecl(Underlying);
  10827. }
  10828. }
  10829. }
  10830. static ExprResult
  10831. buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
  10832. Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
  10833. const DeclarationNameInfo &ReductionId, QualType Ty,
  10834. CXXCastPath &BasePath, Expr *UnresolvedReduction) {
  10835. if (ReductionIdScopeSpec.isInvalid())
  10836. return ExprError();
  10837. SmallVector<UnresolvedSet<8>, 4> Lookups;
  10838. if (S) {
  10839. LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
  10840. Lookup.suppressDiagnostics();
  10841. while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
  10842. NamedDecl *D = Lookup.getRepresentativeDecl();
  10843. do {
  10844. S = S->getParent();
  10845. } while (S && !S->isDeclScope(D));
  10846. if (S)
  10847. S = S->getParent();
  10848. Lookups.emplace_back();
  10849. Lookups.back().append(Lookup.begin(), Lookup.end());
  10850. Lookup.clear();
  10851. }
  10852. } else if (auto *ULE =
  10853. cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
  10854. Lookups.push_back(UnresolvedSet<8>());
  10855. Decl *PrevD = nullptr;
  10856. for (NamedDecl *D : ULE->decls()) {
  10857. if (D == PrevD)
  10858. Lookups.push_back(UnresolvedSet<8>());
  10859. else if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(D))
  10860. Lookups.back().addDecl(DRD);
  10861. PrevD = D;
  10862. }
  10863. }
  10864. if (SemaRef.CurContext->isDependentContext() || Ty->isDependentType() ||
  10865. Ty->isInstantiationDependentType() ||
  10866. Ty->containsUnexpandedParameterPack() ||
  10867. filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) {
  10868. return !D->isInvalidDecl() &&
  10869. (D->getType()->isDependentType() ||
  10870. D->getType()->isInstantiationDependentType() ||
  10871. D->getType()->containsUnexpandedParameterPack());
  10872. })) {
  10873. UnresolvedSet<8> ResSet;
  10874. for (const UnresolvedSet<8> &Set : Lookups) {
  10875. if (Set.empty())
  10876. continue;
  10877. ResSet.append(Set.begin(), Set.end());
  10878. // The last item marks the end of all declarations at the specified scope.
  10879. ResSet.addDecl(Set[Set.size() - 1]);
  10880. }
  10881. return UnresolvedLookupExpr::Create(
  10882. SemaRef.Context, /*NamingClass=*/nullptr,
  10883. ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
  10884. /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
  10885. }
  10886. // Lookup inside the classes.
  10887. // C++ [over.match.oper]p3:
  10888. // For a unary operator @ with an operand of a type whose
  10889. // cv-unqualified version is T1, and for a binary operator @ with
  10890. // a left operand of a type whose cv-unqualified version is T1 and
  10891. // a right operand of a type whose cv-unqualified version is T2,
  10892. // three sets of candidate functions, designated member
  10893. // candidates, non-member candidates and built-in candidates, are
  10894. // constructed as follows:
  10895. // -- If T1 is a complete class type or a class currently being
  10896. // defined, the set of member candidates is the result of the
  10897. // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
  10898. // the set of member candidates is empty.
  10899. LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
  10900. Lookup.suppressDiagnostics();
  10901. if (const auto *TyRec = Ty->getAs<RecordType>()) {
  10902. // Complete the type if it can be completed.
  10903. // If the type is neither complete nor being defined, bail out now.
  10904. if (SemaRef.isCompleteType(Loc, Ty) || TyRec->isBeingDefined() ||
  10905. TyRec->getDecl()->getDefinition()) {
  10906. Lookup.clear();
  10907. SemaRef.LookupQualifiedName(Lookup, TyRec->getDecl());
  10908. if (Lookup.empty()) {
  10909. Lookups.emplace_back();
  10910. Lookups.back().append(Lookup.begin(), Lookup.end());
  10911. }
  10912. }
  10913. }
  10914. // Perform ADL.
  10915. if (SemaRef.getLangOpts().CPlusPlus)
  10916. argumentDependentLookup(SemaRef, ReductionId, Loc, Ty, Lookups);
  10917. if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
  10918. Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
  10919. if (!D->isInvalidDecl() &&
  10920. SemaRef.Context.hasSameType(D->getType(), Ty))
  10921. return D;
  10922. return nullptr;
  10923. }))
  10924. return SemaRef.BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(),
  10925. VK_LValue, Loc);
  10926. if (SemaRef.getLangOpts().CPlusPlus) {
  10927. if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
  10928. Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
  10929. if (!D->isInvalidDecl() &&
  10930. SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
  10931. !Ty.isMoreQualifiedThan(D->getType()))
  10932. return D;
  10933. return nullptr;
  10934. })) {
  10935. CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
  10936. /*DetectVirtual=*/false);
  10937. if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
  10938. if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
  10939. VD->getType().getUnqualifiedType()))) {
  10940. if (SemaRef.CheckBaseClassAccess(
  10941. Loc, VD->getType(), Ty, Paths.front(),
  10942. /*DiagID=*/0) != Sema::AR_inaccessible) {
  10943. SemaRef.BuildBasePathArray(Paths, BasePath);
  10944. return SemaRef.BuildDeclRefExpr(
  10945. VD, VD->getType().getNonReferenceType(), VK_LValue, Loc);
  10946. }
  10947. }
  10948. }
  10949. }
  10950. }
  10951. if (ReductionIdScopeSpec.isSet()) {
  10952. SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range;
  10953. return ExprError();
  10954. }
  10955. return ExprEmpty();
  10956. }
  10957. namespace {
  10958. /// Data for the reduction-based clauses.
  10959. struct ReductionData {
  10960. /// List of original reduction items.
  10961. SmallVector<Expr *, 8> Vars;
  10962. /// List of private copies of the reduction items.
  10963. SmallVector<Expr *, 8> Privates;
  10964. /// LHS expressions for the reduction_op expressions.
  10965. SmallVector<Expr *, 8> LHSs;
  10966. /// RHS expressions for the reduction_op expressions.
  10967. SmallVector<Expr *, 8> RHSs;
  10968. /// Reduction operation expression.
  10969. SmallVector<Expr *, 8> ReductionOps;
  10970. /// Taskgroup descriptors for the corresponding reduction items in
  10971. /// in_reduction clauses.
  10972. SmallVector<Expr *, 8> TaskgroupDescriptors;
  10973. /// List of captures for clause.
  10974. SmallVector<Decl *, 4> ExprCaptures;
  10975. /// List of postupdate expressions.
  10976. SmallVector<Expr *, 4> ExprPostUpdates;
  10977. ReductionData() = delete;
  10978. /// Reserves required memory for the reduction data.
  10979. ReductionData(unsigned Size) {
  10980. Vars.reserve(Size);
  10981. Privates.reserve(Size);
  10982. LHSs.reserve(Size);
  10983. RHSs.reserve(Size);
  10984. ReductionOps.reserve(Size);
  10985. TaskgroupDescriptors.reserve(Size);
  10986. ExprCaptures.reserve(Size);
  10987. ExprPostUpdates.reserve(Size);
  10988. }
  10989. /// Stores reduction item and reduction operation only (required for dependent
  10990. /// reduction item).
  10991. void push(Expr *Item, Expr *ReductionOp) {
  10992. Vars.emplace_back(Item);
  10993. Privates.emplace_back(nullptr);
  10994. LHSs.emplace_back(nullptr);
  10995. RHSs.emplace_back(nullptr);
  10996. ReductionOps.emplace_back(ReductionOp);
  10997. TaskgroupDescriptors.emplace_back(nullptr);
  10998. }
  10999. /// Stores reduction data.
  11000. void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS, Expr *ReductionOp,
  11001. Expr *TaskgroupDescriptor) {
  11002. Vars.emplace_back(Item);
  11003. Privates.emplace_back(Private);
  11004. LHSs.emplace_back(LHS);
  11005. RHSs.emplace_back(RHS);
  11006. ReductionOps.emplace_back(ReductionOp);
  11007. TaskgroupDescriptors.emplace_back(TaskgroupDescriptor);
  11008. }
  11009. };
  11010. } // namespace
  11011. static bool checkOMPArraySectionConstantForReduction(
  11012. ASTContext &Context, const OMPArraySectionExpr *OASE, bool &SingleElement,
  11013. SmallVectorImpl<llvm::APSInt> &ArraySizes) {
  11014. const Expr *Length = OASE->getLength();
  11015. if (Length == nullptr) {
  11016. // For array sections of the form [1:] or [:], we would need to analyze
  11017. // the lower bound...
  11018. if (OASE->getColonLoc().isValid())
  11019. return false;
  11020. // This is an array subscript which has implicit length 1!
  11021. SingleElement = true;
  11022. ArraySizes.push_back(llvm::APSInt::get(1));
  11023. } else {
  11024. Expr::EvalResult Result;
  11025. if (!Length->EvaluateAsInt(Result, Context))
  11026. return false;
  11027. llvm::APSInt ConstantLengthValue = Result.Val.getInt();
  11028. SingleElement = (ConstantLengthValue.getSExtValue() == 1);
  11029. ArraySizes.push_back(ConstantLengthValue);
  11030. }
  11031. // Get the base of this array section and walk up from there.
  11032. const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
  11033. // We require length = 1 for all array sections except the right-most to
  11034. // guarantee that the memory region is contiguous and has no holes in it.
  11035. while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) {
  11036. Length = TempOASE->getLength();
  11037. if (Length == nullptr) {
  11038. // For array sections of the form [1:] or [:], we would need to analyze
  11039. // the lower bound...
  11040. if (OASE->getColonLoc().isValid())
  11041. return false;
  11042. // This is an array subscript which has implicit length 1!
  11043. ArraySizes.push_back(llvm::APSInt::get(1));
  11044. } else {
  11045. Expr::EvalResult Result;
  11046. if (!Length->EvaluateAsInt(Result, Context))
  11047. return false;
  11048. llvm::APSInt ConstantLengthValue = Result.Val.getInt();
  11049. if (ConstantLengthValue.getSExtValue() != 1)
  11050. return false;
  11051. ArraySizes.push_back(ConstantLengthValue);
  11052. }
  11053. Base = TempOASE->getBase()->IgnoreParenImpCasts();
  11054. }
  11055. // If we have a single element, we don't need to add the implicit lengths.
  11056. if (!SingleElement) {
  11057. while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) {
  11058. // Has implicit length 1!
  11059. ArraySizes.push_back(llvm::APSInt::get(1));
  11060. Base = TempASE->getBase()->IgnoreParenImpCasts();
  11061. }
  11062. }
  11063. // This array section can be privatized as a single value or as a constant
  11064. // sized array.
  11065. return true;
  11066. }
  11067. static bool actOnOMPReductionKindClause(
  11068. Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind,
  11069. ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
  11070. SourceLocation ColonLoc, SourceLocation EndLoc,
  11071. CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
  11072. ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) {
  11073. DeclarationName DN = ReductionId.getName();
  11074. OverloadedOperatorKind OOK = DN.getCXXOverloadedOperator();
  11075. BinaryOperatorKind BOK = BO_Comma;
  11076. ASTContext &Context = S.Context;
  11077. // OpenMP [2.14.3.6, reduction clause]
  11078. // C
  11079. // reduction-identifier is either an identifier or one of the following
  11080. // operators: +, -, *, &, |, ^, && and ||
  11081. // C++
  11082. // reduction-identifier is either an id-expression or one of the following
  11083. // operators: +, -, *, &, |, ^, && and ||
  11084. switch (OOK) {
  11085. case OO_Plus:
  11086. case OO_Minus:
  11087. BOK = BO_Add;
  11088. break;
  11089. case OO_Star:
  11090. BOK = BO_Mul;
  11091. break;
  11092. case OO_Amp:
  11093. BOK = BO_And;
  11094. break;
  11095. case OO_Pipe:
  11096. BOK = BO_Or;
  11097. break;
  11098. case OO_Caret:
  11099. BOK = BO_Xor;
  11100. break;
  11101. case OO_AmpAmp:
  11102. BOK = BO_LAnd;
  11103. break;
  11104. case OO_PipePipe:
  11105. BOK = BO_LOr;
  11106. break;
  11107. case OO_New:
  11108. case OO_Delete:
  11109. case OO_Array_New:
  11110. case OO_Array_Delete:
  11111. case OO_Slash:
  11112. case OO_Percent:
  11113. case OO_Tilde:
  11114. case OO_Exclaim:
  11115. case OO_Equal:
  11116. case OO_Less:
  11117. case OO_Greater:
  11118. case OO_LessEqual:
  11119. case OO_GreaterEqual:
  11120. case OO_PlusEqual:
  11121. case OO_MinusEqual:
  11122. case OO_StarEqual:
  11123. case OO_SlashEqual:
  11124. case OO_PercentEqual:
  11125. case OO_CaretEqual:
  11126. case OO_AmpEqual:
  11127. case OO_PipeEqual:
  11128. case OO_LessLess:
  11129. case OO_GreaterGreater:
  11130. case OO_LessLessEqual:
  11131. case OO_GreaterGreaterEqual:
  11132. case OO_EqualEqual:
  11133. case OO_ExclaimEqual:
  11134. case OO_Spaceship:
  11135. case OO_PlusPlus:
  11136. case OO_MinusMinus:
  11137. case OO_Comma:
  11138. case OO_ArrowStar:
  11139. case OO_Arrow:
  11140. case OO_Call:
  11141. case OO_Subscript:
  11142. case OO_Conditional:
  11143. case OO_Coawait:
  11144. case NUM_OVERLOADED_OPERATORS:
  11145. llvm_unreachable("Unexpected reduction identifier");
  11146. case OO_None:
  11147. if (IdentifierInfo *II = DN.getAsIdentifierInfo()) {
  11148. if (II->isStr("max"))
  11149. BOK = BO_GT;
  11150. else if (II->isStr("min"))
  11151. BOK = BO_LT;
  11152. }
  11153. break;
  11154. }
  11155. SourceRange ReductionIdRange;
  11156. if (ReductionIdScopeSpec.isValid())
  11157. ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
  11158. else
  11159. ReductionIdRange.setBegin(ReductionId.getBeginLoc());
  11160. ReductionIdRange.setEnd(ReductionId.getEndLoc());
  11161. auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
  11162. bool FirstIter = true;
  11163. for (Expr *RefExpr : VarList) {
  11164. assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
  11165. // OpenMP [2.1, C/C++]
  11166. // A list item is a variable or array section, subject to the restrictions
  11167. // specified in Section 2.4 on page 42 and in each of the sections
  11168. // describing clauses and directives for which a list appears.
  11169. // OpenMP [2.14.3.3, Restrictions, p.1]
  11170. // A variable that is part of another variable (as an array or
  11171. // structure element) cannot appear in a private clause.
  11172. if (!FirstIter && IR != ER)
  11173. ++IR;
  11174. FirstIter = false;
  11175. SourceLocation ELoc;
  11176. SourceRange ERange;
  11177. Expr *SimpleRefExpr = RefExpr;
  11178. auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
  11179. /*AllowArraySection=*/true);
  11180. if (Res.second) {
  11181. // Try to find 'declare reduction' corresponding construct before using
  11182. // builtin/overloaded operators.
  11183. QualType Type = Context.DependentTy;
  11184. CXXCastPath BasePath;
  11185. ExprResult DeclareReductionRef = buildDeclareReductionRef(
  11186. S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
  11187. ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
  11188. Expr *ReductionOp = nullptr;
  11189. if (S.CurContext->isDependentContext() &&
  11190. (DeclareReductionRef.isUnset() ||
  11191. isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
  11192. ReductionOp = DeclareReductionRef.get();
  11193. // It will be analyzed later.
  11194. RD.push(RefExpr, ReductionOp);
  11195. }
  11196. ValueDecl *D = Res.first;
  11197. if (!D)
  11198. continue;
  11199. Expr *TaskgroupDescriptor = nullptr;
  11200. QualType Type;
  11201. auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
  11202. auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
  11203. if (ASE) {
  11204. Type = ASE->getType().getNonReferenceType();
  11205. } else if (OASE) {
  11206. QualType BaseType =
  11207. OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
  11208. if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
  11209. Type = ATy->getElementType();
  11210. else
  11211. Type = BaseType->getPointeeType();
  11212. Type = Type.getNonReferenceType();
  11213. } else {
  11214. Type = Context.getBaseElementType(D->getType().getNonReferenceType());
  11215. }
  11216. auto *VD = dyn_cast<VarDecl>(D);
  11217. // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
  11218. // A variable that appears in a private clause must not have an incomplete
  11219. // type or a reference type.
  11220. if (S.RequireCompleteType(ELoc, D->getType(),
  11221. diag::err_omp_reduction_incomplete_type))
  11222. continue;
  11223. // OpenMP [2.14.3.6, reduction clause, Restrictions]
  11224. // A list item that appears in a reduction clause must not be
  11225. // const-qualified.
  11226. if (rejectConstNotMutableType(S, D, Type, ClauseKind, ELoc,
  11227. /*AcceptIfMutable*/ false, ASE || OASE))
  11228. continue;
  11229. OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective();
  11230. // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
  11231. // If a list-item is a reference type then it must bind to the same object
  11232. // for all threads of the team.
  11233. if (!ASE && !OASE) {
  11234. if (VD) {
  11235. VarDecl *VDDef = VD->getDefinition();
  11236. if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
  11237. DSARefChecker Check(Stack);
  11238. if (Check.Visit(VDDef->getInit())) {
  11239. S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg)
  11240. << getOpenMPClauseName(ClauseKind) << ERange;
  11241. S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
  11242. continue;
  11243. }
  11244. }
  11245. }
  11246. // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
  11247. // in a Construct]
  11248. // Variables with the predetermined data-sharing attributes may not be
  11249. // listed in data-sharing attributes clauses, except for the cases
  11250. // listed below. For these exceptions only, listing a predetermined
  11251. // variable in a data-sharing attribute clause is allowed and overrides
  11252. // the variable's predetermined data-sharing attributes.
  11253. // OpenMP [2.14.3.6, Restrictions, p.3]
  11254. // Any number of reduction clauses can be specified on the directive,
  11255. // but a list item can appear only once in the reduction clauses for that
  11256. // directive.
  11257. DSAStackTy::DSAVarData DVar = Stack->getTopDSA(D, /*FromParent=*/false);
  11258. if (DVar.CKind == OMPC_reduction) {
  11259. S.Diag(ELoc, diag::err_omp_once_referenced)
  11260. << getOpenMPClauseName(ClauseKind);
  11261. if (DVar.RefExpr)
  11262. S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
  11263. continue;
  11264. }
  11265. if (DVar.CKind != OMPC_unknown) {
  11266. S.Diag(ELoc, diag::err_omp_wrong_dsa)
  11267. << getOpenMPClauseName(DVar.CKind)
  11268. << getOpenMPClauseName(OMPC_reduction);
  11269. reportOriginalDsa(S, Stack, D, DVar);
  11270. continue;
  11271. }
  11272. // OpenMP [2.14.3.6, Restrictions, p.1]
  11273. // A list item that appears in a reduction clause of a worksharing
  11274. // construct must be shared in the parallel regions to which any of the
  11275. // worksharing regions arising from the worksharing construct bind.
  11276. if (isOpenMPWorksharingDirective(CurrDir) &&
  11277. !isOpenMPParallelDirective(CurrDir) &&
  11278. !isOpenMPTeamsDirective(CurrDir)) {
  11279. DVar = Stack->getImplicitDSA(D, true);
  11280. if (DVar.CKind != OMPC_shared) {
  11281. S.Diag(ELoc, diag::err_omp_required_access)
  11282. << getOpenMPClauseName(OMPC_reduction)
  11283. << getOpenMPClauseName(OMPC_shared);
  11284. reportOriginalDsa(S, Stack, D, DVar);
  11285. continue;
  11286. }
  11287. }
  11288. }
  11289. // Try to find 'declare reduction' corresponding construct before using
  11290. // builtin/overloaded operators.
  11291. CXXCastPath BasePath;
  11292. ExprResult DeclareReductionRef = buildDeclareReductionRef(
  11293. S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
  11294. ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
  11295. if (DeclareReductionRef.isInvalid())
  11296. continue;
  11297. if (S.CurContext->isDependentContext() &&
  11298. (DeclareReductionRef.isUnset() ||
  11299. isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
  11300. RD.push(RefExpr, DeclareReductionRef.get());
  11301. continue;
  11302. }
  11303. if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
  11304. // Not allowed reduction identifier is found.
  11305. S.Diag(ReductionId.getBeginLoc(),
  11306. diag::err_omp_unknown_reduction_identifier)
  11307. << Type << ReductionIdRange;
  11308. continue;
  11309. }
  11310. // OpenMP [2.14.3.6, reduction clause, Restrictions]
  11311. // The type of a list item that appears in a reduction clause must be valid
  11312. // for the reduction-identifier. For a max or min reduction in C, the type
  11313. // of the list item must be an allowed arithmetic data type: char, int,
  11314. // float, double, or _Bool, possibly modified with long, short, signed, or
  11315. // unsigned. For a max or min reduction in C++, the type of the list item
  11316. // must be an allowed arithmetic data type: char, wchar_t, int, float,
  11317. // double, or bool, possibly modified with long, short, signed, or unsigned.
  11318. if (DeclareReductionRef.isUnset()) {
  11319. if ((BOK == BO_GT || BOK == BO_LT) &&
  11320. !(Type->isScalarType() ||
  11321. (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
  11322. S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
  11323. << getOpenMPClauseName(ClauseKind) << S.getLangOpts().CPlusPlus;
  11324. if (!ASE && !OASE) {
  11325. bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
  11326. VarDecl::DeclarationOnly;
  11327. S.Diag(D->getLocation(),
  11328. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  11329. << D;
  11330. }
  11331. continue;
  11332. }
  11333. if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
  11334. !S.getLangOpts().CPlusPlus && Type->isFloatingType()) {
  11335. S.Diag(ELoc, diag::err_omp_clause_floating_type_arg)
  11336. << getOpenMPClauseName(ClauseKind);
  11337. if (!ASE && !OASE) {
  11338. bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
  11339. VarDecl::DeclarationOnly;
  11340. S.Diag(D->getLocation(),
  11341. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  11342. << D;
  11343. }
  11344. continue;
  11345. }
  11346. }
  11347. Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
  11348. VarDecl *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs",
  11349. D->hasAttrs() ? &D->getAttrs() : nullptr);
  11350. VarDecl *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(),
  11351. D->hasAttrs() ? &D->getAttrs() : nullptr);
  11352. QualType PrivateTy = Type;
  11353. // Try if we can determine constant lengths for all array sections and avoid
  11354. // the VLA.
  11355. bool ConstantLengthOASE = false;
  11356. if (OASE) {
  11357. bool SingleElement;
  11358. llvm::SmallVector<llvm::APSInt, 4> ArraySizes;
  11359. ConstantLengthOASE = checkOMPArraySectionConstantForReduction(
  11360. Context, OASE, SingleElement, ArraySizes);
  11361. // If we don't have a single element, we must emit a constant array type.
  11362. if (ConstantLengthOASE && !SingleElement) {
  11363. for (llvm::APSInt &Size : ArraySizes)
  11364. PrivateTy = Context.getConstantArrayType(
  11365. PrivateTy, Size, ArrayType::Normal, /*IndexTypeQuals=*/0);
  11366. }
  11367. }
  11368. if ((OASE && !ConstantLengthOASE) ||
  11369. (!OASE && !ASE &&
  11370. D->getType().getNonReferenceType()->isVariablyModifiedType())) {
  11371. if (!Context.getTargetInfo().isVLASupported() &&
  11372. S.shouldDiagnoseTargetSupportFromOpenMP()) {
  11373. S.Diag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
  11374. S.Diag(ELoc, diag::note_vla_unsupported);
  11375. continue;
  11376. }
  11377. // For arrays/array sections only:
  11378. // Create pseudo array type for private copy. The size for this array will
  11379. // be generated during codegen.
  11380. // For array subscripts or single variables Private Ty is the same as Type
  11381. // (type of the variable or single array element).
  11382. PrivateTy = Context.getVariableArrayType(
  11383. Type,
  11384. new (Context) OpaqueValueExpr(ELoc, Context.getSizeType(), VK_RValue),
  11385. ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
  11386. } else if (!ASE && !OASE &&
  11387. Context.getAsArrayType(D->getType().getNonReferenceType())) {
  11388. PrivateTy = D->getType().getNonReferenceType();
  11389. }
  11390. // Private copy.
  11391. VarDecl *PrivateVD =
  11392. buildVarDecl(S, ELoc, PrivateTy, D->getName(),
  11393. D->hasAttrs() ? &D->getAttrs() : nullptr,
  11394. VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
  11395. // Add initializer for private variable.
  11396. Expr *Init = nullptr;
  11397. DeclRefExpr *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc);
  11398. DeclRefExpr *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc);
  11399. if (DeclareReductionRef.isUsable()) {
  11400. auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
  11401. auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
  11402. if (DRD->getInitializer()) {
  11403. Init = DRDRef;
  11404. RHSVD->setInit(DRDRef);
  11405. RHSVD->setInitStyle(VarDecl::CallInit);
  11406. }
  11407. } else {
  11408. switch (BOK) {
  11409. case BO_Add:
  11410. case BO_Xor:
  11411. case BO_Or:
  11412. case BO_LOr:
  11413. // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
  11414. if (Type->isScalarType() || Type->isAnyComplexType())
  11415. Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get();
  11416. break;
  11417. case BO_Mul:
  11418. case BO_LAnd:
  11419. if (Type->isScalarType() || Type->isAnyComplexType()) {
  11420. // '*' and '&&' reduction ops - initializer is '1'.
  11421. Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get();
  11422. }
  11423. break;
  11424. case BO_And: {
  11425. // '&' reduction op - initializer is '~0'.
  11426. QualType OrigType = Type;
  11427. if (auto *ComplexTy = OrigType->getAs<ComplexType>())
  11428. Type = ComplexTy->getElementType();
  11429. if (Type->isRealFloatingType()) {
  11430. llvm::APFloat InitValue =
  11431. llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
  11432. /*isIEEE=*/true);
  11433. Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
  11434. Type, ELoc);
  11435. } else if (Type->isScalarType()) {
  11436. uint64_t Size = Context.getTypeSize(Type);
  11437. QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
  11438. llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
  11439. Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
  11440. }
  11441. if (Init && OrigType->isAnyComplexType()) {
  11442. // Init = 0xFFFF + 0xFFFFi;
  11443. auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
  11444. Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
  11445. }
  11446. Type = OrigType;
  11447. break;
  11448. }
  11449. case BO_LT:
  11450. case BO_GT: {
  11451. // 'min' reduction op - initializer is 'Largest representable number in
  11452. // the reduction list item type'.
  11453. // 'max' reduction op - initializer is 'Least representable number in
  11454. // the reduction list item type'.
  11455. if (Type->isIntegerType() || Type->isPointerType()) {
  11456. bool IsSigned = Type->hasSignedIntegerRepresentation();
  11457. uint64_t Size = Context.getTypeSize(Type);
  11458. QualType IntTy =
  11459. Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
  11460. llvm::APInt InitValue =
  11461. (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
  11462. : llvm::APInt::getMinValue(Size)
  11463. : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
  11464. : llvm::APInt::getMaxValue(Size);
  11465. Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
  11466. if (Type->isPointerType()) {
  11467. // Cast to pointer type.
  11468. ExprResult CastExpr = S.BuildCStyleCastExpr(
  11469. ELoc, Context.getTrivialTypeSourceInfo(Type, ELoc), ELoc, Init);
  11470. if (CastExpr.isInvalid())
  11471. continue;
  11472. Init = CastExpr.get();
  11473. }
  11474. } else if (Type->isRealFloatingType()) {
  11475. llvm::APFloat InitValue = llvm::APFloat::getLargest(
  11476. Context.getFloatTypeSemantics(Type), BOK != BO_LT);
  11477. Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
  11478. Type, ELoc);
  11479. }
  11480. break;
  11481. }
  11482. case BO_PtrMemD:
  11483. case BO_PtrMemI:
  11484. case BO_MulAssign:
  11485. case BO_Div:
  11486. case BO_Rem:
  11487. case BO_Sub:
  11488. case BO_Shl:
  11489. case BO_Shr:
  11490. case BO_LE:
  11491. case BO_GE:
  11492. case BO_EQ:
  11493. case BO_NE:
  11494. case BO_Cmp:
  11495. case BO_AndAssign:
  11496. case BO_XorAssign:
  11497. case BO_OrAssign:
  11498. case BO_Assign:
  11499. case BO_AddAssign:
  11500. case BO_SubAssign:
  11501. case BO_DivAssign:
  11502. case BO_RemAssign:
  11503. case BO_ShlAssign:
  11504. case BO_ShrAssign:
  11505. case BO_Comma:
  11506. llvm_unreachable("Unexpected reduction operation");
  11507. }
  11508. }
  11509. if (Init && DeclareReductionRef.isUnset())
  11510. S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false);
  11511. else if (!Init)
  11512. S.ActOnUninitializedDecl(RHSVD);
  11513. if (RHSVD->isInvalidDecl())
  11514. continue;
  11515. if (!RHSVD->hasInit() &&
  11516. (DeclareReductionRef.isUnset() || !S.LangOpts.CPlusPlus)) {
  11517. S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible)
  11518. << Type << ReductionIdRange;
  11519. bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
  11520. VarDecl::DeclarationOnly;
  11521. S.Diag(D->getLocation(),
  11522. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  11523. << D;
  11524. continue;
  11525. }
  11526. // Store initializer for single element in private copy. Will be used during
  11527. // codegen.
  11528. PrivateVD->setInit(RHSVD->getInit());
  11529. PrivateVD->setInitStyle(RHSVD->getInitStyle());
  11530. DeclRefExpr *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc);
  11531. ExprResult ReductionOp;
  11532. if (DeclareReductionRef.isUsable()) {
  11533. QualType RedTy = DeclareReductionRef.get()->getType();
  11534. QualType PtrRedTy = Context.getPointerType(RedTy);
  11535. ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
  11536. ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
  11537. if (!BasePath.empty()) {
  11538. LHS = S.DefaultLvalueConversion(LHS.get());
  11539. RHS = S.DefaultLvalueConversion(RHS.get());
  11540. LHS = ImplicitCastExpr::Create(Context, PtrRedTy,
  11541. CK_UncheckedDerivedToBase, LHS.get(),
  11542. &BasePath, LHS.get()->getValueKind());
  11543. RHS = ImplicitCastExpr::Create(Context, PtrRedTy,
  11544. CK_UncheckedDerivedToBase, RHS.get(),
  11545. &BasePath, RHS.get()->getValueKind());
  11546. }
  11547. FunctionProtoType::ExtProtoInfo EPI;
  11548. QualType Params[] = {PtrRedTy, PtrRedTy};
  11549. QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
  11550. auto *OVE = new (Context) OpaqueValueExpr(
  11551. ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary,
  11552. S.DefaultLvalueConversion(DeclareReductionRef.get()).get());
  11553. Expr *Args[] = {LHS.get(), RHS.get()};
  11554. ReductionOp =
  11555. CallExpr::Create(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc);
  11556. } else {
  11557. ReductionOp = S.BuildBinOp(
  11558. Stack->getCurScope(), ReductionId.getBeginLoc(), BOK, LHSDRE, RHSDRE);
  11559. if (ReductionOp.isUsable()) {
  11560. if (BOK != BO_LT && BOK != BO_GT) {
  11561. ReductionOp =
  11562. S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
  11563. BO_Assign, LHSDRE, ReductionOp.get());
  11564. } else {
  11565. auto *ConditionalOp = new (Context)
  11566. ConditionalOperator(ReductionOp.get(), ELoc, LHSDRE, ELoc, RHSDRE,
  11567. Type, VK_LValue, OK_Ordinary);
  11568. ReductionOp =
  11569. S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
  11570. BO_Assign, LHSDRE, ConditionalOp);
  11571. }
  11572. if (ReductionOp.isUsable())
  11573. ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get(),
  11574. /*DiscardedValue*/ false);
  11575. }
  11576. if (!ReductionOp.isUsable())
  11577. continue;
  11578. }
  11579. // OpenMP [2.15.4.6, Restrictions, p.2]
  11580. // A list item that appears in an in_reduction clause of a task construct
  11581. // must appear in a task_reduction clause of a construct associated with a
  11582. // taskgroup region that includes the participating task in its taskgroup
  11583. // set. The construct associated with the innermost region that meets this
  11584. // condition must specify the same reduction-identifier as the in_reduction
  11585. // clause.
  11586. if (ClauseKind == OMPC_in_reduction) {
  11587. SourceRange ParentSR;
  11588. BinaryOperatorKind ParentBOK;
  11589. const Expr *ParentReductionOp;
  11590. Expr *ParentBOKTD, *ParentReductionOpTD;
  11591. DSAStackTy::DSAVarData ParentBOKDSA =
  11592. Stack->getTopMostTaskgroupReductionData(D, ParentSR, ParentBOK,
  11593. ParentBOKTD);
  11594. DSAStackTy::DSAVarData ParentReductionOpDSA =
  11595. Stack->getTopMostTaskgroupReductionData(
  11596. D, ParentSR, ParentReductionOp, ParentReductionOpTD);
  11597. bool IsParentBOK = ParentBOKDSA.DKind != OMPD_unknown;
  11598. bool IsParentReductionOp = ParentReductionOpDSA.DKind != OMPD_unknown;
  11599. if (!IsParentBOK && !IsParentReductionOp) {
  11600. S.Diag(ELoc, diag::err_omp_in_reduction_not_task_reduction);
  11601. continue;
  11602. }
  11603. if ((DeclareReductionRef.isUnset() && IsParentReductionOp) ||
  11604. (DeclareReductionRef.isUsable() && IsParentBOK) || BOK != ParentBOK ||
  11605. IsParentReductionOp) {
  11606. bool EmitError = true;
  11607. if (IsParentReductionOp && DeclareReductionRef.isUsable()) {
  11608. llvm::FoldingSetNodeID RedId, ParentRedId;
  11609. ParentReductionOp->Profile(ParentRedId, Context, /*Canonical=*/true);
  11610. DeclareReductionRef.get()->Profile(RedId, Context,
  11611. /*Canonical=*/true);
  11612. EmitError = RedId != ParentRedId;
  11613. }
  11614. if (EmitError) {
  11615. S.Diag(ReductionId.getBeginLoc(),
  11616. diag::err_omp_reduction_identifier_mismatch)
  11617. << ReductionIdRange << RefExpr->getSourceRange();
  11618. S.Diag(ParentSR.getBegin(),
  11619. diag::note_omp_previous_reduction_identifier)
  11620. << ParentSR
  11621. << (IsParentBOK ? ParentBOKDSA.RefExpr
  11622. : ParentReductionOpDSA.RefExpr)
  11623. ->getSourceRange();
  11624. continue;
  11625. }
  11626. }
  11627. TaskgroupDescriptor = IsParentBOK ? ParentBOKTD : ParentReductionOpTD;
  11628. assert(TaskgroupDescriptor && "Taskgroup descriptor must be defined.");
  11629. }
  11630. DeclRefExpr *Ref = nullptr;
  11631. Expr *VarsExpr = RefExpr->IgnoreParens();
  11632. if (!VD && !S.CurContext->isDependentContext()) {
  11633. if (ASE || OASE) {
  11634. TransformExprToCaptures RebuildToCapture(S, D);
  11635. VarsExpr =
  11636. RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
  11637. Ref = RebuildToCapture.getCapturedExpr();
  11638. } else {
  11639. VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false);
  11640. }
  11641. if (!S.isOpenMPCapturedDecl(D)) {
  11642. RD.ExprCaptures.emplace_back(Ref->getDecl());
  11643. if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
  11644. ExprResult RefRes = S.DefaultLvalueConversion(Ref);
  11645. if (!RefRes.isUsable())
  11646. continue;
  11647. ExprResult PostUpdateRes =
  11648. S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
  11649. RefRes.get());
  11650. if (!PostUpdateRes.isUsable())
  11651. continue;
  11652. if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
  11653. Stack->getCurrentDirective() == OMPD_taskgroup) {
  11654. S.Diag(RefExpr->getExprLoc(),
  11655. diag::err_omp_reduction_non_addressable_expression)
  11656. << RefExpr->getSourceRange();
  11657. continue;
  11658. }
  11659. RD.ExprPostUpdates.emplace_back(
  11660. S.IgnoredValueConversions(PostUpdateRes.get()).get());
  11661. }
  11662. }
  11663. }
  11664. // All reduction items are still marked as reduction (to do not increase
  11665. // code base size).
  11666. Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref);
  11667. if (CurrDir == OMPD_taskgroup) {
  11668. if (DeclareReductionRef.isUsable())
  11669. Stack->addTaskgroupReductionData(D, ReductionIdRange,
  11670. DeclareReductionRef.get());
  11671. else
  11672. Stack->addTaskgroupReductionData(D, ReductionIdRange, BOK);
  11673. }
  11674. RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get(),
  11675. TaskgroupDescriptor);
  11676. }
  11677. return RD.Vars.empty();
  11678. }
  11679. OMPClause *Sema::ActOnOpenMPReductionClause(
  11680. ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
  11681. SourceLocation ColonLoc, SourceLocation EndLoc,
  11682. CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
  11683. ArrayRef<Expr *> UnresolvedReductions) {
  11684. ReductionData RD(VarList.size());
  11685. if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_reduction, VarList,
  11686. StartLoc, LParenLoc, ColonLoc, EndLoc,
  11687. ReductionIdScopeSpec, ReductionId,
  11688. UnresolvedReductions, RD))
  11689. return nullptr;
  11690. return OMPReductionClause::Create(
  11691. Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
  11692. ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
  11693. RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
  11694. buildPreInits(Context, RD.ExprCaptures),
  11695. buildPostUpdate(*this, RD.ExprPostUpdates));
  11696. }
  11697. OMPClause *Sema::ActOnOpenMPTaskReductionClause(
  11698. ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
  11699. SourceLocation ColonLoc, SourceLocation EndLoc,
  11700. CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
  11701. ArrayRef<Expr *> UnresolvedReductions) {
  11702. ReductionData RD(VarList.size());
  11703. if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_task_reduction, VarList,
  11704. StartLoc, LParenLoc, ColonLoc, EndLoc,
  11705. ReductionIdScopeSpec, ReductionId,
  11706. UnresolvedReductions, RD))
  11707. return nullptr;
  11708. return OMPTaskReductionClause::Create(
  11709. Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
  11710. ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
  11711. RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
  11712. buildPreInits(Context, RD.ExprCaptures),
  11713. buildPostUpdate(*this, RD.ExprPostUpdates));
  11714. }
  11715. OMPClause *Sema::ActOnOpenMPInReductionClause(
  11716. ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
  11717. SourceLocation ColonLoc, SourceLocation EndLoc,
  11718. CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
  11719. ArrayRef<Expr *> UnresolvedReductions) {
  11720. ReductionData RD(VarList.size());
  11721. if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_in_reduction, VarList,
  11722. StartLoc, LParenLoc, ColonLoc, EndLoc,
  11723. ReductionIdScopeSpec, ReductionId,
  11724. UnresolvedReductions, RD))
  11725. return nullptr;
  11726. return OMPInReductionClause::Create(
  11727. Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
  11728. ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
  11729. RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.TaskgroupDescriptors,
  11730. buildPreInits(Context, RD.ExprCaptures),
  11731. buildPostUpdate(*this, RD.ExprPostUpdates));
  11732. }
  11733. bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
  11734. SourceLocation LinLoc) {
  11735. if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
  11736. LinKind == OMPC_LINEAR_unknown) {
  11737. Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
  11738. return true;
  11739. }
  11740. return false;
  11741. }
  11742. bool Sema::CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc,
  11743. OpenMPLinearClauseKind LinKind,
  11744. QualType Type) {
  11745. const auto *VD = dyn_cast_or_null<VarDecl>(D);
  11746. // A variable must not have an incomplete type or a reference type.
  11747. if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
  11748. return true;
  11749. if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
  11750. !Type->isReferenceType()) {
  11751. Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
  11752. << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
  11753. return true;
  11754. }
  11755. Type = Type.getNonReferenceType();
  11756. // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
  11757. // A variable that is privatized must not have a const-qualified type
  11758. // unless it is of class type with a mutable member. This restriction does
  11759. // not apply to the firstprivate clause.
  11760. if (rejectConstNotMutableType(*this, D, Type, OMPC_linear, ELoc))
  11761. return true;
  11762. // A list item must be of integral or pointer type.
  11763. Type = Type.getUnqualifiedType().getCanonicalType();
  11764. const auto *Ty = Type.getTypePtrOrNull();
  11765. if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
  11766. !Ty->isPointerType())) {
  11767. Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
  11768. if (D) {
  11769. bool IsDecl =
  11770. !VD ||
  11771. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  11772. Diag(D->getLocation(),
  11773. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  11774. << D;
  11775. }
  11776. return true;
  11777. }
  11778. return false;
  11779. }
  11780. OMPClause *Sema::ActOnOpenMPLinearClause(
  11781. ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
  11782. SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
  11783. SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
  11784. SmallVector<Expr *, 8> Vars;
  11785. SmallVector<Expr *, 8> Privates;
  11786. SmallVector<Expr *, 8> Inits;
  11787. SmallVector<Decl *, 4> ExprCaptures;
  11788. SmallVector<Expr *, 4> ExprPostUpdates;
  11789. if (CheckOpenMPLinearModifier(LinKind, LinLoc))
  11790. LinKind = OMPC_LINEAR_val;
  11791. for (Expr *RefExpr : VarList) {
  11792. assert(RefExpr && "NULL expr in OpenMP linear clause.");
  11793. SourceLocation ELoc;
  11794. SourceRange ERange;
  11795. Expr *SimpleRefExpr = RefExpr;
  11796. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  11797. if (Res.second) {
  11798. // It will be analyzed later.
  11799. Vars.push_back(RefExpr);
  11800. Privates.push_back(nullptr);
  11801. Inits.push_back(nullptr);
  11802. }
  11803. ValueDecl *D = Res.first;
  11804. if (!D)
  11805. continue;
  11806. QualType Type = D->getType();
  11807. auto *VD = dyn_cast<VarDecl>(D);
  11808. // OpenMP [2.14.3.7, linear clause]
  11809. // A list-item cannot appear in more than one linear clause.
  11810. // A list-item that appears in a linear clause cannot appear in any
  11811. // other data-sharing attribute clause.
  11812. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
  11813. if (DVar.RefExpr) {
  11814. Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
  11815. << getOpenMPClauseName(OMPC_linear);
  11816. reportOriginalDsa(*this, DSAStack, D, DVar);
  11817. continue;
  11818. }
  11819. if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
  11820. continue;
  11821. Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
  11822. // Build private copy of original var.
  11823. VarDecl *Private =
  11824. buildVarDecl(*this, ELoc, Type, D->getName(),
  11825. D->hasAttrs() ? &D->getAttrs() : nullptr,
  11826. VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
  11827. DeclRefExpr *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
  11828. // Build var to save initial value.
  11829. VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
  11830. Expr *InitExpr;
  11831. DeclRefExpr *Ref = nullptr;
  11832. if (!VD && !CurContext->isDependentContext()) {
  11833. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
  11834. if (!isOpenMPCapturedDecl(D)) {
  11835. ExprCaptures.push_back(Ref->getDecl());
  11836. if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
  11837. ExprResult RefRes = DefaultLvalueConversion(Ref);
  11838. if (!RefRes.isUsable())
  11839. continue;
  11840. ExprResult PostUpdateRes =
  11841. BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
  11842. SimpleRefExpr, RefRes.get());
  11843. if (!PostUpdateRes.isUsable())
  11844. continue;
  11845. ExprPostUpdates.push_back(
  11846. IgnoredValueConversions(PostUpdateRes.get()).get());
  11847. }
  11848. }
  11849. }
  11850. if (LinKind == OMPC_LINEAR_uval)
  11851. InitExpr = VD ? VD->getInit() : SimpleRefExpr;
  11852. else
  11853. InitExpr = VD ? SimpleRefExpr : Ref;
  11854. AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
  11855. /*DirectInit=*/false);
  11856. DeclRefExpr *InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
  11857. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
  11858. Vars.push_back((VD || CurContext->isDependentContext())
  11859. ? RefExpr->IgnoreParens()
  11860. : Ref);
  11861. Privates.push_back(PrivateRef);
  11862. Inits.push_back(InitRef);
  11863. }
  11864. if (Vars.empty())
  11865. return nullptr;
  11866. Expr *StepExpr = Step;
  11867. Expr *CalcStepExpr = nullptr;
  11868. if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
  11869. !Step->isInstantiationDependent() &&
  11870. !Step->containsUnexpandedParameterPack()) {
  11871. SourceLocation StepLoc = Step->getBeginLoc();
  11872. ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
  11873. if (Val.isInvalid())
  11874. return nullptr;
  11875. StepExpr = Val.get();
  11876. // Build var to save the step value.
  11877. VarDecl *SaveVar =
  11878. buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
  11879. ExprResult SaveRef =
  11880. buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
  11881. ExprResult CalcStep =
  11882. BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
  11883. CalcStep = ActOnFinishFullExpr(CalcStep.get(), /*DiscardedValue*/ false);
  11884. // Warn about zero linear step (it would be probably better specified as
  11885. // making corresponding variables 'const').
  11886. llvm::APSInt Result;
  11887. bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
  11888. if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
  11889. Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
  11890. << (Vars.size() > 1);
  11891. if (!IsConstant && CalcStep.isUsable()) {
  11892. // Calculate the step beforehand instead of doing this on each iteration.
  11893. // (This is not used if the number of iterations may be kfold-ed).
  11894. CalcStepExpr = CalcStep.get();
  11895. }
  11896. }
  11897. return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
  11898. ColonLoc, EndLoc, Vars, Privates, Inits,
  11899. StepExpr, CalcStepExpr,
  11900. buildPreInits(Context, ExprCaptures),
  11901. buildPostUpdate(*this, ExprPostUpdates));
  11902. }
  11903. static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
  11904. Expr *NumIterations, Sema &SemaRef,
  11905. Scope *S, DSAStackTy *Stack) {
  11906. // Walk the vars and build update/final expressions for the CodeGen.
  11907. SmallVector<Expr *, 8> Updates;
  11908. SmallVector<Expr *, 8> Finals;
  11909. Expr *Step = Clause.getStep();
  11910. Expr *CalcStep = Clause.getCalcStep();
  11911. // OpenMP [2.14.3.7, linear clause]
  11912. // If linear-step is not specified it is assumed to be 1.
  11913. if (!Step)
  11914. Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
  11915. else if (CalcStep)
  11916. Step = cast<BinaryOperator>(CalcStep)->getLHS();
  11917. bool HasErrors = false;
  11918. auto CurInit = Clause.inits().begin();
  11919. auto CurPrivate = Clause.privates().begin();
  11920. OpenMPLinearClauseKind LinKind = Clause.getModifier();
  11921. for (Expr *RefExpr : Clause.varlists()) {
  11922. SourceLocation ELoc;
  11923. SourceRange ERange;
  11924. Expr *SimpleRefExpr = RefExpr;
  11925. auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange);
  11926. ValueDecl *D = Res.first;
  11927. if (Res.second || !D) {
  11928. Updates.push_back(nullptr);
  11929. Finals.push_back(nullptr);
  11930. HasErrors = true;
  11931. continue;
  11932. }
  11933. auto &&Info = Stack->isLoopControlVariable(D);
  11934. // OpenMP [2.15.11, distribute simd Construct]
  11935. // A list item may not appear in a linear clause, unless it is the loop
  11936. // iteration variable.
  11937. if (isOpenMPDistributeDirective(Stack->getCurrentDirective()) &&
  11938. isOpenMPSimdDirective(Stack->getCurrentDirective()) && !Info.first) {
  11939. SemaRef.Diag(ELoc,
  11940. diag::err_omp_linear_distribute_var_non_loop_iteration);
  11941. Updates.push_back(nullptr);
  11942. Finals.push_back(nullptr);
  11943. HasErrors = true;
  11944. continue;
  11945. }
  11946. Expr *InitExpr = *CurInit;
  11947. // Build privatized reference to the current linear var.
  11948. auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
  11949. Expr *CapturedRef;
  11950. if (LinKind == OMPC_LINEAR_uval)
  11951. CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
  11952. else
  11953. CapturedRef =
  11954. buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
  11955. DE->getType().getUnqualifiedType(), DE->getExprLoc(),
  11956. /*RefersToCapture=*/true);
  11957. // Build update: Var = InitExpr + IV * Step
  11958. ExprResult Update;
  11959. if (!Info.first)
  11960. Update =
  11961. buildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate,
  11962. InitExpr, IV, Step, /* Subtract */ false);
  11963. else
  11964. Update = *CurPrivate;
  11965. Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getBeginLoc(),
  11966. /*DiscardedValue*/ false);
  11967. // Build final: Var = InitExpr + NumIterations * Step
  11968. ExprResult Final;
  11969. if (!Info.first)
  11970. Final =
  11971. buildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
  11972. InitExpr, NumIterations, Step, /*Subtract=*/false);
  11973. else
  11974. Final = *CurPrivate;
  11975. Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getBeginLoc(),
  11976. /*DiscardedValue*/ false);
  11977. if (!Update.isUsable() || !Final.isUsable()) {
  11978. Updates.push_back(nullptr);
  11979. Finals.push_back(nullptr);
  11980. HasErrors = true;
  11981. } else {
  11982. Updates.push_back(Update.get());
  11983. Finals.push_back(Final.get());
  11984. }
  11985. ++CurInit;
  11986. ++CurPrivate;
  11987. }
  11988. Clause.setUpdates(Updates);
  11989. Clause.setFinals(Finals);
  11990. return HasErrors;
  11991. }
  11992. OMPClause *Sema::ActOnOpenMPAlignedClause(
  11993. ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
  11994. SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
  11995. SmallVector<Expr *, 8> Vars;
  11996. for (Expr *RefExpr : VarList) {
  11997. assert(RefExpr && "NULL expr in OpenMP linear clause.");
  11998. SourceLocation ELoc;
  11999. SourceRange ERange;
  12000. Expr *SimpleRefExpr = RefExpr;
  12001. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  12002. if (Res.second) {
  12003. // It will be analyzed later.
  12004. Vars.push_back(RefExpr);
  12005. }
  12006. ValueDecl *D = Res.first;
  12007. if (!D)
  12008. continue;
  12009. QualType QType = D->getType();
  12010. auto *VD = dyn_cast<VarDecl>(D);
  12011. // OpenMP [2.8.1, simd construct, Restrictions]
  12012. // The type of list items appearing in the aligned clause must be
  12013. // array, pointer, reference to array, or reference to pointer.
  12014. QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
  12015. const Type *Ty = QType.getTypePtrOrNull();
  12016. if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
  12017. Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
  12018. << QType << getLangOpts().CPlusPlus << ERange;
  12019. bool IsDecl =
  12020. !VD ||
  12021. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  12022. Diag(D->getLocation(),
  12023. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  12024. << D;
  12025. continue;
  12026. }
  12027. // OpenMP [2.8.1, simd construct, Restrictions]
  12028. // A list-item cannot appear in more than one aligned clause.
  12029. if (const Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
  12030. Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange;
  12031. Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
  12032. << getOpenMPClauseName(OMPC_aligned);
  12033. continue;
  12034. }
  12035. DeclRefExpr *Ref = nullptr;
  12036. if (!VD && isOpenMPCapturedDecl(D))
  12037. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
  12038. Vars.push_back(DefaultFunctionArrayConversion(
  12039. (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
  12040. .get());
  12041. }
  12042. // OpenMP [2.8.1, simd construct, Description]
  12043. // The parameter of the aligned clause, alignment, must be a constant
  12044. // positive integer expression.
  12045. // If no optional parameter is specified, implementation-defined default
  12046. // alignments for SIMD instructions on the target platforms are assumed.
  12047. if (Alignment != nullptr) {
  12048. ExprResult AlignResult =
  12049. VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
  12050. if (AlignResult.isInvalid())
  12051. return nullptr;
  12052. Alignment = AlignResult.get();
  12053. }
  12054. if (Vars.empty())
  12055. return nullptr;
  12056. return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
  12057. EndLoc, Vars, Alignment);
  12058. }
  12059. OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
  12060. SourceLocation StartLoc,
  12061. SourceLocation LParenLoc,
  12062. SourceLocation EndLoc) {
  12063. SmallVector<Expr *, 8> Vars;
  12064. SmallVector<Expr *, 8> SrcExprs;
  12065. SmallVector<Expr *, 8> DstExprs;
  12066. SmallVector<Expr *, 8> AssignmentOps;
  12067. for (Expr *RefExpr : VarList) {
  12068. assert(RefExpr && "NULL expr in OpenMP copyin clause.");
  12069. if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
  12070. // It will be analyzed later.
  12071. Vars.push_back(RefExpr);
  12072. SrcExprs.push_back(nullptr);
  12073. DstExprs.push_back(nullptr);
  12074. AssignmentOps.push_back(nullptr);
  12075. continue;
  12076. }
  12077. SourceLocation ELoc = RefExpr->getExprLoc();
  12078. // OpenMP [2.1, C/C++]
  12079. // A list item is a variable name.
  12080. // OpenMP [2.14.4.1, Restrictions, p.1]
  12081. // A list item that appears in a copyin clause must be threadprivate.
  12082. auto *DE = dyn_cast<DeclRefExpr>(RefExpr);
  12083. if (!DE || !isa<VarDecl>(DE->getDecl())) {
  12084. Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
  12085. << 0 << RefExpr->getSourceRange();
  12086. continue;
  12087. }
  12088. Decl *D = DE->getDecl();
  12089. auto *VD = cast<VarDecl>(D);
  12090. QualType Type = VD->getType();
  12091. if (Type->isDependentType() || Type->isInstantiationDependentType()) {
  12092. // It will be analyzed later.
  12093. Vars.push_back(DE);
  12094. SrcExprs.push_back(nullptr);
  12095. DstExprs.push_back(nullptr);
  12096. AssignmentOps.push_back(nullptr);
  12097. continue;
  12098. }
  12099. // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
  12100. // A list item that appears in a copyin clause must be threadprivate.
  12101. if (!DSAStack->isThreadPrivate(VD)) {
  12102. Diag(ELoc, diag::err_omp_required_access)
  12103. << getOpenMPClauseName(OMPC_copyin)
  12104. << getOpenMPDirectiveName(OMPD_threadprivate);
  12105. continue;
  12106. }
  12107. // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
  12108. // A variable of class type (or array thereof) that appears in a
  12109. // copyin clause requires an accessible, unambiguous copy assignment
  12110. // operator for the class type.
  12111. QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
  12112. VarDecl *SrcVD =
  12113. buildVarDecl(*this, DE->getBeginLoc(), ElemType.getUnqualifiedType(),
  12114. ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
  12115. DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(
  12116. *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
  12117. VarDecl *DstVD =
  12118. buildVarDecl(*this, DE->getBeginLoc(), ElemType, ".copyin.dst",
  12119. VD->hasAttrs() ? &VD->getAttrs() : nullptr);
  12120. DeclRefExpr *PseudoDstExpr =
  12121. buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
  12122. // For arrays generate assignment operation for single element and replace
  12123. // it by the original array element in CodeGen.
  12124. ExprResult AssignmentOp =
  12125. BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign, PseudoDstExpr,
  12126. PseudoSrcExpr);
  12127. if (AssignmentOp.isInvalid())
  12128. continue;
  12129. AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
  12130. /*DiscardedValue*/ false);
  12131. if (AssignmentOp.isInvalid())
  12132. continue;
  12133. DSAStack->addDSA(VD, DE, OMPC_copyin);
  12134. Vars.push_back(DE);
  12135. SrcExprs.push_back(PseudoSrcExpr);
  12136. DstExprs.push_back(PseudoDstExpr);
  12137. AssignmentOps.push_back(AssignmentOp.get());
  12138. }
  12139. if (Vars.empty())
  12140. return nullptr;
  12141. return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
  12142. SrcExprs, DstExprs, AssignmentOps);
  12143. }
  12144. OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
  12145. SourceLocation StartLoc,
  12146. SourceLocation LParenLoc,
  12147. SourceLocation EndLoc) {
  12148. SmallVector<Expr *, 8> Vars;
  12149. SmallVector<Expr *, 8> SrcExprs;
  12150. SmallVector<Expr *, 8> DstExprs;
  12151. SmallVector<Expr *, 8> AssignmentOps;
  12152. for (Expr *RefExpr : VarList) {
  12153. assert(RefExpr && "NULL expr in OpenMP linear clause.");
  12154. SourceLocation ELoc;
  12155. SourceRange ERange;
  12156. Expr *SimpleRefExpr = RefExpr;
  12157. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  12158. if (Res.second) {
  12159. // It will be analyzed later.
  12160. Vars.push_back(RefExpr);
  12161. SrcExprs.push_back(nullptr);
  12162. DstExprs.push_back(nullptr);
  12163. AssignmentOps.push_back(nullptr);
  12164. }
  12165. ValueDecl *D = Res.first;
  12166. if (!D)
  12167. continue;
  12168. QualType Type = D->getType();
  12169. auto *VD = dyn_cast<VarDecl>(D);
  12170. // OpenMP [2.14.4.2, Restrictions, p.2]
  12171. // A list item that appears in a copyprivate clause may not appear in a
  12172. // private or firstprivate clause on the single construct.
  12173. if (!VD || !DSAStack->isThreadPrivate(VD)) {
  12174. DSAStackTy::DSAVarData DVar =
  12175. DSAStack->getTopDSA(D, /*FromParent=*/false);
  12176. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
  12177. DVar.RefExpr) {
  12178. Diag(ELoc, diag::err_omp_wrong_dsa)
  12179. << getOpenMPClauseName(DVar.CKind)
  12180. << getOpenMPClauseName(OMPC_copyprivate);
  12181. reportOriginalDsa(*this, DSAStack, D, DVar);
  12182. continue;
  12183. }
  12184. // OpenMP [2.11.4.2, Restrictions, p.1]
  12185. // All list items that appear in a copyprivate clause must be either
  12186. // threadprivate or private in the enclosing context.
  12187. if (DVar.CKind == OMPC_unknown) {
  12188. DVar = DSAStack->getImplicitDSA(D, false);
  12189. if (DVar.CKind == OMPC_shared) {
  12190. Diag(ELoc, diag::err_omp_required_access)
  12191. << getOpenMPClauseName(OMPC_copyprivate)
  12192. << "threadprivate or private in the enclosing context";
  12193. reportOriginalDsa(*this, DSAStack, D, DVar);
  12194. continue;
  12195. }
  12196. }
  12197. }
  12198. // Variably modified types are not supported.
  12199. if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
  12200. Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
  12201. << getOpenMPClauseName(OMPC_copyprivate) << Type
  12202. << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
  12203. bool IsDecl =
  12204. !VD ||
  12205. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  12206. Diag(D->getLocation(),
  12207. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  12208. << D;
  12209. continue;
  12210. }
  12211. // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
  12212. // A variable of class type (or array thereof) that appears in a
  12213. // copyin clause requires an accessible, unambiguous copy assignment
  12214. // operator for the class type.
  12215. Type = Context.getBaseElementType(Type.getNonReferenceType())
  12216. .getUnqualifiedType();
  12217. VarDecl *SrcVD =
  12218. buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.src",
  12219. D->hasAttrs() ? &D->getAttrs() : nullptr);
  12220. DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
  12221. VarDecl *DstVD =
  12222. buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.dst",
  12223. D->hasAttrs() ? &D->getAttrs() : nullptr);
  12224. DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
  12225. ExprResult AssignmentOp = BuildBinOp(
  12226. DSAStack->getCurScope(), ELoc, BO_Assign, PseudoDstExpr, PseudoSrcExpr);
  12227. if (AssignmentOp.isInvalid())
  12228. continue;
  12229. AssignmentOp =
  12230. ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
  12231. if (AssignmentOp.isInvalid())
  12232. continue;
  12233. // No need to mark vars as copyprivate, they are already threadprivate or
  12234. // implicitly private.
  12235. assert(VD || isOpenMPCapturedDecl(D));
  12236. Vars.push_back(
  12237. VD ? RefExpr->IgnoreParens()
  12238. : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
  12239. SrcExprs.push_back(PseudoSrcExpr);
  12240. DstExprs.push_back(PseudoDstExpr);
  12241. AssignmentOps.push_back(AssignmentOp.get());
  12242. }
  12243. if (Vars.empty())
  12244. return nullptr;
  12245. return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  12246. Vars, SrcExprs, DstExprs, AssignmentOps);
  12247. }
  12248. OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
  12249. SourceLocation StartLoc,
  12250. SourceLocation LParenLoc,
  12251. SourceLocation EndLoc) {
  12252. if (VarList.empty())
  12253. return nullptr;
  12254. return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
  12255. }
  12256. OMPClause *
  12257. Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
  12258. SourceLocation DepLoc, SourceLocation ColonLoc,
  12259. ArrayRef<Expr *> VarList, SourceLocation StartLoc,
  12260. SourceLocation LParenLoc, SourceLocation EndLoc) {
  12261. if (DSAStack->getCurrentDirective() == OMPD_ordered &&
  12262. DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
  12263. Diag(DepLoc, diag::err_omp_unexpected_clause_value)
  12264. << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
  12265. return nullptr;
  12266. }
  12267. if (DSAStack->getCurrentDirective() != OMPD_ordered &&
  12268. (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
  12269. DepKind == OMPC_DEPEND_sink)) {
  12270. unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink};
  12271. Diag(DepLoc, diag::err_omp_unexpected_clause_value)
  12272. << getListOfPossibleValues(OMPC_depend, /*First=*/0,
  12273. /*Last=*/OMPC_DEPEND_unknown, Except)
  12274. << getOpenMPClauseName(OMPC_depend);
  12275. return nullptr;
  12276. }
  12277. SmallVector<Expr *, 8> Vars;
  12278. DSAStackTy::OperatorOffsetTy OpsOffs;
  12279. llvm::APSInt DepCounter(/*BitWidth=*/32);
  12280. llvm::APSInt TotalDepCount(/*BitWidth=*/32);
  12281. if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) {
  12282. if (const Expr *OrderedCountExpr =
  12283. DSAStack->getParentOrderedRegionParam().first) {
  12284. TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
  12285. TotalDepCount.setIsUnsigned(/*Val=*/true);
  12286. }
  12287. }
  12288. for (Expr *RefExpr : VarList) {
  12289. assert(RefExpr && "NULL expr in OpenMP shared clause.");
  12290. if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
  12291. // It will be analyzed later.
  12292. Vars.push_back(RefExpr);
  12293. continue;
  12294. }
  12295. SourceLocation ELoc = RefExpr->getExprLoc();
  12296. Expr *SimpleExpr = RefExpr->IgnoreParenCasts();
  12297. if (DepKind == OMPC_DEPEND_sink) {
  12298. if (DSAStack->getParentOrderedRegionParam().first &&
  12299. DepCounter >= TotalDepCount) {
  12300. Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
  12301. continue;
  12302. }
  12303. ++DepCounter;
  12304. // OpenMP [2.13.9, Summary]
  12305. // depend(dependence-type : vec), where dependence-type is:
  12306. // 'sink' and where vec is the iteration vector, which has the form:
  12307. // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
  12308. // where n is the value specified by the ordered clause in the loop
  12309. // directive, xi denotes the loop iteration variable of the i-th nested
  12310. // loop associated with the loop directive, and di is a constant
  12311. // non-negative integer.
  12312. if (CurContext->isDependentContext()) {
  12313. // It will be analyzed later.
  12314. Vars.push_back(RefExpr);
  12315. continue;
  12316. }
  12317. SimpleExpr = SimpleExpr->IgnoreImplicit();
  12318. OverloadedOperatorKind OOK = OO_None;
  12319. SourceLocation OOLoc;
  12320. Expr *LHS = SimpleExpr;
  12321. Expr *RHS = nullptr;
  12322. if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
  12323. OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
  12324. OOLoc = BO->getOperatorLoc();
  12325. LHS = BO->getLHS()->IgnoreParenImpCasts();
  12326. RHS = BO->getRHS()->IgnoreParenImpCasts();
  12327. } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
  12328. OOK = OCE->getOperator();
  12329. OOLoc = OCE->getOperatorLoc();
  12330. LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
  12331. RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
  12332. } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
  12333. OOK = MCE->getMethodDecl()
  12334. ->getNameInfo()
  12335. .getName()
  12336. .getCXXOverloadedOperator();
  12337. OOLoc = MCE->getCallee()->getExprLoc();
  12338. LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
  12339. RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
  12340. }
  12341. SourceLocation ELoc;
  12342. SourceRange ERange;
  12343. auto Res = getPrivateItem(*this, LHS, ELoc, ERange);
  12344. if (Res.second) {
  12345. // It will be analyzed later.
  12346. Vars.push_back(RefExpr);
  12347. }
  12348. ValueDecl *D = Res.first;
  12349. if (!D)
  12350. continue;
  12351. if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
  12352. Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
  12353. continue;
  12354. }
  12355. if (RHS) {
  12356. ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
  12357. RHS, OMPC_depend, /*StrictlyPositive=*/false);
  12358. if (RHSRes.isInvalid())
  12359. continue;
  12360. }
  12361. if (!CurContext->isDependentContext() &&
  12362. DSAStack->getParentOrderedRegionParam().first &&
  12363. DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
  12364. const ValueDecl *VD =
  12365. DSAStack->getParentLoopControlVariable(DepCounter.getZExtValue());
  12366. if (VD)
  12367. Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
  12368. << 1 << VD;
  12369. else
  12370. Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) << 0;
  12371. continue;
  12372. }
  12373. OpsOffs.emplace_back(RHS, OOK);
  12374. } else {
  12375. auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
  12376. if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
  12377. (ASE &&
  12378. !ASE->getBase()->getType().getNonReferenceType()->isPointerType() &&
  12379. !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
  12380. Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
  12381. << RefExpr->getSourceRange();
  12382. continue;
  12383. }
  12384. bool Suppress = getDiagnostics().getSuppressAllDiagnostics();
  12385. getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
  12386. ExprResult Res =
  12387. CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RefExpr->IgnoreParenImpCasts());
  12388. getDiagnostics().setSuppressAllDiagnostics(Suppress);
  12389. if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr)) {
  12390. Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
  12391. << RefExpr->getSourceRange();
  12392. continue;
  12393. }
  12394. }
  12395. Vars.push_back(RefExpr->IgnoreParenImpCasts());
  12396. }
  12397. if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
  12398. TotalDepCount > VarList.size() &&
  12399. DSAStack->getParentOrderedRegionParam().first &&
  12400. DSAStack->getParentLoopControlVariable(VarList.size() + 1)) {
  12401. Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration)
  12402. << 1 << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
  12403. }
  12404. if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
  12405. Vars.empty())
  12406. return nullptr;
  12407. auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  12408. DepKind, DepLoc, ColonLoc, Vars,
  12409. TotalDepCount.getZExtValue());
  12410. if ((DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) &&
  12411. DSAStack->isParentOrderedRegion())
  12412. DSAStack->addDoacrossDependClause(C, OpsOffs);
  12413. return C;
  12414. }
  12415. OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
  12416. SourceLocation LParenLoc,
  12417. SourceLocation EndLoc) {
  12418. Expr *ValExpr = Device;
  12419. Stmt *HelperValStmt = nullptr;
  12420. // OpenMP [2.9.1, Restrictions]
  12421. // The device expression must evaluate to a non-negative integer value.
  12422. if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
  12423. /*StrictlyPositive=*/false))
  12424. return nullptr;
  12425. OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
  12426. OpenMPDirectiveKind CaptureRegion =
  12427. getOpenMPCaptureRegionForClause(DKind, OMPC_device);
  12428. if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
  12429. ValExpr = MakeFullExpr(ValExpr).get();
  12430. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  12431. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  12432. HelperValStmt = buildPreInits(Context, Captures);
  12433. }
  12434. return new (Context) OMPDeviceClause(ValExpr, HelperValStmt, CaptureRegion,
  12435. StartLoc, LParenLoc, EndLoc);
  12436. }
  12437. static bool checkTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
  12438. DSAStackTy *Stack, QualType QTy,
  12439. bool FullCheck = true) {
  12440. NamedDecl *ND;
  12441. if (QTy->isIncompleteType(&ND)) {
  12442. SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
  12443. return false;
  12444. }
  12445. if (FullCheck && !SemaRef.CurContext->isDependentContext() &&
  12446. !QTy.isTrivialType(SemaRef.Context))
  12447. SemaRef.Diag(SL, diag::warn_omp_non_trivial_type_mapped) << QTy << SR;
  12448. return true;
  12449. }
  12450. /// Return true if it can be proven that the provided array expression
  12451. /// (array section or array subscript) does NOT specify the whole size of the
  12452. /// array whose base type is \a BaseQTy.
  12453. static bool checkArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
  12454. const Expr *E,
  12455. QualType BaseQTy) {
  12456. const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
  12457. // If this is an array subscript, it refers to the whole size if the size of
  12458. // the dimension is constant and equals 1. Also, an array section assumes the
  12459. // format of an array subscript if no colon is used.
  12460. if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) {
  12461. if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
  12462. return ATy->getSize().getSExtValue() != 1;
  12463. // Size can't be evaluated statically.
  12464. return false;
  12465. }
  12466. assert(OASE && "Expecting array section if not an array subscript.");
  12467. const Expr *LowerBound = OASE->getLowerBound();
  12468. const Expr *Length = OASE->getLength();
  12469. // If there is a lower bound that does not evaluates to zero, we are not
  12470. // covering the whole dimension.
  12471. if (LowerBound) {
  12472. Expr::EvalResult Result;
  12473. if (!LowerBound->EvaluateAsInt(Result, SemaRef.getASTContext()))
  12474. return false; // Can't get the integer value as a constant.
  12475. llvm::APSInt ConstLowerBound = Result.Val.getInt();
  12476. if (ConstLowerBound.getSExtValue())
  12477. return true;
  12478. }
  12479. // If we don't have a length we covering the whole dimension.
  12480. if (!Length)
  12481. return false;
  12482. // If the base is a pointer, we don't have a way to get the size of the
  12483. // pointee.
  12484. if (BaseQTy->isPointerType())
  12485. return false;
  12486. // We can only check if the length is the same as the size of the dimension
  12487. // if we have a constant array.
  12488. const auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
  12489. if (!CATy)
  12490. return false;
  12491. Expr::EvalResult Result;
  12492. if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
  12493. return false; // Can't get the integer value as a constant.
  12494. llvm::APSInt ConstLength = Result.Val.getInt();
  12495. return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
  12496. }
  12497. // Return true if it can be proven that the provided array expression (array
  12498. // section or array subscript) does NOT specify a single element of the array
  12499. // whose base type is \a BaseQTy.
  12500. static bool checkArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
  12501. const Expr *E,
  12502. QualType BaseQTy) {
  12503. const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
  12504. // An array subscript always refer to a single element. Also, an array section
  12505. // assumes the format of an array subscript if no colon is used.
  12506. if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid()))
  12507. return false;
  12508. assert(OASE && "Expecting array section if not an array subscript.");
  12509. const Expr *Length = OASE->getLength();
  12510. // If we don't have a length we have to check if the array has unitary size
  12511. // for this dimension. Also, we should always expect a length if the base type
  12512. // is pointer.
  12513. if (!Length) {
  12514. if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
  12515. return ATy->getSize().getSExtValue() != 1;
  12516. // We cannot assume anything.
  12517. return false;
  12518. }
  12519. // Check if the length evaluates to 1.
  12520. Expr::EvalResult Result;
  12521. if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
  12522. return false; // Can't get the integer value as a constant.
  12523. llvm::APSInt ConstLength = Result.Val.getInt();
  12524. return ConstLength.getSExtValue() != 1;
  12525. }
  12526. // Return the expression of the base of the mappable expression or null if it
  12527. // cannot be determined and do all the necessary checks to see if the expression
  12528. // is valid as a standalone mappable expression. In the process, record all the
  12529. // components of the expression.
  12530. static const Expr *checkMapClauseExpressionBase(
  12531. Sema &SemaRef, Expr *E,
  12532. OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
  12533. OpenMPClauseKind CKind, bool NoDiagnose) {
  12534. SourceLocation ELoc = E->getExprLoc();
  12535. SourceRange ERange = E->getSourceRange();
  12536. // The base of elements of list in a map clause have to be either:
  12537. // - a reference to variable or field.
  12538. // - a member expression.
  12539. // - an array expression.
  12540. //
  12541. // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
  12542. // reference to 'r'.
  12543. //
  12544. // If we have:
  12545. //
  12546. // struct SS {
  12547. // Bla S;
  12548. // foo() {
  12549. // #pragma omp target map (S.Arr[:12]);
  12550. // }
  12551. // }
  12552. //
  12553. // We want to retrieve the member expression 'this->S';
  12554. const Expr *RelevantExpr = nullptr;
  12555. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2]
  12556. // If a list item is an array section, it must specify contiguous storage.
  12557. //
  12558. // For this restriction it is sufficient that we make sure only references
  12559. // to variables or fields and array expressions, and that no array sections
  12560. // exist except in the rightmost expression (unless they cover the whole
  12561. // dimension of the array). E.g. these would be invalid:
  12562. //
  12563. // r.ArrS[3:5].Arr[6:7]
  12564. //
  12565. // r.ArrS[3:5].x
  12566. //
  12567. // but these would be valid:
  12568. // r.ArrS[3].Arr[6:7]
  12569. //
  12570. // r.ArrS[3].x
  12571. bool AllowUnitySizeArraySection = true;
  12572. bool AllowWholeSizeArraySection = true;
  12573. while (!RelevantExpr) {
  12574. E = E->IgnoreParenImpCasts();
  12575. if (auto *CurE = dyn_cast<DeclRefExpr>(E)) {
  12576. if (!isa<VarDecl>(CurE->getDecl()))
  12577. return nullptr;
  12578. RelevantExpr = CurE;
  12579. // If we got a reference to a declaration, we should not expect any array
  12580. // section before that.
  12581. AllowUnitySizeArraySection = false;
  12582. AllowWholeSizeArraySection = false;
  12583. // Record the component.
  12584. CurComponents.emplace_back(CurE, CurE->getDecl());
  12585. } else if (auto *CurE = dyn_cast<MemberExpr>(E)) {
  12586. Expr *BaseE = CurE->getBase()->IgnoreParenImpCasts();
  12587. if (isa<CXXThisExpr>(BaseE))
  12588. // We found a base expression: this->Val.
  12589. RelevantExpr = CurE;
  12590. else
  12591. E = BaseE;
  12592. if (!isa<FieldDecl>(CurE->getMemberDecl())) {
  12593. if (!NoDiagnose) {
  12594. SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
  12595. << CurE->getSourceRange();
  12596. return nullptr;
  12597. }
  12598. if (RelevantExpr)
  12599. return nullptr;
  12600. continue;
  12601. }
  12602. auto *FD = cast<FieldDecl>(CurE->getMemberDecl());
  12603. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
  12604. // A bit-field cannot appear in a map clause.
  12605. //
  12606. if (FD->isBitField()) {
  12607. if (!NoDiagnose) {
  12608. SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
  12609. << CurE->getSourceRange() << getOpenMPClauseName(CKind);
  12610. return nullptr;
  12611. }
  12612. if (RelevantExpr)
  12613. return nullptr;
  12614. continue;
  12615. }
  12616. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
  12617. // If the type of a list item is a reference to a type T then the type
  12618. // will be considered to be T for all purposes of this clause.
  12619. QualType CurType = BaseE->getType().getNonReferenceType();
  12620. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
  12621. // A list item cannot be a variable that is a member of a structure with
  12622. // a union type.
  12623. //
  12624. if (CurType->isUnionType()) {
  12625. if (!NoDiagnose) {
  12626. SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
  12627. << CurE->getSourceRange();
  12628. return nullptr;
  12629. }
  12630. continue;
  12631. }
  12632. // If we got a member expression, we should not expect any array section
  12633. // before that:
  12634. //
  12635. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
  12636. // If a list item is an element of a structure, only the rightmost symbol
  12637. // of the variable reference can be an array section.
  12638. //
  12639. AllowUnitySizeArraySection = false;
  12640. AllowWholeSizeArraySection = false;
  12641. // Record the component.
  12642. CurComponents.emplace_back(CurE, FD);
  12643. } else if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) {
  12644. E = CurE->getBase()->IgnoreParenImpCasts();
  12645. if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
  12646. if (!NoDiagnose) {
  12647. SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
  12648. << 0 << CurE->getSourceRange();
  12649. return nullptr;
  12650. }
  12651. continue;
  12652. }
  12653. // If we got an array subscript that express the whole dimension we
  12654. // can have any array expressions before. If it only expressing part of
  12655. // the dimension, we can only have unitary-size array expressions.
  12656. if (checkArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE,
  12657. E->getType()))
  12658. AllowWholeSizeArraySection = false;
  12659. if (const auto *TE = dyn_cast<CXXThisExpr>(E)) {
  12660. Expr::EvalResult Result;
  12661. if (CurE->getIdx()->EvaluateAsInt(Result, SemaRef.getASTContext())) {
  12662. if (!Result.Val.getInt().isNullValue()) {
  12663. SemaRef.Diag(CurE->getIdx()->getExprLoc(),
  12664. diag::err_omp_invalid_map_this_expr);
  12665. SemaRef.Diag(CurE->getIdx()->getExprLoc(),
  12666. diag::note_omp_invalid_subscript_on_this_ptr_map);
  12667. }
  12668. }
  12669. RelevantExpr = TE;
  12670. }
  12671. // Record the component - we don't have any declaration associated.
  12672. CurComponents.emplace_back(CurE, nullptr);
  12673. } else if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) {
  12674. assert(!NoDiagnose && "Array sections cannot be implicitly mapped.");
  12675. E = CurE->getBase()->IgnoreParenImpCasts();
  12676. QualType CurType =
  12677. OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
  12678. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
  12679. // If the type of a list item is a reference to a type T then the type
  12680. // will be considered to be T for all purposes of this clause.
  12681. if (CurType->isReferenceType())
  12682. CurType = CurType->getPointeeType();
  12683. bool IsPointer = CurType->isAnyPointerType();
  12684. if (!IsPointer && !CurType->isArrayType()) {
  12685. SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
  12686. << 0 << CurE->getSourceRange();
  12687. return nullptr;
  12688. }
  12689. bool NotWhole =
  12690. checkArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType);
  12691. bool NotUnity =
  12692. checkArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType);
  12693. if (AllowWholeSizeArraySection) {
  12694. // Any array section is currently allowed. Allowing a whole size array
  12695. // section implies allowing a unity array section as well.
  12696. //
  12697. // If this array section refers to the whole dimension we can still
  12698. // accept other array sections before this one, except if the base is a
  12699. // pointer. Otherwise, only unitary sections are accepted.
  12700. if (NotWhole || IsPointer)
  12701. AllowWholeSizeArraySection = false;
  12702. } else if (AllowUnitySizeArraySection && NotUnity) {
  12703. // A unity or whole array section is not allowed and that is not
  12704. // compatible with the properties of the current array section.
  12705. SemaRef.Diag(
  12706. ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
  12707. << CurE->getSourceRange();
  12708. return nullptr;
  12709. }
  12710. if (const auto *TE = dyn_cast<CXXThisExpr>(E)) {
  12711. Expr::EvalResult ResultR;
  12712. Expr::EvalResult ResultL;
  12713. if (CurE->getLength()->EvaluateAsInt(ResultR,
  12714. SemaRef.getASTContext())) {
  12715. if (!ResultR.Val.getInt().isOneValue()) {
  12716. SemaRef.Diag(CurE->getLength()->getExprLoc(),
  12717. diag::err_omp_invalid_map_this_expr);
  12718. SemaRef.Diag(CurE->getLength()->getExprLoc(),
  12719. diag::note_omp_invalid_length_on_this_ptr_mapping);
  12720. }
  12721. }
  12722. if (CurE->getLowerBound() && CurE->getLowerBound()->EvaluateAsInt(
  12723. ResultL, SemaRef.getASTContext())) {
  12724. if (!ResultL.Val.getInt().isNullValue()) {
  12725. SemaRef.Diag(CurE->getLowerBound()->getExprLoc(),
  12726. diag::err_omp_invalid_map_this_expr);
  12727. SemaRef.Diag(CurE->getLowerBound()->getExprLoc(),
  12728. diag::note_omp_invalid_lower_bound_on_this_ptr_mapping);
  12729. }
  12730. }
  12731. RelevantExpr = TE;
  12732. }
  12733. // Record the component - we don't have any declaration associated.
  12734. CurComponents.emplace_back(CurE, nullptr);
  12735. } else {
  12736. if (!NoDiagnose) {
  12737. // If nothing else worked, this is not a valid map clause expression.
  12738. SemaRef.Diag(
  12739. ELoc, diag::err_omp_expected_named_var_member_or_array_expression)
  12740. << ERange;
  12741. }
  12742. return nullptr;
  12743. }
  12744. }
  12745. return RelevantExpr;
  12746. }
  12747. // Return true if expression E associated with value VD has conflicts with other
  12748. // map information.
  12749. static bool checkMapConflicts(
  12750. Sema &SemaRef, DSAStackTy *DSAS, const ValueDecl *VD, const Expr *E,
  12751. bool CurrentRegionOnly,
  12752. OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
  12753. OpenMPClauseKind CKind) {
  12754. assert(VD && E);
  12755. SourceLocation ELoc = E->getExprLoc();
  12756. SourceRange ERange = E->getSourceRange();
  12757. // In order to easily check the conflicts we need to match each component of
  12758. // the expression under test with the components of the expressions that are
  12759. // already in the stack.
  12760. assert(!CurComponents.empty() && "Map clause expression with no components!");
  12761. assert(CurComponents.back().getAssociatedDeclaration() == VD &&
  12762. "Map clause expression with unexpected base!");
  12763. // Variables to help detecting enclosing problems in data environment nests.
  12764. bool IsEnclosedByDataEnvironmentExpr = false;
  12765. const Expr *EnclosingExpr = nullptr;
  12766. bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
  12767. VD, CurrentRegionOnly,
  12768. [&IsEnclosedByDataEnvironmentExpr, &SemaRef, VD, CurrentRegionOnly, ELoc,
  12769. ERange, CKind, &EnclosingExpr,
  12770. CurComponents](OMPClauseMappableExprCommon::MappableExprComponentListRef
  12771. StackComponents,
  12772. OpenMPClauseKind) {
  12773. assert(!StackComponents.empty() &&
  12774. "Map clause expression with no components!");
  12775. assert(StackComponents.back().getAssociatedDeclaration() == VD &&
  12776. "Map clause expression with unexpected base!");
  12777. (void)VD;
  12778. // The whole expression in the stack.
  12779. const Expr *RE = StackComponents.front().getAssociatedExpression();
  12780. // Expressions must start from the same base. Here we detect at which
  12781. // point both expressions diverge from each other and see if we can
  12782. // detect if the memory referred to both expressions is contiguous and
  12783. // do not overlap.
  12784. auto CI = CurComponents.rbegin();
  12785. auto CE = CurComponents.rend();
  12786. auto SI = StackComponents.rbegin();
  12787. auto SE = StackComponents.rend();
  12788. for (; CI != CE && SI != SE; ++CI, ++SI) {
  12789. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
  12790. // At most one list item can be an array item derived from a given
  12791. // variable in map clauses of the same construct.
  12792. if (CurrentRegionOnly &&
  12793. (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
  12794. isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) &&
  12795. (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
  12796. isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) {
  12797. SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
  12798. diag::err_omp_multiple_array_items_in_map_clause)
  12799. << CI->getAssociatedExpression()->getSourceRange();
  12800. SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
  12801. diag::note_used_here)
  12802. << SI->getAssociatedExpression()->getSourceRange();
  12803. return true;
  12804. }
  12805. // Do both expressions have the same kind?
  12806. if (CI->getAssociatedExpression()->getStmtClass() !=
  12807. SI->getAssociatedExpression()->getStmtClass())
  12808. break;
  12809. // Are we dealing with different variables/fields?
  12810. if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
  12811. break;
  12812. }
  12813. // Check if the extra components of the expressions in the enclosing
  12814. // data environment are redundant for the current base declaration.
  12815. // If they are, the maps completely overlap, which is legal.
  12816. for (; SI != SE; ++SI) {
  12817. QualType Type;
  12818. if (const auto *ASE =
  12819. dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
  12820. Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
  12821. } else if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(
  12822. SI->getAssociatedExpression())) {
  12823. const Expr *E = OASE->getBase()->IgnoreParenImpCasts();
  12824. Type =
  12825. OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
  12826. }
  12827. if (Type.isNull() || Type->isAnyPointerType() ||
  12828. checkArrayExpressionDoesNotReferToWholeSize(
  12829. SemaRef, SI->getAssociatedExpression(), Type))
  12830. break;
  12831. }
  12832. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
  12833. // List items of map clauses in the same construct must not share
  12834. // original storage.
  12835. //
  12836. // If the expressions are exactly the same or one is a subset of the
  12837. // other, it means they are sharing storage.
  12838. if (CI == CE && SI == SE) {
  12839. if (CurrentRegionOnly) {
  12840. if (CKind == OMPC_map) {
  12841. SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
  12842. } else {
  12843. assert(CKind == OMPC_to || CKind == OMPC_from);
  12844. SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
  12845. << ERange;
  12846. }
  12847. SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
  12848. << RE->getSourceRange();
  12849. return true;
  12850. }
  12851. // If we find the same expression in the enclosing data environment,
  12852. // that is legal.
  12853. IsEnclosedByDataEnvironmentExpr = true;
  12854. return false;
  12855. }
  12856. QualType DerivedType =
  12857. std::prev(CI)->getAssociatedDeclaration()->getType();
  12858. SourceLocation DerivedLoc =
  12859. std::prev(CI)->getAssociatedExpression()->getExprLoc();
  12860. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
  12861. // If the type of a list item is a reference to a type T then the type
  12862. // will be considered to be T for all purposes of this clause.
  12863. DerivedType = DerivedType.getNonReferenceType();
  12864. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
  12865. // A variable for which the type is pointer and an array section
  12866. // derived from that variable must not appear as list items of map
  12867. // clauses of the same construct.
  12868. //
  12869. // Also, cover one of the cases in:
  12870. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
  12871. // If any part of the original storage of a list item has corresponding
  12872. // storage in the device data environment, all of the original storage
  12873. // must have corresponding storage in the device data environment.
  12874. //
  12875. if (DerivedType->isAnyPointerType()) {
  12876. if (CI == CE || SI == SE) {
  12877. SemaRef.Diag(
  12878. DerivedLoc,
  12879. diag::err_omp_pointer_mapped_along_with_derived_section)
  12880. << DerivedLoc;
  12881. SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
  12882. << RE->getSourceRange();
  12883. return true;
  12884. }
  12885. if (CI->getAssociatedExpression()->getStmtClass() !=
  12886. SI->getAssociatedExpression()->getStmtClass() ||
  12887. CI->getAssociatedDeclaration()->getCanonicalDecl() ==
  12888. SI->getAssociatedDeclaration()->getCanonicalDecl()) {
  12889. assert(CI != CE && SI != SE);
  12890. SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_dereferenced)
  12891. << DerivedLoc;
  12892. SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
  12893. << RE->getSourceRange();
  12894. return true;
  12895. }
  12896. }
  12897. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
  12898. // List items of map clauses in the same construct must not share
  12899. // original storage.
  12900. //
  12901. // An expression is a subset of the other.
  12902. if (CurrentRegionOnly && (CI == CE || SI == SE)) {
  12903. if (CKind == OMPC_map) {
  12904. if (CI != CE || SI != SE) {
  12905. // Allow constructs like this: map(s, s.ptr[0:1]), where s.ptr is
  12906. // a pointer.
  12907. auto Begin =
  12908. CI != CE ? CurComponents.begin() : StackComponents.begin();
  12909. auto End = CI != CE ? CurComponents.end() : StackComponents.end();
  12910. auto It = Begin;
  12911. while (It != End && !It->getAssociatedDeclaration())
  12912. std::advance(It, 1);
  12913. assert(It != End &&
  12914. "Expected at least one component with the declaration.");
  12915. if (It != Begin && It->getAssociatedDeclaration()
  12916. ->getType()
  12917. .getCanonicalType()
  12918. ->isAnyPointerType()) {
  12919. IsEnclosedByDataEnvironmentExpr = false;
  12920. EnclosingExpr = nullptr;
  12921. return false;
  12922. }
  12923. }
  12924. SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
  12925. } else {
  12926. assert(CKind == OMPC_to || CKind == OMPC_from);
  12927. SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
  12928. << ERange;
  12929. }
  12930. SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
  12931. << RE->getSourceRange();
  12932. return true;
  12933. }
  12934. // The current expression uses the same base as other expression in the
  12935. // data environment but does not contain it completely.
  12936. if (!CurrentRegionOnly && SI != SE)
  12937. EnclosingExpr = RE;
  12938. // The current expression is a subset of the expression in the data
  12939. // environment.
  12940. IsEnclosedByDataEnvironmentExpr |=
  12941. (!CurrentRegionOnly && CI != CE && SI == SE);
  12942. return false;
  12943. });
  12944. if (CurrentRegionOnly)
  12945. return FoundError;
  12946. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
  12947. // If any part of the original storage of a list item has corresponding
  12948. // storage in the device data environment, all of the original storage must
  12949. // have corresponding storage in the device data environment.
  12950. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
  12951. // If a list item is an element of a structure, and a different element of
  12952. // the structure has a corresponding list item in the device data environment
  12953. // prior to a task encountering the construct associated with the map clause,
  12954. // then the list item must also have a corresponding list item in the device
  12955. // data environment prior to the task encountering the construct.
  12956. //
  12957. if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
  12958. SemaRef.Diag(ELoc,
  12959. diag::err_omp_original_storage_is_shared_and_does_not_contain)
  12960. << ERange;
  12961. SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
  12962. << EnclosingExpr->getSourceRange();
  12963. return true;
  12964. }
  12965. return FoundError;
  12966. }
  12967. // Look up the user-defined mapper given the mapper name and mapped type, and
  12968. // build a reference to it.
  12969. static ExprResult buildUserDefinedMapperRef(Sema &SemaRef, Scope *S,
  12970. CXXScopeSpec &MapperIdScopeSpec,
  12971. const DeclarationNameInfo &MapperId,
  12972. QualType Type,
  12973. Expr *UnresolvedMapper) {
  12974. if (MapperIdScopeSpec.isInvalid())
  12975. return ExprError();
  12976. // Find all user-defined mappers with the given MapperId.
  12977. SmallVector<UnresolvedSet<8>, 4> Lookups;
  12978. LookupResult Lookup(SemaRef, MapperId, Sema::LookupOMPMapperName);
  12979. Lookup.suppressDiagnostics();
  12980. if (S) {
  12981. while (S && SemaRef.LookupParsedName(Lookup, S, &MapperIdScopeSpec)) {
  12982. NamedDecl *D = Lookup.getRepresentativeDecl();
  12983. while (S && !S->isDeclScope(D))
  12984. S = S->getParent();
  12985. if (S)
  12986. S = S->getParent();
  12987. Lookups.emplace_back();
  12988. Lookups.back().append(Lookup.begin(), Lookup.end());
  12989. Lookup.clear();
  12990. }
  12991. } else if (auto *ULE = cast_or_null<UnresolvedLookupExpr>(UnresolvedMapper)) {
  12992. // Extract the user-defined mappers with the given MapperId.
  12993. Lookups.push_back(UnresolvedSet<8>());
  12994. for (NamedDecl *D : ULE->decls()) {
  12995. auto *DMD = cast<OMPDeclareMapperDecl>(D);
  12996. assert(DMD && "Expect valid OMPDeclareMapperDecl during instantiation.");
  12997. Lookups.back().addDecl(DMD);
  12998. }
  12999. }
  13000. // Defer the lookup for dependent types. The results will be passed through
  13001. // UnresolvedMapper on instantiation.
  13002. if (SemaRef.CurContext->isDependentContext() || Type->isDependentType() ||
  13003. Type->isInstantiationDependentType() ||
  13004. Type->containsUnexpandedParameterPack() ||
  13005. filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) {
  13006. return !D->isInvalidDecl() &&
  13007. (D->getType()->isDependentType() ||
  13008. D->getType()->isInstantiationDependentType() ||
  13009. D->getType()->containsUnexpandedParameterPack());
  13010. })) {
  13011. UnresolvedSet<8> URS;
  13012. for (const UnresolvedSet<8> &Set : Lookups) {
  13013. if (Set.empty())
  13014. continue;
  13015. URS.append(Set.begin(), Set.end());
  13016. }
  13017. return UnresolvedLookupExpr::Create(
  13018. SemaRef.Context, /*NamingClass=*/nullptr,
  13019. MapperIdScopeSpec.getWithLocInContext(SemaRef.Context), MapperId,
  13020. /*ADL=*/false, /*Overloaded=*/true, URS.begin(), URS.end());
  13021. }
  13022. // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
  13023. // The type must be of struct, union or class type in C and C++
  13024. if (!Type->isStructureOrClassType() && !Type->isUnionType())
  13025. return ExprEmpty();
  13026. SourceLocation Loc = MapperId.getLoc();
  13027. // Perform argument dependent lookup.
  13028. if (SemaRef.getLangOpts().CPlusPlus && !MapperIdScopeSpec.isSet())
  13029. argumentDependentLookup(SemaRef, MapperId, Loc, Type, Lookups);
  13030. // Return the first user-defined mapper with the desired type.
  13031. if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
  13032. Lookups, [&SemaRef, Type](ValueDecl *D) -> ValueDecl * {
  13033. if (!D->isInvalidDecl() &&
  13034. SemaRef.Context.hasSameType(D->getType(), Type))
  13035. return D;
  13036. return nullptr;
  13037. }))
  13038. return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
  13039. // Find the first user-defined mapper with a type derived from the desired
  13040. // type.
  13041. if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
  13042. Lookups, [&SemaRef, Type, Loc](ValueDecl *D) -> ValueDecl * {
  13043. if (!D->isInvalidDecl() &&
  13044. SemaRef.IsDerivedFrom(Loc, Type, D->getType()) &&
  13045. !Type.isMoreQualifiedThan(D->getType()))
  13046. return D;
  13047. return nullptr;
  13048. })) {
  13049. CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
  13050. /*DetectVirtual=*/false);
  13051. if (SemaRef.IsDerivedFrom(Loc, Type, VD->getType(), Paths)) {
  13052. if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
  13053. VD->getType().getUnqualifiedType()))) {
  13054. if (SemaRef.CheckBaseClassAccess(
  13055. Loc, VD->getType(), Type, Paths.front(),
  13056. /*DiagID=*/0) != Sema::AR_inaccessible) {
  13057. return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
  13058. }
  13059. }
  13060. }
  13061. }
  13062. // Report error if a mapper is specified, but cannot be found.
  13063. if (MapperIdScopeSpec.isSet() || MapperId.getAsString() != "default") {
  13064. SemaRef.Diag(Loc, diag::err_omp_invalid_mapper)
  13065. << Type << MapperId.getName();
  13066. return ExprError();
  13067. }
  13068. return ExprEmpty();
  13069. }
  13070. namespace {
  13071. // Utility struct that gathers all the related lists associated with a mappable
  13072. // expression.
  13073. struct MappableVarListInfo {
  13074. // The list of expressions.
  13075. ArrayRef<Expr *> VarList;
  13076. // The list of processed expressions.
  13077. SmallVector<Expr *, 16> ProcessedVarList;
  13078. // The mappble components for each expression.
  13079. OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
  13080. // The base declaration of the variable.
  13081. SmallVector<ValueDecl *, 16> VarBaseDeclarations;
  13082. // The reference to the user-defined mapper associated with every expression.
  13083. SmallVector<Expr *, 16> UDMapperList;
  13084. MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
  13085. // We have a list of components and base declarations for each entry in the
  13086. // variable list.
  13087. VarComponents.reserve(VarList.size());
  13088. VarBaseDeclarations.reserve(VarList.size());
  13089. }
  13090. };
  13091. }
  13092. // Check the validity of the provided variable list for the provided clause kind
  13093. // \a CKind. In the check process the valid expressions, mappable expression
  13094. // components, variables, and user-defined mappers are extracted and used to
  13095. // fill \a ProcessedVarList, \a VarComponents, \a VarBaseDeclarations, and \a
  13096. // UDMapperList in MVLI. \a MapType, \a IsMapTypeImplicit, \a MapperIdScopeSpec,
  13097. // and \a MapperId are expected to be valid if the clause kind is 'map'.
  13098. static void checkMappableExpressionList(
  13099. Sema &SemaRef, DSAStackTy *DSAS, OpenMPClauseKind CKind,
  13100. MappableVarListInfo &MVLI, SourceLocation StartLoc,
  13101. CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo MapperId,
  13102. ArrayRef<Expr *> UnresolvedMappers,
  13103. OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
  13104. bool IsMapTypeImplicit = false) {
  13105. // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
  13106. assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
  13107. "Unexpected clause kind with mappable expressions!");
  13108. // If the identifier of user-defined mapper is not specified, it is "default".
  13109. // We do not change the actual name in this clause to distinguish whether a
  13110. // mapper is specified explicitly, i.e., it is not explicitly specified when
  13111. // MapperId.getName() is empty.
  13112. if (!MapperId.getName() || MapperId.getName().isEmpty()) {
  13113. auto &DeclNames = SemaRef.getASTContext().DeclarationNames;
  13114. MapperId.setName(DeclNames.getIdentifier(
  13115. &SemaRef.getASTContext().Idents.get("default")));
  13116. }
  13117. // Iterators to find the current unresolved mapper expression.
  13118. auto UMIt = UnresolvedMappers.begin(), UMEnd = UnresolvedMappers.end();
  13119. bool UpdateUMIt = false;
  13120. Expr *UnresolvedMapper = nullptr;
  13121. // Keep track of the mappable components and base declarations in this clause.
  13122. // Each entry in the list is going to have a list of components associated. We
  13123. // record each set of the components so that we can build the clause later on.
  13124. // In the end we should have the same amount of declarations and component
  13125. // lists.
  13126. for (Expr *RE : MVLI.VarList) {
  13127. assert(RE && "Null expr in omp to/from/map clause");
  13128. SourceLocation ELoc = RE->getExprLoc();
  13129. // Find the current unresolved mapper expression.
  13130. if (UpdateUMIt && UMIt != UMEnd) {
  13131. UMIt++;
  13132. assert(
  13133. UMIt != UMEnd &&
  13134. "Expect the size of UnresolvedMappers to match with that of VarList");
  13135. }
  13136. UpdateUMIt = true;
  13137. if (UMIt != UMEnd)
  13138. UnresolvedMapper = *UMIt;
  13139. const Expr *VE = RE->IgnoreParenLValueCasts();
  13140. if (VE->isValueDependent() || VE->isTypeDependent() ||
  13141. VE->isInstantiationDependent() ||
  13142. VE->containsUnexpandedParameterPack()) {
  13143. // Try to find the associated user-defined mapper.
  13144. ExprResult ER = buildUserDefinedMapperRef(
  13145. SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
  13146. VE->getType().getCanonicalType(), UnresolvedMapper);
  13147. if (ER.isInvalid())
  13148. continue;
  13149. MVLI.UDMapperList.push_back(ER.get());
  13150. // We can only analyze this information once the missing information is
  13151. // resolved.
  13152. MVLI.ProcessedVarList.push_back(RE);
  13153. continue;
  13154. }
  13155. Expr *SimpleExpr = RE->IgnoreParenCasts();
  13156. if (!RE->IgnoreParenImpCasts()->isLValue()) {
  13157. SemaRef.Diag(ELoc,
  13158. diag::err_omp_expected_named_var_member_or_array_expression)
  13159. << RE->getSourceRange();
  13160. continue;
  13161. }
  13162. OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
  13163. ValueDecl *CurDeclaration = nullptr;
  13164. // Obtain the array or member expression bases if required. Also, fill the
  13165. // components array with all the components identified in the process.
  13166. const Expr *BE = checkMapClauseExpressionBase(
  13167. SemaRef, SimpleExpr, CurComponents, CKind, /*NoDiagnose=*/false);
  13168. if (!BE)
  13169. continue;
  13170. assert(!CurComponents.empty() &&
  13171. "Invalid mappable expression information.");
  13172. if (const auto *TE = dyn_cast<CXXThisExpr>(BE)) {
  13173. // Add store "this" pointer to class in DSAStackTy for future checking
  13174. DSAS->addMappedClassesQualTypes(TE->getType());
  13175. // Try to find the associated user-defined mapper.
  13176. ExprResult ER = buildUserDefinedMapperRef(
  13177. SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
  13178. VE->getType().getCanonicalType(), UnresolvedMapper);
  13179. if (ER.isInvalid())
  13180. continue;
  13181. MVLI.UDMapperList.push_back(ER.get());
  13182. // Skip restriction checking for variable or field declarations
  13183. MVLI.ProcessedVarList.push_back(RE);
  13184. MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
  13185. MVLI.VarComponents.back().append(CurComponents.begin(),
  13186. CurComponents.end());
  13187. MVLI.VarBaseDeclarations.push_back(nullptr);
  13188. continue;
  13189. }
  13190. // For the following checks, we rely on the base declaration which is
  13191. // expected to be associated with the last component. The declaration is
  13192. // expected to be a variable or a field (if 'this' is being mapped).
  13193. CurDeclaration = CurComponents.back().getAssociatedDeclaration();
  13194. assert(CurDeclaration && "Null decl on map clause.");
  13195. assert(
  13196. CurDeclaration->isCanonicalDecl() &&
  13197. "Expecting components to have associated only canonical declarations.");
  13198. auto *VD = dyn_cast<VarDecl>(CurDeclaration);
  13199. const auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
  13200. assert((VD || FD) && "Only variables or fields are expected here!");
  13201. (void)FD;
  13202. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
  13203. // threadprivate variables cannot appear in a map clause.
  13204. // OpenMP 4.5 [2.10.5, target update Construct]
  13205. // threadprivate variables cannot appear in a from clause.
  13206. if (VD && DSAS->isThreadPrivate(VD)) {
  13207. DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
  13208. SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
  13209. << getOpenMPClauseName(CKind);
  13210. reportOriginalDsa(SemaRef, DSAS, VD, DVar);
  13211. continue;
  13212. }
  13213. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
  13214. // A list item cannot appear in both a map clause and a data-sharing
  13215. // attribute clause on the same construct.
  13216. // Check conflicts with other map clause expressions. We check the conflicts
  13217. // with the current construct separately from the enclosing data
  13218. // environment, because the restrictions are different. We only have to
  13219. // check conflicts across regions for the map clauses.
  13220. if (checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
  13221. /*CurrentRegionOnly=*/true, CurComponents, CKind))
  13222. break;
  13223. if (CKind == OMPC_map &&
  13224. checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
  13225. /*CurrentRegionOnly=*/false, CurComponents, CKind))
  13226. break;
  13227. // OpenMP 4.5 [2.10.5, target update Construct]
  13228. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
  13229. // If the type of a list item is a reference to a type T then the type will
  13230. // be considered to be T for all purposes of this clause.
  13231. auto I = llvm::find_if(
  13232. CurComponents,
  13233. [](const OMPClauseMappableExprCommon::MappableComponent &MC) {
  13234. return MC.getAssociatedDeclaration();
  13235. });
  13236. assert(I != CurComponents.end() && "Null decl on map clause.");
  13237. QualType Type =
  13238. I->getAssociatedDeclaration()->getType().getNonReferenceType();
  13239. // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
  13240. // A list item in a to or from clause must have a mappable type.
  13241. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
  13242. // A list item must have a mappable type.
  13243. if (!checkTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
  13244. DSAS, Type))
  13245. continue;
  13246. if (CKind == OMPC_map) {
  13247. // target enter data
  13248. // OpenMP [2.10.2, Restrictions, p. 99]
  13249. // A map-type must be specified in all map clauses and must be either
  13250. // to or alloc.
  13251. OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
  13252. if (DKind == OMPD_target_enter_data &&
  13253. !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
  13254. SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
  13255. << (IsMapTypeImplicit ? 1 : 0)
  13256. << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
  13257. << getOpenMPDirectiveName(DKind);
  13258. continue;
  13259. }
  13260. // target exit_data
  13261. // OpenMP [2.10.3, Restrictions, p. 102]
  13262. // A map-type must be specified in all map clauses and must be either
  13263. // from, release, or delete.
  13264. if (DKind == OMPD_target_exit_data &&
  13265. !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
  13266. MapType == OMPC_MAP_delete)) {
  13267. SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
  13268. << (IsMapTypeImplicit ? 1 : 0)
  13269. << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
  13270. << getOpenMPDirectiveName(DKind);
  13271. continue;
  13272. }
  13273. // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
  13274. // A list item cannot appear in both a map clause and a data-sharing
  13275. // attribute clause on the same construct
  13276. if (VD && isOpenMPTargetExecutionDirective(DKind)) {
  13277. DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
  13278. if (isOpenMPPrivate(DVar.CKind)) {
  13279. SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
  13280. << getOpenMPClauseName(DVar.CKind)
  13281. << getOpenMPClauseName(OMPC_map)
  13282. << getOpenMPDirectiveName(DSAS->getCurrentDirective());
  13283. reportOriginalDsa(SemaRef, DSAS, CurDeclaration, DVar);
  13284. continue;
  13285. }
  13286. }
  13287. }
  13288. // Try to find the associated user-defined mapper.
  13289. ExprResult ER = buildUserDefinedMapperRef(
  13290. SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
  13291. Type.getCanonicalType(), UnresolvedMapper);
  13292. if (ER.isInvalid())
  13293. continue;
  13294. MVLI.UDMapperList.push_back(ER.get());
  13295. // Save the current expression.
  13296. MVLI.ProcessedVarList.push_back(RE);
  13297. // Store the components in the stack so that they can be used to check
  13298. // against other clauses later on.
  13299. DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
  13300. /*WhereFoundClauseKind=*/OMPC_map);
  13301. // Save the components and declaration to create the clause. For purposes of
  13302. // the clause creation, any component list that has has base 'this' uses
  13303. // null as base declaration.
  13304. MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
  13305. MVLI.VarComponents.back().append(CurComponents.begin(),
  13306. CurComponents.end());
  13307. MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
  13308. : CurDeclaration);
  13309. }
  13310. }
  13311. OMPClause *Sema::ActOnOpenMPMapClause(
  13312. ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
  13313. ArrayRef<SourceLocation> MapTypeModifiersLoc,
  13314. CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId,
  13315. OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, SourceLocation MapLoc,
  13316. SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
  13317. const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) {
  13318. OpenMPMapModifierKind Modifiers[] = {OMPC_MAP_MODIFIER_unknown,
  13319. OMPC_MAP_MODIFIER_unknown,
  13320. OMPC_MAP_MODIFIER_unknown};
  13321. SourceLocation ModifiersLoc[OMPMapClause::NumberOfModifiers];
  13322. // Process map-type-modifiers, flag errors for duplicate modifiers.
  13323. unsigned Count = 0;
  13324. for (unsigned I = 0, E = MapTypeModifiers.size(); I < E; ++I) {
  13325. if (MapTypeModifiers[I] != OMPC_MAP_MODIFIER_unknown &&
  13326. llvm::find(Modifiers, MapTypeModifiers[I]) != std::end(Modifiers)) {
  13327. Diag(MapTypeModifiersLoc[I], diag::err_omp_duplicate_map_type_modifier);
  13328. continue;
  13329. }
  13330. assert(Count < OMPMapClause::NumberOfModifiers &&
  13331. "Modifiers exceed the allowed number of map type modifiers");
  13332. Modifiers[Count] = MapTypeModifiers[I];
  13333. ModifiersLoc[Count] = MapTypeModifiersLoc[I];
  13334. ++Count;
  13335. }
  13336. MappableVarListInfo MVLI(VarList);
  13337. checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, Locs.StartLoc,
  13338. MapperIdScopeSpec, MapperId, UnresolvedMappers,
  13339. MapType, IsMapTypeImplicit);
  13340. // We need to produce a map clause even if we don't have variables so that
  13341. // other diagnostics related with non-existing map clauses are accurate.
  13342. return OMPMapClause::Create(Context, Locs, MVLI.ProcessedVarList,
  13343. MVLI.VarBaseDeclarations, MVLI.VarComponents,
  13344. MVLI.UDMapperList, Modifiers, ModifiersLoc,
  13345. MapperIdScopeSpec.getWithLocInContext(Context),
  13346. MapperId, MapType, IsMapTypeImplicit, MapLoc);
  13347. }
  13348. QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
  13349. TypeResult ParsedType) {
  13350. assert(ParsedType.isUsable());
  13351. QualType ReductionType = GetTypeFromParser(ParsedType.get());
  13352. if (ReductionType.isNull())
  13353. return QualType();
  13354. // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
  13355. // A type name in a declare reduction directive cannot be a function type, an
  13356. // array type, a reference type, or a type qualified with const, volatile or
  13357. // restrict.
  13358. if (ReductionType.hasQualifiers()) {
  13359. Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
  13360. return QualType();
  13361. }
  13362. if (ReductionType->isFunctionType()) {
  13363. Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
  13364. return QualType();
  13365. }
  13366. if (ReductionType->isReferenceType()) {
  13367. Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
  13368. return QualType();
  13369. }
  13370. if (ReductionType->isArrayType()) {
  13371. Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
  13372. return QualType();
  13373. }
  13374. return ReductionType;
  13375. }
  13376. Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
  13377. Scope *S, DeclContext *DC, DeclarationName Name,
  13378. ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
  13379. AccessSpecifier AS, Decl *PrevDeclInScope) {
  13380. SmallVector<Decl *, 8> Decls;
  13381. Decls.reserve(ReductionTypes.size());
  13382. LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
  13383. forRedeclarationInCurContext());
  13384. // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
  13385. // A reduction-identifier may not be re-declared in the current scope for the
  13386. // same type or for a type that is compatible according to the base language
  13387. // rules.
  13388. llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
  13389. OMPDeclareReductionDecl *PrevDRD = nullptr;
  13390. bool InCompoundScope = true;
  13391. if (S != nullptr) {
  13392. // Find previous declaration with the same name not referenced in other
  13393. // declarations.
  13394. FunctionScopeInfo *ParentFn = getEnclosingFunction();
  13395. InCompoundScope =
  13396. (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
  13397. LookupName(Lookup, S);
  13398. FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
  13399. /*AllowInlineNamespace=*/false);
  13400. llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
  13401. LookupResult::Filter Filter = Lookup.makeFilter();
  13402. while (Filter.hasNext()) {
  13403. auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
  13404. if (InCompoundScope) {
  13405. auto I = UsedAsPrevious.find(PrevDecl);
  13406. if (I == UsedAsPrevious.end())
  13407. UsedAsPrevious[PrevDecl] = false;
  13408. if (OMPDeclareReductionDecl *D = PrevDecl->getPrevDeclInScope())
  13409. UsedAsPrevious[D] = true;
  13410. }
  13411. PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
  13412. PrevDecl->getLocation();
  13413. }
  13414. Filter.done();
  13415. if (InCompoundScope) {
  13416. for (const auto &PrevData : UsedAsPrevious) {
  13417. if (!PrevData.second) {
  13418. PrevDRD = PrevData.first;
  13419. break;
  13420. }
  13421. }
  13422. }
  13423. } else if (PrevDeclInScope != nullptr) {
  13424. auto *PrevDRDInScope = PrevDRD =
  13425. cast<OMPDeclareReductionDecl>(PrevDeclInScope);
  13426. do {
  13427. PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
  13428. PrevDRDInScope->getLocation();
  13429. PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
  13430. } while (PrevDRDInScope != nullptr);
  13431. }
  13432. for (const auto &TyData : ReductionTypes) {
  13433. const auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
  13434. bool Invalid = false;
  13435. if (I != PreviousRedeclTypes.end()) {
  13436. Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
  13437. << TyData.first;
  13438. Diag(I->second, diag::note_previous_definition);
  13439. Invalid = true;
  13440. }
  13441. PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
  13442. auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
  13443. Name, TyData.first, PrevDRD);
  13444. DC->addDecl(DRD);
  13445. DRD->setAccess(AS);
  13446. Decls.push_back(DRD);
  13447. if (Invalid)
  13448. DRD->setInvalidDecl();
  13449. else
  13450. PrevDRD = DRD;
  13451. }
  13452. return DeclGroupPtrTy::make(
  13453. DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
  13454. }
  13455. void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
  13456. auto *DRD = cast<OMPDeclareReductionDecl>(D);
  13457. // Enter new function scope.
  13458. PushFunctionScope();
  13459. setFunctionHasBranchProtectedScope();
  13460. getCurFunction()->setHasOMPDeclareReductionCombiner();
  13461. if (S != nullptr)
  13462. PushDeclContext(S, DRD);
  13463. else
  13464. CurContext = DRD;
  13465. PushExpressionEvaluationContext(
  13466. ExpressionEvaluationContext::PotentiallyEvaluated);
  13467. QualType ReductionType = DRD->getType();
  13468. // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
  13469. // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
  13470. // uses semantics of argument handles by value, but it should be passed by
  13471. // reference. C lang does not support references, so pass all parameters as
  13472. // pointers.
  13473. // Create 'T omp_in;' variable.
  13474. VarDecl *OmpInParm =
  13475. buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
  13476. // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
  13477. // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
  13478. // uses semantics of argument handles by value, but it should be passed by
  13479. // reference. C lang does not support references, so pass all parameters as
  13480. // pointers.
  13481. // Create 'T omp_out;' variable.
  13482. VarDecl *OmpOutParm =
  13483. buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
  13484. if (S != nullptr) {
  13485. PushOnScopeChains(OmpInParm, S);
  13486. PushOnScopeChains(OmpOutParm, S);
  13487. } else {
  13488. DRD->addDecl(OmpInParm);
  13489. DRD->addDecl(OmpOutParm);
  13490. }
  13491. Expr *InE =
  13492. ::buildDeclRefExpr(*this, OmpInParm, ReductionType, D->getLocation());
  13493. Expr *OutE =
  13494. ::buildDeclRefExpr(*this, OmpOutParm, ReductionType, D->getLocation());
  13495. DRD->setCombinerData(InE, OutE);
  13496. }
  13497. void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
  13498. auto *DRD = cast<OMPDeclareReductionDecl>(D);
  13499. DiscardCleanupsInEvaluationContext();
  13500. PopExpressionEvaluationContext();
  13501. PopDeclContext();
  13502. PopFunctionScopeInfo();
  13503. if (Combiner != nullptr)
  13504. DRD->setCombiner(Combiner);
  13505. else
  13506. DRD->setInvalidDecl();
  13507. }
  13508. VarDecl *Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
  13509. auto *DRD = cast<OMPDeclareReductionDecl>(D);
  13510. // Enter new function scope.
  13511. PushFunctionScope();
  13512. setFunctionHasBranchProtectedScope();
  13513. if (S != nullptr)
  13514. PushDeclContext(S, DRD);
  13515. else
  13516. CurContext = DRD;
  13517. PushExpressionEvaluationContext(
  13518. ExpressionEvaluationContext::PotentiallyEvaluated);
  13519. QualType ReductionType = DRD->getType();
  13520. // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
  13521. // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
  13522. // uses semantics of argument handles by value, but it should be passed by
  13523. // reference. C lang does not support references, so pass all parameters as
  13524. // pointers.
  13525. // Create 'T omp_priv;' variable.
  13526. VarDecl *OmpPrivParm =
  13527. buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
  13528. // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
  13529. // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
  13530. // uses semantics of argument handles by value, but it should be passed by
  13531. // reference. C lang does not support references, so pass all parameters as
  13532. // pointers.
  13533. // Create 'T omp_orig;' variable.
  13534. VarDecl *OmpOrigParm =
  13535. buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
  13536. if (S != nullptr) {
  13537. PushOnScopeChains(OmpPrivParm, S);
  13538. PushOnScopeChains(OmpOrigParm, S);
  13539. } else {
  13540. DRD->addDecl(OmpPrivParm);
  13541. DRD->addDecl(OmpOrigParm);
  13542. }
  13543. Expr *OrigE =
  13544. ::buildDeclRefExpr(*this, OmpOrigParm, ReductionType, D->getLocation());
  13545. Expr *PrivE =
  13546. ::buildDeclRefExpr(*this, OmpPrivParm, ReductionType, D->getLocation());
  13547. DRD->setInitializerData(OrigE, PrivE);
  13548. return OmpPrivParm;
  13549. }
  13550. void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
  13551. VarDecl *OmpPrivParm) {
  13552. auto *DRD = cast<OMPDeclareReductionDecl>(D);
  13553. DiscardCleanupsInEvaluationContext();
  13554. PopExpressionEvaluationContext();
  13555. PopDeclContext();
  13556. PopFunctionScopeInfo();
  13557. if (Initializer != nullptr) {
  13558. DRD->setInitializer(Initializer, OMPDeclareReductionDecl::CallInit);
  13559. } else if (OmpPrivParm->hasInit()) {
  13560. DRD->setInitializer(OmpPrivParm->getInit(),
  13561. OmpPrivParm->isDirectInit()
  13562. ? OMPDeclareReductionDecl::DirectInit
  13563. : OMPDeclareReductionDecl::CopyInit);
  13564. } else {
  13565. DRD->setInvalidDecl();
  13566. }
  13567. }
  13568. Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
  13569. Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
  13570. for (Decl *D : DeclReductions.get()) {
  13571. if (IsValid) {
  13572. if (S)
  13573. PushOnScopeChains(cast<OMPDeclareReductionDecl>(D), S,
  13574. /*AddToContext=*/false);
  13575. } else {
  13576. D->setInvalidDecl();
  13577. }
  13578. }
  13579. return DeclReductions;
  13580. }
  13581. TypeResult Sema::ActOnOpenMPDeclareMapperVarDecl(Scope *S, Declarator &D) {
  13582. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  13583. QualType T = TInfo->getType();
  13584. if (D.isInvalidType())
  13585. return true;
  13586. if (getLangOpts().CPlusPlus) {
  13587. // Check that there are no default arguments (C++ only).
  13588. CheckExtraCXXDefaultArguments(D);
  13589. }
  13590. return CreateParsedType(T, TInfo);
  13591. }
  13592. QualType Sema::ActOnOpenMPDeclareMapperType(SourceLocation TyLoc,
  13593. TypeResult ParsedType) {
  13594. assert(ParsedType.isUsable() && "Expect usable parsed mapper type");
  13595. QualType MapperType = GetTypeFromParser(ParsedType.get());
  13596. assert(!MapperType.isNull() && "Expect valid mapper type");
  13597. // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
  13598. // The type must be of struct, union or class type in C and C++
  13599. if (!MapperType->isStructureOrClassType() && !MapperType->isUnionType()) {
  13600. Diag(TyLoc, diag::err_omp_mapper_wrong_type);
  13601. return QualType();
  13602. }
  13603. return MapperType;
  13604. }
  13605. OMPDeclareMapperDecl *Sema::ActOnOpenMPDeclareMapperDirectiveStart(
  13606. Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType,
  13607. SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS,
  13608. Decl *PrevDeclInScope) {
  13609. LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPMapperName,
  13610. forRedeclarationInCurContext());
  13611. // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
  13612. // A mapper-identifier may not be redeclared in the current scope for the
  13613. // same type or for a type that is compatible according to the base language
  13614. // rules.
  13615. llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
  13616. OMPDeclareMapperDecl *PrevDMD = nullptr;
  13617. bool InCompoundScope = true;
  13618. if (S != nullptr) {
  13619. // Find previous declaration with the same name not referenced in other
  13620. // declarations.
  13621. FunctionScopeInfo *ParentFn = getEnclosingFunction();
  13622. InCompoundScope =
  13623. (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
  13624. LookupName(Lookup, S);
  13625. FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
  13626. /*AllowInlineNamespace=*/false);
  13627. llvm::DenseMap<OMPDeclareMapperDecl *, bool> UsedAsPrevious;
  13628. LookupResult::Filter Filter = Lookup.makeFilter();
  13629. while (Filter.hasNext()) {
  13630. auto *PrevDecl = cast<OMPDeclareMapperDecl>(Filter.next());
  13631. if (InCompoundScope) {
  13632. auto I = UsedAsPrevious.find(PrevDecl);
  13633. if (I == UsedAsPrevious.end())
  13634. UsedAsPrevious[PrevDecl] = false;
  13635. if (OMPDeclareMapperDecl *D = PrevDecl->getPrevDeclInScope())
  13636. UsedAsPrevious[D] = true;
  13637. }
  13638. PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
  13639. PrevDecl->getLocation();
  13640. }
  13641. Filter.done();
  13642. if (InCompoundScope) {
  13643. for (const auto &PrevData : UsedAsPrevious) {
  13644. if (!PrevData.second) {
  13645. PrevDMD = PrevData.first;
  13646. break;
  13647. }
  13648. }
  13649. }
  13650. } else if (PrevDeclInScope) {
  13651. auto *PrevDMDInScope = PrevDMD =
  13652. cast<OMPDeclareMapperDecl>(PrevDeclInScope);
  13653. do {
  13654. PreviousRedeclTypes[PrevDMDInScope->getType().getCanonicalType()] =
  13655. PrevDMDInScope->getLocation();
  13656. PrevDMDInScope = PrevDMDInScope->getPrevDeclInScope();
  13657. } while (PrevDMDInScope != nullptr);
  13658. }
  13659. const auto I = PreviousRedeclTypes.find(MapperType.getCanonicalType());
  13660. bool Invalid = false;
  13661. if (I != PreviousRedeclTypes.end()) {
  13662. Diag(StartLoc, diag::err_omp_declare_mapper_redefinition)
  13663. << MapperType << Name;
  13664. Diag(I->second, diag::note_previous_definition);
  13665. Invalid = true;
  13666. }
  13667. auto *DMD = OMPDeclareMapperDecl::Create(Context, DC, StartLoc, Name,
  13668. MapperType, VN, PrevDMD);
  13669. DC->addDecl(DMD);
  13670. DMD->setAccess(AS);
  13671. if (Invalid)
  13672. DMD->setInvalidDecl();
  13673. // Enter new function scope.
  13674. PushFunctionScope();
  13675. setFunctionHasBranchProtectedScope();
  13676. CurContext = DMD;
  13677. return DMD;
  13678. }
  13679. void Sema::ActOnOpenMPDeclareMapperDirectiveVarDecl(OMPDeclareMapperDecl *DMD,
  13680. Scope *S,
  13681. QualType MapperType,
  13682. SourceLocation StartLoc,
  13683. DeclarationName VN) {
  13684. VarDecl *VD = buildVarDecl(*this, StartLoc, MapperType, VN.getAsString());
  13685. if (S)
  13686. PushOnScopeChains(VD, S);
  13687. else
  13688. DMD->addDecl(VD);
  13689. Expr *MapperVarRefExpr = buildDeclRefExpr(*this, VD, MapperType, StartLoc);
  13690. DMD->setMapperVarRef(MapperVarRefExpr);
  13691. }
  13692. Sema::DeclGroupPtrTy
  13693. Sema::ActOnOpenMPDeclareMapperDirectiveEnd(OMPDeclareMapperDecl *D, Scope *S,
  13694. ArrayRef<OMPClause *> ClauseList) {
  13695. PopDeclContext();
  13696. PopFunctionScopeInfo();
  13697. if (D) {
  13698. if (S)
  13699. PushOnScopeChains(D, S, /*AddToContext=*/false);
  13700. D->CreateClauses(Context, ClauseList);
  13701. }
  13702. return DeclGroupPtrTy::make(DeclGroupRef(D));
  13703. }
  13704. OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
  13705. SourceLocation StartLoc,
  13706. SourceLocation LParenLoc,
  13707. SourceLocation EndLoc) {
  13708. Expr *ValExpr = NumTeams;
  13709. Stmt *HelperValStmt = nullptr;
  13710. // OpenMP [teams Constrcut, Restrictions]
  13711. // The num_teams expression must evaluate to a positive integer value.
  13712. if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
  13713. /*StrictlyPositive=*/true))
  13714. return nullptr;
  13715. OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
  13716. OpenMPDirectiveKind CaptureRegion =
  13717. getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams);
  13718. if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
  13719. ValExpr = MakeFullExpr(ValExpr).get();
  13720. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  13721. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  13722. HelperValStmt = buildPreInits(Context, Captures);
  13723. }
  13724. return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion,
  13725. StartLoc, LParenLoc, EndLoc);
  13726. }
  13727. OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
  13728. SourceLocation StartLoc,
  13729. SourceLocation LParenLoc,
  13730. SourceLocation EndLoc) {
  13731. Expr *ValExpr = ThreadLimit;
  13732. Stmt *HelperValStmt = nullptr;
  13733. // OpenMP [teams Constrcut, Restrictions]
  13734. // The thread_limit expression must evaluate to a positive integer value.
  13735. if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
  13736. /*StrictlyPositive=*/true))
  13737. return nullptr;
  13738. OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
  13739. OpenMPDirectiveKind CaptureRegion =
  13740. getOpenMPCaptureRegionForClause(DKind, OMPC_thread_limit);
  13741. if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
  13742. ValExpr = MakeFullExpr(ValExpr).get();
  13743. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  13744. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  13745. HelperValStmt = buildPreInits(Context, Captures);
  13746. }
  13747. return new (Context) OMPThreadLimitClause(
  13748. ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
  13749. }
  13750. OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
  13751. SourceLocation StartLoc,
  13752. SourceLocation LParenLoc,
  13753. SourceLocation EndLoc) {
  13754. Expr *ValExpr = Priority;
  13755. // OpenMP [2.9.1, task Constrcut]
  13756. // The priority-value is a non-negative numerical scalar expression.
  13757. if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_priority,
  13758. /*StrictlyPositive=*/false))
  13759. return nullptr;
  13760. return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc);
  13761. }
  13762. OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
  13763. SourceLocation StartLoc,
  13764. SourceLocation LParenLoc,
  13765. SourceLocation EndLoc) {
  13766. Expr *ValExpr = Grainsize;
  13767. // OpenMP [2.9.2, taskloop Constrcut]
  13768. // The parameter of the grainsize clause must be a positive integer
  13769. // expression.
  13770. if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize,
  13771. /*StrictlyPositive=*/true))
  13772. return nullptr;
  13773. return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc);
  13774. }
  13775. OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
  13776. SourceLocation StartLoc,
  13777. SourceLocation LParenLoc,
  13778. SourceLocation EndLoc) {
  13779. Expr *ValExpr = NumTasks;
  13780. // OpenMP [2.9.2, taskloop Constrcut]
  13781. // The parameter of the num_tasks clause must be a positive integer
  13782. // expression.
  13783. if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks,
  13784. /*StrictlyPositive=*/true))
  13785. return nullptr;
  13786. return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc);
  13787. }
  13788. OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
  13789. SourceLocation LParenLoc,
  13790. SourceLocation EndLoc) {
  13791. // OpenMP [2.13.2, critical construct, Description]
  13792. // ... where hint-expression is an integer constant expression that evaluates
  13793. // to a valid lock hint.
  13794. ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
  13795. if (HintExpr.isInvalid())
  13796. return nullptr;
  13797. return new (Context)
  13798. OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
  13799. }
  13800. OMPClause *Sema::ActOnOpenMPDistScheduleClause(
  13801. OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
  13802. SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
  13803. SourceLocation EndLoc) {
  13804. if (Kind == OMPC_DIST_SCHEDULE_unknown) {
  13805. std::string Values;
  13806. Values += "'";
  13807. Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
  13808. Values += "'";
  13809. Diag(KindLoc, diag::err_omp_unexpected_clause_value)
  13810. << Values << getOpenMPClauseName(OMPC_dist_schedule);
  13811. return nullptr;
  13812. }
  13813. Expr *ValExpr = ChunkSize;
  13814. Stmt *HelperValStmt = nullptr;
  13815. if (ChunkSize) {
  13816. if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
  13817. !ChunkSize->isInstantiationDependent() &&
  13818. !ChunkSize->containsUnexpandedParameterPack()) {
  13819. SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
  13820. ExprResult Val =
  13821. PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
  13822. if (Val.isInvalid())
  13823. return nullptr;
  13824. ValExpr = Val.get();
  13825. // OpenMP [2.7.1, Restrictions]
  13826. // chunk_size must be a loop invariant integer expression with a positive
  13827. // value.
  13828. llvm::APSInt Result;
  13829. if (ValExpr->isIntegerConstantExpr(Result, Context)) {
  13830. if (Result.isSigned() && !Result.isStrictlyPositive()) {
  13831. Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
  13832. << "dist_schedule" << ChunkSize->getSourceRange();
  13833. return nullptr;
  13834. }
  13835. } else if (getOpenMPCaptureRegionForClause(
  13836. DSAStack->getCurrentDirective(), OMPC_dist_schedule) !=
  13837. OMPD_unknown &&
  13838. !CurContext->isDependentContext()) {
  13839. ValExpr = MakeFullExpr(ValExpr).get();
  13840. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  13841. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  13842. HelperValStmt = buildPreInits(Context, Captures);
  13843. }
  13844. }
  13845. }
  13846. return new (Context)
  13847. OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
  13848. Kind, ValExpr, HelperValStmt);
  13849. }
  13850. OMPClause *Sema::ActOnOpenMPDefaultmapClause(
  13851. OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
  13852. SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
  13853. SourceLocation KindLoc, SourceLocation EndLoc) {
  13854. // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)'
  13855. if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || Kind != OMPC_DEFAULTMAP_scalar) {
  13856. std::string Value;
  13857. SourceLocation Loc;
  13858. Value += "'";
  13859. if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
  13860. Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
  13861. OMPC_DEFAULTMAP_MODIFIER_tofrom);
  13862. Loc = MLoc;
  13863. } else {
  13864. Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
  13865. OMPC_DEFAULTMAP_scalar);
  13866. Loc = KindLoc;
  13867. }
  13868. Value += "'";
  13869. Diag(Loc, diag::err_omp_unexpected_clause_value)
  13870. << Value << getOpenMPClauseName(OMPC_defaultmap);
  13871. return nullptr;
  13872. }
  13873. DSAStack->setDefaultDMAToFromScalar(StartLoc);
  13874. return new (Context)
  13875. OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
  13876. }
  13877. bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) {
  13878. DeclContext *CurLexicalContext = getCurLexicalContext();
  13879. if (!CurLexicalContext->isFileContext() &&
  13880. !CurLexicalContext->isExternCContext() &&
  13881. !CurLexicalContext->isExternCXXContext() &&
  13882. !isa<CXXRecordDecl>(CurLexicalContext) &&
  13883. !isa<ClassTemplateDecl>(CurLexicalContext) &&
  13884. !isa<ClassTemplatePartialSpecializationDecl>(CurLexicalContext) &&
  13885. !isa<ClassTemplateSpecializationDecl>(CurLexicalContext)) {
  13886. Diag(Loc, diag::err_omp_region_not_file_context);
  13887. return false;
  13888. }
  13889. ++DeclareTargetNestingLevel;
  13890. return true;
  13891. }
  13892. void Sema::ActOnFinishOpenMPDeclareTargetDirective() {
  13893. assert(DeclareTargetNestingLevel > 0 &&
  13894. "Unexpected ActOnFinishOpenMPDeclareTargetDirective");
  13895. --DeclareTargetNestingLevel;
  13896. }
  13897. void Sema::ActOnOpenMPDeclareTargetName(Scope *CurScope,
  13898. CXXScopeSpec &ScopeSpec,
  13899. const DeclarationNameInfo &Id,
  13900. OMPDeclareTargetDeclAttr::MapTypeTy MT,
  13901. NamedDeclSetType &SameDirectiveDecls) {
  13902. LookupResult Lookup(*this, Id, LookupOrdinaryName);
  13903. LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
  13904. if (Lookup.isAmbiguous())
  13905. return;
  13906. Lookup.suppressDiagnostics();
  13907. if (!Lookup.isSingleResult()) {
  13908. VarOrFuncDeclFilterCCC CCC(*this);
  13909. if (TypoCorrection Corrected =
  13910. CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, CCC,
  13911. CTK_ErrorRecovery)) {
  13912. diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
  13913. << Id.getName());
  13914. checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
  13915. return;
  13916. }
  13917. Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
  13918. return;
  13919. }
  13920. NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
  13921. if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND) ||
  13922. isa<FunctionTemplateDecl>(ND)) {
  13923. if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl())))
  13924. Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName();
  13925. llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
  13926. OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(
  13927. cast<ValueDecl>(ND));
  13928. if (!Res) {
  13929. auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT);
  13930. ND->addAttr(A);
  13931. if (ASTMutationListener *ML = Context.getASTMutationListener())
  13932. ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
  13933. checkDeclIsAllowedInOpenMPTarget(nullptr, ND, Id.getLoc());
  13934. } else if (*Res != MT) {
  13935. Diag(Id.getLoc(), diag::err_omp_declare_target_to_and_link)
  13936. << Id.getName();
  13937. }
  13938. } else {
  13939. Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
  13940. }
  13941. }
  13942. static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
  13943. Sema &SemaRef, Decl *D) {
  13944. if (!D || !isa<VarDecl>(D))
  13945. return;
  13946. auto *VD = cast<VarDecl>(D);
  13947. if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
  13948. return;
  13949. SemaRef.Diag(VD->getLocation(), diag::warn_omp_not_in_target_context);
  13950. SemaRef.Diag(SL, diag::note_used_here) << SR;
  13951. }
  13952. static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
  13953. Sema &SemaRef, DSAStackTy *Stack,
  13954. ValueDecl *VD) {
  13955. return VD->hasAttr<OMPDeclareTargetDeclAttr>() ||
  13956. checkTypeMappable(SL, SR, SemaRef, Stack, VD->getType(),
  13957. /*FullCheck=*/false);
  13958. }
  13959. void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D,
  13960. SourceLocation IdLoc) {
  13961. if (!D || D->isInvalidDecl())
  13962. return;
  13963. SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
  13964. SourceLocation SL = E ? E->getBeginLoc() : D->getLocation();
  13965. if (auto *VD = dyn_cast<VarDecl>(D)) {
  13966. // Only global variables can be marked as declare target.
  13967. if (!VD->isFileVarDecl() && !VD->isStaticLocal() &&
  13968. !VD->isStaticDataMember())
  13969. return;
  13970. // 2.10.6: threadprivate variable cannot appear in a declare target
  13971. // directive.
  13972. if (DSAStack->isThreadPrivate(VD)) {
  13973. Diag(SL, diag::err_omp_threadprivate_in_target);
  13974. reportOriginalDsa(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
  13975. return;
  13976. }
  13977. }
  13978. if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(D))
  13979. D = FTD->getTemplatedDecl();
  13980. if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
  13981. llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
  13982. OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(FD);
  13983. if (Res && *Res == OMPDeclareTargetDeclAttr::MT_Link) {
  13984. assert(IdLoc.isValid() && "Source location is expected");
  13985. Diag(IdLoc, diag::err_omp_function_in_link_clause);
  13986. Diag(FD->getLocation(), diag::note_defined_here) << FD;
  13987. return;
  13988. }
  13989. }
  13990. if (auto *VD = dyn_cast<ValueDecl>(D)) {
  13991. // Problem if any with var declared with incomplete type will be reported
  13992. // as normal, so no need to check it here.
  13993. if ((E || !VD->getType()->isIncompleteType()) &&
  13994. !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD))
  13995. return;
  13996. if (!E && !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
  13997. // Checking declaration inside declare target region.
  13998. if (isa<VarDecl>(D) || isa<FunctionDecl>(D) ||
  13999. isa<FunctionTemplateDecl>(D)) {
  14000. auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(
  14001. Context, OMPDeclareTargetDeclAttr::MT_To);
  14002. D->addAttr(A);
  14003. if (ASTMutationListener *ML = Context.getASTMutationListener())
  14004. ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
  14005. }
  14006. return;
  14007. }
  14008. }
  14009. if (!E)
  14010. return;
  14011. checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
  14012. }
  14013. OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
  14014. CXXScopeSpec &MapperIdScopeSpec,
  14015. DeclarationNameInfo &MapperId,
  14016. const OMPVarListLocTy &Locs,
  14017. ArrayRef<Expr *> UnresolvedMappers) {
  14018. MappableVarListInfo MVLI(VarList);
  14019. checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, Locs.StartLoc,
  14020. MapperIdScopeSpec, MapperId, UnresolvedMappers);
  14021. if (MVLI.ProcessedVarList.empty())
  14022. return nullptr;
  14023. return OMPToClause::Create(
  14024. Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
  14025. MVLI.VarComponents, MVLI.UDMapperList,
  14026. MapperIdScopeSpec.getWithLocInContext(Context), MapperId);
  14027. }
  14028. OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
  14029. CXXScopeSpec &MapperIdScopeSpec,
  14030. DeclarationNameInfo &MapperId,
  14031. const OMPVarListLocTy &Locs,
  14032. ArrayRef<Expr *> UnresolvedMappers) {
  14033. MappableVarListInfo MVLI(VarList);
  14034. checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, Locs.StartLoc,
  14035. MapperIdScopeSpec, MapperId, UnresolvedMappers);
  14036. if (MVLI.ProcessedVarList.empty())
  14037. return nullptr;
  14038. return OMPFromClause::Create(
  14039. Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
  14040. MVLI.VarComponents, MVLI.UDMapperList,
  14041. MapperIdScopeSpec.getWithLocInContext(Context), MapperId);
  14042. }
  14043. OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
  14044. const OMPVarListLocTy &Locs) {
  14045. MappableVarListInfo MVLI(VarList);
  14046. SmallVector<Expr *, 8> PrivateCopies;
  14047. SmallVector<Expr *, 8> Inits;
  14048. for (Expr *RefExpr : VarList) {
  14049. assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
  14050. SourceLocation ELoc;
  14051. SourceRange ERange;
  14052. Expr *SimpleRefExpr = RefExpr;
  14053. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  14054. if (Res.second) {
  14055. // It will be analyzed later.
  14056. MVLI.ProcessedVarList.push_back(RefExpr);
  14057. PrivateCopies.push_back(nullptr);
  14058. Inits.push_back(nullptr);
  14059. }
  14060. ValueDecl *D = Res.first;
  14061. if (!D)
  14062. continue;
  14063. QualType Type = D->getType();
  14064. Type = Type.getNonReferenceType().getUnqualifiedType();
  14065. auto *VD = dyn_cast<VarDecl>(D);
  14066. // Item should be a pointer or reference to pointer.
  14067. if (!Type->isPointerType()) {
  14068. Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
  14069. << 0 << RefExpr->getSourceRange();
  14070. continue;
  14071. }
  14072. // Build the private variable and the expression that refers to it.
  14073. auto VDPrivate =
  14074. buildVarDecl(*this, ELoc, Type, D->getName(),
  14075. D->hasAttrs() ? &D->getAttrs() : nullptr,
  14076. VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
  14077. if (VDPrivate->isInvalidDecl())
  14078. continue;
  14079. CurContext->addDecl(VDPrivate);
  14080. DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
  14081. *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
  14082. // Add temporary variable to initialize the private copy of the pointer.
  14083. VarDecl *VDInit =
  14084. buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
  14085. DeclRefExpr *VDInitRefExpr = buildDeclRefExpr(
  14086. *this, VDInit, RefExpr->getType(), RefExpr->getExprLoc());
  14087. AddInitializerToDecl(VDPrivate,
  14088. DefaultLvalueConversion(VDInitRefExpr).get(),
  14089. /*DirectInit=*/false);
  14090. // If required, build a capture to implement the privatization initialized
  14091. // with the current list item value.
  14092. DeclRefExpr *Ref = nullptr;
  14093. if (!VD)
  14094. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
  14095. MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
  14096. PrivateCopies.push_back(VDPrivateRefExpr);
  14097. Inits.push_back(VDInitRefExpr);
  14098. // We need to add a data sharing attribute for this variable to make sure it
  14099. // is correctly captured. A variable that shows up in a use_device_ptr has
  14100. // similar properties of a first private variable.
  14101. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
  14102. // Create a mappable component for the list item. List items in this clause
  14103. // only need a component.
  14104. MVLI.VarBaseDeclarations.push_back(D);
  14105. MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
  14106. MVLI.VarComponents.back().push_back(
  14107. OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D));
  14108. }
  14109. if (MVLI.ProcessedVarList.empty())
  14110. return nullptr;
  14111. return OMPUseDevicePtrClause::Create(
  14112. Context, Locs, MVLI.ProcessedVarList, PrivateCopies, Inits,
  14113. MVLI.VarBaseDeclarations, MVLI.VarComponents);
  14114. }
  14115. OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
  14116. const OMPVarListLocTy &Locs) {
  14117. MappableVarListInfo MVLI(VarList);
  14118. for (Expr *RefExpr : VarList) {
  14119. assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
  14120. SourceLocation ELoc;
  14121. SourceRange ERange;
  14122. Expr *SimpleRefExpr = RefExpr;
  14123. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  14124. if (Res.second) {
  14125. // It will be analyzed later.
  14126. MVLI.ProcessedVarList.push_back(RefExpr);
  14127. }
  14128. ValueDecl *D = Res.first;
  14129. if (!D)
  14130. continue;
  14131. QualType Type = D->getType();
  14132. // item should be a pointer or array or reference to pointer or array
  14133. if (!Type.getNonReferenceType()->isPointerType() &&
  14134. !Type.getNonReferenceType()->isArrayType()) {
  14135. Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
  14136. << 0 << RefExpr->getSourceRange();
  14137. continue;
  14138. }
  14139. // Check if the declaration in the clause does not show up in any data
  14140. // sharing attribute.
  14141. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
  14142. if (isOpenMPPrivate(DVar.CKind)) {
  14143. Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
  14144. << getOpenMPClauseName(DVar.CKind)
  14145. << getOpenMPClauseName(OMPC_is_device_ptr)
  14146. << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
  14147. reportOriginalDsa(*this, DSAStack, D, DVar);
  14148. continue;
  14149. }
  14150. const Expr *ConflictExpr;
  14151. if (DSAStack->checkMappableExprComponentListsForDecl(
  14152. D, /*CurrentRegionOnly=*/true,
  14153. [&ConflictExpr](
  14154. OMPClauseMappableExprCommon::MappableExprComponentListRef R,
  14155. OpenMPClauseKind) -> bool {
  14156. ConflictExpr = R.front().getAssociatedExpression();
  14157. return true;
  14158. })) {
  14159. Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
  14160. Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
  14161. << ConflictExpr->getSourceRange();
  14162. continue;
  14163. }
  14164. // Store the components in the stack so that they can be used to check
  14165. // against other clauses later on.
  14166. OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D);
  14167. DSAStack->addMappableExpressionComponents(
  14168. D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
  14169. // Record the expression we've just processed.
  14170. MVLI.ProcessedVarList.push_back(SimpleRefExpr);
  14171. // Create a mappable component for the list item. List items in this clause
  14172. // only need a component. We use a null declaration to signal fields in
  14173. // 'this'.
  14174. assert((isa<DeclRefExpr>(SimpleRefExpr) ||
  14175. isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
  14176. "Unexpected device pointer expression!");
  14177. MVLI.VarBaseDeclarations.push_back(
  14178. isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
  14179. MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
  14180. MVLI.VarComponents.back().push_back(MC);
  14181. }
  14182. if (MVLI.ProcessedVarList.empty())
  14183. return nullptr;
  14184. return OMPIsDevicePtrClause::Create(Context, Locs, MVLI.ProcessedVarList,
  14185. MVLI.VarBaseDeclarations,
  14186. MVLI.VarComponents);
  14187. }
  14188. OMPClause *Sema::ActOnOpenMPAllocateClause(
  14189. Expr *Allocator, ArrayRef<Expr *> VarList, SourceLocation StartLoc,
  14190. SourceLocation ColonLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
  14191. if (Allocator) {
  14192. // OpenMP [2.11.4 allocate Clause, Description]
  14193. // allocator is an expression of omp_allocator_handle_t type.
  14194. if (!findOMPAllocatorHandleT(*this, Allocator->getExprLoc(), DSAStack))
  14195. return nullptr;
  14196. ExprResult AllocatorRes = DefaultLvalueConversion(Allocator);
  14197. if (AllocatorRes.isInvalid())
  14198. return nullptr;
  14199. AllocatorRes = PerformImplicitConversion(AllocatorRes.get(),
  14200. DSAStack->getOMPAllocatorHandleT(),
  14201. Sema::AA_Initializing,
  14202. /*AllowExplicit=*/true);
  14203. if (AllocatorRes.isInvalid())
  14204. return nullptr;
  14205. Allocator = AllocatorRes.get();
  14206. } else {
  14207. // OpenMP 5.0, 2.11.4 allocate Clause, Restrictions.
  14208. // allocate clauses that appear on a target construct or on constructs in a
  14209. // target region must specify an allocator expression unless a requires
  14210. // directive with the dynamic_allocators clause is present in the same
  14211. // compilation unit.
  14212. if (LangOpts.OpenMPIsDevice &&
  14213. !DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())
  14214. targetDiag(StartLoc, diag::err_expected_allocator_expression);
  14215. }
  14216. // Analyze and build list of variables.
  14217. SmallVector<Expr *, 8> Vars;
  14218. for (Expr *RefExpr : VarList) {
  14219. assert(RefExpr && "NULL expr in OpenMP private clause.");
  14220. SourceLocation ELoc;
  14221. SourceRange ERange;
  14222. Expr *SimpleRefExpr = RefExpr;
  14223. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  14224. if (Res.second) {
  14225. // It will be analyzed later.
  14226. Vars.push_back(RefExpr);
  14227. }
  14228. ValueDecl *D = Res.first;
  14229. if (!D)
  14230. continue;
  14231. auto *VD = dyn_cast<VarDecl>(D);
  14232. DeclRefExpr *Ref = nullptr;
  14233. if (!VD && !CurContext->isDependentContext())
  14234. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
  14235. Vars.push_back((VD || CurContext->isDependentContext())
  14236. ? RefExpr->IgnoreParens()
  14237. : Ref);
  14238. }
  14239. if (Vars.empty())
  14240. return nullptr;
  14241. return OMPAllocateClause::Create(Context, StartLoc, LParenLoc, Allocator,
  14242. ColonLoc, EndLoc, Vars);
  14243. }