SemaOpenMP.cpp 527 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264
  1. //===--- SemaOpenMP.cpp - Semantic Analysis for OpenMP constructs ---------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. /// \file
  10. /// \brief This file implements semantic analysis for OpenMP directives and
  11. /// clauses.
  12. ///
  13. //===----------------------------------------------------------------------===//
  14. #include "TreeTransform.h"
  15. #include "clang/AST/ASTContext.h"
  16. #include "clang/AST/ASTMutationListener.h"
  17. #include "clang/AST/CXXInheritance.h"
  18. #include "clang/AST/Decl.h"
  19. #include "clang/AST/DeclCXX.h"
  20. #include "clang/AST/DeclOpenMP.h"
  21. #include "clang/AST/StmtCXX.h"
  22. #include "clang/AST/StmtOpenMP.h"
  23. #include "clang/AST/StmtVisitor.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. /// \brief Default data sharing attributes, which can be applied to directive.
  41. enum DefaultDataSharingAttributes {
  42. DSA_unspecified = 0, /// \brief Data sharing attribute not specified.
  43. DSA_none = 1 << 0, /// \brief Default data sharing attribute 'none'.
  44. DSA_shared = 1 << 1, /// \brief 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. /// \brief 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. private:
  71. struct DSAInfo {
  72. OpenMPClauseKind Attributes = OMPC_unknown;
  73. /// Pointer to a reference expression and a flag which shows that the
  74. /// variable is marked as lastprivate(true) or not (false).
  75. llvm::PointerIntPair<const Expr *, 1, bool> RefExpr;
  76. DeclRefExpr *PrivateCopy = nullptr;
  77. };
  78. using DeclSAMapTy = llvm::SmallDenseMap<const ValueDecl *, DSAInfo, 8>;
  79. using AlignedMapTy = llvm::SmallDenseMap<const ValueDecl *, const Expr *, 8>;
  80. using LCDeclInfo = std::pair<unsigned, VarDecl *>;
  81. using LoopControlVariablesMapTy =
  82. llvm::SmallDenseMap<const ValueDecl *, LCDeclInfo, 8>;
  83. /// Struct that associates a component with the clause kind where they are
  84. /// found.
  85. struct MappedExprComponentTy {
  86. OMPClauseMappableExprCommon::MappableExprComponentLists Components;
  87. OpenMPClauseKind Kind = OMPC_unknown;
  88. };
  89. using MappedExprComponentsTy =
  90. llvm::DenseMap<const ValueDecl *, MappedExprComponentTy>;
  91. using CriticalsWithHintsTy =
  92. llvm::StringMap<std::pair<const OMPCriticalDirective *, llvm::APSInt>>;
  93. using DoacrossDependMapTy =
  94. llvm::DenseMap<OMPDependClause *, OperatorOffsetTy>;
  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. /// \brief 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::PointerIntPair<const Expr *, 1, bool> OrderedRegion;
  133. bool NowaitRegion = false;
  134. bool CancelRegion = false;
  135. unsigned AssociatedLoops = 1;
  136. SourceLocation InnerTeamsRegionLoc;
  137. /// Reference to the taskgroup task_reduction reference expression.
  138. Expr *TaskgroupReductionRef = nullptr;
  139. SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name,
  140. Scope *CurScope, SourceLocation Loc)
  141. : Directive(DKind), DirectiveName(Name), CurScope(CurScope),
  142. ConstructLoc(Loc) {}
  143. SharingMapTy() = default;
  144. };
  145. using StackTy = SmallVector<SharingMapTy, 4>;
  146. /// \brief Stack of used declaration and their data-sharing attributes.
  147. DeclSAMapTy Threadprivates;
  148. const FunctionScopeInfo *CurrentNonCapturingFunctionScope = nullptr;
  149. SmallVector<std::pair<StackTy, const FunctionScopeInfo *>, 4> Stack;
  150. /// \brief true, if check for DSA must be from parent directive, false, if
  151. /// from current directive.
  152. OpenMPClauseKind ClauseKindMode = OMPC_unknown;
  153. Sema &SemaRef;
  154. bool ForceCapturing = false;
  155. CriticalsWithHintsTy Criticals;
  156. using iterator = StackTy::const_reverse_iterator;
  157. DSAVarData getDSA(iterator &Iter, ValueDecl *D) const;
  158. /// \brief Checks if the variable is a local for OpenMP region.
  159. bool isOpenMPLocal(VarDecl *D, iterator Iter) const;
  160. bool isStackEmpty() const {
  161. return Stack.empty() ||
  162. Stack.back().second != CurrentNonCapturingFunctionScope ||
  163. Stack.back().first.empty();
  164. }
  165. public:
  166. explicit DSAStackTy(Sema &S) : SemaRef(S) {}
  167. bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; }
  168. OpenMPClauseKind getClauseParsingMode() const {
  169. assert(isClauseParsingMode() && "Must be in clause parsing mode.");
  170. return ClauseKindMode;
  171. }
  172. void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; }
  173. bool isForceVarCapturing() const { return ForceCapturing; }
  174. void setForceVarCapturing(bool V) { ForceCapturing = V; }
  175. void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
  176. Scope *CurScope, SourceLocation Loc) {
  177. if (Stack.empty() ||
  178. Stack.back().second != CurrentNonCapturingFunctionScope)
  179. Stack.emplace_back(StackTy(), CurrentNonCapturingFunctionScope);
  180. Stack.back().first.emplace_back(DKind, DirName, CurScope, Loc);
  181. Stack.back().first.back().DefaultAttrLoc = Loc;
  182. }
  183. void pop() {
  184. assert(!Stack.back().first.empty() &&
  185. "Data-sharing attributes stack is empty!");
  186. Stack.back().first.pop_back();
  187. }
  188. /// Start new OpenMP region stack in new non-capturing function.
  189. void pushFunction() {
  190. const FunctionScopeInfo *CurFnScope = SemaRef.getCurFunction();
  191. assert(!isa<CapturingScopeInfo>(CurFnScope));
  192. CurrentNonCapturingFunctionScope = CurFnScope;
  193. }
  194. /// Pop region stack for non-capturing function.
  195. void popFunction(const FunctionScopeInfo *OldFSI) {
  196. if (!Stack.empty() && Stack.back().second == OldFSI) {
  197. assert(Stack.back().first.empty());
  198. Stack.pop_back();
  199. }
  200. CurrentNonCapturingFunctionScope = nullptr;
  201. for (const FunctionScopeInfo *FSI : llvm::reverse(SemaRef.FunctionScopes)) {
  202. if (!isa<CapturingScopeInfo>(FSI)) {
  203. CurrentNonCapturingFunctionScope = FSI;
  204. break;
  205. }
  206. }
  207. }
  208. void addCriticalWithHint(const OMPCriticalDirective *D, llvm::APSInt Hint) {
  209. Criticals.try_emplace(D->getDirectiveName().getAsString(), D, Hint);
  210. }
  211. const std::pair<const OMPCriticalDirective *, llvm::APSInt>
  212. getCriticalWithHint(const DeclarationNameInfo &Name) const {
  213. auto I = Criticals.find(Name.getAsString());
  214. if (I != Criticals.end())
  215. return I->second;
  216. return std::make_pair(nullptr, llvm::APSInt());
  217. }
  218. /// \brief If 'aligned' declaration for given variable \a D was not seen yet,
  219. /// add it and return NULL; otherwise return previous occurrence's expression
  220. /// for diagnostics.
  221. const Expr *addUniqueAligned(const ValueDecl *D, const Expr *NewDE);
  222. /// \brief Register specified variable as loop control variable.
  223. void addLoopControlVariable(const ValueDecl *D, VarDecl *Capture);
  224. /// \brief Check if the specified variable is a loop control variable for
  225. /// current region.
  226. /// \return The index of the loop control variable in the list of associated
  227. /// for-loops (from outer to inner).
  228. const LCDeclInfo isLoopControlVariable(const ValueDecl *D) const;
  229. /// \brief Check if the specified variable is a loop control variable for
  230. /// parent region.
  231. /// \return The index of the loop control variable in the list of associated
  232. /// for-loops (from outer to inner).
  233. const LCDeclInfo isParentLoopControlVariable(const ValueDecl *D) const;
  234. /// \brief Get the loop control variable for the I-th loop (or nullptr) in
  235. /// parent directive.
  236. const ValueDecl *getParentLoopControlVariable(unsigned I) const;
  237. /// \brief Adds explicit data sharing attribute to the specified declaration.
  238. void addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A,
  239. DeclRefExpr *PrivateCopy = nullptr);
  240. /// Adds additional information for the reduction items with the reduction id
  241. /// represented as an operator.
  242. void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
  243. BinaryOperatorKind BOK);
  244. /// Adds additional information for the reduction items with the reduction id
  245. /// represented as reduction identifier.
  246. void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
  247. const Expr *ReductionRef);
  248. /// Returns the location and reduction operation from the innermost parent
  249. /// region for the given \p D.
  250. const DSAVarData
  251. getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR,
  252. BinaryOperatorKind &BOK,
  253. Expr *&TaskgroupDescriptor) const;
  254. /// Returns the location and reduction operation from the innermost parent
  255. /// region for the given \p D.
  256. const DSAVarData
  257. getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR,
  258. const Expr *&ReductionRef,
  259. Expr *&TaskgroupDescriptor) const;
  260. /// Return reduction reference expression for the current taskgroup.
  261. Expr *getTaskgroupReductionRef() const {
  262. assert(Stack.back().first.back().Directive == OMPD_taskgroup &&
  263. "taskgroup reference expression requested for non taskgroup "
  264. "directive.");
  265. return Stack.back().first.back().TaskgroupReductionRef;
  266. }
  267. /// Checks if the given \p VD declaration is actually a taskgroup reduction
  268. /// descriptor variable at the \p Level of OpenMP regions.
  269. bool isTaskgroupReductionRef(const ValueDecl *VD, unsigned Level) const {
  270. return Stack.back().first[Level].TaskgroupReductionRef &&
  271. cast<DeclRefExpr>(Stack.back().first[Level].TaskgroupReductionRef)
  272. ->getDecl() == VD;
  273. }
  274. /// \brief Returns data sharing attributes from top of the stack for the
  275. /// specified declaration.
  276. const DSAVarData getTopDSA(ValueDecl *D, bool FromParent);
  277. /// \brief Returns data-sharing attributes for the specified declaration.
  278. const DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent) const;
  279. /// \brief Checks if the specified variables has data-sharing attributes which
  280. /// match specified \a CPred predicate in any directive which matches \a DPred
  281. /// predicate.
  282. const DSAVarData
  283. hasDSA(ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
  284. const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
  285. bool FromParent) const;
  286. /// \brief Checks if the specified variables has data-sharing attributes which
  287. /// match specified \a CPred predicate in any innermost directive which
  288. /// matches \a DPred predicate.
  289. const DSAVarData
  290. hasInnermostDSA(ValueDecl *D,
  291. const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
  292. const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
  293. bool FromParent) const;
  294. /// \brief Checks if the specified variables has explicit data-sharing
  295. /// attributes which match specified \a CPred predicate at the specified
  296. /// OpenMP region.
  297. bool hasExplicitDSA(const ValueDecl *D,
  298. const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
  299. unsigned Level, bool NotLastprivate = false) const;
  300. /// \brief Returns true if the directive at level \Level matches in the
  301. /// specified \a DPred predicate.
  302. bool hasExplicitDirective(
  303. const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
  304. unsigned Level) const;
  305. /// \brief Finds a directive which matches specified \a DPred predicate.
  306. bool hasDirective(
  307. const llvm::function_ref<bool(
  308. OpenMPDirectiveKind, const DeclarationNameInfo &, SourceLocation)>
  309. DPred,
  310. bool FromParent) const;
  311. /// \brief Returns currently analyzed directive.
  312. OpenMPDirectiveKind getCurrentDirective() const {
  313. return isStackEmpty() ? OMPD_unknown : Stack.back().first.back().Directive;
  314. }
  315. /// \brief Returns directive kind at specified level.
  316. OpenMPDirectiveKind getDirective(unsigned Level) const {
  317. assert(!isStackEmpty() && "No directive at specified level.");
  318. return Stack.back().first[Level].Directive;
  319. }
  320. /// \brief Returns parent directive.
  321. OpenMPDirectiveKind getParentDirective() const {
  322. if (isStackEmpty() || Stack.back().first.size() == 1)
  323. return OMPD_unknown;
  324. return std::next(Stack.back().first.rbegin())->Directive;
  325. }
  326. /// \brief Set default data sharing attribute to none.
  327. void setDefaultDSANone(SourceLocation Loc) {
  328. assert(!isStackEmpty());
  329. Stack.back().first.back().DefaultAttr = DSA_none;
  330. Stack.back().first.back().DefaultAttrLoc = Loc;
  331. }
  332. /// \brief Set default data sharing attribute to shared.
  333. void setDefaultDSAShared(SourceLocation Loc) {
  334. assert(!isStackEmpty());
  335. Stack.back().first.back().DefaultAttr = DSA_shared;
  336. Stack.back().first.back().DefaultAttrLoc = Loc;
  337. }
  338. /// Set default data mapping attribute to 'tofrom:scalar'.
  339. void setDefaultDMAToFromScalar(SourceLocation Loc) {
  340. assert(!isStackEmpty());
  341. Stack.back().first.back().DefaultMapAttr = DMA_tofrom_scalar;
  342. Stack.back().first.back().DefaultMapAttrLoc = Loc;
  343. }
  344. DefaultDataSharingAttributes getDefaultDSA() const {
  345. return isStackEmpty() ? DSA_unspecified
  346. : Stack.back().first.back().DefaultAttr;
  347. }
  348. SourceLocation getDefaultDSALocation() const {
  349. return isStackEmpty() ? SourceLocation()
  350. : Stack.back().first.back().DefaultAttrLoc;
  351. }
  352. DefaultMapAttributes getDefaultDMA() const {
  353. return isStackEmpty() ? DMA_unspecified
  354. : Stack.back().first.back().DefaultMapAttr;
  355. }
  356. DefaultMapAttributes getDefaultDMAAtLevel(unsigned Level) const {
  357. return Stack.back().first[Level].DefaultMapAttr;
  358. }
  359. SourceLocation getDefaultDMALocation() const {
  360. return isStackEmpty() ? SourceLocation()
  361. : Stack.back().first.back().DefaultMapAttrLoc;
  362. }
  363. /// \brief Checks if the specified variable is a threadprivate.
  364. bool isThreadPrivate(VarDecl *D) {
  365. const DSAVarData DVar = getTopDSA(D, false);
  366. return isOpenMPThreadPrivate(DVar.CKind);
  367. }
  368. /// \brief Marks current region as ordered (it has an 'ordered' clause).
  369. void setOrderedRegion(bool IsOrdered, const Expr *Param) {
  370. assert(!isStackEmpty());
  371. Stack.back().first.back().OrderedRegion.setInt(IsOrdered);
  372. Stack.back().first.back().OrderedRegion.setPointer(Param);
  373. }
  374. /// \brief Returns true, if parent region is ordered (has associated
  375. /// 'ordered' clause), false - otherwise.
  376. bool isParentOrderedRegion() const {
  377. if (isStackEmpty() || Stack.back().first.size() == 1)
  378. return false;
  379. return std::next(Stack.back().first.rbegin())->OrderedRegion.getInt();
  380. }
  381. /// \brief Returns optional parameter for the ordered region.
  382. const Expr *getParentOrderedRegionParam() const {
  383. if (isStackEmpty() || Stack.back().first.size() == 1)
  384. return nullptr;
  385. return std::next(Stack.back().first.rbegin())->OrderedRegion.getPointer();
  386. }
  387. /// \brief Marks current region as nowait (it has a 'nowait' clause).
  388. void setNowaitRegion(bool IsNowait = true) {
  389. assert(!isStackEmpty());
  390. Stack.back().first.back().NowaitRegion = IsNowait;
  391. }
  392. /// \brief Returns true, if parent region is nowait (has associated
  393. /// 'nowait' clause), false - otherwise.
  394. bool isParentNowaitRegion() const {
  395. if (isStackEmpty() || Stack.back().first.size() == 1)
  396. return false;
  397. return std::next(Stack.back().first.rbegin())->NowaitRegion;
  398. }
  399. /// \brief Marks parent region as cancel region.
  400. void setParentCancelRegion(bool Cancel = true) {
  401. if (!isStackEmpty() && Stack.back().first.size() > 1) {
  402. auto &StackElemRef = *std::next(Stack.back().first.rbegin());
  403. StackElemRef.CancelRegion |= StackElemRef.CancelRegion || Cancel;
  404. }
  405. }
  406. /// \brief Return true if current region has inner cancel construct.
  407. bool isCancelRegion() const {
  408. return isStackEmpty() ? false : Stack.back().first.back().CancelRegion;
  409. }
  410. /// \brief Set collapse value for the region.
  411. void setAssociatedLoops(unsigned Val) {
  412. assert(!isStackEmpty());
  413. Stack.back().first.back().AssociatedLoops = Val;
  414. }
  415. /// \brief Return collapse value for region.
  416. unsigned getAssociatedLoops() const {
  417. return isStackEmpty() ? 0 : Stack.back().first.back().AssociatedLoops;
  418. }
  419. /// \brief Marks current target region as one with closely nested teams
  420. /// region.
  421. void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
  422. if (!isStackEmpty() && Stack.back().first.size() > 1) {
  423. std::next(Stack.back().first.rbegin())->InnerTeamsRegionLoc =
  424. TeamsRegionLoc;
  425. }
  426. }
  427. /// \brief Returns true, if current region has closely nested teams region.
  428. bool hasInnerTeamsRegion() const {
  429. return getInnerTeamsRegionLoc().isValid();
  430. }
  431. /// \brief Returns location of the nested teams region (if any).
  432. SourceLocation getInnerTeamsRegionLoc() const {
  433. return isStackEmpty() ? SourceLocation()
  434. : Stack.back().first.back().InnerTeamsRegionLoc;
  435. }
  436. Scope *getCurScope() const {
  437. return isStackEmpty() ? nullptr : Stack.back().first.back().CurScope;
  438. }
  439. SourceLocation getConstructLoc() const {
  440. return isStackEmpty() ? SourceLocation()
  441. : Stack.back().first.back().ConstructLoc;
  442. }
  443. /// Do the check specified in \a Check to all component lists and return true
  444. /// if any issue is found.
  445. bool checkMappableExprComponentListsForDecl(
  446. const ValueDecl *VD, bool CurrentRegionOnly,
  447. const llvm::function_ref<
  448. bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
  449. OpenMPClauseKind)>
  450. Check) const {
  451. if (isStackEmpty())
  452. return false;
  453. auto SI = Stack.back().first.rbegin();
  454. auto SE = Stack.back().first.rend();
  455. if (SI == SE)
  456. return false;
  457. if (CurrentRegionOnly)
  458. SE = std::next(SI);
  459. else
  460. std::advance(SI, 1);
  461. for (; SI != SE; ++SI) {
  462. auto MI = SI->MappedExprComponents.find(VD);
  463. if (MI != SI->MappedExprComponents.end())
  464. for (OMPClauseMappableExprCommon::MappableExprComponentListRef L :
  465. MI->second.Components)
  466. if (Check(L, MI->second.Kind))
  467. return true;
  468. }
  469. return false;
  470. }
  471. /// Do the check specified in \a Check to all component lists at a given level
  472. /// and return true if any issue is found.
  473. bool checkMappableExprComponentListsForDeclAtLevel(
  474. const ValueDecl *VD, unsigned Level,
  475. const llvm::function_ref<
  476. bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
  477. OpenMPClauseKind)>
  478. Check) const {
  479. if (isStackEmpty())
  480. return false;
  481. auto StartI = Stack.back().first.begin();
  482. auto EndI = Stack.back().first.end();
  483. if (std::distance(StartI, EndI) <= (int)Level)
  484. return false;
  485. std::advance(StartI, Level);
  486. auto MI = StartI->MappedExprComponents.find(VD);
  487. if (MI != StartI->MappedExprComponents.end())
  488. for (OMPClauseMappableExprCommon::MappableExprComponentListRef L :
  489. MI->second.Components)
  490. if (Check(L, MI->second.Kind))
  491. return true;
  492. return false;
  493. }
  494. /// Create a new mappable expression component list associated with a given
  495. /// declaration and initialize it with the provided list of components.
  496. void addMappableExpressionComponents(
  497. const ValueDecl *VD,
  498. OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
  499. OpenMPClauseKind WhereFoundClauseKind) {
  500. assert(!isStackEmpty() &&
  501. "Not expecting to retrieve components from a empty stack!");
  502. MappedExprComponentTy &MEC =
  503. Stack.back().first.back().MappedExprComponents[VD];
  504. // Create new entry and append the new components there.
  505. MEC.Components.resize(MEC.Components.size() + 1);
  506. MEC.Components.back().append(Components.begin(), Components.end());
  507. MEC.Kind = WhereFoundClauseKind;
  508. }
  509. unsigned getNestingLevel() const {
  510. assert(!isStackEmpty());
  511. return Stack.back().first.size() - 1;
  512. }
  513. void addDoacrossDependClause(OMPDependClause *C,
  514. const OperatorOffsetTy &OpsOffs) {
  515. assert(!isStackEmpty() && Stack.back().first.size() > 1);
  516. SharingMapTy &StackElem = *std::next(Stack.back().first.rbegin());
  517. assert(isOpenMPWorksharingDirective(StackElem.Directive));
  518. StackElem.DoacrossDepends.try_emplace(C, OpsOffs);
  519. }
  520. llvm::iterator_range<DoacrossDependMapTy::const_iterator>
  521. getDoacrossDependClauses() const {
  522. assert(!isStackEmpty());
  523. const SharingMapTy &StackElem = Stack.back().first.back();
  524. if (isOpenMPWorksharingDirective(StackElem.Directive)) {
  525. const DoacrossDependMapTy &Ref = StackElem.DoacrossDepends;
  526. return llvm::make_range(Ref.begin(), Ref.end());
  527. }
  528. return llvm::make_range(StackElem.DoacrossDepends.end(),
  529. StackElem.DoacrossDepends.end());
  530. }
  531. };
  532. bool isParallelOrTaskRegion(OpenMPDirectiveKind DKind) {
  533. return isOpenMPParallelDirective(DKind) || isOpenMPTaskingDirective(DKind) ||
  534. isOpenMPTeamsDirective(DKind) || DKind == OMPD_unknown;
  535. }
  536. } // namespace
  537. static const Expr *getExprAsWritten(const Expr *E) {
  538. if (const auto *ExprTemp = dyn_cast<ExprWithCleanups>(E))
  539. E = ExprTemp->getSubExpr();
  540. if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
  541. E = MTE->GetTemporaryExpr();
  542. while (const auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
  543. E = Binder->getSubExpr();
  544. if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
  545. E = ICE->getSubExprAsWritten();
  546. return E->IgnoreParens();
  547. }
  548. static Expr *getExprAsWritten(Expr *E) {
  549. return const_cast<Expr *>(getExprAsWritten(const_cast<const Expr *>(E)));
  550. }
  551. static const ValueDecl *getCanonicalDecl(const ValueDecl *D) {
  552. if (const auto *CED = dyn_cast<OMPCapturedExprDecl>(D))
  553. if (const auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
  554. D = ME->getMemberDecl();
  555. const auto *VD = dyn_cast<VarDecl>(D);
  556. const auto *FD = dyn_cast<FieldDecl>(D);
  557. if (VD != nullptr) {
  558. VD = VD->getCanonicalDecl();
  559. D = VD;
  560. } else {
  561. assert(FD);
  562. FD = FD->getCanonicalDecl();
  563. D = FD;
  564. }
  565. return D;
  566. }
  567. static ValueDecl *getCanonicalDecl(ValueDecl *D) {
  568. return const_cast<ValueDecl *>(
  569. getCanonicalDecl(const_cast<const ValueDecl *>(D)));
  570. }
  571. DSAStackTy::DSAVarData DSAStackTy::getDSA(iterator &Iter,
  572. ValueDecl *D) const {
  573. D = getCanonicalDecl(D);
  574. auto *VD = dyn_cast<VarDecl>(D);
  575. const auto *FD = dyn_cast<FieldDecl>(D);
  576. DSAVarData DVar;
  577. if (isStackEmpty() || Iter == Stack.back().first.rend()) {
  578. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  579. // in a region but not in construct]
  580. // File-scope or namespace-scope variables referenced in called routines
  581. // in the region are shared unless they appear in a threadprivate
  582. // directive.
  583. if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(VD))
  584. DVar.CKind = OMPC_shared;
  585. // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
  586. // in a region but not in construct]
  587. // Variables with static storage duration that are declared in called
  588. // routines in the region are shared.
  589. if (VD && VD->hasGlobalStorage())
  590. DVar.CKind = OMPC_shared;
  591. // Non-static data members are shared by default.
  592. if (FD)
  593. DVar.CKind = OMPC_shared;
  594. return DVar;
  595. }
  596. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  597. // in a Construct, C/C++, predetermined, p.1]
  598. // Variables with automatic storage duration that are declared in a scope
  599. // inside the construct are private.
  600. if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() &&
  601. (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) {
  602. DVar.CKind = OMPC_private;
  603. return DVar;
  604. }
  605. DVar.DKind = Iter->Directive;
  606. // Explicitly specified attributes and local variables with predetermined
  607. // attributes.
  608. if (Iter->SharingMap.count(D)) {
  609. const DSAInfo &Data = Iter->SharingMap.lookup(D);
  610. DVar.RefExpr = Data.RefExpr.getPointer();
  611. DVar.PrivateCopy = Data.PrivateCopy;
  612. DVar.CKind = Data.Attributes;
  613. DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
  614. return DVar;
  615. }
  616. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  617. // in a Construct, C/C++, implicitly determined, p.1]
  618. // In a parallel or task construct, the data-sharing attributes of these
  619. // variables are determined by the default clause, if present.
  620. switch (Iter->DefaultAttr) {
  621. case DSA_shared:
  622. DVar.CKind = OMPC_shared;
  623. DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
  624. return DVar;
  625. case DSA_none:
  626. return DVar;
  627. case DSA_unspecified:
  628. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  629. // in a Construct, implicitly determined, p.2]
  630. // In a parallel construct, if no default clause is present, these
  631. // variables are shared.
  632. DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
  633. if (isOpenMPParallelDirective(DVar.DKind) ||
  634. isOpenMPTeamsDirective(DVar.DKind)) {
  635. DVar.CKind = OMPC_shared;
  636. return DVar;
  637. }
  638. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  639. // in a Construct, implicitly determined, p.4]
  640. // In a task construct, if no default clause is present, a variable that in
  641. // the enclosing context is determined to be shared by all implicit tasks
  642. // bound to the current team is shared.
  643. if (isOpenMPTaskingDirective(DVar.DKind)) {
  644. DSAVarData DVarTemp;
  645. iterator I = Iter, E = Stack.back().first.rend();
  646. do {
  647. ++I;
  648. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
  649. // Referenced in a Construct, implicitly determined, p.6]
  650. // In a task construct, if no default clause is present, a variable
  651. // whose data-sharing attribute is not determined by the rules above is
  652. // firstprivate.
  653. DVarTemp = getDSA(I, D);
  654. if (DVarTemp.CKind != OMPC_shared) {
  655. DVar.RefExpr = nullptr;
  656. DVar.CKind = OMPC_firstprivate;
  657. return DVar;
  658. }
  659. } while (I != E && !isParallelOrTaskRegion(I->Directive));
  660. DVar.CKind =
  661. (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
  662. return DVar;
  663. }
  664. }
  665. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  666. // in a Construct, implicitly determined, p.3]
  667. // For constructs other than task, if no default clause is present, these
  668. // variables inherit their data-sharing attributes from the enclosing
  669. // context.
  670. return getDSA(++Iter, D);
  671. }
  672. const Expr *DSAStackTy::addUniqueAligned(const ValueDecl *D,
  673. const Expr *NewDE) {
  674. assert(!isStackEmpty() && "Data sharing attributes stack is empty");
  675. D = getCanonicalDecl(D);
  676. SharingMapTy &StackElem = Stack.back().first.back();
  677. auto It = StackElem.AlignedMap.find(D);
  678. if (It == StackElem.AlignedMap.end()) {
  679. assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
  680. StackElem.AlignedMap[D] = NewDE;
  681. return nullptr;
  682. }
  683. assert(It->second && "Unexpected nullptr expr in the aligned map");
  684. return It->second;
  685. }
  686. void DSAStackTy::addLoopControlVariable(const ValueDecl *D, VarDecl *Capture) {
  687. assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
  688. D = getCanonicalDecl(D);
  689. SharingMapTy &StackElem = Stack.back().first.back();
  690. StackElem.LCVMap.try_emplace(
  691. D, LCDeclInfo(StackElem.LCVMap.size() + 1, Capture));
  692. }
  693. const DSAStackTy::LCDeclInfo
  694. DSAStackTy::isLoopControlVariable(const ValueDecl *D) const {
  695. assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
  696. D = getCanonicalDecl(D);
  697. const SharingMapTy &StackElem = Stack.back().first.back();
  698. auto It = StackElem.LCVMap.find(D);
  699. if (It != StackElem.LCVMap.end())
  700. return It->second;
  701. return {0, nullptr};
  702. }
  703. const DSAStackTy::LCDeclInfo
  704. DSAStackTy::isParentLoopControlVariable(const ValueDecl *D) const {
  705. assert(!isStackEmpty() && Stack.back().first.size() > 1 &&
  706. "Data-sharing attributes stack is empty");
  707. D = getCanonicalDecl(D);
  708. const SharingMapTy &StackElem = *std::next(Stack.back().first.rbegin());
  709. auto It = StackElem.LCVMap.find(D);
  710. if (It != StackElem.LCVMap.end())
  711. return It->second;
  712. return {0, nullptr};
  713. }
  714. const ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) const {
  715. assert(!isStackEmpty() && Stack.back().first.size() > 1 &&
  716. "Data-sharing attributes stack is empty");
  717. const SharingMapTy &StackElem = *std::next(Stack.back().first.rbegin());
  718. if (StackElem.LCVMap.size() < I)
  719. return nullptr;
  720. for (const auto &Pair : StackElem.LCVMap)
  721. if (Pair.second.first == I)
  722. return Pair.first;
  723. return nullptr;
  724. }
  725. void DSAStackTy::addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A,
  726. DeclRefExpr *PrivateCopy) {
  727. D = getCanonicalDecl(D);
  728. if (A == OMPC_threadprivate) {
  729. DSAInfo &Data = Threadprivates[D];
  730. Data.Attributes = A;
  731. Data.RefExpr.setPointer(E);
  732. Data.PrivateCopy = nullptr;
  733. } else {
  734. assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
  735. DSAInfo &Data = Stack.back().first.back().SharingMap[D];
  736. assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) ||
  737. (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) ||
  738. (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) ||
  739. (isLoopControlVariable(D).first && A == OMPC_private));
  740. if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) {
  741. Data.RefExpr.setInt(/*IntVal=*/true);
  742. return;
  743. }
  744. const bool IsLastprivate =
  745. A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate;
  746. Data.Attributes = A;
  747. Data.RefExpr.setPointerAndInt(E, IsLastprivate);
  748. Data.PrivateCopy = PrivateCopy;
  749. if (PrivateCopy) {
  750. DSAInfo &Data =
  751. Stack.back().first.back().SharingMap[PrivateCopy->getDecl()];
  752. Data.Attributes = A;
  753. Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate);
  754. Data.PrivateCopy = nullptr;
  755. }
  756. }
  757. }
  758. /// \brief Build a variable declaration for OpenMP loop iteration variable.
  759. static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
  760. StringRef Name, const AttrVec *Attrs = nullptr,
  761. DeclRefExpr *OrigRef = nullptr) {
  762. DeclContext *DC = SemaRef.CurContext;
  763. IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
  764. TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
  765. auto *Decl =
  766. VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
  767. if (Attrs) {
  768. for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end());
  769. I != E; ++I)
  770. Decl->addAttr(*I);
  771. }
  772. Decl->setImplicit();
  773. if (OrigRef) {
  774. Decl->addAttr(
  775. OMPReferencedVarAttr::CreateImplicit(SemaRef.Context, OrigRef));
  776. }
  777. return Decl;
  778. }
  779. static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
  780. SourceLocation Loc,
  781. bool RefersToCapture = false) {
  782. D->setReferenced();
  783. D->markUsed(S.Context);
  784. return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
  785. SourceLocation(), D, RefersToCapture, Loc, Ty,
  786. VK_LValue);
  787. }
  788. void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
  789. BinaryOperatorKind BOK) {
  790. D = getCanonicalDecl(D);
  791. assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
  792. assert(
  793. Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction &&
  794. "Additional reduction info may be specified only for reduction items.");
  795. ReductionData &ReductionData = Stack.back().first.back().ReductionMap[D];
  796. assert(ReductionData.ReductionRange.isInvalid() &&
  797. Stack.back().first.back().Directive == OMPD_taskgroup &&
  798. "Additional reduction info may be specified only once for reduction "
  799. "items.");
  800. ReductionData.set(BOK, SR);
  801. Expr *&TaskgroupReductionRef =
  802. Stack.back().first.back().TaskgroupReductionRef;
  803. if (!TaskgroupReductionRef) {
  804. VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(),
  805. SemaRef.Context.VoidPtrTy, ".task_red.");
  806. TaskgroupReductionRef =
  807. buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
  808. }
  809. }
  810. void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
  811. const Expr *ReductionRef) {
  812. D = getCanonicalDecl(D);
  813. assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
  814. assert(
  815. Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction &&
  816. "Additional reduction info may be specified only for reduction items.");
  817. ReductionData &ReductionData = Stack.back().first.back().ReductionMap[D];
  818. assert(ReductionData.ReductionRange.isInvalid() &&
  819. Stack.back().first.back().Directive == OMPD_taskgroup &&
  820. "Additional reduction info may be specified only once for reduction "
  821. "items.");
  822. ReductionData.set(ReductionRef, SR);
  823. Expr *&TaskgroupReductionRef =
  824. Stack.back().first.back().TaskgroupReductionRef;
  825. if (!TaskgroupReductionRef) {
  826. VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(),
  827. SemaRef.Context.VoidPtrTy, ".task_red.");
  828. TaskgroupReductionRef =
  829. buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
  830. }
  831. }
  832. const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData(
  833. const ValueDecl *D, SourceRange &SR, BinaryOperatorKind &BOK,
  834. Expr *&TaskgroupDescriptor) const {
  835. D = getCanonicalDecl(D);
  836. assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
  837. if (Stack.back().first.empty())
  838. return DSAVarData();
  839. for (iterator I = std::next(Stack.back().first.rbegin(), 1),
  840. E = Stack.back().first.rend();
  841. I != E; std::advance(I, 1)) {
  842. const DSAInfo &Data = I->SharingMap.lookup(D);
  843. if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
  844. continue;
  845. const ReductionData &ReductionData = I->ReductionMap.lookup(D);
  846. if (!ReductionData.ReductionOp ||
  847. ReductionData.ReductionOp.is<const Expr *>())
  848. return DSAVarData();
  849. SR = ReductionData.ReductionRange;
  850. BOK = ReductionData.ReductionOp.get<ReductionData::BOKPtrType>();
  851. assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
  852. "expression for the descriptor is not "
  853. "set.");
  854. TaskgroupDescriptor = I->TaskgroupReductionRef;
  855. return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
  856. Data.PrivateCopy, I->DefaultAttrLoc);
  857. }
  858. return DSAVarData();
  859. }
  860. const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData(
  861. const ValueDecl *D, SourceRange &SR, const Expr *&ReductionRef,
  862. Expr *&TaskgroupDescriptor) const {
  863. D = getCanonicalDecl(D);
  864. assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
  865. if (Stack.back().first.empty())
  866. return DSAVarData();
  867. for (iterator I = std::next(Stack.back().first.rbegin(), 1),
  868. E = Stack.back().first.rend();
  869. I != E; std::advance(I, 1)) {
  870. const DSAInfo &Data = I->SharingMap.lookup(D);
  871. if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
  872. continue;
  873. const ReductionData &ReductionData = I->ReductionMap.lookup(D);
  874. if (!ReductionData.ReductionOp ||
  875. !ReductionData.ReductionOp.is<const Expr *>())
  876. return DSAVarData();
  877. SR = ReductionData.ReductionRange;
  878. ReductionRef = ReductionData.ReductionOp.get<const Expr *>();
  879. assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
  880. "expression for the descriptor is not "
  881. "set.");
  882. TaskgroupDescriptor = I->TaskgroupReductionRef;
  883. return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
  884. Data.PrivateCopy, I->DefaultAttrLoc);
  885. }
  886. return DSAVarData();
  887. }
  888. bool DSAStackTy::isOpenMPLocal(VarDecl *D, iterator Iter) const {
  889. D = D->getCanonicalDecl();
  890. if (!isStackEmpty()) {
  891. iterator I = Iter, E = Stack.back().first.rend();
  892. Scope *TopScope = nullptr;
  893. while (I != E && !isParallelOrTaskRegion(I->Directive) &&
  894. !isOpenMPTargetExecutionDirective(I->Directive))
  895. ++I;
  896. if (I == E)
  897. return false;
  898. TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
  899. Scope *CurScope = getCurScope();
  900. while (CurScope != TopScope && !CurScope->isDeclScope(D))
  901. CurScope = CurScope->getParent();
  902. return CurScope != TopScope;
  903. }
  904. return false;
  905. }
  906. const DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D,
  907. bool FromParent) {
  908. D = getCanonicalDecl(D);
  909. DSAVarData DVar;
  910. auto *VD = dyn_cast<VarDecl>(D);
  911. auto TI = Threadprivates.find(D);
  912. if (TI != Threadprivates.end()) {
  913. DVar.RefExpr = TI->getSecond().RefExpr.getPointer();
  914. DVar.CKind = OMPC_threadprivate;
  915. return DVar;
  916. }
  917. if (VD && VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
  918. DVar.RefExpr = buildDeclRefExpr(
  919. SemaRef, VD, D->getType().getNonReferenceType(),
  920. VD->getAttr<OMPThreadPrivateDeclAttr>()->getLocation());
  921. DVar.CKind = OMPC_threadprivate;
  922. addDSA(D, DVar.RefExpr, OMPC_threadprivate);
  923. return DVar;
  924. }
  925. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  926. // in a Construct, C/C++, predetermined, p.1]
  927. // Variables appearing in threadprivate directives are threadprivate.
  928. if ((VD && VD->getTLSKind() != VarDecl::TLS_None &&
  929. !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
  930. SemaRef.getLangOpts().OpenMPUseTLS &&
  931. SemaRef.getASTContext().getTargetInfo().isTLSSupported())) ||
  932. (VD && VD->getStorageClass() == SC_Register &&
  933. VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) {
  934. DVar.RefExpr = buildDeclRefExpr(
  935. SemaRef, VD, D->getType().getNonReferenceType(), D->getLocation());
  936. DVar.CKind = OMPC_threadprivate;
  937. addDSA(D, DVar.RefExpr, OMPC_threadprivate);
  938. return DVar;
  939. }
  940. if (SemaRef.getLangOpts().OpenMPCUDAMode && VD &&
  941. VD->isLocalVarDeclOrParm() && !isStackEmpty() &&
  942. !isLoopControlVariable(D).first) {
  943. iterator IterTarget =
  944. std::find_if(Stack.back().first.rbegin(), Stack.back().first.rend(),
  945. [](const SharingMapTy &Data) {
  946. return isOpenMPTargetExecutionDirective(Data.Directive);
  947. });
  948. if (IterTarget != Stack.back().first.rend()) {
  949. iterator ParentIterTarget = std::next(IterTarget, 1);
  950. for (iterator Iter = Stack.back().first.rbegin();
  951. Iter != ParentIterTarget; std::advance(Iter, 1)) {
  952. if (isOpenMPLocal(VD, Iter)) {
  953. DVar.RefExpr =
  954. buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
  955. D->getLocation());
  956. DVar.CKind = OMPC_threadprivate;
  957. return DVar;
  958. }
  959. }
  960. if (!isClauseParsingMode() || IterTarget != Stack.back().first.rbegin()) {
  961. auto DSAIter = IterTarget->SharingMap.find(D);
  962. if (DSAIter != IterTarget->SharingMap.end() &&
  963. isOpenMPPrivate(DSAIter->getSecond().Attributes)) {
  964. DVar.RefExpr = DSAIter->getSecond().RefExpr.getPointer();
  965. DVar.CKind = OMPC_threadprivate;
  966. return DVar;
  967. }
  968. iterator End = Stack.back().first.rend();
  969. if (!SemaRef.isOpenMPCapturedByRef(
  970. D, std::distance(ParentIterTarget, End))) {
  971. DVar.RefExpr =
  972. buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
  973. IterTarget->ConstructLoc);
  974. DVar.CKind = OMPC_threadprivate;
  975. return DVar;
  976. }
  977. }
  978. }
  979. }
  980. if (isStackEmpty())
  981. // Not in OpenMP execution region and top scope was already checked.
  982. return DVar;
  983. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  984. // in a Construct, C/C++, predetermined, p.4]
  985. // Static data members are shared.
  986. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  987. // in a Construct, C/C++, predetermined, p.7]
  988. // Variables with static storage duration that are declared in a scope
  989. // inside the construct are shared.
  990. auto &&MatchesAlways = [](OpenMPDirectiveKind) { return true; };
  991. if (VD && VD->isStaticDataMember()) {
  992. DSAVarData DVarTemp = hasDSA(D, isOpenMPPrivate, MatchesAlways, FromParent);
  993. if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
  994. return DVar;
  995. DVar.CKind = OMPC_shared;
  996. return DVar;
  997. }
  998. QualType Type = D->getType().getNonReferenceType().getCanonicalType();
  999. bool IsConstant = Type.isConstant(SemaRef.getASTContext());
  1000. Type = SemaRef.getASTContext().getBaseElementType(Type);
  1001. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  1002. // in a Construct, C/C++, predetermined, p.6]
  1003. // Variables with const qualified type having no mutable member are
  1004. // shared.
  1005. const CXXRecordDecl *RD =
  1006. SemaRef.getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr;
  1007. if (const auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD))
  1008. if (const ClassTemplateDecl *CTD = CTSD->getSpecializedTemplate())
  1009. RD = CTD->getTemplatedDecl();
  1010. if (IsConstant &&
  1011. !(SemaRef.getLangOpts().CPlusPlus && RD && RD->hasDefinition() &&
  1012. RD->hasMutableFields())) {
  1013. // Variables with const-qualified type having no mutable member may be
  1014. // listed in a firstprivate clause, even if they are static data members.
  1015. DSAVarData DVarTemp =
  1016. hasDSA(D, [](OpenMPClauseKind C) { return C == OMPC_firstprivate; },
  1017. MatchesAlways, FromParent);
  1018. if (DVarTemp.CKind == OMPC_firstprivate && DVarTemp.RefExpr)
  1019. return DVarTemp;
  1020. DVar.CKind = OMPC_shared;
  1021. return DVar;
  1022. }
  1023. // Explicitly specified attributes and local variables with predetermined
  1024. // attributes.
  1025. iterator I = Stack.back().first.rbegin();
  1026. iterator EndI = Stack.back().first.rend();
  1027. if (FromParent && I != EndI)
  1028. std::advance(I, 1);
  1029. auto It = I->SharingMap.find(D);
  1030. if (It != I->SharingMap.end()) {
  1031. const DSAInfo &Data = It->getSecond();
  1032. DVar.RefExpr = Data.RefExpr.getPointer();
  1033. DVar.PrivateCopy = Data.PrivateCopy;
  1034. DVar.CKind = Data.Attributes;
  1035. DVar.ImplicitDSALoc = I->DefaultAttrLoc;
  1036. DVar.DKind = I->Directive;
  1037. }
  1038. return DVar;
  1039. }
  1040. const DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
  1041. bool FromParent) const {
  1042. if (isStackEmpty()) {
  1043. iterator I;
  1044. return getDSA(I, D);
  1045. }
  1046. D = getCanonicalDecl(D);
  1047. iterator StartI = Stack.back().first.rbegin();
  1048. iterator EndI = Stack.back().first.rend();
  1049. if (FromParent && StartI != EndI)
  1050. std::advance(StartI, 1);
  1051. return getDSA(StartI, D);
  1052. }
  1053. const DSAStackTy::DSAVarData
  1054. DSAStackTy::hasDSA(ValueDecl *D,
  1055. const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
  1056. const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
  1057. bool FromParent) const {
  1058. if (isStackEmpty())
  1059. return {};
  1060. D = getCanonicalDecl(D);
  1061. iterator I = Stack.back().first.rbegin();
  1062. iterator EndI = Stack.back().first.rend();
  1063. if (FromParent && I != EndI)
  1064. std::advance(I, 1);
  1065. for (; I != EndI; std::advance(I, 1)) {
  1066. if (!DPred(I->Directive) && !isParallelOrTaskRegion(I->Directive))
  1067. continue;
  1068. iterator NewI = I;
  1069. DSAVarData DVar = getDSA(NewI, D);
  1070. if (I == NewI && CPred(DVar.CKind))
  1071. return DVar;
  1072. }
  1073. return {};
  1074. }
  1075. const DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA(
  1076. ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
  1077. const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
  1078. bool FromParent) const {
  1079. if (isStackEmpty())
  1080. return {};
  1081. D = getCanonicalDecl(D);
  1082. iterator StartI = Stack.back().first.rbegin();
  1083. iterator EndI = Stack.back().first.rend();
  1084. if (FromParent && StartI != EndI)
  1085. std::advance(StartI, 1);
  1086. if (StartI == EndI || !DPred(StartI->Directive))
  1087. return {};
  1088. iterator NewI = StartI;
  1089. DSAVarData DVar = getDSA(NewI, D);
  1090. return (NewI == StartI && CPred(DVar.CKind)) ? DVar : DSAVarData();
  1091. }
  1092. bool DSAStackTy::hasExplicitDSA(
  1093. const ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
  1094. unsigned Level, bool NotLastprivate) const {
  1095. if (isStackEmpty())
  1096. return false;
  1097. D = getCanonicalDecl(D);
  1098. auto StartI = Stack.back().first.begin();
  1099. auto EndI = Stack.back().first.end();
  1100. if (std::distance(StartI, EndI) <= (int)Level)
  1101. return false;
  1102. std::advance(StartI, Level);
  1103. auto I = StartI->SharingMap.find(D);
  1104. return (I != StartI->SharingMap.end()) &&
  1105. I->getSecond().RefExpr.getPointer() &&
  1106. CPred(I->getSecond().Attributes) &&
  1107. (!NotLastprivate || !I->getSecond().RefExpr.getInt());
  1108. }
  1109. bool DSAStackTy::hasExplicitDirective(
  1110. const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
  1111. unsigned Level) const {
  1112. if (isStackEmpty())
  1113. return false;
  1114. auto StartI = Stack.back().first.begin();
  1115. auto EndI = Stack.back().first.end();
  1116. if (std::distance(StartI, EndI) <= (int)Level)
  1117. return false;
  1118. std::advance(StartI, Level);
  1119. return DPred(StartI->Directive);
  1120. }
  1121. bool DSAStackTy::hasDirective(
  1122. const llvm::function_ref<bool(OpenMPDirectiveKind,
  1123. const DeclarationNameInfo &, SourceLocation)>
  1124. DPred,
  1125. bool FromParent) const {
  1126. // We look only in the enclosing region.
  1127. if (isStackEmpty())
  1128. return false;
  1129. auto StartI = std::next(Stack.back().first.rbegin());
  1130. auto EndI = Stack.back().first.rend();
  1131. if (FromParent && StartI != EndI)
  1132. StartI = std::next(StartI);
  1133. for (auto I = StartI, EE = EndI; I != EE; ++I) {
  1134. if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
  1135. return true;
  1136. }
  1137. return false;
  1138. }
  1139. void Sema::InitDataSharingAttributesStack() {
  1140. VarDataSharingAttributesStack = new DSAStackTy(*this);
  1141. }
  1142. #define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
  1143. void Sema::pushOpenMPFunctionRegion() {
  1144. DSAStack->pushFunction();
  1145. }
  1146. void Sema::popOpenMPFunctionRegion(const FunctionScopeInfo *OldFSI) {
  1147. DSAStack->popFunction(OldFSI);
  1148. }
  1149. static llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy>
  1150. isDeclareTargetDeclaration(const ValueDecl *VD) {
  1151. for (const Decl *D : VD->redecls()) {
  1152. if (!D->hasAttrs())
  1153. continue;
  1154. if (const auto *Attr = D->getAttr<OMPDeclareTargetDeclAttr>())
  1155. return Attr->getMapType();
  1156. }
  1157. return llvm::None;
  1158. }
  1159. bool Sema::isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level) const {
  1160. assert(LangOpts.OpenMP && "OpenMP is not allowed");
  1161. ASTContext &Ctx = getASTContext();
  1162. bool IsByRef = true;
  1163. // Find the directive that is associated with the provided scope.
  1164. D = cast<ValueDecl>(D->getCanonicalDecl());
  1165. QualType Ty = D->getType();
  1166. if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) {
  1167. // This table summarizes how a given variable should be passed to the device
  1168. // given its type and the clauses where it appears. This table is based on
  1169. // the description in OpenMP 4.5 [2.10.4, target Construct] and
  1170. // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses].
  1171. //
  1172. // =========================================================================
  1173. // | type | defaultmap | pvt | first | is_device_ptr | map | res. |
  1174. // | |(tofrom:scalar)| | pvt | | | |
  1175. // =========================================================================
  1176. // | scl | | | | - | | bycopy|
  1177. // | scl | | - | x | - | - | bycopy|
  1178. // | scl | | x | - | - | - | null |
  1179. // | scl | x | | | - | | byref |
  1180. // | scl | x | - | x | - | - | bycopy|
  1181. // | scl | x | x | - | - | - | null |
  1182. // | scl | | - | - | - | x | byref |
  1183. // | scl | x | - | - | - | x | byref |
  1184. //
  1185. // | agg | n.a. | | | - | | byref |
  1186. // | agg | n.a. | - | x | - | - | byref |
  1187. // | agg | n.a. | x | - | - | - | null |
  1188. // | agg | n.a. | - | - | - | x | byref |
  1189. // | agg | n.a. | - | - | - | x[] | byref |
  1190. //
  1191. // | ptr | n.a. | | | - | | bycopy|
  1192. // | ptr | n.a. | - | x | - | - | bycopy|
  1193. // | ptr | n.a. | x | - | - | - | null |
  1194. // | ptr | n.a. | - | - | - | x | byref |
  1195. // | ptr | n.a. | - | - | - | x[] | bycopy|
  1196. // | ptr | n.a. | - | - | x | | bycopy|
  1197. // | ptr | n.a. | - | - | x | x | bycopy|
  1198. // | ptr | n.a. | - | - | x | x[] | bycopy|
  1199. // =========================================================================
  1200. // Legend:
  1201. // scl - scalar
  1202. // ptr - pointer
  1203. // agg - aggregate
  1204. // x - applies
  1205. // - - invalid in this combination
  1206. // [] - mapped with an array section
  1207. // byref - should be mapped by reference
  1208. // byval - should be mapped by value
  1209. // null - initialize a local variable to null on the device
  1210. //
  1211. // Observations:
  1212. // - All scalar declarations that show up in a map clause have to be passed
  1213. // by reference, because they may have been mapped in the enclosing data
  1214. // environment.
  1215. // - If the scalar value does not fit the size of uintptr, it has to be
  1216. // passed by reference, regardless the result in the table above.
  1217. // - For pointers mapped by value that have either an implicit map or an
  1218. // array section, the runtime library may pass the NULL value to the
  1219. // device instead of the value passed to it by the compiler.
  1220. if (Ty->isReferenceType())
  1221. Ty = Ty->castAs<ReferenceType>()->getPointeeType();
  1222. // Locate map clauses and see if the variable being captured is referred to
  1223. // in any of those clauses. Here we only care about variables, not fields,
  1224. // because fields are part of aggregates.
  1225. bool IsVariableUsedInMapClause = false;
  1226. bool IsVariableAssociatedWithSection = false;
  1227. DSAStack->checkMappableExprComponentListsForDeclAtLevel(
  1228. D, Level,
  1229. [&IsVariableUsedInMapClause, &IsVariableAssociatedWithSection, D](
  1230. OMPClauseMappableExprCommon::MappableExprComponentListRef
  1231. MapExprComponents,
  1232. OpenMPClauseKind WhereFoundClauseKind) {
  1233. // Only the map clause information influences how a variable is
  1234. // captured. E.g. is_device_ptr does not require changing the default
  1235. // behavior.
  1236. if (WhereFoundClauseKind != OMPC_map)
  1237. return false;
  1238. auto EI = MapExprComponents.rbegin();
  1239. auto EE = MapExprComponents.rend();
  1240. assert(EI != EE && "Invalid map expression!");
  1241. if (isa<DeclRefExpr>(EI->getAssociatedExpression()))
  1242. IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D;
  1243. ++EI;
  1244. if (EI == EE)
  1245. return false;
  1246. if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) ||
  1247. isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) ||
  1248. isa<MemberExpr>(EI->getAssociatedExpression())) {
  1249. IsVariableAssociatedWithSection = true;
  1250. // There is nothing more we need to know about this variable.
  1251. return true;
  1252. }
  1253. // Keep looking for more map info.
  1254. return false;
  1255. });
  1256. if (IsVariableUsedInMapClause) {
  1257. // If variable is identified in a map clause it is always captured by
  1258. // reference except if it is a pointer that is dereferenced somehow.
  1259. IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection);
  1260. } else {
  1261. // By default, all the data that has a scalar type is mapped by copy
  1262. // (except for reduction variables).
  1263. IsByRef =
  1264. !Ty->isScalarType() ||
  1265. DSAStack->getDefaultDMAAtLevel(Level) == DMA_tofrom_scalar ||
  1266. DSAStack->hasExplicitDSA(
  1267. D, [](OpenMPClauseKind K) { return K == OMPC_reduction; }, Level);
  1268. }
  1269. }
  1270. if (IsByRef && Ty.getNonReferenceType()->isScalarType()) {
  1271. IsByRef =
  1272. !DSAStack->hasExplicitDSA(
  1273. D,
  1274. [](OpenMPClauseKind K) -> bool { return K == OMPC_firstprivate; },
  1275. Level, /*NotLastprivate=*/true) &&
  1276. // If the variable is artificial and must be captured by value - try to
  1277. // capture by value.
  1278. !(isa<OMPCapturedExprDecl>(D) && !D->hasAttr<OMPCaptureNoInitAttr>() &&
  1279. !cast<OMPCapturedExprDecl>(D)->getInit()->isGLValue());
  1280. }
  1281. // When passing data by copy, we need to make sure it fits the uintptr size
  1282. // and alignment, because the runtime library only deals with uintptr types.
  1283. // If it does not fit the uintptr size, we need to pass the data by reference
  1284. // instead.
  1285. if (!IsByRef &&
  1286. (Ctx.getTypeSizeInChars(Ty) >
  1287. Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) ||
  1288. Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) {
  1289. IsByRef = true;
  1290. }
  1291. return IsByRef;
  1292. }
  1293. unsigned Sema::getOpenMPNestingLevel() const {
  1294. assert(getLangOpts().OpenMP);
  1295. return DSAStack->getNestingLevel();
  1296. }
  1297. bool Sema::isInOpenMPTargetExecutionDirective() const {
  1298. return (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) &&
  1299. !DSAStack->isClauseParsingMode()) ||
  1300. DSAStack->hasDirective(
  1301. [](OpenMPDirectiveKind K, const DeclarationNameInfo &,
  1302. SourceLocation) -> bool {
  1303. return isOpenMPTargetExecutionDirective(K);
  1304. },
  1305. false);
  1306. }
  1307. VarDecl *Sema::isOpenMPCapturedDecl(ValueDecl *D) const {
  1308. assert(LangOpts.OpenMP && "OpenMP is not allowed");
  1309. D = getCanonicalDecl(D);
  1310. // If we are attempting to capture a global variable in a directive with
  1311. // 'target' we return true so that this global is also mapped to the device.
  1312. //
  1313. auto *VD = dyn_cast<VarDecl>(D);
  1314. if (VD && !VD->hasLocalStorage() && isInOpenMPTargetExecutionDirective()) {
  1315. // If the declaration is enclosed in a 'declare target' directive,
  1316. // then it should not be captured.
  1317. //
  1318. if (isDeclareTargetDeclaration(VD))
  1319. return nullptr;
  1320. return VD;
  1321. }
  1322. if (DSAStack->getCurrentDirective() != OMPD_unknown &&
  1323. (!DSAStack->isClauseParsingMode() ||
  1324. DSAStack->getParentDirective() != OMPD_unknown)) {
  1325. auto &&Info = DSAStack->isLoopControlVariable(D);
  1326. if (Info.first ||
  1327. (VD && VD->hasLocalStorage() &&
  1328. isParallelOrTaskRegion(DSAStack->getCurrentDirective())) ||
  1329. (VD && DSAStack->isForceVarCapturing()))
  1330. return VD ? VD : Info.second;
  1331. DSAStackTy::DSAVarData DVarPrivate =
  1332. DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
  1333. if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
  1334. return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
  1335. DVarPrivate = DSAStack->hasDSA(D, isOpenMPPrivate,
  1336. [](OpenMPDirectiveKind) { return true; },
  1337. DSAStack->isClauseParsingMode());
  1338. if (DVarPrivate.CKind != OMPC_unknown)
  1339. return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
  1340. }
  1341. return nullptr;
  1342. }
  1343. void Sema::adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex,
  1344. unsigned Level) const {
  1345. SmallVector<OpenMPDirectiveKind, 4> Regions;
  1346. getOpenMPCaptureRegions(Regions, DSAStack->getDirective(Level));
  1347. FunctionScopesIndex -= Regions.size();
  1348. }
  1349. bool Sema::isOpenMPPrivateDecl(const ValueDecl *D, unsigned Level) const {
  1350. assert(LangOpts.OpenMP && "OpenMP is not allowed");
  1351. return DSAStack->hasExplicitDSA(
  1352. D, [](OpenMPClauseKind K) { return K == OMPC_private; }, Level) ||
  1353. (DSAStack->isClauseParsingMode() &&
  1354. DSAStack->getClauseParsingMode() == OMPC_private) ||
  1355. // Consider taskgroup reduction descriptor variable a private to avoid
  1356. // possible capture in the region.
  1357. (DSAStack->hasExplicitDirective(
  1358. [](OpenMPDirectiveKind K) { return K == OMPD_taskgroup; },
  1359. Level) &&
  1360. DSAStack->isTaskgroupReductionRef(D, Level));
  1361. }
  1362. void Sema::setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D,
  1363. unsigned Level) {
  1364. assert(LangOpts.OpenMP && "OpenMP is not allowed");
  1365. D = getCanonicalDecl(D);
  1366. OpenMPClauseKind OMPC = OMPC_unknown;
  1367. for (unsigned I = DSAStack->getNestingLevel() + 1; I > Level; --I) {
  1368. const unsigned NewLevel = I - 1;
  1369. if (DSAStack->hasExplicitDSA(D,
  1370. [&OMPC](const OpenMPClauseKind K) {
  1371. if (isOpenMPPrivate(K)) {
  1372. OMPC = K;
  1373. return true;
  1374. }
  1375. return false;
  1376. },
  1377. NewLevel))
  1378. break;
  1379. if (DSAStack->checkMappableExprComponentListsForDeclAtLevel(
  1380. D, NewLevel,
  1381. [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
  1382. OpenMPClauseKind) { return true; })) {
  1383. OMPC = OMPC_map;
  1384. break;
  1385. }
  1386. if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
  1387. NewLevel)) {
  1388. OMPC = OMPC_map;
  1389. if (D->getType()->isScalarType() &&
  1390. DSAStack->getDefaultDMAAtLevel(NewLevel) !=
  1391. DefaultMapAttributes::DMA_tofrom_scalar)
  1392. OMPC = OMPC_firstprivate;
  1393. break;
  1394. }
  1395. }
  1396. if (OMPC != OMPC_unknown)
  1397. FD->addAttr(OMPCaptureKindAttr::CreateImplicit(Context, OMPC));
  1398. }
  1399. bool Sema::isOpenMPTargetCapturedDecl(const ValueDecl *D,
  1400. unsigned Level) const {
  1401. assert(LangOpts.OpenMP && "OpenMP is not allowed");
  1402. // Return true if the current level is no longer enclosed in a target region.
  1403. const auto *VD = dyn_cast<VarDecl>(D);
  1404. return VD && !VD->hasLocalStorage() &&
  1405. DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
  1406. Level);
  1407. }
  1408. void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
  1409. void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
  1410. const DeclarationNameInfo &DirName,
  1411. Scope *CurScope, SourceLocation Loc) {
  1412. DSAStack->push(DKind, DirName, CurScope, Loc);
  1413. PushExpressionEvaluationContext(
  1414. ExpressionEvaluationContext::PotentiallyEvaluated);
  1415. }
  1416. void Sema::StartOpenMPClause(OpenMPClauseKind K) {
  1417. DSAStack->setClauseParsingMode(K);
  1418. }
  1419. void Sema::EndOpenMPClause() {
  1420. DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
  1421. }
  1422. void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
  1423. // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
  1424. // A variable of class type (or array thereof) that appears in a lastprivate
  1425. // clause requires an accessible, unambiguous default constructor for the
  1426. // class type, unless the list item is also specified in a firstprivate
  1427. // clause.
  1428. if (const auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
  1429. for (OMPClause *C : D->clauses()) {
  1430. if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
  1431. SmallVector<Expr *, 8> PrivateCopies;
  1432. for (Expr *DE : Clause->varlists()) {
  1433. if (DE->isValueDependent() || DE->isTypeDependent()) {
  1434. PrivateCopies.push_back(nullptr);
  1435. continue;
  1436. }
  1437. auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens());
  1438. auto *VD = cast<VarDecl>(DRE->getDecl());
  1439. QualType Type = VD->getType().getNonReferenceType();
  1440. const DSAStackTy::DSAVarData DVar =
  1441. DSAStack->getTopDSA(VD, /*FromParent=*/false);
  1442. if (DVar.CKind == OMPC_lastprivate) {
  1443. // Generate helper private variable and initialize it with the
  1444. // default value. The address of the original variable is replaced
  1445. // by the address of the new private variable in CodeGen. This new
  1446. // variable is not added to IdResolver, so the code in the OpenMP
  1447. // region uses original variable for proper diagnostics.
  1448. VarDecl *VDPrivate = buildVarDecl(
  1449. *this, DE->getExprLoc(), Type.getUnqualifiedType(),
  1450. VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr, DRE);
  1451. ActOnUninitializedDecl(VDPrivate);
  1452. if (VDPrivate->isInvalidDecl())
  1453. continue;
  1454. PrivateCopies.push_back(buildDeclRefExpr(
  1455. *this, VDPrivate, DE->getType(), DE->getExprLoc()));
  1456. } else {
  1457. // The variable is also a firstprivate, so initialization sequence
  1458. // for private copy is generated already.
  1459. PrivateCopies.push_back(nullptr);
  1460. }
  1461. }
  1462. // Set initializers to private copies if no errors were found.
  1463. if (PrivateCopies.size() == Clause->varlist_size())
  1464. Clause->setPrivateCopies(PrivateCopies);
  1465. }
  1466. }
  1467. }
  1468. DSAStack->pop();
  1469. DiscardCleanupsInEvaluationContext();
  1470. PopExpressionEvaluationContext();
  1471. }
  1472. static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
  1473. Expr *NumIterations, Sema &SemaRef,
  1474. Scope *S, DSAStackTy *Stack);
  1475. namespace {
  1476. class VarDeclFilterCCC final : public CorrectionCandidateCallback {
  1477. private:
  1478. Sema &SemaRef;
  1479. public:
  1480. explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
  1481. bool ValidateCandidate(const TypoCorrection &Candidate) override {
  1482. NamedDecl *ND = Candidate.getCorrectionDecl();
  1483. if (const auto *VD = dyn_cast_or_null<VarDecl>(ND)) {
  1484. return VD->hasGlobalStorage() &&
  1485. SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
  1486. SemaRef.getCurScope());
  1487. }
  1488. return false;
  1489. }
  1490. };
  1491. class VarOrFuncDeclFilterCCC final : public CorrectionCandidateCallback {
  1492. private:
  1493. Sema &SemaRef;
  1494. public:
  1495. explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {}
  1496. bool ValidateCandidate(const TypoCorrection &Candidate) override {
  1497. NamedDecl *ND = Candidate.getCorrectionDecl();
  1498. if (ND && (isa<VarDecl>(ND) || isa<FunctionDecl>(ND))) {
  1499. return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
  1500. SemaRef.getCurScope());
  1501. }
  1502. return false;
  1503. }
  1504. };
  1505. } // namespace
  1506. ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
  1507. CXXScopeSpec &ScopeSpec,
  1508. const DeclarationNameInfo &Id) {
  1509. LookupResult Lookup(*this, Id, LookupOrdinaryName);
  1510. LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
  1511. if (Lookup.isAmbiguous())
  1512. return ExprError();
  1513. VarDecl *VD;
  1514. if (!Lookup.isSingleResult()) {
  1515. if (TypoCorrection Corrected = CorrectTypo(
  1516. Id, LookupOrdinaryName, CurScope, nullptr,
  1517. llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) {
  1518. diagnoseTypo(Corrected,
  1519. PDiag(Lookup.empty()
  1520. ? diag::err_undeclared_var_use_suggest
  1521. : diag::err_omp_expected_var_arg_suggest)
  1522. << Id.getName());
  1523. VD = Corrected.getCorrectionDeclAs<VarDecl>();
  1524. } else {
  1525. Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
  1526. : diag::err_omp_expected_var_arg)
  1527. << Id.getName();
  1528. return ExprError();
  1529. }
  1530. } else if (!(VD = Lookup.getAsSingle<VarDecl>())) {
  1531. Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
  1532. Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
  1533. return ExprError();
  1534. }
  1535. Lookup.suppressDiagnostics();
  1536. // OpenMP [2.9.2, Syntax, C/C++]
  1537. // Variables must be file-scope, namespace-scope, or static block-scope.
  1538. if (!VD->hasGlobalStorage()) {
  1539. Diag(Id.getLoc(), diag::err_omp_global_var_arg)
  1540. << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal();
  1541. bool IsDecl =
  1542. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  1543. Diag(VD->getLocation(),
  1544. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  1545. << VD;
  1546. return ExprError();
  1547. }
  1548. VarDecl *CanonicalVD = VD->getCanonicalDecl();
  1549. NamedDecl *ND = CanonicalVD;
  1550. // OpenMP [2.9.2, Restrictions, C/C++, p.2]
  1551. // A threadprivate directive for file-scope variables must appear outside
  1552. // any definition or declaration.
  1553. if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
  1554. !getCurLexicalContext()->isTranslationUnit()) {
  1555. Diag(Id.getLoc(), diag::err_omp_var_scope)
  1556. << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
  1557. bool IsDecl =
  1558. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  1559. Diag(VD->getLocation(),
  1560. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  1561. << VD;
  1562. return ExprError();
  1563. }
  1564. // OpenMP [2.9.2, Restrictions, C/C++, p.3]
  1565. // A threadprivate directive for static class member variables must appear
  1566. // in the class definition, in the same scope in which the member
  1567. // variables are declared.
  1568. if (CanonicalVD->isStaticDataMember() &&
  1569. !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
  1570. Diag(Id.getLoc(), diag::err_omp_var_scope)
  1571. << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
  1572. bool IsDecl =
  1573. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  1574. Diag(VD->getLocation(),
  1575. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  1576. << VD;
  1577. return ExprError();
  1578. }
  1579. // OpenMP [2.9.2, Restrictions, C/C++, p.4]
  1580. // A threadprivate directive for namespace-scope variables must appear
  1581. // outside any definition or declaration other than the namespace
  1582. // definition itself.
  1583. if (CanonicalVD->getDeclContext()->isNamespace() &&
  1584. (!getCurLexicalContext()->isFileContext() ||
  1585. !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
  1586. Diag(Id.getLoc(), diag::err_omp_var_scope)
  1587. << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
  1588. bool IsDecl =
  1589. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  1590. Diag(VD->getLocation(),
  1591. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  1592. << VD;
  1593. return ExprError();
  1594. }
  1595. // OpenMP [2.9.2, Restrictions, C/C++, p.6]
  1596. // A threadprivate directive for static block-scope variables must appear
  1597. // in the scope of the variable and not in a nested scope.
  1598. if (CanonicalVD->isStaticLocal() && CurScope &&
  1599. !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
  1600. Diag(Id.getLoc(), diag::err_omp_var_scope)
  1601. << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
  1602. bool IsDecl =
  1603. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  1604. Diag(VD->getLocation(),
  1605. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  1606. << VD;
  1607. return ExprError();
  1608. }
  1609. // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
  1610. // A threadprivate directive must lexically precede all references to any
  1611. // of the variables in its list.
  1612. if (VD->isUsed() && !DSAStack->isThreadPrivate(VD)) {
  1613. Diag(Id.getLoc(), diag::err_omp_var_used)
  1614. << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
  1615. return ExprError();
  1616. }
  1617. QualType ExprType = VD->getType().getNonReferenceType();
  1618. return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
  1619. SourceLocation(), VD,
  1620. /*RefersToEnclosingVariableOrCapture=*/false,
  1621. Id.getLoc(), ExprType, VK_LValue);
  1622. }
  1623. Sema::DeclGroupPtrTy
  1624. Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
  1625. ArrayRef<Expr *> VarList) {
  1626. if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
  1627. CurContext->addDecl(D);
  1628. return DeclGroupPtrTy::make(DeclGroupRef(D));
  1629. }
  1630. return nullptr;
  1631. }
  1632. namespace {
  1633. class LocalVarRefChecker final
  1634. : public ConstStmtVisitor<LocalVarRefChecker, bool> {
  1635. Sema &SemaRef;
  1636. public:
  1637. bool VisitDeclRefExpr(const DeclRefExpr *E) {
  1638. if (const auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
  1639. if (VD->hasLocalStorage()) {
  1640. SemaRef.Diag(E->getLocStart(),
  1641. diag::err_omp_local_var_in_threadprivate_init)
  1642. << E->getSourceRange();
  1643. SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
  1644. << VD << VD->getSourceRange();
  1645. return true;
  1646. }
  1647. }
  1648. return false;
  1649. }
  1650. bool VisitStmt(const Stmt *S) {
  1651. for (const Stmt *Child : S->children()) {
  1652. if (Child && Visit(Child))
  1653. return true;
  1654. }
  1655. return false;
  1656. }
  1657. explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
  1658. };
  1659. } // namespace
  1660. OMPThreadPrivateDecl *
  1661. Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
  1662. SmallVector<Expr *, 8> Vars;
  1663. for (Expr *RefExpr : VarList) {
  1664. auto *DE = cast<DeclRefExpr>(RefExpr);
  1665. auto *VD = cast<VarDecl>(DE->getDecl());
  1666. SourceLocation ILoc = DE->getExprLoc();
  1667. // Mark variable as used.
  1668. VD->setReferenced();
  1669. VD->markUsed(Context);
  1670. QualType QType = VD->getType();
  1671. if (QType->isDependentType() || QType->isInstantiationDependentType()) {
  1672. // It will be analyzed later.
  1673. Vars.push_back(DE);
  1674. continue;
  1675. }
  1676. // OpenMP [2.9.2, Restrictions, C/C++, p.10]
  1677. // A threadprivate variable must not have an incomplete type.
  1678. if (RequireCompleteType(ILoc, VD->getType(),
  1679. diag::err_omp_threadprivate_incomplete_type)) {
  1680. continue;
  1681. }
  1682. // OpenMP [2.9.2, Restrictions, C/C++, p.10]
  1683. // A threadprivate variable must not have a reference type.
  1684. if (VD->getType()->isReferenceType()) {
  1685. Diag(ILoc, diag::err_omp_ref_type_arg)
  1686. << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
  1687. bool IsDecl =
  1688. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  1689. Diag(VD->getLocation(),
  1690. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  1691. << VD;
  1692. continue;
  1693. }
  1694. // Check if this is a TLS variable. If TLS is not being supported, produce
  1695. // the corresponding diagnostic.
  1696. if ((VD->getTLSKind() != VarDecl::TLS_None &&
  1697. !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
  1698. getLangOpts().OpenMPUseTLS &&
  1699. getASTContext().getTargetInfo().isTLSSupported())) ||
  1700. (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
  1701. !VD->isLocalVarDecl())) {
  1702. Diag(ILoc, diag::err_omp_var_thread_local)
  1703. << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
  1704. bool IsDecl =
  1705. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  1706. Diag(VD->getLocation(),
  1707. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  1708. << VD;
  1709. continue;
  1710. }
  1711. // Check if initial value of threadprivate variable reference variable with
  1712. // local storage (it is not supported by runtime).
  1713. if (const Expr *Init = VD->getAnyInitializer()) {
  1714. LocalVarRefChecker Checker(*this);
  1715. if (Checker.Visit(Init))
  1716. continue;
  1717. }
  1718. Vars.push_back(RefExpr);
  1719. DSAStack->addDSA(VD, DE, OMPC_threadprivate);
  1720. VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
  1721. Context, SourceRange(Loc, Loc)));
  1722. if (ASTMutationListener *ML = Context.getASTMutationListener())
  1723. ML->DeclarationMarkedOpenMPThreadPrivate(VD);
  1724. }
  1725. OMPThreadPrivateDecl *D = nullptr;
  1726. if (!Vars.empty()) {
  1727. D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
  1728. Vars);
  1729. D->setAccess(AS_public);
  1730. }
  1731. return D;
  1732. }
  1733. static void reportOriginalDsa(Sema &SemaRef, const DSAStackTy *Stack,
  1734. const ValueDecl *D,
  1735. const DSAStackTy::DSAVarData &DVar,
  1736. bool IsLoopIterVar = false) {
  1737. if (DVar.RefExpr) {
  1738. SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
  1739. << getOpenMPClauseName(DVar.CKind);
  1740. return;
  1741. }
  1742. enum {
  1743. PDSA_StaticMemberShared,
  1744. PDSA_StaticLocalVarShared,
  1745. PDSA_LoopIterVarPrivate,
  1746. PDSA_LoopIterVarLinear,
  1747. PDSA_LoopIterVarLastprivate,
  1748. PDSA_ConstVarShared,
  1749. PDSA_GlobalVarShared,
  1750. PDSA_TaskVarFirstprivate,
  1751. PDSA_LocalVarPrivate,
  1752. PDSA_Implicit
  1753. } Reason = PDSA_Implicit;
  1754. bool ReportHint = false;
  1755. auto ReportLoc = D->getLocation();
  1756. auto *VD = dyn_cast<VarDecl>(D);
  1757. if (IsLoopIterVar) {
  1758. if (DVar.CKind == OMPC_private)
  1759. Reason = PDSA_LoopIterVarPrivate;
  1760. else if (DVar.CKind == OMPC_lastprivate)
  1761. Reason = PDSA_LoopIterVarLastprivate;
  1762. else
  1763. Reason = PDSA_LoopIterVarLinear;
  1764. } else if (isOpenMPTaskingDirective(DVar.DKind) &&
  1765. DVar.CKind == OMPC_firstprivate) {
  1766. Reason = PDSA_TaskVarFirstprivate;
  1767. ReportLoc = DVar.ImplicitDSALoc;
  1768. } else if (VD && VD->isStaticLocal())
  1769. Reason = PDSA_StaticLocalVarShared;
  1770. else if (VD && VD->isStaticDataMember())
  1771. Reason = PDSA_StaticMemberShared;
  1772. else if (VD && VD->isFileVarDecl())
  1773. Reason = PDSA_GlobalVarShared;
  1774. else if (D->getType().isConstant(SemaRef.getASTContext()))
  1775. Reason = PDSA_ConstVarShared;
  1776. else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
  1777. ReportHint = true;
  1778. Reason = PDSA_LocalVarPrivate;
  1779. }
  1780. if (Reason != PDSA_Implicit) {
  1781. SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
  1782. << Reason << ReportHint
  1783. << getOpenMPDirectiveName(Stack->getCurrentDirective());
  1784. } else if (DVar.ImplicitDSALoc.isValid()) {
  1785. SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
  1786. << getOpenMPClauseName(DVar.CKind);
  1787. }
  1788. }
  1789. namespace {
  1790. class DSAAttrChecker final : public StmtVisitor<DSAAttrChecker, void> {
  1791. DSAStackTy *Stack;
  1792. Sema &SemaRef;
  1793. bool ErrorFound = false;
  1794. CapturedStmt *CS = nullptr;
  1795. llvm::SmallVector<Expr *, 4> ImplicitFirstprivate;
  1796. llvm::SmallVector<Expr *, 4> ImplicitMap;
  1797. Sema::VarsWithInheritedDSAType VarsWithInheritedDSA;
  1798. llvm::SmallDenseSet<const ValueDecl *, 4> ImplicitDeclarations;
  1799. public:
  1800. void VisitDeclRefExpr(DeclRefExpr *E) {
  1801. if (E->isTypeDependent() || E->isValueDependent() ||
  1802. E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
  1803. return;
  1804. if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
  1805. VD = VD->getCanonicalDecl();
  1806. // Skip internally declared variables.
  1807. if (VD->hasLocalStorage() && !CS->capturesVariable(VD))
  1808. return;
  1809. DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
  1810. // Check if the variable has explicit DSA set and stop analysis if it so.
  1811. if (DVar.RefExpr || !ImplicitDeclarations.insert(VD).second)
  1812. return;
  1813. // Skip internally declared static variables.
  1814. llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
  1815. isDeclareTargetDeclaration(VD);
  1816. if (VD->hasGlobalStorage() && !CS->capturesVariable(VD) &&
  1817. (!Res || *Res != OMPDeclareTargetDeclAttr::MT_Link))
  1818. return;
  1819. SourceLocation ELoc = E->getExprLoc();
  1820. OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
  1821. // The default(none) clause requires that each variable that is referenced
  1822. // in the construct, and does not have a predetermined data-sharing
  1823. // attribute, must have its data-sharing attribute explicitly determined
  1824. // by being listed in a data-sharing attribute clause.
  1825. if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
  1826. isParallelOrTaskRegion(DKind) &&
  1827. VarsWithInheritedDSA.count(VD) == 0) {
  1828. VarsWithInheritedDSA[VD] = E;
  1829. return;
  1830. }
  1831. if (isOpenMPTargetExecutionDirective(DKind) &&
  1832. !Stack->isLoopControlVariable(VD).first) {
  1833. if (!Stack->checkMappableExprComponentListsForDecl(
  1834. VD, /*CurrentRegionOnly=*/true,
  1835. [](OMPClauseMappableExprCommon::MappableExprComponentListRef
  1836. StackComponents,
  1837. OpenMPClauseKind) {
  1838. // Variable is used if it has been marked as an array, array
  1839. // section or the variable iself.
  1840. return StackComponents.size() == 1 ||
  1841. std::all_of(
  1842. std::next(StackComponents.rbegin()),
  1843. StackComponents.rend(),
  1844. [](const OMPClauseMappableExprCommon::
  1845. MappableComponent &MC) {
  1846. return MC.getAssociatedDeclaration() ==
  1847. nullptr &&
  1848. (isa<OMPArraySectionExpr>(
  1849. MC.getAssociatedExpression()) ||
  1850. isa<ArraySubscriptExpr>(
  1851. MC.getAssociatedExpression()));
  1852. });
  1853. })) {
  1854. bool IsFirstprivate = false;
  1855. // By default lambdas are captured as firstprivates.
  1856. if (const auto *RD =
  1857. VD->getType().getNonReferenceType()->getAsCXXRecordDecl())
  1858. IsFirstprivate = RD->isLambda();
  1859. IsFirstprivate =
  1860. IsFirstprivate ||
  1861. (VD->getType().getNonReferenceType()->isScalarType() &&
  1862. Stack->getDefaultDMA() != DMA_tofrom_scalar && !Res);
  1863. if (IsFirstprivate)
  1864. ImplicitFirstprivate.emplace_back(E);
  1865. else
  1866. ImplicitMap.emplace_back(E);
  1867. return;
  1868. }
  1869. }
  1870. // OpenMP [2.9.3.6, Restrictions, p.2]
  1871. // A list item that appears in a reduction clause of the innermost
  1872. // enclosing worksharing or parallel construct may not be accessed in an
  1873. // explicit task.
  1874. DVar = Stack->hasInnermostDSA(
  1875. VD, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
  1876. [](OpenMPDirectiveKind K) {
  1877. return isOpenMPParallelDirective(K) ||
  1878. isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
  1879. },
  1880. /*FromParent=*/true);
  1881. if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
  1882. ErrorFound = true;
  1883. SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
  1884. reportOriginalDsa(SemaRef, Stack, VD, DVar);
  1885. return;
  1886. }
  1887. // Define implicit data-sharing attributes for task.
  1888. DVar = Stack->getImplicitDSA(VD, /*FromParent=*/false);
  1889. if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
  1890. !Stack->isLoopControlVariable(VD).first)
  1891. ImplicitFirstprivate.push_back(E);
  1892. }
  1893. }
  1894. void VisitMemberExpr(MemberExpr *E) {
  1895. if (E->isTypeDependent() || E->isValueDependent() ||
  1896. E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
  1897. return;
  1898. auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
  1899. OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
  1900. if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) {
  1901. if (!FD)
  1902. return;
  1903. DSAStackTy::DSAVarData DVar = Stack->getTopDSA(FD, /*FromParent=*/false);
  1904. // Check if the variable has explicit DSA set and stop analysis if it
  1905. // so.
  1906. if (DVar.RefExpr || !ImplicitDeclarations.insert(FD).second)
  1907. return;
  1908. if (isOpenMPTargetExecutionDirective(DKind) &&
  1909. !Stack->isLoopControlVariable(FD).first &&
  1910. !Stack->checkMappableExprComponentListsForDecl(
  1911. FD, /*CurrentRegionOnly=*/true,
  1912. [](OMPClauseMappableExprCommon::MappableExprComponentListRef
  1913. StackComponents,
  1914. OpenMPClauseKind) {
  1915. return isa<CXXThisExpr>(
  1916. cast<MemberExpr>(
  1917. StackComponents.back().getAssociatedExpression())
  1918. ->getBase()
  1919. ->IgnoreParens());
  1920. })) {
  1921. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
  1922. // A bit-field cannot appear in a map clause.
  1923. //
  1924. if (FD->isBitField())
  1925. return;
  1926. ImplicitMap.emplace_back(E);
  1927. return;
  1928. }
  1929. SourceLocation ELoc = E->getExprLoc();
  1930. // OpenMP [2.9.3.6, Restrictions, p.2]
  1931. // A list item that appears in a reduction clause of the innermost
  1932. // enclosing worksharing or parallel construct may not be accessed in
  1933. // an explicit task.
  1934. DVar = Stack->hasInnermostDSA(
  1935. FD, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
  1936. [](OpenMPDirectiveKind K) {
  1937. return isOpenMPParallelDirective(K) ||
  1938. isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
  1939. },
  1940. /*FromParent=*/true);
  1941. if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
  1942. ErrorFound = true;
  1943. SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
  1944. reportOriginalDsa(SemaRef, Stack, FD, DVar);
  1945. return;
  1946. }
  1947. // Define implicit data-sharing attributes for task.
  1948. DVar = Stack->getImplicitDSA(FD, /*FromParent=*/false);
  1949. if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
  1950. !Stack->isLoopControlVariable(FD).first)
  1951. ImplicitFirstprivate.push_back(E);
  1952. return;
  1953. }
  1954. if (isOpenMPTargetExecutionDirective(DKind)) {
  1955. OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
  1956. if (!checkMapClauseExpressionBase(SemaRef, E, CurComponents, OMPC_map,
  1957. /*NoDiagnose=*/true))
  1958. return;
  1959. const auto *VD = cast<ValueDecl>(
  1960. CurComponents.back().getAssociatedDeclaration()->getCanonicalDecl());
  1961. if (!Stack->checkMappableExprComponentListsForDecl(
  1962. VD, /*CurrentRegionOnly=*/true,
  1963. [&CurComponents](
  1964. OMPClauseMappableExprCommon::MappableExprComponentListRef
  1965. StackComponents,
  1966. OpenMPClauseKind) {
  1967. auto CCI = CurComponents.rbegin();
  1968. auto CCE = CurComponents.rend();
  1969. for (const auto &SC : llvm::reverse(StackComponents)) {
  1970. // Do both expressions have the same kind?
  1971. if (CCI->getAssociatedExpression()->getStmtClass() !=
  1972. SC.getAssociatedExpression()->getStmtClass())
  1973. if (!(isa<OMPArraySectionExpr>(
  1974. SC.getAssociatedExpression()) &&
  1975. isa<ArraySubscriptExpr>(
  1976. CCI->getAssociatedExpression())))
  1977. return false;
  1978. const Decl *CCD = CCI->getAssociatedDeclaration();
  1979. const Decl *SCD = SC.getAssociatedDeclaration();
  1980. CCD = CCD ? CCD->getCanonicalDecl() : nullptr;
  1981. SCD = SCD ? SCD->getCanonicalDecl() : nullptr;
  1982. if (SCD != CCD)
  1983. return false;
  1984. std::advance(CCI, 1);
  1985. if (CCI == CCE)
  1986. break;
  1987. }
  1988. return true;
  1989. })) {
  1990. Visit(E->getBase());
  1991. }
  1992. } else {
  1993. Visit(E->getBase());
  1994. }
  1995. }
  1996. void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
  1997. for (OMPClause *C : S->clauses()) {
  1998. // Skip analysis of arguments of implicitly defined firstprivate clause
  1999. // for task|target directives.
  2000. // Skip analysis of arguments of implicitly defined map clause for target
  2001. // directives.
  2002. if (C && !((isa<OMPFirstprivateClause>(C) || isa<OMPMapClause>(C)) &&
  2003. C->isImplicit())) {
  2004. for (Stmt *CC : C->children()) {
  2005. if (CC)
  2006. Visit(CC);
  2007. }
  2008. }
  2009. }
  2010. }
  2011. void VisitStmt(Stmt *S) {
  2012. for (Stmt *C : S->children()) {
  2013. if (C && !isa<OMPExecutableDirective>(C))
  2014. Visit(C);
  2015. }
  2016. }
  2017. bool isErrorFound() const { return ErrorFound; }
  2018. ArrayRef<Expr *> getImplicitFirstprivate() const {
  2019. return ImplicitFirstprivate;
  2020. }
  2021. ArrayRef<Expr *> getImplicitMap() const { return ImplicitMap; }
  2022. const Sema::VarsWithInheritedDSAType &getVarsWithInheritedDSA() const {
  2023. return VarsWithInheritedDSA;
  2024. }
  2025. DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
  2026. : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {}
  2027. };
  2028. } // namespace
  2029. void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
  2030. switch (DKind) {
  2031. case OMPD_parallel:
  2032. case OMPD_parallel_for:
  2033. case OMPD_parallel_for_simd:
  2034. case OMPD_parallel_sections:
  2035. case OMPD_teams:
  2036. case OMPD_teams_distribute:
  2037. case OMPD_teams_distribute_simd: {
  2038. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
  2039. QualType KmpInt32PtrTy =
  2040. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  2041. Sema::CapturedParamNameType Params[] = {
  2042. std::make_pair(".global_tid.", KmpInt32PtrTy),
  2043. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  2044. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2045. };
  2046. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2047. Params);
  2048. break;
  2049. }
  2050. case OMPD_target_teams:
  2051. case OMPD_target_parallel:
  2052. case OMPD_target_parallel_for:
  2053. case OMPD_target_parallel_for_simd:
  2054. case OMPD_target_teams_distribute:
  2055. case OMPD_target_teams_distribute_simd: {
  2056. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
  2057. QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
  2058. QualType KmpInt32PtrTy =
  2059. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  2060. QualType Args[] = {VoidPtrTy};
  2061. FunctionProtoType::ExtProtoInfo EPI;
  2062. EPI.Variadic = true;
  2063. QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
  2064. Sema::CapturedParamNameType Params[] = {
  2065. std::make_pair(".global_tid.", KmpInt32Ty),
  2066. std::make_pair(".part_id.", KmpInt32PtrTy),
  2067. std::make_pair(".privates.", VoidPtrTy),
  2068. std::make_pair(
  2069. ".copy_fn.",
  2070. Context.getPointerType(CopyFnType).withConst().withRestrict()),
  2071. std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
  2072. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2073. };
  2074. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2075. Params);
  2076. // Mark this captured region as inlined, because we don't use outlined
  2077. // function directly.
  2078. getCurCapturedRegion()->TheCapturedDecl->addAttr(
  2079. AlwaysInlineAttr::CreateImplicit(
  2080. Context, AlwaysInlineAttr::Keyword_forceinline));
  2081. Sema::CapturedParamNameType ParamsTarget[] = {
  2082. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2083. };
  2084. // Start a captured region for 'target' with no implicit parameters.
  2085. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2086. ParamsTarget);
  2087. Sema::CapturedParamNameType ParamsTeamsOrParallel[] = {
  2088. std::make_pair(".global_tid.", KmpInt32PtrTy),
  2089. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  2090. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2091. };
  2092. // Start a captured region for 'teams' or 'parallel'. Both regions have
  2093. // the same implicit parameters.
  2094. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2095. ParamsTeamsOrParallel);
  2096. break;
  2097. }
  2098. case OMPD_target:
  2099. case OMPD_target_simd: {
  2100. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
  2101. QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
  2102. QualType KmpInt32PtrTy =
  2103. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  2104. QualType Args[] = {VoidPtrTy};
  2105. FunctionProtoType::ExtProtoInfo EPI;
  2106. EPI.Variadic = true;
  2107. QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
  2108. Sema::CapturedParamNameType Params[] = {
  2109. std::make_pair(".global_tid.", KmpInt32Ty),
  2110. std::make_pair(".part_id.", KmpInt32PtrTy),
  2111. std::make_pair(".privates.", VoidPtrTy),
  2112. std::make_pair(
  2113. ".copy_fn.",
  2114. Context.getPointerType(CopyFnType).withConst().withRestrict()),
  2115. std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
  2116. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2117. };
  2118. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2119. Params);
  2120. // Mark this captured region as inlined, because we don't use outlined
  2121. // function directly.
  2122. getCurCapturedRegion()->TheCapturedDecl->addAttr(
  2123. AlwaysInlineAttr::CreateImplicit(
  2124. Context, AlwaysInlineAttr::Keyword_forceinline));
  2125. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2126. std::make_pair(StringRef(), QualType()));
  2127. break;
  2128. }
  2129. case OMPD_simd:
  2130. case OMPD_for:
  2131. case OMPD_for_simd:
  2132. case OMPD_sections:
  2133. case OMPD_section:
  2134. case OMPD_single:
  2135. case OMPD_master:
  2136. case OMPD_critical:
  2137. case OMPD_taskgroup:
  2138. case OMPD_distribute:
  2139. case OMPD_distribute_simd:
  2140. case OMPD_ordered:
  2141. case OMPD_atomic:
  2142. case OMPD_target_data: {
  2143. Sema::CapturedParamNameType Params[] = {
  2144. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2145. };
  2146. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2147. Params);
  2148. break;
  2149. }
  2150. case OMPD_task: {
  2151. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
  2152. QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
  2153. QualType KmpInt32PtrTy =
  2154. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  2155. QualType Args[] = {VoidPtrTy};
  2156. FunctionProtoType::ExtProtoInfo EPI;
  2157. EPI.Variadic = true;
  2158. QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
  2159. Sema::CapturedParamNameType Params[] = {
  2160. std::make_pair(".global_tid.", KmpInt32Ty),
  2161. std::make_pair(".part_id.", KmpInt32PtrTy),
  2162. std::make_pair(".privates.", VoidPtrTy),
  2163. std::make_pair(
  2164. ".copy_fn.",
  2165. Context.getPointerType(CopyFnType).withConst().withRestrict()),
  2166. std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
  2167. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2168. };
  2169. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2170. Params);
  2171. // Mark this captured region as inlined, because we don't use outlined
  2172. // function directly.
  2173. getCurCapturedRegion()->TheCapturedDecl->addAttr(
  2174. AlwaysInlineAttr::CreateImplicit(
  2175. Context, AlwaysInlineAttr::Keyword_forceinline));
  2176. break;
  2177. }
  2178. case OMPD_taskloop:
  2179. case OMPD_taskloop_simd: {
  2180. QualType KmpInt32Ty =
  2181. Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1)
  2182. .withConst();
  2183. QualType KmpUInt64Ty =
  2184. Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0)
  2185. .withConst();
  2186. QualType KmpInt64Ty =
  2187. Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1)
  2188. .withConst();
  2189. QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
  2190. QualType KmpInt32PtrTy =
  2191. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  2192. QualType Args[] = {VoidPtrTy};
  2193. FunctionProtoType::ExtProtoInfo EPI;
  2194. EPI.Variadic = true;
  2195. QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
  2196. Sema::CapturedParamNameType Params[] = {
  2197. std::make_pair(".global_tid.", KmpInt32Ty),
  2198. std::make_pair(".part_id.", KmpInt32PtrTy),
  2199. std::make_pair(".privates.", VoidPtrTy),
  2200. std::make_pair(
  2201. ".copy_fn.",
  2202. Context.getPointerType(CopyFnType).withConst().withRestrict()),
  2203. std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
  2204. std::make_pair(".lb.", KmpUInt64Ty),
  2205. std::make_pair(".ub.", KmpUInt64Ty),
  2206. std::make_pair(".st.", KmpInt64Ty),
  2207. std::make_pair(".liter.", KmpInt32Ty),
  2208. std::make_pair(".reductions.", VoidPtrTy),
  2209. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2210. };
  2211. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2212. Params);
  2213. // Mark this captured region as inlined, because we don't use outlined
  2214. // function directly.
  2215. getCurCapturedRegion()->TheCapturedDecl->addAttr(
  2216. AlwaysInlineAttr::CreateImplicit(
  2217. Context, AlwaysInlineAttr::Keyword_forceinline));
  2218. break;
  2219. }
  2220. case OMPD_distribute_parallel_for_simd:
  2221. case OMPD_distribute_parallel_for: {
  2222. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
  2223. QualType KmpInt32PtrTy =
  2224. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  2225. Sema::CapturedParamNameType Params[] = {
  2226. std::make_pair(".global_tid.", KmpInt32PtrTy),
  2227. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  2228. std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
  2229. std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
  2230. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2231. };
  2232. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2233. Params);
  2234. break;
  2235. }
  2236. case OMPD_target_teams_distribute_parallel_for:
  2237. case OMPD_target_teams_distribute_parallel_for_simd: {
  2238. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
  2239. QualType KmpInt32PtrTy =
  2240. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  2241. QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
  2242. QualType Args[] = {VoidPtrTy};
  2243. FunctionProtoType::ExtProtoInfo EPI;
  2244. EPI.Variadic = true;
  2245. QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
  2246. Sema::CapturedParamNameType Params[] = {
  2247. std::make_pair(".global_tid.", KmpInt32Ty),
  2248. std::make_pair(".part_id.", KmpInt32PtrTy),
  2249. std::make_pair(".privates.", VoidPtrTy),
  2250. std::make_pair(
  2251. ".copy_fn.",
  2252. Context.getPointerType(CopyFnType).withConst().withRestrict()),
  2253. std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
  2254. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2255. };
  2256. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2257. Params);
  2258. // Mark this captured region as inlined, because we don't use outlined
  2259. // function directly.
  2260. getCurCapturedRegion()->TheCapturedDecl->addAttr(
  2261. AlwaysInlineAttr::CreateImplicit(
  2262. Context, AlwaysInlineAttr::Keyword_forceinline));
  2263. Sema::CapturedParamNameType ParamsTarget[] = {
  2264. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2265. };
  2266. // Start a captured region for 'target' with no implicit parameters.
  2267. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2268. ParamsTarget);
  2269. Sema::CapturedParamNameType ParamsTeams[] = {
  2270. std::make_pair(".global_tid.", KmpInt32PtrTy),
  2271. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  2272. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2273. };
  2274. // Start a captured region for 'target' with no implicit parameters.
  2275. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2276. ParamsTeams);
  2277. Sema::CapturedParamNameType ParamsParallel[] = {
  2278. std::make_pair(".global_tid.", KmpInt32PtrTy),
  2279. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  2280. std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
  2281. std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
  2282. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2283. };
  2284. // Start a captured region for 'teams' or 'parallel'. Both regions have
  2285. // the same implicit parameters.
  2286. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2287. ParamsParallel);
  2288. break;
  2289. }
  2290. case OMPD_teams_distribute_parallel_for:
  2291. case OMPD_teams_distribute_parallel_for_simd: {
  2292. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
  2293. QualType KmpInt32PtrTy =
  2294. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  2295. Sema::CapturedParamNameType ParamsTeams[] = {
  2296. std::make_pair(".global_tid.", KmpInt32PtrTy),
  2297. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  2298. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2299. };
  2300. // Start a captured region for 'target' with no implicit parameters.
  2301. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2302. ParamsTeams);
  2303. Sema::CapturedParamNameType ParamsParallel[] = {
  2304. std::make_pair(".global_tid.", KmpInt32PtrTy),
  2305. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  2306. std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
  2307. std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
  2308. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2309. };
  2310. // Start a captured region for 'teams' or 'parallel'. Both regions have
  2311. // the same implicit parameters.
  2312. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2313. ParamsParallel);
  2314. break;
  2315. }
  2316. case OMPD_target_update:
  2317. case OMPD_target_enter_data:
  2318. case OMPD_target_exit_data: {
  2319. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
  2320. QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
  2321. QualType KmpInt32PtrTy =
  2322. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  2323. QualType Args[] = {VoidPtrTy};
  2324. FunctionProtoType::ExtProtoInfo EPI;
  2325. EPI.Variadic = true;
  2326. QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
  2327. Sema::CapturedParamNameType Params[] = {
  2328. std::make_pair(".global_tid.", KmpInt32Ty),
  2329. std::make_pair(".part_id.", KmpInt32PtrTy),
  2330. std::make_pair(".privates.", VoidPtrTy),
  2331. std::make_pair(
  2332. ".copy_fn.",
  2333. Context.getPointerType(CopyFnType).withConst().withRestrict()),
  2334. std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
  2335. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2336. };
  2337. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2338. Params);
  2339. // Mark this captured region as inlined, because we don't use outlined
  2340. // function directly.
  2341. getCurCapturedRegion()->TheCapturedDecl->addAttr(
  2342. AlwaysInlineAttr::CreateImplicit(
  2343. Context, AlwaysInlineAttr::Keyword_forceinline));
  2344. break;
  2345. }
  2346. case OMPD_threadprivate:
  2347. case OMPD_taskyield:
  2348. case OMPD_barrier:
  2349. case OMPD_taskwait:
  2350. case OMPD_cancellation_point:
  2351. case OMPD_cancel:
  2352. case OMPD_flush:
  2353. case OMPD_declare_reduction:
  2354. case OMPD_declare_simd:
  2355. case OMPD_declare_target:
  2356. case OMPD_end_declare_target:
  2357. llvm_unreachable("OpenMP Directive is not allowed");
  2358. case OMPD_unknown:
  2359. llvm_unreachable("Unknown OpenMP directive");
  2360. }
  2361. }
  2362. int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) {
  2363. SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
  2364. getOpenMPCaptureRegions(CaptureRegions, DKind);
  2365. return CaptureRegions.size();
  2366. }
  2367. static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
  2368. Expr *CaptureExpr, bool WithInit,
  2369. bool AsExpression) {
  2370. assert(CaptureExpr);
  2371. ASTContext &C = S.getASTContext();
  2372. Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
  2373. QualType Ty = Init->getType();
  2374. if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
  2375. if (S.getLangOpts().CPlusPlus) {
  2376. Ty = C.getLValueReferenceType(Ty);
  2377. } else {
  2378. Ty = C.getPointerType(Ty);
  2379. ExprResult Res =
  2380. S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
  2381. if (!Res.isUsable())
  2382. return nullptr;
  2383. Init = Res.get();
  2384. }
  2385. WithInit = true;
  2386. }
  2387. auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty,
  2388. CaptureExpr->getLocStart());
  2389. if (!WithInit)
  2390. CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C));
  2391. S.CurContext->addHiddenDecl(CED);
  2392. S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false);
  2393. return CED;
  2394. }
  2395. static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
  2396. bool WithInit) {
  2397. OMPCapturedExprDecl *CD;
  2398. if (VarDecl *VD = S.isOpenMPCapturedDecl(D))
  2399. CD = cast<OMPCapturedExprDecl>(VD);
  2400. else
  2401. CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
  2402. /*AsExpression=*/false);
  2403. return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
  2404. CaptureExpr->getExprLoc());
  2405. }
  2406. static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
  2407. CaptureExpr = S.DefaultLvalueConversion(CaptureExpr).get();
  2408. if (!Ref) {
  2409. OMPCapturedExprDecl *CD = buildCaptureDecl(
  2410. S, &S.getASTContext().Idents.get(".capture_expr."), CaptureExpr,
  2411. /*WithInit=*/true, /*AsExpression=*/true);
  2412. Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
  2413. CaptureExpr->getExprLoc());
  2414. }
  2415. ExprResult Res = Ref;
  2416. if (!S.getLangOpts().CPlusPlus &&
  2417. CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
  2418. Ref->getType()->isPointerType()) {
  2419. Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
  2420. if (!Res.isUsable())
  2421. return ExprError();
  2422. }
  2423. return S.DefaultLvalueConversion(Res.get());
  2424. }
  2425. namespace {
  2426. // OpenMP directives parsed in this section are represented as a
  2427. // CapturedStatement with an associated statement. If a syntax error
  2428. // is detected during the parsing of the associated statement, the
  2429. // compiler must abort processing and close the CapturedStatement.
  2430. //
  2431. // Combined directives such as 'target parallel' have more than one
  2432. // nested CapturedStatements. This RAII ensures that we unwind out
  2433. // of all the nested CapturedStatements when an error is found.
  2434. class CaptureRegionUnwinderRAII {
  2435. private:
  2436. Sema &S;
  2437. bool &ErrorFound;
  2438. OpenMPDirectiveKind DKind = OMPD_unknown;
  2439. public:
  2440. CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound,
  2441. OpenMPDirectiveKind DKind)
  2442. : S(S), ErrorFound(ErrorFound), DKind(DKind) {}
  2443. ~CaptureRegionUnwinderRAII() {
  2444. if (ErrorFound) {
  2445. int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind);
  2446. while (--ThisCaptureLevel >= 0)
  2447. S.ActOnCapturedRegionError();
  2448. }
  2449. }
  2450. };
  2451. } // namespace
  2452. StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
  2453. ArrayRef<OMPClause *> Clauses) {
  2454. bool ErrorFound = false;
  2455. CaptureRegionUnwinderRAII CaptureRegionUnwinder(
  2456. *this, ErrorFound, DSAStack->getCurrentDirective());
  2457. if (!S.isUsable()) {
  2458. ErrorFound = true;
  2459. return StmtError();
  2460. }
  2461. SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
  2462. getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective());
  2463. OMPOrderedClause *OC = nullptr;
  2464. OMPScheduleClause *SC = nullptr;
  2465. SmallVector<const OMPLinearClause *, 4> LCs;
  2466. SmallVector<const OMPClauseWithPreInit *, 4> PICs;
  2467. // This is required for proper codegen.
  2468. for (OMPClause *Clause : Clauses) {
  2469. if (isOpenMPTaskingDirective(DSAStack->getCurrentDirective()) &&
  2470. Clause->getClauseKind() == OMPC_in_reduction) {
  2471. // Capture taskgroup task_reduction descriptors inside the tasking regions
  2472. // with the corresponding in_reduction items.
  2473. auto *IRC = cast<OMPInReductionClause>(Clause);
  2474. for (Expr *E : IRC->taskgroup_descriptors())
  2475. if (E)
  2476. MarkDeclarationsReferencedInExpr(E);
  2477. }
  2478. if (isOpenMPPrivate(Clause->getClauseKind()) ||
  2479. Clause->getClauseKind() == OMPC_copyprivate ||
  2480. (getLangOpts().OpenMPUseTLS &&
  2481. getASTContext().getTargetInfo().isTLSSupported() &&
  2482. Clause->getClauseKind() == OMPC_copyin)) {
  2483. DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
  2484. // Mark all variables in private list clauses as used in inner region.
  2485. for (Stmt *VarRef : Clause->children()) {
  2486. if (auto *E = cast_or_null<Expr>(VarRef)) {
  2487. MarkDeclarationsReferencedInExpr(E);
  2488. }
  2489. }
  2490. DSAStack->setForceVarCapturing(/*V=*/false);
  2491. } else if (CaptureRegions.size() > 1 ||
  2492. CaptureRegions.back() != OMPD_unknown) {
  2493. if (auto *C = OMPClauseWithPreInit::get(Clause))
  2494. PICs.push_back(C);
  2495. if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
  2496. if (Expr *E = C->getPostUpdateExpr())
  2497. MarkDeclarationsReferencedInExpr(E);
  2498. }
  2499. }
  2500. if (Clause->getClauseKind() == OMPC_schedule)
  2501. SC = cast<OMPScheduleClause>(Clause);
  2502. else if (Clause->getClauseKind() == OMPC_ordered)
  2503. OC = cast<OMPOrderedClause>(Clause);
  2504. else if (Clause->getClauseKind() == OMPC_linear)
  2505. LCs.push_back(cast<OMPLinearClause>(Clause));
  2506. }
  2507. // OpenMP, 2.7.1 Loop Construct, Restrictions
  2508. // The nonmonotonic modifier cannot be specified if an ordered clause is
  2509. // specified.
  2510. if (SC &&
  2511. (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
  2512. SC->getSecondScheduleModifier() ==
  2513. OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
  2514. OC) {
  2515. Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
  2516. ? SC->getFirstScheduleModifierLoc()
  2517. : SC->getSecondScheduleModifierLoc(),
  2518. diag::err_omp_schedule_nonmonotonic_ordered)
  2519. << SourceRange(OC->getLocStart(), OC->getLocEnd());
  2520. ErrorFound = true;
  2521. }
  2522. if (!LCs.empty() && OC && OC->getNumForLoops()) {
  2523. for (const OMPLinearClause *C : LCs) {
  2524. Diag(C->getLocStart(), diag::err_omp_linear_ordered)
  2525. << SourceRange(OC->getLocStart(), OC->getLocEnd());
  2526. }
  2527. ErrorFound = true;
  2528. }
  2529. if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
  2530. isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
  2531. OC->getNumForLoops()) {
  2532. Diag(OC->getLocStart(), diag::err_omp_ordered_simd)
  2533. << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
  2534. ErrorFound = true;
  2535. }
  2536. if (ErrorFound) {
  2537. return StmtError();
  2538. }
  2539. StmtResult SR = S;
  2540. for (OpenMPDirectiveKind ThisCaptureRegion : llvm::reverse(CaptureRegions)) {
  2541. // Mark all variables in private list clauses as used in inner region.
  2542. // Required for proper codegen of combined directives.
  2543. // TODO: add processing for other clauses.
  2544. if (ThisCaptureRegion != OMPD_unknown) {
  2545. for (const clang::OMPClauseWithPreInit *C : PICs) {
  2546. OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion();
  2547. // Find the particular capture region for the clause if the
  2548. // directive is a combined one with multiple capture regions.
  2549. // If the directive is not a combined one, the capture region
  2550. // associated with the clause is OMPD_unknown and is generated
  2551. // only once.
  2552. if (CaptureRegion == ThisCaptureRegion ||
  2553. CaptureRegion == OMPD_unknown) {
  2554. if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
  2555. for (Decl *D : DS->decls())
  2556. MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
  2557. }
  2558. }
  2559. }
  2560. }
  2561. SR = ActOnCapturedRegionEnd(SR.get());
  2562. }
  2563. return SR;
  2564. }
  2565. static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion,
  2566. OpenMPDirectiveKind CancelRegion,
  2567. SourceLocation StartLoc) {
  2568. // CancelRegion is only needed for cancel and cancellation_point.
  2569. if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point)
  2570. return false;
  2571. if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for ||
  2572. CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup)
  2573. return false;
  2574. SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region)
  2575. << getOpenMPDirectiveName(CancelRegion);
  2576. return true;
  2577. }
  2578. static bool checkNestingOfRegions(Sema &SemaRef, const DSAStackTy *Stack,
  2579. OpenMPDirectiveKind CurrentRegion,
  2580. const DeclarationNameInfo &CurrentName,
  2581. OpenMPDirectiveKind CancelRegion,
  2582. SourceLocation StartLoc) {
  2583. if (Stack->getCurScope()) {
  2584. OpenMPDirectiveKind ParentRegion = Stack->getParentDirective();
  2585. OpenMPDirectiveKind OffendingRegion = ParentRegion;
  2586. bool NestingProhibited = false;
  2587. bool CloseNesting = true;
  2588. bool OrphanSeen = false;
  2589. enum {
  2590. NoRecommend,
  2591. ShouldBeInParallelRegion,
  2592. ShouldBeInOrderedRegion,
  2593. ShouldBeInTargetRegion,
  2594. ShouldBeInTeamsRegion
  2595. } Recommend = NoRecommend;
  2596. if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) {
  2597. // OpenMP [2.16, Nesting of Regions]
  2598. // OpenMP constructs may not be nested inside a simd region.
  2599. // OpenMP [2.8.1,simd Construct, Restrictions]
  2600. // An ordered construct with the simd clause is the only OpenMP
  2601. // construct that can appear in the simd region.
  2602. // Allowing a SIMD construct nested in another SIMD construct is an
  2603. // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
  2604. // message.
  2605. SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
  2606. ? diag::err_omp_prohibited_region_simd
  2607. : diag::warn_omp_nesting_simd);
  2608. return CurrentRegion != OMPD_simd;
  2609. }
  2610. if (ParentRegion == OMPD_atomic) {
  2611. // OpenMP [2.16, Nesting of Regions]
  2612. // OpenMP constructs may not be nested inside an atomic region.
  2613. SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
  2614. return true;
  2615. }
  2616. if (CurrentRegion == OMPD_section) {
  2617. // OpenMP [2.7.2, sections Construct, Restrictions]
  2618. // Orphaned section directives are prohibited. That is, the section
  2619. // directives must appear within the sections construct and must not be
  2620. // encountered elsewhere in the sections region.
  2621. if (ParentRegion != OMPD_sections &&
  2622. ParentRegion != OMPD_parallel_sections) {
  2623. SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
  2624. << (ParentRegion != OMPD_unknown)
  2625. << getOpenMPDirectiveName(ParentRegion);
  2626. return true;
  2627. }
  2628. return false;
  2629. }
  2630. // Allow some constructs (except teams) to be orphaned (they could be
  2631. // used in functions, called from OpenMP regions with the required
  2632. // preconditions).
  2633. if (ParentRegion == OMPD_unknown &&
  2634. !isOpenMPNestingTeamsDirective(CurrentRegion))
  2635. return false;
  2636. if (CurrentRegion == OMPD_cancellation_point ||
  2637. CurrentRegion == OMPD_cancel) {
  2638. // OpenMP [2.16, Nesting of Regions]
  2639. // A cancellation point construct for which construct-type-clause is
  2640. // taskgroup must be nested inside a task construct. A cancellation
  2641. // point construct for which construct-type-clause is not taskgroup must
  2642. // be closely nested inside an OpenMP construct that matches the type
  2643. // specified in construct-type-clause.
  2644. // A cancel construct for which construct-type-clause is taskgroup must be
  2645. // nested inside a task construct. A cancel construct for which
  2646. // construct-type-clause is not taskgroup must be closely nested inside an
  2647. // OpenMP construct that matches the type specified in
  2648. // construct-type-clause.
  2649. NestingProhibited =
  2650. !((CancelRegion == OMPD_parallel &&
  2651. (ParentRegion == OMPD_parallel ||
  2652. ParentRegion == OMPD_target_parallel)) ||
  2653. (CancelRegion == OMPD_for &&
  2654. (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
  2655. ParentRegion == OMPD_target_parallel_for ||
  2656. ParentRegion == OMPD_distribute_parallel_for ||
  2657. ParentRegion == OMPD_teams_distribute_parallel_for ||
  2658. ParentRegion == OMPD_target_teams_distribute_parallel_for)) ||
  2659. (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
  2660. (CancelRegion == OMPD_sections &&
  2661. (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
  2662. ParentRegion == OMPD_parallel_sections)));
  2663. } else if (CurrentRegion == OMPD_master) {
  2664. // OpenMP [2.16, Nesting of Regions]
  2665. // A master region may not be closely nested inside a worksharing,
  2666. // atomic, or explicit task region.
  2667. NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
  2668. isOpenMPTaskingDirective(ParentRegion);
  2669. } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
  2670. // OpenMP [2.16, Nesting of Regions]
  2671. // A critical region may not be nested (closely or otherwise) inside a
  2672. // critical region with the same name. Note that this restriction is not
  2673. // sufficient to prevent deadlock.
  2674. SourceLocation PreviousCriticalLoc;
  2675. bool DeadLock = Stack->hasDirective(
  2676. [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
  2677. const DeclarationNameInfo &DNI,
  2678. SourceLocation Loc) {
  2679. if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
  2680. PreviousCriticalLoc = Loc;
  2681. return true;
  2682. }
  2683. return false;
  2684. },
  2685. false /* skip top directive */);
  2686. if (DeadLock) {
  2687. SemaRef.Diag(StartLoc,
  2688. diag::err_omp_prohibited_region_critical_same_name)
  2689. << CurrentName.getName();
  2690. if (PreviousCriticalLoc.isValid())
  2691. SemaRef.Diag(PreviousCriticalLoc,
  2692. diag::note_omp_previous_critical_region);
  2693. return true;
  2694. }
  2695. } else if (CurrentRegion == OMPD_barrier) {
  2696. // OpenMP [2.16, Nesting of Regions]
  2697. // A barrier region may not be closely nested inside a worksharing,
  2698. // explicit task, critical, ordered, atomic, or master region.
  2699. NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
  2700. isOpenMPTaskingDirective(ParentRegion) ||
  2701. ParentRegion == OMPD_master ||
  2702. ParentRegion == OMPD_critical ||
  2703. ParentRegion == OMPD_ordered;
  2704. } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
  2705. !isOpenMPParallelDirective(CurrentRegion) &&
  2706. !isOpenMPTeamsDirective(CurrentRegion)) {
  2707. // OpenMP [2.16, Nesting of Regions]
  2708. // A worksharing region may not be closely nested inside a worksharing,
  2709. // explicit task, critical, ordered, atomic, or master region.
  2710. NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
  2711. isOpenMPTaskingDirective(ParentRegion) ||
  2712. ParentRegion == OMPD_master ||
  2713. ParentRegion == OMPD_critical ||
  2714. ParentRegion == OMPD_ordered;
  2715. Recommend = ShouldBeInParallelRegion;
  2716. } else if (CurrentRegion == OMPD_ordered) {
  2717. // OpenMP [2.16, Nesting of Regions]
  2718. // An ordered region may not be closely nested inside a critical,
  2719. // atomic, or explicit task region.
  2720. // An ordered region must be closely nested inside a loop region (or
  2721. // parallel loop region) with an ordered clause.
  2722. // OpenMP [2.8.1,simd Construct, Restrictions]
  2723. // An ordered construct with the simd clause is the only OpenMP construct
  2724. // that can appear in the simd region.
  2725. NestingProhibited = ParentRegion == OMPD_critical ||
  2726. isOpenMPTaskingDirective(ParentRegion) ||
  2727. !(isOpenMPSimdDirective(ParentRegion) ||
  2728. Stack->isParentOrderedRegion());
  2729. Recommend = ShouldBeInOrderedRegion;
  2730. } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
  2731. // OpenMP [2.16, Nesting of Regions]
  2732. // If specified, a teams construct must be contained within a target
  2733. // construct.
  2734. NestingProhibited = ParentRegion != OMPD_target;
  2735. OrphanSeen = ParentRegion == OMPD_unknown;
  2736. Recommend = ShouldBeInTargetRegion;
  2737. }
  2738. if (!NestingProhibited &&
  2739. !isOpenMPTargetExecutionDirective(CurrentRegion) &&
  2740. !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
  2741. (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
  2742. // OpenMP [2.16, Nesting of Regions]
  2743. // distribute, parallel, parallel sections, parallel workshare, and the
  2744. // parallel loop and parallel loop SIMD constructs are the only OpenMP
  2745. // constructs that can be closely nested in the teams region.
  2746. NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
  2747. !isOpenMPDistributeDirective(CurrentRegion);
  2748. Recommend = ShouldBeInParallelRegion;
  2749. }
  2750. if (!NestingProhibited &&
  2751. isOpenMPNestingDistributeDirective(CurrentRegion)) {
  2752. // OpenMP 4.5 [2.17 Nesting of Regions]
  2753. // The region associated with the distribute construct must be strictly
  2754. // nested inside a teams region
  2755. NestingProhibited =
  2756. (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
  2757. Recommend = ShouldBeInTeamsRegion;
  2758. }
  2759. if (!NestingProhibited &&
  2760. (isOpenMPTargetExecutionDirective(CurrentRegion) ||
  2761. isOpenMPTargetDataManagementDirective(CurrentRegion))) {
  2762. // OpenMP 4.5 [2.17 Nesting of Regions]
  2763. // If a target, target update, target data, target enter data, or
  2764. // target exit data construct is encountered during execution of a
  2765. // target region, the behavior is unspecified.
  2766. NestingProhibited = Stack->hasDirective(
  2767. [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
  2768. SourceLocation) {
  2769. if (isOpenMPTargetExecutionDirective(K)) {
  2770. OffendingRegion = K;
  2771. return true;
  2772. }
  2773. return false;
  2774. },
  2775. false /* don't skip top directive */);
  2776. CloseNesting = false;
  2777. }
  2778. if (NestingProhibited) {
  2779. if (OrphanSeen) {
  2780. SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
  2781. << getOpenMPDirectiveName(CurrentRegion) << Recommend;
  2782. } else {
  2783. SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
  2784. << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
  2785. << Recommend << getOpenMPDirectiveName(CurrentRegion);
  2786. }
  2787. return true;
  2788. }
  2789. }
  2790. return false;
  2791. }
  2792. static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
  2793. ArrayRef<OMPClause *> Clauses,
  2794. ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
  2795. bool ErrorFound = false;
  2796. unsigned NamedModifiersNumber = 0;
  2797. SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers(
  2798. OMPD_unknown + 1);
  2799. SmallVector<SourceLocation, 4> NameModifierLoc;
  2800. for (const OMPClause *C : Clauses) {
  2801. if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
  2802. // At most one if clause without a directive-name-modifier can appear on
  2803. // the directive.
  2804. OpenMPDirectiveKind CurNM = IC->getNameModifier();
  2805. if (FoundNameModifiers[CurNM]) {
  2806. S.Diag(C->getLocStart(), diag::err_omp_more_one_clause)
  2807. << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
  2808. << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
  2809. ErrorFound = true;
  2810. } else if (CurNM != OMPD_unknown) {
  2811. NameModifierLoc.push_back(IC->getNameModifierLoc());
  2812. ++NamedModifiersNumber;
  2813. }
  2814. FoundNameModifiers[CurNM] = IC;
  2815. if (CurNM == OMPD_unknown)
  2816. continue;
  2817. // Check if the specified name modifier is allowed for the current
  2818. // directive.
  2819. // At most one if clause with the particular directive-name-modifier can
  2820. // appear on the directive.
  2821. bool MatchFound = false;
  2822. for (auto NM : AllowedNameModifiers) {
  2823. if (CurNM == NM) {
  2824. MatchFound = true;
  2825. break;
  2826. }
  2827. }
  2828. if (!MatchFound) {
  2829. S.Diag(IC->getNameModifierLoc(),
  2830. diag::err_omp_wrong_if_directive_name_modifier)
  2831. << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
  2832. ErrorFound = true;
  2833. }
  2834. }
  2835. }
  2836. // If any if clause on the directive includes a directive-name-modifier then
  2837. // all if clauses on the directive must include a directive-name-modifier.
  2838. if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
  2839. if (NamedModifiersNumber == AllowedNameModifiers.size()) {
  2840. S.Diag(FoundNameModifiers[OMPD_unknown]->getLocStart(),
  2841. diag::err_omp_no_more_if_clause);
  2842. } else {
  2843. std::string Values;
  2844. std::string Sep(", ");
  2845. unsigned AllowedCnt = 0;
  2846. unsigned TotalAllowedNum =
  2847. AllowedNameModifiers.size() - NamedModifiersNumber;
  2848. for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
  2849. ++Cnt) {
  2850. OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
  2851. if (!FoundNameModifiers[NM]) {
  2852. Values += "'";
  2853. Values += getOpenMPDirectiveName(NM);
  2854. Values += "'";
  2855. if (AllowedCnt + 2 == TotalAllowedNum)
  2856. Values += " or ";
  2857. else if (AllowedCnt + 1 != TotalAllowedNum)
  2858. Values += Sep;
  2859. ++AllowedCnt;
  2860. }
  2861. }
  2862. S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getLocStart(),
  2863. diag::err_omp_unnamed_if_clause)
  2864. << (TotalAllowedNum > 1) << Values;
  2865. }
  2866. for (SourceLocation Loc : NameModifierLoc) {
  2867. S.Diag(Loc, diag::note_omp_previous_named_if_clause);
  2868. }
  2869. ErrorFound = true;
  2870. }
  2871. return ErrorFound;
  2872. }
  2873. StmtResult Sema::ActOnOpenMPExecutableDirective(
  2874. OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
  2875. OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
  2876. Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
  2877. StmtResult Res = StmtError();
  2878. // First check CancelRegion which is then used in checkNestingOfRegions.
  2879. if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) ||
  2880. checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
  2881. StartLoc))
  2882. return StmtError();
  2883. llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
  2884. VarsWithInheritedDSAType VarsWithInheritedDSA;
  2885. bool ErrorFound = false;
  2886. ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
  2887. if (AStmt && !CurContext->isDependentContext()) {
  2888. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  2889. // Check default data sharing attributes for referenced variables.
  2890. DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
  2891. int ThisCaptureLevel = getOpenMPCaptureLevels(Kind);
  2892. Stmt *S = AStmt;
  2893. while (--ThisCaptureLevel >= 0)
  2894. S = cast<CapturedStmt>(S)->getCapturedStmt();
  2895. DSAChecker.Visit(S);
  2896. if (DSAChecker.isErrorFound())
  2897. return StmtError();
  2898. // Generate list of implicitly defined firstprivate variables.
  2899. VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
  2900. SmallVector<Expr *, 4> ImplicitFirstprivates(
  2901. DSAChecker.getImplicitFirstprivate().begin(),
  2902. DSAChecker.getImplicitFirstprivate().end());
  2903. SmallVector<Expr *, 4> ImplicitMaps(DSAChecker.getImplicitMap().begin(),
  2904. DSAChecker.getImplicitMap().end());
  2905. // Mark taskgroup task_reduction descriptors as implicitly firstprivate.
  2906. for (OMPClause *C : Clauses) {
  2907. if (auto *IRC = dyn_cast<OMPInReductionClause>(C)) {
  2908. for (Expr *E : IRC->taskgroup_descriptors())
  2909. if (E)
  2910. ImplicitFirstprivates.emplace_back(E);
  2911. }
  2912. }
  2913. if (!ImplicitFirstprivates.empty()) {
  2914. if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
  2915. ImplicitFirstprivates, SourceLocation(), SourceLocation(),
  2916. SourceLocation())) {
  2917. ClausesWithImplicit.push_back(Implicit);
  2918. ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
  2919. ImplicitFirstprivates.size();
  2920. } else {
  2921. ErrorFound = true;
  2922. }
  2923. }
  2924. if (!ImplicitMaps.empty()) {
  2925. if (OMPClause *Implicit = ActOnOpenMPMapClause(
  2926. OMPC_MAP_unknown, OMPC_MAP_tofrom, /*IsMapTypeImplicit=*/true,
  2927. SourceLocation(), SourceLocation(), ImplicitMaps,
  2928. SourceLocation(), SourceLocation(), SourceLocation())) {
  2929. ClausesWithImplicit.emplace_back(Implicit);
  2930. ErrorFound |=
  2931. cast<OMPMapClause>(Implicit)->varlist_size() != ImplicitMaps.size();
  2932. } else {
  2933. ErrorFound = true;
  2934. }
  2935. }
  2936. }
  2937. llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
  2938. switch (Kind) {
  2939. case OMPD_parallel:
  2940. Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
  2941. EndLoc);
  2942. AllowedNameModifiers.push_back(OMPD_parallel);
  2943. break;
  2944. case OMPD_simd:
  2945. Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
  2946. VarsWithInheritedDSA);
  2947. break;
  2948. case OMPD_for:
  2949. Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
  2950. VarsWithInheritedDSA);
  2951. break;
  2952. case OMPD_for_simd:
  2953. Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
  2954. EndLoc, VarsWithInheritedDSA);
  2955. break;
  2956. case OMPD_sections:
  2957. Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
  2958. EndLoc);
  2959. break;
  2960. case OMPD_section:
  2961. assert(ClausesWithImplicit.empty() &&
  2962. "No clauses are allowed for 'omp section' directive");
  2963. Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
  2964. break;
  2965. case OMPD_single:
  2966. Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
  2967. EndLoc);
  2968. break;
  2969. case OMPD_master:
  2970. assert(ClausesWithImplicit.empty() &&
  2971. "No clauses are allowed for 'omp master' directive");
  2972. Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
  2973. break;
  2974. case OMPD_critical:
  2975. Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
  2976. StartLoc, EndLoc);
  2977. break;
  2978. case OMPD_parallel_for:
  2979. Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
  2980. EndLoc, VarsWithInheritedDSA);
  2981. AllowedNameModifiers.push_back(OMPD_parallel);
  2982. break;
  2983. case OMPD_parallel_for_simd:
  2984. Res = ActOnOpenMPParallelForSimdDirective(
  2985. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  2986. AllowedNameModifiers.push_back(OMPD_parallel);
  2987. break;
  2988. case OMPD_parallel_sections:
  2989. Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
  2990. StartLoc, EndLoc);
  2991. AllowedNameModifiers.push_back(OMPD_parallel);
  2992. break;
  2993. case OMPD_task:
  2994. Res =
  2995. ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
  2996. AllowedNameModifiers.push_back(OMPD_task);
  2997. break;
  2998. case OMPD_taskyield:
  2999. assert(ClausesWithImplicit.empty() &&
  3000. "No clauses are allowed for 'omp taskyield' directive");
  3001. assert(AStmt == nullptr &&
  3002. "No associated statement allowed for 'omp taskyield' directive");
  3003. Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
  3004. break;
  3005. case OMPD_barrier:
  3006. assert(ClausesWithImplicit.empty() &&
  3007. "No clauses are allowed for 'omp barrier' directive");
  3008. assert(AStmt == nullptr &&
  3009. "No associated statement allowed for 'omp barrier' directive");
  3010. Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
  3011. break;
  3012. case OMPD_taskwait:
  3013. assert(ClausesWithImplicit.empty() &&
  3014. "No clauses are allowed for 'omp taskwait' directive");
  3015. assert(AStmt == nullptr &&
  3016. "No associated statement allowed for 'omp taskwait' directive");
  3017. Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
  3018. break;
  3019. case OMPD_taskgroup:
  3020. Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc,
  3021. EndLoc);
  3022. break;
  3023. case OMPD_flush:
  3024. assert(AStmt == nullptr &&
  3025. "No associated statement allowed for 'omp flush' directive");
  3026. Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
  3027. break;
  3028. case OMPD_ordered:
  3029. Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
  3030. EndLoc);
  3031. break;
  3032. case OMPD_atomic:
  3033. Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
  3034. EndLoc);
  3035. break;
  3036. case OMPD_teams:
  3037. Res =
  3038. ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
  3039. break;
  3040. case OMPD_target:
  3041. Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
  3042. EndLoc);
  3043. AllowedNameModifiers.push_back(OMPD_target);
  3044. break;
  3045. case OMPD_target_parallel:
  3046. Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
  3047. StartLoc, EndLoc);
  3048. AllowedNameModifiers.push_back(OMPD_target);
  3049. AllowedNameModifiers.push_back(OMPD_parallel);
  3050. break;
  3051. case OMPD_target_parallel_for:
  3052. Res = ActOnOpenMPTargetParallelForDirective(
  3053. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  3054. AllowedNameModifiers.push_back(OMPD_target);
  3055. AllowedNameModifiers.push_back(OMPD_parallel);
  3056. break;
  3057. case OMPD_cancellation_point:
  3058. assert(ClausesWithImplicit.empty() &&
  3059. "No clauses are allowed for 'omp cancellation point' directive");
  3060. assert(AStmt == nullptr && "No associated statement allowed for 'omp "
  3061. "cancellation point' directive");
  3062. Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
  3063. break;
  3064. case OMPD_cancel:
  3065. assert(AStmt == nullptr &&
  3066. "No associated statement allowed for 'omp cancel' directive");
  3067. Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
  3068. CancelRegion);
  3069. AllowedNameModifiers.push_back(OMPD_cancel);
  3070. break;
  3071. case OMPD_target_data:
  3072. Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
  3073. EndLoc);
  3074. AllowedNameModifiers.push_back(OMPD_target_data);
  3075. break;
  3076. case OMPD_target_enter_data:
  3077. Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
  3078. EndLoc, AStmt);
  3079. AllowedNameModifiers.push_back(OMPD_target_enter_data);
  3080. break;
  3081. case OMPD_target_exit_data:
  3082. Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
  3083. EndLoc, AStmt);
  3084. AllowedNameModifiers.push_back(OMPD_target_exit_data);
  3085. break;
  3086. case OMPD_taskloop:
  3087. Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
  3088. EndLoc, VarsWithInheritedDSA);
  3089. AllowedNameModifiers.push_back(OMPD_taskloop);
  3090. break;
  3091. case OMPD_taskloop_simd:
  3092. Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
  3093. EndLoc, VarsWithInheritedDSA);
  3094. AllowedNameModifiers.push_back(OMPD_taskloop);
  3095. break;
  3096. case OMPD_distribute:
  3097. Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
  3098. EndLoc, VarsWithInheritedDSA);
  3099. break;
  3100. case OMPD_target_update:
  3101. Res = ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc,
  3102. EndLoc, AStmt);
  3103. AllowedNameModifiers.push_back(OMPD_target_update);
  3104. break;
  3105. case OMPD_distribute_parallel_for:
  3106. Res = ActOnOpenMPDistributeParallelForDirective(
  3107. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  3108. AllowedNameModifiers.push_back(OMPD_parallel);
  3109. break;
  3110. case OMPD_distribute_parallel_for_simd:
  3111. Res = ActOnOpenMPDistributeParallelForSimdDirective(
  3112. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  3113. AllowedNameModifiers.push_back(OMPD_parallel);
  3114. break;
  3115. case OMPD_distribute_simd:
  3116. Res = ActOnOpenMPDistributeSimdDirective(
  3117. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  3118. break;
  3119. case OMPD_target_parallel_for_simd:
  3120. Res = ActOnOpenMPTargetParallelForSimdDirective(
  3121. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  3122. AllowedNameModifiers.push_back(OMPD_target);
  3123. AllowedNameModifiers.push_back(OMPD_parallel);
  3124. break;
  3125. case OMPD_target_simd:
  3126. Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
  3127. EndLoc, VarsWithInheritedDSA);
  3128. AllowedNameModifiers.push_back(OMPD_target);
  3129. break;
  3130. case OMPD_teams_distribute:
  3131. Res = ActOnOpenMPTeamsDistributeDirective(
  3132. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  3133. break;
  3134. case OMPD_teams_distribute_simd:
  3135. Res = ActOnOpenMPTeamsDistributeSimdDirective(
  3136. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  3137. break;
  3138. case OMPD_teams_distribute_parallel_for_simd:
  3139. Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
  3140. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  3141. AllowedNameModifiers.push_back(OMPD_parallel);
  3142. break;
  3143. case OMPD_teams_distribute_parallel_for:
  3144. Res = ActOnOpenMPTeamsDistributeParallelForDirective(
  3145. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  3146. AllowedNameModifiers.push_back(OMPD_parallel);
  3147. break;
  3148. case OMPD_target_teams:
  3149. Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
  3150. EndLoc);
  3151. AllowedNameModifiers.push_back(OMPD_target);
  3152. break;
  3153. case OMPD_target_teams_distribute:
  3154. Res = ActOnOpenMPTargetTeamsDistributeDirective(
  3155. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  3156. AllowedNameModifiers.push_back(OMPD_target);
  3157. break;
  3158. case OMPD_target_teams_distribute_parallel_for:
  3159. Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective(
  3160. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  3161. AllowedNameModifiers.push_back(OMPD_target);
  3162. AllowedNameModifiers.push_back(OMPD_parallel);
  3163. break;
  3164. case OMPD_target_teams_distribute_parallel_for_simd:
  3165. Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
  3166. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  3167. AllowedNameModifiers.push_back(OMPD_target);
  3168. AllowedNameModifiers.push_back(OMPD_parallel);
  3169. break;
  3170. case OMPD_target_teams_distribute_simd:
  3171. Res = ActOnOpenMPTargetTeamsDistributeSimdDirective(
  3172. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  3173. AllowedNameModifiers.push_back(OMPD_target);
  3174. break;
  3175. case OMPD_declare_target:
  3176. case OMPD_end_declare_target:
  3177. case OMPD_threadprivate:
  3178. case OMPD_declare_reduction:
  3179. case OMPD_declare_simd:
  3180. llvm_unreachable("OpenMP Directive is not allowed");
  3181. case OMPD_unknown:
  3182. llvm_unreachable("Unknown OpenMP directive");
  3183. }
  3184. for (const auto &P : VarsWithInheritedDSA) {
  3185. Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
  3186. << P.first << P.second->getSourceRange();
  3187. }
  3188. ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound;
  3189. if (!AllowedNameModifiers.empty())
  3190. ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
  3191. ErrorFound;
  3192. if (ErrorFound)
  3193. return StmtError();
  3194. return Res;
  3195. }
  3196. Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
  3197. DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
  3198. ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
  3199. ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
  3200. ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
  3201. assert(Aligneds.size() == Alignments.size());
  3202. assert(Linears.size() == LinModifiers.size());
  3203. assert(Linears.size() == Steps.size());
  3204. if (!DG || DG.get().isNull())
  3205. return DeclGroupPtrTy();
  3206. if (!DG.get().isSingleDecl()) {
  3207. Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd);
  3208. return DG;
  3209. }
  3210. Decl *ADecl = DG.get().getSingleDecl();
  3211. if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
  3212. ADecl = FTD->getTemplatedDecl();
  3213. auto *FD = dyn_cast<FunctionDecl>(ADecl);
  3214. if (!FD) {
  3215. Diag(ADecl->getLocation(), diag::err_omp_function_expected);
  3216. return DeclGroupPtrTy();
  3217. }
  3218. // OpenMP [2.8.2, declare simd construct, Description]
  3219. // The parameter of the simdlen clause must be a constant positive integer
  3220. // expression.
  3221. ExprResult SL;
  3222. if (Simdlen)
  3223. SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
  3224. // OpenMP [2.8.2, declare simd construct, Description]
  3225. // The special this pointer can be used as if was one of the arguments to the
  3226. // function in any of the linear, aligned, or uniform clauses.
  3227. // The uniform clause declares one or more arguments to have an invariant
  3228. // value for all concurrent invocations of the function in the execution of a
  3229. // single SIMD loop.
  3230. llvm::DenseMap<const Decl *, const Expr *> UniformedArgs;
  3231. const Expr *UniformedLinearThis = nullptr;
  3232. for (const Expr *E : Uniforms) {
  3233. E = E->IgnoreParenImpCasts();
  3234. if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
  3235. if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
  3236. if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
  3237. FD->getParamDecl(PVD->getFunctionScopeIndex())
  3238. ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
  3239. UniformedArgs.try_emplace(PVD->getCanonicalDecl(), E);
  3240. continue;
  3241. }
  3242. if (isa<CXXThisExpr>(E)) {
  3243. UniformedLinearThis = E;
  3244. continue;
  3245. }
  3246. Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
  3247. << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
  3248. }
  3249. // OpenMP [2.8.2, declare simd construct, Description]
  3250. // The aligned clause declares that the object to which each list item points
  3251. // is aligned to the number of bytes expressed in the optional parameter of
  3252. // the aligned clause.
  3253. // The special this pointer can be used as if was one of the arguments to the
  3254. // function in any of the linear, aligned, or uniform clauses.
  3255. // The type of list items appearing in the aligned clause must be array,
  3256. // pointer, reference to array, or reference to pointer.
  3257. llvm::DenseMap<const Decl *, const Expr *> AlignedArgs;
  3258. const Expr *AlignedThis = nullptr;
  3259. for (const Expr *E : Aligneds) {
  3260. E = E->IgnoreParenImpCasts();
  3261. if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
  3262. if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
  3263. const VarDecl *CanonPVD = PVD->getCanonicalDecl();
  3264. if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
  3265. FD->getParamDecl(PVD->getFunctionScopeIndex())
  3266. ->getCanonicalDecl() == CanonPVD) {
  3267. // OpenMP [2.8.1, simd construct, Restrictions]
  3268. // A list-item cannot appear in more than one aligned clause.
  3269. if (AlignedArgs.count(CanonPVD) > 0) {
  3270. Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
  3271. << 1 << E->getSourceRange();
  3272. Diag(AlignedArgs[CanonPVD]->getExprLoc(),
  3273. diag::note_omp_explicit_dsa)
  3274. << getOpenMPClauseName(OMPC_aligned);
  3275. continue;
  3276. }
  3277. AlignedArgs[CanonPVD] = E;
  3278. QualType QTy = PVD->getType()
  3279. .getNonReferenceType()
  3280. .getUnqualifiedType()
  3281. .getCanonicalType();
  3282. const Type *Ty = QTy.getTypePtrOrNull();
  3283. if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
  3284. Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
  3285. << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
  3286. Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
  3287. }
  3288. continue;
  3289. }
  3290. }
  3291. if (isa<CXXThisExpr>(E)) {
  3292. if (AlignedThis) {
  3293. Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
  3294. << 2 << E->getSourceRange();
  3295. Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
  3296. << getOpenMPClauseName(OMPC_aligned);
  3297. }
  3298. AlignedThis = E;
  3299. continue;
  3300. }
  3301. Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
  3302. << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
  3303. }
  3304. // The optional parameter of the aligned clause, alignment, must be a constant
  3305. // positive integer expression. If no optional parameter is specified,
  3306. // implementation-defined default alignments for SIMD instructions on the
  3307. // target platforms are assumed.
  3308. SmallVector<const Expr *, 4> NewAligns;
  3309. for (Expr *E : Alignments) {
  3310. ExprResult Align;
  3311. if (E)
  3312. Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
  3313. NewAligns.push_back(Align.get());
  3314. }
  3315. // OpenMP [2.8.2, declare simd construct, Description]
  3316. // The linear clause declares one or more list items to be private to a SIMD
  3317. // lane and to have a linear relationship with respect to the iteration space
  3318. // of a loop.
  3319. // The special this pointer can be used as if was one of the arguments to the
  3320. // function in any of the linear, aligned, or uniform clauses.
  3321. // When a linear-step expression is specified in a linear clause it must be
  3322. // either a constant integer expression or an integer-typed parameter that is
  3323. // specified in a uniform clause on the directive.
  3324. llvm::DenseMap<const Decl *, const Expr *> LinearArgs;
  3325. const bool IsUniformedThis = UniformedLinearThis != nullptr;
  3326. auto MI = LinModifiers.begin();
  3327. for (const Expr *E : Linears) {
  3328. auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
  3329. ++MI;
  3330. E = E->IgnoreParenImpCasts();
  3331. if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
  3332. if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
  3333. const VarDecl *CanonPVD = PVD->getCanonicalDecl();
  3334. if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
  3335. FD->getParamDecl(PVD->getFunctionScopeIndex())
  3336. ->getCanonicalDecl() == CanonPVD) {
  3337. // OpenMP [2.15.3.7, linear Clause, Restrictions]
  3338. // A list-item cannot appear in more than one linear clause.
  3339. if (LinearArgs.count(CanonPVD) > 0) {
  3340. Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
  3341. << getOpenMPClauseName(OMPC_linear)
  3342. << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
  3343. Diag(LinearArgs[CanonPVD]->getExprLoc(),
  3344. diag::note_omp_explicit_dsa)
  3345. << getOpenMPClauseName(OMPC_linear);
  3346. continue;
  3347. }
  3348. // Each argument can appear in at most one uniform or linear clause.
  3349. if (UniformedArgs.count(CanonPVD) > 0) {
  3350. Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
  3351. << getOpenMPClauseName(OMPC_linear)
  3352. << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
  3353. Diag(UniformedArgs[CanonPVD]->getExprLoc(),
  3354. diag::note_omp_explicit_dsa)
  3355. << getOpenMPClauseName(OMPC_uniform);
  3356. continue;
  3357. }
  3358. LinearArgs[CanonPVD] = E;
  3359. if (E->isValueDependent() || E->isTypeDependent() ||
  3360. E->isInstantiationDependent() ||
  3361. E->containsUnexpandedParameterPack())
  3362. continue;
  3363. (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
  3364. PVD->getOriginalType());
  3365. continue;
  3366. }
  3367. }
  3368. if (isa<CXXThisExpr>(E)) {
  3369. if (UniformedLinearThis) {
  3370. Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
  3371. << getOpenMPClauseName(OMPC_linear)
  3372. << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
  3373. << E->getSourceRange();
  3374. Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
  3375. << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
  3376. : OMPC_linear);
  3377. continue;
  3378. }
  3379. UniformedLinearThis = E;
  3380. if (E->isValueDependent() || E->isTypeDependent() ||
  3381. E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
  3382. continue;
  3383. (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
  3384. E->getType());
  3385. continue;
  3386. }
  3387. Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
  3388. << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
  3389. }
  3390. Expr *Step = nullptr;
  3391. Expr *NewStep = nullptr;
  3392. SmallVector<Expr *, 4> NewSteps;
  3393. for (Expr *E : Steps) {
  3394. // Skip the same step expression, it was checked already.
  3395. if (Step == E || !E) {
  3396. NewSteps.push_back(E ? NewStep : nullptr);
  3397. continue;
  3398. }
  3399. Step = E;
  3400. if (const auto *DRE = dyn_cast<DeclRefExpr>(Step))
  3401. if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
  3402. const VarDecl *CanonPVD = PVD->getCanonicalDecl();
  3403. if (UniformedArgs.count(CanonPVD) == 0) {
  3404. Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
  3405. << Step->getSourceRange();
  3406. } else if (E->isValueDependent() || E->isTypeDependent() ||
  3407. E->isInstantiationDependent() ||
  3408. E->containsUnexpandedParameterPack() ||
  3409. CanonPVD->getType()->hasIntegerRepresentation()) {
  3410. NewSteps.push_back(Step);
  3411. } else {
  3412. Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
  3413. << Step->getSourceRange();
  3414. }
  3415. continue;
  3416. }
  3417. NewStep = Step;
  3418. if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
  3419. !Step->isInstantiationDependent() &&
  3420. !Step->containsUnexpandedParameterPack()) {
  3421. NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
  3422. .get();
  3423. if (NewStep)
  3424. NewStep = VerifyIntegerConstantExpression(NewStep).get();
  3425. }
  3426. NewSteps.push_back(NewStep);
  3427. }
  3428. auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
  3429. Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
  3430. Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
  3431. const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
  3432. const_cast<Expr **>(Linears.data()), Linears.size(),
  3433. const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
  3434. NewSteps.data(), NewSteps.size(), SR);
  3435. ADecl->addAttr(NewAttr);
  3436. return ConvertDeclToDeclGroup(ADecl);
  3437. }
  3438. StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
  3439. Stmt *AStmt,
  3440. SourceLocation StartLoc,
  3441. SourceLocation EndLoc) {
  3442. if (!AStmt)
  3443. return StmtError();
  3444. auto *CS = cast<CapturedStmt>(AStmt);
  3445. // 1.2.2 OpenMP Language Terminology
  3446. // Structured block - An executable statement with a single entry at the
  3447. // top and a single exit at the bottom.
  3448. // The point of exit cannot be a branch out of the structured block.
  3449. // longjmp() and throw() must not violate the entry/exit criteria.
  3450. CS->getCapturedDecl()->setNothrow();
  3451. setFunctionHasBranchProtectedScope();
  3452. return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
  3453. DSAStack->isCancelRegion());
  3454. }
  3455. namespace {
  3456. /// \brief Helper class for checking canonical form of the OpenMP loops and
  3457. /// extracting iteration space of each loop in the loop nest, that will be used
  3458. /// for IR generation.
  3459. class OpenMPIterationSpaceChecker {
  3460. /// \brief Reference to Sema.
  3461. Sema &SemaRef;
  3462. /// \brief A location for diagnostics (when there is no some better location).
  3463. SourceLocation DefaultLoc;
  3464. /// \brief A location for diagnostics (when increment is not compatible).
  3465. SourceLocation ConditionLoc;
  3466. /// \brief A source location for referring to loop init later.
  3467. SourceRange InitSrcRange;
  3468. /// \brief A source location for referring to condition later.
  3469. SourceRange ConditionSrcRange;
  3470. /// \brief A source location for referring to increment later.
  3471. SourceRange IncrementSrcRange;
  3472. /// \brief Loop variable.
  3473. ValueDecl *LCDecl = nullptr;
  3474. /// \brief Reference to loop variable.
  3475. Expr *LCRef = nullptr;
  3476. /// \brief Lower bound (initializer for the var).
  3477. Expr *LB = nullptr;
  3478. /// \brief Upper bound.
  3479. Expr *UB = nullptr;
  3480. /// \brief Loop step (increment).
  3481. Expr *Step = nullptr;
  3482. /// \brief This flag is true when condition is one of:
  3483. /// Var < UB
  3484. /// Var <= UB
  3485. /// UB > Var
  3486. /// UB >= Var
  3487. bool TestIsLessOp = false;
  3488. /// \brief This flag is true when condition is strict ( < or > ).
  3489. bool TestIsStrictOp = false;
  3490. /// \brief This flag is true when step is subtracted on each iteration.
  3491. bool SubtractStep = false;
  3492. public:
  3493. OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
  3494. : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {}
  3495. /// \brief Check init-expr for canonical loop form and save loop counter
  3496. /// variable - #Var and its initialization value - #LB.
  3497. bool checkAndSetInit(Stmt *S, bool EmitDiags = true);
  3498. /// \brief Check test-expr for canonical form, save upper-bound (#UB), flags
  3499. /// for less/greater and for strict/non-strict comparison.
  3500. bool checkAndSetCond(Expr *S);
  3501. /// \brief Check incr-expr for canonical loop form and return true if it
  3502. /// does not conform, otherwise save loop step (#Step).
  3503. bool checkAndSetInc(Expr *S);
  3504. /// \brief Return the loop counter variable.
  3505. ValueDecl *getLoopDecl() const { return LCDecl; }
  3506. /// \brief Return the reference expression to loop counter variable.
  3507. Expr *getLoopDeclRefExpr() const { return LCRef; }
  3508. /// \brief Source range of the loop init.
  3509. SourceRange getInitSrcRange() const { return InitSrcRange; }
  3510. /// \brief Source range of the loop condition.
  3511. SourceRange getConditionSrcRange() const { return ConditionSrcRange; }
  3512. /// \brief Source range of the loop increment.
  3513. SourceRange getIncrementSrcRange() const { return IncrementSrcRange; }
  3514. /// \brief True if the step should be subtracted.
  3515. bool shouldSubtractStep() const { return SubtractStep; }
  3516. /// \brief Build the expression to calculate the number of iterations.
  3517. Expr *buildNumIterations(
  3518. Scope *S, const bool LimitedType,
  3519. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
  3520. /// \brief Build the precondition expression for the loops.
  3521. Expr *
  3522. buildPreCond(Scope *S, Expr *Cond,
  3523. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
  3524. /// \brief Build reference expression to the counter be used for codegen.
  3525. DeclRefExpr *
  3526. buildCounterVar(llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
  3527. DSAStackTy &DSA) const;
  3528. /// \brief Build reference expression to the private counter be used for
  3529. /// codegen.
  3530. Expr *buildPrivateCounterVar() const;
  3531. /// \brief Build initialization of the counter be used for codegen.
  3532. Expr *buildCounterInit() const;
  3533. /// \brief Build step of the counter be used for codegen.
  3534. Expr *buildCounterStep() const;
  3535. /// \brief Return true if any expression is dependent.
  3536. bool dependent() const;
  3537. private:
  3538. /// \brief Check the right-hand side of an assignment in the increment
  3539. /// expression.
  3540. bool checkAndSetIncRHS(Expr *RHS);
  3541. /// \brief Helper to set loop counter variable and its initializer.
  3542. bool setLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB);
  3543. /// \brief Helper to set upper bound.
  3544. bool setUB(Expr *NewUB, bool LessOp, bool StrictOp, SourceRange SR,
  3545. SourceLocation SL);
  3546. /// \brief Helper to set loop increment.
  3547. bool setStep(Expr *NewStep, bool Subtract);
  3548. };
  3549. bool OpenMPIterationSpaceChecker::dependent() const {
  3550. if (!LCDecl) {
  3551. assert(!LB && !UB && !Step);
  3552. return false;
  3553. }
  3554. return LCDecl->getType()->isDependentType() ||
  3555. (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
  3556. (Step && Step->isValueDependent());
  3557. }
  3558. bool OpenMPIterationSpaceChecker::setLCDeclAndLB(ValueDecl *NewLCDecl,
  3559. Expr *NewLCRefExpr,
  3560. Expr *NewLB) {
  3561. // State consistency checking to ensure correct usage.
  3562. assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
  3563. UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
  3564. if (!NewLCDecl || !NewLB)
  3565. return true;
  3566. LCDecl = getCanonicalDecl(NewLCDecl);
  3567. LCRef = NewLCRefExpr;
  3568. if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
  3569. if (const CXXConstructorDecl *Ctor = CE->getConstructor())
  3570. if ((Ctor->isCopyOrMoveConstructor() ||
  3571. Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
  3572. CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
  3573. NewLB = CE->getArg(0)->IgnoreParenImpCasts();
  3574. LB = NewLB;
  3575. return false;
  3576. }
  3577. bool OpenMPIterationSpaceChecker::setUB(Expr *NewUB, bool LessOp, bool StrictOp,
  3578. SourceRange SR, SourceLocation SL) {
  3579. // State consistency checking to ensure correct usage.
  3580. assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
  3581. Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
  3582. if (!NewUB)
  3583. return true;
  3584. UB = NewUB;
  3585. TestIsLessOp = LessOp;
  3586. TestIsStrictOp = StrictOp;
  3587. ConditionSrcRange = SR;
  3588. ConditionLoc = SL;
  3589. return false;
  3590. }
  3591. bool OpenMPIterationSpaceChecker::setStep(Expr *NewStep, bool Subtract) {
  3592. // State consistency checking to ensure correct usage.
  3593. assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
  3594. if (!NewStep)
  3595. return true;
  3596. if (!NewStep->isValueDependent()) {
  3597. // Check that the step is integer expression.
  3598. SourceLocation StepLoc = NewStep->getLocStart();
  3599. ExprResult Val = SemaRef.PerformOpenMPImplicitIntegerConversion(
  3600. StepLoc, getExprAsWritten(NewStep));
  3601. if (Val.isInvalid())
  3602. return true;
  3603. NewStep = Val.get();
  3604. // OpenMP [2.6, Canonical Loop Form, Restrictions]
  3605. // If test-expr is of form var relational-op b and relational-op is < or
  3606. // <= then incr-expr must cause var to increase on each iteration of the
  3607. // loop. If test-expr is of form var relational-op b and relational-op is
  3608. // > or >= then incr-expr must cause var to decrease on each iteration of
  3609. // the loop.
  3610. // If test-expr is of form b relational-op var and relational-op is < or
  3611. // <= then incr-expr must cause var to decrease on each iteration of the
  3612. // loop. If test-expr is of form b relational-op var and relational-op is
  3613. // > or >= then incr-expr must cause var to increase on each iteration of
  3614. // the loop.
  3615. llvm::APSInt Result;
  3616. bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
  3617. bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
  3618. bool IsConstNeg =
  3619. IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
  3620. bool IsConstPos =
  3621. IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
  3622. bool IsConstZero = IsConstant && !Result.getBoolValue();
  3623. if (UB && (IsConstZero ||
  3624. (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract))
  3625. : (IsConstPos || (IsUnsigned && !Subtract))))) {
  3626. SemaRef.Diag(NewStep->getExprLoc(),
  3627. diag::err_omp_loop_incr_not_compatible)
  3628. << LCDecl << TestIsLessOp << NewStep->getSourceRange();
  3629. SemaRef.Diag(ConditionLoc,
  3630. diag::note_omp_loop_cond_requres_compatible_incr)
  3631. << TestIsLessOp << ConditionSrcRange;
  3632. return true;
  3633. }
  3634. if (TestIsLessOp == Subtract) {
  3635. NewStep =
  3636. SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
  3637. .get();
  3638. Subtract = !Subtract;
  3639. }
  3640. }
  3641. Step = NewStep;
  3642. SubtractStep = Subtract;
  3643. return false;
  3644. }
  3645. bool OpenMPIterationSpaceChecker::checkAndSetInit(Stmt *S, bool EmitDiags) {
  3646. // Check init-expr for canonical loop form and save loop counter
  3647. // variable - #Var and its initialization value - #LB.
  3648. // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
  3649. // var = lb
  3650. // integer-type var = lb
  3651. // random-access-iterator-type var = lb
  3652. // pointer-type var = lb
  3653. //
  3654. if (!S) {
  3655. if (EmitDiags) {
  3656. SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
  3657. }
  3658. return true;
  3659. }
  3660. if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
  3661. if (!ExprTemp->cleanupsHaveSideEffects())
  3662. S = ExprTemp->getSubExpr();
  3663. InitSrcRange = S->getSourceRange();
  3664. if (Expr *E = dyn_cast<Expr>(S))
  3665. S = E->IgnoreParens();
  3666. if (auto *BO = dyn_cast<BinaryOperator>(S)) {
  3667. if (BO->getOpcode() == BO_Assign) {
  3668. Expr *LHS = BO->getLHS()->IgnoreParens();
  3669. if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
  3670. if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
  3671. if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
  3672. return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
  3673. return setLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS());
  3674. }
  3675. if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
  3676. if (ME->isArrow() &&
  3677. isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
  3678. return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
  3679. }
  3680. }
  3681. } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
  3682. if (DS->isSingleDecl()) {
  3683. if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
  3684. if (Var->hasInit() && !Var->getType()->isReferenceType()) {
  3685. // Accept non-canonical init form here but emit ext. warning.
  3686. if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
  3687. SemaRef.Diag(S->getLocStart(),
  3688. diag::ext_omp_loop_not_canonical_init)
  3689. << S->getSourceRange();
  3690. return setLCDeclAndLB(Var, nullptr, Var->getInit());
  3691. }
  3692. }
  3693. }
  3694. } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
  3695. if (CE->getOperator() == OO_Equal) {
  3696. Expr *LHS = CE->getArg(0);
  3697. if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
  3698. if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
  3699. if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
  3700. return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
  3701. return setLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1));
  3702. }
  3703. if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
  3704. if (ME->isArrow() &&
  3705. isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
  3706. return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
  3707. }
  3708. }
  3709. }
  3710. if (dependent() || SemaRef.CurContext->isDependentContext())
  3711. return false;
  3712. if (EmitDiags) {
  3713. SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_init)
  3714. << S->getSourceRange();
  3715. }
  3716. return true;
  3717. }
  3718. /// \brief Ignore parenthesizes, implicit casts, copy constructor and return the
  3719. /// variable (which may be the loop variable) if possible.
  3720. static const ValueDecl *getInitLCDecl(const Expr *E) {
  3721. if (!E)
  3722. return nullptr;
  3723. E = getExprAsWritten(E);
  3724. if (const auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
  3725. if (const CXXConstructorDecl *Ctor = CE->getConstructor())
  3726. if ((Ctor->isCopyOrMoveConstructor() ||
  3727. Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
  3728. CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
  3729. E = CE->getArg(0)->IgnoreParenImpCasts();
  3730. if (const auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
  3731. if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
  3732. return getCanonicalDecl(VD);
  3733. }
  3734. if (const auto *ME = dyn_cast_or_null<MemberExpr>(E))
  3735. if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
  3736. return getCanonicalDecl(ME->getMemberDecl());
  3737. return nullptr;
  3738. }
  3739. bool OpenMPIterationSpaceChecker::checkAndSetCond(Expr *S) {
  3740. // Check test-expr for canonical form, save upper-bound UB, flags for
  3741. // less/greater and for strict/non-strict comparison.
  3742. // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
  3743. // var relational-op b
  3744. // b relational-op var
  3745. //
  3746. if (!S) {
  3747. SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << LCDecl;
  3748. return true;
  3749. }
  3750. S = getExprAsWritten(S);
  3751. SourceLocation CondLoc = S->getLocStart();
  3752. if (auto *BO = dyn_cast<BinaryOperator>(S)) {
  3753. if (BO->isRelationalOp()) {
  3754. if (getInitLCDecl(BO->getLHS()) == LCDecl)
  3755. return setUB(BO->getRHS(),
  3756. (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
  3757. (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
  3758. BO->getSourceRange(), BO->getOperatorLoc());
  3759. if (getInitLCDecl(BO->getRHS()) == LCDecl)
  3760. return setUB(BO->getLHS(),
  3761. (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
  3762. (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
  3763. BO->getSourceRange(), BO->getOperatorLoc());
  3764. }
  3765. } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
  3766. if (CE->getNumArgs() == 2) {
  3767. auto Op = CE->getOperator();
  3768. switch (Op) {
  3769. case OO_Greater:
  3770. case OO_GreaterEqual:
  3771. case OO_Less:
  3772. case OO_LessEqual:
  3773. if (getInitLCDecl(CE->getArg(0)) == LCDecl)
  3774. return setUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
  3775. Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
  3776. CE->getOperatorLoc());
  3777. if (getInitLCDecl(CE->getArg(1)) == LCDecl)
  3778. return setUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
  3779. Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
  3780. CE->getOperatorLoc());
  3781. break;
  3782. default:
  3783. break;
  3784. }
  3785. }
  3786. }
  3787. if (dependent() || SemaRef.CurContext->isDependentContext())
  3788. return false;
  3789. SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
  3790. << S->getSourceRange() << LCDecl;
  3791. return true;
  3792. }
  3793. bool OpenMPIterationSpaceChecker::checkAndSetIncRHS(Expr *RHS) {
  3794. // RHS of canonical loop form increment can be:
  3795. // var + incr
  3796. // incr + var
  3797. // var - incr
  3798. //
  3799. RHS = RHS->IgnoreParenImpCasts();
  3800. if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
  3801. if (BO->isAdditiveOp()) {
  3802. bool IsAdd = BO->getOpcode() == BO_Add;
  3803. if (getInitLCDecl(BO->getLHS()) == LCDecl)
  3804. return setStep(BO->getRHS(), !IsAdd);
  3805. if (IsAdd && getInitLCDecl(BO->getRHS()) == LCDecl)
  3806. return setStep(BO->getLHS(), /*Subtract=*/false);
  3807. }
  3808. } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
  3809. bool IsAdd = CE->getOperator() == OO_Plus;
  3810. if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
  3811. if (getInitLCDecl(CE->getArg(0)) == LCDecl)
  3812. return setStep(CE->getArg(1), !IsAdd);
  3813. if (IsAdd && getInitLCDecl(CE->getArg(1)) == LCDecl)
  3814. return setStep(CE->getArg(0), /*Subtract=*/false);
  3815. }
  3816. }
  3817. if (dependent() || SemaRef.CurContext->isDependentContext())
  3818. return false;
  3819. SemaRef.Diag(RHS->getLocStart(), diag::err_omp_loop_not_canonical_incr)
  3820. << RHS->getSourceRange() << LCDecl;
  3821. return true;
  3822. }
  3823. bool OpenMPIterationSpaceChecker::checkAndSetInc(Expr *S) {
  3824. // Check incr-expr for canonical loop form and return true if it
  3825. // does not conform.
  3826. // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
  3827. // ++var
  3828. // var++
  3829. // --var
  3830. // var--
  3831. // var += incr
  3832. // var -= incr
  3833. // var = var + incr
  3834. // var = incr + var
  3835. // var = var - incr
  3836. //
  3837. if (!S) {
  3838. SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
  3839. return true;
  3840. }
  3841. if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
  3842. if (!ExprTemp->cleanupsHaveSideEffects())
  3843. S = ExprTemp->getSubExpr();
  3844. IncrementSrcRange = S->getSourceRange();
  3845. S = S->IgnoreParens();
  3846. if (auto *UO = dyn_cast<UnaryOperator>(S)) {
  3847. if (UO->isIncrementDecrementOp() &&
  3848. getInitLCDecl(UO->getSubExpr()) == LCDecl)
  3849. return setStep(SemaRef
  3850. .ActOnIntegerConstant(UO->getLocStart(),
  3851. (UO->isDecrementOp() ? -1 : 1))
  3852. .get(),
  3853. /*Subtract=*/false);
  3854. } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
  3855. switch (BO->getOpcode()) {
  3856. case BO_AddAssign:
  3857. case BO_SubAssign:
  3858. if (getInitLCDecl(BO->getLHS()) == LCDecl)
  3859. return setStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
  3860. break;
  3861. case BO_Assign:
  3862. if (getInitLCDecl(BO->getLHS()) == LCDecl)
  3863. return checkAndSetIncRHS(BO->getRHS());
  3864. break;
  3865. default:
  3866. break;
  3867. }
  3868. } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
  3869. switch (CE->getOperator()) {
  3870. case OO_PlusPlus:
  3871. case OO_MinusMinus:
  3872. if (getInitLCDecl(CE->getArg(0)) == LCDecl)
  3873. return setStep(SemaRef
  3874. .ActOnIntegerConstant(
  3875. CE->getLocStart(),
  3876. ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
  3877. .get(),
  3878. /*Subtract=*/false);
  3879. break;
  3880. case OO_PlusEqual:
  3881. case OO_MinusEqual:
  3882. if (getInitLCDecl(CE->getArg(0)) == LCDecl)
  3883. return setStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
  3884. break;
  3885. case OO_Equal:
  3886. if (getInitLCDecl(CE->getArg(0)) == LCDecl)
  3887. return checkAndSetIncRHS(CE->getArg(1));
  3888. break;
  3889. default:
  3890. break;
  3891. }
  3892. }
  3893. if (dependent() || SemaRef.CurContext->isDependentContext())
  3894. return false;
  3895. SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_incr)
  3896. << S->getSourceRange() << LCDecl;
  3897. return true;
  3898. }
  3899. static ExprResult
  3900. tryBuildCapture(Sema &SemaRef, Expr *Capture,
  3901. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
  3902. if (SemaRef.CurContext->isDependentContext())
  3903. return ExprResult(Capture);
  3904. if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
  3905. return SemaRef.PerformImplicitConversion(
  3906. Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
  3907. /*AllowExplicit=*/true);
  3908. auto I = Captures.find(Capture);
  3909. if (I != Captures.end())
  3910. return buildCapture(SemaRef, Capture, I->second);
  3911. DeclRefExpr *Ref = nullptr;
  3912. ExprResult Res = buildCapture(SemaRef, Capture, Ref);
  3913. Captures[Capture] = Ref;
  3914. return Res;
  3915. }
  3916. /// \brief Build the expression to calculate the number of iterations.
  3917. Expr *OpenMPIterationSpaceChecker::buildNumIterations(
  3918. Scope *S, const bool LimitedType,
  3919. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
  3920. ExprResult Diff;
  3921. QualType VarType = LCDecl->getType().getNonReferenceType();
  3922. if (VarType->isIntegerType() || VarType->isPointerType() ||
  3923. SemaRef.getLangOpts().CPlusPlus) {
  3924. // Upper - Lower
  3925. Expr *UBExpr = TestIsLessOp ? UB : LB;
  3926. Expr *LBExpr = TestIsLessOp ? LB : UB;
  3927. Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
  3928. Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
  3929. if (!Upper || !Lower)
  3930. return nullptr;
  3931. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
  3932. if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
  3933. // BuildBinOp already emitted error, this one is to point user to upper
  3934. // and lower bound, and to tell what is passed to 'operator-'.
  3935. SemaRef.Diag(Upper->getLocStart(), diag::err_omp_loop_diff_cxx)
  3936. << Upper->getSourceRange() << Lower->getSourceRange();
  3937. return nullptr;
  3938. }
  3939. }
  3940. if (!Diff.isUsable())
  3941. return nullptr;
  3942. // Upper - Lower [- 1]
  3943. if (TestIsStrictOp)
  3944. Diff = SemaRef.BuildBinOp(
  3945. S, DefaultLoc, BO_Sub, Diff.get(),
  3946. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
  3947. if (!Diff.isUsable())
  3948. return nullptr;
  3949. // Upper - Lower [- 1] + Step
  3950. ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
  3951. if (!NewStep.isUsable())
  3952. return nullptr;
  3953. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
  3954. if (!Diff.isUsable())
  3955. return nullptr;
  3956. // Parentheses (for dumping/debugging purposes only).
  3957. Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
  3958. if (!Diff.isUsable())
  3959. return nullptr;
  3960. // (Upper - Lower [- 1] + Step) / Step
  3961. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
  3962. if (!Diff.isUsable())
  3963. return nullptr;
  3964. // OpenMP runtime requires 32-bit or 64-bit loop variables.
  3965. QualType Type = Diff.get()->getType();
  3966. ASTContext &C = SemaRef.Context;
  3967. bool UseVarType = VarType->hasIntegerRepresentation() &&
  3968. C.getTypeSize(Type) > C.getTypeSize(VarType);
  3969. if (!Type->isIntegerType() || UseVarType) {
  3970. unsigned NewSize =
  3971. UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
  3972. bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
  3973. : Type->hasSignedIntegerRepresentation();
  3974. Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
  3975. if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
  3976. Diff = SemaRef.PerformImplicitConversion(
  3977. Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
  3978. if (!Diff.isUsable())
  3979. return nullptr;
  3980. }
  3981. }
  3982. if (LimitedType) {
  3983. unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
  3984. if (NewSize != C.getTypeSize(Type)) {
  3985. if (NewSize < C.getTypeSize(Type)) {
  3986. assert(NewSize == 64 && "incorrect loop var size");
  3987. SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
  3988. << InitSrcRange << ConditionSrcRange;
  3989. }
  3990. QualType NewType = C.getIntTypeForBitwidth(
  3991. NewSize, Type->hasSignedIntegerRepresentation() ||
  3992. C.getTypeSize(Type) < NewSize);
  3993. if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
  3994. Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
  3995. Sema::AA_Converting, true);
  3996. if (!Diff.isUsable())
  3997. return nullptr;
  3998. }
  3999. }
  4000. }
  4001. return Diff.get();
  4002. }
  4003. Expr *OpenMPIterationSpaceChecker::buildPreCond(
  4004. Scope *S, Expr *Cond,
  4005. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
  4006. // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
  4007. bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
  4008. SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
  4009. ExprResult NewLB = tryBuildCapture(SemaRef, LB, Captures);
  4010. ExprResult NewUB = tryBuildCapture(SemaRef, UB, Captures);
  4011. if (!NewLB.isUsable() || !NewUB.isUsable())
  4012. return nullptr;
  4013. ExprResult CondExpr =
  4014. SemaRef.BuildBinOp(S, DefaultLoc,
  4015. TestIsLessOp ? (TestIsStrictOp ? BO_LT : BO_LE)
  4016. : (TestIsStrictOp ? BO_GT : BO_GE),
  4017. NewLB.get(), NewUB.get());
  4018. if (CondExpr.isUsable()) {
  4019. if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
  4020. SemaRef.Context.BoolTy))
  4021. CondExpr = SemaRef.PerformImplicitConversion(
  4022. CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
  4023. /*AllowExplicit=*/true);
  4024. }
  4025. SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
  4026. // Otherwise use original loop conditon and evaluate it in runtime.
  4027. return CondExpr.isUsable() ? CondExpr.get() : Cond;
  4028. }
  4029. /// \brief Build reference expression to the counter be used for codegen.
  4030. DeclRefExpr *OpenMPIterationSpaceChecker::buildCounterVar(
  4031. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, DSAStackTy &DSA) const {
  4032. auto *VD = dyn_cast<VarDecl>(LCDecl);
  4033. if (!VD) {
  4034. VD = SemaRef.isOpenMPCapturedDecl(LCDecl);
  4035. DeclRefExpr *Ref = buildDeclRefExpr(
  4036. SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
  4037. const DSAStackTy::DSAVarData Data =
  4038. DSA.getTopDSA(LCDecl, /*FromParent=*/false);
  4039. // If the loop control decl is explicitly marked as private, do not mark it
  4040. // as captured again.
  4041. if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
  4042. Captures.insert(std::make_pair(LCRef, Ref));
  4043. return Ref;
  4044. }
  4045. return buildDeclRefExpr(SemaRef, VD, VD->getType().getNonReferenceType(),
  4046. DefaultLoc);
  4047. }
  4048. Expr *OpenMPIterationSpaceChecker::buildPrivateCounterVar() const {
  4049. if (LCDecl && !LCDecl->isInvalidDecl()) {
  4050. QualType Type = LCDecl->getType().getNonReferenceType();
  4051. VarDecl *PrivateVar = buildVarDecl(
  4052. SemaRef, DefaultLoc, Type, LCDecl->getName(),
  4053. LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr,
  4054. isa<VarDecl>(LCDecl)
  4055. ? buildDeclRefExpr(SemaRef, cast<VarDecl>(LCDecl), Type, DefaultLoc)
  4056. : nullptr);
  4057. if (PrivateVar->isInvalidDecl())
  4058. return nullptr;
  4059. return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
  4060. }
  4061. return nullptr;
  4062. }
  4063. /// \brief Build initialization of the counter to be used for codegen.
  4064. Expr *OpenMPIterationSpaceChecker::buildCounterInit() const { return LB; }
  4065. /// \brief Build step of the counter be used for codegen.
  4066. Expr *OpenMPIterationSpaceChecker::buildCounterStep() const { return Step; }
  4067. /// \brief Iteration space of a single for loop.
  4068. struct LoopIterationSpace final {
  4069. /// \brief Condition of the loop.
  4070. Expr *PreCond = nullptr;
  4071. /// \brief This expression calculates the number of iterations in the loop.
  4072. /// It is always possible to calculate it before starting the loop.
  4073. Expr *NumIterations = nullptr;
  4074. /// \brief The loop counter variable.
  4075. Expr *CounterVar = nullptr;
  4076. /// \brief Private loop counter variable.
  4077. Expr *PrivateCounterVar = nullptr;
  4078. /// \brief This is initializer for the initial value of #CounterVar.
  4079. Expr *CounterInit = nullptr;
  4080. /// \brief This is step for the #CounterVar used to generate its update:
  4081. /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
  4082. Expr *CounterStep = nullptr;
  4083. /// \brief Should step be subtracted?
  4084. bool Subtract = false;
  4085. /// \brief Source range of the loop init.
  4086. SourceRange InitSrcRange;
  4087. /// \brief Source range of the loop condition.
  4088. SourceRange CondSrcRange;
  4089. /// \brief Source range of the loop increment.
  4090. SourceRange IncSrcRange;
  4091. };
  4092. } // namespace
  4093. void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
  4094. assert(getLangOpts().OpenMP && "OpenMP is not active.");
  4095. assert(Init && "Expected loop in canonical form.");
  4096. unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
  4097. if (AssociatedLoops > 0 &&
  4098. isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
  4099. OpenMPIterationSpaceChecker ISC(*this, ForLoc);
  4100. if (!ISC.checkAndSetInit(Init, /*EmitDiags=*/false)) {
  4101. if (ValueDecl *D = ISC.getLoopDecl()) {
  4102. auto *VD = dyn_cast<VarDecl>(D);
  4103. if (!VD) {
  4104. if (VarDecl *Private = isOpenMPCapturedDecl(D)) {
  4105. VD = Private;
  4106. } else {
  4107. DeclRefExpr *Ref = buildCapture(*this, D, ISC.getLoopDeclRefExpr(),
  4108. /*WithInit=*/false);
  4109. VD = cast<VarDecl>(Ref->getDecl());
  4110. }
  4111. }
  4112. DSAStack->addLoopControlVariable(D, VD);
  4113. }
  4114. }
  4115. DSAStack->setAssociatedLoops(AssociatedLoops - 1);
  4116. }
  4117. }
  4118. /// \brief Called on a for stmt to check and extract its iteration space
  4119. /// for further processing (such as collapsing).
  4120. static bool checkOpenMPIterationSpace(
  4121. OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
  4122. unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
  4123. Expr *CollapseLoopCountExpr, Expr *OrderedLoopCountExpr,
  4124. Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
  4125. LoopIterationSpace &ResultIterSpace,
  4126. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
  4127. // OpenMP [2.6, Canonical Loop Form]
  4128. // for (init-expr; test-expr; incr-expr) structured-block
  4129. auto *For = dyn_cast_or_null<ForStmt>(S);
  4130. if (!For) {
  4131. SemaRef.Diag(S->getLocStart(), diag::err_omp_not_for)
  4132. << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
  4133. << getOpenMPDirectiveName(DKind) << NestedLoopCount
  4134. << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
  4135. if (NestedLoopCount > 1) {
  4136. if (CollapseLoopCountExpr && OrderedLoopCountExpr)
  4137. SemaRef.Diag(DSA.getConstructLoc(),
  4138. diag::note_omp_collapse_ordered_expr)
  4139. << 2 << CollapseLoopCountExpr->getSourceRange()
  4140. << OrderedLoopCountExpr->getSourceRange();
  4141. else if (CollapseLoopCountExpr)
  4142. SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
  4143. diag::note_omp_collapse_ordered_expr)
  4144. << 0 << CollapseLoopCountExpr->getSourceRange();
  4145. else
  4146. SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
  4147. diag::note_omp_collapse_ordered_expr)
  4148. << 1 << OrderedLoopCountExpr->getSourceRange();
  4149. }
  4150. return true;
  4151. }
  4152. assert(For->getBody());
  4153. OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
  4154. // Check init.
  4155. Stmt *Init = For->getInit();
  4156. if (ISC.checkAndSetInit(Init))
  4157. return true;
  4158. bool HasErrors = false;
  4159. // Check loop variable's type.
  4160. if (ValueDecl *LCDecl = ISC.getLoopDecl()) {
  4161. Expr *LoopDeclRefExpr = ISC.getLoopDeclRefExpr();
  4162. // OpenMP [2.6, Canonical Loop Form]
  4163. // Var is one of the following:
  4164. // A variable of signed or unsigned integer type.
  4165. // For C++, a variable of a random access iterator type.
  4166. // For C, a variable of a pointer type.
  4167. QualType VarType = LCDecl->getType().getNonReferenceType();
  4168. if (!VarType->isDependentType() && !VarType->isIntegerType() &&
  4169. !VarType->isPointerType() &&
  4170. !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
  4171. SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_variable_type)
  4172. << SemaRef.getLangOpts().CPlusPlus;
  4173. HasErrors = true;
  4174. }
  4175. // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
  4176. // a Construct
  4177. // The loop iteration variable(s) in the associated for-loop(s) of a for or
  4178. // parallel for construct is (are) private.
  4179. // The loop iteration variable in the associated for-loop of a simd
  4180. // construct with just one associated for-loop is linear with a
  4181. // constant-linear-step that is the increment of the associated for-loop.
  4182. // Exclude loop var from the list of variables with implicitly defined data
  4183. // sharing attributes.
  4184. VarsWithImplicitDSA.erase(LCDecl);
  4185. // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
  4186. // in a Construct, C/C++].
  4187. // The loop iteration variable in the associated for-loop of a simd
  4188. // construct with just one associated for-loop may be listed in a linear
  4189. // clause with a constant-linear-step that is the increment of the
  4190. // associated for-loop.
  4191. // The loop iteration variable(s) in the associated for-loop(s) of a for or
  4192. // parallel for construct may be listed in a private or lastprivate clause.
  4193. DSAStackTy::DSAVarData DVar = DSA.getTopDSA(LCDecl, false);
  4194. // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
  4195. // declared in the loop and it is predetermined as a private.
  4196. OpenMPClauseKind PredeterminedCKind =
  4197. isOpenMPSimdDirective(DKind)
  4198. ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
  4199. : OMPC_private;
  4200. if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
  4201. DVar.CKind != PredeterminedCKind) ||
  4202. ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
  4203. isOpenMPDistributeDirective(DKind)) &&
  4204. !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
  4205. DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
  4206. (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
  4207. SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_var_dsa)
  4208. << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
  4209. << getOpenMPClauseName(PredeterminedCKind);
  4210. if (DVar.RefExpr == nullptr)
  4211. DVar.CKind = PredeterminedCKind;
  4212. reportOriginalDsa(SemaRef, &DSA, LCDecl, DVar, /*IsLoopIterVar=*/true);
  4213. HasErrors = true;
  4214. } else if (LoopDeclRefExpr != nullptr) {
  4215. // Make the loop iteration variable private (for worksharing constructs),
  4216. // linear (for simd directives with the only one associated loop) or
  4217. // lastprivate (for simd directives with several collapsed or ordered
  4218. // loops).
  4219. if (DVar.CKind == OMPC_unknown)
  4220. DVar = DSA.hasDSA(LCDecl, isOpenMPPrivate,
  4221. [](OpenMPDirectiveKind) -> bool { return true; },
  4222. /*FromParent=*/false);
  4223. DSA.addDSA(LCDecl, LoopDeclRefExpr, PredeterminedCKind);
  4224. }
  4225. assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
  4226. // Check test-expr.
  4227. HasErrors |= ISC.checkAndSetCond(For->getCond());
  4228. // Check incr-expr.
  4229. HasErrors |= ISC.checkAndSetInc(For->getInc());
  4230. }
  4231. if (ISC.dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
  4232. return HasErrors;
  4233. // Build the loop's iteration space representation.
  4234. ResultIterSpace.PreCond =
  4235. ISC.buildPreCond(DSA.getCurScope(), For->getCond(), Captures);
  4236. ResultIterSpace.NumIterations = ISC.buildNumIterations(
  4237. DSA.getCurScope(),
  4238. (isOpenMPWorksharingDirective(DKind) ||
  4239. isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)),
  4240. Captures);
  4241. ResultIterSpace.CounterVar = ISC.buildCounterVar(Captures, DSA);
  4242. ResultIterSpace.PrivateCounterVar = ISC.buildPrivateCounterVar();
  4243. ResultIterSpace.CounterInit = ISC.buildCounterInit();
  4244. ResultIterSpace.CounterStep = ISC.buildCounterStep();
  4245. ResultIterSpace.InitSrcRange = ISC.getInitSrcRange();
  4246. ResultIterSpace.CondSrcRange = ISC.getConditionSrcRange();
  4247. ResultIterSpace.IncSrcRange = ISC.getIncrementSrcRange();
  4248. ResultIterSpace.Subtract = ISC.shouldSubtractStep();
  4249. HasErrors |= (ResultIterSpace.PreCond == nullptr ||
  4250. ResultIterSpace.NumIterations == nullptr ||
  4251. ResultIterSpace.CounterVar == nullptr ||
  4252. ResultIterSpace.PrivateCounterVar == nullptr ||
  4253. ResultIterSpace.CounterInit == nullptr ||
  4254. ResultIterSpace.CounterStep == nullptr);
  4255. return HasErrors;
  4256. }
  4257. /// \brief Build 'VarRef = Start.
  4258. static ExprResult
  4259. buildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
  4260. ExprResult Start,
  4261. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
  4262. // Build 'VarRef = Start.
  4263. ExprResult NewStart = tryBuildCapture(SemaRef, Start.get(), Captures);
  4264. if (!NewStart.isUsable())
  4265. return ExprError();
  4266. if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
  4267. VarRef.get()->getType())) {
  4268. NewStart = SemaRef.PerformImplicitConversion(
  4269. NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
  4270. /*AllowExplicit=*/true);
  4271. if (!NewStart.isUsable())
  4272. return ExprError();
  4273. }
  4274. ExprResult Init =
  4275. SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
  4276. return Init;
  4277. }
  4278. /// \brief Build 'VarRef = Start + Iter * Step'.
  4279. static ExprResult buildCounterUpdate(
  4280. Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
  4281. ExprResult Start, ExprResult Iter, ExprResult Step, bool Subtract,
  4282. llvm::MapVector<const Expr *, DeclRefExpr *> *Captures = nullptr) {
  4283. // Add parentheses (for debugging purposes only).
  4284. Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
  4285. if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
  4286. !Step.isUsable())
  4287. return ExprError();
  4288. ExprResult NewStep = Step;
  4289. if (Captures)
  4290. NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
  4291. if (NewStep.isInvalid())
  4292. return ExprError();
  4293. ExprResult Update =
  4294. SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
  4295. if (!Update.isUsable())
  4296. return ExprError();
  4297. // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
  4298. // 'VarRef = Start (+|-) Iter * Step'.
  4299. ExprResult NewStart = Start;
  4300. if (Captures)
  4301. NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
  4302. if (NewStart.isInvalid())
  4303. return ExprError();
  4304. // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
  4305. ExprResult SavedUpdate = Update;
  4306. ExprResult UpdateVal;
  4307. if (VarRef.get()->getType()->isOverloadableType() ||
  4308. NewStart.get()->getType()->isOverloadableType() ||
  4309. Update.get()->getType()->isOverloadableType()) {
  4310. bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
  4311. SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
  4312. Update =
  4313. SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
  4314. if (Update.isUsable()) {
  4315. UpdateVal =
  4316. SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
  4317. VarRef.get(), SavedUpdate.get());
  4318. if (UpdateVal.isUsable()) {
  4319. Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
  4320. UpdateVal.get());
  4321. }
  4322. }
  4323. SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
  4324. }
  4325. // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
  4326. if (!Update.isUsable() || !UpdateVal.isUsable()) {
  4327. Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
  4328. NewStart.get(), SavedUpdate.get());
  4329. if (!Update.isUsable())
  4330. return ExprError();
  4331. if (!SemaRef.Context.hasSameType(Update.get()->getType(),
  4332. VarRef.get()->getType())) {
  4333. Update = SemaRef.PerformImplicitConversion(
  4334. Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
  4335. if (!Update.isUsable())
  4336. return ExprError();
  4337. }
  4338. Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
  4339. }
  4340. return Update;
  4341. }
  4342. /// \brief Convert integer expression \a E to make it have at least \a Bits
  4343. /// bits.
  4344. static ExprResult widenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
  4345. if (E == nullptr)
  4346. return ExprError();
  4347. ASTContext &C = SemaRef.Context;
  4348. QualType OldType = E->getType();
  4349. unsigned HasBits = C.getTypeSize(OldType);
  4350. if (HasBits >= Bits)
  4351. return ExprResult(E);
  4352. // OK to convert to signed, because new type has more bits than old.
  4353. QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
  4354. return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
  4355. true);
  4356. }
  4357. /// \brief Check if the given expression \a E is a constant integer that fits
  4358. /// into \a Bits bits.
  4359. static bool fitsInto(unsigned Bits, bool Signed, const Expr *E, Sema &SemaRef) {
  4360. if (E == nullptr)
  4361. return false;
  4362. llvm::APSInt Result;
  4363. if (E->isIntegerConstantExpr(Result, SemaRef.Context))
  4364. return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
  4365. return false;
  4366. }
  4367. /// Build preinits statement for the given declarations.
  4368. static Stmt *buildPreInits(ASTContext &Context,
  4369. MutableArrayRef<Decl *> PreInits) {
  4370. if (!PreInits.empty()) {
  4371. return new (Context) DeclStmt(
  4372. DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
  4373. SourceLocation(), SourceLocation());
  4374. }
  4375. return nullptr;
  4376. }
  4377. /// Build preinits statement for the given declarations.
  4378. static Stmt *
  4379. buildPreInits(ASTContext &Context,
  4380. const llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
  4381. if (!Captures.empty()) {
  4382. SmallVector<Decl *, 16> PreInits;
  4383. for (const auto &Pair : Captures)
  4384. PreInits.push_back(Pair.second->getDecl());
  4385. return buildPreInits(Context, PreInits);
  4386. }
  4387. return nullptr;
  4388. }
  4389. /// Build postupdate expression for the given list of postupdates expressions.
  4390. static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
  4391. Expr *PostUpdate = nullptr;
  4392. if (!PostUpdates.empty()) {
  4393. for (Expr *E : PostUpdates) {
  4394. Expr *ConvE = S.BuildCStyleCastExpr(
  4395. E->getExprLoc(),
  4396. S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
  4397. E->getExprLoc(), E)
  4398. .get();
  4399. PostUpdate = PostUpdate
  4400. ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
  4401. PostUpdate, ConvE)
  4402. .get()
  4403. : ConvE;
  4404. }
  4405. }
  4406. return PostUpdate;
  4407. }
  4408. /// \brief Called on a for stmt to check itself and nested loops (if any).
  4409. /// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
  4410. /// number of collapsed loops otherwise.
  4411. static unsigned
  4412. checkOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
  4413. Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
  4414. DSAStackTy &DSA,
  4415. Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
  4416. OMPLoopDirective::HelperExprs &Built) {
  4417. unsigned NestedLoopCount = 1;
  4418. if (CollapseLoopCountExpr) {
  4419. // Found 'collapse' clause - calculate collapse number.
  4420. llvm::APSInt Result;
  4421. if (CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
  4422. NestedLoopCount = Result.getLimitedValue();
  4423. }
  4424. if (OrderedLoopCountExpr) {
  4425. // Found 'ordered' clause - calculate collapse number.
  4426. llvm::APSInt Result;
  4427. if (OrderedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) {
  4428. if (Result.getLimitedValue() < NestedLoopCount) {
  4429. SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
  4430. diag::err_omp_wrong_ordered_loop_count)
  4431. << OrderedLoopCountExpr->getSourceRange();
  4432. SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
  4433. diag::note_collapse_loop_count)
  4434. << CollapseLoopCountExpr->getSourceRange();
  4435. }
  4436. NestedLoopCount = Result.getLimitedValue();
  4437. }
  4438. }
  4439. // This is helper routine for loop directives (e.g., 'for', 'simd',
  4440. // 'for simd', etc.).
  4441. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  4442. SmallVector<LoopIterationSpace, 4> IterSpaces;
  4443. IterSpaces.resize(NestedLoopCount);
  4444. Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
  4445. for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
  4446. if (checkOpenMPIterationSpace(DKind, CurStmt, SemaRef, DSA, Cnt,
  4447. NestedLoopCount, CollapseLoopCountExpr,
  4448. OrderedLoopCountExpr, VarsWithImplicitDSA,
  4449. IterSpaces[Cnt], Captures))
  4450. return 0;
  4451. // Move on to the next nested for loop, or to the loop body.
  4452. // OpenMP [2.8.1, simd construct, Restrictions]
  4453. // All loops associated with the construct must be perfectly nested; that
  4454. // is, there must be no intervening code nor any OpenMP directive between
  4455. // any two loops.
  4456. CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
  4457. }
  4458. Built.clear(/* size */ NestedLoopCount);
  4459. if (SemaRef.CurContext->isDependentContext())
  4460. return NestedLoopCount;
  4461. // An example of what is generated for the following code:
  4462. //
  4463. // #pragma omp simd collapse(2) ordered(2)
  4464. // for (i = 0; i < NI; ++i)
  4465. // for (k = 0; k < NK; ++k)
  4466. // for (j = J0; j < NJ; j+=2) {
  4467. // <loop body>
  4468. // }
  4469. //
  4470. // We generate the code below.
  4471. // Note: the loop body may be outlined in CodeGen.
  4472. // Note: some counters may be C++ classes, operator- is used to find number of
  4473. // iterations and operator+= to calculate counter value.
  4474. // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
  4475. // or i64 is currently supported).
  4476. //
  4477. // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
  4478. // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
  4479. // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
  4480. // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
  4481. // // similar updates for vars in clauses (e.g. 'linear')
  4482. // <loop body (using local i and j)>
  4483. // }
  4484. // i = NI; // assign final values of counters
  4485. // j = NJ;
  4486. //
  4487. // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
  4488. // the iteration counts of the collapsed for loops.
  4489. // Precondition tests if there is at least one iteration (all conditions are
  4490. // true).
  4491. auto PreCond = ExprResult(IterSpaces[0].PreCond);
  4492. Expr *N0 = IterSpaces[0].NumIterations;
  4493. ExprResult LastIteration32 =
  4494. widenIterationCount(/*Bits=*/32,
  4495. SemaRef
  4496. .PerformImplicitConversion(
  4497. N0->IgnoreImpCasts(), N0->getType(),
  4498. Sema::AA_Converting, /*AllowExplicit=*/true)
  4499. .get(),
  4500. SemaRef);
  4501. ExprResult LastIteration64 = widenIterationCount(
  4502. /*Bits=*/64,
  4503. SemaRef
  4504. .PerformImplicitConversion(N0->IgnoreImpCasts(), N0->getType(),
  4505. Sema::AA_Converting,
  4506. /*AllowExplicit=*/true)
  4507. .get(),
  4508. SemaRef);
  4509. if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
  4510. return NestedLoopCount;
  4511. ASTContext &C = SemaRef.Context;
  4512. bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
  4513. Scope *CurScope = DSA.getCurScope();
  4514. for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
  4515. if (PreCond.isUsable()) {
  4516. PreCond =
  4517. SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
  4518. PreCond.get(), IterSpaces[Cnt].PreCond);
  4519. }
  4520. Expr *N = IterSpaces[Cnt].NumIterations;
  4521. SourceLocation Loc = N->getExprLoc();
  4522. AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
  4523. if (LastIteration32.isUsable())
  4524. LastIteration32 = SemaRef.BuildBinOp(
  4525. CurScope, Loc, BO_Mul, LastIteration32.get(),
  4526. SemaRef
  4527. .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
  4528. Sema::AA_Converting,
  4529. /*AllowExplicit=*/true)
  4530. .get());
  4531. if (LastIteration64.isUsable())
  4532. LastIteration64 = SemaRef.BuildBinOp(
  4533. CurScope, Loc, BO_Mul, LastIteration64.get(),
  4534. SemaRef
  4535. .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
  4536. Sema::AA_Converting,
  4537. /*AllowExplicit=*/true)
  4538. .get());
  4539. }
  4540. // Choose either the 32-bit or 64-bit version.
  4541. ExprResult LastIteration = LastIteration64;
  4542. if (LastIteration32.isUsable() &&
  4543. C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
  4544. (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
  4545. fitsInto(
  4546. /*Bits=*/32,
  4547. LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
  4548. LastIteration64.get(), SemaRef)))
  4549. LastIteration = LastIteration32;
  4550. QualType VType = LastIteration.get()->getType();
  4551. QualType RealVType = VType;
  4552. QualType StrideVType = VType;
  4553. if (isOpenMPTaskLoopDirective(DKind)) {
  4554. VType =
  4555. SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
  4556. StrideVType =
  4557. SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
  4558. }
  4559. if (!LastIteration.isUsable())
  4560. return 0;
  4561. // Save the number of iterations.
  4562. ExprResult NumIterations = LastIteration;
  4563. {
  4564. LastIteration = SemaRef.BuildBinOp(
  4565. CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
  4566. LastIteration.get(),
  4567. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
  4568. if (!LastIteration.isUsable())
  4569. return 0;
  4570. }
  4571. // Calculate the last iteration number beforehand instead of doing this on
  4572. // each iteration. Do not do this if the number of iterations may be kfold-ed.
  4573. llvm::APSInt Result;
  4574. bool IsConstant =
  4575. LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
  4576. ExprResult CalcLastIteration;
  4577. if (!IsConstant) {
  4578. ExprResult SaveRef =
  4579. tryBuildCapture(SemaRef, LastIteration.get(), Captures);
  4580. LastIteration = SaveRef;
  4581. // Prepare SaveRef + 1.
  4582. NumIterations = SemaRef.BuildBinOp(
  4583. CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
  4584. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
  4585. if (!NumIterations.isUsable())
  4586. return 0;
  4587. }
  4588. SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
  4589. // Build variables passed into runtime, necessary for worksharing directives.
  4590. ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB;
  4591. if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
  4592. isOpenMPDistributeDirective(DKind)) {
  4593. // Lower bound variable, initialized with zero.
  4594. VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
  4595. LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
  4596. SemaRef.AddInitializerToDecl(LBDecl,
  4597. SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
  4598. /*DirectInit*/ false);
  4599. // Upper bound variable, initialized with last iteration number.
  4600. VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
  4601. UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
  4602. SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
  4603. /*DirectInit*/ false);
  4604. // A 32-bit variable-flag where runtime returns 1 for the last iteration.
  4605. // This will be used to implement clause 'lastprivate'.
  4606. QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
  4607. VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
  4608. IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
  4609. SemaRef.AddInitializerToDecl(ILDecl,
  4610. SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
  4611. /*DirectInit*/ false);
  4612. // Stride variable returned by runtime (we initialize it to 1 by default).
  4613. VarDecl *STDecl =
  4614. buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
  4615. ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
  4616. SemaRef.AddInitializerToDecl(STDecl,
  4617. SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
  4618. /*DirectInit*/ false);
  4619. // Build expression: UB = min(UB, LastIteration)
  4620. // It is necessary for CodeGen of directives with static scheduling.
  4621. ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
  4622. UB.get(), LastIteration.get());
  4623. ExprResult CondOp = SemaRef.ActOnConditionalOp(
  4624. InitLoc, InitLoc, IsUBGreater.get(), LastIteration.get(), UB.get());
  4625. EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
  4626. CondOp.get());
  4627. EUB = SemaRef.ActOnFinishFullExpr(EUB.get());
  4628. // If we have a combined directive that combines 'distribute', 'for' or
  4629. // 'simd' we need to be able to access the bounds of the schedule of the
  4630. // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
  4631. // by scheduling 'distribute' have to be passed to the schedule of 'for'.
  4632. if (isOpenMPLoopBoundSharingDirective(DKind)) {
  4633. // Lower bound variable, initialized with zero.
  4634. VarDecl *CombLBDecl =
  4635. buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb");
  4636. CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc);
  4637. SemaRef.AddInitializerToDecl(
  4638. CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
  4639. /*DirectInit*/ false);
  4640. // Upper bound variable, initialized with last iteration number.
  4641. VarDecl *CombUBDecl =
  4642. buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub");
  4643. CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc);
  4644. SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(),
  4645. /*DirectInit*/ false);
  4646. ExprResult CombIsUBGreater = SemaRef.BuildBinOp(
  4647. CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get());
  4648. ExprResult CombCondOp =
  4649. SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(),
  4650. LastIteration.get(), CombUB.get());
  4651. CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(),
  4652. CombCondOp.get());
  4653. CombEUB = SemaRef.ActOnFinishFullExpr(CombEUB.get());
  4654. const CapturedDecl *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
  4655. // We expect to have at least 2 more parameters than the 'parallel'
  4656. // directive does - the lower and upper bounds of the previous schedule.
  4657. assert(CD->getNumParams() >= 4 &&
  4658. "Unexpected number of parameters in loop combined directive");
  4659. // Set the proper type for the bounds given what we learned from the
  4660. // enclosed loops.
  4661. ImplicitParamDecl *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
  4662. ImplicitParamDecl *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
  4663. // Previous lower and upper bounds are obtained from the region
  4664. // parameters.
  4665. PrevLB =
  4666. buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
  4667. PrevUB =
  4668. buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
  4669. }
  4670. }
  4671. // Build the iteration variable and its initialization before loop.
  4672. ExprResult IV;
  4673. ExprResult Init, CombInit;
  4674. {
  4675. VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
  4676. IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
  4677. Expr *RHS =
  4678. (isOpenMPWorksharingDirective(DKind) ||
  4679. isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
  4680. ? LB.get()
  4681. : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
  4682. Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
  4683. Init = SemaRef.ActOnFinishFullExpr(Init.get());
  4684. if (isOpenMPLoopBoundSharingDirective(DKind)) {
  4685. Expr *CombRHS =
  4686. (isOpenMPWorksharingDirective(DKind) ||
  4687. isOpenMPTaskLoopDirective(DKind) ||
  4688. isOpenMPDistributeDirective(DKind))
  4689. ? CombLB.get()
  4690. : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
  4691. CombInit =
  4692. SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS);
  4693. CombInit = SemaRef.ActOnFinishFullExpr(CombInit.get());
  4694. }
  4695. }
  4696. // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops.
  4697. SourceLocation CondLoc = AStmt->getLocStart();
  4698. ExprResult Cond =
  4699. (isOpenMPWorksharingDirective(DKind) ||
  4700. isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
  4701. ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get())
  4702. : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
  4703. NumIterations.get());
  4704. ExprResult CombCond;
  4705. if (isOpenMPLoopBoundSharingDirective(DKind)) {
  4706. CombCond =
  4707. SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), CombUB.get());
  4708. }
  4709. // Loop increment (IV = IV + 1)
  4710. SourceLocation IncLoc = AStmt->getLocStart();
  4711. ExprResult Inc =
  4712. SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
  4713. SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
  4714. if (!Inc.isUsable())
  4715. return 0;
  4716. Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
  4717. Inc = SemaRef.ActOnFinishFullExpr(Inc.get());
  4718. if (!Inc.isUsable())
  4719. return 0;
  4720. // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
  4721. // Used for directives with static scheduling.
  4722. // In combined construct, add combined version that use CombLB and CombUB
  4723. // base variables for the update
  4724. ExprResult NextLB, NextUB, CombNextLB, CombNextUB;
  4725. if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
  4726. isOpenMPDistributeDirective(DKind)) {
  4727. // LB + ST
  4728. NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
  4729. if (!NextLB.isUsable())
  4730. return 0;
  4731. // LB = LB + ST
  4732. NextLB =
  4733. SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
  4734. NextLB = SemaRef.ActOnFinishFullExpr(NextLB.get());
  4735. if (!NextLB.isUsable())
  4736. return 0;
  4737. // UB + ST
  4738. NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
  4739. if (!NextUB.isUsable())
  4740. return 0;
  4741. // UB = UB + ST
  4742. NextUB =
  4743. SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
  4744. NextUB = SemaRef.ActOnFinishFullExpr(NextUB.get());
  4745. if (!NextUB.isUsable())
  4746. return 0;
  4747. if (isOpenMPLoopBoundSharingDirective(DKind)) {
  4748. CombNextLB =
  4749. SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get());
  4750. if (!NextLB.isUsable())
  4751. return 0;
  4752. // LB = LB + ST
  4753. CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(),
  4754. CombNextLB.get());
  4755. CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get());
  4756. if (!CombNextLB.isUsable())
  4757. return 0;
  4758. // UB + ST
  4759. CombNextUB =
  4760. SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get());
  4761. if (!CombNextUB.isUsable())
  4762. return 0;
  4763. // UB = UB + ST
  4764. CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(),
  4765. CombNextUB.get());
  4766. CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get());
  4767. if (!CombNextUB.isUsable())
  4768. return 0;
  4769. }
  4770. }
  4771. // Create increment expression for distribute loop when combined in a same
  4772. // directive with for as IV = IV + ST; ensure upper bound expression based
  4773. // on PrevUB instead of NumIterations - used to implement 'for' when found
  4774. // in combination with 'distribute', like in 'distribute parallel for'
  4775. SourceLocation DistIncLoc = AStmt->getLocStart();
  4776. ExprResult DistCond, DistInc, PrevEUB;
  4777. if (isOpenMPLoopBoundSharingDirective(DKind)) {
  4778. DistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get());
  4779. assert(DistCond.isUsable() && "distribute cond expr was not built");
  4780. DistInc =
  4781. SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get());
  4782. assert(DistInc.isUsable() && "distribute inc expr was not built");
  4783. DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(),
  4784. DistInc.get());
  4785. DistInc = SemaRef.ActOnFinishFullExpr(DistInc.get());
  4786. assert(DistInc.isUsable() && "distribute inc expr was not built");
  4787. // Build expression: UB = min(UB, prevUB) for #for in composite or combined
  4788. // construct
  4789. SourceLocation DistEUBLoc = AStmt->getLocStart();
  4790. ExprResult IsUBGreater =
  4791. SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, UB.get(), PrevUB.get());
  4792. ExprResult CondOp = SemaRef.ActOnConditionalOp(
  4793. DistEUBLoc, DistEUBLoc, IsUBGreater.get(), PrevUB.get(), UB.get());
  4794. PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(),
  4795. CondOp.get());
  4796. PrevEUB = SemaRef.ActOnFinishFullExpr(PrevEUB.get());
  4797. }
  4798. // Build updates and final values of the loop counters.
  4799. bool HasErrors = false;
  4800. Built.Counters.resize(NestedLoopCount);
  4801. Built.Inits.resize(NestedLoopCount);
  4802. Built.Updates.resize(NestedLoopCount);
  4803. Built.Finals.resize(NestedLoopCount);
  4804. SmallVector<Expr *, 4> LoopMultipliers;
  4805. {
  4806. ExprResult Div;
  4807. // Go from inner nested loop to outer.
  4808. for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
  4809. LoopIterationSpace &IS = IterSpaces[Cnt];
  4810. SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
  4811. // Build: Iter = (IV / Div) % IS.NumIters
  4812. // where Div is product of previous iterations' IS.NumIters.
  4813. ExprResult Iter;
  4814. if (Div.isUsable()) {
  4815. Iter =
  4816. SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get());
  4817. } else {
  4818. Iter = IV;
  4819. assert((Cnt == (int)NestedLoopCount - 1) &&
  4820. "unusable div expected on first iteration only");
  4821. }
  4822. if (Cnt != 0 && Iter.isUsable())
  4823. Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(),
  4824. IS.NumIterations);
  4825. if (!Iter.isUsable()) {
  4826. HasErrors = true;
  4827. break;
  4828. }
  4829. // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
  4830. auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
  4831. DeclRefExpr *CounterVar = buildDeclRefExpr(
  4832. SemaRef, VD, IS.CounterVar->getType(), IS.CounterVar->getExprLoc(),
  4833. /*RefersToCapture=*/true);
  4834. ExprResult Init = buildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
  4835. IS.CounterInit, Captures);
  4836. if (!Init.isUsable()) {
  4837. HasErrors = true;
  4838. break;
  4839. }
  4840. ExprResult Update = buildCounterUpdate(
  4841. SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
  4842. IS.CounterStep, IS.Subtract, &Captures);
  4843. if (!Update.isUsable()) {
  4844. HasErrors = true;
  4845. break;
  4846. }
  4847. // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
  4848. ExprResult Final = buildCounterUpdate(
  4849. SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit,
  4850. IS.NumIterations, IS.CounterStep, IS.Subtract, &Captures);
  4851. if (!Final.isUsable()) {
  4852. HasErrors = true;
  4853. break;
  4854. }
  4855. // Build Div for the next iteration: Div <- Div * IS.NumIters
  4856. if (Cnt != 0) {
  4857. if (Div.isUnset())
  4858. Div = IS.NumIterations;
  4859. else
  4860. Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(),
  4861. IS.NumIterations);
  4862. // Add parentheses (for debugging purposes only).
  4863. if (Div.isUsable())
  4864. Div = tryBuildCapture(SemaRef, Div.get(), Captures);
  4865. if (!Div.isUsable()) {
  4866. HasErrors = true;
  4867. break;
  4868. }
  4869. LoopMultipliers.push_back(Div.get());
  4870. }
  4871. if (!Update.isUsable() || !Final.isUsable()) {
  4872. HasErrors = true;
  4873. break;
  4874. }
  4875. // Save results
  4876. Built.Counters[Cnt] = IS.CounterVar;
  4877. Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
  4878. Built.Inits[Cnt] = Init.get();
  4879. Built.Updates[Cnt] = Update.get();
  4880. Built.Finals[Cnt] = Final.get();
  4881. }
  4882. }
  4883. if (HasErrors)
  4884. return 0;
  4885. // Save results
  4886. Built.IterationVarRef = IV.get();
  4887. Built.LastIteration = LastIteration.get();
  4888. Built.NumIterations = NumIterations.get();
  4889. Built.CalcLastIteration =
  4890. SemaRef.ActOnFinishFullExpr(CalcLastIteration.get()).get();
  4891. Built.PreCond = PreCond.get();
  4892. Built.PreInits = buildPreInits(C, Captures);
  4893. Built.Cond = Cond.get();
  4894. Built.Init = Init.get();
  4895. Built.Inc = Inc.get();
  4896. Built.LB = LB.get();
  4897. Built.UB = UB.get();
  4898. Built.IL = IL.get();
  4899. Built.ST = ST.get();
  4900. Built.EUB = EUB.get();
  4901. Built.NLB = NextLB.get();
  4902. Built.NUB = NextUB.get();
  4903. Built.PrevLB = PrevLB.get();
  4904. Built.PrevUB = PrevUB.get();
  4905. Built.DistInc = DistInc.get();
  4906. Built.PrevEUB = PrevEUB.get();
  4907. Built.DistCombinedFields.LB = CombLB.get();
  4908. Built.DistCombinedFields.UB = CombUB.get();
  4909. Built.DistCombinedFields.EUB = CombEUB.get();
  4910. Built.DistCombinedFields.Init = CombInit.get();
  4911. Built.DistCombinedFields.Cond = CombCond.get();
  4912. Built.DistCombinedFields.NLB = CombNextLB.get();
  4913. Built.DistCombinedFields.NUB = CombNextUB.get();
  4914. Expr *CounterVal = SemaRef.DefaultLvalueConversion(IV.get()).get();
  4915. // Fill data for doacross depend clauses.
  4916. for (const auto &Pair : DSA.getDoacrossDependClauses()) {
  4917. if (Pair.first->getDependencyKind() == OMPC_DEPEND_source) {
  4918. Pair.first->setCounterValue(CounterVal);
  4919. } else {
  4920. if (NestedLoopCount != Pair.second.size() ||
  4921. NestedLoopCount != LoopMultipliers.size() + 1) {
  4922. // Erroneous case - clause has some problems.
  4923. Pair.first->setCounterValue(CounterVal);
  4924. continue;
  4925. }
  4926. assert(Pair.first->getDependencyKind() == OMPC_DEPEND_sink);
  4927. auto I = Pair.second.rbegin();
  4928. auto IS = IterSpaces.rbegin();
  4929. auto ILM = LoopMultipliers.rbegin();
  4930. Expr *UpCounterVal = CounterVal;
  4931. Expr *Multiplier = nullptr;
  4932. for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
  4933. if (I->first) {
  4934. assert(IS->CounterStep);
  4935. Expr *NormalizedOffset =
  4936. SemaRef
  4937. .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Div,
  4938. I->first, IS->CounterStep)
  4939. .get();
  4940. if (Multiplier) {
  4941. NormalizedOffset =
  4942. SemaRef
  4943. .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Mul,
  4944. NormalizedOffset, Multiplier)
  4945. .get();
  4946. }
  4947. assert(I->second == OO_Plus || I->second == OO_Minus);
  4948. BinaryOperatorKind BOK = (I->second == OO_Plus) ? BO_Add : BO_Sub;
  4949. UpCounterVal = SemaRef
  4950. .BuildBinOp(CurScope, I->first->getExprLoc(), BOK,
  4951. UpCounterVal, NormalizedOffset)
  4952. .get();
  4953. }
  4954. Multiplier = *ILM;
  4955. ++I;
  4956. ++IS;
  4957. ++ILM;
  4958. }
  4959. Pair.first->setCounterValue(UpCounterVal);
  4960. }
  4961. }
  4962. return NestedLoopCount;
  4963. }
  4964. static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
  4965. auto CollapseClauses =
  4966. OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
  4967. if (CollapseClauses.begin() != CollapseClauses.end())
  4968. return (*CollapseClauses.begin())->getNumForLoops();
  4969. return nullptr;
  4970. }
  4971. static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
  4972. auto OrderedClauses =
  4973. OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
  4974. if (OrderedClauses.begin() != OrderedClauses.end())
  4975. return (*OrderedClauses.begin())->getNumForLoops();
  4976. return nullptr;
  4977. }
  4978. static bool checkSimdlenSafelenSpecified(Sema &S,
  4979. const ArrayRef<OMPClause *> Clauses) {
  4980. const OMPSafelenClause *Safelen = nullptr;
  4981. const OMPSimdlenClause *Simdlen = nullptr;
  4982. for (const OMPClause *Clause : Clauses) {
  4983. if (Clause->getClauseKind() == OMPC_safelen)
  4984. Safelen = cast<OMPSafelenClause>(Clause);
  4985. else if (Clause->getClauseKind() == OMPC_simdlen)
  4986. Simdlen = cast<OMPSimdlenClause>(Clause);
  4987. if (Safelen && Simdlen)
  4988. break;
  4989. }
  4990. if (Simdlen && Safelen) {
  4991. llvm::APSInt SimdlenRes, SafelenRes;
  4992. const Expr *SimdlenLength = Simdlen->getSimdlen();
  4993. const Expr *SafelenLength = Safelen->getSafelen();
  4994. if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
  4995. SimdlenLength->isInstantiationDependent() ||
  4996. SimdlenLength->containsUnexpandedParameterPack())
  4997. return false;
  4998. if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
  4999. SafelenLength->isInstantiationDependent() ||
  5000. SafelenLength->containsUnexpandedParameterPack())
  5001. return false;
  5002. SimdlenLength->EvaluateAsInt(SimdlenRes, S.Context);
  5003. SafelenLength->EvaluateAsInt(SafelenRes, S.Context);
  5004. // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
  5005. // If both simdlen and safelen clauses are specified, the value of the
  5006. // simdlen parameter must be less than or equal to the value of the safelen
  5007. // parameter.
  5008. if (SimdlenRes > SafelenRes) {
  5009. S.Diag(SimdlenLength->getExprLoc(),
  5010. diag::err_omp_wrong_simdlen_safelen_values)
  5011. << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
  5012. return true;
  5013. }
  5014. }
  5015. return false;
  5016. }
  5017. StmtResult
  5018. Sema::ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
  5019. SourceLocation StartLoc, SourceLocation EndLoc,
  5020. VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  5021. if (!AStmt)
  5022. return StmtError();
  5023. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  5024. OMPLoopDirective::HelperExprs B;
  5025. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  5026. // define the nested loops number.
  5027. unsigned NestedLoopCount = checkOpenMPLoop(
  5028. OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
  5029. AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
  5030. if (NestedLoopCount == 0)
  5031. return StmtError();
  5032. assert((CurContext->isDependentContext() || B.builtAll()) &&
  5033. "omp simd loop exprs were not built");
  5034. if (!CurContext->isDependentContext()) {
  5035. // Finalize the clauses that need pre-built expressions for CodeGen.
  5036. for (OMPClause *C : Clauses) {
  5037. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  5038. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  5039. B.NumIterations, *this, CurScope,
  5040. DSAStack))
  5041. return StmtError();
  5042. }
  5043. }
  5044. if (checkSimdlenSafelenSpecified(*this, Clauses))
  5045. return StmtError();
  5046. setFunctionHasBranchProtectedScope();
  5047. return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
  5048. Clauses, AStmt, B);
  5049. }
  5050. StmtResult
  5051. Sema::ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
  5052. SourceLocation StartLoc, SourceLocation EndLoc,
  5053. VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  5054. if (!AStmt)
  5055. return StmtError();
  5056. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  5057. OMPLoopDirective::HelperExprs B;
  5058. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  5059. // define the nested loops number.
  5060. unsigned NestedLoopCount = checkOpenMPLoop(
  5061. OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
  5062. AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
  5063. if (NestedLoopCount == 0)
  5064. return StmtError();
  5065. assert((CurContext->isDependentContext() || B.builtAll()) &&
  5066. "omp for loop exprs were not built");
  5067. if (!CurContext->isDependentContext()) {
  5068. // Finalize the clauses that need pre-built expressions for CodeGen.
  5069. for (OMPClause *C : Clauses) {
  5070. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  5071. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  5072. B.NumIterations, *this, CurScope,
  5073. DSAStack))
  5074. return StmtError();
  5075. }
  5076. }
  5077. setFunctionHasBranchProtectedScope();
  5078. return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
  5079. Clauses, AStmt, B, DSAStack->isCancelRegion());
  5080. }
  5081. StmtResult Sema::ActOnOpenMPForSimdDirective(
  5082. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  5083. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  5084. if (!AStmt)
  5085. return StmtError();
  5086. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  5087. OMPLoopDirective::HelperExprs B;
  5088. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  5089. // define the nested loops number.
  5090. unsigned NestedLoopCount =
  5091. checkOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
  5092. getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
  5093. VarsWithImplicitDSA, B);
  5094. if (NestedLoopCount == 0)
  5095. return StmtError();
  5096. assert((CurContext->isDependentContext() || B.builtAll()) &&
  5097. "omp for simd loop exprs were not built");
  5098. if (!CurContext->isDependentContext()) {
  5099. // Finalize the clauses that need pre-built expressions for CodeGen.
  5100. for (OMPClause *C : Clauses) {
  5101. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  5102. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  5103. B.NumIterations, *this, CurScope,
  5104. DSAStack))
  5105. return StmtError();
  5106. }
  5107. }
  5108. if (checkSimdlenSafelenSpecified(*this, Clauses))
  5109. return StmtError();
  5110. setFunctionHasBranchProtectedScope();
  5111. return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
  5112. Clauses, AStmt, B);
  5113. }
  5114. StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
  5115. Stmt *AStmt,
  5116. SourceLocation StartLoc,
  5117. SourceLocation EndLoc) {
  5118. if (!AStmt)
  5119. return StmtError();
  5120. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  5121. auto BaseStmt = AStmt;
  5122. while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
  5123. BaseStmt = CS->getCapturedStmt();
  5124. if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
  5125. auto S = C->children();
  5126. if (S.begin() == S.end())
  5127. return StmtError();
  5128. // All associated statements must be '#pragma omp section' except for
  5129. // the first one.
  5130. for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
  5131. if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
  5132. if (SectionStmt)
  5133. Diag(SectionStmt->getLocStart(),
  5134. diag::err_omp_sections_substmt_not_section);
  5135. return StmtError();
  5136. }
  5137. cast<OMPSectionDirective>(SectionStmt)
  5138. ->setHasCancel(DSAStack->isCancelRegion());
  5139. }
  5140. } else {
  5141. Diag(AStmt->getLocStart(), diag::err_omp_sections_not_compound_stmt);
  5142. return StmtError();
  5143. }
  5144. setFunctionHasBranchProtectedScope();
  5145. return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
  5146. DSAStack->isCancelRegion());
  5147. }
  5148. StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
  5149. SourceLocation StartLoc,
  5150. SourceLocation EndLoc) {
  5151. if (!AStmt)
  5152. return StmtError();
  5153. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  5154. setFunctionHasBranchProtectedScope();
  5155. DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
  5156. return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
  5157. DSAStack->isCancelRegion());
  5158. }
  5159. StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
  5160. Stmt *AStmt,
  5161. SourceLocation StartLoc,
  5162. SourceLocation EndLoc) {
  5163. if (!AStmt)
  5164. return StmtError();
  5165. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  5166. setFunctionHasBranchProtectedScope();
  5167. // OpenMP [2.7.3, single Construct, Restrictions]
  5168. // The copyprivate clause must not be used with the nowait clause.
  5169. const OMPClause *Nowait = nullptr;
  5170. const OMPClause *Copyprivate = nullptr;
  5171. for (const OMPClause *Clause : Clauses) {
  5172. if (Clause->getClauseKind() == OMPC_nowait)
  5173. Nowait = Clause;
  5174. else if (Clause->getClauseKind() == OMPC_copyprivate)
  5175. Copyprivate = Clause;
  5176. if (Copyprivate && Nowait) {
  5177. Diag(Copyprivate->getLocStart(),
  5178. diag::err_omp_single_copyprivate_with_nowait);
  5179. Diag(Nowait->getLocStart(), diag::note_omp_nowait_clause_here);
  5180. return StmtError();
  5181. }
  5182. }
  5183. return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
  5184. }
  5185. StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
  5186. SourceLocation StartLoc,
  5187. SourceLocation EndLoc) {
  5188. if (!AStmt)
  5189. return StmtError();
  5190. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  5191. setFunctionHasBranchProtectedScope();
  5192. return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
  5193. }
  5194. StmtResult Sema::ActOnOpenMPCriticalDirective(
  5195. const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
  5196. Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
  5197. if (!AStmt)
  5198. return StmtError();
  5199. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  5200. bool ErrorFound = false;
  5201. llvm::APSInt Hint;
  5202. SourceLocation HintLoc;
  5203. bool DependentHint = false;
  5204. for (const OMPClause *C : Clauses) {
  5205. if (C->getClauseKind() == OMPC_hint) {
  5206. if (!DirName.getName()) {
  5207. Diag(C->getLocStart(), diag::err_omp_hint_clause_no_name);
  5208. ErrorFound = true;
  5209. }
  5210. Expr *E = cast<OMPHintClause>(C)->getHint();
  5211. if (E->isTypeDependent() || E->isValueDependent() ||
  5212. E->isInstantiationDependent()) {
  5213. DependentHint = true;
  5214. } else {
  5215. Hint = E->EvaluateKnownConstInt(Context);
  5216. HintLoc = C->getLocStart();
  5217. }
  5218. }
  5219. }
  5220. if (ErrorFound)
  5221. return StmtError();
  5222. const auto Pair = DSAStack->getCriticalWithHint(DirName);
  5223. if (Pair.first && DirName.getName() && !DependentHint) {
  5224. if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
  5225. Diag(StartLoc, diag::err_omp_critical_with_hint);
  5226. if (HintLoc.isValid())
  5227. Diag(HintLoc, diag::note_omp_critical_hint_here)
  5228. << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
  5229. else
  5230. Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
  5231. if (const auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
  5232. Diag(C->getLocStart(), diag::note_omp_critical_hint_here)
  5233. << 1
  5234. << C->getHint()->EvaluateKnownConstInt(Context).toString(
  5235. /*Radix=*/10, /*Signed=*/false);
  5236. } else {
  5237. Diag(Pair.first->getLocStart(), diag::note_omp_critical_no_hint) << 1;
  5238. }
  5239. }
  5240. }
  5241. setFunctionHasBranchProtectedScope();
  5242. auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
  5243. Clauses, AStmt);
  5244. if (!Pair.first && DirName.getName() && !DependentHint)
  5245. DSAStack->addCriticalWithHint(Dir, Hint);
  5246. return Dir;
  5247. }
  5248. StmtResult Sema::ActOnOpenMPParallelForDirective(
  5249. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  5250. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  5251. if (!AStmt)
  5252. return StmtError();
  5253. auto *CS = cast<CapturedStmt>(AStmt);
  5254. // 1.2.2 OpenMP Language Terminology
  5255. // Structured block - An executable statement with a single entry at the
  5256. // top and a single exit at the bottom.
  5257. // The point of exit cannot be a branch out of the structured block.
  5258. // longjmp() and throw() must not violate the entry/exit criteria.
  5259. CS->getCapturedDecl()->setNothrow();
  5260. OMPLoopDirective::HelperExprs B;
  5261. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  5262. // define the nested loops number.
  5263. unsigned NestedLoopCount =
  5264. checkOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
  5265. getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
  5266. VarsWithImplicitDSA, B);
  5267. if (NestedLoopCount == 0)
  5268. return StmtError();
  5269. assert((CurContext->isDependentContext() || B.builtAll()) &&
  5270. "omp parallel for loop exprs were not built");
  5271. if (!CurContext->isDependentContext()) {
  5272. // Finalize the clauses that need pre-built expressions for CodeGen.
  5273. for (OMPClause *C : Clauses) {
  5274. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  5275. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  5276. B.NumIterations, *this, CurScope,
  5277. DSAStack))
  5278. return StmtError();
  5279. }
  5280. }
  5281. setFunctionHasBranchProtectedScope();
  5282. return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
  5283. NestedLoopCount, Clauses, AStmt, B,
  5284. DSAStack->isCancelRegion());
  5285. }
  5286. StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
  5287. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  5288. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  5289. if (!AStmt)
  5290. return StmtError();
  5291. auto *CS = cast<CapturedStmt>(AStmt);
  5292. // 1.2.2 OpenMP Language Terminology
  5293. // Structured block - An executable statement with a single entry at the
  5294. // top and a single exit at the bottom.
  5295. // The point of exit cannot be a branch out of the structured block.
  5296. // longjmp() and throw() must not violate the entry/exit criteria.
  5297. CS->getCapturedDecl()->setNothrow();
  5298. OMPLoopDirective::HelperExprs B;
  5299. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  5300. // define the nested loops number.
  5301. unsigned NestedLoopCount =
  5302. checkOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
  5303. getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
  5304. VarsWithImplicitDSA, B);
  5305. if (NestedLoopCount == 0)
  5306. return StmtError();
  5307. if (!CurContext->isDependentContext()) {
  5308. // Finalize the clauses that need pre-built expressions for CodeGen.
  5309. for (OMPClause *C : Clauses) {
  5310. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  5311. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  5312. B.NumIterations, *this, CurScope,
  5313. DSAStack))
  5314. return StmtError();
  5315. }
  5316. }
  5317. if (checkSimdlenSafelenSpecified(*this, Clauses))
  5318. return StmtError();
  5319. setFunctionHasBranchProtectedScope();
  5320. return OMPParallelForSimdDirective::Create(
  5321. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  5322. }
  5323. StmtResult
  5324. Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
  5325. Stmt *AStmt, SourceLocation StartLoc,
  5326. SourceLocation EndLoc) {
  5327. if (!AStmt)
  5328. return StmtError();
  5329. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  5330. auto BaseStmt = AStmt;
  5331. while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
  5332. BaseStmt = CS->getCapturedStmt();
  5333. if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
  5334. auto S = C->children();
  5335. if (S.begin() == S.end())
  5336. return StmtError();
  5337. // All associated statements must be '#pragma omp section' except for
  5338. // the first one.
  5339. for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
  5340. if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
  5341. if (SectionStmt)
  5342. Diag(SectionStmt->getLocStart(),
  5343. diag::err_omp_parallel_sections_substmt_not_section);
  5344. return StmtError();
  5345. }
  5346. cast<OMPSectionDirective>(SectionStmt)
  5347. ->setHasCancel(DSAStack->isCancelRegion());
  5348. }
  5349. } else {
  5350. Diag(AStmt->getLocStart(),
  5351. diag::err_omp_parallel_sections_not_compound_stmt);
  5352. return StmtError();
  5353. }
  5354. setFunctionHasBranchProtectedScope();
  5355. return OMPParallelSectionsDirective::Create(
  5356. Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
  5357. }
  5358. StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
  5359. Stmt *AStmt, SourceLocation StartLoc,
  5360. SourceLocation EndLoc) {
  5361. if (!AStmt)
  5362. return StmtError();
  5363. auto *CS = cast<CapturedStmt>(AStmt);
  5364. // 1.2.2 OpenMP Language Terminology
  5365. // Structured block - An executable statement with a single entry at the
  5366. // top and a single exit at the bottom.
  5367. // The point of exit cannot be a branch out of the structured block.
  5368. // longjmp() and throw() must not violate the entry/exit criteria.
  5369. CS->getCapturedDecl()->setNothrow();
  5370. setFunctionHasBranchProtectedScope();
  5371. return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
  5372. DSAStack->isCancelRegion());
  5373. }
  5374. StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
  5375. SourceLocation EndLoc) {
  5376. return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
  5377. }
  5378. StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
  5379. SourceLocation EndLoc) {
  5380. return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
  5381. }
  5382. StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
  5383. SourceLocation EndLoc) {
  5384. return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
  5385. }
  5386. StmtResult Sema::ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
  5387. Stmt *AStmt,
  5388. SourceLocation StartLoc,
  5389. SourceLocation EndLoc) {
  5390. if (!AStmt)
  5391. return StmtError();
  5392. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  5393. setFunctionHasBranchProtectedScope();
  5394. return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, Clauses,
  5395. AStmt,
  5396. DSAStack->getTaskgroupReductionRef());
  5397. }
  5398. StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
  5399. SourceLocation StartLoc,
  5400. SourceLocation EndLoc) {
  5401. assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
  5402. return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
  5403. }
  5404. StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
  5405. Stmt *AStmt,
  5406. SourceLocation StartLoc,
  5407. SourceLocation EndLoc) {
  5408. const OMPClause *DependFound = nullptr;
  5409. const OMPClause *DependSourceClause = nullptr;
  5410. const OMPClause *DependSinkClause = nullptr;
  5411. bool ErrorFound = false;
  5412. const OMPThreadsClause *TC = nullptr;
  5413. const OMPSIMDClause *SC = nullptr;
  5414. for (const OMPClause *C : Clauses) {
  5415. if (auto *DC = dyn_cast<OMPDependClause>(C)) {
  5416. DependFound = C;
  5417. if (DC->getDependencyKind() == OMPC_DEPEND_source) {
  5418. if (DependSourceClause) {
  5419. Diag(C->getLocStart(), diag::err_omp_more_one_clause)
  5420. << getOpenMPDirectiveName(OMPD_ordered)
  5421. << getOpenMPClauseName(OMPC_depend) << 2;
  5422. ErrorFound = true;
  5423. } else {
  5424. DependSourceClause = C;
  5425. }
  5426. if (DependSinkClause) {
  5427. Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
  5428. << 0;
  5429. ErrorFound = true;
  5430. }
  5431. } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
  5432. if (DependSourceClause) {
  5433. Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
  5434. << 1;
  5435. ErrorFound = true;
  5436. }
  5437. DependSinkClause = C;
  5438. }
  5439. } else if (C->getClauseKind() == OMPC_threads) {
  5440. TC = cast<OMPThreadsClause>(C);
  5441. } else if (C->getClauseKind() == OMPC_simd) {
  5442. SC = cast<OMPSIMDClause>(C);
  5443. }
  5444. }
  5445. if (!ErrorFound && !SC &&
  5446. isOpenMPSimdDirective(DSAStack->getParentDirective())) {
  5447. // OpenMP [2.8.1,simd Construct, Restrictions]
  5448. // An ordered construct with the simd clause is the only OpenMP construct
  5449. // that can appear in the simd region.
  5450. Diag(StartLoc, diag::err_omp_prohibited_region_simd);
  5451. ErrorFound = true;
  5452. } else if (DependFound && (TC || SC)) {
  5453. Diag(DependFound->getLocStart(), diag::err_omp_depend_clause_thread_simd)
  5454. << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
  5455. ErrorFound = true;
  5456. } else if (DependFound && !DSAStack->getParentOrderedRegionParam()) {
  5457. Diag(DependFound->getLocStart(),
  5458. diag::err_omp_ordered_directive_without_param);
  5459. ErrorFound = true;
  5460. } else if (TC || Clauses.empty()) {
  5461. if (const Expr *Param = DSAStack->getParentOrderedRegionParam()) {
  5462. SourceLocation ErrLoc = TC ? TC->getLocStart() : StartLoc;
  5463. Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
  5464. << (TC != nullptr);
  5465. Diag(Param->getLocStart(), diag::note_omp_ordered_param);
  5466. ErrorFound = true;
  5467. }
  5468. }
  5469. if ((!AStmt && !DependFound) || ErrorFound)
  5470. return StmtError();
  5471. if (AStmt) {
  5472. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  5473. setFunctionHasBranchProtectedScope();
  5474. }
  5475. return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
  5476. }
  5477. namespace {
  5478. /// \brief Helper class for checking expression in 'omp atomic [update]'
  5479. /// construct.
  5480. class OpenMPAtomicUpdateChecker {
  5481. /// \brief Error results for atomic update expressions.
  5482. enum ExprAnalysisErrorCode {
  5483. /// \brief A statement is not an expression statement.
  5484. NotAnExpression,
  5485. /// \brief Expression is not builtin binary or unary operation.
  5486. NotABinaryOrUnaryExpression,
  5487. /// \brief Unary operation is not post-/pre- increment/decrement operation.
  5488. NotAnUnaryIncDecExpression,
  5489. /// \brief An expression is not of scalar type.
  5490. NotAScalarType,
  5491. /// \brief A binary operation is not an assignment operation.
  5492. NotAnAssignmentOp,
  5493. /// \brief RHS part of the binary operation is not a binary expression.
  5494. NotABinaryExpression,
  5495. /// \brief RHS part is not additive/multiplicative/shift/biwise binary
  5496. /// expression.
  5497. NotABinaryOperator,
  5498. /// \brief RHS binary operation does not have reference to the updated LHS
  5499. /// part.
  5500. NotAnUpdateExpression,
  5501. /// \brief No errors is found.
  5502. NoError
  5503. };
  5504. /// \brief Reference to Sema.
  5505. Sema &SemaRef;
  5506. /// \brief A location for note diagnostics (when error is found).
  5507. SourceLocation NoteLoc;
  5508. /// \brief 'x' lvalue part of the source atomic expression.
  5509. Expr *X;
  5510. /// \brief 'expr' rvalue part of the source atomic expression.
  5511. Expr *E;
  5512. /// \brief Helper expression of the form
  5513. /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
  5514. /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
  5515. Expr *UpdateExpr;
  5516. /// \brief Is 'x' a LHS in a RHS part of full update expression. It is
  5517. /// important for non-associative operations.
  5518. bool IsXLHSInRHSPart;
  5519. BinaryOperatorKind Op;
  5520. SourceLocation OpLoc;
  5521. /// \brief true if the source expression is a postfix unary operation, false
  5522. /// if it is a prefix unary operation.
  5523. bool IsPostfixUpdate;
  5524. public:
  5525. OpenMPAtomicUpdateChecker(Sema &SemaRef)
  5526. : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
  5527. IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
  5528. /// \brief Check specified statement that it is suitable for 'atomic update'
  5529. /// constructs and extract 'x', 'expr' and Operation from the original
  5530. /// expression. If DiagId and NoteId == 0, then only check is performed
  5531. /// without error notification.
  5532. /// \param DiagId Diagnostic which should be emitted if error is found.
  5533. /// \param NoteId Diagnostic note for the main error message.
  5534. /// \return true if statement is not an update expression, false otherwise.
  5535. bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
  5536. /// \brief Return the 'x' lvalue part of the source atomic expression.
  5537. Expr *getX() const { return X; }
  5538. /// \brief Return the 'expr' rvalue part of the source atomic expression.
  5539. Expr *getExpr() const { return E; }
  5540. /// \brief Return the update expression used in calculation of the updated
  5541. /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
  5542. /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
  5543. Expr *getUpdateExpr() const { return UpdateExpr; }
  5544. /// \brief Return true if 'x' is LHS in RHS part of full update expression,
  5545. /// false otherwise.
  5546. bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
  5547. /// \brief true if the source expression is a postfix unary operation, false
  5548. /// if it is a prefix unary operation.
  5549. bool isPostfixUpdate() const { return IsPostfixUpdate; }
  5550. private:
  5551. bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
  5552. unsigned NoteId = 0);
  5553. };
  5554. } // namespace
  5555. bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
  5556. BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
  5557. ExprAnalysisErrorCode ErrorFound = NoError;
  5558. SourceLocation ErrorLoc, NoteLoc;
  5559. SourceRange ErrorRange, NoteRange;
  5560. // Allowed constructs are:
  5561. // x = x binop expr;
  5562. // x = expr binop x;
  5563. if (AtomicBinOp->getOpcode() == BO_Assign) {
  5564. X = AtomicBinOp->getLHS();
  5565. if (const auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
  5566. AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
  5567. if (AtomicInnerBinOp->isMultiplicativeOp() ||
  5568. AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
  5569. AtomicInnerBinOp->isBitwiseOp()) {
  5570. Op = AtomicInnerBinOp->getOpcode();
  5571. OpLoc = AtomicInnerBinOp->getOperatorLoc();
  5572. Expr *LHS = AtomicInnerBinOp->getLHS();
  5573. Expr *RHS = AtomicInnerBinOp->getRHS();
  5574. llvm::FoldingSetNodeID XId, LHSId, RHSId;
  5575. X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
  5576. /*Canonical=*/true);
  5577. LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
  5578. /*Canonical=*/true);
  5579. RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
  5580. /*Canonical=*/true);
  5581. if (XId == LHSId) {
  5582. E = RHS;
  5583. IsXLHSInRHSPart = true;
  5584. } else if (XId == RHSId) {
  5585. E = LHS;
  5586. IsXLHSInRHSPart = false;
  5587. } else {
  5588. ErrorLoc = AtomicInnerBinOp->getExprLoc();
  5589. ErrorRange = AtomicInnerBinOp->getSourceRange();
  5590. NoteLoc = X->getExprLoc();
  5591. NoteRange = X->getSourceRange();
  5592. ErrorFound = NotAnUpdateExpression;
  5593. }
  5594. } else {
  5595. ErrorLoc = AtomicInnerBinOp->getExprLoc();
  5596. ErrorRange = AtomicInnerBinOp->getSourceRange();
  5597. NoteLoc = AtomicInnerBinOp->getOperatorLoc();
  5598. NoteRange = SourceRange(NoteLoc, NoteLoc);
  5599. ErrorFound = NotABinaryOperator;
  5600. }
  5601. } else {
  5602. NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
  5603. NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
  5604. ErrorFound = NotABinaryExpression;
  5605. }
  5606. } else {
  5607. ErrorLoc = AtomicBinOp->getExprLoc();
  5608. ErrorRange = AtomicBinOp->getSourceRange();
  5609. NoteLoc = AtomicBinOp->getOperatorLoc();
  5610. NoteRange = SourceRange(NoteLoc, NoteLoc);
  5611. ErrorFound = NotAnAssignmentOp;
  5612. }
  5613. if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
  5614. SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
  5615. SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
  5616. return true;
  5617. }
  5618. if (SemaRef.CurContext->isDependentContext())
  5619. E = X = UpdateExpr = nullptr;
  5620. return ErrorFound != NoError;
  5621. }
  5622. bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
  5623. unsigned NoteId) {
  5624. ExprAnalysisErrorCode ErrorFound = NoError;
  5625. SourceLocation ErrorLoc, NoteLoc;
  5626. SourceRange ErrorRange, NoteRange;
  5627. // Allowed constructs are:
  5628. // x++;
  5629. // x--;
  5630. // ++x;
  5631. // --x;
  5632. // x binop= expr;
  5633. // x = x binop expr;
  5634. // x = expr binop x;
  5635. if (auto *AtomicBody = dyn_cast<Expr>(S)) {
  5636. AtomicBody = AtomicBody->IgnoreParenImpCasts();
  5637. if (AtomicBody->getType()->isScalarType() ||
  5638. AtomicBody->isInstantiationDependent()) {
  5639. if (const auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
  5640. AtomicBody->IgnoreParenImpCasts())) {
  5641. // Check for Compound Assignment Operation
  5642. Op = BinaryOperator::getOpForCompoundAssignment(
  5643. AtomicCompAssignOp->getOpcode());
  5644. OpLoc = AtomicCompAssignOp->getOperatorLoc();
  5645. E = AtomicCompAssignOp->getRHS();
  5646. X = AtomicCompAssignOp->getLHS()->IgnoreParens();
  5647. IsXLHSInRHSPart = true;
  5648. } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
  5649. AtomicBody->IgnoreParenImpCasts())) {
  5650. // Check for Binary Operation
  5651. if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
  5652. return true;
  5653. } else if (const auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
  5654. AtomicBody->IgnoreParenImpCasts())) {
  5655. // Check for Unary Operation
  5656. if (AtomicUnaryOp->isIncrementDecrementOp()) {
  5657. IsPostfixUpdate = AtomicUnaryOp->isPostfix();
  5658. Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
  5659. OpLoc = AtomicUnaryOp->getOperatorLoc();
  5660. X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
  5661. E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
  5662. IsXLHSInRHSPart = true;
  5663. } else {
  5664. ErrorFound = NotAnUnaryIncDecExpression;
  5665. ErrorLoc = AtomicUnaryOp->getExprLoc();
  5666. ErrorRange = AtomicUnaryOp->getSourceRange();
  5667. NoteLoc = AtomicUnaryOp->getOperatorLoc();
  5668. NoteRange = SourceRange(NoteLoc, NoteLoc);
  5669. }
  5670. } else if (!AtomicBody->isInstantiationDependent()) {
  5671. ErrorFound = NotABinaryOrUnaryExpression;
  5672. NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
  5673. NoteRange = ErrorRange = AtomicBody->getSourceRange();
  5674. }
  5675. } else {
  5676. ErrorFound = NotAScalarType;
  5677. NoteLoc = ErrorLoc = AtomicBody->getLocStart();
  5678. NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
  5679. }
  5680. } else {
  5681. ErrorFound = NotAnExpression;
  5682. NoteLoc = ErrorLoc = S->getLocStart();
  5683. NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
  5684. }
  5685. if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
  5686. SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
  5687. SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
  5688. return true;
  5689. }
  5690. if (SemaRef.CurContext->isDependentContext())
  5691. E = X = UpdateExpr = nullptr;
  5692. if (ErrorFound == NoError && E && X) {
  5693. // Build an update expression of form 'OpaqueValueExpr(x) binop
  5694. // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
  5695. // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
  5696. auto *OVEX = new (SemaRef.getASTContext())
  5697. OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
  5698. auto *OVEExpr = new (SemaRef.getASTContext())
  5699. OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
  5700. ExprResult Update =
  5701. SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
  5702. IsXLHSInRHSPart ? OVEExpr : OVEX);
  5703. if (Update.isInvalid())
  5704. return true;
  5705. Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
  5706. Sema::AA_Casting);
  5707. if (Update.isInvalid())
  5708. return true;
  5709. UpdateExpr = Update.get();
  5710. }
  5711. return ErrorFound != NoError;
  5712. }
  5713. StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
  5714. Stmt *AStmt,
  5715. SourceLocation StartLoc,
  5716. SourceLocation EndLoc) {
  5717. if (!AStmt)
  5718. return StmtError();
  5719. auto *CS = cast<CapturedStmt>(AStmt);
  5720. // 1.2.2 OpenMP Language Terminology
  5721. // Structured block - An executable statement with a single entry at the
  5722. // top and a single exit at the bottom.
  5723. // The point of exit cannot be a branch out of the structured block.
  5724. // longjmp() and throw() must not violate the entry/exit criteria.
  5725. OpenMPClauseKind AtomicKind = OMPC_unknown;
  5726. SourceLocation AtomicKindLoc;
  5727. for (const OMPClause *C : Clauses) {
  5728. if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
  5729. C->getClauseKind() == OMPC_update ||
  5730. C->getClauseKind() == OMPC_capture) {
  5731. if (AtomicKind != OMPC_unknown) {
  5732. Diag(C->getLocStart(), diag::err_omp_atomic_several_clauses)
  5733. << SourceRange(C->getLocStart(), C->getLocEnd());
  5734. Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
  5735. << getOpenMPClauseName(AtomicKind);
  5736. } else {
  5737. AtomicKind = C->getClauseKind();
  5738. AtomicKindLoc = C->getLocStart();
  5739. }
  5740. }
  5741. }
  5742. Stmt *Body = CS->getCapturedStmt();
  5743. if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
  5744. Body = EWC->getSubExpr();
  5745. Expr *X = nullptr;
  5746. Expr *V = nullptr;
  5747. Expr *E = nullptr;
  5748. Expr *UE = nullptr;
  5749. bool IsXLHSInRHSPart = false;
  5750. bool IsPostfixUpdate = false;
  5751. // OpenMP [2.12.6, atomic Construct]
  5752. // In the next expressions:
  5753. // * x and v (as applicable) are both l-value expressions with scalar type.
  5754. // * During the execution of an atomic region, multiple syntactic
  5755. // occurrences of x must designate the same storage location.
  5756. // * Neither of v and expr (as applicable) may access the storage location
  5757. // designated by x.
  5758. // * Neither of x and expr (as applicable) may access the storage location
  5759. // designated by v.
  5760. // * expr is an expression with scalar type.
  5761. // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
  5762. // * binop, binop=, ++, and -- are not overloaded operators.
  5763. // * The expression x binop expr must be numerically equivalent to x binop
  5764. // (expr). This requirement is satisfied if the operators in expr have
  5765. // precedence greater than binop, or by using parentheses around expr or
  5766. // subexpressions of expr.
  5767. // * The expression expr binop x must be numerically equivalent to (expr)
  5768. // binop x. This requirement is satisfied if the operators in expr have
  5769. // precedence equal to or greater than binop, or by using parentheses around
  5770. // expr or subexpressions of expr.
  5771. // * For forms that allow multiple occurrences of x, the number of times
  5772. // that x is evaluated is unspecified.
  5773. if (AtomicKind == OMPC_read) {
  5774. enum {
  5775. NotAnExpression,
  5776. NotAnAssignmentOp,
  5777. NotAScalarType,
  5778. NotAnLValue,
  5779. NoError
  5780. } ErrorFound = NoError;
  5781. SourceLocation ErrorLoc, NoteLoc;
  5782. SourceRange ErrorRange, NoteRange;
  5783. // If clause is read:
  5784. // v = x;
  5785. if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
  5786. const auto *AtomicBinOp =
  5787. dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
  5788. if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
  5789. X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
  5790. V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
  5791. if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
  5792. (V->isInstantiationDependent() || V->getType()->isScalarType())) {
  5793. if (!X->isLValue() || !V->isLValue()) {
  5794. const Expr *NotLValueExpr = X->isLValue() ? V : X;
  5795. ErrorFound = NotAnLValue;
  5796. ErrorLoc = AtomicBinOp->getExprLoc();
  5797. ErrorRange = AtomicBinOp->getSourceRange();
  5798. NoteLoc = NotLValueExpr->getExprLoc();
  5799. NoteRange = NotLValueExpr->getSourceRange();
  5800. }
  5801. } else if (!X->isInstantiationDependent() ||
  5802. !V->isInstantiationDependent()) {
  5803. const Expr *NotScalarExpr =
  5804. (X->isInstantiationDependent() || X->getType()->isScalarType())
  5805. ? V
  5806. : X;
  5807. ErrorFound = NotAScalarType;
  5808. ErrorLoc = AtomicBinOp->getExprLoc();
  5809. ErrorRange = AtomicBinOp->getSourceRange();
  5810. NoteLoc = NotScalarExpr->getExprLoc();
  5811. NoteRange = NotScalarExpr->getSourceRange();
  5812. }
  5813. } else if (!AtomicBody->isInstantiationDependent()) {
  5814. ErrorFound = NotAnAssignmentOp;
  5815. ErrorLoc = AtomicBody->getExprLoc();
  5816. ErrorRange = AtomicBody->getSourceRange();
  5817. NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
  5818. : AtomicBody->getExprLoc();
  5819. NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
  5820. : AtomicBody->getSourceRange();
  5821. }
  5822. } else {
  5823. ErrorFound = NotAnExpression;
  5824. NoteLoc = ErrorLoc = Body->getLocStart();
  5825. NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
  5826. }
  5827. if (ErrorFound != NoError) {
  5828. Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
  5829. << ErrorRange;
  5830. Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
  5831. << NoteRange;
  5832. return StmtError();
  5833. }
  5834. if (CurContext->isDependentContext())
  5835. V = X = nullptr;
  5836. } else if (AtomicKind == OMPC_write) {
  5837. enum {
  5838. NotAnExpression,
  5839. NotAnAssignmentOp,
  5840. NotAScalarType,
  5841. NotAnLValue,
  5842. NoError
  5843. } ErrorFound = NoError;
  5844. SourceLocation ErrorLoc, NoteLoc;
  5845. SourceRange ErrorRange, NoteRange;
  5846. // If clause is write:
  5847. // x = expr;
  5848. if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
  5849. const auto *AtomicBinOp =
  5850. dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
  5851. if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
  5852. X = AtomicBinOp->getLHS();
  5853. E = AtomicBinOp->getRHS();
  5854. if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
  5855. (E->isInstantiationDependent() || E->getType()->isScalarType())) {
  5856. if (!X->isLValue()) {
  5857. ErrorFound = NotAnLValue;
  5858. ErrorLoc = AtomicBinOp->getExprLoc();
  5859. ErrorRange = AtomicBinOp->getSourceRange();
  5860. NoteLoc = X->getExprLoc();
  5861. NoteRange = X->getSourceRange();
  5862. }
  5863. } else if (!X->isInstantiationDependent() ||
  5864. !E->isInstantiationDependent()) {
  5865. const Expr *NotScalarExpr =
  5866. (X->isInstantiationDependent() || X->getType()->isScalarType())
  5867. ? E
  5868. : X;
  5869. ErrorFound = NotAScalarType;
  5870. ErrorLoc = AtomicBinOp->getExprLoc();
  5871. ErrorRange = AtomicBinOp->getSourceRange();
  5872. NoteLoc = NotScalarExpr->getExprLoc();
  5873. NoteRange = NotScalarExpr->getSourceRange();
  5874. }
  5875. } else if (!AtomicBody->isInstantiationDependent()) {
  5876. ErrorFound = NotAnAssignmentOp;
  5877. ErrorLoc = AtomicBody->getExprLoc();
  5878. ErrorRange = AtomicBody->getSourceRange();
  5879. NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
  5880. : AtomicBody->getExprLoc();
  5881. NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
  5882. : AtomicBody->getSourceRange();
  5883. }
  5884. } else {
  5885. ErrorFound = NotAnExpression;
  5886. NoteLoc = ErrorLoc = Body->getLocStart();
  5887. NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
  5888. }
  5889. if (ErrorFound != NoError) {
  5890. Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
  5891. << ErrorRange;
  5892. Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
  5893. << NoteRange;
  5894. return StmtError();
  5895. }
  5896. if (CurContext->isDependentContext())
  5897. E = X = nullptr;
  5898. } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
  5899. // If clause is update:
  5900. // x++;
  5901. // x--;
  5902. // ++x;
  5903. // --x;
  5904. // x binop= expr;
  5905. // x = x binop expr;
  5906. // x = expr binop x;
  5907. OpenMPAtomicUpdateChecker Checker(*this);
  5908. if (Checker.checkStatement(
  5909. Body, (AtomicKind == OMPC_update)
  5910. ? diag::err_omp_atomic_update_not_expression_statement
  5911. : diag::err_omp_atomic_not_expression_statement,
  5912. diag::note_omp_atomic_update))
  5913. return StmtError();
  5914. if (!CurContext->isDependentContext()) {
  5915. E = Checker.getExpr();
  5916. X = Checker.getX();
  5917. UE = Checker.getUpdateExpr();
  5918. IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
  5919. }
  5920. } else if (AtomicKind == OMPC_capture) {
  5921. enum {
  5922. NotAnAssignmentOp,
  5923. NotACompoundStatement,
  5924. NotTwoSubstatements,
  5925. NotASpecificExpression,
  5926. NoError
  5927. } ErrorFound = NoError;
  5928. SourceLocation ErrorLoc, NoteLoc;
  5929. SourceRange ErrorRange, NoteRange;
  5930. if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
  5931. // If clause is a capture:
  5932. // v = x++;
  5933. // v = x--;
  5934. // v = ++x;
  5935. // v = --x;
  5936. // v = x binop= expr;
  5937. // v = x = x binop expr;
  5938. // v = x = expr binop x;
  5939. const auto *AtomicBinOp =
  5940. dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
  5941. if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
  5942. V = AtomicBinOp->getLHS();
  5943. Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
  5944. OpenMPAtomicUpdateChecker Checker(*this);
  5945. if (Checker.checkStatement(
  5946. Body, diag::err_omp_atomic_capture_not_expression_statement,
  5947. diag::note_omp_atomic_update))
  5948. return StmtError();
  5949. E = Checker.getExpr();
  5950. X = Checker.getX();
  5951. UE = Checker.getUpdateExpr();
  5952. IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
  5953. IsPostfixUpdate = Checker.isPostfixUpdate();
  5954. } else if (!AtomicBody->isInstantiationDependent()) {
  5955. ErrorLoc = AtomicBody->getExprLoc();
  5956. ErrorRange = AtomicBody->getSourceRange();
  5957. NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
  5958. : AtomicBody->getExprLoc();
  5959. NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
  5960. : AtomicBody->getSourceRange();
  5961. ErrorFound = NotAnAssignmentOp;
  5962. }
  5963. if (ErrorFound != NoError) {
  5964. Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
  5965. << ErrorRange;
  5966. Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
  5967. return StmtError();
  5968. }
  5969. if (CurContext->isDependentContext())
  5970. UE = V = E = X = nullptr;
  5971. } else {
  5972. // If clause is a capture:
  5973. // { v = x; x = expr; }
  5974. // { v = x; x++; }
  5975. // { v = x; x--; }
  5976. // { v = x; ++x; }
  5977. // { v = x; --x; }
  5978. // { v = x; x binop= expr; }
  5979. // { v = x; x = x binop expr; }
  5980. // { v = x; x = expr binop x; }
  5981. // { x++; v = x; }
  5982. // { x--; v = x; }
  5983. // { ++x; v = x; }
  5984. // { --x; v = x; }
  5985. // { x binop= expr; v = x; }
  5986. // { x = x binop expr; v = x; }
  5987. // { x = expr binop x; v = x; }
  5988. if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
  5989. // Check that this is { expr1; expr2; }
  5990. if (CS->size() == 2) {
  5991. Stmt *First = CS->body_front();
  5992. Stmt *Second = CS->body_back();
  5993. if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
  5994. First = EWC->getSubExpr()->IgnoreParenImpCasts();
  5995. if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
  5996. Second = EWC->getSubExpr()->IgnoreParenImpCasts();
  5997. // Need to find what subexpression is 'v' and what is 'x'.
  5998. OpenMPAtomicUpdateChecker Checker(*this);
  5999. bool IsUpdateExprFound = !Checker.checkStatement(Second);
  6000. BinaryOperator *BinOp = nullptr;
  6001. if (IsUpdateExprFound) {
  6002. BinOp = dyn_cast<BinaryOperator>(First);
  6003. IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
  6004. }
  6005. if (IsUpdateExprFound && !CurContext->isDependentContext()) {
  6006. // { v = x; x++; }
  6007. // { v = x; x--; }
  6008. // { v = x; ++x; }
  6009. // { v = x; --x; }
  6010. // { v = x; x binop= expr; }
  6011. // { v = x; x = x binop expr; }
  6012. // { v = x; x = expr binop x; }
  6013. // Check that the first expression has form v = x.
  6014. Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
  6015. llvm::FoldingSetNodeID XId, PossibleXId;
  6016. Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
  6017. PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
  6018. IsUpdateExprFound = XId == PossibleXId;
  6019. if (IsUpdateExprFound) {
  6020. V = BinOp->getLHS();
  6021. X = Checker.getX();
  6022. E = Checker.getExpr();
  6023. UE = Checker.getUpdateExpr();
  6024. IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
  6025. IsPostfixUpdate = true;
  6026. }
  6027. }
  6028. if (!IsUpdateExprFound) {
  6029. IsUpdateExprFound = !Checker.checkStatement(First);
  6030. BinOp = nullptr;
  6031. if (IsUpdateExprFound) {
  6032. BinOp = dyn_cast<BinaryOperator>(Second);
  6033. IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
  6034. }
  6035. if (IsUpdateExprFound && !CurContext->isDependentContext()) {
  6036. // { x++; v = x; }
  6037. // { x--; v = x; }
  6038. // { ++x; v = x; }
  6039. // { --x; v = x; }
  6040. // { x binop= expr; v = x; }
  6041. // { x = x binop expr; v = x; }
  6042. // { x = expr binop x; v = x; }
  6043. // Check that the second expression has form v = x.
  6044. Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
  6045. llvm::FoldingSetNodeID XId, PossibleXId;
  6046. Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
  6047. PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
  6048. IsUpdateExprFound = XId == PossibleXId;
  6049. if (IsUpdateExprFound) {
  6050. V = BinOp->getLHS();
  6051. X = Checker.getX();
  6052. E = Checker.getExpr();
  6053. UE = Checker.getUpdateExpr();
  6054. IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
  6055. IsPostfixUpdate = false;
  6056. }
  6057. }
  6058. }
  6059. if (!IsUpdateExprFound) {
  6060. // { v = x; x = expr; }
  6061. auto *FirstExpr = dyn_cast<Expr>(First);
  6062. auto *SecondExpr = dyn_cast<Expr>(Second);
  6063. if (!FirstExpr || !SecondExpr ||
  6064. !(FirstExpr->isInstantiationDependent() ||
  6065. SecondExpr->isInstantiationDependent())) {
  6066. auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
  6067. if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
  6068. ErrorFound = NotAnAssignmentOp;
  6069. NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
  6070. : First->getLocStart();
  6071. NoteRange = ErrorRange = FirstBinOp
  6072. ? FirstBinOp->getSourceRange()
  6073. : SourceRange(ErrorLoc, ErrorLoc);
  6074. } else {
  6075. auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
  6076. if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
  6077. ErrorFound = NotAnAssignmentOp;
  6078. NoteLoc = ErrorLoc = SecondBinOp
  6079. ? SecondBinOp->getOperatorLoc()
  6080. : Second->getLocStart();
  6081. NoteRange = ErrorRange =
  6082. SecondBinOp ? SecondBinOp->getSourceRange()
  6083. : SourceRange(ErrorLoc, ErrorLoc);
  6084. } else {
  6085. Expr *PossibleXRHSInFirst =
  6086. FirstBinOp->getRHS()->IgnoreParenImpCasts();
  6087. Expr *PossibleXLHSInSecond =
  6088. SecondBinOp->getLHS()->IgnoreParenImpCasts();
  6089. llvm::FoldingSetNodeID X1Id, X2Id;
  6090. PossibleXRHSInFirst->Profile(X1Id, Context,
  6091. /*Canonical=*/true);
  6092. PossibleXLHSInSecond->Profile(X2Id, Context,
  6093. /*Canonical=*/true);
  6094. IsUpdateExprFound = X1Id == X2Id;
  6095. if (IsUpdateExprFound) {
  6096. V = FirstBinOp->getLHS();
  6097. X = SecondBinOp->getLHS();
  6098. E = SecondBinOp->getRHS();
  6099. UE = nullptr;
  6100. IsXLHSInRHSPart = false;
  6101. IsPostfixUpdate = true;
  6102. } else {
  6103. ErrorFound = NotASpecificExpression;
  6104. ErrorLoc = FirstBinOp->getExprLoc();
  6105. ErrorRange = FirstBinOp->getSourceRange();
  6106. NoteLoc = SecondBinOp->getLHS()->getExprLoc();
  6107. NoteRange = SecondBinOp->getRHS()->getSourceRange();
  6108. }
  6109. }
  6110. }
  6111. }
  6112. }
  6113. } else {
  6114. NoteLoc = ErrorLoc = Body->getLocStart();
  6115. NoteRange = ErrorRange =
  6116. SourceRange(Body->getLocStart(), Body->getLocStart());
  6117. ErrorFound = NotTwoSubstatements;
  6118. }
  6119. } else {
  6120. NoteLoc = ErrorLoc = Body->getLocStart();
  6121. NoteRange = ErrorRange =
  6122. SourceRange(Body->getLocStart(), Body->getLocStart());
  6123. ErrorFound = NotACompoundStatement;
  6124. }
  6125. if (ErrorFound != NoError) {
  6126. Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
  6127. << ErrorRange;
  6128. Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
  6129. return StmtError();
  6130. }
  6131. if (CurContext->isDependentContext())
  6132. UE = V = E = X = nullptr;
  6133. }
  6134. }
  6135. setFunctionHasBranchProtectedScope();
  6136. return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
  6137. X, V, E, UE, IsXLHSInRHSPart,
  6138. IsPostfixUpdate);
  6139. }
  6140. StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
  6141. Stmt *AStmt,
  6142. SourceLocation StartLoc,
  6143. SourceLocation EndLoc) {
  6144. if (!AStmt)
  6145. return StmtError();
  6146. auto *CS = cast<CapturedStmt>(AStmt);
  6147. // 1.2.2 OpenMP Language Terminology
  6148. // Structured block - An executable statement with a single entry at the
  6149. // top and a single exit at the bottom.
  6150. // The point of exit cannot be a branch out of the structured block.
  6151. // longjmp() and throw() must not violate the entry/exit criteria.
  6152. CS->getCapturedDecl()->setNothrow();
  6153. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target);
  6154. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  6155. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  6156. // 1.2.2 OpenMP Language Terminology
  6157. // Structured block - An executable statement with a single entry at the
  6158. // top and a single exit at the bottom.
  6159. // The point of exit cannot be a branch out of the structured block.
  6160. // longjmp() and throw() must not violate the entry/exit criteria.
  6161. CS->getCapturedDecl()->setNothrow();
  6162. }
  6163. // OpenMP [2.16, Nesting of Regions]
  6164. // If specified, a teams construct must be contained within a target
  6165. // construct. That target construct must contain no statements or directives
  6166. // outside of the teams construct.
  6167. if (DSAStack->hasInnerTeamsRegion()) {
  6168. const Stmt *S = CS->IgnoreContainers(/*IgnoreCaptured=*/true);
  6169. bool OMPTeamsFound = true;
  6170. if (const auto *CS = dyn_cast<CompoundStmt>(S)) {
  6171. auto I = CS->body_begin();
  6172. while (I != CS->body_end()) {
  6173. const auto *OED = dyn_cast<OMPExecutableDirective>(*I);
  6174. if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) {
  6175. OMPTeamsFound = false;
  6176. break;
  6177. }
  6178. ++I;
  6179. }
  6180. assert(I != CS->body_end() && "Not found statement");
  6181. S = *I;
  6182. } else {
  6183. const auto *OED = dyn_cast<OMPExecutableDirective>(S);
  6184. OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
  6185. }
  6186. if (!OMPTeamsFound) {
  6187. Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
  6188. Diag(DSAStack->getInnerTeamsRegionLoc(),
  6189. diag::note_omp_nested_teams_construct_here);
  6190. Diag(S->getLocStart(), diag::note_omp_nested_statement_here)
  6191. << isa<OMPExecutableDirective>(S);
  6192. return StmtError();
  6193. }
  6194. }
  6195. setFunctionHasBranchProtectedScope();
  6196. return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
  6197. }
  6198. StmtResult
  6199. Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
  6200. Stmt *AStmt, SourceLocation StartLoc,
  6201. SourceLocation EndLoc) {
  6202. if (!AStmt)
  6203. return StmtError();
  6204. auto *CS = cast<CapturedStmt>(AStmt);
  6205. // 1.2.2 OpenMP Language Terminology
  6206. // Structured block - An executable statement with a single entry at the
  6207. // top and a single exit at the bottom.
  6208. // The point of exit cannot be a branch out of the structured block.
  6209. // longjmp() and throw() must not violate the entry/exit criteria.
  6210. CS->getCapturedDecl()->setNothrow();
  6211. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel);
  6212. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  6213. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  6214. // 1.2.2 OpenMP Language Terminology
  6215. // Structured block - An executable statement with a single entry at the
  6216. // top and a single exit at the bottom.
  6217. // The point of exit cannot be a branch out of the structured block.
  6218. // longjmp() and throw() must not violate the entry/exit criteria.
  6219. CS->getCapturedDecl()->setNothrow();
  6220. }
  6221. setFunctionHasBranchProtectedScope();
  6222. return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
  6223. AStmt);
  6224. }
  6225. StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
  6226. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  6227. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  6228. if (!AStmt)
  6229. return StmtError();
  6230. auto *CS = cast<CapturedStmt>(AStmt);
  6231. // 1.2.2 OpenMP Language Terminology
  6232. // Structured block - An executable statement with a single entry at the
  6233. // top and a single exit at the bottom.
  6234. // The point of exit cannot be a branch out of the structured block.
  6235. // longjmp() and throw() must not violate the entry/exit criteria.
  6236. CS->getCapturedDecl()->setNothrow();
  6237. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
  6238. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  6239. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  6240. // 1.2.2 OpenMP Language Terminology
  6241. // Structured block - An executable statement with a single entry at the
  6242. // top and a single exit at the bottom.
  6243. // The point of exit cannot be a branch out of the structured block.
  6244. // longjmp() and throw() must not violate the entry/exit criteria.
  6245. CS->getCapturedDecl()->setNothrow();
  6246. }
  6247. OMPLoopDirective::HelperExprs B;
  6248. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  6249. // define the nested loops number.
  6250. unsigned NestedLoopCount =
  6251. checkOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
  6252. getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
  6253. VarsWithImplicitDSA, B);
  6254. if (NestedLoopCount == 0)
  6255. return StmtError();
  6256. assert((CurContext->isDependentContext() || B.builtAll()) &&
  6257. "omp target parallel for loop exprs were not built");
  6258. if (!CurContext->isDependentContext()) {
  6259. // Finalize the clauses that need pre-built expressions for CodeGen.
  6260. for (OMPClause *C : Clauses) {
  6261. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  6262. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  6263. B.NumIterations, *this, CurScope,
  6264. DSAStack))
  6265. return StmtError();
  6266. }
  6267. }
  6268. setFunctionHasBranchProtectedScope();
  6269. return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc,
  6270. NestedLoopCount, Clauses, AStmt,
  6271. B, DSAStack->isCancelRegion());
  6272. }
  6273. /// Check for existence of a map clause in the list of clauses.
  6274. static bool hasClauses(ArrayRef<OMPClause *> Clauses,
  6275. const OpenMPClauseKind K) {
  6276. return llvm::any_of(
  6277. Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; });
  6278. }
  6279. template <typename... Params>
  6280. static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K,
  6281. const Params... ClauseTypes) {
  6282. return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...);
  6283. }
  6284. StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
  6285. Stmt *AStmt,
  6286. SourceLocation StartLoc,
  6287. SourceLocation EndLoc) {
  6288. if (!AStmt)
  6289. return StmtError();
  6290. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  6291. // OpenMP [2.10.1, Restrictions, p. 97]
  6292. // At least one map clause must appear on the directive.
  6293. if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr)) {
  6294. Diag(StartLoc, diag::err_omp_no_clause_for_directive)
  6295. << "'map' or 'use_device_ptr'"
  6296. << getOpenMPDirectiveName(OMPD_target_data);
  6297. return StmtError();
  6298. }
  6299. setFunctionHasBranchProtectedScope();
  6300. return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
  6301. AStmt);
  6302. }
  6303. StmtResult
  6304. Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
  6305. SourceLocation StartLoc,
  6306. SourceLocation EndLoc, Stmt *AStmt) {
  6307. if (!AStmt)
  6308. return StmtError();
  6309. auto *CS = cast<CapturedStmt>(AStmt);
  6310. // 1.2.2 OpenMP Language Terminology
  6311. // Structured block - An executable statement with a single entry at the
  6312. // top and a single exit at the bottom.
  6313. // The point of exit cannot be a branch out of the structured block.
  6314. // longjmp() and throw() must not violate the entry/exit criteria.
  6315. CS->getCapturedDecl()->setNothrow();
  6316. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_enter_data);
  6317. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  6318. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  6319. // 1.2.2 OpenMP Language Terminology
  6320. // Structured block - An executable statement with a single entry at the
  6321. // top and a single exit at the bottom.
  6322. // The point of exit cannot be a branch out of the structured block.
  6323. // longjmp() and throw() must not violate the entry/exit criteria.
  6324. CS->getCapturedDecl()->setNothrow();
  6325. }
  6326. // OpenMP [2.10.2, Restrictions, p. 99]
  6327. // At least one map clause must appear on the directive.
  6328. if (!hasClauses(Clauses, OMPC_map)) {
  6329. Diag(StartLoc, diag::err_omp_no_clause_for_directive)
  6330. << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data);
  6331. return StmtError();
  6332. }
  6333. return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
  6334. AStmt);
  6335. }
  6336. StmtResult
  6337. Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
  6338. SourceLocation StartLoc,
  6339. SourceLocation EndLoc, Stmt *AStmt) {
  6340. if (!AStmt)
  6341. return StmtError();
  6342. auto *CS = cast<CapturedStmt>(AStmt);
  6343. // 1.2.2 OpenMP Language Terminology
  6344. // Structured block - An executable statement with a single entry at the
  6345. // top and a single exit at the bottom.
  6346. // The point of exit cannot be a branch out of the structured block.
  6347. // longjmp() and throw() must not violate the entry/exit criteria.
  6348. CS->getCapturedDecl()->setNothrow();
  6349. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_exit_data);
  6350. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  6351. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  6352. // 1.2.2 OpenMP Language Terminology
  6353. // Structured block - An executable statement with a single entry at the
  6354. // top and a single exit at the bottom.
  6355. // The point of exit cannot be a branch out of the structured block.
  6356. // longjmp() and throw() must not violate the entry/exit criteria.
  6357. CS->getCapturedDecl()->setNothrow();
  6358. }
  6359. // OpenMP [2.10.3, Restrictions, p. 102]
  6360. // At least one map clause must appear on the directive.
  6361. if (!hasClauses(Clauses, OMPC_map)) {
  6362. Diag(StartLoc, diag::err_omp_no_clause_for_directive)
  6363. << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data);
  6364. return StmtError();
  6365. }
  6366. return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
  6367. AStmt);
  6368. }
  6369. StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
  6370. SourceLocation StartLoc,
  6371. SourceLocation EndLoc,
  6372. Stmt *AStmt) {
  6373. if (!AStmt)
  6374. return StmtError();
  6375. auto *CS = cast<CapturedStmt>(AStmt);
  6376. // 1.2.2 OpenMP Language Terminology
  6377. // Structured block - An executable statement with a single entry at the
  6378. // top and a single exit at the bottom.
  6379. // The point of exit cannot be a branch out of the structured block.
  6380. // longjmp() and throw() must not violate the entry/exit criteria.
  6381. CS->getCapturedDecl()->setNothrow();
  6382. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_update);
  6383. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  6384. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  6385. // 1.2.2 OpenMP Language Terminology
  6386. // Structured block - An executable statement with a single entry at the
  6387. // top and a single exit at the bottom.
  6388. // The point of exit cannot be a branch out of the structured block.
  6389. // longjmp() and throw() must not violate the entry/exit criteria.
  6390. CS->getCapturedDecl()->setNothrow();
  6391. }
  6392. if (!hasClauses(Clauses, OMPC_to, OMPC_from)) {
  6393. Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
  6394. return StmtError();
  6395. }
  6396. return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses,
  6397. AStmt);
  6398. }
  6399. StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
  6400. Stmt *AStmt, SourceLocation StartLoc,
  6401. SourceLocation EndLoc) {
  6402. if (!AStmt)
  6403. return StmtError();
  6404. auto *CS = cast<CapturedStmt>(AStmt);
  6405. // 1.2.2 OpenMP Language Terminology
  6406. // Structured block - An executable statement with a single entry at the
  6407. // top and a single exit at the bottom.
  6408. // The point of exit cannot be a branch out of the structured block.
  6409. // longjmp() and throw() must not violate the entry/exit criteria.
  6410. CS->getCapturedDecl()->setNothrow();
  6411. setFunctionHasBranchProtectedScope();
  6412. DSAStack->setParentTeamsRegionLoc(StartLoc);
  6413. return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
  6414. }
  6415. StmtResult
  6416. Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
  6417. SourceLocation EndLoc,
  6418. OpenMPDirectiveKind CancelRegion) {
  6419. if (DSAStack->isParentNowaitRegion()) {
  6420. Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
  6421. return StmtError();
  6422. }
  6423. if (DSAStack->isParentOrderedRegion()) {
  6424. Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
  6425. return StmtError();
  6426. }
  6427. return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
  6428. CancelRegion);
  6429. }
  6430. StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
  6431. SourceLocation StartLoc,
  6432. SourceLocation EndLoc,
  6433. OpenMPDirectiveKind CancelRegion) {
  6434. if (DSAStack->isParentNowaitRegion()) {
  6435. Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
  6436. return StmtError();
  6437. }
  6438. if (DSAStack->isParentOrderedRegion()) {
  6439. Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
  6440. return StmtError();
  6441. }
  6442. DSAStack->setParentCancelRegion(/*Cancel=*/true);
  6443. return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
  6444. CancelRegion);
  6445. }
  6446. static bool checkGrainsizeNumTasksClauses(Sema &S,
  6447. ArrayRef<OMPClause *> Clauses) {
  6448. const OMPClause *PrevClause = nullptr;
  6449. bool ErrorFound = false;
  6450. for (const OMPClause *C : Clauses) {
  6451. if (C->getClauseKind() == OMPC_grainsize ||
  6452. C->getClauseKind() == OMPC_num_tasks) {
  6453. if (!PrevClause)
  6454. PrevClause = C;
  6455. else if (PrevClause->getClauseKind() != C->getClauseKind()) {
  6456. S.Diag(C->getLocStart(),
  6457. diag::err_omp_grainsize_num_tasks_mutually_exclusive)
  6458. << getOpenMPClauseName(C->getClauseKind())
  6459. << getOpenMPClauseName(PrevClause->getClauseKind());
  6460. S.Diag(PrevClause->getLocStart(),
  6461. diag::note_omp_previous_grainsize_num_tasks)
  6462. << getOpenMPClauseName(PrevClause->getClauseKind());
  6463. ErrorFound = true;
  6464. }
  6465. }
  6466. }
  6467. return ErrorFound;
  6468. }
  6469. static bool checkReductionClauseWithNogroup(Sema &S,
  6470. ArrayRef<OMPClause *> Clauses) {
  6471. const OMPClause *ReductionClause = nullptr;
  6472. const OMPClause *NogroupClause = nullptr;
  6473. for (const OMPClause *C : Clauses) {
  6474. if (C->getClauseKind() == OMPC_reduction) {
  6475. ReductionClause = C;
  6476. if (NogroupClause)
  6477. break;
  6478. continue;
  6479. }
  6480. if (C->getClauseKind() == OMPC_nogroup) {
  6481. NogroupClause = C;
  6482. if (ReductionClause)
  6483. break;
  6484. continue;
  6485. }
  6486. }
  6487. if (ReductionClause && NogroupClause) {
  6488. S.Diag(ReductionClause->getLocStart(), diag::err_omp_reduction_with_nogroup)
  6489. << SourceRange(NogroupClause->getLocStart(),
  6490. NogroupClause->getLocEnd());
  6491. return true;
  6492. }
  6493. return false;
  6494. }
  6495. StmtResult Sema::ActOnOpenMPTaskLoopDirective(
  6496. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  6497. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  6498. if (!AStmt)
  6499. return StmtError();
  6500. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  6501. OMPLoopDirective::HelperExprs B;
  6502. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  6503. // define the nested loops number.
  6504. unsigned NestedLoopCount =
  6505. checkOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
  6506. /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
  6507. VarsWithImplicitDSA, B);
  6508. if (NestedLoopCount == 0)
  6509. return StmtError();
  6510. assert((CurContext->isDependentContext() || B.builtAll()) &&
  6511. "omp for loop exprs were not built");
  6512. // OpenMP, [2.9.2 taskloop Construct, Restrictions]
  6513. // The grainsize clause and num_tasks clause are mutually exclusive and may
  6514. // not appear on the same taskloop directive.
  6515. if (checkGrainsizeNumTasksClauses(*this, Clauses))
  6516. return StmtError();
  6517. // OpenMP, [2.9.2 taskloop Construct, Restrictions]
  6518. // If a reduction clause is present on the taskloop directive, the nogroup
  6519. // clause must not be specified.
  6520. if (checkReductionClauseWithNogroup(*this, Clauses))
  6521. return StmtError();
  6522. setFunctionHasBranchProtectedScope();
  6523. return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
  6524. NestedLoopCount, Clauses, AStmt, B);
  6525. }
  6526. StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
  6527. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  6528. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  6529. if (!AStmt)
  6530. return StmtError();
  6531. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  6532. OMPLoopDirective::HelperExprs B;
  6533. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  6534. // define the nested loops number.
  6535. unsigned NestedLoopCount =
  6536. checkOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
  6537. /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
  6538. VarsWithImplicitDSA, B);
  6539. if (NestedLoopCount == 0)
  6540. return StmtError();
  6541. assert((CurContext->isDependentContext() || B.builtAll()) &&
  6542. "omp for loop exprs were not built");
  6543. if (!CurContext->isDependentContext()) {
  6544. // Finalize the clauses that need pre-built expressions for CodeGen.
  6545. for (OMPClause *C : Clauses) {
  6546. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  6547. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  6548. B.NumIterations, *this, CurScope,
  6549. DSAStack))
  6550. return StmtError();
  6551. }
  6552. }
  6553. // OpenMP, [2.9.2 taskloop Construct, Restrictions]
  6554. // The grainsize clause and num_tasks clause are mutually exclusive and may
  6555. // not appear on the same taskloop directive.
  6556. if (checkGrainsizeNumTasksClauses(*this, Clauses))
  6557. return StmtError();
  6558. // OpenMP, [2.9.2 taskloop Construct, Restrictions]
  6559. // If a reduction clause is present on the taskloop directive, the nogroup
  6560. // clause must not be specified.
  6561. if (checkReductionClauseWithNogroup(*this, Clauses))
  6562. return StmtError();
  6563. if (checkSimdlenSafelenSpecified(*this, Clauses))
  6564. return StmtError();
  6565. setFunctionHasBranchProtectedScope();
  6566. return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
  6567. NestedLoopCount, Clauses, AStmt, B);
  6568. }
  6569. StmtResult Sema::ActOnOpenMPDistributeDirective(
  6570. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  6571. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  6572. if (!AStmt)
  6573. return StmtError();
  6574. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  6575. OMPLoopDirective::HelperExprs B;
  6576. // In presence of clause 'collapse' with number of loops, it will
  6577. // define the nested loops number.
  6578. unsigned NestedLoopCount =
  6579. checkOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
  6580. nullptr /*ordered not a clause on distribute*/, AStmt,
  6581. *this, *DSAStack, VarsWithImplicitDSA, B);
  6582. if (NestedLoopCount == 0)
  6583. return StmtError();
  6584. assert((CurContext->isDependentContext() || B.builtAll()) &&
  6585. "omp for loop exprs were not built");
  6586. setFunctionHasBranchProtectedScope();
  6587. return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
  6588. NestedLoopCount, Clauses, AStmt, B);
  6589. }
  6590. StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
  6591. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  6592. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  6593. if (!AStmt)
  6594. return StmtError();
  6595. auto *CS = cast<CapturedStmt>(AStmt);
  6596. // 1.2.2 OpenMP Language Terminology
  6597. // Structured block - An executable statement with a single entry at the
  6598. // top and a single exit at the bottom.
  6599. // The point of exit cannot be a branch out of the structured block.
  6600. // longjmp() and throw() must not violate the entry/exit criteria.
  6601. CS->getCapturedDecl()->setNothrow();
  6602. for (int ThisCaptureLevel =
  6603. getOpenMPCaptureLevels(OMPD_distribute_parallel_for);
  6604. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  6605. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  6606. // 1.2.2 OpenMP Language Terminology
  6607. // Structured block - An executable statement with a single entry at the
  6608. // top and a single exit at the bottom.
  6609. // The point of exit cannot be a branch out of the structured block.
  6610. // longjmp() and throw() must not violate the entry/exit criteria.
  6611. CS->getCapturedDecl()->setNothrow();
  6612. }
  6613. OMPLoopDirective::HelperExprs B;
  6614. // In presence of clause 'collapse' with number of loops, it will
  6615. // define the nested loops number.
  6616. unsigned NestedLoopCount = checkOpenMPLoop(
  6617. OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
  6618. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  6619. VarsWithImplicitDSA, B);
  6620. if (NestedLoopCount == 0)
  6621. return StmtError();
  6622. assert((CurContext->isDependentContext() || B.builtAll()) &&
  6623. "omp for loop exprs were not built");
  6624. setFunctionHasBranchProtectedScope();
  6625. return OMPDistributeParallelForDirective::Create(
  6626. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
  6627. DSAStack->isCancelRegion());
  6628. }
  6629. StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
  6630. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  6631. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  6632. if (!AStmt)
  6633. return StmtError();
  6634. auto *CS = cast<CapturedStmt>(AStmt);
  6635. // 1.2.2 OpenMP Language Terminology
  6636. // Structured block - An executable statement with a single entry at the
  6637. // top and a single exit at the bottom.
  6638. // The point of exit cannot be a branch out of the structured block.
  6639. // longjmp() and throw() must not violate the entry/exit criteria.
  6640. CS->getCapturedDecl()->setNothrow();
  6641. for (int ThisCaptureLevel =
  6642. getOpenMPCaptureLevels(OMPD_distribute_parallel_for_simd);
  6643. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  6644. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  6645. // 1.2.2 OpenMP Language Terminology
  6646. // Structured block - An executable statement with a single entry at the
  6647. // top and a single exit at the bottom.
  6648. // The point of exit cannot be a branch out of the structured block.
  6649. // longjmp() and throw() must not violate the entry/exit criteria.
  6650. CS->getCapturedDecl()->setNothrow();
  6651. }
  6652. OMPLoopDirective::HelperExprs B;
  6653. // In presence of clause 'collapse' with number of loops, it will
  6654. // define the nested loops number.
  6655. unsigned NestedLoopCount = checkOpenMPLoop(
  6656. OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
  6657. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  6658. VarsWithImplicitDSA, B);
  6659. if (NestedLoopCount == 0)
  6660. return StmtError();
  6661. assert((CurContext->isDependentContext() || B.builtAll()) &&
  6662. "omp for loop exprs were not built");
  6663. if (!CurContext->isDependentContext()) {
  6664. // Finalize the clauses that need pre-built expressions for CodeGen.
  6665. for (OMPClause *C : Clauses) {
  6666. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  6667. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  6668. B.NumIterations, *this, CurScope,
  6669. DSAStack))
  6670. return StmtError();
  6671. }
  6672. }
  6673. if (checkSimdlenSafelenSpecified(*this, Clauses))
  6674. return StmtError();
  6675. setFunctionHasBranchProtectedScope();
  6676. return OMPDistributeParallelForSimdDirective::Create(
  6677. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  6678. }
  6679. StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
  6680. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  6681. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  6682. if (!AStmt)
  6683. return StmtError();
  6684. auto *CS = cast<CapturedStmt>(AStmt);
  6685. // 1.2.2 OpenMP Language Terminology
  6686. // Structured block - An executable statement with a single entry at the
  6687. // top and a single exit at the bottom.
  6688. // The point of exit cannot be a branch out of the structured block.
  6689. // longjmp() and throw() must not violate the entry/exit criteria.
  6690. CS->getCapturedDecl()->setNothrow();
  6691. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_distribute_simd);
  6692. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  6693. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  6694. // 1.2.2 OpenMP Language Terminology
  6695. // Structured block - An executable statement with a single entry at the
  6696. // top and a single exit at the bottom.
  6697. // The point of exit cannot be a branch out of the structured block.
  6698. // longjmp() and throw() must not violate the entry/exit criteria.
  6699. CS->getCapturedDecl()->setNothrow();
  6700. }
  6701. OMPLoopDirective::HelperExprs B;
  6702. // In presence of clause 'collapse' with number of loops, it will
  6703. // define the nested loops number.
  6704. unsigned NestedLoopCount =
  6705. checkOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
  6706. nullptr /*ordered not a clause on distribute*/, CS, *this,
  6707. *DSAStack, VarsWithImplicitDSA, B);
  6708. if (NestedLoopCount == 0)
  6709. return StmtError();
  6710. assert((CurContext->isDependentContext() || B.builtAll()) &&
  6711. "omp for loop exprs were not built");
  6712. if (!CurContext->isDependentContext()) {
  6713. // Finalize the clauses that need pre-built expressions for CodeGen.
  6714. for (OMPClause *C : Clauses) {
  6715. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  6716. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  6717. B.NumIterations, *this, CurScope,
  6718. DSAStack))
  6719. return StmtError();
  6720. }
  6721. }
  6722. if (checkSimdlenSafelenSpecified(*this, Clauses))
  6723. return StmtError();
  6724. setFunctionHasBranchProtectedScope();
  6725. return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
  6726. NestedLoopCount, Clauses, AStmt, B);
  6727. }
  6728. StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
  6729. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  6730. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  6731. if (!AStmt)
  6732. return StmtError();
  6733. auto *CS = cast<CapturedStmt>(AStmt);
  6734. // 1.2.2 OpenMP Language Terminology
  6735. // Structured block - An executable statement with a single entry at the
  6736. // top and a single exit at the bottom.
  6737. // The point of exit cannot be a branch out of the structured block.
  6738. // longjmp() and throw() must not violate the entry/exit criteria.
  6739. CS->getCapturedDecl()->setNothrow();
  6740. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
  6741. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  6742. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  6743. // 1.2.2 OpenMP Language Terminology
  6744. // Structured block - An executable statement with a single entry at the
  6745. // top and a single exit at the bottom.
  6746. // The point of exit cannot be a branch out of the structured block.
  6747. // longjmp() and throw() must not violate the entry/exit criteria.
  6748. CS->getCapturedDecl()->setNothrow();
  6749. }
  6750. OMPLoopDirective::HelperExprs B;
  6751. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  6752. // define the nested loops number.
  6753. unsigned NestedLoopCount = checkOpenMPLoop(
  6754. OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
  6755. getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
  6756. VarsWithImplicitDSA, B);
  6757. if (NestedLoopCount == 0)
  6758. return StmtError();
  6759. assert((CurContext->isDependentContext() || B.builtAll()) &&
  6760. "omp target parallel for simd loop exprs were not built");
  6761. if (!CurContext->isDependentContext()) {
  6762. // Finalize the clauses that need pre-built expressions for CodeGen.
  6763. for (OMPClause *C : Clauses) {
  6764. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  6765. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  6766. B.NumIterations, *this, CurScope,
  6767. DSAStack))
  6768. return StmtError();
  6769. }
  6770. }
  6771. if (checkSimdlenSafelenSpecified(*this, Clauses))
  6772. return StmtError();
  6773. setFunctionHasBranchProtectedScope();
  6774. return OMPTargetParallelForSimdDirective::Create(
  6775. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  6776. }
  6777. StmtResult Sema::ActOnOpenMPTargetSimdDirective(
  6778. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  6779. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  6780. if (!AStmt)
  6781. return StmtError();
  6782. auto *CS = cast<CapturedStmt>(AStmt);
  6783. // 1.2.2 OpenMP Language Terminology
  6784. // Structured block - An executable statement with a single entry at the
  6785. // top and a single exit at the bottom.
  6786. // The point of exit cannot be a branch out of the structured block.
  6787. // longjmp() and throw() must not violate the entry/exit criteria.
  6788. CS->getCapturedDecl()->setNothrow();
  6789. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_simd);
  6790. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  6791. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  6792. // 1.2.2 OpenMP Language Terminology
  6793. // Structured block - An executable statement with a single entry at the
  6794. // top and a single exit at the bottom.
  6795. // The point of exit cannot be a branch out of the structured block.
  6796. // longjmp() and throw() must not violate the entry/exit criteria.
  6797. CS->getCapturedDecl()->setNothrow();
  6798. }
  6799. OMPLoopDirective::HelperExprs B;
  6800. // In presence of clause 'collapse' with number of loops, it will define the
  6801. // nested loops number.
  6802. unsigned NestedLoopCount =
  6803. checkOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
  6804. getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
  6805. VarsWithImplicitDSA, B);
  6806. if (NestedLoopCount == 0)
  6807. return StmtError();
  6808. assert((CurContext->isDependentContext() || B.builtAll()) &&
  6809. "omp target simd loop exprs were not built");
  6810. if (!CurContext->isDependentContext()) {
  6811. // Finalize the clauses that need pre-built expressions for CodeGen.
  6812. for (OMPClause *C : Clauses) {
  6813. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  6814. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  6815. B.NumIterations, *this, CurScope,
  6816. DSAStack))
  6817. return StmtError();
  6818. }
  6819. }
  6820. if (checkSimdlenSafelenSpecified(*this, Clauses))
  6821. return StmtError();
  6822. setFunctionHasBranchProtectedScope();
  6823. return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
  6824. NestedLoopCount, Clauses, AStmt, B);
  6825. }
  6826. StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
  6827. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  6828. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  6829. if (!AStmt)
  6830. return StmtError();
  6831. auto *CS = cast<CapturedStmt>(AStmt);
  6832. // 1.2.2 OpenMP Language Terminology
  6833. // Structured block - An executable statement with a single entry at the
  6834. // top and a single exit at the bottom.
  6835. // The point of exit cannot be a branch out of the structured block.
  6836. // longjmp() and throw() must not violate the entry/exit criteria.
  6837. CS->getCapturedDecl()->setNothrow();
  6838. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_teams_distribute);
  6839. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  6840. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  6841. // 1.2.2 OpenMP Language Terminology
  6842. // Structured block - An executable statement with a single entry at the
  6843. // top and a single exit at the bottom.
  6844. // The point of exit cannot be a branch out of the structured block.
  6845. // longjmp() and throw() must not violate the entry/exit criteria.
  6846. CS->getCapturedDecl()->setNothrow();
  6847. }
  6848. OMPLoopDirective::HelperExprs B;
  6849. // In presence of clause 'collapse' with number of loops, it will
  6850. // define the nested loops number.
  6851. unsigned NestedLoopCount =
  6852. checkOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
  6853. nullptr /*ordered not a clause on distribute*/, CS, *this,
  6854. *DSAStack, VarsWithImplicitDSA, B);
  6855. if (NestedLoopCount == 0)
  6856. return StmtError();
  6857. assert((CurContext->isDependentContext() || B.builtAll()) &&
  6858. "omp teams distribute loop exprs were not built");
  6859. setFunctionHasBranchProtectedScope();
  6860. DSAStack->setParentTeamsRegionLoc(StartLoc);
  6861. return OMPTeamsDistributeDirective::Create(
  6862. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  6863. }
  6864. StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
  6865. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  6866. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  6867. if (!AStmt)
  6868. return StmtError();
  6869. auto *CS = cast<CapturedStmt>(AStmt);
  6870. // 1.2.2 OpenMP Language Terminology
  6871. // Structured block - An executable statement with a single entry at the
  6872. // top and a single exit at the bottom.
  6873. // The point of exit cannot be a branch out of the structured block.
  6874. // longjmp() and throw() must not violate the entry/exit criteria.
  6875. CS->getCapturedDecl()->setNothrow();
  6876. for (int ThisCaptureLevel =
  6877. getOpenMPCaptureLevels(OMPD_teams_distribute_simd);
  6878. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  6879. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  6880. // 1.2.2 OpenMP Language Terminology
  6881. // Structured block - An executable statement with a single entry at the
  6882. // top and a single exit at the bottom.
  6883. // The point of exit cannot be a branch out of the structured block.
  6884. // longjmp() and throw() must not violate the entry/exit criteria.
  6885. CS->getCapturedDecl()->setNothrow();
  6886. }
  6887. OMPLoopDirective::HelperExprs B;
  6888. // In presence of clause 'collapse' with number of loops, it will
  6889. // define the nested loops number.
  6890. unsigned NestedLoopCount = checkOpenMPLoop(
  6891. OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
  6892. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  6893. VarsWithImplicitDSA, B);
  6894. if (NestedLoopCount == 0)
  6895. return StmtError();
  6896. assert((CurContext->isDependentContext() || B.builtAll()) &&
  6897. "omp teams distribute simd loop exprs were not built");
  6898. if (!CurContext->isDependentContext()) {
  6899. // Finalize the clauses that need pre-built expressions for CodeGen.
  6900. for (OMPClause *C : Clauses) {
  6901. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  6902. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  6903. B.NumIterations, *this, CurScope,
  6904. DSAStack))
  6905. return StmtError();
  6906. }
  6907. }
  6908. if (checkSimdlenSafelenSpecified(*this, Clauses))
  6909. return StmtError();
  6910. setFunctionHasBranchProtectedScope();
  6911. DSAStack->setParentTeamsRegionLoc(StartLoc);
  6912. return OMPTeamsDistributeSimdDirective::Create(
  6913. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  6914. }
  6915. StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
  6916. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  6917. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  6918. if (!AStmt)
  6919. return StmtError();
  6920. auto *CS = cast<CapturedStmt>(AStmt);
  6921. // 1.2.2 OpenMP Language Terminology
  6922. // Structured block - An executable statement with a single entry at the
  6923. // top and a single exit at the bottom.
  6924. // The point of exit cannot be a branch out of the structured block.
  6925. // longjmp() and throw() must not violate the entry/exit criteria.
  6926. CS->getCapturedDecl()->setNothrow();
  6927. for (int ThisCaptureLevel =
  6928. getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for_simd);
  6929. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  6930. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  6931. // 1.2.2 OpenMP Language Terminology
  6932. // Structured block - An executable statement with a single entry at the
  6933. // top and a single exit at the bottom.
  6934. // The point of exit cannot be a branch out of the structured block.
  6935. // longjmp() and throw() must not violate the entry/exit criteria.
  6936. CS->getCapturedDecl()->setNothrow();
  6937. }
  6938. OMPLoopDirective::HelperExprs B;
  6939. // In presence of clause 'collapse' with number of loops, it will
  6940. // define the nested loops number.
  6941. unsigned NestedLoopCount = checkOpenMPLoop(
  6942. OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
  6943. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  6944. VarsWithImplicitDSA, B);
  6945. if (NestedLoopCount == 0)
  6946. return StmtError();
  6947. assert((CurContext->isDependentContext() || B.builtAll()) &&
  6948. "omp for loop exprs were not built");
  6949. if (!CurContext->isDependentContext()) {
  6950. // Finalize the clauses that need pre-built expressions for CodeGen.
  6951. for (OMPClause *C : Clauses) {
  6952. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  6953. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  6954. B.NumIterations, *this, CurScope,
  6955. DSAStack))
  6956. return StmtError();
  6957. }
  6958. }
  6959. if (checkSimdlenSafelenSpecified(*this, Clauses))
  6960. return StmtError();
  6961. setFunctionHasBranchProtectedScope();
  6962. DSAStack->setParentTeamsRegionLoc(StartLoc);
  6963. return OMPTeamsDistributeParallelForSimdDirective::Create(
  6964. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  6965. }
  6966. StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
  6967. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  6968. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  6969. if (!AStmt)
  6970. return StmtError();
  6971. auto *CS = cast<CapturedStmt>(AStmt);
  6972. // 1.2.2 OpenMP Language Terminology
  6973. // Structured block - An executable statement with a single entry at the
  6974. // top and a single exit at the bottom.
  6975. // The point of exit cannot be a branch out of the structured block.
  6976. // longjmp() and throw() must not violate the entry/exit criteria.
  6977. CS->getCapturedDecl()->setNothrow();
  6978. for (int ThisCaptureLevel =
  6979. getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for);
  6980. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  6981. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  6982. // 1.2.2 OpenMP Language Terminology
  6983. // Structured block - An executable statement with a single entry at the
  6984. // top and a single exit at the bottom.
  6985. // The point of exit cannot be a branch out of the structured block.
  6986. // longjmp() and throw() must not violate the entry/exit criteria.
  6987. CS->getCapturedDecl()->setNothrow();
  6988. }
  6989. OMPLoopDirective::HelperExprs B;
  6990. // In presence of clause 'collapse' with number of loops, it will
  6991. // define the nested loops number.
  6992. unsigned NestedLoopCount = checkOpenMPLoop(
  6993. OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
  6994. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  6995. VarsWithImplicitDSA, B);
  6996. if (NestedLoopCount == 0)
  6997. return StmtError();
  6998. assert((CurContext->isDependentContext() || B.builtAll()) &&
  6999. "omp for loop exprs were not built");
  7000. setFunctionHasBranchProtectedScope();
  7001. DSAStack->setParentTeamsRegionLoc(StartLoc);
  7002. return OMPTeamsDistributeParallelForDirective::Create(
  7003. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
  7004. DSAStack->isCancelRegion());
  7005. }
  7006. StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
  7007. Stmt *AStmt,
  7008. SourceLocation StartLoc,
  7009. SourceLocation EndLoc) {
  7010. if (!AStmt)
  7011. return StmtError();
  7012. auto *CS = cast<CapturedStmt>(AStmt);
  7013. // 1.2.2 OpenMP Language Terminology
  7014. // Structured block - An executable statement with a single entry at the
  7015. // top and a single exit at the bottom.
  7016. // The point of exit cannot be a branch out of the structured block.
  7017. // longjmp() and throw() must not violate the entry/exit criteria.
  7018. CS->getCapturedDecl()->setNothrow();
  7019. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_teams);
  7020. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  7021. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  7022. // 1.2.2 OpenMP Language Terminology
  7023. // Structured block - An executable statement with a single entry at the
  7024. // top and a single exit at the bottom.
  7025. // The point of exit cannot be a branch out of the structured block.
  7026. // longjmp() and throw() must not violate the entry/exit criteria.
  7027. CS->getCapturedDecl()->setNothrow();
  7028. }
  7029. setFunctionHasBranchProtectedScope();
  7030. return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
  7031. AStmt);
  7032. }
  7033. StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective(
  7034. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  7035. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  7036. if (!AStmt)
  7037. return StmtError();
  7038. auto *CS = cast<CapturedStmt>(AStmt);
  7039. // 1.2.2 OpenMP Language Terminology
  7040. // Structured block - An executable statement with a single entry at the
  7041. // top and a single exit at the bottom.
  7042. // The point of exit cannot be a branch out of the structured block.
  7043. // longjmp() and throw() must not violate the entry/exit criteria.
  7044. CS->getCapturedDecl()->setNothrow();
  7045. for (int ThisCaptureLevel =
  7046. getOpenMPCaptureLevels(OMPD_target_teams_distribute);
  7047. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  7048. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  7049. // 1.2.2 OpenMP Language Terminology
  7050. // Structured block - An executable statement with a single entry at the
  7051. // top and a single exit at the bottom.
  7052. // The point of exit cannot be a branch out of the structured block.
  7053. // longjmp() and throw() must not violate the entry/exit criteria.
  7054. CS->getCapturedDecl()->setNothrow();
  7055. }
  7056. OMPLoopDirective::HelperExprs B;
  7057. // In presence of clause 'collapse' with number of loops, it will
  7058. // define the nested loops number.
  7059. unsigned NestedLoopCount = checkOpenMPLoop(
  7060. OMPD_target_teams_distribute, getCollapseNumberExpr(Clauses),
  7061. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  7062. VarsWithImplicitDSA, B);
  7063. if (NestedLoopCount == 0)
  7064. return StmtError();
  7065. assert((CurContext->isDependentContext() || B.builtAll()) &&
  7066. "omp target teams distribute loop exprs were not built");
  7067. setFunctionHasBranchProtectedScope();
  7068. return OMPTargetTeamsDistributeDirective::Create(
  7069. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  7070. }
  7071. StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective(
  7072. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  7073. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  7074. if (!AStmt)
  7075. return StmtError();
  7076. auto *CS = cast<CapturedStmt>(AStmt);
  7077. // 1.2.2 OpenMP Language Terminology
  7078. // Structured block - An executable statement with a single entry at the
  7079. // top and a single exit at the bottom.
  7080. // The point of exit cannot be a branch out of the structured block.
  7081. // longjmp() and throw() must not violate the entry/exit criteria.
  7082. CS->getCapturedDecl()->setNothrow();
  7083. for (int ThisCaptureLevel =
  7084. getOpenMPCaptureLevels(OMPD_target_teams_distribute_parallel_for);
  7085. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  7086. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  7087. // 1.2.2 OpenMP Language Terminology
  7088. // Structured block - An executable statement with a single entry at the
  7089. // top and a single exit at the bottom.
  7090. // The point of exit cannot be a branch out of the structured block.
  7091. // longjmp() and throw() must not violate the entry/exit criteria.
  7092. CS->getCapturedDecl()->setNothrow();
  7093. }
  7094. OMPLoopDirective::HelperExprs B;
  7095. // In presence of clause 'collapse' with number of loops, it will
  7096. // define the nested loops number.
  7097. unsigned NestedLoopCount = checkOpenMPLoop(
  7098. OMPD_target_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
  7099. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  7100. VarsWithImplicitDSA, B);
  7101. if (NestedLoopCount == 0)
  7102. return StmtError();
  7103. assert((CurContext->isDependentContext() || B.builtAll()) &&
  7104. "omp target teams distribute parallel for loop exprs were not built");
  7105. if (!CurContext->isDependentContext()) {
  7106. // Finalize the clauses that need pre-built expressions for CodeGen.
  7107. for (OMPClause *C : Clauses) {
  7108. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  7109. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  7110. B.NumIterations, *this, CurScope,
  7111. DSAStack))
  7112. return StmtError();
  7113. }
  7114. }
  7115. setFunctionHasBranchProtectedScope();
  7116. return OMPTargetTeamsDistributeParallelForDirective::Create(
  7117. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
  7118. DSAStack->isCancelRegion());
  7119. }
  7120. StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
  7121. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  7122. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  7123. if (!AStmt)
  7124. return StmtError();
  7125. auto *CS = cast<CapturedStmt>(AStmt);
  7126. // 1.2.2 OpenMP Language Terminology
  7127. // Structured block - An executable statement with a single entry at the
  7128. // top and a single exit at the bottom.
  7129. // The point of exit cannot be a branch out of the structured block.
  7130. // longjmp() and throw() must not violate the entry/exit criteria.
  7131. CS->getCapturedDecl()->setNothrow();
  7132. for (int ThisCaptureLevel = getOpenMPCaptureLevels(
  7133. OMPD_target_teams_distribute_parallel_for_simd);
  7134. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  7135. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  7136. // 1.2.2 OpenMP Language Terminology
  7137. // Structured block - An executable statement with a single entry at the
  7138. // top and a single exit at the bottom.
  7139. // The point of exit cannot be a branch out of the structured block.
  7140. // longjmp() and throw() must not violate the entry/exit criteria.
  7141. CS->getCapturedDecl()->setNothrow();
  7142. }
  7143. OMPLoopDirective::HelperExprs B;
  7144. // In presence of clause 'collapse' with number of loops, it will
  7145. // define the nested loops number.
  7146. unsigned NestedLoopCount =
  7147. checkOpenMPLoop(OMPD_target_teams_distribute_parallel_for_simd,
  7148. getCollapseNumberExpr(Clauses),
  7149. nullptr /*ordered not a clause on distribute*/, CS, *this,
  7150. *DSAStack, VarsWithImplicitDSA, B);
  7151. if (NestedLoopCount == 0)
  7152. return StmtError();
  7153. assert((CurContext->isDependentContext() || B.builtAll()) &&
  7154. "omp target teams distribute parallel for simd loop exprs were not "
  7155. "built");
  7156. if (!CurContext->isDependentContext()) {
  7157. // Finalize the clauses that need pre-built expressions for CodeGen.
  7158. for (OMPClause *C : Clauses) {
  7159. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  7160. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  7161. B.NumIterations, *this, CurScope,
  7162. DSAStack))
  7163. return StmtError();
  7164. }
  7165. }
  7166. if (checkSimdlenSafelenSpecified(*this, Clauses))
  7167. return StmtError();
  7168. setFunctionHasBranchProtectedScope();
  7169. return OMPTargetTeamsDistributeParallelForSimdDirective::Create(
  7170. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  7171. }
  7172. StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective(
  7173. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  7174. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  7175. if (!AStmt)
  7176. return StmtError();
  7177. auto *CS = cast<CapturedStmt>(AStmt);
  7178. // 1.2.2 OpenMP Language Terminology
  7179. // Structured block - An executable statement with a single entry at the
  7180. // top and a single exit at the bottom.
  7181. // The point of exit cannot be a branch out of the structured block.
  7182. // longjmp() and throw() must not violate the entry/exit criteria.
  7183. CS->getCapturedDecl()->setNothrow();
  7184. for (int ThisCaptureLevel =
  7185. getOpenMPCaptureLevels(OMPD_target_teams_distribute_simd);
  7186. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  7187. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  7188. // 1.2.2 OpenMP Language Terminology
  7189. // Structured block - An executable statement with a single entry at the
  7190. // top and a single exit at the bottom.
  7191. // The point of exit cannot be a branch out of the structured block.
  7192. // longjmp() and throw() must not violate the entry/exit criteria.
  7193. CS->getCapturedDecl()->setNothrow();
  7194. }
  7195. OMPLoopDirective::HelperExprs B;
  7196. // In presence of clause 'collapse' with number of loops, it will
  7197. // define the nested loops number.
  7198. unsigned NestedLoopCount = checkOpenMPLoop(
  7199. OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses),
  7200. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  7201. VarsWithImplicitDSA, B);
  7202. if (NestedLoopCount == 0)
  7203. return StmtError();
  7204. assert((CurContext->isDependentContext() || B.builtAll()) &&
  7205. "omp target teams distribute simd loop exprs were not built");
  7206. if (!CurContext->isDependentContext()) {
  7207. // Finalize the clauses that need pre-built expressions for CodeGen.
  7208. for (OMPClause *C : Clauses) {
  7209. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  7210. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  7211. B.NumIterations, *this, CurScope,
  7212. DSAStack))
  7213. return StmtError();
  7214. }
  7215. }
  7216. if (checkSimdlenSafelenSpecified(*this, Clauses))
  7217. return StmtError();
  7218. setFunctionHasBranchProtectedScope();
  7219. return OMPTargetTeamsDistributeSimdDirective::Create(
  7220. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  7221. }
  7222. OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
  7223. SourceLocation StartLoc,
  7224. SourceLocation LParenLoc,
  7225. SourceLocation EndLoc) {
  7226. OMPClause *Res = nullptr;
  7227. switch (Kind) {
  7228. case OMPC_final:
  7229. Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
  7230. break;
  7231. case OMPC_num_threads:
  7232. Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
  7233. break;
  7234. case OMPC_safelen:
  7235. Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
  7236. break;
  7237. case OMPC_simdlen:
  7238. Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
  7239. break;
  7240. case OMPC_collapse:
  7241. Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
  7242. break;
  7243. case OMPC_ordered:
  7244. Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
  7245. break;
  7246. case OMPC_device:
  7247. Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
  7248. break;
  7249. case OMPC_num_teams:
  7250. Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
  7251. break;
  7252. case OMPC_thread_limit:
  7253. Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
  7254. break;
  7255. case OMPC_priority:
  7256. Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
  7257. break;
  7258. case OMPC_grainsize:
  7259. Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
  7260. break;
  7261. case OMPC_num_tasks:
  7262. Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
  7263. break;
  7264. case OMPC_hint:
  7265. Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
  7266. break;
  7267. case OMPC_if:
  7268. case OMPC_default:
  7269. case OMPC_proc_bind:
  7270. case OMPC_schedule:
  7271. case OMPC_private:
  7272. case OMPC_firstprivate:
  7273. case OMPC_lastprivate:
  7274. case OMPC_shared:
  7275. case OMPC_reduction:
  7276. case OMPC_task_reduction:
  7277. case OMPC_in_reduction:
  7278. case OMPC_linear:
  7279. case OMPC_aligned:
  7280. case OMPC_copyin:
  7281. case OMPC_copyprivate:
  7282. case OMPC_nowait:
  7283. case OMPC_untied:
  7284. case OMPC_mergeable:
  7285. case OMPC_threadprivate:
  7286. case OMPC_flush:
  7287. case OMPC_read:
  7288. case OMPC_write:
  7289. case OMPC_update:
  7290. case OMPC_capture:
  7291. case OMPC_seq_cst:
  7292. case OMPC_depend:
  7293. case OMPC_threads:
  7294. case OMPC_simd:
  7295. case OMPC_map:
  7296. case OMPC_nogroup:
  7297. case OMPC_dist_schedule:
  7298. case OMPC_defaultmap:
  7299. case OMPC_unknown:
  7300. case OMPC_uniform:
  7301. case OMPC_to:
  7302. case OMPC_from:
  7303. case OMPC_use_device_ptr:
  7304. case OMPC_is_device_ptr:
  7305. llvm_unreachable("Clause is not allowed.");
  7306. }
  7307. return Res;
  7308. }
  7309. // An OpenMP directive such as 'target parallel' has two captured regions:
  7310. // for the 'target' and 'parallel' respectively. This function returns
  7311. // the region in which to capture expressions associated with a clause.
  7312. // A return value of OMPD_unknown signifies that the expression should not
  7313. // be captured.
  7314. static OpenMPDirectiveKind getOpenMPCaptureRegionForClause(
  7315. OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
  7316. OpenMPDirectiveKind NameModifier = OMPD_unknown) {
  7317. OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
  7318. switch (CKind) {
  7319. case OMPC_if:
  7320. switch (DKind) {
  7321. case OMPD_target_parallel:
  7322. case OMPD_target_parallel_for:
  7323. case OMPD_target_parallel_for_simd:
  7324. // If this clause applies to the nested 'parallel' region, capture within
  7325. // the 'target' region, otherwise do not capture.
  7326. if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
  7327. CaptureRegion = OMPD_target;
  7328. break;
  7329. case OMPD_target_teams_distribute_parallel_for:
  7330. case OMPD_target_teams_distribute_parallel_for_simd:
  7331. // If this clause applies to the nested 'parallel' region, capture within
  7332. // the 'teams' region, otherwise do not capture.
  7333. if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
  7334. CaptureRegion = OMPD_teams;
  7335. break;
  7336. case OMPD_teams_distribute_parallel_for:
  7337. case OMPD_teams_distribute_parallel_for_simd:
  7338. CaptureRegion = OMPD_teams;
  7339. break;
  7340. case OMPD_target_update:
  7341. case OMPD_target_enter_data:
  7342. case OMPD_target_exit_data:
  7343. CaptureRegion = OMPD_task;
  7344. break;
  7345. case OMPD_cancel:
  7346. case OMPD_parallel:
  7347. case OMPD_parallel_sections:
  7348. case OMPD_parallel_for:
  7349. case OMPD_parallel_for_simd:
  7350. case OMPD_target:
  7351. case OMPD_target_simd:
  7352. case OMPD_target_teams:
  7353. case OMPD_target_teams_distribute:
  7354. case OMPD_target_teams_distribute_simd:
  7355. case OMPD_distribute_parallel_for:
  7356. case OMPD_distribute_parallel_for_simd:
  7357. case OMPD_task:
  7358. case OMPD_taskloop:
  7359. case OMPD_taskloop_simd:
  7360. case OMPD_target_data:
  7361. // Do not capture if-clause expressions.
  7362. break;
  7363. case OMPD_threadprivate:
  7364. case OMPD_taskyield:
  7365. case OMPD_barrier:
  7366. case OMPD_taskwait:
  7367. case OMPD_cancellation_point:
  7368. case OMPD_flush:
  7369. case OMPD_declare_reduction:
  7370. case OMPD_declare_simd:
  7371. case OMPD_declare_target:
  7372. case OMPD_end_declare_target:
  7373. case OMPD_teams:
  7374. case OMPD_simd:
  7375. case OMPD_for:
  7376. case OMPD_for_simd:
  7377. case OMPD_sections:
  7378. case OMPD_section:
  7379. case OMPD_single:
  7380. case OMPD_master:
  7381. case OMPD_critical:
  7382. case OMPD_taskgroup:
  7383. case OMPD_distribute:
  7384. case OMPD_ordered:
  7385. case OMPD_atomic:
  7386. case OMPD_distribute_simd:
  7387. case OMPD_teams_distribute:
  7388. case OMPD_teams_distribute_simd:
  7389. llvm_unreachable("Unexpected OpenMP directive with if-clause");
  7390. case OMPD_unknown:
  7391. llvm_unreachable("Unknown OpenMP directive");
  7392. }
  7393. break;
  7394. case OMPC_num_threads:
  7395. switch (DKind) {
  7396. case OMPD_target_parallel:
  7397. case OMPD_target_parallel_for:
  7398. case OMPD_target_parallel_for_simd:
  7399. CaptureRegion = OMPD_target;
  7400. break;
  7401. case OMPD_teams_distribute_parallel_for:
  7402. case OMPD_teams_distribute_parallel_for_simd:
  7403. case OMPD_target_teams_distribute_parallel_for:
  7404. case OMPD_target_teams_distribute_parallel_for_simd:
  7405. CaptureRegion = OMPD_teams;
  7406. break;
  7407. case OMPD_parallel:
  7408. case OMPD_parallel_sections:
  7409. case OMPD_parallel_for:
  7410. case OMPD_parallel_for_simd:
  7411. case OMPD_distribute_parallel_for:
  7412. case OMPD_distribute_parallel_for_simd:
  7413. // Do not capture num_threads-clause expressions.
  7414. break;
  7415. case OMPD_target_data:
  7416. case OMPD_target_enter_data:
  7417. case OMPD_target_exit_data:
  7418. case OMPD_target_update:
  7419. case OMPD_target:
  7420. case OMPD_target_simd:
  7421. case OMPD_target_teams:
  7422. case OMPD_target_teams_distribute:
  7423. case OMPD_target_teams_distribute_simd:
  7424. case OMPD_cancel:
  7425. case OMPD_task:
  7426. case OMPD_taskloop:
  7427. case OMPD_taskloop_simd:
  7428. case OMPD_threadprivate:
  7429. case OMPD_taskyield:
  7430. case OMPD_barrier:
  7431. case OMPD_taskwait:
  7432. case OMPD_cancellation_point:
  7433. case OMPD_flush:
  7434. case OMPD_declare_reduction:
  7435. case OMPD_declare_simd:
  7436. case OMPD_declare_target:
  7437. case OMPD_end_declare_target:
  7438. case OMPD_teams:
  7439. case OMPD_simd:
  7440. case OMPD_for:
  7441. case OMPD_for_simd:
  7442. case OMPD_sections:
  7443. case OMPD_section:
  7444. case OMPD_single:
  7445. case OMPD_master:
  7446. case OMPD_critical:
  7447. case OMPD_taskgroup:
  7448. case OMPD_distribute:
  7449. case OMPD_ordered:
  7450. case OMPD_atomic:
  7451. case OMPD_distribute_simd:
  7452. case OMPD_teams_distribute:
  7453. case OMPD_teams_distribute_simd:
  7454. llvm_unreachable("Unexpected OpenMP directive with num_threads-clause");
  7455. case OMPD_unknown:
  7456. llvm_unreachable("Unknown OpenMP directive");
  7457. }
  7458. break;
  7459. case OMPC_num_teams:
  7460. switch (DKind) {
  7461. case OMPD_target_teams:
  7462. case OMPD_target_teams_distribute:
  7463. case OMPD_target_teams_distribute_simd:
  7464. case OMPD_target_teams_distribute_parallel_for:
  7465. case OMPD_target_teams_distribute_parallel_for_simd:
  7466. CaptureRegion = OMPD_target;
  7467. break;
  7468. case OMPD_teams_distribute_parallel_for:
  7469. case OMPD_teams_distribute_parallel_for_simd:
  7470. case OMPD_teams:
  7471. case OMPD_teams_distribute:
  7472. case OMPD_teams_distribute_simd:
  7473. // Do not capture num_teams-clause expressions.
  7474. break;
  7475. case OMPD_distribute_parallel_for:
  7476. case OMPD_distribute_parallel_for_simd:
  7477. case OMPD_task:
  7478. case OMPD_taskloop:
  7479. case OMPD_taskloop_simd:
  7480. case OMPD_target_data:
  7481. case OMPD_target_enter_data:
  7482. case OMPD_target_exit_data:
  7483. case OMPD_target_update:
  7484. case OMPD_cancel:
  7485. case OMPD_parallel:
  7486. case OMPD_parallel_sections:
  7487. case OMPD_parallel_for:
  7488. case OMPD_parallel_for_simd:
  7489. case OMPD_target:
  7490. case OMPD_target_simd:
  7491. case OMPD_target_parallel:
  7492. case OMPD_target_parallel_for:
  7493. case OMPD_target_parallel_for_simd:
  7494. case OMPD_threadprivate:
  7495. case OMPD_taskyield:
  7496. case OMPD_barrier:
  7497. case OMPD_taskwait:
  7498. case OMPD_cancellation_point:
  7499. case OMPD_flush:
  7500. case OMPD_declare_reduction:
  7501. case OMPD_declare_simd:
  7502. case OMPD_declare_target:
  7503. case OMPD_end_declare_target:
  7504. case OMPD_simd:
  7505. case OMPD_for:
  7506. case OMPD_for_simd:
  7507. case OMPD_sections:
  7508. case OMPD_section:
  7509. case OMPD_single:
  7510. case OMPD_master:
  7511. case OMPD_critical:
  7512. case OMPD_taskgroup:
  7513. case OMPD_distribute:
  7514. case OMPD_ordered:
  7515. case OMPD_atomic:
  7516. case OMPD_distribute_simd:
  7517. llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
  7518. case OMPD_unknown:
  7519. llvm_unreachable("Unknown OpenMP directive");
  7520. }
  7521. break;
  7522. case OMPC_thread_limit:
  7523. switch (DKind) {
  7524. case OMPD_target_teams:
  7525. case OMPD_target_teams_distribute:
  7526. case OMPD_target_teams_distribute_simd:
  7527. case OMPD_target_teams_distribute_parallel_for:
  7528. case OMPD_target_teams_distribute_parallel_for_simd:
  7529. CaptureRegion = OMPD_target;
  7530. break;
  7531. case OMPD_teams_distribute_parallel_for:
  7532. case OMPD_teams_distribute_parallel_for_simd:
  7533. case OMPD_teams:
  7534. case OMPD_teams_distribute:
  7535. case OMPD_teams_distribute_simd:
  7536. // Do not capture thread_limit-clause expressions.
  7537. break;
  7538. case OMPD_distribute_parallel_for:
  7539. case OMPD_distribute_parallel_for_simd:
  7540. case OMPD_task:
  7541. case OMPD_taskloop:
  7542. case OMPD_taskloop_simd:
  7543. case OMPD_target_data:
  7544. case OMPD_target_enter_data:
  7545. case OMPD_target_exit_data:
  7546. case OMPD_target_update:
  7547. case OMPD_cancel:
  7548. case OMPD_parallel:
  7549. case OMPD_parallel_sections:
  7550. case OMPD_parallel_for:
  7551. case OMPD_parallel_for_simd:
  7552. case OMPD_target:
  7553. case OMPD_target_simd:
  7554. case OMPD_target_parallel:
  7555. case OMPD_target_parallel_for:
  7556. case OMPD_target_parallel_for_simd:
  7557. case OMPD_threadprivate:
  7558. case OMPD_taskyield:
  7559. case OMPD_barrier:
  7560. case OMPD_taskwait:
  7561. case OMPD_cancellation_point:
  7562. case OMPD_flush:
  7563. case OMPD_declare_reduction:
  7564. case OMPD_declare_simd:
  7565. case OMPD_declare_target:
  7566. case OMPD_end_declare_target:
  7567. case OMPD_simd:
  7568. case OMPD_for:
  7569. case OMPD_for_simd:
  7570. case OMPD_sections:
  7571. case OMPD_section:
  7572. case OMPD_single:
  7573. case OMPD_master:
  7574. case OMPD_critical:
  7575. case OMPD_taskgroup:
  7576. case OMPD_distribute:
  7577. case OMPD_ordered:
  7578. case OMPD_atomic:
  7579. case OMPD_distribute_simd:
  7580. llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause");
  7581. case OMPD_unknown:
  7582. llvm_unreachable("Unknown OpenMP directive");
  7583. }
  7584. break;
  7585. case OMPC_schedule:
  7586. switch (DKind) {
  7587. case OMPD_parallel_for:
  7588. case OMPD_parallel_for_simd:
  7589. case OMPD_distribute_parallel_for:
  7590. case OMPD_distribute_parallel_for_simd:
  7591. case OMPD_teams_distribute_parallel_for:
  7592. case OMPD_teams_distribute_parallel_for_simd:
  7593. case OMPD_target_parallel_for:
  7594. case OMPD_target_parallel_for_simd:
  7595. case OMPD_target_teams_distribute_parallel_for:
  7596. case OMPD_target_teams_distribute_parallel_for_simd:
  7597. CaptureRegion = OMPD_parallel;
  7598. break;
  7599. case OMPD_for:
  7600. case OMPD_for_simd:
  7601. // Do not capture schedule-clause expressions.
  7602. break;
  7603. case OMPD_task:
  7604. case OMPD_taskloop:
  7605. case OMPD_taskloop_simd:
  7606. case OMPD_target_data:
  7607. case OMPD_target_enter_data:
  7608. case OMPD_target_exit_data:
  7609. case OMPD_target_update:
  7610. case OMPD_teams:
  7611. case OMPD_teams_distribute:
  7612. case OMPD_teams_distribute_simd:
  7613. case OMPD_target_teams_distribute:
  7614. case OMPD_target_teams_distribute_simd:
  7615. case OMPD_target:
  7616. case OMPD_target_simd:
  7617. case OMPD_target_parallel:
  7618. case OMPD_cancel:
  7619. case OMPD_parallel:
  7620. case OMPD_parallel_sections:
  7621. case OMPD_threadprivate:
  7622. case OMPD_taskyield:
  7623. case OMPD_barrier:
  7624. case OMPD_taskwait:
  7625. case OMPD_cancellation_point:
  7626. case OMPD_flush:
  7627. case OMPD_declare_reduction:
  7628. case OMPD_declare_simd:
  7629. case OMPD_declare_target:
  7630. case OMPD_end_declare_target:
  7631. case OMPD_simd:
  7632. case OMPD_sections:
  7633. case OMPD_section:
  7634. case OMPD_single:
  7635. case OMPD_master:
  7636. case OMPD_critical:
  7637. case OMPD_taskgroup:
  7638. case OMPD_distribute:
  7639. case OMPD_ordered:
  7640. case OMPD_atomic:
  7641. case OMPD_distribute_simd:
  7642. case OMPD_target_teams:
  7643. llvm_unreachable("Unexpected OpenMP directive with schedule clause");
  7644. case OMPD_unknown:
  7645. llvm_unreachable("Unknown OpenMP directive");
  7646. }
  7647. break;
  7648. case OMPC_dist_schedule:
  7649. switch (DKind) {
  7650. case OMPD_teams_distribute_parallel_for:
  7651. case OMPD_teams_distribute_parallel_for_simd:
  7652. case OMPD_teams_distribute:
  7653. case OMPD_teams_distribute_simd:
  7654. case OMPD_target_teams_distribute_parallel_for:
  7655. case OMPD_target_teams_distribute_parallel_for_simd:
  7656. case OMPD_target_teams_distribute:
  7657. case OMPD_target_teams_distribute_simd:
  7658. CaptureRegion = OMPD_teams;
  7659. break;
  7660. case OMPD_distribute_parallel_for:
  7661. case OMPD_distribute_parallel_for_simd:
  7662. case OMPD_distribute:
  7663. case OMPD_distribute_simd:
  7664. // Do not capture thread_limit-clause expressions.
  7665. break;
  7666. case OMPD_parallel_for:
  7667. case OMPD_parallel_for_simd:
  7668. case OMPD_target_parallel_for_simd:
  7669. case OMPD_target_parallel_for:
  7670. case OMPD_task:
  7671. case OMPD_taskloop:
  7672. case OMPD_taskloop_simd:
  7673. case OMPD_target_data:
  7674. case OMPD_target_enter_data:
  7675. case OMPD_target_exit_data:
  7676. case OMPD_target_update:
  7677. case OMPD_teams:
  7678. case OMPD_target:
  7679. case OMPD_target_simd:
  7680. case OMPD_target_parallel:
  7681. case OMPD_cancel:
  7682. case OMPD_parallel:
  7683. case OMPD_parallel_sections:
  7684. case OMPD_threadprivate:
  7685. case OMPD_taskyield:
  7686. case OMPD_barrier:
  7687. case OMPD_taskwait:
  7688. case OMPD_cancellation_point:
  7689. case OMPD_flush:
  7690. case OMPD_declare_reduction:
  7691. case OMPD_declare_simd:
  7692. case OMPD_declare_target:
  7693. case OMPD_end_declare_target:
  7694. case OMPD_simd:
  7695. case OMPD_for:
  7696. case OMPD_for_simd:
  7697. case OMPD_sections:
  7698. case OMPD_section:
  7699. case OMPD_single:
  7700. case OMPD_master:
  7701. case OMPD_critical:
  7702. case OMPD_taskgroup:
  7703. case OMPD_ordered:
  7704. case OMPD_atomic:
  7705. case OMPD_target_teams:
  7706. llvm_unreachable("Unexpected OpenMP directive with schedule clause");
  7707. case OMPD_unknown:
  7708. llvm_unreachable("Unknown OpenMP directive");
  7709. }
  7710. break;
  7711. case OMPC_device:
  7712. switch (DKind) {
  7713. case OMPD_target_update:
  7714. case OMPD_target_enter_data:
  7715. case OMPD_target_exit_data:
  7716. case OMPD_target:
  7717. case OMPD_target_simd:
  7718. case OMPD_target_teams:
  7719. case OMPD_target_parallel:
  7720. case OMPD_target_teams_distribute:
  7721. case OMPD_target_teams_distribute_simd:
  7722. case OMPD_target_parallel_for:
  7723. case OMPD_target_parallel_for_simd:
  7724. case OMPD_target_teams_distribute_parallel_for:
  7725. case OMPD_target_teams_distribute_parallel_for_simd:
  7726. CaptureRegion = OMPD_task;
  7727. break;
  7728. case OMPD_target_data:
  7729. // Do not capture device-clause expressions.
  7730. break;
  7731. case OMPD_teams_distribute_parallel_for:
  7732. case OMPD_teams_distribute_parallel_for_simd:
  7733. case OMPD_teams:
  7734. case OMPD_teams_distribute:
  7735. case OMPD_teams_distribute_simd:
  7736. case OMPD_distribute_parallel_for:
  7737. case OMPD_distribute_parallel_for_simd:
  7738. case OMPD_task:
  7739. case OMPD_taskloop:
  7740. case OMPD_taskloop_simd:
  7741. case OMPD_cancel:
  7742. case OMPD_parallel:
  7743. case OMPD_parallel_sections:
  7744. case OMPD_parallel_for:
  7745. case OMPD_parallel_for_simd:
  7746. case OMPD_threadprivate:
  7747. case OMPD_taskyield:
  7748. case OMPD_barrier:
  7749. case OMPD_taskwait:
  7750. case OMPD_cancellation_point:
  7751. case OMPD_flush:
  7752. case OMPD_declare_reduction:
  7753. case OMPD_declare_simd:
  7754. case OMPD_declare_target:
  7755. case OMPD_end_declare_target:
  7756. case OMPD_simd:
  7757. case OMPD_for:
  7758. case OMPD_for_simd:
  7759. case OMPD_sections:
  7760. case OMPD_section:
  7761. case OMPD_single:
  7762. case OMPD_master:
  7763. case OMPD_critical:
  7764. case OMPD_taskgroup:
  7765. case OMPD_distribute:
  7766. case OMPD_ordered:
  7767. case OMPD_atomic:
  7768. case OMPD_distribute_simd:
  7769. llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
  7770. case OMPD_unknown:
  7771. llvm_unreachable("Unknown OpenMP directive");
  7772. }
  7773. break;
  7774. case OMPC_firstprivate:
  7775. case OMPC_lastprivate:
  7776. case OMPC_reduction:
  7777. case OMPC_task_reduction:
  7778. case OMPC_in_reduction:
  7779. case OMPC_linear:
  7780. case OMPC_default:
  7781. case OMPC_proc_bind:
  7782. case OMPC_final:
  7783. case OMPC_safelen:
  7784. case OMPC_simdlen:
  7785. case OMPC_collapse:
  7786. case OMPC_private:
  7787. case OMPC_shared:
  7788. case OMPC_aligned:
  7789. case OMPC_copyin:
  7790. case OMPC_copyprivate:
  7791. case OMPC_ordered:
  7792. case OMPC_nowait:
  7793. case OMPC_untied:
  7794. case OMPC_mergeable:
  7795. case OMPC_threadprivate:
  7796. case OMPC_flush:
  7797. case OMPC_read:
  7798. case OMPC_write:
  7799. case OMPC_update:
  7800. case OMPC_capture:
  7801. case OMPC_seq_cst:
  7802. case OMPC_depend:
  7803. case OMPC_threads:
  7804. case OMPC_simd:
  7805. case OMPC_map:
  7806. case OMPC_priority:
  7807. case OMPC_grainsize:
  7808. case OMPC_nogroup:
  7809. case OMPC_num_tasks:
  7810. case OMPC_hint:
  7811. case OMPC_defaultmap:
  7812. case OMPC_unknown:
  7813. case OMPC_uniform:
  7814. case OMPC_to:
  7815. case OMPC_from:
  7816. case OMPC_use_device_ptr:
  7817. case OMPC_is_device_ptr:
  7818. llvm_unreachable("Unexpected OpenMP clause.");
  7819. }
  7820. return CaptureRegion;
  7821. }
  7822. OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
  7823. Expr *Condition, SourceLocation StartLoc,
  7824. SourceLocation LParenLoc,
  7825. SourceLocation NameModifierLoc,
  7826. SourceLocation ColonLoc,
  7827. SourceLocation EndLoc) {
  7828. Expr *ValExpr = Condition;
  7829. Stmt *HelperValStmt = nullptr;
  7830. OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
  7831. if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
  7832. !Condition->isInstantiationDependent() &&
  7833. !Condition->containsUnexpandedParameterPack()) {
  7834. ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
  7835. if (Val.isInvalid())
  7836. return nullptr;
  7837. ValExpr = Val.get();
  7838. OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
  7839. CaptureRegion =
  7840. getOpenMPCaptureRegionForClause(DKind, OMPC_if, NameModifier);
  7841. if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
  7842. ValExpr = MakeFullExpr(ValExpr).get();
  7843. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  7844. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  7845. HelperValStmt = buildPreInits(Context, Captures);
  7846. }
  7847. }
  7848. return new (Context)
  7849. OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
  7850. LParenLoc, NameModifierLoc, ColonLoc, EndLoc);
  7851. }
  7852. OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
  7853. SourceLocation StartLoc,
  7854. SourceLocation LParenLoc,
  7855. SourceLocation EndLoc) {
  7856. Expr *ValExpr = Condition;
  7857. if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
  7858. !Condition->isInstantiationDependent() &&
  7859. !Condition->containsUnexpandedParameterPack()) {
  7860. ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
  7861. if (Val.isInvalid())
  7862. return nullptr;
  7863. ValExpr = MakeFullExpr(Val.get()).get();
  7864. }
  7865. return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
  7866. }
  7867. ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
  7868. Expr *Op) {
  7869. if (!Op)
  7870. return ExprError();
  7871. class IntConvertDiagnoser : public ICEConvertDiagnoser {
  7872. public:
  7873. IntConvertDiagnoser()
  7874. : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
  7875. SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
  7876. QualType T) override {
  7877. return S.Diag(Loc, diag::err_omp_not_integral) << T;
  7878. }
  7879. SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
  7880. QualType T) override {
  7881. return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
  7882. }
  7883. SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
  7884. QualType T,
  7885. QualType ConvTy) override {
  7886. return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
  7887. }
  7888. SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
  7889. QualType ConvTy) override {
  7890. return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
  7891. << ConvTy->isEnumeralType() << ConvTy;
  7892. }
  7893. SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
  7894. QualType T) override {
  7895. return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
  7896. }
  7897. SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
  7898. QualType ConvTy) override {
  7899. return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
  7900. << ConvTy->isEnumeralType() << ConvTy;
  7901. }
  7902. SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
  7903. QualType) override {
  7904. llvm_unreachable("conversion functions are permitted");
  7905. }
  7906. } ConvertDiagnoser;
  7907. return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
  7908. }
  7909. static bool isNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef,
  7910. OpenMPClauseKind CKind,
  7911. bool StrictlyPositive) {
  7912. if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
  7913. !ValExpr->isInstantiationDependent()) {
  7914. SourceLocation Loc = ValExpr->getExprLoc();
  7915. ExprResult Value =
  7916. SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
  7917. if (Value.isInvalid())
  7918. return false;
  7919. ValExpr = Value.get();
  7920. // The expression must evaluate to a non-negative integer value.
  7921. llvm::APSInt Result;
  7922. if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
  7923. Result.isSigned() &&
  7924. !((!StrictlyPositive && Result.isNonNegative()) ||
  7925. (StrictlyPositive && Result.isStrictlyPositive()))) {
  7926. SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
  7927. << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
  7928. << ValExpr->getSourceRange();
  7929. return false;
  7930. }
  7931. }
  7932. return true;
  7933. }
  7934. OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
  7935. SourceLocation StartLoc,
  7936. SourceLocation LParenLoc,
  7937. SourceLocation EndLoc) {
  7938. Expr *ValExpr = NumThreads;
  7939. Stmt *HelperValStmt = nullptr;
  7940. // OpenMP [2.5, Restrictions]
  7941. // The num_threads expression must evaluate to a positive integer value.
  7942. if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
  7943. /*StrictlyPositive=*/true))
  7944. return nullptr;
  7945. OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
  7946. OpenMPDirectiveKind CaptureRegion =
  7947. getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads);
  7948. if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
  7949. ValExpr = MakeFullExpr(ValExpr).get();
  7950. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  7951. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  7952. HelperValStmt = buildPreInits(Context, Captures);
  7953. }
  7954. return new (Context) OMPNumThreadsClause(
  7955. ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
  7956. }
  7957. ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
  7958. OpenMPClauseKind CKind,
  7959. bool StrictlyPositive) {
  7960. if (!E)
  7961. return ExprError();
  7962. if (E->isValueDependent() || E->isTypeDependent() ||
  7963. E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
  7964. return E;
  7965. llvm::APSInt Result;
  7966. ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
  7967. if (ICE.isInvalid())
  7968. return ExprError();
  7969. if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
  7970. (!StrictlyPositive && !Result.isNonNegative())) {
  7971. Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
  7972. << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
  7973. << E->getSourceRange();
  7974. return ExprError();
  7975. }
  7976. if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
  7977. Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
  7978. << E->getSourceRange();
  7979. return ExprError();
  7980. }
  7981. if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
  7982. DSAStack->setAssociatedLoops(Result.getExtValue());
  7983. else if (CKind == OMPC_ordered)
  7984. DSAStack->setAssociatedLoops(Result.getExtValue());
  7985. return ICE;
  7986. }
  7987. OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
  7988. SourceLocation LParenLoc,
  7989. SourceLocation EndLoc) {
  7990. // OpenMP [2.8.1, simd construct, Description]
  7991. // The parameter of the safelen clause must be a constant
  7992. // positive integer expression.
  7993. ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
  7994. if (Safelen.isInvalid())
  7995. return nullptr;
  7996. return new (Context)
  7997. OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
  7998. }
  7999. OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
  8000. SourceLocation LParenLoc,
  8001. SourceLocation EndLoc) {
  8002. // OpenMP [2.8.1, simd construct, Description]
  8003. // The parameter of the simdlen clause must be a constant
  8004. // positive integer expression.
  8005. ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
  8006. if (Simdlen.isInvalid())
  8007. return nullptr;
  8008. return new (Context)
  8009. OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
  8010. }
  8011. OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
  8012. SourceLocation StartLoc,
  8013. SourceLocation LParenLoc,
  8014. SourceLocation EndLoc) {
  8015. // OpenMP [2.7.1, loop construct, Description]
  8016. // OpenMP [2.8.1, simd construct, Description]
  8017. // OpenMP [2.9.6, distribute construct, Description]
  8018. // The parameter of the collapse clause must be a constant
  8019. // positive integer expression.
  8020. ExprResult NumForLoopsResult =
  8021. VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
  8022. if (NumForLoopsResult.isInvalid())
  8023. return nullptr;
  8024. return new (Context)
  8025. OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
  8026. }
  8027. OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
  8028. SourceLocation EndLoc,
  8029. SourceLocation LParenLoc,
  8030. Expr *NumForLoops) {
  8031. // OpenMP [2.7.1, loop construct, Description]
  8032. // OpenMP [2.8.1, simd construct, Description]
  8033. // OpenMP [2.9.6, distribute construct, Description]
  8034. // The parameter of the ordered clause must be a constant
  8035. // positive integer expression if any.
  8036. if (NumForLoops && LParenLoc.isValid()) {
  8037. ExprResult NumForLoopsResult =
  8038. VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
  8039. if (NumForLoopsResult.isInvalid())
  8040. return nullptr;
  8041. NumForLoops = NumForLoopsResult.get();
  8042. } else {
  8043. NumForLoops = nullptr;
  8044. }
  8045. DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops);
  8046. return new (Context)
  8047. OMPOrderedClause(NumForLoops, StartLoc, LParenLoc, EndLoc);
  8048. }
  8049. OMPClause *Sema::ActOnOpenMPSimpleClause(
  8050. OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
  8051. SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
  8052. OMPClause *Res = nullptr;
  8053. switch (Kind) {
  8054. case OMPC_default:
  8055. Res =
  8056. ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
  8057. ArgumentLoc, StartLoc, LParenLoc, EndLoc);
  8058. break;
  8059. case OMPC_proc_bind:
  8060. Res = ActOnOpenMPProcBindClause(
  8061. static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
  8062. LParenLoc, EndLoc);
  8063. break;
  8064. case OMPC_if:
  8065. case OMPC_final:
  8066. case OMPC_num_threads:
  8067. case OMPC_safelen:
  8068. case OMPC_simdlen:
  8069. case OMPC_collapse:
  8070. case OMPC_schedule:
  8071. case OMPC_private:
  8072. case OMPC_firstprivate:
  8073. case OMPC_lastprivate:
  8074. case OMPC_shared:
  8075. case OMPC_reduction:
  8076. case OMPC_task_reduction:
  8077. case OMPC_in_reduction:
  8078. case OMPC_linear:
  8079. case OMPC_aligned:
  8080. case OMPC_copyin:
  8081. case OMPC_copyprivate:
  8082. case OMPC_ordered:
  8083. case OMPC_nowait:
  8084. case OMPC_untied:
  8085. case OMPC_mergeable:
  8086. case OMPC_threadprivate:
  8087. case OMPC_flush:
  8088. case OMPC_read:
  8089. case OMPC_write:
  8090. case OMPC_update:
  8091. case OMPC_capture:
  8092. case OMPC_seq_cst:
  8093. case OMPC_depend:
  8094. case OMPC_device:
  8095. case OMPC_threads:
  8096. case OMPC_simd:
  8097. case OMPC_map:
  8098. case OMPC_num_teams:
  8099. case OMPC_thread_limit:
  8100. case OMPC_priority:
  8101. case OMPC_grainsize:
  8102. case OMPC_nogroup:
  8103. case OMPC_num_tasks:
  8104. case OMPC_hint:
  8105. case OMPC_dist_schedule:
  8106. case OMPC_defaultmap:
  8107. case OMPC_unknown:
  8108. case OMPC_uniform:
  8109. case OMPC_to:
  8110. case OMPC_from:
  8111. case OMPC_use_device_ptr:
  8112. case OMPC_is_device_ptr:
  8113. llvm_unreachable("Clause is not allowed.");
  8114. }
  8115. return Res;
  8116. }
  8117. static std::string
  8118. getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
  8119. ArrayRef<unsigned> Exclude = llvm::None) {
  8120. SmallString<256> Buffer;
  8121. llvm::raw_svector_ostream Out(Buffer);
  8122. unsigned Bound = Last >= 2 ? Last - 2 : 0;
  8123. unsigned Skipped = Exclude.size();
  8124. auto S = Exclude.begin(), E = Exclude.end();
  8125. for (unsigned I = First; I < Last; ++I) {
  8126. if (std::find(S, E, I) != E) {
  8127. --Skipped;
  8128. continue;
  8129. }
  8130. Out << "'" << getOpenMPSimpleClauseTypeName(K, I) << "'";
  8131. if (I == Bound - Skipped)
  8132. Out << " or ";
  8133. else if (I != Bound + 1 - Skipped)
  8134. Out << ", ";
  8135. }
  8136. return Out.str();
  8137. }
  8138. OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
  8139. SourceLocation KindKwLoc,
  8140. SourceLocation StartLoc,
  8141. SourceLocation LParenLoc,
  8142. SourceLocation EndLoc) {
  8143. if (Kind == OMPC_DEFAULT_unknown) {
  8144. static_assert(OMPC_DEFAULT_unknown > 0,
  8145. "OMPC_DEFAULT_unknown not greater than 0");
  8146. Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
  8147. << getListOfPossibleValues(OMPC_default, /*First=*/0,
  8148. /*Last=*/OMPC_DEFAULT_unknown)
  8149. << getOpenMPClauseName(OMPC_default);
  8150. return nullptr;
  8151. }
  8152. switch (Kind) {
  8153. case OMPC_DEFAULT_none:
  8154. DSAStack->setDefaultDSANone(KindKwLoc);
  8155. break;
  8156. case OMPC_DEFAULT_shared:
  8157. DSAStack->setDefaultDSAShared(KindKwLoc);
  8158. break;
  8159. case OMPC_DEFAULT_unknown:
  8160. llvm_unreachable("Clause kind is not allowed.");
  8161. break;
  8162. }
  8163. return new (Context)
  8164. OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
  8165. }
  8166. OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
  8167. SourceLocation KindKwLoc,
  8168. SourceLocation StartLoc,
  8169. SourceLocation LParenLoc,
  8170. SourceLocation EndLoc) {
  8171. if (Kind == OMPC_PROC_BIND_unknown) {
  8172. Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
  8173. << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0,
  8174. /*Last=*/OMPC_PROC_BIND_unknown)
  8175. << getOpenMPClauseName(OMPC_proc_bind);
  8176. return nullptr;
  8177. }
  8178. return new (Context)
  8179. OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
  8180. }
  8181. OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
  8182. OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
  8183. SourceLocation StartLoc, SourceLocation LParenLoc,
  8184. ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
  8185. SourceLocation EndLoc) {
  8186. OMPClause *Res = nullptr;
  8187. switch (Kind) {
  8188. case OMPC_schedule:
  8189. enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
  8190. assert(Argument.size() == NumberOfElements &&
  8191. ArgumentLoc.size() == NumberOfElements);
  8192. Res = ActOnOpenMPScheduleClause(
  8193. static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
  8194. static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
  8195. static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
  8196. StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
  8197. ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
  8198. break;
  8199. case OMPC_if:
  8200. assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
  8201. Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
  8202. Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
  8203. DelimLoc, EndLoc);
  8204. break;
  8205. case OMPC_dist_schedule:
  8206. Res = ActOnOpenMPDistScheduleClause(
  8207. static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
  8208. StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
  8209. break;
  8210. case OMPC_defaultmap:
  8211. enum { Modifier, DefaultmapKind };
  8212. Res = ActOnOpenMPDefaultmapClause(
  8213. static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
  8214. static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
  8215. StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
  8216. EndLoc);
  8217. break;
  8218. case OMPC_final:
  8219. case OMPC_num_threads:
  8220. case OMPC_safelen:
  8221. case OMPC_simdlen:
  8222. case OMPC_collapse:
  8223. case OMPC_default:
  8224. case OMPC_proc_bind:
  8225. case OMPC_private:
  8226. case OMPC_firstprivate:
  8227. case OMPC_lastprivate:
  8228. case OMPC_shared:
  8229. case OMPC_reduction:
  8230. case OMPC_task_reduction:
  8231. case OMPC_in_reduction:
  8232. case OMPC_linear:
  8233. case OMPC_aligned:
  8234. case OMPC_copyin:
  8235. case OMPC_copyprivate:
  8236. case OMPC_ordered:
  8237. case OMPC_nowait:
  8238. case OMPC_untied:
  8239. case OMPC_mergeable:
  8240. case OMPC_threadprivate:
  8241. case OMPC_flush:
  8242. case OMPC_read:
  8243. case OMPC_write:
  8244. case OMPC_update:
  8245. case OMPC_capture:
  8246. case OMPC_seq_cst:
  8247. case OMPC_depend:
  8248. case OMPC_device:
  8249. case OMPC_threads:
  8250. case OMPC_simd:
  8251. case OMPC_map:
  8252. case OMPC_num_teams:
  8253. case OMPC_thread_limit:
  8254. case OMPC_priority:
  8255. case OMPC_grainsize:
  8256. case OMPC_nogroup:
  8257. case OMPC_num_tasks:
  8258. case OMPC_hint:
  8259. case OMPC_unknown:
  8260. case OMPC_uniform:
  8261. case OMPC_to:
  8262. case OMPC_from:
  8263. case OMPC_use_device_ptr:
  8264. case OMPC_is_device_ptr:
  8265. llvm_unreachable("Clause is not allowed.");
  8266. }
  8267. return Res;
  8268. }
  8269. static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
  8270. OpenMPScheduleClauseModifier M2,
  8271. SourceLocation M1Loc, SourceLocation M2Loc) {
  8272. if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
  8273. SmallVector<unsigned, 2> Excluded;
  8274. if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
  8275. Excluded.push_back(M2);
  8276. if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
  8277. Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
  8278. if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
  8279. Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
  8280. S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
  8281. << getListOfPossibleValues(OMPC_schedule,
  8282. /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
  8283. /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
  8284. Excluded)
  8285. << getOpenMPClauseName(OMPC_schedule);
  8286. return true;
  8287. }
  8288. return false;
  8289. }
  8290. OMPClause *Sema::ActOnOpenMPScheduleClause(
  8291. OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
  8292. OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
  8293. SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
  8294. SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
  8295. if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
  8296. checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
  8297. return nullptr;
  8298. // OpenMP, 2.7.1, Loop Construct, Restrictions
  8299. // Either the monotonic modifier or the nonmonotonic modifier can be specified
  8300. // but not both.
  8301. if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
  8302. (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
  8303. M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
  8304. (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
  8305. M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
  8306. Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
  8307. << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
  8308. << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
  8309. return nullptr;
  8310. }
  8311. if (Kind == OMPC_SCHEDULE_unknown) {
  8312. std::string Values;
  8313. if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
  8314. unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
  8315. Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
  8316. /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
  8317. Exclude);
  8318. } else {
  8319. Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
  8320. /*Last=*/OMPC_SCHEDULE_unknown);
  8321. }
  8322. Diag(KindLoc, diag::err_omp_unexpected_clause_value)
  8323. << Values << getOpenMPClauseName(OMPC_schedule);
  8324. return nullptr;
  8325. }
  8326. // OpenMP, 2.7.1, Loop Construct, Restrictions
  8327. // The nonmonotonic modifier can only be specified with schedule(dynamic) or
  8328. // schedule(guided).
  8329. if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
  8330. M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
  8331. Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
  8332. Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
  8333. diag::err_omp_schedule_nonmonotonic_static);
  8334. return nullptr;
  8335. }
  8336. Expr *ValExpr = ChunkSize;
  8337. Stmt *HelperValStmt = nullptr;
  8338. if (ChunkSize) {
  8339. if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
  8340. !ChunkSize->isInstantiationDependent() &&
  8341. !ChunkSize->containsUnexpandedParameterPack()) {
  8342. SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
  8343. ExprResult Val =
  8344. PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
  8345. if (Val.isInvalid())
  8346. return nullptr;
  8347. ValExpr = Val.get();
  8348. // OpenMP [2.7.1, Restrictions]
  8349. // chunk_size must be a loop invariant integer expression with a positive
  8350. // value.
  8351. llvm::APSInt Result;
  8352. if (ValExpr->isIntegerConstantExpr(Result, Context)) {
  8353. if (Result.isSigned() && !Result.isStrictlyPositive()) {
  8354. Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
  8355. << "schedule" << 1 << ChunkSize->getSourceRange();
  8356. return nullptr;
  8357. }
  8358. } else if (getOpenMPCaptureRegionForClause(
  8359. DSAStack->getCurrentDirective(), OMPC_schedule) !=
  8360. OMPD_unknown &&
  8361. !CurContext->isDependentContext()) {
  8362. ValExpr = MakeFullExpr(ValExpr).get();
  8363. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  8364. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  8365. HelperValStmt = buildPreInits(Context, Captures);
  8366. }
  8367. }
  8368. }
  8369. return new (Context)
  8370. OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
  8371. ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
  8372. }
  8373. OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
  8374. SourceLocation StartLoc,
  8375. SourceLocation EndLoc) {
  8376. OMPClause *Res = nullptr;
  8377. switch (Kind) {
  8378. case OMPC_ordered:
  8379. Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
  8380. break;
  8381. case OMPC_nowait:
  8382. Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
  8383. break;
  8384. case OMPC_untied:
  8385. Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
  8386. break;
  8387. case OMPC_mergeable:
  8388. Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
  8389. break;
  8390. case OMPC_read:
  8391. Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
  8392. break;
  8393. case OMPC_write:
  8394. Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
  8395. break;
  8396. case OMPC_update:
  8397. Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
  8398. break;
  8399. case OMPC_capture:
  8400. Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
  8401. break;
  8402. case OMPC_seq_cst:
  8403. Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
  8404. break;
  8405. case OMPC_threads:
  8406. Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
  8407. break;
  8408. case OMPC_simd:
  8409. Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
  8410. break;
  8411. case OMPC_nogroup:
  8412. Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
  8413. break;
  8414. case OMPC_if:
  8415. case OMPC_final:
  8416. case OMPC_num_threads:
  8417. case OMPC_safelen:
  8418. case OMPC_simdlen:
  8419. case OMPC_collapse:
  8420. case OMPC_schedule:
  8421. case OMPC_private:
  8422. case OMPC_firstprivate:
  8423. case OMPC_lastprivate:
  8424. case OMPC_shared:
  8425. case OMPC_reduction:
  8426. case OMPC_task_reduction:
  8427. case OMPC_in_reduction:
  8428. case OMPC_linear:
  8429. case OMPC_aligned:
  8430. case OMPC_copyin:
  8431. case OMPC_copyprivate:
  8432. case OMPC_default:
  8433. case OMPC_proc_bind:
  8434. case OMPC_threadprivate:
  8435. case OMPC_flush:
  8436. case OMPC_depend:
  8437. case OMPC_device:
  8438. case OMPC_map:
  8439. case OMPC_num_teams:
  8440. case OMPC_thread_limit:
  8441. case OMPC_priority:
  8442. case OMPC_grainsize:
  8443. case OMPC_num_tasks:
  8444. case OMPC_hint:
  8445. case OMPC_dist_schedule:
  8446. case OMPC_defaultmap:
  8447. case OMPC_unknown:
  8448. case OMPC_uniform:
  8449. case OMPC_to:
  8450. case OMPC_from:
  8451. case OMPC_use_device_ptr:
  8452. case OMPC_is_device_ptr:
  8453. llvm_unreachable("Clause is not allowed.");
  8454. }
  8455. return Res;
  8456. }
  8457. OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
  8458. SourceLocation EndLoc) {
  8459. DSAStack->setNowaitRegion();
  8460. return new (Context) OMPNowaitClause(StartLoc, EndLoc);
  8461. }
  8462. OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
  8463. SourceLocation EndLoc) {
  8464. return new (Context) OMPUntiedClause(StartLoc, EndLoc);
  8465. }
  8466. OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
  8467. SourceLocation EndLoc) {
  8468. return new (Context) OMPMergeableClause(StartLoc, EndLoc);
  8469. }
  8470. OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
  8471. SourceLocation EndLoc) {
  8472. return new (Context) OMPReadClause(StartLoc, EndLoc);
  8473. }
  8474. OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
  8475. SourceLocation EndLoc) {
  8476. return new (Context) OMPWriteClause(StartLoc, EndLoc);
  8477. }
  8478. OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
  8479. SourceLocation EndLoc) {
  8480. return new (Context) OMPUpdateClause(StartLoc, EndLoc);
  8481. }
  8482. OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
  8483. SourceLocation EndLoc) {
  8484. return new (Context) OMPCaptureClause(StartLoc, EndLoc);
  8485. }
  8486. OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
  8487. SourceLocation EndLoc) {
  8488. return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
  8489. }
  8490. OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
  8491. SourceLocation EndLoc) {
  8492. return new (Context) OMPThreadsClause(StartLoc, EndLoc);
  8493. }
  8494. OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
  8495. SourceLocation EndLoc) {
  8496. return new (Context) OMPSIMDClause(StartLoc, EndLoc);
  8497. }
  8498. OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
  8499. SourceLocation EndLoc) {
  8500. return new (Context) OMPNogroupClause(StartLoc, EndLoc);
  8501. }
  8502. OMPClause *Sema::ActOnOpenMPVarListClause(
  8503. OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
  8504. SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
  8505. SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
  8506. const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind,
  8507. OpenMPLinearClauseKind LinKind, OpenMPMapClauseKind MapTypeModifier,
  8508. OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
  8509. SourceLocation DepLinMapLoc) {
  8510. OMPClause *Res = nullptr;
  8511. switch (Kind) {
  8512. case OMPC_private:
  8513. Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
  8514. break;
  8515. case OMPC_firstprivate:
  8516. Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
  8517. break;
  8518. case OMPC_lastprivate:
  8519. Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
  8520. break;
  8521. case OMPC_shared:
  8522. Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
  8523. break;
  8524. case OMPC_reduction:
  8525. Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
  8526. EndLoc, ReductionIdScopeSpec, ReductionId);
  8527. break;
  8528. case OMPC_task_reduction:
  8529. Res = ActOnOpenMPTaskReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
  8530. EndLoc, ReductionIdScopeSpec,
  8531. ReductionId);
  8532. break;
  8533. case OMPC_in_reduction:
  8534. Res =
  8535. ActOnOpenMPInReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
  8536. EndLoc, ReductionIdScopeSpec, ReductionId);
  8537. break;
  8538. case OMPC_linear:
  8539. Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
  8540. LinKind, DepLinMapLoc, ColonLoc, EndLoc);
  8541. break;
  8542. case OMPC_aligned:
  8543. Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
  8544. ColonLoc, EndLoc);
  8545. break;
  8546. case OMPC_copyin:
  8547. Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
  8548. break;
  8549. case OMPC_copyprivate:
  8550. Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
  8551. break;
  8552. case OMPC_flush:
  8553. Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
  8554. break;
  8555. case OMPC_depend:
  8556. Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList,
  8557. StartLoc, LParenLoc, EndLoc);
  8558. break;
  8559. case OMPC_map:
  8560. Res = ActOnOpenMPMapClause(MapTypeModifier, MapType, IsMapTypeImplicit,
  8561. DepLinMapLoc, ColonLoc, VarList, StartLoc,
  8562. LParenLoc, EndLoc);
  8563. break;
  8564. case OMPC_to:
  8565. Res = ActOnOpenMPToClause(VarList, StartLoc, LParenLoc, EndLoc);
  8566. break;
  8567. case OMPC_from:
  8568. Res = ActOnOpenMPFromClause(VarList, StartLoc, LParenLoc, EndLoc);
  8569. break;
  8570. case OMPC_use_device_ptr:
  8571. Res = ActOnOpenMPUseDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
  8572. break;
  8573. case OMPC_is_device_ptr:
  8574. Res = ActOnOpenMPIsDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
  8575. break;
  8576. case OMPC_if:
  8577. case OMPC_final:
  8578. case OMPC_num_threads:
  8579. case OMPC_safelen:
  8580. case OMPC_simdlen:
  8581. case OMPC_collapse:
  8582. case OMPC_default:
  8583. case OMPC_proc_bind:
  8584. case OMPC_schedule:
  8585. case OMPC_ordered:
  8586. case OMPC_nowait:
  8587. case OMPC_untied:
  8588. case OMPC_mergeable:
  8589. case OMPC_threadprivate:
  8590. case OMPC_read:
  8591. case OMPC_write:
  8592. case OMPC_update:
  8593. case OMPC_capture:
  8594. case OMPC_seq_cst:
  8595. case OMPC_device:
  8596. case OMPC_threads:
  8597. case OMPC_simd:
  8598. case OMPC_num_teams:
  8599. case OMPC_thread_limit:
  8600. case OMPC_priority:
  8601. case OMPC_grainsize:
  8602. case OMPC_nogroup:
  8603. case OMPC_num_tasks:
  8604. case OMPC_hint:
  8605. case OMPC_dist_schedule:
  8606. case OMPC_defaultmap:
  8607. case OMPC_unknown:
  8608. case OMPC_uniform:
  8609. llvm_unreachable("Clause is not allowed.");
  8610. }
  8611. return Res;
  8612. }
  8613. ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
  8614. ExprObjectKind OK, SourceLocation Loc) {
  8615. ExprResult Res = BuildDeclRefExpr(
  8616. Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
  8617. if (!Res.isUsable())
  8618. return ExprError();
  8619. if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
  8620. Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
  8621. if (!Res.isUsable())
  8622. return ExprError();
  8623. }
  8624. if (VK != VK_LValue && Res.get()->isGLValue()) {
  8625. Res = DefaultLvalueConversion(Res.get());
  8626. if (!Res.isUsable())
  8627. return ExprError();
  8628. }
  8629. return Res;
  8630. }
  8631. static std::pair<ValueDecl *, bool>
  8632. getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
  8633. SourceRange &ERange, bool AllowArraySection = false) {
  8634. if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
  8635. RefExpr->containsUnexpandedParameterPack())
  8636. return std::make_pair(nullptr, true);
  8637. // OpenMP [3.1, C/C++]
  8638. // A list item is a variable name.
  8639. // OpenMP [2.9.3.3, Restrictions, p.1]
  8640. // A variable that is part of another variable (as an array or
  8641. // structure element) cannot appear in a private clause.
  8642. RefExpr = RefExpr->IgnoreParens();
  8643. enum {
  8644. NoArrayExpr = -1,
  8645. ArraySubscript = 0,
  8646. OMPArraySection = 1
  8647. } IsArrayExpr = NoArrayExpr;
  8648. if (AllowArraySection) {
  8649. if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
  8650. Expr *Base = ASE->getBase()->IgnoreParenImpCasts();
  8651. while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
  8652. Base = TempASE->getBase()->IgnoreParenImpCasts();
  8653. RefExpr = Base;
  8654. IsArrayExpr = ArraySubscript;
  8655. } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
  8656. Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
  8657. while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
  8658. Base = TempOASE->getBase()->IgnoreParenImpCasts();
  8659. while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
  8660. Base = TempASE->getBase()->IgnoreParenImpCasts();
  8661. RefExpr = Base;
  8662. IsArrayExpr = OMPArraySection;
  8663. }
  8664. }
  8665. ELoc = RefExpr->getExprLoc();
  8666. ERange = RefExpr->getSourceRange();
  8667. RefExpr = RefExpr->IgnoreParenImpCasts();
  8668. auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
  8669. auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
  8670. if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
  8671. (S.getCurrentThisType().isNull() || !ME ||
  8672. !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
  8673. !isa<FieldDecl>(ME->getMemberDecl()))) {
  8674. if (IsArrayExpr != NoArrayExpr) {
  8675. S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr
  8676. << ERange;
  8677. } else {
  8678. S.Diag(ELoc,
  8679. AllowArraySection
  8680. ? diag::err_omp_expected_var_name_member_expr_or_array_item
  8681. : diag::err_omp_expected_var_name_member_expr)
  8682. << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
  8683. }
  8684. return std::make_pair(nullptr, false);
  8685. }
  8686. return std::make_pair(
  8687. getCanonicalDecl(DE ? DE->getDecl() : ME->getMemberDecl()), false);
  8688. }
  8689. OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
  8690. SourceLocation StartLoc,
  8691. SourceLocation LParenLoc,
  8692. SourceLocation EndLoc) {
  8693. SmallVector<Expr *, 8> Vars;
  8694. SmallVector<Expr *, 8> PrivateCopies;
  8695. for (Expr *RefExpr : VarList) {
  8696. assert(RefExpr && "NULL expr in OpenMP private clause.");
  8697. SourceLocation ELoc;
  8698. SourceRange ERange;
  8699. Expr *SimpleRefExpr = RefExpr;
  8700. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  8701. if (Res.second) {
  8702. // It will be analyzed later.
  8703. Vars.push_back(RefExpr);
  8704. PrivateCopies.push_back(nullptr);
  8705. }
  8706. ValueDecl *D = Res.first;
  8707. if (!D)
  8708. continue;
  8709. QualType Type = D->getType();
  8710. auto *VD = dyn_cast<VarDecl>(D);
  8711. // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
  8712. // A variable that appears in a private clause must not have an incomplete
  8713. // type or a reference type.
  8714. if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
  8715. continue;
  8716. Type = Type.getNonReferenceType();
  8717. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  8718. // in a Construct]
  8719. // Variables with the predetermined data-sharing attributes may not be
  8720. // listed in data-sharing attributes clauses, except for the cases
  8721. // listed below. For these exceptions only, listing a predetermined
  8722. // variable in a data-sharing attribute clause is allowed and overrides
  8723. // the variable's predetermined data-sharing attributes.
  8724. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
  8725. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
  8726. Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
  8727. << getOpenMPClauseName(OMPC_private);
  8728. reportOriginalDsa(*this, DSAStack, D, DVar);
  8729. continue;
  8730. }
  8731. OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
  8732. // Variably modified types are not supported for tasks.
  8733. if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
  8734. isOpenMPTaskingDirective(CurrDir)) {
  8735. Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
  8736. << getOpenMPClauseName(OMPC_private) << Type
  8737. << getOpenMPDirectiveName(CurrDir);
  8738. bool IsDecl =
  8739. !VD ||
  8740. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  8741. Diag(D->getLocation(),
  8742. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  8743. << D;
  8744. continue;
  8745. }
  8746. // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
  8747. // A list item cannot appear in both a map clause and a data-sharing
  8748. // attribute clause on the same construct
  8749. if (isOpenMPTargetExecutionDirective(CurrDir)) {
  8750. OpenMPClauseKind ConflictKind;
  8751. if (DSAStack->checkMappableExprComponentListsForDecl(
  8752. VD, /*CurrentRegionOnly=*/true,
  8753. [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
  8754. OpenMPClauseKind WhereFoundClauseKind) -> bool {
  8755. ConflictKind = WhereFoundClauseKind;
  8756. return true;
  8757. })) {
  8758. Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
  8759. << getOpenMPClauseName(OMPC_private)
  8760. << getOpenMPClauseName(ConflictKind)
  8761. << getOpenMPDirectiveName(CurrDir);
  8762. reportOriginalDsa(*this, DSAStack, D, DVar);
  8763. continue;
  8764. }
  8765. }
  8766. // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
  8767. // A variable of class type (or array thereof) that appears in a private
  8768. // clause requires an accessible, unambiguous default constructor for the
  8769. // class type.
  8770. // Generate helper private variable and initialize it with the default
  8771. // value. The address of the original variable is replaced by the address of
  8772. // the new private variable in CodeGen. This new variable is not added to
  8773. // IdResolver, so the code in the OpenMP region uses original variable for
  8774. // proper diagnostics.
  8775. Type = Type.getUnqualifiedType();
  8776. VarDecl *VDPrivate =
  8777. buildVarDecl(*this, ELoc, Type, D->getName(),
  8778. D->hasAttrs() ? &D->getAttrs() : nullptr,
  8779. VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
  8780. ActOnUninitializedDecl(VDPrivate);
  8781. if (VDPrivate->isInvalidDecl())
  8782. continue;
  8783. DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
  8784. *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
  8785. DeclRefExpr *Ref = nullptr;
  8786. if (!VD && !CurContext->isDependentContext())
  8787. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
  8788. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
  8789. Vars.push_back((VD || CurContext->isDependentContext())
  8790. ? RefExpr->IgnoreParens()
  8791. : Ref);
  8792. PrivateCopies.push_back(VDPrivateRefExpr);
  8793. }
  8794. if (Vars.empty())
  8795. return nullptr;
  8796. return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
  8797. PrivateCopies);
  8798. }
  8799. namespace {
  8800. class DiagsUninitializedSeveretyRAII {
  8801. private:
  8802. DiagnosticsEngine &Diags;
  8803. SourceLocation SavedLoc;
  8804. bool IsIgnored = false;
  8805. public:
  8806. DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
  8807. bool IsIgnored)
  8808. : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
  8809. if (!IsIgnored) {
  8810. Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
  8811. /*Map*/ diag::Severity::Ignored, Loc);
  8812. }
  8813. }
  8814. ~DiagsUninitializedSeveretyRAII() {
  8815. if (!IsIgnored)
  8816. Diags.popMappings(SavedLoc);
  8817. }
  8818. };
  8819. }
  8820. OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
  8821. SourceLocation StartLoc,
  8822. SourceLocation LParenLoc,
  8823. SourceLocation EndLoc) {
  8824. SmallVector<Expr *, 8> Vars;
  8825. SmallVector<Expr *, 8> PrivateCopies;
  8826. SmallVector<Expr *, 8> Inits;
  8827. SmallVector<Decl *, 4> ExprCaptures;
  8828. bool IsImplicitClause =
  8829. StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
  8830. SourceLocation ImplicitClauseLoc = DSAStack->getConstructLoc();
  8831. for (Expr *RefExpr : VarList) {
  8832. assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
  8833. SourceLocation ELoc;
  8834. SourceRange ERange;
  8835. Expr *SimpleRefExpr = RefExpr;
  8836. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  8837. if (Res.second) {
  8838. // It will be analyzed later.
  8839. Vars.push_back(RefExpr);
  8840. PrivateCopies.push_back(nullptr);
  8841. Inits.push_back(nullptr);
  8842. }
  8843. ValueDecl *D = Res.first;
  8844. if (!D)
  8845. continue;
  8846. ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
  8847. QualType Type = D->getType();
  8848. auto *VD = dyn_cast<VarDecl>(D);
  8849. // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
  8850. // A variable that appears in a private clause must not have an incomplete
  8851. // type or a reference type.
  8852. if (RequireCompleteType(ELoc, Type,
  8853. diag::err_omp_firstprivate_incomplete_type))
  8854. continue;
  8855. Type = Type.getNonReferenceType();
  8856. // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
  8857. // A variable of class type (or array thereof) that appears in a private
  8858. // clause requires an accessible, unambiguous copy constructor for the
  8859. // class type.
  8860. QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
  8861. // If an implicit firstprivate variable found it was checked already.
  8862. DSAStackTy::DSAVarData TopDVar;
  8863. if (!IsImplicitClause) {
  8864. DSAStackTy::DSAVarData DVar =
  8865. DSAStack->getTopDSA(D, /*FromParent=*/false);
  8866. TopDVar = DVar;
  8867. OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
  8868. bool IsConstant = ElemType.isConstant(Context);
  8869. // OpenMP [2.4.13, Data-sharing Attribute Clauses]
  8870. // A list item that specifies a given variable may not appear in more
  8871. // than one clause on the same directive, except that a variable may be
  8872. // specified in both firstprivate and lastprivate clauses.
  8873. // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
  8874. // A list item may appear in a firstprivate or lastprivate clause but not
  8875. // both.
  8876. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
  8877. (isOpenMPDistributeDirective(CurrDir) ||
  8878. DVar.CKind != OMPC_lastprivate) &&
  8879. DVar.RefExpr) {
  8880. Diag(ELoc, diag::err_omp_wrong_dsa)
  8881. << getOpenMPClauseName(DVar.CKind)
  8882. << getOpenMPClauseName(OMPC_firstprivate);
  8883. reportOriginalDsa(*this, DSAStack, D, DVar);
  8884. continue;
  8885. }
  8886. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  8887. // in a Construct]
  8888. // Variables with the predetermined data-sharing attributes may not be
  8889. // listed in data-sharing attributes clauses, except for the cases
  8890. // listed below. For these exceptions only, listing a predetermined
  8891. // variable in a data-sharing attribute clause is allowed and overrides
  8892. // the variable's predetermined data-sharing attributes.
  8893. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  8894. // in a Construct, C/C++, p.2]
  8895. // Variables with const-qualified type having no mutable member may be
  8896. // listed in a firstprivate clause, even if they are static data members.
  8897. if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
  8898. DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
  8899. Diag(ELoc, diag::err_omp_wrong_dsa)
  8900. << getOpenMPClauseName(DVar.CKind)
  8901. << getOpenMPClauseName(OMPC_firstprivate);
  8902. reportOriginalDsa(*this, DSAStack, D, DVar);
  8903. continue;
  8904. }
  8905. // OpenMP [2.9.3.4, Restrictions, p.2]
  8906. // A list item that is private within a parallel region must not appear
  8907. // in a firstprivate clause on a worksharing construct if any of the
  8908. // worksharing regions arising from the worksharing construct ever bind
  8909. // to any of the parallel regions arising from the parallel construct.
  8910. // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
  8911. // A list item that is private within a teams region must not appear in a
  8912. // firstprivate clause on a distribute construct if any of the distribute
  8913. // regions arising from the distribute construct ever bind to any of the
  8914. // teams regions arising from the teams construct.
  8915. // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
  8916. // A list item that appears in a reduction clause of a teams construct
  8917. // must not appear in a firstprivate clause on a distribute construct if
  8918. // any of the distribute regions arising from the distribute construct
  8919. // ever bind to any of the teams regions arising from the teams construct.
  8920. if ((isOpenMPWorksharingDirective(CurrDir) ||
  8921. isOpenMPDistributeDirective(CurrDir)) &&
  8922. !isOpenMPParallelDirective(CurrDir) &&
  8923. !isOpenMPTeamsDirective(CurrDir)) {
  8924. DVar = DSAStack->getImplicitDSA(D, true);
  8925. if (DVar.CKind != OMPC_shared &&
  8926. (isOpenMPParallelDirective(DVar.DKind) ||
  8927. isOpenMPTeamsDirective(DVar.DKind) ||
  8928. DVar.DKind == OMPD_unknown)) {
  8929. Diag(ELoc, diag::err_omp_required_access)
  8930. << getOpenMPClauseName(OMPC_firstprivate)
  8931. << getOpenMPClauseName(OMPC_shared);
  8932. reportOriginalDsa(*this, DSAStack, D, DVar);
  8933. continue;
  8934. }
  8935. }
  8936. // OpenMP [2.9.3.4, Restrictions, p.3]
  8937. // A list item that appears in a reduction clause of a parallel construct
  8938. // must not appear in a firstprivate clause on a worksharing or task
  8939. // construct if any of the worksharing or task regions arising from the
  8940. // worksharing or task construct ever bind to any of the parallel regions
  8941. // arising from the parallel construct.
  8942. // OpenMP [2.9.3.4, Restrictions, p.4]
  8943. // A list item that appears in a reduction clause in worksharing
  8944. // construct must not appear in a firstprivate clause in a task construct
  8945. // encountered during execution of any of the worksharing regions arising
  8946. // from the worksharing construct.
  8947. if (isOpenMPTaskingDirective(CurrDir)) {
  8948. DVar = DSAStack->hasInnermostDSA(
  8949. D, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
  8950. [](OpenMPDirectiveKind K) {
  8951. return isOpenMPParallelDirective(K) ||
  8952. isOpenMPWorksharingDirective(K) ||
  8953. isOpenMPTeamsDirective(K);
  8954. },
  8955. /*FromParent=*/true);
  8956. if (DVar.CKind == OMPC_reduction &&
  8957. (isOpenMPParallelDirective(DVar.DKind) ||
  8958. isOpenMPWorksharingDirective(DVar.DKind) ||
  8959. isOpenMPTeamsDirective(DVar.DKind))) {
  8960. Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
  8961. << getOpenMPDirectiveName(DVar.DKind);
  8962. reportOriginalDsa(*this, DSAStack, D, DVar);
  8963. continue;
  8964. }
  8965. }
  8966. // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
  8967. // A list item cannot appear in both a map clause and a data-sharing
  8968. // attribute clause on the same construct
  8969. if (isOpenMPTargetExecutionDirective(CurrDir)) {
  8970. OpenMPClauseKind ConflictKind;
  8971. if (DSAStack->checkMappableExprComponentListsForDecl(
  8972. VD, /*CurrentRegionOnly=*/true,
  8973. [&ConflictKind](
  8974. OMPClauseMappableExprCommon::MappableExprComponentListRef,
  8975. OpenMPClauseKind WhereFoundClauseKind) {
  8976. ConflictKind = WhereFoundClauseKind;
  8977. return true;
  8978. })) {
  8979. Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
  8980. << getOpenMPClauseName(OMPC_firstprivate)
  8981. << getOpenMPClauseName(ConflictKind)
  8982. << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
  8983. reportOriginalDsa(*this, DSAStack, D, DVar);
  8984. continue;
  8985. }
  8986. }
  8987. }
  8988. // Variably modified types are not supported for tasks.
  8989. if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
  8990. isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
  8991. Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
  8992. << getOpenMPClauseName(OMPC_firstprivate) << Type
  8993. << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
  8994. bool IsDecl =
  8995. !VD ||
  8996. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  8997. Diag(D->getLocation(),
  8998. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  8999. << D;
  9000. continue;
  9001. }
  9002. Type = Type.getUnqualifiedType();
  9003. VarDecl *VDPrivate =
  9004. buildVarDecl(*this, ELoc, Type, D->getName(),
  9005. D->hasAttrs() ? &D->getAttrs() : nullptr,
  9006. VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
  9007. // Generate helper private variable and initialize it with the value of the
  9008. // original variable. The address of the original variable is replaced by
  9009. // the address of the new private variable in the CodeGen. This new variable
  9010. // is not added to IdResolver, so the code in the OpenMP region uses
  9011. // original variable for proper diagnostics and variable capturing.
  9012. Expr *VDInitRefExpr = nullptr;
  9013. // For arrays generate initializer for single element and replace it by the
  9014. // original array element in CodeGen.
  9015. if (Type->isArrayType()) {
  9016. VarDecl *VDInit =
  9017. buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
  9018. VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
  9019. Expr *Init = DefaultLvalueConversion(VDInitRefExpr).get();
  9020. ElemType = ElemType.getUnqualifiedType();
  9021. VarDecl *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
  9022. ".firstprivate.temp");
  9023. InitializedEntity Entity =
  9024. InitializedEntity::InitializeVariable(VDInitTemp);
  9025. InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
  9026. InitializationSequence InitSeq(*this, Entity, Kind, Init);
  9027. ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
  9028. if (Result.isInvalid())
  9029. VDPrivate->setInvalidDecl();
  9030. else
  9031. VDPrivate->setInit(Result.getAs<Expr>());
  9032. // Remove temp variable declaration.
  9033. Context.Deallocate(VDInitTemp);
  9034. } else {
  9035. VarDecl *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
  9036. ".firstprivate.temp");
  9037. VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
  9038. RefExpr->getExprLoc());
  9039. AddInitializerToDecl(VDPrivate,
  9040. DefaultLvalueConversion(VDInitRefExpr).get(),
  9041. /*DirectInit=*/false);
  9042. }
  9043. if (VDPrivate->isInvalidDecl()) {
  9044. if (IsImplicitClause) {
  9045. Diag(RefExpr->getExprLoc(),
  9046. diag::note_omp_task_predetermined_firstprivate_here);
  9047. }
  9048. continue;
  9049. }
  9050. CurContext->addDecl(VDPrivate);
  9051. DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
  9052. *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
  9053. RefExpr->getExprLoc());
  9054. DeclRefExpr *Ref = nullptr;
  9055. if (!VD && !CurContext->isDependentContext()) {
  9056. if (TopDVar.CKind == OMPC_lastprivate) {
  9057. Ref = TopDVar.PrivateCopy;
  9058. } else {
  9059. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
  9060. if (!isOpenMPCapturedDecl(D))
  9061. ExprCaptures.push_back(Ref->getDecl());
  9062. }
  9063. }
  9064. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
  9065. Vars.push_back((VD || CurContext->isDependentContext())
  9066. ? RefExpr->IgnoreParens()
  9067. : Ref);
  9068. PrivateCopies.push_back(VDPrivateRefExpr);
  9069. Inits.push_back(VDInitRefExpr);
  9070. }
  9071. if (Vars.empty())
  9072. return nullptr;
  9073. return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  9074. Vars, PrivateCopies, Inits,
  9075. buildPreInits(Context, ExprCaptures));
  9076. }
  9077. OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
  9078. SourceLocation StartLoc,
  9079. SourceLocation LParenLoc,
  9080. SourceLocation EndLoc) {
  9081. SmallVector<Expr *, 8> Vars;
  9082. SmallVector<Expr *, 8> SrcExprs;
  9083. SmallVector<Expr *, 8> DstExprs;
  9084. SmallVector<Expr *, 8> AssignmentOps;
  9085. SmallVector<Decl *, 4> ExprCaptures;
  9086. SmallVector<Expr *, 4> ExprPostUpdates;
  9087. for (Expr *RefExpr : VarList) {
  9088. assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
  9089. SourceLocation ELoc;
  9090. SourceRange ERange;
  9091. Expr *SimpleRefExpr = RefExpr;
  9092. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  9093. if (Res.second) {
  9094. // It will be analyzed later.
  9095. Vars.push_back(RefExpr);
  9096. SrcExprs.push_back(nullptr);
  9097. DstExprs.push_back(nullptr);
  9098. AssignmentOps.push_back(nullptr);
  9099. }
  9100. ValueDecl *D = Res.first;
  9101. if (!D)
  9102. continue;
  9103. QualType Type = D->getType();
  9104. auto *VD = dyn_cast<VarDecl>(D);
  9105. // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
  9106. // A variable that appears in a lastprivate clause must not have an
  9107. // incomplete type or a reference type.
  9108. if (RequireCompleteType(ELoc, Type,
  9109. diag::err_omp_lastprivate_incomplete_type))
  9110. continue;
  9111. Type = Type.getNonReferenceType();
  9112. OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
  9113. // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
  9114. // in a Construct]
  9115. // Variables with the predetermined data-sharing attributes may not be
  9116. // listed in data-sharing attributes clauses, except for the cases
  9117. // listed below.
  9118. // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
  9119. // A list item may appear in a firstprivate or lastprivate clause but not
  9120. // both.
  9121. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
  9122. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
  9123. (isOpenMPDistributeDirective(CurrDir) ||
  9124. DVar.CKind != OMPC_firstprivate) &&
  9125. (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
  9126. Diag(ELoc, diag::err_omp_wrong_dsa)
  9127. << getOpenMPClauseName(DVar.CKind)
  9128. << getOpenMPClauseName(OMPC_lastprivate);
  9129. reportOriginalDsa(*this, DSAStack, D, DVar);
  9130. continue;
  9131. }
  9132. // OpenMP [2.14.3.5, Restrictions, p.2]
  9133. // A list item that is private within a parallel region, or that appears in
  9134. // the reduction clause of a parallel construct, must not appear in a
  9135. // lastprivate clause on a worksharing construct if any of the corresponding
  9136. // worksharing regions ever binds to any of the corresponding parallel
  9137. // regions.
  9138. DSAStackTy::DSAVarData TopDVar = DVar;
  9139. if (isOpenMPWorksharingDirective(CurrDir) &&
  9140. !isOpenMPParallelDirective(CurrDir) &&
  9141. !isOpenMPTeamsDirective(CurrDir)) {
  9142. DVar = DSAStack->getImplicitDSA(D, true);
  9143. if (DVar.CKind != OMPC_shared) {
  9144. Diag(ELoc, diag::err_omp_required_access)
  9145. << getOpenMPClauseName(OMPC_lastprivate)
  9146. << getOpenMPClauseName(OMPC_shared);
  9147. reportOriginalDsa(*this, DSAStack, D, DVar);
  9148. continue;
  9149. }
  9150. }
  9151. // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
  9152. // A variable of class type (or array thereof) that appears in a
  9153. // lastprivate clause requires an accessible, unambiguous default
  9154. // constructor for the class type, unless the list item is also specified
  9155. // in a firstprivate clause.
  9156. // A variable of class type (or array thereof) that appears in a
  9157. // lastprivate clause requires an accessible, unambiguous copy assignment
  9158. // operator for the class type.
  9159. Type = Context.getBaseElementType(Type).getNonReferenceType();
  9160. VarDecl *SrcVD = buildVarDecl(*this, ERange.getBegin(),
  9161. Type.getUnqualifiedType(), ".lastprivate.src",
  9162. D->hasAttrs() ? &D->getAttrs() : nullptr);
  9163. DeclRefExpr *PseudoSrcExpr =
  9164. buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
  9165. VarDecl *DstVD =
  9166. buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
  9167. D->hasAttrs() ? &D->getAttrs() : nullptr);
  9168. DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
  9169. // For arrays generate assignment operation for single element and replace
  9170. // it by the original array element in CodeGen.
  9171. ExprResult AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
  9172. PseudoDstExpr, PseudoSrcExpr);
  9173. if (AssignmentOp.isInvalid())
  9174. continue;
  9175. AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
  9176. /*DiscardedValue=*/true);
  9177. if (AssignmentOp.isInvalid())
  9178. continue;
  9179. DeclRefExpr *Ref = nullptr;
  9180. if (!VD && !CurContext->isDependentContext()) {
  9181. if (TopDVar.CKind == OMPC_firstprivate) {
  9182. Ref = TopDVar.PrivateCopy;
  9183. } else {
  9184. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
  9185. if (!isOpenMPCapturedDecl(D))
  9186. ExprCaptures.push_back(Ref->getDecl());
  9187. }
  9188. if (TopDVar.CKind == OMPC_firstprivate ||
  9189. (!isOpenMPCapturedDecl(D) &&
  9190. Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
  9191. ExprResult RefRes = DefaultLvalueConversion(Ref);
  9192. if (!RefRes.isUsable())
  9193. continue;
  9194. ExprResult PostUpdateRes =
  9195. BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
  9196. RefRes.get());
  9197. if (!PostUpdateRes.isUsable())
  9198. continue;
  9199. ExprPostUpdates.push_back(
  9200. IgnoredValueConversions(PostUpdateRes.get()).get());
  9201. }
  9202. }
  9203. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
  9204. Vars.push_back((VD || CurContext->isDependentContext())
  9205. ? RefExpr->IgnoreParens()
  9206. : Ref);
  9207. SrcExprs.push_back(PseudoSrcExpr);
  9208. DstExprs.push_back(PseudoDstExpr);
  9209. AssignmentOps.push_back(AssignmentOp.get());
  9210. }
  9211. if (Vars.empty())
  9212. return nullptr;
  9213. return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  9214. Vars, SrcExprs, DstExprs, AssignmentOps,
  9215. buildPreInits(Context, ExprCaptures),
  9216. buildPostUpdate(*this, ExprPostUpdates));
  9217. }
  9218. OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
  9219. SourceLocation StartLoc,
  9220. SourceLocation LParenLoc,
  9221. SourceLocation EndLoc) {
  9222. SmallVector<Expr *, 8> Vars;
  9223. for (Expr *RefExpr : VarList) {
  9224. assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
  9225. SourceLocation ELoc;
  9226. SourceRange ERange;
  9227. Expr *SimpleRefExpr = RefExpr;
  9228. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  9229. if (Res.second) {
  9230. // It will be analyzed later.
  9231. Vars.push_back(RefExpr);
  9232. }
  9233. ValueDecl *D = Res.first;
  9234. if (!D)
  9235. continue;
  9236. auto *VD = dyn_cast<VarDecl>(D);
  9237. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  9238. // in a Construct]
  9239. // Variables with the predetermined data-sharing attributes may not be
  9240. // listed in data-sharing attributes clauses, except for the cases
  9241. // listed below. For these exceptions only, listing a predetermined
  9242. // variable in a data-sharing attribute clause is allowed and overrides
  9243. // the variable's predetermined data-sharing attributes.
  9244. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
  9245. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
  9246. DVar.RefExpr) {
  9247. Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
  9248. << getOpenMPClauseName(OMPC_shared);
  9249. reportOriginalDsa(*this, DSAStack, D, DVar);
  9250. continue;
  9251. }
  9252. DeclRefExpr *Ref = nullptr;
  9253. if (!VD && isOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
  9254. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
  9255. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
  9256. Vars.push_back((VD || !Ref || CurContext->isDependentContext())
  9257. ? RefExpr->IgnoreParens()
  9258. : Ref);
  9259. }
  9260. if (Vars.empty())
  9261. return nullptr;
  9262. return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
  9263. }
  9264. namespace {
  9265. class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
  9266. DSAStackTy *Stack;
  9267. public:
  9268. bool VisitDeclRefExpr(DeclRefExpr *E) {
  9269. if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
  9270. DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
  9271. if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
  9272. return false;
  9273. if (DVar.CKind != OMPC_unknown)
  9274. return true;
  9275. DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
  9276. VD, isOpenMPPrivate, [](OpenMPDirectiveKind) { return true; },
  9277. /*FromParent=*/true);
  9278. return DVarPrivate.CKind != OMPC_unknown;
  9279. }
  9280. return false;
  9281. }
  9282. bool VisitStmt(Stmt *S) {
  9283. for (Stmt *Child : S->children()) {
  9284. if (Child && Visit(Child))
  9285. return true;
  9286. }
  9287. return false;
  9288. }
  9289. explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
  9290. };
  9291. } // namespace
  9292. namespace {
  9293. // Transform MemberExpression for specified FieldDecl of current class to
  9294. // DeclRefExpr to specified OMPCapturedExprDecl.
  9295. class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
  9296. typedef TreeTransform<TransformExprToCaptures> BaseTransform;
  9297. ValueDecl *Field = nullptr;
  9298. DeclRefExpr *CapturedExpr = nullptr;
  9299. public:
  9300. TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
  9301. : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
  9302. ExprResult TransformMemberExpr(MemberExpr *E) {
  9303. if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
  9304. E->getMemberDecl() == Field) {
  9305. CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
  9306. return CapturedExpr;
  9307. }
  9308. return BaseTransform::TransformMemberExpr(E);
  9309. }
  9310. DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
  9311. };
  9312. } // namespace
  9313. template <typename T, typename U>
  9314. static T filterLookupForUDR(SmallVectorImpl<U> &Lookups,
  9315. const llvm::function_ref<T(ValueDecl *)> Gen) {
  9316. for (U &Set : Lookups) {
  9317. for (auto *D : Set) {
  9318. if (T Res = Gen(cast<ValueDecl>(D)))
  9319. return Res;
  9320. }
  9321. }
  9322. return T();
  9323. }
  9324. static ExprResult
  9325. buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
  9326. Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
  9327. const DeclarationNameInfo &ReductionId, QualType Ty,
  9328. CXXCastPath &BasePath, Expr *UnresolvedReduction) {
  9329. if (ReductionIdScopeSpec.isInvalid())
  9330. return ExprError();
  9331. SmallVector<UnresolvedSet<8>, 4> Lookups;
  9332. if (S) {
  9333. LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
  9334. Lookup.suppressDiagnostics();
  9335. while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
  9336. NamedDecl *D = Lookup.getRepresentativeDecl();
  9337. do {
  9338. S = S->getParent();
  9339. } while (S && !S->isDeclScope(D));
  9340. if (S)
  9341. S = S->getParent();
  9342. Lookups.push_back(UnresolvedSet<8>());
  9343. Lookups.back().append(Lookup.begin(), Lookup.end());
  9344. Lookup.clear();
  9345. }
  9346. } else if (auto *ULE =
  9347. cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
  9348. Lookups.push_back(UnresolvedSet<8>());
  9349. Decl *PrevD = nullptr;
  9350. for (NamedDecl *D : ULE->decls()) {
  9351. if (D == PrevD)
  9352. Lookups.push_back(UnresolvedSet<8>());
  9353. else if (auto *DRD = cast<OMPDeclareReductionDecl>(D))
  9354. Lookups.back().addDecl(DRD);
  9355. PrevD = D;
  9356. }
  9357. }
  9358. if (SemaRef.CurContext->isDependentContext() || Ty->isDependentType() ||
  9359. Ty->isInstantiationDependentType() ||
  9360. Ty->containsUnexpandedParameterPack() ||
  9361. filterLookupForUDR<bool>(Lookups, [](ValueDecl *D) {
  9362. return !D->isInvalidDecl() &&
  9363. (D->getType()->isDependentType() ||
  9364. D->getType()->isInstantiationDependentType() ||
  9365. D->getType()->containsUnexpandedParameterPack());
  9366. })) {
  9367. UnresolvedSet<8> ResSet;
  9368. for (const UnresolvedSet<8> &Set : Lookups) {
  9369. ResSet.append(Set.begin(), Set.end());
  9370. // The last item marks the end of all declarations at the specified scope.
  9371. ResSet.addDecl(Set[Set.size() - 1]);
  9372. }
  9373. return UnresolvedLookupExpr::Create(
  9374. SemaRef.Context, /*NamingClass=*/nullptr,
  9375. ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
  9376. /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
  9377. }
  9378. if (auto *VD = filterLookupForUDR<ValueDecl *>(
  9379. Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
  9380. if (!D->isInvalidDecl() &&
  9381. SemaRef.Context.hasSameType(D->getType(), Ty))
  9382. return D;
  9383. return nullptr;
  9384. }))
  9385. return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
  9386. if (auto *VD = filterLookupForUDR<ValueDecl *>(
  9387. Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
  9388. if (!D->isInvalidDecl() &&
  9389. SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
  9390. !Ty.isMoreQualifiedThan(D->getType()))
  9391. return D;
  9392. return nullptr;
  9393. })) {
  9394. CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
  9395. /*DetectVirtual=*/false);
  9396. if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
  9397. if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
  9398. VD->getType().getUnqualifiedType()))) {
  9399. if (SemaRef.CheckBaseClassAccess(Loc, VD->getType(), Ty, Paths.front(),
  9400. /*DiagID=*/0) !=
  9401. Sema::AR_inaccessible) {
  9402. SemaRef.BuildBasePathArray(Paths, BasePath);
  9403. return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
  9404. }
  9405. }
  9406. }
  9407. }
  9408. if (ReductionIdScopeSpec.isSet()) {
  9409. SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range;
  9410. return ExprError();
  9411. }
  9412. return ExprEmpty();
  9413. }
  9414. namespace {
  9415. /// Data for the reduction-based clauses.
  9416. struct ReductionData {
  9417. /// List of original reduction items.
  9418. SmallVector<Expr *, 8> Vars;
  9419. /// List of private copies of the reduction items.
  9420. SmallVector<Expr *, 8> Privates;
  9421. /// LHS expressions for the reduction_op expressions.
  9422. SmallVector<Expr *, 8> LHSs;
  9423. /// RHS expressions for the reduction_op expressions.
  9424. SmallVector<Expr *, 8> RHSs;
  9425. /// Reduction operation expression.
  9426. SmallVector<Expr *, 8> ReductionOps;
  9427. /// Taskgroup descriptors for the corresponding reduction items in
  9428. /// in_reduction clauses.
  9429. SmallVector<Expr *, 8> TaskgroupDescriptors;
  9430. /// List of captures for clause.
  9431. SmallVector<Decl *, 4> ExprCaptures;
  9432. /// List of postupdate expressions.
  9433. SmallVector<Expr *, 4> ExprPostUpdates;
  9434. ReductionData() = delete;
  9435. /// Reserves required memory for the reduction data.
  9436. ReductionData(unsigned Size) {
  9437. Vars.reserve(Size);
  9438. Privates.reserve(Size);
  9439. LHSs.reserve(Size);
  9440. RHSs.reserve(Size);
  9441. ReductionOps.reserve(Size);
  9442. TaskgroupDescriptors.reserve(Size);
  9443. ExprCaptures.reserve(Size);
  9444. ExprPostUpdates.reserve(Size);
  9445. }
  9446. /// Stores reduction item and reduction operation only (required for dependent
  9447. /// reduction item).
  9448. void push(Expr *Item, Expr *ReductionOp) {
  9449. Vars.emplace_back(Item);
  9450. Privates.emplace_back(nullptr);
  9451. LHSs.emplace_back(nullptr);
  9452. RHSs.emplace_back(nullptr);
  9453. ReductionOps.emplace_back(ReductionOp);
  9454. TaskgroupDescriptors.emplace_back(nullptr);
  9455. }
  9456. /// Stores reduction data.
  9457. void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS, Expr *ReductionOp,
  9458. Expr *TaskgroupDescriptor) {
  9459. Vars.emplace_back(Item);
  9460. Privates.emplace_back(Private);
  9461. LHSs.emplace_back(LHS);
  9462. RHSs.emplace_back(RHS);
  9463. ReductionOps.emplace_back(ReductionOp);
  9464. TaskgroupDescriptors.emplace_back(TaskgroupDescriptor);
  9465. }
  9466. };
  9467. } // namespace
  9468. static bool checkOMPArraySectionConstantForReduction(
  9469. ASTContext &Context, const OMPArraySectionExpr *OASE, bool &SingleElement,
  9470. SmallVectorImpl<llvm::APSInt> &ArraySizes) {
  9471. const Expr *Length = OASE->getLength();
  9472. if (Length == nullptr) {
  9473. // For array sections of the form [1:] or [:], we would need to analyze
  9474. // the lower bound...
  9475. if (OASE->getColonLoc().isValid())
  9476. return false;
  9477. // This is an array subscript which has implicit length 1!
  9478. SingleElement = true;
  9479. ArraySizes.push_back(llvm::APSInt::get(1));
  9480. } else {
  9481. llvm::APSInt ConstantLengthValue;
  9482. if (!Length->EvaluateAsInt(ConstantLengthValue, Context))
  9483. return false;
  9484. SingleElement = (ConstantLengthValue.getSExtValue() == 1);
  9485. ArraySizes.push_back(ConstantLengthValue);
  9486. }
  9487. // Get the base of this array section and walk up from there.
  9488. const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
  9489. // We require length = 1 for all array sections except the right-most to
  9490. // guarantee that the memory region is contiguous and has no holes in it.
  9491. while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) {
  9492. Length = TempOASE->getLength();
  9493. if (Length == nullptr) {
  9494. // For array sections of the form [1:] or [:], we would need to analyze
  9495. // the lower bound...
  9496. if (OASE->getColonLoc().isValid())
  9497. return false;
  9498. // This is an array subscript which has implicit length 1!
  9499. ArraySizes.push_back(llvm::APSInt::get(1));
  9500. } else {
  9501. llvm::APSInt ConstantLengthValue;
  9502. if (!Length->EvaluateAsInt(ConstantLengthValue, Context) ||
  9503. ConstantLengthValue.getSExtValue() != 1)
  9504. return false;
  9505. ArraySizes.push_back(ConstantLengthValue);
  9506. }
  9507. Base = TempOASE->getBase()->IgnoreParenImpCasts();
  9508. }
  9509. // If we have a single element, we don't need to add the implicit lengths.
  9510. if (!SingleElement) {
  9511. while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) {
  9512. // Has implicit length 1!
  9513. ArraySizes.push_back(llvm::APSInt::get(1));
  9514. Base = TempASE->getBase()->IgnoreParenImpCasts();
  9515. }
  9516. }
  9517. // This array section can be privatized as a single value or as a constant
  9518. // sized array.
  9519. return true;
  9520. }
  9521. static bool actOnOMPReductionKindClause(
  9522. Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind,
  9523. ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
  9524. SourceLocation ColonLoc, SourceLocation EndLoc,
  9525. CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
  9526. ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) {
  9527. DeclarationName DN = ReductionId.getName();
  9528. OverloadedOperatorKind OOK = DN.getCXXOverloadedOperator();
  9529. BinaryOperatorKind BOK = BO_Comma;
  9530. ASTContext &Context = S.Context;
  9531. // OpenMP [2.14.3.6, reduction clause]
  9532. // C
  9533. // reduction-identifier is either an identifier or one of the following
  9534. // operators: +, -, *, &, |, ^, && and ||
  9535. // C++
  9536. // reduction-identifier is either an id-expression or one of the following
  9537. // operators: +, -, *, &, |, ^, && and ||
  9538. switch (OOK) {
  9539. case OO_Plus:
  9540. case OO_Minus:
  9541. BOK = BO_Add;
  9542. break;
  9543. case OO_Star:
  9544. BOK = BO_Mul;
  9545. break;
  9546. case OO_Amp:
  9547. BOK = BO_And;
  9548. break;
  9549. case OO_Pipe:
  9550. BOK = BO_Or;
  9551. break;
  9552. case OO_Caret:
  9553. BOK = BO_Xor;
  9554. break;
  9555. case OO_AmpAmp:
  9556. BOK = BO_LAnd;
  9557. break;
  9558. case OO_PipePipe:
  9559. BOK = BO_LOr;
  9560. break;
  9561. case OO_New:
  9562. case OO_Delete:
  9563. case OO_Array_New:
  9564. case OO_Array_Delete:
  9565. case OO_Slash:
  9566. case OO_Percent:
  9567. case OO_Tilde:
  9568. case OO_Exclaim:
  9569. case OO_Equal:
  9570. case OO_Less:
  9571. case OO_Greater:
  9572. case OO_LessEqual:
  9573. case OO_GreaterEqual:
  9574. case OO_PlusEqual:
  9575. case OO_MinusEqual:
  9576. case OO_StarEqual:
  9577. case OO_SlashEqual:
  9578. case OO_PercentEqual:
  9579. case OO_CaretEqual:
  9580. case OO_AmpEqual:
  9581. case OO_PipeEqual:
  9582. case OO_LessLess:
  9583. case OO_GreaterGreater:
  9584. case OO_LessLessEqual:
  9585. case OO_GreaterGreaterEqual:
  9586. case OO_EqualEqual:
  9587. case OO_ExclaimEqual:
  9588. case OO_Spaceship:
  9589. case OO_PlusPlus:
  9590. case OO_MinusMinus:
  9591. case OO_Comma:
  9592. case OO_ArrowStar:
  9593. case OO_Arrow:
  9594. case OO_Call:
  9595. case OO_Subscript:
  9596. case OO_Conditional:
  9597. case OO_Coawait:
  9598. case NUM_OVERLOADED_OPERATORS:
  9599. llvm_unreachable("Unexpected reduction identifier");
  9600. case OO_None:
  9601. if (IdentifierInfo *II = DN.getAsIdentifierInfo()) {
  9602. if (II->isStr("max"))
  9603. BOK = BO_GT;
  9604. else if (II->isStr("min"))
  9605. BOK = BO_LT;
  9606. }
  9607. break;
  9608. }
  9609. SourceRange ReductionIdRange;
  9610. if (ReductionIdScopeSpec.isValid())
  9611. ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
  9612. else
  9613. ReductionIdRange.setBegin(ReductionId.getBeginLoc());
  9614. ReductionIdRange.setEnd(ReductionId.getEndLoc());
  9615. auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
  9616. bool FirstIter = true;
  9617. for (Expr *RefExpr : VarList) {
  9618. assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
  9619. // OpenMP [2.1, C/C++]
  9620. // A list item is a variable or array section, subject to the restrictions
  9621. // specified in Section 2.4 on page 42 and in each of the sections
  9622. // describing clauses and directives for which a list appears.
  9623. // OpenMP [2.14.3.3, Restrictions, p.1]
  9624. // A variable that is part of another variable (as an array or
  9625. // structure element) cannot appear in a private clause.
  9626. if (!FirstIter && IR != ER)
  9627. ++IR;
  9628. FirstIter = false;
  9629. SourceLocation ELoc;
  9630. SourceRange ERange;
  9631. Expr *SimpleRefExpr = RefExpr;
  9632. auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
  9633. /*AllowArraySection=*/true);
  9634. if (Res.second) {
  9635. // Try to find 'declare reduction' corresponding construct before using
  9636. // builtin/overloaded operators.
  9637. QualType Type = Context.DependentTy;
  9638. CXXCastPath BasePath;
  9639. ExprResult DeclareReductionRef = buildDeclareReductionRef(
  9640. S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
  9641. ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
  9642. Expr *ReductionOp = nullptr;
  9643. if (S.CurContext->isDependentContext() &&
  9644. (DeclareReductionRef.isUnset() ||
  9645. isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
  9646. ReductionOp = DeclareReductionRef.get();
  9647. // It will be analyzed later.
  9648. RD.push(RefExpr, ReductionOp);
  9649. }
  9650. ValueDecl *D = Res.first;
  9651. if (!D)
  9652. continue;
  9653. Expr *TaskgroupDescriptor = nullptr;
  9654. QualType Type;
  9655. auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
  9656. auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
  9657. if (ASE) {
  9658. Type = ASE->getType().getNonReferenceType();
  9659. } else if (OASE) {
  9660. QualType BaseType =
  9661. OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
  9662. if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
  9663. Type = ATy->getElementType();
  9664. else
  9665. Type = BaseType->getPointeeType();
  9666. Type = Type.getNonReferenceType();
  9667. } else {
  9668. Type = Context.getBaseElementType(D->getType().getNonReferenceType());
  9669. }
  9670. auto *VD = dyn_cast<VarDecl>(D);
  9671. // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
  9672. // A variable that appears in a private clause must not have an incomplete
  9673. // type or a reference type.
  9674. if (S.RequireCompleteType(ELoc, Type,
  9675. diag::err_omp_reduction_incomplete_type))
  9676. continue;
  9677. // OpenMP [2.14.3.6, reduction clause, Restrictions]
  9678. // A list item that appears in a reduction clause must not be
  9679. // const-qualified.
  9680. if (Type.getNonReferenceType().isConstant(Context)) {
  9681. S.Diag(ELoc, diag::err_omp_const_reduction_list_item) << ERange;
  9682. if (!ASE && !OASE) {
  9683. bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
  9684. VarDecl::DeclarationOnly;
  9685. S.Diag(D->getLocation(),
  9686. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  9687. << D;
  9688. }
  9689. continue;
  9690. }
  9691. // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
  9692. // If a list-item is a reference type then it must bind to the same object
  9693. // for all threads of the team.
  9694. if (!ASE && !OASE && VD) {
  9695. VarDecl *VDDef = VD->getDefinition();
  9696. if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
  9697. DSARefChecker Check(Stack);
  9698. if (Check.Visit(VDDef->getInit())) {
  9699. S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg)
  9700. << getOpenMPClauseName(ClauseKind) << ERange;
  9701. S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
  9702. continue;
  9703. }
  9704. }
  9705. }
  9706. // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
  9707. // in a Construct]
  9708. // Variables with the predetermined data-sharing attributes may not be
  9709. // listed in data-sharing attributes clauses, except for the cases
  9710. // listed below. For these exceptions only, listing a predetermined
  9711. // variable in a data-sharing attribute clause is allowed and overrides
  9712. // the variable's predetermined data-sharing attributes.
  9713. // OpenMP [2.14.3.6, Restrictions, p.3]
  9714. // Any number of reduction clauses can be specified on the directive,
  9715. // but a list item can appear only once in the reduction clauses for that
  9716. // directive.
  9717. DSAStackTy::DSAVarData DVar = Stack->getTopDSA(D, /*FromParent=*/false);
  9718. if (DVar.CKind == OMPC_reduction) {
  9719. S.Diag(ELoc, diag::err_omp_once_referenced)
  9720. << getOpenMPClauseName(ClauseKind);
  9721. if (DVar.RefExpr)
  9722. S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
  9723. continue;
  9724. }
  9725. if (DVar.CKind != OMPC_unknown) {
  9726. S.Diag(ELoc, diag::err_omp_wrong_dsa)
  9727. << getOpenMPClauseName(DVar.CKind)
  9728. << getOpenMPClauseName(OMPC_reduction);
  9729. reportOriginalDsa(S, Stack, D, DVar);
  9730. continue;
  9731. }
  9732. // OpenMP [2.14.3.6, Restrictions, p.1]
  9733. // A list item that appears in a reduction clause of a worksharing
  9734. // construct must be shared in the parallel regions to which any of the
  9735. // worksharing regions arising from the worksharing construct bind.
  9736. OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective();
  9737. if (isOpenMPWorksharingDirective(CurrDir) &&
  9738. !isOpenMPParallelDirective(CurrDir) &&
  9739. !isOpenMPTeamsDirective(CurrDir)) {
  9740. DVar = Stack->getImplicitDSA(D, true);
  9741. if (DVar.CKind != OMPC_shared) {
  9742. S.Diag(ELoc, diag::err_omp_required_access)
  9743. << getOpenMPClauseName(OMPC_reduction)
  9744. << getOpenMPClauseName(OMPC_shared);
  9745. reportOriginalDsa(S, Stack, D, DVar);
  9746. continue;
  9747. }
  9748. }
  9749. // Try to find 'declare reduction' corresponding construct before using
  9750. // builtin/overloaded operators.
  9751. CXXCastPath BasePath;
  9752. ExprResult DeclareReductionRef = buildDeclareReductionRef(
  9753. S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
  9754. ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
  9755. if (DeclareReductionRef.isInvalid())
  9756. continue;
  9757. if (S.CurContext->isDependentContext() &&
  9758. (DeclareReductionRef.isUnset() ||
  9759. isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
  9760. RD.push(RefExpr, DeclareReductionRef.get());
  9761. continue;
  9762. }
  9763. if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
  9764. // Not allowed reduction identifier is found.
  9765. S.Diag(ReductionId.getLocStart(),
  9766. diag::err_omp_unknown_reduction_identifier)
  9767. << Type << ReductionIdRange;
  9768. continue;
  9769. }
  9770. // OpenMP [2.14.3.6, reduction clause, Restrictions]
  9771. // The type of a list item that appears in a reduction clause must be valid
  9772. // for the reduction-identifier. For a max or min reduction in C, the type
  9773. // of the list item must be an allowed arithmetic data type: char, int,
  9774. // float, double, or _Bool, possibly modified with long, short, signed, or
  9775. // unsigned. For a max or min reduction in C++, the type of the list item
  9776. // must be an allowed arithmetic data type: char, wchar_t, int, float,
  9777. // double, or bool, possibly modified with long, short, signed, or unsigned.
  9778. if (DeclareReductionRef.isUnset()) {
  9779. if ((BOK == BO_GT || BOK == BO_LT) &&
  9780. !(Type->isScalarType() ||
  9781. (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
  9782. S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
  9783. << getOpenMPClauseName(ClauseKind) << S.getLangOpts().CPlusPlus;
  9784. if (!ASE && !OASE) {
  9785. bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
  9786. VarDecl::DeclarationOnly;
  9787. S.Diag(D->getLocation(),
  9788. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  9789. << D;
  9790. }
  9791. continue;
  9792. }
  9793. if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
  9794. !S.getLangOpts().CPlusPlus && Type->isFloatingType()) {
  9795. S.Diag(ELoc, diag::err_omp_clause_floating_type_arg)
  9796. << getOpenMPClauseName(ClauseKind);
  9797. if (!ASE && !OASE) {
  9798. bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
  9799. VarDecl::DeclarationOnly;
  9800. S.Diag(D->getLocation(),
  9801. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  9802. << D;
  9803. }
  9804. continue;
  9805. }
  9806. }
  9807. Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
  9808. VarDecl *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs",
  9809. D->hasAttrs() ? &D->getAttrs() : nullptr);
  9810. VarDecl *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(),
  9811. D->hasAttrs() ? &D->getAttrs() : nullptr);
  9812. QualType PrivateTy = Type;
  9813. // Try if we can determine constant lengths for all array sections and avoid
  9814. // the VLA.
  9815. bool ConstantLengthOASE = false;
  9816. if (OASE) {
  9817. bool SingleElement;
  9818. llvm::SmallVector<llvm::APSInt, 4> ArraySizes;
  9819. ConstantLengthOASE = checkOMPArraySectionConstantForReduction(
  9820. Context, OASE, SingleElement, ArraySizes);
  9821. // If we don't have a single element, we must emit a constant array type.
  9822. if (ConstantLengthOASE && !SingleElement) {
  9823. for (llvm::APSInt &Size : ArraySizes)
  9824. PrivateTy = Context.getConstantArrayType(
  9825. PrivateTy, Size, ArrayType::Normal, /*IndexTypeQuals=*/0);
  9826. }
  9827. }
  9828. if ((OASE && !ConstantLengthOASE) ||
  9829. (!OASE && !ASE &&
  9830. D->getType().getNonReferenceType()->isVariablyModifiedType())) {
  9831. if (!Context.getTargetInfo().isVLASupported() &&
  9832. S.shouldDiagnoseTargetSupportFromOpenMP()) {
  9833. S.Diag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
  9834. S.Diag(ELoc, diag::note_vla_unsupported);
  9835. continue;
  9836. }
  9837. // For arrays/array sections only:
  9838. // Create pseudo array type for private copy. The size for this array will
  9839. // be generated during codegen.
  9840. // For array subscripts or single variables Private Ty is the same as Type
  9841. // (type of the variable or single array element).
  9842. PrivateTy = Context.getVariableArrayType(
  9843. Type,
  9844. new (Context) OpaqueValueExpr(ELoc, Context.getSizeType(), VK_RValue),
  9845. ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
  9846. } else if (!ASE && !OASE &&
  9847. Context.getAsArrayType(D->getType().getNonReferenceType())) {
  9848. PrivateTy = D->getType().getNonReferenceType();
  9849. }
  9850. // Private copy.
  9851. VarDecl *PrivateVD =
  9852. buildVarDecl(S, ELoc, PrivateTy, D->getName(),
  9853. D->hasAttrs() ? &D->getAttrs() : nullptr,
  9854. VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
  9855. // Add initializer for private variable.
  9856. Expr *Init = nullptr;
  9857. DeclRefExpr *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc);
  9858. DeclRefExpr *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc);
  9859. if (DeclareReductionRef.isUsable()) {
  9860. auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
  9861. auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
  9862. if (DRD->getInitializer()) {
  9863. Init = DRDRef;
  9864. RHSVD->setInit(DRDRef);
  9865. RHSVD->setInitStyle(VarDecl::CallInit);
  9866. }
  9867. } else {
  9868. switch (BOK) {
  9869. case BO_Add:
  9870. case BO_Xor:
  9871. case BO_Or:
  9872. case BO_LOr:
  9873. // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
  9874. if (Type->isScalarType() || Type->isAnyComplexType())
  9875. Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get();
  9876. break;
  9877. case BO_Mul:
  9878. case BO_LAnd:
  9879. if (Type->isScalarType() || Type->isAnyComplexType()) {
  9880. // '*' and '&&' reduction ops - initializer is '1'.
  9881. Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get();
  9882. }
  9883. break;
  9884. case BO_And: {
  9885. // '&' reduction op - initializer is '~0'.
  9886. QualType OrigType = Type;
  9887. if (auto *ComplexTy = OrigType->getAs<ComplexType>())
  9888. Type = ComplexTy->getElementType();
  9889. if (Type->isRealFloatingType()) {
  9890. llvm::APFloat InitValue =
  9891. llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
  9892. /*isIEEE=*/true);
  9893. Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
  9894. Type, ELoc);
  9895. } else if (Type->isScalarType()) {
  9896. uint64_t Size = Context.getTypeSize(Type);
  9897. QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
  9898. llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
  9899. Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
  9900. }
  9901. if (Init && OrigType->isAnyComplexType()) {
  9902. // Init = 0xFFFF + 0xFFFFi;
  9903. auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
  9904. Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
  9905. }
  9906. Type = OrigType;
  9907. break;
  9908. }
  9909. case BO_LT:
  9910. case BO_GT: {
  9911. // 'min' reduction op - initializer is 'Largest representable number in
  9912. // the reduction list item type'.
  9913. // 'max' reduction op - initializer is 'Least representable number in
  9914. // the reduction list item type'.
  9915. if (Type->isIntegerType() || Type->isPointerType()) {
  9916. bool IsSigned = Type->hasSignedIntegerRepresentation();
  9917. uint64_t Size = Context.getTypeSize(Type);
  9918. QualType IntTy =
  9919. Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
  9920. llvm::APInt InitValue =
  9921. (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
  9922. : llvm::APInt::getMinValue(Size)
  9923. : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
  9924. : llvm::APInt::getMaxValue(Size);
  9925. Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
  9926. if (Type->isPointerType()) {
  9927. // Cast to pointer type.
  9928. ExprResult CastExpr = S.BuildCStyleCastExpr(
  9929. ELoc, Context.getTrivialTypeSourceInfo(Type, ELoc), ELoc, Init);
  9930. if (CastExpr.isInvalid())
  9931. continue;
  9932. Init = CastExpr.get();
  9933. }
  9934. } else if (Type->isRealFloatingType()) {
  9935. llvm::APFloat InitValue = llvm::APFloat::getLargest(
  9936. Context.getFloatTypeSemantics(Type), BOK != BO_LT);
  9937. Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
  9938. Type, ELoc);
  9939. }
  9940. break;
  9941. }
  9942. case BO_PtrMemD:
  9943. case BO_PtrMemI:
  9944. case BO_MulAssign:
  9945. case BO_Div:
  9946. case BO_Rem:
  9947. case BO_Sub:
  9948. case BO_Shl:
  9949. case BO_Shr:
  9950. case BO_LE:
  9951. case BO_GE:
  9952. case BO_EQ:
  9953. case BO_NE:
  9954. case BO_Cmp:
  9955. case BO_AndAssign:
  9956. case BO_XorAssign:
  9957. case BO_OrAssign:
  9958. case BO_Assign:
  9959. case BO_AddAssign:
  9960. case BO_SubAssign:
  9961. case BO_DivAssign:
  9962. case BO_RemAssign:
  9963. case BO_ShlAssign:
  9964. case BO_ShrAssign:
  9965. case BO_Comma:
  9966. llvm_unreachable("Unexpected reduction operation");
  9967. }
  9968. }
  9969. if (Init && DeclareReductionRef.isUnset())
  9970. S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false);
  9971. else if (!Init)
  9972. S.ActOnUninitializedDecl(RHSVD);
  9973. if (RHSVD->isInvalidDecl())
  9974. continue;
  9975. if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) {
  9976. S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible)
  9977. << Type << ReductionIdRange;
  9978. bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
  9979. VarDecl::DeclarationOnly;
  9980. S.Diag(D->getLocation(),
  9981. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  9982. << D;
  9983. continue;
  9984. }
  9985. // Store initializer for single element in private copy. Will be used during
  9986. // codegen.
  9987. PrivateVD->setInit(RHSVD->getInit());
  9988. PrivateVD->setInitStyle(RHSVD->getInitStyle());
  9989. DeclRefExpr *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc);
  9990. ExprResult ReductionOp;
  9991. if (DeclareReductionRef.isUsable()) {
  9992. QualType RedTy = DeclareReductionRef.get()->getType();
  9993. QualType PtrRedTy = Context.getPointerType(RedTy);
  9994. ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
  9995. ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
  9996. if (!BasePath.empty()) {
  9997. LHS = S.DefaultLvalueConversion(LHS.get());
  9998. RHS = S.DefaultLvalueConversion(RHS.get());
  9999. LHS = ImplicitCastExpr::Create(Context, PtrRedTy,
  10000. CK_UncheckedDerivedToBase, LHS.get(),
  10001. &BasePath, LHS.get()->getValueKind());
  10002. RHS = ImplicitCastExpr::Create(Context, PtrRedTy,
  10003. CK_UncheckedDerivedToBase, RHS.get(),
  10004. &BasePath, RHS.get()->getValueKind());
  10005. }
  10006. FunctionProtoType::ExtProtoInfo EPI;
  10007. QualType Params[] = {PtrRedTy, PtrRedTy};
  10008. QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
  10009. auto *OVE = new (Context) OpaqueValueExpr(
  10010. ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary,
  10011. S.DefaultLvalueConversion(DeclareReductionRef.get()).get());
  10012. Expr *Args[] = {LHS.get(), RHS.get()};
  10013. ReductionOp = new (Context)
  10014. CallExpr(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc);
  10015. } else {
  10016. ReductionOp = S.BuildBinOp(
  10017. Stack->getCurScope(), ReductionId.getLocStart(), BOK, LHSDRE, RHSDRE);
  10018. if (ReductionOp.isUsable()) {
  10019. if (BOK != BO_LT && BOK != BO_GT) {
  10020. ReductionOp =
  10021. S.BuildBinOp(Stack->getCurScope(), ReductionId.getLocStart(),
  10022. BO_Assign, LHSDRE, ReductionOp.get());
  10023. } else {
  10024. auto *ConditionalOp = new (Context)
  10025. ConditionalOperator(ReductionOp.get(), ELoc, LHSDRE, ELoc, RHSDRE,
  10026. Type, VK_LValue, OK_Ordinary);
  10027. ReductionOp =
  10028. S.BuildBinOp(Stack->getCurScope(), ReductionId.getLocStart(),
  10029. BO_Assign, LHSDRE, ConditionalOp);
  10030. }
  10031. if (ReductionOp.isUsable())
  10032. ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get());
  10033. }
  10034. if (!ReductionOp.isUsable())
  10035. continue;
  10036. }
  10037. // OpenMP [2.15.4.6, Restrictions, p.2]
  10038. // A list item that appears in an in_reduction clause of a task construct
  10039. // must appear in a task_reduction clause of a construct associated with a
  10040. // taskgroup region that includes the participating task in its taskgroup
  10041. // set. The construct associated with the innermost region that meets this
  10042. // condition must specify the same reduction-identifier as the in_reduction
  10043. // clause.
  10044. if (ClauseKind == OMPC_in_reduction) {
  10045. SourceRange ParentSR;
  10046. BinaryOperatorKind ParentBOK;
  10047. const Expr *ParentReductionOp;
  10048. Expr *ParentBOKTD, *ParentReductionOpTD;
  10049. DSAStackTy::DSAVarData ParentBOKDSA =
  10050. Stack->getTopMostTaskgroupReductionData(D, ParentSR, ParentBOK,
  10051. ParentBOKTD);
  10052. DSAStackTy::DSAVarData ParentReductionOpDSA =
  10053. Stack->getTopMostTaskgroupReductionData(
  10054. D, ParentSR, ParentReductionOp, ParentReductionOpTD);
  10055. bool IsParentBOK = ParentBOKDSA.DKind != OMPD_unknown;
  10056. bool IsParentReductionOp = ParentReductionOpDSA.DKind != OMPD_unknown;
  10057. if (!IsParentBOK && !IsParentReductionOp) {
  10058. S.Diag(ELoc, diag::err_omp_in_reduction_not_task_reduction);
  10059. continue;
  10060. }
  10061. if ((DeclareReductionRef.isUnset() && IsParentReductionOp) ||
  10062. (DeclareReductionRef.isUsable() && IsParentBOK) || BOK != ParentBOK ||
  10063. IsParentReductionOp) {
  10064. bool EmitError = true;
  10065. if (IsParentReductionOp && DeclareReductionRef.isUsable()) {
  10066. llvm::FoldingSetNodeID RedId, ParentRedId;
  10067. ParentReductionOp->Profile(ParentRedId, Context, /*Canonical=*/true);
  10068. DeclareReductionRef.get()->Profile(RedId, Context,
  10069. /*Canonical=*/true);
  10070. EmitError = RedId != ParentRedId;
  10071. }
  10072. if (EmitError) {
  10073. S.Diag(ReductionId.getLocStart(),
  10074. diag::err_omp_reduction_identifier_mismatch)
  10075. << ReductionIdRange << RefExpr->getSourceRange();
  10076. S.Diag(ParentSR.getBegin(),
  10077. diag::note_omp_previous_reduction_identifier)
  10078. << ParentSR
  10079. << (IsParentBOK ? ParentBOKDSA.RefExpr
  10080. : ParentReductionOpDSA.RefExpr)
  10081. ->getSourceRange();
  10082. continue;
  10083. }
  10084. }
  10085. TaskgroupDescriptor = IsParentBOK ? ParentBOKTD : ParentReductionOpTD;
  10086. assert(TaskgroupDescriptor && "Taskgroup descriptor must be defined.");
  10087. }
  10088. DeclRefExpr *Ref = nullptr;
  10089. Expr *VarsExpr = RefExpr->IgnoreParens();
  10090. if (!VD && !S.CurContext->isDependentContext()) {
  10091. if (ASE || OASE) {
  10092. TransformExprToCaptures RebuildToCapture(S, D);
  10093. VarsExpr =
  10094. RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
  10095. Ref = RebuildToCapture.getCapturedExpr();
  10096. } else {
  10097. VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false);
  10098. }
  10099. if (!S.isOpenMPCapturedDecl(D)) {
  10100. RD.ExprCaptures.emplace_back(Ref->getDecl());
  10101. if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
  10102. ExprResult RefRes = S.DefaultLvalueConversion(Ref);
  10103. if (!RefRes.isUsable())
  10104. continue;
  10105. ExprResult PostUpdateRes =
  10106. S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
  10107. RefRes.get());
  10108. if (!PostUpdateRes.isUsable())
  10109. continue;
  10110. if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
  10111. Stack->getCurrentDirective() == OMPD_taskgroup) {
  10112. S.Diag(RefExpr->getExprLoc(),
  10113. diag::err_omp_reduction_non_addressable_expression)
  10114. << RefExpr->getSourceRange();
  10115. continue;
  10116. }
  10117. RD.ExprPostUpdates.emplace_back(
  10118. S.IgnoredValueConversions(PostUpdateRes.get()).get());
  10119. }
  10120. }
  10121. }
  10122. // All reduction items are still marked as reduction (to do not increase
  10123. // code base size).
  10124. Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref);
  10125. if (CurrDir == OMPD_taskgroup) {
  10126. if (DeclareReductionRef.isUsable())
  10127. Stack->addTaskgroupReductionData(D, ReductionIdRange,
  10128. DeclareReductionRef.get());
  10129. else
  10130. Stack->addTaskgroupReductionData(D, ReductionIdRange, BOK);
  10131. }
  10132. RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get(),
  10133. TaskgroupDescriptor);
  10134. }
  10135. return RD.Vars.empty();
  10136. }
  10137. OMPClause *Sema::ActOnOpenMPReductionClause(
  10138. ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
  10139. SourceLocation ColonLoc, SourceLocation EndLoc,
  10140. CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
  10141. ArrayRef<Expr *> UnresolvedReductions) {
  10142. ReductionData RD(VarList.size());
  10143. if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_reduction, VarList,
  10144. StartLoc, LParenLoc, ColonLoc, EndLoc,
  10145. ReductionIdScopeSpec, ReductionId,
  10146. UnresolvedReductions, RD))
  10147. return nullptr;
  10148. return OMPReductionClause::Create(
  10149. Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
  10150. ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
  10151. RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
  10152. buildPreInits(Context, RD.ExprCaptures),
  10153. buildPostUpdate(*this, RD.ExprPostUpdates));
  10154. }
  10155. OMPClause *Sema::ActOnOpenMPTaskReductionClause(
  10156. ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
  10157. SourceLocation ColonLoc, SourceLocation EndLoc,
  10158. CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
  10159. ArrayRef<Expr *> UnresolvedReductions) {
  10160. ReductionData RD(VarList.size());
  10161. if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_task_reduction, VarList,
  10162. StartLoc, LParenLoc, ColonLoc, EndLoc,
  10163. ReductionIdScopeSpec, ReductionId,
  10164. UnresolvedReductions, RD))
  10165. return nullptr;
  10166. return OMPTaskReductionClause::Create(
  10167. Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
  10168. ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
  10169. RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
  10170. buildPreInits(Context, RD.ExprCaptures),
  10171. buildPostUpdate(*this, RD.ExprPostUpdates));
  10172. }
  10173. OMPClause *Sema::ActOnOpenMPInReductionClause(
  10174. ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
  10175. SourceLocation ColonLoc, SourceLocation EndLoc,
  10176. CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
  10177. ArrayRef<Expr *> UnresolvedReductions) {
  10178. ReductionData RD(VarList.size());
  10179. if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_in_reduction, VarList,
  10180. StartLoc, LParenLoc, ColonLoc, EndLoc,
  10181. ReductionIdScopeSpec, ReductionId,
  10182. UnresolvedReductions, RD))
  10183. return nullptr;
  10184. return OMPInReductionClause::Create(
  10185. Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
  10186. ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
  10187. RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.TaskgroupDescriptors,
  10188. buildPreInits(Context, RD.ExprCaptures),
  10189. buildPostUpdate(*this, RD.ExprPostUpdates));
  10190. }
  10191. bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
  10192. SourceLocation LinLoc) {
  10193. if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
  10194. LinKind == OMPC_LINEAR_unknown) {
  10195. Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
  10196. return true;
  10197. }
  10198. return false;
  10199. }
  10200. bool Sema::CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc,
  10201. OpenMPLinearClauseKind LinKind,
  10202. QualType Type) {
  10203. const auto *VD = dyn_cast_or_null<VarDecl>(D);
  10204. // A variable must not have an incomplete type or a reference type.
  10205. if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
  10206. return true;
  10207. if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
  10208. !Type->isReferenceType()) {
  10209. Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
  10210. << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
  10211. return true;
  10212. }
  10213. Type = Type.getNonReferenceType();
  10214. // A list item must not be const-qualified.
  10215. if (Type.isConstant(Context)) {
  10216. Diag(ELoc, diag::err_omp_const_variable)
  10217. << getOpenMPClauseName(OMPC_linear);
  10218. if (D) {
  10219. bool IsDecl =
  10220. !VD ||
  10221. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  10222. Diag(D->getLocation(),
  10223. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  10224. << D;
  10225. }
  10226. return true;
  10227. }
  10228. // A list item must be of integral or pointer type.
  10229. Type = Type.getUnqualifiedType().getCanonicalType();
  10230. const auto *Ty = Type.getTypePtrOrNull();
  10231. if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
  10232. !Ty->isPointerType())) {
  10233. Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
  10234. if (D) {
  10235. bool IsDecl =
  10236. !VD ||
  10237. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  10238. Diag(D->getLocation(),
  10239. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  10240. << D;
  10241. }
  10242. return true;
  10243. }
  10244. return false;
  10245. }
  10246. OMPClause *Sema::ActOnOpenMPLinearClause(
  10247. ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
  10248. SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
  10249. SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
  10250. SmallVector<Expr *, 8> Vars;
  10251. SmallVector<Expr *, 8> Privates;
  10252. SmallVector<Expr *, 8> Inits;
  10253. SmallVector<Decl *, 4> ExprCaptures;
  10254. SmallVector<Expr *, 4> ExprPostUpdates;
  10255. if (CheckOpenMPLinearModifier(LinKind, LinLoc))
  10256. LinKind = OMPC_LINEAR_val;
  10257. for (Expr *RefExpr : VarList) {
  10258. assert(RefExpr && "NULL expr in OpenMP linear clause.");
  10259. SourceLocation ELoc;
  10260. SourceRange ERange;
  10261. Expr *SimpleRefExpr = RefExpr;
  10262. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
  10263. /*AllowArraySection=*/false);
  10264. if (Res.second) {
  10265. // It will be analyzed later.
  10266. Vars.push_back(RefExpr);
  10267. Privates.push_back(nullptr);
  10268. Inits.push_back(nullptr);
  10269. }
  10270. ValueDecl *D = Res.first;
  10271. if (!D)
  10272. continue;
  10273. QualType Type = D->getType();
  10274. auto *VD = dyn_cast<VarDecl>(D);
  10275. // OpenMP [2.14.3.7, linear clause]
  10276. // A list-item cannot appear in more than one linear clause.
  10277. // A list-item that appears in a linear clause cannot appear in any
  10278. // other data-sharing attribute clause.
  10279. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
  10280. if (DVar.RefExpr) {
  10281. Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
  10282. << getOpenMPClauseName(OMPC_linear);
  10283. reportOriginalDsa(*this, DSAStack, D, DVar);
  10284. continue;
  10285. }
  10286. if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
  10287. continue;
  10288. Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
  10289. // Build private copy of original var.
  10290. VarDecl *Private =
  10291. buildVarDecl(*this, ELoc, Type, D->getName(),
  10292. D->hasAttrs() ? &D->getAttrs() : nullptr,
  10293. VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
  10294. DeclRefExpr *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
  10295. // Build var to save initial value.
  10296. VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
  10297. Expr *InitExpr;
  10298. DeclRefExpr *Ref = nullptr;
  10299. if (!VD && !CurContext->isDependentContext()) {
  10300. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
  10301. if (!isOpenMPCapturedDecl(D)) {
  10302. ExprCaptures.push_back(Ref->getDecl());
  10303. if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
  10304. ExprResult RefRes = DefaultLvalueConversion(Ref);
  10305. if (!RefRes.isUsable())
  10306. continue;
  10307. ExprResult PostUpdateRes =
  10308. BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
  10309. SimpleRefExpr, RefRes.get());
  10310. if (!PostUpdateRes.isUsable())
  10311. continue;
  10312. ExprPostUpdates.push_back(
  10313. IgnoredValueConversions(PostUpdateRes.get()).get());
  10314. }
  10315. }
  10316. }
  10317. if (LinKind == OMPC_LINEAR_uval)
  10318. InitExpr = VD ? VD->getInit() : SimpleRefExpr;
  10319. else
  10320. InitExpr = VD ? SimpleRefExpr : Ref;
  10321. AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
  10322. /*DirectInit=*/false);
  10323. DeclRefExpr *InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
  10324. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
  10325. Vars.push_back((VD || CurContext->isDependentContext())
  10326. ? RefExpr->IgnoreParens()
  10327. : Ref);
  10328. Privates.push_back(PrivateRef);
  10329. Inits.push_back(InitRef);
  10330. }
  10331. if (Vars.empty())
  10332. return nullptr;
  10333. Expr *StepExpr = Step;
  10334. Expr *CalcStepExpr = nullptr;
  10335. if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
  10336. !Step->isInstantiationDependent() &&
  10337. !Step->containsUnexpandedParameterPack()) {
  10338. SourceLocation StepLoc = Step->getLocStart();
  10339. ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
  10340. if (Val.isInvalid())
  10341. return nullptr;
  10342. StepExpr = Val.get();
  10343. // Build var to save the step value.
  10344. VarDecl *SaveVar =
  10345. buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
  10346. ExprResult SaveRef =
  10347. buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
  10348. ExprResult CalcStep =
  10349. BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
  10350. CalcStep = ActOnFinishFullExpr(CalcStep.get());
  10351. // Warn about zero linear step (it would be probably better specified as
  10352. // making corresponding variables 'const').
  10353. llvm::APSInt Result;
  10354. bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
  10355. if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
  10356. Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
  10357. << (Vars.size() > 1);
  10358. if (!IsConstant && CalcStep.isUsable()) {
  10359. // Calculate the step beforehand instead of doing this on each iteration.
  10360. // (This is not used if the number of iterations may be kfold-ed).
  10361. CalcStepExpr = CalcStep.get();
  10362. }
  10363. }
  10364. return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
  10365. ColonLoc, EndLoc, Vars, Privates, Inits,
  10366. StepExpr, CalcStepExpr,
  10367. buildPreInits(Context, ExprCaptures),
  10368. buildPostUpdate(*this, ExprPostUpdates));
  10369. }
  10370. static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
  10371. Expr *NumIterations, Sema &SemaRef,
  10372. Scope *S, DSAStackTy *Stack) {
  10373. // Walk the vars and build update/final expressions for the CodeGen.
  10374. SmallVector<Expr *, 8> Updates;
  10375. SmallVector<Expr *, 8> Finals;
  10376. Expr *Step = Clause.getStep();
  10377. Expr *CalcStep = Clause.getCalcStep();
  10378. // OpenMP [2.14.3.7, linear clause]
  10379. // If linear-step is not specified it is assumed to be 1.
  10380. if (!Step)
  10381. Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
  10382. else if (CalcStep)
  10383. Step = cast<BinaryOperator>(CalcStep)->getLHS();
  10384. bool HasErrors = false;
  10385. auto CurInit = Clause.inits().begin();
  10386. auto CurPrivate = Clause.privates().begin();
  10387. OpenMPLinearClauseKind LinKind = Clause.getModifier();
  10388. for (Expr *RefExpr : Clause.varlists()) {
  10389. SourceLocation ELoc;
  10390. SourceRange ERange;
  10391. Expr *SimpleRefExpr = RefExpr;
  10392. auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange,
  10393. /*AllowArraySection=*/false);
  10394. ValueDecl *D = Res.first;
  10395. if (Res.second || !D) {
  10396. Updates.push_back(nullptr);
  10397. Finals.push_back(nullptr);
  10398. HasErrors = true;
  10399. continue;
  10400. }
  10401. auto &&Info = Stack->isLoopControlVariable(D);
  10402. // OpenMP [2.15.11, distribute simd Construct]
  10403. // A list item may not appear in a linear clause, unless it is the loop
  10404. // iteration variable.
  10405. if (isOpenMPDistributeDirective(Stack->getCurrentDirective()) &&
  10406. isOpenMPSimdDirective(Stack->getCurrentDirective()) && !Info.first) {
  10407. SemaRef.Diag(ELoc,
  10408. diag::err_omp_linear_distribute_var_non_loop_iteration);
  10409. Updates.push_back(nullptr);
  10410. Finals.push_back(nullptr);
  10411. HasErrors = true;
  10412. continue;
  10413. }
  10414. Expr *InitExpr = *CurInit;
  10415. // Build privatized reference to the current linear var.
  10416. auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
  10417. Expr *CapturedRef;
  10418. if (LinKind == OMPC_LINEAR_uval)
  10419. CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
  10420. else
  10421. CapturedRef =
  10422. buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
  10423. DE->getType().getUnqualifiedType(), DE->getExprLoc(),
  10424. /*RefersToCapture=*/true);
  10425. // Build update: Var = InitExpr + IV * Step
  10426. ExprResult Update;
  10427. if (!Info.first)
  10428. Update =
  10429. buildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate,
  10430. InitExpr, IV, Step, /* Subtract */ false);
  10431. else
  10432. Update = *CurPrivate;
  10433. Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getLocStart(),
  10434. /*DiscardedValue=*/true);
  10435. // Build final: Var = InitExpr + NumIterations * Step
  10436. ExprResult Final;
  10437. if (!Info.first)
  10438. Final =
  10439. buildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
  10440. InitExpr, NumIterations, Step, /*Subtract=*/false);
  10441. else
  10442. Final = *CurPrivate;
  10443. Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getLocStart(),
  10444. /*DiscardedValue=*/true);
  10445. if (!Update.isUsable() || !Final.isUsable()) {
  10446. Updates.push_back(nullptr);
  10447. Finals.push_back(nullptr);
  10448. HasErrors = true;
  10449. } else {
  10450. Updates.push_back(Update.get());
  10451. Finals.push_back(Final.get());
  10452. }
  10453. ++CurInit;
  10454. ++CurPrivate;
  10455. }
  10456. Clause.setUpdates(Updates);
  10457. Clause.setFinals(Finals);
  10458. return HasErrors;
  10459. }
  10460. OMPClause *Sema::ActOnOpenMPAlignedClause(
  10461. ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
  10462. SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
  10463. SmallVector<Expr *, 8> Vars;
  10464. for (Expr *RefExpr : VarList) {
  10465. assert(RefExpr && "NULL expr in OpenMP linear clause.");
  10466. SourceLocation ELoc;
  10467. SourceRange ERange;
  10468. Expr *SimpleRefExpr = RefExpr;
  10469. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
  10470. /*AllowArraySection=*/false);
  10471. if (Res.second) {
  10472. // It will be analyzed later.
  10473. Vars.push_back(RefExpr);
  10474. }
  10475. ValueDecl *D = Res.first;
  10476. if (!D)
  10477. continue;
  10478. QualType QType = D->getType();
  10479. auto *VD = dyn_cast<VarDecl>(D);
  10480. // OpenMP [2.8.1, simd construct, Restrictions]
  10481. // The type of list items appearing in the aligned clause must be
  10482. // array, pointer, reference to array, or reference to pointer.
  10483. QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
  10484. const Type *Ty = QType.getTypePtrOrNull();
  10485. if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
  10486. Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
  10487. << QType << getLangOpts().CPlusPlus << ERange;
  10488. bool IsDecl =
  10489. !VD ||
  10490. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  10491. Diag(D->getLocation(),
  10492. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  10493. << D;
  10494. continue;
  10495. }
  10496. // OpenMP [2.8.1, simd construct, Restrictions]
  10497. // A list-item cannot appear in more than one aligned clause.
  10498. if (const Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
  10499. Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange;
  10500. Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
  10501. << getOpenMPClauseName(OMPC_aligned);
  10502. continue;
  10503. }
  10504. DeclRefExpr *Ref = nullptr;
  10505. if (!VD && isOpenMPCapturedDecl(D))
  10506. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
  10507. Vars.push_back(DefaultFunctionArrayConversion(
  10508. (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
  10509. .get());
  10510. }
  10511. // OpenMP [2.8.1, simd construct, Description]
  10512. // The parameter of the aligned clause, alignment, must be a constant
  10513. // positive integer expression.
  10514. // If no optional parameter is specified, implementation-defined default
  10515. // alignments for SIMD instructions on the target platforms are assumed.
  10516. if (Alignment != nullptr) {
  10517. ExprResult AlignResult =
  10518. VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
  10519. if (AlignResult.isInvalid())
  10520. return nullptr;
  10521. Alignment = AlignResult.get();
  10522. }
  10523. if (Vars.empty())
  10524. return nullptr;
  10525. return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
  10526. EndLoc, Vars, Alignment);
  10527. }
  10528. OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
  10529. SourceLocation StartLoc,
  10530. SourceLocation LParenLoc,
  10531. SourceLocation EndLoc) {
  10532. SmallVector<Expr *, 8> Vars;
  10533. SmallVector<Expr *, 8> SrcExprs;
  10534. SmallVector<Expr *, 8> DstExprs;
  10535. SmallVector<Expr *, 8> AssignmentOps;
  10536. for (Expr *RefExpr : VarList) {
  10537. assert(RefExpr && "NULL expr in OpenMP copyin clause.");
  10538. if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
  10539. // It will be analyzed later.
  10540. Vars.push_back(RefExpr);
  10541. SrcExprs.push_back(nullptr);
  10542. DstExprs.push_back(nullptr);
  10543. AssignmentOps.push_back(nullptr);
  10544. continue;
  10545. }
  10546. SourceLocation ELoc = RefExpr->getExprLoc();
  10547. // OpenMP [2.1, C/C++]
  10548. // A list item is a variable name.
  10549. // OpenMP [2.14.4.1, Restrictions, p.1]
  10550. // A list item that appears in a copyin clause must be threadprivate.
  10551. auto *DE = dyn_cast<DeclRefExpr>(RefExpr);
  10552. if (!DE || !isa<VarDecl>(DE->getDecl())) {
  10553. Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
  10554. << 0 << RefExpr->getSourceRange();
  10555. continue;
  10556. }
  10557. Decl *D = DE->getDecl();
  10558. auto *VD = cast<VarDecl>(D);
  10559. QualType Type = VD->getType();
  10560. if (Type->isDependentType() || Type->isInstantiationDependentType()) {
  10561. // It will be analyzed later.
  10562. Vars.push_back(DE);
  10563. SrcExprs.push_back(nullptr);
  10564. DstExprs.push_back(nullptr);
  10565. AssignmentOps.push_back(nullptr);
  10566. continue;
  10567. }
  10568. // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
  10569. // A list item that appears in a copyin clause must be threadprivate.
  10570. if (!DSAStack->isThreadPrivate(VD)) {
  10571. Diag(ELoc, diag::err_omp_required_access)
  10572. << getOpenMPClauseName(OMPC_copyin)
  10573. << getOpenMPDirectiveName(OMPD_threadprivate);
  10574. continue;
  10575. }
  10576. // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
  10577. // A variable of class type (or array thereof) that appears in a
  10578. // copyin clause requires an accessible, unambiguous copy assignment
  10579. // operator for the class type.
  10580. QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
  10581. VarDecl *SrcVD =
  10582. buildVarDecl(*this, DE->getLocStart(), ElemType.getUnqualifiedType(),
  10583. ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
  10584. DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(
  10585. *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
  10586. VarDecl *DstVD =
  10587. buildVarDecl(*this, DE->getLocStart(), ElemType, ".copyin.dst",
  10588. VD->hasAttrs() ? &VD->getAttrs() : nullptr);
  10589. DeclRefExpr *PseudoDstExpr =
  10590. buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
  10591. // For arrays generate assignment operation for single element and replace
  10592. // it by the original array element in CodeGen.
  10593. ExprResult AssignmentOp =
  10594. BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign, PseudoDstExpr,
  10595. PseudoSrcExpr);
  10596. if (AssignmentOp.isInvalid())
  10597. continue;
  10598. AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
  10599. /*DiscardedValue=*/true);
  10600. if (AssignmentOp.isInvalid())
  10601. continue;
  10602. DSAStack->addDSA(VD, DE, OMPC_copyin);
  10603. Vars.push_back(DE);
  10604. SrcExprs.push_back(PseudoSrcExpr);
  10605. DstExprs.push_back(PseudoDstExpr);
  10606. AssignmentOps.push_back(AssignmentOp.get());
  10607. }
  10608. if (Vars.empty())
  10609. return nullptr;
  10610. return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
  10611. SrcExprs, DstExprs, AssignmentOps);
  10612. }
  10613. OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
  10614. SourceLocation StartLoc,
  10615. SourceLocation LParenLoc,
  10616. SourceLocation EndLoc) {
  10617. SmallVector<Expr *, 8> Vars;
  10618. SmallVector<Expr *, 8> SrcExprs;
  10619. SmallVector<Expr *, 8> DstExprs;
  10620. SmallVector<Expr *, 8> AssignmentOps;
  10621. for (Expr *RefExpr : VarList) {
  10622. assert(RefExpr && "NULL expr in OpenMP linear clause.");
  10623. SourceLocation ELoc;
  10624. SourceRange ERange;
  10625. Expr *SimpleRefExpr = RefExpr;
  10626. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
  10627. /*AllowArraySection=*/false);
  10628. if (Res.second) {
  10629. // It will be analyzed later.
  10630. Vars.push_back(RefExpr);
  10631. SrcExprs.push_back(nullptr);
  10632. DstExprs.push_back(nullptr);
  10633. AssignmentOps.push_back(nullptr);
  10634. }
  10635. ValueDecl *D = Res.first;
  10636. if (!D)
  10637. continue;
  10638. QualType Type = D->getType();
  10639. auto *VD = dyn_cast<VarDecl>(D);
  10640. // OpenMP [2.14.4.2, Restrictions, p.2]
  10641. // A list item that appears in a copyprivate clause may not appear in a
  10642. // private or firstprivate clause on the single construct.
  10643. if (!VD || !DSAStack->isThreadPrivate(VD)) {
  10644. DSAStackTy::DSAVarData DVar =
  10645. DSAStack->getTopDSA(D, /*FromParent=*/false);
  10646. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
  10647. DVar.RefExpr) {
  10648. Diag(ELoc, diag::err_omp_wrong_dsa)
  10649. << getOpenMPClauseName(DVar.CKind)
  10650. << getOpenMPClauseName(OMPC_copyprivate);
  10651. reportOriginalDsa(*this, DSAStack, D, DVar);
  10652. continue;
  10653. }
  10654. // OpenMP [2.11.4.2, Restrictions, p.1]
  10655. // All list items that appear in a copyprivate clause must be either
  10656. // threadprivate or private in the enclosing context.
  10657. if (DVar.CKind == OMPC_unknown) {
  10658. DVar = DSAStack->getImplicitDSA(D, false);
  10659. if (DVar.CKind == OMPC_shared) {
  10660. Diag(ELoc, diag::err_omp_required_access)
  10661. << getOpenMPClauseName(OMPC_copyprivate)
  10662. << "threadprivate or private in the enclosing context";
  10663. reportOriginalDsa(*this, DSAStack, D, DVar);
  10664. continue;
  10665. }
  10666. }
  10667. }
  10668. // Variably modified types are not supported.
  10669. if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
  10670. Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
  10671. << getOpenMPClauseName(OMPC_copyprivate) << Type
  10672. << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
  10673. bool IsDecl =
  10674. !VD ||
  10675. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  10676. Diag(D->getLocation(),
  10677. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  10678. << D;
  10679. continue;
  10680. }
  10681. // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
  10682. // A variable of class type (or array thereof) that appears in a
  10683. // copyin clause requires an accessible, unambiguous copy assignment
  10684. // operator for the class type.
  10685. Type = Context.getBaseElementType(Type.getNonReferenceType())
  10686. .getUnqualifiedType();
  10687. VarDecl *SrcVD =
  10688. buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.src",
  10689. D->hasAttrs() ? &D->getAttrs() : nullptr);
  10690. DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
  10691. VarDecl *DstVD =
  10692. buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.dst",
  10693. D->hasAttrs() ? &D->getAttrs() : nullptr);
  10694. DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
  10695. ExprResult AssignmentOp = BuildBinOp(
  10696. DSAStack->getCurScope(), ELoc, BO_Assign, PseudoDstExpr, PseudoSrcExpr);
  10697. if (AssignmentOp.isInvalid())
  10698. continue;
  10699. AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
  10700. /*DiscardedValue=*/true);
  10701. if (AssignmentOp.isInvalid())
  10702. continue;
  10703. // No need to mark vars as copyprivate, they are already threadprivate or
  10704. // implicitly private.
  10705. assert(VD || isOpenMPCapturedDecl(D));
  10706. Vars.push_back(
  10707. VD ? RefExpr->IgnoreParens()
  10708. : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
  10709. SrcExprs.push_back(PseudoSrcExpr);
  10710. DstExprs.push_back(PseudoDstExpr);
  10711. AssignmentOps.push_back(AssignmentOp.get());
  10712. }
  10713. if (Vars.empty())
  10714. return nullptr;
  10715. return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  10716. Vars, SrcExprs, DstExprs, AssignmentOps);
  10717. }
  10718. OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
  10719. SourceLocation StartLoc,
  10720. SourceLocation LParenLoc,
  10721. SourceLocation EndLoc) {
  10722. if (VarList.empty())
  10723. return nullptr;
  10724. return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
  10725. }
  10726. OMPClause *
  10727. Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
  10728. SourceLocation DepLoc, SourceLocation ColonLoc,
  10729. ArrayRef<Expr *> VarList, SourceLocation StartLoc,
  10730. SourceLocation LParenLoc, SourceLocation EndLoc) {
  10731. if (DSAStack->getCurrentDirective() == OMPD_ordered &&
  10732. DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
  10733. Diag(DepLoc, diag::err_omp_unexpected_clause_value)
  10734. << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
  10735. return nullptr;
  10736. }
  10737. if (DSAStack->getCurrentDirective() != OMPD_ordered &&
  10738. (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
  10739. DepKind == OMPC_DEPEND_sink)) {
  10740. unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink};
  10741. Diag(DepLoc, diag::err_omp_unexpected_clause_value)
  10742. << getListOfPossibleValues(OMPC_depend, /*First=*/0,
  10743. /*Last=*/OMPC_DEPEND_unknown, Except)
  10744. << getOpenMPClauseName(OMPC_depend);
  10745. return nullptr;
  10746. }
  10747. SmallVector<Expr *, 8> Vars;
  10748. DSAStackTy::OperatorOffsetTy OpsOffs;
  10749. llvm::APSInt DepCounter(/*BitWidth=*/32);
  10750. llvm::APSInt TotalDepCount(/*BitWidth=*/32);
  10751. if (DepKind == OMPC_DEPEND_sink) {
  10752. if (const Expr *OrderedCountExpr = DSAStack->getParentOrderedRegionParam()) {
  10753. TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
  10754. TotalDepCount.setIsUnsigned(/*Val=*/true);
  10755. }
  10756. }
  10757. for (Expr *RefExpr : VarList) {
  10758. assert(RefExpr && "NULL expr in OpenMP shared clause.");
  10759. if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
  10760. // It will be analyzed later.
  10761. Vars.push_back(RefExpr);
  10762. continue;
  10763. }
  10764. SourceLocation ELoc = RefExpr->getExprLoc();
  10765. Expr *SimpleExpr = RefExpr->IgnoreParenCasts();
  10766. if (DepKind == OMPC_DEPEND_sink) {
  10767. if (DSAStack->getParentOrderedRegionParam() &&
  10768. DepCounter >= TotalDepCount) {
  10769. Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
  10770. continue;
  10771. }
  10772. ++DepCounter;
  10773. // OpenMP [2.13.9, Summary]
  10774. // depend(dependence-type : vec), where dependence-type is:
  10775. // 'sink' and where vec is the iteration vector, which has the form:
  10776. // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
  10777. // where n is the value specified by the ordered clause in the loop
  10778. // directive, xi denotes the loop iteration variable of the i-th nested
  10779. // loop associated with the loop directive, and di is a constant
  10780. // non-negative integer.
  10781. if (CurContext->isDependentContext()) {
  10782. // It will be analyzed later.
  10783. Vars.push_back(RefExpr);
  10784. continue;
  10785. }
  10786. SimpleExpr = SimpleExpr->IgnoreImplicit();
  10787. OverloadedOperatorKind OOK = OO_None;
  10788. SourceLocation OOLoc;
  10789. Expr *LHS = SimpleExpr;
  10790. Expr *RHS = nullptr;
  10791. if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
  10792. OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
  10793. OOLoc = BO->getOperatorLoc();
  10794. LHS = BO->getLHS()->IgnoreParenImpCasts();
  10795. RHS = BO->getRHS()->IgnoreParenImpCasts();
  10796. } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
  10797. OOK = OCE->getOperator();
  10798. OOLoc = OCE->getOperatorLoc();
  10799. LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
  10800. RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
  10801. } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
  10802. OOK = MCE->getMethodDecl()
  10803. ->getNameInfo()
  10804. .getName()
  10805. .getCXXOverloadedOperator();
  10806. OOLoc = MCE->getCallee()->getExprLoc();
  10807. LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
  10808. RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
  10809. }
  10810. SourceLocation ELoc;
  10811. SourceRange ERange;
  10812. auto Res = getPrivateItem(*this, LHS, ELoc, ERange,
  10813. /*AllowArraySection=*/false);
  10814. if (Res.second) {
  10815. // It will be analyzed later.
  10816. Vars.push_back(RefExpr);
  10817. }
  10818. ValueDecl *D = Res.first;
  10819. if (!D)
  10820. continue;
  10821. if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
  10822. Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
  10823. continue;
  10824. }
  10825. if (RHS) {
  10826. ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
  10827. RHS, OMPC_depend, /*StrictlyPositive=*/false);
  10828. if (RHSRes.isInvalid())
  10829. continue;
  10830. }
  10831. if (!CurContext->isDependentContext() &&
  10832. DSAStack->getParentOrderedRegionParam() &&
  10833. DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
  10834. const ValueDecl *VD =
  10835. DSAStack->getParentLoopControlVariable(DepCounter.getZExtValue());
  10836. if (VD)
  10837. Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
  10838. << 1 << VD;
  10839. else
  10840. Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) << 0;
  10841. continue;
  10842. }
  10843. OpsOffs.emplace_back(RHS, OOK);
  10844. } else {
  10845. auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
  10846. if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
  10847. (ASE &&
  10848. !ASE->getBase()->getType().getNonReferenceType()->isPointerType() &&
  10849. !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
  10850. Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
  10851. << RefExpr->getSourceRange();
  10852. continue;
  10853. }
  10854. bool Suppress = getDiagnostics().getSuppressAllDiagnostics();
  10855. getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
  10856. ExprResult Res =
  10857. CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RefExpr->IgnoreParenImpCasts());
  10858. getDiagnostics().setSuppressAllDiagnostics(Suppress);
  10859. if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr)) {
  10860. Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
  10861. << RefExpr->getSourceRange();
  10862. continue;
  10863. }
  10864. }
  10865. Vars.push_back(RefExpr->IgnoreParenImpCasts());
  10866. }
  10867. if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
  10868. TotalDepCount > VarList.size() &&
  10869. DSAStack->getParentOrderedRegionParam() &&
  10870. DSAStack->getParentLoopControlVariable(VarList.size() + 1)) {
  10871. Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration)
  10872. << 1 << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
  10873. }
  10874. if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
  10875. Vars.empty())
  10876. return nullptr;
  10877. auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  10878. DepKind, DepLoc, ColonLoc, Vars);
  10879. if ((DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) &&
  10880. DSAStack->isParentOrderedRegion())
  10881. DSAStack->addDoacrossDependClause(C, OpsOffs);
  10882. return C;
  10883. }
  10884. OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
  10885. SourceLocation LParenLoc,
  10886. SourceLocation EndLoc) {
  10887. Expr *ValExpr = Device;
  10888. Stmt *HelperValStmt = nullptr;
  10889. // OpenMP [2.9.1, Restrictions]
  10890. // The device expression must evaluate to a non-negative integer value.
  10891. if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
  10892. /*StrictlyPositive=*/false))
  10893. return nullptr;
  10894. OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
  10895. OpenMPDirectiveKind CaptureRegion =
  10896. getOpenMPCaptureRegionForClause(DKind, OMPC_device);
  10897. if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
  10898. ValExpr = MakeFullExpr(ValExpr).get();
  10899. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  10900. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  10901. HelperValStmt = buildPreInits(Context, Captures);
  10902. }
  10903. return new (Context) OMPDeviceClause(ValExpr, HelperValStmt, CaptureRegion,
  10904. StartLoc, LParenLoc, EndLoc);
  10905. }
  10906. static bool checkTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
  10907. DSAStackTy *Stack, QualType QTy,
  10908. bool FullCheck = true) {
  10909. NamedDecl *ND;
  10910. if (QTy->isIncompleteType(&ND)) {
  10911. SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
  10912. return false;
  10913. }
  10914. if (FullCheck && !SemaRef.CurContext->isDependentContext() &&
  10915. !QTy.isTrivialType(SemaRef.Context))
  10916. SemaRef.Diag(SL, diag::warn_omp_non_trivial_type_mapped) << QTy << SR;
  10917. return true;
  10918. }
  10919. /// \brief Return true if it can be proven that the provided array expression
  10920. /// (array section or array subscript) does NOT specify the whole size of the
  10921. /// array whose base type is \a BaseQTy.
  10922. static bool checkArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
  10923. const Expr *E,
  10924. QualType BaseQTy) {
  10925. const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
  10926. // If this is an array subscript, it refers to the whole size if the size of
  10927. // the dimension is constant and equals 1. Also, an array section assumes the
  10928. // format of an array subscript if no colon is used.
  10929. if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) {
  10930. if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
  10931. return ATy->getSize().getSExtValue() != 1;
  10932. // Size can't be evaluated statically.
  10933. return false;
  10934. }
  10935. assert(OASE && "Expecting array section if not an array subscript.");
  10936. const Expr *LowerBound = OASE->getLowerBound();
  10937. const Expr *Length = OASE->getLength();
  10938. // If there is a lower bound that does not evaluates to zero, we are not
  10939. // covering the whole dimension.
  10940. if (LowerBound) {
  10941. llvm::APSInt ConstLowerBound;
  10942. if (!LowerBound->EvaluateAsInt(ConstLowerBound, SemaRef.getASTContext()))
  10943. return false; // Can't get the integer value as a constant.
  10944. if (ConstLowerBound.getSExtValue())
  10945. return true;
  10946. }
  10947. // If we don't have a length we covering the whole dimension.
  10948. if (!Length)
  10949. return false;
  10950. // If the base is a pointer, we don't have a way to get the size of the
  10951. // pointee.
  10952. if (BaseQTy->isPointerType())
  10953. return false;
  10954. // We can only check if the length is the same as the size of the dimension
  10955. // if we have a constant array.
  10956. const auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
  10957. if (!CATy)
  10958. return false;
  10959. llvm::APSInt ConstLength;
  10960. if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
  10961. return false; // Can't get the integer value as a constant.
  10962. return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
  10963. }
  10964. // Return true if it can be proven that the provided array expression (array
  10965. // section or array subscript) does NOT specify a single element of the array
  10966. // whose base type is \a BaseQTy.
  10967. static bool checkArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
  10968. const Expr *E,
  10969. QualType BaseQTy) {
  10970. const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
  10971. // An array subscript always refer to a single element. Also, an array section
  10972. // assumes the format of an array subscript if no colon is used.
  10973. if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid()))
  10974. return false;
  10975. assert(OASE && "Expecting array section if not an array subscript.");
  10976. const Expr *Length = OASE->getLength();
  10977. // If we don't have a length we have to check if the array has unitary size
  10978. // for this dimension. Also, we should always expect a length if the base type
  10979. // is pointer.
  10980. if (!Length) {
  10981. if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
  10982. return ATy->getSize().getSExtValue() != 1;
  10983. // We cannot assume anything.
  10984. return false;
  10985. }
  10986. // Check if the length evaluates to 1.
  10987. llvm::APSInt ConstLength;
  10988. if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
  10989. return false; // Can't get the integer value as a constant.
  10990. return ConstLength.getSExtValue() != 1;
  10991. }
  10992. // Return the expression of the base of the mappable expression or null if it
  10993. // cannot be determined and do all the necessary checks to see if the expression
  10994. // is valid as a standalone mappable expression. In the process, record all the
  10995. // components of the expression.
  10996. static const Expr *checkMapClauseExpressionBase(
  10997. Sema &SemaRef, Expr *E,
  10998. OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
  10999. OpenMPClauseKind CKind, bool NoDiagnose) {
  11000. SourceLocation ELoc = E->getExprLoc();
  11001. SourceRange ERange = E->getSourceRange();
  11002. // The base of elements of list in a map clause have to be either:
  11003. // - a reference to variable or field.
  11004. // - a member expression.
  11005. // - an array expression.
  11006. //
  11007. // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
  11008. // reference to 'r'.
  11009. //
  11010. // If we have:
  11011. //
  11012. // struct SS {
  11013. // Bla S;
  11014. // foo() {
  11015. // #pragma omp target map (S.Arr[:12]);
  11016. // }
  11017. // }
  11018. //
  11019. // We want to retrieve the member expression 'this->S';
  11020. const Expr *RelevantExpr = nullptr;
  11021. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2]
  11022. // If a list item is an array section, it must specify contiguous storage.
  11023. //
  11024. // For this restriction it is sufficient that we make sure only references
  11025. // to variables or fields and array expressions, and that no array sections
  11026. // exist except in the rightmost expression (unless they cover the whole
  11027. // dimension of the array). E.g. these would be invalid:
  11028. //
  11029. // r.ArrS[3:5].Arr[6:7]
  11030. //
  11031. // r.ArrS[3:5].x
  11032. //
  11033. // but these would be valid:
  11034. // r.ArrS[3].Arr[6:7]
  11035. //
  11036. // r.ArrS[3].x
  11037. bool AllowUnitySizeArraySection = true;
  11038. bool AllowWholeSizeArraySection = true;
  11039. while (!RelevantExpr) {
  11040. E = E->IgnoreParenImpCasts();
  11041. if (auto *CurE = dyn_cast<DeclRefExpr>(E)) {
  11042. if (!isa<VarDecl>(CurE->getDecl()))
  11043. return nullptr;
  11044. RelevantExpr = CurE;
  11045. // If we got a reference to a declaration, we should not expect any array
  11046. // section before that.
  11047. AllowUnitySizeArraySection = false;
  11048. AllowWholeSizeArraySection = false;
  11049. // Record the component.
  11050. CurComponents.emplace_back(CurE, CurE->getDecl());
  11051. } else if (auto *CurE = dyn_cast<MemberExpr>(E)) {
  11052. Expr *BaseE = CurE->getBase()->IgnoreParenImpCasts();
  11053. if (isa<CXXThisExpr>(BaseE))
  11054. // We found a base expression: this->Val.
  11055. RelevantExpr = CurE;
  11056. else
  11057. E = BaseE;
  11058. if (!isa<FieldDecl>(CurE->getMemberDecl())) {
  11059. if (!NoDiagnose) {
  11060. SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
  11061. << CurE->getSourceRange();
  11062. return nullptr;
  11063. }
  11064. if (RelevantExpr)
  11065. return nullptr;
  11066. continue;
  11067. }
  11068. auto *FD = cast<FieldDecl>(CurE->getMemberDecl());
  11069. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
  11070. // A bit-field cannot appear in a map clause.
  11071. //
  11072. if (FD->isBitField()) {
  11073. if (!NoDiagnose) {
  11074. SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
  11075. << CurE->getSourceRange() << getOpenMPClauseName(CKind);
  11076. return nullptr;
  11077. }
  11078. if (RelevantExpr)
  11079. return nullptr;
  11080. continue;
  11081. }
  11082. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
  11083. // If the type of a list item is a reference to a type T then the type
  11084. // will be considered to be T for all purposes of this clause.
  11085. QualType CurType = BaseE->getType().getNonReferenceType();
  11086. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
  11087. // A list item cannot be a variable that is a member of a structure with
  11088. // a union type.
  11089. //
  11090. if (CurType->isUnionType()) {
  11091. if (!NoDiagnose) {
  11092. SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
  11093. << CurE->getSourceRange();
  11094. return nullptr;
  11095. }
  11096. continue;
  11097. }
  11098. // If we got a member expression, we should not expect any array section
  11099. // before that:
  11100. //
  11101. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
  11102. // If a list item is an element of a structure, only the rightmost symbol
  11103. // of the variable reference can be an array section.
  11104. //
  11105. AllowUnitySizeArraySection = false;
  11106. AllowWholeSizeArraySection = false;
  11107. // Record the component.
  11108. CurComponents.emplace_back(CurE, FD);
  11109. } else if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) {
  11110. E = CurE->getBase()->IgnoreParenImpCasts();
  11111. if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
  11112. if (!NoDiagnose) {
  11113. SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
  11114. << 0 << CurE->getSourceRange();
  11115. return nullptr;
  11116. }
  11117. continue;
  11118. }
  11119. // If we got an array subscript that express the whole dimension we
  11120. // can have any array expressions before. If it only expressing part of
  11121. // the dimension, we can only have unitary-size array expressions.
  11122. if (checkArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE,
  11123. E->getType()))
  11124. AllowWholeSizeArraySection = false;
  11125. // Record the component - we don't have any declaration associated.
  11126. CurComponents.emplace_back(CurE, nullptr);
  11127. } else if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) {
  11128. assert(!NoDiagnose && "Array sections cannot be implicitly mapped.");
  11129. E = CurE->getBase()->IgnoreParenImpCasts();
  11130. QualType CurType =
  11131. OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
  11132. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
  11133. // If the type of a list item is a reference to a type T then the type
  11134. // will be considered to be T for all purposes of this clause.
  11135. if (CurType->isReferenceType())
  11136. CurType = CurType->getPointeeType();
  11137. bool IsPointer = CurType->isAnyPointerType();
  11138. if (!IsPointer && !CurType->isArrayType()) {
  11139. SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
  11140. << 0 << CurE->getSourceRange();
  11141. return nullptr;
  11142. }
  11143. bool NotWhole =
  11144. checkArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType);
  11145. bool NotUnity =
  11146. checkArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType);
  11147. if (AllowWholeSizeArraySection) {
  11148. // Any array section is currently allowed. Allowing a whole size array
  11149. // section implies allowing a unity array section as well.
  11150. //
  11151. // If this array section refers to the whole dimension we can still
  11152. // accept other array sections before this one, except if the base is a
  11153. // pointer. Otherwise, only unitary sections are accepted.
  11154. if (NotWhole || IsPointer)
  11155. AllowWholeSizeArraySection = false;
  11156. } else if (AllowUnitySizeArraySection && NotUnity) {
  11157. // A unity or whole array section is not allowed and that is not
  11158. // compatible with the properties of the current array section.
  11159. SemaRef.Diag(
  11160. ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
  11161. << CurE->getSourceRange();
  11162. return nullptr;
  11163. }
  11164. // Record the component - we don't have any declaration associated.
  11165. CurComponents.emplace_back(CurE, nullptr);
  11166. } else {
  11167. if (!NoDiagnose) {
  11168. // If nothing else worked, this is not a valid map clause expression.
  11169. SemaRef.Diag(
  11170. ELoc, diag::err_omp_expected_named_var_member_or_array_expression)
  11171. << ERange;
  11172. }
  11173. return nullptr;
  11174. }
  11175. }
  11176. return RelevantExpr;
  11177. }
  11178. // Return true if expression E associated with value VD has conflicts with other
  11179. // map information.
  11180. static bool checkMapConflicts(
  11181. Sema &SemaRef, DSAStackTy *DSAS, const ValueDecl *VD, const Expr *E,
  11182. bool CurrentRegionOnly,
  11183. OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
  11184. OpenMPClauseKind CKind) {
  11185. assert(VD && E);
  11186. SourceLocation ELoc = E->getExprLoc();
  11187. SourceRange ERange = E->getSourceRange();
  11188. // In order to easily check the conflicts we need to match each component of
  11189. // the expression under test with the components of the expressions that are
  11190. // already in the stack.
  11191. assert(!CurComponents.empty() && "Map clause expression with no components!");
  11192. assert(CurComponents.back().getAssociatedDeclaration() == VD &&
  11193. "Map clause expression with unexpected base!");
  11194. // Variables to help detecting enclosing problems in data environment nests.
  11195. bool IsEnclosedByDataEnvironmentExpr = false;
  11196. const Expr *EnclosingExpr = nullptr;
  11197. bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
  11198. VD, CurrentRegionOnly,
  11199. [&IsEnclosedByDataEnvironmentExpr, &SemaRef, VD, CurrentRegionOnly, ELoc,
  11200. ERange, CKind, &EnclosingExpr,
  11201. CurComponents](OMPClauseMappableExprCommon::MappableExprComponentListRef
  11202. StackComponents,
  11203. OpenMPClauseKind) {
  11204. assert(!StackComponents.empty() &&
  11205. "Map clause expression with no components!");
  11206. assert(StackComponents.back().getAssociatedDeclaration() == VD &&
  11207. "Map clause expression with unexpected base!");
  11208. (void)VD;
  11209. // The whole expression in the stack.
  11210. const Expr *RE = StackComponents.front().getAssociatedExpression();
  11211. // Expressions must start from the same base. Here we detect at which
  11212. // point both expressions diverge from each other and see if we can
  11213. // detect if the memory referred to both expressions is contiguous and
  11214. // do not overlap.
  11215. auto CI = CurComponents.rbegin();
  11216. auto CE = CurComponents.rend();
  11217. auto SI = StackComponents.rbegin();
  11218. auto SE = StackComponents.rend();
  11219. for (; CI != CE && SI != SE; ++CI, ++SI) {
  11220. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
  11221. // At most one list item can be an array item derived from a given
  11222. // variable in map clauses of the same construct.
  11223. if (CurrentRegionOnly &&
  11224. (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
  11225. isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) &&
  11226. (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
  11227. isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) {
  11228. SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
  11229. diag::err_omp_multiple_array_items_in_map_clause)
  11230. << CI->getAssociatedExpression()->getSourceRange();
  11231. SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
  11232. diag::note_used_here)
  11233. << SI->getAssociatedExpression()->getSourceRange();
  11234. return true;
  11235. }
  11236. // Do both expressions have the same kind?
  11237. if (CI->getAssociatedExpression()->getStmtClass() !=
  11238. SI->getAssociatedExpression()->getStmtClass())
  11239. break;
  11240. // Are we dealing with different variables/fields?
  11241. if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
  11242. break;
  11243. }
  11244. // Check if the extra components of the expressions in the enclosing
  11245. // data environment are redundant for the current base declaration.
  11246. // If they are, the maps completely overlap, which is legal.
  11247. for (; SI != SE; ++SI) {
  11248. QualType Type;
  11249. if (const auto *ASE =
  11250. dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
  11251. Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
  11252. } else if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(
  11253. SI->getAssociatedExpression())) {
  11254. const Expr *E = OASE->getBase()->IgnoreParenImpCasts();
  11255. Type =
  11256. OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
  11257. }
  11258. if (Type.isNull() || Type->isAnyPointerType() ||
  11259. checkArrayExpressionDoesNotReferToWholeSize(
  11260. SemaRef, SI->getAssociatedExpression(), Type))
  11261. break;
  11262. }
  11263. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
  11264. // List items of map clauses in the same construct must not share
  11265. // original storage.
  11266. //
  11267. // If the expressions are exactly the same or one is a subset of the
  11268. // other, it means they are sharing storage.
  11269. if (CI == CE && SI == SE) {
  11270. if (CurrentRegionOnly) {
  11271. if (CKind == OMPC_map) {
  11272. SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
  11273. } else {
  11274. assert(CKind == OMPC_to || CKind == OMPC_from);
  11275. SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
  11276. << ERange;
  11277. }
  11278. SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
  11279. << RE->getSourceRange();
  11280. return true;
  11281. }
  11282. // If we find the same expression in the enclosing data environment,
  11283. // that is legal.
  11284. IsEnclosedByDataEnvironmentExpr = true;
  11285. return false;
  11286. }
  11287. QualType DerivedType =
  11288. std::prev(CI)->getAssociatedDeclaration()->getType();
  11289. SourceLocation DerivedLoc =
  11290. std::prev(CI)->getAssociatedExpression()->getExprLoc();
  11291. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
  11292. // If the type of a list item is a reference to a type T then the type
  11293. // will be considered to be T for all purposes of this clause.
  11294. DerivedType = DerivedType.getNonReferenceType();
  11295. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
  11296. // A variable for which the type is pointer and an array section
  11297. // derived from that variable must not appear as list items of map
  11298. // clauses of the same construct.
  11299. //
  11300. // Also, cover one of the cases in:
  11301. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
  11302. // If any part of the original storage of a list item has corresponding
  11303. // storage in the device data environment, all of the original storage
  11304. // must have corresponding storage in the device data environment.
  11305. //
  11306. if (DerivedType->isAnyPointerType()) {
  11307. if (CI == CE || SI == SE) {
  11308. SemaRef.Diag(
  11309. DerivedLoc,
  11310. diag::err_omp_pointer_mapped_along_with_derived_section)
  11311. << DerivedLoc;
  11312. SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
  11313. << RE->getSourceRange();
  11314. return true;
  11315. }
  11316. if (CI->getAssociatedExpression()->getStmtClass() !=
  11317. SI->getAssociatedExpression()->getStmtClass() ||
  11318. CI->getAssociatedDeclaration()->getCanonicalDecl() ==
  11319. SI->getAssociatedDeclaration()->getCanonicalDecl()) {
  11320. assert(CI != CE && SI != SE);
  11321. SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_dereferenced)
  11322. << DerivedLoc;
  11323. SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
  11324. << RE->getSourceRange();
  11325. return true;
  11326. }
  11327. }
  11328. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
  11329. // List items of map clauses in the same construct must not share
  11330. // original storage.
  11331. //
  11332. // An expression is a subset of the other.
  11333. if (CurrentRegionOnly && (CI == CE || SI == SE)) {
  11334. if (CKind == OMPC_map) {
  11335. SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
  11336. } else {
  11337. assert(CKind == OMPC_to || CKind == OMPC_from);
  11338. SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
  11339. << ERange;
  11340. }
  11341. SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
  11342. << RE->getSourceRange();
  11343. return true;
  11344. }
  11345. // The current expression uses the same base as other expression in the
  11346. // data environment but does not contain it completely.
  11347. if (!CurrentRegionOnly && SI != SE)
  11348. EnclosingExpr = RE;
  11349. // The current expression is a subset of the expression in the data
  11350. // environment.
  11351. IsEnclosedByDataEnvironmentExpr |=
  11352. (!CurrentRegionOnly && CI != CE && SI == SE);
  11353. return false;
  11354. });
  11355. if (CurrentRegionOnly)
  11356. return FoundError;
  11357. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
  11358. // If any part of the original storage of a list item has corresponding
  11359. // storage in the device data environment, all of the original storage must
  11360. // have corresponding storage in the device data environment.
  11361. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
  11362. // If a list item is an element of a structure, and a different element of
  11363. // the structure has a corresponding list item in the device data environment
  11364. // prior to a task encountering the construct associated with the map clause,
  11365. // then the list item must also have a corresponding list item in the device
  11366. // data environment prior to the task encountering the construct.
  11367. //
  11368. if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
  11369. SemaRef.Diag(ELoc,
  11370. diag::err_omp_original_storage_is_shared_and_does_not_contain)
  11371. << ERange;
  11372. SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
  11373. << EnclosingExpr->getSourceRange();
  11374. return true;
  11375. }
  11376. return FoundError;
  11377. }
  11378. namespace {
  11379. // Utility struct that gathers all the related lists associated with a mappable
  11380. // expression.
  11381. struct MappableVarListInfo {
  11382. // The list of expressions.
  11383. ArrayRef<Expr *> VarList;
  11384. // The list of processed expressions.
  11385. SmallVector<Expr *, 16> ProcessedVarList;
  11386. // The mappble components for each expression.
  11387. OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
  11388. // The base declaration of the variable.
  11389. SmallVector<ValueDecl *, 16> VarBaseDeclarations;
  11390. MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
  11391. // We have a list of components and base declarations for each entry in the
  11392. // variable list.
  11393. VarComponents.reserve(VarList.size());
  11394. VarBaseDeclarations.reserve(VarList.size());
  11395. }
  11396. };
  11397. }
  11398. // Check the validity of the provided variable list for the provided clause kind
  11399. // \a CKind. In the check process the valid expressions, and mappable expression
  11400. // components and variables are extracted and used to fill \a Vars,
  11401. // \a ClauseComponents, and \a ClauseBaseDeclarations. \a MapType and
  11402. // \a IsMapTypeImplicit are expected to be valid if the clause kind is 'map'.
  11403. static void
  11404. checkMappableExpressionList(Sema &SemaRef, DSAStackTy *DSAS,
  11405. OpenMPClauseKind CKind, MappableVarListInfo &MVLI,
  11406. SourceLocation StartLoc,
  11407. OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
  11408. bool IsMapTypeImplicit = false) {
  11409. // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
  11410. assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
  11411. "Unexpected clause kind with mappable expressions!");
  11412. // Keep track of the mappable components and base declarations in this clause.
  11413. // Each entry in the list is going to have a list of components associated. We
  11414. // record each set of the components so that we can build the clause later on.
  11415. // In the end we should have the same amount of declarations and component
  11416. // lists.
  11417. for (Expr *RE : MVLI.VarList) {
  11418. assert(RE && "Null expr in omp to/from/map clause");
  11419. SourceLocation ELoc = RE->getExprLoc();
  11420. const Expr *VE = RE->IgnoreParenLValueCasts();
  11421. if (VE->isValueDependent() || VE->isTypeDependent() ||
  11422. VE->isInstantiationDependent() ||
  11423. VE->containsUnexpandedParameterPack()) {
  11424. // We can only analyze this information once the missing information is
  11425. // resolved.
  11426. MVLI.ProcessedVarList.push_back(RE);
  11427. continue;
  11428. }
  11429. Expr *SimpleExpr = RE->IgnoreParenCasts();
  11430. if (!RE->IgnoreParenImpCasts()->isLValue()) {
  11431. SemaRef.Diag(ELoc,
  11432. diag::err_omp_expected_named_var_member_or_array_expression)
  11433. << RE->getSourceRange();
  11434. continue;
  11435. }
  11436. OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
  11437. ValueDecl *CurDeclaration = nullptr;
  11438. // Obtain the array or member expression bases if required. Also, fill the
  11439. // components array with all the components identified in the process.
  11440. const Expr *BE = checkMapClauseExpressionBase(
  11441. SemaRef, SimpleExpr, CurComponents, CKind, /*NoDiagnose=*/false);
  11442. if (!BE)
  11443. continue;
  11444. assert(!CurComponents.empty() &&
  11445. "Invalid mappable expression information.");
  11446. // For the following checks, we rely on the base declaration which is
  11447. // expected to be associated with the last component. The declaration is
  11448. // expected to be a variable or a field (if 'this' is being mapped).
  11449. CurDeclaration = CurComponents.back().getAssociatedDeclaration();
  11450. assert(CurDeclaration && "Null decl on map clause.");
  11451. assert(
  11452. CurDeclaration->isCanonicalDecl() &&
  11453. "Expecting components to have associated only canonical declarations.");
  11454. auto *VD = dyn_cast<VarDecl>(CurDeclaration);
  11455. const auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
  11456. assert((VD || FD) && "Only variables or fields are expected here!");
  11457. (void)FD;
  11458. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
  11459. // threadprivate variables cannot appear in a map clause.
  11460. // OpenMP 4.5 [2.10.5, target update Construct]
  11461. // threadprivate variables cannot appear in a from clause.
  11462. if (VD && DSAS->isThreadPrivate(VD)) {
  11463. DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
  11464. SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
  11465. << getOpenMPClauseName(CKind);
  11466. reportOriginalDsa(SemaRef, DSAS, VD, DVar);
  11467. continue;
  11468. }
  11469. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
  11470. // A list item cannot appear in both a map clause and a data-sharing
  11471. // attribute clause on the same construct.
  11472. // Check conflicts with other map clause expressions. We check the conflicts
  11473. // with the current construct separately from the enclosing data
  11474. // environment, because the restrictions are different. We only have to
  11475. // check conflicts across regions for the map clauses.
  11476. if (checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
  11477. /*CurrentRegionOnly=*/true, CurComponents, CKind))
  11478. break;
  11479. if (CKind == OMPC_map &&
  11480. checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
  11481. /*CurrentRegionOnly=*/false, CurComponents, CKind))
  11482. break;
  11483. // OpenMP 4.5 [2.10.5, target update Construct]
  11484. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
  11485. // If the type of a list item is a reference to a type T then the type will
  11486. // be considered to be T for all purposes of this clause.
  11487. QualType Type = CurDeclaration->getType().getNonReferenceType();
  11488. // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
  11489. // A list item in a to or from clause must have a mappable type.
  11490. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
  11491. // A list item must have a mappable type.
  11492. if (!checkTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
  11493. DSAS, Type))
  11494. continue;
  11495. if (CKind == OMPC_map) {
  11496. // target enter data
  11497. // OpenMP [2.10.2, Restrictions, p. 99]
  11498. // A map-type must be specified in all map clauses and must be either
  11499. // to or alloc.
  11500. OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
  11501. if (DKind == OMPD_target_enter_data &&
  11502. !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
  11503. SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
  11504. << (IsMapTypeImplicit ? 1 : 0)
  11505. << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
  11506. << getOpenMPDirectiveName(DKind);
  11507. continue;
  11508. }
  11509. // target exit_data
  11510. // OpenMP [2.10.3, Restrictions, p. 102]
  11511. // A map-type must be specified in all map clauses and must be either
  11512. // from, release, or delete.
  11513. if (DKind == OMPD_target_exit_data &&
  11514. !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
  11515. MapType == OMPC_MAP_delete)) {
  11516. SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
  11517. << (IsMapTypeImplicit ? 1 : 0)
  11518. << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
  11519. << getOpenMPDirectiveName(DKind);
  11520. continue;
  11521. }
  11522. // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
  11523. // A list item cannot appear in both a map clause and a data-sharing
  11524. // attribute clause on the same construct
  11525. if (VD && isOpenMPTargetExecutionDirective(DKind)) {
  11526. DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
  11527. if (isOpenMPPrivate(DVar.CKind)) {
  11528. SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
  11529. << getOpenMPClauseName(DVar.CKind)
  11530. << getOpenMPClauseName(OMPC_map)
  11531. << getOpenMPDirectiveName(DSAS->getCurrentDirective());
  11532. reportOriginalDsa(SemaRef, DSAS, CurDeclaration, DVar);
  11533. continue;
  11534. }
  11535. }
  11536. }
  11537. // Save the current expression.
  11538. MVLI.ProcessedVarList.push_back(RE);
  11539. // Store the components in the stack so that they can be used to check
  11540. // against other clauses later on.
  11541. DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
  11542. /*WhereFoundClauseKind=*/OMPC_map);
  11543. // Save the components and declaration to create the clause. For purposes of
  11544. // the clause creation, any component list that has has base 'this' uses
  11545. // null as base declaration.
  11546. MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
  11547. MVLI.VarComponents.back().append(CurComponents.begin(),
  11548. CurComponents.end());
  11549. MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
  11550. : CurDeclaration);
  11551. }
  11552. }
  11553. OMPClause *
  11554. Sema::ActOnOpenMPMapClause(OpenMPMapClauseKind MapTypeModifier,
  11555. OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
  11556. SourceLocation MapLoc, SourceLocation ColonLoc,
  11557. ArrayRef<Expr *> VarList, SourceLocation StartLoc,
  11558. SourceLocation LParenLoc, SourceLocation EndLoc) {
  11559. MappableVarListInfo MVLI(VarList);
  11560. checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, StartLoc,
  11561. MapType, IsMapTypeImplicit);
  11562. // We need to produce a map clause even if we don't have variables so that
  11563. // other diagnostics related with non-existing map clauses are accurate.
  11564. return OMPMapClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  11565. MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
  11566. MVLI.VarComponents, MapTypeModifier, MapType,
  11567. IsMapTypeImplicit, MapLoc);
  11568. }
  11569. QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
  11570. TypeResult ParsedType) {
  11571. assert(ParsedType.isUsable());
  11572. QualType ReductionType = GetTypeFromParser(ParsedType.get());
  11573. if (ReductionType.isNull())
  11574. return QualType();
  11575. // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
  11576. // A type name in a declare reduction directive cannot be a function type, an
  11577. // array type, a reference type, or a type qualified with const, volatile or
  11578. // restrict.
  11579. if (ReductionType.hasQualifiers()) {
  11580. Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
  11581. return QualType();
  11582. }
  11583. if (ReductionType->isFunctionType()) {
  11584. Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
  11585. return QualType();
  11586. }
  11587. if (ReductionType->isReferenceType()) {
  11588. Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
  11589. return QualType();
  11590. }
  11591. if (ReductionType->isArrayType()) {
  11592. Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
  11593. return QualType();
  11594. }
  11595. return ReductionType;
  11596. }
  11597. Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
  11598. Scope *S, DeclContext *DC, DeclarationName Name,
  11599. ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
  11600. AccessSpecifier AS, Decl *PrevDeclInScope) {
  11601. SmallVector<Decl *, 8> Decls;
  11602. Decls.reserve(ReductionTypes.size());
  11603. LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
  11604. forRedeclarationInCurContext());
  11605. // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
  11606. // A reduction-identifier may not be re-declared in the current scope for the
  11607. // same type or for a type that is compatible according to the base language
  11608. // rules.
  11609. llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
  11610. OMPDeclareReductionDecl *PrevDRD = nullptr;
  11611. bool InCompoundScope = true;
  11612. if (S != nullptr) {
  11613. // Find previous declaration with the same name not referenced in other
  11614. // declarations.
  11615. FunctionScopeInfo *ParentFn = getEnclosingFunction();
  11616. InCompoundScope =
  11617. (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
  11618. LookupName(Lookup, S);
  11619. FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
  11620. /*AllowInlineNamespace=*/false);
  11621. llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
  11622. LookupResult::Filter Filter = Lookup.makeFilter();
  11623. while (Filter.hasNext()) {
  11624. auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
  11625. if (InCompoundScope) {
  11626. auto I = UsedAsPrevious.find(PrevDecl);
  11627. if (I == UsedAsPrevious.end())
  11628. UsedAsPrevious[PrevDecl] = false;
  11629. if (OMPDeclareReductionDecl *D = PrevDecl->getPrevDeclInScope())
  11630. UsedAsPrevious[D] = true;
  11631. }
  11632. PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
  11633. PrevDecl->getLocation();
  11634. }
  11635. Filter.done();
  11636. if (InCompoundScope) {
  11637. for (const auto &PrevData : UsedAsPrevious) {
  11638. if (!PrevData.second) {
  11639. PrevDRD = PrevData.first;
  11640. break;
  11641. }
  11642. }
  11643. }
  11644. } else if (PrevDeclInScope != nullptr) {
  11645. auto *PrevDRDInScope = PrevDRD =
  11646. cast<OMPDeclareReductionDecl>(PrevDeclInScope);
  11647. do {
  11648. PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
  11649. PrevDRDInScope->getLocation();
  11650. PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
  11651. } while (PrevDRDInScope != nullptr);
  11652. }
  11653. for (const auto &TyData : ReductionTypes) {
  11654. const auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
  11655. bool Invalid = false;
  11656. if (I != PreviousRedeclTypes.end()) {
  11657. Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
  11658. << TyData.first;
  11659. Diag(I->second, diag::note_previous_definition);
  11660. Invalid = true;
  11661. }
  11662. PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
  11663. auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
  11664. Name, TyData.first, PrevDRD);
  11665. DC->addDecl(DRD);
  11666. DRD->setAccess(AS);
  11667. Decls.push_back(DRD);
  11668. if (Invalid)
  11669. DRD->setInvalidDecl();
  11670. else
  11671. PrevDRD = DRD;
  11672. }
  11673. return DeclGroupPtrTy::make(
  11674. DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
  11675. }
  11676. void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
  11677. auto *DRD = cast<OMPDeclareReductionDecl>(D);
  11678. // Enter new function scope.
  11679. PushFunctionScope();
  11680. setFunctionHasBranchProtectedScope();
  11681. getCurFunction()->setHasOMPDeclareReductionCombiner();
  11682. if (S != nullptr)
  11683. PushDeclContext(S, DRD);
  11684. else
  11685. CurContext = DRD;
  11686. PushExpressionEvaluationContext(
  11687. ExpressionEvaluationContext::PotentiallyEvaluated);
  11688. QualType ReductionType = DRD->getType();
  11689. // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
  11690. // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
  11691. // uses semantics of argument handles by value, but it should be passed by
  11692. // reference. C lang does not support references, so pass all parameters as
  11693. // pointers.
  11694. // Create 'T omp_in;' variable.
  11695. VarDecl *OmpInParm =
  11696. buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
  11697. // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
  11698. // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
  11699. // uses semantics of argument handles by value, but it should be passed by
  11700. // reference. C lang does not support references, so pass all parameters as
  11701. // pointers.
  11702. // Create 'T omp_out;' variable.
  11703. VarDecl *OmpOutParm =
  11704. buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
  11705. if (S != nullptr) {
  11706. PushOnScopeChains(OmpInParm, S);
  11707. PushOnScopeChains(OmpOutParm, S);
  11708. } else {
  11709. DRD->addDecl(OmpInParm);
  11710. DRD->addDecl(OmpOutParm);
  11711. }
  11712. }
  11713. void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
  11714. auto *DRD = cast<OMPDeclareReductionDecl>(D);
  11715. DiscardCleanupsInEvaluationContext();
  11716. PopExpressionEvaluationContext();
  11717. PopDeclContext();
  11718. PopFunctionScopeInfo();
  11719. if (Combiner != nullptr)
  11720. DRD->setCombiner(Combiner);
  11721. else
  11722. DRD->setInvalidDecl();
  11723. }
  11724. VarDecl *Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
  11725. auto *DRD = cast<OMPDeclareReductionDecl>(D);
  11726. // Enter new function scope.
  11727. PushFunctionScope();
  11728. setFunctionHasBranchProtectedScope();
  11729. if (S != nullptr)
  11730. PushDeclContext(S, DRD);
  11731. else
  11732. CurContext = DRD;
  11733. PushExpressionEvaluationContext(
  11734. ExpressionEvaluationContext::PotentiallyEvaluated);
  11735. QualType ReductionType = DRD->getType();
  11736. // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
  11737. // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
  11738. // uses semantics of argument handles by value, but it should be passed by
  11739. // reference. C lang does not support references, so pass all parameters as
  11740. // pointers.
  11741. // Create 'T omp_priv;' variable.
  11742. VarDecl *OmpPrivParm =
  11743. buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
  11744. // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
  11745. // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
  11746. // uses semantics of argument handles by value, but it should be passed by
  11747. // reference. C lang does not support references, so pass all parameters as
  11748. // pointers.
  11749. // Create 'T omp_orig;' variable.
  11750. VarDecl *OmpOrigParm =
  11751. buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
  11752. if (S != nullptr) {
  11753. PushOnScopeChains(OmpPrivParm, S);
  11754. PushOnScopeChains(OmpOrigParm, S);
  11755. } else {
  11756. DRD->addDecl(OmpPrivParm);
  11757. DRD->addDecl(OmpOrigParm);
  11758. }
  11759. return OmpPrivParm;
  11760. }
  11761. void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
  11762. VarDecl *OmpPrivParm) {
  11763. auto *DRD = cast<OMPDeclareReductionDecl>(D);
  11764. DiscardCleanupsInEvaluationContext();
  11765. PopExpressionEvaluationContext();
  11766. PopDeclContext();
  11767. PopFunctionScopeInfo();
  11768. if (Initializer != nullptr) {
  11769. DRD->setInitializer(Initializer, OMPDeclareReductionDecl::CallInit);
  11770. } else if (OmpPrivParm->hasInit()) {
  11771. DRD->setInitializer(OmpPrivParm->getInit(),
  11772. OmpPrivParm->isDirectInit()
  11773. ? OMPDeclareReductionDecl::DirectInit
  11774. : OMPDeclareReductionDecl::CopyInit);
  11775. } else {
  11776. DRD->setInvalidDecl();
  11777. }
  11778. }
  11779. Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
  11780. Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
  11781. for (Decl *D : DeclReductions.get()) {
  11782. if (IsValid) {
  11783. if (S)
  11784. PushOnScopeChains(cast<OMPDeclareReductionDecl>(D), S,
  11785. /*AddToContext=*/false);
  11786. } else {
  11787. D->setInvalidDecl();
  11788. }
  11789. }
  11790. return DeclReductions;
  11791. }
  11792. OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
  11793. SourceLocation StartLoc,
  11794. SourceLocation LParenLoc,
  11795. SourceLocation EndLoc) {
  11796. Expr *ValExpr = NumTeams;
  11797. Stmt *HelperValStmt = nullptr;
  11798. // OpenMP [teams Constrcut, Restrictions]
  11799. // The num_teams expression must evaluate to a positive integer value.
  11800. if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
  11801. /*StrictlyPositive=*/true))
  11802. return nullptr;
  11803. OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
  11804. OpenMPDirectiveKind CaptureRegion =
  11805. getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams);
  11806. if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
  11807. ValExpr = MakeFullExpr(ValExpr).get();
  11808. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  11809. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  11810. HelperValStmt = buildPreInits(Context, Captures);
  11811. }
  11812. return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion,
  11813. StartLoc, LParenLoc, EndLoc);
  11814. }
  11815. OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
  11816. SourceLocation StartLoc,
  11817. SourceLocation LParenLoc,
  11818. SourceLocation EndLoc) {
  11819. Expr *ValExpr = ThreadLimit;
  11820. Stmt *HelperValStmt = nullptr;
  11821. // OpenMP [teams Constrcut, Restrictions]
  11822. // The thread_limit expression must evaluate to a positive integer value.
  11823. if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
  11824. /*StrictlyPositive=*/true))
  11825. return nullptr;
  11826. OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
  11827. OpenMPDirectiveKind CaptureRegion =
  11828. getOpenMPCaptureRegionForClause(DKind, OMPC_thread_limit);
  11829. if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
  11830. ValExpr = MakeFullExpr(ValExpr).get();
  11831. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  11832. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  11833. HelperValStmt = buildPreInits(Context, Captures);
  11834. }
  11835. return new (Context) OMPThreadLimitClause(
  11836. ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
  11837. }
  11838. OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
  11839. SourceLocation StartLoc,
  11840. SourceLocation LParenLoc,
  11841. SourceLocation EndLoc) {
  11842. Expr *ValExpr = Priority;
  11843. // OpenMP [2.9.1, task Constrcut]
  11844. // The priority-value is a non-negative numerical scalar expression.
  11845. if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_priority,
  11846. /*StrictlyPositive=*/false))
  11847. return nullptr;
  11848. return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc);
  11849. }
  11850. OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
  11851. SourceLocation StartLoc,
  11852. SourceLocation LParenLoc,
  11853. SourceLocation EndLoc) {
  11854. Expr *ValExpr = Grainsize;
  11855. // OpenMP [2.9.2, taskloop Constrcut]
  11856. // The parameter of the grainsize clause must be a positive integer
  11857. // expression.
  11858. if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize,
  11859. /*StrictlyPositive=*/true))
  11860. return nullptr;
  11861. return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc);
  11862. }
  11863. OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
  11864. SourceLocation StartLoc,
  11865. SourceLocation LParenLoc,
  11866. SourceLocation EndLoc) {
  11867. Expr *ValExpr = NumTasks;
  11868. // OpenMP [2.9.2, taskloop Constrcut]
  11869. // The parameter of the num_tasks clause must be a positive integer
  11870. // expression.
  11871. if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks,
  11872. /*StrictlyPositive=*/true))
  11873. return nullptr;
  11874. return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc);
  11875. }
  11876. OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
  11877. SourceLocation LParenLoc,
  11878. SourceLocation EndLoc) {
  11879. // OpenMP [2.13.2, critical construct, Description]
  11880. // ... where hint-expression is an integer constant expression that evaluates
  11881. // to a valid lock hint.
  11882. ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
  11883. if (HintExpr.isInvalid())
  11884. return nullptr;
  11885. return new (Context)
  11886. OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
  11887. }
  11888. OMPClause *Sema::ActOnOpenMPDistScheduleClause(
  11889. OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
  11890. SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
  11891. SourceLocation EndLoc) {
  11892. if (Kind == OMPC_DIST_SCHEDULE_unknown) {
  11893. std::string Values;
  11894. Values += "'";
  11895. Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
  11896. Values += "'";
  11897. Diag(KindLoc, diag::err_omp_unexpected_clause_value)
  11898. << Values << getOpenMPClauseName(OMPC_dist_schedule);
  11899. return nullptr;
  11900. }
  11901. Expr *ValExpr = ChunkSize;
  11902. Stmt *HelperValStmt = nullptr;
  11903. if (ChunkSize) {
  11904. if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
  11905. !ChunkSize->isInstantiationDependent() &&
  11906. !ChunkSize->containsUnexpandedParameterPack()) {
  11907. SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
  11908. ExprResult Val =
  11909. PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
  11910. if (Val.isInvalid())
  11911. return nullptr;
  11912. ValExpr = Val.get();
  11913. // OpenMP [2.7.1, Restrictions]
  11914. // chunk_size must be a loop invariant integer expression with a positive
  11915. // value.
  11916. llvm::APSInt Result;
  11917. if (ValExpr->isIntegerConstantExpr(Result, Context)) {
  11918. if (Result.isSigned() && !Result.isStrictlyPositive()) {
  11919. Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
  11920. << "dist_schedule" << ChunkSize->getSourceRange();
  11921. return nullptr;
  11922. }
  11923. } else if (getOpenMPCaptureRegionForClause(
  11924. DSAStack->getCurrentDirective(), OMPC_dist_schedule) !=
  11925. OMPD_unknown &&
  11926. !CurContext->isDependentContext()) {
  11927. ValExpr = MakeFullExpr(ValExpr).get();
  11928. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  11929. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  11930. HelperValStmt = buildPreInits(Context, Captures);
  11931. }
  11932. }
  11933. }
  11934. return new (Context)
  11935. OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
  11936. Kind, ValExpr, HelperValStmt);
  11937. }
  11938. OMPClause *Sema::ActOnOpenMPDefaultmapClause(
  11939. OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
  11940. SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
  11941. SourceLocation KindLoc, SourceLocation EndLoc) {
  11942. // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)'
  11943. if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || Kind != OMPC_DEFAULTMAP_scalar) {
  11944. std::string Value;
  11945. SourceLocation Loc;
  11946. Value += "'";
  11947. if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
  11948. Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
  11949. OMPC_DEFAULTMAP_MODIFIER_tofrom);
  11950. Loc = MLoc;
  11951. } else {
  11952. Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
  11953. OMPC_DEFAULTMAP_scalar);
  11954. Loc = KindLoc;
  11955. }
  11956. Value += "'";
  11957. Diag(Loc, diag::err_omp_unexpected_clause_value)
  11958. << Value << getOpenMPClauseName(OMPC_defaultmap);
  11959. return nullptr;
  11960. }
  11961. DSAStack->setDefaultDMAToFromScalar(StartLoc);
  11962. return new (Context)
  11963. OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
  11964. }
  11965. bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) {
  11966. DeclContext *CurLexicalContext = getCurLexicalContext();
  11967. if (!CurLexicalContext->isFileContext() &&
  11968. !CurLexicalContext->isExternCContext() &&
  11969. !CurLexicalContext->isExternCXXContext() &&
  11970. !isa<CXXRecordDecl>(CurLexicalContext) &&
  11971. !isa<ClassTemplateDecl>(CurLexicalContext) &&
  11972. !isa<ClassTemplatePartialSpecializationDecl>(CurLexicalContext) &&
  11973. !isa<ClassTemplateSpecializationDecl>(CurLexicalContext)) {
  11974. Diag(Loc, diag::err_omp_region_not_file_context);
  11975. return false;
  11976. }
  11977. if (IsInOpenMPDeclareTargetContext) {
  11978. Diag(Loc, diag::err_omp_enclosed_declare_target);
  11979. return false;
  11980. }
  11981. IsInOpenMPDeclareTargetContext = true;
  11982. return true;
  11983. }
  11984. void Sema::ActOnFinishOpenMPDeclareTargetDirective() {
  11985. assert(IsInOpenMPDeclareTargetContext &&
  11986. "Unexpected ActOnFinishOpenMPDeclareTargetDirective");
  11987. IsInOpenMPDeclareTargetContext = false;
  11988. }
  11989. void Sema::ActOnOpenMPDeclareTargetName(Scope *CurScope,
  11990. CXXScopeSpec &ScopeSpec,
  11991. const DeclarationNameInfo &Id,
  11992. OMPDeclareTargetDeclAttr::MapTypeTy MT,
  11993. NamedDeclSetType &SameDirectiveDecls) {
  11994. LookupResult Lookup(*this, Id, LookupOrdinaryName);
  11995. LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
  11996. if (Lookup.isAmbiguous())
  11997. return;
  11998. Lookup.suppressDiagnostics();
  11999. if (!Lookup.isSingleResult()) {
  12000. if (TypoCorrection Corrected =
  12001. CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr,
  12002. llvm::make_unique<VarOrFuncDeclFilterCCC>(*this),
  12003. CTK_ErrorRecovery)) {
  12004. diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
  12005. << Id.getName());
  12006. checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
  12007. return;
  12008. }
  12009. Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
  12010. return;
  12011. }
  12012. NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
  12013. if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) {
  12014. if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl())))
  12015. Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName();
  12016. if (!ND->hasAttr<OMPDeclareTargetDeclAttr>()) {
  12017. auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT);
  12018. ND->addAttr(A);
  12019. if (ASTMutationListener *ML = Context.getASTMutationListener())
  12020. ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
  12021. checkDeclIsAllowedInOpenMPTarget(nullptr, ND, Id.getLoc());
  12022. } else if (ND->getAttr<OMPDeclareTargetDeclAttr>()->getMapType() != MT) {
  12023. Diag(Id.getLoc(), diag::err_omp_declare_target_to_and_link)
  12024. << Id.getName();
  12025. }
  12026. } else {
  12027. Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
  12028. }
  12029. }
  12030. static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
  12031. Sema &SemaRef, Decl *D) {
  12032. if (!D)
  12033. return;
  12034. const Decl *LD = nullptr;
  12035. if (isa<TagDecl>(D)) {
  12036. LD = cast<TagDecl>(D)->getDefinition();
  12037. } else if (isa<VarDecl>(D)) {
  12038. LD = cast<VarDecl>(D)->getDefinition();
  12039. // If this is an implicit variable that is legal and we do not need to do
  12040. // anything.
  12041. if (cast<VarDecl>(D)->isImplicit()) {
  12042. auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(
  12043. SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
  12044. D->addAttr(A);
  12045. if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
  12046. ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
  12047. return;
  12048. }
  12049. } else if (const auto *F = dyn_cast<FunctionDecl>(D)) {
  12050. const FunctionDecl *FD = nullptr;
  12051. if (cast<FunctionDecl>(D)->hasBody(FD)) {
  12052. LD = FD;
  12053. // If the definition is associated with the current declaration in the
  12054. // target region (it can be e.g. a lambda) that is legal and we do not
  12055. // need to do anything else.
  12056. if (LD == D) {
  12057. auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(
  12058. SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
  12059. D->addAttr(A);
  12060. if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
  12061. ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
  12062. return;
  12063. }
  12064. } else if (F->isFunctionTemplateSpecialization() &&
  12065. F->getTemplateSpecializationKind() ==
  12066. TSK_ImplicitInstantiation) {
  12067. // Check if the function is implicitly instantiated from the template
  12068. // defined in the declare target region.
  12069. const FunctionTemplateDecl *FTD = F->getPrimaryTemplate();
  12070. if (FTD && FTD->hasAttr<OMPDeclareTargetDeclAttr>())
  12071. return;
  12072. }
  12073. }
  12074. if (!LD)
  12075. LD = D;
  12076. if (LD && !LD->hasAttr<OMPDeclareTargetDeclAttr>() &&
  12077. (isa<VarDecl>(LD) || isa<FunctionDecl>(LD))) {
  12078. // Outlined declaration is not declared target.
  12079. if (LD->isOutOfLine()) {
  12080. SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
  12081. SemaRef.Diag(SL, diag::note_used_here) << SR;
  12082. } else {
  12083. const DeclContext *DC = LD->getDeclContext();
  12084. while (DC &&
  12085. (!isa<FunctionDecl>(DC) ||
  12086. !cast<FunctionDecl>(DC)->hasAttr<OMPDeclareTargetDeclAttr>()))
  12087. DC = DC->getParent();
  12088. if (DC)
  12089. return;
  12090. // Is not declared in target context.
  12091. SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
  12092. SemaRef.Diag(SL, diag::note_used_here) << SR;
  12093. }
  12094. // Mark decl as declared target to prevent further diagnostic.
  12095. auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(
  12096. SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
  12097. D->addAttr(A);
  12098. if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
  12099. ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
  12100. }
  12101. }
  12102. static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
  12103. Sema &SemaRef, DSAStackTy *Stack,
  12104. ValueDecl *VD) {
  12105. return VD->hasAttr<OMPDeclareTargetDeclAttr>() ||
  12106. checkTypeMappable(SL, SR, SemaRef, Stack, VD->getType(),
  12107. /*FullCheck=*/false);
  12108. }
  12109. void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D,
  12110. SourceLocation IdLoc) {
  12111. if (!D || D->isInvalidDecl())
  12112. return;
  12113. SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
  12114. SourceLocation SL = E ? E->getLocStart() : D->getLocation();
  12115. // 2.10.6: threadprivate variable cannot appear in a declare target directive.
  12116. if (auto *VD = dyn_cast<VarDecl>(D)) {
  12117. if (DSAStack->isThreadPrivate(VD)) {
  12118. Diag(SL, diag::err_omp_threadprivate_in_target);
  12119. reportOriginalDsa(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
  12120. return;
  12121. }
  12122. }
  12123. if (auto *VD = dyn_cast<ValueDecl>(D)) {
  12124. // Problem if any with var declared with incomplete type will be reported
  12125. // as normal, so no need to check it here.
  12126. if ((E || !VD->getType()->isIncompleteType()) &&
  12127. !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD)) {
  12128. // Mark decl as declared target to prevent further diagnostic.
  12129. if (isa<VarDecl>(VD) || isa<FunctionDecl>(VD) ||
  12130. isa<FunctionTemplateDecl>(VD)) {
  12131. auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(
  12132. Context, OMPDeclareTargetDeclAttr::MT_To);
  12133. VD->addAttr(A);
  12134. if (ASTMutationListener *ML = Context.getASTMutationListener())
  12135. ML->DeclarationMarkedOpenMPDeclareTarget(VD, A);
  12136. }
  12137. return;
  12138. }
  12139. }
  12140. if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
  12141. if (FD->hasAttr<OMPDeclareTargetDeclAttr>() &&
  12142. (FD->getAttr<OMPDeclareTargetDeclAttr>()->getMapType() ==
  12143. OMPDeclareTargetDeclAttr::MT_Link)) {
  12144. assert(IdLoc.isValid() && "Source location is expected");
  12145. Diag(IdLoc, diag::err_omp_function_in_link_clause);
  12146. Diag(FD->getLocation(), diag::note_defined_here) << FD;
  12147. return;
  12148. }
  12149. }
  12150. if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(D)) {
  12151. if (FTD->hasAttr<OMPDeclareTargetDeclAttr>() &&
  12152. (FTD->getAttr<OMPDeclareTargetDeclAttr>()->getMapType() ==
  12153. OMPDeclareTargetDeclAttr::MT_Link)) {
  12154. assert(IdLoc.isValid() && "Source location is expected");
  12155. Diag(IdLoc, diag::err_omp_function_in_link_clause);
  12156. Diag(FTD->getLocation(), diag::note_defined_here) << FTD;
  12157. return;
  12158. }
  12159. }
  12160. if (!E) {
  12161. // Checking declaration inside declare target region.
  12162. if (!D->hasAttr<OMPDeclareTargetDeclAttr>() &&
  12163. (isa<VarDecl>(D) || isa<FunctionDecl>(D) ||
  12164. isa<FunctionTemplateDecl>(D))) {
  12165. auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(
  12166. Context, OMPDeclareTargetDeclAttr::MT_To);
  12167. D->addAttr(A);
  12168. if (ASTMutationListener *ML = Context.getASTMutationListener())
  12169. ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
  12170. }
  12171. return;
  12172. }
  12173. checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
  12174. }
  12175. OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
  12176. SourceLocation StartLoc,
  12177. SourceLocation LParenLoc,
  12178. SourceLocation EndLoc) {
  12179. MappableVarListInfo MVLI(VarList);
  12180. checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, StartLoc);
  12181. if (MVLI.ProcessedVarList.empty())
  12182. return nullptr;
  12183. return OMPToClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  12184. MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
  12185. MVLI.VarComponents);
  12186. }
  12187. OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
  12188. SourceLocation StartLoc,
  12189. SourceLocation LParenLoc,
  12190. SourceLocation EndLoc) {
  12191. MappableVarListInfo MVLI(VarList);
  12192. checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, StartLoc);
  12193. if (MVLI.ProcessedVarList.empty())
  12194. return nullptr;
  12195. return OMPFromClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  12196. MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
  12197. MVLI.VarComponents);
  12198. }
  12199. OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
  12200. SourceLocation StartLoc,
  12201. SourceLocation LParenLoc,
  12202. SourceLocation EndLoc) {
  12203. MappableVarListInfo MVLI(VarList);
  12204. SmallVector<Expr *, 8> PrivateCopies;
  12205. SmallVector<Expr *, 8> Inits;
  12206. for (Expr *RefExpr : VarList) {
  12207. assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
  12208. SourceLocation ELoc;
  12209. SourceRange ERange;
  12210. Expr *SimpleRefExpr = RefExpr;
  12211. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  12212. if (Res.second) {
  12213. // It will be analyzed later.
  12214. MVLI.ProcessedVarList.push_back(RefExpr);
  12215. PrivateCopies.push_back(nullptr);
  12216. Inits.push_back(nullptr);
  12217. }
  12218. ValueDecl *D = Res.first;
  12219. if (!D)
  12220. continue;
  12221. QualType Type = D->getType();
  12222. Type = Type.getNonReferenceType().getUnqualifiedType();
  12223. auto *VD = dyn_cast<VarDecl>(D);
  12224. // Item should be a pointer or reference to pointer.
  12225. if (!Type->isPointerType()) {
  12226. Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
  12227. << 0 << RefExpr->getSourceRange();
  12228. continue;
  12229. }
  12230. // Build the private variable and the expression that refers to it.
  12231. auto VDPrivate =
  12232. buildVarDecl(*this, ELoc, Type, D->getName(),
  12233. D->hasAttrs() ? &D->getAttrs() : nullptr,
  12234. VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
  12235. if (VDPrivate->isInvalidDecl())
  12236. continue;
  12237. CurContext->addDecl(VDPrivate);
  12238. DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
  12239. *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
  12240. // Add temporary variable to initialize the private copy of the pointer.
  12241. VarDecl *VDInit =
  12242. buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
  12243. DeclRefExpr *VDInitRefExpr = buildDeclRefExpr(
  12244. *this, VDInit, RefExpr->getType(), RefExpr->getExprLoc());
  12245. AddInitializerToDecl(VDPrivate,
  12246. DefaultLvalueConversion(VDInitRefExpr).get(),
  12247. /*DirectInit=*/false);
  12248. // If required, build a capture to implement the privatization initialized
  12249. // with the current list item value.
  12250. DeclRefExpr *Ref = nullptr;
  12251. if (!VD)
  12252. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
  12253. MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
  12254. PrivateCopies.push_back(VDPrivateRefExpr);
  12255. Inits.push_back(VDInitRefExpr);
  12256. // We need to add a data sharing attribute for this variable to make sure it
  12257. // is correctly captured. A variable that shows up in a use_device_ptr has
  12258. // similar properties of a first private variable.
  12259. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
  12260. // Create a mappable component for the list item. List items in this clause
  12261. // only need a component.
  12262. MVLI.VarBaseDeclarations.push_back(D);
  12263. MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
  12264. MVLI.VarComponents.back().push_back(
  12265. OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D));
  12266. }
  12267. if (MVLI.ProcessedVarList.empty())
  12268. return nullptr;
  12269. return OMPUseDevicePtrClause::Create(
  12270. Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
  12271. PrivateCopies, Inits, MVLI.VarBaseDeclarations, MVLI.VarComponents);
  12272. }
  12273. OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
  12274. SourceLocation StartLoc,
  12275. SourceLocation LParenLoc,
  12276. SourceLocation EndLoc) {
  12277. MappableVarListInfo MVLI(VarList);
  12278. for (Expr *RefExpr : VarList) {
  12279. assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
  12280. SourceLocation ELoc;
  12281. SourceRange ERange;
  12282. Expr *SimpleRefExpr = RefExpr;
  12283. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  12284. if (Res.second) {
  12285. // It will be analyzed later.
  12286. MVLI.ProcessedVarList.push_back(RefExpr);
  12287. }
  12288. ValueDecl *D = Res.first;
  12289. if (!D)
  12290. continue;
  12291. QualType Type = D->getType();
  12292. // item should be a pointer or array or reference to pointer or array
  12293. if (!Type.getNonReferenceType()->isPointerType() &&
  12294. !Type.getNonReferenceType()->isArrayType()) {
  12295. Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
  12296. << 0 << RefExpr->getSourceRange();
  12297. continue;
  12298. }
  12299. // Check if the declaration in the clause does not show up in any data
  12300. // sharing attribute.
  12301. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
  12302. if (isOpenMPPrivate(DVar.CKind)) {
  12303. Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
  12304. << getOpenMPClauseName(DVar.CKind)
  12305. << getOpenMPClauseName(OMPC_is_device_ptr)
  12306. << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
  12307. reportOriginalDsa(*this, DSAStack, D, DVar);
  12308. continue;
  12309. }
  12310. const Expr *ConflictExpr;
  12311. if (DSAStack->checkMappableExprComponentListsForDecl(
  12312. D, /*CurrentRegionOnly=*/true,
  12313. [&ConflictExpr](
  12314. OMPClauseMappableExprCommon::MappableExprComponentListRef R,
  12315. OpenMPClauseKind) -> bool {
  12316. ConflictExpr = R.front().getAssociatedExpression();
  12317. return true;
  12318. })) {
  12319. Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
  12320. Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
  12321. << ConflictExpr->getSourceRange();
  12322. continue;
  12323. }
  12324. // Store the components in the stack so that they can be used to check
  12325. // against other clauses later on.
  12326. OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D);
  12327. DSAStack->addMappableExpressionComponents(
  12328. D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
  12329. // Record the expression we've just processed.
  12330. MVLI.ProcessedVarList.push_back(SimpleRefExpr);
  12331. // Create a mappable component for the list item. List items in this clause
  12332. // only need a component. We use a null declaration to signal fields in
  12333. // 'this'.
  12334. assert((isa<DeclRefExpr>(SimpleRefExpr) ||
  12335. isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
  12336. "Unexpected device pointer expression!");
  12337. MVLI.VarBaseDeclarations.push_back(
  12338. isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
  12339. MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
  12340. MVLI.VarComponents.back().push_back(MC);
  12341. }
  12342. if (MVLI.ProcessedVarList.empty())
  12343. return nullptr;
  12344. return OMPIsDevicePtrClause::Create(
  12345. Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
  12346. MVLI.VarBaseDeclarations, MVLI.VarComponents);
  12347. }