hlslParseHelper.cpp 420 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039
  1. //
  2. // Copyright (C) 2017-2018 Google, Inc.
  3. // Copyright (C) 2017 LunarG, Inc.
  4. //
  5. // All rights reserved.
  6. //
  7. // Redistribution and use in source and binary forms, with or without
  8. // modification, are permitted provided that the following conditions
  9. // are met:
  10. //
  11. // Redistributions of source code must retain the above copyright
  12. // notice, this list of conditions and the following disclaimer.
  13. //
  14. // Redistributions in binary form must reproduce the above
  15. // copyright notice, this list of conditions and the following
  16. // disclaimer in the documentation and/or other materials provided
  17. // with the distribution.
  18. //
  19. // Neither the name of 3Dlabs Inc. Ltd. nor the names of its
  20. // contributors may be used to endorse or promote products derived
  21. // from this software without specific prior written permission.
  22. //
  23. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  24. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  25. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
  26. // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
  27. // COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
  28. // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
  29. // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  30. // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  31. // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  32. // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
  33. // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  34. // POSSIBILITY OF SUCH DAMAGE.
  35. //
  36. #include "hlslParseHelper.h"
  37. #include "hlslScanContext.h"
  38. #include "hlslGrammar.h"
  39. #include "hlslAttributes.h"
  40. #include "../glslang/Include/Common.h"
  41. #include "../glslang/MachineIndependent/Scan.h"
  42. #include "../glslang/MachineIndependent/preprocessor/PpContext.h"
  43. #include "../glslang/OSDependent/osinclude.h"
  44. #include <algorithm>
  45. #include <functional>
  46. #include <cctype>
  47. #include <array>
  48. #include <set>
  49. namespace glslang {
  50. HlslParseContext::HlslParseContext(TSymbolTable& symbolTable, TIntermediate& interm, bool parsingBuiltins,
  51. int version, EProfile profile, const SpvVersion& spvVersion, EShLanguage language,
  52. TInfoSink& infoSink,
  53. const TString sourceEntryPointName,
  54. bool forwardCompatible, EShMessages messages) :
  55. TParseContextBase(symbolTable, interm, parsingBuiltins, version, profile, spvVersion, language, infoSink,
  56. forwardCompatible, messages, &sourceEntryPointName),
  57. annotationNestingLevel(0),
  58. inputPatch(nullptr),
  59. nextInLocation(0), nextOutLocation(0),
  60. entryPointFunction(nullptr),
  61. entryPointFunctionBody(nullptr),
  62. gsStreamOutput(nullptr),
  63. clipDistanceOutput(nullptr),
  64. cullDistanceOutput(nullptr),
  65. clipDistanceInput(nullptr),
  66. cullDistanceInput(nullptr),
  67. parsingEntrypointParameters(false)
  68. {
  69. globalUniformDefaults.clear();
  70. globalUniformDefaults.layoutMatrix = ElmRowMajor;
  71. globalUniformDefaults.layoutPacking = ElpStd140;
  72. globalBufferDefaults.clear();
  73. globalBufferDefaults.layoutMatrix = ElmRowMajor;
  74. globalBufferDefaults.layoutPacking = ElpStd430;
  75. globalInputDefaults.clear();
  76. globalOutputDefaults.clear();
  77. clipSemanticNSizeIn.fill(0);
  78. cullSemanticNSizeIn.fill(0);
  79. clipSemanticNSizeOut.fill(0);
  80. cullSemanticNSizeOut.fill(0);
  81. // "Shaders in the transform
  82. // feedback capturing mode have an initial global default of
  83. // layout(xfb_buffer = 0) out;"
  84. if (language == EShLangVertex ||
  85. language == EShLangTessControl ||
  86. language == EShLangTessEvaluation ||
  87. language == EShLangGeometry)
  88. globalOutputDefaults.layoutXfbBuffer = 0;
  89. if (language == EShLangGeometry)
  90. globalOutputDefaults.layoutStream = 0;
  91. }
  92. HlslParseContext::~HlslParseContext()
  93. {
  94. }
  95. void HlslParseContext::initializeExtensionBehavior()
  96. {
  97. TParseContextBase::initializeExtensionBehavior();
  98. // HLSL allows #line by default.
  99. extensionBehavior[E_GL_GOOGLE_cpp_style_line_directive] = EBhEnable;
  100. }
  101. void HlslParseContext::setLimits(const TBuiltInResource& r)
  102. {
  103. resources = r;
  104. intermediate.setLimits(resources);
  105. }
  106. //
  107. // Parse an array of strings using the parser in HlslRules.
  108. //
  109. // Returns true for successful acceptance of the shader, false if any errors.
  110. //
  111. bool HlslParseContext::parseShaderStrings(TPpContext& ppContext, TInputScanner& input, bool versionWillBeError)
  112. {
  113. currentScanner = &input;
  114. ppContext.setInput(input, versionWillBeError);
  115. HlslScanContext scanContext(*this, ppContext);
  116. HlslGrammar grammar(scanContext, *this);
  117. if (!grammar.parse()) {
  118. // Print a message formated such that if you click on the message it will take you right to
  119. // the line through most UIs.
  120. const glslang::TSourceLoc& sourceLoc = input.getSourceLoc();
  121. infoSink.info << sourceLoc.getFilenameStr() << "(" << sourceLoc.line << "): error at column " << sourceLoc.column
  122. << ", HLSL parsing failed.\n";
  123. ++numErrors;
  124. return false;
  125. }
  126. finish();
  127. return numErrors == 0;
  128. }
  129. //
  130. // Return true if this l-value node should be converted in some manner.
  131. // For instance: turning a load aggregate into a store in an l-value.
  132. //
  133. bool HlslParseContext::shouldConvertLValue(const TIntermNode* node) const
  134. {
  135. if (node == nullptr || node->getAsTyped() == nullptr)
  136. return false;
  137. const TIntermAggregate* lhsAsAggregate = node->getAsAggregate();
  138. const TIntermBinary* lhsAsBinary = node->getAsBinaryNode();
  139. // If it's a swizzled/indexed aggregate, look at the left node instead.
  140. if (lhsAsBinary != nullptr &&
  141. (lhsAsBinary->getOp() == EOpVectorSwizzle || lhsAsBinary->getOp() == EOpIndexDirect))
  142. lhsAsAggregate = lhsAsBinary->getLeft()->getAsAggregate();
  143. if (lhsAsAggregate != nullptr && lhsAsAggregate->getOp() == EOpImageLoad)
  144. return true;
  145. return false;
  146. }
  147. void HlslParseContext::growGlobalUniformBlock(const TSourceLoc& loc, TType& memberType, const TString& memberName,
  148. TTypeList* newTypeList)
  149. {
  150. newTypeList = nullptr;
  151. correctUniform(memberType.getQualifier());
  152. if (memberType.isStruct()) {
  153. auto it = ioTypeMap.find(memberType.getStruct());
  154. if (it != ioTypeMap.end() && it->second.uniform)
  155. newTypeList = it->second.uniform;
  156. }
  157. TParseContextBase::growGlobalUniformBlock(loc, memberType, memberName, newTypeList);
  158. }
  159. //
  160. // Return a TLayoutFormat corresponding to the given texture type.
  161. //
  162. TLayoutFormat HlslParseContext::getLayoutFromTxType(const TSourceLoc& loc, const TType& txType)
  163. {
  164. if (txType.isStruct()) {
  165. // TODO: implement.
  166. error(loc, "unimplemented: structure type in image or buffer", "", "");
  167. return ElfNone;
  168. }
  169. const int components = txType.getVectorSize();
  170. const TBasicType txBasicType = txType.getBasicType();
  171. const auto selectFormat = [this,&components](TLayoutFormat v1, TLayoutFormat v2, TLayoutFormat v4) -> TLayoutFormat {
  172. if (intermediate.getNoStorageFormat())
  173. return ElfNone;
  174. return components == 1 ? v1 :
  175. components == 2 ? v2 : v4;
  176. };
  177. switch (txBasicType) {
  178. case EbtFloat: return selectFormat(ElfR32f, ElfRg32f, ElfRgba32f);
  179. case EbtInt: return selectFormat(ElfR32i, ElfRg32i, ElfRgba32i);
  180. case EbtUint: return selectFormat(ElfR32ui, ElfRg32ui, ElfRgba32ui);
  181. default:
  182. error(loc, "unknown basic type in image format", "", "");
  183. return ElfNone;
  184. }
  185. }
  186. //
  187. // Both test and if necessary, spit out an error, to see if the node is really
  188. // an l-value that can be operated on this way.
  189. //
  190. // Returns true if there was an error.
  191. //
  192. bool HlslParseContext::lValueErrorCheck(const TSourceLoc& loc, const char* op, TIntermTyped* node)
  193. {
  194. if (shouldConvertLValue(node)) {
  195. // if we're writing to a texture, it must be an RW form.
  196. TIntermAggregate* lhsAsAggregate = node->getAsAggregate();
  197. TIntermTyped* object = lhsAsAggregate->getSequence()[0]->getAsTyped();
  198. if (!object->getType().getSampler().isImage()) {
  199. error(loc, "operator[] on a non-RW texture must be an r-value", "", "");
  200. return true;
  201. }
  202. }
  203. // We tolerate samplers as l-values, even though they are nominally
  204. // illegal, because we expect a later optimization to eliminate them.
  205. if (node->getType().getBasicType() == EbtSampler) {
  206. intermediate.setNeedsLegalization();
  207. return false;
  208. }
  209. // Let the base class check errors
  210. return TParseContextBase::lValueErrorCheck(loc, op, node);
  211. }
  212. //
  213. // This function handles l-value conversions and verifications. It uses, but is not synonymous
  214. // with lValueErrorCheck. That function accepts an l-value directly, while this one must be
  215. // given the surrounding tree - e.g, with an assignment, so we can convert the assign into a
  216. // series of other image operations.
  217. //
  218. // Most things are passed through unmodified, except for error checking.
  219. //
  220. TIntermTyped* HlslParseContext::handleLvalue(const TSourceLoc& loc, const char* op, TIntermTyped*& node)
  221. {
  222. if (node == nullptr)
  223. return nullptr;
  224. TIntermBinary* nodeAsBinary = node->getAsBinaryNode();
  225. TIntermUnary* nodeAsUnary = node->getAsUnaryNode();
  226. TIntermAggregate* sequence = nullptr;
  227. TIntermTyped* lhs = nodeAsUnary ? nodeAsUnary->getOperand() :
  228. nodeAsBinary ? nodeAsBinary->getLeft() :
  229. nullptr;
  230. // Early bail out if there is no conversion to apply
  231. if (!shouldConvertLValue(lhs)) {
  232. if (lhs != nullptr)
  233. if (lValueErrorCheck(loc, op, lhs))
  234. return nullptr;
  235. return node;
  236. }
  237. // *** If we get here, we're going to apply some conversion to an l-value.
  238. // Helper to create a load.
  239. const auto makeLoad = [&](TIntermSymbol* rhsTmp, TIntermTyped* object, TIntermTyped* coord, const TType& derefType) {
  240. TIntermAggregate* loadOp = new TIntermAggregate(EOpImageLoad);
  241. loadOp->setLoc(loc);
  242. loadOp->getSequence().push_back(object);
  243. loadOp->getSequence().push_back(intermediate.addSymbol(*coord->getAsSymbolNode()));
  244. loadOp->setType(derefType);
  245. sequence = intermediate.growAggregate(sequence,
  246. intermediate.addAssign(EOpAssign, rhsTmp, loadOp, loc),
  247. loc);
  248. };
  249. // Helper to create a store.
  250. const auto makeStore = [&](TIntermTyped* object, TIntermTyped* coord, TIntermSymbol* rhsTmp) {
  251. TIntermAggregate* storeOp = new TIntermAggregate(EOpImageStore);
  252. storeOp->getSequence().push_back(object);
  253. storeOp->getSequence().push_back(coord);
  254. storeOp->getSequence().push_back(intermediate.addSymbol(*rhsTmp));
  255. storeOp->setLoc(loc);
  256. storeOp->setType(TType(EbtVoid));
  257. sequence = intermediate.growAggregate(sequence, storeOp);
  258. };
  259. // Helper to create an assign.
  260. const auto makeBinary = [&](TOperator op, TIntermTyped* lhs, TIntermTyped* rhs) {
  261. sequence = intermediate.growAggregate(sequence,
  262. intermediate.addBinaryNode(op, lhs, rhs, loc, lhs->getType()),
  263. loc);
  264. };
  265. // Helper to complete sequence by adding trailing variable, so we evaluate to the right value.
  266. const auto finishSequence = [&](TIntermSymbol* rhsTmp, const TType& derefType) -> TIntermAggregate* {
  267. // Add a trailing use of the temp, so the sequence returns the proper value.
  268. sequence = intermediate.growAggregate(sequence, intermediate.addSymbol(*rhsTmp));
  269. sequence->setOperator(EOpSequence);
  270. sequence->setLoc(loc);
  271. sequence->setType(derefType);
  272. return sequence;
  273. };
  274. // Helper to add unary op
  275. const auto makeUnary = [&](TOperator op, TIntermSymbol* rhsTmp) {
  276. sequence = intermediate.growAggregate(sequence,
  277. intermediate.addUnaryNode(op, intermediate.addSymbol(*rhsTmp), loc,
  278. rhsTmp->getType()),
  279. loc);
  280. };
  281. // Return true if swizzle or index writes all components of the given variable.
  282. const auto writesAllComponents = [&](TIntermSymbol* var, TIntermBinary* swizzle) -> bool {
  283. if (swizzle == nullptr) // not a swizzle or index
  284. return true;
  285. // Track which components are being set.
  286. std::array<bool, 4> compIsSet;
  287. compIsSet.fill(false);
  288. const TIntermConstantUnion* asConst = swizzle->getRight()->getAsConstantUnion();
  289. const TIntermAggregate* asAggregate = swizzle->getRight()->getAsAggregate();
  290. // This could be either a direct index, or a swizzle.
  291. if (asConst) {
  292. compIsSet[asConst->getConstArray()[0].getIConst()] = true;
  293. } else if (asAggregate) {
  294. const TIntermSequence& seq = asAggregate->getSequence();
  295. for (int comp=0; comp<int(seq.size()); ++comp)
  296. compIsSet[seq[comp]->getAsConstantUnion()->getConstArray()[0].getIConst()] = true;
  297. } else {
  298. assert(0);
  299. }
  300. // Return true if all components are being set by the index or swizzle
  301. return std::all_of(compIsSet.begin(), compIsSet.begin() + var->getType().getVectorSize(),
  302. [](bool isSet) { return isSet; } );
  303. };
  304. // Create swizzle matching input swizzle
  305. const auto addSwizzle = [&](TIntermSymbol* var, TIntermBinary* swizzle) -> TIntermTyped* {
  306. if (swizzle)
  307. return intermediate.addBinaryNode(swizzle->getOp(), var, swizzle->getRight(), loc, swizzle->getType());
  308. else
  309. return var;
  310. };
  311. TIntermBinary* lhsAsBinary = lhs->getAsBinaryNode();
  312. TIntermAggregate* lhsAsAggregate = lhs->getAsAggregate();
  313. bool lhsIsSwizzle = false;
  314. // If it's a swizzled L-value, remember the swizzle, and use the LHS.
  315. if (lhsAsBinary != nullptr && (lhsAsBinary->getOp() == EOpVectorSwizzle || lhsAsBinary->getOp() == EOpIndexDirect)) {
  316. lhsAsAggregate = lhsAsBinary->getLeft()->getAsAggregate();
  317. lhsIsSwizzle = true;
  318. }
  319. TIntermTyped* object = lhsAsAggregate->getSequence()[0]->getAsTyped();
  320. TIntermTyped* coord = lhsAsAggregate->getSequence()[1]->getAsTyped();
  321. const TSampler& texSampler = object->getType().getSampler();
  322. TType objDerefType;
  323. getTextureReturnType(texSampler, objDerefType);
  324. if (nodeAsBinary) {
  325. TIntermTyped* rhs = nodeAsBinary->getRight();
  326. const TOperator assignOp = nodeAsBinary->getOp();
  327. bool isModifyOp = false;
  328. switch (assignOp) {
  329. case EOpAddAssign:
  330. case EOpSubAssign:
  331. case EOpMulAssign:
  332. case EOpVectorTimesMatrixAssign:
  333. case EOpVectorTimesScalarAssign:
  334. case EOpMatrixTimesScalarAssign:
  335. case EOpMatrixTimesMatrixAssign:
  336. case EOpDivAssign:
  337. case EOpModAssign:
  338. case EOpAndAssign:
  339. case EOpInclusiveOrAssign:
  340. case EOpExclusiveOrAssign:
  341. case EOpLeftShiftAssign:
  342. case EOpRightShiftAssign:
  343. isModifyOp = true;
  344. // fall through...
  345. case EOpAssign:
  346. {
  347. // Since this is an lvalue, we'll convert an image load to a sequence like this
  348. // (to still provide the value):
  349. // OpSequence
  350. // OpImageStore(object, lhs, rhs)
  351. // rhs
  352. // But if it's not a simple symbol RHS (say, a fn call), we don't want to duplicate the RHS,
  353. // so we'll convert instead to this:
  354. // OpSequence
  355. // rhsTmp = rhs
  356. // OpImageStore(object, coord, rhsTmp)
  357. // rhsTmp
  358. // If this is a read-modify-write op, like +=, we issue:
  359. // OpSequence
  360. // coordtmp = load's param1
  361. // rhsTmp = OpImageLoad(object, coordTmp)
  362. // rhsTmp op= rhs
  363. // OpImageStore(object, coordTmp, rhsTmp)
  364. // rhsTmp
  365. //
  366. // If the lvalue is swizzled, we apply that when writing the temp variable, like so:
  367. // ...
  368. // rhsTmp.some_swizzle = ...
  369. // For partial writes, an error is generated.
  370. TIntermSymbol* rhsTmp = rhs->getAsSymbolNode();
  371. TIntermTyped* coordTmp = coord;
  372. if (rhsTmp == nullptr || isModifyOp || lhsIsSwizzle) {
  373. rhsTmp = makeInternalVariableNode(loc, "storeTemp", objDerefType);
  374. // Partial updates not yet supported
  375. if (!writesAllComponents(rhsTmp, lhsAsBinary)) {
  376. error(loc, "unimplemented: partial image updates", "", "");
  377. }
  378. // Assign storeTemp = rhs
  379. if (isModifyOp) {
  380. // We have to make a temp var for the coordinate, to avoid evaluating it twice.
  381. coordTmp = makeInternalVariableNode(loc, "coordTemp", coord->getType());
  382. makeBinary(EOpAssign, coordTmp, coord); // coordtmp = load[param1]
  383. makeLoad(rhsTmp, object, coordTmp, objDerefType); // rhsTmp = OpImageLoad(object, coordTmp)
  384. }
  385. // rhsTmp op= rhs.
  386. makeBinary(assignOp, addSwizzle(intermediate.addSymbol(*rhsTmp), lhsAsBinary), rhs);
  387. }
  388. makeStore(object, coordTmp, rhsTmp); // add a store
  389. return finishSequence(rhsTmp, objDerefType); // return rhsTmp from sequence
  390. }
  391. default:
  392. break;
  393. }
  394. }
  395. if (nodeAsUnary) {
  396. const TOperator assignOp = nodeAsUnary->getOp();
  397. switch (assignOp) {
  398. case EOpPreIncrement:
  399. case EOpPreDecrement:
  400. {
  401. // We turn this into:
  402. // OpSequence
  403. // coordtmp = load's param1
  404. // rhsTmp = OpImageLoad(object, coordTmp)
  405. // rhsTmp op
  406. // OpImageStore(object, coordTmp, rhsTmp)
  407. // rhsTmp
  408. TIntermSymbol* rhsTmp = makeInternalVariableNode(loc, "storeTemp", objDerefType);
  409. TIntermTyped* coordTmp = makeInternalVariableNode(loc, "coordTemp", coord->getType());
  410. makeBinary(EOpAssign, coordTmp, coord); // coordtmp = load[param1]
  411. makeLoad(rhsTmp, object, coordTmp, objDerefType); // rhsTmp = OpImageLoad(object, coordTmp)
  412. makeUnary(assignOp, rhsTmp); // op rhsTmp
  413. makeStore(object, coordTmp, rhsTmp); // OpImageStore(object, coordTmp, rhsTmp)
  414. return finishSequence(rhsTmp, objDerefType); // return rhsTmp from sequence
  415. }
  416. case EOpPostIncrement:
  417. case EOpPostDecrement:
  418. {
  419. // We turn this into:
  420. // OpSequence
  421. // coordtmp = load's param1
  422. // rhsTmp1 = OpImageLoad(object, coordTmp)
  423. // rhsTmp2 = rhsTmp1
  424. // rhsTmp2 op
  425. // OpImageStore(object, coordTmp, rhsTmp2)
  426. // rhsTmp1 (pre-op value)
  427. TIntermSymbol* rhsTmp1 = makeInternalVariableNode(loc, "storeTempPre", objDerefType);
  428. TIntermSymbol* rhsTmp2 = makeInternalVariableNode(loc, "storeTempPost", objDerefType);
  429. TIntermTyped* coordTmp = makeInternalVariableNode(loc, "coordTemp", coord->getType());
  430. makeBinary(EOpAssign, coordTmp, coord); // coordtmp = load[param1]
  431. makeLoad(rhsTmp1, object, coordTmp, objDerefType); // rhsTmp1 = OpImageLoad(object, coordTmp)
  432. makeBinary(EOpAssign, rhsTmp2, rhsTmp1); // rhsTmp2 = rhsTmp1
  433. makeUnary(assignOp, rhsTmp2); // rhsTmp op
  434. makeStore(object, coordTmp, rhsTmp2); // OpImageStore(object, coordTmp, rhsTmp2)
  435. return finishSequence(rhsTmp1, objDerefType); // return rhsTmp from sequence
  436. }
  437. default:
  438. break;
  439. }
  440. }
  441. if (lhs)
  442. if (lValueErrorCheck(loc, op, lhs))
  443. return nullptr;
  444. return node;
  445. }
  446. void HlslParseContext::handlePragma(const TSourceLoc& loc, const TVector<TString>& tokens)
  447. {
  448. if (pragmaCallback)
  449. pragmaCallback(loc.line, tokens);
  450. if (tokens.size() == 0)
  451. return;
  452. // These pragmas are case insensitive in HLSL, so we'll compare in lower case.
  453. TVector<TString> lowerTokens = tokens;
  454. for (auto it = lowerTokens.begin(); it != lowerTokens.end(); ++it)
  455. std::transform(it->begin(), it->end(), it->begin(), ::tolower);
  456. // Handle pack_matrix
  457. if (tokens.size() == 4 && lowerTokens[0] == "pack_matrix" && tokens[1] == "(" && tokens[3] == ")") {
  458. // Note that HLSL semantic order is Mrc, not Mcr like SPIR-V, so we reverse the sense.
  459. // Row major becomes column major and vice versa.
  460. if (lowerTokens[2] == "row_major") {
  461. globalUniformDefaults.layoutMatrix = globalBufferDefaults.layoutMatrix = ElmColumnMajor;
  462. } else if (lowerTokens[2] == "column_major") {
  463. globalUniformDefaults.layoutMatrix = globalBufferDefaults.layoutMatrix = ElmRowMajor;
  464. } else {
  465. // unknown majorness strings are treated as (HLSL column major)==(SPIR-V row major)
  466. warn(loc, "unknown pack_matrix pragma value", tokens[2].c_str(), "");
  467. globalUniformDefaults.layoutMatrix = globalBufferDefaults.layoutMatrix = ElmRowMajor;
  468. }
  469. return;
  470. }
  471. // Handle once
  472. if (lowerTokens[0] == "once") {
  473. warn(loc, "not implemented", "#pragma once", "");
  474. return;
  475. }
  476. }
  477. //
  478. // Look at a '.' matrix selector string and change it into components
  479. // for a matrix. There are two types:
  480. //
  481. // _21 second row, first column (one based)
  482. // _m21 third row, second column (zero based)
  483. //
  484. // Returns true if there is no error.
  485. //
  486. bool HlslParseContext::parseMatrixSwizzleSelector(const TSourceLoc& loc, const TString& fields, int cols, int rows,
  487. TSwizzleSelectors<TMatrixSelector>& components)
  488. {
  489. int startPos[MaxSwizzleSelectors];
  490. int numComps = 0;
  491. TString compString = fields;
  492. // Find where each component starts,
  493. // recording the first character position after the '_'.
  494. for (size_t c = 0; c < compString.size(); ++c) {
  495. if (compString[c] == '_') {
  496. if (numComps >= MaxSwizzleSelectors) {
  497. error(loc, "matrix component swizzle has too many components", compString.c_str(), "");
  498. return false;
  499. }
  500. if (c > compString.size() - 3 ||
  501. ((compString[c+1] == 'm' || compString[c+1] == 'M') && c > compString.size() - 4)) {
  502. error(loc, "matrix component swizzle missing", compString.c_str(), "");
  503. return false;
  504. }
  505. startPos[numComps++] = (int)c + 1;
  506. }
  507. }
  508. // Process each component
  509. for (int i = 0; i < numComps; ++i) {
  510. int pos = startPos[i];
  511. int bias = -1;
  512. if (compString[pos] == 'm' || compString[pos] == 'M') {
  513. bias = 0;
  514. ++pos;
  515. }
  516. TMatrixSelector comp;
  517. comp.coord1 = compString[pos+0] - '0' + bias;
  518. comp.coord2 = compString[pos+1] - '0' + bias;
  519. if (comp.coord1 < 0 || comp.coord1 >= cols) {
  520. error(loc, "matrix row component out of range", compString.c_str(), "");
  521. return false;
  522. }
  523. if (comp.coord2 < 0 || comp.coord2 >= rows) {
  524. error(loc, "matrix column component out of range", compString.c_str(), "");
  525. return false;
  526. }
  527. components.push_back(comp);
  528. }
  529. return true;
  530. }
  531. // If the 'comps' express a column of a matrix,
  532. // return the column. Column means the first coords all match.
  533. //
  534. // Otherwise, return -1.
  535. //
  536. int HlslParseContext::getMatrixComponentsColumn(int rows, const TSwizzleSelectors<TMatrixSelector>& selector)
  537. {
  538. int col = -1;
  539. // right number of comps?
  540. if (selector.size() != rows)
  541. return -1;
  542. // all comps in the same column?
  543. // rows in order?
  544. col = selector[0].coord1;
  545. for (int i = 0; i < rows; ++i) {
  546. if (col != selector[i].coord1)
  547. return -1;
  548. if (i != selector[i].coord2)
  549. return -1;
  550. }
  551. return col;
  552. }
  553. //
  554. // Handle seeing a variable identifier in the grammar.
  555. //
  556. TIntermTyped* HlslParseContext::handleVariable(const TSourceLoc& loc, const TString* string)
  557. {
  558. int thisDepth;
  559. TSymbol* symbol = symbolTable.find(*string, thisDepth);
  560. if (symbol && symbol->getAsVariable() && symbol->getAsVariable()->isUserType()) {
  561. error(loc, "expected symbol, not user-defined type", string->c_str(), "");
  562. return nullptr;
  563. }
  564. const TVariable* variable = nullptr;
  565. const TAnonMember* anon = symbol ? symbol->getAsAnonMember() : nullptr;
  566. TIntermTyped* node = nullptr;
  567. if (anon) {
  568. // It was a member of an anonymous container, which could be a 'this' structure.
  569. // Create a subtree for its dereference.
  570. if (thisDepth > 0) {
  571. variable = getImplicitThis(thisDepth);
  572. if (variable == nullptr)
  573. error(loc, "cannot access member variables (static member function?)", "this", "");
  574. }
  575. if (variable == nullptr)
  576. variable = anon->getAnonContainer().getAsVariable();
  577. TIntermTyped* container = intermediate.addSymbol(*variable, loc);
  578. TIntermTyped* constNode = intermediate.addConstantUnion(anon->getMemberNumber(), loc);
  579. node = intermediate.addIndex(EOpIndexDirectStruct, container, constNode, loc);
  580. node->setType(*(*variable->getType().getStruct())[anon->getMemberNumber()].type);
  581. if (node->getType().hiddenMember())
  582. error(loc, "member of nameless block was not redeclared", string->c_str(), "");
  583. } else {
  584. // Not a member of an anonymous container.
  585. // The symbol table search was done in the lexical phase.
  586. // See if it was a variable.
  587. variable = symbol ? symbol->getAsVariable() : nullptr;
  588. if (variable) {
  589. if ((variable->getType().getBasicType() == EbtBlock ||
  590. variable->getType().getBasicType() == EbtStruct) && variable->getType().getStruct() == nullptr) {
  591. error(loc, "cannot be used (maybe an instance name is needed)", string->c_str(), "");
  592. variable = nullptr;
  593. }
  594. } else {
  595. if (symbol)
  596. error(loc, "variable name expected", string->c_str(), "");
  597. }
  598. // Recovery, if it wasn't found or was not a variable.
  599. if (variable == nullptr) {
  600. error(loc, "unknown variable", string->c_str(), "");
  601. variable = new TVariable(string, TType(EbtVoid));
  602. }
  603. if (variable->getType().getQualifier().isFrontEndConstant())
  604. node = intermediate.addConstantUnion(variable->getConstArray(), variable->getType(), loc);
  605. else
  606. node = intermediate.addSymbol(*variable, loc);
  607. }
  608. if (variable->getType().getQualifier().isIo())
  609. intermediate.addIoAccessed(*string);
  610. return node;
  611. }
  612. //
  613. // Handle operator[] on any objects it applies to. Currently:
  614. // Textures
  615. // Buffers
  616. //
  617. TIntermTyped* HlslParseContext::handleBracketOperator(const TSourceLoc& loc, TIntermTyped* base, TIntermTyped* index)
  618. {
  619. // handle r-value operator[] on textures and images. l-values will be processed later.
  620. if (base->getType().getBasicType() == EbtSampler && !base->isArray()) {
  621. const TSampler& sampler = base->getType().getSampler();
  622. if (sampler.isImage() || sampler.isTexture()) {
  623. if (! mipsOperatorMipArg.empty() && mipsOperatorMipArg.back().mipLevel == nullptr) {
  624. // The first operator[] to a .mips[] sequence is the mip level. We'll remember it.
  625. mipsOperatorMipArg.back().mipLevel = index;
  626. return base; // next [] index is to the same base.
  627. } else {
  628. TIntermAggregate* load = new TIntermAggregate(sampler.isImage() ? EOpImageLoad : EOpTextureFetch);
  629. TType sampReturnType;
  630. getTextureReturnType(sampler, sampReturnType);
  631. load->setType(sampReturnType);
  632. load->setLoc(loc);
  633. load->getSequence().push_back(base);
  634. load->getSequence().push_back(index);
  635. // Textures need a MIP. If we saw one go by, use it. Otherwise, use zero.
  636. if (sampler.isTexture()) {
  637. if (! mipsOperatorMipArg.empty()) {
  638. load->getSequence().push_back(mipsOperatorMipArg.back().mipLevel);
  639. mipsOperatorMipArg.pop_back();
  640. } else {
  641. load->getSequence().push_back(intermediate.addConstantUnion(0, loc, true));
  642. }
  643. }
  644. return load;
  645. }
  646. }
  647. }
  648. // Handle operator[] on structured buffers: this indexes into the array element of the buffer.
  649. // indexStructBufferContent returns nullptr if it isn't a structuredbuffer (SSBO).
  650. TIntermTyped* sbArray = indexStructBufferContent(loc, base);
  651. if (sbArray != nullptr) {
  652. // Now we'll apply the [] index to that array
  653. const TOperator idxOp = (index->getQualifier().storage == EvqConst) ? EOpIndexDirect : EOpIndexIndirect;
  654. TIntermTyped* element = intermediate.addIndex(idxOp, sbArray, index, loc);
  655. const TType derefType(sbArray->getType(), 0);
  656. element->setType(derefType);
  657. return element;
  658. }
  659. return nullptr;
  660. }
  661. //
  662. // Cast index value to a uint if it isn't already (for operator[], load indexes, etc)
  663. TIntermTyped* HlslParseContext::makeIntegerIndex(TIntermTyped* index)
  664. {
  665. const TBasicType indexBasicType = index->getType().getBasicType();
  666. const int vecSize = index->getType().getVectorSize();
  667. // We can use int types directly as the index
  668. if (indexBasicType == EbtInt || indexBasicType == EbtUint ||
  669. indexBasicType == EbtInt64 || indexBasicType == EbtUint64)
  670. return index;
  671. // Cast index to unsigned integer if it isn't one.
  672. return intermediate.addConversion(EOpConstructUint, TType(EbtUint, EvqTemporary, vecSize), index);
  673. }
  674. //
  675. // Handle seeing a base[index] dereference in the grammar.
  676. //
  677. TIntermTyped* HlslParseContext::handleBracketDereference(const TSourceLoc& loc, TIntermTyped* base, TIntermTyped* index)
  678. {
  679. index = makeIntegerIndex(index);
  680. if (index == nullptr) {
  681. error(loc, " unknown index type ", "", "");
  682. return nullptr;
  683. }
  684. TIntermTyped* result = handleBracketOperator(loc, base, index);
  685. if (result != nullptr)
  686. return result; // it was handled as an operator[]
  687. bool flattened = false;
  688. int indexValue = 0;
  689. if (index->getQualifier().isFrontEndConstant())
  690. indexValue = index->getAsConstantUnion()->getConstArray()[0].getIConst();
  691. variableCheck(base);
  692. if (! base->isArray() && ! base->isMatrix() && ! base->isVector()) {
  693. if (base->getAsSymbolNode())
  694. error(loc, " left of '[' is not of type array, matrix, or vector ",
  695. base->getAsSymbolNode()->getName().c_str(), "");
  696. else
  697. error(loc, " left of '[' is not of type array, matrix, or vector ", "expression", "");
  698. } else if (base->getType().getQualifier().isFrontEndConstant() &&
  699. index->getQualifier().isFrontEndConstant()) {
  700. // both base and index are front-end constants
  701. checkIndex(loc, base->getType(), indexValue);
  702. return intermediate.foldDereference(base, indexValue, loc);
  703. } else {
  704. // at least one of base and index is variable...
  705. if (index->getQualifier().isFrontEndConstant())
  706. checkIndex(loc, base->getType(), indexValue);
  707. if (base->getType().isScalarOrVec1())
  708. result = base;
  709. else if (base->getAsSymbolNode() && wasFlattened(base)) {
  710. if (index->getQualifier().storage != EvqConst)
  711. error(loc, "Invalid variable index to flattened array", base->getAsSymbolNode()->getName().c_str(), "");
  712. result = flattenAccess(base, indexValue);
  713. flattened = (result != base);
  714. } else {
  715. if (index->getQualifier().isFrontEndConstant()) {
  716. if (base->getType().isUnsizedArray())
  717. base->getWritableType().updateImplicitArraySize(indexValue + 1);
  718. else
  719. checkIndex(loc, base->getType(), indexValue);
  720. result = intermediate.addIndex(EOpIndexDirect, base, index, loc);
  721. } else
  722. result = intermediate.addIndex(EOpIndexIndirect, base, index, loc);
  723. }
  724. }
  725. if (result == nullptr) {
  726. // Insert dummy error-recovery result
  727. result = intermediate.addConstantUnion(0.0, EbtFloat, loc);
  728. } else {
  729. // If the array reference was flattened, it has the correct type. E.g, if it was
  730. // a uniform array, it was flattened INTO a set of scalar uniforms, not scalar temps.
  731. // In that case, we preserve the qualifiers.
  732. if (!flattened) {
  733. // Insert valid dereferenced result
  734. TType newType(base->getType(), 0); // dereferenced type
  735. if (base->getType().getQualifier().storage == EvqConst && index->getQualifier().storage == EvqConst)
  736. newType.getQualifier().storage = EvqConst;
  737. else
  738. newType.getQualifier().storage = EvqTemporary;
  739. result->setType(newType);
  740. }
  741. }
  742. return result;
  743. }
  744. // Handle seeing a binary node with a math operation.
  745. TIntermTyped* HlslParseContext::handleBinaryMath(const TSourceLoc& loc, const char* str, TOperator op,
  746. TIntermTyped* left, TIntermTyped* right)
  747. {
  748. TIntermTyped* result = intermediate.addBinaryMath(op, left, right, loc);
  749. if (result == nullptr)
  750. binaryOpError(loc, str, left->getCompleteString(), right->getCompleteString());
  751. return result;
  752. }
  753. // Handle seeing a unary node with a math operation.
  754. TIntermTyped* HlslParseContext::handleUnaryMath(const TSourceLoc& loc, const char* str, TOperator op,
  755. TIntermTyped* childNode)
  756. {
  757. TIntermTyped* result = intermediate.addUnaryMath(op, childNode, loc);
  758. if (result)
  759. return result;
  760. else
  761. unaryOpError(loc, str, childNode->getCompleteString());
  762. return childNode;
  763. }
  764. //
  765. // Return true if the name is a struct buffer method
  766. //
  767. bool HlslParseContext::isStructBufferMethod(const TString& name) const
  768. {
  769. return
  770. name == "GetDimensions" ||
  771. name == "Load" ||
  772. name == "Load2" ||
  773. name == "Load3" ||
  774. name == "Load4" ||
  775. name == "Store" ||
  776. name == "Store2" ||
  777. name == "Store3" ||
  778. name == "Store4" ||
  779. name == "InterlockedAdd" ||
  780. name == "InterlockedAnd" ||
  781. name == "InterlockedCompareExchange" ||
  782. name == "InterlockedCompareStore" ||
  783. name == "InterlockedExchange" ||
  784. name == "InterlockedMax" ||
  785. name == "InterlockedMin" ||
  786. name == "InterlockedOr" ||
  787. name == "InterlockedXor" ||
  788. name == "IncrementCounter" ||
  789. name == "DecrementCounter" ||
  790. name == "Append" ||
  791. name == "Consume";
  792. }
  793. //
  794. // Handle seeing a base.field dereference in the grammar, where 'field' is a
  795. // swizzle or member variable.
  796. //
  797. TIntermTyped* HlslParseContext::handleDotDereference(const TSourceLoc& loc, TIntermTyped* base, const TString& field)
  798. {
  799. variableCheck(base);
  800. if (base->isArray()) {
  801. error(loc, "cannot apply to an array:", ".", field.c_str());
  802. return base;
  803. }
  804. TIntermTyped* result = base;
  805. if (base->getType().getBasicType() == EbtSampler) {
  806. // Handle .mips[mipid][pos] operation on textures
  807. const TSampler& sampler = base->getType().getSampler();
  808. if (sampler.isTexture() && field == "mips") {
  809. // Push a null to signify that we expect a mip level under operator[] next.
  810. mipsOperatorMipArg.push_back(tMipsOperatorData(loc, nullptr));
  811. // Keep 'result' pointing to 'base', since we expect an operator[] to go by next.
  812. } else {
  813. if (field == "mips")
  814. error(loc, "unexpected texture type for .mips[][] operator:",
  815. base->getType().getCompleteString().c_str(), "");
  816. else
  817. error(loc, "unexpected operator on texture type:", field.c_str(),
  818. base->getType().getCompleteString().c_str());
  819. }
  820. } else if (base->isVector() || base->isScalar()) {
  821. TSwizzleSelectors<TVectorSelector> selectors;
  822. bool numeric = false;
  823. parseSwizzleSelector(loc, field, base->getVectorSize(), selectors, numeric);
  824. if (base->isScalar()) {
  825. if (selectors.size() == 1)
  826. return result;
  827. else {
  828. TType type(base->getBasicType(), EvqTemporary, selectors.size());
  829. return addConstructor(loc, base, type);
  830. }
  831. }
  832. if (base->getVectorSize() == 1) {
  833. TType scalarType(base->getBasicType(), EvqTemporary, 1);
  834. if (selectors.size() == 1)
  835. return addConstructor(loc, base, scalarType);
  836. else {
  837. TType vectorType(base->getBasicType(), EvqTemporary, selectors.size());
  838. return addConstructor(loc, addConstructor(loc, base, scalarType), vectorType);
  839. }
  840. }
  841. if (base->getType().getQualifier().isFrontEndConstant())
  842. result = intermediate.foldSwizzle(base, selectors, loc);
  843. else {
  844. if (selectors.size() == 1) {
  845. TIntermTyped* index = intermediate.addConstantUnion(selectors[0], loc);
  846. result = intermediate.addIndex(EOpIndexDirect, base, index, loc);
  847. result->setType(TType(base->getBasicType(), EvqTemporary));
  848. } else {
  849. TIntermTyped* index = intermediate.addSwizzle(selectors, loc);
  850. result = intermediate.addIndex(EOpVectorSwizzle, base, index, loc);
  851. result->setType(TType(base->getBasicType(), EvqTemporary, base->getType().getQualifier().precision,
  852. selectors.size()));
  853. }
  854. }
  855. } else if (base->isMatrix()) {
  856. TSwizzleSelectors<TMatrixSelector> selectors;
  857. if (! parseMatrixSwizzleSelector(loc, field, base->getMatrixCols(), base->getMatrixRows(), selectors))
  858. return result;
  859. if (selectors.size() == 1) {
  860. // Representable by m[c][r]
  861. if (base->getType().getQualifier().isFrontEndConstant()) {
  862. result = intermediate.foldDereference(base, selectors[0].coord1, loc);
  863. result = intermediate.foldDereference(result, selectors[0].coord2, loc);
  864. } else {
  865. result = intermediate.addIndex(EOpIndexDirect, base,
  866. intermediate.addConstantUnion(selectors[0].coord1, loc),
  867. loc);
  868. TType dereferencedCol(base->getType(), 0);
  869. result->setType(dereferencedCol);
  870. result = intermediate.addIndex(EOpIndexDirect, result,
  871. intermediate.addConstantUnion(selectors[0].coord2, loc),
  872. loc);
  873. TType dereferenced(dereferencedCol, 0);
  874. result->setType(dereferenced);
  875. }
  876. } else {
  877. int column = getMatrixComponentsColumn(base->getMatrixRows(), selectors);
  878. if (column >= 0) {
  879. // Representable by m[c]
  880. if (base->getType().getQualifier().isFrontEndConstant())
  881. result = intermediate.foldDereference(base, column, loc);
  882. else {
  883. result = intermediate.addIndex(EOpIndexDirect, base, intermediate.addConstantUnion(column, loc),
  884. loc);
  885. TType dereferenced(base->getType(), 0);
  886. result->setType(dereferenced);
  887. }
  888. } else {
  889. // general case, not a column, not a single component
  890. TIntermTyped* index = intermediate.addSwizzle(selectors, loc);
  891. result = intermediate.addIndex(EOpMatrixSwizzle, base, index, loc);
  892. result->setType(TType(base->getBasicType(), EvqTemporary, base->getType().getQualifier().precision,
  893. selectors.size()));
  894. }
  895. }
  896. } else if (base->getBasicType() == EbtStruct || base->getBasicType() == EbtBlock) {
  897. const TTypeList* fields = base->getType().getStruct();
  898. bool fieldFound = false;
  899. int member;
  900. for (member = 0; member < (int)fields->size(); ++member) {
  901. if ((*fields)[member].type->getFieldName() == field) {
  902. fieldFound = true;
  903. break;
  904. }
  905. }
  906. if (fieldFound) {
  907. if (base->getAsSymbolNode() && wasFlattened(base)) {
  908. result = flattenAccess(base, member);
  909. } else {
  910. if (base->getType().getQualifier().storage == EvqConst)
  911. result = intermediate.foldDereference(base, member, loc);
  912. else {
  913. TIntermTyped* index = intermediate.addConstantUnion(member, loc);
  914. result = intermediate.addIndex(EOpIndexDirectStruct, base, index, loc);
  915. result->setType(*(*fields)[member].type);
  916. }
  917. }
  918. } else
  919. error(loc, "no such field in structure", field.c_str(), "");
  920. } else
  921. error(loc, "does not apply to this type:", field.c_str(), base->getType().getCompleteString().c_str());
  922. return result;
  923. }
  924. //
  925. // Return true if the field should be treated as a built-in method.
  926. // Return false otherwise.
  927. //
  928. bool HlslParseContext::isBuiltInMethod(const TSourceLoc&, TIntermTyped* base, const TString& field)
  929. {
  930. if (base == nullptr)
  931. return false;
  932. variableCheck(base);
  933. if (base->getType().getBasicType() == EbtSampler) {
  934. return true;
  935. } else if (isStructBufferType(base->getType()) && isStructBufferMethod(field)) {
  936. return true;
  937. } else if (field == "Append" ||
  938. field == "RestartStrip") {
  939. // We cannot check the type here: it may be sanitized if we're not compiling a geometry shader, but
  940. // the code is around in the shader source.
  941. return true;
  942. } else
  943. return false;
  944. }
  945. // Independently establish a built-in that is a member of a structure.
  946. // 'arraySizes' are what's desired for the independent built-in, whatever
  947. // the higher-level source/expression of them was.
  948. void HlslParseContext::splitBuiltIn(const TString& baseName, const TType& memberType, const TArraySizes* arraySizes,
  949. const TQualifier& outerQualifier)
  950. {
  951. // Because of arrays of structs, we might be asked more than once,
  952. // but the arraySizes passed in should have captured the whole thing
  953. // the first time.
  954. // However, clip/cull rely on multiple updates.
  955. if (!isClipOrCullDistance(memberType))
  956. if (splitBuiltIns.find(tInterstageIoData(memberType.getQualifier().builtIn, outerQualifier.storage)) !=
  957. splitBuiltIns.end())
  958. return;
  959. TVariable* ioVar = makeInternalVariable(baseName + "." + memberType.getFieldName(), memberType);
  960. if (arraySizes != nullptr && !memberType.isArray())
  961. ioVar->getWritableType().copyArraySizes(*arraySizes);
  962. splitBuiltIns[tInterstageIoData(memberType.getQualifier().builtIn, outerQualifier.storage)] = ioVar;
  963. if (!isClipOrCullDistance(ioVar->getType()))
  964. trackLinkage(*ioVar);
  965. // Merge qualifier from the user structure
  966. mergeQualifiers(ioVar->getWritableType().getQualifier(), outerQualifier);
  967. // Fix the builtin type if needed (e.g, some types require fixed array sizes, no matter how the
  968. // shader declared them). This is done after mergeQualifiers(), in case fixBuiltInIoType looks
  969. // at the qualifier to determine e.g, in or out qualifications.
  970. fixBuiltInIoType(ioVar->getWritableType());
  971. // But, not location, we're losing that
  972. ioVar->getWritableType().getQualifier().layoutLocation = TQualifier::layoutLocationEnd;
  973. }
  974. // Split a type into
  975. // 1. a struct of non-I/O members
  976. // 2. a collection of independent I/O variables
  977. void HlslParseContext::split(const TVariable& variable)
  978. {
  979. // Create a new variable:
  980. const TType& clonedType = *variable.getType().clone();
  981. const TType& splitType = split(clonedType, variable.getName(), clonedType.getQualifier());
  982. splitNonIoVars[variable.getUniqueId()] = makeInternalVariable(variable.getName(), splitType);
  983. }
  984. // Recursive implementation of split().
  985. // Returns reference to the modified type.
  986. const TType& HlslParseContext::split(const TType& type, const TString& name, const TQualifier& outerQualifier)
  987. {
  988. if (type.isStruct()) {
  989. TTypeList* userStructure = type.getWritableStruct();
  990. for (auto ioType = userStructure->begin(); ioType != userStructure->end(); ) {
  991. if (ioType->type->isBuiltIn()) {
  992. // move out the built-in
  993. splitBuiltIn(name, *ioType->type, type.getArraySizes(), outerQualifier);
  994. ioType = userStructure->erase(ioType);
  995. } else {
  996. split(*ioType->type, name + "." + ioType->type->getFieldName(), outerQualifier);
  997. ++ioType;
  998. }
  999. }
  1000. }
  1001. return type;
  1002. }
  1003. // Is this an aggregate that should be flattened?
  1004. // Can be applied to intermediate levels of type in a hierarchy.
  1005. // Some things like flattening uniform arrays are only about the top level
  1006. // of the aggregate, triggered on 'topLevel'.
  1007. bool HlslParseContext::shouldFlatten(const TType& type, TStorageQualifier qualifier, bool topLevel) const
  1008. {
  1009. switch (qualifier) {
  1010. case EvqVaryingIn:
  1011. case EvqVaryingOut:
  1012. return type.isStruct() || type.isArray();
  1013. case EvqUniform:
  1014. return (type.isArray() && intermediate.getFlattenUniformArrays() && topLevel) ||
  1015. (type.isStruct() && type.containsOpaque());
  1016. default:
  1017. return false;
  1018. };
  1019. }
  1020. // Top level variable flattening: construct data
  1021. void HlslParseContext::flatten(const TVariable& variable, bool linkage)
  1022. {
  1023. const TType& type = variable.getType();
  1024. // If it's a standalone built-in, there is nothing to flatten
  1025. if (type.isBuiltIn() && !type.isStruct())
  1026. return;
  1027. auto entry = flattenMap.insert(std::make_pair(variable.getUniqueId(),
  1028. TFlattenData(type.getQualifier().layoutBinding,
  1029. type.getQualifier().layoutLocation)));
  1030. // the item is a map pair, so first->second is the TFlattenData itself.
  1031. flatten(variable, type, entry.first->second, variable.getName(), linkage, type.getQualifier(), nullptr);
  1032. }
  1033. // Recursively flatten the given variable at the provided type, building the flattenData as we go.
  1034. //
  1035. // This is mutually recursive with flattenStruct and flattenArray.
  1036. // We are going to flatten an arbitrarily nested composite structure into a linear sequence of
  1037. // members, and later on, we want to turn a path through the tree structure into a final
  1038. // location in this linear sequence.
  1039. //
  1040. // If the tree was N-ary, that can be directly calculated. However, we are dealing with
  1041. // arbitrary numbers - perhaps a struct of 7 members containing an array of 3. Thus, we must
  1042. // build a data structure to allow the sequence of bracket and dot operators on arrays and
  1043. // structs to arrive at the proper member.
  1044. //
  1045. // To avoid storing a tree with pointers, we are going to flatten the tree into a vector of integers.
  1046. // The leaves are the indexes into the flattened member array.
  1047. // Each level will have the next location for the Nth item stored sequentially, so for instance:
  1048. //
  1049. // struct { float2 a[2]; int b; float4 c[3] };
  1050. //
  1051. // This will produce the following flattened tree:
  1052. // Pos: 0 1 2 3 4 5 6 7 8 9 10 11 12 13
  1053. // (3, 7, 8, 5, 6, 0, 1, 2, 11, 12, 13, 3, 4, 5}
  1054. //
  1055. // Given a reference to mystruct.c[1], the access chain is (2,1), so we traverse:
  1056. // (0+2) = 8 --> (8+1) = 12 --> 12 = 4
  1057. //
  1058. // so the 4th flattened member in traversal order is ours.
  1059. //
  1060. int HlslParseContext::flatten(const TVariable& variable, const TType& type,
  1061. TFlattenData& flattenData, TString name, bool linkage,
  1062. const TQualifier& outerQualifier,
  1063. const TArraySizes* builtInArraySizes)
  1064. {
  1065. // If something is an arrayed struct, the array flattener will recursively call flatten()
  1066. // to then flatten the struct, so this is an "if else": we don't do both.
  1067. if (type.isArray())
  1068. return flattenArray(variable, type, flattenData, name, linkage, outerQualifier);
  1069. else if (type.isStruct())
  1070. return flattenStruct(variable, type, flattenData, name, linkage, outerQualifier, builtInArraySizes);
  1071. else {
  1072. assert(0); // should never happen
  1073. return -1;
  1074. }
  1075. }
  1076. // Add a single flattened member to the flattened data being tracked for the composite
  1077. // Returns true for the final flattening level.
  1078. int HlslParseContext::addFlattenedMember(const TVariable& variable, const TType& type, TFlattenData& flattenData,
  1079. const TString& memberName, bool linkage,
  1080. const TQualifier& outerQualifier,
  1081. const TArraySizes* builtInArraySizes)
  1082. {
  1083. if (!shouldFlatten(type, outerQualifier.storage, false)) {
  1084. // This is as far as we flatten. Insert the variable.
  1085. TVariable* memberVariable = makeInternalVariable(memberName, type);
  1086. mergeQualifiers(memberVariable->getWritableType().getQualifier(), variable.getType().getQualifier());
  1087. if (flattenData.nextBinding != TQualifier::layoutBindingEnd)
  1088. memberVariable->getWritableType().getQualifier().layoutBinding = flattenData.nextBinding++;
  1089. if (memberVariable->getType().isBuiltIn()) {
  1090. // inherited locations are nonsensical for built-ins (TODO: what if semantic had a number)
  1091. memberVariable->getWritableType().getQualifier().layoutLocation = TQualifier::layoutLocationEnd;
  1092. } else {
  1093. // inherited locations must be auto bumped, not replicated
  1094. if (flattenData.nextLocation != TQualifier::layoutLocationEnd) {
  1095. memberVariable->getWritableType().getQualifier().layoutLocation = flattenData.nextLocation;
  1096. flattenData.nextLocation += intermediate.computeTypeLocationSize(memberVariable->getType(), language);
  1097. nextOutLocation = std::max(nextOutLocation, flattenData.nextLocation);
  1098. }
  1099. }
  1100. flattenData.offsets.push_back(static_cast<int>(flattenData.members.size()));
  1101. flattenData.members.push_back(memberVariable);
  1102. if (linkage)
  1103. trackLinkage(*memberVariable);
  1104. return static_cast<int>(flattenData.offsets.size()) - 1; // location of the member reference
  1105. } else {
  1106. // Further recursion required
  1107. return flatten(variable, type, flattenData, memberName, linkage, outerQualifier, builtInArraySizes);
  1108. }
  1109. }
  1110. // Figure out the mapping between an aggregate's top members and an
  1111. // equivalent set of individual variables.
  1112. //
  1113. // Assumes shouldFlatten() or equivalent was called first.
  1114. int HlslParseContext::flattenStruct(const TVariable& variable, const TType& type,
  1115. TFlattenData& flattenData, TString name, bool linkage,
  1116. const TQualifier& outerQualifier,
  1117. const TArraySizes* builtInArraySizes)
  1118. {
  1119. assert(type.isStruct());
  1120. auto members = *type.getStruct();
  1121. // Reserve space for this tree level.
  1122. int start = static_cast<int>(flattenData.offsets.size());
  1123. int pos = start;
  1124. flattenData.offsets.resize(int(pos + members.size()), -1);
  1125. for (int member = 0; member < (int)members.size(); ++member) {
  1126. TType& dereferencedType = *members[member].type;
  1127. if (dereferencedType.isBuiltIn())
  1128. splitBuiltIn(variable.getName(), dereferencedType, builtInArraySizes, outerQualifier);
  1129. else {
  1130. const int mpos = addFlattenedMember(variable, dereferencedType, flattenData,
  1131. name + "." + dereferencedType.getFieldName(),
  1132. linkage, outerQualifier,
  1133. builtInArraySizes == nullptr && dereferencedType.isArray()
  1134. ? dereferencedType.getArraySizes()
  1135. : builtInArraySizes);
  1136. flattenData.offsets[pos++] = mpos;
  1137. }
  1138. }
  1139. return start;
  1140. }
  1141. // Figure out mapping between an array's members and an
  1142. // equivalent set of individual variables.
  1143. //
  1144. // Assumes shouldFlatten() or equivalent was called first.
  1145. int HlslParseContext::flattenArray(const TVariable& variable, const TType& type,
  1146. TFlattenData& flattenData, TString name, bool linkage,
  1147. const TQualifier& outerQualifier)
  1148. {
  1149. assert(type.isSizedArray());
  1150. const int size = type.getOuterArraySize();
  1151. const TType dereferencedType(type, 0);
  1152. if (name.empty())
  1153. name = variable.getName();
  1154. // Reserve space for this tree level.
  1155. int start = static_cast<int>(flattenData.offsets.size());
  1156. int pos = start;
  1157. flattenData.offsets.resize(int(pos + size), -1);
  1158. for (int element=0; element < size; ++element) {
  1159. char elementNumBuf[20]; // sufficient for MAXINT
  1160. snprintf(elementNumBuf, sizeof(elementNumBuf)-1, "[%d]", element);
  1161. const int mpos = addFlattenedMember(variable, dereferencedType, flattenData,
  1162. name + elementNumBuf, linkage, outerQualifier,
  1163. type.getArraySizes());
  1164. flattenData.offsets[pos++] = mpos;
  1165. }
  1166. return start;
  1167. }
  1168. // Return true if we have flattened this node.
  1169. bool HlslParseContext::wasFlattened(const TIntermTyped* node) const
  1170. {
  1171. return node != nullptr && node->getAsSymbolNode() != nullptr &&
  1172. wasFlattened(node->getAsSymbolNode()->getId());
  1173. }
  1174. // Return true if we have split this structure
  1175. bool HlslParseContext::wasSplit(const TIntermTyped* node) const
  1176. {
  1177. return node != nullptr && node->getAsSymbolNode() != nullptr &&
  1178. wasSplit(node->getAsSymbolNode()->getId());
  1179. }
  1180. // Turn an access into an aggregate that was flattened to instead be
  1181. // an access to the individual variable the member was flattened to.
  1182. // Assumes wasFlattened() or equivalent was called first.
  1183. TIntermTyped* HlslParseContext::flattenAccess(TIntermTyped* base, int member)
  1184. {
  1185. const TType dereferencedType(base->getType(), member); // dereferenced type
  1186. const TIntermSymbol& symbolNode = *base->getAsSymbolNode();
  1187. TIntermTyped* flattened = flattenAccess(symbolNode.getId(), member, base->getQualifier().storage,
  1188. dereferencedType, symbolNode.getFlattenSubset());
  1189. return flattened ? flattened : base;
  1190. }
  1191. TIntermTyped* HlslParseContext::flattenAccess(int uniqueId, int member, TStorageQualifier outerStorage,
  1192. const TType& dereferencedType, int subset)
  1193. {
  1194. const auto flattenData = flattenMap.find(uniqueId);
  1195. if (flattenData == flattenMap.end())
  1196. return nullptr;
  1197. // Calculate new cumulative offset from the packed tree
  1198. int newSubset = flattenData->second.offsets[subset >= 0 ? subset + member : member];
  1199. TIntermSymbol* subsetSymbol;
  1200. if (!shouldFlatten(dereferencedType, outerStorage, false)) {
  1201. // Finished flattening: create symbol for variable
  1202. member = flattenData->second.offsets[newSubset];
  1203. const TVariable* memberVariable = flattenData->second.members[member];
  1204. subsetSymbol = intermediate.addSymbol(*memberVariable);
  1205. subsetSymbol->setFlattenSubset(-1);
  1206. } else {
  1207. // If this is not the final flattening, accumulate the position and return
  1208. // an object of the partially dereferenced type.
  1209. subsetSymbol = new TIntermSymbol(uniqueId, "flattenShadow", dereferencedType);
  1210. subsetSymbol->setFlattenSubset(newSubset);
  1211. }
  1212. return subsetSymbol;
  1213. }
  1214. // For finding where the first leaf is in a subtree of a multi-level aggregate
  1215. // that is just getting a subset assigned. Follows the same logic as flattenAccess,
  1216. // but logically going down the "left-most" tree branch each step of the way.
  1217. //
  1218. // Returns the offset into the first leaf of the subset.
  1219. int HlslParseContext::findSubtreeOffset(const TIntermNode& node) const
  1220. {
  1221. const TIntermSymbol* sym = node.getAsSymbolNode();
  1222. if (sym == nullptr)
  1223. return 0;
  1224. if (!sym->isArray() && !sym->isStruct())
  1225. return 0;
  1226. int subset = sym->getFlattenSubset();
  1227. if (subset == -1)
  1228. return 0;
  1229. // Getting this far means a partial aggregate is identified by the flatten subset.
  1230. // Find the first leaf of the subset.
  1231. const auto flattenData = flattenMap.find(sym->getId());
  1232. if (flattenData == flattenMap.end())
  1233. return 0;
  1234. return findSubtreeOffset(sym->getType(), subset, flattenData->second.offsets);
  1235. do {
  1236. subset = flattenData->second.offsets[subset];
  1237. } while (true);
  1238. }
  1239. // Recursively do the desent
  1240. int HlslParseContext::findSubtreeOffset(const TType& type, int subset, const TVector<int>& offsets) const
  1241. {
  1242. if (!type.isArray() && !type.isStruct())
  1243. return offsets[subset];
  1244. TType derefType(type, 0);
  1245. return findSubtreeOffset(derefType, offsets[subset], offsets);
  1246. };
  1247. // Find and return the split IO TVariable for id, or nullptr if none.
  1248. TVariable* HlslParseContext::getSplitNonIoVar(int id) const
  1249. {
  1250. const auto splitNonIoVar = splitNonIoVars.find(id);
  1251. if (splitNonIoVar == splitNonIoVars.end())
  1252. return nullptr;
  1253. return splitNonIoVar->second;
  1254. }
  1255. // Pass through to base class after remembering built-in mappings.
  1256. void HlslParseContext::trackLinkage(TSymbol& symbol)
  1257. {
  1258. TBuiltInVariable biType = symbol.getType().getQualifier().builtIn;
  1259. if (biType != EbvNone)
  1260. builtInTessLinkageSymbols[biType] = symbol.clone();
  1261. TParseContextBase::trackLinkage(symbol);
  1262. }
  1263. // Returns true if the built-in is a clip or cull distance variable.
  1264. bool HlslParseContext::isClipOrCullDistance(TBuiltInVariable builtIn)
  1265. {
  1266. return builtIn == EbvClipDistance || builtIn == EbvCullDistance;
  1267. }
  1268. // Some types require fixed array sizes in SPIR-V, but can be scalars or
  1269. // arrays of sizes SPIR-V doesn't allow. For example, tessellation factors.
  1270. // This creates the right size. A conversion is performed when the internal
  1271. // type is copied to or from the external type. This corrects the externally
  1272. // facing input or output type to abide downstream semantics.
  1273. void HlslParseContext::fixBuiltInIoType(TType& type)
  1274. {
  1275. int requiredArraySize = 0;
  1276. int requiredVectorSize = 0;
  1277. switch (type.getQualifier().builtIn) {
  1278. case EbvTessLevelOuter: requiredArraySize = 4; break;
  1279. case EbvTessLevelInner: requiredArraySize = 2; break;
  1280. case EbvSampleMask:
  1281. {
  1282. // Promote scalar to array of size 1. Leave existing arrays alone.
  1283. if (!type.isArray())
  1284. requiredArraySize = 1;
  1285. break;
  1286. }
  1287. case EbvWorkGroupId: requiredVectorSize = 3; break;
  1288. case EbvGlobalInvocationId: requiredVectorSize = 3; break;
  1289. case EbvLocalInvocationId: requiredVectorSize = 3; break;
  1290. case EbvTessCoord: requiredVectorSize = 3; break;
  1291. default:
  1292. if (isClipOrCullDistance(type)) {
  1293. const int loc = type.getQualifier().layoutLocation;
  1294. if (type.getQualifier().builtIn == EbvClipDistance) {
  1295. if (type.getQualifier().storage == EvqVaryingIn)
  1296. clipSemanticNSizeIn[loc] = type.getVectorSize();
  1297. else
  1298. clipSemanticNSizeOut[loc] = type.getVectorSize();
  1299. } else {
  1300. if (type.getQualifier().storage == EvqVaryingIn)
  1301. cullSemanticNSizeIn[loc] = type.getVectorSize();
  1302. else
  1303. cullSemanticNSizeOut[loc] = type.getVectorSize();
  1304. }
  1305. }
  1306. return;
  1307. }
  1308. // Alter or set vector size as needed.
  1309. if (requiredVectorSize > 0) {
  1310. TType newType(type.getBasicType(), type.getQualifier().storage, requiredVectorSize);
  1311. newType.getQualifier() = type.getQualifier();
  1312. type.shallowCopy(newType);
  1313. }
  1314. // Alter or set array size as needed.
  1315. if (requiredArraySize > 0) {
  1316. if (!type.isArray() || type.getOuterArraySize() != requiredArraySize) {
  1317. TArraySizes* arraySizes = new TArraySizes;
  1318. arraySizes->addInnerSize(requiredArraySize);
  1319. type.transferArraySizes(arraySizes);
  1320. }
  1321. }
  1322. }
  1323. // Variables that correspond to the user-interface in and out of a stage
  1324. // (not the built-in interface) are
  1325. // - assigned locations
  1326. // - registered as a linkage node (part of the stage's external interface).
  1327. // Assumes it is called in the order in which locations should be assigned.
  1328. void HlslParseContext::assignToInterface(TVariable& variable)
  1329. {
  1330. const auto assignLocation = [&](TVariable& variable) {
  1331. TType& type = variable.getWritableType();
  1332. if (!type.isStruct() || type.getStruct()->size() > 0) {
  1333. TQualifier& qualifier = type.getQualifier();
  1334. if (qualifier.storage == EvqVaryingIn || qualifier.storage == EvqVaryingOut) {
  1335. if (qualifier.builtIn == EbvNone && !qualifier.hasLocation()) {
  1336. // Strip off the outer array dimension for those having an extra one.
  1337. int size;
  1338. if (type.isArray() && qualifier.isArrayedIo(language)) {
  1339. TType elementType(type, 0);
  1340. size = intermediate.computeTypeLocationSize(elementType, language);
  1341. } else
  1342. size = intermediate.computeTypeLocationSize(type, language);
  1343. if (qualifier.storage == EvqVaryingIn) {
  1344. variable.getWritableType().getQualifier().layoutLocation = nextInLocation;
  1345. nextInLocation += size;
  1346. } else {
  1347. variable.getWritableType().getQualifier().layoutLocation = nextOutLocation;
  1348. nextOutLocation += size;
  1349. }
  1350. }
  1351. trackLinkage(variable);
  1352. }
  1353. }
  1354. };
  1355. if (wasFlattened(variable.getUniqueId())) {
  1356. auto& memberList = flattenMap[variable.getUniqueId()].members;
  1357. for (auto member = memberList.begin(); member != memberList.end(); ++member)
  1358. assignLocation(**member);
  1359. } else if (wasSplit(variable.getUniqueId())) {
  1360. TVariable* splitIoVar = getSplitNonIoVar(variable.getUniqueId());
  1361. assignLocation(*splitIoVar);
  1362. } else {
  1363. assignLocation(variable);
  1364. }
  1365. }
  1366. //
  1367. // Handle seeing a function declarator in the grammar. This is the precursor
  1368. // to recognizing a function prototype or function definition.
  1369. //
  1370. void HlslParseContext::handleFunctionDeclarator(const TSourceLoc& loc, TFunction& function, bool prototype)
  1371. {
  1372. //
  1373. // Multiple declarations of the same function name are allowed.
  1374. //
  1375. // If this is a definition, the definition production code will check for redefinitions
  1376. // (we don't know at this point if it's a definition or not).
  1377. //
  1378. bool builtIn;
  1379. TSymbol* symbol = symbolTable.find(function.getMangledName(), &builtIn);
  1380. const TFunction* prevDec = symbol ? symbol->getAsFunction() : 0;
  1381. if (prototype) {
  1382. // All built-in functions are defined, even though they don't have a body.
  1383. // Count their prototype as a definition instead.
  1384. if (symbolTable.atBuiltInLevel())
  1385. function.setDefined();
  1386. else {
  1387. if (prevDec && ! builtIn)
  1388. symbol->getAsFunction()->setPrototyped(); // need a writable one, but like having prevDec as a const
  1389. function.setPrototyped();
  1390. }
  1391. }
  1392. // This insert won't actually insert it if it's a duplicate signature, but it will still check for
  1393. // other forms of name collisions.
  1394. if (! symbolTable.insert(function))
  1395. error(loc, "function name is redeclaration of existing name", function.getName().c_str(), "");
  1396. }
  1397. // For struct buffers with counters, we must pass the counter buffer as hidden parameter.
  1398. // This adds the hidden parameter to the parameter list in 'paramNodes' if needed.
  1399. // Otherwise, it's a no-op
  1400. void HlslParseContext::addStructBufferHiddenCounterParam(const TSourceLoc& loc, TParameter& param,
  1401. TIntermAggregate*& paramNodes)
  1402. {
  1403. if (! hasStructBuffCounter(*param.type))
  1404. return;
  1405. const TString counterBlockName(intermediate.addCounterBufferName(*param.name));
  1406. TType counterType;
  1407. counterBufferType(loc, counterType);
  1408. TVariable *variable = makeInternalVariable(counterBlockName, counterType);
  1409. if (! symbolTable.insert(*variable))
  1410. error(loc, "redefinition", variable->getName().c_str(), "");
  1411. paramNodes = intermediate.growAggregate(paramNodes,
  1412. intermediate.addSymbol(*variable, loc),
  1413. loc);
  1414. }
  1415. //
  1416. // Handle seeing the function prototype in front of a function definition in the grammar.
  1417. // The body is handled after this function returns.
  1418. //
  1419. // Returns an aggregate of parameter-symbol nodes.
  1420. //
  1421. TIntermAggregate* HlslParseContext::handleFunctionDefinition(const TSourceLoc& loc, TFunction& function,
  1422. const TAttributes& attributes,
  1423. TIntermNode*& entryPointTree)
  1424. {
  1425. currentCaller = function.getMangledName();
  1426. TSymbol* symbol = symbolTable.find(function.getMangledName());
  1427. TFunction* prevDec = symbol ? symbol->getAsFunction() : nullptr;
  1428. if (prevDec == nullptr)
  1429. error(loc, "can't find function", function.getName().c_str(), "");
  1430. // Note: 'prevDec' could be 'function' if this is the first time we've seen function
  1431. // as it would have just been put in the symbol table. Otherwise, we're looking up
  1432. // an earlier occurrence.
  1433. if (prevDec && prevDec->isDefined()) {
  1434. // Then this function already has a body.
  1435. error(loc, "function already has a body", function.getName().c_str(), "");
  1436. }
  1437. if (prevDec && ! prevDec->isDefined()) {
  1438. prevDec->setDefined();
  1439. // Remember the return type for later checking for RETURN statements.
  1440. currentFunctionType = &(prevDec->getType());
  1441. } else
  1442. currentFunctionType = new TType(EbtVoid);
  1443. functionReturnsValue = false;
  1444. // Entry points need different I/O and other handling, transform it so the
  1445. // rest of this function doesn't care.
  1446. entryPointTree = transformEntryPoint(loc, function, attributes);
  1447. //
  1448. // New symbol table scope for body of function plus its arguments
  1449. //
  1450. pushScope();
  1451. //
  1452. // Insert parameters into the symbol table.
  1453. // If the parameter has no name, it's not an error, just don't insert it
  1454. // (could be used for unused args).
  1455. //
  1456. // Also, accumulate the list of parameters into the AST, so lower level code
  1457. // knows where to find parameters.
  1458. //
  1459. TIntermAggregate* paramNodes = new TIntermAggregate;
  1460. for (int i = 0; i < function.getParamCount(); i++) {
  1461. TParameter& param = function[i];
  1462. if (param.name != nullptr) {
  1463. TVariable *variable = new TVariable(param.name, *param.type);
  1464. if (i == 0 && function.hasImplicitThis()) {
  1465. // Anonymous 'this' members are already in a symbol-table level,
  1466. // and we need to know what function parameter to map them to.
  1467. symbolTable.makeInternalVariable(*variable);
  1468. pushImplicitThis(variable);
  1469. }
  1470. // Insert the parameters with name in the symbol table.
  1471. if (! symbolTable.insert(*variable))
  1472. error(loc, "redefinition", variable->getName().c_str(), "");
  1473. // Add parameters to the AST list.
  1474. if (shouldFlatten(variable->getType(), variable->getType().getQualifier().storage, true)) {
  1475. // Expand the AST parameter nodes (but not the name mangling or symbol table view)
  1476. // for structures that need to be flattened.
  1477. flatten(*variable, false);
  1478. const TTypeList* structure = variable->getType().getStruct();
  1479. for (int mem = 0; mem < (int)structure->size(); ++mem) {
  1480. paramNodes = intermediate.growAggregate(paramNodes,
  1481. flattenAccess(variable->getUniqueId(), mem,
  1482. variable->getType().getQualifier().storage,
  1483. *(*structure)[mem].type),
  1484. loc);
  1485. }
  1486. } else {
  1487. // Add the parameter to the AST
  1488. paramNodes = intermediate.growAggregate(paramNodes,
  1489. intermediate.addSymbol(*variable, loc),
  1490. loc);
  1491. }
  1492. // Add hidden AST parameter for struct buffer counters, if needed.
  1493. addStructBufferHiddenCounterParam(loc, param, paramNodes);
  1494. } else
  1495. paramNodes = intermediate.growAggregate(paramNodes, intermediate.addSymbol(*param.type, loc), loc);
  1496. }
  1497. if (function.hasIllegalImplicitThis())
  1498. pushImplicitThis(nullptr);
  1499. intermediate.setAggregateOperator(paramNodes, EOpParameters, TType(EbtVoid), loc);
  1500. loopNestingLevel = 0;
  1501. controlFlowNestingLevel = 0;
  1502. postEntryPointReturn = false;
  1503. return paramNodes;
  1504. }
  1505. // Handle all [attrib] attribute for the shader entry point
  1506. void HlslParseContext::handleEntryPointAttributes(const TSourceLoc& loc, const TAttributes& attributes)
  1507. {
  1508. for (auto it = attributes.begin(); it != attributes.end(); ++it) {
  1509. switch (it->name) {
  1510. case EatNumThreads:
  1511. {
  1512. const TIntermSequence& sequence = it->args->getSequence();
  1513. for (int lid = 0; lid < int(sequence.size()); ++lid)
  1514. intermediate.setLocalSize(lid, sequence[lid]->getAsConstantUnion()->getConstArray()[0].getIConst());
  1515. break;
  1516. }
  1517. case EatMaxVertexCount:
  1518. {
  1519. int maxVertexCount;
  1520. if (! it->getInt(maxVertexCount)) {
  1521. error(loc, "invalid maxvertexcount", "", "");
  1522. } else {
  1523. if (! intermediate.setVertices(maxVertexCount))
  1524. error(loc, "cannot change previously set maxvertexcount attribute", "", "");
  1525. }
  1526. break;
  1527. }
  1528. case EatPatchConstantFunc:
  1529. {
  1530. TString pcfName;
  1531. if (! it->getString(pcfName, 0, false)) {
  1532. error(loc, "invalid patch constant function", "", "");
  1533. } else {
  1534. patchConstantFunctionName = pcfName;
  1535. }
  1536. break;
  1537. }
  1538. case EatDomain:
  1539. {
  1540. // Handle [domain("...")]
  1541. TString domainStr;
  1542. if (! it->getString(domainStr)) {
  1543. error(loc, "invalid domain", "", "");
  1544. } else {
  1545. TLayoutGeometry domain = ElgNone;
  1546. if (domainStr == "tri") {
  1547. domain = ElgTriangles;
  1548. } else if (domainStr == "quad") {
  1549. domain = ElgQuads;
  1550. } else if (domainStr == "isoline") {
  1551. domain = ElgIsolines;
  1552. } else {
  1553. error(loc, "unsupported domain type", domainStr.c_str(), "");
  1554. }
  1555. if (language == EShLangTessEvaluation) {
  1556. if (! intermediate.setInputPrimitive(domain))
  1557. error(loc, "cannot change previously set domain", TQualifier::getGeometryString(domain), "");
  1558. } else {
  1559. if (! intermediate.setOutputPrimitive(domain))
  1560. error(loc, "cannot change previously set domain", TQualifier::getGeometryString(domain), "");
  1561. }
  1562. }
  1563. break;
  1564. }
  1565. case EatOutputTopology:
  1566. {
  1567. // Handle [outputtopology("...")]
  1568. TString topologyStr;
  1569. if (! it->getString(topologyStr)) {
  1570. error(loc, "invalid outputtopology", "", "");
  1571. } else {
  1572. TVertexOrder vertexOrder = EvoNone;
  1573. TLayoutGeometry primitive = ElgNone;
  1574. if (topologyStr == "point") {
  1575. intermediate.setPointMode();
  1576. } else if (topologyStr == "line") {
  1577. primitive = ElgIsolines;
  1578. } else if (topologyStr == "triangle_cw") {
  1579. vertexOrder = EvoCw;
  1580. primitive = ElgTriangles;
  1581. } else if (topologyStr == "triangle_ccw") {
  1582. vertexOrder = EvoCcw;
  1583. primitive = ElgTriangles;
  1584. } else {
  1585. error(loc, "unsupported outputtopology type", topologyStr.c_str(), "");
  1586. }
  1587. if (vertexOrder != EvoNone) {
  1588. if (! intermediate.setVertexOrder(vertexOrder)) {
  1589. error(loc, "cannot change previously set outputtopology",
  1590. TQualifier::getVertexOrderString(vertexOrder), "");
  1591. }
  1592. }
  1593. if (primitive != ElgNone)
  1594. intermediate.setOutputPrimitive(primitive);
  1595. }
  1596. break;
  1597. }
  1598. case EatPartitioning:
  1599. {
  1600. // Handle [partitioning("...")]
  1601. TString partitionStr;
  1602. if (! it->getString(partitionStr)) {
  1603. error(loc, "invalid partitioning", "", "");
  1604. } else {
  1605. TVertexSpacing partitioning = EvsNone;
  1606. if (partitionStr == "integer") {
  1607. partitioning = EvsEqual;
  1608. } else if (partitionStr == "fractional_even") {
  1609. partitioning = EvsFractionalEven;
  1610. } else if (partitionStr == "fractional_odd") {
  1611. partitioning = EvsFractionalOdd;
  1612. //} else if (partition == "pow2") { // TODO: currently nothing to map this to.
  1613. } else {
  1614. error(loc, "unsupported partitioning type", partitionStr.c_str(), "");
  1615. }
  1616. if (! intermediate.setVertexSpacing(partitioning))
  1617. error(loc, "cannot change previously set partitioning",
  1618. TQualifier::getVertexSpacingString(partitioning), "");
  1619. }
  1620. break;
  1621. }
  1622. case EatOutputControlPoints:
  1623. {
  1624. // Handle [outputcontrolpoints("...")]
  1625. int ctrlPoints;
  1626. if (! it->getInt(ctrlPoints)) {
  1627. error(loc, "invalid outputcontrolpoints", "", "");
  1628. } else {
  1629. if (! intermediate.setVertices(ctrlPoints)) {
  1630. error(loc, "cannot change previously set outputcontrolpoints attribute", "", "");
  1631. }
  1632. }
  1633. break;
  1634. }
  1635. case EatEarlyDepthStencil:
  1636. intermediate.setEarlyFragmentTests();
  1637. break;
  1638. case EatBuiltIn:
  1639. case EatLocation:
  1640. // tolerate these because of dual use of entrypoint and type attributes
  1641. break;
  1642. default:
  1643. warn(loc, "attribute does not apply to entry point", "", "");
  1644. break;
  1645. }
  1646. }
  1647. }
  1648. // Update the given type with any type-like attribute information in the
  1649. // attributes.
  1650. void HlslParseContext::transferTypeAttributes(const TSourceLoc& loc, const TAttributes& attributes, TType& type,
  1651. bool allowEntry)
  1652. {
  1653. if (attributes.size() == 0)
  1654. return;
  1655. int value;
  1656. TString builtInString;
  1657. for (auto it = attributes.begin(); it != attributes.end(); ++it) {
  1658. switch (it->name) {
  1659. case EatLocation:
  1660. // location
  1661. if (it->getInt(value))
  1662. type.getQualifier().layoutLocation = value;
  1663. else
  1664. error(loc, "needs a literal integer", "location", "");
  1665. break;
  1666. case EatBinding:
  1667. // binding
  1668. if (it->getInt(value)) {
  1669. type.getQualifier().layoutBinding = value;
  1670. type.getQualifier().layoutSet = 0;
  1671. } else
  1672. error(loc, "needs a literal integer", "binding", "");
  1673. // set
  1674. if (it->getInt(value, 1))
  1675. type.getQualifier().layoutSet = value;
  1676. break;
  1677. case EatGlobalBinding:
  1678. // global cbuffer binding
  1679. if (it->getInt(value))
  1680. globalUniformBinding = value;
  1681. else
  1682. error(loc, "needs a literal integer", "global binding", "");
  1683. // global cbuffer set
  1684. if (it->getInt(value, 1))
  1685. globalUniformSet = value;
  1686. break;
  1687. case EatInputAttachment:
  1688. // input attachment
  1689. if (it->getInt(value))
  1690. type.getQualifier().layoutAttachment = value;
  1691. else
  1692. error(loc, "needs a literal integer", "input attachment", "");
  1693. break;
  1694. case EatBuiltIn:
  1695. // PointSize built-in
  1696. if (it->getString(builtInString, 0, false)) {
  1697. if (builtInString == "PointSize")
  1698. type.getQualifier().builtIn = EbvPointSize;
  1699. }
  1700. break;
  1701. case EatPushConstant:
  1702. // push_constant
  1703. type.getQualifier().layoutPushConstant = true;
  1704. break;
  1705. case EatConstantId:
  1706. // specialization constant
  1707. if (it->getInt(value)) {
  1708. TSourceLoc loc;
  1709. loc.init();
  1710. setSpecConstantId(loc, type.getQualifier(), value);
  1711. }
  1712. break;
  1713. // image formats
  1714. case EatFormatRgba32f: type.getQualifier().layoutFormat = ElfRgba32f; break;
  1715. case EatFormatRgba16f: type.getQualifier().layoutFormat = ElfRgba16f; break;
  1716. case EatFormatR32f: type.getQualifier().layoutFormat = ElfR32f; break;
  1717. case EatFormatRgba8: type.getQualifier().layoutFormat = ElfRgba8; break;
  1718. case EatFormatRgba8Snorm: type.getQualifier().layoutFormat = ElfRgba8Snorm; break;
  1719. case EatFormatRg32f: type.getQualifier().layoutFormat = ElfRg32f; break;
  1720. case EatFormatRg16f: type.getQualifier().layoutFormat = ElfRg16f; break;
  1721. case EatFormatR11fG11fB10f: type.getQualifier().layoutFormat = ElfR11fG11fB10f; break;
  1722. case EatFormatR16f: type.getQualifier().layoutFormat = ElfR16f; break;
  1723. case EatFormatRgba16: type.getQualifier().layoutFormat = ElfRgba16; break;
  1724. case EatFormatRgb10A2: type.getQualifier().layoutFormat = ElfRgb10A2; break;
  1725. case EatFormatRg16: type.getQualifier().layoutFormat = ElfRg16; break;
  1726. case EatFormatRg8: type.getQualifier().layoutFormat = ElfRg8; break;
  1727. case EatFormatR16: type.getQualifier().layoutFormat = ElfR16; break;
  1728. case EatFormatR8: type.getQualifier().layoutFormat = ElfR8; break;
  1729. case EatFormatRgba16Snorm: type.getQualifier().layoutFormat = ElfRgba16Snorm; break;
  1730. case EatFormatRg16Snorm: type.getQualifier().layoutFormat = ElfRg16Snorm; break;
  1731. case EatFormatRg8Snorm: type.getQualifier().layoutFormat = ElfRg8Snorm; break;
  1732. case EatFormatR16Snorm: type.getQualifier().layoutFormat = ElfR16Snorm; break;
  1733. case EatFormatR8Snorm: type.getQualifier().layoutFormat = ElfR8Snorm; break;
  1734. case EatFormatRgba32i: type.getQualifier().layoutFormat = ElfRgba32i; break;
  1735. case EatFormatRgba16i: type.getQualifier().layoutFormat = ElfRgba16i; break;
  1736. case EatFormatRgba8i: type.getQualifier().layoutFormat = ElfRgba8i; break;
  1737. case EatFormatR32i: type.getQualifier().layoutFormat = ElfR32i; break;
  1738. case EatFormatRg32i: type.getQualifier().layoutFormat = ElfRg32i; break;
  1739. case EatFormatRg16i: type.getQualifier().layoutFormat = ElfRg16i; break;
  1740. case EatFormatRg8i: type.getQualifier().layoutFormat = ElfRg8i; break;
  1741. case EatFormatR16i: type.getQualifier().layoutFormat = ElfR16i; break;
  1742. case EatFormatR8i: type.getQualifier().layoutFormat = ElfR8i; break;
  1743. case EatFormatRgba32ui: type.getQualifier().layoutFormat = ElfRgba32ui; break;
  1744. case EatFormatRgba16ui: type.getQualifier().layoutFormat = ElfRgba16ui; break;
  1745. case EatFormatRgba8ui: type.getQualifier().layoutFormat = ElfRgba8ui; break;
  1746. case EatFormatR32ui: type.getQualifier().layoutFormat = ElfR32ui; break;
  1747. case EatFormatRgb10a2ui: type.getQualifier().layoutFormat = ElfRgb10a2ui; break;
  1748. case EatFormatRg32ui: type.getQualifier().layoutFormat = ElfRg32ui; break;
  1749. case EatFormatRg16ui: type.getQualifier().layoutFormat = ElfRg16ui; break;
  1750. case EatFormatRg8ui: type.getQualifier().layoutFormat = ElfRg8ui; break;
  1751. case EatFormatR16ui: type.getQualifier().layoutFormat = ElfR16ui; break;
  1752. case EatFormatR8ui: type.getQualifier().layoutFormat = ElfR8ui; break;
  1753. case EatFormatUnknown: type.getQualifier().layoutFormat = ElfNone; break;
  1754. case EatNonWritable: type.getQualifier().readonly = true; break;
  1755. case EatNonReadable: type.getQualifier().writeonly = true; break;
  1756. default:
  1757. if (! allowEntry)
  1758. warn(loc, "attribute does not apply to a type", "", "");
  1759. break;
  1760. }
  1761. }
  1762. }
  1763. //
  1764. // Do all special handling for the entry point, including wrapping
  1765. // the shader's entry point with the official entry point that will call it.
  1766. //
  1767. // The following:
  1768. //
  1769. // retType shaderEntryPoint(args...) // shader declared entry point
  1770. // { body }
  1771. //
  1772. // Becomes
  1773. //
  1774. // out retType ret;
  1775. // in iargs<that are input>...;
  1776. // out oargs<that are output> ...;
  1777. //
  1778. // void shaderEntryPoint() // synthesized, but official, entry point
  1779. // {
  1780. // args<that are input> = iargs...;
  1781. // ret = @shaderEntryPoint(args...);
  1782. // oargs = args<that are output>...;
  1783. // }
  1784. // retType @shaderEntryPoint(args...)
  1785. // { body }
  1786. //
  1787. // The symbol table will still map the original entry point name to the
  1788. // the modified function and its new name:
  1789. //
  1790. // symbol table: shaderEntryPoint -> @shaderEntryPoint
  1791. //
  1792. // Returns nullptr if no entry-point tree was built, otherwise, returns
  1793. // a subtree that creates the entry point.
  1794. //
  1795. TIntermNode* HlslParseContext::transformEntryPoint(const TSourceLoc& loc, TFunction& userFunction,
  1796. const TAttributes& attributes)
  1797. {
  1798. // Return true if this is a tessellation patch constant function input to a domain shader.
  1799. const auto isDsPcfInput = [this](const TType& type) {
  1800. return language == EShLangTessEvaluation &&
  1801. type.contains([](const TType* t) {
  1802. return t->getQualifier().builtIn == EbvTessLevelOuter ||
  1803. t->getQualifier().builtIn == EbvTessLevelInner;
  1804. });
  1805. };
  1806. // if we aren't in the entry point, fix the IO as such and exit
  1807. if (! isEntrypointName(userFunction.getName())) {
  1808. remapNonEntryPointIO(userFunction);
  1809. return nullptr;
  1810. }
  1811. entryPointFunction = &userFunction; // needed in finish()
  1812. // Handle entry point attributes
  1813. handleEntryPointAttributes(loc, attributes);
  1814. // entry point logic...
  1815. // Move parameters and return value to shader in/out
  1816. TVariable* entryPointOutput; // gets created in remapEntryPointIO
  1817. TVector<TVariable*> inputs;
  1818. TVector<TVariable*> outputs;
  1819. remapEntryPointIO(userFunction, entryPointOutput, inputs, outputs);
  1820. // Further this return/in/out transform by flattening, splitting, and assigning locations
  1821. const auto makeVariableInOut = [&](TVariable& variable) {
  1822. if (variable.getType().isStruct()) {
  1823. if (variable.getType().getQualifier().isArrayedIo(language)) {
  1824. if (variable.getType().containsBuiltIn())
  1825. split(variable);
  1826. } else if (shouldFlatten(variable.getType(), EvqVaryingIn /* not assigned yet, but close enough */, true))
  1827. flatten(variable, false /* don't track linkage here, it will be tracked in assignToInterface() */);
  1828. }
  1829. // TODO: flatten arrays too
  1830. // TODO: flatten everything in I/O
  1831. // TODO: replace all split with flatten, make all paths can create flattened I/O, then split code can be removed
  1832. // For clip and cull distance, multiple output variables potentially get merged
  1833. // into one in assignClipCullDistance. That code in assignClipCullDistance
  1834. // handles the interface logic, so we avoid it here in that case.
  1835. if (!isClipOrCullDistance(variable.getType()))
  1836. assignToInterface(variable);
  1837. };
  1838. if (entryPointOutput != nullptr)
  1839. makeVariableInOut(*entryPointOutput);
  1840. for (auto it = inputs.begin(); it != inputs.end(); ++it)
  1841. if (!isDsPcfInput((*it)->getType())) // wait until the end for PCF input (see comment below)
  1842. makeVariableInOut(*(*it));
  1843. for (auto it = outputs.begin(); it != outputs.end(); ++it)
  1844. makeVariableInOut(*(*it));
  1845. // In the domain shader, PCF input must be at the end of the linkage. That's because in the
  1846. // hull shader there is no ordering: the output comes from the separate PCF, which does not
  1847. // participate in the argument list. That is always put at the end of the HS linkage, so the
  1848. // input side of the DS must match. The argument may be in any position in the DS argument list
  1849. // however, so this ensures the linkage is built in the correct order regardless of argument order.
  1850. if (language == EShLangTessEvaluation) {
  1851. for (auto it = inputs.begin(); it != inputs.end(); ++it)
  1852. if (isDsPcfInput((*it)->getType()))
  1853. makeVariableInOut(*(*it));
  1854. }
  1855. // Synthesize the call
  1856. pushScope(); // matches the one in handleFunctionBody()
  1857. // new signature
  1858. TType voidType(EbtVoid);
  1859. TFunction synthEntryPoint(&userFunction.getName(), voidType);
  1860. TIntermAggregate* synthParams = new TIntermAggregate();
  1861. intermediate.setAggregateOperator(synthParams, EOpParameters, voidType, loc);
  1862. intermediate.setEntryPointMangledName(synthEntryPoint.getMangledName().c_str());
  1863. intermediate.incrementEntryPointCount();
  1864. TFunction callee(&userFunction.getName(), voidType); // call based on old name, which is still in the symbol table
  1865. // change original name
  1866. userFunction.addPrefix("@"); // change the name in the function, but not in the symbol table
  1867. // Copy inputs (shader-in -> calling arg), while building up the call node
  1868. TVector<TVariable*> argVars;
  1869. TIntermAggregate* synthBody = new TIntermAggregate();
  1870. auto inputIt = inputs.begin();
  1871. TIntermTyped* callingArgs = nullptr;
  1872. for (int i = 0; i < userFunction.getParamCount(); i++) {
  1873. TParameter& param = userFunction[i];
  1874. argVars.push_back(makeInternalVariable(*param.name, *param.type));
  1875. argVars.back()->getWritableType().getQualifier().makeTemporary();
  1876. // Track the input patch, which is the only non-builtin supported by hull shader PCF.
  1877. if (param.getDeclaredBuiltIn() == EbvInputPatch)
  1878. inputPatch = argVars.back();
  1879. TIntermSymbol* arg = intermediate.addSymbol(*argVars.back());
  1880. handleFunctionArgument(&callee, callingArgs, arg);
  1881. if (param.type->getQualifier().isParamInput()) {
  1882. intermediate.growAggregate(synthBody, handleAssign(loc, EOpAssign, arg,
  1883. intermediate.addSymbol(**inputIt)));
  1884. inputIt++;
  1885. }
  1886. }
  1887. // Call
  1888. currentCaller = synthEntryPoint.getMangledName();
  1889. TIntermTyped* callReturn = handleFunctionCall(loc, &callee, callingArgs);
  1890. currentCaller = userFunction.getMangledName();
  1891. // Return value
  1892. if (entryPointOutput) {
  1893. TIntermTyped* returnAssign;
  1894. // For hull shaders, the wrapped entry point return value is written to
  1895. // an array element as indexed by invocation ID, which we might have to make up.
  1896. // This is required to match SPIR-V semantics.
  1897. if (language == EShLangTessControl) {
  1898. TIntermSymbol* invocationIdSym = findTessLinkageSymbol(EbvInvocationId);
  1899. // If there is no user declared invocation ID, we must make one.
  1900. if (invocationIdSym == nullptr) {
  1901. TType invocationIdType(EbtUint, EvqIn, 1);
  1902. TString* invocationIdName = NewPoolTString("InvocationId");
  1903. invocationIdType.getQualifier().builtIn = EbvInvocationId;
  1904. TVariable* variable = makeInternalVariable(*invocationIdName, invocationIdType);
  1905. globalQualifierFix(loc, variable->getWritableType().getQualifier());
  1906. trackLinkage(*variable);
  1907. invocationIdSym = intermediate.addSymbol(*variable);
  1908. }
  1909. TIntermTyped* element = intermediate.addIndex(EOpIndexIndirect, intermediate.addSymbol(*entryPointOutput),
  1910. invocationIdSym, loc);
  1911. // Set the type of the array element being dereferenced
  1912. const TType derefElementType(entryPointOutput->getType(), 0);
  1913. element->setType(derefElementType);
  1914. returnAssign = handleAssign(loc, EOpAssign, element, callReturn);
  1915. } else {
  1916. returnAssign = handleAssign(loc, EOpAssign, intermediate.addSymbol(*entryPointOutput), callReturn);
  1917. }
  1918. intermediate.growAggregate(synthBody, returnAssign);
  1919. } else
  1920. intermediate.growAggregate(synthBody, callReturn);
  1921. // Output copies
  1922. auto outputIt = outputs.begin();
  1923. for (int i = 0; i < userFunction.getParamCount(); i++) {
  1924. TParameter& param = userFunction[i];
  1925. // GS outputs are via emit, so we do not copy them here.
  1926. if (param.type->getQualifier().isParamOutput()) {
  1927. if (param.getDeclaredBuiltIn() == EbvGsOutputStream) {
  1928. // GS output stream does not assign outputs here: it's the Append() method
  1929. // which writes to the output, probably multiple times separated by Emit.
  1930. // We merely remember the output to use, here.
  1931. gsStreamOutput = *outputIt;
  1932. } else {
  1933. intermediate.growAggregate(synthBody, handleAssign(loc, EOpAssign,
  1934. intermediate.addSymbol(**outputIt),
  1935. intermediate.addSymbol(*argVars[i])));
  1936. }
  1937. outputIt++;
  1938. }
  1939. }
  1940. // Put the pieces together to form a full function subtree
  1941. // for the synthesized entry point.
  1942. synthBody->setOperator(EOpSequence);
  1943. TIntermNode* synthFunctionDef = synthParams;
  1944. handleFunctionBody(loc, synthEntryPoint, synthBody, synthFunctionDef);
  1945. entryPointFunctionBody = synthBody;
  1946. return synthFunctionDef;
  1947. }
  1948. void HlslParseContext::handleFunctionBody(const TSourceLoc& loc, TFunction& function, TIntermNode* functionBody,
  1949. TIntermNode*& node)
  1950. {
  1951. node = intermediate.growAggregate(node, functionBody);
  1952. intermediate.setAggregateOperator(node, EOpFunction, function.getType(), loc);
  1953. node->getAsAggregate()->setName(function.getMangledName().c_str());
  1954. popScope();
  1955. if (function.hasImplicitThis())
  1956. popImplicitThis();
  1957. if (function.getType().getBasicType() != EbtVoid && ! functionReturnsValue)
  1958. error(loc, "function does not return a value:", "", function.getName().c_str());
  1959. }
  1960. // AST I/O is done through shader globals declared in the 'in' or 'out'
  1961. // storage class. An HLSL entry point has a return value, input parameters
  1962. // and output parameters. These need to get remapped to the AST I/O.
  1963. void HlslParseContext::remapEntryPointIO(TFunction& function, TVariable*& returnValue,
  1964. TVector<TVariable*>& inputs, TVector<TVariable*>& outputs)
  1965. {
  1966. // We might have in input structure type with no decorations that caused it
  1967. // to look like an input type, yet it has (e.g.) interpolation types that
  1968. // must be modified that turn it into an input type.
  1969. // Hence, a missing ioTypeMap for 'input' might need to be synthesized.
  1970. const auto synthesizeEditedInput = [this](TType& type) {
  1971. // True if a type needs to be 'flat'
  1972. const auto needsFlat = [](const TType& type) {
  1973. return type.containsBasicType(EbtInt) ||
  1974. type.containsBasicType(EbtUint) ||
  1975. type.containsBasicType(EbtInt64) ||
  1976. type.containsBasicType(EbtUint64) ||
  1977. type.containsBasicType(EbtBool) ||
  1978. type.containsBasicType(EbtDouble);
  1979. };
  1980. if (language == EShLangFragment && needsFlat(type)) {
  1981. if (type.isStruct()) {
  1982. TTypeList* finalList = nullptr;
  1983. auto it = ioTypeMap.find(type.getStruct());
  1984. if (it == ioTypeMap.end() || it->second.input == nullptr) {
  1985. // Getting here means we have no input struct, but we need one.
  1986. auto list = new TTypeList;
  1987. for (auto member = type.getStruct()->begin(); member != type.getStruct()->end(); ++member) {
  1988. TType* newType = new TType;
  1989. newType->shallowCopy(*member->type);
  1990. TTypeLoc typeLoc = { newType, member->loc };
  1991. list->push_back(typeLoc);
  1992. }
  1993. // install the new input type
  1994. if (it == ioTypeMap.end()) {
  1995. tIoKinds newLists = { list, nullptr, nullptr };
  1996. ioTypeMap[type.getStruct()] = newLists;
  1997. } else
  1998. it->second.input = list;
  1999. finalList = list;
  2000. } else
  2001. finalList = it->second.input;
  2002. // edit for 'flat'
  2003. for (auto member = finalList->begin(); member != finalList->end(); ++member) {
  2004. if (needsFlat(*member->type)) {
  2005. member->type->getQualifier().clearInterpolation();
  2006. member->type->getQualifier().flat = true;
  2007. }
  2008. }
  2009. } else {
  2010. type.getQualifier().clearInterpolation();
  2011. type.getQualifier().flat = true;
  2012. }
  2013. }
  2014. };
  2015. // Do the actual work to make a type be a shader input or output variable,
  2016. // and clear the original to be non-IO (for use as a normal function parameter/return).
  2017. const auto makeIoVariable = [this](const char* name, TType& type, TStorageQualifier storage) -> TVariable* {
  2018. TVariable* ioVariable = makeInternalVariable(name, type);
  2019. clearUniformInputOutput(type.getQualifier());
  2020. if (type.isStruct()) {
  2021. auto newLists = ioTypeMap.find(ioVariable->getType().getStruct());
  2022. if (newLists != ioTypeMap.end()) {
  2023. if (storage == EvqVaryingIn && newLists->second.input)
  2024. ioVariable->getWritableType().setStruct(newLists->second.input);
  2025. else if (storage == EvqVaryingOut && newLists->second.output)
  2026. ioVariable->getWritableType().setStruct(newLists->second.output);
  2027. }
  2028. }
  2029. if (storage == EvqVaryingIn) {
  2030. correctInput(ioVariable->getWritableType().getQualifier());
  2031. if (language == EShLangTessEvaluation)
  2032. if (!ioVariable->getType().isArray())
  2033. ioVariable->getWritableType().getQualifier().patch = true;
  2034. } else {
  2035. correctOutput(ioVariable->getWritableType().getQualifier());
  2036. }
  2037. ioVariable->getWritableType().getQualifier().storage = storage;
  2038. fixBuiltInIoType(ioVariable->getWritableType());
  2039. return ioVariable;
  2040. };
  2041. // return value is actually a shader-scoped output (out)
  2042. if (function.getType().getBasicType() == EbtVoid) {
  2043. returnValue = nullptr;
  2044. } else {
  2045. if (language == EShLangTessControl) {
  2046. // tessellation evaluation in HLSL writes a per-ctrl-pt value, but it needs to be an
  2047. // array in SPIR-V semantics. We'll write to it indexed by invocation ID.
  2048. returnValue = makeIoVariable("@entryPointOutput", function.getWritableType(), EvqVaryingOut);
  2049. TType outputType;
  2050. outputType.shallowCopy(function.getType());
  2051. // vertices has necessarily already been set when handling entry point attributes.
  2052. TArraySizes* arraySizes = new TArraySizes;
  2053. arraySizes->addInnerSize(intermediate.getVertices());
  2054. outputType.transferArraySizes(arraySizes);
  2055. clearUniformInputOutput(function.getWritableType().getQualifier());
  2056. returnValue = makeIoVariable("@entryPointOutput", outputType, EvqVaryingOut);
  2057. } else {
  2058. returnValue = makeIoVariable("@entryPointOutput", function.getWritableType(), EvqVaryingOut);
  2059. }
  2060. }
  2061. // parameters are actually shader-scoped inputs and outputs (in or out)
  2062. for (int i = 0; i < function.getParamCount(); i++) {
  2063. TType& paramType = *function[i].type;
  2064. if (paramType.getQualifier().isParamInput()) {
  2065. synthesizeEditedInput(paramType);
  2066. TVariable* argAsGlobal = makeIoVariable(function[i].name->c_str(), paramType, EvqVaryingIn);
  2067. inputs.push_back(argAsGlobal);
  2068. }
  2069. if (paramType.getQualifier().isParamOutput()) {
  2070. TVariable* argAsGlobal = makeIoVariable(function[i].name->c_str(), paramType, EvqVaryingOut);
  2071. outputs.push_back(argAsGlobal);
  2072. }
  2073. }
  2074. }
  2075. // An HLSL function that looks like an entry point, but is not,
  2076. // declares entry point IO built-ins, but these have to be undone.
  2077. void HlslParseContext::remapNonEntryPointIO(TFunction& function)
  2078. {
  2079. // return value
  2080. if (function.getType().getBasicType() != EbtVoid)
  2081. clearUniformInputOutput(function.getWritableType().getQualifier());
  2082. // parameters.
  2083. // References to structuredbuffer types are left unmodified
  2084. for (int i = 0; i < function.getParamCount(); i++)
  2085. if (!isReference(*function[i].type))
  2086. clearUniformInputOutput(function[i].type->getQualifier());
  2087. }
  2088. // Handle function returns, including type conversions to the function return type
  2089. // if necessary.
  2090. TIntermNode* HlslParseContext::handleReturnValue(const TSourceLoc& loc, TIntermTyped* value)
  2091. {
  2092. functionReturnsValue = true;
  2093. if (currentFunctionType->getBasicType() == EbtVoid) {
  2094. error(loc, "void function cannot return a value", "return", "");
  2095. return intermediate.addBranch(EOpReturn, loc);
  2096. } else if (*currentFunctionType != value->getType()) {
  2097. value = intermediate.addConversion(EOpReturn, *currentFunctionType, value);
  2098. if (value && *currentFunctionType != value->getType())
  2099. value = intermediate.addUniShapeConversion(EOpReturn, *currentFunctionType, value);
  2100. if (value == nullptr || *currentFunctionType != value->getType()) {
  2101. error(loc, "type does not match, or is not convertible to, the function's return type", "return", "");
  2102. return value;
  2103. }
  2104. }
  2105. return intermediate.addBranch(EOpReturn, value, loc);
  2106. }
  2107. void HlslParseContext::handleFunctionArgument(TFunction* function,
  2108. TIntermTyped*& arguments, TIntermTyped* newArg)
  2109. {
  2110. TParameter param = { 0, new TType, nullptr };
  2111. param.type->shallowCopy(newArg->getType());
  2112. function->addParameter(param);
  2113. if (arguments)
  2114. arguments = intermediate.growAggregate(arguments, newArg);
  2115. else
  2116. arguments = newArg;
  2117. }
  2118. // Position may require special handling: we can optionally invert Y.
  2119. // See: https://github.com/KhronosGroup/glslang/issues/1173
  2120. // https://github.com/KhronosGroup/glslang/issues/494
  2121. TIntermTyped* HlslParseContext::assignPosition(const TSourceLoc& loc, TOperator op,
  2122. TIntermTyped* left, TIntermTyped* right)
  2123. {
  2124. // If we are not asked for Y inversion, use a plain old assign.
  2125. if (!intermediate.getInvertY())
  2126. return intermediate.addAssign(op, left, right, loc);
  2127. // If we get here, we should invert Y.
  2128. TIntermAggregate* assignList = nullptr;
  2129. // If this is a complex rvalue, we don't want to dereference it many times. Create a temporary.
  2130. TVariable* rhsTempVar = nullptr;
  2131. rhsTempVar = makeInternalVariable("@position", right->getType());
  2132. rhsTempVar->getWritableType().getQualifier().makeTemporary();
  2133. {
  2134. TIntermTyped* rhsTempSym = intermediate.addSymbol(*rhsTempVar, loc);
  2135. assignList = intermediate.growAggregate(assignList,
  2136. intermediate.addAssign(EOpAssign, rhsTempSym, right, loc), loc);
  2137. }
  2138. // pos.y = -pos.y
  2139. {
  2140. const int Y = 1;
  2141. TIntermTyped* tempSymL = intermediate.addSymbol(*rhsTempVar, loc);
  2142. TIntermTyped* tempSymR = intermediate.addSymbol(*rhsTempVar, loc);
  2143. TIntermTyped* index = intermediate.addConstantUnion(Y, loc);
  2144. TIntermTyped* lhsElement = intermediate.addIndex(EOpIndexDirect, tempSymL, index, loc);
  2145. TIntermTyped* rhsElement = intermediate.addIndex(EOpIndexDirect, tempSymR, index, loc);
  2146. const TType derefType(right->getType(), 0);
  2147. lhsElement->setType(derefType);
  2148. rhsElement->setType(derefType);
  2149. TIntermTyped* yNeg = intermediate.addUnaryMath(EOpNegative, rhsElement, loc);
  2150. assignList = intermediate.growAggregate(assignList, intermediate.addAssign(EOpAssign, lhsElement, yNeg, loc));
  2151. }
  2152. // Assign the rhs temp (now with Y inversion) to the final output
  2153. {
  2154. TIntermTyped* rhsTempSym = intermediate.addSymbol(*rhsTempVar, loc);
  2155. assignList = intermediate.growAggregate(assignList, intermediate.addAssign(op, left, rhsTempSym, loc));
  2156. }
  2157. assert(assignList != nullptr);
  2158. assignList->setOperator(EOpSequence);
  2159. return assignList;
  2160. }
  2161. // Clip and cull distance require special handling due to a semantic mismatch. In HLSL,
  2162. // these can be float scalar, float vector, or arrays of float scalar or float vector.
  2163. // In SPIR-V, they are arrays of scalar floats in all cases. We must copy individual components
  2164. // (e.g, both x and y components of a float2) out into the destination float array.
  2165. //
  2166. // The values are assigned to sequential members of the output array. The inner dimension
  2167. // is vector components. The outer dimension is array elements.
  2168. TIntermAggregate* HlslParseContext::assignClipCullDistance(const TSourceLoc& loc, TOperator op, int semanticId,
  2169. TIntermTyped* left, TIntermTyped* right)
  2170. {
  2171. switch (language) {
  2172. case EShLangFragment:
  2173. case EShLangVertex:
  2174. case EShLangGeometry:
  2175. break;
  2176. default:
  2177. error(loc, "unimplemented: clip/cull not currently implemented for this stage", "", "");
  2178. return nullptr;
  2179. }
  2180. TVariable** clipCullVar = nullptr;
  2181. // Figure out if we are assigning to, or from, clip or cull distance.
  2182. const bool isOutput = isClipOrCullDistance(left->getType());
  2183. // This is the rvalue or lvalue holding the clip or cull distance.
  2184. TIntermTyped* clipCullNode = isOutput ? left : right;
  2185. // This is the value going into or out of the clip or cull distance.
  2186. TIntermTyped* internalNode = isOutput ? right : left;
  2187. const TBuiltInVariable builtInType = clipCullNode->getQualifier().builtIn;
  2188. decltype(clipSemanticNSizeIn)* semanticNSize = nullptr;
  2189. // Refer to either the clip or the cull distance, depending on semantic.
  2190. switch (builtInType) {
  2191. case EbvClipDistance:
  2192. clipCullVar = isOutput ? &clipDistanceOutput : &clipDistanceInput;
  2193. semanticNSize = isOutput ? &clipSemanticNSizeOut : &clipSemanticNSizeIn;
  2194. break;
  2195. case EbvCullDistance:
  2196. clipCullVar = isOutput ? &cullDistanceOutput : &cullDistanceInput;
  2197. semanticNSize = isOutput ? &cullSemanticNSizeOut : &cullSemanticNSizeIn;
  2198. break;
  2199. // called invalidly: we expected a clip or a cull distance.
  2200. // static compile time problem: should not happen.
  2201. default: assert(0); return nullptr;
  2202. }
  2203. // This is the offset in the destination array of a given semantic's data
  2204. std::array<int, maxClipCullRegs> semanticOffset;
  2205. // Calculate offset of variable of semantic N in destination array
  2206. int arrayLoc = 0;
  2207. int vecItems = 0;
  2208. for (int x = 0; x < maxClipCullRegs; ++x) {
  2209. // See if we overflowed the vec4 packing
  2210. if ((vecItems + (*semanticNSize)[x]) > 4) {
  2211. arrayLoc = (arrayLoc + 3) & (~0x3); // round up to next multiple of 4
  2212. vecItems = 0;
  2213. }
  2214. semanticOffset[x] = arrayLoc;
  2215. vecItems += (*semanticNSize)[x];
  2216. arrayLoc += (*semanticNSize)[x];
  2217. }
  2218. // It can have up to 2 array dimensions (in the case of geometry shader inputs)
  2219. const TArraySizes* const internalArraySizes = internalNode->getType().getArraySizes();
  2220. const int internalArrayDims = internalNode->getType().isArray() ? internalArraySizes->getNumDims() : 0;
  2221. // vector sizes:
  2222. const int internalVectorSize = internalNode->getType().getVectorSize();
  2223. // array sizes, or 1 if it's not an array:
  2224. const int internalInnerArraySize = (internalArrayDims > 0 ? internalArraySizes->getDimSize(internalArrayDims-1) : 1);
  2225. const int internalOuterArraySize = (internalArrayDims > 1 ? internalArraySizes->getDimSize(0) : 1);
  2226. // The created type may be an array of arrays, e.g, for geometry shader inputs.
  2227. const bool isImplicitlyArrayed = (language == EShLangGeometry && !isOutput);
  2228. // If we haven't created the output already, create it now.
  2229. if (*clipCullVar == nullptr) {
  2230. // ClipDistance and CullDistance are handled specially in the entry point input/output copy
  2231. // algorithm, because they may need to be unpacked from components of vectors (or a scalar)
  2232. // into a float array, or vice versa. Here, we make the array the right size and type,
  2233. // which depends on the incoming data, which has several potential dimensions:
  2234. // * Semantic ID
  2235. // * vector size
  2236. // * array size
  2237. // Of those, semantic ID and array size cannot appear simultaneously.
  2238. //
  2239. // Also to note: for implicitly arrayed forms (e.g, geometry shader inputs), we need to create two
  2240. // array dimensions. The shader's declaration may have one or two array dimensions. One is always
  2241. // the geometry's dimension.
  2242. const bool useInnerSize = internalArrayDims > 1 || !isImplicitlyArrayed;
  2243. const int requiredInnerArraySize = arrayLoc * (useInnerSize ? internalInnerArraySize : 1);
  2244. const int requiredOuterArraySize = (internalArrayDims > 0) ? internalArraySizes->getDimSize(0) : 1;
  2245. TType clipCullType(EbtFloat, clipCullNode->getType().getQualifier().storage, 1);
  2246. clipCullType.getQualifier() = clipCullNode->getType().getQualifier();
  2247. // Create required array dimension
  2248. TArraySizes* arraySizes = new TArraySizes;
  2249. if (isImplicitlyArrayed)
  2250. arraySizes->addInnerSize(requiredOuterArraySize);
  2251. arraySizes->addInnerSize(requiredInnerArraySize);
  2252. clipCullType.transferArraySizes(arraySizes);
  2253. // Obtain symbol name: we'll use that for the symbol we introduce.
  2254. TIntermSymbol* sym = clipCullNode->getAsSymbolNode();
  2255. assert(sym != nullptr);
  2256. // We are moving the semantic ID from the layout location, so it is no longer needed or
  2257. // desired there.
  2258. clipCullType.getQualifier().layoutLocation = TQualifier::layoutLocationEnd;
  2259. // Create variable and track its linkage
  2260. *clipCullVar = makeInternalVariable(sym->getName().c_str(), clipCullType);
  2261. trackLinkage(**clipCullVar);
  2262. }
  2263. // Create symbol for the clip or cull variable.
  2264. TIntermSymbol* clipCullSym = intermediate.addSymbol(**clipCullVar);
  2265. // vector sizes:
  2266. const int clipCullVectorSize = clipCullSym->getType().getVectorSize();
  2267. // array sizes, or 1 if it's not an array:
  2268. const TArraySizes* const clipCullArraySizes = clipCullSym->getType().getArraySizes();
  2269. const int clipCullOuterArraySize = isImplicitlyArrayed ? clipCullArraySizes->getDimSize(0) : 1;
  2270. const int clipCullInnerArraySize = clipCullArraySizes->getDimSize(isImplicitlyArrayed ? 1 : 0);
  2271. // clipCullSym has got to be an array of scalar floats, per SPIR-V semantics.
  2272. // fixBuiltInIoType() should have handled that upstream.
  2273. assert(clipCullSym->getType().isArray());
  2274. assert(clipCullSym->getType().getVectorSize() == 1);
  2275. assert(clipCullSym->getType().getBasicType() == EbtFloat);
  2276. // We may be creating multiple sub-assignments. This is an aggregate to hold them.
  2277. // TODO: it would be possible to be clever sometimes and avoid the sequence node if not needed.
  2278. TIntermAggregate* assignList = nullptr;
  2279. // Holds individual component assignments as we make them.
  2280. TIntermTyped* clipCullAssign = nullptr;
  2281. // If the types are homomorphic, use a simple assign. No need to mess about with
  2282. // individual components.
  2283. if (clipCullSym->getType().isArray() == internalNode->getType().isArray() &&
  2284. clipCullInnerArraySize == internalInnerArraySize &&
  2285. clipCullOuterArraySize == internalOuterArraySize &&
  2286. clipCullVectorSize == internalVectorSize) {
  2287. if (isOutput)
  2288. clipCullAssign = intermediate.addAssign(op, clipCullSym, internalNode, loc);
  2289. else
  2290. clipCullAssign = intermediate.addAssign(op, internalNode, clipCullSym, loc);
  2291. assignList = intermediate.growAggregate(assignList, clipCullAssign);
  2292. assignList->setOperator(EOpSequence);
  2293. return assignList;
  2294. }
  2295. // We are going to copy each component of the internal (per array element if indicated) to sequential
  2296. // array elements of the clipCullSym. This tracks the lhs element we're writing to as we go along.
  2297. // We may be starting in the middle - e.g, for a non-zero semantic ID calculated above.
  2298. int clipCullInnerArrayPos = semanticOffset[semanticId];
  2299. int clipCullOuterArrayPos = 0;
  2300. // Lambda to add an index to a node, set the type of the result, and return the new node.
  2301. const auto addIndex = [this, &loc](TIntermTyped* node, int pos) -> TIntermTyped* {
  2302. const TType derefType(node->getType(), 0);
  2303. node = intermediate.addIndex(EOpIndexDirect, node, intermediate.addConstantUnion(pos, loc), loc);
  2304. node->setType(derefType);
  2305. return node;
  2306. };
  2307. // Loop through every component of every element of the internal, and copy to or from the matching external.
  2308. for (int internalOuterArrayPos = 0; internalOuterArrayPos < internalOuterArraySize; ++internalOuterArrayPos) {
  2309. for (int internalInnerArrayPos = 0; internalInnerArrayPos < internalInnerArraySize; ++internalInnerArrayPos) {
  2310. for (int internalComponent = 0; internalComponent < internalVectorSize; ++internalComponent) {
  2311. // clip/cull array member to read from / write to:
  2312. TIntermTyped* clipCullMember = clipCullSym;
  2313. // If implicitly arrayed, there is an outer array dimension involved
  2314. if (isImplicitlyArrayed)
  2315. clipCullMember = addIndex(clipCullMember, clipCullOuterArrayPos);
  2316. // Index into proper array position for clip cull member
  2317. clipCullMember = addIndex(clipCullMember, clipCullInnerArrayPos++);
  2318. // if needed, start over with next outer array slice.
  2319. if (isImplicitlyArrayed && clipCullInnerArrayPos >= clipCullInnerArraySize) {
  2320. clipCullInnerArrayPos = semanticOffset[semanticId];
  2321. ++clipCullOuterArrayPos;
  2322. }
  2323. // internal member to read from / write to:
  2324. TIntermTyped* internalMember = internalNode;
  2325. // If internal node has outer array dimension, index appropriately.
  2326. if (internalArrayDims > 1)
  2327. internalMember = addIndex(internalMember, internalOuterArrayPos);
  2328. // If internal node has inner array dimension, index appropriately.
  2329. if (internalArrayDims > 0)
  2330. internalMember = addIndex(internalMember, internalInnerArrayPos);
  2331. // If internal node is a vector, extract the component of interest.
  2332. if (internalNode->getType().isVector())
  2333. internalMember = addIndex(internalMember, internalComponent);
  2334. // Create an assignment: output from internal to clip cull, or input from clip cull to internal.
  2335. if (isOutput)
  2336. clipCullAssign = intermediate.addAssign(op, clipCullMember, internalMember, loc);
  2337. else
  2338. clipCullAssign = intermediate.addAssign(op, internalMember, clipCullMember, loc);
  2339. // Track assignment in the sequence.
  2340. assignList = intermediate.growAggregate(assignList, clipCullAssign);
  2341. }
  2342. }
  2343. }
  2344. assert(assignList != nullptr);
  2345. assignList->setOperator(EOpSequence);
  2346. return assignList;
  2347. }
  2348. // Some simple source assignments need to be flattened to a sequence
  2349. // of AST assignments. Catch these and flatten, otherwise, pass through
  2350. // to intermediate.addAssign().
  2351. //
  2352. // Also, assignment to matrix swizzles requires multiple component assignments,
  2353. // intercept those as well.
  2354. TIntermTyped* HlslParseContext::handleAssign(const TSourceLoc& loc, TOperator op, TIntermTyped* left,
  2355. TIntermTyped* right)
  2356. {
  2357. if (left == nullptr || right == nullptr)
  2358. return nullptr;
  2359. // writing to opaques will require fixing transforms
  2360. if (left->getType().containsOpaque())
  2361. intermediate.setNeedsLegalization();
  2362. if (left->getAsOperator() && left->getAsOperator()->getOp() == EOpMatrixSwizzle)
  2363. return handleAssignToMatrixSwizzle(loc, op, left, right);
  2364. // Return true if the given node is an index operation into a split variable.
  2365. const auto indexesSplit = [this](const TIntermTyped* node) -> bool {
  2366. const TIntermBinary* binaryNode = node->getAsBinaryNode();
  2367. if (binaryNode == nullptr)
  2368. return false;
  2369. return (binaryNode->getOp() == EOpIndexDirect || binaryNode->getOp() == EOpIndexIndirect) &&
  2370. wasSplit(binaryNode->getLeft());
  2371. };
  2372. // Return true if this stage assigns clip position with potentially inverted Y
  2373. const auto assignsClipPos = [this](const TIntermTyped* node) -> bool {
  2374. return node->getType().getQualifier().builtIn == EbvPosition &&
  2375. (language == EShLangVertex || language == EShLangGeometry || language == EShLangTessEvaluation);
  2376. };
  2377. const bool isSplitLeft = wasSplit(left) || indexesSplit(left);
  2378. const bool isSplitRight = wasSplit(right) || indexesSplit(right);
  2379. const bool isFlattenLeft = wasFlattened(left);
  2380. const bool isFlattenRight = wasFlattened(right);
  2381. // OK to do a single assign if neither side is split or flattened. Otherwise,
  2382. // fall through to a member-wise copy.
  2383. if (!isFlattenLeft && !isFlattenRight && !isSplitLeft && !isSplitRight) {
  2384. // Clip and cull distance requires more processing. See comment above assignClipCullDistance.
  2385. if (isClipOrCullDistance(left->getType()) || isClipOrCullDistance(right->getType())) {
  2386. const bool isOutput = isClipOrCullDistance(left->getType());
  2387. const int semanticId = (isOutput ? left : right)->getType().getQualifier().layoutLocation;
  2388. return assignClipCullDistance(loc, op, semanticId, left, right);
  2389. } else if (assignsClipPos(left)) {
  2390. // Position can require special handling: see comment above assignPosition
  2391. return assignPosition(loc, op, left, right);
  2392. } else if (left->getQualifier().builtIn == EbvSampleMask) {
  2393. // Certain builtins are required to be arrayed outputs in SPIR-V, but may internally be scalars
  2394. // in the shader. Copy the scalar RHS into the LHS array element zero, if that happens.
  2395. if (left->isArray() && !right->isArray()) {
  2396. const TType derefType(left->getType(), 0);
  2397. left = intermediate.addIndex(EOpIndexDirect, left, intermediate.addConstantUnion(0, loc), loc);
  2398. left->setType(derefType);
  2399. // Fall through to add assign.
  2400. }
  2401. }
  2402. return intermediate.addAssign(op, left, right, loc);
  2403. }
  2404. TIntermAggregate* assignList = nullptr;
  2405. const TVector<TVariable*>* leftVariables = nullptr;
  2406. const TVector<TVariable*>* rightVariables = nullptr;
  2407. // A temporary to store the right node's value, so we don't keep indirecting into it
  2408. // if it's not a simple symbol.
  2409. TVariable* rhsTempVar = nullptr;
  2410. // If the RHS is a simple symbol node, we'll copy it for each member.
  2411. TIntermSymbol* cloneSymNode = nullptr;
  2412. int memberCount = 0;
  2413. // Track how many items there are to copy.
  2414. if (left->getType().isStruct())
  2415. memberCount = (int)left->getType().getStruct()->size();
  2416. if (left->getType().isArray())
  2417. memberCount = left->getType().getCumulativeArraySize();
  2418. if (isFlattenLeft)
  2419. leftVariables = &flattenMap.find(left->getAsSymbolNode()->getId())->second.members;
  2420. if (isFlattenRight) {
  2421. rightVariables = &flattenMap.find(right->getAsSymbolNode()->getId())->second.members;
  2422. } else {
  2423. // The RHS is not flattened. There are several cases:
  2424. // 1. 1 item to copy: Use the RHS directly.
  2425. // 2. >1 item, simple symbol RHS: we'll create a new TIntermSymbol node for each, but no assign to temp.
  2426. // 3. >1 item, complex RHS: assign it to a new temp variable, and create a TIntermSymbol for each member.
  2427. if (memberCount <= 1) {
  2428. // case 1: we'll use the symbol directly below. Nothing to do.
  2429. } else {
  2430. if (right->getAsSymbolNode() != nullptr) {
  2431. // case 2: we'll copy the symbol per iteration below.
  2432. cloneSymNode = right->getAsSymbolNode();
  2433. } else {
  2434. // case 3: assign to a temp, and indirect into that.
  2435. rhsTempVar = makeInternalVariable("flattenTemp", right->getType());
  2436. rhsTempVar->getWritableType().getQualifier().makeTemporary();
  2437. TIntermTyped* noFlattenRHS = intermediate.addSymbol(*rhsTempVar, loc);
  2438. // Add this to the aggregate being built.
  2439. assignList = intermediate.growAggregate(assignList,
  2440. intermediate.addAssign(op, noFlattenRHS, right, loc), loc);
  2441. }
  2442. }
  2443. }
  2444. // When dealing with split arrayed structures of built-ins, the arrayness is moved to the extracted built-in
  2445. // variables, which is awkward when copying between split and unsplit structures. This variable tracks
  2446. // array indirections so they can be percolated from outer structs to inner variables.
  2447. std::vector <int> arrayElement;
  2448. TStorageQualifier leftStorage = left->getType().getQualifier().storage;
  2449. TStorageQualifier rightStorage = right->getType().getQualifier().storage;
  2450. int leftOffset = findSubtreeOffset(*left);
  2451. int rightOffset = findSubtreeOffset(*right);
  2452. const auto getMember = [&](bool isLeft, const TType& type, int member, TIntermTyped* splitNode, int splitMember,
  2453. bool flattened)
  2454. -> TIntermTyped * {
  2455. const bool split = isLeft ? isSplitLeft : isSplitRight;
  2456. TIntermTyped* subTree;
  2457. const TType derefType(type, member);
  2458. const TVariable* builtInVar = nullptr;
  2459. if ((flattened || split) && derefType.isBuiltIn()) {
  2460. auto splitPair = splitBuiltIns.find(HlslParseContext::tInterstageIoData(
  2461. derefType.getQualifier().builtIn,
  2462. isLeft ? leftStorage : rightStorage));
  2463. if (splitPair != splitBuiltIns.end())
  2464. builtInVar = splitPair->second;
  2465. }
  2466. if (builtInVar != nullptr) {
  2467. // copy from interstage IO built-in if needed
  2468. subTree = intermediate.addSymbol(*builtInVar);
  2469. if (subTree->getType().isArray()) {
  2470. // Arrayness of builtIn symbols isn't handled by the normal recursion:
  2471. // it's been extracted and moved to the built-in.
  2472. if (!arrayElement.empty()) {
  2473. const TType splitDerefType(subTree->getType(), arrayElement.back());
  2474. subTree = intermediate.addIndex(EOpIndexDirect, subTree,
  2475. intermediate.addConstantUnion(arrayElement.back(), loc), loc);
  2476. subTree->setType(splitDerefType);
  2477. } else if (splitNode->getAsOperator() != nullptr && (splitNode->getAsOperator()->getOp() == EOpIndexIndirect)) {
  2478. // This might also be a stage with arrayed outputs, in which case there's an index
  2479. // operation we should transfer to the output builtin.
  2480. const TType splitDerefType(subTree->getType(), 0);
  2481. subTree = intermediate.addIndex(splitNode->getAsOperator()->getOp(), subTree,
  2482. splitNode->getAsBinaryNode()->getRight(), loc);
  2483. subTree->setType(splitDerefType);
  2484. }
  2485. }
  2486. } else if (flattened && !shouldFlatten(derefType, isLeft ? leftStorage : rightStorage, false)) {
  2487. if (isLeft)
  2488. subTree = intermediate.addSymbol(*(*leftVariables)[leftOffset++]);
  2489. else
  2490. subTree = intermediate.addSymbol(*(*rightVariables)[rightOffset++]);
  2491. } else {
  2492. // Index operator if it's an aggregate, else EOpNull
  2493. const TOperator accessOp = type.isArray() ? EOpIndexDirect
  2494. : type.isStruct() ? EOpIndexDirectStruct
  2495. : EOpNull;
  2496. if (accessOp == EOpNull) {
  2497. subTree = splitNode;
  2498. } else {
  2499. subTree = intermediate.addIndex(accessOp, splitNode, intermediate.addConstantUnion(splitMember, loc),
  2500. loc);
  2501. const TType splitDerefType(splitNode->getType(), splitMember);
  2502. subTree->setType(splitDerefType);
  2503. }
  2504. }
  2505. return subTree;
  2506. };
  2507. // Use the proper RHS node: a new symbol from a TVariable, copy
  2508. // of an TIntermSymbol node, or sometimes the right node directly.
  2509. right = rhsTempVar != nullptr ? intermediate.addSymbol(*rhsTempVar, loc) :
  2510. cloneSymNode != nullptr ? intermediate.addSymbol(*cloneSymNode) :
  2511. right;
  2512. // Cannot use auto here, because this is recursive, and auto can't work out the type without seeing the
  2513. // whole thing. So, we'll resort to an explicit type via std::function.
  2514. const std::function<void(TIntermTyped* left, TIntermTyped* right, TIntermTyped* splitLeft, TIntermTyped* splitRight,
  2515. bool topLevel)>
  2516. traverse = [&](TIntermTyped* left, TIntermTyped* right, TIntermTyped* splitLeft, TIntermTyped* splitRight,
  2517. bool topLevel) -> void {
  2518. // If we get here, we are assigning to or from a whole array or struct that must be
  2519. // flattened, so have to do member-by-member assignment:
  2520. bool shouldFlattenSubsetLeft = isFlattenLeft && shouldFlatten(left->getType(), leftStorage, topLevel);
  2521. bool shouldFlattenSubsetRight = isFlattenRight && shouldFlatten(right->getType(), rightStorage, topLevel);
  2522. if ((left->getType().isArray() || right->getType().isArray()) &&
  2523. (shouldFlattenSubsetLeft || isSplitLeft ||
  2524. shouldFlattenSubsetRight || isSplitRight)) {
  2525. const int elementsL = left->getType().isArray() ? left->getType().getOuterArraySize() : 1;
  2526. const int elementsR = right->getType().isArray() ? right->getType().getOuterArraySize() : 1;
  2527. // The arrays might not be the same size,
  2528. // e.g., if the size has been forced for EbvTessLevelInner/Outer.
  2529. const int elementsToCopy = std::min(elementsL, elementsR);
  2530. // array case
  2531. for (int element = 0; element < elementsToCopy; ++element) {
  2532. arrayElement.push_back(element);
  2533. // Add a new AST symbol node if we have a temp variable holding a complex RHS.
  2534. TIntermTyped* subLeft = getMember(true, left->getType(), element, left, element,
  2535. shouldFlattenSubsetLeft);
  2536. TIntermTyped* subRight = getMember(false, right->getType(), element, right, element,
  2537. shouldFlattenSubsetRight);
  2538. TIntermTyped* subSplitLeft = isSplitLeft ? getMember(true, left->getType(), element, splitLeft,
  2539. element, shouldFlattenSubsetLeft)
  2540. : subLeft;
  2541. TIntermTyped* subSplitRight = isSplitRight ? getMember(false, right->getType(), element, splitRight,
  2542. element, shouldFlattenSubsetRight)
  2543. : subRight;
  2544. traverse(subLeft, subRight, subSplitLeft, subSplitRight, false);
  2545. arrayElement.pop_back();
  2546. }
  2547. } else if (left->getType().isStruct() && (shouldFlattenSubsetLeft || isSplitLeft ||
  2548. shouldFlattenSubsetRight || isSplitRight)) {
  2549. // struct case
  2550. const auto& membersL = *left->getType().getStruct();
  2551. const auto& membersR = *right->getType().getStruct();
  2552. // These track the members in the split structures corresponding to the same in the unsplit structures,
  2553. // which we traverse in parallel.
  2554. int memberL = 0;
  2555. int memberR = 0;
  2556. // Handle empty structure assignment
  2557. if (int(membersL.size()) == 0 && int(membersR.size()) == 0)
  2558. assignList = intermediate.growAggregate(assignList, intermediate.addAssign(op, left, right, loc), loc);
  2559. for (int member = 0; member < int(membersL.size()); ++member) {
  2560. const TType& typeL = *membersL[member].type;
  2561. const TType& typeR = *membersR[member].type;
  2562. TIntermTyped* subLeft = getMember(true, left->getType(), member, left, member,
  2563. shouldFlattenSubsetLeft);
  2564. TIntermTyped* subRight = getMember(false, right->getType(), member, right, member,
  2565. shouldFlattenSubsetRight);
  2566. // If there is no splitting, use the same values to avoid inefficiency.
  2567. TIntermTyped* subSplitLeft = isSplitLeft ? getMember(true, left->getType(), member, splitLeft,
  2568. memberL, shouldFlattenSubsetLeft)
  2569. : subLeft;
  2570. TIntermTyped* subSplitRight = isSplitRight ? getMember(false, right->getType(), member, splitRight,
  2571. memberR, shouldFlattenSubsetRight)
  2572. : subRight;
  2573. if (isClipOrCullDistance(subSplitLeft->getType()) || isClipOrCullDistance(subSplitRight->getType())) {
  2574. // Clip and cull distance built-in assignment is complex in its own right, and is handled in
  2575. // a separate function dedicated to that task. See comment above assignClipCullDistance;
  2576. const bool isOutput = isClipOrCullDistance(subSplitLeft->getType());
  2577. // Since all clip/cull semantics boil down to the same built-in type, we need to get the
  2578. // semantic ID from the dereferenced type's layout location, to avoid an N-1 mapping.
  2579. const TType derefType((isOutput ? left : right)->getType(), member);
  2580. const int semanticId = derefType.getQualifier().layoutLocation;
  2581. TIntermAggregate* clipCullAssign = assignClipCullDistance(loc, op, semanticId,
  2582. subSplitLeft, subSplitRight);
  2583. assignList = intermediate.growAggregate(assignList, clipCullAssign, loc);
  2584. } else if (assignsClipPos(subSplitLeft)) {
  2585. // Position can require special handling: see comment above assignPosition
  2586. TIntermTyped* positionAssign = assignPosition(loc, op, subSplitLeft, subSplitRight);
  2587. assignList = intermediate.growAggregate(assignList, positionAssign, loc);
  2588. } else if (!shouldFlattenSubsetLeft && !shouldFlattenSubsetRight &&
  2589. !typeL.containsBuiltIn() && !typeR.containsBuiltIn()) {
  2590. // If this is the final flattening (no nested types below to flatten)
  2591. // we'll copy the member, else recurse into the type hierarchy.
  2592. // However, if splitting the struct, that means we can copy a whole
  2593. // subtree here IFF it does not itself contain any interstage built-in
  2594. // IO variables, so we only have to recurse into it if there's something
  2595. // for splitting to do. That can save a lot of AST verbosity for
  2596. // a bunch of memberwise copies.
  2597. assignList = intermediate.growAggregate(assignList,
  2598. intermediate.addAssign(op, subSplitLeft, subSplitRight, loc),
  2599. loc);
  2600. } else {
  2601. traverse(subLeft, subRight, subSplitLeft, subSplitRight, false);
  2602. }
  2603. memberL += (typeL.isBuiltIn() ? 0 : 1);
  2604. memberR += (typeR.isBuiltIn() ? 0 : 1);
  2605. }
  2606. } else {
  2607. // Member copy
  2608. assignList = intermediate.growAggregate(assignList, intermediate.addAssign(op, left, right, loc), loc);
  2609. }
  2610. };
  2611. TIntermTyped* splitLeft = left;
  2612. TIntermTyped* splitRight = right;
  2613. // If either left or right was a split structure, we must read or write it, but still have to
  2614. // parallel-recurse through the unsplit structure to identify the built-in IO vars.
  2615. // The left can be either a symbol, or an index into a symbol (e.g, array reference)
  2616. if (isSplitLeft) {
  2617. if (indexesSplit(left)) {
  2618. // Index case: Refer to the indexed symbol, if the left is an index operator.
  2619. const TIntermSymbol* symNode = left->getAsBinaryNode()->getLeft()->getAsSymbolNode();
  2620. TIntermTyped* splitLeftNonIo = intermediate.addSymbol(*getSplitNonIoVar(symNode->getId()), loc);
  2621. splitLeft = intermediate.addIndex(left->getAsBinaryNode()->getOp(), splitLeftNonIo,
  2622. left->getAsBinaryNode()->getRight(), loc);
  2623. const TType derefType(splitLeftNonIo->getType(), 0);
  2624. splitLeft->setType(derefType);
  2625. } else {
  2626. // Symbol case: otherwise, if not indexed, we have the symbol directly.
  2627. const TIntermSymbol* symNode = left->getAsSymbolNode();
  2628. splitLeft = intermediate.addSymbol(*getSplitNonIoVar(symNode->getId()), loc);
  2629. }
  2630. }
  2631. if (isSplitRight)
  2632. splitRight = intermediate.addSymbol(*getSplitNonIoVar(right->getAsSymbolNode()->getId()), loc);
  2633. // This makes the whole assignment, recursing through subtypes as needed.
  2634. traverse(left, right, splitLeft, splitRight, true);
  2635. assert(assignList != nullptr);
  2636. assignList->setOperator(EOpSequence);
  2637. return assignList;
  2638. }
  2639. // An assignment to matrix swizzle must be decomposed into individual assignments.
  2640. // These must be selected component-wise from the RHS and stored component-wise
  2641. // into the LHS.
  2642. TIntermTyped* HlslParseContext::handleAssignToMatrixSwizzle(const TSourceLoc& loc, TOperator op, TIntermTyped* left,
  2643. TIntermTyped* right)
  2644. {
  2645. assert(left->getAsOperator() && left->getAsOperator()->getOp() == EOpMatrixSwizzle);
  2646. if (op != EOpAssign)
  2647. error(loc, "only simple assignment to non-simple matrix swizzle is supported", "assign", "");
  2648. // isolate the matrix and swizzle nodes
  2649. TIntermTyped* matrix = left->getAsBinaryNode()->getLeft()->getAsTyped();
  2650. const TIntermSequence& swizzle = left->getAsBinaryNode()->getRight()->getAsAggregate()->getSequence();
  2651. // if the RHS isn't already a simple vector, let's store into one
  2652. TIntermSymbol* vector = right->getAsSymbolNode();
  2653. TIntermTyped* vectorAssign = nullptr;
  2654. if (vector == nullptr) {
  2655. // create a new intermediate vector variable to assign to
  2656. TType vectorType(matrix->getBasicType(), EvqTemporary, matrix->getQualifier().precision, (int)swizzle.size()/2);
  2657. vector = intermediate.addSymbol(*makeInternalVariable("intermVec", vectorType), loc);
  2658. // assign the right to the new vector
  2659. vectorAssign = handleAssign(loc, op, vector, right);
  2660. }
  2661. // Assign the vector components to the matrix components.
  2662. // Store this as a sequence, so a single aggregate node represents this
  2663. // entire operation.
  2664. TIntermAggregate* result = intermediate.makeAggregate(vectorAssign);
  2665. TType columnType(matrix->getType(), 0);
  2666. TType componentType(columnType, 0);
  2667. TType indexType(EbtInt);
  2668. for (int i = 0; i < (int)swizzle.size(); i += 2) {
  2669. // the right component, single index into the RHS vector
  2670. TIntermTyped* rightComp = intermediate.addIndex(EOpIndexDirect, vector,
  2671. intermediate.addConstantUnion(i/2, loc), loc);
  2672. // the left component, double index into the LHS matrix
  2673. TIntermTyped* leftComp = intermediate.addIndex(EOpIndexDirect, matrix,
  2674. intermediate.addConstantUnion(swizzle[i]->getAsConstantUnion()->getConstArray(),
  2675. indexType, loc),
  2676. loc);
  2677. leftComp->setType(columnType);
  2678. leftComp = intermediate.addIndex(EOpIndexDirect, leftComp,
  2679. intermediate.addConstantUnion(swizzle[i+1]->getAsConstantUnion()->getConstArray(),
  2680. indexType, loc),
  2681. loc);
  2682. leftComp->setType(componentType);
  2683. // Add the assignment to the aggregate
  2684. result = intermediate.growAggregate(result, intermediate.addAssign(op, leftComp, rightComp, loc));
  2685. }
  2686. result->setOp(EOpSequence);
  2687. return result;
  2688. }
  2689. //
  2690. // HLSL atomic operations have slightly different arguments than
  2691. // GLSL/AST/SPIRV. The semantics are converted below in decomposeIntrinsic.
  2692. // This provides the post-decomposition equivalent opcode.
  2693. //
  2694. TOperator HlslParseContext::mapAtomicOp(const TSourceLoc& loc, TOperator op, bool isImage)
  2695. {
  2696. switch (op) {
  2697. case EOpInterlockedAdd: return isImage ? EOpImageAtomicAdd : EOpAtomicAdd;
  2698. case EOpInterlockedAnd: return isImage ? EOpImageAtomicAnd : EOpAtomicAnd;
  2699. case EOpInterlockedCompareExchange: return isImage ? EOpImageAtomicCompSwap : EOpAtomicCompSwap;
  2700. case EOpInterlockedMax: return isImage ? EOpImageAtomicMax : EOpAtomicMax;
  2701. case EOpInterlockedMin: return isImage ? EOpImageAtomicMin : EOpAtomicMin;
  2702. case EOpInterlockedOr: return isImage ? EOpImageAtomicOr : EOpAtomicOr;
  2703. case EOpInterlockedXor: return isImage ? EOpImageAtomicXor : EOpAtomicXor;
  2704. case EOpInterlockedExchange: return isImage ? EOpImageAtomicExchange : EOpAtomicExchange;
  2705. case EOpInterlockedCompareStore: // TODO: ...
  2706. default:
  2707. error(loc, "unknown atomic operation", "unknown op", "");
  2708. return EOpNull;
  2709. }
  2710. }
  2711. //
  2712. // Create a combined sampler/texture from separate sampler and texture.
  2713. //
  2714. TIntermAggregate* HlslParseContext::handleSamplerTextureCombine(const TSourceLoc& loc, TIntermTyped* argTex,
  2715. TIntermTyped* argSampler)
  2716. {
  2717. TIntermAggregate* txcombine = new TIntermAggregate(EOpConstructTextureSampler);
  2718. txcombine->getSequence().push_back(argTex);
  2719. txcombine->getSequence().push_back(argSampler);
  2720. TSampler samplerType = argTex->getType().getSampler();
  2721. samplerType.combined = true;
  2722. // TODO:
  2723. // This block exists until the spec no longer requires shadow modes on texture objects.
  2724. // It can be deleted after that, along with the shadowTextureVariant member.
  2725. {
  2726. const bool shadowMode = argSampler->getType().getSampler().shadow;
  2727. TIntermSymbol* texSymbol = argTex->getAsSymbolNode();
  2728. if (texSymbol == nullptr)
  2729. texSymbol = argTex->getAsBinaryNode()->getLeft()->getAsSymbolNode();
  2730. if (texSymbol == nullptr) {
  2731. error(loc, "unable to find texture symbol", "", "");
  2732. return nullptr;
  2733. }
  2734. // This forces the texture's shadow state to be the sampler's
  2735. // shadow state. This depends on downstream optimization to
  2736. // DCE one variant in [shadow, nonshadow] if both are present,
  2737. // or the SPIR-V module would be invalid.
  2738. int newId = texSymbol->getId();
  2739. // Check to see if this texture has been given a shadow mode already.
  2740. // If so, look up the one we already have.
  2741. const auto textureShadowEntry = textureShadowVariant.find(texSymbol->getId());
  2742. if (textureShadowEntry != textureShadowVariant.end())
  2743. newId = textureShadowEntry->second->get(shadowMode);
  2744. else
  2745. textureShadowVariant[texSymbol->getId()] = NewPoolObject(tShadowTextureSymbols(), 1);
  2746. // Sometimes we have to create another symbol (if this texture has been seen before,
  2747. // and we haven't created the form for this shadow mode).
  2748. if (newId == -1) {
  2749. TType texType;
  2750. texType.shallowCopy(argTex->getType());
  2751. texType.getSampler().shadow = shadowMode; // set appropriate shadow mode.
  2752. globalQualifierFix(loc, texType.getQualifier());
  2753. TVariable* newTexture = makeInternalVariable(texSymbol->getName(), texType);
  2754. trackLinkage(*newTexture);
  2755. newId = newTexture->getUniqueId();
  2756. }
  2757. assert(newId != -1);
  2758. if (textureShadowVariant.find(newId) == textureShadowVariant.end())
  2759. textureShadowVariant[newId] = textureShadowVariant[texSymbol->getId()];
  2760. textureShadowVariant[newId]->set(shadowMode, newId);
  2761. // Remember this shadow mode in the texture and the merged type.
  2762. argTex->getWritableType().getSampler().shadow = shadowMode;
  2763. samplerType.shadow = shadowMode;
  2764. texSymbol->switchId(newId);
  2765. }
  2766. txcombine->setType(TType(samplerType, EvqTemporary));
  2767. txcombine->setLoc(loc);
  2768. return txcombine;
  2769. }
  2770. // Return true if this a buffer type that has an associated counter buffer.
  2771. bool HlslParseContext::hasStructBuffCounter(const TType& type) const
  2772. {
  2773. switch (type.getQualifier().declaredBuiltIn) {
  2774. case EbvAppendConsume: // fall through...
  2775. case EbvRWStructuredBuffer: // ...
  2776. return true;
  2777. default:
  2778. return false; // the other structuredbuffer types do not have a counter.
  2779. }
  2780. }
  2781. void HlslParseContext::counterBufferType(const TSourceLoc& loc, TType& type)
  2782. {
  2783. // Counter type
  2784. TType* counterType = new TType(EbtUint, EvqBuffer);
  2785. counterType->setFieldName(intermediate.implicitCounterName);
  2786. TTypeList* blockStruct = new TTypeList;
  2787. TTypeLoc member = { counterType, loc };
  2788. blockStruct->push_back(member);
  2789. TType blockType(blockStruct, "", counterType->getQualifier());
  2790. blockType.getQualifier().storage = EvqBuffer;
  2791. type.shallowCopy(blockType);
  2792. shareStructBufferType(type);
  2793. }
  2794. // declare counter for a structured buffer type
  2795. void HlslParseContext::declareStructBufferCounter(const TSourceLoc& loc, const TType& bufferType, const TString& name)
  2796. {
  2797. // Bail out if not a struct buffer
  2798. if (! isStructBufferType(bufferType))
  2799. return;
  2800. if (! hasStructBuffCounter(bufferType))
  2801. return;
  2802. TType blockType;
  2803. counterBufferType(loc, blockType);
  2804. TString* blockName = NewPoolTString(intermediate.addCounterBufferName(name).c_str());
  2805. // Counter buffer is not yet in use
  2806. structBufferCounter[*blockName] = false;
  2807. shareStructBufferType(blockType);
  2808. declareBlock(loc, blockType, blockName);
  2809. }
  2810. // return the counter that goes with a given structuredbuffer
  2811. TIntermTyped* HlslParseContext::getStructBufferCounter(const TSourceLoc& loc, TIntermTyped* buffer)
  2812. {
  2813. // Bail out if not a struct buffer
  2814. if (buffer == nullptr || ! isStructBufferType(buffer->getType()))
  2815. return nullptr;
  2816. const TString counterBlockName(intermediate.addCounterBufferName(buffer->getAsSymbolNode()->getName()));
  2817. // Mark the counter as being used
  2818. structBufferCounter[counterBlockName] = true;
  2819. TIntermTyped* counterVar = handleVariable(loc, &counterBlockName); // find the block structure
  2820. TIntermTyped* index = intermediate.addConstantUnion(0, loc); // index to counter inside block struct
  2821. TIntermTyped* counterMember = intermediate.addIndex(EOpIndexDirectStruct, counterVar, index, loc);
  2822. counterMember->setType(TType(EbtUint));
  2823. return counterMember;
  2824. }
  2825. //
  2826. // Decompose structure buffer methods into AST
  2827. //
  2828. void HlslParseContext::decomposeStructBufferMethods(const TSourceLoc& loc, TIntermTyped*& node, TIntermNode* arguments)
  2829. {
  2830. if (node == nullptr || node->getAsOperator() == nullptr || arguments == nullptr)
  2831. return;
  2832. const TOperator op = node->getAsOperator()->getOp();
  2833. TIntermAggregate* argAggregate = arguments->getAsAggregate();
  2834. // Buffer is the object upon which method is called, so always arg 0
  2835. TIntermTyped* bufferObj = nullptr;
  2836. // The parameters can be an aggregate, or just a the object as a symbol if there are no fn params.
  2837. if (argAggregate) {
  2838. if (argAggregate->getSequence().empty())
  2839. return;
  2840. if (argAggregate->getSequence()[0])
  2841. bufferObj = argAggregate->getSequence()[0]->getAsTyped();
  2842. } else {
  2843. bufferObj = arguments->getAsSymbolNode();
  2844. }
  2845. if (bufferObj == nullptr || bufferObj->getAsSymbolNode() == nullptr)
  2846. return;
  2847. // Some methods require a hidden internal counter, obtained via getStructBufferCounter().
  2848. // This lambda adds something to it and returns the old value.
  2849. const auto incDecCounter = [&](int incval) -> TIntermTyped* {
  2850. TIntermTyped* incrementValue = intermediate.addConstantUnion(static_cast<unsigned int>(incval), loc, true);
  2851. TIntermTyped* counter = getStructBufferCounter(loc, bufferObj); // obtain the counter member
  2852. if (counter == nullptr)
  2853. return nullptr;
  2854. TIntermAggregate* counterIncrement = new TIntermAggregate(EOpAtomicAdd);
  2855. counterIncrement->setType(TType(EbtUint, EvqTemporary));
  2856. counterIncrement->setLoc(loc);
  2857. counterIncrement->getSequence().push_back(counter);
  2858. counterIncrement->getSequence().push_back(incrementValue);
  2859. return counterIncrement;
  2860. };
  2861. // Index to obtain the runtime sized array out of the buffer.
  2862. TIntermTyped* argArray = indexStructBufferContent(loc, bufferObj);
  2863. if (argArray == nullptr)
  2864. return; // It might not be a struct buffer method.
  2865. switch (op) {
  2866. case EOpMethodLoad:
  2867. {
  2868. TIntermTyped* argIndex = makeIntegerIndex(argAggregate->getSequence()[1]->getAsTyped()); // index
  2869. const TType& bufferType = bufferObj->getType();
  2870. const TBuiltInVariable builtInType = bufferType.getQualifier().declaredBuiltIn;
  2871. // Byte address buffers index in bytes (only multiples of 4 permitted... not so much a byte address
  2872. // buffer then, but that's what it calls itself.
  2873. const bool isByteAddressBuffer = (builtInType == EbvByteAddressBuffer ||
  2874. builtInType == EbvRWByteAddressBuffer);
  2875. if (isByteAddressBuffer)
  2876. argIndex = intermediate.addBinaryNode(EOpRightShift, argIndex,
  2877. intermediate.addConstantUnion(2, loc, true),
  2878. loc, TType(EbtInt));
  2879. // Index into the array to find the item being loaded.
  2880. const TOperator idxOp = (argIndex->getQualifier().storage == EvqConst) ? EOpIndexDirect : EOpIndexIndirect;
  2881. node = intermediate.addIndex(idxOp, argArray, argIndex, loc);
  2882. const TType derefType(argArray->getType(), 0);
  2883. node->setType(derefType);
  2884. }
  2885. break;
  2886. case EOpMethodLoad2:
  2887. case EOpMethodLoad3:
  2888. case EOpMethodLoad4:
  2889. {
  2890. TIntermTyped* argIndex = makeIntegerIndex(argAggregate->getSequence()[1]->getAsTyped()); // index
  2891. TOperator constructOp = EOpNull;
  2892. int size = 0;
  2893. switch (op) {
  2894. case EOpMethodLoad2: size = 2; constructOp = EOpConstructVec2; break;
  2895. case EOpMethodLoad3: size = 3; constructOp = EOpConstructVec3; break;
  2896. case EOpMethodLoad4: size = 4; constructOp = EOpConstructVec4; break;
  2897. default: assert(0);
  2898. }
  2899. TIntermTyped* body = nullptr;
  2900. // First, we'll store the address in a variable to avoid multiple shifts
  2901. // (we must convert the byte address to an item address)
  2902. TIntermTyped* byteAddrIdx = intermediate.addBinaryNode(EOpRightShift, argIndex,
  2903. intermediate.addConstantUnion(2, loc, true),
  2904. loc, TType(EbtInt));
  2905. TVariable* byteAddrSym = makeInternalVariable("byteAddrTemp", TType(EbtInt, EvqTemporary));
  2906. TIntermTyped* byteAddrIdxVar = intermediate.addSymbol(*byteAddrSym, loc);
  2907. body = intermediate.growAggregate(body, intermediate.addAssign(EOpAssign, byteAddrIdxVar, byteAddrIdx, loc));
  2908. TIntermTyped* vec = nullptr;
  2909. // These are only valid on (rw)byteaddressbuffers, so we can always perform the >>2
  2910. // address conversion.
  2911. for (int idx=0; idx<size; ++idx) {
  2912. TIntermTyped* offsetIdx = byteAddrIdxVar;
  2913. // add index offset
  2914. if (idx != 0)
  2915. offsetIdx = intermediate.addBinaryNode(EOpAdd, offsetIdx,
  2916. intermediate.addConstantUnion(idx, loc, true),
  2917. loc, TType(EbtInt));
  2918. const TOperator idxOp = (offsetIdx->getQualifier().storage == EvqConst) ? EOpIndexDirect
  2919. : EOpIndexIndirect;
  2920. TIntermTyped* indexVal = intermediate.addIndex(idxOp, argArray, offsetIdx, loc);
  2921. TType derefType(argArray->getType(), 0);
  2922. derefType.getQualifier().makeTemporary();
  2923. indexVal->setType(derefType);
  2924. vec = intermediate.growAggregate(vec, indexVal);
  2925. }
  2926. vec->setType(TType(argArray->getBasicType(), EvqTemporary, size));
  2927. vec->getAsAggregate()->setOperator(constructOp);
  2928. body = intermediate.growAggregate(body, vec);
  2929. body->setType(vec->getType());
  2930. body->getAsAggregate()->setOperator(EOpSequence);
  2931. node = body;
  2932. }
  2933. break;
  2934. case EOpMethodStore:
  2935. case EOpMethodStore2:
  2936. case EOpMethodStore3:
  2937. case EOpMethodStore4:
  2938. {
  2939. TIntermTyped* argIndex = makeIntegerIndex(argAggregate->getSequence()[1]->getAsTyped()); // index
  2940. TIntermTyped* argValue = argAggregate->getSequence()[2]->getAsTyped(); // value
  2941. // Index into the array to find the item being loaded.
  2942. // Byte address buffers index in bytes (only multiples of 4 permitted... not so much a byte address
  2943. // buffer then, but that's what it calls itself).
  2944. int size = 0;
  2945. switch (op) {
  2946. case EOpMethodStore: size = 1; break;
  2947. case EOpMethodStore2: size = 2; break;
  2948. case EOpMethodStore3: size = 3; break;
  2949. case EOpMethodStore4: size = 4; break;
  2950. default: assert(0);
  2951. }
  2952. TIntermAggregate* body = nullptr;
  2953. // First, we'll store the address in a variable to avoid multiple shifts
  2954. // (we must convert the byte address to an item address)
  2955. TIntermTyped* byteAddrIdx = intermediate.addBinaryNode(EOpRightShift, argIndex,
  2956. intermediate.addConstantUnion(2, loc, true), loc, TType(EbtInt));
  2957. TVariable* byteAddrSym = makeInternalVariable("byteAddrTemp", TType(EbtInt, EvqTemporary));
  2958. TIntermTyped* byteAddrIdxVar = intermediate.addSymbol(*byteAddrSym, loc);
  2959. body = intermediate.growAggregate(body, intermediate.addAssign(EOpAssign, byteAddrIdxVar, byteAddrIdx, loc));
  2960. for (int idx=0; idx<size; ++idx) {
  2961. TIntermTyped* offsetIdx = byteAddrIdxVar;
  2962. TIntermTyped* idxConst = intermediate.addConstantUnion(idx, loc, true);
  2963. // add index offset
  2964. if (idx != 0)
  2965. offsetIdx = intermediate.addBinaryNode(EOpAdd, offsetIdx, idxConst, loc, TType(EbtInt));
  2966. const TOperator idxOp = (offsetIdx->getQualifier().storage == EvqConst) ? EOpIndexDirect
  2967. : EOpIndexIndirect;
  2968. TIntermTyped* lValue = intermediate.addIndex(idxOp, argArray, offsetIdx, loc);
  2969. const TType derefType(argArray->getType(), 0);
  2970. lValue->setType(derefType);
  2971. TIntermTyped* rValue;
  2972. if (size == 1) {
  2973. rValue = argValue;
  2974. } else {
  2975. rValue = intermediate.addIndex(EOpIndexDirect, argValue, idxConst, loc);
  2976. const TType indexType(argValue->getType(), 0);
  2977. rValue->setType(indexType);
  2978. }
  2979. TIntermTyped* assign = intermediate.addAssign(EOpAssign, lValue, rValue, loc);
  2980. body = intermediate.growAggregate(body, assign);
  2981. }
  2982. body->setOperator(EOpSequence);
  2983. node = body;
  2984. }
  2985. break;
  2986. case EOpMethodGetDimensions:
  2987. {
  2988. const int numArgs = (int)argAggregate->getSequence().size();
  2989. TIntermTyped* argNumItems = argAggregate->getSequence()[1]->getAsTyped(); // out num items
  2990. TIntermTyped* argStride = numArgs > 2 ? argAggregate->getSequence()[2]->getAsTyped() : nullptr; // out stride
  2991. TIntermAggregate* body = nullptr;
  2992. // Length output:
  2993. if (argArray->getType().isSizedArray()) {
  2994. const int length = argArray->getType().getOuterArraySize();
  2995. TIntermTyped* assign = intermediate.addAssign(EOpAssign, argNumItems,
  2996. intermediate.addConstantUnion(length, loc, true), loc);
  2997. body = intermediate.growAggregate(body, assign, loc);
  2998. } else {
  2999. TIntermTyped* lengthCall = intermediate.addBuiltInFunctionCall(loc, EOpArrayLength, true, argArray,
  3000. argNumItems->getType());
  3001. TIntermTyped* assign = intermediate.addAssign(EOpAssign, argNumItems, lengthCall, loc);
  3002. body = intermediate.growAggregate(body, assign, loc);
  3003. }
  3004. // Stride output:
  3005. if (argStride != nullptr) {
  3006. int size;
  3007. int stride;
  3008. intermediate.getMemberAlignment(argArray->getType(), size, stride, argArray->getType().getQualifier().layoutPacking,
  3009. argArray->getType().getQualifier().layoutMatrix == ElmRowMajor);
  3010. TIntermTyped* assign = intermediate.addAssign(EOpAssign, argStride,
  3011. intermediate.addConstantUnion(stride, loc, true), loc);
  3012. body = intermediate.growAggregate(body, assign);
  3013. }
  3014. body->setOperator(EOpSequence);
  3015. node = body;
  3016. }
  3017. break;
  3018. case EOpInterlockedAdd:
  3019. case EOpInterlockedAnd:
  3020. case EOpInterlockedExchange:
  3021. case EOpInterlockedMax:
  3022. case EOpInterlockedMin:
  3023. case EOpInterlockedOr:
  3024. case EOpInterlockedXor:
  3025. case EOpInterlockedCompareExchange:
  3026. case EOpInterlockedCompareStore:
  3027. {
  3028. // We'll replace the first argument with the block dereference, and let
  3029. // downstream decomposition handle the rest.
  3030. TIntermSequence& sequence = argAggregate->getSequence();
  3031. TIntermTyped* argIndex = makeIntegerIndex(sequence[1]->getAsTyped()); // index
  3032. argIndex = intermediate.addBinaryNode(EOpRightShift, argIndex, intermediate.addConstantUnion(2, loc, true),
  3033. loc, TType(EbtInt));
  3034. const TOperator idxOp = (argIndex->getQualifier().storage == EvqConst) ? EOpIndexDirect : EOpIndexIndirect;
  3035. TIntermTyped* element = intermediate.addIndex(idxOp, argArray, argIndex, loc);
  3036. const TType derefType(argArray->getType(), 0);
  3037. element->setType(derefType);
  3038. // Replace the numeric byte offset parameter with array reference.
  3039. sequence[1] = element;
  3040. sequence.erase(sequence.begin(), sequence.begin()+1);
  3041. }
  3042. break;
  3043. case EOpMethodIncrementCounter:
  3044. {
  3045. node = incDecCounter(1);
  3046. break;
  3047. }
  3048. case EOpMethodDecrementCounter:
  3049. {
  3050. TIntermTyped* preIncValue = incDecCounter(-1); // result is original value
  3051. node = intermediate.addBinaryNode(EOpAdd, preIncValue, intermediate.addConstantUnion(-1, loc, true), loc,
  3052. preIncValue->getType());
  3053. break;
  3054. }
  3055. case EOpMethodAppend:
  3056. {
  3057. TIntermTyped* oldCounter = incDecCounter(1);
  3058. TIntermTyped* lValue = intermediate.addIndex(EOpIndexIndirect, argArray, oldCounter, loc);
  3059. TIntermTyped* rValue = argAggregate->getSequence()[1]->getAsTyped();
  3060. const TType derefType(argArray->getType(), 0);
  3061. lValue->setType(derefType);
  3062. node = intermediate.addAssign(EOpAssign, lValue, rValue, loc);
  3063. break;
  3064. }
  3065. case EOpMethodConsume:
  3066. {
  3067. TIntermTyped* oldCounter = incDecCounter(-1);
  3068. TIntermTyped* newCounter = intermediate.addBinaryNode(EOpAdd, oldCounter,
  3069. intermediate.addConstantUnion(-1, loc, true), loc,
  3070. oldCounter->getType());
  3071. node = intermediate.addIndex(EOpIndexIndirect, argArray, newCounter, loc);
  3072. const TType derefType(argArray->getType(), 0);
  3073. node->setType(derefType);
  3074. break;
  3075. }
  3076. default:
  3077. break; // most pass through unchanged
  3078. }
  3079. }
  3080. // Create array of standard sample positions for given sample count.
  3081. // TODO: remove when a real method to query sample pos exists in SPIR-V.
  3082. TIntermConstantUnion* HlslParseContext::getSamplePosArray(int count)
  3083. {
  3084. struct tSamplePos { float x, y; };
  3085. static const tSamplePos pos1[] = {
  3086. { 0.0/16.0, 0.0/16.0 },
  3087. };
  3088. // standard sample positions for 2, 4, 8, and 16 samples.
  3089. static const tSamplePos pos2[] = {
  3090. { 4.0/16.0, 4.0/16.0 }, {-4.0/16.0, -4.0/16.0 },
  3091. };
  3092. static const tSamplePos pos4[] = {
  3093. {-2.0/16.0, -6.0/16.0 }, { 6.0/16.0, -2.0/16.0 }, {-6.0/16.0, 2.0/16.0 }, { 2.0/16.0, 6.0/16.0 },
  3094. };
  3095. static const tSamplePos pos8[] = {
  3096. { 1.0/16.0, -3.0/16.0 }, {-1.0/16.0, 3.0/16.0 }, { 5.0/16.0, 1.0/16.0 }, {-3.0/16.0, -5.0/16.0 },
  3097. {-5.0/16.0, 5.0/16.0 }, {-7.0/16.0, -1.0/16.0 }, { 3.0/16.0, 7.0/16.0 }, { 7.0/16.0, -7.0/16.0 },
  3098. };
  3099. static const tSamplePos pos16[] = {
  3100. { 1.0/16.0, 1.0/16.0 }, {-1.0/16.0, -3.0/16.0 }, {-3.0/16.0, 2.0/16.0 }, { 4.0/16.0, -1.0/16.0 },
  3101. {-5.0/16.0, -2.0/16.0 }, { 2.0/16.0, 5.0/16.0 }, { 5.0/16.0, 3.0/16.0 }, { 3.0/16.0, -5.0/16.0 },
  3102. {-2.0/16.0, 6.0/16.0 }, { 0.0/16.0, -7.0/16.0 }, {-4.0/16.0, -6.0/16.0 }, {-6.0/16.0, 4.0/16.0 },
  3103. {-8.0/16.0, 0.0/16.0 }, { 7.0/16.0, -4.0/16.0 }, { 6.0/16.0, 7.0/16.0 }, {-7.0/16.0, -8.0/16.0 },
  3104. };
  3105. const tSamplePos* sampleLoc = nullptr;
  3106. int numSamples = count;
  3107. switch (count) {
  3108. case 2: sampleLoc = pos2; break;
  3109. case 4: sampleLoc = pos4; break;
  3110. case 8: sampleLoc = pos8; break;
  3111. case 16: sampleLoc = pos16; break;
  3112. default:
  3113. sampleLoc = pos1;
  3114. numSamples = 1;
  3115. }
  3116. TConstUnionArray* values = new TConstUnionArray(numSamples*2);
  3117. for (int pos=0; pos<count; ++pos) {
  3118. TConstUnion x, y;
  3119. x.setDConst(sampleLoc[pos].x);
  3120. y.setDConst(sampleLoc[pos].y);
  3121. (*values)[pos*2+0] = x;
  3122. (*values)[pos*2+1] = y;
  3123. }
  3124. TType retType(EbtFloat, EvqConst, 2);
  3125. if (numSamples != 1) {
  3126. TArraySizes* arraySizes = new TArraySizes;
  3127. arraySizes->addInnerSize(numSamples);
  3128. retType.transferArraySizes(arraySizes);
  3129. }
  3130. return new TIntermConstantUnion(*values, retType);
  3131. }
  3132. //
  3133. // Decompose DX9 and DX10 sample intrinsics & object methods into AST
  3134. //
  3135. void HlslParseContext::decomposeSampleMethods(const TSourceLoc& loc, TIntermTyped*& node, TIntermNode* arguments)
  3136. {
  3137. if (node == nullptr || !node->getAsOperator())
  3138. return;
  3139. // Sampler return must always be a vec4, but we can construct a shorter vector or a structure from it.
  3140. const auto convertReturn = [&loc, &node, this](TIntermTyped* result, const TSampler& sampler) -> TIntermTyped* {
  3141. result->setType(TType(node->getType().getBasicType(), EvqTemporary, node->getVectorSize()));
  3142. TIntermTyped* convertedResult = nullptr;
  3143. TType retType;
  3144. getTextureReturnType(sampler, retType);
  3145. if (retType.isStruct()) {
  3146. // For type convenience, conversionAggregate points to the convertedResult (we know it's an aggregate here)
  3147. TIntermAggregate* conversionAggregate = new TIntermAggregate;
  3148. convertedResult = conversionAggregate;
  3149. // Convert vector output to return structure. We will need a temp symbol to copy the results to.
  3150. TVariable* structVar = makeInternalVariable("@sampleStructTemp", retType);
  3151. // We also need a temp symbol to hold the result of the texture. We don't want to re-fetch the
  3152. // sample each time we'll index into the result, so we'll copy to this, and index into the copy.
  3153. TVariable* sampleShadow = makeInternalVariable("@sampleResultShadow", result->getType());
  3154. // Initial copy from texture to our sample result shadow.
  3155. TIntermTyped* shadowCopy = intermediate.addAssign(EOpAssign, intermediate.addSymbol(*sampleShadow, loc),
  3156. result, loc);
  3157. conversionAggregate->getSequence().push_back(shadowCopy);
  3158. unsigned vec4Pos = 0;
  3159. for (unsigned m = 0; m < unsigned(retType.getStruct()->size()); ++m) {
  3160. const TType memberType(retType, m); // dereferenced type of the member we're about to assign.
  3161. // Check for bad struct members. This should have been caught upstream. Complain, because
  3162. // wwe don't know what to do with it. This algorithm could be generalized to handle
  3163. // other things, e.g, sub-structures, but HLSL doesn't allow them.
  3164. if (!memberType.isVector() && !memberType.isScalar()) {
  3165. error(loc, "expected: scalar or vector type in texture structure", "", "");
  3166. return nullptr;
  3167. }
  3168. // Index into the struct variable to find the member to assign.
  3169. TIntermTyped* structMember = intermediate.addIndex(EOpIndexDirectStruct,
  3170. intermediate.addSymbol(*structVar, loc),
  3171. intermediate.addConstantUnion(m, loc), loc);
  3172. structMember->setType(memberType);
  3173. // Assign each component of (possible) vector in struct member.
  3174. for (int component = 0; component < memberType.getVectorSize(); ++component) {
  3175. TIntermTyped* vec4Member = intermediate.addIndex(EOpIndexDirect,
  3176. intermediate.addSymbol(*sampleShadow, loc),
  3177. intermediate.addConstantUnion(vec4Pos++, loc), loc);
  3178. vec4Member->setType(TType(memberType.getBasicType(), EvqTemporary, 1));
  3179. TIntermTyped* memberAssign = nullptr;
  3180. if (memberType.isVector()) {
  3181. // Vector member: we need to create an access chain to the vector component.
  3182. TIntermTyped* structVecComponent = intermediate.addIndex(EOpIndexDirect, structMember,
  3183. intermediate.addConstantUnion(component, loc), loc);
  3184. memberAssign = intermediate.addAssign(EOpAssign, structVecComponent, vec4Member, loc);
  3185. } else {
  3186. // Scalar member: we can assign to it directly.
  3187. memberAssign = intermediate.addAssign(EOpAssign, structMember, vec4Member, loc);
  3188. }
  3189. conversionAggregate->getSequence().push_back(memberAssign);
  3190. }
  3191. }
  3192. // Add completed variable so the expression results in the whole struct value we just built.
  3193. conversionAggregate->getSequence().push_back(intermediate.addSymbol(*structVar, loc));
  3194. // Make it a sequence.
  3195. intermediate.setAggregateOperator(conversionAggregate, EOpSequence, retType, loc);
  3196. } else {
  3197. // vector clamp the output if template vector type is smaller than sample result.
  3198. if (retType.getVectorSize() < node->getVectorSize()) {
  3199. // Too many components. Construct shorter vector from it.
  3200. const TOperator op = intermediate.mapTypeToConstructorOp(retType);
  3201. convertedResult = constructBuiltIn(retType, op, result, loc, false);
  3202. } else {
  3203. // Enough components. Use directly.
  3204. convertedResult = result;
  3205. }
  3206. }
  3207. convertedResult->setLoc(loc);
  3208. return convertedResult;
  3209. };
  3210. const TOperator op = node->getAsOperator()->getOp();
  3211. const TIntermAggregate* argAggregate = arguments ? arguments->getAsAggregate() : nullptr;
  3212. // Bail out if not a sampler method.
  3213. // Note though this is odd to do before checking the op, because the op
  3214. // could be something that takes the arguments, and the function in question
  3215. // takes the result of the op. So, this is not the final word.
  3216. if (arguments != nullptr) {
  3217. if (argAggregate == nullptr) {
  3218. if (arguments->getAsTyped()->getBasicType() != EbtSampler)
  3219. return;
  3220. } else {
  3221. if (argAggregate->getSequence().size() == 0 ||
  3222. argAggregate->getSequence()[0] == nullptr ||
  3223. argAggregate->getSequence()[0]->getAsTyped()->getBasicType() != EbtSampler)
  3224. return;
  3225. }
  3226. }
  3227. switch (op) {
  3228. // **** DX9 intrinsics: ****
  3229. case EOpTexture:
  3230. {
  3231. // Texture with ddx & ddy is really gradient form in HLSL
  3232. if (argAggregate->getSequence().size() == 4)
  3233. node->getAsAggregate()->setOperator(EOpTextureGrad);
  3234. break;
  3235. }
  3236. case EOpTextureLod: //is almost EOpTextureBias (only args & operations are different)
  3237. {
  3238. TIntermTyped *argSamp = argAggregate->getSequence()[0]->getAsTyped(); // sampler
  3239. TIntermTyped *argCoord = argAggregate->getSequence()[1]->getAsTyped(); // coord
  3240. assert(argCoord->getVectorSize() == 4);
  3241. TIntermTyped *w = intermediate.addConstantUnion(3, loc, true);
  3242. TIntermTyped *argLod = intermediate.addIndex(EOpIndexDirect, argCoord, w, loc);
  3243. TOperator constructOp = EOpNull;
  3244. const TSampler &sampler = argSamp->getType().getSampler();
  3245. int coordSize = 0;
  3246. switch (sampler.dim)
  3247. {
  3248. case Esd1D: constructOp = EOpConstructFloat; coordSize = 1; break; // 1D
  3249. case Esd2D: constructOp = EOpConstructVec2; coordSize = 2; break; // 2D
  3250. case Esd3D: constructOp = EOpConstructVec3; coordSize = 3; break; // 3D
  3251. case EsdCube: constructOp = EOpConstructVec3; coordSize = 3; break; // also 3D
  3252. default:
  3253. break;
  3254. }
  3255. TIntermAggregate *constructCoord = new TIntermAggregate(constructOp);
  3256. constructCoord->getSequence().push_back(argCoord);
  3257. constructCoord->setLoc(loc);
  3258. constructCoord->setType(TType(argCoord->getBasicType(), EvqTemporary, coordSize));
  3259. TIntermAggregate *tex = new TIntermAggregate(EOpTextureLod);
  3260. tex->getSequence().push_back(argSamp); // sampler
  3261. tex->getSequence().push_back(constructCoord); // coordinate
  3262. tex->getSequence().push_back(argLod); // lod
  3263. node = convertReturn(tex, sampler);
  3264. break;
  3265. }
  3266. case EOpTextureBias:
  3267. {
  3268. TIntermTyped* arg0 = argAggregate->getSequence()[0]->getAsTyped(); // sampler
  3269. TIntermTyped* arg1 = argAggregate->getSequence()[1]->getAsTyped(); // coord
  3270. // HLSL puts bias in W component of coordinate. We extract it and add it to
  3271. // the argument list, instead
  3272. TIntermTyped* w = intermediate.addConstantUnion(3, loc, true);
  3273. TIntermTyped* bias = intermediate.addIndex(EOpIndexDirect, arg1, w, loc);
  3274. TOperator constructOp = EOpNull;
  3275. const TSampler& sampler = arg0->getType().getSampler();
  3276. switch (sampler.dim) {
  3277. case Esd1D: constructOp = EOpConstructFloat; break; // 1D
  3278. case Esd2D: constructOp = EOpConstructVec2; break; // 2D
  3279. case Esd3D: constructOp = EOpConstructVec3; break; // 3D
  3280. case EsdCube: constructOp = EOpConstructVec3; break; // also 3D
  3281. default: break;
  3282. }
  3283. TIntermAggregate* constructCoord = new TIntermAggregate(constructOp);
  3284. constructCoord->getSequence().push_back(arg1);
  3285. constructCoord->setLoc(loc);
  3286. // The input vector should never be less than 2, since there's always a bias.
  3287. // The max is for safety, and should be a no-op.
  3288. constructCoord->setType(TType(arg1->getBasicType(), EvqTemporary, std::max(arg1->getVectorSize() - 1, 0)));
  3289. TIntermAggregate* tex = new TIntermAggregate(EOpTexture);
  3290. tex->getSequence().push_back(arg0); // sampler
  3291. tex->getSequence().push_back(constructCoord); // coordinate
  3292. tex->getSequence().push_back(bias); // bias
  3293. node = convertReturn(tex, sampler);
  3294. break;
  3295. }
  3296. // **** DX10 methods: ****
  3297. case EOpMethodSample: // fall through
  3298. case EOpMethodSampleBias: // ...
  3299. {
  3300. TIntermTyped* argTex = argAggregate->getSequence()[0]->getAsTyped();
  3301. TIntermTyped* argSamp = argAggregate->getSequence()[1]->getAsTyped();
  3302. TIntermTyped* argCoord = argAggregate->getSequence()[2]->getAsTyped();
  3303. TIntermTyped* argBias = nullptr;
  3304. TIntermTyped* argOffset = nullptr;
  3305. const TSampler& sampler = argTex->getType().getSampler();
  3306. int nextArg = 3;
  3307. if (op == EOpMethodSampleBias) // SampleBias has a bias arg
  3308. argBias = argAggregate->getSequence()[nextArg++]->getAsTyped();
  3309. TOperator textureOp = EOpTexture;
  3310. if ((int)argAggregate->getSequence().size() == (nextArg+1)) { // last parameter is offset form
  3311. textureOp = EOpTextureOffset;
  3312. argOffset = argAggregate->getSequence()[nextArg++]->getAsTyped();
  3313. }
  3314. TIntermAggregate* txcombine = handleSamplerTextureCombine(loc, argTex, argSamp);
  3315. TIntermAggregate* txsample = new TIntermAggregate(textureOp);
  3316. txsample->getSequence().push_back(txcombine);
  3317. txsample->getSequence().push_back(argCoord);
  3318. if (argBias != nullptr)
  3319. txsample->getSequence().push_back(argBias);
  3320. if (argOffset != nullptr)
  3321. txsample->getSequence().push_back(argOffset);
  3322. node = convertReturn(txsample, sampler);
  3323. break;
  3324. }
  3325. case EOpMethodSampleGrad: // ...
  3326. {
  3327. TIntermTyped* argTex = argAggregate->getSequence()[0]->getAsTyped();
  3328. TIntermTyped* argSamp = argAggregate->getSequence()[1]->getAsTyped();
  3329. TIntermTyped* argCoord = argAggregate->getSequence()[2]->getAsTyped();
  3330. TIntermTyped* argDDX = argAggregate->getSequence()[3]->getAsTyped();
  3331. TIntermTyped* argDDY = argAggregate->getSequence()[4]->getAsTyped();
  3332. TIntermTyped* argOffset = nullptr;
  3333. const TSampler& sampler = argTex->getType().getSampler();
  3334. TOperator textureOp = EOpTextureGrad;
  3335. if (argAggregate->getSequence().size() == 6) { // last parameter is offset form
  3336. textureOp = EOpTextureGradOffset;
  3337. argOffset = argAggregate->getSequence()[5]->getAsTyped();
  3338. }
  3339. TIntermAggregate* txcombine = handleSamplerTextureCombine(loc, argTex, argSamp);
  3340. TIntermAggregate* txsample = new TIntermAggregate(textureOp);
  3341. txsample->getSequence().push_back(txcombine);
  3342. txsample->getSequence().push_back(argCoord);
  3343. txsample->getSequence().push_back(argDDX);
  3344. txsample->getSequence().push_back(argDDY);
  3345. if (argOffset != nullptr)
  3346. txsample->getSequence().push_back(argOffset);
  3347. node = convertReturn(txsample, sampler);
  3348. break;
  3349. }
  3350. case EOpMethodGetDimensions:
  3351. {
  3352. // AST returns a vector of results, which we break apart component-wise into
  3353. // separate values to assign to the HLSL method's outputs, ala:
  3354. // tx . GetDimensions(width, height);
  3355. // float2 sizeQueryTemp = EOpTextureQuerySize
  3356. // width = sizeQueryTemp.X;
  3357. // height = sizeQueryTemp.Y;
  3358. TIntermTyped* argTex = argAggregate->getSequence()[0]->getAsTyped();
  3359. const TType& texType = argTex->getType();
  3360. assert(texType.getBasicType() == EbtSampler);
  3361. const TSampler& sampler = texType.getSampler();
  3362. const TSamplerDim dim = sampler.dim;
  3363. const bool isImage = sampler.isImage();
  3364. const bool isMs = sampler.isMultiSample();
  3365. const int numArgs = (int)argAggregate->getSequence().size();
  3366. int numDims = 0;
  3367. switch (dim) {
  3368. case Esd1D: numDims = 1; break; // W
  3369. case Esd2D: numDims = 2; break; // W, H
  3370. case Esd3D: numDims = 3; break; // W, H, D
  3371. case EsdCube: numDims = 2; break; // W, H (cube)
  3372. case EsdBuffer: numDims = 1; break; // W (buffers)
  3373. case EsdRect: numDims = 2; break; // W, H (rect)
  3374. default:
  3375. assert(0 && "unhandled texture dimension");
  3376. }
  3377. // Arrayed adds another dimension for the number of array elements
  3378. if (sampler.isArrayed())
  3379. ++numDims;
  3380. // Establish whether the method itself is querying mip levels. This can be false even
  3381. // if the underlying query requires a MIP level, due to the available HLSL method overloads.
  3382. const bool mipQuery = (numArgs > (numDims + 1 + (isMs ? 1 : 0)));
  3383. // Establish whether we must use the LOD form of query (even if the method did not supply a mip level to query).
  3384. // True if:
  3385. // 1. 1D/2D/3D/Cube AND multisample==0 AND NOT image (those can be sent to the non-LOD query)
  3386. // or,
  3387. // 2. There is a LOD (because the non-LOD query cannot be used in that case, per spec)
  3388. const bool mipRequired =
  3389. ((dim == Esd1D || dim == Esd2D || dim == Esd3D || dim == EsdCube) && !isMs && !isImage) || // 1...
  3390. mipQuery; // 2...
  3391. // AST assumes integer return. Will be converted to float if required.
  3392. TIntermAggregate* sizeQuery = new TIntermAggregate(isImage ? EOpImageQuerySize : EOpTextureQuerySize);
  3393. sizeQuery->getSequence().push_back(argTex);
  3394. // If we're building an LOD query, add the LOD.
  3395. if (mipRequired) {
  3396. // If the base HLSL query had no MIP level given, use level 0.
  3397. TIntermTyped* queryLod = mipQuery ? argAggregate->getSequence()[1]->getAsTyped() :
  3398. intermediate.addConstantUnion(0, loc, true);
  3399. sizeQuery->getSequence().push_back(queryLod);
  3400. }
  3401. sizeQuery->setType(TType(EbtUint, EvqTemporary, numDims));
  3402. sizeQuery->setLoc(loc);
  3403. // Return value from size query
  3404. TVariable* tempArg = makeInternalVariable("sizeQueryTemp", sizeQuery->getType());
  3405. tempArg->getWritableType().getQualifier().makeTemporary();
  3406. TIntermTyped* sizeQueryAssign = intermediate.addAssign(EOpAssign,
  3407. intermediate.addSymbol(*tempArg, loc),
  3408. sizeQuery, loc);
  3409. // Compound statement for assigning outputs
  3410. TIntermAggregate* compoundStatement = intermediate.makeAggregate(sizeQueryAssign, loc);
  3411. // Index of first output parameter
  3412. const int outParamBase = mipQuery ? 2 : 1;
  3413. for (int compNum = 0; compNum < numDims; ++compNum) {
  3414. TIntermTyped* indexedOut = nullptr;
  3415. TIntermSymbol* sizeQueryReturn = intermediate.addSymbol(*tempArg, loc);
  3416. if (numDims > 1) {
  3417. TIntermTyped* component = intermediate.addConstantUnion(compNum, loc, true);
  3418. indexedOut = intermediate.addIndex(EOpIndexDirect, sizeQueryReturn, component, loc);
  3419. indexedOut->setType(TType(EbtUint, EvqTemporary, 1));
  3420. indexedOut->setLoc(loc);
  3421. } else {
  3422. indexedOut = sizeQueryReturn;
  3423. }
  3424. TIntermTyped* outParam = argAggregate->getSequence()[outParamBase + compNum]->getAsTyped();
  3425. TIntermTyped* compAssign = intermediate.addAssign(EOpAssign, outParam, indexedOut, loc);
  3426. compoundStatement = intermediate.growAggregate(compoundStatement, compAssign);
  3427. }
  3428. // handle mip level parameter
  3429. if (mipQuery) {
  3430. TIntermTyped* outParam = argAggregate->getSequence()[outParamBase + numDims]->getAsTyped();
  3431. TIntermAggregate* levelsQuery = new TIntermAggregate(EOpTextureQueryLevels);
  3432. levelsQuery->getSequence().push_back(argTex);
  3433. levelsQuery->setType(TType(EbtUint, EvqTemporary, 1));
  3434. levelsQuery->setLoc(loc);
  3435. TIntermTyped* compAssign = intermediate.addAssign(EOpAssign, outParam, levelsQuery, loc);
  3436. compoundStatement = intermediate.growAggregate(compoundStatement, compAssign);
  3437. }
  3438. // 2DMS formats query # samples, which needs a different query op
  3439. if (sampler.isMultiSample()) {
  3440. TIntermTyped* outParam = argAggregate->getSequence()[outParamBase + numDims]->getAsTyped();
  3441. TIntermAggregate* samplesQuery = new TIntermAggregate(EOpImageQuerySamples);
  3442. samplesQuery->getSequence().push_back(argTex);
  3443. samplesQuery->setType(TType(EbtUint, EvqTemporary, 1));
  3444. samplesQuery->setLoc(loc);
  3445. TIntermTyped* compAssign = intermediate.addAssign(EOpAssign, outParam, samplesQuery, loc);
  3446. compoundStatement = intermediate.growAggregate(compoundStatement, compAssign);
  3447. }
  3448. compoundStatement->setOperator(EOpSequence);
  3449. compoundStatement->setLoc(loc);
  3450. compoundStatement->setType(TType(EbtVoid));
  3451. node = compoundStatement;
  3452. break;
  3453. }
  3454. case EOpMethodSampleCmp: // fall through...
  3455. case EOpMethodSampleCmpLevelZero:
  3456. {
  3457. TIntermTyped* argTex = argAggregate->getSequence()[0]->getAsTyped();
  3458. TIntermTyped* argSamp = argAggregate->getSequence()[1]->getAsTyped();
  3459. TIntermTyped* argCoord = argAggregate->getSequence()[2]->getAsTyped();
  3460. TIntermTyped* argCmpVal = argAggregate->getSequence()[3]->getAsTyped();
  3461. TIntermTyped* argOffset = nullptr;
  3462. // Sampler argument should be a sampler.
  3463. if (argSamp->getType().getBasicType() != EbtSampler) {
  3464. error(loc, "expected: sampler type", "", "");
  3465. return;
  3466. }
  3467. // Sampler should be a SamplerComparisonState
  3468. if (! argSamp->getType().getSampler().isShadow()) {
  3469. error(loc, "expected: SamplerComparisonState", "", "");
  3470. return;
  3471. }
  3472. // optional offset value
  3473. if (argAggregate->getSequence().size() > 4)
  3474. argOffset = argAggregate->getSequence()[4]->getAsTyped();
  3475. const int coordDimWithCmpVal = argCoord->getType().getVectorSize() + 1; // +1 for cmp
  3476. // AST wants comparison value as one of the texture coordinates
  3477. TOperator constructOp = EOpNull;
  3478. switch (coordDimWithCmpVal) {
  3479. // 1D can't happen: there's always at least 1 coordinate dimension + 1 cmp val
  3480. case 2: constructOp = EOpConstructVec2; break;
  3481. case 3: constructOp = EOpConstructVec3; break;
  3482. case 4: constructOp = EOpConstructVec4; break;
  3483. case 5: constructOp = EOpConstructVec4; break; // cubeArrayShadow, cmp value is separate arg.
  3484. default: assert(0); break;
  3485. }
  3486. TIntermAggregate* coordWithCmp = new TIntermAggregate(constructOp);
  3487. coordWithCmp->getSequence().push_back(argCoord);
  3488. if (coordDimWithCmpVal != 5) // cube array shadow is special.
  3489. coordWithCmp->getSequence().push_back(argCmpVal);
  3490. coordWithCmp->setLoc(loc);
  3491. coordWithCmp->setType(TType(argCoord->getBasicType(), EvqTemporary, std::min(coordDimWithCmpVal, 4)));
  3492. TOperator textureOp = (op == EOpMethodSampleCmpLevelZero ? EOpTextureLod : EOpTexture);
  3493. if (argOffset != nullptr)
  3494. textureOp = (op == EOpMethodSampleCmpLevelZero ? EOpTextureLodOffset : EOpTextureOffset);
  3495. // Create combined sampler & texture op
  3496. TIntermAggregate* txcombine = handleSamplerTextureCombine(loc, argTex, argSamp);
  3497. TIntermAggregate* txsample = new TIntermAggregate(textureOp);
  3498. txsample->getSequence().push_back(txcombine);
  3499. txsample->getSequence().push_back(coordWithCmp);
  3500. if (coordDimWithCmpVal == 5) // cube array shadow is special: cmp val follows coord.
  3501. txsample->getSequence().push_back(argCmpVal);
  3502. // the LevelZero form uses 0 as an explicit LOD
  3503. if (op == EOpMethodSampleCmpLevelZero)
  3504. txsample->getSequence().push_back(intermediate.addConstantUnion(0.0, EbtFloat, loc, true));
  3505. // Add offset if present
  3506. if (argOffset != nullptr)
  3507. txsample->getSequence().push_back(argOffset);
  3508. txsample->setType(node->getType());
  3509. txsample->setLoc(loc);
  3510. node = txsample;
  3511. break;
  3512. }
  3513. case EOpMethodLoad:
  3514. {
  3515. TIntermTyped* argTex = argAggregate->getSequence()[0]->getAsTyped();
  3516. TIntermTyped* argCoord = argAggregate->getSequence()[1]->getAsTyped();
  3517. TIntermTyped* argOffset = nullptr;
  3518. TIntermTyped* lodComponent = nullptr;
  3519. TIntermTyped* coordSwizzle = nullptr;
  3520. const TSampler& sampler = argTex->getType().getSampler();
  3521. const bool isMS = sampler.isMultiSample();
  3522. const bool isBuffer = sampler.dim == EsdBuffer;
  3523. const bool isImage = sampler.isImage();
  3524. const TBasicType coordBaseType = argCoord->getType().getBasicType();
  3525. // Last component of coordinate is the mip level, for non-MS. we separate them here:
  3526. if (isMS || isBuffer || isImage) {
  3527. // MS, Buffer, and Image have no LOD
  3528. coordSwizzle = argCoord;
  3529. } else {
  3530. // Extract coordinate
  3531. int swizzleSize = argCoord->getType().getVectorSize() - (isMS ? 0 : 1);
  3532. TSwizzleSelectors<TVectorSelector> coordFields;
  3533. for (int i = 0; i < swizzleSize; ++i)
  3534. coordFields.push_back(i);
  3535. TIntermTyped* coordIdx = intermediate.addSwizzle(coordFields, loc);
  3536. coordSwizzle = intermediate.addIndex(EOpVectorSwizzle, argCoord, coordIdx, loc);
  3537. coordSwizzle->setType(TType(coordBaseType, EvqTemporary, coordFields.size()));
  3538. // Extract LOD
  3539. TIntermTyped* lodIdx = intermediate.addConstantUnion(coordFields.size(), loc, true);
  3540. lodComponent = intermediate.addIndex(EOpIndexDirect, argCoord, lodIdx, loc);
  3541. lodComponent->setType(TType(coordBaseType, EvqTemporary, 1));
  3542. }
  3543. const int numArgs = (int)argAggregate->getSequence().size();
  3544. const bool hasOffset = ((!isMS && numArgs == 3) || (isMS && numArgs == 4));
  3545. // Create texel fetch
  3546. const TOperator fetchOp = (isImage ? EOpImageLoad :
  3547. hasOffset ? EOpTextureFetchOffset :
  3548. EOpTextureFetch);
  3549. TIntermAggregate* txfetch = new TIntermAggregate(fetchOp);
  3550. // Build up the fetch
  3551. txfetch->getSequence().push_back(argTex);
  3552. txfetch->getSequence().push_back(coordSwizzle);
  3553. if (isMS) {
  3554. // add 2DMS sample index
  3555. TIntermTyped* argSampleIdx = argAggregate->getSequence()[2]->getAsTyped();
  3556. txfetch->getSequence().push_back(argSampleIdx);
  3557. } else if (isBuffer) {
  3558. // Nothing else to do for buffers.
  3559. } else if (isImage) {
  3560. // Nothing else to do for images.
  3561. } else {
  3562. // 2DMS and buffer have no LOD, but everything else does.
  3563. txfetch->getSequence().push_back(lodComponent);
  3564. }
  3565. // Obtain offset arg, if there is one.
  3566. if (hasOffset) {
  3567. const int offsetPos = (isMS ? 3 : 2);
  3568. argOffset = argAggregate->getSequence()[offsetPos]->getAsTyped();
  3569. txfetch->getSequence().push_back(argOffset);
  3570. }
  3571. node = convertReturn(txfetch, sampler);
  3572. break;
  3573. }
  3574. case EOpMethodSampleLevel:
  3575. {
  3576. TIntermTyped* argTex = argAggregate->getSequence()[0]->getAsTyped();
  3577. TIntermTyped* argSamp = argAggregate->getSequence()[1]->getAsTyped();
  3578. TIntermTyped* argCoord = argAggregate->getSequence()[2]->getAsTyped();
  3579. TIntermTyped* argLod = argAggregate->getSequence()[3]->getAsTyped();
  3580. TIntermTyped* argOffset = nullptr;
  3581. const TSampler& sampler = argTex->getType().getSampler();
  3582. const int numArgs = (int)argAggregate->getSequence().size();
  3583. if (numArgs == 5) // offset, if present
  3584. argOffset = argAggregate->getSequence()[4]->getAsTyped();
  3585. const TOperator textureOp = (argOffset == nullptr ? EOpTextureLod : EOpTextureLodOffset);
  3586. TIntermAggregate* txsample = new TIntermAggregate(textureOp);
  3587. TIntermAggregate* txcombine = handleSamplerTextureCombine(loc, argTex, argSamp);
  3588. txsample->getSequence().push_back(txcombine);
  3589. txsample->getSequence().push_back(argCoord);
  3590. txsample->getSequence().push_back(argLod);
  3591. if (argOffset != nullptr)
  3592. txsample->getSequence().push_back(argOffset);
  3593. node = convertReturn(txsample, sampler);
  3594. break;
  3595. }
  3596. case EOpMethodGather:
  3597. {
  3598. TIntermTyped* argTex = argAggregate->getSequence()[0]->getAsTyped();
  3599. TIntermTyped* argSamp = argAggregate->getSequence()[1]->getAsTyped();
  3600. TIntermTyped* argCoord = argAggregate->getSequence()[2]->getAsTyped();
  3601. TIntermTyped* argOffset = nullptr;
  3602. // Offset is optional
  3603. if (argAggregate->getSequence().size() > 3)
  3604. argOffset = argAggregate->getSequence()[3]->getAsTyped();
  3605. const TOperator textureOp = (argOffset == nullptr ? EOpTextureGather : EOpTextureGatherOffset);
  3606. TIntermAggregate* txgather = new TIntermAggregate(textureOp);
  3607. TIntermAggregate* txcombine = handleSamplerTextureCombine(loc, argTex, argSamp);
  3608. txgather->getSequence().push_back(txcombine);
  3609. txgather->getSequence().push_back(argCoord);
  3610. // Offset if not given is implicitly channel 0 (red)
  3611. if (argOffset != nullptr)
  3612. txgather->getSequence().push_back(argOffset);
  3613. txgather->setType(node->getType());
  3614. txgather->setLoc(loc);
  3615. node = txgather;
  3616. break;
  3617. }
  3618. case EOpMethodGatherRed: // fall through...
  3619. case EOpMethodGatherGreen: // ...
  3620. case EOpMethodGatherBlue: // ...
  3621. case EOpMethodGatherAlpha: // ...
  3622. case EOpMethodGatherCmpRed: // ...
  3623. case EOpMethodGatherCmpGreen: // ...
  3624. case EOpMethodGatherCmpBlue: // ...
  3625. case EOpMethodGatherCmpAlpha: // ...
  3626. {
  3627. int channel = 0; // the channel we are gathering
  3628. int cmpValues = 0; // 1 if there is a compare value (handier than a bool below)
  3629. switch (op) {
  3630. case EOpMethodGatherCmpRed: cmpValues = 1; // fall through
  3631. case EOpMethodGatherRed: channel = 0; break;
  3632. case EOpMethodGatherCmpGreen: cmpValues = 1; // fall through
  3633. case EOpMethodGatherGreen: channel = 1; break;
  3634. case EOpMethodGatherCmpBlue: cmpValues = 1; // fall through
  3635. case EOpMethodGatherBlue: channel = 2; break;
  3636. case EOpMethodGatherCmpAlpha: cmpValues = 1; // fall through
  3637. case EOpMethodGatherAlpha: channel = 3; break;
  3638. default: assert(0); break;
  3639. }
  3640. // For now, we have nothing to map the component-wise comparison forms
  3641. // to, because neither GLSL nor SPIR-V has such an opcode. Issue an
  3642. // unimplemented error instead. Most of the machinery is here if that
  3643. // should ever become available. However, red can be passed through
  3644. // to OpImageDrefGather. G/B/A cannot, because that opcode does not
  3645. // accept a component.
  3646. if (cmpValues != 0 && op != EOpMethodGatherCmpRed) {
  3647. error(loc, "unimplemented: component-level gather compare", "", "");
  3648. return;
  3649. }
  3650. int arg = 0;
  3651. TIntermTyped* argTex = argAggregate->getSequence()[arg++]->getAsTyped();
  3652. TIntermTyped* argSamp = argAggregate->getSequence()[arg++]->getAsTyped();
  3653. TIntermTyped* argCoord = argAggregate->getSequence()[arg++]->getAsTyped();
  3654. TIntermTyped* argOffset = nullptr;
  3655. TIntermTyped* argOffsets[4] = { nullptr, nullptr, nullptr, nullptr };
  3656. // TIntermTyped* argStatus = nullptr; // TODO: residency
  3657. TIntermTyped* argCmp = nullptr;
  3658. const TSamplerDim dim = argTex->getType().getSampler().dim;
  3659. const int argSize = (int)argAggregate->getSequence().size();
  3660. bool hasStatus = (argSize == (5+cmpValues) || argSize == (8+cmpValues));
  3661. bool hasOffset1 = false;
  3662. bool hasOffset4 = false;
  3663. // Sampler argument should be a sampler.
  3664. if (argSamp->getType().getBasicType() != EbtSampler) {
  3665. error(loc, "expected: sampler type", "", "");
  3666. return;
  3667. }
  3668. // Cmp forms require SamplerComparisonState
  3669. if (cmpValues > 0 && ! argSamp->getType().getSampler().isShadow()) {
  3670. error(loc, "expected: SamplerComparisonState", "", "");
  3671. return;
  3672. }
  3673. // Only 2D forms can have offsets. Discover if we have 0, 1 or 4 offsets.
  3674. if (dim == Esd2D) {
  3675. hasOffset1 = (argSize == (4+cmpValues) || argSize == (5+cmpValues));
  3676. hasOffset4 = (argSize == (7+cmpValues) || argSize == (8+cmpValues));
  3677. }
  3678. assert(!(hasOffset1 && hasOffset4));
  3679. TOperator textureOp = EOpTextureGather;
  3680. // Compare forms have compare value
  3681. if (cmpValues != 0)
  3682. argCmp = argOffset = argAggregate->getSequence()[arg++]->getAsTyped();
  3683. // Some forms have single offset
  3684. if (hasOffset1) {
  3685. textureOp = EOpTextureGatherOffset; // single offset form
  3686. argOffset = argAggregate->getSequence()[arg++]->getAsTyped();
  3687. }
  3688. // Some forms have 4 gather offsets
  3689. if (hasOffset4) {
  3690. textureOp = EOpTextureGatherOffsets; // note plural, for 4 offset form
  3691. for (int offsetNum = 0; offsetNum < 4; ++offsetNum)
  3692. argOffsets[offsetNum] = argAggregate->getSequence()[arg++]->getAsTyped();
  3693. }
  3694. // Residency status
  3695. if (hasStatus) {
  3696. // argStatus = argAggregate->getSequence()[arg++]->getAsTyped();
  3697. error(loc, "unimplemented: residency status", "", "");
  3698. return;
  3699. }
  3700. TIntermAggregate* txgather = new TIntermAggregate(textureOp);
  3701. TIntermAggregate* txcombine = handleSamplerTextureCombine(loc, argTex, argSamp);
  3702. TIntermTyped* argChannel = intermediate.addConstantUnion(channel, loc, true);
  3703. txgather->getSequence().push_back(txcombine);
  3704. txgather->getSequence().push_back(argCoord);
  3705. // AST wants an array of 4 offsets, where HLSL has separate args. Here
  3706. // we construct an array from the separate args.
  3707. if (hasOffset4) {
  3708. TType arrayType(EbtInt, EvqTemporary, 2);
  3709. TArraySizes* arraySizes = new TArraySizes;
  3710. arraySizes->addInnerSize(4);
  3711. arrayType.transferArraySizes(arraySizes);
  3712. TIntermAggregate* initList = new TIntermAggregate(EOpNull);
  3713. for (int offsetNum = 0; offsetNum < 4; ++offsetNum)
  3714. initList->getSequence().push_back(argOffsets[offsetNum]);
  3715. argOffset = addConstructor(loc, initList, arrayType);
  3716. }
  3717. // Add comparison value if we have one
  3718. if (argCmp != nullptr)
  3719. txgather->getSequence().push_back(argCmp);
  3720. // Add offset (either 1, or an array of 4) if we have one
  3721. if (argOffset != nullptr)
  3722. txgather->getSequence().push_back(argOffset);
  3723. // Add channel value if the sampler is not shadow
  3724. if (! argSamp->getType().getSampler().isShadow())
  3725. txgather->getSequence().push_back(argChannel);
  3726. txgather->setType(node->getType());
  3727. txgather->setLoc(loc);
  3728. node = txgather;
  3729. break;
  3730. }
  3731. case EOpMethodCalculateLevelOfDetail:
  3732. case EOpMethodCalculateLevelOfDetailUnclamped:
  3733. {
  3734. TIntermTyped* argTex = argAggregate->getSequence()[0]->getAsTyped();
  3735. TIntermTyped* argSamp = argAggregate->getSequence()[1]->getAsTyped();
  3736. TIntermTyped* argCoord = argAggregate->getSequence()[2]->getAsTyped();
  3737. TIntermAggregate* txquerylod = new TIntermAggregate(EOpTextureQueryLod);
  3738. TIntermAggregate* txcombine = handleSamplerTextureCombine(loc, argTex, argSamp);
  3739. txquerylod->getSequence().push_back(txcombine);
  3740. txquerylod->getSequence().push_back(argCoord);
  3741. TIntermTyped* lodComponent = intermediate.addConstantUnion(
  3742. op == EOpMethodCalculateLevelOfDetail ? 0 : 1,
  3743. loc, true);
  3744. TIntermTyped* lodComponentIdx = intermediate.addIndex(EOpIndexDirect, txquerylod, lodComponent, loc);
  3745. lodComponentIdx->setType(TType(EbtFloat, EvqTemporary, 1));
  3746. node = lodComponentIdx;
  3747. break;
  3748. }
  3749. case EOpMethodGetSamplePosition:
  3750. {
  3751. // TODO: this entire decomposition exists because there is not yet a way to query
  3752. // the sample position directly through SPIR-V. Instead, we return fixed sample
  3753. // positions for common cases. *** If the sample positions are set differently,
  3754. // this will be wrong. ***
  3755. TIntermTyped* argTex = argAggregate->getSequence()[0]->getAsTyped();
  3756. TIntermTyped* argSampIdx = argAggregate->getSequence()[1]->getAsTyped();
  3757. TIntermAggregate* samplesQuery = new TIntermAggregate(EOpImageQuerySamples);
  3758. samplesQuery->getSequence().push_back(argTex);
  3759. samplesQuery->setType(TType(EbtUint, EvqTemporary, 1));
  3760. samplesQuery->setLoc(loc);
  3761. TIntermAggregate* compoundStatement = nullptr;
  3762. TVariable* outSampleCount = makeInternalVariable("@sampleCount", TType(EbtUint));
  3763. outSampleCount->getWritableType().getQualifier().makeTemporary();
  3764. TIntermTyped* compAssign = intermediate.addAssign(EOpAssign, intermediate.addSymbol(*outSampleCount, loc),
  3765. samplesQuery, loc);
  3766. compoundStatement = intermediate.growAggregate(compoundStatement, compAssign);
  3767. TIntermTyped* idxtest[4];
  3768. // Create tests against 2, 4, 8, and 16 sample values
  3769. int count = 0;
  3770. for (int val = 2; val <= 16; val *= 2)
  3771. idxtest[count++] =
  3772. intermediate.addBinaryNode(EOpEqual,
  3773. intermediate.addSymbol(*outSampleCount, loc),
  3774. intermediate.addConstantUnion(val, loc),
  3775. loc, TType(EbtBool));
  3776. const TOperator idxOp = (argSampIdx->getQualifier().storage == EvqConst) ? EOpIndexDirect : EOpIndexIndirect;
  3777. // Create index ops into position arrays given sample index.
  3778. // TODO: should it be clamped?
  3779. TIntermTyped* index[4];
  3780. count = 0;
  3781. for (int val = 2; val <= 16; val *= 2) {
  3782. index[count] = intermediate.addIndex(idxOp, getSamplePosArray(val), argSampIdx, loc);
  3783. index[count++]->setType(TType(EbtFloat, EvqTemporary, 2));
  3784. }
  3785. // Create expression as:
  3786. // (sampleCount == 2) ? pos2[idx] :
  3787. // (sampleCount == 4) ? pos4[idx] :
  3788. // (sampleCount == 8) ? pos8[idx] :
  3789. // (sampleCount == 16) ? pos16[idx] : float2(0,0);
  3790. TIntermTyped* test =
  3791. intermediate.addSelection(idxtest[0], index[0],
  3792. intermediate.addSelection(idxtest[1], index[1],
  3793. intermediate.addSelection(idxtest[2], index[2],
  3794. intermediate.addSelection(idxtest[3], index[3],
  3795. getSamplePosArray(1), loc), loc), loc), loc);
  3796. compoundStatement = intermediate.growAggregate(compoundStatement, test);
  3797. compoundStatement->setOperator(EOpSequence);
  3798. compoundStatement->setLoc(loc);
  3799. compoundStatement->setType(TType(EbtFloat, EvqTemporary, 2));
  3800. node = compoundStatement;
  3801. break;
  3802. }
  3803. case EOpSubpassLoad:
  3804. {
  3805. const TIntermTyped* argSubpass =
  3806. argAggregate ? argAggregate->getSequence()[0]->getAsTyped() :
  3807. arguments->getAsTyped();
  3808. const TSampler& sampler = argSubpass->getType().getSampler();
  3809. // subpass load: the multisample form is overloaded. Here, we convert that to
  3810. // the EOpSubpassLoadMS opcode.
  3811. if (argAggregate != nullptr && argAggregate->getSequence().size() > 1)
  3812. node->getAsOperator()->setOp(EOpSubpassLoadMS);
  3813. node = convertReturn(node, sampler);
  3814. break;
  3815. }
  3816. default:
  3817. break; // most pass through unchanged
  3818. }
  3819. }
  3820. //
  3821. // Decompose geometry shader methods
  3822. //
  3823. void HlslParseContext::decomposeGeometryMethods(const TSourceLoc& loc, TIntermTyped*& node, TIntermNode* arguments)
  3824. {
  3825. if (node == nullptr || !node->getAsOperator())
  3826. return;
  3827. const TOperator op = node->getAsOperator()->getOp();
  3828. const TIntermAggregate* argAggregate = arguments ? arguments->getAsAggregate() : nullptr;
  3829. switch (op) {
  3830. case EOpMethodAppend:
  3831. if (argAggregate) {
  3832. // Don't emit these for non-GS stage, since we won't have the gsStreamOutput symbol.
  3833. if (language != EShLangGeometry) {
  3834. node = nullptr;
  3835. return;
  3836. }
  3837. TIntermAggregate* sequence = nullptr;
  3838. TIntermAggregate* emit = new TIntermAggregate(EOpEmitVertex);
  3839. emit->setLoc(loc);
  3840. emit->setType(TType(EbtVoid));
  3841. TIntermTyped* data = argAggregate->getSequence()[1]->getAsTyped();
  3842. // This will be patched in finalization during finalizeAppendMethods()
  3843. sequence = intermediate.growAggregate(sequence, data, loc);
  3844. sequence = intermediate.growAggregate(sequence, emit);
  3845. sequence->setOperator(EOpSequence);
  3846. sequence->setLoc(loc);
  3847. sequence->setType(TType(EbtVoid));
  3848. gsAppends.push_back({sequence, loc});
  3849. node = sequence;
  3850. }
  3851. break;
  3852. case EOpMethodRestartStrip:
  3853. {
  3854. // Don't emit these for non-GS stage, since we won't have the gsStreamOutput symbol.
  3855. if (language != EShLangGeometry) {
  3856. node = nullptr;
  3857. return;
  3858. }
  3859. TIntermAggregate* cut = new TIntermAggregate(EOpEndPrimitive);
  3860. cut->setLoc(loc);
  3861. cut->setType(TType(EbtVoid));
  3862. node = cut;
  3863. }
  3864. break;
  3865. default:
  3866. break; // most pass through unchanged
  3867. }
  3868. }
  3869. //
  3870. // Optionally decompose intrinsics to AST opcodes.
  3871. //
  3872. void HlslParseContext::decomposeIntrinsic(const TSourceLoc& loc, TIntermTyped*& node, TIntermNode* arguments)
  3873. {
  3874. // Helper to find image data for image atomics:
  3875. // OpImageLoad(image[idx])
  3876. // We take the image load apart and add its params to the atomic op aggregate node
  3877. const auto imageAtomicParams = [this, &loc, &node](TIntermAggregate* atomic, TIntermTyped* load) {
  3878. TIntermAggregate* loadOp = load->getAsAggregate();
  3879. if (loadOp == nullptr) {
  3880. error(loc, "unknown image type in atomic operation", "", "");
  3881. node = nullptr;
  3882. return;
  3883. }
  3884. atomic->getSequence().push_back(loadOp->getSequence()[0]);
  3885. atomic->getSequence().push_back(loadOp->getSequence()[1]);
  3886. };
  3887. // Return true if this is an imageLoad, which we will change to an image atomic.
  3888. const auto isImageParam = [](TIntermTyped* image) -> bool {
  3889. TIntermAggregate* imageAggregate = image->getAsAggregate();
  3890. return imageAggregate != nullptr && imageAggregate->getOp() == EOpImageLoad;
  3891. };
  3892. const auto lookupBuiltinVariable = [&](const char* name, TBuiltInVariable builtin, TType& type) -> TIntermTyped* {
  3893. TSymbol* symbol = symbolTable.find(name);
  3894. if (nullptr == symbol) {
  3895. type.getQualifier().builtIn = builtin;
  3896. TVariable* variable = new TVariable(NewPoolTString(name), type);
  3897. symbolTable.insert(*variable);
  3898. symbol = symbolTable.find(name);
  3899. assert(symbol && "Inserted symbol could not be found!");
  3900. }
  3901. return intermediate.addSymbol(*(symbol->getAsVariable()), loc);
  3902. };
  3903. // HLSL intrinsics can be pass through to native AST opcodes, or decomposed here to existing AST
  3904. // opcodes for compatibility with existing software stacks.
  3905. static const bool decomposeHlslIntrinsics = true;
  3906. if (!decomposeHlslIntrinsics || !node || !node->getAsOperator())
  3907. return;
  3908. const TIntermAggregate* argAggregate = arguments ? arguments->getAsAggregate() : nullptr;
  3909. TIntermUnary* fnUnary = node->getAsUnaryNode();
  3910. const TOperator op = node->getAsOperator()->getOp();
  3911. switch (op) {
  3912. case EOpGenMul:
  3913. {
  3914. // mul(a,b) -> MatrixTimesMatrix, MatrixTimesVector, MatrixTimesScalar, VectorTimesScalar, Dot, Mul
  3915. // Since we are treating HLSL rows like GLSL columns (the first matrix indirection),
  3916. // we must reverse the operand order here. Hence, arg0 gets sequence[1], etc.
  3917. TIntermTyped* arg0 = argAggregate->getSequence()[1]->getAsTyped();
  3918. TIntermTyped* arg1 = argAggregate->getSequence()[0]->getAsTyped();
  3919. if (arg0->isVector() && arg1->isVector()) { // vec * vec
  3920. node->getAsAggregate()->setOperator(EOpDot);
  3921. } else {
  3922. node = handleBinaryMath(loc, "mul", EOpMul, arg0, arg1);
  3923. }
  3924. break;
  3925. }
  3926. case EOpRcp:
  3927. {
  3928. // rcp(a) -> 1 / a
  3929. TIntermTyped* arg0 = fnUnary->getOperand();
  3930. TBasicType type0 = arg0->getBasicType();
  3931. TIntermTyped* one = intermediate.addConstantUnion(1, type0, loc, true);
  3932. node = handleBinaryMath(loc, "rcp", EOpDiv, one, arg0);
  3933. break;
  3934. }
  3935. case EOpAny: // fall through
  3936. case EOpAll:
  3937. {
  3938. TIntermTyped* typedArg = arguments->getAsTyped();
  3939. // HLSL allows float/etc types here, and the SPIR-V opcode requires a bool.
  3940. // We'll convert here. Note that for efficiency, we could add a smarter
  3941. // decomposition for some type cases, e.g, maybe by decomposing a dot product.
  3942. if (typedArg->getType().getBasicType() != EbtBool) {
  3943. const TType boolType(EbtBool, EvqTemporary,
  3944. typedArg->getVectorSize(),
  3945. typedArg->getMatrixCols(),
  3946. typedArg->getMatrixRows(),
  3947. typedArg->isVector());
  3948. typedArg = intermediate.addConversion(EOpConstructBool, boolType, typedArg);
  3949. node->getAsUnaryNode()->setOperand(typedArg);
  3950. }
  3951. break;
  3952. }
  3953. case EOpSaturate:
  3954. {
  3955. // saturate(a) -> clamp(a,0,1)
  3956. TIntermTyped* arg0 = fnUnary->getOperand();
  3957. TBasicType type0 = arg0->getBasicType();
  3958. TIntermAggregate* clamp = new TIntermAggregate(EOpClamp);
  3959. clamp->getSequence().push_back(arg0);
  3960. clamp->getSequence().push_back(intermediate.addConstantUnion(0, type0, loc, true));
  3961. clamp->getSequence().push_back(intermediate.addConstantUnion(1, type0, loc, true));
  3962. clamp->setLoc(loc);
  3963. clamp->setType(node->getType());
  3964. clamp->getWritableType().getQualifier().makeTemporary();
  3965. node = clamp;
  3966. break;
  3967. }
  3968. case EOpSinCos:
  3969. {
  3970. // sincos(a,b,c) -> b = sin(a), c = cos(a)
  3971. TIntermTyped* arg0 = argAggregate->getSequence()[0]->getAsTyped();
  3972. TIntermTyped* arg1 = argAggregate->getSequence()[1]->getAsTyped();
  3973. TIntermTyped* arg2 = argAggregate->getSequence()[2]->getAsTyped();
  3974. TIntermTyped* sinStatement = handleUnaryMath(loc, "sin", EOpSin, arg0);
  3975. TIntermTyped* cosStatement = handleUnaryMath(loc, "cos", EOpCos, arg0);
  3976. TIntermTyped* sinAssign = intermediate.addAssign(EOpAssign, arg1, sinStatement, loc);
  3977. TIntermTyped* cosAssign = intermediate.addAssign(EOpAssign, arg2, cosStatement, loc);
  3978. TIntermAggregate* compoundStatement = intermediate.makeAggregate(sinAssign, loc);
  3979. compoundStatement = intermediate.growAggregate(compoundStatement, cosAssign);
  3980. compoundStatement->setOperator(EOpSequence);
  3981. compoundStatement->setLoc(loc);
  3982. compoundStatement->setType(TType(EbtVoid));
  3983. node = compoundStatement;
  3984. break;
  3985. }
  3986. case EOpClip:
  3987. {
  3988. // clip(a) -> if (any(a<0)) discard;
  3989. TIntermTyped* arg0 = fnUnary->getOperand();
  3990. TBasicType type0 = arg0->getBasicType();
  3991. TIntermTyped* compareNode = nullptr;
  3992. // For non-scalars: per experiment with FXC compiler, discard if any component < 0.
  3993. if (!arg0->isScalar()) {
  3994. // component-wise compare: a < 0
  3995. TIntermAggregate* less = new TIntermAggregate(EOpLessThan);
  3996. less->getSequence().push_back(arg0);
  3997. less->setLoc(loc);
  3998. // make vec or mat of bool matching dimensions of input
  3999. less->setType(TType(EbtBool, EvqTemporary,
  4000. arg0->getType().getVectorSize(),
  4001. arg0->getType().getMatrixCols(),
  4002. arg0->getType().getMatrixRows(),
  4003. arg0->getType().isVector()));
  4004. // calculate # of components for comparison const
  4005. const int constComponentCount =
  4006. std::max(arg0->getType().getVectorSize(), 1) *
  4007. std::max(arg0->getType().getMatrixCols(), 1) *
  4008. std::max(arg0->getType().getMatrixRows(), 1);
  4009. TConstUnion zero;
  4010. if (arg0->getType().isIntegerDomain())
  4011. zero.setDConst(0);
  4012. else
  4013. zero.setDConst(0.0);
  4014. TConstUnionArray zeros(constComponentCount, zero);
  4015. less->getSequence().push_back(intermediate.addConstantUnion(zeros, arg0->getType(), loc, true));
  4016. compareNode = intermediate.addBuiltInFunctionCall(loc, EOpAny, true, less, TType(EbtBool));
  4017. } else {
  4018. TIntermTyped* zero;
  4019. if (arg0->getType().isIntegerDomain())
  4020. zero = intermediate.addConstantUnion(0, loc, true);
  4021. else
  4022. zero = intermediate.addConstantUnion(0.0, type0, loc, true);
  4023. compareNode = handleBinaryMath(loc, "clip", EOpLessThan, arg0, zero);
  4024. }
  4025. TIntermBranch* killNode = intermediate.addBranch(EOpKill, loc);
  4026. node = new TIntermSelection(compareNode, killNode, nullptr);
  4027. node->setLoc(loc);
  4028. break;
  4029. }
  4030. case EOpLog10:
  4031. {
  4032. // log10(a) -> log2(a) * 0.301029995663981 (== 1/log2(10))
  4033. TIntermTyped* arg0 = fnUnary->getOperand();
  4034. TIntermTyped* log2 = handleUnaryMath(loc, "log2", EOpLog2, arg0);
  4035. TIntermTyped* base = intermediate.addConstantUnion(0.301029995663981f, EbtFloat, loc, true);
  4036. node = handleBinaryMath(loc, "mul", EOpMul, log2, base);
  4037. break;
  4038. }
  4039. case EOpDst:
  4040. {
  4041. // dest.x = 1;
  4042. // dest.y = src0.y * src1.y;
  4043. // dest.z = src0.z;
  4044. // dest.w = src1.w;
  4045. TIntermTyped* arg0 = argAggregate->getSequence()[0]->getAsTyped();
  4046. TIntermTyped* arg1 = argAggregate->getSequence()[1]->getAsTyped();
  4047. TIntermTyped* y = intermediate.addConstantUnion(1, loc, true);
  4048. TIntermTyped* z = intermediate.addConstantUnion(2, loc, true);
  4049. TIntermTyped* w = intermediate.addConstantUnion(3, loc, true);
  4050. TIntermTyped* src0y = intermediate.addIndex(EOpIndexDirect, arg0, y, loc);
  4051. TIntermTyped* src1y = intermediate.addIndex(EOpIndexDirect, arg1, y, loc);
  4052. TIntermTyped* src0z = intermediate.addIndex(EOpIndexDirect, arg0, z, loc);
  4053. TIntermTyped* src1w = intermediate.addIndex(EOpIndexDirect, arg1, w, loc);
  4054. TIntermAggregate* dst = new TIntermAggregate(EOpConstructVec4);
  4055. dst->getSequence().push_back(intermediate.addConstantUnion(1.0, EbtFloat, loc, true));
  4056. dst->getSequence().push_back(handleBinaryMath(loc, "mul", EOpMul, src0y, src1y));
  4057. dst->getSequence().push_back(src0z);
  4058. dst->getSequence().push_back(src1w);
  4059. dst->setType(TType(EbtFloat, EvqTemporary, 4));
  4060. dst->setLoc(loc);
  4061. node = dst;
  4062. break;
  4063. }
  4064. case EOpInterlockedAdd: // optional last argument (if present) is assigned from return value
  4065. case EOpInterlockedMin: // ...
  4066. case EOpInterlockedMax: // ...
  4067. case EOpInterlockedAnd: // ...
  4068. case EOpInterlockedOr: // ...
  4069. case EOpInterlockedXor: // ...
  4070. case EOpInterlockedExchange: // always has output arg
  4071. {
  4072. TIntermTyped* arg0 = argAggregate->getSequence()[0]->getAsTyped(); // dest
  4073. TIntermTyped* arg1 = argAggregate->getSequence()[1]->getAsTyped(); // value
  4074. TIntermTyped* arg2 = nullptr;
  4075. if (argAggregate->getSequence().size() > 2)
  4076. arg2 = argAggregate->getSequence()[2]->getAsTyped();
  4077. const bool isImage = isImageParam(arg0);
  4078. const TOperator atomicOp = mapAtomicOp(loc, op, isImage);
  4079. TIntermAggregate* atomic = new TIntermAggregate(atomicOp);
  4080. atomic->setType(arg0->getType());
  4081. atomic->getWritableType().getQualifier().makeTemporary();
  4082. atomic->setLoc(loc);
  4083. if (isImage) {
  4084. // orig_value = imageAtomicOp(image, loc, data)
  4085. imageAtomicParams(atomic, arg0);
  4086. atomic->getSequence().push_back(arg1);
  4087. if (argAggregate->getSequence().size() > 2) {
  4088. node = intermediate.addAssign(EOpAssign, arg2, atomic, loc);
  4089. } else {
  4090. node = atomic; // no assignment needed, as there was no out var.
  4091. }
  4092. } else {
  4093. // Normal memory variable:
  4094. // arg0 = mem, arg1 = data, arg2(optional,out) = orig_value
  4095. if (argAggregate->getSequence().size() > 2) {
  4096. // optional output param is present. return value goes to arg2.
  4097. atomic->getSequence().push_back(arg0);
  4098. atomic->getSequence().push_back(arg1);
  4099. node = intermediate.addAssign(EOpAssign, arg2, atomic, loc);
  4100. } else {
  4101. // Set the matching operator. Since output is absent, this is all we need to do.
  4102. node->getAsAggregate()->setOperator(atomicOp);
  4103. node->setType(atomic->getType());
  4104. }
  4105. }
  4106. break;
  4107. }
  4108. case EOpInterlockedCompareExchange:
  4109. {
  4110. TIntermTyped* arg0 = argAggregate->getSequence()[0]->getAsTyped(); // dest
  4111. TIntermTyped* arg1 = argAggregate->getSequence()[1]->getAsTyped(); // cmp
  4112. TIntermTyped* arg2 = argAggregate->getSequence()[2]->getAsTyped(); // value
  4113. TIntermTyped* arg3 = argAggregate->getSequence()[3]->getAsTyped(); // orig
  4114. const bool isImage = isImageParam(arg0);
  4115. TIntermAggregate* atomic = new TIntermAggregate(mapAtomicOp(loc, op, isImage));
  4116. atomic->setLoc(loc);
  4117. atomic->setType(arg2->getType());
  4118. atomic->getWritableType().getQualifier().makeTemporary();
  4119. if (isImage) {
  4120. imageAtomicParams(atomic, arg0);
  4121. } else {
  4122. atomic->getSequence().push_back(arg0);
  4123. }
  4124. atomic->getSequence().push_back(arg1);
  4125. atomic->getSequence().push_back(arg2);
  4126. node = intermediate.addAssign(EOpAssign, arg3, atomic, loc);
  4127. break;
  4128. }
  4129. case EOpEvaluateAttributeSnapped:
  4130. {
  4131. // SPIR-V InterpolateAtOffset uses float vec2 offset in pixels
  4132. // HLSL uses int2 offset on a 16x16 grid in [-8..7] on x & y:
  4133. // iU = (iU<<28)>>28
  4134. // fU = ((float)iU)/16
  4135. // Targets might handle this natively, in which case they can disable
  4136. // decompositions.
  4137. TIntermTyped* arg0 = argAggregate->getSequence()[0]->getAsTyped(); // value
  4138. TIntermTyped* arg1 = argAggregate->getSequence()[1]->getAsTyped(); // offset
  4139. TIntermTyped* i28 = intermediate.addConstantUnion(28, loc, true);
  4140. TIntermTyped* iU = handleBinaryMath(loc, ">>", EOpRightShift,
  4141. handleBinaryMath(loc, "<<", EOpLeftShift, arg1, i28),
  4142. i28);
  4143. TIntermTyped* recip16 = intermediate.addConstantUnion((1.0/16.0), EbtFloat, loc, true);
  4144. TIntermTyped* floatOffset = handleBinaryMath(loc, "mul", EOpMul,
  4145. intermediate.addConversion(EOpConstructFloat,
  4146. TType(EbtFloat, EvqTemporary, 2), iU),
  4147. recip16);
  4148. TIntermAggregate* interp = new TIntermAggregate(EOpInterpolateAtOffset);
  4149. interp->getSequence().push_back(arg0);
  4150. interp->getSequence().push_back(floatOffset);
  4151. interp->setLoc(loc);
  4152. interp->setType(arg0->getType());
  4153. interp->getWritableType().getQualifier().makeTemporary();
  4154. node = interp;
  4155. break;
  4156. }
  4157. case EOpLit:
  4158. {
  4159. TIntermTyped* n_dot_l = argAggregate->getSequence()[0]->getAsTyped();
  4160. TIntermTyped* n_dot_h = argAggregate->getSequence()[1]->getAsTyped();
  4161. TIntermTyped* m = argAggregate->getSequence()[2]->getAsTyped();
  4162. TIntermAggregate* dst = new TIntermAggregate(EOpConstructVec4);
  4163. // Ambient
  4164. dst->getSequence().push_back(intermediate.addConstantUnion(1.0, EbtFloat, loc, true));
  4165. // Diffuse:
  4166. TIntermTyped* zero = intermediate.addConstantUnion(0.0, EbtFloat, loc, true);
  4167. TIntermAggregate* diffuse = new TIntermAggregate(EOpMax);
  4168. diffuse->getSequence().push_back(n_dot_l);
  4169. diffuse->getSequence().push_back(zero);
  4170. diffuse->setLoc(loc);
  4171. diffuse->setType(TType(EbtFloat));
  4172. dst->getSequence().push_back(diffuse);
  4173. // Specular:
  4174. TIntermAggregate* min_ndot = new TIntermAggregate(EOpMin);
  4175. min_ndot->getSequence().push_back(n_dot_l);
  4176. min_ndot->getSequence().push_back(n_dot_h);
  4177. min_ndot->setLoc(loc);
  4178. min_ndot->setType(TType(EbtFloat));
  4179. TIntermTyped* compare = handleBinaryMath(loc, "<", EOpLessThan, min_ndot, zero);
  4180. TIntermTyped* n_dot_h_m = handleBinaryMath(loc, "mul", EOpMul, n_dot_h, m); // n_dot_h * m
  4181. dst->getSequence().push_back(intermediate.addSelection(compare, zero, n_dot_h_m, loc));
  4182. // One:
  4183. dst->getSequence().push_back(intermediate.addConstantUnion(1.0, EbtFloat, loc, true));
  4184. dst->setLoc(loc);
  4185. dst->setType(TType(EbtFloat, EvqTemporary, 4));
  4186. node = dst;
  4187. break;
  4188. }
  4189. case EOpAsDouble:
  4190. {
  4191. // asdouble accepts two 32 bit ints. we can use EOpUint64BitsToDouble, but must
  4192. // first construct a uint64.
  4193. TIntermTyped* arg0 = argAggregate->getSequence()[0]->getAsTyped();
  4194. TIntermTyped* arg1 = argAggregate->getSequence()[1]->getAsTyped();
  4195. if (arg0->getType().isVector()) { // TODO: ...
  4196. error(loc, "double2 conversion not implemented", "asdouble", "");
  4197. break;
  4198. }
  4199. TIntermAggregate* uint64 = new TIntermAggregate(EOpConstructUVec2);
  4200. uint64->getSequence().push_back(arg0);
  4201. uint64->getSequence().push_back(arg1);
  4202. uint64->setType(TType(EbtUint, EvqTemporary, 2)); // convert 2 uints to a uint2
  4203. uint64->setLoc(loc);
  4204. // bitcast uint2 to a double
  4205. TIntermTyped* convert = new TIntermUnary(EOpUint64BitsToDouble);
  4206. convert->getAsUnaryNode()->setOperand(uint64);
  4207. convert->setLoc(loc);
  4208. convert->setType(TType(EbtDouble, EvqTemporary));
  4209. node = convert;
  4210. break;
  4211. }
  4212. case EOpF16tof32:
  4213. {
  4214. // input uvecN with low 16 bits of each component holding a float16. convert to float32.
  4215. TIntermTyped* argValue = node->getAsUnaryNode()->getOperand();
  4216. TIntermTyped* zero = intermediate.addConstantUnion(0, loc, true);
  4217. const int vecSize = argValue->getType().getVectorSize();
  4218. TOperator constructOp = EOpNull;
  4219. switch (vecSize) {
  4220. case 1: constructOp = EOpNull; break; // direct use, no construct needed
  4221. case 2: constructOp = EOpConstructVec2; break;
  4222. case 3: constructOp = EOpConstructVec3; break;
  4223. case 4: constructOp = EOpConstructVec4; break;
  4224. default: assert(0); break;
  4225. }
  4226. // For scalar case, we don't need to construct another type.
  4227. TIntermAggregate* result = (vecSize > 1) ? new TIntermAggregate(constructOp) : nullptr;
  4228. if (result) {
  4229. result->setType(TType(EbtFloat, EvqTemporary, vecSize));
  4230. result->setLoc(loc);
  4231. }
  4232. for (int idx = 0; idx < vecSize; ++idx) {
  4233. TIntermTyped* idxConst = intermediate.addConstantUnion(idx, loc, true);
  4234. TIntermTyped* component = argValue->getType().isVector() ?
  4235. intermediate.addIndex(EOpIndexDirect, argValue, idxConst, loc) : argValue;
  4236. if (component != argValue)
  4237. component->setType(TType(argValue->getBasicType(), EvqTemporary));
  4238. TIntermTyped* unpackOp = new TIntermUnary(EOpUnpackHalf2x16);
  4239. unpackOp->setType(TType(EbtFloat, EvqTemporary, 2));
  4240. unpackOp->getAsUnaryNode()->setOperand(component);
  4241. unpackOp->setLoc(loc);
  4242. TIntermTyped* lowOrder = intermediate.addIndex(EOpIndexDirect, unpackOp, zero, loc);
  4243. if (result != nullptr) {
  4244. result->getSequence().push_back(lowOrder);
  4245. node = result;
  4246. } else {
  4247. node = lowOrder;
  4248. }
  4249. }
  4250. break;
  4251. }
  4252. case EOpF32tof16:
  4253. {
  4254. // input floatN converted to 16 bit float in low order bits of each component of uintN
  4255. TIntermTyped* argValue = node->getAsUnaryNode()->getOperand();
  4256. TIntermTyped* zero = intermediate.addConstantUnion(0.0, EbtFloat, loc, true);
  4257. const int vecSize = argValue->getType().getVectorSize();
  4258. TOperator constructOp = EOpNull;
  4259. switch (vecSize) {
  4260. case 1: constructOp = EOpNull; break; // direct use, no construct needed
  4261. case 2: constructOp = EOpConstructUVec2; break;
  4262. case 3: constructOp = EOpConstructUVec3; break;
  4263. case 4: constructOp = EOpConstructUVec4; break;
  4264. default: assert(0); break;
  4265. }
  4266. // For scalar case, we don't need to construct another type.
  4267. TIntermAggregate* result = (vecSize > 1) ? new TIntermAggregate(constructOp) : nullptr;
  4268. if (result) {
  4269. result->setType(TType(EbtUint, EvqTemporary, vecSize));
  4270. result->setLoc(loc);
  4271. }
  4272. for (int idx = 0; idx < vecSize; ++idx) {
  4273. TIntermTyped* idxConst = intermediate.addConstantUnion(idx, loc, true);
  4274. TIntermTyped* component = argValue->getType().isVector() ?
  4275. intermediate.addIndex(EOpIndexDirect, argValue, idxConst, loc) : argValue;
  4276. if (component != argValue)
  4277. component->setType(TType(argValue->getBasicType(), EvqTemporary));
  4278. TIntermAggregate* vec2ComponentAndZero = new TIntermAggregate(EOpConstructVec2);
  4279. vec2ComponentAndZero->getSequence().push_back(component);
  4280. vec2ComponentAndZero->getSequence().push_back(zero);
  4281. vec2ComponentAndZero->setType(TType(EbtFloat, EvqTemporary, 2));
  4282. vec2ComponentAndZero->setLoc(loc);
  4283. TIntermTyped* packOp = new TIntermUnary(EOpPackHalf2x16);
  4284. packOp->getAsUnaryNode()->setOperand(vec2ComponentAndZero);
  4285. packOp->setLoc(loc);
  4286. packOp->setType(TType(EbtUint, EvqTemporary));
  4287. if (result != nullptr) {
  4288. result->getSequence().push_back(packOp);
  4289. node = result;
  4290. } else {
  4291. node = packOp;
  4292. }
  4293. }
  4294. break;
  4295. }
  4296. case EOpD3DCOLORtoUBYTE4:
  4297. {
  4298. // ivec4 ( x.zyxw * 255.001953 );
  4299. TIntermTyped* arg0 = node->getAsUnaryNode()->getOperand();
  4300. TSwizzleSelectors<TVectorSelector> selectors;
  4301. selectors.push_back(2);
  4302. selectors.push_back(1);
  4303. selectors.push_back(0);
  4304. selectors.push_back(3);
  4305. TIntermTyped* swizzleIdx = intermediate.addSwizzle(selectors, loc);
  4306. TIntermTyped* swizzled = intermediate.addIndex(EOpVectorSwizzle, arg0, swizzleIdx, loc);
  4307. swizzled->setType(arg0->getType());
  4308. swizzled->getWritableType().getQualifier().makeTemporary();
  4309. TIntermTyped* conversion = intermediate.addConstantUnion(255.001953f, EbtFloat, loc, true);
  4310. TIntermTyped* rangeConverted = handleBinaryMath(loc, "mul", EOpMul, conversion, swizzled);
  4311. rangeConverted->setType(arg0->getType());
  4312. rangeConverted->getWritableType().getQualifier().makeTemporary();
  4313. node = intermediate.addConversion(EOpConstructInt, TType(EbtInt, EvqTemporary, 4), rangeConverted);
  4314. node->setLoc(loc);
  4315. node->setType(TType(EbtInt, EvqTemporary, 4));
  4316. break;
  4317. }
  4318. case EOpIsFinite:
  4319. {
  4320. // Since OPIsFinite in SPIR-V is only supported with the Kernel capability, we translate
  4321. // it to !isnan && !isinf
  4322. TIntermTyped* arg0 = node->getAsUnaryNode()->getOperand();
  4323. // We'll make a temporary in case the RHS is cmoplex
  4324. TVariable* tempArg = makeInternalVariable("@finitetmp", arg0->getType());
  4325. tempArg->getWritableType().getQualifier().makeTemporary();
  4326. TIntermTyped* tmpArgAssign = intermediate.addAssign(EOpAssign,
  4327. intermediate.addSymbol(*tempArg, loc),
  4328. arg0, loc);
  4329. TIntermAggregate* compoundStatement = intermediate.makeAggregate(tmpArgAssign, loc);
  4330. const TType boolType(EbtBool, EvqTemporary, arg0->getVectorSize(), arg0->getMatrixCols(),
  4331. arg0->getMatrixRows());
  4332. TIntermTyped* isnan = handleUnaryMath(loc, "isnan", EOpIsNan, intermediate.addSymbol(*tempArg, loc));
  4333. isnan->setType(boolType);
  4334. TIntermTyped* notnan = handleUnaryMath(loc, "!", EOpLogicalNot, isnan);
  4335. notnan->setType(boolType);
  4336. TIntermTyped* isinf = handleUnaryMath(loc, "isinf", EOpIsInf, intermediate.addSymbol(*tempArg, loc));
  4337. isinf->setType(boolType);
  4338. TIntermTyped* notinf = handleUnaryMath(loc, "!", EOpLogicalNot, isinf);
  4339. notinf->setType(boolType);
  4340. TIntermTyped* andNode = handleBinaryMath(loc, "and", EOpLogicalAnd, notnan, notinf);
  4341. andNode->setType(boolType);
  4342. compoundStatement = intermediate.growAggregate(compoundStatement, andNode);
  4343. compoundStatement->setOperator(EOpSequence);
  4344. compoundStatement->setLoc(loc);
  4345. compoundStatement->setType(boolType);
  4346. node = compoundStatement;
  4347. break;
  4348. }
  4349. case EOpWaveGetLaneCount:
  4350. {
  4351. // Mapped to gl_SubgroupSize builtin (We preprend @ to the symbol
  4352. // so that it inhabits the symbol table, but has a user-invalid name
  4353. // in-case some source HLSL defined the symbol also).
  4354. TType type(EbtUint, EvqVaryingIn);
  4355. node = lookupBuiltinVariable("@gl_SubgroupSize", EbvSubgroupSize2, type);
  4356. break;
  4357. }
  4358. case EOpWaveGetLaneIndex:
  4359. {
  4360. // Mapped to gl_SubgroupInvocationID builtin (We preprend @ to the
  4361. // symbol so that it inhabits the symbol table, but has a
  4362. // user-invalid name in-case some source HLSL defined the symbol
  4363. // also).
  4364. TType type(EbtUint, EvqVaryingIn);
  4365. node = lookupBuiltinVariable("@gl_SubgroupInvocationID", EbvSubgroupInvocation2, type);
  4366. break;
  4367. }
  4368. case EOpWaveActiveCountBits:
  4369. {
  4370. // Mapped to subgroupBallotBitCount(subgroupBallot()) builtin
  4371. // uvec4 type.
  4372. TType uvec4Type(EbtUint, EvqTemporary, 4);
  4373. // Get the uvec4 return from subgroupBallot().
  4374. TIntermTyped* res = intermediate.addBuiltInFunctionCall(loc,
  4375. EOpSubgroupBallot, true, arguments, uvec4Type);
  4376. // uint type.
  4377. TType uintType(EbtUint, EvqTemporary);
  4378. node = intermediate.addBuiltInFunctionCall(loc,
  4379. EOpSubgroupBallotBitCount, true, res, uintType);
  4380. break;
  4381. }
  4382. case EOpWavePrefixCountBits:
  4383. {
  4384. // Mapped to subgroupBallotInclusiveBitCount(subgroupBallot())
  4385. // builtin
  4386. // uvec4 type.
  4387. TType uvec4Type(EbtUint, EvqTemporary, 4);
  4388. // Get the uvec4 return from subgroupBallot().
  4389. TIntermTyped* res = intermediate.addBuiltInFunctionCall(loc,
  4390. EOpSubgroupBallot, true, arguments, uvec4Type);
  4391. // uint type.
  4392. TType uintType(EbtUint, EvqTemporary);
  4393. node = intermediate.addBuiltInFunctionCall(loc,
  4394. EOpSubgroupBallotInclusiveBitCount, true, res, uintType);
  4395. break;
  4396. }
  4397. default:
  4398. break; // most pass through unchanged
  4399. }
  4400. }
  4401. //
  4402. // Handle seeing function call syntax in the grammar, which could be any of
  4403. // - .length() method
  4404. // - constructor
  4405. // - a call to a built-in function mapped to an operator
  4406. // - a call to a built-in function that will remain a function call (e.g., texturing)
  4407. // - user function
  4408. // - subroutine call (not implemented yet)
  4409. //
  4410. TIntermTyped* HlslParseContext::handleFunctionCall(const TSourceLoc& loc, TFunction* function, TIntermTyped* arguments)
  4411. {
  4412. TIntermTyped* result = nullptr;
  4413. TOperator op = function->getBuiltInOp();
  4414. if (op != EOpNull) {
  4415. //
  4416. // Then this should be a constructor.
  4417. // Don't go through the symbol table for constructors.
  4418. // Their parameters will be verified algorithmically.
  4419. //
  4420. TType type(EbtVoid); // use this to get the type back
  4421. if (! constructorError(loc, arguments, *function, op, type)) {
  4422. //
  4423. // It's a constructor, of type 'type'.
  4424. //
  4425. result = handleConstructor(loc, arguments, type);
  4426. if (result == nullptr) {
  4427. error(loc, "cannot construct with these arguments", type.getCompleteString().c_str(), "");
  4428. return nullptr;
  4429. }
  4430. }
  4431. } else {
  4432. //
  4433. // Find it in the symbol table.
  4434. //
  4435. const TFunction* fnCandidate = nullptr;
  4436. bool builtIn = false;
  4437. int thisDepth = 0;
  4438. // For mat mul, the situation is unusual: we have to compare vector sizes to mat row or col sizes,
  4439. // and clamp the opposite arg. Since that's complex, we farm it off to a separate method.
  4440. // It doesn't naturally fall out of processing an argument at a time in isolation.
  4441. if (function->getName() == "mul")
  4442. addGenMulArgumentConversion(loc, *function, arguments);
  4443. TIntermAggregate* aggregate = arguments ? arguments->getAsAggregate() : nullptr;
  4444. // TODO: this needs improvement: there's no way at present to look up a signature in
  4445. // the symbol table for an arbitrary type. This is a temporary hack until that ability exists.
  4446. // It will have false positives, since it doesn't check arg counts or types.
  4447. if (arguments) {
  4448. // Check if first argument is struct buffer type. It may be an aggregate or a symbol, so we
  4449. // look for either case.
  4450. TIntermTyped* arg0 = nullptr;
  4451. if (aggregate && aggregate->getSequence().size() > 0 && aggregate->getSequence()[0])
  4452. arg0 = aggregate->getSequence()[0]->getAsTyped();
  4453. else if (arguments->getAsSymbolNode())
  4454. arg0 = arguments->getAsSymbolNode();
  4455. if (arg0 != nullptr && isStructBufferType(arg0->getType())) {
  4456. static const int methodPrefixSize = sizeof(BUILTIN_PREFIX)-1;
  4457. if (function->getName().length() > methodPrefixSize &&
  4458. isStructBufferMethod(function->getName().substr(methodPrefixSize))) {
  4459. const TString mangle = function->getName() + "(";
  4460. TSymbol* symbol = symbolTable.find(mangle, &builtIn);
  4461. if (symbol)
  4462. fnCandidate = symbol->getAsFunction();
  4463. }
  4464. }
  4465. }
  4466. if (fnCandidate == nullptr)
  4467. fnCandidate = findFunction(loc, *function, builtIn, thisDepth, arguments);
  4468. if (fnCandidate) {
  4469. // This is a declared function that might map to
  4470. // - a built-in operator,
  4471. // - a built-in function not mapped to an operator, or
  4472. // - a user function.
  4473. // turn an implicit member-function resolution into an explicit call
  4474. TString callerName;
  4475. if (thisDepth == 0)
  4476. callerName = fnCandidate->getMangledName();
  4477. else {
  4478. // get the explicit (full) name of the function
  4479. callerName = currentTypePrefix[currentTypePrefix.size() - thisDepth];
  4480. callerName += fnCandidate->getMangledName();
  4481. // insert the implicit calling argument
  4482. pushFrontArguments(intermediate.addSymbol(*getImplicitThis(thisDepth)), arguments);
  4483. }
  4484. // Convert 'in' arguments, so that types match.
  4485. // However, skip those that need expansion, that is covered next.
  4486. if (arguments)
  4487. addInputArgumentConversions(*fnCandidate, arguments);
  4488. // Expand arguments. Some arguments must physically expand to a different set
  4489. // than what the shader declared and passes.
  4490. if (arguments && !builtIn)
  4491. expandArguments(loc, *fnCandidate, arguments);
  4492. // Expansion may have changed the form of arguments
  4493. aggregate = arguments ? arguments->getAsAggregate() : nullptr;
  4494. op = fnCandidate->getBuiltInOp();
  4495. if (builtIn && op != EOpNull) {
  4496. // A function call mapped to a built-in operation.
  4497. result = intermediate.addBuiltInFunctionCall(loc, op, fnCandidate->getParamCount() == 1, arguments,
  4498. fnCandidate->getType());
  4499. if (result == nullptr) {
  4500. error(arguments->getLoc(), " wrong operand type", "Internal Error",
  4501. "built in unary operator function. Type: %s",
  4502. static_cast<TIntermTyped*>(arguments)->getCompleteString().c_str());
  4503. } else if (result->getAsOperator()) {
  4504. builtInOpCheck(loc, *fnCandidate, *result->getAsOperator());
  4505. }
  4506. } else {
  4507. // This is a function call not mapped to built-in operator.
  4508. // It could still be a built-in function, but only if PureOperatorBuiltins == false.
  4509. result = intermediate.setAggregateOperator(arguments, EOpFunctionCall, fnCandidate->getType(), loc);
  4510. TIntermAggregate* call = result->getAsAggregate();
  4511. call->setName(callerName);
  4512. // this is how we know whether the given function is a built-in function or a user-defined function
  4513. // if builtIn == false, it's a userDefined -> could be an overloaded built-in function also
  4514. // if builtIn == true, it's definitely a built-in function with EOpNull
  4515. if (! builtIn) {
  4516. call->setUserDefined();
  4517. intermediate.addToCallGraph(infoSink, currentCaller, callerName);
  4518. }
  4519. }
  4520. // for decompositions, since we want to operate on the function node, not the aggregate holding
  4521. // output conversions.
  4522. const TIntermTyped* fnNode = result;
  4523. decomposeStructBufferMethods(loc, result, arguments); // HLSL->AST struct buffer method decompositions
  4524. decomposeIntrinsic(loc, result, arguments); // HLSL->AST intrinsic decompositions
  4525. decomposeSampleMethods(loc, result, arguments); // HLSL->AST sample method decompositions
  4526. decomposeGeometryMethods(loc, result, arguments); // HLSL->AST geometry method decompositions
  4527. // Create the qualifier list, carried in the AST for the call.
  4528. // Because some arguments expand to multiple arguments, the qualifier list will
  4529. // be longer than the formal parameter list.
  4530. if (result == fnNode && result->getAsAggregate()) {
  4531. TQualifierList& qualifierList = result->getAsAggregate()->getQualifierList();
  4532. for (int i = 0; i < fnCandidate->getParamCount(); ++i) {
  4533. TStorageQualifier qual = (*fnCandidate)[i].type->getQualifier().storage;
  4534. if (hasStructBuffCounter(*(*fnCandidate)[i].type)) {
  4535. // add buffer and counter buffer argument qualifier
  4536. qualifierList.push_back(qual);
  4537. qualifierList.push_back(qual);
  4538. } else if (shouldFlatten(*(*fnCandidate)[i].type, (*fnCandidate)[i].type->getQualifier().storage,
  4539. true)) {
  4540. // add structure member expansion
  4541. for (int memb = 0; memb < (int)(*fnCandidate)[i].type->getStruct()->size(); ++memb)
  4542. qualifierList.push_back(qual);
  4543. } else {
  4544. // Normal 1:1 case
  4545. qualifierList.push_back(qual);
  4546. }
  4547. }
  4548. }
  4549. // Convert 'out' arguments. If it was a constant folded built-in, it won't be an aggregate anymore.
  4550. // Built-ins with a single argument aren't called with an aggregate, but they also don't have an output.
  4551. // Also, build the qualifier list for user function calls, which are always called with an aggregate.
  4552. // We don't do this is if there has been a decomposition, which will have added its own conversions
  4553. // for output parameters.
  4554. if (result == fnNode && result->getAsAggregate())
  4555. result = addOutputArgumentConversions(*fnCandidate, *result->getAsOperator());
  4556. }
  4557. }
  4558. // generic error recovery
  4559. // TODO: simplification: localize all the error recoveries that look like this, and taking type into account to
  4560. // reduce cascades
  4561. if (result == nullptr)
  4562. result = intermediate.addConstantUnion(0.0, EbtFloat, loc);
  4563. return result;
  4564. }
  4565. // An initial argument list is difficult: it can be null, or a single node,
  4566. // or an aggregate if more than one argument. Add one to the front, maintaining
  4567. // this lack of uniformity.
  4568. void HlslParseContext::pushFrontArguments(TIntermTyped* front, TIntermTyped*& arguments)
  4569. {
  4570. if (arguments == nullptr)
  4571. arguments = front;
  4572. else if (arguments->getAsAggregate() != nullptr)
  4573. arguments->getAsAggregate()->getSequence().insert(arguments->getAsAggregate()->getSequence().begin(), front);
  4574. else
  4575. arguments = intermediate.growAggregate(front, arguments);
  4576. }
  4577. //
  4578. // HLSL allows mismatched dimensions on vec*mat, mat*vec, vec*vec, and mat*mat. This is a
  4579. // situation not well suited to resolution in intrinsic selection, but we can do so here, since we
  4580. // can look at both arguments insert explicit shape changes if required.
  4581. //
  4582. void HlslParseContext::addGenMulArgumentConversion(const TSourceLoc& loc, TFunction& call, TIntermTyped*& args)
  4583. {
  4584. TIntermAggregate* argAggregate = args ? args->getAsAggregate() : nullptr;
  4585. if (argAggregate == nullptr || argAggregate->getSequence().size() != 2) {
  4586. // It really ought to have two arguments.
  4587. error(loc, "expected: mul arguments", "", "");
  4588. return;
  4589. }
  4590. TIntermTyped* arg0 = argAggregate->getSequence()[0]->getAsTyped();
  4591. TIntermTyped* arg1 = argAggregate->getSequence()[1]->getAsTyped();
  4592. if (arg0->isVector() && arg1->isVector()) {
  4593. // For:
  4594. // vec * vec: it's handled during intrinsic selection, so while we could do it here,
  4595. // we can also ignore it, which is easier.
  4596. } else if (arg0->isVector() && arg1->isMatrix()) {
  4597. // vec * mat: we clamp the vec if the mat col is smaller, else clamp the mat col.
  4598. if (arg0->getVectorSize() < arg1->getMatrixCols()) {
  4599. // vec is smaller, so truncate larger mat dimension
  4600. const TType truncType(arg1->getBasicType(), arg1->getQualifier().storage, arg1->getQualifier().precision,
  4601. 0, arg0->getVectorSize(), arg1->getMatrixRows());
  4602. arg1 = addConstructor(loc, arg1, truncType);
  4603. } else if (arg0->getVectorSize() > arg1->getMatrixCols()) {
  4604. // vec is larger, so truncate vec to mat size
  4605. const TType truncType(arg0->getBasicType(), arg0->getQualifier().storage, arg0->getQualifier().precision,
  4606. arg1->getMatrixCols());
  4607. arg0 = addConstructor(loc, arg0, truncType);
  4608. }
  4609. } else if (arg0->isMatrix() && arg1->isVector()) {
  4610. // mat * vec: we clamp the vec if the mat col is smaller, else clamp the mat col.
  4611. if (arg1->getVectorSize() < arg0->getMatrixRows()) {
  4612. // vec is smaller, so truncate larger mat dimension
  4613. const TType truncType(arg0->getBasicType(), arg0->getQualifier().storage, arg0->getQualifier().precision,
  4614. 0, arg0->getMatrixCols(), arg1->getVectorSize());
  4615. arg0 = addConstructor(loc, arg0, truncType);
  4616. } else if (arg1->getVectorSize() > arg0->getMatrixRows()) {
  4617. // vec is larger, so truncate vec to mat size
  4618. const TType truncType(arg1->getBasicType(), arg1->getQualifier().storage, arg1->getQualifier().precision,
  4619. arg0->getMatrixRows());
  4620. arg1 = addConstructor(loc, arg1, truncType);
  4621. }
  4622. } else if (arg0->isMatrix() && arg1->isMatrix()) {
  4623. // mat * mat: we clamp the smaller inner dimension to match the other matrix size.
  4624. // Remember, HLSL Mrc = GLSL/SPIRV Mcr.
  4625. if (arg0->getMatrixRows() > arg1->getMatrixCols()) {
  4626. const TType truncType(arg0->getBasicType(), arg0->getQualifier().storage, arg0->getQualifier().precision,
  4627. 0, arg0->getMatrixCols(), arg1->getMatrixCols());
  4628. arg0 = addConstructor(loc, arg0, truncType);
  4629. } else if (arg0->getMatrixRows() < arg1->getMatrixCols()) {
  4630. const TType truncType(arg1->getBasicType(), arg1->getQualifier().storage, arg1->getQualifier().precision,
  4631. 0, arg0->getMatrixRows(), arg1->getMatrixRows());
  4632. arg1 = addConstructor(loc, arg1, truncType);
  4633. }
  4634. } else {
  4635. // It's something with scalars: we'll just leave it alone. Function selection will handle it
  4636. // downstream.
  4637. }
  4638. // Warn if we altered one of the arguments
  4639. if (arg0 != argAggregate->getSequence()[0] || arg1 != argAggregate->getSequence()[1])
  4640. warn(loc, "mul() matrix size mismatch", "", "");
  4641. // Put arguments back. (They might be unchanged, in which case this is harmless).
  4642. argAggregate->getSequence()[0] = arg0;
  4643. argAggregate->getSequence()[1] = arg1;
  4644. call[0].type = &arg0->getWritableType();
  4645. call[1].type = &arg1->getWritableType();
  4646. }
  4647. //
  4648. // Add any needed implicit conversions for function-call arguments to input parameters.
  4649. //
  4650. void HlslParseContext::addInputArgumentConversions(const TFunction& function, TIntermTyped*& arguments)
  4651. {
  4652. TIntermAggregate* aggregate = arguments->getAsAggregate();
  4653. // Replace a single argument with a single argument.
  4654. const auto setArg = [&](int paramNum, TIntermTyped* arg) {
  4655. if (function.getParamCount() == 1)
  4656. arguments = arg;
  4657. else {
  4658. if (aggregate == nullptr)
  4659. arguments = arg;
  4660. else
  4661. aggregate->getSequence()[paramNum] = arg;
  4662. }
  4663. };
  4664. // Process each argument's conversion
  4665. for (int param = 0; param < function.getParamCount(); ++param) {
  4666. if (! function[param].type->getQualifier().isParamInput())
  4667. continue;
  4668. // At this early point there is a slight ambiguity between whether an aggregate 'arguments'
  4669. // is the single argument itself or its children are the arguments. Only one argument
  4670. // means take 'arguments' itself as the one argument.
  4671. TIntermTyped* arg = function.getParamCount() == 1
  4672. ? arguments->getAsTyped()
  4673. : (aggregate ?
  4674. aggregate->getSequence()[param]->getAsTyped() :
  4675. arguments->getAsTyped());
  4676. if (*function[param].type != arg->getType()) {
  4677. // In-qualified arguments just need an extra node added above the argument to
  4678. // convert to the correct type.
  4679. TIntermTyped* convArg = intermediate.addConversion(EOpFunctionCall, *function[param].type, arg);
  4680. if (convArg != nullptr)
  4681. convArg = intermediate.addUniShapeConversion(EOpFunctionCall, *function[param].type, convArg);
  4682. if (convArg != nullptr)
  4683. setArg(param, convArg);
  4684. else
  4685. error(arg->getLoc(), "cannot convert input argument, argument", "", "%d", param);
  4686. } else {
  4687. if (wasFlattened(arg)) {
  4688. // If both formal and calling arg are to be flattened, leave that to argument
  4689. // expansion, not conversion.
  4690. if (!shouldFlatten(*function[param].type, function[param].type->getQualifier().storage, true)) {
  4691. // Will make a two-level subtree.
  4692. // The deepest will copy member-by-member to build the structure to pass.
  4693. // The level above that will be a two-operand EOpComma sequence that follows the copy by the
  4694. // object itself.
  4695. TVariable* internalAggregate = makeInternalVariable("aggShadow", *function[param].type);
  4696. internalAggregate->getWritableType().getQualifier().makeTemporary();
  4697. TIntermSymbol* internalSymbolNode = new TIntermSymbol(internalAggregate->getUniqueId(),
  4698. internalAggregate->getName(),
  4699. internalAggregate->getType());
  4700. internalSymbolNode->setLoc(arg->getLoc());
  4701. // This makes the deepest level, the member-wise copy
  4702. TIntermAggregate* assignAgg = handleAssign(arg->getLoc(), EOpAssign,
  4703. internalSymbolNode, arg)->getAsAggregate();
  4704. // Now, pair that with the resulting aggregate.
  4705. assignAgg = intermediate.growAggregate(assignAgg, internalSymbolNode, arg->getLoc());
  4706. assignAgg->setOperator(EOpComma);
  4707. assignAgg->setType(internalAggregate->getType());
  4708. setArg(param, assignAgg);
  4709. }
  4710. }
  4711. }
  4712. }
  4713. }
  4714. //
  4715. // Add any needed implicit expansion of calling arguments from what the shader listed to what's
  4716. // internally needed for the AST (given the constraints downstream).
  4717. //
  4718. void HlslParseContext::expandArguments(const TSourceLoc& loc, const TFunction& function, TIntermTyped*& arguments)
  4719. {
  4720. TIntermAggregate* aggregate = arguments->getAsAggregate();
  4721. int functionParamNumberOffset = 0;
  4722. // Replace a single argument with a single argument.
  4723. const auto setArg = [&](int paramNum, TIntermTyped* arg) {
  4724. if (function.getParamCount() + functionParamNumberOffset == 1)
  4725. arguments = arg;
  4726. else {
  4727. if (aggregate == nullptr)
  4728. arguments = arg;
  4729. else
  4730. aggregate->getSequence()[paramNum] = arg;
  4731. }
  4732. };
  4733. // Replace a single argument with a list of arguments
  4734. const auto setArgList = [&](int paramNum, const TVector<TIntermTyped*>& args) {
  4735. if (args.size() == 1)
  4736. setArg(paramNum, args.front());
  4737. else if (args.size() > 1) {
  4738. if (function.getParamCount() + functionParamNumberOffset == 1) {
  4739. arguments = intermediate.makeAggregate(args.front());
  4740. std::for_each(args.begin() + 1, args.end(),
  4741. [&](TIntermTyped* arg) {
  4742. arguments = intermediate.growAggregate(arguments, arg);
  4743. });
  4744. } else {
  4745. auto it = aggregate->getSequence().erase(aggregate->getSequence().begin() + paramNum);
  4746. aggregate->getSequence().insert(it, args.begin(), args.end());
  4747. }
  4748. functionParamNumberOffset += (int)(args.size() - 1);
  4749. }
  4750. };
  4751. // Process each argument's conversion
  4752. for (int param = 0; param < function.getParamCount(); ++param) {
  4753. // At this early point there is a slight ambiguity between whether an aggregate 'arguments'
  4754. // is the single argument itself or its children are the arguments. Only one argument
  4755. // means take 'arguments' itself as the one argument.
  4756. TIntermTyped* arg = function.getParamCount() == 1
  4757. ? arguments->getAsTyped()
  4758. : (aggregate ?
  4759. aggregate->getSequence()[param + functionParamNumberOffset]->getAsTyped() :
  4760. arguments->getAsTyped());
  4761. if (wasFlattened(arg) && shouldFlatten(*function[param].type, function[param].type->getQualifier().storage, true)) {
  4762. // Need to pass the structure members instead of the structure.
  4763. TVector<TIntermTyped*> memberArgs;
  4764. for (int memb = 0; memb < (int)arg->getType().getStruct()->size(); ++memb)
  4765. memberArgs.push_back(flattenAccess(arg, memb));
  4766. setArgList(param + functionParamNumberOffset, memberArgs);
  4767. }
  4768. }
  4769. // TODO: if we need both hidden counter args (below) and struct expansion (above)
  4770. // the two algorithms need to be merged: Each assumes the list starts out 1:1 between
  4771. // parameters and arguments.
  4772. // If any argument is a pass-by-reference struct buffer with an associated counter
  4773. // buffer, we have to add another hidden parameter for that counter.
  4774. if (aggregate)
  4775. addStructBuffArguments(loc, aggregate);
  4776. }
  4777. //
  4778. // Add any needed implicit output conversions for function-call arguments. This
  4779. // can require a new tree topology, complicated further by whether the function
  4780. // has a return value.
  4781. //
  4782. // Returns a node of a subtree that evaluates to the return value of the function.
  4783. //
  4784. TIntermTyped* HlslParseContext::addOutputArgumentConversions(const TFunction& function, TIntermOperator& intermNode)
  4785. {
  4786. assert (intermNode.getAsAggregate() != nullptr || intermNode.getAsUnaryNode() != nullptr);
  4787. const TSourceLoc& loc = intermNode.getLoc();
  4788. TIntermSequence argSequence; // temp sequence for unary node args
  4789. if (intermNode.getAsUnaryNode())
  4790. argSequence.push_back(intermNode.getAsUnaryNode()->getOperand());
  4791. TIntermSequence& arguments = argSequence.empty() ? intermNode.getAsAggregate()->getSequence() : argSequence;
  4792. const auto needsConversion = [&](int argNum) {
  4793. return function[argNum].type->getQualifier().isParamOutput() &&
  4794. (*function[argNum].type != arguments[argNum]->getAsTyped()->getType() ||
  4795. shouldConvertLValue(arguments[argNum]) ||
  4796. wasFlattened(arguments[argNum]->getAsTyped()));
  4797. };
  4798. // Will there be any output conversions?
  4799. bool outputConversions = false;
  4800. for (int i = 0; i < function.getParamCount(); ++i) {
  4801. if (needsConversion(i)) {
  4802. outputConversions = true;
  4803. break;
  4804. }
  4805. }
  4806. if (! outputConversions)
  4807. return &intermNode;
  4808. // Setup for the new tree, if needed:
  4809. //
  4810. // Output conversions need a different tree topology.
  4811. // Out-qualified arguments need a temporary of the correct type, with the call
  4812. // followed by an assignment of the temporary to the original argument:
  4813. // void: function(arg, ...) -> ( function(tempArg, ...), arg = tempArg, ...)
  4814. // ret = function(arg, ...) -> ret = (tempRet = function(tempArg, ...), arg = tempArg, ..., tempRet)
  4815. // Where the "tempArg" type needs no conversion as an argument, but will convert on assignment.
  4816. TIntermTyped* conversionTree = nullptr;
  4817. TVariable* tempRet = nullptr;
  4818. if (intermNode.getBasicType() != EbtVoid) {
  4819. // do the "tempRet = function(...), " bit from above
  4820. tempRet = makeInternalVariable("tempReturn", intermNode.getType());
  4821. TIntermSymbol* tempRetNode = intermediate.addSymbol(*tempRet, loc);
  4822. conversionTree = intermediate.addAssign(EOpAssign, tempRetNode, &intermNode, loc);
  4823. } else
  4824. conversionTree = &intermNode;
  4825. conversionTree = intermediate.makeAggregate(conversionTree);
  4826. // Process each argument's conversion
  4827. for (int i = 0; i < function.getParamCount(); ++i) {
  4828. if (needsConversion(i)) {
  4829. // Out-qualified arguments needing conversion need to use the topology setup above.
  4830. // Do the " ...(tempArg, ...), arg = tempArg" bit from above.
  4831. // Make a temporary for what the function expects the argument to look like.
  4832. TVariable* tempArg = makeInternalVariable("tempArg", *function[i].type);
  4833. tempArg->getWritableType().getQualifier().makeTemporary();
  4834. TIntermSymbol* tempArgNode = intermediate.addSymbol(*tempArg, loc);
  4835. // This makes the deepest level, the member-wise copy
  4836. TIntermTyped* tempAssign = handleAssign(arguments[i]->getLoc(), EOpAssign, arguments[i]->getAsTyped(),
  4837. tempArgNode);
  4838. tempAssign = handleLvalue(arguments[i]->getLoc(), "assign", tempAssign);
  4839. conversionTree = intermediate.growAggregate(conversionTree, tempAssign, arguments[i]->getLoc());
  4840. // replace the argument with another node for the same tempArg variable
  4841. arguments[i] = intermediate.addSymbol(*tempArg, loc);
  4842. }
  4843. }
  4844. // Finalize the tree topology (see bigger comment above).
  4845. if (tempRet) {
  4846. // do the "..., tempRet" bit from above
  4847. TIntermSymbol* tempRetNode = intermediate.addSymbol(*tempRet, loc);
  4848. conversionTree = intermediate.growAggregate(conversionTree, tempRetNode, loc);
  4849. }
  4850. conversionTree = intermediate.setAggregateOperator(conversionTree, EOpComma, intermNode.getType(), loc);
  4851. return conversionTree;
  4852. }
  4853. //
  4854. // Add any needed "hidden" counter buffer arguments for function calls.
  4855. //
  4856. // Modifies the 'aggregate' argument if needed. Otherwise, is no-op.
  4857. //
  4858. void HlslParseContext::addStructBuffArguments(const TSourceLoc& loc, TIntermAggregate*& aggregate)
  4859. {
  4860. // See if there are any SB types with counters.
  4861. const bool hasStructBuffArg =
  4862. std::any_of(aggregate->getSequence().begin(),
  4863. aggregate->getSequence().end(),
  4864. [this](const TIntermNode* node) {
  4865. return (node && node->getAsTyped() != nullptr) && hasStructBuffCounter(node->getAsTyped()->getType());
  4866. });
  4867. // Nothing to do, if we didn't find one.
  4868. if (! hasStructBuffArg)
  4869. return;
  4870. TIntermSequence argsWithCounterBuffers;
  4871. for (int param = 0; param < int(aggregate->getSequence().size()); ++param) {
  4872. argsWithCounterBuffers.push_back(aggregate->getSequence()[param]);
  4873. if (hasStructBuffCounter(aggregate->getSequence()[param]->getAsTyped()->getType())) {
  4874. const TIntermSymbol* blockSym = aggregate->getSequence()[param]->getAsSymbolNode();
  4875. if (blockSym != nullptr) {
  4876. TType counterType;
  4877. counterBufferType(loc, counterType);
  4878. const TString counterBlockName(intermediate.addCounterBufferName(blockSym->getName()));
  4879. TVariable* variable = makeInternalVariable(counterBlockName, counterType);
  4880. // Mark this buffer's counter block as being in use
  4881. structBufferCounter[counterBlockName] = true;
  4882. TIntermSymbol* sym = intermediate.addSymbol(*variable, loc);
  4883. argsWithCounterBuffers.push_back(sym);
  4884. }
  4885. }
  4886. }
  4887. // Swap with the temp list we've built up.
  4888. aggregate->getSequence().swap(argsWithCounterBuffers);
  4889. }
  4890. //
  4891. // Do additional checking of built-in function calls that is not caught
  4892. // by normal semantic checks on argument type, extension tagging, etc.
  4893. //
  4894. // Assumes there has been a semantically correct match to a built-in function prototype.
  4895. //
  4896. void HlslParseContext::builtInOpCheck(const TSourceLoc& loc, const TFunction& fnCandidate, TIntermOperator& callNode)
  4897. {
  4898. // Set up convenience accessors to the argument(s). There is almost always
  4899. // multiple arguments for the cases below, but when there might be one,
  4900. // check the unaryArg first.
  4901. const TIntermSequence* argp = nullptr; // confusing to use [] syntax on a pointer, so this is to help get a reference
  4902. const TIntermTyped* unaryArg = nullptr;
  4903. const TIntermTyped* arg0 = nullptr;
  4904. if (callNode.getAsAggregate()) {
  4905. argp = &callNode.getAsAggregate()->getSequence();
  4906. if (argp->size() > 0)
  4907. arg0 = (*argp)[0]->getAsTyped();
  4908. } else {
  4909. assert(callNode.getAsUnaryNode());
  4910. unaryArg = callNode.getAsUnaryNode()->getOperand();
  4911. arg0 = unaryArg;
  4912. }
  4913. const TIntermSequence& aggArgs = *argp; // only valid when unaryArg is nullptr
  4914. switch (callNode.getOp()) {
  4915. case EOpTextureGather:
  4916. case EOpTextureGatherOffset:
  4917. case EOpTextureGatherOffsets:
  4918. {
  4919. // Figure out which variants are allowed by what extensions,
  4920. // and what arguments must be constant for which situations.
  4921. TString featureString = fnCandidate.getName() + "(...)";
  4922. const char* feature = featureString.c_str();
  4923. int compArg = -1; // track which argument, if any, is the constant component argument
  4924. switch (callNode.getOp()) {
  4925. case EOpTextureGather:
  4926. // More than two arguments needs gpu_shader5, and rectangular or shadow needs gpu_shader5,
  4927. // otherwise, need GL_ARB_texture_gather.
  4928. if (fnCandidate.getParamCount() > 2 || fnCandidate[0].type->getSampler().dim == EsdRect ||
  4929. fnCandidate[0].type->getSampler().shadow) {
  4930. if (! fnCandidate[0].type->getSampler().shadow)
  4931. compArg = 2;
  4932. }
  4933. break;
  4934. case EOpTextureGatherOffset:
  4935. // GL_ARB_texture_gather is good enough for 2D non-shadow textures with no component argument
  4936. if (! fnCandidate[0].type->getSampler().shadow)
  4937. compArg = 3;
  4938. break;
  4939. case EOpTextureGatherOffsets:
  4940. if (! fnCandidate[0].type->getSampler().shadow)
  4941. compArg = 3;
  4942. break;
  4943. default:
  4944. break;
  4945. }
  4946. if (compArg > 0 && compArg < fnCandidate.getParamCount()) {
  4947. if (aggArgs[compArg]->getAsConstantUnion()) {
  4948. int value = aggArgs[compArg]->getAsConstantUnion()->getConstArray()[0].getIConst();
  4949. if (value < 0 || value > 3)
  4950. error(loc, "must be 0, 1, 2, or 3:", feature, "component argument");
  4951. } else
  4952. error(loc, "must be a compile-time constant:", feature, "component argument");
  4953. }
  4954. break;
  4955. }
  4956. case EOpTextureOffset:
  4957. case EOpTextureFetchOffset:
  4958. case EOpTextureProjOffset:
  4959. case EOpTextureLodOffset:
  4960. case EOpTextureProjLodOffset:
  4961. case EOpTextureGradOffset:
  4962. case EOpTextureProjGradOffset:
  4963. {
  4964. // Handle texture-offset limits checking
  4965. // Pick which argument has to hold constant offsets
  4966. int arg = -1;
  4967. switch (callNode.getOp()) {
  4968. case EOpTextureOffset: arg = 2; break;
  4969. case EOpTextureFetchOffset: arg = (arg0->getType().getSampler().dim != EsdRect) ? 3 : 2; break;
  4970. case EOpTextureProjOffset: arg = 2; break;
  4971. case EOpTextureLodOffset: arg = 3; break;
  4972. case EOpTextureProjLodOffset: arg = 3; break;
  4973. case EOpTextureGradOffset: arg = 4; break;
  4974. case EOpTextureProjGradOffset: arg = 4; break;
  4975. default:
  4976. assert(0);
  4977. break;
  4978. }
  4979. if (arg > 0) {
  4980. if (aggArgs[arg]->getAsConstantUnion() == nullptr)
  4981. error(loc, "argument must be compile-time constant", "texel offset", "");
  4982. else {
  4983. const TType& type = aggArgs[arg]->getAsTyped()->getType();
  4984. for (int c = 0; c < type.getVectorSize(); ++c) {
  4985. int offset = aggArgs[arg]->getAsConstantUnion()->getConstArray()[c].getIConst();
  4986. if (offset > resources.maxProgramTexelOffset || offset < resources.minProgramTexelOffset)
  4987. error(loc, "value is out of range:", "texel offset",
  4988. "[gl_MinProgramTexelOffset, gl_MaxProgramTexelOffset]");
  4989. }
  4990. }
  4991. }
  4992. break;
  4993. }
  4994. case EOpTextureQuerySamples:
  4995. case EOpImageQuerySamples:
  4996. break;
  4997. case EOpImageAtomicAdd:
  4998. case EOpImageAtomicMin:
  4999. case EOpImageAtomicMax:
  5000. case EOpImageAtomicAnd:
  5001. case EOpImageAtomicOr:
  5002. case EOpImageAtomicXor:
  5003. case EOpImageAtomicExchange:
  5004. case EOpImageAtomicCompSwap:
  5005. break;
  5006. case EOpInterpolateAtCentroid:
  5007. case EOpInterpolateAtSample:
  5008. case EOpInterpolateAtOffset:
  5009. // Make sure the first argument is an interpolant, or an array element of an interpolant
  5010. if (arg0->getType().getQualifier().storage != EvqVaryingIn) {
  5011. // It might still be an array element.
  5012. //
  5013. // We could check more, but the semantics of the first argument are already met; the
  5014. // only way to turn an array into a float/vec* is array dereference and swizzle.
  5015. //
  5016. // ES and desktop 4.3 and earlier: swizzles may not be used
  5017. // desktop 4.4 and later: swizzles may be used
  5018. const TIntermTyped* base = TIntermediate::findLValueBase(arg0, true);
  5019. if (base == nullptr || base->getType().getQualifier().storage != EvqVaryingIn)
  5020. error(loc, "first argument must be an interpolant, or interpolant-array element",
  5021. fnCandidate.getName().c_str(), "");
  5022. }
  5023. break;
  5024. default:
  5025. break;
  5026. }
  5027. }
  5028. //
  5029. // Handle seeing something in a grammar production that can be done by calling
  5030. // a constructor.
  5031. //
  5032. // The constructor still must be "handled" by handleFunctionCall(), which will
  5033. // then call handleConstructor().
  5034. //
  5035. TFunction* HlslParseContext::makeConstructorCall(const TSourceLoc& loc, const TType& type)
  5036. {
  5037. TOperator op = intermediate.mapTypeToConstructorOp(type);
  5038. if (op == EOpNull) {
  5039. error(loc, "cannot construct this type", type.getBasicString(), "");
  5040. return nullptr;
  5041. }
  5042. TString empty("");
  5043. return new TFunction(&empty, type, op);
  5044. }
  5045. //
  5046. // Handle seeing a "COLON semantic" at the end of a type declaration,
  5047. // by updating the type according to the semantic.
  5048. //
  5049. void HlslParseContext::handleSemantic(TSourceLoc loc, TQualifier& qualifier, TBuiltInVariable builtIn,
  5050. const TString& upperCase)
  5051. {
  5052. // Parse and return semantic number. If limit is 0, it will be ignored. Otherwise, if the parsed
  5053. // semantic number is >= limit, errorMsg is issued and 0 is returned.
  5054. // TODO: it would be nicer if limit and errorMsg had default parameters, but some compilers don't yet
  5055. // accept those in lambda functions.
  5056. const auto getSemanticNumber = [this, loc](const TString& semantic, unsigned int limit, const char* errorMsg) -> unsigned int {
  5057. size_t pos = semantic.find_last_not_of("0123456789");
  5058. if (pos == std::string::npos)
  5059. return 0u;
  5060. unsigned int semanticNum = (unsigned int)atoi(semantic.c_str() + pos + 1);
  5061. if (limit != 0 && semanticNum >= limit) {
  5062. error(loc, errorMsg, semantic.c_str(), "");
  5063. return 0u;
  5064. }
  5065. return semanticNum;
  5066. };
  5067. switch(builtIn) {
  5068. case EbvNone:
  5069. // Get location numbers from fragment outputs, instead of
  5070. // auto-assigning them.
  5071. if (language == EShLangFragment && upperCase.compare(0, 9, "SV_TARGET") == 0) {
  5072. qualifier.layoutLocation = getSemanticNumber(upperCase, 0, nullptr);
  5073. nextOutLocation = std::max(nextOutLocation, qualifier.layoutLocation + 1u);
  5074. } else if (upperCase.compare(0, 15, "SV_CLIPDISTANCE") == 0) {
  5075. builtIn = EbvClipDistance;
  5076. qualifier.layoutLocation = getSemanticNumber(upperCase, maxClipCullRegs, "invalid clip semantic");
  5077. } else if (upperCase.compare(0, 15, "SV_CULLDISTANCE") == 0) {
  5078. builtIn = EbvCullDistance;
  5079. qualifier.layoutLocation = getSemanticNumber(upperCase, maxClipCullRegs, "invalid cull semantic");
  5080. }
  5081. break;
  5082. case EbvPosition:
  5083. // adjust for stage in/out
  5084. if (language == EShLangFragment)
  5085. builtIn = EbvFragCoord;
  5086. break;
  5087. case EbvFragStencilRef:
  5088. error(loc, "unimplemented; need ARB_shader_stencil_export", "SV_STENCILREF", "");
  5089. break;
  5090. case EbvTessLevelInner:
  5091. case EbvTessLevelOuter:
  5092. qualifier.patch = true;
  5093. break;
  5094. default:
  5095. break;
  5096. }
  5097. if (qualifier.builtIn == EbvNone)
  5098. qualifier.builtIn = builtIn;
  5099. qualifier.semanticName = intermediate.addSemanticName(upperCase);
  5100. }
  5101. //
  5102. // Handle seeing something like "PACKOFFSET LEFT_PAREN c[Subcomponent][.component] RIGHT_PAREN"
  5103. //
  5104. // 'location' has the "c[Subcomponent]" part.
  5105. // 'component' points to the "component" part, or nullptr if not present.
  5106. //
  5107. void HlslParseContext::handlePackOffset(const TSourceLoc& loc, TQualifier& qualifier, const glslang::TString& location,
  5108. const glslang::TString* component)
  5109. {
  5110. if (location.size() == 0 || location[0] != 'c') {
  5111. error(loc, "expected 'c'", "packoffset", "");
  5112. return;
  5113. }
  5114. if (location.size() == 1)
  5115. return;
  5116. if (! isdigit(location[1])) {
  5117. error(loc, "expected number after 'c'", "packoffset", "");
  5118. return;
  5119. }
  5120. qualifier.layoutOffset = 16 * atoi(location.substr(1, location.size()).c_str());
  5121. if (component != nullptr) {
  5122. int componentOffset = 0;
  5123. switch ((*component)[0]) {
  5124. case 'x': componentOffset = 0; break;
  5125. case 'y': componentOffset = 4; break;
  5126. case 'z': componentOffset = 8; break;
  5127. case 'w': componentOffset = 12; break;
  5128. default:
  5129. componentOffset = -1;
  5130. break;
  5131. }
  5132. if (componentOffset < 0 || component->size() > 1) {
  5133. error(loc, "expected {x, y, z, w} for component", "packoffset", "");
  5134. return;
  5135. }
  5136. qualifier.layoutOffset += componentOffset;
  5137. }
  5138. }
  5139. //
  5140. // Handle seeing something like "REGISTER LEFT_PAREN [shader_profile,] Type# RIGHT_PAREN"
  5141. //
  5142. // 'profile' points to the shader_profile part, or nullptr if not present.
  5143. // 'desc' is the type# part.
  5144. //
  5145. void HlslParseContext::handleRegister(const TSourceLoc& loc, TQualifier& qualifier, const glslang::TString* profile,
  5146. const glslang::TString& desc, int subComponent, const glslang::TString* spaceDesc)
  5147. {
  5148. if (profile != nullptr)
  5149. warn(loc, "ignoring shader_profile", "register", "");
  5150. if (desc.size() < 1) {
  5151. error(loc, "expected register type", "register", "");
  5152. return;
  5153. }
  5154. int regNumber = 0;
  5155. if (desc.size() > 1) {
  5156. if (isdigit(desc[1]))
  5157. regNumber = atoi(desc.substr(1, desc.size()).c_str());
  5158. else {
  5159. error(loc, "expected register number after register type", "register", "");
  5160. return;
  5161. }
  5162. }
  5163. // more information about register types see
  5164. // https://docs.microsoft.com/en-us/windows/desktop/direct3dhlsl/dx-graphics-hlsl-variable-register
  5165. const std::vector<std::string>& resourceInfo = intermediate.getResourceSetBinding();
  5166. switch (std::tolower(desc[0])) {
  5167. case 'c':
  5168. // c register is the register slot in the global const buffer
  5169. // each slot is a vector of 4 32 bit components
  5170. qualifier.layoutOffset = regNumber * 4 * 4;
  5171. break;
  5172. // const buffer register slot
  5173. case 'b':
  5174. // textrues and structured buffers
  5175. case 't':
  5176. // samplers
  5177. case 's':
  5178. // uav resources
  5179. case 'u':
  5180. // if nothing else has set the binding, do so now
  5181. // (other mechanisms override this one)
  5182. if (!qualifier.hasBinding())
  5183. qualifier.layoutBinding = regNumber + subComponent;
  5184. // This handles per-register layout sets numbers. For the global mode which sets
  5185. // every symbol to the same value, see setLinkageLayoutSets().
  5186. if ((resourceInfo.size() % 3) == 0) {
  5187. // Apply per-symbol resource set and binding.
  5188. for (auto it = resourceInfo.cbegin(); it != resourceInfo.cend(); it = it + 3) {
  5189. if (strcmp(desc.c_str(), it[0].c_str()) == 0) {
  5190. qualifier.layoutSet = atoi(it[1].c_str());
  5191. qualifier.layoutBinding = atoi(it[2].c_str()) + subComponent;
  5192. break;
  5193. }
  5194. }
  5195. }
  5196. break;
  5197. default:
  5198. warn(loc, "ignoring unrecognized register type", "register", "%c", desc[0]);
  5199. break;
  5200. }
  5201. // space
  5202. unsigned int setNumber;
  5203. const auto crackSpace = [&]() -> bool {
  5204. const int spaceLen = 5;
  5205. if (spaceDesc->size() < spaceLen + 1)
  5206. return false;
  5207. if (spaceDesc->compare(0, spaceLen, "space") != 0)
  5208. return false;
  5209. if (! isdigit((*spaceDesc)[spaceLen]))
  5210. return false;
  5211. setNumber = atoi(spaceDesc->substr(spaceLen, spaceDesc->size()).c_str());
  5212. return true;
  5213. };
  5214. // if nothing else has set the set, do so now
  5215. // (other mechanisms override this one)
  5216. if (spaceDesc && !qualifier.hasSet()) {
  5217. if (! crackSpace()) {
  5218. error(loc, "expected spaceN", "register", "");
  5219. return;
  5220. }
  5221. qualifier.layoutSet = setNumber;
  5222. }
  5223. }
  5224. // Convert to a scalar boolean, or if not allowed by HLSL semantics,
  5225. // report an error and return nullptr.
  5226. TIntermTyped* HlslParseContext::convertConditionalExpression(const TSourceLoc& loc, TIntermTyped* condition,
  5227. bool mustBeScalar)
  5228. {
  5229. if (mustBeScalar && !condition->getType().isScalarOrVec1()) {
  5230. error(loc, "requires a scalar", "conditional expression", "");
  5231. return nullptr;
  5232. }
  5233. return intermediate.addConversion(EOpConstructBool, TType(EbtBool, EvqTemporary, condition->getVectorSize()),
  5234. condition);
  5235. }
  5236. //
  5237. // Same error message for all places assignments don't work.
  5238. //
  5239. void HlslParseContext::assignError(const TSourceLoc& loc, const char* op, TString left, TString right)
  5240. {
  5241. error(loc, "", op, "cannot convert from '%s' to '%s'",
  5242. right.c_str(), left.c_str());
  5243. }
  5244. //
  5245. // Same error message for all places unary operations don't work.
  5246. //
  5247. void HlslParseContext::unaryOpError(const TSourceLoc& loc, const char* op, TString operand)
  5248. {
  5249. error(loc, " wrong operand type", op,
  5250. "no operation '%s' exists that takes an operand of type %s (or there is no acceptable conversion)",
  5251. op, operand.c_str());
  5252. }
  5253. //
  5254. // Same error message for all binary operations don't work.
  5255. //
  5256. void HlslParseContext::binaryOpError(const TSourceLoc& loc, const char* op, TString left, TString right)
  5257. {
  5258. error(loc, " wrong operand types:", op,
  5259. "no operation '%s' exists that takes a left-hand operand of type '%s' and "
  5260. "a right operand of type '%s' (or there is no acceptable conversion)",
  5261. op, left.c_str(), right.c_str());
  5262. }
  5263. //
  5264. // A basic type of EbtVoid is a key that the name string was seen in the source, but
  5265. // it was not found as a variable in the symbol table. If so, give the error
  5266. // message and insert a dummy variable in the symbol table to prevent future errors.
  5267. //
  5268. void HlslParseContext::variableCheck(TIntermTyped*& nodePtr)
  5269. {
  5270. TIntermSymbol* symbol = nodePtr->getAsSymbolNode();
  5271. if (! symbol)
  5272. return;
  5273. if (symbol->getType().getBasicType() == EbtVoid) {
  5274. error(symbol->getLoc(), "undeclared identifier", symbol->getName().c_str(), "");
  5275. // Add to symbol table to prevent future error messages on the same name
  5276. if (symbol->getName().size() > 0) {
  5277. TVariable* fakeVariable = new TVariable(&symbol->getName(), TType(EbtFloat));
  5278. symbolTable.insert(*fakeVariable);
  5279. // substitute a symbol node for this new variable
  5280. nodePtr = intermediate.addSymbol(*fakeVariable, symbol->getLoc());
  5281. }
  5282. }
  5283. }
  5284. //
  5285. // Both test, and if necessary spit out an error, to see if the node is really
  5286. // a constant.
  5287. //
  5288. void HlslParseContext::constantValueCheck(TIntermTyped* node, const char* token)
  5289. {
  5290. if (node->getQualifier().storage != EvqConst)
  5291. error(node->getLoc(), "constant expression required", token, "");
  5292. }
  5293. //
  5294. // Both test, and if necessary spit out an error, to see if the node is really
  5295. // an integer.
  5296. //
  5297. void HlslParseContext::integerCheck(const TIntermTyped* node, const char* token)
  5298. {
  5299. if ((node->getBasicType() == EbtInt || node->getBasicType() == EbtUint) && node->isScalar())
  5300. return;
  5301. error(node->getLoc(), "scalar integer expression required", token, "");
  5302. }
  5303. //
  5304. // Both test, and if necessary spit out an error, to see if we are currently
  5305. // globally scoped.
  5306. //
  5307. void HlslParseContext::globalCheck(const TSourceLoc& loc, const char* token)
  5308. {
  5309. if (! symbolTable.atGlobalLevel())
  5310. error(loc, "not allowed in nested scope", token, "");
  5311. }
  5312. bool HlslParseContext::builtInName(const TString& /*identifier*/)
  5313. {
  5314. return false;
  5315. }
  5316. //
  5317. // Make sure there is enough data and not too many arguments provided to the
  5318. // constructor to build something of the type of the constructor. Also returns
  5319. // the type of the constructor.
  5320. //
  5321. // Returns true if there was an error in construction.
  5322. //
  5323. bool HlslParseContext::constructorError(const TSourceLoc& loc, TIntermNode* node, TFunction& function,
  5324. TOperator op, TType& type)
  5325. {
  5326. type.shallowCopy(function.getType());
  5327. bool constructingMatrix = false;
  5328. switch (op) {
  5329. case EOpConstructTextureSampler:
  5330. error(loc, "unhandled texture constructor", "constructor", "");
  5331. return true;
  5332. case EOpConstructMat2x2:
  5333. case EOpConstructMat2x3:
  5334. case EOpConstructMat2x4:
  5335. case EOpConstructMat3x2:
  5336. case EOpConstructMat3x3:
  5337. case EOpConstructMat3x4:
  5338. case EOpConstructMat4x2:
  5339. case EOpConstructMat4x3:
  5340. case EOpConstructMat4x4:
  5341. case EOpConstructDMat2x2:
  5342. case EOpConstructDMat2x3:
  5343. case EOpConstructDMat2x4:
  5344. case EOpConstructDMat3x2:
  5345. case EOpConstructDMat3x3:
  5346. case EOpConstructDMat3x4:
  5347. case EOpConstructDMat4x2:
  5348. case EOpConstructDMat4x3:
  5349. case EOpConstructDMat4x4:
  5350. case EOpConstructIMat2x2:
  5351. case EOpConstructIMat2x3:
  5352. case EOpConstructIMat2x4:
  5353. case EOpConstructIMat3x2:
  5354. case EOpConstructIMat3x3:
  5355. case EOpConstructIMat3x4:
  5356. case EOpConstructIMat4x2:
  5357. case EOpConstructIMat4x3:
  5358. case EOpConstructIMat4x4:
  5359. case EOpConstructUMat2x2:
  5360. case EOpConstructUMat2x3:
  5361. case EOpConstructUMat2x4:
  5362. case EOpConstructUMat3x2:
  5363. case EOpConstructUMat3x3:
  5364. case EOpConstructUMat3x4:
  5365. case EOpConstructUMat4x2:
  5366. case EOpConstructUMat4x3:
  5367. case EOpConstructUMat4x4:
  5368. case EOpConstructBMat2x2:
  5369. case EOpConstructBMat2x3:
  5370. case EOpConstructBMat2x4:
  5371. case EOpConstructBMat3x2:
  5372. case EOpConstructBMat3x3:
  5373. case EOpConstructBMat3x4:
  5374. case EOpConstructBMat4x2:
  5375. case EOpConstructBMat4x3:
  5376. case EOpConstructBMat4x4:
  5377. constructingMatrix = true;
  5378. break;
  5379. default:
  5380. break;
  5381. }
  5382. //
  5383. // Walk the arguments for first-pass checks and collection of information.
  5384. //
  5385. int size = 0;
  5386. bool constType = true;
  5387. bool full = false;
  5388. bool overFull = false;
  5389. bool matrixInMatrix = false;
  5390. bool arrayArg = false;
  5391. for (int arg = 0; arg < function.getParamCount(); ++arg) {
  5392. if (function[arg].type->isArray()) {
  5393. if (function[arg].type->isUnsizedArray()) {
  5394. // Can't construct from an unsized array.
  5395. error(loc, "array argument must be sized", "constructor", "");
  5396. return true;
  5397. }
  5398. arrayArg = true;
  5399. }
  5400. if (constructingMatrix && function[arg].type->isMatrix())
  5401. matrixInMatrix = true;
  5402. // 'full' will go to true when enough args have been seen. If we loop
  5403. // again, there is an extra argument.
  5404. if (full) {
  5405. // For vectors and matrices, it's okay to have too many components
  5406. // available, but not okay to have unused arguments.
  5407. overFull = true;
  5408. }
  5409. size += function[arg].type->computeNumComponents();
  5410. if (op != EOpConstructStruct && ! type.isArray() && size >= type.computeNumComponents())
  5411. full = true;
  5412. if (function[arg].type->getQualifier().storage != EvqConst)
  5413. constType = false;
  5414. }
  5415. if (constType)
  5416. type.getQualifier().storage = EvqConst;
  5417. if (type.isArray()) {
  5418. if (function.getParamCount() == 0) {
  5419. error(loc, "array constructor must have at least one argument", "constructor", "");
  5420. return true;
  5421. }
  5422. if (type.isUnsizedArray()) {
  5423. // auto adapt the constructor type to the number of arguments
  5424. type.changeOuterArraySize(function.getParamCount());
  5425. } else if (type.getOuterArraySize() != function.getParamCount() && type.computeNumComponents() > size) {
  5426. error(loc, "array constructor needs one argument per array element", "constructor", "");
  5427. return true;
  5428. }
  5429. if (type.isArrayOfArrays()) {
  5430. // Types have to match, but we're still making the type.
  5431. // Finish making the type, and the comparison is done later
  5432. // when checking for conversion.
  5433. TArraySizes& arraySizes = *type.getArraySizes();
  5434. // At least the dimensionalities have to match.
  5435. if (! function[0].type->isArray() ||
  5436. arraySizes.getNumDims() != function[0].type->getArraySizes()->getNumDims() + 1) {
  5437. error(loc, "array constructor argument not correct type to construct array element", "constructor", "");
  5438. return true;
  5439. }
  5440. if (arraySizes.isInnerUnsized()) {
  5441. // "Arrays of arrays ..., and the size for any dimension is optional"
  5442. // That means we need to adopt (from the first argument) the other array sizes into the type.
  5443. for (int d = 1; d < arraySizes.getNumDims(); ++d) {
  5444. if (arraySizes.getDimSize(d) == UnsizedArraySize) {
  5445. arraySizes.setDimSize(d, function[0].type->getArraySizes()->getDimSize(d - 1));
  5446. }
  5447. }
  5448. }
  5449. }
  5450. }
  5451. // Some array -> array type casts are okay
  5452. if (arrayArg && function.getParamCount() == 1 && op != EOpConstructStruct && type.isArray() &&
  5453. !type.isArrayOfArrays() && !function[0].type->isArrayOfArrays() &&
  5454. type.getVectorSize() >= 1 && function[0].type->getVectorSize() >= 1)
  5455. return false;
  5456. if (arrayArg && op != EOpConstructStruct && ! type.isArrayOfArrays()) {
  5457. error(loc, "constructing non-array constituent from array argument", "constructor", "");
  5458. return true;
  5459. }
  5460. if (matrixInMatrix && ! type.isArray()) {
  5461. return false;
  5462. }
  5463. if (overFull) {
  5464. error(loc, "too many arguments", "constructor", "");
  5465. return true;
  5466. }
  5467. if (op == EOpConstructStruct && ! type.isArray()) {
  5468. if (isScalarConstructor(node))
  5469. return false;
  5470. // Self-type construction: e.g, we can construct a struct from a single identically typed object.
  5471. if (function.getParamCount() == 1 && type == *function[0].type)
  5472. return false;
  5473. if ((int)type.getStruct()->size() != function.getParamCount()) {
  5474. error(loc, "Number of constructor parameters does not match the number of structure fields", "constructor", "");
  5475. return true;
  5476. }
  5477. }
  5478. if ((op != EOpConstructStruct && size != 1 && size < type.computeNumComponents()) ||
  5479. (op == EOpConstructStruct && size < type.computeNumComponents())) {
  5480. error(loc, "not enough data provided for construction", "constructor", "");
  5481. return true;
  5482. }
  5483. return false;
  5484. }
  5485. // See if 'node', in the context of constructing aggregates, is a scalar argument
  5486. // to a constructor.
  5487. //
  5488. bool HlslParseContext::isScalarConstructor(const TIntermNode* node)
  5489. {
  5490. // Obviously, it must be a scalar, but an aggregate node might not be fully
  5491. // completed yet: holding a sequence of initializers under an aggregate
  5492. // would not yet be typed, so don't check it's type. This corresponds to
  5493. // the aggregate operator also not being set yet. (An aggregate operation
  5494. // that legitimately yields a scalar will have a getOp() of that operator,
  5495. // not EOpNull.)
  5496. return node->getAsTyped() != nullptr &&
  5497. node->getAsTyped()->isScalar() &&
  5498. (node->getAsAggregate() == nullptr || node->getAsAggregate()->getOp() != EOpNull);
  5499. }
  5500. // Checks to see if a void variable has been declared and raise an error message for such a case
  5501. //
  5502. // returns true in case of an error
  5503. //
  5504. bool HlslParseContext::voidErrorCheck(const TSourceLoc& loc, const TString& identifier, const TBasicType basicType)
  5505. {
  5506. if (basicType == EbtVoid) {
  5507. error(loc, "illegal use of type 'void'", identifier.c_str(), "");
  5508. return true;
  5509. }
  5510. return false;
  5511. }
  5512. //
  5513. // Fix just a full qualifier (no variables or types yet, but qualifier is complete) at global level.
  5514. //
  5515. void HlslParseContext::globalQualifierFix(const TSourceLoc&, TQualifier& qualifier)
  5516. {
  5517. // move from parameter/unknown qualifiers to pipeline in/out qualifiers
  5518. switch (qualifier.storage) {
  5519. case EvqIn:
  5520. qualifier.storage = EvqVaryingIn;
  5521. break;
  5522. case EvqOut:
  5523. qualifier.storage = EvqVaryingOut;
  5524. break;
  5525. default:
  5526. break;
  5527. }
  5528. }
  5529. //
  5530. // Merge characteristics of the 'src' qualifier into the 'dst'.
  5531. // If there is duplication, issue error messages, unless 'force'
  5532. // is specified, which means to just override default settings.
  5533. //
  5534. // Also, when force is false, it will be assumed that 'src' follows
  5535. // 'dst', for the purpose of error checking order for versions
  5536. // that require specific orderings of qualifiers.
  5537. //
  5538. void HlslParseContext::mergeQualifiers(TQualifier& dst, const TQualifier& src)
  5539. {
  5540. // Storage qualification
  5541. if (dst.storage == EvqTemporary || dst.storage == EvqGlobal)
  5542. dst.storage = src.storage;
  5543. else if ((dst.storage == EvqIn && src.storage == EvqOut) ||
  5544. (dst.storage == EvqOut && src.storage == EvqIn))
  5545. dst.storage = EvqInOut;
  5546. else if ((dst.storage == EvqIn && src.storage == EvqConst) ||
  5547. (dst.storage == EvqConst && src.storage == EvqIn))
  5548. dst.storage = EvqConstReadOnly;
  5549. // Layout qualifiers
  5550. mergeObjectLayoutQualifiers(dst, src, false);
  5551. // individual qualifiers
  5552. bool repeated = false;
  5553. #define MERGE_SINGLETON(field) repeated |= dst.field && src.field; dst.field |= src.field;
  5554. MERGE_SINGLETON(invariant);
  5555. MERGE_SINGLETON(noContraction);
  5556. MERGE_SINGLETON(centroid);
  5557. MERGE_SINGLETON(smooth);
  5558. MERGE_SINGLETON(flat);
  5559. MERGE_SINGLETON(nopersp);
  5560. MERGE_SINGLETON(patch);
  5561. MERGE_SINGLETON(sample);
  5562. MERGE_SINGLETON(coherent);
  5563. MERGE_SINGLETON(volatil);
  5564. MERGE_SINGLETON(restrict);
  5565. MERGE_SINGLETON(readonly);
  5566. MERGE_SINGLETON(writeonly);
  5567. MERGE_SINGLETON(specConstant);
  5568. MERGE_SINGLETON(nonUniform);
  5569. }
  5570. // used to flatten the sampler type space into a single dimension
  5571. // correlates with the declaration of defaultSamplerPrecision[]
  5572. int HlslParseContext::computeSamplerTypeIndex(TSampler& sampler)
  5573. {
  5574. int arrayIndex = sampler.arrayed ? 1 : 0;
  5575. int shadowIndex = sampler.shadow ? 1 : 0;
  5576. int externalIndex = sampler.external ? 1 : 0;
  5577. return EsdNumDims *
  5578. (EbtNumTypes * (2 * (2 * arrayIndex + shadowIndex) + externalIndex) + sampler.type) + sampler.dim;
  5579. }
  5580. //
  5581. // Do size checking for an array type's size.
  5582. //
  5583. void HlslParseContext::arraySizeCheck(const TSourceLoc& loc, TIntermTyped* expr, TArraySize& sizePair)
  5584. {
  5585. bool isConst = false;
  5586. sizePair.size = 1;
  5587. sizePair.node = nullptr;
  5588. TIntermConstantUnion* constant = expr->getAsConstantUnion();
  5589. if (constant) {
  5590. // handle true (non-specialization) constant
  5591. sizePair.size = constant->getConstArray()[0].getIConst();
  5592. isConst = true;
  5593. } else {
  5594. // see if it's a specialization constant instead
  5595. if (expr->getQualifier().isSpecConstant()) {
  5596. isConst = true;
  5597. sizePair.node = expr;
  5598. TIntermSymbol* symbol = expr->getAsSymbolNode();
  5599. if (symbol && symbol->getConstArray().size() > 0)
  5600. sizePair.size = symbol->getConstArray()[0].getIConst();
  5601. }
  5602. }
  5603. if (! isConst || (expr->getBasicType() != EbtInt && expr->getBasicType() != EbtUint)) {
  5604. error(loc, "array size must be a constant integer expression", "", "");
  5605. return;
  5606. }
  5607. if (sizePair.size <= 0) {
  5608. error(loc, "array size must be a positive integer", "", "");
  5609. return;
  5610. }
  5611. }
  5612. //
  5613. // Require array to be completely sized
  5614. //
  5615. void HlslParseContext::arraySizeRequiredCheck(const TSourceLoc& loc, const TArraySizes& arraySizes)
  5616. {
  5617. if (arraySizes.hasUnsized())
  5618. error(loc, "array size required", "", "");
  5619. }
  5620. void HlslParseContext::structArrayCheck(const TSourceLoc& /*loc*/, const TType& type)
  5621. {
  5622. const TTypeList& structure = *type.getStruct();
  5623. for (int m = 0; m < (int)structure.size(); ++m) {
  5624. const TType& member = *structure[m].type;
  5625. if (member.isArray())
  5626. arraySizeRequiredCheck(structure[m].loc, *member.getArraySizes());
  5627. }
  5628. }
  5629. //
  5630. // Do all the semantic checking for declaring or redeclaring an array, with and
  5631. // without a size, and make the right changes to the symbol table.
  5632. //
  5633. void HlslParseContext::declareArray(const TSourceLoc& loc, const TString& identifier, const TType& type,
  5634. TSymbol*& symbol, bool track)
  5635. {
  5636. if (symbol == nullptr) {
  5637. bool currentScope;
  5638. symbol = symbolTable.find(identifier, nullptr, &currentScope);
  5639. if (symbol && builtInName(identifier) && ! symbolTable.atBuiltInLevel()) {
  5640. // bad shader (errors already reported) trying to redeclare a built-in name as an array
  5641. return;
  5642. }
  5643. if (symbol == nullptr || ! currentScope) {
  5644. //
  5645. // Successfully process a new definition.
  5646. // (Redeclarations have to take place at the same scope; otherwise they are hiding declarations)
  5647. //
  5648. symbol = new TVariable(&identifier, type);
  5649. symbolTable.insert(*symbol);
  5650. if (track && symbolTable.atGlobalLevel())
  5651. trackLinkage(*symbol);
  5652. return;
  5653. }
  5654. if (symbol->getAsAnonMember()) {
  5655. error(loc, "cannot redeclare a user-block member array", identifier.c_str(), "");
  5656. symbol = nullptr;
  5657. return;
  5658. }
  5659. }
  5660. //
  5661. // Process a redeclaration.
  5662. //
  5663. if (symbol == nullptr) {
  5664. error(loc, "array variable name expected", identifier.c_str(), "");
  5665. return;
  5666. }
  5667. // redeclareBuiltinVariable() should have already done the copyUp()
  5668. TType& existingType = symbol->getWritableType();
  5669. if (existingType.isSizedArray()) {
  5670. // be more lenient for input arrays to geometry shaders and tessellation control outputs,
  5671. // where the redeclaration is the same size
  5672. return;
  5673. }
  5674. existingType.updateArraySizes(type);
  5675. }
  5676. //
  5677. // Enforce non-initializer type/qualifier rules.
  5678. //
  5679. void HlslParseContext::fixConstInit(const TSourceLoc& loc, const TString& identifier, TType& type,
  5680. TIntermTyped*& initializer)
  5681. {
  5682. //
  5683. // Make the qualifier make sense, given that there is an initializer.
  5684. //
  5685. if (initializer == nullptr) {
  5686. if (type.getQualifier().storage == EvqConst ||
  5687. type.getQualifier().storage == EvqConstReadOnly) {
  5688. initializer = intermediate.makeAggregate(loc);
  5689. warn(loc, "variable with qualifier 'const' not initialized; zero initializing", identifier.c_str(), "");
  5690. }
  5691. }
  5692. }
  5693. //
  5694. // See if the identifier is a built-in symbol that can be redeclared, and if so,
  5695. // copy the symbol table's read-only built-in variable to the current
  5696. // global level, where it can be modified based on the passed in type.
  5697. //
  5698. // Returns nullptr if no redeclaration took place; meaning a normal declaration still
  5699. // needs to occur for it, not necessarily an error.
  5700. //
  5701. // Returns a redeclared and type-modified variable if a redeclared occurred.
  5702. //
  5703. TSymbol* HlslParseContext::redeclareBuiltinVariable(const TSourceLoc& /*loc*/, const TString& identifier,
  5704. const TQualifier& /*qualifier*/,
  5705. const TShaderQualifiers& /*publicType*/)
  5706. {
  5707. if (! builtInName(identifier) || symbolTable.atBuiltInLevel() || ! symbolTable.atGlobalLevel())
  5708. return nullptr;
  5709. return nullptr;
  5710. }
  5711. //
  5712. // Generate index to the array element in a structure buffer (SSBO)
  5713. //
  5714. TIntermTyped* HlslParseContext::indexStructBufferContent(const TSourceLoc& loc, TIntermTyped* buffer) const
  5715. {
  5716. // Bail out if not a struct buffer
  5717. if (buffer == nullptr || ! isStructBufferType(buffer->getType()))
  5718. return nullptr;
  5719. // Runtime sized array is always the last element.
  5720. const TTypeList* bufferStruct = buffer->getType().getStruct();
  5721. TIntermTyped* arrayPosition = intermediate.addConstantUnion(unsigned(bufferStruct->size()-1), loc);
  5722. TIntermTyped* argArray = intermediate.addIndex(EOpIndexDirectStruct, buffer, arrayPosition, loc);
  5723. argArray->setType(*(*bufferStruct)[bufferStruct->size()-1].type);
  5724. return argArray;
  5725. }
  5726. //
  5727. // IFF type is a structuredbuffer/byteaddressbuffer type, return the content
  5728. // (template) type. E.g, StructuredBuffer<MyType> -> MyType. Else return nullptr.
  5729. //
  5730. TType* HlslParseContext::getStructBufferContentType(const TType& type) const
  5731. {
  5732. if (type.getBasicType() != EbtBlock || type.getQualifier().storage != EvqBuffer)
  5733. return nullptr;
  5734. const int memberCount = (int)type.getStruct()->size();
  5735. assert(memberCount > 0);
  5736. TType* contentType = (*type.getStruct())[memberCount-1].type;
  5737. return contentType->isUnsizedArray() ? contentType : nullptr;
  5738. }
  5739. //
  5740. // If an existing struct buffer has a sharable type, then share it.
  5741. //
  5742. void HlslParseContext::shareStructBufferType(TType& type)
  5743. {
  5744. // PackOffset must be equivalent to share types on a per-member basis.
  5745. // Note: cannot use auto type due to recursion. Thus, this is a std::function.
  5746. const std::function<bool(TType& lhs, TType& rhs)>
  5747. compareQualifiers = [&](TType& lhs, TType& rhs) -> bool {
  5748. if (lhs.getQualifier().layoutOffset != rhs.getQualifier().layoutOffset)
  5749. return false;
  5750. if (lhs.isStruct() != rhs.isStruct())
  5751. return false;
  5752. if (lhs.isStruct() && rhs.isStruct()) {
  5753. if (lhs.getStruct()->size() != rhs.getStruct()->size())
  5754. return false;
  5755. for (int i = 0; i < int(lhs.getStruct()->size()); ++i)
  5756. if (!compareQualifiers(*(*lhs.getStruct())[i].type, *(*rhs.getStruct())[i].type))
  5757. return false;
  5758. }
  5759. return true;
  5760. };
  5761. // We need to compare certain qualifiers in addition to the type.
  5762. const auto typeEqual = [compareQualifiers](TType& lhs, TType& rhs) -> bool {
  5763. if (lhs.getQualifier().readonly != rhs.getQualifier().readonly)
  5764. return false;
  5765. // If both are structures, recursively look for packOffset equality
  5766. // as well as type equality.
  5767. return compareQualifiers(lhs, rhs) && lhs == rhs;
  5768. };
  5769. // This is an exhaustive O(N) search, but real world shaders have
  5770. // only a small number of these.
  5771. for (int idx = 0; idx < int(structBufferTypes.size()); ++idx) {
  5772. // If the deep structure matches, modulo qualifiers, use it
  5773. if (typeEqual(*structBufferTypes[idx], type)) {
  5774. type.shallowCopy(*structBufferTypes[idx]);
  5775. return;
  5776. }
  5777. }
  5778. // Otherwise, remember it:
  5779. TType* typeCopy = new TType;
  5780. typeCopy->shallowCopy(type);
  5781. structBufferTypes.push_back(typeCopy);
  5782. }
  5783. void HlslParseContext::paramFix(TType& type)
  5784. {
  5785. switch (type.getQualifier().storage) {
  5786. case EvqConst:
  5787. type.getQualifier().storage = EvqConstReadOnly;
  5788. break;
  5789. case EvqGlobal:
  5790. case EvqUniform:
  5791. case EvqTemporary:
  5792. type.getQualifier().storage = EvqIn;
  5793. break;
  5794. case EvqBuffer:
  5795. {
  5796. // SSBO parameter. These do not go through the declareBlock path since they are fn parameters.
  5797. correctUniform(type.getQualifier());
  5798. TQualifier bufferQualifier = globalBufferDefaults;
  5799. mergeObjectLayoutQualifiers(bufferQualifier, type.getQualifier(), true);
  5800. bufferQualifier.storage = type.getQualifier().storage;
  5801. bufferQualifier.readonly = type.getQualifier().readonly;
  5802. bufferQualifier.coherent = type.getQualifier().coherent;
  5803. bufferQualifier.declaredBuiltIn = type.getQualifier().declaredBuiltIn;
  5804. type.getQualifier() = bufferQualifier;
  5805. break;
  5806. }
  5807. default:
  5808. break;
  5809. }
  5810. }
  5811. void HlslParseContext::specializationCheck(const TSourceLoc& loc, const TType& type, const char* op)
  5812. {
  5813. if (type.containsSpecializationSize())
  5814. error(loc, "can't use with types containing arrays sized with a specialization constant", op, "");
  5815. }
  5816. //
  5817. // Layout qualifier stuff.
  5818. //
  5819. // Put the id's layout qualification into the public type, for qualifiers not having a number set.
  5820. // This is before we know any type information for error checking.
  5821. void HlslParseContext::setLayoutQualifier(const TSourceLoc& loc, TQualifier& qualifier, TString& id)
  5822. {
  5823. std::transform(id.begin(), id.end(), id.begin(), ::tolower);
  5824. if (id == TQualifier::getLayoutMatrixString(ElmColumnMajor)) {
  5825. qualifier.layoutMatrix = ElmRowMajor;
  5826. return;
  5827. }
  5828. if (id == TQualifier::getLayoutMatrixString(ElmRowMajor)) {
  5829. qualifier.layoutMatrix = ElmColumnMajor;
  5830. return;
  5831. }
  5832. if (id == "push_constant") {
  5833. requireVulkan(loc, "push_constant");
  5834. qualifier.layoutPushConstant = true;
  5835. return;
  5836. }
  5837. if (language == EShLangGeometry || language == EShLangTessEvaluation) {
  5838. if (id == TQualifier::getGeometryString(ElgTriangles)) {
  5839. // publicType.shaderQualifiers.geometry = ElgTriangles;
  5840. warn(loc, "ignored", id.c_str(), "");
  5841. return;
  5842. }
  5843. if (language == EShLangGeometry) {
  5844. if (id == TQualifier::getGeometryString(ElgPoints)) {
  5845. // publicType.shaderQualifiers.geometry = ElgPoints;
  5846. warn(loc, "ignored", id.c_str(), "");
  5847. return;
  5848. }
  5849. if (id == TQualifier::getGeometryString(ElgLineStrip)) {
  5850. // publicType.shaderQualifiers.geometry = ElgLineStrip;
  5851. warn(loc, "ignored", id.c_str(), "");
  5852. return;
  5853. }
  5854. if (id == TQualifier::getGeometryString(ElgLines)) {
  5855. // publicType.shaderQualifiers.geometry = ElgLines;
  5856. warn(loc, "ignored", id.c_str(), "");
  5857. return;
  5858. }
  5859. if (id == TQualifier::getGeometryString(ElgLinesAdjacency)) {
  5860. // publicType.shaderQualifiers.geometry = ElgLinesAdjacency;
  5861. warn(loc, "ignored", id.c_str(), "");
  5862. return;
  5863. }
  5864. if (id == TQualifier::getGeometryString(ElgTrianglesAdjacency)) {
  5865. // publicType.shaderQualifiers.geometry = ElgTrianglesAdjacency;
  5866. warn(loc, "ignored", id.c_str(), "");
  5867. return;
  5868. }
  5869. if (id == TQualifier::getGeometryString(ElgTriangleStrip)) {
  5870. // publicType.shaderQualifiers.geometry = ElgTriangleStrip;
  5871. warn(loc, "ignored", id.c_str(), "");
  5872. return;
  5873. }
  5874. } else {
  5875. assert(language == EShLangTessEvaluation);
  5876. // input primitive
  5877. if (id == TQualifier::getGeometryString(ElgTriangles)) {
  5878. // publicType.shaderQualifiers.geometry = ElgTriangles;
  5879. warn(loc, "ignored", id.c_str(), "");
  5880. return;
  5881. }
  5882. if (id == TQualifier::getGeometryString(ElgQuads)) {
  5883. // publicType.shaderQualifiers.geometry = ElgQuads;
  5884. warn(loc, "ignored", id.c_str(), "");
  5885. return;
  5886. }
  5887. if (id == TQualifier::getGeometryString(ElgIsolines)) {
  5888. // publicType.shaderQualifiers.geometry = ElgIsolines;
  5889. warn(loc, "ignored", id.c_str(), "");
  5890. return;
  5891. }
  5892. // vertex spacing
  5893. if (id == TQualifier::getVertexSpacingString(EvsEqual)) {
  5894. // publicType.shaderQualifiers.spacing = EvsEqual;
  5895. warn(loc, "ignored", id.c_str(), "");
  5896. return;
  5897. }
  5898. if (id == TQualifier::getVertexSpacingString(EvsFractionalEven)) {
  5899. // publicType.shaderQualifiers.spacing = EvsFractionalEven;
  5900. warn(loc, "ignored", id.c_str(), "");
  5901. return;
  5902. }
  5903. if (id == TQualifier::getVertexSpacingString(EvsFractionalOdd)) {
  5904. // publicType.shaderQualifiers.spacing = EvsFractionalOdd;
  5905. warn(loc, "ignored", id.c_str(), "");
  5906. return;
  5907. }
  5908. // triangle order
  5909. if (id == TQualifier::getVertexOrderString(EvoCw)) {
  5910. // publicType.shaderQualifiers.order = EvoCw;
  5911. warn(loc, "ignored", id.c_str(), "");
  5912. return;
  5913. }
  5914. if (id == TQualifier::getVertexOrderString(EvoCcw)) {
  5915. // publicType.shaderQualifiers.order = EvoCcw;
  5916. warn(loc, "ignored", id.c_str(), "");
  5917. return;
  5918. }
  5919. // point mode
  5920. if (id == "point_mode") {
  5921. // publicType.shaderQualifiers.pointMode = true;
  5922. warn(loc, "ignored", id.c_str(), "");
  5923. return;
  5924. }
  5925. }
  5926. }
  5927. if (language == EShLangFragment) {
  5928. if (id == "origin_upper_left") {
  5929. // publicType.shaderQualifiers.originUpperLeft = true;
  5930. warn(loc, "ignored", id.c_str(), "");
  5931. return;
  5932. }
  5933. if (id == "pixel_center_integer") {
  5934. // publicType.shaderQualifiers.pixelCenterInteger = true;
  5935. warn(loc, "ignored", id.c_str(), "");
  5936. return;
  5937. }
  5938. if (id == "early_fragment_tests") {
  5939. // publicType.shaderQualifiers.earlyFragmentTests = true;
  5940. warn(loc, "ignored", id.c_str(), "");
  5941. return;
  5942. }
  5943. for (TLayoutDepth depth = (TLayoutDepth)(EldNone + 1); depth < EldCount; depth = (TLayoutDepth)(depth + 1)) {
  5944. if (id == TQualifier::getLayoutDepthString(depth)) {
  5945. // publicType.shaderQualifiers.layoutDepth = depth;
  5946. warn(loc, "ignored", id.c_str(), "");
  5947. return;
  5948. }
  5949. }
  5950. if (id.compare(0, 13, "blend_support") == 0) {
  5951. bool found = false;
  5952. for (TBlendEquationShift be = (TBlendEquationShift)0; be < EBlendCount; be = (TBlendEquationShift)(be + 1)) {
  5953. if (id == TQualifier::getBlendEquationString(be)) {
  5954. requireExtensions(loc, 1, &E_GL_KHR_blend_equation_advanced, "blend equation");
  5955. intermediate.addBlendEquation(be);
  5956. // publicType.shaderQualifiers.blendEquation = true;
  5957. warn(loc, "ignored", id.c_str(), "");
  5958. found = true;
  5959. break;
  5960. }
  5961. }
  5962. if (! found)
  5963. error(loc, "unknown blend equation", "blend_support", "");
  5964. return;
  5965. }
  5966. }
  5967. error(loc, "unrecognized layout identifier, or qualifier requires assignment (e.g., binding = 4)", id.c_str(), "");
  5968. }
  5969. // Put the id's layout qualifier value into the public type, for qualifiers having a number set.
  5970. // This is before we know any type information for error checking.
  5971. void HlslParseContext::setLayoutQualifier(const TSourceLoc& loc, TQualifier& qualifier, TString& id,
  5972. const TIntermTyped* node)
  5973. {
  5974. const char* feature = "layout-id value";
  5975. // const char* nonLiteralFeature = "non-literal layout-id value";
  5976. integerCheck(node, feature);
  5977. const TIntermConstantUnion* constUnion = node->getAsConstantUnion();
  5978. int value = 0;
  5979. if (constUnion) {
  5980. value = constUnion->getConstArray()[0].getIConst();
  5981. }
  5982. std::transform(id.begin(), id.end(), id.begin(), ::tolower);
  5983. if (id == "offset") {
  5984. qualifier.layoutOffset = value;
  5985. return;
  5986. } else if (id == "align") {
  5987. // "The specified alignment must be a power of 2, or a compile-time error results."
  5988. if (! IsPow2(value))
  5989. error(loc, "must be a power of 2", "align", "");
  5990. else
  5991. qualifier.layoutAlign = value;
  5992. return;
  5993. } else if (id == "location") {
  5994. if ((unsigned int)value >= TQualifier::layoutLocationEnd)
  5995. error(loc, "location is too large", id.c_str(), "");
  5996. else
  5997. qualifier.layoutLocation = value;
  5998. return;
  5999. } else if (id == "set") {
  6000. if ((unsigned int)value >= TQualifier::layoutSetEnd)
  6001. error(loc, "set is too large", id.c_str(), "");
  6002. else
  6003. qualifier.layoutSet = value;
  6004. return;
  6005. } else if (id == "binding") {
  6006. if ((unsigned int)value >= TQualifier::layoutBindingEnd)
  6007. error(loc, "binding is too large", id.c_str(), "");
  6008. else
  6009. qualifier.layoutBinding = value;
  6010. return;
  6011. } else if (id == "component") {
  6012. if ((unsigned)value >= TQualifier::layoutComponentEnd)
  6013. error(loc, "component is too large", id.c_str(), "");
  6014. else
  6015. qualifier.layoutComponent = value;
  6016. return;
  6017. } else if (id.compare(0, 4, "xfb_") == 0) {
  6018. // "Any shader making any static use (after preprocessing) of any of these
  6019. // *xfb_* qualifiers will cause the shader to be in a transform feedback
  6020. // capturing mode and hence responsible for describing the transform feedback
  6021. // setup."
  6022. intermediate.setXfbMode();
  6023. if (id == "xfb_buffer") {
  6024. // "It is a compile-time error to specify an *xfb_buffer* that is greater than
  6025. // the implementation-dependent constant gl_MaxTransformFeedbackBuffers."
  6026. if (value >= resources.maxTransformFeedbackBuffers)
  6027. error(loc, "buffer is too large:", id.c_str(), "gl_MaxTransformFeedbackBuffers is %d",
  6028. resources.maxTransformFeedbackBuffers);
  6029. if (value >= (int)TQualifier::layoutXfbBufferEnd)
  6030. error(loc, "buffer is too large:", id.c_str(), "internal max is %d", TQualifier::layoutXfbBufferEnd - 1);
  6031. else
  6032. qualifier.layoutXfbBuffer = value;
  6033. return;
  6034. } else if (id == "xfb_offset") {
  6035. if (value >= (int)TQualifier::layoutXfbOffsetEnd)
  6036. error(loc, "offset is too large:", id.c_str(), "internal max is %d", TQualifier::layoutXfbOffsetEnd - 1);
  6037. else
  6038. qualifier.layoutXfbOffset = value;
  6039. return;
  6040. } else if (id == "xfb_stride") {
  6041. // "The resulting stride (implicit or explicit), when divided by 4, must be less than or equal to the
  6042. // implementation-dependent constant gl_MaxTransformFeedbackInterleavedComponents."
  6043. if (value > 4 * resources.maxTransformFeedbackInterleavedComponents)
  6044. error(loc, "1/4 stride is too large:", id.c_str(), "gl_MaxTransformFeedbackInterleavedComponents is %d",
  6045. resources.maxTransformFeedbackInterleavedComponents);
  6046. else if (value >= (int)TQualifier::layoutXfbStrideEnd)
  6047. error(loc, "stride is too large:", id.c_str(), "internal max is %d", TQualifier::layoutXfbStrideEnd - 1);
  6048. if (value < (int)TQualifier::layoutXfbStrideEnd)
  6049. qualifier.layoutXfbStride = value;
  6050. return;
  6051. }
  6052. }
  6053. if (id == "input_attachment_index") {
  6054. requireVulkan(loc, "input_attachment_index");
  6055. if (value >= (int)TQualifier::layoutAttachmentEnd)
  6056. error(loc, "attachment index is too large", id.c_str(), "");
  6057. else
  6058. qualifier.layoutAttachment = value;
  6059. return;
  6060. }
  6061. if (id == "constant_id") {
  6062. setSpecConstantId(loc, qualifier, value);
  6063. return;
  6064. }
  6065. switch (language) {
  6066. case EShLangVertex:
  6067. break;
  6068. case EShLangTessControl:
  6069. if (id == "vertices") {
  6070. if (value == 0)
  6071. error(loc, "must be greater than 0", "vertices", "");
  6072. else
  6073. // publicType.shaderQualifiers.vertices = value;
  6074. warn(loc, "ignored", id.c_str(), "");
  6075. return;
  6076. }
  6077. break;
  6078. case EShLangTessEvaluation:
  6079. break;
  6080. case EShLangGeometry:
  6081. if (id == "invocations") {
  6082. if (value == 0)
  6083. error(loc, "must be at least 1", "invocations", "");
  6084. else
  6085. // publicType.shaderQualifiers.invocations = value;
  6086. warn(loc, "ignored", id.c_str(), "");
  6087. return;
  6088. }
  6089. if (id == "max_vertices") {
  6090. // publicType.shaderQualifiers.vertices = value;
  6091. warn(loc, "ignored", id.c_str(), "");
  6092. if (value > resources.maxGeometryOutputVertices)
  6093. error(loc, "too large, must be less than gl_MaxGeometryOutputVertices", "max_vertices", "");
  6094. return;
  6095. }
  6096. if (id == "stream") {
  6097. qualifier.layoutStream = value;
  6098. return;
  6099. }
  6100. break;
  6101. case EShLangFragment:
  6102. if (id == "index") {
  6103. qualifier.layoutIndex = value;
  6104. return;
  6105. }
  6106. break;
  6107. case EShLangCompute:
  6108. if (id.compare(0, 11, "local_size_") == 0) {
  6109. if (id == "local_size_x") {
  6110. // publicType.shaderQualifiers.localSize[0] = value;
  6111. warn(loc, "ignored", id.c_str(), "");
  6112. return;
  6113. }
  6114. if (id == "local_size_y") {
  6115. // publicType.shaderQualifiers.localSize[1] = value;
  6116. warn(loc, "ignored", id.c_str(), "");
  6117. return;
  6118. }
  6119. if (id == "local_size_z") {
  6120. // publicType.shaderQualifiers.localSize[2] = value;
  6121. warn(loc, "ignored", id.c_str(), "");
  6122. return;
  6123. }
  6124. if (spvVersion.spv != 0) {
  6125. if (id == "local_size_x_id") {
  6126. // publicType.shaderQualifiers.localSizeSpecId[0] = value;
  6127. warn(loc, "ignored", id.c_str(), "");
  6128. return;
  6129. }
  6130. if (id == "local_size_y_id") {
  6131. // publicType.shaderQualifiers.localSizeSpecId[1] = value;
  6132. warn(loc, "ignored", id.c_str(), "");
  6133. return;
  6134. }
  6135. if (id == "local_size_z_id") {
  6136. // publicType.shaderQualifiers.localSizeSpecId[2] = value;
  6137. warn(loc, "ignored", id.c_str(), "");
  6138. return;
  6139. }
  6140. }
  6141. }
  6142. break;
  6143. default:
  6144. break;
  6145. }
  6146. error(loc, "there is no such layout identifier for this stage taking an assigned value", id.c_str(), "");
  6147. }
  6148. void HlslParseContext::setSpecConstantId(const TSourceLoc& loc, TQualifier& qualifier, int value)
  6149. {
  6150. if (value >= (int)TQualifier::layoutSpecConstantIdEnd) {
  6151. error(loc, "specialization-constant id is too large", "constant_id", "");
  6152. } else {
  6153. qualifier.layoutSpecConstantId = value;
  6154. qualifier.specConstant = true;
  6155. if (! intermediate.addUsedConstantId(value))
  6156. error(loc, "specialization-constant id already used", "constant_id", "");
  6157. }
  6158. return;
  6159. }
  6160. // Merge any layout qualifier information from src into dst, leaving everything else in dst alone
  6161. //
  6162. // "More than one layout qualifier may appear in a single declaration.
  6163. // Additionally, the same layout-qualifier-name can occur multiple times
  6164. // within a layout qualifier or across multiple layout qualifiers in the
  6165. // same declaration. When the same layout-qualifier-name occurs
  6166. // multiple times, in a single declaration, the last occurrence overrides
  6167. // the former occurrence(s). Further, if such a layout-qualifier-name
  6168. // will effect subsequent declarations or other observable behavior, it
  6169. // is only the last occurrence that will have any effect, behaving as if
  6170. // the earlier occurrence(s) within the declaration are not present.
  6171. // This is also true for overriding layout-qualifier-names, where one
  6172. // overrides the other (e.g., row_major vs. column_major); only the last
  6173. // occurrence has any effect."
  6174. //
  6175. void HlslParseContext::mergeObjectLayoutQualifiers(TQualifier& dst, const TQualifier& src, bool inheritOnly)
  6176. {
  6177. if (src.hasMatrix())
  6178. dst.layoutMatrix = src.layoutMatrix;
  6179. if (src.hasPacking())
  6180. dst.layoutPacking = src.layoutPacking;
  6181. if (src.hasStream())
  6182. dst.layoutStream = src.layoutStream;
  6183. if (src.hasFormat())
  6184. dst.layoutFormat = src.layoutFormat;
  6185. if (src.hasXfbBuffer())
  6186. dst.layoutXfbBuffer = src.layoutXfbBuffer;
  6187. if (src.hasAlign())
  6188. dst.layoutAlign = src.layoutAlign;
  6189. if (! inheritOnly) {
  6190. if (src.hasLocation())
  6191. dst.layoutLocation = src.layoutLocation;
  6192. if (src.hasComponent())
  6193. dst.layoutComponent = src.layoutComponent;
  6194. if (src.hasIndex())
  6195. dst.layoutIndex = src.layoutIndex;
  6196. if (src.hasOffset())
  6197. dst.layoutOffset = src.layoutOffset;
  6198. if (src.hasSet())
  6199. dst.layoutSet = src.layoutSet;
  6200. if (src.layoutBinding != TQualifier::layoutBindingEnd)
  6201. dst.layoutBinding = src.layoutBinding;
  6202. if (src.hasXfbStride())
  6203. dst.layoutXfbStride = src.layoutXfbStride;
  6204. if (src.hasXfbOffset())
  6205. dst.layoutXfbOffset = src.layoutXfbOffset;
  6206. if (src.hasAttachment())
  6207. dst.layoutAttachment = src.layoutAttachment;
  6208. if (src.hasSpecConstantId())
  6209. dst.layoutSpecConstantId = src.layoutSpecConstantId;
  6210. if (src.layoutPushConstant)
  6211. dst.layoutPushConstant = true;
  6212. }
  6213. }
  6214. //
  6215. // Look up a function name in the symbol table, and make sure it is a function.
  6216. //
  6217. // First, look for an exact match. If there is none, use the generic selector
  6218. // TParseContextBase::selectFunction() to find one, parameterized by the
  6219. // convertible() and better() predicates defined below.
  6220. //
  6221. // Return the function symbol if found, otherwise nullptr.
  6222. //
  6223. const TFunction* HlslParseContext::findFunction(const TSourceLoc& loc, TFunction& call, bool& builtIn, int& thisDepth,
  6224. TIntermTyped*& args)
  6225. {
  6226. if (symbolTable.isFunctionNameVariable(call.getName())) {
  6227. error(loc, "can't use function syntax on variable", call.getName().c_str(), "");
  6228. return nullptr;
  6229. }
  6230. // first, look for an exact match
  6231. bool dummyScope;
  6232. TSymbol* symbol = symbolTable.find(call.getMangledName(), &builtIn, &dummyScope, &thisDepth);
  6233. if (symbol)
  6234. return symbol->getAsFunction();
  6235. // no exact match, use the generic selector, parameterized by the GLSL rules
  6236. // create list of candidates to send
  6237. TVector<const TFunction*> candidateList;
  6238. symbolTable.findFunctionNameList(call.getMangledName(), candidateList, builtIn);
  6239. // These built-in ops can accept any type, so we bypass the argument selection
  6240. if (candidateList.size() == 1 && builtIn &&
  6241. (candidateList[0]->getBuiltInOp() == EOpMethodAppend ||
  6242. candidateList[0]->getBuiltInOp() == EOpMethodRestartStrip ||
  6243. candidateList[0]->getBuiltInOp() == EOpMethodIncrementCounter ||
  6244. candidateList[0]->getBuiltInOp() == EOpMethodDecrementCounter ||
  6245. candidateList[0]->getBuiltInOp() == EOpMethodAppend ||
  6246. candidateList[0]->getBuiltInOp() == EOpMethodConsume)) {
  6247. return candidateList[0];
  6248. }
  6249. bool allowOnlyUpConversions = true;
  6250. // can 'from' convert to 'to'?
  6251. const auto convertible = [&](const TType& from, const TType& to, TOperator op, int arg) -> bool {
  6252. if (from == to)
  6253. return true;
  6254. // no aggregate conversions
  6255. if (from.isArray() || to.isArray() ||
  6256. from.isStruct() || to.isStruct())
  6257. return false;
  6258. switch (op) {
  6259. case EOpInterlockedAdd:
  6260. case EOpInterlockedAnd:
  6261. case EOpInterlockedCompareExchange:
  6262. case EOpInterlockedCompareStore:
  6263. case EOpInterlockedExchange:
  6264. case EOpInterlockedMax:
  6265. case EOpInterlockedMin:
  6266. case EOpInterlockedOr:
  6267. case EOpInterlockedXor:
  6268. // We do not promote the texture or image type for these ocodes. Normally that would not
  6269. // be an issue because it's a buffer, but we haven't decomposed the opcode yet, and at this
  6270. // stage it's merely e.g, a basic integer type.
  6271. //
  6272. // Instead, we want to promote other arguments, but stay within the same family. In other
  6273. // words, InterlockedAdd(RWBuffer<int>, ...) will always use the int flavor, never the uint flavor,
  6274. // but it is allowed to promote its other arguments.
  6275. if (arg == 0)
  6276. return false;
  6277. break;
  6278. case EOpMethodSample:
  6279. case EOpMethodSampleBias:
  6280. case EOpMethodSampleCmp:
  6281. case EOpMethodSampleCmpLevelZero:
  6282. case EOpMethodSampleGrad:
  6283. case EOpMethodSampleLevel:
  6284. case EOpMethodLoad:
  6285. case EOpMethodGetDimensions:
  6286. case EOpMethodGetSamplePosition:
  6287. case EOpMethodGather:
  6288. case EOpMethodCalculateLevelOfDetail:
  6289. case EOpMethodCalculateLevelOfDetailUnclamped:
  6290. case EOpMethodGatherRed:
  6291. case EOpMethodGatherGreen:
  6292. case EOpMethodGatherBlue:
  6293. case EOpMethodGatherAlpha:
  6294. case EOpMethodGatherCmp:
  6295. case EOpMethodGatherCmpRed:
  6296. case EOpMethodGatherCmpGreen:
  6297. case EOpMethodGatherCmpBlue:
  6298. case EOpMethodGatherCmpAlpha:
  6299. case EOpMethodAppend:
  6300. case EOpMethodRestartStrip:
  6301. // those are method calls, the object type can not be changed
  6302. // they are equal if the dim and type match (is dim sufficient?)
  6303. if (arg == 0)
  6304. return from.getSampler().type == to.getSampler().type &&
  6305. from.getSampler().arrayed == to.getSampler().arrayed &&
  6306. from.getSampler().shadow == to.getSampler().shadow &&
  6307. from.getSampler().ms == to.getSampler().ms &&
  6308. from.getSampler().dim == to.getSampler().dim;
  6309. break;
  6310. default:
  6311. break;
  6312. }
  6313. // basic types have to be convertible
  6314. if (allowOnlyUpConversions)
  6315. if (! intermediate.canImplicitlyPromote(from.getBasicType(), to.getBasicType(), EOpFunctionCall))
  6316. return false;
  6317. // shapes have to be convertible
  6318. if ((from.isScalarOrVec1() && to.isScalarOrVec1()) ||
  6319. (from.isScalarOrVec1() && to.isVector()) ||
  6320. (from.isScalarOrVec1() && to.isMatrix()) ||
  6321. (from.isVector() && to.isVector() && from.getVectorSize() >= to.getVectorSize()))
  6322. return true;
  6323. // TODO: what are the matrix rules? they go here
  6324. return false;
  6325. };
  6326. // Is 'to2' a better conversion than 'to1'?
  6327. // Ties should not be considered as better.
  6328. // Assumes 'convertible' already said true.
  6329. const auto better = [](const TType& from, const TType& to1, const TType& to2) -> bool {
  6330. // exact match is always better than mismatch
  6331. if (from == to2)
  6332. return from != to1;
  6333. if (from == to1)
  6334. return false;
  6335. // shape changes are always worse
  6336. if (from.isScalar() || from.isVector()) {
  6337. if (from.getVectorSize() == to2.getVectorSize() &&
  6338. from.getVectorSize() != to1.getVectorSize())
  6339. return true;
  6340. if (from.getVectorSize() == to1.getVectorSize() &&
  6341. from.getVectorSize() != to2.getVectorSize())
  6342. return false;
  6343. }
  6344. // Handle sampler betterness: An exact sampler match beats a non-exact match.
  6345. // (If we just looked at basic type, all EbtSamplers would look the same).
  6346. // If any type is not a sampler, just use the linearize function below.
  6347. if (from.getBasicType() == EbtSampler && to1.getBasicType() == EbtSampler && to2.getBasicType() == EbtSampler) {
  6348. // We can ignore the vector size in the comparison.
  6349. TSampler to1Sampler = to1.getSampler();
  6350. TSampler to2Sampler = to2.getSampler();
  6351. to1Sampler.vectorSize = to2Sampler.vectorSize = from.getSampler().vectorSize;
  6352. if (from.getSampler() == to2Sampler)
  6353. return from.getSampler() != to1Sampler;
  6354. if (from.getSampler() == to1Sampler)
  6355. return false;
  6356. }
  6357. // Might or might not be changing shape, which means basic type might
  6358. // or might not match, so within that, the question is how big a
  6359. // basic-type conversion is being done.
  6360. //
  6361. // Use a hierarchy of domains, translated to order of magnitude
  6362. // in a linearized view:
  6363. // - floating-point vs. integer
  6364. // - 32 vs. 64 bit (or width in general)
  6365. // - bool vs. non bool
  6366. // - signed vs. not signed
  6367. const auto linearize = [](const TBasicType& basicType) -> int {
  6368. switch (basicType) {
  6369. case EbtBool: return 1;
  6370. case EbtInt: return 10;
  6371. case EbtUint: return 11;
  6372. case EbtInt64: return 20;
  6373. case EbtUint64: return 21;
  6374. case EbtFloat: return 100;
  6375. case EbtDouble: return 110;
  6376. default: return 0;
  6377. }
  6378. };
  6379. return abs(linearize(to2.getBasicType()) - linearize(from.getBasicType())) <
  6380. abs(linearize(to1.getBasicType()) - linearize(from.getBasicType()));
  6381. };
  6382. // for ambiguity reporting
  6383. bool tie = false;
  6384. // send to the generic selector
  6385. const TFunction* bestMatch = selectFunction(candidateList, call, convertible, better, tie);
  6386. if (bestMatch == nullptr) {
  6387. // If there is nothing selected by allowing only up-conversions (to a larger linearize() value),
  6388. // we instead try down-conversions, which are valid in HLSL, but not preferred if there are any
  6389. // upconversions possible.
  6390. allowOnlyUpConversions = false;
  6391. bestMatch = selectFunction(candidateList, call, convertible, better, tie);
  6392. }
  6393. if (bestMatch == nullptr) {
  6394. error(loc, "no matching overloaded function found", call.getName().c_str(), "");
  6395. return nullptr;
  6396. }
  6397. // For built-ins, we can convert across the arguments. This will happen in several steps:
  6398. // Step 1: If there's an exact match, use it.
  6399. // Step 2a: Otherwise, get the operator from the best match and promote arguments:
  6400. // Step 2b: reconstruct the TFunction based on the new arg types
  6401. // Step 3: Re-select after type promotion is applied, to find proper candidate.
  6402. if (builtIn) {
  6403. // Step 1: If there's an exact match, use it.
  6404. if (call.getMangledName() == bestMatch->getMangledName())
  6405. return bestMatch;
  6406. // Step 2a: Otherwise, get the operator from the best match and promote arguments as if we
  6407. // are that kind of operator.
  6408. if (args != nullptr) {
  6409. // The arg list can be a unary node, or an aggregate. We have to handle both.
  6410. // We will use the normal promote() facilities, which require an interm node.
  6411. TIntermOperator* promote = nullptr;
  6412. if (call.getParamCount() == 1) {
  6413. promote = new TIntermUnary(bestMatch->getBuiltInOp());
  6414. promote->getAsUnaryNode()->setOperand(args->getAsTyped());
  6415. } else {
  6416. promote = new TIntermAggregate(bestMatch->getBuiltInOp());
  6417. promote->getAsAggregate()->getSequence().swap(args->getAsAggregate()->getSequence());
  6418. }
  6419. if (! intermediate.promote(promote))
  6420. return nullptr;
  6421. // Obtain the promoted arg list.
  6422. if (call.getParamCount() == 1) {
  6423. args = promote->getAsUnaryNode()->getOperand();
  6424. } else {
  6425. promote->getAsAggregate()->getSequence().swap(args->getAsAggregate()->getSequence());
  6426. }
  6427. }
  6428. // Step 2b: reconstruct the TFunction based on the new arg types
  6429. TFunction convertedCall(&call.getName(), call.getType(), call.getBuiltInOp());
  6430. if (args->getAsAggregate()) {
  6431. // Handle aggregates: put all args into the new function call
  6432. for (int arg = 0; arg < int(args->getAsAggregate()->getSequence().size()); ++arg) {
  6433. // TODO: But for constness, we could avoid the new & shallowCopy, and use the pointer directly.
  6434. TParameter param = { 0, new TType, nullptr };
  6435. param.type->shallowCopy(args->getAsAggregate()->getSequence()[arg]->getAsTyped()->getType());
  6436. convertedCall.addParameter(param);
  6437. }
  6438. } else if (args->getAsUnaryNode()) {
  6439. // Handle unaries: put all args into the new function call
  6440. TParameter param = { 0, new TType, nullptr };
  6441. param.type->shallowCopy(args->getAsUnaryNode()->getOperand()->getAsTyped()->getType());
  6442. convertedCall.addParameter(param);
  6443. } else if (args->getAsTyped()) {
  6444. // Handle bare e.g, floats, not in an aggregate.
  6445. TParameter param = { 0, new TType, nullptr };
  6446. param.type->shallowCopy(args->getAsTyped()->getType());
  6447. convertedCall.addParameter(param);
  6448. } else {
  6449. assert(0); // unknown argument list.
  6450. return nullptr;
  6451. }
  6452. // Step 3: Re-select after type promotion, to find proper candidate
  6453. // send to the generic selector
  6454. bestMatch = selectFunction(candidateList, convertedCall, convertible, better, tie);
  6455. // At this point, there should be no tie.
  6456. }
  6457. if (tie)
  6458. error(loc, "ambiguous best function under implicit type conversion", call.getName().c_str(), "");
  6459. // Append default parameter values if needed
  6460. if (!tie && bestMatch != nullptr) {
  6461. for (int defParam = call.getParamCount(); defParam < bestMatch->getParamCount(); ++defParam) {
  6462. handleFunctionArgument(&call, args, (*bestMatch)[defParam].defaultValue);
  6463. }
  6464. }
  6465. return bestMatch;
  6466. }
  6467. //
  6468. // Do everything necessary to handle a typedef declaration, for a single symbol.
  6469. //
  6470. // 'parseType' is the type part of the declaration (to the left)
  6471. // 'arraySizes' is the arrayness tagged on the identifier (to the right)
  6472. //
  6473. void HlslParseContext::declareTypedef(const TSourceLoc& loc, const TString& identifier, const TType& parseType)
  6474. {
  6475. TVariable* typeSymbol = new TVariable(&identifier, parseType, true);
  6476. if (! symbolTable.insert(*typeSymbol))
  6477. error(loc, "name already defined", "typedef", identifier.c_str());
  6478. }
  6479. // Do everything necessary to handle a struct declaration, including
  6480. // making IO aliases because HLSL allows mixed IO in a struct that specializes
  6481. // based on the usage (input, output, uniform, none).
  6482. void HlslParseContext::declareStruct(const TSourceLoc& loc, TString& structName, TType& type)
  6483. {
  6484. // If it was named, which means the type can be reused later, add
  6485. // it to the symbol table. (Unless it's a block, in which
  6486. // case the name is not a type.)
  6487. if (type.getBasicType() == EbtBlock || structName.size() == 0)
  6488. return;
  6489. TVariable* userTypeDef = new TVariable(&structName, type, true);
  6490. if (! symbolTable.insert(*userTypeDef)) {
  6491. error(loc, "redefinition", structName.c_str(), "struct");
  6492. return;
  6493. }
  6494. // See if we need IO aliases for the structure typeList
  6495. const auto condAlloc = [](bool pred, TTypeList*& list) {
  6496. if (pred && list == nullptr)
  6497. list = new TTypeList;
  6498. };
  6499. tIoKinds newLists = { nullptr, nullptr, nullptr }; // allocate for each kind found
  6500. for (auto member = type.getStruct()->begin(); member != type.getStruct()->end(); ++member) {
  6501. condAlloc(hasUniform(member->type->getQualifier()), newLists.uniform);
  6502. condAlloc( hasInput(member->type->getQualifier()), newLists.input);
  6503. condAlloc( hasOutput(member->type->getQualifier()), newLists.output);
  6504. if (member->type->isStruct()) {
  6505. auto it = ioTypeMap.find(member->type->getStruct());
  6506. if (it != ioTypeMap.end()) {
  6507. condAlloc(it->second.uniform != nullptr, newLists.uniform);
  6508. condAlloc(it->second.input != nullptr, newLists.input);
  6509. condAlloc(it->second.output != nullptr, newLists.output);
  6510. }
  6511. }
  6512. }
  6513. if (newLists.uniform == nullptr &&
  6514. newLists.input == nullptr &&
  6515. newLists.output == nullptr) {
  6516. // Won't do any IO caching, clear up the type and get out now.
  6517. for (auto member = type.getStruct()->begin(); member != type.getStruct()->end(); ++member)
  6518. clearUniformInputOutput(member->type->getQualifier());
  6519. return;
  6520. }
  6521. // We have IO involved.
  6522. // Make a pure typeList for the symbol table, and cache side copies of IO versions.
  6523. for (auto member = type.getStruct()->begin(); member != type.getStruct()->end(); ++member) {
  6524. const auto inheritStruct = [&](TTypeList* s, TTypeLoc& ioMember) {
  6525. if (s != nullptr) {
  6526. ioMember.type = new TType;
  6527. ioMember.type->shallowCopy(*member->type);
  6528. ioMember.type->setStruct(s);
  6529. }
  6530. };
  6531. const auto newMember = [&](TTypeLoc& m) {
  6532. if (m.type == nullptr) {
  6533. m.type = new TType;
  6534. m.type->shallowCopy(*member->type);
  6535. }
  6536. };
  6537. TTypeLoc newUniformMember = { nullptr, member->loc };
  6538. TTypeLoc newInputMember = { nullptr, member->loc };
  6539. TTypeLoc newOutputMember = { nullptr, member->loc };
  6540. if (member->type->isStruct()) {
  6541. // swap in an IO child if there is one
  6542. auto it = ioTypeMap.find(member->type->getStruct());
  6543. if (it != ioTypeMap.end()) {
  6544. inheritStruct(it->second.uniform, newUniformMember);
  6545. inheritStruct(it->second.input, newInputMember);
  6546. inheritStruct(it->second.output, newOutputMember);
  6547. }
  6548. }
  6549. if (newLists.uniform) {
  6550. newMember(newUniformMember);
  6551. // inherit default matrix layout (changeable via #pragma pack_matrix), if none given.
  6552. if (member->type->isMatrix() && member->type->getQualifier().layoutMatrix == ElmNone)
  6553. newUniformMember.type->getQualifier().layoutMatrix = globalUniformDefaults.layoutMatrix;
  6554. correctUniform(newUniformMember.type->getQualifier());
  6555. newLists.uniform->push_back(newUniformMember);
  6556. }
  6557. if (newLists.input) {
  6558. newMember(newInputMember);
  6559. correctInput(newInputMember.type->getQualifier());
  6560. newLists.input->push_back(newInputMember);
  6561. }
  6562. if (newLists.output) {
  6563. newMember(newOutputMember);
  6564. correctOutput(newOutputMember.type->getQualifier());
  6565. newLists.output->push_back(newOutputMember);
  6566. }
  6567. // make original pure
  6568. clearUniformInputOutput(member->type->getQualifier());
  6569. }
  6570. ioTypeMap[type.getStruct()] = newLists;
  6571. }
  6572. // Lookup a user-type by name.
  6573. // If found, fill in the type and return the defining symbol.
  6574. // If not found, return nullptr.
  6575. TSymbol* HlslParseContext::lookupUserType(const TString& typeName, TType& type)
  6576. {
  6577. TSymbol* symbol = symbolTable.find(typeName);
  6578. if (symbol && symbol->getAsVariable() && symbol->getAsVariable()->isUserType()) {
  6579. type.shallowCopy(symbol->getType());
  6580. return symbol;
  6581. } else
  6582. return nullptr;
  6583. }
  6584. //
  6585. // Do everything necessary to handle a variable (non-block) declaration.
  6586. // Either redeclaring a variable, or making a new one, updating the symbol
  6587. // table, and all error checking.
  6588. //
  6589. // Returns a subtree node that computes an initializer, if needed.
  6590. // Returns nullptr if there is no code to execute for initialization.
  6591. //
  6592. // 'parseType' is the type part of the declaration (to the left)
  6593. // 'arraySizes' is the arrayness tagged on the identifier (to the right)
  6594. //
  6595. TIntermNode* HlslParseContext::declareVariable(const TSourceLoc& loc, const TString& identifier, TType& type,
  6596. TIntermTyped* initializer)
  6597. {
  6598. if (voidErrorCheck(loc, identifier, type.getBasicType()))
  6599. return nullptr;
  6600. // Global consts with initializers that are non-const act like EvqGlobal in HLSL.
  6601. // This test is implicitly recursive, because initializers propagate constness
  6602. // up the aggregate node tree during creation. E.g, for:
  6603. // { { 1, 2 }, { 3, 4 } }
  6604. // the initializer list is marked EvqConst at the top node, and remains so here. However:
  6605. // { 1, { myvar, 2 }, 3 }
  6606. // is not a const intializer, and still becomes EvqGlobal here.
  6607. const bool nonConstInitializer = (initializer != nullptr && initializer->getQualifier().storage != EvqConst);
  6608. if (type.getQualifier().storage == EvqConst && symbolTable.atGlobalLevel() && nonConstInitializer) {
  6609. // Force to global
  6610. type.getQualifier().storage = EvqGlobal;
  6611. }
  6612. // make const and initialization consistent
  6613. fixConstInit(loc, identifier, type, initializer);
  6614. // Check for redeclaration of built-ins and/or attempting to declare a reserved name
  6615. TSymbol* symbol = nullptr;
  6616. inheritGlobalDefaults(type.getQualifier());
  6617. const bool flattenVar = shouldFlatten(type, type.getQualifier().storage, true);
  6618. // correct IO in the type
  6619. switch (type.getQualifier().storage) {
  6620. case EvqGlobal:
  6621. case EvqTemporary:
  6622. clearUniformInputOutput(type.getQualifier());
  6623. break;
  6624. case EvqUniform:
  6625. case EvqBuffer:
  6626. correctUniform(type.getQualifier());
  6627. if (type.isStruct()) {
  6628. auto it = ioTypeMap.find(type.getStruct());
  6629. if (it != ioTypeMap.end())
  6630. type.setStruct(it->second.uniform);
  6631. }
  6632. break;
  6633. default:
  6634. break;
  6635. }
  6636. // Declare the variable
  6637. if (type.isArray()) {
  6638. // array case
  6639. declareArray(loc, identifier, type, symbol, !flattenVar);
  6640. } else {
  6641. // non-array case
  6642. if (symbol == nullptr)
  6643. symbol = declareNonArray(loc, identifier, type, !flattenVar);
  6644. else if (type != symbol->getType())
  6645. error(loc, "cannot change the type of", "redeclaration", symbol->getName().c_str());
  6646. }
  6647. if (symbol == nullptr)
  6648. return nullptr;
  6649. if (flattenVar)
  6650. flatten(*symbol->getAsVariable(), symbolTable.atGlobalLevel());
  6651. if (initializer == nullptr)
  6652. return nullptr;
  6653. // Deal with initializer
  6654. TVariable* variable = symbol->getAsVariable();
  6655. if (variable == nullptr) {
  6656. error(loc, "initializer requires a variable, not a member", identifier.c_str(), "");
  6657. return nullptr;
  6658. }
  6659. return executeInitializer(loc, initializer, variable);
  6660. }
  6661. // Pick up global defaults from the provide global defaults into dst.
  6662. void HlslParseContext::inheritGlobalDefaults(TQualifier& dst) const
  6663. {
  6664. if (dst.storage == EvqVaryingOut) {
  6665. if (! dst.hasStream() && language == EShLangGeometry)
  6666. dst.layoutStream = globalOutputDefaults.layoutStream;
  6667. if (! dst.hasXfbBuffer())
  6668. dst.layoutXfbBuffer = globalOutputDefaults.layoutXfbBuffer;
  6669. }
  6670. }
  6671. //
  6672. // Make an internal-only variable whose name is for debug purposes only
  6673. // and won't be searched for. Callers will only use the return value to use
  6674. // the variable, not the name to look it up. It is okay if the name
  6675. // is the same as other names; there won't be any conflict.
  6676. //
  6677. TVariable* HlslParseContext::makeInternalVariable(const char* name, const TType& type) const
  6678. {
  6679. TString* nameString = NewPoolTString(name);
  6680. TVariable* variable = new TVariable(nameString, type);
  6681. symbolTable.makeInternalVariable(*variable);
  6682. return variable;
  6683. }
  6684. // Make a symbol node holding a new internal temporary variable.
  6685. TIntermSymbol* HlslParseContext::makeInternalVariableNode(const TSourceLoc& loc, const char* name,
  6686. const TType& type) const
  6687. {
  6688. TVariable* tmpVar = makeInternalVariable(name, type);
  6689. tmpVar->getWritableType().getQualifier().makeTemporary();
  6690. return intermediate.addSymbol(*tmpVar, loc);
  6691. }
  6692. //
  6693. // Declare a non-array variable, the main point being there is no redeclaration
  6694. // for resizing allowed.
  6695. //
  6696. // Return the successfully declared variable.
  6697. //
  6698. TVariable* HlslParseContext::declareNonArray(const TSourceLoc& loc, const TString& identifier, const TType& type,
  6699. bool track)
  6700. {
  6701. // make a new variable
  6702. TVariable* variable = new TVariable(&identifier, type);
  6703. // add variable to symbol table
  6704. if (symbolTable.insert(*variable)) {
  6705. if (track && symbolTable.atGlobalLevel())
  6706. trackLinkage(*variable);
  6707. return variable;
  6708. }
  6709. error(loc, "redefinition", variable->getName().c_str(), "");
  6710. return nullptr;
  6711. }
  6712. //
  6713. // Handle all types of initializers from the grammar.
  6714. //
  6715. // Returning nullptr just means there is no code to execute to handle the
  6716. // initializer, which will, for example, be the case for constant initializers.
  6717. //
  6718. // Returns a subtree that accomplished the initialization.
  6719. //
  6720. TIntermNode* HlslParseContext::executeInitializer(const TSourceLoc& loc, TIntermTyped* initializer, TVariable* variable)
  6721. {
  6722. //
  6723. // Identifier must be of type constant, a global, or a temporary, and
  6724. // starting at version 120, desktop allows uniforms to have initializers.
  6725. //
  6726. TStorageQualifier qualifier = variable->getType().getQualifier().storage;
  6727. //
  6728. // If the initializer was from braces { ... }, we convert the whole subtree to a
  6729. // constructor-style subtree, allowing the rest of the code to operate
  6730. // identically for both kinds of initializers.
  6731. //
  6732. //
  6733. // Type can't be deduced from the initializer list, so a skeletal type to
  6734. // follow has to be passed in. Constness and specialization-constness
  6735. // should be deduced bottom up, not dictated by the skeletal type.
  6736. //
  6737. TType skeletalType;
  6738. skeletalType.shallowCopy(variable->getType());
  6739. skeletalType.getQualifier().makeTemporary();
  6740. if (initializer->getAsAggregate() && initializer->getAsAggregate()->getOp() == EOpNull)
  6741. initializer = convertInitializerList(loc, skeletalType, initializer, nullptr);
  6742. if (initializer == nullptr) {
  6743. // error recovery; don't leave const without constant values
  6744. if (qualifier == EvqConst)
  6745. variable->getWritableType().getQualifier().storage = EvqTemporary;
  6746. return nullptr;
  6747. }
  6748. // Fix outer arrayness if variable is unsized, getting size from the initializer
  6749. if (initializer->getType().isSizedArray() && variable->getType().isUnsizedArray())
  6750. variable->getWritableType().changeOuterArraySize(initializer->getType().getOuterArraySize());
  6751. // Inner arrayness can also get set by an initializer
  6752. if (initializer->getType().isArrayOfArrays() && variable->getType().isArrayOfArrays() &&
  6753. initializer->getType().getArraySizes()->getNumDims() ==
  6754. variable->getType().getArraySizes()->getNumDims()) {
  6755. // adopt unsized sizes from the initializer's sizes
  6756. for (int d = 1; d < variable->getType().getArraySizes()->getNumDims(); ++d) {
  6757. if (variable->getType().getArraySizes()->getDimSize(d) == UnsizedArraySize) {
  6758. variable->getWritableType().getArraySizes()->setDimSize(d,
  6759. initializer->getType().getArraySizes()->getDimSize(d));
  6760. }
  6761. }
  6762. }
  6763. // Uniform and global consts require a constant initializer
  6764. if (qualifier == EvqUniform && initializer->getType().getQualifier().storage != EvqConst) {
  6765. error(loc, "uniform initializers must be constant", "=", "'%s'", variable->getType().getCompleteString().c_str());
  6766. variable->getWritableType().getQualifier().storage = EvqTemporary;
  6767. return nullptr;
  6768. }
  6769. // Const variables require a constant initializer
  6770. if (qualifier == EvqConst) {
  6771. if (initializer->getType().getQualifier().storage != EvqConst) {
  6772. variable->getWritableType().getQualifier().storage = EvqConstReadOnly;
  6773. qualifier = EvqConstReadOnly;
  6774. }
  6775. }
  6776. if (qualifier == EvqConst || qualifier == EvqUniform) {
  6777. // Compile-time tagging of the variable with its constant value...
  6778. initializer = intermediate.addConversion(EOpAssign, variable->getType(), initializer);
  6779. if (initializer != nullptr && variable->getType() != initializer->getType())
  6780. initializer = intermediate.addUniShapeConversion(EOpAssign, variable->getType(), initializer);
  6781. if (initializer == nullptr || !initializer->getAsConstantUnion() ||
  6782. variable->getType() != initializer->getType()) {
  6783. error(loc, "non-matching or non-convertible constant type for const initializer",
  6784. variable->getType().getStorageQualifierString(), "");
  6785. variable->getWritableType().getQualifier().storage = EvqTemporary;
  6786. return nullptr;
  6787. }
  6788. variable->setConstArray(initializer->getAsConstantUnion()->getConstArray());
  6789. } else {
  6790. // normal assigning of a value to a variable...
  6791. specializationCheck(loc, initializer->getType(), "initializer");
  6792. TIntermSymbol* intermSymbol = intermediate.addSymbol(*variable, loc);
  6793. TIntermNode* initNode = handleAssign(loc, EOpAssign, intermSymbol, initializer);
  6794. if (initNode == nullptr)
  6795. assignError(loc, "=", intermSymbol->getCompleteString(), initializer->getCompleteString());
  6796. return initNode;
  6797. }
  6798. return nullptr;
  6799. }
  6800. //
  6801. // Reprocess any initializer-list { ... } parts of the initializer.
  6802. // Need to hierarchically assign correct types and implicit
  6803. // conversions. Will do this mimicking the same process used for
  6804. // creating a constructor-style initializer, ensuring we get the
  6805. // same form.
  6806. //
  6807. // Returns a node representing an expression for the initializer list expressed
  6808. // as the correct type.
  6809. //
  6810. // Returns nullptr if there is an error.
  6811. //
  6812. TIntermTyped* HlslParseContext::convertInitializerList(const TSourceLoc& loc, const TType& type,
  6813. TIntermTyped* initializer, TIntermTyped* scalarInit)
  6814. {
  6815. // Will operate recursively. Once a subtree is found that is constructor style,
  6816. // everything below it is already good: Only the "top part" of the initializer
  6817. // can be an initializer list, where "top part" can extend for several (or all) levels.
  6818. // see if we have bottomed out in the tree within the initializer-list part
  6819. TIntermAggregate* initList = initializer->getAsAggregate();
  6820. if (initList == nullptr || initList->getOp() != EOpNull) {
  6821. // We don't have a list, but if it's a scalar and the 'type' is a
  6822. // composite, we need to lengthen below to make it useful.
  6823. // Otherwise, this is an already formed object to initialize with.
  6824. if (type.isScalar() || !initializer->getType().isScalar())
  6825. return initializer;
  6826. else
  6827. initList = intermediate.makeAggregate(initializer);
  6828. }
  6829. // Of the initializer-list set of nodes, need to process bottom up,
  6830. // so recurse deep, then process on the way up.
  6831. // Go down the tree here...
  6832. if (type.isArray()) {
  6833. // The type's array might be unsized, which could be okay, so base sizes on the size of the aggregate.
  6834. // Later on, initializer execution code will deal with array size logic.
  6835. TType arrayType;
  6836. arrayType.shallowCopy(type); // sharing struct stuff is fine
  6837. arrayType.copyArraySizes(*type.getArraySizes()); // but get a fresh copy of the array information, to edit below
  6838. // edit array sizes to fill in unsized dimensions
  6839. if (type.isUnsizedArray())
  6840. arrayType.changeOuterArraySize((int)initList->getSequence().size());
  6841. // set unsized array dimensions that can be derived from the initializer's first element
  6842. if (arrayType.isArrayOfArrays() && initList->getSequence().size() > 0) {
  6843. TIntermTyped* firstInit = initList->getSequence()[0]->getAsTyped();
  6844. if (firstInit->getType().isArray() &&
  6845. arrayType.getArraySizes()->getNumDims() == firstInit->getType().getArraySizes()->getNumDims() + 1) {
  6846. for (int d = 1; d < arrayType.getArraySizes()->getNumDims(); ++d) {
  6847. if (arrayType.getArraySizes()->getDimSize(d) == UnsizedArraySize)
  6848. arrayType.getArraySizes()->setDimSize(d, firstInit->getType().getArraySizes()->getDimSize(d - 1));
  6849. }
  6850. }
  6851. }
  6852. // lengthen list to be long enough
  6853. lengthenList(loc, initList->getSequence(), arrayType.getOuterArraySize(), scalarInit);
  6854. // recursively process each element
  6855. TType elementType(arrayType, 0); // dereferenced type
  6856. for (int i = 0; i < arrayType.getOuterArraySize(); ++i) {
  6857. initList->getSequence()[i] = convertInitializerList(loc, elementType,
  6858. initList->getSequence()[i]->getAsTyped(), scalarInit);
  6859. if (initList->getSequence()[i] == nullptr)
  6860. return nullptr;
  6861. }
  6862. return addConstructor(loc, initList, arrayType);
  6863. } else if (type.isStruct()) {
  6864. // do we have implicit assignments to opaques?
  6865. for (size_t i = initList->getSequence().size(); i < type.getStruct()->size(); ++i) {
  6866. if ((*type.getStruct())[i].type->containsOpaque()) {
  6867. error(loc, "cannot implicitly initialize opaque members", "initializer list", "");
  6868. return nullptr;
  6869. }
  6870. }
  6871. // lengthen list to be long enough
  6872. lengthenList(loc, initList->getSequence(), static_cast<int>(type.getStruct()->size()), scalarInit);
  6873. if (type.getStruct()->size() != initList->getSequence().size()) {
  6874. error(loc, "wrong number of structure members", "initializer list", "");
  6875. return nullptr;
  6876. }
  6877. for (size_t i = 0; i < type.getStruct()->size(); ++i) {
  6878. initList->getSequence()[i] = convertInitializerList(loc, *(*type.getStruct())[i].type,
  6879. initList->getSequence()[i]->getAsTyped(), scalarInit);
  6880. if (initList->getSequence()[i] == nullptr)
  6881. return nullptr;
  6882. }
  6883. } else if (type.isMatrix()) {
  6884. if (type.computeNumComponents() == (int)initList->getSequence().size()) {
  6885. // This means the matrix is initialized component-wise, rather than as
  6886. // a series of rows and columns. We can just use the list directly as
  6887. // a constructor; no further processing needed.
  6888. } else {
  6889. // lengthen list to be long enough
  6890. lengthenList(loc, initList->getSequence(), type.getMatrixCols(), scalarInit);
  6891. if (type.getMatrixCols() != (int)initList->getSequence().size()) {
  6892. error(loc, "wrong number of matrix columns:", "initializer list", type.getCompleteString().c_str());
  6893. return nullptr;
  6894. }
  6895. TType vectorType(type, 0); // dereferenced type
  6896. for (int i = 0; i < type.getMatrixCols(); ++i) {
  6897. initList->getSequence()[i] = convertInitializerList(loc, vectorType,
  6898. initList->getSequence()[i]->getAsTyped(), scalarInit);
  6899. if (initList->getSequence()[i] == nullptr)
  6900. return nullptr;
  6901. }
  6902. }
  6903. } else if (type.isVector()) {
  6904. // lengthen list to be long enough
  6905. lengthenList(loc, initList->getSequence(), type.getVectorSize(), scalarInit);
  6906. // error check; we're at bottom, so work is finished below
  6907. if (type.getVectorSize() != (int)initList->getSequence().size()) {
  6908. error(loc, "wrong vector size (or rows in a matrix column):", "initializer list",
  6909. type.getCompleteString().c_str());
  6910. return nullptr;
  6911. }
  6912. } else if (type.isScalar()) {
  6913. // lengthen list to be long enough
  6914. lengthenList(loc, initList->getSequence(), 1, scalarInit);
  6915. if ((int)initList->getSequence().size() != 1) {
  6916. error(loc, "scalar expected one element:", "initializer list", type.getCompleteString().c_str());
  6917. return nullptr;
  6918. }
  6919. } else {
  6920. error(loc, "unexpected initializer-list type:", "initializer list", type.getCompleteString().c_str());
  6921. return nullptr;
  6922. }
  6923. // Now that the subtree is processed, process this node as if the
  6924. // initializer list is a set of arguments to a constructor.
  6925. TIntermTyped* emulatedConstructorArguments;
  6926. if (initList->getSequence().size() == 1)
  6927. emulatedConstructorArguments = initList->getSequence()[0]->getAsTyped();
  6928. else
  6929. emulatedConstructorArguments = initList;
  6930. return addConstructor(loc, emulatedConstructorArguments, type);
  6931. }
  6932. // Lengthen list to be long enough to cover any gap from the current list size
  6933. // to 'size'. If the list is longer, do nothing.
  6934. // The value to lengthen with is the default for short lists.
  6935. //
  6936. // By default, lists that are too short due to lack of initializers initialize to zero.
  6937. // Alternatively, it could be a scalar initializer for a structure. Both cases are handled,
  6938. // based on whether something is passed in as 'scalarInit'.
  6939. //
  6940. // 'scalarInit' must be safe to use each time this is called (no side effects replication).
  6941. //
  6942. void HlslParseContext::lengthenList(const TSourceLoc& loc, TIntermSequence& list, int size, TIntermTyped* scalarInit)
  6943. {
  6944. for (int c = (int)list.size(); c < size; ++c) {
  6945. if (scalarInit == nullptr)
  6946. list.push_back(intermediate.addConstantUnion(0, loc));
  6947. else
  6948. list.push_back(scalarInit);
  6949. }
  6950. }
  6951. //
  6952. // Test for the correctness of the parameters passed to various constructor functions
  6953. // and also convert them to the right data type, if allowed and required.
  6954. //
  6955. // Returns nullptr for an error or the constructed node (aggregate or typed) for no error.
  6956. //
  6957. TIntermTyped* HlslParseContext::handleConstructor(const TSourceLoc& loc, TIntermTyped* node, const TType& type)
  6958. {
  6959. if (node == nullptr)
  6960. return nullptr;
  6961. // Construct identical type
  6962. if (type == node->getType())
  6963. return node;
  6964. // Handle the idiom "(struct type)<scalar value>"
  6965. if (type.isStruct() && isScalarConstructor(node)) {
  6966. // 'node' will almost always get used multiple times, so should not be used directly,
  6967. // it would create a DAG instead of a tree, which might be okay (would
  6968. // like to formalize that for constants and symbols), but if it has
  6969. // side effects, they would get executed multiple times, which is not okay.
  6970. if (node->getAsConstantUnion() == nullptr && node->getAsSymbolNode() == nullptr) {
  6971. TIntermAggregate* seq = intermediate.makeAggregate(loc);
  6972. TIntermSymbol* copy = makeInternalVariableNode(loc, "scalarCopy", node->getType());
  6973. seq = intermediate.growAggregate(seq, intermediate.addBinaryNode(EOpAssign, copy, node, loc));
  6974. seq = intermediate.growAggregate(seq, convertInitializerList(loc, type, intermediate.makeAggregate(loc), copy));
  6975. seq->setOp(EOpComma);
  6976. seq->setType(type);
  6977. return seq;
  6978. } else
  6979. return convertInitializerList(loc, type, intermediate.makeAggregate(loc), node);
  6980. }
  6981. return addConstructor(loc, node, type);
  6982. }
  6983. // Add a constructor, either from the grammar, or other programmatic reasons.
  6984. //
  6985. // 'node' is what to construct from.
  6986. // 'type' is what type to construct.
  6987. //
  6988. // Returns the constructed object.
  6989. // Return nullptr if it can't be done.
  6990. //
  6991. TIntermTyped* HlslParseContext::addConstructor(const TSourceLoc& loc, TIntermTyped* node, const TType& type)
  6992. {
  6993. TIntermAggregate* aggrNode = node->getAsAggregate();
  6994. TOperator op = intermediate.mapTypeToConstructorOp(type);
  6995. if (op == EOpConstructTextureSampler)
  6996. return intermediate.setAggregateOperator(aggrNode, op, type, loc);
  6997. TTypeList::const_iterator memberTypes;
  6998. if (op == EOpConstructStruct)
  6999. memberTypes = type.getStruct()->begin();
  7000. TType elementType;
  7001. if (type.isArray()) {
  7002. TType dereferenced(type, 0);
  7003. elementType.shallowCopy(dereferenced);
  7004. } else
  7005. elementType.shallowCopy(type);
  7006. bool singleArg;
  7007. if (aggrNode != nullptr) {
  7008. if (aggrNode->getOp() != EOpNull)
  7009. singleArg = true;
  7010. else
  7011. singleArg = false;
  7012. } else
  7013. singleArg = true;
  7014. TIntermTyped *newNode;
  7015. if (singleArg) {
  7016. // Handle array -> array conversion
  7017. // Constructing an array of one type from an array of another type is allowed,
  7018. // assuming there are enough components available (semantic-checked earlier).
  7019. if (type.isArray() && node->isArray())
  7020. newNode = convertArray(node, type);
  7021. // If structure constructor or array constructor is being called
  7022. // for only one parameter inside the aggregate, we need to call constructAggregate function once.
  7023. else if (type.isArray())
  7024. newNode = constructAggregate(node, elementType, 1, node->getLoc());
  7025. else if (op == EOpConstructStruct)
  7026. newNode = constructAggregate(node, *(*memberTypes).type, 1, node->getLoc());
  7027. else {
  7028. // shape conversion for matrix constructor from scalar. HLSL semantics are: scalar
  7029. // is replicated into every element of the matrix (not just the diagnonal), so
  7030. // that is handled specially here.
  7031. if (type.isMatrix() && node->getType().isScalarOrVec1())
  7032. node = intermediate.addShapeConversion(type, node);
  7033. newNode = constructBuiltIn(type, op, node, node->getLoc(), false);
  7034. }
  7035. if (newNode && (type.isArray() || op == EOpConstructStruct))
  7036. newNode = intermediate.setAggregateOperator(newNode, EOpConstructStruct, type, loc);
  7037. return newNode;
  7038. }
  7039. //
  7040. // Handle list of arguments.
  7041. //
  7042. TIntermSequence& sequenceVector = aggrNode->getSequence(); // Stores the information about the parameter to the constructor
  7043. // if the structure constructor contains more than one parameter, then construct
  7044. // each parameter
  7045. int paramCount = 0; // keeps a track of the constructor parameter number being checked
  7046. // for each parameter to the constructor call, check to see if the right type is passed or convert them
  7047. // to the right type if possible (and allowed).
  7048. // for structure constructors, just check if the right type is passed, no conversion is allowed.
  7049. for (TIntermSequence::iterator p = sequenceVector.begin();
  7050. p != sequenceVector.end(); p++, paramCount++) {
  7051. if (type.isArray())
  7052. newNode = constructAggregate(*p, elementType, paramCount + 1, node->getLoc());
  7053. else if (op == EOpConstructStruct)
  7054. newNode = constructAggregate(*p, *(memberTypes[paramCount]).type, paramCount + 1, node->getLoc());
  7055. else
  7056. newNode = constructBuiltIn(type, op, (*p)->getAsTyped(), node->getLoc(), true);
  7057. if (newNode)
  7058. *p = newNode;
  7059. else
  7060. return nullptr;
  7061. }
  7062. TIntermTyped* constructor = intermediate.setAggregateOperator(aggrNode, op, type, loc);
  7063. return constructor;
  7064. }
  7065. // Function for constructor implementation. Calls addUnaryMath with appropriate EOp value
  7066. // for the parameter to the constructor (passed to this function). Essentially, it converts
  7067. // the parameter types correctly. If a constructor expects an int (like ivec2) and is passed a
  7068. // float, then float is converted to int.
  7069. //
  7070. // Returns nullptr for an error or the constructed node.
  7071. //
  7072. TIntermTyped* HlslParseContext::constructBuiltIn(const TType& type, TOperator op, TIntermTyped* node,
  7073. const TSourceLoc& loc, bool subset)
  7074. {
  7075. TIntermTyped* newNode;
  7076. TOperator basicOp;
  7077. //
  7078. // First, convert types as needed.
  7079. //
  7080. switch (op) {
  7081. case EOpConstructF16Vec2:
  7082. case EOpConstructF16Vec3:
  7083. case EOpConstructF16Vec4:
  7084. case EOpConstructF16Mat2x2:
  7085. case EOpConstructF16Mat2x3:
  7086. case EOpConstructF16Mat2x4:
  7087. case EOpConstructF16Mat3x2:
  7088. case EOpConstructF16Mat3x3:
  7089. case EOpConstructF16Mat3x4:
  7090. case EOpConstructF16Mat4x2:
  7091. case EOpConstructF16Mat4x3:
  7092. case EOpConstructF16Mat4x4:
  7093. case EOpConstructFloat16:
  7094. basicOp = EOpConstructFloat16;
  7095. break;
  7096. case EOpConstructVec2:
  7097. case EOpConstructVec3:
  7098. case EOpConstructVec4:
  7099. case EOpConstructMat2x2:
  7100. case EOpConstructMat2x3:
  7101. case EOpConstructMat2x4:
  7102. case EOpConstructMat3x2:
  7103. case EOpConstructMat3x3:
  7104. case EOpConstructMat3x4:
  7105. case EOpConstructMat4x2:
  7106. case EOpConstructMat4x3:
  7107. case EOpConstructMat4x4:
  7108. case EOpConstructFloat:
  7109. basicOp = EOpConstructFloat;
  7110. break;
  7111. case EOpConstructDVec2:
  7112. case EOpConstructDVec3:
  7113. case EOpConstructDVec4:
  7114. case EOpConstructDMat2x2:
  7115. case EOpConstructDMat2x3:
  7116. case EOpConstructDMat2x4:
  7117. case EOpConstructDMat3x2:
  7118. case EOpConstructDMat3x3:
  7119. case EOpConstructDMat3x4:
  7120. case EOpConstructDMat4x2:
  7121. case EOpConstructDMat4x3:
  7122. case EOpConstructDMat4x4:
  7123. case EOpConstructDouble:
  7124. basicOp = EOpConstructDouble;
  7125. break;
  7126. case EOpConstructI16Vec2:
  7127. case EOpConstructI16Vec3:
  7128. case EOpConstructI16Vec4:
  7129. case EOpConstructInt16:
  7130. basicOp = EOpConstructInt16;
  7131. break;
  7132. case EOpConstructIVec2:
  7133. case EOpConstructIVec3:
  7134. case EOpConstructIVec4:
  7135. case EOpConstructIMat2x2:
  7136. case EOpConstructIMat2x3:
  7137. case EOpConstructIMat2x4:
  7138. case EOpConstructIMat3x2:
  7139. case EOpConstructIMat3x3:
  7140. case EOpConstructIMat3x4:
  7141. case EOpConstructIMat4x2:
  7142. case EOpConstructIMat4x3:
  7143. case EOpConstructIMat4x4:
  7144. case EOpConstructInt:
  7145. basicOp = EOpConstructInt;
  7146. break;
  7147. case EOpConstructU16Vec2:
  7148. case EOpConstructU16Vec3:
  7149. case EOpConstructU16Vec4:
  7150. case EOpConstructUint16:
  7151. basicOp = EOpConstructUint16;
  7152. break;
  7153. case EOpConstructUVec2:
  7154. case EOpConstructUVec3:
  7155. case EOpConstructUVec4:
  7156. case EOpConstructUMat2x2:
  7157. case EOpConstructUMat2x3:
  7158. case EOpConstructUMat2x4:
  7159. case EOpConstructUMat3x2:
  7160. case EOpConstructUMat3x3:
  7161. case EOpConstructUMat3x4:
  7162. case EOpConstructUMat4x2:
  7163. case EOpConstructUMat4x3:
  7164. case EOpConstructUMat4x4:
  7165. case EOpConstructUint:
  7166. basicOp = EOpConstructUint;
  7167. break;
  7168. case EOpConstructBVec2:
  7169. case EOpConstructBVec3:
  7170. case EOpConstructBVec4:
  7171. case EOpConstructBMat2x2:
  7172. case EOpConstructBMat2x3:
  7173. case EOpConstructBMat2x4:
  7174. case EOpConstructBMat3x2:
  7175. case EOpConstructBMat3x3:
  7176. case EOpConstructBMat3x4:
  7177. case EOpConstructBMat4x2:
  7178. case EOpConstructBMat4x3:
  7179. case EOpConstructBMat4x4:
  7180. case EOpConstructBool:
  7181. basicOp = EOpConstructBool;
  7182. break;
  7183. default:
  7184. error(loc, "unsupported construction", "", "");
  7185. return nullptr;
  7186. }
  7187. newNode = intermediate.addUnaryMath(basicOp, node, node->getLoc());
  7188. if (newNode == nullptr) {
  7189. error(loc, "can't convert", "constructor", "");
  7190. return nullptr;
  7191. }
  7192. //
  7193. // Now, if there still isn't an operation to do the construction, and we need one, add one.
  7194. //
  7195. // Otherwise, skip out early.
  7196. if (subset || (newNode != node && newNode->getType() == type))
  7197. return newNode;
  7198. // setAggregateOperator will insert a new node for the constructor, as needed.
  7199. return intermediate.setAggregateOperator(newNode, op, type, loc);
  7200. }
  7201. // Convert the array in node to the requested type, which is also an array.
  7202. // Returns nullptr on failure, otherwise returns aggregate holding the list of
  7203. // elements needed to construct the array.
  7204. TIntermTyped* HlslParseContext::convertArray(TIntermTyped* node, const TType& type)
  7205. {
  7206. assert(node->isArray() && type.isArray());
  7207. if (node->getType().computeNumComponents() < type.computeNumComponents())
  7208. return nullptr;
  7209. // TODO: write an argument replicator, for the case the argument should not be
  7210. // executed multiple times, yet multiple copies are needed.
  7211. TIntermTyped* constructee = node->getAsTyped();
  7212. // track where we are in consuming the argument
  7213. int constructeeElement = 0;
  7214. int constructeeComponent = 0;
  7215. // bump up to the next component to consume
  7216. const auto getNextComponent = [&]() {
  7217. TIntermTyped* component;
  7218. component = handleBracketDereference(node->getLoc(), constructee,
  7219. intermediate.addConstantUnion(constructeeElement, node->getLoc()));
  7220. if (component->isVector())
  7221. component = handleBracketDereference(node->getLoc(), component,
  7222. intermediate.addConstantUnion(constructeeComponent, node->getLoc()));
  7223. // bump component pointer up
  7224. ++constructeeComponent;
  7225. if (constructeeComponent == constructee->getVectorSize()) {
  7226. constructeeComponent = 0;
  7227. ++constructeeElement;
  7228. }
  7229. return component;
  7230. };
  7231. // make one subnode per constructed array element
  7232. TIntermAggregate* constructor = nullptr;
  7233. TType derefType(type, 0);
  7234. TType speculativeComponentType(derefType, 0);
  7235. TType* componentType = derefType.isVector() ? &speculativeComponentType : &derefType;
  7236. TOperator componentOp = intermediate.mapTypeToConstructorOp(*componentType);
  7237. TType crossType(node->getBasicType(), EvqTemporary, type.getVectorSize());
  7238. for (int e = 0; e < type.getOuterArraySize(); ++e) {
  7239. // construct an element
  7240. TIntermTyped* elementArg;
  7241. if (type.getVectorSize() == constructee->getVectorSize()) {
  7242. // same element shape
  7243. elementArg = handleBracketDereference(node->getLoc(), constructee,
  7244. intermediate.addConstantUnion(e, node->getLoc()));
  7245. } else {
  7246. // mismatched element shapes
  7247. if (type.getVectorSize() == 1)
  7248. elementArg = getNextComponent();
  7249. else {
  7250. // make a vector
  7251. TIntermAggregate* elementConstructee = nullptr;
  7252. for (int c = 0; c < type.getVectorSize(); ++c)
  7253. elementConstructee = intermediate.growAggregate(elementConstructee, getNextComponent());
  7254. elementArg = addConstructor(node->getLoc(), elementConstructee, crossType);
  7255. }
  7256. }
  7257. // convert basic types
  7258. elementArg = intermediate.addConversion(componentOp, derefType, elementArg);
  7259. if (elementArg == nullptr)
  7260. return nullptr;
  7261. // combine with top-level constructor
  7262. constructor = intermediate.growAggregate(constructor, elementArg);
  7263. }
  7264. return constructor;
  7265. }
  7266. // This function tests for the type of the parameters to the structure or array constructor. Raises
  7267. // an error message if the expected type does not match the parameter passed to the constructor.
  7268. //
  7269. // Returns nullptr for an error or the input node itself if the expected and the given parameter types match.
  7270. //
  7271. TIntermTyped* HlslParseContext::constructAggregate(TIntermNode* node, const TType& type, int paramCount,
  7272. const TSourceLoc& loc)
  7273. {
  7274. // Handle cases that map more 1:1 between constructor arguments and constructed.
  7275. TIntermTyped* converted = intermediate.addConversion(EOpConstructStruct, type, node->getAsTyped());
  7276. if (converted == nullptr || converted->getType() != type) {
  7277. error(loc, "", "constructor", "cannot convert parameter %d from '%s' to '%s'", paramCount,
  7278. node->getAsTyped()->getType().getCompleteString().c_str(), type.getCompleteString().c_str());
  7279. return nullptr;
  7280. }
  7281. return converted;
  7282. }
  7283. //
  7284. // Do everything needed to add an interface block.
  7285. //
  7286. void HlslParseContext::declareBlock(const TSourceLoc& loc, TType& type, const TString* instanceName)
  7287. {
  7288. assert(type.getWritableStruct() != nullptr);
  7289. // Clean up top-level decorations that don't belong.
  7290. switch (type.getQualifier().storage) {
  7291. case EvqUniform:
  7292. case EvqBuffer:
  7293. correctUniform(type.getQualifier());
  7294. break;
  7295. case EvqVaryingIn:
  7296. correctInput(type.getQualifier());
  7297. break;
  7298. case EvqVaryingOut:
  7299. correctOutput(type.getQualifier());
  7300. break;
  7301. default:
  7302. break;
  7303. }
  7304. TTypeList& typeList = *type.getWritableStruct();
  7305. // fix and check for member storage qualifiers and types that don't belong within a block
  7306. for (unsigned int member = 0; member < typeList.size(); ++member) {
  7307. TType& memberType = *typeList[member].type;
  7308. TQualifier& memberQualifier = memberType.getQualifier();
  7309. const TSourceLoc& memberLoc = typeList[member].loc;
  7310. globalQualifierFix(memberLoc, memberQualifier);
  7311. memberQualifier.storage = type.getQualifier().storage;
  7312. if (memberType.isStruct()) {
  7313. // clean up and pick up the right set of decorations
  7314. auto it = ioTypeMap.find(memberType.getStruct());
  7315. switch (type.getQualifier().storage) {
  7316. case EvqUniform:
  7317. case EvqBuffer:
  7318. correctUniform(type.getQualifier());
  7319. if (it != ioTypeMap.end() && it->second.uniform)
  7320. memberType.setStruct(it->second.uniform);
  7321. break;
  7322. case EvqVaryingIn:
  7323. correctInput(type.getQualifier());
  7324. if (it != ioTypeMap.end() && it->second.input)
  7325. memberType.setStruct(it->second.input);
  7326. break;
  7327. case EvqVaryingOut:
  7328. correctOutput(type.getQualifier());
  7329. if (it != ioTypeMap.end() && it->second.output)
  7330. memberType.setStruct(it->second.output);
  7331. break;
  7332. default:
  7333. break;
  7334. }
  7335. }
  7336. }
  7337. // Make default block qualification, and adjust the member qualifications
  7338. TQualifier defaultQualification;
  7339. switch (type.getQualifier().storage) {
  7340. case EvqUniform: defaultQualification = globalUniformDefaults; break;
  7341. case EvqBuffer: defaultQualification = globalBufferDefaults; break;
  7342. case EvqVaryingIn: defaultQualification = globalInputDefaults; break;
  7343. case EvqVaryingOut: defaultQualification = globalOutputDefaults; break;
  7344. default: defaultQualification.clear(); break;
  7345. }
  7346. // Special case for "push_constant uniform", which has a default of std430,
  7347. // contrary to normal uniform defaults, and can't have a default tracked for it.
  7348. if (type.getQualifier().layoutPushConstant && ! type.getQualifier().hasPacking())
  7349. type.getQualifier().layoutPacking = ElpStd430;
  7350. // fix and check for member layout qualifiers
  7351. mergeObjectLayoutQualifiers(defaultQualification, type.getQualifier(), true);
  7352. bool memberWithLocation = false;
  7353. bool memberWithoutLocation = false;
  7354. for (unsigned int member = 0; member < typeList.size(); ++member) {
  7355. TQualifier& memberQualifier = typeList[member].type->getQualifier();
  7356. const TSourceLoc& memberLoc = typeList[member].loc;
  7357. if (memberQualifier.hasStream()) {
  7358. if (defaultQualification.layoutStream != memberQualifier.layoutStream)
  7359. error(memberLoc, "member cannot contradict block", "stream", "");
  7360. }
  7361. // "This includes a block's inheritance of the
  7362. // current global default buffer, a block member's inheritance of the block's
  7363. // buffer, and the requirement that any *xfb_buffer* declared on a block
  7364. // member must match the buffer inherited from the block."
  7365. if (memberQualifier.hasXfbBuffer()) {
  7366. if (defaultQualification.layoutXfbBuffer != memberQualifier.layoutXfbBuffer)
  7367. error(memberLoc, "member cannot contradict block (or what block inherited from global)", "xfb_buffer", "");
  7368. }
  7369. if (memberQualifier.hasLocation()) {
  7370. switch (type.getQualifier().storage) {
  7371. case EvqVaryingIn:
  7372. case EvqVaryingOut:
  7373. memberWithLocation = true;
  7374. break;
  7375. default:
  7376. break;
  7377. }
  7378. } else
  7379. memberWithoutLocation = true;
  7380. TQualifier newMemberQualification = defaultQualification;
  7381. mergeQualifiers(newMemberQualification, memberQualifier);
  7382. memberQualifier = newMemberQualification;
  7383. }
  7384. // Process the members
  7385. fixBlockLocations(loc, type.getQualifier(), typeList, memberWithLocation, memberWithoutLocation);
  7386. fixXfbOffsets(type.getQualifier(), typeList);
  7387. fixBlockUniformOffsets(type.getQualifier(), typeList);
  7388. // reverse merge, so that currentBlockQualifier now has all layout information
  7389. // (can't use defaultQualification directly, it's missing other non-layout-default-class qualifiers)
  7390. mergeObjectLayoutQualifiers(type.getQualifier(), defaultQualification, true);
  7391. //
  7392. // Build and add the interface block as a new type named 'blockName'
  7393. //
  7394. // Use the instance name as the interface name if one exists, else the block name.
  7395. const TString& interfaceName = (instanceName && !instanceName->empty()) ? *instanceName : type.getTypeName();
  7396. TType blockType(&typeList, interfaceName, type.getQualifier());
  7397. if (type.isArray())
  7398. blockType.transferArraySizes(type.getArraySizes());
  7399. // Add the variable, as anonymous or named instanceName.
  7400. // Make an anonymous variable if no name was provided.
  7401. if (instanceName == nullptr)
  7402. instanceName = NewPoolTString("");
  7403. TVariable& variable = *new TVariable(instanceName, blockType);
  7404. if (! symbolTable.insert(variable)) {
  7405. if (*instanceName == "")
  7406. error(loc, "nameless block contains a member that already has a name at global scope",
  7407. "" /* blockName->c_str() */, "");
  7408. else
  7409. error(loc, "block instance name redefinition", variable.getName().c_str(), "");
  7410. return;
  7411. }
  7412. // Save it in the AST for linker use.
  7413. if (symbolTable.atGlobalLevel())
  7414. trackLinkage(variable);
  7415. }
  7416. //
  7417. // "For a block, this process applies to the entire block, or until the first member
  7418. // is reached that has a location layout qualifier. When a block member is declared with a location
  7419. // qualifier, its location comes from that qualifier: The member's location qualifier overrides the block-level
  7420. // declaration. Subsequent members are again assigned consecutive locations, based on the newest location,
  7421. // until the next member declared with a location qualifier. The values used for locations do not have to be
  7422. // declared in increasing order."
  7423. void HlslParseContext::fixBlockLocations(const TSourceLoc& loc, TQualifier& qualifier, TTypeList& typeList, bool memberWithLocation, bool memberWithoutLocation)
  7424. {
  7425. // "If a block has no block-level location layout qualifier, it is required that either all or none of its members
  7426. // have a location layout qualifier, or a compile-time error results."
  7427. if (! qualifier.hasLocation() && memberWithLocation && memberWithoutLocation)
  7428. error(loc, "either the block needs a location, or all members need a location, or no members have a location", "location", "");
  7429. else {
  7430. if (memberWithLocation) {
  7431. // remove any block-level location and make it per *every* member
  7432. int nextLocation = 0; // by the rule above, initial value is not relevant
  7433. if (qualifier.hasAnyLocation()) {
  7434. nextLocation = qualifier.layoutLocation;
  7435. qualifier.layoutLocation = TQualifier::layoutLocationEnd;
  7436. if (qualifier.hasComponent()) {
  7437. // "It is a compile-time error to apply the *component* qualifier to a ... block"
  7438. error(loc, "cannot apply to a block", "component", "");
  7439. }
  7440. if (qualifier.hasIndex()) {
  7441. error(loc, "cannot apply to a block", "index", "");
  7442. }
  7443. }
  7444. for (unsigned int member = 0; member < typeList.size(); ++member) {
  7445. TQualifier& memberQualifier = typeList[member].type->getQualifier();
  7446. const TSourceLoc& memberLoc = typeList[member].loc;
  7447. if (! memberQualifier.hasLocation()) {
  7448. if (nextLocation >= (int)TQualifier::layoutLocationEnd)
  7449. error(memberLoc, "location is too large", "location", "");
  7450. memberQualifier.layoutLocation = nextLocation;
  7451. memberQualifier.layoutComponent = 0;
  7452. }
  7453. nextLocation = memberQualifier.layoutLocation +
  7454. intermediate.computeTypeLocationSize(*typeList[member].type, language);
  7455. }
  7456. }
  7457. }
  7458. }
  7459. void HlslParseContext::fixXfbOffsets(TQualifier& qualifier, TTypeList& typeList)
  7460. {
  7461. // "If a block is qualified with xfb_offset, all its
  7462. // members are assigned transform feedback buffer offsets. If a block is not qualified with xfb_offset, any
  7463. // members of that block not qualified with an xfb_offset will not be assigned transform feedback buffer
  7464. // offsets."
  7465. if (! qualifier.hasXfbBuffer() || ! qualifier.hasXfbOffset())
  7466. return;
  7467. int nextOffset = qualifier.layoutXfbOffset;
  7468. for (unsigned int member = 0; member < typeList.size(); ++member) {
  7469. TQualifier& memberQualifier = typeList[member].type->getQualifier();
  7470. bool contains64BitType = false;
  7471. bool contains32BitType = false;
  7472. bool contains16BitType = false;
  7473. int memberSize = intermediate.computeTypeXfbSize(*typeList[member].type, contains64BitType, contains32BitType, contains16BitType);
  7474. // see if we need to auto-assign an offset to this member
  7475. if (! memberQualifier.hasXfbOffset()) {
  7476. // "if applied to an aggregate containing a double or 64-bit integer, the offset must also be a multiple of 8"
  7477. if (contains64BitType)
  7478. RoundToPow2(nextOffset, 8);
  7479. else if (contains32BitType)
  7480. RoundToPow2(nextOffset, 4);
  7481. // "if applied to an aggregate containing a half float or 16-bit integer, the offset must also be a multiple of 2"
  7482. else if (contains16BitType)
  7483. RoundToPow2(nextOffset, 2);
  7484. memberQualifier.layoutXfbOffset = nextOffset;
  7485. } else
  7486. nextOffset = memberQualifier.layoutXfbOffset;
  7487. nextOffset += memberSize;
  7488. }
  7489. // The above gave all block members an offset, so we can take it off the block now,
  7490. // which will avoid double counting the offset usage.
  7491. qualifier.layoutXfbOffset = TQualifier::layoutXfbOffsetEnd;
  7492. }
  7493. // Calculate and save the offset of each block member, using the recursively
  7494. // defined block offset rules and the user-provided offset and align.
  7495. //
  7496. // Also, compute and save the total size of the block. For the block's size, arrayness
  7497. // is not taken into account, as each element is backed by a separate buffer.
  7498. //
  7499. void HlslParseContext::fixBlockUniformOffsets(const TQualifier& qualifier, TTypeList& typeList)
  7500. {
  7501. if (! qualifier.isUniformOrBuffer())
  7502. return;
  7503. if (qualifier.layoutPacking != ElpStd140 && qualifier.layoutPacking != ElpStd430 && qualifier.layoutPacking != ElpScalar)
  7504. return;
  7505. int offset = 0;
  7506. int memberSize;
  7507. for (unsigned int member = 0; member < typeList.size(); ++member) {
  7508. TQualifier& memberQualifier = typeList[member].type->getQualifier();
  7509. const TSourceLoc& memberLoc = typeList[member].loc;
  7510. // "When align is applied to an array, it effects only the start of the array, not the array's internal stride."
  7511. // modify just the children's view of matrix layout, if there is one for this member
  7512. TLayoutMatrix subMatrixLayout = typeList[member].type->getQualifier().layoutMatrix;
  7513. int dummyStride;
  7514. int memberAlignment = intermediate.getMemberAlignment(*typeList[member].type, memberSize, dummyStride,
  7515. qualifier.layoutPacking,
  7516. subMatrixLayout != ElmNone
  7517. ? subMatrixLayout == ElmRowMajor
  7518. : qualifier.layoutMatrix == ElmRowMajor);
  7519. if (memberQualifier.hasOffset()) {
  7520. // "The specified offset must be a multiple
  7521. // of the base alignment of the type of the block member it qualifies, or a compile-time error results."
  7522. if (! IsMultipleOfPow2(memberQualifier.layoutOffset, memberAlignment))
  7523. error(memberLoc, "must be a multiple of the member's alignment", "offset", "");
  7524. // "The offset qualifier forces the qualified member to start at or after the specified
  7525. // integral-constant expression, which will be its byte offset from the beginning of the buffer.
  7526. // "The actual offset of a member is computed as
  7527. // follows: If offset was declared, start with that offset, otherwise start with the next available offset."
  7528. offset = std::max(offset, memberQualifier.layoutOffset);
  7529. }
  7530. // "The actual alignment of a member will be the greater of the specified align alignment and the standard
  7531. // (e.g., std140) base alignment for the member's type."
  7532. if (memberQualifier.hasAlign())
  7533. memberAlignment = std::max(memberAlignment, memberQualifier.layoutAlign);
  7534. // "If the resulting offset is not a multiple of the actual alignment,
  7535. // increase it to the first offset that is a multiple of
  7536. // the actual alignment."
  7537. RoundToPow2(offset, memberAlignment);
  7538. typeList[member].type->getQualifier().layoutOffset = offset;
  7539. offset += memberSize;
  7540. }
  7541. }
  7542. // For an identifier that is already declared, add more qualification to it.
  7543. void HlslParseContext::addQualifierToExisting(const TSourceLoc& loc, TQualifier qualifier, const TString& identifier)
  7544. {
  7545. TSymbol* symbol = symbolTable.find(identifier);
  7546. if (symbol == nullptr) {
  7547. error(loc, "identifier not previously declared", identifier.c_str(), "");
  7548. return;
  7549. }
  7550. if (symbol->getAsFunction()) {
  7551. error(loc, "cannot re-qualify a function name", identifier.c_str(), "");
  7552. return;
  7553. }
  7554. if (qualifier.isAuxiliary() ||
  7555. qualifier.isMemory() ||
  7556. qualifier.isInterpolation() ||
  7557. qualifier.hasLayout() ||
  7558. qualifier.storage != EvqTemporary ||
  7559. qualifier.precision != EpqNone) {
  7560. error(loc, "cannot add storage, auxiliary, memory, interpolation, layout, or precision qualifier to an existing variable", identifier.c_str(), "");
  7561. return;
  7562. }
  7563. // For read-only built-ins, add a new symbol for holding the modified qualifier.
  7564. // This will bring up an entire block, if a block type has to be modified (e.g., gl_Position inside a block)
  7565. if (symbol->isReadOnly())
  7566. symbol = symbolTable.copyUp(symbol);
  7567. if (qualifier.invariant) {
  7568. if (intermediate.inIoAccessed(identifier))
  7569. error(loc, "cannot change qualification after use", "invariant", "");
  7570. symbol->getWritableType().getQualifier().invariant = true;
  7571. } else if (qualifier.noContraction) {
  7572. if (intermediate.inIoAccessed(identifier))
  7573. error(loc, "cannot change qualification after use", "precise", "");
  7574. symbol->getWritableType().getQualifier().noContraction = true;
  7575. } else if (qualifier.specConstant) {
  7576. symbol->getWritableType().getQualifier().makeSpecConstant();
  7577. if (qualifier.hasSpecConstantId())
  7578. symbol->getWritableType().getQualifier().layoutSpecConstantId = qualifier.layoutSpecConstantId;
  7579. } else
  7580. warn(loc, "unknown requalification", "", "");
  7581. }
  7582. void HlslParseContext::addQualifierToExisting(const TSourceLoc& loc, TQualifier qualifier, TIdentifierList& identifiers)
  7583. {
  7584. for (unsigned int i = 0; i < identifiers.size(); ++i)
  7585. addQualifierToExisting(loc, qualifier, *identifiers[i]);
  7586. }
  7587. //
  7588. // Update the intermediate for the given input geometry
  7589. //
  7590. bool HlslParseContext::handleInputGeometry(const TSourceLoc& loc, const TLayoutGeometry& geometry)
  7591. {
  7592. // these can be declared on non-entry-points, in which case they lose their meaning
  7593. if (! parsingEntrypointParameters)
  7594. return true;
  7595. switch (geometry) {
  7596. case ElgPoints: // fall through
  7597. case ElgLines: // ...
  7598. case ElgTriangles: // ...
  7599. case ElgLinesAdjacency: // ...
  7600. case ElgTrianglesAdjacency: // ...
  7601. if (! intermediate.setInputPrimitive(geometry)) {
  7602. error(loc, "input primitive geometry redefinition", TQualifier::getGeometryString(geometry), "");
  7603. return false;
  7604. }
  7605. break;
  7606. default:
  7607. error(loc, "cannot apply to 'in'", TQualifier::getGeometryString(geometry), "");
  7608. return false;
  7609. }
  7610. return true;
  7611. }
  7612. //
  7613. // Update the intermediate for the given output geometry
  7614. //
  7615. bool HlslParseContext::handleOutputGeometry(const TSourceLoc& loc, const TLayoutGeometry& geometry)
  7616. {
  7617. // If this is not a geometry shader, ignore. It might be a mixed shader including several stages.
  7618. // Since that's an OK situation, return true for success.
  7619. if (language != EShLangGeometry)
  7620. return true;
  7621. // these can be declared on non-entry-points, in which case they lose their meaning
  7622. if (! parsingEntrypointParameters)
  7623. return true;
  7624. switch (geometry) {
  7625. case ElgPoints:
  7626. case ElgLineStrip:
  7627. case ElgTriangleStrip:
  7628. if (! intermediate.setOutputPrimitive(geometry)) {
  7629. error(loc, "output primitive geometry redefinition", TQualifier::getGeometryString(geometry), "");
  7630. return false;
  7631. }
  7632. break;
  7633. default:
  7634. error(loc, "cannot apply to 'out'", TQualifier::getGeometryString(geometry), "");
  7635. return false;
  7636. }
  7637. return true;
  7638. }
  7639. //
  7640. // Selection attributes
  7641. //
  7642. void HlslParseContext::handleSelectionAttributes(const TSourceLoc& loc, TIntermSelection* selection,
  7643. const TAttributes& attributes)
  7644. {
  7645. if (selection == nullptr)
  7646. return;
  7647. for (auto it = attributes.begin(); it != attributes.end(); ++it) {
  7648. switch (it->name) {
  7649. case EatFlatten:
  7650. selection->setFlatten();
  7651. break;
  7652. case EatBranch:
  7653. selection->setDontFlatten();
  7654. break;
  7655. default:
  7656. warn(loc, "attribute does not apply to a selection", "", "");
  7657. break;
  7658. }
  7659. }
  7660. }
  7661. //
  7662. // Switch attributes
  7663. //
  7664. void HlslParseContext::handleSwitchAttributes(const TSourceLoc& loc, TIntermSwitch* selection,
  7665. const TAttributes& attributes)
  7666. {
  7667. if (selection == nullptr)
  7668. return;
  7669. for (auto it = attributes.begin(); it != attributes.end(); ++it) {
  7670. switch (it->name) {
  7671. case EatFlatten:
  7672. selection->setFlatten();
  7673. break;
  7674. case EatBranch:
  7675. selection->setDontFlatten();
  7676. break;
  7677. default:
  7678. warn(loc, "attribute does not apply to a switch", "", "");
  7679. break;
  7680. }
  7681. }
  7682. }
  7683. //
  7684. // Loop attributes
  7685. //
  7686. void HlslParseContext::handleLoopAttributes(const TSourceLoc& loc, TIntermLoop* loop,
  7687. const TAttributes& attributes)
  7688. {
  7689. if (loop == nullptr)
  7690. return;
  7691. for (auto it = attributes.begin(); it != attributes.end(); ++it) {
  7692. switch (it->name) {
  7693. case EatUnroll:
  7694. loop->setUnroll();
  7695. break;
  7696. case EatLoop:
  7697. loop->setDontUnroll();
  7698. break;
  7699. default:
  7700. warn(loc, "attribute does not apply to a loop", "", "");
  7701. break;
  7702. }
  7703. }
  7704. }
  7705. //
  7706. // Updating default qualifier for the case of a declaration with just a qualifier,
  7707. // no type, block, or identifier.
  7708. //
  7709. void HlslParseContext::updateStandaloneQualifierDefaults(const TSourceLoc& loc, const TPublicType& publicType)
  7710. {
  7711. if (publicType.shaderQualifiers.vertices != TQualifier::layoutNotSet) {
  7712. assert(language == EShLangTessControl || language == EShLangGeometry);
  7713. // const char* id = (language == EShLangTessControl) ? "vertices" : "max_vertices";
  7714. }
  7715. if (publicType.shaderQualifiers.invocations != TQualifier::layoutNotSet) {
  7716. if (! intermediate.setInvocations(publicType.shaderQualifiers.invocations))
  7717. error(loc, "cannot change previously set layout value", "invocations", "");
  7718. }
  7719. if (publicType.shaderQualifiers.geometry != ElgNone) {
  7720. if (publicType.qualifier.storage == EvqVaryingIn) {
  7721. switch (publicType.shaderQualifiers.geometry) {
  7722. case ElgPoints:
  7723. case ElgLines:
  7724. case ElgLinesAdjacency:
  7725. case ElgTriangles:
  7726. case ElgTrianglesAdjacency:
  7727. case ElgQuads:
  7728. case ElgIsolines:
  7729. break;
  7730. default:
  7731. error(loc, "cannot apply to input", TQualifier::getGeometryString(publicType.shaderQualifiers.geometry),
  7732. "");
  7733. }
  7734. } else if (publicType.qualifier.storage == EvqVaryingOut) {
  7735. handleOutputGeometry(loc, publicType.shaderQualifiers.geometry);
  7736. } else
  7737. error(loc, "cannot apply to:", TQualifier::getGeometryString(publicType.shaderQualifiers.geometry),
  7738. GetStorageQualifierString(publicType.qualifier.storage));
  7739. }
  7740. if (publicType.shaderQualifiers.spacing != EvsNone)
  7741. intermediate.setVertexSpacing(publicType.shaderQualifiers.spacing);
  7742. if (publicType.shaderQualifiers.order != EvoNone)
  7743. intermediate.setVertexOrder(publicType.shaderQualifiers.order);
  7744. if (publicType.shaderQualifiers.pointMode)
  7745. intermediate.setPointMode();
  7746. for (int i = 0; i < 3; ++i) {
  7747. if (publicType.shaderQualifiers.localSize[i] > 1) {
  7748. int max = 0;
  7749. switch (i) {
  7750. case 0: max = resources.maxComputeWorkGroupSizeX; break;
  7751. case 1: max = resources.maxComputeWorkGroupSizeY; break;
  7752. case 2: max = resources.maxComputeWorkGroupSizeZ; break;
  7753. default: break;
  7754. }
  7755. if (intermediate.getLocalSize(i) > (unsigned int)max)
  7756. error(loc, "too large; see gl_MaxComputeWorkGroupSize", "local_size", "");
  7757. // Fix the existing constant gl_WorkGroupSize with this new information.
  7758. TVariable* workGroupSize = getEditableVariable("gl_WorkGroupSize");
  7759. workGroupSize->getWritableConstArray()[i].setUConst(intermediate.getLocalSize(i));
  7760. }
  7761. if (publicType.shaderQualifiers.localSizeSpecId[i] != TQualifier::layoutNotSet) {
  7762. intermediate.setLocalSizeSpecId(i, publicType.shaderQualifiers.localSizeSpecId[i]);
  7763. // Set the workgroup built-in variable as a specialization constant
  7764. TVariable* workGroupSize = getEditableVariable("gl_WorkGroupSize");
  7765. workGroupSize->getWritableType().getQualifier().specConstant = true;
  7766. }
  7767. }
  7768. if (publicType.shaderQualifiers.earlyFragmentTests)
  7769. intermediate.setEarlyFragmentTests();
  7770. const TQualifier& qualifier = publicType.qualifier;
  7771. switch (qualifier.storage) {
  7772. case EvqUniform:
  7773. if (qualifier.hasMatrix())
  7774. globalUniformDefaults.layoutMatrix = qualifier.layoutMatrix;
  7775. if (qualifier.hasPacking())
  7776. globalUniformDefaults.layoutPacking = qualifier.layoutPacking;
  7777. break;
  7778. case EvqBuffer:
  7779. if (qualifier.hasMatrix())
  7780. globalBufferDefaults.layoutMatrix = qualifier.layoutMatrix;
  7781. if (qualifier.hasPacking())
  7782. globalBufferDefaults.layoutPacking = qualifier.layoutPacking;
  7783. break;
  7784. case EvqVaryingIn:
  7785. break;
  7786. case EvqVaryingOut:
  7787. if (qualifier.hasStream())
  7788. globalOutputDefaults.layoutStream = qualifier.layoutStream;
  7789. if (qualifier.hasXfbBuffer())
  7790. globalOutputDefaults.layoutXfbBuffer = qualifier.layoutXfbBuffer;
  7791. if (globalOutputDefaults.hasXfbBuffer() && qualifier.hasXfbStride()) {
  7792. if (! intermediate.setXfbBufferStride(globalOutputDefaults.layoutXfbBuffer, qualifier.layoutXfbStride))
  7793. error(loc, "all stride settings must match for xfb buffer", "xfb_stride", "%d",
  7794. qualifier.layoutXfbBuffer);
  7795. }
  7796. break;
  7797. default:
  7798. error(loc, "default qualifier requires 'uniform', 'buffer', 'in', or 'out' storage qualification", "", "");
  7799. return;
  7800. }
  7801. }
  7802. //
  7803. // Take the sequence of statements that has been built up since the last case/default,
  7804. // put it on the list of top-level nodes for the current (inner-most) switch statement,
  7805. // and follow that by the case/default we are on now. (See switch topology comment on
  7806. // TIntermSwitch.)
  7807. //
  7808. void HlslParseContext::wrapupSwitchSubsequence(TIntermAggregate* statements, TIntermNode* branchNode)
  7809. {
  7810. TIntermSequence* switchSequence = switchSequenceStack.back();
  7811. if (statements) {
  7812. statements->setOperator(EOpSequence);
  7813. switchSequence->push_back(statements);
  7814. }
  7815. if (branchNode) {
  7816. // check all previous cases for the same label (or both are 'default')
  7817. for (unsigned int s = 0; s < switchSequence->size(); ++s) {
  7818. TIntermBranch* prevBranch = (*switchSequence)[s]->getAsBranchNode();
  7819. if (prevBranch) {
  7820. TIntermTyped* prevExpression = prevBranch->getExpression();
  7821. TIntermTyped* newExpression = branchNode->getAsBranchNode()->getExpression();
  7822. if (prevExpression == nullptr && newExpression == nullptr)
  7823. error(branchNode->getLoc(), "duplicate label", "default", "");
  7824. else if (prevExpression != nullptr &&
  7825. newExpression != nullptr &&
  7826. prevExpression->getAsConstantUnion() &&
  7827. newExpression->getAsConstantUnion() &&
  7828. prevExpression->getAsConstantUnion()->getConstArray()[0].getIConst() ==
  7829. newExpression->getAsConstantUnion()->getConstArray()[0].getIConst())
  7830. error(branchNode->getLoc(), "duplicated value", "case", "");
  7831. }
  7832. }
  7833. switchSequence->push_back(branchNode);
  7834. }
  7835. }
  7836. //
  7837. // Turn the top-level node sequence built up of wrapupSwitchSubsequence
  7838. // into a switch node.
  7839. //
  7840. TIntermNode* HlslParseContext::addSwitch(const TSourceLoc& loc, TIntermTyped* expression,
  7841. TIntermAggregate* lastStatements, const TAttributes& attributes)
  7842. {
  7843. wrapupSwitchSubsequence(lastStatements, nullptr);
  7844. if (expression == nullptr ||
  7845. (expression->getBasicType() != EbtInt && expression->getBasicType() != EbtUint) ||
  7846. expression->getType().isArray() || expression->getType().isMatrix() || expression->getType().isVector())
  7847. error(loc, "condition must be a scalar integer expression", "switch", "");
  7848. // If there is nothing to do, drop the switch but still execute the expression
  7849. TIntermSequence* switchSequence = switchSequenceStack.back();
  7850. if (switchSequence->size() == 0)
  7851. return expression;
  7852. if (lastStatements == nullptr) {
  7853. // emulate a break for error recovery
  7854. lastStatements = intermediate.makeAggregate(intermediate.addBranch(EOpBreak, loc));
  7855. lastStatements->setOperator(EOpSequence);
  7856. switchSequence->push_back(lastStatements);
  7857. }
  7858. TIntermAggregate* body = new TIntermAggregate(EOpSequence);
  7859. body->getSequence() = *switchSequenceStack.back();
  7860. body->setLoc(loc);
  7861. TIntermSwitch* switchNode = new TIntermSwitch(expression, body);
  7862. switchNode->setLoc(loc);
  7863. handleSwitchAttributes(loc, switchNode, attributes);
  7864. return switchNode;
  7865. }
  7866. // Make a new symbol-table level that is made out of the members of a structure.
  7867. // This should be done as an anonymous struct (name is "") so that the symbol table
  7868. // finds the members with no explicit reference to a 'this' variable.
  7869. void HlslParseContext::pushThisScope(const TType& thisStruct, const TVector<TFunctionDeclarator>& functionDeclarators)
  7870. {
  7871. // member variables
  7872. TVariable& thisVariable = *new TVariable(NewPoolTString(""), thisStruct);
  7873. symbolTable.pushThis(thisVariable);
  7874. // member functions
  7875. for (auto it = functionDeclarators.begin(); it != functionDeclarators.end(); ++it) {
  7876. // member should have a prefix matching currentTypePrefix.back()
  7877. // but, symbol lookup within the class scope will just use the
  7878. // unprefixed name. Hence, there are two: one fully prefixed and
  7879. // one with no prefix.
  7880. TFunction& member = *it->function->clone();
  7881. member.removePrefix(currentTypePrefix.back());
  7882. symbolTable.insert(member);
  7883. }
  7884. }
  7885. // Track levels of class/struct/namespace nesting with a prefix string using
  7886. // the type names separated by the scoping operator. E.g., two levels
  7887. // would look like:
  7888. //
  7889. // outer::inner
  7890. //
  7891. // The string is empty when at normal global level.
  7892. //
  7893. void HlslParseContext::pushNamespace(const TString& typeName)
  7894. {
  7895. // make new type prefix
  7896. TString newPrefix;
  7897. if (currentTypePrefix.size() > 0)
  7898. newPrefix = currentTypePrefix.back();
  7899. newPrefix.append(typeName);
  7900. newPrefix.append(scopeMangler);
  7901. currentTypePrefix.push_back(newPrefix);
  7902. }
  7903. // Opposite of pushNamespace(), see above
  7904. void HlslParseContext::popNamespace()
  7905. {
  7906. currentTypePrefix.pop_back();
  7907. }
  7908. // Use the class/struct nesting string to create a global name for
  7909. // a member of a class/struct.
  7910. void HlslParseContext::getFullNamespaceName(TString*& name) const
  7911. {
  7912. if (currentTypePrefix.size() == 0)
  7913. return;
  7914. TString* fullName = NewPoolTString(currentTypePrefix.back().c_str());
  7915. fullName->append(*name);
  7916. name = fullName;
  7917. }
  7918. // Helper function to add the namespace scope mangling syntax to a string.
  7919. void HlslParseContext::addScopeMangler(TString& name)
  7920. {
  7921. name.append(scopeMangler);
  7922. }
  7923. // Return true if this has uniform-interface like decorations.
  7924. bool HlslParseContext::hasUniform(const TQualifier& qualifier) const
  7925. {
  7926. return qualifier.hasUniformLayout() ||
  7927. qualifier.layoutPushConstant;
  7928. }
  7929. // Potentially not the opposite of hasUniform(), as if some characteristic is
  7930. // ever used for more than one thing (e.g., uniform or input), hasUniform() should
  7931. // say it exists, but clearUniform() should leave it in place.
  7932. void HlslParseContext::clearUniform(TQualifier& qualifier)
  7933. {
  7934. qualifier.clearUniformLayout();
  7935. qualifier.layoutPushConstant = false;
  7936. }
  7937. // Return false if builtIn by itself doesn't force this qualifier to be an input qualifier.
  7938. bool HlslParseContext::isInputBuiltIn(const TQualifier& qualifier) const
  7939. {
  7940. switch (qualifier.builtIn) {
  7941. case EbvPosition:
  7942. case EbvPointSize:
  7943. return language != EShLangVertex && language != EShLangCompute && language != EShLangFragment;
  7944. case EbvClipDistance:
  7945. case EbvCullDistance:
  7946. return language != EShLangVertex && language != EShLangCompute;
  7947. case EbvFragCoord:
  7948. case EbvFace:
  7949. case EbvHelperInvocation:
  7950. case EbvLayer:
  7951. case EbvPointCoord:
  7952. case EbvSampleId:
  7953. case EbvSampleMask:
  7954. case EbvSamplePosition:
  7955. case EbvViewportIndex:
  7956. return language == EShLangFragment;
  7957. case EbvGlobalInvocationId:
  7958. case EbvLocalInvocationIndex:
  7959. case EbvLocalInvocationId:
  7960. case EbvNumWorkGroups:
  7961. case EbvWorkGroupId:
  7962. case EbvWorkGroupSize:
  7963. return language == EShLangCompute;
  7964. case EbvInvocationId:
  7965. return language == EShLangTessControl || language == EShLangTessEvaluation || language == EShLangGeometry;
  7966. case EbvPatchVertices:
  7967. return language == EShLangTessControl || language == EShLangTessEvaluation;
  7968. case EbvInstanceId:
  7969. case EbvInstanceIndex:
  7970. case EbvVertexId:
  7971. case EbvVertexIndex:
  7972. return language == EShLangVertex;
  7973. case EbvPrimitiveId:
  7974. return language == EShLangGeometry || language == EShLangFragment || language == EShLangTessControl;
  7975. case EbvTessLevelInner:
  7976. case EbvTessLevelOuter:
  7977. return language == EShLangTessEvaluation;
  7978. case EbvTessCoord:
  7979. return language == EShLangTessEvaluation;
  7980. default:
  7981. return false;
  7982. }
  7983. }
  7984. // Return true if there are decorations to preserve for input-like storage.
  7985. bool HlslParseContext::hasInput(const TQualifier& qualifier) const
  7986. {
  7987. if (qualifier.hasAnyLocation())
  7988. return true;
  7989. if (language == EShLangFragment && (qualifier.isInterpolation() || qualifier.centroid || qualifier.sample))
  7990. return true;
  7991. if (language == EShLangTessEvaluation && qualifier.patch)
  7992. return true;
  7993. if (isInputBuiltIn(qualifier))
  7994. return true;
  7995. return false;
  7996. }
  7997. // Return false if builtIn by itself doesn't force this qualifier to be an output qualifier.
  7998. bool HlslParseContext::isOutputBuiltIn(const TQualifier& qualifier) const
  7999. {
  8000. switch (qualifier.builtIn) {
  8001. case EbvPosition:
  8002. case EbvPointSize:
  8003. case EbvClipVertex:
  8004. case EbvClipDistance:
  8005. case EbvCullDistance:
  8006. return language != EShLangFragment && language != EShLangCompute;
  8007. case EbvFragDepth:
  8008. case EbvFragDepthGreater:
  8009. case EbvFragDepthLesser:
  8010. case EbvSampleMask:
  8011. return language == EShLangFragment;
  8012. case EbvLayer:
  8013. case EbvViewportIndex:
  8014. return language == EShLangGeometry || language == EShLangVertex;
  8015. case EbvPrimitiveId:
  8016. return language == EShLangGeometry;
  8017. case EbvTessLevelInner:
  8018. case EbvTessLevelOuter:
  8019. return language == EShLangTessControl;
  8020. default:
  8021. return false;
  8022. }
  8023. }
  8024. // Return true if there are decorations to preserve for output-like storage.
  8025. bool HlslParseContext::hasOutput(const TQualifier& qualifier) const
  8026. {
  8027. if (qualifier.hasAnyLocation())
  8028. return true;
  8029. if (language != EShLangFragment && language != EShLangCompute && qualifier.hasXfb())
  8030. return true;
  8031. if (language == EShLangTessControl && qualifier.patch)
  8032. return true;
  8033. if (language == EShLangGeometry && qualifier.hasStream())
  8034. return true;
  8035. if (isOutputBuiltIn(qualifier))
  8036. return true;
  8037. return false;
  8038. }
  8039. // Make the IO decorations etc. be appropriate only for an input interface.
  8040. void HlslParseContext::correctInput(TQualifier& qualifier)
  8041. {
  8042. clearUniform(qualifier);
  8043. if (language == EShLangVertex)
  8044. qualifier.clearInterstage();
  8045. if (language != EShLangTessEvaluation)
  8046. qualifier.patch = false;
  8047. if (language != EShLangFragment) {
  8048. qualifier.clearInterpolation();
  8049. qualifier.sample = false;
  8050. }
  8051. qualifier.clearStreamLayout();
  8052. qualifier.clearXfbLayout();
  8053. if (! isInputBuiltIn(qualifier))
  8054. qualifier.builtIn = EbvNone;
  8055. }
  8056. // Make the IO decorations etc. be appropriate only for an output interface.
  8057. void HlslParseContext::correctOutput(TQualifier& qualifier)
  8058. {
  8059. clearUniform(qualifier);
  8060. if (language == EShLangFragment)
  8061. qualifier.clearInterstage();
  8062. if (language != EShLangGeometry)
  8063. qualifier.clearStreamLayout();
  8064. if (language == EShLangFragment)
  8065. qualifier.clearXfbLayout();
  8066. if (language != EShLangTessControl)
  8067. qualifier.patch = false;
  8068. switch (qualifier.builtIn) {
  8069. case EbvFragDepth:
  8070. intermediate.setDepthReplacing();
  8071. intermediate.setDepth(EldAny);
  8072. break;
  8073. case EbvFragDepthGreater:
  8074. intermediate.setDepthReplacing();
  8075. intermediate.setDepth(EldGreater);
  8076. qualifier.builtIn = EbvFragDepth;
  8077. break;
  8078. case EbvFragDepthLesser:
  8079. intermediate.setDepthReplacing();
  8080. intermediate.setDepth(EldLess);
  8081. qualifier.builtIn = EbvFragDepth;
  8082. break;
  8083. default:
  8084. break;
  8085. }
  8086. if (! isOutputBuiltIn(qualifier))
  8087. qualifier.builtIn = EbvNone;
  8088. }
  8089. // Make the IO decorations etc. be appropriate only for uniform type interfaces.
  8090. void HlslParseContext::correctUniform(TQualifier& qualifier)
  8091. {
  8092. if (qualifier.declaredBuiltIn == EbvNone)
  8093. qualifier.declaredBuiltIn = qualifier.builtIn;
  8094. qualifier.builtIn = EbvNone;
  8095. qualifier.clearInterstage();
  8096. qualifier.clearInterstageLayout();
  8097. }
  8098. // Clear out all IO/Uniform stuff, so this has nothing to do with being an IO interface.
  8099. void HlslParseContext::clearUniformInputOutput(TQualifier& qualifier)
  8100. {
  8101. clearUniform(qualifier);
  8102. correctUniform(qualifier);
  8103. }
  8104. // Set texture return type. Returns success (not all types are valid).
  8105. bool HlslParseContext::setTextureReturnType(TSampler& sampler, const TType& retType, const TSourceLoc& loc)
  8106. {
  8107. // Seed the output with an invalid index. We will set it to a valid one if we can.
  8108. sampler.structReturnIndex = TSampler::noReturnStruct;
  8109. // Arrays aren't supported.
  8110. if (retType.isArray()) {
  8111. error(loc, "Arrays not supported in texture template types", "", "");
  8112. return false;
  8113. }
  8114. // If return type is a vector, remember the vector size in the sampler, and return.
  8115. if (retType.isVector() || retType.isScalar()) {
  8116. sampler.vectorSize = retType.getVectorSize();
  8117. return true;
  8118. }
  8119. // If it wasn't a vector, it must be a struct meeting certain requirements. The requirements
  8120. // are checked below: just check for struct-ness here.
  8121. if (!retType.isStruct()) {
  8122. error(loc, "Invalid texture template type", "", "");
  8123. return false;
  8124. }
  8125. // TODO: Subpass doesn't handle struct returns, due to some oddities with fn overloading.
  8126. if (sampler.isSubpass()) {
  8127. error(loc, "Unimplemented: structure template type in subpass input", "", "");
  8128. return false;
  8129. }
  8130. TTypeList* members = retType.getWritableStruct();
  8131. // Check for too many or not enough structure members.
  8132. if (members->size() > 4 || members->size() == 0) {
  8133. error(loc, "Invalid member count in texture template structure", "", "");
  8134. return false;
  8135. }
  8136. // Error checking: We must have <= 4 total components, all of the same basic type.
  8137. unsigned totalComponents = 0;
  8138. for (unsigned m = 0; m < members->size(); ++m) {
  8139. // Check for bad member types
  8140. if (!(*members)[m].type->isScalar() && !(*members)[m].type->isVector()) {
  8141. error(loc, "Invalid texture template struct member type", "", "");
  8142. return false;
  8143. }
  8144. const unsigned memberVectorSize = (*members)[m].type->getVectorSize();
  8145. totalComponents += memberVectorSize;
  8146. // too many total member components
  8147. if (totalComponents > 4) {
  8148. error(loc, "Too many components in texture template structure type", "", "");
  8149. return false;
  8150. }
  8151. // All members must be of a common basic type
  8152. if ((*members)[m].type->getBasicType() != (*members)[0].type->getBasicType()) {
  8153. error(loc, "Texture template structure members must same basic type", "", "");
  8154. return false;
  8155. }
  8156. }
  8157. // If the structure in the return type already exists in the table, we'll use it. Otherwise, we'll make
  8158. // a new entry. This is a linear search, but it hardly ever happens, and the list cannot be very large.
  8159. for (unsigned int idx = 0; idx < textureReturnStruct.size(); ++idx) {
  8160. if (textureReturnStruct[idx] == members) {
  8161. sampler.structReturnIndex = idx;
  8162. return true;
  8163. }
  8164. }
  8165. // It wasn't found as an existing entry. See if we have room for a new one.
  8166. if (textureReturnStruct.size() >= TSampler::structReturnSlots) {
  8167. error(loc, "Texture template struct return slots exceeded", "", "");
  8168. return false;
  8169. }
  8170. // Insert it in the vector that tracks struct return types.
  8171. sampler.structReturnIndex = unsigned(textureReturnStruct.size());
  8172. textureReturnStruct.push_back(members);
  8173. // Success!
  8174. return true;
  8175. }
  8176. // Return the sampler return type in retType.
  8177. void HlslParseContext::getTextureReturnType(const TSampler& sampler, TType& retType) const
  8178. {
  8179. if (sampler.hasReturnStruct()) {
  8180. assert(textureReturnStruct.size() >= sampler.structReturnIndex);
  8181. // We land here if the texture return is a structure.
  8182. TTypeList* blockStruct = textureReturnStruct[sampler.structReturnIndex];
  8183. const TType resultType(blockStruct, "");
  8184. retType.shallowCopy(resultType);
  8185. } else {
  8186. // We land here if the texture return is a vector or scalar.
  8187. const TType resultType(sampler.type, EvqTemporary, sampler.getVectorSize());
  8188. retType.shallowCopy(resultType);
  8189. }
  8190. }
  8191. // Return a symbol for the tessellation linkage variable of the given TBuiltInVariable type
  8192. TIntermSymbol* HlslParseContext::findTessLinkageSymbol(TBuiltInVariable biType) const
  8193. {
  8194. const auto it = builtInTessLinkageSymbols.find(biType);
  8195. if (it == builtInTessLinkageSymbols.end()) // if it wasn't declared by the user, return nullptr
  8196. return nullptr;
  8197. return intermediate.addSymbol(*it->second->getAsVariable());
  8198. }
  8199. // Find the patch constant function (issues error, returns nullptr if not found)
  8200. const TFunction* HlslParseContext::findPatchConstantFunction(const TSourceLoc& loc)
  8201. {
  8202. if (symbolTable.isFunctionNameVariable(patchConstantFunctionName)) {
  8203. error(loc, "can't use variable in patch constant function", patchConstantFunctionName.c_str(), "");
  8204. return nullptr;
  8205. }
  8206. const TString mangledName = patchConstantFunctionName + "(";
  8207. // create list of PCF candidates
  8208. TVector<const TFunction*> candidateList;
  8209. bool builtIn;
  8210. symbolTable.findFunctionNameList(mangledName, candidateList, builtIn);
  8211. // We have to have one and only one, or we don't know which to pick: the patchconstantfunc does not
  8212. // allow any disambiguation of overloads.
  8213. if (candidateList.empty()) {
  8214. error(loc, "patch constant function not found", patchConstantFunctionName.c_str(), "");
  8215. return nullptr;
  8216. }
  8217. // Based on directed experiments, it appears that if there are overloaded patchconstantfunctions,
  8218. // HLSL picks the last one in shader source order. Since that isn't yet implemented here, error
  8219. // out if there is more than one candidate.
  8220. if (candidateList.size() > 1) {
  8221. error(loc, "ambiguous patch constant function", patchConstantFunctionName.c_str(), "");
  8222. return nullptr;
  8223. }
  8224. return candidateList[0];
  8225. }
  8226. // Finalization step: Add patch constant function invocation
  8227. void HlslParseContext::addPatchConstantInvocation()
  8228. {
  8229. TSourceLoc loc;
  8230. loc.init();
  8231. // If there's no patch constant function, or we're not a HS, do nothing.
  8232. if (patchConstantFunctionName.empty() || language != EShLangTessControl)
  8233. return;
  8234. // Look for built-in variables in a function's parameter list.
  8235. const auto findBuiltIns = [&](const TFunction& function, std::set<tInterstageIoData>& builtIns) {
  8236. for (int p=0; p<function.getParamCount(); ++p) {
  8237. TStorageQualifier storage = function[p].type->getQualifier().storage;
  8238. if (storage == EvqConstReadOnly) // treated identically to input
  8239. storage = EvqIn;
  8240. if (function[p].getDeclaredBuiltIn() != EbvNone)
  8241. builtIns.insert(HlslParseContext::tInterstageIoData(function[p].getDeclaredBuiltIn(), storage));
  8242. else
  8243. builtIns.insert(HlslParseContext::tInterstageIoData(function[p].type->getQualifier().builtIn, storage));
  8244. }
  8245. };
  8246. // If we synthesize a built-in interface variable, we must add it to the linkage.
  8247. const auto addToLinkage = [&](const TType& type, const TString* name, TIntermSymbol** symbolNode) {
  8248. if (name == nullptr) {
  8249. error(loc, "unable to locate patch function parameter name", "", "");
  8250. return;
  8251. } else {
  8252. TVariable& variable = *new TVariable(name, type);
  8253. if (! symbolTable.insert(variable)) {
  8254. error(loc, "unable to declare patch constant function interface variable", name->c_str(), "");
  8255. return;
  8256. }
  8257. globalQualifierFix(loc, variable.getWritableType().getQualifier());
  8258. if (symbolNode != nullptr)
  8259. *symbolNode = intermediate.addSymbol(variable);
  8260. trackLinkage(variable);
  8261. }
  8262. };
  8263. const auto isOutputPatch = [](TFunction& patchConstantFunction, int param) {
  8264. const TType& type = *patchConstantFunction[param].type;
  8265. const TBuiltInVariable biType = patchConstantFunction[param].getDeclaredBuiltIn();
  8266. return type.isSizedArray() && biType == EbvOutputPatch;
  8267. };
  8268. // We will perform these steps. Each is in a scoped block for separation: they could
  8269. // become separate functions to make addPatchConstantInvocation shorter.
  8270. //
  8271. // 1. Union the interfaces, and create built-ins for anything present in the PCF and
  8272. // declared as a built-in variable that isn't present in the entry point's signature.
  8273. //
  8274. // 2. Synthesizes a call to the patchconstfunction using built-in variables from either main,
  8275. // or the ones we created. Matching is based on built-in type. We may use synthesized
  8276. // variables from (1) above.
  8277. //
  8278. // 2B: Synthesize per control point invocations of wrapped entry point if the PCF requires them.
  8279. //
  8280. // 3. Create a return sequence: copy the return value (if any) from the PCF to a
  8281. // (non-sanitized) output variable. In case this may involve multiple copies, such as for
  8282. // an arrayed variable, a temporary copy of the PCF output is created to avoid multiple
  8283. // indirections into a complex R-value coming from the call to the PCF.
  8284. //
  8285. // 4. Create a barrier.
  8286. //
  8287. // 5/5B. Call the PCF inside an if test for (invocation id == 0).
  8288. TFunction* patchConstantFunctionPtr = const_cast<TFunction*>(findPatchConstantFunction(loc));
  8289. if (patchConstantFunctionPtr == nullptr)
  8290. return;
  8291. TFunction& patchConstantFunction = *patchConstantFunctionPtr;
  8292. const int pcfParamCount = patchConstantFunction.getParamCount();
  8293. TIntermSymbol* invocationIdSym = findTessLinkageSymbol(EbvInvocationId);
  8294. TIntermSequence& epBodySeq = entryPointFunctionBody->getAsAggregate()->getSequence();
  8295. int outPatchParam = -1; // -1 means there isn't one.
  8296. // ================ Step 1A: Union Interfaces ================
  8297. // Our patch constant function.
  8298. {
  8299. std::set<tInterstageIoData> pcfBuiltIns; // patch constant function built-ins
  8300. std::set<tInterstageIoData> epfBuiltIns; // entry point function built-ins
  8301. assert(entryPointFunction);
  8302. assert(entryPointFunctionBody);
  8303. findBuiltIns(patchConstantFunction, pcfBuiltIns);
  8304. findBuiltIns(*entryPointFunction, epfBuiltIns);
  8305. // Find the set of built-ins in the PCF that are not present in the entry point.
  8306. std::set<tInterstageIoData> notInEntryPoint;
  8307. notInEntryPoint = pcfBuiltIns;
  8308. // std::set_difference not usable on unordered containers
  8309. for (auto bi = epfBuiltIns.begin(); bi != epfBuiltIns.end(); ++bi)
  8310. notInEntryPoint.erase(*bi);
  8311. // Now we'll add those to the entry and to the linkage.
  8312. for (int p=0; p<pcfParamCount; ++p) {
  8313. const TBuiltInVariable biType = patchConstantFunction[p].getDeclaredBuiltIn();
  8314. TStorageQualifier storage = patchConstantFunction[p].type->getQualifier().storage;
  8315. // Track whether there is an output patch param
  8316. if (isOutputPatch(patchConstantFunction, p)) {
  8317. if (outPatchParam >= 0) {
  8318. // Presently we only support one per ctrl pt input.
  8319. error(loc, "unimplemented: multiple output patches in patch constant function", "", "");
  8320. return;
  8321. }
  8322. outPatchParam = p;
  8323. }
  8324. if (biType != EbvNone) {
  8325. TType* paramType = patchConstantFunction[p].type->clone();
  8326. if (storage == EvqConstReadOnly) // treated identically to input
  8327. storage = EvqIn;
  8328. // Presently, the only non-built-in we support is InputPatch, which is treated as
  8329. // a pseudo-built-in.
  8330. if (biType == EbvInputPatch) {
  8331. builtInTessLinkageSymbols[biType] = inputPatch;
  8332. } else if (biType == EbvOutputPatch) {
  8333. // Nothing...
  8334. } else {
  8335. // Use the original declaration type for the linkage
  8336. paramType->getQualifier().builtIn = biType;
  8337. if (notInEntryPoint.count(tInterstageIoData(biType, storage)) == 1)
  8338. addToLinkage(*paramType, patchConstantFunction[p].name, nullptr);
  8339. }
  8340. }
  8341. }
  8342. // If we didn't find it because the shader made one, add our own.
  8343. if (invocationIdSym == nullptr) {
  8344. TType invocationIdType(EbtUint, EvqIn, 1);
  8345. TString* invocationIdName = NewPoolTString("InvocationId");
  8346. invocationIdType.getQualifier().builtIn = EbvInvocationId;
  8347. addToLinkage(invocationIdType, invocationIdName, &invocationIdSym);
  8348. }
  8349. assert(invocationIdSym);
  8350. }
  8351. TIntermTyped* pcfArguments = nullptr;
  8352. TVariable* perCtrlPtVar = nullptr;
  8353. // ================ Step 1B: Argument synthesis ================
  8354. // Create pcfArguments for synthesis of patchconstantfunction invocation
  8355. {
  8356. for (int p=0; p<pcfParamCount; ++p) {
  8357. TIntermTyped* inputArg = nullptr;
  8358. if (p == outPatchParam) {
  8359. if (perCtrlPtVar == nullptr) {
  8360. perCtrlPtVar = makeInternalVariable(*patchConstantFunction[outPatchParam].name,
  8361. *patchConstantFunction[outPatchParam].type);
  8362. perCtrlPtVar->getWritableType().getQualifier().makeTemporary();
  8363. }
  8364. inputArg = intermediate.addSymbol(*perCtrlPtVar, loc);
  8365. } else {
  8366. // find which built-in it is
  8367. const TBuiltInVariable biType = patchConstantFunction[p].getDeclaredBuiltIn();
  8368. if (biType == EbvInputPatch && inputPatch == nullptr) {
  8369. error(loc, "unimplemented: PCF input patch without entry point input patch parameter", "", "");
  8370. return;
  8371. }
  8372. inputArg = findTessLinkageSymbol(biType);
  8373. if (inputArg == nullptr) {
  8374. error(loc, "unable to find patch constant function built-in variable", "", "");
  8375. return;
  8376. }
  8377. }
  8378. if (pcfParamCount == 1)
  8379. pcfArguments = inputArg;
  8380. else
  8381. pcfArguments = intermediate.growAggregate(pcfArguments, inputArg);
  8382. }
  8383. }
  8384. // ================ Step 2: Synthesize call to PCF ================
  8385. TIntermAggregate* pcfCallSequence = nullptr;
  8386. TIntermTyped* pcfCall = nullptr;
  8387. {
  8388. // Create a function call to the patchconstantfunction
  8389. if (pcfArguments)
  8390. addInputArgumentConversions(patchConstantFunction, pcfArguments);
  8391. // Synthetic call.
  8392. pcfCall = intermediate.setAggregateOperator(pcfArguments, EOpFunctionCall, patchConstantFunction.getType(), loc);
  8393. pcfCall->getAsAggregate()->setUserDefined();
  8394. pcfCall->getAsAggregate()->setName(patchConstantFunction.getMangledName());
  8395. intermediate.addToCallGraph(infoSink, intermediate.getEntryPointMangledName().c_str(),
  8396. patchConstantFunction.getMangledName());
  8397. if (pcfCall->getAsAggregate()) {
  8398. TQualifierList& qualifierList = pcfCall->getAsAggregate()->getQualifierList();
  8399. for (int i = 0; i < patchConstantFunction.getParamCount(); ++i) {
  8400. TStorageQualifier qual = patchConstantFunction[i].type->getQualifier().storage;
  8401. qualifierList.push_back(qual);
  8402. }
  8403. pcfCall = addOutputArgumentConversions(patchConstantFunction, *pcfCall->getAsOperator());
  8404. }
  8405. }
  8406. // ================ Step 2B: Per Control Point synthesis ================
  8407. // If there is per control point data, we must either emulate that with multiple
  8408. // invocations of the entry point to build up an array, or (TODO:) use a yet
  8409. // unavailable extension to look across the SIMD lanes. This is the former
  8410. // as a placeholder for the latter.
  8411. if (outPatchParam >= 0) {
  8412. // We must introduce a local temp variable of the type wanted by the PCF input.
  8413. const int arraySize = patchConstantFunction[outPatchParam].type->getOuterArraySize();
  8414. if (entryPointFunction->getType().getBasicType() == EbtVoid) {
  8415. error(loc, "entry point must return a value for use with patch constant function", "", "");
  8416. return;
  8417. }
  8418. // Create calls to wrapped main to fill in the array. We will substitute fixed values
  8419. // of invocation ID when calling the wrapped main.
  8420. // This is the type of the each member of the per ctrl point array.
  8421. const TType derefType(perCtrlPtVar->getType(), 0);
  8422. for (int cpt = 0; cpt < arraySize; ++cpt) {
  8423. // TODO: improve. substr(1) here is to avoid the '@' that was grafted on but isn't in the symtab
  8424. // for this function.
  8425. const TString origName = entryPointFunction->getName().substr(1);
  8426. TFunction callee(&origName, TType(EbtVoid));
  8427. TIntermTyped* callingArgs = nullptr;
  8428. for (int i = 0; i < entryPointFunction->getParamCount(); i++) {
  8429. TParameter& param = (*entryPointFunction)[i];
  8430. TType& paramType = *param.type;
  8431. if (paramType.getQualifier().isParamOutput()) {
  8432. error(loc, "unimplemented: entry point outputs in patch constant function invocation", "", "");
  8433. return;
  8434. }
  8435. if (paramType.getQualifier().isParamInput()) {
  8436. TIntermTyped* arg = nullptr;
  8437. if ((*entryPointFunction)[i].getDeclaredBuiltIn() == EbvInvocationId) {
  8438. // substitute invocation ID with the array element ID
  8439. arg = intermediate.addConstantUnion(cpt, loc);
  8440. } else {
  8441. TVariable* argVar = makeInternalVariable(*param.name, *param.type);
  8442. argVar->getWritableType().getQualifier().makeTemporary();
  8443. arg = intermediate.addSymbol(*argVar);
  8444. }
  8445. handleFunctionArgument(&callee, callingArgs, arg);
  8446. }
  8447. }
  8448. // Call and assign to per ctrl point variable
  8449. currentCaller = intermediate.getEntryPointMangledName().c_str();
  8450. TIntermTyped* callReturn = handleFunctionCall(loc, &callee, callingArgs);
  8451. TIntermTyped* index = intermediate.addConstantUnion(cpt, loc);
  8452. TIntermSymbol* perCtrlPtSym = intermediate.addSymbol(*perCtrlPtVar, loc);
  8453. TIntermTyped* element = intermediate.addIndex(EOpIndexDirect, perCtrlPtSym, index, loc);
  8454. element->setType(derefType);
  8455. element->setLoc(loc);
  8456. pcfCallSequence = intermediate.growAggregate(pcfCallSequence,
  8457. handleAssign(loc, EOpAssign, element, callReturn));
  8458. }
  8459. }
  8460. // ================ Step 3: Create return Sequence ================
  8461. // Return sequence: copy PCF result to a temporary, then to shader output variable.
  8462. if (pcfCall->getBasicType() != EbtVoid) {
  8463. const TType* retType = &patchConstantFunction.getType(); // return type from the PCF
  8464. TType outType; // output type that goes with the return type.
  8465. outType.shallowCopy(*retType);
  8466. // substitute the output type
  8467. const auto newLists = ioTypeMap.find(retType->getStruct());
  8468. if (newLists != ioTypeMap.end())
  8469. outType.setStruct(newLists->second.output);
  8470. // Substitute the top level type's built-in type
  8471. if (patchConstantFunction.getDeclaredBuiltInType() != EbvNone)
  8472. outType.getQualifier().builtIn = patchConstantFunction.getDeclaredBuiltInType();
  8473. outType.getQualifier().patch = true; // make it a per-patch variable
  8474. TVariable* pcfOutput = makeInternalVariable("@patchConstantOutput", outType);
  8475. pcfOutput->getWritableType().getQualifier().storage = EvqVaryingOut;
  8476. if (pcfOutput->getType().containsBuiltIn())
  8477. split(*pcfOutput);
  8478. assignToInterface(*pcfOutput);
  8479. TIntermSymbol* pcfOutputSym = intermediate.addSymbol(*pcfOutput, loc);
  8480. // The call to the PCF is a complex R-value: we want to store it in a temp to avoid
  8481. // repeated calls to the PCF:
  8482. TVariable* pcfCallResult = makeInternalVariable("@patchConstantResult", *retType);
  8483. pcfCallResult->getWritableType().getQualifier().makeTemporary();
  8484. TIntermSymbol* pcfResultVar = intermediate.addSymbol(*pcfCallResult, loc);
  8485. TIntermNode* pcfResultAssign = handleAssign(loc, EOpAssign, pcfResultVar, pcfCall);
  8486. TIntermNode* pcfResultToOut = handleAssign(loc, EOpAssign, pcfOutputSym,
  8487. intermediate.addSymbol(*pcfCallResult, loc));
  8488. pcfCallSequence = intermediate.growAggregate(pcfCallSequence, pcfResultAssign);
  8489. pcfCallSequence = intermediate.growAggregate(pcfCallSequence, pcfResultToOut);
  8490. } else {
  8491. pcfCallSequence = intermediate.growAggregate(pcfCallSequence, pcfCall);
  8492. }
  8493. // ================ Step 4: Barrier ================
  8494. TIntermTyped* barrier = new TIntermAggregate(EOpBarrier);
  8495. barrier->setLoc(loc);
  8496. barrier->setType(TType(EbtVoid));
  8497. epBodySeq.insert(epBodySeq.end(), barrier);
  8498. // ================ Step 5: Test on invocation ID ================
  8499. TIntermTyped* zero = intermediate.addConstantUnion(0, loc, true);
  8500. TIntermTyped* cmp = intermediate.addBinaryNode(EOpEqual, invocationIdSym, zero, loc, TType(EbtBool));
  8501. // ================ Step 5B: Create if statement on Invocation ID == 0 ================
  8502. intermediate.setAggregateOperator(pcfCallSequence, EOpSequence, TType(EbtVoid), loc);
  8503. TIntermTyped* invocationIdTest = new TIntermSelection(cmp, pcfCallSequence, nullptr);
  8504. invocationIdTest->setLoc(loc);
  8505. // add our test sequence before the return.
  8506. epBodySeq.insert(epBodySeq.end(), invocationIdTest);
  8507. }
  8508. // Finalization step: remove unused buffer blocks from linkage (we don't know until the
  8509. // shader is entirely compiled).
  8510. // Preserve order of remaining symbols.
  8511. void HlslParseContext::removeUnusedStructBufferCounters()
  8512. {
  8513. const auto endIt = std::remove_if(linkageSymbols.begin(), linkageSymbols.end(),
  8514. [this](const TSymbol* sym) {
  8515. const auto sbcIt = structBufferCounter.find(sym->getName());
  8516. return sbcIt != structBufferCounter.end() && !sbcIt->second;
  8517. });
  8518. linkageSymbols.erase(endIt, linkageSymbols.end());
  8519. }
  8520. // Finalization step: patch texture shadow modes to match samplers they were combined with
  8521. void HlslParseContext::fixTextureShadowModes()
  8522. {
  8523. for (auto symbol = linkageSymbols.begin(); symbol != linkageSymbols.end(); ++symbol) {
  8524. TSampler& sampler = (*symbol)->getWritableType().getSampler();
  8525. if (sampler.isTexture()) {
  8526. const auto shadowMode = textureShadowVariant.find((*symbol)->getUniqueId());
  8527. if (shadowMode != textureShadowVariant.end()) {
  8528. if (shadowMode->second->overloaded())
  8529. // Texture needs legalization if it's been seen with both shadow and non-shadow modes.
  8530. intermediate.setNeedsLegalization();
  8531. sampler.shadow = shadowMode->second->isShadowId((*symbol)->getUniqueId());
  8532. }
  8533. }
  8534. }
  8535. }
  8536. // Finalization step: patch append methods to use proper stream output, which isn't known until
  8537. // main is parsed, which could happen after the append method is parsed.
  8538. void HlslParseContext::finalizeAppendMethods()
  8539. {
  8540. TSourceLoc loc;
  8541. loc.init();
  8542. // Nothing to do: bypass test for valid stream output.
  8543. if (gsAppends.empty())
  8544. return;
  8545. if (gsStreamOutput == nullptr) {
  8546. error(loc, "unable to find output symbol for Append()", "", "");
  8547. return;
  8548. }
  8549. // Patch append sequences, now that we know the stream output symbol.
  8550. for (auto append = gsAppends.begin(); append != gsAppends.end(); ++append) {
  8551. append->node->getSequence()[0] =
  8552. handleAssign(append->loc, EOpAssign,
  8553. intermediate.addSymbol(*gsStreamOutput, append->loc),
  8554. append->node->getSequence()[0]->getAsTyped());
  8555. }
  8556. }
  8557. // post-processing
  8558. void HlslParseContext::finish()
  8559. {
  8560. // Error check: There was a dangling .mips operator. These are not nested constructs in the grammar, so
  8561. // cannot be detected there. This is not strictly needed in a non-validating parser; it's just helpful.
  8562. if (! mipsOperatorMipArg.empty()) {
  8563. error(mipsOperatorMipArg.back().loc, "unterminated mips operator:", "", "");
  8564. }
  8565. removeUnusedStructBufferCounters();
  8566. addPatchConstantInvocation();
  8567. fixTextureShadowModes();
  8568. finalizeAppendMethods();
  8569. // Communicate out (esp. for command line) that we formed AST that will make
  8570. // illegal AST SPIR-V and it needs transforms to legalize it.
  8571. if (intermediate.needsLegalization() && (messages & EShMsgHlslLegalization))
  8572. infoSink.info << "WARNING: AST will form illegal SPIR-V; need to transform to legalize";
  8573. TParseContextBase::finish();
  8574. }
  8575. } // end namespace glslang