SPIRVEmitter.cpp 388 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679
  1. //===------- SPIRVEmitter.h - SPIR-V Binary Code Emitter --------*- C++ -*-===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements a SPIR-V emitter class that takes in HLSL AST and emits
  10. // SPIR-V binary words.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "SPIRVEmitter.h"
  14. #include "dxc/HlslIntrinsicOp.h"
  15. #include "spirv-tools/optimizer.hpp"
  16. #include "llvm/ADT/StringExtras.h"
  17. #include "InitListHandler.h"
  18. namespace clang {
  19. namespace spirv {
  20. namespace {
  21. /// Returns the type of the given decl. If the given decl is a FunctionDecl,
  22. /// returns its result type.
  23. inline QualType getTypeOrFnRetType(const ValueDecl *decl) {
  24. if (const auto *funcDecl = dyn_cast<FunctionDecl>(decl)) {
  25. return funcDecl->getReturnType();
  26. }
  27. return decl->getType();
  28. }
  29. // Returns true if the given decl has the given semantic.
  30. bool hasSemantic(const DeclaratorDecl *decl,
  31. hlsl::DXIL::SemanticKind semanticKind) {
  32. using namespace hlsl;
  33. for (auto *annotation : decl->getUnusualAnnotations()) {
  34. if (auto *semanticDecl = dyn_cast<SemanticDecl>(annotation)) {
  35. llvm::StringRef semanticName;
  36. uint32_t semanticIndex = 0;
  37. Semantic::DecomposeNameAndIndex(semanticDecl->SemanticName, &semanticName,
  38. &semanticIndex);
  39. const auto *semantic = Semantic::GetByName(semanticName);
  40. if (semantic->GetKind() == semanticKind)
  41. return true;
  42. }
  43. }
  44. return false;
  45. }
  46. bool patchConstFuncTakesHullOutputPatch(FunctionDecl *pcf) {
  47. for (const auto *param : pcf->parameters())
  48. if (hlsl::IsHLSLOutputPatchType(param->getType()))
  49. return true;
  50. return false;
  51. }
  52. // TODO: Maybe we should move these type probing functions to TypeTranslator.
  53. /// Returns true if the given type is a bool or vector of bool type.
  54. bool isBoolOrVecOfBoolType(QualType type) {
  55. QualType elemType = {};
  56. return (TypeTranslator::isScalarType(type, &elemType) ||
  57. TypeTranslator::isVectorType(type, &elemType)) &&
  58. elemType->isBooleanType();
  59. }
  60. /// Returns true if the given type is a signed integer or vector of signed
  61. /// integer type.
  62. bool isSintOrVecOfSintType(QualType type) {
  63. QualType elemType = {};
  64. return (TypeTranslator::isScalarType(type, &elemType) ||
  65. TypeTranslator::isVectorType(type, &elemType)) &&
  66. elemType->isSignedIntegerType();
  67. }
  68. /// Returns true if the given type is an unsigned integer or vector of unsigned
  69. /// integer type.
  70. bool isUintOrVecOfUintType(QualType type) {
  71. QualType elemType = {};
  72. return (TypeTranslator::isScalarType(type, &elemType) ||
  73. TypeTranslator::isVectorType(type, &elemType)) &&
  74. elemType->isUnsignedIntegerType();
  75. }
  76. /// Returns true if the given type is a float or vector of float type.
  77. bool isFloatOrVecOfFloatType(QualType type) {
  78. QualType elemType = {};
  79. return (TypeTranslator::isScalarType(type, &elemType) ||
  80. TypeTranslator::isVectorType(type, &elemType)) &&
  81. elemType->isFloatingType();
  82. }
  83. /// Returns true if the given type is a bool or vector/matrix of bool type.
  84. bool isBoolOrVecMatOfBoolType(QualType type) {
  85. return isBoolOrVecOfBoolType(type) ||
  86. (hlsl::IsHLSLMatType(type) &&
  87. hlsl::GetHLSLMatElementType(type)->isBooleanType());
  88. }
  89. /// Returns true if the given type is a signed integer or vector/matrix of
  90. /// signed integer type.
  91. bool isSintOrVecMatOfSintType(QualType type) {
  92. return isSintOrVecOfSintType(type) ||
  93. (hlsl::IsHLSLMatType(type) &&
  94. hlsl::GetHLSLMatElementType(type)->isSignedIntegerType());
  95. }
  96. /// Returns true if the given type is an unsigned integer or vector/matrix of
  97. /// unsigned integer type.
  98. bool isUintOrVecMatOfUintType(QualType type) {
  99. return isUintOrVecOfUintType(type) ||
  100. (hlsl::IsHLSLMatType(type) &&
  101. hlsl::GetHLSLMatElementType(type)->isUnsignedIntegerType());
  102. }
  103. /// Returns true if the given type is a float or vector/matrix of float type.
  104. bool isFloatOrVecMatOfFloatType(QualType type) {
  105. return isFloatOrVecOfFloatType(type) ||
  106. (hlsl::IsHLSLMatType(type) &&
  107. hlsl::GetHLSLMatElementType(type)->isFloatingType());
  108. }
  109. inline bool isSpirvMatrixOp(spv::Op opcode) {
  110. return opcode == spv::Op::OpMatrixTimesMatrix ||
  111. opcode == spv::Op::OpMatrixTimesVector ||
  112. opcode == spv::Op::OpMatrixTimesScalar;
  113. }
  114. /// If expr is a (RW)StructuredBuffer.Load(), returns the object and writes
  115. /// index. Otherwiser, returns false.
  116. // TODO: The following doesn't handle Load(int, int) yet. And it is basically a
  117. // duplicate of doCXXMemberCallExpr.
  118. const Expr *isStructuredBufferLoad(const Expr *expr, const Expr **index) {
  119. using namespace hlsl;
  120. if (const auto *indexing = dyn_cast<CXXMemberCallExpr>(expr)) {
  121. const auto *callee = indexing->getDirectCallee();
  122. uint32_t opcode = static_cast<uint32_t>(IntrinsicOp::Num_Intrinsics);
  123. llvm::StringRef group;
  124. if (GetIntrinsicOp(callee, opcode, group)) {
  125. if (static_cast<IntrinsicOp>(opcode) == IntrinsicOp::MOP_Load) {
  126. const auto *object = indexing->getImplicitObjectArgument();
  127. if (TypeTranslator::isStructuredBuffer(object->getType())) {
  128. *index = indexing->getArg(0);
  129. return indexing->getImplicitObjectArgument();
  130. }
  131. }
  132. }
  133. }
  134. return nullptr;
  135. }
  136. /// Returns true if the given VarDecl will be translated into a SPIR-V variable
  137. /// not in the Private or Function storage class.
  138. inline bool isExternalVar(const VarDecl *var) {
  139. // Class static variables should be put in the Private storage class.
  140. // groupshared variables are allowed to be declared as "static". But we still
  141. // need to put them in the Workgroup storage class. That is, when seeing
  142. // "static groupshared", ignore "static".
  143. return var->hasExternalFormalLinkage() ? !var->isStaticDataMember()
  144. : var->getAttr<HLSLGroupSharedAttr>();
  145. }
  146. /// Returns the referenced variable's DeclContext if the given expr is
  147. /// a DeclRefExpr referencing a ConstantBuffer/TextureBuffer. Otherwise,
  148. /// returns nullptr.
  149. const DeclContext *isConstantTextureBufferDeclRef(const Expr *expr) {
  150. if (const auto *declRefExpr = dyn_cast<DeclRefExpr>(expr->IgnoreParenCasts()))
  151. if (const auto *varDecl = dyn_cast<VarDecl>(declRefExpr->getFoundDecl()))
  152. if (TypeTranslator::isConstantTextureBuffer(varDecl))
  153. return varDecl->getType()->getAs<RecordType>()->getDecl();
  154. return nullptr;
  155. }
  156. /// Returns true if
  157. /// * the given expr is an DeclRefExpr referencing a kind of structured or byte
  158. /// buffer and it is non-alias one, or
  159. /// * the given expr is an CallExpr returning a kind of structured or byte
  160. /// buffer.
  161. ///
  162. /// Note: legalization specific code
  163. bool isReferencingNonAliasStructuredOrByteBuffer(const Expr *expr) {
  164. expr = expr->IgnoreParenCasts();
  165. if (const auto *declRefExpr = dyn_cast<DeclRefExpr>(expr)) {
  166. if (const auto *varDecl = dyn_cast<VarDecl>(declRefExpr->getFoundDecl()))
  167. if (TypeTranslator::isAKindOfStructuredOrByteBuffer(varDecl->getType()))
  168. return isExternalVar(varDecl);
  169. } else if (const auto *callExpr = dyn_cast<CallExpr>(expr)) {
  170. if (TypeTranslator::isAKindOfStructuredOrByteBuffer(callExpr->getType()))
  171. return true;
  172. }
  173. return false;
  174. }
  175. bool spirvToolsLegalize(spv_target_env env, std::vector<uint32_t> *module,
  176. std::string *messages) {
  177. spvtools::Optimizer optimizer(env);
  178. optimizer.SetMessageConsumer(
  179. [messages](spv_message_level_t /*level*/, const char * /*source*/,
  180. const spv_position_t & /*position*/,
  181. const char *message) { *messages += message; });
  182. optimizer.RegisterLegalizationPasses();
  183. optimizer.RegisterPass(spvtools::CreateReplaceInvalidOpcodePass());
  184. optimizer.RegisterPass(spvtools::CreateCompactIdsPass());
  185. return optimizer.Run(module->data(), module->size(), module);
  186. }
  187. bool spirvToolsOptimize(spv_target_env env, std::vector<uint32_t> *module,
  188. std::string *messages) {
  189. spvtools::Optimizer optimizer(env);
  190. optimizer.SetMessageConsumer(
  191. [messages](spv_message_level_t /*level*/, const char * /*source*/,
  192. const spv_position_t & /*position*/,
  193. const char *message) { *messages += message; });
  194. optimizer.RegisterPerformancePasses();
  195. optimizer.RegisterPass(spvtools::CreateCompactIdsPass());
  196. return optimizer.Run(module->data(), module->size(), module);
  197. }
  198. bool spirvToolsValidate(spv_target_env env, std::vector<uint32_t> *module,
  199. std::string *messages, bool relaxLogicalPointer) {
  200. spvtools::SpirvTools tools(env);
  201. tools.SetMessageConsumer(
  202. [messages](spv_message_level_t /*level*/, const char * /*source*/,
  203. const spv_position_t & /*position*/,
  204. const char *message) { *messages += message; });
  205. spvtools::ValidatorOptions options;
  206. options.SetRelaxLogicalPointer(relaxLogicalPointer);
  207. return tools.Validate(module->data(), module->size(), options);
  208. }
  209. /// Translates atomic HLSL opcodes into the equivalent SPIR-V opcode.
  210. spv::Op translateAtomicHlslOpcodeToSpirvOpcode(hlsl::IntrinsicOp opcode) {
  211. using namespace hlsl;
  212. using namespace spv;
  213. switch (opcode) {
  214. case IntrinsicOp::IOP_InterlockedAdd:
  215. case IntrinsicOp::MOP_InterlockedAdd:
  216. return Op::OpAtomicIAdd;
  217. case IntrinsicOp::IOP_InterlockedAnd:
  218. case IntrinsicOp::MOP_InterlockedAnd:
  219. return Op::OpAtomicAnd;
  220. case IntrinsicOp::IOP_InterlockedOr:
  221. case IntrinsicOp::MOP_InterlockedOr:
  222. return Op::OpAtomicOr;
  223. case IntrinsicOp::IOP_InterlockedXor:
  224. case IntrinsicOp::MOP_InterlockedXor:
  225. return Op::OpAtomicXor;
  226. case IntrinsicOp::IOP_InterlockedUMax:
  227. case IntrinsicOp::MOP_InterlockedUMax:
  228. return Op::OpAtomicUMax;
  229. case IntrinsicOp::IOP_InterlockedUMin:
  230. case IntrinsicOp::MOP_InterlockedUMin:
  231. return Op::OpAtomicUMin;
  232. case IntrinsicOp::IOP_InterlockedMax:
  233. case IntrinsicOp::MOP_InterlockedMax:
  234. return Op::OpAtomicSMax;
  235. case IntrinsicOp::IOP_InterlockedMin:
  236. case IntrinsicOp::MOP_InterlockedMin:
  237. return Op::OpAtomicSMin;
  238. case IntrinsicOp::IOP_InterlockedExchange:
  239. case IntrinsicOp::MOP_InterlockedExchange:
  240. return Op::OpAtomicExchange;
  241. }
  242. assert(false && "unimplemented hlsl intrinsic opcode");
  243. return Op::Max;
  244. }
  245. // Returns true if the given opcode is an accepted binary opcode in
  246. // OpSpecConstantOp.
  247. bool isAcceptedSpecConstantBinaryOp(spv::Op op) {
  248. switch (op) {
  249. case spv::Op::OpIAdd:
  250. case spv::Op::OpISub:
  251. case spv::Op::OpIMul:
  252. case spv::Op::OpUDiv:
  253. case spv::Op::OpSDiv:
  254. case spv::Op::OpUMod:
  255. case spv::Op::OpSRem:
  256. case spv::Op::OpSMod:
  257. case spv::Op::OpShiftRightLogical:
  258. case spv::Op::OpShiftRightArithmetic:
  259. case spv::Op::OpShiftLeftLogical:
  260. case spv::Op::OpBitwiseOr:
  261. case spv::Op::OpBitwiseXor:
  262. case spv::Op::OpBitwiseAnd:
  263. case spv::Op::OpVectorShuffle:
  264. case spv::Op::OpCompositeExtract:
  265. case spv::Op::OpCompositeInsert:
  266. case spv::Op::OpLogicalOr:
  267. case spv::Op::OpLogicalAnd:
  268. case spv::Op::OpLogicalNot:
  269. case spv::Op::OpLogicalEqual:
  270. case spv::Op::OpLogicalNotEqual:
  271. case spv::Op::OpIEqual:
  272. case spv::Op::OpINotEqual:
  273. case spv::Op::OpULessThan:
  274. case spv::Op::OpSLessThan:
  275. case spv::Op::OpUGreaterThan:
  276. case spv::Op::OpSGreaterThan:
  277. case spv::Op::OpULessThanEqual:
  278. case spv::Op::OpSLessThanEqual:
  279. case spv::Op::OpUGreaterThanEqual:
  280. case spv::Op::OpSGreaterThanEqual:
  281. return true;
  282. }
  283. return false;
  284. }
  285. /// Returns true if the given expression is an accepted initializer for a spec
  286. /// constant.
  287. bool isAcceptedSpecConstantInit(const Expr *init) {
  288. // Allow numeric casts
  289. init = init->IgnoreParenCasts();
  290. if (isa<CXXBoolLiteralExpr>(init) || isa<IntegerLiteral>(init) ||
  291. isa<FloatingLiteral>(init))
  292. return true;
  293. // Allow the minus operator which is used to specify negative values
  294. if (const auto *unaryOp = dyn_cast<UnaryOperator>(init))
  295. return unaryOp->getOpcode() == UO_Minus &&
  296. isAcceptedSpecConstantInit(unaryOp->getSubExpr());
  297. return false;
  298. }
  299. /// Returns true if the given function parameter can act as shader stage
  300. /// input parameter.
  301. inline bool canActAsInParmVar(const ParmVarDecl *param) {
  302. // If the parameter has no in/out/inout attribute, it is defaulted to
  303. // an in parameter.
  304. return !param->hasAttr<HLSLOutAttr>() &&
  305. // GS output streams are marked as inout, but it should not be
  306. // used as in parameter.
  307. !hlsl::IsHLSLStreamOutputType(param->getType());
  308. }
  309. /// Returns true if the given function parameter can act as shader stage
  310. /// output parameter.
  311. inline bool canActAsOutParmVar(const ParmVarDecl *param) {
  312. return param->hasAttr<HLSLOutAttr>() || param->hasAttr<HLSLInOutAttr>();
  313. }
  314. /// Returns true if the given expression is of builtin type and can be evaluated
  315. /// to a constant zero. Returns false otherwise.
  316. inline bool evaluatesToConstZero(const Expr *expr, ASTContext &astContext) {
  317. const auto type = expr->getType();
  318. if (!type->isBuiltinType())
  319. return false;
  320. Expr::EvalResult evalResult;
  321. if (expr->EvaluateAsRValue(evalResult, astContext) &&
  322. !evalResult.HasSideEffects) {
  323. const auto &val = evalResult.Val;
  324. return ((type->isBooleanType() && !val.getInt().getBoolValue()) ||
  325. (type->isIntegerType() && !val.getInt().getBoolValue()) ||
  326. (type->isFloatingType() && val.getFloat().isZero()));
  327. }
  328. return false;
  329. }
  330. /// Returns the HLSLBufferDecl if the given VarDecl is inside a cbuffer/tbuffer.
  331. /// Returns nullptr otherwise, including varDecl is a ConstantBuffer or
  332. /// TextureBuffer itself.
  333. inline const HLSLBufferDecl *getCTBufferContext(const VarDecl *varDecl) {
  334. if (const auto *bufferDecl =
  335. dyn_cast<HLSLBufferDecl>(varDecl->getDeclContext()))
  336. // Filter ConstantBuffer/TextureBuffer
  337. if (!bufferDecl->isConstantBufferView())
  338. return bufferDecl;
  339. return nullptr;
  340. }
  341. /// Returns the real definition of the callee of the given CallExpr.
  342. ///
  343. /// If we are calling a forward-declared function, callee will be the
  344. /// FunctionDecl for the foward-declared function, not the actual
  345. /// definition. The foward-delcaration and defintion are two completely
  346. /// different AST nodes.
  347. inline const FunctionDecl *getCalleeDefinition(const CallExpr *expr) {
  348. const auto *callee = expr->getDirectCallee();
  349. if (callee->isThisDeclarationADefinition())
  350. return callee;
  351. // We need to update callee to the actual definition here
  352. if (!callee->isDefined(callee))
  353. return nullptr;
  354. return callee;
  355. }
  356. /// Returns the referenced definition. The given expr is expected to be a
  357. /// DeclRefExpr or CallExpr after ignoring casts. Returns nullptr otherwise.
  358. const DeclaratorDecl *getReferencedDef(const Expr *expr) {
  359. if (!expr)
  360. return nullptr;
  361. expr = expr->IgnoreParenCasts();
  362. if (const auto *declRefExpr = dyn_cast<DeclRefExpr>(expr)) {
  363. return dyn_cast_or_null<DeclaratorDecl>(declRefExpr->getDecl());
  364. }
  365. if (const auto *callExpr = dyn_cast<CallExpr>(expr)) {
  366. return getCalleeDefinition(callExpr);
  367. }
  368. return nullptr;
  369. }
  370. /// Returns the number of base classes if this type is a derived class/struct.
  371. /// Returns zero otherwise.
  372. inline uint32_t getNumBaseClasses(QualType type) {
  373. if (const auto *cxxDecl = type->getAsCXXRecordDecl())
  374. return cxxDecl->getNumBases();
  375. return 0;
  376. }
  377. /// Gets the index sequence of casting a derived object to a base object by
  378. /// following the cast chain.
  379. void getBaseClassIndices(const CastExpr *expr,
  380. llvm::SmallVectorImpl<uint32_t> *indices) {
  381. assert(expr->getCastKind() == CK_UncheckedDerivedToBase ||
  382. expr->getCastKind() == CK_HLSLDerivedToBase);
  383. indices->clear();
  384. QualType derivedType = expr->getSubExpr()->getType();
  385. const auto *derivedDecl = derivedType->getAsCXXRecordDecl();
  386. // Go through the base cast chain: for each of the derived to base cast, find
  387. // the index of the base in question in the derived's bases.
  388. for (auto pathIt = expr->path_begin(), pathIe = expr->path_end();
  389. pathIt != pathIe; ++pathIt) {
  390. // The type of the base in question
  391. const auto baseType = (*pathIt)->getType();
  392. uint32_t index = 0;
  393. for (auto baseIt = derivedDecl->bases_begin(),
  394. baseIe = derivedDecl->bases_end();
  395. baseIt != baseIe; ++baseIt, ++index)
  396. if (baseIt->getType() == baseType) {
  397. indices->push_back(index);
  398. break;
  399. }
  400. assert(index < derivedDecl->getNumBases());
  401. // Continue to proceed the next base in the chain
  402. derivedType = baseType;
  403. derivedDecl = derivedType->getAsCXXRecordDecl();
  404. }
  405. }
  406. spv::Capability getCapabilityForGroupNonUniform(spv::Op opcode) {
  407. switch (opcode) {
  408. case spv::Op::OpGroupNonUniformElect:
  409. return spv::Capability::GroupNonUniform;
  410. case spv::Op::OpGroupNonUniformAny:
  411. case spv::Op::OpGroupNonUniformAll:
  412. case spv::Op::OpGroupNonUniformAllEqual:
  413. return spv::Capability::GroupNonUniformVote;
  414. case spv::Op::OpGroupNonUniformBallot:
  415. case spv::Op::OpGroupNonUniformBallotBitCount:
  416. case spv::Op::OpGroupNonUniformBroadcast:
  417. case spv::Op::OpGroupNonUniformBroadcastFirst:
  418. return spv::Capability::GroupNonUniformBallot;
  419. case spv::Op::OpGroupNonUniformIAdd:
  420. case spv::Op::OpGroupNonUniformFAdd:
  421. case spv::Op::OpGroupNonUniformIMul:
  422. case spv::Op::OpGroupNonUniformFMul:
  423. case spv::Op::OpGroupNonUniformSMax:
  424. case spv::Op::OpGroupNonUniformUMax:
  425. case spv::Op::OpGroupNonUniformFMax:
  426. case spv::Op::OpGroupNonUniformSMin:
  427. case spv::Op::OpGroupNonUniformUMin:
  428. case spv::Op::OpGroupNonUniformFMin:
  429. case spv::Op::OpGroupNonUniformBitwiseAnd:
  430. case spv::Op::OpGroupNonUniformBitwiseOr:
  431. case spv::Op::OpGroupNonUniformBitwiseXor:
  432. return spv::Capability::GroupNonUniformArithmetic;
  433. case spv::Op::OpGroupNonUniformQuadBroadcast:
  434. case spv::Op::OpGroupNonUniformQuadSwap:
  435. return spv::Capability::GroupNonUniformQuad;
  436. }
  437. assert(false && "unhandled opcode");
  438. return spv::Capability::Max;
  439. }
  440. std::string getNamespacePrefix(const Decl *decl) {
  441. std::string nsPrefix = "";
  442. const DeclContext *dc = decl->getDeclContext();
  443. while (dc && !dc->isTranslationUnit()) {
  444. if (const NamespaceDecl *ns = dyn_cast<NamespaceDecl>(dc)) {
  445. if (!ns->isAnonymousNamespace()) {
  446. nsPrefix = ns->getName().str() + "::" + nsPrefix;
  447. }
  448. }
  449. dc = dc->getParent();
  450. }
  451. return nsPrefix;
  452. }
  453. std::string getFnName(const FunctionDecl *fn) {
  454. // Prefix the function name with the struct name if necessary
  455. std::string classOrStructName = "";
  456. if (const auto *memberFn = dyn_cast<CXXMethodDecl>(fn))
  457. if (const auto *st = dyn_cast<CXXRecordDecl>(memberFn->getDeclContext()))
  458. classOrStructName = st->getName().str() + ".";
  459. return getNamespacePrefix(fn) + classOrStructName + fn->getName().str();
  460. }
  461. } // namespace
  462. SPIRVEmitter::SPIRVEmitter(CompilerInstance &ci, EmitSPIRVOptions &options)
  463. : theCompilerInstance(ci), astContext(ci.getASTContext()),
  464. diags(ci.getDiagnostics()), spirvOptions(options),
  465. entryFunctionName(ci.getCodeGenOpts().HLSLEntryFunction),
  466. shaderModel(*hlsl::ShaderModel::GetByName(
  467. ci.getCodeGenOpts().HLSLProfile.c_str())),
  468. theContext(), featureManager(diags, options),
  469. theBuilder(&theContext, &featureManager, options.enableReflect),
  470. typeTranslator(astContext, theBuilder, diags, options),
  471. declIdMapper(shaderModel, astContext, theBuilder, typeTranslator,
  472. featureManager, options),
  473. entryFunctionId(0), curFunction(nullptr), curThis(0),
  474. seenPushConstantAt(), isSpecConstantMode(false),
  475. needsLegalization(false) {
  476. if (shaderModel.GetKind() == hlsl::ShaderModel::Kind::Invalid)
  477. emitError("unknown shader module: %0", {}) << shaderModel.GetName();
  478. if (options.invertY && !shaderModel.IsVS() && !shaderModel.IsDS() &&
  479. !shaderModel.IsGS())
  480. emitError("-fvk-invert-y can only be used in VS/DS/GS", {});
  481. if (options.useGlLayout && options.useDxLayout)
  482. emitError("cannot specify both -fvk-use-dx-layout and -fvk-use-gl-layout",
  483. {});
  484. options.Initialize();
  485. // Set shader module version
  486. theBuilder.setShaderModelVersion(shaderModel.GetMajor(),
  487. shaderModel.GetMinor());
  488. // Set debug info
  489. const auto &inputFiles = ci.getFrontendOpts().Inputs;
  490. if (options.enableDebugInfo && !inputFiles.empty())
  491. theBuilder.setSourceFileName(theContext.takeNextId(),
  492. inputFiles.front().getFile().str());
  493. }
  494. void SPIRVEmitter::HandleTranslationUnit(ASTContext &context) {
  495. // Stop translating if there are errors in previous compilation stages.
  496. if (context.getDiagnostics().hasErrorOccurred())
  497. return;
  498. TranslationUnitDecl *tu = context.getTranslationUnitDecl();
  499. // The entry function is the seed of the queue.
  500. for (auto *decl : tu->decls()) {
  501. if (auto *funcDecl = dyn_cast<FunctionDecl>(decl)) {
  502. if (funcDecl->getName() == entryFunctionName) {
  503. workQueue.insert(funcDecl);
  504. }
  505. } else {
  506. // If ignoring unused resources, defer Decl handling inside
  507. // TranslationUnit to the time of first referencing.
  508. if (!spirvOptions.ignoreUnusedResources) {
  509. doDecl(decl);
  510. }
  511. }
  512. }
  513. // Translate all functions reachable from the entry function.
  514. // The queue can grow in the meanwhile; so need to keep evaluating
  515. // workQueue.size().
  516. for (uint32_t i = 0; i < workQueue.size(); ++i) {
  517. doDecl(workQueue[i]);
  518. }
  519. if (context.getDiagnostics().hasErrorOccurred())
  520. return;
  521. const spv_target_env targetEnv = featureManager.getTargetEnv();
  522. AddRequiredCapabilitiesForShaderModel();
  523. // Addressing and memory model are required in a valid SPIR-V module.
  524. theBuilder.setAddressingModel(spv::AddressingModel::Logical);
  525. theBuilder.setMemoryModel(spv::MemoryModel::GLSL450);
  526. theBuilder.addEntryPoint(getSpirvShaderStage(shaderModel), entryFunctionId,
  527. entryFunctionName, declIdMapper.collectStageVars());
  528. // Add Location decorations to stage input/output variables.
  529. if (!declIdMapper.decorateStageIOLocations())
  530. return;
  531. // Add descriptor set and binding decorations to resource variables.
  532. if (!declIdMapper.decorateResourceBindings())
  533. return;
  534. // Output the constructed module.
  535. std::vector<uint32_t> m = theBuilder.takeModule();
  536. if (!spirvOptions.codeGenHighLevel) {
  537. // Run legalization passes
  538. if (needsLegalization || declIdMapper.requiresLegalization()) {
  539. std::string messages;
  540. if (!spirvToolsLegalize(targetEnv, &m, &messages)) {
  541. emitFatalError("failed to legalize SPIR-V: %0", {}) << messages;
  542. emitNote("please file a bug report on "
  543. "https://github.com/Microsoft/DirectXShaderCompiler/issues "
  544. "with source code if possible",
  545. {});
  546. return;
  547. } else if (!messages.empty()) {
  548. emitWarning("SPIR-V legalization: %0", {}) << messages;
  549. }
  550. }
  551. // Run optimization passes
  552. if (theCompilerInstance.getCodeGenOpts().OptimizationLevel > 0) {
  553. std::string messages;
  554. if (!spirvToolsOptimize(targetEnv, &m, &messages)) {
  555. emitFatalError("failed to optimize SPIR-V: %0", {}) << messages;
  556. emitNote("please file a bug report on "
  557. "https://github.com/Microsoft/DirectXShaderCompiler/issues "
  558. "with source code if possible",
  559. {});
  560. return;
  561. }
  562. }
  563. }
  564. // Validate the generated SPIR-V code
  565. if (!spirvOptions.disableValidation) {
  566. std::string messages;
  567. if (!spirvToolsValidate(targetEnv, &m, &messages,
  568. declIdMapper.requiresLegalization())) {
  569. emitFatalError("generated SPIR-V is invalid: %0", {}) << messages;
  570. emitNote("please file a bug report on "
  571. "https://github.com/Microsoft/DirectXShaderCompiler/issues "
  572. "with source code if possible",
  573. {});
  574. return;
  575. }
  576. }
  577. theCompilerInstance.getOutStream()->write(
  578. reinterpret_cast<const char *>(m.data()), m.size() * 4);
  579. }
  580. void SPIRVEmitter::doDecl(const Decl *decl) {
  581. if (decl->isImplicit() || isa<EmptyDecl>(decl) || isa<TypedefDecl>(decl))
  582. return;
  583. if (const auto *varDecl = dyn_cast<VarDecl>(decl)) {
  584. // We can have VarDecls inside cbuffer/tbuffer. For those VarDecls, we need
  585. // to emit their cbuffer/tbuffer as a whole and access each individual one
  586. // using access chains.
  587. if (const auto *bufferDecl = getCTBufferContext(varDecl)) {
  588. doHLSLBufferDecl(bufferDecl);
  589. } else {
  590. doVarDecl(varDecl);
  591. }
  592. } else if (const auto *namespaceDecl = dyn_cast<NamespaceDecl>(decl)) {
  593. for (auto *subDecl : namespaceDecl->decls())
  594. // Note: We only emit functions as they are discovered through the call
  595. // graph starting from the entry-point. We should not emit unused
  596. // functions inside namespaces.
  597. if (!isa<FunctionDecl>(subDecl))
  598. doDecl(subDecl);
  599. } else if (const auto *funcDecl = dyn_cast<FunctionDecl>(decl)) {
  600. doFunctionDecl(funcDecl);
  601. } else if (const auto *bufferDecl = dyn_cast<HLSLBufferDecl>(decl)) {
  602. doHLSLBufferDecl(bufferDecl);
  603. } else if (const auto *recordDecl = dyn_cast<RecordDecl>(decl)) {
  604. doRecordDecl(recordDecl);
  605. } else {
  606. emitError("decl type %0 unimplemented", decl->getLocation())
  607. << decl->getDeclKindName();
  608. }
  609. }
  610. void SPIRVEmitter::doStmt(const Stmt *stmt,
  611. llvm::ArrayRef<const Attr *> attrs) {
  612. if (const auto *compoundStmt = dyn_cast<CompoundStmt>(stmt)) {
  613. for (auto *st : compoundStmt->body())
  614. doStmt(st);
  615. } else if (const auto *retStmt = dyn_cast<ReturnStmt>(stmt)) {
  616. doReturnStmt(retStmt);
  617. } else if (const auto *declStmt = dyn_cast<DeclStmt>(stmt)) {
  618. doDeclStmt(declStmt);
  619. } else if (const auto *ifStmt = dyn_cast<IfStmt>(stmt)) {
  620. doIfStmt(ifStmt, attrs);
  621. } else if (const auto *switchStmt = dyn_cast<SwitchStmt>(stmt)) {
  622. doSwitchStmt(switchStmt, attrs);
  623. } else if (const auto *caseStmt = dyn_cast<CaseStmt>(stmt)) {
  624. processCaseStmtOrDefaultStmt(stmt);
  625. } else if (const auto *defaultStmt = dyn_cast<DefaultStmt>(stmt)) {
  626. processCaseStmtOrDefaultStmt(stmt);
  627. } else if (const auto *breakStmt = dyn_cast<BreakStmt>(stmt)) {
  628. doBreakStmt(breakStmt);
  629. } else if (const auto *theDoStmt = dyn_cast<DoStmt>(stmt)) {
  630. doDoStmt(theDoStmt, attrs);
  631. } else if (const auto *discardStmt = dyn_cast<DiscardStmt>(stmt)) {
  632. doDiscardStmt(discardStmt);
  633. } else if (const auto *continueStmt = dyn_cast<ContinueStmt>(stmt)) {
  634. doContinueStmt(continueStmt);
  635. } else if (const auto *whileStmt = dyn_cast<WhileStmt>(stmt)) {
  636. doWhileStmt(whileStmt, attrs);
  637. } else if (const auto *forStmt = dyn_cast<ForStmt>(stmt)) {
  638. doForStmt(forStmt, attrs);
  639. } else if (const auto *nullStmt = dyn_cast<NullStmt>(stmt)) {
  640. // For the null statement ";". We don't need to do anything.
  641. } else if (const auto *expr = dyn_cast<Expr>(stmt)) {
  642. // All cases for expressions used as statements
  643. doExpr(expr);
  644. } else if (const auto *attrStmt = dyn_cast<AttributedStmt>(stmt)) {
  645. doStmt(attrStmt->getSubStmt(), attrStmt->getAttrs());
  646. } else {
  647. emitError("statement class '%0' unimplemented", stmt->getLocStart())
  648. << stmt->getStmtClassName() << stmt->getSourceRange();
  649. }
  650. }
  651. SpirvEvalInfo SPIRVEmitter::doDeclRefExpr(const DeclRefExpr *expr) {
  652. const auto *decl = expr->getDecl();
  653. auto id = declIdMapper.getDeclEvalInfo(decl, false);
  654. if (spirvOptions.ignoreUnusedResources && !id) {
  655. // First time referencing a Decl inside TranslationUnit. Register
  656. // into DeclResultIdMapper and emit SPIR-V for it and then query
  657. // again.
  658. doDecl(decl);
  659. id = declIdMapper.getDeclEvalInfo(decl);
  660. }
  661. return id;
  662. }
  663. SpirvEvalInfo SPIRVEmitter::doExpr(const Expr *expr) {
  664. SpirvEvalInfo result(/*id*/ 0);
  665. // Provide a hint to the typeTranslator that if a literal is discovered, its
  666. // intended usage is as this expression type.
  667. TypeTranslator::LiteralTypeHint hint(typeTranslator, expr->getType());
  668. expr = expr->IgnoreParens();
  669. if (const auto *declRefExpr = dyn_cast<DeclRefExpr>(expr)) {
  670. result = doDeclRefExpr(declRefExpr);
  671. } else if (const auto *memberExpr = dyn_cast<MemberExpr>(expr)) {
  672. result = doMemberExpr(memberExpr);
  673. } else if (const auto *castExpr = dyn_cast<CastExpr>(expr)) {
  674. result = doCastExpr(castExpr);
  675. } else if (const auto *initListExpr = dyn_cast<InitListExpr>(expr)) {
  676. result = doInitListExpr(initListExpr);
  677. } else if (const auto *boolLiteral = dyn_cast<CXXBoolLiteralExpr>(expr)) {
  678. const auto value =
  679. theBuilder.getConstantBool(boolLiteral->getValue(), isSpecConstantMode);
  680. result = SpirvEvalInfo(value).setConstant().setRValue();
  681. } else if (const auto *intLiteral = dyn_cast<IntegerLiteral>(expr)) {
  682. const auto value = translateAPInt(intLiteral->getValue(), expr->getType());
  683. result = SpirvEvalInfo(value).setConstant().setRValue();
  684. } else if (const auto *floatLiteral = dyn_cast<FloatingLiteral>(expr)) {
  685. const auto value =
  686. translateAPFloat(floatLiteral->getValue(), expr->getType());
  687. result = SpirvEvalInfo(value).setConstant().setRValue();
  688. } else if (const auto *compoundAssignOp =
  689. dyn_cast<CompoundAssignOperator>(expr)) {
  690. // CompoundAssignOperator is a subclass of BinaryOperator. It should be
  691. // checked before BinaryOperator.
  692. result = doCompoundAssignOperator(compoundAssignOp);
  693. } else if (const auto *binOp = dyn_cast<BinaryOperator>(expr)) {
  694. result = doBinaryOperator(binOp);
  695. } else if (const auto *unaryOp = dyn_cast<UnaryOperator>(expr)) {
  696. result = doUnaryOperator(unaryOp);
  697. } else if (const auto *vecElemExpr = dyn_cast<HLSLVectorElementExpr>(expr)) {
  698. result = doHLSLVectorElementExpr(vecElemExpr);
  699. } else if (const auto *matElemExpr = dyn_cast<ExtMatrixElementExpr>(expr)) {
  700. result = doExtMatrixElementExpr(matElemExpr);
  701. } else if (const auto *funcCall = dyn_cast<CallExpr>(expr)) {
  702. result = doCallExpr(funcCall);
  703. } else if (const auto *subscriptExpr = dyn_cast<ArraySubscriptExpr>(expr)) {
  704. result = doArraySubscriptExpr(subscriptExpr);
  705. } else if (const auto *condExpr = dyn_cast<ConditionalOperator>(expr)) {
  706. result = doConditionalOperator(condExpr);
  707. } else if (const auto *defaultArgExpr = dyn_cast<CXXDefaultArgExpr>(expr)) {
  708. result = doExpr(defaultArgExpr->getParam()->getDefaultArg());
  709. } else if (isa<CXXThisExpr>(expr)) {
  710. assert(curThis);
  711. result = curThis;
  712. } else {
  713. emitError("expression class '%0' unimplemented", expr->getExprLoc())
  714. << expr->getStmtClassName() << expr->getSourceRange();
  715. }
  716. return result;
  717. }
  718. SpirvEvalInfo SPIRVEmitter::loadIfGLValue(const Expr *expr) {
  719. // We are trying to load the value here, which is what an LValueToRValue
  720. // implicit cast is intended to do. We can ignore the cast if exists.
  721. expr = expr->IgnoreParenLValueCasts();
  722. return loadIfGLValue(expr, doExpr(expr));
  723. }
  724. SpirvEvalInfo SPIRVEmitter::loadIfGLValue(const Expr *expr,
  725. SpirvEvalInfo info) {
  726. // Do nothing if this is already rvalue
  727. if (info.isRValue())
  728. return info;
  729. // Check whether we are trying to load an array of opaque objects as a whole.
  730. // If true, we are likely to copy it as a whole. To assist per-element
  731. // copying, avoid the load here and return the pointer directly.
  732. // TODO: consider moving this hack into SPIRV-Tools as a transformation.
  733. if (TypeTranslator::isOpaqueArrayType(expr->getType()))
  734. return info;
  735. // Check whether we are trying to load an externally visible structured/byte
  736. // buffer as a whole. If true, it means we are creating alias for it. Avoid
  737. // the load and write the pointer directly to the alias variable then.
  738. //
  739. // Also for the case of alias function returns. If we are trying to load an
  740. // alias function return as a whole, it means we are assigning it to another
  741. // alias variable. Avoid the load and write the pointer directly.
  742. //
  743. // Note: legalization specific code
  744. if (isReferencingNonAliasStructuredOrByteBuffer(expr)) {
  745. return info.setRValue();
  746. }
  747. if (loadIfAliasVarRef(expr, info)) {
  748. // We are loading an alias variable as a whole here. This is likely for
  749. // wholesale assignments or function returns. Need to load the pointer.
  750. //
  751. // Note: legalization specific code
  752. return info;
  753. }
  754. uint32_t valType = 0;
  755. // TODO: Ouch. Very hacky. We need special path to get the value type if
  756. // we are loading a whole ConstantBuffer/TextureBuffer since the normal
  757. // type translation path won't work.
  758. if (const auto *declContext = isConstantTextureBufferDeclRef(expr)) {
  759. valType = declIdMapper.getCTBufferPushConstantTypeId(declContext);
  760. } else {
  761. valType =
  762. typeTranslator.translateType(expr->getType(), info.getLayoutRule());
  763. }
  764. uint32_t loadedId = theBuilder.createLoad(valType, info);
  765. // Special-case: According to the SPIR-V Spec: There is no physical size or
  766. // bit pattern defined for boolean type. Therefore an unsigned integer is used
  767. // to represent booleans when layout is required. In such cases, after loading
  768. // the uint, we should perform a comparison.
  769. {
  770. uint32_t vecSize = 1, numRows = 0, numCols = 0;
  771. if (info.getLayoutRule() != LayoutRule::Void &&
  772. isBoolOrVecMatOfBoolType(expr->getType())) {
  773. const auto exprType = expr->getType();
  774. QualType uintType = astContext.UnsignedIntTy;
  775. QualType boolType = astContext.BoolTy;
  776. if (TypeTranslator::isScalarType(exprType) ||
  777. TypeTranslator::isVectorType(exprType, nullptr, &vecSize)) {
  778. const auto fromType =
  779. vecSize == 1 ? uintType
  780. : astContext.getExtVectorType(uintType, vecSize);
  781. const auto toType =
  782. vecSize == 1 ? boolType
  783. : astContext.getExtVectorType(boolType, vecSize);
  784. loadedId = castToBool(loadedId, fromType, toType);
  785. } else {
  786. const bool isMat =
  787. TypeTranslator::isMxNMatrix(exprType, nullptr, &numRows, &numCols);
  788. assert(isMat);
  789. const auto uintRowQualType =
  790. astContext.getExtVectorType(uintType, numCols);
  791. const auto uintRowQualTypeId =
  792. typeTranslator.translateType(uintRowQualType);
  793. const auto boolRowQualType =
  794. astContext.getExtVectorType(boolType, numCols);
  795. const auto boolRowQualTypeId =
  796. typeTranslator.translateType(boolRowQualType);
  797. const uint32_t resultTypeId =
  798. theBuilder.getMatType(boolType, boolRowQualTypeId, numRows);
  799. llvm::SmallVector<uint32_t, 4> rows;
  800. for (uint32_t i = 0; i < numRows; ++i) {
  801. const auto row = theBuilder.createCompositeExtract(uintRowQualTypeId,
  802. loadedId, {i});
  803. rows.push_back(castToBool(row, uintRowQualType, boolRowQualType));
  804. }
  805. loadedId = theBuilder.createCompositeConstruct(resultTypeId, rows);
  806. }
  807. // Now that it is converted to Bool, it has no layout rule.
  808. // This result-id should be evaluated as bool from here on out.
  809. info.setLayoutRule(LayoutRule::Void);
  810. }
  811. }
  812. return info.setResultId(loadedId).setRValue();
  813. }
  814. SpirvEvalInfo SPIRVEmitter::loadIfAliasVarRef(const Expr *expr) {
  815. auto info = doExpr(expr);
  816. loadIfAliasVarRef(expr, info);
  817. return info;
  818. }
  819. bool SPIRVEmitter::loadIfAliasVarRef(const Expr *varExpr, SpirvEvalInfo &info) {
  820. if (info.containsAliasComponent() &&
  821. TypeTranslator::isAKindOfStructuredOrByteBuffer(varExpr->getType())) {
  822. // Aliased-to variables are all in the Uniform storage class with GLSL
  823. // std430 layout rules.
  824. const auto ptrType = typeTranslator.translateType(varExpr->getType());
  825. // Load the pointer of the aliased-to-variable if the expression has a
  826. // pointer to pointer type. That is, the expression itself is a lvalue.
  827. // (Note that we translate alias function return values as pointer types,
  828. // not pointer to pointer types.)
  829. if (varExpr->isGLValue())
  830. info.setResultId(theBuilder.createLoad(ptrType, info));
  831. info.setStorageClass(spv::StorageClass::Uniform)
  832. .setLayoutRule(spirvOptions.sBufferLayoutRule)
  833. // Now it is a pointer to the global resource, which is lvalue.
  834. .setRValue(false)
  835. // Set to false to indicate that we've performed dereference over the
  836. // pointer-to-pointer and now should fallback to the normal path
  837. .setContainsAliasComponent(false);
  838. return true;
  839. }
  840. return false;
  841. }
  842. uint32_t SPIRVEmitter::castToType(uint32_t value, QualType fromType,
  843. QualType toType, SourceLocation srcLoc) {
  844. if (isFloatOrVecOfFloatType(toType))
  845. return castToFloat(value, fromType, toType, srcLoc);
  846. // Order matters here. Bool (vector) values will also be considered as uint
  847. // (vector) values. So given a bool (vector) argument, isUintOrVecOfUintType()
  848. // will also return true. We need to check bool before uint. The opposite is
  849. // not true.
  850. if (isBoolOrVecOfBoolType(toType))
  851. return castToBool(value, fromType, toType);
  852. if (isSintOrVecOfSintType(toType) || isUintOrVecOfUintType(toType))
  853. return castToInt(value, fromType, toType, srcLoc);
  854. emitError("casting to type %0 unimplemented", {}) << toType;
  855. return 0;
  856. }
  857. void SPIRVEmitter::doFunctionDecl(const FunctionDecl *decl) {
  858. assert(decl->isThisDeclarationADefinition());
  859. // A RAII class for maintaining the current function under traversal.
  860. class FnEnvRAII {
  861. public:
  862. // Creates a new instance which sets fnEnv to the newFn on creation,
  863. // and resets fnEnv to its original value on destruction.
  864. FnEnvRAII(const FunctionDecl **fnEnv, const FunctionDecl *newFn)
  865. : oldFn(*fnEnv), fnSlot(fnEnv) {
  866. *fnEnv = newFn;
  867. }
  868. ~FnEnvRAII() { *fnSlot = oldFn; }
  869. private:
  870. const FunctionDecl *oldFn;
  871. const FunctionDecl **fnSlot;
  872. };
  873. FnEnvRAII fnEnvRAII(&curFunction, decl);
  874. // We are about to start translation for a new function. Clear the break stack
  875. // and the continue stack.
  876. breakStack = std::stack<uint32_t>();
  877. continueStack = std::stack<uint32_t>();
  878. // This will allow the entry-point name to be something like
  879. // myNamespace::myEntrypointFunc.
  880. std::string funcName = getFnName(decl);
  881. uint32_t funcId = 0;
  882. if (funcName == entryFunctionName) {
  883. // The entry function surely does not have pre-assigned <result-id> for
  884. // it like other functions that got added to the work queue following
  885. // function calls.
  886. funcId = theContext.takeNextId();
  887. funcName = "src." + funcName;
  888. // Create wrapper for the entry function
  889. if (!emitEntryFunctionWrapper(decl, funcId))
  890. return;
  891. } else {
  892. // Non-entry functions are added to the work queue following function
  893. // calls. We have already assigned <result-id>s for it when translating
  894. // its call site. Query it here.
  895. funcId = declIdMapper.getDeclEvalInfo(decl);
  896. }
  897. const uint32_t retType =
  898. declIdMapper.getTypeAndCreateCounterForPotentialAliasVar(decl);
  899. // Construct the function signature.
  900. llvm::SmallVector<uint32_t, 4> paramTypes;
  901. bool isNonStaticMemberFn = false;
  902. if (const auto *memberFn = dyn_cast<CXXMethodDecl>(decl)) {
  903. isNonStaticMemberFn = !memberFn->isStatic();
  904. if (isNonStaticMemberFn) {
  905. // For non-static member function, the first parameter should be the
  906. // object on which we are invoking this method.
  907. const uint32_t valueType = typeTranslator.translateType(
  908. memberFn->getThisType(astContext)->getPointeeType());
  909. const uint32_t ptrType =
  910. theBuilder.getPointerType(valueType, spv::StorageClass::Function);
  911. paramTypes.push_back(ptrType);
  912. }
  913. }
  914. for (const auto *param : decl->params()) {
  915. const uint32_t valueType =
  916. declIdMapper.getTypeAndCreateCounterForPotentialAliasVar(param);
  917. const uint32_t ptrType =
  918. theBuilder.getPointerType(valueType, spv::StorageClass::Function);
  919. paramTypes.push_back(ptrType);
  920. }
  921. const uint32_t funcType = theBuilder.getFunctionType(retType, paramTypes);
  922. theBuilder.beginFunction(funcType, retType, funcName, funcId);
  923. if (isNonStaticMemberFn) {
  924. // Remember the parameter for the this object so later we can handle
  925. // CXXThisExpr correctly.
  926. curThis = theBuilder.addFnParam(paramTypes[0], "param.this");
  927. }
  928. // Create all parameters.
  929. for (uint32_t i = 0; i < decl->getNumParams(); ++i) {
  930. const ParmVarDecl *paramDecl = decl->getParamDecl(i);
  931. (void)declIdMapper.createFnParam(paramDecl);
  932. }
  933. if (decl->hasBody()) {
  934. // The entry basic block.
  935. const uint32_t entryLabel = theBuilder.createBasicBlock("bb.entry");
  936. theBuilder.setInsertPoint(entryLabel);
  937. // Process all statments in the body.
  938. doStmt(decl->getBody());
  939. // We have processed all Stmts in this function and now in the last
  940. // basic block. Make sure we have a termination instruction.
  941. if (!theBuilder.isCurrentBasicBlockTerminated()) {
  942. const auto retType = decl->getReturnType();
  943. if (retType->isVoidType()) {
  944. theBuilder.createReturn();
  945. } else {
  946. // If the source code does not provide a proper return value for some
  947. // control flow path, it's undefined behavior. We just return null
  948. // value here.
  949. theBuilder.createReturnValue(
  950. theBuilder.getConstantNull(typeTranslator.translateType(retType)));
  951. }
  952. }
  953. }
  954. theBuilder.endFunction();
  955. }
  956. bool SPIRVEmitter::validateVKAttributes(const NamedDecl *decl) {
  957. bool success = true;
  958. if (const auto *varDecl = dyn_cast<VarDecl>(decl)) {
  959. const auto varType = varDecl->getType();
  960. if ((TypeTranslator::isSubpassInput(varType) ||
  961. TypeTranslator::isSubpassInputMS(varType)) &&
  962. !varDecl->hasAttr<VKInputAttachmentIndexAttr>()) {
  963. emitError("missing vk::input_attachment_index attribute",
  964. varDecl->getLocation());
  965. success = false;
  966. }
  967. }
  968. if (const auto *iaiAttr = decl->getAttr<VKInputAttachmentIndexAttr>()) {
  969. if (!shaderModel.IsPS()) {
  970. emitError("SubpassInput(MS) only allowed in pixel shader",
  971. decl->getLocation());
  972. success = false;
  973. }
  974. if (!decl->isExternallyVisible()) {
  975. emitError("SubpassInput(MS) must be externally visible",
  976. decl->getLocation());
  977. success = false;
  978. }
  979. // We only allow VKInputAttachmentIndexAttr to be attached to global
  980. // variables. So it should be fine to cast here.
  981. const auto elementType =
  982. hlsl::GetHLSLResourceResultType(cast<VarDecl>(decl)->getType());
  983. if (!TypeTranslator::isScalarType(elementType) &&
  984. !TypeTranslator::isVectorType(elementType)) {
  985. emitError(
  986. "only scalar/vector types allowed as SubpassInput(MS) parameter type",
  987. decl->getLocation());
  988. // Return directly to avoid further type processing, which will hit
  989. // asserts in TypeTranslator.
  990. return false;
  991. }
  992. }
  993. // The frontend will make sure that
  994. // * vk::push_constant applies to global variables of struct type
  995. // * vk::binding applies to global variables or cbuffers/tbuffers
  996. // * vk::counter_binding applies to global variables of RW/Append/Consume
  997. // StructuredBuffer
  998. // * vk::location applies to function parameters/returns and struct fields
  999. // So the only case we need to check co-existence is vk::push_constant and
  1000. // vk::binding.
  1001. if (const auto *pcAttr = decl->getAttr<VKPushConstantAttr>()) {
  1002. const auto loc = pcAttr->getLocation();
  1003. if (seenPushConstantAt.isInvalid()) {
  1004. seenPushConstantAt = loc;
  1005. } else {
  1006. // TODO: Actually this is slightly incorrect. The Vulkan spec says:
  1007. // There must be no more than one push constant block statically used
  1008. // per shader entry point.
  1009. // But we are checking whether there are more than one push constant
  1010. // blocks defined. Tracking usage requires more work.
  1011. emitError("cannot have more than one push constant block", loc);
  1012. emitNote("push constant block previously defined here",
  1013. seenPushConstantAt);
  1014. success = false;
  1015. }
  1016. if (decl->hasAttr<VKBindingAttr>()) {
  1017. emitError("vk::push_constant attribute cannot be used together with "
  1018. "vk::binding attribute",
  1019. loc);
  1020. success = false;
  1021. }
  1022. }
  1023. return success;
  1024. }
  1025. void SPIRVEmitter::doHLSLBufferDecl(const HLSLBufferDecl *bufferDecl) {
  1026. // This is a cbuffer/tbuffer decl.
  1027. // Check and emit warnings for member intializers which are not
  1028. // supported in Vulkan
  1029. for (const auto *member : bufferDecl->decls()) {
  1030. if (const auto *varMember = dyn_cast<VarDecl>(member)) {
  1031. if (const auto *init = varMember->getInit())
  1032. emitWarning("%select{tbuffer|cbuffer}0 member initializer "
  1033. "ignored since no equivalent in Vulkan",
  1034. init->getExprLoc())
  1035. << bufferDecl->isCBuffer() << init->getSourceRange();
  1036. // We cannot handle external initialization of column-major matrices now.
  1037. if (typeTranslator.isOrContainsNonFpColMajorMatrix(varMember->getType(),
  1038. varMember)) {
  1039. emitError("externally initialized non-floating-point column-major "
  1040. "matrices not supported yet",
  1041. varMember->getLocation());
  1042. }
  1043. }
  1044. }
  1045. if (!validateVKAttributes(bufferDecl))
  1046. return;
  1047. (void)declIdMapper.createCTBuffer(bufferDecl);
  1048. }
  1049. void SPIRVEmitter::doRecordDecl(const RecordDecl *recordDecl) {
  1050. // Ignore implict records
  1051. // Somehow we'll have implicit records with:
  1052. // static const int Length = count;
  1053. // that can mess up with the normal CodeGen.
  1054. if (recordDecl->isImplicit())
  1055. return;
  1056. // Handle each static member with inline initializer.
  1057. // Each static member has a corresponding VarDecl inside the
  1058. // RecordDecl. For those defined in the translation unit,
  1059. // their VarDecls do not have initializer.
  1060. for (auto *subDecl : recordDecl->decls())
  1061. if (auto *varDecl = dyn_cast<VarDecl>(subDecl))
  1062. if (varDecl->isStaticDataMember() && varDecl->hasInit())
  1063. doVarDecl(varDecl);
  1064. }
  1065. void SPIRVEmitter::doVarDecl(const VarDecl *decl) {
  1066. if (!validateVKAttributes(decl))
  1067. return;
  1068. // We cannot handle external initialization of column-major matrices now.
  1069. if (isExternalVar(decl) &&
  1070. typeTranslator.isOrContainsNonFpColMajorMatrix(decl->getType(), decl)) {
  1071. emitError("externally initialized non-floating-point column-major "
  1072. "matrices not supported yet",
  1073. decl->getLocation());
  1074. }
  1075. if (const auto *arrayType =
  1076. astContext.getAsConstantArrayType(decl->getType())) {
  1077. if (TypeTranslator::isAKindOfStructuredOrByteBuffer(
  1078. arrayType->getElementType())) {
  1079. emitError("arrays of structured/byte buffers unsupported",
  1080. decl->getLocation());
  1081. return;
  1082. }
  1083. }
  1084. if (decl->hasAttr<VKConstantIdAttr>()) {
  1085. // This is a VarDecl for specialization constant.
  1086. createSpecConstant(decl);
  1087. return;
  1088. }
  1089. if (decl->hasAttr<VKPushConstantAttr>()) {
  1090. // This is a VarDecl for PushConstant block.
  1091. (void)declIdMapper.createPushConstant(decl);
  1092. return;
  1093. }
  1094. if (isa<HLSLBufferDecl>(decl->getDeclContext())) {
  1095. // This is a VarDecl of a ConstantBuffer/TextureBuffer type.
  1096. (void)declIdMapper.createCTBuffer(decl);
  1097. return;
  1098. }
  1099. SpirvEvalInfo varId(0);
  1100. // The contents in externally visible variables can be updated via the
  1101. // pipeline. They should be handled differently from file and function scope
  1102. // variables.
  1103. // File scope variables (static "global" and "local" variables) belongs to
  1104. // the Private storage class, while function scope variables (normal "local"
  1105. // variables) belongs to the Function storage class.
  1106. if (isExternalVar(decl)) {
  1107. varId = declIdMapper.createExternVar(decl);
  1108. } else {
  1109. // We already know the variable is not externally visible here. If it does
  1110. // not have local storage, it should be file scope variable.
  1111. const bool isFileScopeVar = !decl->hasLocalStorage();
  1112. if (isFileScopeVar)
  1113. varId = declIdMapper.createFileVar(decl, llvm::None);
  1114. else
  1115. varId = declIdMapper.createFnVar(decl, llvm::None);
  1116. // Emit OpStore to initialize the variable
  1117. // TODO: revert back to use OpVariable initializer
  1118. // We should only evaluate the initializer once for a static variable.
  1119. if (isFileScopeVar) {
  1120. if (decl->isStaticLocal()) {
  1121. initOnce(decl->getType(), decl->getName(), varId, decl->getInit());
  1122. } else {
  1123. // Defer to initialize these global variables at the beginning of the
  1124. // entry function.
  1125. toInitGloalVars.push_back(decl);
  1126. }
  1127. }
  1128. // Function local variables. Just emit OpStore at the current insert point.
  1129. else if (const Expr *init = decl->getInit()) {
  1130. if (const auto constId = tryToEvaluateAsConst(init))
  1131. theBuilder.createStore(varId, constId);
  1132. else
  1133. storeValue(varId, loadIfGLValue(init), decl->getType());
  1134. // Update counter variable associated with local variables
  1135. tryToAssignCounterVar(decl, init);
  1136. }
  1137. // Variables that are not externally visible and of opaque types should
  1138. // request legalization.
  1139. if (!needsLegalization && TypeTranslator::isOpaqueType(decl->getType()))
  1140. needsLegalization = true;
  1141. }
  1142. if (TypeTranslator::isRelaxedPrecisionType(decl->getType(), spirvOptions)) {
  1143. theBuilder.decorate(varId, spv::Decoration::RelaxedPrecision);
  1144. }
  1145. // All variables that are of opaque struct types should request legalization.
  1146. if (!needsLegalization && TypeTranslator::isOpaqueStructType(decl->getType()))
  1147. needsLegalization = true;
  1148. }
  1149. spv::LoopControlMask SPIRVEmitter::translateLoopAttribute(const Stmt *stmt,
  1150. const Attr &attr) {
  1151. switch (attr.getKind()) {
  1152. case attr::HLSLLoop:
  1153. case attr::HLSLFastOpt:
  1154. return spv::LoopControlMask::DontUnroll;
  1155. case attr::HLSLUnroll:
  1156. return spv::LoopControlMask::Unroll;
  1157. case attr::HLSLAllowUAVCondition:
  1158. emitWarning("unsupported allow_uav_condition attribute ignored",
  1159. stmt->getLocStart());
  1160. break;
  1161. default:
  1162. llvm_unreachable("found unknown loop attribute");
  1163. }
  1164. return spv::LoopControlMask::MaskNone;
  1165. }
  1166. void SPIRVEmitter::doDiscardStmt(const DiscardStmt *discardStmt) {
  1167. assert(!theBuilder.isCurrentBasicBlockTerminated());
  1168. theBuilder.createKill();
  1169. // Some statements that alter the control flow (break, continue, return, and
  1170. // discard), require creation of a new basic block to hold any statement that
  1171. // may follow them.
  1172. const uint32_t newBB = theBuilder.createBasicBlock();
  1173. theBuilder.setInsertPoint(newBB);
  1174. }
  1175. void SPIRVEmitter::doDoStmt(const DoStmt *theDoStmt,
  1176. llvm::ArrayRef<const Attr *> attrs) {
  1177. // do-while loops are composed of:
  1178. //
  1179. // do {
  1180. // <body>
  1181. // } while(<check>);
  1182. //
  1183. // SPIR-V requires loops to have a merge basic block as well as a continue
  1184. // basic block. Even though do-while loops do not have an explicit continue
  1185. // block as in for-loops, we still do need to create a continue block.
  1186. //
  1187. // Since SPIR-V requires structured control flow, we need two more basic
  1188. // blocks, <header> and <merge>. <header> is the block before control flow
  1189. // diverges, and <merge> is the block where control flow subsequently
  1190. // converges. The <check> can be performed in the <continue> basic block.
  1191. // The final CFG should normally be like the following. Exceptions
  1192. // will occur with non-local exits like loop breaks or early returns.
  1193. //
  1194. // +----------+
  1195. // | header | <-----------------------------------+
  1196. // +----------+ |
  1197. // | | (true)
  1198. // v |
  1199. // +------+ +--------------------+ |
  1200. // | body | ----> | continue (<check>) |-----------+
  1201. // +------+ +--------------------+
  1202. // |
  1203. // | (false)
  1204. // +-------+ |
  1205. // | merge | <-------------+
  1206. // +-------+
  1207. //
  1208. // For more details, see "2.11. Structured Control Flow" in the SPIR-V spec.
  1209. const spv::LoopControlMask loopControl =
  1210. attrs.empty() ? spv::LoopControlMask::MaskNone
  1211. : translateLoopAttribute(theDoStmt, *attrs.front());
  1212. // Create basic blocks
  1213. const uint32_t headerBB = theBuilder.createBasicBlock("do_while.header");
  1214. const uint32_t bodyBB = theBuilder.createBasicBlock("do_while.body");
  1215. const uint32_t continueBB = theBuilder.createBasicBlock("do_while.continue");
  1216. const uint32_t mergeBB = theBuilder.createBasicBlock("do_while.merge");
  1217. // Make sure any continue statements branch to the continue block, and any
  1218. // break statements branch to the merge block.
  1219. continueStack.push(continueBB);
  1220. breakStack.push(mergeBB);
  1221. // Branch from the current insert point to the header block.
  1222. theBuilder.createBranch(headerBB);
  1223. theBuilder.addSuccessor(headerBB);
  1224. // Process the <header> block
  1225. // The header block must always branch to the body.
  1226. theBuilder.setInsertPoint(headerBB);
  1227. theBuilder.createBranch(bodyBB, mergeBB, continueBB, loopControl);
  1228. theBuilder.addSuccessor(bodyBB);
  1229. // The current basic block has OpLoopMerge instruction. We need to set its
  1230. // continue and merge target.
  1231. theBuilder.setContinueTarget(continueBB);
  1232. theBuilder.setMergeTarget(mergeBB);
  1233. // Process the <body> block
  1234. theBuilder.setInsertPoint(bodyBB);
  1235. if (const Stmt *body = theDoStmt->getBody()) {
  1236. doStmt(body);
  1237. }
  1238. if (!theBuilder.isCurrentBasicBlockTerminated())
  1239. theBuilder.createBranch(continueBB);
  1240. theBuilder.addSuccessor(continueBB);
  1241. // Process the <continue> block. The check for whether the loop should
  1242. // continue lies in the continue block.
  1243. // *NOTE*: There's a SPIR-V rule that when a conditional branch is to occur in
  1244. // a continue block of a loop, there should be no OpSelectionMerge. Only an
  1245. // OpBranchConditional must be specified.
  1246. theBuilder.setInsertPoint(continueBB);
  1247. uint32_t condition = 0;
  1248. if (const Expr *check = theDoStmt->getCond()) {
  1249. condition = doExpr(check);
  1250. } else {
  1251. condition = theBuilder.getConstantBool(true);
  1252. }
  1253. theBuilder.createConditionalBranch(condition, headerBB, mergeBB);
  1254. theBuilder.addSuccessor(headerBB);
  1255. theBuilder.addSuccessor(mergeBB);
  1256. // Set insertion point to the <merge> block for subsequent statements
  1257. theBuilder.setInsertPoint(mergeBB);
  1258. // Done with the current scope's continue block and merge block.
  1259. continueStack.pop();
  1260. breakStack.pop();
  1261. }
  1262. void SPIRVEmitter::doContinueStmt(const ContinueStmt *continueStmt) {
  1263. assert(!theBuilder.isCurrentBasicBlockTerminated());
  1264. const uint32_t continueTargetBB = continueStack.top();
  1265. theBuilder.createBranch(continueTargetBB);
  1266. theBuilder.addSuccessor(continueTargetBB);
  1267. // Some statements that alter the control flow (break, continue, return, and
  1268. // discard), require creation of a new basic block to hold any statement that
  1269. // may follow them. For example: StmtB and StmtC below are put inside a new
  1270. // basic block which is unreachable.
  1271. //
  1272. // while (true) {
  1273. // StmtA;
  1274. // continue;
  1275. // StmtB;
  1276. // StmtC;
  1277. // }
  1278. const uint32_t newBB = theBuilder.createBasicBlock();
  1279. theBuilder.setInsertPoint(newBB);
  1280. }
  1281. void SPIRVEmitter::doWhileStmt(const WhileStmt *whileStmt,
  1282. llvm::ArrayRef<const Attr *> attrs) {
  1283. // While loops are composed of:
  1284. // while (<check>) { <body> }
  1285. //
  1286. // SPIR-V requires loops to have a merge basic block as well as a continue
  1287. // basic block. Even though while loops do not have an explicit continue
  1288. // block as in for-loops, we still do need to create a continue block.
  1289. //
  1290. // Since SPIR-V requires structured control flow, we need two more basic
  1291. // blocks, <header> and <merge>. <header> is the block before control flow
  1292. // diverges, and <merge> is the block where control flow subsequently
  1293. // converges. The <check> block can take the responsibility of the <header>
  1294. // block. The final CFG should normally be like the following. Exceptions
  1295. // will occur with non-local exits like loop breaks or early returns.
  1296. //
  1297. // +----------+
  1298. // | header | <------------------+
  1299. // | (check) | |
  1300. // +----------+ |
  1301. // | |
  1302. // +-------+-------+ |
  1303. // | false | true |
  1304. // | v |
  1305. // | +------+ +------------------+
  1306. // | | body | --> | continue (no-op) |
  1307. // v +------+ +------------------+
  1308. // +-------+
  1309. // | merge |
  1310. // +-------+
  1311. //
  1312. // For more details, see "2.11. Structured Control Flow" in the SPIR-V spec.
  1313. const spv::LoopControlMask loopControl =
  1314. attrs.empty() ? spv::LoopControlMask::MaskNone
  1315. : translateLoopAttribute(whileStmt, *attrs.front());
  1316. // Create basic blocks
  1317. const uint32_t checkBB = theBuilder.createBasicBlock("while.check");
  1318. const uint32_t bodyBB = theBuilder.createBasicBlock("while.body");
  1319. const uint32_t continueBB = theBuilder.createBasicBlock("while.continue");
  1320. const uint32_t mergeBB = theBuilder.createBasicBlock("while.merge");
  1321. // Make sure any continue statements branch to the continue block, and any
  1322. // break statements branch to the merge block.
  1323. continueStack.push(continueBB);
  1324. breakStack.push(mergeBB);
  1325. // Process the <check> block
  1326. theBuilder.createBranch(checkBB);
  1327. theBuilder.addSuccessor(checkBB);
  1328. theBuilder.setInsertPoint(checkBB);
  1329. // If we have:
  1330. // while (int a = foo()) {...}
  1331. // we should evaluate 'a' by calling 'foo()' every single time the check has
  1332. // to occur.
  1333. if (const auto *condVarDecl = whileStmt->getConditionVariableDeclStmt())
  1334. doStmt(condVarDecl);
  1335. uint32_t condition = 0;
  1336. if (const Expr *check = whileStmt->getCond()) {
  1337. condition = doExpr(check);
  1338. } else {
  1339. condition = theBuilder.getConstantBool(true);
  1340. }
  1341. theBuilder.createConditionalBranch(condition, bodyBB,
  1342. /*false branch*/ mergeBB,
  1343. /*merge*/ mergeBB, continueBB,
  1344. spv::SelectionControlMask::MaskNone,
  1345. loopControl);
  1346. theBuilder.addSuccessor(bodyBB);
  1347. theBuilder.addSuccessor(mergeBB);
  1348. // The current basic block has OpLoopMerge instruction. We need to set its
  1349. // continue and merge target.
  1350. theBuilder.setContinueTarget(continueBB);
  1351. theBuilder.setMergeTarget(mergeBB);
  1352. // Process the <body> block
  1353. theBuilder.setInsertPoint(bodyBB);
  1354. if (const Stmt *body = whileStmt->getBody()) {
  1355. doStmt(body);
  1356. }
  1357. if (!theBuilder.isCurrentBasicBlockTerminated())
  1358. theBuilder.createBranch(continueBB);
  1359. theBuilder.addSuccessor(continueBB);
  1360. // Process the <continue> block. While loops do not have an explicit
  1361. // continue block. The continue block just branches to the <check> block.
  1362. theBuilder.setInsertPoint(continueBB);
  1363. theBuilder.createBranch(checkBB);
  1364. theBuilder.addSuccessor(checkBB);
  1365. // Set insertion point to the <merge> block for subsequent statements
  1366. theBuilder.setInsertPoint(mergeBB);
  1367. // Done with the current scope's continue and merge blocks.
  1368. continueStack.pop();
  1369. breakStack.pop();
  1370. }
  1371. void SPIRVEmitter::doForStmt(const ForStmt *forStmt,
  1372. llvm::ArrayRef<const Attr *> attrs) {
  1373. // for loops are composed of:
  1374. // for (<init>; <check>; <continue>) <body>
  1375. //
  1376. // To translate a for loop, we'll need to emit all <init> statements
  1377. // in the current basic block, and then have separate basic blocks for
  1378. // <check>, <continue>, and <body>. Besides, since SPIR-V requires
  1379. // structured control flow, we need two more basic blocks, <header>
  1380. // and <merge>. <header> is the block before control flow diverges,
  1381. // while <merge> is the block where control flow subsequently converges.
  1382. // The <check> block can take the responsibility of the <header> block.
  1383. // The final CFG should normally be like the following. Exceptions will
  1384. // occur with non-local exits like loop breaks or early returns.
  1385. // +--------+
  1386. // | init |
  1387. // +--------+
  1388. // |
  1389. // v
  1390. // +----------+
  1391. // | header | <---------------+
  1392. // | (check) | |
  1393. // +----------+ |
  1394. // | |
  1395. // +-------+-------+ |
  1396. // | false | true |
  1397. // | v |
  1398. // | +------+ +----------+
  1399. // | | body | --> | continue |
  1400. // v +------+ +----------+
  1401. // +-------+
  1402. // | merge |
  1403. // +-------+
  1404. //
  1405. // For more details, see "2.11. Structured Control Flow" in the SPIR-V spec.
  1406. const spv::LoopControlMask loopControl =
  1407. attrs.empty() ? spv::LoopControlMask::MaskNone
  1408. : translateLoopAttribute(forStmt, *attrs.front());
  1409. // Create basic blocks
  1410. const uint32_t checkBB = theBuilder.createBasicBlock("for.check");
  1411. const uint32_t bodyBB = theBuilder.createBasicBlock("for.body");
  1412. const uint32_t continueBB = theBuilder.createBasicBlock("for.continue");
  1413. const uint32_t mergeBB = theBuilder.createBasicBlock("for.merge");
  1414. // Make sure any continue statements branch to the continue block, and any
  1415. // break statements branch to the merge block.
  1416. continueStack.push(continueBB);
  1417. breakStack.push(mergeBB);
  1418. // Process the <init> block
  1419. if (const Stmt *initStmt = forStmt->getInit()) {
  1420. doStmt(initStmt);
  1421. }
  1422. theBuilder.createBranch(checkBB);
  1423. theBuilder.addSuccessor(checkBB);
  1424. // Process the <check> block
  1425. theBuilder.setInsertPoint(checkBB);
  1426. uint32_t condition;
  1427. if (const Expr *check = forStmt->getCond()) {
  1428. condition = doExpr(check);
  1429. } else {
  1430. condition = theBuilder.getConstantBool(true);
  1431. }
  1432. theBuilder.createConditionalBranch(condition, bodyBB,
  1433. /*false branch*/ mergeBB,
  1434. /*merge*/ mergeBB, continueBB,
  1435. spv::SelectionControlMask::MaskNone,
  1436. loopControl);
  1437. theBuilder.addSuccessor(bodyBB);
  1438. theBuilder.addSuccessor(mergeBB);
  1439. // The current basic block has OpLoopMerge instruction. We need to set its
  1440. // continue and merge target.
  1441. theBuilder.setContinueTarget(continueBB);
  1442. theBuilder.setMergeTarget(mergeBB);
  1443. // Process the <body> block
  1444. theBuilder.setInsertPoint(bodyBB);
  1445. if (const Stmt *body = forStmt->getBody()) {
  1446. doStmt(body);
  1447. }
  1448. if (!theBuilder.isCurrentBasicBlockTerminated())
  1449. theBuilder.createBranch(continueBB);
  1450. theBuilder.addSuccessor(continueBB);
  1451. // Process the <continue> block
  1452. theBuilder.setInsertPoint(continueBB);
  1453. if (const Expr *cont = forStmt->getInc()) {
  1454. doExpr(cont);
  1455. }
  1456. theBuilder.createBranch(checkBB); // <continue> should jump back to header
  1457. theBuilder.addSuccessor(checkBB);
  1458. // Set insertion point to the <merge> block for subsequent statements
  1459. theBuilder.setInsertPoint(mergeBB);
  1460. // Done with the current scope's continue block and merge block.
  1461. continueStack.pop();
  1462. breakStack.pop();
  1463. }
  1464. void SPIRVEmitter::doIfStmt(const IfStmt *ifStmt,
  1465. llvm::ArrayRef<const Attr *> attrs) {
  1466. // if statements are composed of:
  1467. // if (<check>) { <then> } else { <else> }
  1468. //
  1469. // To translate if statements, we'll need to emit the <check> expressions
  1470. // in the current basic block, and then create separate basic blocks for
  1471. // <then> and <else>. Additionally, we'll need a <merge> block as per
  1472. // SPIR-V's structured control flow requirements. Depending whether there
  1473. // exists the else branch, the final CFG should normally be like the
  1474. // following. Exceptions will occur with non-local exits like loop breaks
  1475. // or early returns.
  1476. // +-------+ +-------+
  1477. // | check | | check |
  1478. // +-------+ +-------+
  1479. // | |
  1480. // +-------+-------+ +-----+-----+
  1481. // | true | false | true | false
  1482. // v v or v |
  1483. // +------+ +------+ +------+ |
  1484. // | then | | else | | then | |
  1485. // +------+ +------+ +------+ |
  1486. // | | | v
  1487. // | +-------+ | | +-------+
  1488. // +-> | merge | <-+ +---> | merge |
  1489. // +-------+ +-------+
  1490. { // Try to see if we can const-eval the condition
  1491. bool condition = false;
  1492. if (ifStmt->getCond()->EvaluateAsBooleanCondition(condition, astContext)) {
  1493. if (condition) {
  1494. doStmt(ifStmt->getThen());
  1495. } else if (ifStmt->getElse()) {
  1496. doStmt(ifStmt->getElse());
  1497. }
  1498. return;
  1499. }
  1500. }
  1501. auto selectionControl = spv::SelectionControlMask::MaskNone;
  1502. if (!attrs.empty()) {
  1503. const Attr *attribute = attrs.front();
  1504. switch (attribute->getKind()) {
  1505. case attr::HLSLBranch:
  1506. selectionControl = spv::SelectionControlMask::DontFlatten;
  1507. break;
  1508. case attr::HLSLFlatten:
  1509. selectionControl = spv::SelectionControlMask::Flatten;
  1510. break;
  1511. default:
  1512. emitWarning("unknown if statement attribute '%0' ignored",
  1513. attribute->getLocation())
  1514. << attribute->getSpelling();
  1515. break;
  1516. }
  1517. }
  1518. if (const auto *declStmt = ifStmt->getConditionVariableDeclStmt())
  1519. doDeclStmt(declStmt);
  1520. // First emit the instruction for evaluating the condition.
  1521. const uint32_t condition = doExpr(ifStmt->getCond());
  1522. // Then we need to emit the instruction for the conditional branch.
  1523. // We'll need the <label-id> for the then/else/merge block to do so.
  1524. const bool hasElse = ifStmt->getElse() != nullptr;
  1525. const uint32_t thenBB = theBuilder.createBasicBlock("if.true");
  1526. const uint32_t mergeBB = theBuilder.createBasicBlock("if.merge");
  1527. const uint32_t elseBB =
  1528. hasElse ? theBuilder.createBasicBlock("if.false") : mergeBB;
  1529. // Create the branch instruction. This will end the current basic block.
  1530. theBuilder.createConditionalBranch(condition, thenBB, elseBB, mergeBB,
  1531. /*continue*/ 0, selectionControl);
  1532. theBuilder.addSuccessor(thenBB);
  1533. theBuilder.addSuccessor(elseBB);
  1534. // The current basic block has the OpSelectionMerge instruction. We need
  1535. // to record its merge target.
  1536. theBuilder.setMergeTarget(mergeBB);
  1537. // Handle the then branch
  1538. theBuilder.setInsertPoint(thenBB);
  1539. doStmt(ifStmt->getThen());
  1540. if (!theBuilder.isCurrentBasicBlockTerminated())
  1541. theBuilder.createBranch(mergeBB);
  1542. theBuilder.addSuccessor(mergeBB);
  1543. // Handle the else branch (if exists)
  1544. if (hasElse) {
  1545. theBuilder.setInsertPoint(elseBB);
  1546. doStmt(ifStmt->getElse());
  1547. if (!theBuilder.isCurrentBasicBlockTerminated())
  1548. theBuilder.createBranch(mergeBB);
  1549. theBuilder.addSuccessor(mergeBB);
  1550. }
  1551. // From now on, we'll emit instructions into the merge block.
  1552. theBuilder.setInsertPoint(mergeBB);
  1553. }
  1554. void SPIRVEmitter::doReturnStmt(const ReturnStmt *stmt) {
  1555. if (const auto *retVal = stmt->getRetValue()) {
  1556. // Update counter variable associated with function returns
  1557. tryToAssignCounterVar(curFunction, retVal);
  1558. const auto retInfo = loadIfGLValue(retVal);
  1559. const auto retType = retVal->getType();
  1560. if (retInfo.getStorageClass() != spv::StorageClass::Function &&
  1561. retType->isStructureType()) {
  1562. // We are returning some value from a non-Function storage class. Need to
  1563. // create a temporary variable to "convert" the value to Function storage
  1564. // class and then return.
  1565. const uint32_t valType = typeTranslator.translateType(retType);
  1566. const uint32_t tempVar = theBuilder.addFnVar(valType, "temp.var.ret");
  1567. storeValue(tempVar, retInfo, retType);
  1568. theBuilder.createReturnValue(theBuilder.createLoad(valType, tempVar));
  1569. } else {
  1570. theBuilder.createReturnValue(retInfo);
  1571. }
  1572. } else {
  1573. theBuilder.createReturn();
  1574. }
  1575. // We are translating a ReturnStmt, we should be in some function's body.
  1576. assert(curFunction->hasBody());
  1577. // If this return statement is the last statement in the function, then
  1578. // whe have no more work to do.
  1579. if (cast<CompoundStmt>(curFunction->getBody())->body_back() == stmt)
  1580. return;
  1581. // Some statements that alter the control flow (break, continue, return, and
  1582. // discard), require creation of a new basic block to hold any statement that
  1583. // may follow them. In this case, the newly created basic block will contain
  1584. // any statement that may come after an early return.
  1585. const uint32_t newBB = theBuilder.createBasicBlock();
  1586. theBuilder.setInsertPoint(newBB);
  1587. }
  1588. void SPIRVEmitter::doBreakStmt(const BreakStmt *breakStmt) {
  1589. assert(!theBuilder.isCurrentBasicBlockTerminated());
  1590. uint32_t breakTargetBB = breakStack.top();
  1591. theBuilder.addSuccessor(breakTargetBB);
  1592. theBuilder.createBranch(breakTargetBB);
  1593. // Some statements that alter the control flow (break, continue, return, and
  1594. // discard), require creation of a new basic block to hold any statement that
  1595. // may follow them. For example: StmtB and StmtC below are put inside a new
  1596. // basic block which is unreachable.
  1597. //
  1598. // while (true) {
  1599. // StmtA;
  1600. // break;
  1601. // StmtB;
  1602. // StmtC;
  1603. // }
  1604. const uint32_t newBB = theBuilder.createBasicBlock();
  1605. theBuilder.setInsertPoint(newBB);
  1606. }
  1607. void SPIRVEmitter::doSwitchStmt(const SwitchStmt *switchStmt,
  1608. llvm::ArrayRef<const Attr *> attrs) {
  1609. // Switch statements are composed of:
  1610. // switch (<condition variable>) {
  1611. // <CaseStmt>
  1612. // <CaseStmt>
  1613. // <CaseStmt>
  1614. // <DefaultStmt> (optional)
  1615. // }
  1616. //
  1617. // +-------+
  1618. // | check |
  1619. // +-------+
  1620. // |
  1621. // +-------+-------+----------------+---------------+
  1622. // | 1 | 2 | 3 | (others)
  1623. // v v v v
  1624. // +-------+ +-------------+ +-------+ +------------+
  1625. // | case1 | | case2 | | case3 | ... | default |
  1626. // | | |(fallthrough)|---->| | | (optional) |
  1627. // +-------+ |+------------+ +-------+ +------------+
  1628. // | | |
  1629. // | | |
  1630. // | +-------+ | |
  1631. // | | | <--------------------+ |
  1632. // +-> | merge | |
  1633. // | | <-------------------------------------+
  1634. // +-------+
  1635. // If no attributes are given, or if "forcecase" attribute was provided,
  1636. // we'll do our best to use OpSwitch if possible.
  1637. // If any of the cases compares to a variable (rather than an integer
  1638. // literal), we cannot use OpSwitch because OpSwitch expects literal
  1639. // numbers as parameters.
  1640. const bool isAttrForceCase =
  1641. !attrs.empty() && attrs.front()->getKind() == attr::HLSLForceCase;
  1642. const bool canUseSpirvOpSwitch =
  1643. (attrs.empty() || isAttrForceCase) &&
  1644. allSwitchCasesAreIntegerLiterals(switchStmt->getBody());
  1645. if (isAttrForceCase && !canUseSpirvOpSwitch)
  1646. emitWarning("ignored 'forcecase' attribute for the switch statement "
  1647. "since one or more case values are not integer literals",
  1648. switchStmt->getLocStart());
  1649. if (canUseSpirvOpSwitch)
  1650. processSwitchStmtUsingSpirvOpSwitch(switchStmt);
  1651. else
  1652. processSwitchStmtUsingIfStmts(switchStmt);
  1653. }
  1654. SpirvEvalInfo
  1655. SPIRVEmitter::doArraySubscriptExpr(const ArraySubscriptExpr *expr) {
  1656. llvm::SmallVector<uint32_t, 4> indices;
  1657. auto info = loadIfAliasVarRef(collectArrayStructIndices(expr, &indices));
  1658. if (!indices.empty()) {
  1659. (void)turnIntoElementPtr(info, expr->getType(), indices);
  1660. }
  1661. return info;
  1662. }
  1663. SpirvEvalInfo SPIRVEmitter::doBinaryOperator(const BinaryOperator *expr) {
  1664. const auto opcode = expr->getOpcode();
  1665. // Handle assignment first since we need to evaluate rhs before lhs.
  1666. // For other binary operations, we need to evaluate lhs before rhs.
  1667. if (opcode == BO_Assign) {
  1668. // Update counter variable associated with lhs of assignments
  1669. tryToAssignCounterVar(expr->getLHS(), expr->getRHS());
  1670. return processAssignment(expr->getLHS(), loadIfGLValue(expr->getRHS()),
  1671. /*isCompoundAssignment=*/false);
  1672. }
  1673. // Try to optimize floatMxN * float and floatN * float case
  1674. if (opcode == BO_Mul) {
  1675. if (SpirvEvalInfo result = tryToGenFloatMatrixScale(expr))
  1676. return result;
  1677. if (SpirvEvalInfo result = tryToGenFloatVectorScale(expr))
  1678. return result;
  1679. }
  1680. return processBinaryOp(expr->getLHS(), expr->getRHS(), opcode,
  1681. expr->getLHS()->getType(), expr->getType(),
  1682. expr->getSourceRange());
  1683. }
  1684. SpirvEvalInfo SPIRVEmitter::doCallExpr(const CallExpr *callExpr) {
  1685. if (const auto *operatorCall = dyn_cast<CXXOperatorCallExpr>(callExpr))
  1686. return doCXXOperatorCallExpr(operatorCall);
  1687. if (const auto *memberCall = dyn_cast<CXXMemberCallExpr>(callExpr))
  1688. return doCXXMemberCallExpr(memberCall);
  1689. // Intrinsic functions such as 'dot' or 'mul'
  1690. if (hlsl::IsIntrinsicOp(callExpr->getDirectCallee())) {
  1691. return processIntrinsicCallExpr(callExpr);
  1692. }
  1693. // Normal standalone functions
  1694. return processCall(callExpr);
  1695. }
  1696. SpirvEvalInfo SPIRVEmitter::processCall(const CallExpr *callExpr) {
  1697. const FunctionDecl *callee = getCalleeDefinition(callExpr);
  1698. // Note that we always want the defintion because Stmts/Exprs in the
  1699. // function body references the parameters in the definition.
  1700. if (!callee) {
  1701. emitError("found undefined function", callExpr->getExprLoc());
  1702. return 0;
  1703. }
  1704. const auto numParams = callee->getNumParams();
  1705. bool isNonStaticMemberCall = false;
  1706. QualType objectType = {}; // Type of the object (if exists)
  1707. SpirvEvalInfo objectEvalInfo = 0; // EvalInfo for the object (if exists)
  1708. bool needsTempVar = false; // Whether we need temporary variable.
  1709. llvm::SmallVector<uint32_t, 4> params; // Temporary variables
  1710. llvm::SmallVector<SpirvEvalInfo, 4> args; // Evaluated arguments
  1711. if (const auto *memberCall = dyn_cast<CXXMemberCallExpr>(callExpr)) {
  1712. const auto *memberFn = cast<CXXMethodDecl>(memberCall->getCalleeDecl());
  1713. isNonStaticMemberCall = !memberFn->isStatic();
  1714. if (isNonStaticMemberCall) {
  1715. // For non-static member calls, evaluate the object and pass it as the
  1716. // first argument.
  1717. const auto *object = memberCall->getImplicitObjectArgument();
  1718. object = object->IgnoreParenNoopCasts(astContext);
  1719. // Update counter variable associated with the implicit object
  1720. tryToAssignCounterVar(getOrCreateDeclForMethodObject(memberFn), object);
  1721. objectType = object->getType();
  1722. objectEvalInfo = doExpr(object);
  1723. uint32_t objectId = objectEvalInfo;
  1724. // If not already a variable, we need to create a temporary variable and
  1725. // pass the object pointer to the function. Example:
  1726. // getObject().objectMethod();
  1727. // Also, any parameter passed to the member function must be of Function
  1728. // storage class.
  1729. needsTempVar =
  1730. objectEvalInfo.isRValue() ||
  1731. objectEvalInfo.getStorageClass() != spv::StorageClass::Function;
  1732. if (needsTempVar) {
  1733. objectId =
  1734. createTemporaryVar(objectType, TypeTranslator::getName(objectType),
  1735. // May need to load to use as initializer
  1736. loadIfGLValue(object, objectEvalInfo));
  1737. }
  1738. args.push_back(objectId);
  1739. // We do not need to create a new temporary variable for the this
  1740. // object. Use the evaluated argument.
  1741. params.push_back(args.back());
  1742. }
  1743. }
  1744. // Evaluate parameters
  1745. for (uint32_t i = 0; i < numParams; ++i) {
  1746. // We want the argument variable here so that we can write back to it
  1747. // later. We will do the OpLoad of this argument manually. So ingore
  1748. // the LValueToRValue implicit cast here.
  1749. auto *arg = callExpr->getArg(i)->IgnoreParenLValueCasts();
  1750. const auto *param = callee->getParamDecl(i);
  1751. // We need to create variables for holding the values to be used as
  1752. // arguments. The variables themselves are of pointer types.
  1753. const uint32_t varType =
  1754. declIdMapper.getTypeAndCreateCounterForPotentialAliasVar(param);
  1755. const std::string varName = "param.var." + param->getNameAsString();
  1756. const uint32_t tempVarId = theBuilder.addFnVar(varType, varName);
  1757. params.push_back(tempVarId);
  1758. args.push_back(doExpr(arg));
  1759. // Update counter variable associated with function parameters
  1760. tryToAssignCounterVar(param, arg);
  1761. // Manually load the argument here
  1762. const auto rhsVal = loadIfGLValue(arg, args.back());
  1763. // Initialize the temporary variables using the contents of the arguments
  1764. storeValue(tempVarId, rhsVal, param->getType());
  1765. }
  1766. // Push the callee into the work queue if it is not there.
  1767. if (!workQueue.count(callee)) {
  1768. workQueue.insert(callee);
  1769. }
  1770. const uint32_t retType =
  1771. declIdMapper.getTypeAndCreateCounterForPotentialAliasVar(callee);
  1772. // Get or forward declare the function <result-id>
  1773. const uint32_t funcId = declIdMapper.getOrRegisterFnResultId(callee);
  1774. const uint32_t retVal =
  1775. theBuilder.createFunctionCall(retType, funcId, params);
  1776. // If we created a temporary variable for the lvalue object this method is
  1777. // invoked upon, we need to copy the contents in the temporary variable back
  1778. // to the original object's variable in case there are side effects.
  1779. if (needsTempVar && !objectEvalInfo.isRValue()) {
  1780. const uint32_t typeId = typeTranslator.translateType(objectType);
  1781. const uint32_t value = theBuilder.createLoad(typeId, params.front());
  1782. storeValue(objectEvalInfo, value, objectType);
  1783. }
  1784. // Go through all parameters and write those marked as out/inout
  1785. for (uint32_t i = 0; i < numParams; ++i) {
  1786. const auto *param = callee->getParamDecl(i);
  1787. if (canActAsOutParmVar(param)) {
  1788. const auto *arg = callExpr->getArg(i);
  1789. const uint32_t index = i + isNonStaticMemberCall;
  1790. const uint32_t typeId = typeTranslator.translateType(param->getType());
  1791. const uint32_t value = theBuilder.createLoad(typeId, params[index]);
  1792. processAssignment(arg, value, false, args[index]);
  1793. }
  1794. }
  1795. // Inherit the SpirvEvalInfo from the function definition
  1796. return declIdMapper.getDeclEvalInfo(callee).setResultId(retVal);
  1797. }
  1798. SpirvEvalInfo SPIRVEmitter::doCastExpr(const CastExpr *expr) {
  1799. const Expr *subExpr = expr->getSubExpr();
  1800. const QualType subExprType = subExpr->getType();
  1801. const QualType toType = expr->getType();
  1802. // Unfortunately the front-end fails to deduce some types in certain cases.
  1803. // Provide a hint about literal type usage if possible.
  1804. TypeTranslator::LiteralTypeHint hint(typeTranslator);
  1805. // 'literal int' to 'float' conversion. If a literal integer is to be used as
  1806. // a 32-bit float, the hint is a 32-bit integer.
  1807. if (toType->isFloatingType() &&
  1808. subExprType->isSpecificBuiltinType(BuiltinType::LitInt) &&
  1809. llvm::APFloat::getSizeInBits(astContext.getFloatTypeSemantics(toType)) ==
  1810. 32)
  1811. hint.setHint(astContext.IntTy);
  1812. // 'literal float' to 'float' conversion where intended type is float32.
  1813. if (toType->isFloatingType() &&
  1814. subExprType->isSpecificBuiltinType(BuiltinType::LitFloat) &&
  1815. llvm::APFloat::getSizeInBits(astContext.getFloatTypeSemantics(toType)) ==
  1816. 32)
  1817. hint.setHint(astContext.FloatTy);
  1818. // TODO: We could provide other useful hints. For instance:
  1819. // For the case of toType being a boolean, if the fromType is a literal float,
  1820. // we could provide a FloatTy hint and if the fromType is a literal integer,
  1821. // we could provide an IntTy hint. The front-end, however, seems to deduce the
  1822. // correct type in these cases; therefore we currently don't provide any
  1823. // additional hints.
  1824. switch (expr->getCastKind()) {
  1825. case CastKind::CK_LValueToRValue:
  1826. return loadIfGLValue(subExpr);
  1827. case CastKind::CK_NoOp:
  1828. return doExpr(subExpr);
  1829. case CastKind::CK_IntegralCast:
  1830. case CastKind::CK_FloatingToIntegral:
  1831. case CastKind::CK_HLSLCC_IntegralCast:
  1832. case CastKind::CK_HLSLCC_FloatingToIntegral: {
  1833. // Integer literals in the AST are represented using 64bit APInt
  1834. // themselves and then implicitly casted into the expected bitwidth.
  1835. // We need special treatment of integer literals here because generating
  1836. // a 64bit constant and then explicit casting in SPIR-V requires Int64
  1837. // capability. We should avoid introducing unnecessary capabilities to
  1838. // our best.
  1839. if (const uint32_t valueId = tryToEvaluateAsConst(expr))
  1840. return SpirvEvalInfo(valueId).setConstant().setRValue();
  1841. const auto valueId =
  1842. castToInt(doExpr(subExpr), subExprType, toType, subExpr->getExprLoc());
  1843. return SpirvEvalInfo(valueId).setRValue();
  1844. }
  1845. case CastKind::CK_FloatingCast:
  1846. case CastKind::CK_IntegralToFloating:
  1847. case CastKind::CK_HLSLCC_FloatingCast:
  1848. case CastKind::CK_HLSLCC_IntegralToFloating: {
  1849. // First try to see if we can do constant folding for floating point
  1850. // numbers like what we are doing for integers in the above.
  1851. if (const uint32_t valueId = tryToEvaluateAsConst(expr))
  1852. return SpirvEvalInfo(valueId).setConstant().setRValue();
  1853. const auto valueId = castToFloat(doExpr(subExpr), subExprType, toType,
  1854. subExpr->getExprLoc());
  1855. return SpirvEvalInfo(valueId).setRValue();
  1856. }
  1857. case CastKind::CK_IntegralToBoolean:
  1858. case CastKind::CK_FloatingToBoolean:
  1859. case CastKind::CK_HLSLCC_IntegralToBoolean:
  1860. case CastKind::CK_HLSLCC_FloatingToBoolean: {
  1861. // First try to see if we can do constant folding.
  1862. if (const uint32_t valueId = tryToEvaluateAsConst(expr))
  1863. return SpirvEvalInfo(valueId).setConstant().setRValue();
  1864. const auto valueId = castToBool(doExpr(subExpr), subExprType, toType);
  1865. return SpirvEvalInfo(valueId).setRValue();
  1866. }
  1867. case CastKind::CK_HLSLVectorSplat: {
  1868. const size_t size = hlsl::GetHLSLVecSize(expr->getType());
  1869. return createVectorSplat(subExpr, size);
  1870. }
  1871. case CastKind::CK_HLSLVectorTruncationCast: {
  1872. const uint32_t toVecTypeId = typeTranslator.translateType(toType);
  1873. const uint32_t elemTypeId =
  1874. typeTranslator.translateType(hlsl::GetHLSLVecElementType(toType));
  1875. const auto toSize = hlsl::GetHLSLVecSize(toType);
  1876. const uint32_t composite = doExpr(subExpr);
  1877. llvm::SmallVector<uint32_t, 4> elements;
  1878. for (uint32_t i = 0; i < toSize; ++i) {
  1879. elements.push_back(
  1880. theBuilder.createCompositeExtract(elemTypeId, composite, {i}));
  1881. }
  1882. auto valueId = elements.front();
  1883. if (toSize > 1)
  1884. valueId = theBuilder.createCompositeConstruct(toVecTypeId, elements);
  1885. return SpirvEvalInfo(valueId).setRValue();
  1886. }
  1887. case CastKind::CK_HLSLVectorToScalarCast: {
  1888. // The underlying should already be a vector of size 1.
  1889. assert(hlsl::GetHLSLVecSize(subExprType) == 1);
  1890. return doExpr(subExpr);
  1891. }
  1892. case CastKind::CK_HLSLVectorToMatrixCast: {
  1893. // If target type is already an 1xN matrix type, we just return the
  1894. // underlying vector.
  1895. if (TypeTranslator::is1xNMatrix(toType))
  1896. return doExpr(subExpr);
  1897. // A vector can have no more than 4 elements. The only remaining case
  1898. // is casting from size-4 vector to size-2-by-2 matrix.
  1899. const auto vec = loadIfGLValue(subExpr);
  1900. QualType elemType = {};
  1901. uint32_t rowCount = 0, colCount = 0;
  1902. const bool isMat =
  1903. TypeTranslator::isMxNMatrix(toType, &elemType, &rowCount, &colCount);
  1904. assert(isMat && rowCount == 2 && colCount == 2);
  1905. uint32_t vec2Type =
  1906. theBuilder.getVecType(typeTranslator.translateType(elemType), 2);
  1907. const auto subVec1 =
  1908. theBuilder.createVectorShuffle(vec2Type, vec, vec, {0, 1});
  1909. const auto subVec2 =
  1910. theBuilder.createVectorShuffle(vec2Type, vec, vec, {2, 3});
  1911. const auto mat = theBuilder.createCompositeConstruct(
  1912. theBuilder.getMatType(elemType, vec2Type, 2), {subVec1, subVec2});
  1913. return SpirvEvalInfo(mat).setRValue();
  1914. }
  1915. case CastKind::CK_HLSLMatrixSplat: {
  1916. // From scalar to matrix
  1917. uint32_t rowCount = 0, colCount = 0;
  1918. hlsl::GetHLSLMatRowColCount(toType, rowCount, colCount);
  1919. // Handle degenerated cases first
  1920. if (rowCount == 1 && colCount == 1)
  1921. return doExpr(subExpr);
  1922. if (colCount == 1)
  1923. return createVectorSplat(subExpr, rowCount);
  1924. const auto vecSplat = createVectorSplat(subExpr, colCount);
  1925. if (rowCount == 1)
  1926. return vecSplat;
  1927. const uint32_t matType = typeTranslator.translateType(toType);
  1928. llvm::SmallVector<uint32_t, 4> vectors(size_t(rowCount), vecSplat);
  1929. if (vecSplat.isConstant()) {
  1930. const auto valueId = theBuilder.getConstantComposite(matType, vectors);
  1931. return SpirvEvalInfo(valueId).setConstant().setRValue();
  1932. } else {
  1933. const auto valueId =
  1934. theBuilder.createCompositeConstruct(matType, vectors);
  1935. return SpirvEvalInfo(valueId).setRValue();
  1936. }
  1937. }
  1938. case CastKind::CK_HLSLMatrixTruncationCast: {
  1939. const QualType srcType = subExprType;
  1940. const uint32_t srcId = doExpr(subExpr);
  1941. const QualType elemType = hlsl::GetHLSLMatElementType(srcType);
  1942. const uint32_t dstTypeId = typeTranslator.translateType(toType);
  1943. llvm::SmallVector<uint32_t, 4> indexes;
  1944. // It is possible that the source matrix is in fact a vector.
  1945. // For example: Truncate float1x3 --> float1x2.
  1946. // The front-end disallows float1x3 --> float2x1.
  1947. {
  1948. uint32_t srcVecSize = 0, dstVecSize = 0;
  1949. if (TypeTranslator::isVectorType(srcType, nullptr, &srcVecSize) &&
  1950. TypeTranslator::isVectorType(toType, nullptr, &dstVecSize)) {
  1951. for (uint32_t i = 0; i < dstVecSize; ++i)
  1952. indexes.push_back(i);
  1953. const auto valId =
  1954. theBuilder.createVectorShuffle(dstTypeId, srcId, srcId, indexes);
  1955. return SpirvEvalInfo(valId).setRValue();
  1956. }
  1957. }
  1958. uint32_t srcRows = 0, srcCols = 0, dstRows = 0, dstCols = 0;
  1959. hlsl::GetHLSLMatRowColCount(srcType, srcRows, srcCols);
  1960. hlsl::GetHLSLMatRowColCount(toType, dstRows, dstCols);
  1961. const uint32_t elemTypeId = typeTranslator.translateType(elemType);
  1962. const uint32_t srcRowType = theBuilder.getVecType(elemTypeId, srcCols);
  1963. // Indexes to pass to OpVectorShuffle
  1964. for (uint32_t i = 0; i < dstCols; ++i)
  1965. indexes.push_back(i);
  1966. llvm::SmallVector<uint32_t, 4> extractedVecs;
  1967. for (uint32_t row = 0; row < dstRows; ++row) {
  1968. // Extract a row
  1969. uint32_t rowId =
  1970. theBuilder.createCompositeExtract(srcRowType, srcId, {row});
  1971. // Extract the necessary columns from that row.
  1972. // The front-end ensures dstCols <= srcCols.
  1973. // If dstCols equals srcCols, we can use the whole row directly.
  1974. if (dstCols == 1) {
  1975. rowId = theBuilder.createCompositeExtract(elemTypeId, rowId, {0});
  1976. } else if (dstCols < srcCols) {
  1977. rowId = theBuilder.createVectorShuffle(
  1978. theBuilder.getVecType(elemTypeId, dstCols), rowId, rowId, indexes);
  1979. }
  1980. extractedVecs.push_back(rowId);
  1981. }
  1982. uint32_t valId = extractedVecs.front();
  1983. if (extractedVecs.size() > 1) {
  1984. valId = theBuilder.createCompositeConstruct(
  1985. typeTranslator.translateType(toType), extractedVecs);
  1986. }
  1987. return SpirvEvalInfo(valId).setRValue();
  1988. }
  1989. case CastKind::CK_HLSLMatrixToScalarCast: {
  1990. // The underlying should already be a matrix of 1x1.
  1991. assert(TypeTranslator::is1x1Matrix(subExprType));
  1992. return doExpr(subExpr);
  1993. }
  1994. case CastKind::CK_HLSLMatrixToVectorCast: {
  1995. // The underlying should already be a matrix of 1xN.
  1996. assert(TypeTranslator::is1xNMatrix(subExprType) ||
  1997. TypeTranslator::isMx1Matrix(subExprType));
  1998. return doExpr(subExpr);
  1999. }
  2000. case CastKind::CK_FunctionToPointerDecay:
  2001. // Just need to return the function id
  2002. return doExpr(subExpr);
  2003. case CastKind::CK_FlatConversion: {
  2004. uint32_t subExprId = 0;
  2005. QualType evalType = subExprType;
  2006. // Optimization: we can use OpConstantNull for cases where we want to
  2007. // initialize an entire data structure to zeros.
  2008. if (evaluatesToConstZero(subExpr, astContext)) {
  2009. subExprId =
  2010. theBuilder.getConstantNull(typeTranslator.translateType(toType));
  2011. return SpirvEvalInfo(subExprId).setRValue().setConstant();
  2012. }
  2013. TypeTranslator::LiteralTypeHint hint(typeTranslator);
  2014. // Try to evaluate float literals as float rather than double.
  2015. if (const auto *floatLiteral = dyn_cast<FloatingLiteral>(subExpr)) {
  2016. subExprId = tryToEvaluateAsFloat32(floatLiteral->getValue());
  2017. if (subExprId)
  2018. evalType = astContext.FloatTy;
  2019. }
  2020. // Evaluate 'literal float' initializer type as float rather than double.
  2021. // TODO: This could result in rounding error if the initializer is a
  2022. // non-literal expression that requires larger than 32 bits and has the
  2023. // 'literal float' type.
  2024. else if (subExprType->isSpecificBuiltinType(BuiltinType::LitFloat)) {
  2025. evalType = astContext.FloatTy;
  2026. hint.setHint(astContext.FloatTy);
  2027. }
  2028. // Try to evaluate integer literals as 32-bit int rather than 64-bit int.
  2029. else if (const auto *intLiteral = dyn_cast<IntegerLiteral>(subExpr)) {
  2030. const bool isSigned = subExprType->isSignedIntegerType();
  2031. subExprId = tryToEvaluateAsInt32(intLiteral->getValue(), isSigned);
  2032. if (subExprId)
  2033. evalType = isSigned ? astContext.IntTy : astContext.UnsignedIntTy;
  2034. }
  2035. // For assigning one array instance to another one with the same array type
  2036. // (regardless of constness and literalness), the rhs will be wrapped in a
  2037. // FlatConversion:
  2038. // |- <lhs>
  2039. // `- ImplicitCastExpr <FlatConversion>
  2040. // `- ImplicitCastExpr <LValueToRValue>
  2041. // `- <rhs>
  2042. // This FlatConversion does not affect CodeGen, so that we can ignore it.
  2043. else if (subExprType->isArrayType() &&
  2044. typeTranslator.isSameType(expr->getType(), subExprType)) {
  2045. return doExpr(subExpr);
  2046. }
  2047. if (!subExprId)
  2048. subExprId = doExpr(subExpr);
  2049. const auto valId =
  2050. processFlatConversion(toType, evalType, subExprId, expr->getExprLoc());
  2051. return SpirvEvalInfo(valId).setRValue();
  2052. }
  2053. case CastKind::CK_UncheckedDerivedToBase:
  2054. case CastKind::CK_HLSLDerivedToBase: {
  2055. // Find the index sequence of the base to which we are casting
  2056. llvm::SmallVector<uint32_t, 4> baseIndices;
  2057. getBaseClassIndices(expr, &baseIndices);
  2058. // Turn them in to SPIR-V constants
  2059. for (uint32_t i = 0; i < baseIndices.size(); ++i)
  2060. baseIndices[i] = theBuilder.getConstantUint32(baseIndices[i]);
  2061. auto derivedInfo = doExpr(subExpr);
  2062. return turnIntoElementPtr(derivedInfo, expr->getType(), baseIndices);
  2063. }
  2064. default:
  2065. emitError("implicit cast kind '%0' unimplemented", expr->getExprLoc())
  2066. << expr->getCastKindName() << expr->getSourceRange();
  2067. expr->dump();
  2068. return 0;
  2069. }
  2070. }
  2071. uint32_t SPIRVEmitter::processFlatConversion(const QualType type,
  2072. const QualType initType,
  2073. const uint32_t initId,
  2074. SourceLocation srcLoc) {
  2075. // Try to translate the canonical type first
  2076. const auto canonicalType = type.getCanonicalType();
  2077. if (canonicalType != type)
  2078. return processFlatConversion(canonicalType, initType, initId, srcLoc);
  2079. // Primitive types
  2080. {
  2081. QualType ty = {};
  2082. if (TypeTranslator::isScalarType(type, &ty)) {
  2083. if (const auto *builtinType = ty->getAs<BuiltinType>()) {
  2084. switch (builtinType->getKind()) {
  2085. case BuiltinType::Void: {
  2086. emitError("cannot create a constant of void type", srcLoc);
  2087. return 0;
  2088. }
  2089. case BuiltinType::Bool:
  2090. return castToBool(initId, initType, ty);
  2091. // Target type is an integer variant.
  2092. case BuiltinType::Int:
  2093. case BuiltinType::Short:
  2094. case BuiltinType::Min12Int:
  2095. case BuiltinType::UShort:
  2096. case BuiltinType::UInt:
  2097. case BuiltinType::Long:
  2098. case BuiltinType::LongLong:
  2099. case BuiltinType::ULong:
  2100. case BuiltinType::ULongLong:
  2101. return castToInt(initId, initType, ty, srcLoc);
  2102. // Target type is a float variant.
  2103. case BuiltinType::Double:
  2104. case BuiltinType::Float:
  2105. case BuiltinType::Half:
  2106. case BuiltinType::Min10Float:
  2107. return castToFloat(initId, initType, ty, srcLoc);
  2108. default:
  2109. emitError("flat conversion of type %0 unimplemented", srcLoc)
  2110. << builtinType->getTypeClassName();
  2111. return 0;
  2112. }
  2113. }
  2114. }
  2115. }
  2116. // Vector types
  2117. {
  2118. QualType elemType = {};
  2119. uint32_t elemCount = {};
  2120. if (TypeTranslator::isVectorType(type, &elemType, &elemCount)) {
  2121. const uint32_t elemId =
  2122. processFlatConversion(elemType, initType, initId, srcLoc);
  2123. llvm::SmallVector<uint32_t, 4> constituents(size_t(elemCount), elemId);
  2124. return theBuilder.createCompositeConstruct(
  2125. typeTranslator.translateType(type), constituents);
  2126. }
  2127. }
  2128. // Matrix types
  2129. {
  2130. QualType elemType = {};
  2131. uint32_t rowCount = 0, colCount = 0;
  2132. if (TypeTranslator::isMxNMatrix(type, &elemType, &rowCount, &colCount)) {
  2133. // By default HLSL matrices are row major, while SPIR-V matrices are
  2134. // column major. We are mapping what HLSL semantically mean a row into a
  2135. // column here.
  2136. const uint32_t vecType = theBuilder.getVecType(
  2137. typeTranslator.translateType(elemType), colCount);
  2138. const uint32_t elemId =
  2139. processFlatConversion(elemType, initType, initId, srcLoc);
  2140. const llvm::SmallVector<uint32_t, 4> constituents(size_t(colCount),
  2141. elemId);
  2142. const uint32_t colId =
  2143. theBuilder.createCompositeConstruct(vecType, constituents);
  2144. const llvm::SmallVector<uint32_t, 4> rows(size_t(rowCount), colId);
  2145. return theBuilder.createCompositeConstruct(
  2146. typeTranslator.translateType(type), rows);
  2147. }
  2148. }
  2149. // Struct type
  2150. if (const auto *structType = type->getAs<RecordType>()) {
  2151. const auto *decl = structType->getDecl();
  2152. llvm::SmallVector<uint32_t, 4> fields;
  2153. for (const auto *field : decl->fields()) {
  2154. // There is a special case for FlatConversion. If T is a struct with only
  2155. // one member, S, then (T)<an-instance-of-S> is allowed, which essentially
  2156. // constructs a new T instance using the instance of S as its only member.
  2157. // Check whether we are handling that case here first.
  2158. if (field->getType().getCanonicalType() == initType.getCanonicalType()) {
  2159. fields.push_back(initId);
  2160. } else {
  2161. fields.push_back(
  2162. processFlatConversion(field->getType(), initType, initId, srcLoc));
  2163. }
  2164. }
  2165. return theBuilder.createCompositeConstruct(
  2166. typeTranslator.translateType(type), fields);
  2167. }
  2168. // Array type
  2169. if (const auto *arrayType = astContext.getAsConstantArrayType(type)) {
  2170. const auto size =
  2171. static_cast<uint32_t>(arrayType->getSize().getZExtValue());
  2172. const uint32_t elemId = processFlatConversion(arrayType->getElementType(),
  2173. initType, initId, srcLoc);
  2174. llvm::SmallVector<uint32_t, 4> constituents(size_t(size), elemId);
  2175. return theBuilder.createCompositeConstruct(
  2176. typeTranslator.translateType(type), constituents);
  2177. }
  2178. emitError("flat conversion of type %0 unimplemented", {})
  2179. << type->getTypeClassName();
  2180. type->dump();
  2181. return 0;
  2182. }
  2183. SpirvEvalInfo
  2184. SPIRVEmitter::doCompoundAssignOperator(const CompoundAssignOperator *expr) {
  2185. const auto opcode = expr->getOpcode();
  2186. // Try to optimize floatMxN *= float and floatN *= float case
  2187. if (opcode == BO_MulAssign) {
  2188. if (SpirvEvalInfo result = tryToGenFloatMatrixScale(expr))
  2189. return result;
  2190. if (SpirvEvalInfo result = tryToGenFloatVectorScale(expr))
  2191. return result;
  2192. }
  2193. const auto *rhs = expr->getRHS();
  2194. const auto *lhs = expr->getLHS();
  2195. SpirvEvalInfo lhsPtr = 0;
  2196. const auto result =
  2197. processBinaryOp(lhs, rhs, opcode, expr->getComputationLHSType(),
  2198. expr->getType(), expr->getSourceRange(), &lhsPtr);
  2199. return processAssignment(lhs, result, true, lhsPtr);
  2200. }
  2201. SpirvEvalInfo
  2202. SPIRVEmitter::doConditionalOperator(const ConditionalOperator *expr) {
  2203. const auto type = expr->getType();
  2204. // Enhancement for special case when the ConditionalOperator return type is a
  2205. // literal type. For example:
  2206. //
  2207. // float a = cond ? 1 : 2;
  2208. // int b = cond ? 1.5 : 2.5;
  2209. //
  2210. // There will be no indications about whether '1' and '2' should be used as
  2211. // 32-bit or 64-bit integers. Similarly, there will be no indication about
  2212. // whether '1.5' and '2.5' should be used as 32-bit or 64-bit floats.
  2213. //
  2214. // We want to avoid using 64-bit int and 64-bit float as much as possible.
  2215. //
  2216. // Note that if the literal is in fact large enough that it can't be
  2217. // represented in 32 bits (e.g. integer larger than 3e+9), we should *not*
  2218. // provide a hint.
  2219. TypeTranslator::LiteralTypeHint hint(typeTranslator);
  2220. const bool isLitInt = type->isSpecificBuiltinType(BuiltinType::LitInt);
  2221. const bool isLitFloat = type->isSpecificBuiltinType(BuiltinType::LitFloat);
  2222. // Return type of ConditionalOperator is a 'literal int' or 'literal float'
  2223. if (isLitInt || isLitFloat) {
  2224. // There is no hint about the intended usage of the literal type.
  2225. if (typeTranslator.getIntendedLiteralType(type) == type) {
  2226. // If either branch is a literal that is larger than 32-bits, do not
  2227. // provide a hint.
  2228. if (!isLiteralLargerThan32Bits(expr->getTrueExpr()) &&
  2229. !isLiteralLargerThan32Bits(expr->getFalseExpr())) {
  2230. if (isLitInt)
  2231. hint.setHint(astContext.IntTy);
  2232. else if (isLitFloat)
  2233. hint.setHint(astContext.FloatTy);
  2234. }
  2235. }
  2236. }
  2237. // According to HLSL doc, all sides of the ?: expression are always
  2238. // evaluated.
  2239. const uint32_t typeId = typeTranslator.translateType(type);
  2240. // If we are selecting between two SampleState objects, none of the three
  2241. // operands has a LValueToRValue implicit cast.
  2242. uint32_t condition = loadIfGLValue(expr->getCond());
  2243. const auto trueBranch = loadIfGLValue(expr->getTrueExpr());
  2244. const auto falseBranch = loadIfGLValue(expr->getFalseExpr());
  2245. // For cases where the return type is a scalar or a vector, we can use
  2246. // OpSelect to choose between the two. OpSelect's return type must be either
  2247. // scalar or vector.
  2248. if (TypeTranslator::isScalarType(type) ||
  2249. TypeTranslator::isVectorType(type)) {
  2250. // The SPIR-V OpSelect instruction must have a selection argument that is
  2251. // the same size as the return type. If the return type is a vector, the
  2252. // selection must be a vector of booleans (one per output component).
  2253. uint32_t count = 0;
  2254. if (TypeTranslator::isVectorType(expr->getType(), nullptr, &count) &&
  2255. !TypeTranslator::isVectorType(expr->getCond()->getType())) {
  2256. const uint32_t condVecType =
  2257. theBuilder.getVecType(theBuilder.getBoolType(), count);
  2258. const llvm::SmallVector<uint32_t, 4> components(size_t(count), condition);
  2259. condition = theBuilder.createCompositeConstruct(condVecType, components);
  2260. }
  2261. auto valueId =
  2262. theBuilder.createSelect(typeId, condition, trueBranch, falseBranch);
  2263. return SpirvEvalInfo(valueId).setRValue();
  2264. }
  2265. // If we can't use OpSelect, we need to create if-else control flow.
  2266. const uint32_t tempVar = theBuilder.addFnVar(typeId, "temp.var.ternary");
  2267. const uint32_t thenBB = theBuilder.createBasicBlock("if.true");
  2268. const uint32_t mergeBB = theBuilder.createBasicBlock("if.merge");
  2269. const uint32_t elseBB = theBuilder.createBasicBlock("if.false");
  2270. // Create the branch instruction. This will end the current basic block.
  2271. theBuilder.createConditionalBranch(condition, thenBB, elseBB, mergeBB);
  2272. theBuilder.addSuccessor(thenBB);
  2273. theBuilder.addSuccessor(elseBB);
  2274. theBuilder.setMergeTarget(mergeBB);
  2275. // Handle the then branch
  2276. theBuilder.setInsertPoint(thenBB);
  2277. theBuilder.createStore(tempVar, trueBranch);
  2278. theBuilder.createBranch(mergeBB);
  2279. theBuilder.addSuccessor(mergeBB);
  2280. // Handle the else branch
  2281. theBuilder.setInsertPoint(elseBB);
  2282. theBuilder.createStore(tempVar, falseBranch);
  2283. theBuilder.createBranch(mergeBB);
  2284. theBuilder.addSuccessor(mergeBB);
  2285. // From now on, emit instructions into the merge block.
  2286. theBuilder.setInsertPoint(mergeBB);
  2287. return SpirvEvalInfo(theBuilder.createLoad(typeId, tempVar)).setRValue();
  2288. }
  2289. uint32_t SPIRVEmitter::processByteAddressBufferStructuredBufferGetDimensions(
  2290. const CXXMemberCallExpr *expr) {
  2291. const auto *object = expr->getImplicitObjectArgument();
  2292. const auto objectId = loadIfAliasVarRef(object);
  2293. const auto type = object->getType();
  2294. const bool isByteAddressBuffer = TypeTranslator::isByteAddressBuffer(type) ||
  2295. TypeTranslator::isRWByteAddressBuffer(type);
  2296. const bool isStructuredBuffer =
  2297. TypeTranslator::isStructuredBuffer(type) ||
  2298. TypeTranslator::isAppendStructuredBuffer(type) ||
  2299. TypeTranslator::isConsumeStructuredBuffer(type);
  2300. assert(isByteAddressBuffer || isStructuredBuffer);
  2301. // (RW)ByteAddressBuffers/(RW)StructuredBuffers are represented as a structure
  2302. // with only one member that is a runtime array. We need to perform
  2303. // OpArrayLength on member 0.
  2304. const auto uintType = theBuilder.getUint32Type();
  2305. uint32_t length =
  2306. theBuilder.createBinaryOp(spv::Op::OpArrayLength, uintType, objectId, 0);
  2307. // For (RW)ByteAddressBuffers, GetDimensions() must return the array length
  2308. // in bytes, but OpArrayLength returns the number of uints in the runtime
  2309. // array. Therefore we must multiply the results by 4.
  2310. if (isByteAddressBuffer) {
  2311. length = theBuilder.createBinaryOp(spv::Op::OpIMul, uintType, length,
  2312. theBuilder.getConstantUint32(4u));
  2313. }
  2314. theBuilder.createStore(doExpr(expr->getArg(0)), length);
  2315. if (isStructuredBuffer) {
  2316. // For (RW)StructuredBuffer, the stride of the runtime array (which is the
  2317. // size of the struct) must also be written to the second argument.
  2318. uint32_t size = 0, stride = 0;
  2319. std::tie(std::ignore, size) = typeTranslator.getAlignmentAndSize(
  2320. type, spirvOptions.sBufferLayoutRule, &stride);
  2321. const auto sizeId = theBuilder.getConstantUint32(size);
  2322. theBuilder.createStore(doExpr(expr->getArg(1)), sizeId);
  2323. }
  2324. return 0;
  2325. }
  2326. uint32_t SPIRVEmitter::processRWByteAddressBufferAtomicMethods(
  2327. hlsl::IntrinsicOp opcode, const CXXMemberCallExpr *expr) {
  2328. // The signature of RWByteAddressBuffer atomic methods are largely:
  2329. // void Interlocked*(in UINT dest, in UINT value);
  2330. // void Interlocked*(in UINT dest, in UINT value, out UINT original_value);
  2331. const auto *object = expr->getImplicitObjectArgument();
  2332. const auto objectInfo = loadIfAliasVarRef(object);
  2333. const auto uintType = theBuilder.getUint32Type();
  2334. const uint32_t zero = theBuilder.getConstantUint32(0);
  2335. const uint32_t offset = doExpr(expr->getArg(0));
  2336. // Right shift by 2 to convert the byte offset to uint32_t offset
  2337. const uint32_t address =
  2338. theBuilder.createBinaryOp(spv::Op::OpShiftRightLogical, uintType, offset,
  2339. theBuilder.getConstantUint32(2));
  2340. const auto ptrType =
  2341. theBuilder.getPointerType(uintType, objectInfo.getStorageClass());
  2342. const uint32_t ptr =
  2343. theBuilder.createAccessChain(ptrType, objectInfo, {zero, address});
  2344. const uint32_t scope = theBuilder.getConstantUint32(1); // Device
  2345. const bool isCompareExchange =
  2346. opcode == hlsl::IntrinsicOp::MOP_InterlockedCompareExchange;
  2347. const bool isCompareStore =
  2348. opcode == hlsl::IntrinsicOp::MOP_InterlockedCompareStore;
  2349. if (isCompareExchange || isCompareStore) {
  2350. const uint32_t comparator = doExpr(expr->getArg(1));
  2351. const uint32_t originalVal = theBuilder.createAtomicCompareExchange(
  2352. uintType, ptr, scope, zero, zero, doExpr(expr->getArg(2)), comparator);
  2353. if (isCompareExchange)
  2354. theBuilder.createStore(doExpr(expr->getArg(3)), originalVal);
  2355. } else {
  2356. const uint32_t value = doExpr(expr->getArg(1));
  2357. const uint32_t originalVal = theBuilder.createAtomicOp(
  2358. translateAtomicHlslOpcodeToSpirvOpcode(opcode), uintType, ptr, scope,
  2359. zero, value);
  2360. if (expr->getNumArgs() > 2)
  2361. theBuilder.createStore(doExpr(expr->getArg(2)), originalVal);
  2362. }
  2363. return 0;
  2364. }
  2365. uint32_t SPIRVEmitter::processGetSamplePosition(const CXXMemberCallExpr *expr) {
  2366. const auto *object = expr->getImplicitObjectArgument()->IgnoreParens();
  2367. const auto sampleCount = theBuilder.createUnaryOp(
  2368. spv::Op::OpImageQuerySamples, theBuilder.getUint32Type(),
  2369. loadIfGLValue(object));
  2370. emitWarning(
  2371. "GetSamplePosition only supports standard sample settings with 1, 2, 4, "
  2372. "8, or 16 samples and will return float2(0, 0) for other cases",
  2373. expr->getCallee()->getExprLoc());
  2374. return emitGetSamplePosition(sampleCount, doExpr(expr->getArg(0)));
  2375. }
  2376. SpirvEvalInfo SPIRVEmitter::processSubpassLoad(const CXXMemberCallExpr *expr) {
  2377. const auto *object = expr->getImplicitObjectArgument()->IgnoreParens();
  2378. const uint32_t sample = expr->getNumArgs() == 1 ? doExpr(expr->getArg(0)) : 0;
  2379. const uint32_t zero = theBuilder.getConstantInt32(0);
  2380. const uint32_t location = theBuilder.getConstantComposite(
  2381. theBuilder.getVecType(theBuilder.getInt32Type(), 2), {zero, zero});
  2382. return processBufferTextureLoad(object, location, /*constOffset*/ 0,
  2383. /*varOffset*/ 0, /*lod*/ sample,
  2384. /*residencyCode*/ 0);
  2385. }
  2386. uint32_t
  2387. SPIRVEmitter::processBufferTextureGetDimensions(const CXXMemberCallExpr *expr) {
  2388. const auto *object = expr->getImplicitObjectArgument();
  2389. const auto objectId = loadIfGLValue(object);
  2390. const auto type = object->getType();
  2391. const auto *recType = type->getAs<RecordType>();
  2392. assert(recType);
  2393. const auto typeName = recType->getDecl()->getName();
  2394. const auto numArgs = expr->getNumArgs();
  2395. const Expr *mipLevel = nullptr, *numLevels = nullptr, *numSamples = nullptr;
  2396. assert(TypeTranslator::isTexture(type) || TypeTranslator::isRWTexture(type) ||
  2397. TypeTranslator::isBuffer(type) || TypeTranslator::isRWBuffer(type));
  2398. // For Texture1D, arguments are either:
  2399. // a) width
  2400. // b) MipLevel, width, NumLevels
  2401. // For Texture1DArray, arguments are either:
  2402. // a) width, elements
  2403. // b) MipLevel, width, elements, NumLevels
  2404. // For Texture2D, arguments are either:
  2405. // a) width, height
  2406. // b) MipLevel, width, height, NumLevels
  2407. // For Texture2DArray, arguments are either:
  2408. // a) width, height, elements
  2409. // b) MipLevel, width, height, elements, NumLevels
  2410. // For Texture3D, arguments are either:
  2411. // a) width, height, depth
  2412. // b) MipLevel, width, height, depth, NumLevels
  2413. // For Texture2DMS, arguments are: width, height, NumSamples
  2414. // For Texture2DMSArray, arguments are: width, height, elements, NumSamples
  2415. // For TextureCube, arguments are either:
  2416. // a) width, height
  2417. // b) MipLevel, width, height, NumLevels
  2418. // For TextureCubeArray, arguments are either:
  2419. // a) width, height, elements
  2420. // b) MipLevel, width, height, elements, NumLevels
  2421. // Note: SPIR-V Spec requires return type of OpImageQuerySize(Lod) to be a
  2422. // scalar/vector of integers. SPIR-V Spec also requires return type of
  2423. // OpImageQueryLevels and OpImageQuerySamples to be scalar integers.
  2424. // The HLSL methods, however, have overloaded functions which have float
  2425. // output arguments. Since the AST naturally won't have casting AST nodes for
  2426. // such cases, we'll have to perform the cast ourselves.
  2427. const auto storeToOutputArg = [this](const Expr *outputArg,
  2428. uint32_t toStoreId) {
  2429. const auto outputArgType = outputArg->getType();
  2430. // Perform cast to float if necessary.
  2431. if (isFloatOrVecMatOfFloatType(outputArgType)) {
  2432. toStoreId = theBuilder.createUnaryOp(
  2433. spv::Op::OpConvertUToF, typeTranslator.translateType(outputArgType),
  2434. toStoreId);
  2435. }
  2436. theBuilder.createStore(doExpr(outputArg), toStoreId);
  2437. };
  2438. if ((typeName == "Texture1D" && numArgs > 1) ||
  2439. (typeName == "Texture2D" && numArgs > 2) ||
  2440. (typeName == "TextureCube" && numArgs > 2) ||
  2441. (typeName == "Texture3D" && numArgs > 3) ||
  2442. (typeName == "Texture1DArray" && numArgs > 2) ||
  2443. (typeName == "TextureCubeArray" && numArgs > 3) ||
  2444. (typeName == "Texture2DArray" && numArgs > 3)) {
  2445. mipLevel = expr->getArg(0);
  2446. numLevels = expr->getArg(numArgs - 1);
  2447. }
  2448. if (TypeTranslator::isTextureMS(type)) {
  2449. numSamples = expr->getArg(numArgs - 1);
  2450. }
  2451. uint32_t querySize = numArgs;
  2452. // If numLevels arg is present, mipLevel must also be present. These are not
  2453. // queried via ImageQuerySizeLod.
  2454. if (numLevels)
  2455. querySize -= 2;
  2456. // If numLevels arg is present, mipLevel must also be present.
  2457. else if (numSamples)
  2458. querySize -= 1;
  2459. const uint32_t uintId = theBuilder.getUint32Type();
  2460. const uint32_t resultTypeId =
  2461. querySize == 1 ? uintId : theBuilder.getVecType(uintId, querySize);
  2462. // Only Texture types use ImageQuerySizeLod.
  2463. // TextureMS, RWTexture, Buffers, RWBuffers use ImageQuerySize.
  2464. uint32_t lod = 0;
  2465. if (TypeTranslator::isTexture(type) && !numSamples) {
  2466. if (mipLevel) {
  2467. // For Texture types when mipLevel argument is present.
  2468. lod = doExpr(mipLevel);
  2469. } else {
  2470. // For Texture types when mipLevel argument is omitted.
  2471. lod = theBuilder.getConstantInt32(0);
  2472. }
  2473. }
  2474. const uint32_t query =
  2475. lod ? theBuilder.createBinaryOp(spv::Op::OpImageQuerySizeLod,
  2476. resultTypeId, objectId, lod)
  2477. : theBuilder.createUnaryOp(spv::Op::OpImageQuerySize, resultTypeId,
  2478. objectId);
  2479. if (querySize == 1) {
  2480. const uint32_t argIndex = mipLevel ? 1 : 0;
  2481. storeToOutputArg(expr->getArg(argIndex), query);
  2482. } else {
  2483. for (uint32_t i = 0; i < querySize; ++i) {
  2484. const uint32_t component =
  2485. theBuilder.createCompositeExtract(uintId, query, {i});
  2486. // If the first arg is the mipmap level, we must write the results
  2487. // starting from Arg(i+1), not Arg(i).
  2488. const uint32_t argIndex = mipLevel ? i + 1 : i;
  2489. storeToOutputArg(expr->getArg(argIndex), component);
  2490. }
  2491. }
  2492. if (numLevels || numSamples) {
  2493. const Expr *numLevelsSamplesArg = numLevels ? numLevels : numSamples;
  2494. const spv::Op opcode =
  2495. numLevels ? spv::Op::OpImageQueryLevels : spv::Op::OpImageQuerySamples;
  2496. const uint32_t numLevelsSamplesQuery =
  2497. theBuilder.createUnaryOp(opcode, uintId, objectId);
  2498. storeToOutputArg(numLevelsSamplesArg, numLevelsSamplesQuery);
  2499. }
  2500. return 0;
  2501. }
  2502. uint32_t
  2503. SPIRVEmitter::processTextureLevelOfDetail(const CXXMemberCallExpr *expr) {
  2504. // Possible signatures are as follows:
  2505. // Texture1D(Array).CalculateLevelOfDetail(SamplerState S, float x);
  2506. // Texture2D(Array).CalculateLevelOfDetail(SamplerState S, float2 xy);
  2507. // TextureCube(Array).CalculateLevelOfDetail(SamplerState S, float3 xyz);
  2508. // Texture3D.CalculateLevelOfDetail(SamplerState S, float3 xyz);
  2509. // Return type is always a single float (LOD).
  2510. assert(expr->getNumArgs() == 2u);
  2511. const auto *object = expr->getImplicitObjectArgument();
  2512. const uint32_t objectId = loadIfGLValue(object);
  2513. const uint32_t samplerState = doExpr(expr->getArg(0));
  2514. const uint32_t coordinate = doExpr(expr->getArg(1));
  2515. const uint32_t sampledImageType = theBuilder.getSampledImageType(
  2516. typeTranslator.translateType(object->getType()));
  2517. const uint32_t sampledImage = theBuilder.createBinaryOp(
  2518. spv::Op::OpSampledImage, sampledImageType, objectId, samplerState);
  2519. // The result type of OpImageQueryLod must be a float2.
  2520. const uint32_t queryResultType =
  2521. theBuilder.getVecType(theBuilder.getFloat32Type(), 2u);
  2522. const uint32_t query = theBuilder.createBinaryOp(
  2523. spv::Op::OpImageQueryLod, queryResultType, sampledImage, coordinate);
  2524. // The first component of the float2 contains the mipmap array layer.
  2525. return theBuilder.createCompositeExtract(theBuilder.getFloat32Type(), query,
  2526. {0});
  2527. }
  2528. uint32_t SPIRVEmitter::processTextureGatherRGBACmpRGBA(
  2529. const CXXMemberCallExpr *expr, const bool isCmp, const uint32_t component) {
  2530. // Parameters for .Gather{Red|Green|Blue|Alpha}() are one of the following
  2531. // two sets:
  2532. // * SamplerState s, float2 location, int2 offset
  2533. // * SamplerState s, float2 location, int2 offset0, int2 offset1,
  2534. // int offset2, int2 offset3
  2535. //
  2536. // An additional 'out uint status' parameter can appear in both of the above.
  2537. //
  2538. // Parameters for .GatherCmp{Red|Green|Blue|Alpha}() are one of the following
  2539. // two sets:
  2540. // * SamplerState s, float2 location, float compare_value, int2 offset
  2541. // * SamplerState s, float2 location, float compare_value, int2 offset1,
  2542. // int2 offset2, int2 offset3, int2 offset4
  2543. //
  2544. // An additional 'out uint status' parameter can appear in both of the above.
  2545. //
  2546. // TextureCube's signature is somewhat different from the rest.
  2547. // Parameters for .Gather{Red|Green|Blue|Alpha}() for TextureCube are:
  2548. // * SamplerState s, float2 location, out uint status
  2549. // Parameters for .GatherCmp{Red|Green|Blue|Alpha}() for TextureCube are:
  2550. // * SamplerState s, float2 location, float compare_value, out uint status
  2551. //
  2552. // Return type is always a 4-component vector.
  2553. const FunctionDecl *callee = expr->getDirectCallee();
  2554. const auto numArgs = expr->getNumArgs();
  2555. const auto *imageExpr = expr->getImplicitObjectArgument();
  2556. const QualType imageType = imageExpr->getType();
  2557. const auto imageTypeId = typeTranslator.translateType(imageType);
  2558. const auto retTypeId = typeTranslator.translateType(callee->getReturnType());
  2559. // If the last arg is an unsigned integer, it must be the status.
  2560. const bool hasStatusArg =
  2561. expr->getArg(numArgs - 1)->getType()->isUnsignedIntegerType();
  2562. // Subtract 1 for status arg (if it exists), subtract 1 for compare_value (if
  2563. // it exists), and subtract 2 for SamplerState and location.
  2564. const auto numOffsetArgs = numArgs - hasStatusArg - isCmp - 2;
  2565. // No offset args for TextureCube, 1 or 4 offset args for the rest.
  2566. assert(numOffsetArgs == 0 || numOffsetArgs == 1 || numOffsetArgs == 4);
  2567. const uint32_t image = loadIfGLValue(imageExpr);
  2568. const uint32_t sampler = doExpr(expr->getArg(0));
  2569. const uint32_t coordinate = doExpr(expr->getArg(1));
  2570. const uint32_t compareVal = isCmp ? doExpr(expr->getArg(2)) : 0;
  2571. // Handle offsets (if any).
  2572. bool needsEmulation = false;
  2573. uint32_t constOffset = 0, varOffset = 0, constOffsets = 0;
  2574. if (numOffsetArgs == 1) {
  2575. // The offset arg is not optional.
  2576. handleOffsetInMethodCall(expr, 2 + isCmp, &constOffset, &varOffset);
  2577. } else if (numOffsetArgs == 4) {
  2578. const auto offset0 = tryToEvaluateAsConst(expr->getArg(2 + isCmp));
  2579. const auto offset1 = tryToEvaluateAsConst(expr->getArg(3 + isCmp));
  2580. const auto offset2 = tryToEvaluateAsConst(expr->getArg(4 + isCmp));
  2581. const auto offset3 = tryToEvaluateAsConst(expr->getArg(5 + isCmp));
  2582. // If any of the offsets is not constant, we then need to emulate the call
  2583. // using 4 OpImageGather instructions. Otherwise, we can leverage the
  2584. // ConstOffsets image operand.
  2585. if (offset0 && offset1 && offset2 && offset3) {
  2586. const uint32_t v2i32 =
  2587. theBuilder.getVecType(theBuilder.getInt32Type(), 2);
  2588. const uint32_t offsetType =
  2589. theBuilder.getArrayType(v2i32, theBuilder.getConstantUint32(4));
  2590. constOffsets = theBuilder.getConstantComposite(
  2591. offsetType, {offset0, offset1, offset2, offset3});
  2592. } else {
  2593. needsEmulation = true;
  2594. }
  2595. }
  2596. const auto status = hasStatusArg ? doExpr(expr->getArg(numArgs - 1)) : 0;
  2597. if (needsEmulation) {
  2598. const auto elemType = typeTranslator.translateType(
  2599. hlsl::GetHLSLVecElementType(callee->getReturnType()));
  2600. uint32_t texels[4];
  2601. for (uint32_t i = 0; i < 4; ++i) {
  2602. varOffset = doExpr(expr->getArg(2 + isCmp + i));
  2603. const uint32_t gatherRet = theBuilder.createImageGather(
  2604. retTypeId, imageTypeId, image, sampler, coordinate,
  2605. theBuilder.getConstantInt32(component), compareVal, /*constOffset*/ 0,
  2606. varOffset, /*constOffsets*/ 0, /*sampleNumber*/ 0, status);
  2607. texels[i] = theBuilder.createCompositeExtract(elemType, gatherRet, {i});
  2608. }
  2609. return theBuilder.createCompositeConstruct(
  2610. retTypeId, {texels[0], texels[1], texels[2], texels[3]});
  2611. }
  2612. return theBuilder.createImageGather(
  2613. retTypeId, imageTypeId, image, sampler, coordinate,
  2614. theBuilder.getConstantInt32(component), compareVal, constOffset,
  2615. varOffset, constOffsets, /*sampleNumber*/ 0, status);
  2616. }
  2617. uint32_t SPIRVEmitter::processTextureGatherCmp(const CXXMemberCallExpr *expr) {
  2618. // Signature for Texture2D/Texture2DArray:
  2619. //
  2620. // float4 GatherCmp(
  2621. // in SamplerComparisonState s,
  2622. // in float2 location,
  2623. // in float compare_value
  2624. // [,in int2 offset]
  2625. // [,out uint Status]
  2626. // );
  2627. //
  2628. // Signature for TextureCube/TextureCubeArray:
  2629. //
  2630. // float4 GatherCmp(
  2631. // in SamplerComparisonState s,
  2632. // in float2 location,
  2633. // in float compare_value,
  2634. // out uint Status
  2635. // );
  2636. //
  2637. // Other Texture types do not have the GatherCmp method.
  2638. const FunctionDecl *callee = expr->getDirectCallee();
  2639. const auto numArgs = expr->getNumArgs();
  2640. const bool hasStatusArg =
  2641. expr->getArg(numArgs - 1)->getType()->isUnsignedIntegerType();
  2642. const bool hasOffsetArg = (numArgs == 5) || (numArgs == 4 && !hasStatusArg);
  2643. const auto *imageExpr = expr->getImplicitObjectArgument();
  2644. const uint32_t image = loadIfGLValue(imageExpr);
  2645. const uint32_t sampler = doExpr(expr->getArg(0));
  2646. const uint32_t coordinate = doExpr(expr->getArg(1));
  2647. const uint32_t comparator = doExpr(expr->getArg(2));
  2648. uint32_t constOffset = 0, varOffset = 0;
  2649. if (hasOffsetArg)
  2650. handleOffsetInMethodCall(expr, 3, &constOffset, &varOffset);
  2651. const auto retType = typeTranslator.translateType(callee->getReturnType());
  2652. const auto imageType = typeTranslator.translateType(imageExpr->getType());
  2653. const auto status = hasStatusArg ? doExpr(expr->getArg(numArgs - 1)) : 0;
  2654. return theBuilder.createImageGather(
  2655. retType, imageType, image, sampler, coordinate, /*component*/ 0,
  2656. comparator, constOffset, varOffset, /*constOffsets*/ 0,
  2657. /*sampleNumber*/ 0, status);
  2658. }
  2659. SpirvEvalInfo SPIRVEmitter::processBufferTextureLoad(
  2660. const Expr *object, const uint32_t locationId, uint32_t constOffset,
  2661. uint32_t varOffset, uint32_t lod, uint32_t residencyCode) {
  2662. // Loading for Buffer and RWBuffer translates to an OpImageFetch.
  2663. // The result type of an OpImageFetch must be a vec4 of float or int.
  2664. const auto type = object->getType();
  2665. assert(TypeTranslator::isBuffer(type) || TypeTranslator::isRWBuffer(type) ||
  2666. TypeTranslator::isTexture(type) || TypeTranslator::isRWTexture(type) ||
  2667. TypeTranslator::isSubpassInput(type) ||
  2668. TypeTranslator::isSubpassInputMS(type));
  2669. const bool doFetch =
  2670. TypeTranslator::isBuffer(type) || TypeTranslator::isTexture(type);
  2671. const uint32_t objectId = loadIfGLValue(object);
  2672. // For Texture2DMS and Texture2DMSArray, Sample must be used rather than Lod.
  2673. uint32_t sampleNumber = 0;
  2674. if (TypeTranslator::isTextureMS(type) ||
  2675. TypeTranslator::isSubpassInputMS(type)) {
  2676. sampleNumber = lod;
  2677. lod = 0;
  2678. }
  2679. const auto sampledType = hlsl::GetHLSLResourceResultType(type);
  2680. QualType elemType = sampledType;
  2681. uint32_t elemCount = 1;
  2682. uint32_t elemTypeId = 0;
  2683. (void)TypeTranslator::isVectorType(sampledType, &elemType, &elemCount);
  2684. if (elemType->isFloatingType()) {
  2685. elemTypeId = theBuilder.getFloat32Type();
  2686. } else if (elemType->isSignedIntegerType()) {
  2687. elemTypeId = theBuilder.getInt32Type();
  2688. } else if (elemType->isUnsignedIntegerType()) {
  2689. elemTypeId = theBuilder.getUint32Type();
  2690. } else {
  2691. emitError("buffer/texture type unimplemented", object->getExprLoc());
  2692. return 0;
  2693. }
  2694. // OpImageFetch and OpImageRead can only fetch a vector of 4 elements.
  2695. const uint32_t texelTypeId = theBuilder.getVecType(elemTypeId, 4u);
  2696. const uint32_t texel = theBuilder.createImageFetchOrRead(
  2697. doFetch, texelTypeId, type, objectId, locationId, lod, constOffset,
  2698. varOffset, /*constOffsets*/ 0, sampleNumber, residencyCode);
  2699. // If the result type is a vec1, vec2, or vec3, some extra processing
  2700. // (extraction) is required.
  2701. uint32_t retVal = extractVecFromVec4(texel, elemCount, elemTypeId);
  2702. return SpirvEvalInfo(retVal).setRValue();
  2703. }
  2704. SpirvEvalInfo SPIRVEmitter::processByteAddressBufferLoadStore(
  2705. const CXXMemberCallExpr *expr, uint32_t numWords, bool doStore) {
  2706. uint32_t resultId = 0;
  2707. const auto object = expr->getImplicitObjectArgument();
  2708. const auto type = object->getType();
  2709. const auto objectInfo = loadIfAliasVarRef(object);
  2710. assert(numWords >= 1 && numWords <= 4);
  2711. if (doStore) {
  2712. assert(typeTranslator.isRWByteAddressBuffer(type));
  2713. assert(expr->getNumArgs() == 2);
  2714. } else {
  2715. assert(typeTranslator.isRWByteAddressBuffer(type) ||
  2716. typeTranslator.isByteAddressBuffer(type));
  2717. if (expr->getNumArgs() == 2) {
  2718. emitError(
  2719. "(RW)ByteAddressBuffer::Load(in address, out status) not supported",
  2720. expr->getExprLoc());
  2721. return 0;
  2722. }
  2723. }
  2724. const Expr *addressExpr = expr->getArg(0);
  2725. const uint32_t byteAddress = doExpr(addressExpr);
  2726. const uint32_t addressTypeId =
  2727. typeTranslator.translateType(addressExpr->getType());
  2728. // Do a OpShiftRightLogical by 2 (divide by 4 to get aligned memory
  2729. // access). The AST always casts the address to unsinged integer, so shift
  2730. // by unsinged integer 2.
  2731. const uint32_t constUint2 = theBuilder.getConstantUint32(2);
  2732. const uint32_t address = theBuilder.createBinaryOp(
  2733. spv::Op::OpShiftRightLogical, addressTypeId, byteAddress, constUint2);
  2734. // Perform access chain into the RWByteAddressBuffer.
  2735. // First index must be zero (member 0 of the struct is a
  2736. // runtimeArray). The second index passed to OpAccessChain should be
  2737. // the address.
  2738. const uint32_t uintTypeId = theBuilder.getUint32Type();
  2739. const uint32_t ptrType =
  2740. theBuilder.getPointerType(uintTypeId, objectInfo.getStorageClass());
  2741. const uint32_t constUint0 = theBuilder.getConstantUint32(0);
  2742. if (doStore) {
  2743. const uint32_t valuesId = doExpr(expr->getArg(1));
  2744. uint32_t curStoreAddress = address;
  2745. for (uint32_t wordCounter = 0; wordCounter < numWords; ++wordCounter) {
  2746. // Extract a 32-bit word from the input.
  2747. const uint32_t curValue = numWords == 1
  2748. ? valuesId
  2749. : theBuilder.createCompositeExtract(
  2750. uintTypeId, valuesId, {wordCounter});
  2751. // Update the output address if necessary.
  2752. if (wordCounter > 0) {
  2753. const uint32_t offset = theBuilder.getConstantUint32(wordCounter);
  2754. curStoreAddress = theBuilder.createBinaryOp(
  2755. spv::Op::OpIAdd, addressTypeId, address, offset);
  2756. }
  2757. // Store the word to the right address at the output.
  2758. const uint32_t storePtr = theBuilder.createAccessChain(
  2759. ptrType, objectInfo, {constUint0, curStoreAddress});
  2760. theBuilder.createStore(storePtr, curValue);
  2761. }
  2762. } else {
  2763. uint32_t loadPtr = theBuilder.createAccessChain(ptrType, objectInfo,
  2764. {constUint0, address});
  2765. resultId = theBuilder.createLoad(uintTypeId, loadPtr);
  2766. if (numWords > 1) {
  2767. // Load word 2, 3, and 4 where necessary. Use OpCompositeConstruct to
  2768. // return a vector result.
  2769. llvm::SmallVector<uint32_t, 4> values;
  2770. values.push_back(resultId);
  2771. for (uint32_t wordCounter = 2; wordCounter <= numWords; ++wordCounter) {
  2772. const uint32_t offset = theBuilder.getConstantUint32(wordCounter - 1);
  2773. const uint32_t newAddress = theBuilder.createBinaryOp(
  2774. spv::Op::OpIAdd, addressTypeId, address, offset);
  2775. loadPtr = theBuilder.createAccessChain(ptrType, objectInfo,
  2776. {constUint0, newAddress});
  2777. values.push_back(theBuilder.createLoad(uintTypeId, loadPtr));
  2778. }
  2779. const uint32_t resultType =
  2780. theBuilder.getVecType(addressTypeId, numWords);
  2781. resultId = theBuilder.createCompositeConstruct(resultType, values);
  2782. }
  2783. }
  2784. return SpirvEvalInfo(resultId).setRValue();
  2785. }
  2786. SpirvEvalInfo
  2787. SPIRVEmitter::processStructuredBufferLoad(const CXXMemberCallExpr *expr) {
  2788. if (expr->getNumArgs() == 2) {
  2789. emitError(
  2790. "(RW)StructuredBuffer::Load(in location, out status) not supported",
  2791. expr->getExprLoc());
  2792. return 0;
  2793. }
  2794. const auto *buffer = expr->getImplicitObjectArgument();
  2795. auto info = loadIfAliasVarRef(buffer);
  2796. const QualType structType =
  2797. hlsl::GetHLSLResourceResultType(buffer->getType());
  2798. const uint32_t zero = theBuilder.getConstantInt32(0);
  2799. const uint32_t index = doExpr(expr->getArg(0));
  2800. return turnIntoElementPtr(info, structType, {zero, index});
  2801. }
  2802. uint32_t SPIRVEmitter::incDecRWACSBufferCounter(const CXXMemberCallExpr *expr,
  2803. bool isInc, bool loadObject) {
  2804. const uint32_t i32Type = theBuilder.getInt32Type();
  2805. const uint32_t one = theBuilder.getConstantUint32(1); // As scope: Device
  2806. const uint32_t zero = theBuilder.getConstantUint32(0); // As memory sema: None
  2807. const uint32_t sOne = theBuilder.getConstantInt32(1);
  2808. const auto *object =
  2809. expr->getImplicitObjectArgument()->IgnoreParenNoopCasts(astContext);
  2810. if (loadObject) {
  2811. // We don't need the object's <result-id> here since counter variable is a
  2812. // separate variable. But we still need the side effects of evaluating the
  2813. // object, e.g., if the source code is foo(...).IncrementCounter(), we still
  2814. // want to emit the code for foo(...).
  2815. (void)doExpr(object);
  2816. }
  2817. const auto *counterPair = getFinalACSBufferCounter(object);
  2818. if (!counterPair) {
  2819. emitFatalError("cannot find the associated counter variable",
  2820. object->getExprLoc());
  2821. return 0;
  2822. }
  2823. const uint32_t counterPtrType = theBuilder.getPointerType(
  2824. theBuilder.getInt32Type(), spv::StorageClass::Uniform);
  2825. const uint32_t counterPtr = theBuilder.createAccessChain(
  2826. counterPtrType, counterPair->get(theBuilder, typeTranslator), {zero});
  2827. uint32_t index = 0;
  2828. if (isInc) {
  2829. index = theBuilder.createAtomicOp(spv::Op::OpAtomicIAdd, i32Type,
  2830. counterPtr, one, zero, sOne);
  2831. } else {
  2832. // Note that OpAtomicISub returns the value before the subtraction;
  2833. // so we need to do substraction again with OpAtomicISub's return value.
  2834. const auto prev = theBuilder.createAtomicOp(spv::Op::OpAtomicISub, i32Type,
  2835. counterPtr, one, zero, sOne);
  2836. index = theBuilder.createBinaryOp(spv::Op::OpISub, i32Type, prev, sOne);
  2837. }
  2838. return index;
  2839. }
  2840. bool SPIRVEmitter::tryToAssignCounterVar(const DeclaratorDecl *dstDecl,
  2841. const Expr *srcExpr) {
  2842. // We are handling associated counters here. Casts should not alter which
  2843. // associated counter to manipulate.
  2844. srcExpr = srcExpr->IgnoreParenCasts();
  2845. // For parameters of forward-declared functions. We must make sure the
  2846. // associated counter variable is created. But for forward-declared functions,
  2847. // the translation of the real definition may not be started yet.
  2848. if (const auto *param = dyn_cast<ParmVarDecl>(dstDecl))
  2849. declIdMapper.createFnParamCounterVar(param);
  2850. // For implicit objects of methods. Similar to the above.
  2851. else if (const auto *thisObject = dyn_cast<ImplicitParamDecl>(dstDecl))
  2852. declIdMapper.createFnParamCounterVar(thisObject);
  2853. // Handle AssocCounter#1 (see CounterVarFields comment)
  2854. if (const auto *dstPair = declIdMapper.getCounterIdAliasPair(dstDecl)) {
  2855. const auto *srcPair = getFinalACSBufferCounter(srcExpr);
  2856. if (!srcPair) {
  2857. emitFatalError("cannot find the associated counter variable",
  2858. srcExpr->getExprLoc());
  2859. return false;
  2860. }
  2861. dstPair->assign(*srcPair, theBuilder, typeTranslator);
  2862. return true;
  2863. }
  2864. // Handle AssocCounter#3
  2865. llvm::SmallVector<uint32_t, 4> srcIndices;
  2866. const auto *dstFields = declIdMapper.getCounterVarFields(dstDecl);
  2867. const auto *srcFields = getIntermediateACSBufferCounter(srcExpr, &srcIndices);
  2868. if (dstFields && srcFields) {
  2869. if (!dstFields->assign(*srcFields, theBuilder, typeTranslator)) {
  2870. emitFatalError("cannot handle associated counter variable assignment",
  2871. srcExpr->getExprLoc());
  2872. return false;
  2873. }
  2874. return true;
  2875. }
  2876. // AssocCounter#2 and AssocCounter#4 for the lhs cannot happen since the lhs
  2877. // is a stand-alone decl in this method.
  2878. return false;
  2879. }
  2880. bool SPIRVEmitter::tryToAssignCounterVar(const Expr *dstExpr,
  2881. const Expr *srcExpr) {
  2882. dstExpr = dstExpr->IgnoreParenCasts();
  2883. srcExpr = srcExpr->IgnoreParenCasts();
  2884. const auto *dstPair = getFinalACSBufferCounter(dstExpr);
  2885. const auto *srcPair = getFinalACSBufferCounter(srcExpr);
  2886. if ((dstPair == nullptr) != (srcPair == nullptr)) {
  2887. emitFatalError("cannot handle associated counter variable assignment",
  2888. srcExpr->getExprLoc());
  2889. return false;
  2890. }
  2891. // Handle AssocCounter#1 & AssocCounter#2
  2892. if (dstPair && srcPair) {
  2893. dstPair->assign(*srcPair, theBuilder, typeTranslator);
  2894. return true;
  2895. }
  2896. // Handle AssocCounter#3 & AssocCounter#4
  2897. llvm::SmallVector<uint32_t, 4> dstIndices;
  2898. llvm::SmallVector<uint32_t, 4> srcIndices;
  2899. const auto *srcFields = getIntermediateACSBufferCounter(srcExpr, &srcIndices);
  2900. const auto *dstFields = getIntermediateACSBufferCounter(dstExpr, &dstIndices);
  2901. if (dstFields && srcFields) {
  2902. return dstFields->assign(*srcFields, dstIndices, srcIndices, theBuilder,
  2903. typeTranslator);
  2904. }
  2905. return false;
  2906. }
  2907. const CounterIdAliasPair *
  2908. SPIRVEmitter::getFinalACSBufferCounter(const Expr *expr) {
  2909. // AssocCounter#1: referencing some stand-alone variable
  2910. if (const auto *decl = getReferencedDef(expr))
  2911. return declIdMapper.getCounterIdAliasPair(decl);
  2912. // AssocCounter#2: referencing some non-struct field
  2913. llvm::SmallVector<uint32_t, 4> indices;
  2914. const auto *base =
  2915. collectArrayStructIndices(expr, &indices, /*rawIndex=*/true);
  2916. const auto *decl =
  2917. (base && isa<CXXThisExpr>(base))
  2918. ? getOrCreateDeclForMethodObject(cast<CXXMethodDecl>(curFunction))
  2919. : getReferencedDef(base);
  2920. return declIdMapper.getCounterIdAliasPair(decl, &indices);
  2921. }
  2922. const CounterVarFields *SPIRVEmitter::getIntermediateACSBufferCounter(
  2923. const Expr *expr, llvm::SmallVector<uint32_t, 4> *indices) {
  2924. const auto *base =
  2925. collectArrayStructIndices(expr, indices, /*rawIndex=*/true);
  2926. const auto *decl =
  2927. (base && isa<CXXThisExpr>(base))
  2928. // Use the decl we created to represent the implicit object
  2929. ? getOrCreateDeclForMethodObject(cast<CXXMethodDecl>(curFunction))
  2930. // Find the referenced decl from the original source code
  2931. : getReferencedDef(base);
  2932. return declIdMapper.getCounterVarFields(decl);
  2933. }
  2934. const ImplicitParamDecl *
  2935. SPIRVEmitter::getOrCreateDeclForMethodObject(const CXXMethodDecl *method) {
  2936. const auto found = thisDecls.find(method);
  2937. if (found != thisDecls.end())
  2938. return found->second;
  2939. const std::string name = method->getName().str() + ".this";
  2940. // Create a new identifier to convey the name
  2941. auto &identifier = astContext.Idents.get(name);
  2942. return thisDecls[method] = ImplicitParamDecl::Create(
  2943. astContext, /*DC=*/nullptr, SourceLocation(), &identifier,
  2944. method->getThisType(astContext)->getPointeeType());
  2945. }
  2946. SpirvEvalInfo
  2947. SPIRVEmitter::processACSBufferAppendConsume(const CXXMemberCallExpr *expr) {
  2948. const bool isAppend = expr->getNumArgs() == 1;
  2949. const uint32_t zero = theBuilder.getConstantUint32(0);
  2950. const auto *object =
  2951. expr->getImplicitObjectArgument()->IgnoreParenNoopCasts(astContext);
  2952. auto bufferInfo = loadIfAliasVarRef(object);
  2953. uint32_t index = incDecRWACSBufferCounter(
  2954. expr, isAppend,
  2955. // We have already translated the object in the above. Avoid duplication.
  2956. /*loadObject=*/false);
  2957. const auto bufferElemTy = hlsl::GetHLSLResourceResultType(object->getType());
  2958. (void)turnIntoElementPtr(bufferInfo, bufferElemTy, {zero, index});
  2959. if (isAppend) {
  2960. // Write out the value
  2961. storeValue(bufferInfo, doExpr(expr->getArg(0)), bufferElemTy);
  2962. return 0;
  2963. } else {
  2964. // Note that we are returning a pointer (lvalue) here inorder to further
  2965. // acess the fields in this element, e.g., buffer.Consume().a.b. So we
  2966. // cannot forcefully set all normal function calls as returning rvalue.
  2967. return bufferInfo;
  2968. }
  2969. }
  2970. uint32_t
  2971. SPIRVEmitter::processStreamOutputAppend(const CXXMemberCallExpr *expr) {
  2972. // TODO: handle multiple stream-output objects
  2973. const auto *object =
  2974. expr->getImplicitObjectArgument()->IgnoreParenNoopCasts(astContext);
  2975. const auto *stream = cast<DeclRefExpr>(object)->getDecl();
  2976. const uint32_t value = doExpr(expr->getArg(0));
  2977. declIdMapper.writeBackOutputStream(stream, stream->getType(), value);
  2978. theBuilder.createEmitVertex();
  2979. return 0;
  2980. }
  2981. uint32_t
  2982. SPIRVEmitter::processStreamOutputRestart(const CXXMemberCallExpr *expr) {
  2983. // TODO: handle multiple stream-output objects
  2984. theBuilder.createEndPrimitive();
  2985. return 0;
  2986. }
  2987. uint32_t SPIRVEmitter::emitGetSamplePosition(const uint32_t sampleCount,
  2988. const uint32_t sampleIndex) {
  2989. struct Float2 {
  2990. float x;
  2991. float y;
  2992. };
  2993. static const Float2 pos2[] = {
  2994. {4.0 / 16.0, 4.0 / 16.0},
  2995. {-4.0 / 16.0, -4.0 / 16.0},
  2996. };
  2997. static const Float2 pos4[] = {
  2998. {-2.0 / 16.0, -6.0 / 16.0},
  2999. {6.0 / 16.0, -2.0 / 16.0},
  3000. {-6.0 / 16.0, 2.0 / 16.0},
  3001. {2.0 / 16.0, 6.0 / 16.0},
  3002. };
  3003. static const Float2 pos8[] = {
  3004. {1.0 / 16.0, -3.0 / 16.0}, {-1.0 / 16.0, 3.0 / 16.0},
  3005. {5.0 / 16.0, 1.0 / 16.0}, {-3.0 / 16.0, -5.0 / 16.0},
  3006. {-5.0 / 16.0, 5.0 / 16.0}, {-7.0 / 16.0, -1.0 / 16.0},
  3007. {3.0 / 16.0, 7.0 / 16.0}, {7.0 / 16.0, -7.0 / 16.0},
  3008. };
  3009. static const Float2 pos16[] = {
  3010. {1.0 / 16.0, 1.0 / 16.0}, {-1.0 / 16.0, -3.0 / 16.0},
  3011. {-3.0 / 16.0, 2.0 / 16.0}, {4.0 / 16.0, -1.0 / 16.0},
  3012. {-5.0 / 16.0, -2.0 / 16.0}, {2.0 / 16.0, 5.0 / 16.0},
  3013. {5.0 / 16.0, 3.0 / 16.0}, {3.0 / 16.0, -5.0 / 16.0},
  3014. {-2.0 / 16.0, 6.0 / 16.0}, {0.0 / 16.0, -7.0 / 16.0},
  3015. {-4.0 / 16.0, -6.0 / 16.0}, {-6.0 / 16.0, 4.0 / 16.0},
  3016. {-8.0 / 16.0, 0.0 / 16.0}, {7.0 / 16.0, -4.0 / 16.0},
  3017. {6.0 / 16.0, 7.0 / 16.0}, {-7.0 / 16.0, -8.0 / 16.0},
  3018. };
  3019. // We are emitting the SPIR-V for the following HLSL source code:
  3020. //
  3021. // float2 position;
  3022. //
  3023. // if (count == 2) {
  3024. // position = pos2[index];
  3025. // }
  3026. // else if (count == 4) {
  3027. // position = pos4[index];
  3028. // }
  3029. // else if (count == 8) {
  3030. // position = pos8[index];
  3031. // }
  3032. // else if (count == 16) {
  3033. // position = pos16[index];
  3034. // }
  3035. // else {
  3036. // position = float2(0.0f, 0.0f);
  3037. // }
  3038. const uint32_t boolType = theBuilder.getBoolType();
  3039. const auto v2f32Type = theBuilder.getVecType(theBuilder.getFloat32Type(), 2);
  3040. const uint32_t ptrType =
  3041. theBuilder.getPointerType(v2f32Type, spv::StorageClass::Function);
  3042. // Creates a SPIR-V function scope variable of type float2[len].
  3043. const auto createArray = [this, v2f32Type](const Float2 *ptr, uint32_t len) {
  3044. llvm::SmallVector<uint32_t, 16> components;
  3045. for (uint32_t i = 0; i < len; ++i) {
  3046. const auto x = theBuilder.getConstantFloat32(ptr[i].x);
  3047. const auto y = theBuilder.getConstantFloat32(ptr[i].y);
  3048. components.push_back(theBuilder.getConstantComposite(v2f32Type, {x, y}));
  3049. }
  3050. const auto arrType =
  3051. theBuilder.getArrayType(v2f32Type, theBuilder.getConstantUint32(len));
  3052. const auto val = theBuilder.getConstantComposite(arrType, components);
  3053. const std::string varName =
  3054. "var.GetSamplePosition.data." + std::to_string(len);
  3055. const auto var = theBuilder.addFnVar(arrType, varName);
  3056. theBuilder.createStore(var, val);
  3057. return var;
  3058. };
  3059. const uint32_t pos2Arr = createArray(pos2, 2);
  3060. const uint32_t pos4Arr = createArray(pos4, 4);
  3061. const uint32_t pos8Arr = createArray(pos8, 8);
  3062. const uint32_t pos16Arr = createArray(pos16, 16);
  3063. const uint32_t resultVar =
  3064. theBuilder.addFnVar(v2f32Type, "var.GetSamplePosition.result");
  3065. const uint32_t then2BB =
  3066. theBuilder.createBasicBlock("if.GetSamplePosition.then2");
  3067. const uint32_t then4BB =
  3068. theBuilder.createBasicBlock("if.GetSamplePosition.then4");
  3069. const uint32_t then8BB =
  3070. theBuilder.createBasicBlock("if.GetSamplePosition.then8");
  3071. const uint32_t then16BB =
  3072. theBuilder.createBasicBlock("if.GetSamplePosition.then16");
  3073. const uint32_t else2BB =
  3074. theBuilder.createBasicBlock("if.GetSamplePosition.else2");
  3075. const uint32_t else4BB =
  3076. theBuilder.createBasicBlock("if.GetSamplePosition.else4");
  3077. const uint32_t else8BB =
  3078. theBuilder.createBasicBlock("if.GetSamplePosition.else8");
  3079. const uint32_t else16BB =
  3080. theBuilder.createBasicBlock("if.GetSamplePosition.else16");
  3081. const uint32_t merge2BB =
  3082. theBuilder.createBasicBlock("if.GetSamplePosition.merge2");
  3083. const uint32_t merge4BB =
  3084. theBuilder.createBasicBlock("if.GetSamplePosition.merge4");
  3085. const uint32_t merge8BB =
  3086. theBuilder.createBasicBlock("if.GetSamplePosition.merge8");
  3087. const uint32_t merge16BB =
  3088. theBuilder.createBasicBlock("if.GetSamplePosition.merge16");
  3089. // if (count == 2) {
  3090. const auto check2 =
  3091. theBuilder.createBinaryOp(spv::Op::OpIEqual, boolType, sampleCount,
  3092. theBuilder.getConstantUint32(2));
  3093. theBuilder.createConditionalBranch(check2, then2BB, else2BB, merge2BB);
  3094. theBuilder.addSuccessor(then2BB);
  3095. theBuilder.addSuccessor(else2BB);
  3096. theBuilder.setMergeTarget(merge2BB);
  3097. // position = pos2[index];
  3098. // }
  3099. theBuilder.setInsertPoint(then2BB);
  3100. auto ac = theBuilder.createAccessChain(ptrType, pos2Arr, {sampleIndex});
  3101. theBuilder.createStore(resultVar, theBuilder.createLoad(v2f32Type, ac));
  3102. theBuilder.createBranch(merge2BB);
  3103. theBuilder.addSuccessor(merge2BB);
  3104. // else if (count == 4) {
  3105. theBuilder.setInsertPoint(else2BB);
  3106. const auto check4 =
  3107. theBuilder.createBinaryOp(spv::Op::OpIEqual, boolType, sampleCount,
  3108. theBuilder.getConstantUint32(4));
  3109. theBuilder.createConditionalBranch(check4, then4BB, else4BB, merge4BB);
  3110. theBuilder.addSuccessor(then4BB);
  3111. theBuilder.addSuccessor(else4BB);
  3112. theBuilder.setMergeTarget(merge4BB);
  3113. // position = pos4[index];
  3114. // }
  3115. theBuilder.setInsertPoint(then4BB);
  3116. ac = theBuilder.createAccessChain(ptrType, pos4Arr, {sampleIndex});
  3117. theBuilder.createStore(resultVar, theBuilder.createLoad(v2f32Type, ac));
  3118. theBuilder.createBranch(merge4BB);
  3119. theBuilder.addSuccessor(merge4BB);
  3120. // else if (count == 8) {
  3121. theBuilder.setInsertPoint(else4BB);
  3122. const auto check8 =
  3123. theBuilder.createBinaryOp(spv::Op::OpIEqual, boolType, sampleCount,
  3124. theBuilder.getConstantUint32(8));
  3125. theBuilder.createConditionalBranch(check8, then8BB, else8BB, merge8BB);
  3126. theBuilder.addSuccessor(then8BB);
  3127. theBuilder.addSuccessor(else8BB);
  3128. theBuilder.setMergeTarget(merge8BB);
  3129. // position = pos8[index];
  3130. // }
  3131. theBuilder.setInsertPoint(then8BB);
  3132. ac = theBuilder.createAccessChain(ptrType, pos8Arr, {sampleIndex});
  3133. theBuilder.createStore(resultVar, theBuilder.createLoad(v2f32Type, ac));
  3134. theBuilder.createBranch(merge8BB);
  3135. theBuilder.addSuccessor(merge8BB);
  3136. // else if (count == 16) {
  3137. theBuilder.setInsertPoint(else8BB);
  3138. const auto check16 =
  3139. theBuilder.createBinaryOp(spv::Op::OpIEqual, boolType, sampleCount,
  3140. theBuilder.getConstantUint32(16));
  3141. theBuilder.createConditionalBranch(check16, then16BB, else16BB, merge16BB);
  3142. theBuilder.addSuccessor(then16BB);
  3143. theBuilder.addSuccessor(else16BB);
  3144. theBuilder.setMergeTarget(merge16BB);
  3145. // position = pos16[index];
  3146. // }
  3147. theBuilder.setInsertPoint(then16BB);
  3148. ac = theBuilder.createAccessChain(ptrType, pos16Arr, {sampleIndex});
  3149. theBuilder.createStore(resultVar, theBuilder.createLoad(v2f32Type, ac));
  3150. theBuilder.createBranch(merge16BB);
  3151. theBuilder.addSuccessor(merge16BB);
  3152. // else {
  3153. // position = float2(0.0f, 0.0f);
  3154. // }
  3155. theBuilder.setInsertPoint(else16BB);
  3156. const auto zero = theBuilder.getConstantFloat32(0);
  3157. const auto v2f32Zero =
  3158. theBuilder.getConstantComposite(v2f32Type, {zero, zero});
  3159. theBuilder.createStore(resultVar, v2f32Zero);
  3160. theBuilder.createBranch(merge16BB);
  3161. theBuilder.addSuccessor(merge16BB);
  3162. theBuilder.setInsertPoint(merge16BB);
  3163. theBuilder.createBranch(merge8BB);
  3164. theBuilder.addSuccessor(merge8BB);
  3165. theBuilder.setInsertPoint(merge8BB);
  3166. theBuilder.createBranch(merge4BB);
  3167. theBuilder.addSuccessor(merge4BB);
  3168. theBuilder.setInsertPoint(merge4BB);
  3169. theBuilder.createBranch(merge2BB);
  3170. theBuilder.addSuccessor(merge2BB);
  3171. theBuilder.setInsertPoint(merge2BB);
  3172. return theBuilder.createLoad(v2f32Type, resultVar);
  3173. }
  3174. SpirvEvalInfo SPIRVEmitter::doCXXMemberCallExpr(const CXXMemberCallExpr *expr) {
  3175. const FunctionDecl *callee = expr->getDirectCallee();
  3176. llvm::StringRef group;
  3177. uint32_t opcode = static_cast<uint32_t>(hlsl::IntrinsicOp::Num_Intrinsics);
  3178. if (hlsl::GetIntrinsicOp(callee, opcode, group)) {
  3179. return processIntrinsicMemberCall(expr,
  3180. static_cast<hlsl::IntrinsicOp>(opcode));
  3181. }
  3182. return processCall(expr);
  3183. }
  3184. void SPIRVEmitter::handleOffsetInMethodCall(const CXXMemberCallExpr *expr,
  3185. uint32_t index,
  3186. uint32_t *constOffset,
  3187. uint32_t *varOffset) {
  3188. // Ensure the given arg index is not out-of-range.
  3189. assert(index < expr->getNumArgs());
  3190. *constOffset = *varOffset = 0; // Initialize both first
  3191. if (*constOffset = tryToEvaluateAsConst(expr->getArg(index)))
  3192. return; // Constant offset
  3193. else
  3194. *varOffset = doExpr(expr->getArg(index));
  3195. };
  3196. SpirvEvalInfo
  3197. SPIRVEmitter::processIntrinsicMemberCall(const CXXMemberCallExpr *expr,
  3198. hlsl::IntrinsicOp opcode) {
  3199. using namespace hlsl;
  3200. uint32_t retVal = 0;
  3201. switch (opcode) {
  3202. case IntrinsicOp::MOP_Sample:
  3203. retVal = processTextureSampleGather(expr, /*isSample=*/true);
  3204. break;
  3205. case IntrinsicOp::MOP_Gather:
  3206. retVal = processTextureSampleGather(expr, /*isSample=*/false);
  3207. break;
  3208. case IntrinsicOp::MOP_SampleBias:
  3209. retVal = processTextureSampleBiasLevel(expr, /*isBias=*/true);
  3210. break;
  3211. case IntrinsicOp::MOP_SampleLevel:
  3212. retVal = processTextureSampleBiasLevel(expr, /*isBias=*/false);
  3213. break;
  3214. case IntrinsicOp::MOP_SampleGrad:
  3215. retVal = processTextureSampleGrad(expr);
  3216. break;
  3217. case IntrinsicOp::MOP_SampleCmp:
  3218. retVal = processTextureSampleCmpCmpLevelZero(expr, /*isCmp=*/true);
  3219. break;
  3220. case IntrinsicOp::MOP_SampleCmpLevelZero:
  3221. retVal = processTextureSampleCmpCmpLevelZero(expr, /*isCmp=*/false);
  3222. break;
  3223. case IntrinsicOp::MOP_GatherRed:
  3224. retVal = processTextureGatherRGBACmpRGBA(expr, /*isCmp=*/false, 0);
  3225. break;
  3226. case IntrinsicOp::MOP_GatherGreen:
  3227. retVal = processTextureGatherRGBACmpRGBA(expr, /*isCmp=*/false, 1);
  3228. break;
  3229. case IntrinsicOp::MOP_GatherBlue:
  3230. retVal = processTextureGatherRGBACmpRGBA(expr, /*isCmp=*/false, 2);
  3231. break;
  3232. case IntrinsicOp::MOP_GatherAlpha:
  3233. retVal = processTextureGatherRGBACmpRGBA(expr, /*isCmp=*/false, 3);
  3234. break;
  3235. case IntrinsicOp::MOP_GatherCmp:
  3236. retVal = processTextureGatherCmp(expr);
  3237. break;
  3238. case IntrinsicOp::MOP_GatherCmpRed:
  3239. retVal = processTextureGatherRGBACmpRGBA(expr, /*isCmp=*/true, 0);
  3240. break;
  3241. case IntrinsicOp::MOP_Load:
  3242. return processBufferTextureLoad(expr);
  3243. case IntrinsicOp::MOP_Load2:
  3244. return processByteAddressBufferLoadStore(expr, 2, /*doStore*/ false);
  3245. case IntrinsicOp::MOP_Load3:
  3246. return processByteAddressBufferLoadStore(expr, 3, /*doStore*/ false);
  3247. case IntrinsicOp::MOP_Load4:
  3248. return processByteAddressBufferLoadStore(expr, 4, /*doStore*/ false);
  3249. case IntrinsicOp::MOP_Store:
  3250. return processByteAddressBufferLoadStore(expr, 1, /*doStore*/ true);
  3251. case IntrinsicOp::MOP_Store2:
  3252. return processByteAddressBufferLoadStore(expr, 2, /*doStore*/ true);
  3253. case IntrinsicOp::MOP_Store3:
  3254. return processByteAddressBufferLoadStore(expr, 3, /*doStore*/ true);
  3255. case IntrinsicOp::MOP_Store4:
  3256. return processByteAddressBufferLoadStore(expr, 4, /*doStore*/ true);
  3257. case IntrinsicOp::MOP_GetDimensions:
  3258. retVal = processGetDimensions(expr);
  3259. break;
  3260. case IntrinsicOp::MOP_CalculateLevelOfDetail:
  3261. retVal = processTextureLevelOfDetail(expr);
  3262. break;
  3263. case IntrinsicOp::MOP_IncrementCounter:
  3264. retVal = theBuilder.createUnaryOp(
  3265. spv::Op::OpBitcast, theBuilder.getUint32Type(),
  3266. incDecRWACSBufferCounter(expr, /*isInc*/ true));
  3267. break;
  3268. case IntrinsicOp::MOP_DecrementCounter:
  3269. retVal = theBuilder.createUnaryOp(
  3270. spv::Op::OpBitcast, theBuilder.getUint32Type(),
  3271. incDecRWACSBufferCounter(expr, /*isInc*/ false));
  3272. break;
  3273. case IntrinsicOp::MOP_Append:
  3274. if (hlsl::IsHLSLStreamOutputType(
  3275. expr->getImplicitObjectArgument()->getType()))
  3276. return processStreamOutputAppend(expr);
  3277. else
  3278. return processACSBufferAppendConsume(expr);
  3279. case IntrinsicOp::MOP_Consume:
  3280. return processACSBufferAppendConsume(expr);
  3281. case IntrinsicOp::MOP_RestartStrip:
  3282. retVal = processStreamOutputRestart(expr);
  3283. break;
  3284. case IntrinsicOp::MOP_InterlockedAdd:
  3285. case IntrinsicOp::MOP_InterlockedAnd:
  3286. case IntrinsicOp::MOP_InterlockedOr:
  3287. case IntrinsicOp::MOP_InterlockedXor:
  3288. case IntrinsicOp::MOP_InterlockedUMax:
  3289. case IntrinsicOp::MOP_InterlockedUMin:
  3290. case IntrinsicOp::MOP_InterlockedMax:
  3291. case IntrinsicOp::MOP_InterlockedMin:
  3292. case IntrinsicOp::MOP_InterlockedExchange:
  3293. case IntrinsicOp::MOP_InterlockedCompareExchange:
  3294. case IntrinsicOp::MOP_InterlockedCompareStore:
  3295. retVal = processRWByteAddressBufferAtomicMethods(opcode, expr);
  3296. break;
  3297. case IntrinsicOp::MOP_GetSamplePosition:
  3298. retVal = processGetSamplePosition(expr);
  3299. break;
  3300. case IntrinsicOp::MOP_SubpassLoad:
  3301. retVal = processSubpassLoad(expr);
  3302. break;
  3303. case IntrinsicOp::MOP_GatherCmpGreen:
  3304. case IntrinsicOp::MOP_GatherCmpBlue:
  3305. case IntrinsicOp::MOP_GatherCmpAlpha:
  3306. case IntrinsicOp::MOP_CalculateLevelOfDetailUnclamped:
  3307. emitError("no equivalent for %0 intrinsic method in Vulkan",
  3308. expr->getCallee()->getExprLoc())
  3309. << expr->getMethodDecl()->getName();
  3310. return 0;
  3311. default:
  3312. emitError("intrinsic '%0' method unimplemented",
  3313. expr->getCallee()->getExprLoc())
  3314. << expr->getDirectCallee()->getName();
  3315. return 0;
  3316. }
  3317. return SpirvEvalInfo(retVal).setRValue();
  3318. }
  3319. uint32_t SPIRVEmitter::createImageSample(
  3320. QualType retType, uint32_t imageType, uint32_t image, uint32_t sampler,
  3321. uint32_t coordinate, uint32_t compareVal, uint32_t bias, uint32_t lod,
  3322. std::pair<uint32_t, uint32_t> grad, uint32_t constOffset,
  3323. uint32_t varOffset, uint32_t constOffsets, uint32_t sample, uint32_t minLod,
  3324. uint32_t residencyCodeId) {
  3325. const auto retTypeId = typeTranslator.translateType(retType);
  3326. // SampleDref* instructions in SPIR-V always return a scalar.
  3327. // They also have the correct type in HLSL.
  3328. if (compareVal) {
  3329. return theBuilder.createImageSample(retTypeId, imageType, image, sampler,
  3330. coordinate, compareVal, bias, lod, grad,
  3331. constOffset, varOffset, constOffsets,
  3332. sample, minLod, residencyCodeId);
  3333. }
  3334. // Non-Dref Sample instructions in SPIR-V must always return a vec4.
  3335. auto texelTypeId = retTypeId;
  3336. QualType elemType = {};
  3337. uint32_t elemTypeId = 0;
  3338. uint32_t retVecSize = 0;
  3339. if (TypeTranslator::isVectorType(retType, &elemType, &retVecSize) &&
  3340. retVecSize != 4) {
  3341. elemTypeId = typeTranslator.translateType(elemType);
  3342. texelTypeId = theBuilder.getVecType(elemTypeId, 4);
  3343. } else if (TypeTranslator::isScalarType(retType)) {
  3344. retVecSize = 1;
  3345. elemTypeId = typeTranslator.translateType(retType);
  3346. texelTypeId = theBuilder.getVecType(elemTypeId, 4);
  3347. }
  3348. // The Lod and Grad image operands requires explicit-lod instructions.
  3349. // Otherwise we use implicit-lod instructions.
  3350. const bool isExplicit = lod || (grad.first && grad.second);
  3351. // Implicit-lod instructions are only allowed in pixel shader.
  3352. if (!shaderModel.IsPS() && !isExplicit)
  3353. needsLegalization = true;
  3354. uint32_t retVal = theBuilder.createImageSample(
  3355. texelTypeId, imageType, image, sampler, coordinate, compareVal, bias, lod,
  3356. grad, constOffset, varOffset, constOffsets, sample, minLod,
  3357. residencyCodeId);
  3358. // Extract smaller vector from the vec4 result if necessary.
  3359. if (texelTypeId != retTypeId) {
  3360. retVal = extractVecFromVec4(retVal, retVecSize, elemTypeId);
  3361. }
  3362. return retVal;
  3363. }
  3364. uint32_t SPIRVEmitter::processTextureSampleGather(const CXXMemberCallExpr *expr,
  3365. const bool isSample) {
  3366. // Signatures:
  3367. // For Texture1D, Texture1DArray, Texture2D, Texture2DArray, Texture3D:
  3368. // DXGI_FORMAT Object.Sample(sampler_state S,
  3369. // float Location
  3370. // [, int Offset]
  3371. // [, float Clamp]
  3372. // [, out uint Status]);
  3373. //
  3374. // For TextureCube and TextureCubeArray:
  3375. // DXGI_FORMAT Object.Sample(sampler_state S,
  3376. // float Location
  3377. // [, float Clamp]
  3378. // [, out uint Status]);
  3379. //
  3380. // For Texture2D/Texture2DArray:
  3381. // <Template Type>4 Object.Gather(sampler_state S,
  3382. // float2|3|4 Location,
  3383. // int2 Offset
  3384. // [, uint Status]);
  3385. //
  3386. // For TextureCube/TextureCubeArray:
  3387. // <Template Type>4 Object.Gather(sampler_state S,
  3388. // float2|3|4 Location
  3389. // [, uint Status]);
  3390. //
  3391. // Other Texture types do not have a Gather method.
  3392. const auto numArgs = expr->getNumArgs();
  3393. const bool hasStatusArg =
  3394. expr->getArg(numArgs - 1)->getType()->isUnsignedIntegerType();
  3395. uint32_t clamp = 0;
  3396. if (numArgs > 2 && expr->getArg(2)->getType()->isFloatingType())
  3397. clamp = doExpr(expr->getArg(2));
  3398. else if (numArgs > 3 && expr->getArg(3)->getType()->isFloatingType())
  3399. clamp = doExpr(expr->getArg(3));
  3400. const bool hasClampArg = (clamp != 0);
  3401. const auto status = hasStatusArg ? doExpr(expr->getArg(numArgs - 1)) : 0;
  3402. // Subtract 1 for status (if it exists), subtract 1 for clamp (if it exists),
  3403. // and subtract 2 for sampler_state and location.
  3404. const bool hasOffsetArg = numArgs - hasStatusArg - hasClampArg - 2 > 0;
  3405. const auto *imageExpr = expr->getImplicitObjectArgument();
  3406. const uint32_t imageType = typeTranslator.translateType(imageExpr->getType());
  3407. const uint32_t image = loadIfGLValue(imageExpr);
  3408. const uint32_t sampler = doExpr(expr->getArg(0));
  3409. const uint32_t coordinate = doExpr(expr->getArg(1));
  3410. // .Sample()/.Gather() may have a third optional paramter for offset.
  3411. uint32_t constOffset = 0, varOffset = 0;
  3412. if (hasOffsetArg)
  3413. handleOffsetInMethodCall(expr, 2, &constOffset, &varOffset);
  3414. const auto retType = expr->getDirectCallee()->getReturnType();
  3415. const auto retTypeId = typeTranslator.translateType(retType);
  3416. if (isSample) {
  3417. return createImageSample(
  3418. retType, imageType, image, sampler, coordinate, /*compareVal*/ 0,
  3419. /*bias*/ 0, /*lod*/ 0, std::make_pair(0, 0), constOffset, varOffset,
  3420. /*constOffsets*/ 0, /*sampleNumber*/ 0, /*minLod*/ clamp, status);
  3421. } else {
  3422. return theBuilder.createImageGather(
  3423. retTypeId, imageType, image, sampler, coordinate,
  3424. // .Gather() doc says we return four components of red data.
  3425. theBuilder.getConstantInt32(0), /*compareVal*/ 0, constOffset,
  3426. varOffset, /*constOffsets*/ 0, /*sampleNumber*/ 0, status);
  3427. }
  3428. }
  3429. uint32_t
  3430. SPIRVEmitter::processTextureSampleBiasLevel(const CXXMemberCallExpr *expr,
  3431. const bool isBias) {
  3432. // Signatures:
  3433. // For Texture1D, Texture1DArray, Texture2D, Texture2DArray, and Texture3D:
  3434. // DXGI_FORMAT Object.SampleBias(sampler_state S,
  3435. // float Location,
  3436. // float Bias
  3437. // [, int Offset]
  3438. // [, float clamp]
  3439. // [, out uint Status]);
  3440. //
  3441. // For TextureCube and TextureCubeArray:
  3442. // DXGI_FORMAT Object.SampleBias(sampler_state S,
  3443. // float Location,
  3444. // float Bias
  3445. // [, float clamp]
  3446. // [, out uint Status]);
  3447. //
  3448. // For Texture1D, Texture1DArray, Texture2D, Texture2DArray, and Texture3D:
  3449. // DXGI_FORMAT Object.SampleLevel(sampler_state S,
  3450. // float Location,
  3451. // float LOD
  3452. // [, int Offset]
  3453. // [, out uint Status]);
  3454. //
  3455. // For TextureCube and TextureCubeArray:
  3456. // DXGI_FORMAT Object.SampleLevel(sampler_state S,
  3457. // float Location,
  3458. // float LOD
  3459. // [, out uint Status]);
  3460. const auto numArgs = expr->getNumArgs();
  3461. const bool hasStatusArg =
  3462. expr->getArg(numArgs - 1)->getType()->isUnsignedIntegerType();
  3463. const auto status = hasStatusArg ? doExpr(expr->getArg(numArgs - 1)) : 0;
  3464. uint32_t clamp = 0;
  3465. // The .SampleLevel() methods do not take the clamp argument.
  3466. if (isBias) {
  3467. if (numArgs > 3 && expr->getArg(3)->getType()->isFloatingType())
  3468. clamp = doExpr(expr->getArg(3));
  3469. else if (numArgs > 4 && expr->getArg(4)->getType()->isFloatingType())
  3470. clamp = doExpr(expr->getArg(4));
  3471. }
  3472. const bool hasClampArg = clamp != 0;
  3473. // Subtract 1 for clamp (if it exists), 1 for status (if it exists),
  3474. // and 3 for sampler_state, location, and Bias/LOD.
  3475. const bool hasOffsetArg = numArgs - hasClampArg - hasStatusArg - 3 > 0;
  3476. const auto *imageExpr = expr->getImplicitObjectArgument();
  3477. const uint32_t imageType = typeTranslator.translateType(imageExpr->getType());
  3478. const uint32_t image = loadIfGLValue(imageExpr);
  3479. const uint32_t sampler = doExpr(expr->getArg(0));
  3480. const uint32_t coordinate = doExpr(expr->getArg(1));
  3481. uint32_t lod = 0;
  3482. uint32_t bias = 0;
  3483. if (isBias) {
  3484. bias = doExpr(expr->getArg(2));
  3485. } else {
  3486. lod = doExpr(expr->getArg(2));
  3487. }
  3488. // If offset is present in .Bias()/.SampleLevel(), it is the fourth argument.
  3489. uint32_t constOffset = 0, varOffset = 0;
  3490. if (hasOffsetArg)
  3491. handleOffsetInMethodCall(expr, 3, &constOffset, &varOffset);
  3492. const auto retType = expr->getDirectCallee()->getReturnType();
  3493. return createImageSample(retType, imageType, image, sampler, coordinate,
  3494. /*compareVal*/ 0, bias, lod, std::make_pair(0, 0),
  3495. constOffset, varOffset, /*constOffsets*/ 0,
  3496. /*sampleNumber*/ 0, /*minLod*/ clamp, status);
  3497. }
  3498. uint32_t SPIRVEmitter::processTextureSampleGrad(const CXXMemberCallExpr *expr) {
  3499. // Signature:
  3500. // For Texture1D, Texture1DArray, Texture2D, Texture2DArray, and Texture3D:
  3501. // DXGI_FORMAT Object.SampleGrad(sampler_state S,
  3502. // float Location,
  3503. // float DDX,
  3504. // float DDY
  3505. // [, int Offset]
  3506. // [, float Clamp]
  3507. // [, out uint Status]);
  3508. //
  3509. // For TextureCube and TextureCubeArray:
  3510. // DXGI_FORMAT Object.SampleGrad(sampler_state S,
  3511. // float Location,
  3512. // float DDX,
  3513. // float DDY
  3514. // [, float Clamp]
  3515. // [, out uint Status]);
  3516. const auto numArgs = expr->getNumArgs();
  3517. const bool hasStatusArg =
  3518. expr->getArg(numArgs - 1)->getType()->isUnsignedIntegerType();
  3519. const auto status = hasStatusArg ? doExpr(expr->getArg(numArgs - 1)) : 0;
  3520. uint32_t clamp = 0;
  3521. if (numArgs > 4 && expr->getArg(4)->getType()->isFloatingType())
  3522. clamp = doExpr(expr->getArg(4));
  3523. else if (numArgs > 5 && expr->getArg(5)->getType()->isFloatingType())
  3524. clamp = doExpr(expr->getArg(5));
  3525. const bool hasClampArg = clamp != 0;
  3526. // Subtract 1 for clamp (if it exists), 1 for status (if it exists),
  3527. // and 4 for sampler_state, location, DDX, and DDY;
  3528. const bool hasOffsetArg = numArgs - hasClampArg - hasStatusArg - 4 > 0;
  3529. const auto *imageExpr = expr->getImplicitObjectArgument();
  3530. const uint32_t imageType = typeTranslator.translateType(imageExpr->getType());
  3531. const uint32_t image = loadIfGLValue(imageExpr);
  3532. const uint32_t sampler = doExpr(expr->getArg(0));
  3533. const uint32_t coordinate = doExpr(expr->getArg(1));
  3534. const uint32_t ddx = doExpr(expr->getArg(2));
  3535. const uint32_t ddy = doExpr(expr->getArg(3));
  3536. // If offset is present in .SampleGrad(), it is the fifth argument.
  3537. uint32_t constOffset = 0, varOffset = 0;
  3538. if (hasOffsetArg)
  3539. handleOffsetInMethodCall(expr, 4, &constOffset, &varOffset);
  3540. const auto retType = expr->getDirectCallee()->getReturnType();
  3541. return createImageSample(
  3542. retType, imageType, image, sampler, coordinate, /*compareVal*/ 0,
  3543. /*bias*/ 0, /*lod*/ 0, std::make_pair(ddx, ddy), constOffset, varOffset,
  3544. /*constOffsets*/ 0, /*sampleNumber*/ 0, /*minLod*/ clamp, status);
  3545. }
  3546. uint32_t
  3547. SPIRVEmitter::processTextureSampleCmpCmpLevelZero(const CXXMemberCallExpr *expr,
  3548. const bool isCmp) {
  3549. // .SampleCmp() Signature:
  3550. //
  3551. // For Texture1D, Texture1DArray, Texture2D, Texture2DArray:
  3552. // float Object.SampleCmp(
  3553. // SamplerComparisonState S,
  3554. // float Location,
  3555. // float CompareValue
  3556. // [, int Offset]
  3557. // [, float Clamp]
  3558. // [, out uint Status]
  3559. // );
  3560. //
  3561. // For TextureCube and TextureCubeArray:
  3562. // float Object.SampleCmp(
  3563. // SamplerComparisonState S,
  3564. // float Location,
  3565. // float CompareValue
  3566. // [, float Clamp]
  3567. // [, out uint Status]
  3568. // );
  3569. //
  3570. // .SampleCmpLevelZero() is identical to .SampleCmp() on mipmap level 0 only.
  3571. // It never takes a clamp argument, which is good because lod and clamp may
  3572. // not be used together.
  3573. //
  3574. // .SampleCmpLevelZero() Signature:
  3575. //
  3576. // For Texture1D, Texture1DArray, Texture2D, Texture2DArray:
  3577. // float Object.SampleCmpLevelZero(
  3578. // SamplerComparisonState S,
  3579. // float Location,
  3580. // float CompareValue
  3581. // [, int Offset]
  3582. // [, out uint Status]
  3583. // );
  3584. //
  3585. // For TextureCube and TextureCubeArray:
  3586. // float Object.SampleCmpLevelZero(
  3587. // SamplerComparisonState S,
  3588. // float Location,
  3589. // float CompareValue
  3590. // [, out uint Status]
  3591. // );
  3592. const auto numArgs = expr->getNumArgs();
  3593. const bool hasStatusArg =
  3594. expr->getArg(numArgs - 1)->getType()->isUnsignedIntegerType();
  3595. const auto status = hasStatusArg ? doExpr(expr->getArg(numArgs - 1)) : 0;
  3596. uint32_t clamp = 0;
  3597. // The .SampleCmpLevelZero() methods do not take the clamp argument.
  3598. if (isCmp) {
  3599. if (numArgs > 3 && expr->getArg(3)->getType()->isFloatingType())
  3600. clamp = doExpr(expr->getArg(3));
  3601. else if (numArgs > 4 && expr->getArg(4)->getType()->isFloatingType())
  3602. clamp = doExpr(expr->getArg(4));
  3603. }
  3604. const bool hasClampArg = clamp != 0;
  3605. // Subtract 1 for clamp (if it exists), 1 for status (if it exists),
  3606. // and 3 for sampler_state, location, and compare_value.
  3607. const bool hasOffsetArg = numArgs - hasClampArg - hasStatusArg - 3 > 0;
  3608. const auto *imageExpr = expr->getImplicitObjectArgument();
  3609. const uint32_t image = loadIfGLValue(imageExpr);
  3610. const uint32_t sampler = doExpr(expr->getArg(0));
  3611. const uint32_t coordinate = doExpr(expr->getArg(1));
  3612. const uint32_t compareVal = doExpr(expr->getArg(2));
  3613. // If offset is present in .SampleCmp(), it will be the fourth argument.
  3614. uint32_t constOffset = 0, varOffset = 0;
  3615. if (hasOffsetArg)
  3616. handleOffsetInMethodCall(expr, 3, &constOffset, &varOffset);
  3617. const uint32_t lod = isCmp ? 0 : theBuilder.getConstantFloat32(0);
  3618. const auto retType = expr->getDirectCallee()->getReturnType();
  3619. // TODO: Hack. Drivers are expecting the Depth value in OpTypeImage to match
  3620. // the OpImageSample* instruction: Depth=0 for normal sampling, and Depth=1
  3621. // for depth-comparison sampling. That behavior is not what the spec says;
  3622. // Vulkan spec reads "The 'Depth' operand of OpTypeImage is ignored."
  3623. // We always generate OpTypeImage variables with Depth=0. Hack this only
  3624. // depth-comparison sampling code path to use Depth=1 for the OpTypeImage
  3625. // used by OpSampledImage. This causes inconsistent types in SPIR-V, but
  3626. // pleases drivers. Whatever.
  3627. const auto imageType = typeTranslator.translateResourceType(
  3628. imageExpr->getType(), LayoutRule::Void, /*isDepthCmp=*/true);
  3629. return createImageSample(retType, imageType, image, sampler, coordinate,
  3630. compareVal, /*bias*/ 0, lod, std::make_pair(0, 0),
  3631. constOffset, varOffset, /*constOffsets*/ 0,
  3632. /*sampleNumber*/ 0, /*minLod*/ clamp, status);
  3633. }
  3634. SpirvEvalInfo
  3635. SPIRVEmitter::processBufferTextureLoad(const CXXMemberCallExpr *expr) {
  3636. // Signature:
  3637. // For Texture1D, Texture1DArray, Texture2D, Texture2DArray, Texture3D:
  3638. // ret Object.Load(int Location
  3639. // [, int Offset]
  3640. // [, uint status]);
  3641. //
  3642. // For Texture2DMS and Texture2DMSArray, there is one additional argument:
  3643. // ret Object.Load(int Location
  3644. // [, int SampleIndex]
  3645. // [, int Offset]
  3646. // [, uint status]);
  3647. //
  3648. // For (RW)Buffer, RWTexture1D, RWTexture1DArray, RWTexture2D,
  3649. // RWTexture2DArray, RWTexture3D:
  3650. // ret Object.Load (int Location
  3651. // [, uint status]);
  3652. //
  3653. // Note: (RW)ByteAddressBuffer and (RW)StructuredBuffer types also have Load
  3654. // methods that take an additional Status argument. However, since these types
  3655. // are not represented as OpTypeImage in SPIR-V, we don't have a way of
  3656. // figuring out the Residency Code for them. Therefore having the Status
  3657. // argument for these types is not supported.
  3658. //
  3659. // For (RW)ByteAddressBuffer:
  3660. // ret Object.{Load,Load2,Load3,Load4} (int Location
  3661. // [, uint status]);
  3662. //
  3663. // For (RW)StructuredBuffer:
  3664. // ret Object.Load (int Location
  3665. // [, uint status]);
  3666. //
  3667. const auto *object = expr->getImplicitObjectArgument();
  3668. const auto objectType = object->getType();
  3669. if (typeTranslator.isRWByteAddressBuffer(objectType) ||
  3670. typeTranslator.isByteAddressBuffer(objectType))
  3671. return processByteAddressBufferLoadStore(expr, 1, /*doStore*/ false);
  3672. if (TypeTranslator::isStructuredBuffer(objectType))
  3673. return processStructuredBufferLoad(expr);
  3674. const auto numArgs = expr->getNumArgs();
  3675. const auto *location = expr->getArg(0);
  3676. const bool isTextureMS = TypeTranslator::isTextureMS(objectType);
  3677. const bool hasStatusArg =
  3678. expr->getArg(numArgs - 1)->getType()->isUnsignedIntegerType();
  3679. const auto status = hasStatusArg ? doExpr(expr->getArg(numArgs - 1)) : 0;
  3680. if (TypeTranslator::isBuffer(objectType) ||
  3681. TypeTranslator::isRWBuffer(objectType) ||
  3682. TypeTranslator::isRWTexture(objectType))
  3683. return processBufferTextureLoad(object, doExpr(location), /*constOffset*/ 0,
  3684. /*varOffset*/ 0, /*lod*/ 0,
  3685. /*residencyCode*/ status);
  3686. // Subtract 1 for status (if it exists), and 1 for sampleIndex (if it exists),
  3687. // and 1 for location.
  3688. const bool hasOffsetArg = numArgs - hasStatusArg - isTextureMS - 1 > 0;
  3689. if (TypeTranslator::isTexture(objectType)) {
  3690. // .Load() has a second optional paramter for offset.
  3691. const auto locationId = doExpr(location);
  3692. uint32_t constOffset = 0, varOffset = 0;
  3693. uint32_t coordinate = locationId, lod = 0;
  3694. if (isTextureMS) {
  3695. // SampleIndex is only available when the Object is of Texture2DMS or
  3696. // Texture2DMSArray types. Under those cases, Offset will be the third
  3697. // parameter (index 2).
  3698. lod = doExpr(expr->getArg(1));
  3699. if (hasOffsetArg)
  3700. handleOffsetInMethodCall(expr, 2, &constOffset, &varOffset);
  3701. } else {
  3702. // For Texture Load() functions, the location parameter is a vector
  3703. // that consists of both the coordinate and the mipmap level (via the
  3704. // last vector element). We need to split it here since the
  3705. // OpImageFetch SPIR-V instruction encodes them as separate arguments.
  3706. splitVecLastElement(location->getType(), locationId, &coordinate, &lod);
  3707. // For textures other than Texture2DMS(Array), offset should be the
  3708. // second parameter (index 1).
  3709. if (hasOffsetArg)
  3710. handleOffsetInMethodCall(expr, 1, &constOffset, &varOffset);
  3711. }
  3712. return processBufferTextureLoad(object, coordinate, constOffset, varOffset,
  3713. lod, status);
  3714. }
  3715. emitError("Load() of the given object type unimplemented",
  3716. object->getExprLoc());
  3717. return 0;
  3718. }
  3719. uint32_t SPIRVEmitter::processGetDimensions(const CXXMemberCallExpr *expr) {
  3720. const auto objectType = expr->getImplicitObjectArgument()->getType();
  3721. if (TypeTranslator::isTexture(objectType) ||
  3722. TypeTranslator::isRWTexture(objectType) ||
  3723. TypeTranslator::isBuffer(objectType) ||
  3724. TypeTranslator::isRWBuffer(objectType)) {
  3725. return processBufferTextureGetDimensions(expr);
  3726. } else if (TypeTranslator::isByteAddressBuffer(objectType) ||
  3727. TypeTranslator::isRWByteAddressBuffer(objectType) ||
  3728. TypeTranslator::isStructuredBuffer(objectType) ||
  3729. TypeTranslator::isAppendStructuredBuffer(objectType) ||
  3730. TypeTranslator::isConsumeStructuredBuffer(objectType)) {
  3731. return processByteAddressBufferStructuredBufferGetDimensions(expr);
  3732. } else {
  3733. emitError("GetDimensions() of the given object type unimplemented",
  3734. expr->getExprLoc());
  3735. return 0;
  3736. }
  3737. }
  3738. SpirvEvalInfo
  3739. SPIRVEmitter::doCXXOperatorCallExpr(const CXXOperatorCallExpr *expr) {
  3740. { // Handle Buffer/RWBuffer/Texture/RWTexture indexing
  3741. const Expr *baseExpr = nullptr;
  3742. const Expr *indexExpr = nullptr;
  3743. const Expr *lodExpr = nullptr;
  3744. // For Textures, regular indexing (operator[]) uses slice 0.
  3745. if (isBufferTextureIndexing(expr, &baseExpr, &indexExpr)) {
  3746. const uint32_t lod = TypeTranslator::isTexture(baseExpr->getType())
  3747. ? theBuilder.getConstantUint32(0)
  3748. : 0;
  3749. return processBufferTextureLoad(baseExpr, doExpr(indexExpr),
  3750. /*constOffset*/ 0, /*varOffset*/ 0, lod,
  3751. /*residencyCode*/ 0);
  3752. }
  3753. // .mips[][] or .sample[][] must use the correct slice.
  3754. if (isTextureMipsSampleIndexing(expr, &baseExpr, &indexExpr, &lodExpr)) {
  3755. const uint32_t lod = doExpr(lodExpr);
  3756. return processBufferTextureLoad(baseExpr, doExpr(indexExpr),
  3757. /*constOffset*/ 0, /*varOffset*/ 0, lod,
  3758. /*residencyCode*/ 0);
  3759. }
  3760. }
  3761. llvm::SmallVector<uint32_t, 4> indices;
  3762. const Expr *baseExpr = collectArrayStructIndices(expr, &indices);
  3763. auto base = loadIfAliasVarRef(baseExpr);
  3764. if (indices.empty())
  3765. return base; // For indexing into size-1 vectors and 1xN matrices
  3766. // If we are indexing into a rvalue, to use OpAccessChain, we first need
  3767. // to create a local variable to hold the rvalue.
  3768. //
  3769. // TODO: We can optimize the codegen by emitting OpCompositeExtract if
  3770. // all indices are contant integers.
  3771. if (base.isRValue()) {
  3772. base = createTemporaryVar(baseExpr->getType(), "vector", base);
  3773. }
  3774. return turnIntoElementPtr(base, expr->getType(), indices);
  3775. }
  3776. SpirvEvalInfo
  3777. SPIRVEmitter::doExtMatrixElementExpr(const ExtMatrixElementExpr *expr) {
  3778. const Expr *baseExpr = expr->getBase();
  3779. const auto baseInfo = doExpr(baseExpr);
  3780. const auto layoutRule = baseInfo.getLayoutRule();
  3781. const auto elemType = hlsl::GetHLSLMatElementType(baseExpr->getType());
  3782. const auto accessor = expr->getEncodedElementAccess();
  3783. const uint32_t elemTypeId =
  3784. typeTranslator.translateType(elemType, layoutRule);
  3785. uint32_t rowCount = 0, colCount = 0;
  3786. hlsl::GetHLSLMatRowColCount(baseExpr->getType(), rowCount, colCount);
  3787. // Construct a temporary vector out of all elements accessed:
  3788. // 1. Create access chain for each element using OpAccessChain
  3789. // 2. Load each element using OpLoad
  3790. // 3. Create the vector using OpCompositeConstruct
  3791. llvm::SmallVector<uint32_t, 4> elements;
  3792. for (uint32_t i = 0; i < accessor.Count; ++i) {
  3793. uint32_t row = 0, col = 0, elem = 0;
  3794. accessor.GetPosition(i, &row, &col);
  3795. llvm::SmallVector<uint32_t, 2> indices;
  3796. // If the matrix only has one row/column, we are indexing into a vector
  3797. // then. Only one index is needed for such cases.
  3798. if (rowCount > 1)
  3799. indices.push_back(row);
  3800. if (colCount > 1)
  3801. indices.push_back(col);
  3802. if (baseExpr->isGLValue()) {
  3803. for (uint32_t i = 0; i < indices.size(); ++i)
  3804. indices[i] = theBuilder.getConstantInt32(indices[i]);
  3805. const uint32_t ptrType =
  3806. theBuilder.getPointerType(elemTypeId, baseInfo.getStorageClass());
  3807. if (!indices.empty()) {
  3808. assert(!baseInfo.isRValue());
  3809. // Load the element via access chain
  3810. elem = theBuilder.createAccessChain(ptrType, baseInfo, indices);
  3811. } else {
  3812. // The matrix is of size 1x1. No need to use access chain, base should
  3813. // be the source pointer.
  3814. elem = baseInfo;
  3815. }
  3816. elem = theBuilder.createLoad(elemTypeId, elem);
  3817. } else { // e.g., (mat1 + mat2)._m11
  3818. elem = theBuilder.createCompositeExtract(elemTypeId, baseInfo, indices);
  3819. }
  3820. elements.push_back(elem);
  3821. }
  3822. const auto size = elements.size();
  3823. auto valueId = elements.front();
  3824. if (size > 1) {
  3825. const uint32_t vecType = theBuilder.getVecType(elemTypeId, size);
  3826. valueId = theBuilder.createCompositeConstruct(vecType, elements);
  3827. }
  3828. // Note: Special-case: Booleans have no physical layout, and therefore when
  3829. // layout is required booleans are represented as unsigned integers.
  3830. // Therefore, after loading the uint we should convert it boolean.
  3831. if (elemType->isBooleanType() && layoutRule != LayoutRule::Void) {
  3832. const auto fromType =
  3833. size == 1 ? astContext.UnsignedIntTy
  3834. : astContext.getExtVectorType(astContext.UnsignedIntTy, size);
  3835. const auto toType =
  3836. size == 1 ? astContext.BoolTy
  3837. : astContext.getExtVectorType(astContext.BoolTy, size);
  3838. valueId = castToBool(valueId, fromType, toType);
  3839. }
  3840. return SpirvEvalInfo(valueId).setRValue();
  3841. }
  3842. SpirvEvalInfo
  3843. SPIRVEmitter::doHLSLVectorElementExpr(const HLSLVectorElementExpr *expr) {
  3844. const Expr *baseExpr = nullptr;
  3845. hlsl::VectorMemberAccessPositions accessor;
  3846. condenseVectorElementExpr(expr, &baseExpr, &accessor);
  3847. const QualType baseType = baseExpr->getType();
  3848. assert(hlsl::IsHLSLVecType(baseType));
  3849. const auto baseSize = hlsl::GetHLSLVecSize(baseType);
  3850. const auto accessorSize = static_cast<size_t>(accessor.Count);
  3851. // Depending on the number of elements selected, we emit different
  3852. // instructions.
  3853. // For vectors of size greater than 1, if we are only selecting one element,
  3854. // typical access chain or composite extraction should be fine. But if we
  3855. // are selecting more than one elements, we must resolve to vector specific
  3856. // operations.
  3857. // For size-1 vectors, if we are selecting their single elements multiple
  3858. // times, we need composite construct instructions.
  3859. if (accessorSize == 1) {
  3860. auto baseInfo = doExpr(baseExpr);
  3861. if (baseSize == 1) {
  3862. // Selecting one element from a size-1 vector. The underlying vector is
  3863. // already treated as a scalar.
  3864. return baseInfo;
  3865. }
  3866. // If the base is an lvalue, we should emit an access chain instruction
  3867. // so that we can load/store the specified element. For rvalue base,
  3868. // we should use composite extraction. We should check the immediate base
  3869. // instead of the original base here since we can have something like
  3870. // v.xyyz to turn a lvalue v into rvalue.
  3871. const auto type =
  3872. typeTranslator.translateType(expr->getType(), baseInfo.getLayoutRule());
  3873. if (!baseInfo.isRValue()) { // E.g., v.x;
  3874. const uint32_t ptrType =
  3875. theBuilder.getPointerType(type, baseInfo.getStorageClass());
  3876. const uint32_t index = theBuilder.getConstantInt32(accessor.Swz0);
  3877. // We need a lvalue here. Do not try to load.
  3878. return baseInfo.setResultId(
  3879. theBuilder.createAccessChain(ptrType, baseInfo, {index}));
  3880. } else { // E.g., (v + w).x;
  3881. // The original base vector may not be a rvalue. Need to load it if
  3882. // it is lvalue since ImplicitCastExpr (LValueToRValue) will be missing
  3883. // for that case.
  3884. auto result =
  3885. theBuilder.createCompositeExtract(type, baseInfo, {accessor.Swz0});
  3886. // Special-case: Booleans in SPIR-V do not have a physical layout. Uint is
  3887. // used to represent them when layout is required.
  3888. if (expr->getType()->isBooleanType() &&
  3889. baseInfo.getLayoutRule() != LayoutRule::Void)
  3890. result =
  3891. castToBool(result, astContext.UnsignedIntTy, astContext.BoolTy);
  3892. return baseInfo.setResultId(result);
  3893. }
  3894. }
  3895. if (baseSize == 1) {
  3896. // Selecting more than one element from a size-1 vector, for example,
  3897. // <scalar>.xx. Construct the vector.
  3898. auto info = loadIfGLValue(baseExpr);
  3899. const auto type =
  3900. typeTranslator.translateType(expr->getType(), info.getLayoutRule());
  3901. llvm::SmallVector<uint32_t, 4> components(accessorSize, info);
  3902. return info
  3903. .setResultId(theBuilder.createCompositeConstruct(type, components))
  3904. .setRValue();
  3905. }
  3906. llvm::SmallVector<uint32_t, 4> selectors;
  3907. selectors.resize(accessorSize);
  3908. // Whether we are selecting elements in the original order
  3909. bool originalOrder = baseSize == accessorSize;
  3910. for (uint32_t i = 0; i < accessorSize; ++i) {
  3911. accessor.GetPosition(i, &selectors[i]);
  3912. // We can select more elements than the vector provides. This handles
  3913. // that case too.
  3914. originalOrder &= selectors[i] == i;
  3915. }
  3916. if (originalOrder)
  3917. return doExpr(baseExpr);
  3918. auto info = loadIfGLValue(baseExpr);
  3919. const auto type =
  3920. typeTranslator.translateType(expr->getType(), info.getLayoutRule());
  3921. // Use base for both vectors. But we are only selecting values from the
  3922. // first one.
  3923. return info.setResultId(
  3924. theBuilder.createVectorShuffle(type, info, info, selectors));
  3925. }
  3926. SpirvEvalInfo SPIRVEmitter::doInitListExpr(const InitListExpr *expr) {
  3927. if (const uint32_t id = tryToEvaluateAsConst(expr))
  3928. return SpirvEvalInfo(id).setRValue();
  3929. return SpirvEvalInfo(InitListHandler(*this).process(expr)).setRValue();
  3930. }
  3931. SpirvEvalInfo SPIRVEmitter::doMemberExpr(const MemberExpr *expr) {
  3932. llvm::SmallVector<uint32_t, 4> indices;
  3933. const Expr *base = collectArrayStructIndices(expr, &indices);
  3934. auto info = loadIfAliasVarRef(base);
  3935. if (!indices.empty()) {
  3936. // Sometime we are accessing the member of a rvalue, e.g.,
  3937. // <some-function-returing-a-struct>().<some-field>
  3938. // Create a temporary variable to hold the rvalue so that we can use access
  3939. // chain to index into it.
  3940. if (info.isRValue()) {
  3941. SpirvEvalInfo tempVar = createTemporaryVar(
  3942. base->getType(), TypeTranslator::getName(base->getType()), info);
  3943. (void)turnIntoElementPtr(tempVar, expr->getType(), indices);
  3944. info.setResultId(theBuilder.createLoad(
  3945. typeTranslator.translateType(expr->getType()), tempVar));
  3946. } else {
  3947. (void)turnIntoElementPtr(info, expr->getType(), indices);
  3948. }
  3949. }
  3950. return info;
  3951. }
  3952. uint32_t SPIRVEmitter::createTemporaryVar(QualType type, llvm::StringRef name,
  3953. const SpirvEvalInfo &init) {
  3954. // We are creating a temporary variable in the Function storage class here,
  3955. // which means it has void layout rule.
  3956. const uint32_t varType = typeTranslator.translateType(type);
  3957. const std::string varName = "temp.var." + name.str();
  3958. const uint32_t varId = theBuilder.addFnVar(varType, varName);
  3959. storeValue(varId, init, type);
  3960. return varId;
  3961. }
  3962. SpirvEvalInfo SPIRVEmitter::doUnaryOperator(const UnaryOperator *expr) {
  3963. const auto opcode = expr->getOpcode();
  3964. const auto *subExpr = expr->getSubExpr();
  3965. const auto subType = subExpr->getType();
  3966. auto subValue = doExpr(subExpr);
  3967. const auto subTypeId = typeTranslator.translateType(subType);
  3968. switch (opcode) {
  3969. case UO_PreInc:
  3970. case UO_PreDec:
  3971. case UO_PostInc:
  3972. case UO_PostDec: {
  3973. const bool isPre = opcode == UO_PreInc || opcode == UO_PreDec;
  3974. const bool isInc = opcode == UO_PreInc || opcode == UO_PostInc;
  3975. const spv::Op spvOp = translateOp(isInc ? BO_Add : BO_Sub, subType);
  3976. const uint32_t originValue = theBuilder.createLoad(subTypeId, subValue);
  3977. const uint32_t one = hlsl::IsHLSLMatType(subType)
  3978. ? getMatElemValueOne(subType)
  3979. : getValueOne(subType);
  3980. uint32_t incValue = 0;
  3981. if (TypeTranslator::isMxNMatrix(subType)) {
  3982. // For matrices, we can only increment/decrement each vector of it.
  3983. const auto actOnEachVec = [this, spvOp, one](uint32_t /*index*/,
  3984. uint32_t vecType,
  3985. uint32_t lhsVec) {
  3986. const auto valId =
  3987. theBuilder.createBinaryOp(spvOp, vecType, lhsVec, one);
  3988. return SpirvEvalInfo(valId).setRValue();
  3989. };
  3990. incValue = processEachVectorInMatrix(subExpr, originValue, actOnEachVec);
  3991. } else {
  3992. incValue = theBuilder.createBinaryOp(spvOp, subTypeId, originValue, one);
  3993. }
  3994. theBuilder.createStore(subValue, incValue);
  3995. // Prefix increment/decrement operator returns a lvalue, while postfix
  3996. // increment/decrement returns a rvalue.
  3997. return isPre ? subValue : SpirvEvalInfo(originValue).setRValue();
  3998. }
  3999. case UO_Not: {
  4000. const auto valId =
  4001. theBuilder.createUnaryOp(spv::Op::OpNot, subTypeId, subValue);
  4002. return SpirvEvalInfo(valId).setRValue();
  4003. }
  4004. case UO_LNot: {
  4005. // Parsing will do the necessary casting to make sure we are applying the
  4006. // ! operator on boolean values.
  4007. const auto valId =
  4008. theBuilder.createUnaryOp(spv::Op::OpLogicalNot, subTypeId, subValue);
  4009. return SpirvEvalInfo(valId).setRValue();
  4010. }
  4011. case UO_Plus:
  4012. // No need to do anything for the prefix + operator.
  4013. return subValue;
  4014. case UO_Minus: {
  4015. // SPIR-V have two opcodes for negating values: OpSNegate and OpFNegate.
  4016. const spv::Op spvOp = isFloatOrVecOfFloatType(subType) ? spv::Op::OpFNegate
  4017. : spv::Op::OpSNegate;
  4018. const auto valId = theBuilder.createUnaryOp(spvOp, subTypeId, subValue);
  4019. return SpirvEvalInfo(valId).setRValue();
  4020. }
  4021. default:
  4022. break;
  4023. }
  4024. emitError("unary operator '%0' unimplemented", expr->getExprLoc())
  4025. << expr->getOpcodeStr(opcode);
  4026. expr->dump();
  4027. return 0;
  4028. }
  4029. spv::Op SPIRVEmitter::translateOp(BinaryOperator::Opcode op, QualType type) {
  4030. const bool isSintType = isSintOrVecMatOfSintType(type);
  4031. const bool isUintType = isUintOrVecMatOfUintType(type);
  4032. const bool isFloatType = isFloatOrVecMatOfFloatType(type);
  4033. #define BIN_OP_CASE_INT_FLOAT(kind, intBinOp, floatBinOp) \
  4034. \
  4035. case BO_##kind: { \
  4036. if (isSintType || isUintType) { \
  4037. return spv::Op::Op##intBinOp; \
  4038. } \
  4039. if (isFloatType) { \
  4040. return spv::Op::Op##floatBinOp; \
  4041. } \
  4042. } break
  4043. #define BIN_OP_CASE_SINT_UINT_FLOAT(kind, sintBinOp, uintBinOp, floatBinOp) \
  4044. \
  4045. case BO_##kind: { \
  4046. if (isSintType) { \
  4047. return spv::Op::Op##sintBinOp; \
  4048. } \
  4049. if (isUintType) { \
  4050. return spv::Op::Op##uintBinOp; \
  4051. } \
  4052. if (isFloatType) { \
  4053. return spv::Op::Op##floatBinOp; \
  4054. } \
  4055. } break
  4056. #define BIN_OP_CASE_SINT_UINT(kind, sintBinOp, uintBinOp) \
  4057. \
  4058. case BO_##kind: { \
  4059. if (isSintType) { \
  4060. return spv::Op::Op##sintBinOp; \
  4061. } \
  4062. if (isUintType) { \
  4063. return spv::Op::Op##uintBinOp; \
  4064. } \
  4065. } break
  4066. switch (op) {
  4067. case BO_EQ: {
  4068. if (isBoolOrVecMatOfBoolType(type))
  4069. return spv::Op::OpLogicalEqual;
  4070. if (isSintType || isUintType)
  4071. return spv::Op::OpIEqual;
  4072. if (isFloatType)
  4073. return spv::Op::OpFOrdEqual;
  4074. } break;
  4075. case BO_NE: {
  4076. if (isBoolOrVecMatOfBoolType(type))
  4077. return spv::Op::OpLogicalNotEqual;
  4078. if (isSintType || isUintType)
  4079. return spv::Op::OpINotEqual;
  4080. if (isFloatType)
  4081. return spv::Op::OpFOrdNotEqual;
  4082. } break;
  4083. // According to HLSL doc, all sides of the && and || expression are always
  4084. // evaluated.
  4085. case BO_LAnd:
  4086. return spv::Op::OpLogicalAnd;
  4087. case BO_LOr:
  4088. return spv::Op::OpLogicalOr;
  4089. BIN_OP_CASE_INT_FLOAT(Add, IAdd, FAdd);
  4090. BIN_OP_CASE_INT_FLOAT(AddAssign, IAdd, FAdd);
  4091. BIN_OP_CASE_INT_FLOAT(Sub, ISub, FSub);
  4092. BIN_OP_CASE_INT_FLOAT(SubAssign, ISub, FSub);
  4093. BIN_OP_CASE_INT_FLOAT(Mul, IMul, FMul);
  4094. BIN_OP_CASE_INT_FLOAT(MulAssign, IMul, FMul);
  4095. BIN_OP_CASE_SINT_UINT_FLOAT(Div, SDiv, UDiv, FDiv);
  4096. BIN_OP_CASE_SINT_UINT_FLOAT(DivAssign, SDiv, UDiv, FDiv);
  4097. // According to HLSL spec, "the modulus operator returns the remainder of
  4098. // a division." "The % operator is defined only in cases where either both
  4099. // sides are positive or both sides are negative."
  4100. //
  4101. // In SPIR-V, there are two reminder operations: Op*Rem and Op*Mod. With
  4102. // the former, the sign of a non-0 result comes from Operand 1, while
  4103. // with the latter, from Operand 2.
  4104. //
  4105. // For operands with different signs, technically we can map % to either
  4106. // Op*Rem or Op*Mod since it's undefined behavior. But it is more
  4107. // consistent with C (HLSL starts as a C derivative) and Clang frontend
  4108. // const expression evaluation if we map % to Op*Rem.
  4109. //
  4110. // Note there is no OpURem in SPIR-V.
  4111. BIN_OP_CASE_SINT_UINT_FLOAT(Rem, SRem, UMod, FRem);
  4112. BIN_OP_CASE_SINT_UINT_FLOAT(RemAssign, SRem, UMod, FRem);
  4113. BIN_OP_CASE_SINT_UINT_FLOAT(LT, SLessThan, ULessThan, FOrdLessThan);
  4114. BIN_OP_CASE_SINT_UINT_FLOAT(LE, SLessThanEqual, ULessThanEqual,
  4115. FOrdLessThanEqual);
  4116. BIN_OP_CASE_SINT_UINT_FLOAT(GT, SGreaterThan, UGreaterThan,
  4117. FOrdGreaterThan);
  4118. BIN_OP_CASE_SINT_UINT_FLOAT(GE, SGreaterThanEqual, UGreaterThanEqual,
  4119. FOrdGreaterThanEqual);
  4120. BIN_OP_CASE_SINT_UINT(And, BitwiseAnd, BitwiseAnd);
  4121. BIN_OP_CASE_SINT_UINT(AndAssign, BitwiseAnd, BitwiseAnd);
  4122. BIN_OP_CASE_SINT_UINT(Or, BitwiseOr, BitwiseOr);
  4123. BIN_OP_CASE_SINT_UINT(OrAssign, BitwiseOr, BitwiseOr);
  4124. BIN_OP_CASE_SINT_UINT(Xor, BitwiseXor, BitwiseXor);
  4125. BIN_OP_CASE_SINT_UINT(XorAssign, BitwiseXor, BitwiseXor);
  4126. BIN_OP_CASE_SINT_UINT(Shl, ShiftLeftLogical, ShiftLeftLogical);
  4127. BIN_OP_CASE_SINT_UINT(ShlAssign, ShiftLeftLogical, ShiftLeftLogical);
  4128. BIN_OP_CASE_SINT_UINT(Shr, ShiftRightArithmetic, ShiftRightLogical);
  4129. BIN_OP_CASE_SINT_UINT(ShrAssign, ShiftRightArithmetic, ShiftRightLogical);
  4130. default:
  4131. break;
  4132. }
  4133. #undef BIN_OP_CASE_INT_FLOAT
  4134. #undef BIN_OP_CASE_SINT_UINT_FLOAT
  4135. #undef BIN_OP_CASE_SINT_UINT
  4136. emitError("translating binary operator '%0' unimplemented", {})
  4137. << BinaryOperator::getOpcodeStr(op);
  4138. return spv::Op::OpNop;
  4139. }
  4140. SpirvEvalInfo SPIRVEmitter::processAssignment(const Expr *lhs,
  4141. const SpirvEvalInfo &rhs,
  4142. const bool isCompoundAssignment,
  4143. SpirvEvalInfo lhsPtr) {
  4144. // Assigning to vector swizzling should be handled differently.
  4145. if (SpirvEvalInfo result = tryToAssignToVectorElements(lhs, rhs))
  4146. return result;
  4147. // Assigning to matrix swizzling should be handled differently.
  4148. if (SpirvEvalInfo result = tryToAssignToMatrixElements(lhs, rhs))
  4149. return result;
  4150. // Assigning to a RWBuffer/RWTexture should be handled differently.
  4151. if (SpirvEvalInfo result = tryToAssignToRWBufferRWTexture(lhs, rhs))
  4152. return result;
  4153. // Normal assignment procedure
  4154. if (!lhsPtr)
  4155. lhsPtr = doExpr(lhs);
  4156. storeValue(lhsPtr, rhs, lhs->getType());
  4157. // Plain assignment returns a rvalue, while compound assignment returns
  4158. // lvalue.
  4159. return isCompoundAssignment ? lhsPtr : rhs;
  4160. }
  4161. void SPIRVEmitter::storeValue(const SpirvEvalInfo &lhsPtr,
  4162. const SpirvEvalInfo &rhsVal,
  4163. const QualType lhsValType) {
  4164. QualType matElemType = {};
  4165. const bool lhsIsMat = typeTranslator.isMxNMatrix(lhsValType, &matElemType);
  4166. const bool lhsIsFloatMat = lhsIsMat && matElemType->isFloatingType();
  4167. const bool lhsIsNonFpMat = lhsIsMat && !matElemType->isFloatingType();
  4168. if (typeTranslator.isScalarType(lhsValType) ||
  4169. typeTranslator.isVectorType(lhsValType) || lhsIsFloatMat) {
  4170. uint32_t rhsValId = rhsVal;
  4171. // Special-case: According to the SPIR-V Spec: There is no physical size
  4172. // or bit pattern defined for boolean type. Therefore an unsigned integer
  4173. // is used to represent booleans when layout is required. In such cases,
  4174. // we should cast the boolean to uint before creating OpStore.
  4175. if (isBoolOrVecOfBoolType(lhsValType) &&
  4176. lhsPtr.getLayoutRule() != LayoutRule::Void) {
  4177. uint32_t vecSize = 1;
  4178. const bool isVec =
  4179. TypeTranslator::isVectorType(lhsValType, nullptr, &vecSize);
  4180. const auto toType =
  4181. isVec ? astContext.getExtVectorType(astContext.UnsignedIntTy, vecSize)
  4182. : astContext.UnsignedIntTy;
  4183. const auto fromType =
  4184. isVec ? astContext.getExtVectorType(astContext.BoolTy, vecSize)
  4185. : astContext.BoolTy;
  4186. rhsValId = castToInt(rhsValId, fromType, toType, {});
  4187. }
  4188. theBuilder.createStore(lhsPtr, rhsValId);
  4189. } else if (TypeTranslator::isOpaqueType(lhsValType)) {
  4190. // Resource types are represented using RecordType in the AST.
  4191. // Handle them before the general RecordType.
  4192. //
  4193. // HLSL allows to put resource types that translating into SPIR-V opaque
  4194. // types in structs, or assign to variables of resource types. These can all
  4195. // result in illegal SPIR-V for Vulkan. We just translate here literally and
  4196. // let SPIRV-Tools opt to do the legalization work.
  4197. //
  4198. // Note: legalization specific code
  4199. theBuilder.createStore(lhsPtr, rhsVal);
  4200. needsLegalization = true;
  4201. } else if (TypeTranslator::isAKindOfStructuredOrByteBuffer(lhsValType)) {
  4202. // The rhs should be a pointer and the lhs should be a pointer-to-pointer.
  4203. // Directly store the pointer here and let SPIRV-Tools opt to do the clean
  4204. // up.
  4205. //
  4206. // Note: legalization specific code
  4207. theBuilder.createStore(lhsPtr, rhsVal);
  4208. needsLegalization = true;
  4209. // For ConstantBuffers/TextureBuffers, we decompose and assign each field
  4210. // recursively like normal structs using the following logic.
  4211. //
  4212. // The frontend forbids declaring ConstantBuffer<T> or TextureBuffer<T>
  4213. // variables as function parameters/returns/variables, but happily accepts
  4214. // assignments/returns from ConstantBuffer<T>/TextureBuffer<T> to function
  4215. // parameters/returns/variables of type T. And ConstantBuffer<T> is not
  4216. // represented differently as struct T.
  4217. } else if (TypeTranslator::isOpaqueArrayType(lhsValType)) {
  4218. // For opaque array types, we cannot perform OpLoad on the whole array and
  4219. // then write out as a whole; instead, we need to OpLoad each element
  4220. // using access chains. This is to influence later SPIR-V transformations
  4221. // to use access chains to access each opaque object; if we do array
  4222. // wholesale handling here, they will be in the final transformed code.
  4223. // Drivers don't like that.
  4224. // TODO: consider moving this hack into SPIRV-Tools as a transformation.
  4225. assert(lhsValType->isConstantArrayType());
  4226. assert(!rhsVal.isRValue());
  4227. const auto *arrayType = astContext.getAsConstantArrayType(lhsValType);
  4228. const auto elemType = arrayType->getElementType();
  4229. const auto arraySize =
  4230. static_cast<uint32_t>(arrayType->getSize().getZExtValue());
  4231. // Do separate load of each element via access chain
  4232. llvm::SmallVector<uint32_t, 8> elements;
  4233. for (uint32_t i = 0; i < arraySize; ++i) {
  4234. const auto subRhsValType =
  4235. typeTranslator.translateType(elemType, rhsVal.getLayoutRule());
  4236. const auto subRhsPtrType =
  4237. theBuilder.getPointerType(subRhsValType, rhsVal.getStorageClass());
  4238. const auto subRhsPtr = theBuilder.createAccessChain(
  4239. subRhsPtrType, rhsVal, {theBuilder.getConstantInt32(i)});
  4240. elements.push_back(theBuilder.createLoad(subRhsValType, subRhsPtr));
  4241. }
  4242. // Create a new composite and write out once
  4243. const auto lhsValTypeId =
  4244. typeTranslator.translateType(lhsValType, lhsPtr.getLayoutRule());
  4245. theBuilder.createStore(
  4246. lhsPtr, theBuilder.createCompositeConstruct(lhsValTypeId, elements));
  4247. } else if (lhsPtr.getLayoutRule() == rhsVal.getLayoutRule()) {
  4248. // If lhs and rhs has the same memory layout, we should be safe to load
  4249. // from rhs and directly store into lhs and avoid decomposing rhs.
  4250. // Note: this check should happen after those setting needsLegalization.
  4251. // TODO: is this optimization always correct?
  4252. theBuilder.createStore(lhsPtr, rhsVal);
  4253. } else if (lhsValType->isRecordType() || lhsValType->isConstantArrayType() ||
  4254. lhsIsNonFpMat) {
  4255. theBuilder.createStore(
  4256. lhsPtr, reconstructValue(rhsVal, lhsValType, lhsPtr.getLayoutRule()));
  4257. } else {
  4258. emitError("storing value of type %0 unimplemented", {}) << lhsValType;
  4259. }
  4260. }
  4261. uint32_t SPIRVEmitter::reconstructValue(const SpirvEvalInfo &srcVal,
  4262. const QualType valType,
  4263. LayoutRule dstLR) {
  4264. // Lambda for casting scalar or vector of bool<-->uint in cases where one side
  4265. // of the reconstruction (lhs or rhs) has a layout rule.
  4266. const auto handleBooleanLayout = [this, &srcVal, dstLR](uint32_t val,
  4267. QualType valType) {
  4268. // We only need to cast if we have a scalar or vector of booleans.
  4269. if (!isBoolOrVecOfBoolType(valType))
  4270. return val;
  4271. LayoutRule srcLR = srcVal.getLayoutRule();
  4272. // Source value has a layout rule, and has therefore been represented
  4273. // as a uint. Cast it to boolean before using.
  4274. bool shouldCastToBool =
  4275. srcLR != LayoutRule::Void && dstLR == LayoutRule::Void;
  4276. // Destination has a layout rule, and should therefore be represented
  4277. // as a uint. Cast to uint before using.
  4278. bool shouldCastToUint =
  4279. srcLR == LayoutRule::Void && dstLR != LayoutRule::Void;
  4280. // No boolean layout issues to take care of.
  4281. if (!shouldCastToBool && !shouldCastToUint)
  4282. return val;
  4283. uint32_t vecSize = 1;
  4284. TypeTranslator::isVectorType(valType, nullptr, &vecSize);
  4285. QualType boolType =
  4286. vecSize == 1 ? astContext.BoolTy
  4287. : astContext.getExtVectorType(astContext.BoolTy, vecSize);
  4288. QualType uintType =
  4289. vecSize == 1
  4290. ? astContext.UnsignedIntTy
  4291. : astContext.getExtVectorType(astContext.UnsignedIntTy, vecSize);
  4292. if (shouldCastToBool)
  4293. return castToBool(val, uintType, boolType);
  4294. if (shouldCastToUint)
  4295. return castToInt(val, boolType, uintType, {});
  4296. return val;
  4297. };
  4298. // Lambda for cases where we want to reconstruct an array
  4299. const auto reconstructArray = [this, &srcVal, valType,
  4300. dstLR](uint32_t arraySize,
  4301. QualType arrayElemType) {
  4302. llvm::SmallVector<uint32_t, 4> elements;
  4303. for (uint32_t i = 0; i < arraySize; ++i) {
  4304. const auto subSrcValType =
  4305. typeTranslator.translateType(arrayElemType, srcVal.getLayoutRule());
  4306. const auto subSrcVal =
  4307. theBuilder.createCompositeExtract(subSrcValType, srcVal, {i});
  4308. elements.push_back(reconstructValue(srcVal.substResultId(subSrcVal),
  4309. arrayElemType, dstLR));
  4310. }
  4311. const auto dstValType = typeTranslator.translateType(valType, dstLR);
  4312. return theBuilder.createCompositeConstruct(dstValType, elements);
  4313. };
  4314. // Constant arrays
  4315. if (const auto *arrayType = astContext.getAsConstantArrayType(valType)) {
  4316. const auto elemType = arrayType->getElementType();
  4317. const auto size =
  4318. static_cast<uint32_t>(arrayType->getSize().getZExtValue());
  4319. return reconstructArray(size, elemType);
  4320. }
  4321. // Non-floating-point matrices
  4322. QualType matElemType = {};
  4323. uint32_t numRows = 0, numCols = 0;
  4324. const bool isNonFpMat =
  4325. typeTranslator.isMxNMatrix(valType, &matElemType, &numRows, &numCols) &&
  4326. !matElemType->isFloatingType();
  4327. if (isNonFpMat) {
  4328. // Note: This check should happen before the RecordType check.
  4329. // Non-fp matrices are represented as arrays of vectors in SPIR-V.
  4330. // Each array element is a vector. Get the QualType for the vector.
  4331. const auto elemType = astContext.getExtVectorType(matElemType, numCols);
  4332. return reconstructArray(numRows, elemType);
  4333. }
  4334. // Note: This check should happen before the RecordType check since
  4335. // vector/matrix/resource types are represented as RecordType in the AST.
  4336. if (hlsl::IsHLSLVecMatType(valType) || hlsl::IsHLSLResourceType(valType))
  4337. return handleBooleanLayout(srcVal, valType);
  4338. // Structs
  4339. if (const auto *recordType = valType->getAs<RecordType>()) {
  4340. uint32_t index = 0;
  4341. llvm::SmallVector<uint32_t, 4> elements;
  4342. for (const auto *field : recordType->getDecl()->fields()) {
  4343. const auto subSrcValType = typeTranslator.translateType(
  4344. field->getType(), srcVal.getLayoutRule());
  4345. const auto subSrcVal =
  4346. theBuilder.createCompositeExtract(subSrcValType, srcVal, {index});
  4347. elements.push_back(reconstructValue(srcVal.substResultId(subSrcVal),
  4348. field->getType(), dstLR));
  4349. ++index;
  4350. }
  4351. const auto dstValType = typeTranslator.translateType(valType, dstLR);
  4352. return theBuilder.createCompositeConstruct(dstValType, elements);
  4353. }
  4354. return handleBooleanLayout(srcVal, valType);
  4355. }
  4356. SpirvEvalInfo SPIRVEmitter::processBinaryOp(const Expr *lhs, const Expr *rhs,
  4357. const BinaryOperatorKind opcode,
  4358. const QualType computationType,
  4359. const QualType resultType,
  4360. SourceRange sourceRange,
  4361. SpirvEvalInfo *lhsInfo,
  4362. const spv::Op mandateGenOpcode) {
  4363. const QualType lhsType = lhs->getType();
  4364. const QualType rhsType = rhs->getType();
  4365. // Binary logical operations (such as ==, !=, etc) that return a boolean type
  4366. // may get a literal (e.g. 0, 1, etc.) as lhs or rhs args. Since only
  4367. // non-zero-ness of these literals matter, they can be translated as 32-bits.
  4368. TypeTranslator::LiteralTypeHint hint(typeTranslator);
  4369. if (resultType->isBooleanType()) {
  4370. if (lhsType->isSpecificBuiltinType(BuiltinType::LitInt) ||
  4371. rhsType->isSpecificBuiltinType(BuiltinType::LitInt))
  4372. hint.setHint(astContext.IntTy);
  4373. if (lhsType->isSpecificBuiltinType(BuiltinType::LitFloat) ||
  4374. rhsType->isSpecificBuiltinType(BuiltinType::LitFloat))
  4375. hint.setHint(astContext.FloatTy);
  4376. }
  4377. // If the operands are of matrix type, we need to dispatch the operation
  4378. // onto each element vector iff the operands are not degenerated matrices
  4379. // and we don't have a matrix specific SPIR-V instruction for the operation.
  4380. if (!isSpirvMatrixOp(mandateGenOpcode) &&
  4381. TypeTranslator::isMxNMatrix(lhsType)) {
  4382. return processMatrixBinaryOp(lhs, rhs, opcode, sourceRange);
  4383. }
  4384. // Comma operator works differently from other binary operations as there is
  4385. // no SPIR-V instruction for it. For each comma, we must evaluate lhs and rhs
  4386. // respectively, and return the results of rhs.
  4387. if (opcode == BO_Comma) {
  4388. (void)doExpr(lhs);
  4389. return doExpr(rhs);
  4390. }
  4391. SpirvEvalInfo rhsVal = 0, lhsPtr = 0, lhsVal = 0;
  4392. if (BinaryOperator::isCompoundAssignmentOp(opcode)) {
  4393. // Evalute rhs before lhs
  4394. rhsVal = loadIfGLValue(rhs);
  4395. lhsVal = lhsPtr = doExpr(lhs);
  4396. // This is a compound assignment. We need to load the lhs value if lhs
  4397. // is not already rvalue and does not generate a vector shuffle.
  4398. if (!lhsPtr.isRValue() && !isVectorShuffle(lhs)) {
  4399. lhsVal = loadIfGLValue(lhs, lhsPtr);
  4400. }
  4401. // For a compound assignments, the AST does not have the proper implicit
  4402. // cast if lhs and rhs have different types. So we need to manually cast lhs
  4403. // to the computation type.
  4404. if (computationType != lhsType)
  4405. lhsVal.setResultId(
  4406. castToType(lhsVal, lhsType, computationType, lhs->getExprLoc()));
  4407. } else {
  4408. // Evalute lhs before rhs
  4409. lhsPtr = doExpr(lhs);
  4410. lhsVal = loadIfGLValue(lhs, lhsPtr);
  4411. rhsVal = loadIfGLValue(rhs);
  4412. }
  4413. if (lhsInfo)
  4414. *lhsInfo = lhsPtr;
  4415. const spv::Op spvOp = (mandateGenOpcode == spv::Op::Max)
  4416. ? translateOp(opcode, computationType)
  4417. : mandateGenOpcode;
  4418. switch (opcode) {
  4419. case BO_Shl:
  4420. case BO_Shr:
  4421. case BO_ShlAssign:
  4422. case BO_ShrAssign:
  4423. // We need to cull the RHS to make sure that we are not shifting by an
  4424. // amount that is larger than the bitwidth of the LHS.
  4425. rhsVal.setResultId(theBuilder.createBinaryOp(
  4426. spv::Op::OpBitwiseAnd, typeTranslator.translateType(computationType),
  4427. rhsVal, getMaskForBitwidthValue(rhsType)));
  4428. // Fall through
  4429. case BO_Add:
  4430. case BO_Sub:
  4431. case BO_Mul:
  4432. case BO_Div:
  4433. case BO_Rem:
  4434. case BO_LT:
  4435. case BO_LE:
  4436. case BO_GT:
  4437. case BO_GE:
  4438. case BO_EQ:
  4439. case BO_NE:
  4440. case BO_And:
  4441. case BO_Or:
  4442. case BO_Xor:
  4443. case BO_LAnd:
  4444. case BO_LOr:
  4445. case BO_AddAssign:
  4446. case BO_SubAssign:
  4447. case BO_MulAssign:
  4448. case BO_DivAssign:
  4449. case BO_RemAssign:
  4450. case BO_AndAssign:
  4451. case BO_OrAssign:
  4452. case BO_XorAssign: {
  4453. // To evaluate this expression as an OpSpecConstantOp, we need to make sure
  4454. // both operands are constant and at least one of them is a spec constant.
  4455. if (lhsVal.isConstant() && rhsVal.isConstant() &&
  4456. (lhsVal.isSpecConstant() || rhsVal.isSpecConstant()) &&
  4457. isAcceptedSpecConstantBinaryOp(spvOp)) {
  4458. const auto valId = theBuilder.createSpecConstantBinaryOp(
  4459. spvOp, typeTranslator.translateType(resultType), lhsVal, rhsVal);
  4460. return SpirvEvalInfo(valId).setRValue().setSpecConstant();
  4461. }
  4462. // Normal binary operation
  4463. uint32_t valId = 0;
  4464. if (BinaryOperator::isCompoundAssignmentOp(opcode)) {
  4465. valId = theBuilder.createBinaryOp(
  4466. spvOp, typeTranslator.translateType(computationType), lhsVal, rhsVal);
  4467. // For a compound assignments, the AST does not have the proper implicit
  4468. // cast if lhs and rhs have different types. So we need to manually cast
  4469. // the result back to lhs' type.
  4470. if (computationType != lhsType)
  4471. valId = castToType(valId, computationType, lhsType, lhs->getExprLoc());
  4472. } else {
  4473. valId = theBuilder.createBinaryOp(
  4474. spvOp, typeTranslator.translateType(resultType), lhsVal, rhsVal);
  4475. }
  4476. auto result = SpirvEvalInfo(valId).setRValue();
  4477. if (lhsVal.isRelaxedPrecision() || rhsVal.isRelaxedPrecision())
  4478. result.setRelaxedPrecision();
  4479. return result;
  4480. }
  4481. case BO_Assign:
  4482. llvm_unreachable("assignment should not be handled here");
  4483. }
  4484. emitError("binary operator '%0' unimplemented", lhs->getExprLoc())
  4485. << BinaryOperator::getOpcodeStr(opcode) << sourceRange;
  4486. return 0;
  4487. }
  4488. void SPIRVEmitter::initOnce(QualType varType, std::string varName,
  4489. uint32_t varPtr, const Expr *varInit) {
  4490. // For uninitialized resource objects, we do nothing since there is no
  4491. // meaningful zero values for them.
  4492. if (!varInit && hlsl::IsHLSLResourceType(varType))
  4493. return;
  4494. const uint32_t boolType = theBuilder.getBoolType();
  4495. varName = "init.done." + varName;
  4496. // Create a file/module visible variable to hold the initialization state.
  4497. const uint32_t initDoneVar =
  4498. theBuilder.addModuleVar(boolType, spv::StorageClass::Private, varName,
  4499. theBuilder.getConstantBool(false));
  4500. const uint32_t condition = theBuilder.createLoad(boolType, initDoneVar);
  4501. const uint32_t todoBB = theBuilder.createBasicBlock("if.init.todo");
  4502. const uint32_t doneBB = theBuilder.createBasicBlock("if.init.done");
  4503. // If initDoneVar contains true, we jump to the "done" basic block; otherwise,
  4504. // jump to the "todo" basic block.
  4505. theBuilder.createConditionalBranch(condition, doneBB, todoBB, doneBB);
  4506. theBuilder.addSuccessor(todoBB);
  4507. theBuilder.addSuccessor(doneBB);
  4508. theBuilder.setMergeTarget(doneBB);
  4509. theBuilder.setInsertPoint(todoBB);
  4510. // Do initialization and mark done
  4511. if (varInit) {
  4512. storeValue(
  4513. // Static function variable are of private storage class
  4514. SpirvEvalInfo(varPtr).setStorageClass(spv::StorageClass::Private),
  4515. doExpr(varInit), varInit->getType());
  4516. } else {
  4517. const auto typeId = typeTranslator.translateType(varType);
  4518. theBuilder.createStore(varPtr, theBuilder.getConstantNull(typeId));
  4519. }
  4520. theBuilder.createStore(initDoneVar, theBuilder.getConstantBool(true));
  4521. theBuilder.createBranch(doneBB);
  4522. theBuilder.addSuccessor(doneBB);
  4523. theBuilder.setInsertPoint(doneBB);
  4524. }
  4525. bool SPIRVEmitter::isVectorShuffle(const Expr *expr) {
  4526. // TODO: the following check is essentially duplicated from
  4527. // doHLSLVectorElementExpr. Should unify them.
  4528. if (const auto *vecElemExpr = dyn_cast<HLSLVectorElementExpr>(expr)) {
  4529. const Expr *base = nullptr;
  4530. hlsl::VectorMemberAccessPositions accessor;
  4531. condenseVectorElementExpr(vecElemExpr, &base, &accessor);
  4532. const auto accessorSize = accessor.Count;
  4533. if (accessorSize == 1) {
  4534. // Selecting only one element. OpAccessChain or OpCompositeExtract for
  4535. // such cases.
  4536. return false;
  4537. }
  4538. const auto baseSize = hlsl::GetHLSLVecSize(base->getType());
  4539. if (accessorSize != baseSize)
  4540. return true;
  4541. for (uint32_t i = 0; i < accessorSize; ++i) {
  4542. uint32_t position;
  4543. accessor.GetPosition(i, &position);
  4544. if (position != i)
  4545. return true;
  4546. }
  4547. // Selecting exactly the original vector. No vector shuffle generated.
  4548. return false;
  4549. }
  4550. return false;
  4551. }
  4552. bool SPIRVEmitter::isTextureMipsSampleIndexing(const CXXOperatorCallExpr *expr,
  4553. const Expr **base,
  4554. const Expr **location,
  4555. const Expr **lod) {
  4556. if (!expr)
  4557. return false;
  4558. // <object>.mips[][] consists of an outer operator[] and an inner operator[]
  4559. const CXXOperatorCallExpr *outerExpr = expr;
  4560. if (outerExpr->getOperator() != OverloadedOperatorKind::OO_Subscript)
  4561. return false;
  4562. const Expr *arg0 = outerExpr->getArg(0)->IgnoreParenNoopCasts(astContext);
  4563. const CXXOperatorCallExpr *innerExpr = dyn_cast<CXXOperatorCallExpr>(arg0);
  4564. // Must have an inner operator[]
  4565. if (!innerExpr ||
  4566. innerExpr->getOperator() != OverloadedOperatorKind::OO_Subscript) {
  4567. return false;
  4568. }
  4569. const Expr *innerArg0 =
  4570. innerExpr->getArg(0)->IgnoreParenNoopCasts(astContext);
  4571. const MemberExpr *memberExpr = dyn_cast<MemberExpr>(innerArg0);
  4572. if (!memberExpr)
  4573. return false;
  4574. // Must be accessing the member named "mips" or "sample"
  4575. const auto &memberName =
  4576. memberExpr->getMemberNameInfo().getName().getAsString();
  4577. if (memberName != "mips" && memberName != "sample")
  4578. return false;
  4579. const Expr *object = memberExpr->getBase();
  4580. const auto objectType = object->getType();
  4581. if (!TypeTranslator::isTexture(objectType))
  4582. return false;
  4583. if (base)
  4584. *base = object;
  4585. if (lod)
  4586. *lod = innerExpr->getArg(1);
  4587. if (location)
  4588. *location = outerExpr->getArg(1);
  4589. return true;
  4590. }
  4591. bool SPIRVEmitter::isBufferTextureIndexing(const CXXOperatorCallExpr *indexExpr,
  4592. const Expr **base,
  4593. const Expr **index) {
  4594. if (!indexExpr)
  4595. return false;
  4596. // Must be operator[]
  4597. if (indexExpr->getOperator() != OverloadedOperatorKind::OO_Subscript)
  4598. return false;
  4599. const Expr *object = indexExpr->getArg(0);
  4600. const auto objectType = object->getType();
  4601. if (TypeTranslator::isBuffer(objectType) ||
  4602. TypeTranslator::isRWBuffer(objectType) ||
  4603. TypeTranslator::isTexture(objectType) ||
  4604. TypeTranslator::isRWTexture(objectType)) {
  4605. if (base)
  4606. *base = object;
  4607. if (index)
  4608. *index = indexExpr->getArg(1);
  4609. return true;
  4610. }
  4611. return false;
  4612. }
  4613. void SPIRVEmitter::condenseVectorElementExpr(
  4614. const HLSLVectorElementExpr *expr, const Expr **basePtr,
  4615. hlsl::VectorMemberAccessPositions *flattenedAccessor) {
  4616. llvm::SmallVector<hlsl::VectorMemberAccessPositions, 2> accessors;
  4617. accessors.push_back(expr->getEncodedElementAccess());
  4618. // Recursively descending until we find the true base vector. In the
  4619. // meanwhile, collecting accessors in the reverse order.
  4620. *basePtr = expr->getBase();
  4621. while (const auto *vecElemBase = dyn_cast<HLSLVectorElementExpr>(*basePtr)) {
  4622. accessors.push_back(vecElemBase->getEncodedElementAccess());
  4623. *basePtr = vecElemBase->getBase();
  4624. }
  4625. *flattenedAccessor = accessors.back();
  4626. for (int32_t i = accessors.size() - 2; i >= 0; --i) {
  4627. const auto &currentAccessor = accessors[i];
  4628. // Apply the current level of accessor to the flattened accessor of all
  4629. // previous levels of ones.
  4630. hlsl::VectorMemberAccessPositions combinedAccessor;
  4631. for (uint32_t j = 0; j < currentAccessor.Count; ++j) {
  4632. uint32_t currentPosition = 0;
  4633. currentAccessor.GetPosition(j, &currentPosition);
  4634. uint32_t previousPosition = 0;
  4635. flattenedAccessor->GetPosition(currentPosition, &previousPosition);
  4636. combinedAccessor.SetPosition(j, previousPosition);
  4637. }
  4638. combinedAccessor.Count = currentAccessor.Count;
  4639. combinedAccessor.IsValid =
  4640. flattenedAccessor->IsValid && currentAccessor.IsValid;
  4641. *flattenedAccessor = combinedAccessor;
  4642. }
  4643. }
  4644. SpirvEvalInfo SPIRVEmitter::createVectorSplat(const Expr *scalarExpr,
  4645. uint32_t size) {
  4646. bool isConstVal = false;
  4647. SpirvEvalInfo scalarVal = 0;
  4648. // Try to evaluate the element as constant first. If successful, then we
  4649. // can generate constant instructions for this vector splat.
  4650. if (scalarVal = tryToEvaluateAsConst(scalarExpr)) {
  4651. isConstVal = true;
  4652. } else {
  4653. scalarVal = doExpr(scalarExpr);
  4654. }
  4655. if (size == 1) {
  4656. // Just return the scalar value for vector splat with size 1.
  4657. // Note that can be used as an lvalue, so we need to carry over
  4658. // the lvalueness for non-constant cases.
  4659. return isConstVal ? scalarVal.setConstant().setRValue() : scalarVal;
  4660. }
  4661. const uint32_t vecType = theBuilder.getVecType(
  4662. typeTranslator.translateType(scalarExpr->getType()), size);
  4663. llvm::SmallVector<uint32_t, 4> elements(size_t(size), scalarVal);
  4664. // TODO: we are saying the constant has Function storage class here.
  4665. // Should find a more meaningful one.
  4666. if (isConstVal) {
  4667. const auto valueId = theBuilder.getConstantComposite(vecType, elements);
  4668. return SpirvEvalInfo(valueId).setConstant().setRValue();
  4669. } else {
  4670. const auto valueId = theBuilder.createCompositeConstruct(vecType, elements);
  4671. return SpirvEvalInfo(valueId).setRValue();
  4672. }
  4673. }
  4674. void SPIRVEmitter::splitVecLastElement(QualType vecType, uint32_t vec,
  4675. uint32_t *residual,
  4676. uint32_t *lastElement) {
  4677. assert(hlsl::IsHLSLVecType(vecType));
  4678. const uint32_t count = hlsl::GetHLSLVecSize(vecType);
  4679. assert(count > 1);
  4680. const uint32_t elemTypeId =
  4681. typeTranslator.translateType(hlsl::GetHLSLVecElementType(vecType));
  4682. if (count == 2) {
  4683. *residual = theBuilder.createCompositeExtract(elemTypeId, vec, 0);
  4684. } else {
  4685. llvm::SmallVector<uint32_t, 4> indices;
  4686. for (uint32_t i = 0; i < count - 1; ++i)
  4687. indices.push_back(i);
  4688. const uint32_t typeId = theBuilder.getVecType(elemTypeId, count - 1);
  4689. *residual = theBuilder.createVectorShuffle(typeId, vec, vec, indices);
  4690. }
  4691. *lastElement =
  4692. theBuilder.createCompositeExtract(elemTypeId, vec, {count - 1});
  4693. }
  4694. SpirvEvalInfo
  4695. SPIRVEmitter::tryToGenFloatVectorScale(const BinaryOperator *expr) {
  4696. const QualType type = expr->getType();
  4697. const SourceRange range = expr->getSourceRange();
  4698. // We can only translate floatN * float into OpVectorTimesScalar.
  4699. // So the result type must be floatN.
  4700. if (!hlsl::IsHLSLVecType(type) ||
  4701. !hlsl::GetHLSLVecElementType(type)->isFloatingType())
  4702. return 0;
  4703. const Expr *lhs = expr->getLHS();
  4704. const Expr *rhs = expr->getRHS();
  4705. // Multiplying a float vector with a float scalar will be represented in
  4706. // AST via a binary operation with two float vectors as operands; one of
  4707. // the operand is from an implicit cast with kind CK_HLSLVectorSplat.
  4708. // vector * scalar
  4709. if (hlsl::IsHLSLVecType(lhs->getType())) {
  4710. if (const auto *cast = dyn_cast<ImplicitCastExpr>(rhs)) {
  4711. if (cast->getCastKind() == CK_HLSLVectorSplat) {
  4712. const QualType vecType = expr->getType();
  4713. if (isa<CompoundAssignOperator>(expr)) {
  4714. SpirvEvalInfo lhsPtr = 0;
  4715. const auto result = processBinaryOp(
  4716. lhs, cast->getSubExpr(), expr->getOpcode(), vecType, vecType,
  4717. range, &lhsPtr, spv::Op::OpVectorTimesScalar);
  4718. return processAssignment(lhs, result, true, lhsPtr);
  4719. } else {
  4720. return processBinaryOp(lhs, cast->getSubExpr(), expr->getOpcode(),
  4721. vecType, vecType, range, nullptr,
  4722. spv::Op::OpVectorTimesScalar);
  4723. }
  4724. }
  4725. }
  4726. }
  4727. // scalar * vector
  4728. if (hlsl::IsHLSLVecType(rhs->getType())) {
  4729. if (const auto *cast = dyn_cast<ImplicitCastExpr>(lhs)) {
  4730. if (cast->getCastKind() == CK_HLSLVectorSplat) {
  4731. const QualType vecType = expr->getType();
  4732. // We need to switch the positions of lhs and rhs here because
  4733. // OpVectorTimesScalar requires the first operand to be a vector and
  4734. // the second to be a scalar.
  4735. return processBinaryOp(rhs, cast->getSubExpr(), expr->getOpcode(),
  4736. vecType, vecType, range, nullptr,
  4737. spv::Op::OpVectorTimesScalar);
  4738. }
  4739. }
  4740. }
  4741. return 0;
  4742. }
  4743. SpirvEvalInfo
  4744. SPIRVEmitter::tryToGenFloatMatrixScale(const BinaryOperator *expr) {
  4745. const QualType type = expr->getType();
  4746. const SourceRange range = expr->getSourceRange();
  4747. // We can only translate floatMxN * float into OpMatrixTimesScalar.
  4748. // So the result type must be floatMxN.
  4749. if (!hlsl::IsHLSLMatType(type) ||
  4750. !hlsl::GetHLSLMatElementType(type)->isFloatingType())
  4751. return 0;
  4752. const Expr *lhs = expr->getLHS();
  4753. const Expr *rhs = expr->getRHS();
  4754. const QualType lhsType = lhs->getType();
  4755. const QualType rhsType = rhs->getType();
  4756. const auto selectOpcode = [](const QualType ty) {
  4757. return TypeTranslator::isMx1Matrix(ty) || TypeTranslator::is1xNMatrix(ty)
  4758. ? spv::Op::OpVectorTimesScalar
  4759. : spv::Op::OpMatrixTimesScalar;
  4760. };
  4761. // Multiplying a float matrix with a float scalar will be represented in
  4762. // AST via a binary operation with two float matrices as operands; one of
  4763. // the operand is from an implicit cast with kind CK_HLSLMatrixSplat.
  4764. // matrix * scalar
  4765. if (hlsl::IsHLSLMatType(lhsType)) {
  4766. if (const auto *cast = dyn_cast<ImplicitCastExpr>(rhs)) {
  4767. if (cast->getCastKind() == CK_HLSLMatrixSplat) {
  4768. const QualType matType = expr->getType();
  4769. const spv::Op opcode = selectOpcode(lhsType);
  4770. if (isa<CompoundAssignOperator>(expr)) {
  4771. SpirvEvalInfo lhsPtr = 0;
  4772. const auto result =
  4773. processBinaryOp(lhs, cast->getSubExpr(), expr->getOpcode(),
  4774. matType, matType, range, &lhsPtr, opcode);
  4775. return processAssignment(lhs, result, true, lhsPtr);
  4776. } else {
  4777. return processBinaryOp(lhs, cast->getSubExpr(), expr->getOpcode(),
  4778. matType, matType, range, nullptr, opcode);
  4779. }
  4780. }
  4781. }
  4782. }
  4783. // scalar * matrix
  4784. if (hlsl::IsHLSLMatType(rhsType)) {
  4785. if (const auto *cast = dyn_cast<ImplicitCastExpr>(lhs)) {
  4786. if (cast->getCastKind() == CK_HLSLMatrixSplat) {
  4787. const QualType matType = expr->getType();
  4788. const spv::Op opcode = selectOpcode(rhsType);
  4789. // We need to switch the positions of lhs and rhs here because
  4790. // OpMatrixTimesScalar requires the first operand to be a matrix and
  4791. // the second to be a scalar.
  4792. return processBinaryOp(rhs, cast->getSubExpr(), expr->getOpcode(),
  4793. matType, matType, range, nullptr, opcode);
  4794. }
  4795. }
  4796. }
  4797. return 0;
  4798. }
  4799. SpirvEvalInfo
  4800. SPIRVEmitter::tryToAssignToVectorElements(const Expr *lhs,
  4801. const SpirvEvalInfo &rhs) {
  4802. // Assigning to a vector swizzling lhs is tricky if we are neither
  4803. // writing to one element nor all elements in their original order.
  4804. // Under such cases, we need to create a new vector swizzling involving
  4805. // both the lhs and rhs vectors and then write the result of this swizzling
  4806. // into the base vector of lhs.
  4807. // For example, for vec4.yz = vec2, we nee to do the following:
  4808. //
  4809. // %vec4Val = OpLoad %v4float %vec4
  4810. // %vec2Val = OpLoad %v2float %vec2
  4811. // %shuffle = OpVectorShuffle %v4float %vec4Val %vec2Val 0 4 5 3
  4812. // OpStore %vec4 %shuffle
  4813. //
  4814. // When doing the vector shuffle, we use the lhs base vector as the first
  4815. // vector and the rhs vector as the second vector. Therefore, all elements
  4816. // in the second vector will be selected into the shuffle result.
  4817. const auto *lhsExpr = dyn_cast<HLSLVectorElementExpr>(lhs);
  4818. if (!lhsExpr)
  4819. return 0;
  4820. // Special case for <scalar-value>.x, which will have an AST of
  4821. // HLSLVectorElementExpr whose base is an ImplicitCastExpr
  4822. // (CK_HLSLVectorSplat). We just need to assign to <scalar-value>
  4823. // for such case.
  4824. if (const auto *baseCast = dyn_cast<CastExpr>(lhsExpr->getBase()))
  4825. if (baseCast->getCastKind() == CastKind::CK_HLSLVectorSplat &&
  4826. hlsl::GetHLSLVecSize(baseCast->getType()) == 1)
  4827. return processAssignment(baseCast->getSubExpr(), rhs, false);
  4828. const Expr *base = nullptr;
  4829. hlsl::VectorMemberAccessPositions accessor;
  4830. condenseVectorElementExpr(lhsExpr, &base, &accessor);
  4831. const QualType baseType = base->getType();
  4832. assert(hlsl::IsHLSLVecType(baseType));
  4833. const uint32_t baseTypeId = typeTranslator.translateType(baseType);
  4834. const auto baseSize = hlsl::GetHLSLVecSize(baseType);
  4835. const auto accessorSize = accessor.Count;
  4836. // Whether selecting the whole original vector
  4837. bool isSelectOrigin = accessorSize == baseSize;
  4838. // Assigning to one component
  4839. if (accessorSize == 1) {
  4840. if (isBufferTextureIndexing(dyn_cast_or_null<CXXOperatorCallExpr>(base))) {
  4841. // Assigning to one component of a RWBuffer/RWTexture element
  4842. // We need to use OpImageWrite here.
  4843. // Compose the new vector value first
  4844. const uint32_t oldVec = doExpr(base);
  4845. const uint32_t newVec = theBuilder.createCompositeInsert(
  4846. baseTypeId, oldVec, {accessor.Swz0}, rhs);
  4847. const auto result = tryToAssignToRWBufferRWTexture(base, newVec);
  4848. assert(result); // Definitely RWBuffer/RWTexture assignment
  4849. return rhs; // TODO: incorrect for compound assignments
  4850. } else {
  4851. // Assigning to one normal vector component. Nothing special, just fall
  4852. // back to the normal CodeGen path.
  4853. return 0;
  4854. }
  4855. }
  4856. if (isSelectOrigin) {
  4857. for (uint32_t i = 0; i < accessorSize; ++i) {
  4858. uint32_t position;
  4859. accessor.GetPosition(i, &position);
  4860. if (position != i)
  4861. isSelectOrigin = false;
  4862. }
  4863. }
  4864. // Assigning to the original vector
  4865. if (isSelectOrigin) {
  4866. // Ignore this HLSLVectorElementExpr and dispatch to base
  4867. return processAssignment(base, rhs, false);
  4868. }
  4869. llvm::SmallVector<uint32_t, 4> selectors;
  4870. selectors.resize(baseSize);
  4871. // Assume we are selecting all original elements first.
  4872. for (uint32_t i = 0; i < baseSize; ++i) {
  4873. selectors[i] = i;
  4874. }
  4875. // Now fix up the elements that actually got overwritten by the rhs vector.
  4876. // Since we are using the rhs vector as the second vector, their index
  4877. // should be offset'ed by the size of the lhs base vector.
  4878. for (uint32_t i = 0; i < accessor.Count; ++i) {
  4879. uint32_t position;
  4880. accessor.GetPosition(i, &position);
  4881. selectors[position] = baseSize + i;
  4882. }
  4883. const auto vec1 = doExpr(base);
  4884. const uint32_t vec1Val =
  4885. vec1.isRValue() ? vec1 : theBuilder.createLoad(baseTypeId, vec1);
  4886. const uint32_t shuffle =
  4887. theBuilder.createVectorShuffle(baseTypeId, vec1Val, rhs, selectors);
  4888. if (!tryToAssignToRWBufferRWTexture(base, shuffle))
  4889. theBuilder.createStore(vec1, shuffle);
  4890. // TODO: OK, this return value is incorrect for compound assignments, for
  4891. // which cases we should return lvalues. Should at least emit errors if
  4892. // this return value is used (can be checked via ASTContext.getParents).
  4893. return rhs;
  4894. }
  4895. SpirvEvalInfo
  4896. SPIRVEmitter::tryToAssignToRWBufferRWTexture(const Expr *lhs,
  4897. const SpirvEvalInfo &rhs) {
  4898. const Expr *baseExpr = nullptr;
  4899. const Expr *indexExpr = nullptr;
  4900. const auto lhsExpr = dyn_cast<CXXOperatorCallExpr>(lhs);
  4901. if (isBufferTextureIndexing(lhsExpr, &baseExpr, &indexExpr)) {
  4902. const uint32_t locId = doExpr(indexExpr);
  4903. const QualType imageType = baseExpr->getType();
  4904. const uint32_t imageId = theBuilder.createLoad(
  4905. typeTranslator.translateType(imageType), doExpr(baseExpr));
  4906. theBuilder.createImageWrite(imageType, imageId, locId, rhs);
  4907. return rhs;
  4908. }
  4909. return 0;
  4910. }
  4911. SpirvEvalInfo
  4912. SPIRVEmitter::tryToAssignToMatrixElements(const Expr *lhs,
  4913. const SpirvEvalInfo &rhs) {
  4914. const auto *lhsExpr = dyn_cast<ExtMatrixElementExpr>(lhs);
  4915. if (!lhsExpr)
  4916. return 0;
  4917. const Expr *baseMat = lhsExpr->getBase();
  4918. const auto base = doExpr(baseMat);
  4919. const QualType elemType = hlsl::GetHLSLMatElementType(baseMat->getType());
  4920. const uint32_t elemTypeId = typeTranslator.translateType(elemType);
  4921. uint32_t rowCount = 0, colCount = 0;
  4922. hlsl::GetHLSLMatRowColCount(baseMat->getType(), rowCount, colCount);
  4923. // For each lhs element written to:
  4924. // 1. Extract the corresponding rhs element using OpCompositeExtract
  4925. // 2. Create access chain for the lhs element using OpAccessChain
  4926. // 3. Write using OpStore
  4927. const auto accessor = lhsExpr->getEncodedElementAccess();
  4928. for (uint32_t i = 0; i < accessor.Count; ++i) {
  4929. uint32_t row = 0, col = 0;
  4930. accessor.GetPosition(i, &row, &col);
  4931. llvm::SmallVector<uint32_t, 2> indices;
  4932. // If the matrix only have one row/column, we are indexing into a vector
  4933. // then. Only one index is needed for such cases.
  4934. if (rowCount > 1)
  4935. indices.push_back(row);
  4936. if (colCount > 1)
  4937. indices.push_back(col);
  4938. for (uint32_t i = 0; i < indices.size(); ++i)
  4939. indices[i] = theBuilder.getConstantInt32(indices[i]);
  4940. // If we are writing to only one element, the rhs should already be a
  4941. // scalar value.
  4942. uint32_t rhsElem = rhs;
  4943. if (accessor.Count > 1)
  4944. rhsElem = theBuilder.createCompositeExtract(elemTypeId, rhs, {i});
  4945. const uint32_t ptrType =
  4946. theBuilder.getPointerType(elemTypeId, base.getStorageClass());
  4947. // If the lhs is actually a matrix of size 1x1, we don't need the access
  4948. // chain. base is already the dest pointer.
  4949. uint32_t lhsElemPtr = base;
  4950. if (!indices.empty()) {
  4951. assert(!base.isRValue());
  4952. // Load the element via access chain
  4953. lhsElemPtr = theBuilder.createAccessChain(ptrType, lhsElemPtr, indices);
  4954. }
  4955. theBuilder.createStore(lhsElemPtr, rhsElem);
  4956. }
  4957. // TODO: OK, this return value is incorrect for compound assignments, for
  4958. // which cases we should return lvalues. Should at least emit errors if
  4959. // this return value is used (can be checked via ASTContext.getParents).
  4960. return rhs;
  4961. }
  4962. SpirvEvalInfo SPIRVEmitter::processEachVectorInMatrix(
  4963. const Expr *matrix, const uint32_t matrixVal,
  4964. llvm::function_ref<uint32_t(uint32_t, uint32_t, uint32_t)>
  4965. actOnEachVector) {
  4966. const auto matType = matrix->getType();
  4967. assert(TypeTranslator::isMxNMatrix(matType));
  4968. const uint32_t vecType = typeTranslator.getComponentVectorType(matType);
  4969. uint32_t rowCount = 0, colCount = 0;
  4970. hlsl::GetHLSLMatRowColCount(matType, rowCount, colCount);
  4971. llvm::SmallVector<uint32_t, 4> vectors;
  4972. // Extract each component vector and do operation on it
  4973. for (uint32_t i = 0; i < rowCount; ++i) {
  4974. const uint32_t lhsVec =
  4975. theBuilder.createCompositeExtract(vecType, matrixVal, {i});
  4976. vectors.push_back(actOnEachVector(i, vecType, lhsVec));
  4977. }
  4978. // Construct the result matrix
  4979. const auto valId = theBuilder.createCompositeConstruct(
  4980. typeTranslator.translateType(matType), vectors);
  4981. return SpirvEvalInfo(valId).setRValue();
  4982. }
  4983. void SPIRVEmitter::createSpecConstant(const VarDecl *varDecl) {
  4984. class SpecConstantEnvRAII {
  4985. public:
  4986. // Creates a new instance which sets mode to true on creation,
  4987. // and resets mode to false on destruction.
  4988. SpecConstantEnvRAII(bool *mode) : modeSlot(mode) { *modeSlot = true; }
  4989. ~SpecConstantEnvRAII() { *modeSlot = false; }
  4990. private:
  4991. bool *modeSlot;
  4992. };
  4993. const QualType varType = varDecl->getType();
  4994. bool hasError = false;
  4995. if (!varDecl->isExternallyVisible()) {
  4996. emitError("specialization constant must be externally visible",
  4997. varDecl->getLocation());
  4998. hasError = true;
  4999. }
  5000. if (const auto *builtinType = varType->getAs<BuiltinType>()) {
  5001. switch (builtinType->getKind()) {
  5002. case BuiltinType::Bool:
  5003. case BuiltinType::Int:
  5004. case BuiltinType::UInt:
  5005. case BuiltinType::Float:
  5006. break;
  5007. default:
  5008. emitError("unsupported specialization constant type",
  5009. varDecl->getLocStart());
  5010. hasError = true;
  5011. }
  5012. }
  5013. const auto *init = varDecl->getInit();
  5014. if (!init) {
  5015. emitError("missing default value for specialization constant",
  5016. varDecl->getLocation());
  5017. hasError = true;
  5018. } else if (!isAcceptedSpecConstantInit(init)) {
  5019. emitError("unsupported specialization constant initializer",
  5020. init->getLocStart())
  5021. << init->getSourceRange();
  5022. hasError = true;
  5023. }
  5024. if (hasError)
  5025. return;
  5026. SpecConstantEnvRAII specConstantEnvRAII(&isSpecConstantMode);
  5027. const auto specConstant = doExpr(init);
  5028. // We are not creating a variable to hold the spec constant, instead, we
  5029. // translate the varDecl directly into the spec constant here.
  5030. theBuilder.decorateSpecId(
  5031. specConstant, varDecl->getAttr<VKConstantIdAttr>()->getSpecConstId());
  5032. declIdMapper.registerSpecConstant(varDecl, specConstant);
  5033. }
  5034. SpirvEvalInfo
  5035. SPIRVEmitter::processMatrixBinaryOp(const Expr *lhs, const Expr *rhs,
  5036. const BinaryOperatorKind opcode,
  5037. SourceRange range) {
  5038. // TODO: some code are duplicated from processBinaryOp. Try to unify them.
  5039. const auto lhsType = lhs->getType();
  5040. assert(TypeTranslator::isMxNMatrix(lhsType));
  5041. const spv::Op spvOp = translateOp(opcode, lhsType);
  5042. uint32_t rhsVal, lhsPtr, lhsVal;
  5043. if (BinaryOperator::isCompoundAssignmentOp(opcode)) {
  5044. // Evalute rhs before lhs
  5045. rhsVal = doExpr(rhs);
  5046. lhsPtr = doExpr(lhs);
  5047. const uint32_t lhsTy = typeTranslator.translateType(lhsType);
  5048. lhsVal = theBuilder.createLoad(lhsTy, lhsPtr);
  5049. } else {
  5050. // Evalute lhs before rhs
  5051. lhsVal = lhsPtr = doExpr(lhs);
  5052. rhsVal = doExpr(rhs);
  5053. }
  5054. switch (opcode) {
  5055. case BO_Add:
  5056. case BO_Sub:
  5057. case BO_Mul:
  5058. case BO_Div:
  5059. case BO_Rem:
  5060. case BO_AddAssign:
  5061. case BO_SubAssign:
  5062. case BO_MulAssign:
  5063. case BO_DivAssign:
  5064. case BO_RemAssign: {
  5065. const uint32_t vecType = typeTranslator.getComponentVectorType(lhsType);
  5066. const auto actOnEachVec = [this, spvOp, rhsVal](uint32_t index,
  5067. uint32_t vecType,
  5068. uint32_t lhsVec) {
  5069. // For each vector of lhs, we need to load the corresponding vector of
  5070. // rhs and do the operation on them.
  5071. const uint32_t rhsVec =
  5072. theBuilder.createCompositeExtract(vecType, rhsVal, {index});
  5073. const auto valId =
  5074. theBuilder.createBinaryOp(spvOp, vecType, lhsVec, rhsVec);
  5075. return SpirvEvalInfo(valId).setRValue();
  5076. };
  5077. return processEachVectorInMatrix(lhs, lhsVal, actOnEachVec);
  5078. }
  5079. case BO_Assign:
  5080. llvm_unreachable("assignment should not be handled here");
  5081. default:
  5082. break;
  5083. }
  5084. emitError("binary operator '%0' over matrix type unimplemented",
  5085. lhs->getExprLoc())
  5086. << BinaryOperator::getOpcodeStr(opcode) << range;
  5087. return 0;
  5088. }
  5089. const Expr *SPIRVEmitter::collectArrayStructIndices(
  5090. const Expr *expr, llvm::SmallVectorImpl<uint32_t> *indices, bool rawIndex) {
  5091. if (const auto *indexing = dyn_cast<MemberExpr>(expr)) {
  5092. // First check whether this is referring to a static member. If it is, we
  5093. // create a DeclRefExpr for it.
  5094. if (auto *varDecl = dyn_cast<VarDecl>(indexing->getMemberDecl()))
  5095. if (varDecl->isStaticDataMember())
  5096. return DeclRefExpr::Create(
  5097. astContext, NestedNameSpecifierLoc(), SourceLocation(), varDecl,
  5098. /*RefersToEnclosingVariableOrCapture=*/false, SourceLocation(),
  5099. varDecl->getType(), VK_LValue);
  5100. const Expr *base = collectArrayStructIndices(
  5101. indexing->getBase()->IgnoreParenNoopCasts(astContext), indices,
  5102. rawIndex);
  5103. // Append the index of the current level
  5104. const auto *fieldDecl = cast<FieldDecl>(indexing->getMemberDecl());
  5105. assert(fieldDecl);
  5106. // If we are accessing a derived struct, we need to account for the number
  5107. // of base structs, since they are placed as fields at the beginning of the
  5108. // derived struct.
  5109. const uint32_t index = getNumBaseClasses(indexing->getBase()->getType()) +
  5110. fieldDecl->getFieldIndex();
  5111. indices->push_back(rawIndex ? index : theBuilder.getConstantInt32(index));
  5112. return base;
  5113. }
  5114. // Provide a hint to the TypeTranslator that the integer literal used to
  5115. // index into the following cases should be translated as a 32-bit integer.
  5116. TypeTranslator::LiteralTypeHint hint(typeTranslator, astContext.IntTy);
  5117. if (const auto *indexing = dyn_cast<ArraySubscriptExpr>(expr)) {
  5118. if (rawIndex)
  5119. return nullptr; // TODO: handle constant array index
  5120. // The base of an ArraySubscriptExpr has a wrapping LValueToRValue implicit
  5121. // cast. We need to ingore it to avoid creating OpLoad.
  5122. const Expr *thisBase = indexing->getBase()->IgnoreParenLValueCasts();
  5123. const Expr *base = collectArrayStructIndices(thisBase, indices, rawIndex);
  5124. indices->push_back(doExpr(indexing->getIdx()));
  5125. return base;
  5126. }
  5127. if (const auto *indexing = dyn_cast<CXXOperatorCallExpr>(expr))
  5128. if (indexing->getOperator() == OverloadedOperatorKind::OO_Subscript) {
  5129. if (rawIndex)
  5130. return nullptr; // TODO: handle constant array index
  5131. const Expr *thisBase =
  5132. indexing->getArg(0)->IgnoreParenNoopCasts(astContext);
  5133. const auto thisBaseType = thisBase->getType();
  5134. const Expr *base = collectArrayStructIndices(thisBase, indices, rawIndex);
  5135. if (thisBaseType != base->getType() &&
  5136. TypeTranslator::isAKindOfStructuredOrByteBuffer(thisBaseType)) {
  5137. // The immediate base is a kind of structured or byte buffer. It should
  5138. // be an alias variable. Break the normal index collecting chain.
  5139. // Return the immediate base as the base so that we can apply other
  5140. // hacks for legalization over it.
  5141. //
  5142. // Note: legalization specific code
  5143. indices->clear();
  5144. base = thisBase;
  5145. }
  5146. // If the base is a StructureType, we need to push an addtional index 0
  5147. // here. This is because we created an additional OpTypeRuntimeArray
  5148. // in the structure.
  5149. if (TypeTranslator::isStructuredBuffer(thisBaseType))
  5150. indices->push_back(theBuilder.getConstantInt32(0));
  5151. if ((hlsl::IsHLSLVecType(thisBaseType) &&
  5152. (hlsl::GetHLSLVecSize(thisBaseType) == 1)) ||
  5153. typeTranslator.is1x1Matrix(thisBaseType) ||
  5154. typeTranslator.is1xNMatrix(thisBaseType)) {
  5155. // If this is a size-1 vector or 1xN matrix, ignore the index.
  5156. } else {
  5157. indices->push_back(doExpr(indexing->getArg(1)));
  5158. }
  5159. return base;
  5160. }
  5161. {
  5162. const Expr *index = nullptr;
  5163. // TODO: the following is duplicating the logic in doCXXMemberCallExpr.
  5164. if (const auto *object = isStructuredBufferLoad(expr, &index)) {
  5165. if (rawIndex)
  5166. return nullptr; // TODO: handle constant array index
  5167. // For object.Load(index), there should be no more indexing into the
  5168. // object.
  5169. indices->push_back(theBuilder.getConstantInt32(0));
  5170. indices->push_back(doExpr(index));
  5171. return object;
  5172. }
  5173. }
  5174. // This the deepest we can go. No more array or struct indexing.
  5175. return expr;
  5176. }
  5177. SpirvEvalInfo &SPIRVEmitter::turnIntoElementPtr(
  5178. SpirvEvalInfo &info, QualType elemType,
  5179. const llvm::SmallVector<uint32_t, 4> &indices) {
  5180. assert(!info.isRValue());
  5181. const uint32_t ptrType = theBuilder.getPointerType(
  5182. typeTranslator.translateType(elemType, info.getLayoutRule()),
  5183. info.getStorageClass());
  5184. return info.setResultId(theBuilder.createAccessChain(ptrType, info, indices));
  5185. }
  5186. uint32_t SPIRVEmitter::castToBool(const uint32_t fromVal, QualType fromType,
  5187. QualType toBoolType) {
  5188. if (TypeTranslator::isSameScalarOrVecType(fromType, toBoolType))
  5189. return fromVal;
  5190. const uint32_t boolType = typeTranslator.translateType(toBoolType);
  5191. { // Special case handling for converting to a matrix of booleans.
  5192. QualType elemType = {};
  5193. uint32_t rowCount = 0, colCount = 0;
  5194. if (TypeTranslator::isMxNMatrix(fromType, &elemType, &rowCount,
  5195. &colCount)) {
  5196. const auto fromRowQualType =
  5197. astContext.getExtVectorType(elemType, colCount);
  5198. const auto fromRowQualTypeId =
  5199. typeTranslator.translateType(fromRowQualType);
  5200. const auto toBoolRowQualType =
  5201. astContext.getExtVectorType(astContext.BoolTy, colCount);
  5202. llvm::SmallVector<uint32_t, 4> rows;
  5203. for (uint32_t i = 0; i < rowCount; ++i) {
  5204. const auto row =
  5205. theBuilder.createCompositeExtract(fromRowQualTypeId, fromVal, {i});
  5206. rows.push_back(castToBool(row, fromRowQualType, toBoolRowQualType));
  5207. }
  5208. return theBuilder.createCompositeConstruct(boolType, rows);
  5209. }
  5210. }
  5211. // Converting to bool means comparing with value zero.
  5212. const spv::Op spvOp = translateOp(BO_NE, fromType);
  5213. const uint32_t zeroVal = getValueZero(fromType);
  5214. return theBuilder.createBinaryOp(spvOp, boolType, fromVal, zeroVal);
  5215. }
  5216. uint32_t SPIRVEmitter::castToInt(uint32_t fromVal, QualType fromType,
  5217. QualType toIntType, SourceLocation srcLoc) {
  5218. if (TypeTranslator::isSameScalarOrVecType(fromType, toIntType))
  5219. return fromVal;
  5220. uint32_t intType = typeTranslator.translateType(toIntType);
  5221. if (isBoolOrVecOfBoolType(fromType)) {
  5222. const uint32_t one = getValueOne(toIntType);
  5223. const uint32_t zero = getValueZero(toIntType);
  5224. return theBuilder.createSelect(intType, fromVal, one, zero);
  5225. }
  5226. if (isSintOrVecOfSintType(fromType) || isUintOrVecOfUintType(fromType)) {
  5227. // First convert the source to the bitwidth of the destination if necessary.
  5228. uint32_t convertedType = 0;
  5229. fromVal = convertBitwidth(fromVal, fromType, toIntType, &convertedType);
  5230. // If bitwidth conversion was the only thing we needed to do, we're done.
  5231. if (convertedType == typeTranslator.translateType(toIntType))
  5232. return fromVal;
  5233. return theBuilder.createUnaryOp(spv::Op::OpBitcast, intType, fromVal);
  5234. }
  5235. if (isFloatOrVecOfFloatType(fromType)) {
  5236. // First convert the source to the bitwidth of the destination if necessary.
  5237. fromVal = convertBitwidth(fromVal, fromType, toIntType);
  5238. if (isSintOrVecOfSintType(toIntType)) {
  5239. return theBuilder.createUnaryOp(spv::Op::OpConvertFToS, intType, fromVal);
  5240. } else if (isUintOrVecOfUintType(toIntType)) {
  5241. return theBuilder.createUnaryOp(spv::Op::OpConvertFToU, intType, fromVal);
  5242. } else {
  5243. emitError("casting from floating point to integer unimplemented", srcLoc);
  5244. }
  5245. }
  5246. {
  5247. QualType elemType = {};
  5248. uint32_t numRows = 0, numCols = 0;
  5249. if (TypeTranslator::isMxNMatrix(fromType, &elemType, &numRows, &numCols)) {
  5250. // The source matrix and the target matrix must have the same dimensions.
  5251. QualType toElemType = {};
  5252. uint32_t toNumRows = 0, toNumCols = 0;
  5253. const bool isMat = TypeTranslator::isMxNMatrix(toIntType, &toElemType,
  5254. &toNumRows, &toNumCols);
  5255. assert(isMat && numRows == toNumRows && numCols == toNumCols);
  5256. (void)toNumRows;
  5257. (void)toNumCols;
  5258. // Casting to a matrix of integers: Cast each row and construct a
  5259. // composite.
  5260. llvm::SmallVector<uint32_t, 4> castedRows;
  5261. const uint32_t vecType = typeTranslator.getComponentVectorType(fromType);
  5262. const auto fromVecQualType =
  5263. astContext.getExtVectorType(elemType, numCols);
  5264. const auto toIntVecQualType =
  5265. astContext.getExtVectorType(toElemType, numCols);
  5266. for (uint32_t row = 0; row < numRows; ++row) {
  5267. const auto rowId =
  5268. theBuilder.createCompositeExtract(vecType, fromVal, {row});
  5269. castedRows.push_back(
  5270. castToInt(rowId, fromVecQualType, toIntVecQualType, srcLoc));
  5271. }
  5272. return theBuilder.createCompositeConstruct(intType, castedRows);
  5273. }
  5274. }
  5275. return 0;
  5276. }
  5277. uint32_t SPIRVEmitter::convertBitwidth(uint32_t fromVal, QualType fromType,
  5278. QualType toType, uint32_t *resultType) {
  5279. // At the moment, we will not make bitwidth conversions for literal int and
  5280. // literal float types because they always indicate 64-bit and do not
  5281. // represent what SPIR-V was actually resolved to.
  5282. // TODO: If the evaluated type is added to SpirvEvalInfo, change 'fromVal' to
  5283. // SpirvEvalInfo and use it to handle literal types more accurately.
  5284. if (fromType->isSpecificBuiltinType(BuiltinType::LitFloat) ||
  5285. fromType->isSpecificBuiltinType(BuiltinType::LitInt))
  5286. return fromVal;
  5287. const auto fromBitwidth = typeTranslator.getElementSpirvBitwidth(fromType);
  5288. const auto toBitwidth = typeTranslator.getElementSpirvBitwidth(toType);
  5289. if (fromBitwidth == toBitwidth) {
  5290. if (resultType)
  5291. *resultType = typeTranslator.translateType(fromType);
  5292. return fromVal;
  5293. }
  5294. // We want the 'fromType' with the 'toBitwidth'.
  5295. const uint32_t targetTypeId =
  5296. typeTranslator.getTypeWithCustomBitwidth(fromType, toBitwidth);
  5297. if (resultType)
  5298. *resultType = targetTypeId;
  5299. if (isFloatOrVecOfFloatType(fromType))
  5300. return theBuilder.createUnaryOp(spv::Op::OpFConvert, targetTypeId, fromVal);
  5301. if (isSintOrVecOfSintType(fromType))
  5302. return theBuilder.createUnaryOp(spv::Op::OpSConvert, targetTypeId, fromVal);
  5303. if (isUintOrVecOfUintType(fromType))
  5304. return theBuilder.createUnaryOp(spv::Op::OpUConvert, targetTypeId, fromVal);
  5305. llvm_unreachable("invalid type passed to convertBitwidth");
  5306. }
  5307. uint32_t SPIRVEmitter::castToFloat(uint32_t fromVal, QualType fromType,
  5308. QualType toFloatType,
  5309. SourceLocation srcLoc) {
  5310. if (TypeTranslator::isSameScalarOrVecType(fromType, toFloatType))
  5311. return fromVal;
  5312. const uint32_t floatType = typeTranslator.translateType(toFloatType);
  5313. if (isBoolOrVecOfBoolType(fromType)) {
  5314. const uint32_t one = getValueOne(toFloatType);
  5315. const uint32_t zero = getValueZero(toFloatType);
  5316. return theBuilder.createSelect(floatType, fromVal, one, zero);
  5317. }
  5318. if (isSintOrVecOfSintType(fromType)) {
  5319. // First convert the source to the bitwidth of the destination if necessary.
  5320. fromVal = convertBitwidth(fromVal, fromType, toFloatType);
  5321. return theBuilder.createUnaryOp(spv::Op::OpConvertSToF, floatType, fromVal);
  5322. }
  5323. if (isUintOrVecOfUintType(fromType)) {
  5324. // First convert the source to the bitwidth of the destination if necessary.
  5325. fromVal = convertBitwidth(fromVal, fromType, toFloatType);
  5326. return theBuilder.createUnaryOp(spv::Op::OpConvertUToF, floatType, fromVal);
  5327. }
  5328. if (isFloatOrVecOfFloatType(fromType)) {
  5329. // This is the case of float to float conversion with different bitwidths.
  5330. return convertBitwidth(fromVal, fromType, toFloatType);
  5331. }
  5332. // Casting matrix types
  5333. {
  5334. QualType elemType = {};
  5335. uint32_t numRows = 0, numCols = 0;
  5336. if (TypeTranslator::isMxNMatrix(fromType, &elemType, &numRows, &numCols)) {
  5337. // The source matrix and the target matrix must have the same dimensions.
  5338. QualType toElemType = {};
  5339. uint32_t toNumRows = 0, toNumCols = 0;
  5340. const auto isMat = TypeTranslator::isMxNMatrix(toFloatType, &toElemType,
  5341. &toNumRows, &toNumCols);
  5342. assert(isMat && numRows == toNumRows && numCols == toNumCols);
  5343. (void)toNumRows;
  5344. (void)toNumCols;
  5345. // Casting to a matrix of floats: Cast each row and construct a
  5346. // composite.
  5347. llvm::SmallVector<uint32_t, 4> castedRows;
  5348. const uint32_t vecType = typeTranslator.getComponentVectorType(fromType);
  5349. const auto fromVecQualType =
  5350. astContext.getExtVectorType(elemType, numCols);
  5351. const auto toIntVecQualType =
  5352. astContext.getExtVectorType(toElemType, numCols);
  5353. for (uint32_t row = 0; row < numRows; ++row) {
  5354. const auto rowId =
  5355. theBuilder.createCompositeExtract(vecType, fromVal, {row});
  5356. castedRows.push_back(
  5357. castToFloat(rowId, fromVecQualType, toIntVecQualType, srcLoc));
  5358. }
  5359. return theBuilder.createCompositeConstruct(floatType, castedRows);
  5360. }
  5361. }
  5362. emitError("casting to floating point unimplemented", srcLoc);
  5363. return 0;
  5364. }
  5365. SpirvEvalInfo SPIRVEmitter::processIntrinsicCallExpr(const CallExpr *callExpr) {
  5366. const FunctionDecl *callee = callExpr->getDirectCallee();
  5367. assert(hlsl::IsIntrinsicOp(callee) &&
  5368. "doIntrinsicCallExpr was called for a non-intrinsic function.");
  5369. const bool isFloatType = isFloatOrVecMatOfFloatType(callExpr->getType());
  5370. const bool isSintType = isSintOrVecMatOfSintType(callExpr->getType());
  5371. // Figure out which intrinsic function to translate.
  5372. llvm::StringRef group;
  5373. uint32_t opcode = static_cast<uint32_t>(hlsl::IntrinsicOp::Num_Intrinsics);
  5374. hlsl::GetIntrinsicOp(callee, opcode, group);
  5375. GLSLstd450 glslOpcode = GLSLstd450Bad;
  5376. uint32_t retVal = 0;
  5377. #define INTRINSIC_SPIRV_OP_WITH_CAP_CASE(intrinsicOp, spirvOp, doEachVec, cap) \
  5378. case hlsl::IntrinsicOp::IOP_##intrinsicOp: { \
  5379. theBuilder.requireCapability(cap); \
  5380. retVal = processIntrinsicUsingSpirvInst(callExpr, spv::Op::Op##spirvOp, \
  5381. doEachVec); \
  5382. } break
  5383. #define INTRINSIC_SPIRV_OP_CASE(intrinsicOp, spirvOp, doEachVec) \
  5384. case hlsl::IntrinsicOp::IOP_##intrinsicOp: { \
  5385. retVal = processIntrinsicUsingSpirvInst(callExpr, spv::Op::Op##spirvOp, \
  5386. doEachVec); \
  5387. } break
  5388. #define INTRINSIC_OP_CASE(intrinsicOp, glslOp, doEachVec) \
  5389. case hlsl::IntrinsicOp::IOP_##intrinsicOp: { \
  5390. glslOpcode = GLSLstd450::GLSLstd450##glslOp; \
  5391. retVal = processIntrinsicUsingGLSLInst(callExpr, glslOpcode, doEachVec); \
  5392. } break
  5393. #define INTRINSIC_OP_CASE_INT_FLOAT(intrinsicOp, glslIntOp, glslFloatOp, \
  5394. doEachVec) \
  5395. case hlsl::IntrinsicOp::IOP_##intrinsicOp: { \
  5396. glslOpcode = isFloatType ? GLSLstd450::GLSLstd450##glslFloatOp \
  5397. : GLSLstd450::GLSLstd450##glslIntOp; \
  5398. retVal = processIntrinsicUsingGLSLInst(callExpr, glslOpcode, doEachVec); \
  5399. } break
  5400. #define INTRINSIC_OP_CASE_SINT_UINT(intrinsicOp, glslSintOp, glslUintOp, \
  5401. doEachVec) \
  5402. case hlsl::IntrinsicOp::IOP_##intrinsicOp: { \
  5403. glslOpcode = isSintType ? GLSLstd450::GLSLstd450##glslSintOp \
  5404. : GLSLstd450::GLSLstd450##glslUintOp; \
  5405. retVal = processIntrinsicUsingGLSLInst(callExpr, glslOpcode, doEachVec); \
  5406. } break
  5407. #define INTRINSIC_OP_CASE_SINT_UINT_FLOAT(intrinsicOp, glslSintOp, glslUintOp, \
  5408. glslFloatOp, doEachVec) \
  5409. case hlsl::IntrinsicOp::IOP_##intrinsicOp: { \
  5410. glslOpcode = isFloatType \
  5411. ? GLSLstd450::GLSLstd450##glslFloatOp \
  5412. : isSintType ? GLSLstd450::GLSLstd450##glslSintOp \
  5413. : GLSLstd450::GLSLstd450##glslUintOp; \
  5414. retVal = processIntrinsicUsingGLSLInst(callExpr, glslOpcode, doEachVec); \
  5415. } break
  5416. switch (const auto hlslOpcode = static_cast<hlsl::IntrinsicOp>(opcode)) {
  5417. case hlsl::IntrinsicOp::IOP_InterlockedAdd:
  5418. case hlsl::IntrinsicOp::IOP_InterlockedAnd:
  5419. case hlsl::IntrinsicOp::IOP_InterlockedMax:
  5420. case hlsl::IntrinsicOp::IOP_InterlockedUMax:
  5421. case hlsl::IntrinsicOp::IOP_InterlockedMin:
  5422. case hlsl::IntrinsicOp::IOP_InterlockedUMin:
  5423. case hlsl::IntrinsicOp::IOP_InterlockedOr:
  5424. case hlsl::IntrinsicOp::IOP_InterlockedXor:
  5425. case hlsl::IntrinsicOp::IOP_InterlockedExchange:
  5426. case hlsl::IntrinsicOp::IOP_InterlockedCompareStore:
  5427. case hlsl::IntrinsicOp::IOP_InterlockedCompareExchange:
  5428. retVal = processIntrinsicInterlockedMethod(callExpr, hlslOpcode);
  5429. break;
  5430. case hlsl::IntrinsicOp::IOP_tex1D:
  5431. case hlsl::IntrinsicOp::IOP_tex1Dbias:
  5432. case hlsl::IntrinsicOp::IOP_tex1Dgrad:
  5433. case hlsl::IntrinsicOp::IOP_tex1Dlod:
  5434. case hlsl::IntrinsicOp::IOP_tex1Dproj:
  5435. case hlsl::IntrinsicOp::IOP_tex2D:
  5436. case hlsl::IntrinsicOp::IOP_tex2Dbias:
  5437. case hlsl::IntrinsicOp::IOP_tex2Dgrad:
  5438. case hlsl::IntrinsicOp::IOP_tex2Dlod:
  5439. case hlsl::IntrinsicOp::IOP_tex2Dproj:
  5440. case hlsl::IntrinsicOp::IOP_tex3D:
  5441. case hlsl::IntrinsicOp::IOP_tex3Dbias:
  5442. case hlsl::IntrinsicOp::IOP_tex3Dgrad:
  5443. case hlsl::IntrinsicOp::IOP_tex3Dlod:
  5444. case hlsl::IntrinsicOp::IOP_tex3Dproj:
  5445. case hlsl::IntrinsicOp::IOP_texCUBE:
  5446. case hlsl::IntrinsicOp::IOP_texCUBEbias:
  5447. case hlsl::IntrinsicOp::IOP_texCUBEgrad:
  5448. case hlsl::IntrinsicOp::IOP_texCUBElod:
  5449. case hlsl::IntrinsicOp::IOP_texCUBEproj: {
  5450. emitError("deprecated %0 intrinsic function will not be supported",
  5451. callExpr->getExprLoc())
  5452. << callee->getName();
  5453. return 0;
  5454. }
  5455. case hlsl::IntrinsicOp::IOP_dot:
  5456. retVal = processIntrinsicDot(callExpr);
  5457. break;
  5458. case hlsl::IntrinsicOp::IOP_GroupMemoryBarrier:
  5459. retVal = processIntrinsicMemoryBarrier(callExpr,
  5460. /*isDevice*/ false,
  5461. /*groupSync*/ false,
  5462. /*isAllBarrier*/ false);
  5463. break;
  5464. case hlsl::IntrinsicOp::IOP_GroupMemoryBarrierWithGroupSync:
  5465. retVal = processIntrinsicMemoryBarrier(callExpr,
  5466. /*isDevice*/ false,
  5467. /*groupSync*/ true,
  5468. /*isAllBarrier*/ false);
  5469. break;
  5470. case hlsl::IntrinsicOp::IOP_DeviceMemoryBarrier:
  5471. retVal = processIntrinsicMemoryBarrier(callExpr, /*isDevice*/ true,
  5472. /*groupSync*/ false,
  5473. /*isAllBarrier*/ false);
  5474. break;
  5475. case hlsl::IntrinsicOp::IOP_DeviceMemoryBarrierWithGroupSync:
  5476. retVal = processIntrinsicMemoryBarrier(callExpr, /*isDevice*/ true,
  5477. /*groupSync*/ true,
  5478. /*isAllBarrier*/ false);
  5479. break;
  5480. case hlsl::IntrinsicOp::IOP_AllMemoryBarrier:
  5481. retVal = processIntrinsicMemoryBarrier(callExpr, /*isDevice*/ true,
  5482. /*groupSync*/ false,
  5483. /*isAllBarrier*/ true);
  5484. break;
  5485. case hlsl::IntrinsicOp::IOP_AllMemoryBarrierWithGroupSync:
  5486. retVal = processIntrinsicMemoryBarrier(callExpr, /*isDevice*/ true,
  5487. /*groupSync*/ true,
  5488. /*isAllBarrier*/ true);
  5489. break;
  5490. case hlsl::IntrinsicOp::IOP_CheckAccessFullyMapped:
  5491. retVal =
  5492. theBuilder.createImageSparseTexelsResident(doExpr(callExpr->getArg(0)));
  5493. break;
  5494. case hlsl::IntrinsicOp::IOP_mul:
  5495. case hlsl::IntrinsicOp::IOP_umul:
  5496. retVal = processIntrinsicMul(callExpr);
  5497. break;
  5498. case hlsl::IntrinsicOp::IOP_all:
  5499. retVal = processIntrinsicAllOrAny(callExpr, spv::Op::OpAll);
  5500. break;
  5501. case hlsl::IntrinsicOp::IOP_any:
  5502. retVal = processIntrinsicAllOrAny(callExpr, spv::Op::OpAny);
  5503. break;
  5504. case hlsl::IntrinsicOp::IOP_asdouble:
  5505. case hlsl::IntrinsicOp::IOP_asfloat:
  5506. case hlsl::IntrinsicOp::IOP_asint:
  5507. case hlsl::IntrinsicOp::IOP_asuint:
  5508. retVal = processIntrinsicAsType(callExpr);
  5509. break;
  5510. case hlsl::IntrinsicOp::IOP_clip:
  5511. retVal = processIntrinsicClip(callExpr);
  5512. break;
  5513. case hlsl::IntrinsicOp::IOP_dst:
  5514. retVal = processIntrinsicDst(callExpr);
  5515. break;
  5516. case hlsl::IntrinsicOp::IOP_clamp:
  5517. case hlsl::IntrinsicOp::IOP_uclamp:
  5518. retVal = processIntrinsicClamp(callExpr);
  5519. break;
  5520. case hlsl::IntrinsicOp::IOP_frexp:
  5521. retVal = processIntrinsicFrexp(callExpr);
  5522. break;
  5523. case hlsl::IntrinsicOp::IOP_ldexp:
  5524. retVal = processIntrinsicLdexp(callExpr);
  5525. break;
  5526. case hlsl::IntrinsicOp::IOP_lit:
  5527. retVal = processIntrinsicLit(callExpr);
  5528. break;
  5529. case hlsl::IntrinsicOp::IOP_modf:
  5530. retVal = processIntrinsicModf(callExpr);
  5531. break;
  5532. case hlsl::IntrinsicOp::IOP_msad4:
  5533. retVal = processIntrinsicMsad4(callExpr);
  5534. break;
  5535. case hlsl::IntrinsicOp::IOP_sign: {
  5536. if (isFloatOrVecMatOfFloatType(callExpr->getArg(0)->getType()))
  5537. retVal = processIntrinsicFloatSign(callExpr);
  5538. else
  5539. retVal =
  5540. processIntrinsicUsingGLSLInst(callExpr, GLSLstd450::GLSLstd450SSign,
  5541. /*actPerRowForMatrices*/ true);
  5542. } break;
  5543. case hlsl::IntrinsicOp::IOP_D3DCOLORtoUBYTE4:
  5544. retVal = processD3DCOLORtoUBYTE4(callExpr);
  5545. break;
  5546. case hlsl::IntrinsicOp::IOP_isfinite:
  5547. retVal = processIntrinsicIsFinite(callExpr);
  5548. break;
  5549. case hlsl::IntrinsicOp::IOP_sincos:
  5550. retVal = processIntrinsicSinCos(callExpr);
  5551. break;
  5552. case hlsl::IntrinsicOp::IOP_rcp:
  5553. retVal = processIntrinsicRcp(callExpr);
  5554. break;
  5555. case hlsl::IntrinsicOp::IOP_saturate:
  5556. retVal = processIntrinsicSaturate(callExpr);
  5557. break;
  5558. case hlsl::IntrinsicOp::IOP_log10:
  5559. retVal = processIntrinsicLog10(callExpr);
  5560. break;
  5561. case hlsl::IntrinsicOp::IOP_f16tof32:
  5562. retVal = processIntrinsicF16ToF32(callExpr);
  5563. break;
  5564. case hlsl::IntrinsicOp::IOP_f32tof16:
  5565. retVal = processIntrinsicF32ToF16(callExpr);
  5566. break;
  5567. case hlsl::IntrinsicOp::IOP_WaveGetLaneCount: {
  5568. featureManager.requestTargetEnv(SPV_ENV_VULKAN_1_1, "WaveGetLaneCount",
  5569. callExpr->getExprLoc());
  5570. const uint32_t retType =
  5571. typeTranslator.translateType(callExpr->getCallReturnType(astContext));
  5572. const uint32_t varId =
  5573. declIdMapper.getBuiltinVar(spv::BuiltIn::SubgroupSize);
  5574. retVal = theBuilder.createLoad(retType, varId);
  5575. } break;
  5576. case hlsl::IntrinsicOp::IOP_WaveGetLaneIndex: {
  5577. featureManager.requestTargetEnv(SPV_ENV_VULKAN_1_1, "WaveGetLaneIndex",
  5578. callExpr->getExprLoc());
  5579. const uint32_t retType =
  5580. typeTranslator.translateType(callExpr->getCallReturnType(astContext));
  5581. const uint32_t varId =
  5582. declIdMapper.getBuiltinVar(spv::BuiltIn::SubgroupLocalInvocationId);
  5583. retVal = theBuilder.createLoad(retType, varId);
  5584. } break;
  5585. case hlsl::IntrinsicOp::IOP_WaveIsFirstLane:
  5586. retVal = processWaveQuery(callExpr, spv::Op::OpGroupNonUniformElect);
  5587. break;
  5588. case hlsl::IntrinsicOp::IOP_WaveActiveAllTrue:
  5589. retVal = processWaveVote(callExpr, spv::Op::OpGroupNonUniformAll);
  5590. break;
  5591. case hlsl::IntrinsicOp::IOP_WaveActiveAnyTrue:
  5592. retVal = processWaveVote(callExpr, spv::Op::OpGroupNonUniformAny);
  5593. break;
  5594. case hlsl::IntrinsicOp::IOP_WaveActiveBallot:
  5595. retVal = processWaveVote(callExpr, spv::Op::OpGroupNonUniformBallot);
  5596. break;
  5597. case hlsl::IntrinsicOp::IOP_WaveActiveAllEqual:
  5598. retVal = processWaveVote(callExpr, spv::Op::OpGroupNonUniformAllEqual);
  5599. break;
  5600. case hlsl::IntrinsicOp::IOP_WaveActiveCountBits:
  5601. retVal = processWaveReductionOrPrefix(
  5602. callExpr, spv::Op::OpGroupNonUniformBallotBitCount,
  5603. spv::GroupOperation::Reduce);
  5604. break;
  5605. case hlsl::IntrinsicOp::IOP_WaveActiveUSum:
  5606. case hlsl::IntrinsicOp::IOP_WaveActiveSum:
  5607. case hlsl::IntrinsicOp::IOP_WaveActiveUProduct:
  5608. case hlsl::IntrinsicOp::IOP_WaveActiveProduct:
  5609. case hlsl::IntrinsicOp::IOP_WaveActiveUMax:
  5610. case hlsl::IntrinsicOp::IOP_WaveActiveMax:
  5611. case hlsl::IntrinsicOp::IOP_WaveActiveUMin:
  5612. case hlsl::IntrinsicOp::IOP_WaveActiveMin:
  5613. case hlsl::IntrinsicOp::IOP_WaveActiveBitAnd:
  5614. case hlsl::IntrinsicOp::IOP_WaveActiveBitOr:
  5615. case hlsl::IntrinsicOp::IOP_WaveActiveBitXor: {
  5616. const auto retType = callExpr->getCallReturnType(astContext);
  5617. retVal = processWaveReductionOrPrefix(
  5618. callExpr, translateWaveOp(hlslOpcode, retType, callExpr->getExprLoc()),
  5619. spv::GroupOperation::Reduce);
  5620. } break;
  5621. case hlsl::IntrinsicOp::IOP_WavePrefixUSum:
  5622. case hlsl::IntrinsicOp::IOP_WavePrefixSum:
  5623. case hlsl::IntrinsicOp::IOP_WavePrefixUProduct:
  5624. case hlsl::IntrinsicOp::IOP_WavePrefixProduct: {
  5625. const auto retType = callExpr->getCallReturnType(astContext);
  5626. retVal = processWaveReductionOrPrefix(
  5627. callExpr, translateWaveOp(hlslOpcode, retType, callExpr->getExprLoc()),
  5628. spv::GroupOperation::ExclusiveScan);
  5629. } break;
  5630. case hlsl::IntrinsicOp::IOP_WavePrefixCountBits:
  5631. retVal = processWaveReductionOrPrefix(
  5632. callExpr, spv::Op::OpGroupNonUniformBallotBitCount,
  5633. spv::GroupOperation::ExclusiveScan);
  5634. break;
  5635. case hlsl::IntrinsicOp::IOP_WaveReadLaneAt:
  5636. case hlsl::IntrinsicOp::IOP_WaveReadLaneFirst:
  5637. retVal = processWaveBroadcast(callExpr);
  5638. break;
  5639. case hlsl::IntrinsicOp::IOP_QuadReadAcrossX:
  5640. case hlsl::IntrinsicOp::IOP_QuadReadAcrossY:
  5641. case hlsl::IntrinsicOp::IOP_QuadReadAcrossDiagonal:
  5642. case hlsl::IntrinsicOp::IOP_QuadReadLaneAt:
  5643. retVal = processWaveQuadWideShuffle(callExpr, hlslOpcode);
  5644. break;
  5645. case hlsl::IntrinsicOp::IOP_abort:
  5646. case hlsl::IntrinsicOp::IOP_GetRenderTargetSampleCount:
  5647. case hlsl::IntrinsicOp::IOP_GetRenderTargetSamplePosition: {
  5648. emitError("no equivalent for %0 intrinsic function in Vulkan",
  5649. callExpr->getExprLoc())
  5650. << callee->getName();
  5651. return 0;
  5652. }
  5653. case hlsl::IntrinsicOp::IOP_transpose: {
  5654. const Expr *mat = callExpr->getArg(0);
  5655. const QualType matType = mat->getType();
  5656. if (hlsl::GetHLSLMatElementType(matType)->isFloatingType())
  5657. retVal =
  5658. processIntrinsicUsingSpirvInst(callExpr, spv::Op::OpTranspose, false);
  5659. else
  5660. retVal = processNonFpMatrixTranspose(matType, doExpr(mat));
  5661. break;
  5662. }
  5663. INTRINSIC_SPIRV_OP_CASE(ddx, DPdx, true);
  5664. INTRINSIC_SPIRV_OP_WITH_CAP_CASE(ddx_coarse, DPdxCoarse, false,
  5665. spv::Capability::DerivativeControl);
  5666. INTRINSIC_SPIRV_OP_WITH_CAP_CASE(ddx_fine, DPdxFine, false,
  5667. spv::Capability::DerivativeControl);
  5668. INTRINSIC_SPIRV_OP_CASE(ddy, DPdy, true);
  5669. INTRINSIC_SPIRV_OP_WITH_CAP_CASE(ddy_coarse, DPdyCoarse, false,
  5670. spv::Capability::DerivativeControl);
  5671. INTRINSIC_SPIRV_OP_WITH_CAP_CASE(ddy_fine, DPdyFine, false,
  5672. spv::Capability::DerivativeControl);
  5673. INTRINSIC_SPIRV_OP_CASE(countbits, BitCount, false);
  5674. INTRINSIC_SPIRV_OP_CASE(isinf, IsInf, true);
  5675. INTRINSIC_SPIRV_OP_CASE(isnan, IsNan, true);
  5676. INTRINSIC_SPIRV_OP_CASE(fmod, FMod, true);
  5677. INTRINSIC_SPIRV_OP_CASE(fwidth, Fwidth, true);
  5678. INTRINSIC_SPIRV_OP_CASE(reversebits, BitReverse, false);
  5679. INTRINSIC_OP_CASE(round, Round, true);
  5680. INTRINSIC_OP_CASE_INT_FLOAT(abs, SAbs, FAbs, true);
  5681. INTRINSIC_OP_CASE(acos, Acos, true);
  5682. INTRINSIC_OP_CASE(asin, Asin, true);
  5683. INTRINSIC_OP_CASE(atan, Atan, true);
  5684. INTRINSIC_OP_CASE(atan2, Atan2, true);
  5685. INTRINSIC_OP_CASE(ceil, Ceil, true);
  5686. INTRINSIC_OP_CASE(cos, Cos, true);
  5687. INTRINSIC_OP_CASE(cosh, Cosh, true);
  5688. INTRINSIC_OP_CASE(cross, Cross, false);
  5689. INTRINSIC_OP_CASE(degrees, Degrees, true);
  5690. INTRINSIC_OP_CASE(distance, Distance, false);
  5691. INTRINSIC_OP_CASE(determinant, Determinant, false);
  5692. INTRINSIC_OP_CASE(exp, Exp, true);
  5693. INTRINSIC_OP_CASE(exp2, Exp2, true);
  5694. INTRINSIC_OP_CASE_SINT_UINT(firstbithigh, FindSMsb, FindUMsb, false);
  5695. INTRINSIC_OP_CASE_SINT_UINT(ufirstbithigh, FindSMsb, FindUMsb, false);
  5696. INTRINSIC_OP_CASE(faceforward, FaceForward, false);
  5697. INTRINSIC_OP_CASE(firstbitlow, FindILsb, false);
  5698. INTRINSIC_OP_CASE(floor, Floor, true);
  5699. INTRINSIC_OP_CASE(fma, Fma, true);
  5700. INTRINSIC_OP_CASE(frac, Fract, true);
  5701. INTRINSIC_OP_CASE(length, Length, false);
  5702. INTRINSIC_OP_CASE(lerp, FMix, true);
  5703. INTRINSIC_OP_CASE(log, Log, true);
  5704. INTRINSIC_OP_CASE(log2, Log2, true);
  5705. INTRINSIC_OP_CASE(mad, Fma, true);
  5706. INTRINSIC_OP_CASE_SINT_UINT_FLOAT(max, SMax, UMax, FMax, true);
  5707. INTRINSIC_OP_CASE(umax, UMax, true);
  5708. INTRINSIC_OP_CASE_SINT_UINT_FLOAT(min, SMin, UMin, FMin, true);
  5709. INTRINSIC_OP_CASE(umin, UMin, true);
  5710. INTRINSIC_OP_CASE(normalize, Normalize, false);
  5711. INTRINSIC_OP_CASE(pow, Pow, true);
  5712. INTRINSIC_OP_CASE(radians, Radians, true);
  5713. INTRINSIC_OP_CASE(reflect, Reflect, false);
  5714. INTRINSIC_OP_CASE(refract, Refract, false);
  5715. INTRINSIC_OP_CASE(rsqrt, InverseSqrt, true);
  5716. INTRINSIC_OP_CASE(smoothstep, SmoothStep, true);
  5717. INTRINSIC_OP_CASE(step, Step, true);
  5718. INTRINSIC_OP_CASE(sin, Sin, true);
  5719. INTRINSIC_OP_CASE(sinh, Sinh, true);
  5720. INTRINSIC_OP_CASE(tan, Tan, true);
  5721. INTRINSIC_OP_CASE(tanh, Tanh, true);
  5722. INTRINSIC_OP_CASE(sqrt, Sqrt, true);
  5723. INTRINSIC_OP_CASE(trunc, Trunc, true);
  5724. default:
  5725. emitError("%0 intrinsic function unimplemented", callExpr->getExprLoc())
  5726. << callee->getName();
  5727. return 0;
  5728. }
  5729. #undef INTRINSIC_OP_CASE
  5730. #undef INTRINSIC_OP_CASE_INT_FLOAT
  5731. return SpirvEvalInfo(retVal).setRValue();
  5732. }
  5733. uint32_t
  5734. SPIRVEmitter::processIntrinsicInterlockedMethod(const CallExpr *expr,
  5735. hlsl::IntrinsicOp opcode) {
  5736. // The signature of intrinsic atomic methods are:
  5737. // void Interlocked*(in R dest, in T value);
  5738. // void Interlocked*(in R dest, in T value, out T original_value);
  5739. // Note: ALL Interlocked*() methods are forced to have an unsigned integer
  5740. // 'value'. Meaning, T is forced to be 'unsigned int'. If the provided
  5741. // parameter is not an unsigned integer, the frontend inserts an
  5742. // 'ImplicitCastExpr' to convert it to unsigned integer. OpAtomicIAdd (and
  5743. // other SPIR-V OpAtomic* instructions) require that the pointee in 'dest' to
  5744. // be of the same type as T. This will result in an invalid SPIR-V if 'dest'
  5745. // is a signed integer typed resource such as RWTexture1D<int>. For example,
  5746. // the following OpAtomicIAdd is invalid because the pointee type defined in
  5747. // %1 is a signed integer, while the value passed to atomic add (%3) is an
  5748. // unsigned integer.
  5749. //
  5750. // %_ptr_Image_int = OpTypePointer Image %int
  5751. // %1 = OpImageTexelPointer %_ptr_Image_int %RWTexture1D_int %index %uint_0
  5752. // %2 = OpLoad %int %value
  5753. // %3 = OpBitcast %uint %2 <-------- Inserted by the frontend
  5754. // %4 = OpAtomicIAdd %int %1 %uint_1 %uint_0 %3
  5755. //
  5756. // In such cases, we bypass the forced IntegralCast.
  5757. // Moreover, the frontend does not add a cast AST node to cast uint to int
  5758. // where necessary. To ensure SPIR-V validity, we add that where necessary.
  5759. const uint32_t zero = theBuilder.getConstantUint32(0);
  5760. const uint32_t scope = theBuilder.getConstantUint32(1); // Device
  5761. const auto *dest = expr->getArg(0);
  5762. const auto baseType = dest->getType();
  5763. const uint32_t baseTypeId = typeTranslator.translateType(baseType);
  5764. const auto doArg = [baseType, this](const CallExpr *callExpr,
  5765. uint32_t argIndex) {
  5766. const Expr *valueExpr = callExpr->getArg(argIndex);
  5767. if (const auto *castExpr = dyn_cast<ImplicitCastExpr>(valueExpr))
  5768. if (castExpr->getCastKind() == CK_IntegralCast &&
  5769. castExpr->getSubExpr()->getType() == baseType)
  5770. valueExpr = castExpr->getSubExpr();
  5771. uint32_t argId = doExpr(valueExpr);
  5772. if (valueExpr->getType() != baseType)
  5773. argId = castToInt(argId, valueExpr->getType(), baseType,
  5774. valueExpr->getExprLoc());
  5775. return argId;
  5776. };
  5777. const auto writeToOutputArg = [&baseType, dest, this](
  5778. uint32_t toWrite, const CallExpr *callExpr,
  5779. uint32_t outputArgIndex) {
  5780. const auto outputArg = callExpr->getArg(outputArgIndex);
  5781. const auto outputArgType = outputArg->getType();
  5782. if (baseType != outputArgType)
  5783. toWrite = castToInt(toWrite, baseType, outputArgType, dest->getExprLoc());
  5784. theBuilder.createStore(doExpr(outputArg), toWrite);
  5785. };
  5786. // If the argument is indexing into a texture/buffer, we need to create an
  5787. // OpImageTexelPointer instruction.
  5788. uint32_t ptr = 0;
  5789. if (const auto *callExpr = dyn_cast<CXXOperatorCallExpr>(dest)) {
  5790. const Expr *base = nullptr;
  5791. const Expr *index = nullptr;
  5792. if (isBufferTextureIndexing(callExpr, &base, &index)) {
  5793. const auto ptrType =
  5794. theBuilder.getPointerType(baseTypeId, spv::StorageClass::Image);
  5795. auto baseId = doExpr(base);
  5796. if (baseId.isRValue()) {
  5797. // OpImageTexelPointer's Image argument must have a type of
  5798. // OpTypePointer with Type OpTypeImage. Need to create a temporary
  5799. // variable if the baseId is an rvalue.
  5800. baseId = createTemporaryVar(
  5801. base->getType(), TypeTranslator::getName(base->getType()), baseId);
  5802. }
  5803. const auto coordId = doExpr(index);
  5804. ptr = theBuilder.createImageTexelPointer(ptrType, baseId, coordId, zero);
  5805. }
  5806. }
  5807. if (!ptr)
  5808. ptr = doExpr(dest);
  5809. const bool isCompareExchange =
  5810. opcode == hlsl::IntrinsicOp::IOP_InterlockedCompareExchange;
  5811. const bool isCompareStore =
  5812. opcode == hlsl::IntrinsicOp::IOP_InterlockedCompareStore;
  5813. if (isCompareExchange || isCompareStore) {
  5814. const uint32_t comparator = doArg(expr, 1);
  5815. const uint32_t valueId = doArg(expr, 2);
  5816. const uint32_t originalVal = theBuilder.createAtomicCompareExchange(
  5817. baseTypeId, ptr, scope, zero, zero, valueId, comparator);
  5818. if (isCompareExchange)
  5819. writeToOutputArg(originalVal, expr, 3);
  5820. } else {
  5821. const uint32_t valueId = doArg(expr, 1);
  5822. // Since these atomic operations write through the provided pointer, the
  5823. // signed vs. unsigned opcode must be decided based on the pointee type
  5824. // of the first argument. However, the frontend decides the opcode based on
  5825. // the second argument (value). Therefore, the HLSL opcode provided by the
  5826. // frontend may be wrong. Therefore we need the following code to make sure
  5827. // we are using the correct SPIR-V opcode.
  5828. spv::Op atomicOp = translateAtomicHlslOpcodeToSpirvOpcode(opcode);
  5829. if (atomicOp == spv::Op::OpAtomicUMax && baseType->isSignedIntegerType())
  5830. atomicOp = spv::Op::OpAtomicSMax;
  5831. if (atomicOp == spv::Op::OpAtomicSMax && baseType->isUnsignedIntegerType())
  5832. atomicOp = spv::Op::OpAtomicUMax;
  5833. if (atomicOp == spv::Op::OpAtomicUMin && baseType->isSignedIntegerType())
  5834. atomicOp = spv::Op::OpAtomicSMin;
  5835. if (atomicOp == spv::Op::OpAtomicSMin && baseType->isUnsignedIntegerType())
  5836. atomicOp = spv::Op::OpAtomicUMin;
  5837. const uint32_t originalVal = theBuilder.createAtomicOp(
  5838. atomicOp, baseTypeId, ptr, scope, zero, valueId);
  5839. if (expr->getNumArgs() > 2)
  5840. writeToOutputArg(originalVal, expr, 2);
  5841. }
  5842. return 0;
  5843. }
  5844. uint32_t SPIRVEmitter::processIntrinsicMsad4(const CallExpr *callExpr) {
  5845. emitWarning("msad4 intrinsic function is emulated using many SPIR-V "
  5846. "instructions due to lack of direct SPIR-V equivalent",
  5847. callExpr->getExprLoc());
  5848. // Compares a 4-byte reference value and an 8-byte source value and
  5849. // accumulates a vector of 4 sums. Each sum corresponds to the masked sum
  5850. // of absolute differences of a different byte alignment between the
  5851. // reference value and the source value.
  5852. // If we have:
  5853. // uint v0; // reference
  5854. // uint2 v1; // source
  5855. // uint4 v2; // accum
  5856. // uint4 o0; // result of msad4
  5857. // uint4 r0, t0; // temporary values
  5858. //
  5859. // Then msad4(v0, v1, v2) translates to the following SM5 assembly according
  5860. // to fxc:
  5861. // Step 1:
  5862. // ushr r0.xyz, v1.xxxx, l(8, 16, 24, 0)
  5863. // Step 2:
  5864. // [result], [ width ], [ offset ], [ insert ], [ base ]
  5865. // bfi t0.yzw, l(0, 8, 16, 24), l(0, 24, 16, 8), v1.yyyy , r0.xxyz
  5866. // mov t0.x, v1.x
  5867. // Step 3:
  5868. // msad o0.xyzw, v0.xxxx, t0.xyzw, v2.xyzw
  5869. const uint32_t glsl = theBuilder.getGLSLExtInstSet();
  5870. const auto boolType = theBuilder.getBoolType();
  5871. const auto intType = theBuilder.getInt32Type();
  5872. const auto uintType = theBuilder.getUint32Type();
  5873. const auto uint4Type = theBuilder.getVecType(uintType, 4);
  5874. const uint32_t reference = doExpr(callExpr->getArg(0));
  5875. const uint32_t source = doExpr(callExpr->getArg(1));
  5876. const uint32_t accum = doExpr(callExpr->getArg(2));
  5877. const auto uint0 = theBuilder.getConstantUint32(0);
  5878. const auto uint8 = theBuilder.getConstantUint32(8);
  5879. const auto uint16 = theBuilder.getConstantUint32(16);
  5880. const auto uint24 = theBuilder.getConstantUint32(24);
  5881. // Step 1.
  5882. const uint32_t v1x = theBuilder.createCompositeExtract(uintType, source, {0});
  5883. // r0.x = v1xS8 = v1.x shifted by 8 bits
  5884. uint32_t v1xS8 = theBuilder.createBinaryOp(spv::Op::OpShiftLeftLogical,
  5885. uintType, v1x, uint8);
  5886. // r0.y = v1xS16 = v1.x shifted by 16 bits
  5887. uint32_t v1xS16 = theBuilder.createBinaryOp(spv::Op::OpShiftLeftLogical,
  5888. uintType, v1x, uint16);
  5889. // r0.z = v1xS24 = v1.x shifted by 24 bits
  5890. uint32_t v1xS24 = theBuilder.createBinaryOp(spv::Op::OpShiftLeftLogical,
  5891. uintType, v1x, uint24);
  5892. // Step 2.
  5893. // Do bfi 3 times. DXIL bfi is equivalent to SPIR-V OpBitFieldInsert.
  5894. const uint32_t v1y = theBuilder.createCompositeExtract(uintType, source, {1});
  5895. // Note that t0.x = v1.x, nothing we need to do for that.
  5896. const uint32_t t0y =
  5897. theBuilder.createBitFieldInsert(uintType, /*base*/ v1xS8, /*insert*/ v1y,
  5898. /*offset*/ uint24,
  5899. /*width*/ uint8);
  5900. const uint32_t t0z =
  5901. theBuilder.createBitFieldInsert(uintType, /*base*/ v1xS16, /*insert*/ v1y,
  5902. /*offset*/ uint16,
  5903. /*width*/ uint16);
  5904. const uint32_t t0w =
  5905. theBuilder.createBitFieldInsert(uintType, /*base*/ v1xS24, /*insert*/ v1y,
  5906. /*offset*/ uint8,
  5907. /*width*/ uint24);
  5908. // Step 3. MSAD (Masked Sum of Absolute Differences)
  5909. // Now perform MSAD four times.
  5910. // Need to mimic this algorithm in SPIR-V!
  5911. //
  5912. // UINT msad( UINT ref, UINT src, UINT accum )
  5913. // {
  5914. // for (UINT i = 0; i < 4; i++)
  5915. // {
  5916. // BYTE refByte, srcByte, absDiff;
  5917. //
  5918. // refByte = (BYTE)(ref >> (i * 8));
  5919. // if (!refByte)
  5920. // {
  5921. // continue;
  5922. // }
  5923. //
  5924. // srcByte = (BYTE)(src >> (i * 8));
  5925. // if (refByte >= srcByte)
  5926. // {
  5927. // absDiff = refByte - srcByte;
  5928. // }
  5929. // else
  5930. // {
  5931. // absDiff = srcByte - refByte;
  5932. // }
  5933. //
  5934. // // The recommended overflow behavior for MSAD is
  5935. // // to do a 32-bit saturate. This is not
  5936. // // required, however, and wrapping is allowed.
  5937. // // So from an application point of view,
  5938. // // overflow behavior is undefined.
  5939. // if (UINT_MAX - accum < absDiff)
  5940. // {
  5941. // accum = UINT_MAX;
  5942. // break;
  5943. // }
  5944. // accum += absDiff;
  5945. // }
  5946. //
  5947. // return accum;
  5948. // }
  5949. llvm::SmallVector<uint32_t, 4> result;
  5950. const uint32_t accum0 =
  5951. theBuilder.createCompositeExtract(uintType, accum, {0});
  5952. const uint32_t accum1 =
  5953. theBuilder.createCompositeExtract(uintType, accum, {1});
  5954. const uint32_t accum2 =
  5955. theBuilder.createCompositeExtract(uintType, accum, {2});
  5956. const uint32_t accum3 =
  5957. theBuilder.createCompositeExtract(uintType, accum, {3});
  5958. const llvm::SmallVector<uint32_t, 4> sources = {v1x, t0y, t0z, t0w};
  5959. llvm::SmallVector<uint32_t, 4> accums = {accum0, accum1, accum2, accum3};
  5960. llvm::SmallVector<uint32_t, 4> refBytes;
  5961. llvm::SmallVector<uint32_t, 4> signedRefBytes;
  5962. llvm::SmallVector<uint32_t, 4> isRefByteZero;
  5963. for (uint32_t i = 0; i < 4; ++i) {
  5964. refBytes.push_back(theBuilder.createBitFieldExtract(
  5965. uintType, reference, /*offset*/ theBuilder.getConstantUint32(i * 8),
  5966. /*count*/ uint8, /*isSigned*/ false));
  5967. signedRefBytes.push_back(
  5968. theBuilder.createUnaryOp(spv::Op::OpBitcast, intType, refBytes.back()));
  5969. isRefByteZero.push_back(theBuilder.createBinaryOp(
  5970. spv::Op::OpIEqual, boolType, refBytes.back(), uint0));
  5971. }
  5972. for (uint32_t msadNum = 0; msadNum < 4; ++msadNum) {
  5973. for (uint32_t byteCount = 0; byteCount < 4; ++byteCount) {
  5974. // 'count' is always 8 because we are extracting 8 bits out of 32.
  5975. const uint32_t srcByte = theBuilder.createBitFieldExtract(
  5976. uintType, sources[msadNum],
  5977. /*offset*/ theBuilder.getConstantUint32(8 * byteCount),
  5978. /*count*/ uint8, /*isSigned*/ false);
  5979. const uint32_t signedSrcByte =
  5980. theBuilder.createUnaryOp(spv::Op::OpBitcast, intType, srcByte);
  5981. const uint32_t sub = theBuilder.createBinaryOp(
  5982. spv::Op::OpISub, intType, signedRefBytes[byteCount], signedSrcByte);
  5983. const uint32_t absSub = theBuilder.createExtInst(
  5984. intType, glsl, GLSLstd450::GLSLstd450SAbs, {sub});
  5985. const uint32_t diff = theBuilder.createSelect(
  5986. uintType, isRefByteZero[byteCount], uint0,
  5987. theBuilder.createUnaryOp(spv::Op::OpBitcast, uintType, absSub));
  5988. // As pointed out by the DXIL reference above, it is *not* required to
  5989. // saturate the output to UINT_MAX in case of overflow. Wrapping around is
  5990. // also allowed. For simplicity, we will wrap around at this point.
  5991. accums[msadNum] = theBuilder.createBinaryOp(spv::Op::OpIAdd, uintType,
  5992. accums[msadNum], diff);
  5993. }
  5994. }
  5995. return theBuilder.createCompositeConstruct(uint4Type, accums);
  5996. }
  5997. uint32_t SPIRVEmitter::processWaveQuery(const CallExpr *callExpr,
  5998. spv::Op opcode) {
  5999. // Signatures:
  6000. // bool WaveIsFirstLane()
  6001. // uint WaveGetLaneCount()
  6002. // uint WaveGetLaneIndex()
  6003. assert(callExpr->getNumArgs() == 0);
  6004. featureManager.requestTargetEnv(SPV_ENV_VULKAN_1_1, "Wave Operation",
  6005. callExpr->getExprLoc());
  6006. theBuilder.requireCapability(getCapabilityForGroupNonUniform(opcode));
  6007. const uint32_t subgroupScope = theBuilder.getConstantInt32(3);
  6008. const uint32_t retType =
  6009. typeTranslator.translateType(callExpr->getCallReturnType(astContext));
  6010. return theBuilder.createGroupNonUniformOp(opcode, retType, subgroupScope);
  6011. }
  6012. uint32_t SPIRVEmitter::processWaveVote(const CallExpr *callExpr,
  6013. spv::Op opcode) {
  6014. // Signatures:
  6015. // bool WaveActiveAnyTrue( bool expr )
  6016. // bool WaveActiveAllTrue( bool expr )
  6017. // bool uint4 WaveActiveBallot( bool expr )
  6018. assert(callExpr->getNumArgs() == 1);
  6019. featureManager.requestTargetEnv(SPV_ENV_VULKAN_1_1, "Wave Operation",
  6020. callExpr->getExprLoc());
  6021. theBuilder.requireCapability(getCapabilityForGroupNonUniform(opcode));
  6022. const uint32_t predicate = doExpr(callExpr->getArg(0));
  6023. const uint32_t subgroupScope = theBuilder.getConstantInt32(3);
  6024. const uint32_t retType =
  6025. typeTranslator.translateType(callExpr->getCallReturnType(astContext));
  6026. return theBuilder.createGroupNonUniformUnaryOp(opcode, retType, subgroupScope,
  6027. predicate);
  6028. }
  6029. spv::Op SPIRVEmitter::translateWaveOp(hlsl::IntrinsicOp op, QualType type,
  6030. SourceLocation srcLoc) {
  6031. const bool isSintType = isSintOrVecMatOfSintType(type);
  6032. const bool isUintType = isUintOrVecMatOfUintType(type);
  6033. const bool isFloatType = isFloatOrVecMatOfFloatType(type);
  6034. #define WAVE_OP_CASE_INT(kind, intWaveOp) \
  6035. \
  6036. case hlsl::IntrinsicOp::IOP_Wave##kind: { \
  6037. if (isSintType || isUintType) { \
  6038. return spv::Op::OpGroupNonUniform##intWaveOp; \
  6039. } \
  6040. } break
  6041. #define WAVE_OP_CASE_INT_FLOAT(kind, intWaveOp, floatWaveOp) \
  6042. \
  6043. case hlsl::IntrinsicOp::IOP_Wave##kind: { \
  6044. if (isSintType || isUintType) { \
  6045. return spv::Op::OpGroupNonUniform##intWaveOp; \
  6046. } \
  6047. if (isFloatType) { \
  6048. return spv::Op::OpGroupNonUniform##floatWaveOp; \
  6049. } \
  6050. } break
  6051. #define WAVE_OP_CASE_SINT_UINT_FLOAT(kind, sintWaveOp, uintWaveOp, \
  6052. floatWaveOp) \
  6053. \
  6054. case hlsl::IntrinsicOp::IOP_Wave##kind: { \
  6055. if (isSintType) { \
  6056. return spv::Op::OpGroupNonUniform##sintWaveOp; \
  6057. } \
  6058. if (isUintType) { \
  6059. return spv::Op::OpGroupNonUniform##uintWaveOp; \
  6060. } \
  6061. if (isFloatType) { \
  6062. return spv::Op::OpGroupNonUniform##floatWaveOp; \
  6063. } \
  6064. } break
  6065. switch (op) {
  6066. WAVE_OP_CASE_INT_FLOAT(ActiveUSum, IAdd, FAdd);
  6067. WAVE_OP_CASE_INT_FLOAT(ActiveSum, IAdd, FAdd);
  6068. WAVE_OP_CASE_INT_FLOAT(ActiveUProduct, IMul, FMul);
  6069. WAVE_OP_CASE_INT_FLOAT(ActiveProduct, IMul, FMul);
  6070. WAVE_OP_CASE_INT_FLOAT(PrefixUSum, IAdd, FAdd);
  6071. WAVE_OP_CASE_INT_FLOAT(PrefixSum, IAdd, FAdd);
  6072. WAVE_OP_CASE_INT_FLOAT(PrefixUProduct, IMul, FMul);
  6073. WAVE_OP_CASE_INT_FLOAT(PrefixProduct, IMul, FMul);
  6074. WAVE_OP_CASE_INT(ActiveBitAnd, BitwiseAnd);
  6075. WAVE_OP_CASE_INT(ActiveBitOr, BitwiseOr);
  6076. WAVE_OP_CASE_INT(ActiveBitXor, BitwiseXor);
  6077. WAVE_OP_CASE_SINT_UINT_FLOAT(ActiveUMax, SMax, UMax, FMax);
  6078. WAVE_OP_CASE_SINT_UINT_FLOAT(ActiveMax, SMax, UMax, FMax);
  6079. WAVE_OP_CASE_SINT_UINT_FLOAT(ActiveUMin, SMin, UMin, FMin);
  6080. WAVE_OP_CASE_SINT_UINT_FLOAT(ActiveMin, SMin, UMin, FMin);
  6081. }
  6082. #undef WAVE_OP_CASE_INT_FLOAT
  6083. #undef WAVE_OP_CASE_INT
  6084. #undef WAVE_OP_CASE_SINT_UINT_FLOAT
  6085. emitError("translating wave operator '%0' unimplemented", srcLoc)
  6086. << static_cast<uint32_t>(op);
  6087. return spv::Op::OpNop;
  6088. }
  6089. uint32_t SPIRVEmitter::processWaveReductionOrPrefix(
  6090. const CallExpr *callExpr, spv::Op opcode, spv::GroupOperation groupOp) {
  6091. // Signatures:
  6092. // bool WaveActiveAllEqual( <type> expr )
  6093. // uint WaveActiveCountBits( bool bBit )
  6094. // <type> WaveActiveSum( <type> expr )
  6095. // <type> WaveActiveProduct( <type> expr )
  6096. // <int_type> WaveActiveBitAnd( <int_type> expr )
  6097. // <int_type> WaveActiveBitOr( <int_type> expr )
  6098. // <int_type> WaveActiveBitXor( <int_type> expr )
  6099. // <type> WaveActiveMin( <type> expr)
  6100. // <type> WaveActiveMax( <type> expr)
  6101. //
  6102. // uint WavePrefixCountBits(Bool bBit)
  6103. // <type> WavePrefixProduct(<type> value)
  6104. // <type> WavePrefixSum(<type> value)
  6105. assert(callExpr->getNumArgs() == 1);
  6106. featureManager.requestTargetEnv(SPV_ENV_VULKAN_1_1, "Wave Operation",
  6107. callExpr->getExprLoc());
  6108. theBuilder.requireCapability(getCapabilityForGroupNonUniform(opcode));
  6109. const uint32_t predicate = doExpr(callExpr->getArg(0));
  6110. const uint32_t subgroupScope = theBuilder.getConstantInt32(3);
  6111. const uint32_t retType =
  6112. typeTranslator.translateType(callExpr->getCallReturnType(astContext));
  6113. return theBuilder.createGroupNonUniformUnaryOp(
  6114. opcode, retType, subgroupScope, predicate,
  6115. llvm::Optional<spv::GroupOperation>(groupOp));
  6116. }
  6117. uint32_t SPIRVEmitter::processWaveBroadcast(const CallExpr *callExpr) {
  6118. // Signatures:
  6119. // <type> WaveReadLaneFirst(<type> expr)
  6120. // <type> WaveReadLaneAt(<type> expr, uint laneIndex)
  6121. const auto numArgs = callExpr->getNumArgs();
  6122. assert(numArgs == 1 || numArgs == 2);
  6123. featureManager.requestTargetEnv(SPV_ENV_VULKAN_1_1, "Wave Operation",
  6124. callExpr->getExprLoc());
  6125. theBuilder.requireCapability(spv::Capability::GroupNonUniformBallot);
  6126. const uint32_t value = doExpr(callExpr->getArg(0));
  6127. const uint32_t subgroupScope = theBuilder.getConstantInt32(3);
  6128. const uint32_t retType =
  6129. typeTranslator.translateType(callExpr->getCallReturnType(astContext));
  6130. if (numArgs == 2)
  6131. return theBuilder.createGroupNonUniformBinaryOp(
  6132. spv::Op::OpGroupNonUniformBroadcast, retType, subgroupScope, value,
  6133. doExpr(callExpr->getArg(1)));
  6134. else
  6135. return theBuilder.createGroupNonUniformUnaryOp(
  6136. spv::Op::OpGroupNonUniformBroadcastFirst, retType, subgroupScope,
  6137. value);
  6138. }
  6139. uint32_t SPIRVEmitter::processWaveQuadWideShuffle(const CallExpr *callExpr,
  6140. hlsl::IntrinsicOp op) {
  6141. // Signatures:
  6142. // <type> QuadReadAcrossX(<type> localValue)
  6143. // <type> QuadReadAcrossY(<type> localValue)
  6144. // <type> QuadReadAcrossDiagonal(<type> localValue)
  6145. // <type> QuadReadLaneAt(<type> sourceValue, uint quadLaneID)
  6146. assert(callExpr->getNumArgs() == 1 || callExpr->getNumArgs() == 2);
  6147. featureManager.requestTargetEnv(SPV_ENV_VULKAN_1_1, "Wave Operation",
  6148. callExpr->getExprLoc());
  6149. theBuilder.requireCapability(spv::Capability::GroupNonUniformQuad);
  6150. const uint32_t value = doExpr(callExpr->getArg(0));
  6151. const uint32_t subgroupScope = theBuilder.getConstantInt32(3);
  6152. const uint32_t retType =
  6153. typeTranslator.translateType(callExpr->getCallReturnType(astContext));
  6154. uint32_t target = 0;
  6155. spv::Op opcode = spv::Op::OpGroupNonUniformQuadSwap;
  6156. switch (op) {
  6157. case hlsl::IntrinsicOp::IOP_QuadReadAcrossX:
  6158. target = theBuilder.getConstantUint32(0);
  6159. break;
  6160. case hlsl::IntrinsicOp::IOP_QuadReadAcrossY:
  6161. target = theBuilder.getConstantUint32(1);
  6162. break;
  6163. case hlsl::IntrinsicOp::IOP_QuadReadAcrossDiagonal:
  6164. target = theBuilder.getConstantUint32(2);
  6165. break;
  6166. case hlsl::IntrinsicOp::IOP_QuadReadLaneAt:
  6167. target = doExpr(callExpr->getArg(1));
  6168. opcode = spv::Op::OpGroupNonUniformQuadBroadcast;
  6169. break;
  6170. default:
  6171. llvm_unreachable("case should not appear here");
  6172. }
  6173. return theBuilder.createGroupNonUniformBinaryOp(opcode, retType,
  6174. subgroupScope, value, target);
  6175. }
  6176. uint32_t SPIRVEmitter::processIntrinsicModf(const CallExpr *callExpr) {
  6177. // Signature is: ret modf(x, ip)
  6178. // [in] x: the input floating-point value.
  6179. // [out] ip: the integer portion of x.
  6180. // [out] ret: the fractional portion of x.
  6181. // All of the above must be a scalar, vector, or matrix with the same
  6182. // component types. Component types can be float or int.
  6183. // The ModfStruct SPIR-V instruction returns a struct. The first member is the
  6184. // fractional part and the second member is the integer portion.
  6185. // ModfStruct {
  6186. // <scalar or vector of float> frac;
  6187. // <scalar or vector of float> ip;
  6188. // }
  6189. // Note if the input number (x) is not a float (i.e. 'x' is an int), it is
  6190. // automatically converted to float before modf is invoked. Sadly, the 'ip'
  6191. // argument is not treated the same way. Therefore, in such cases we'll have
  6192. // to manually convert the float result into int.
  6193. const uint32_t glslInstSetId = theBuilder.getGLSLExtInstSet();
  6194. const Expr *arg = callExpr->getArg(0);
  6195. const Expr *ipArg = callExpr->getArg(1);
  6196. const auto argType = arg->getType();
  6197. const auto ipType = ipArg->getType();
  6198. const auto returnType = callExpr->getType();
  6199. const auto returnTypeId = typeTranslator.translateType(returnType);
  6200. const auto ipTypeId = typeTranslator.translateType(ipType);
  6201. const uint32_t argId = doExpr(arg);
  6202. const uint32_t ipId = doExpr(ipArg);
  6203. // For scalar and vector argument types.
  6204. {
  6205. if (TypeTranslator::isScalarType(argType) ||
  6206. TypeTranslator::isVectorType(argType)) {
  6207. const auto argTypeId = typeTranslator.translateType(argType);
  6208. // The struct members *must* have the same type.
  6209. const auto modfStructTypeId = theBuilder.getStructType(
  6210. {argTypeId, argTypeId}, "ModfStructType", {"frac", "ip"});
  6211. const auto modf =
  6212. theBuilder.createExtInst(modfStructTypeId, glslInstSetId,
  6213. GLSLstd450::GLSLstd450ModfStruct, {argId});
  6214. auto ip = theBuilder.createCompositeExtract(argTypeId, modf, {1});
  6215. // This will do nothing if the input number (x) and the ip are both of the
  6216. // same type. Otherwise, it will convert the ip into int as necessary.
  6217. ip = castToInt(ip, argType, ipType, arg->getExprLoc());
  6218. theBuilder.createStore(ipId, ip);
  6219. return theBuilder.createCompositeExtract(argTypeId, modf, {0});
  6220. }
  6221. }
  6222. // For matrix argument types.
  6223. {
  6224. uint32_t rowCount = 0, colCount = 0;
  6225. QualType elemType = {};
  6226. if (TypeTranslator::isMxNMatrix(argType, &elemType, &rowCount, &colCount)) {
  6227. const auto elemTypeId = typeTranslator.translateType(elemType);
  6228. const auto colTypeId = theBuilder.getVecType(elemTypeId, colCount);
  6229. const auto modfStructTypeId = theBuilder.getStructType(
  6230. {colTypeId, colTypeId}, "ModfStructType", {"frac", "ip"});
  6231. llvm::SmallVector<uint32_t, 4> fracs;
  6232. llvm::SmallVector<uint32_t, 4> ips;
  6233. for (uint32_t i = 0; i < rowCount; ++i) {
  6234. const auto curRow =
  6235. theBuilder.createCompositeExtract(colTypeId, argId, {i});
  6236. const auto modf = theBuilder.createExtInst(
  6237. modfStructTypeId, glslInstSetId, GLSLstd450::GLSLstd450ModfStruct,
  6238. {curRow});
  6239. auto ip = theBuilder.createCompositeExtract(colTypeId, modf, {1});
  6240. ips.push_back(ip);
  6241. fracs.push_back(
  6242. theBuilder.createCompositeExtract(colTypeId, modf, {0}));
  6243. }
  6244. uint32_t ip = theBuilder.createCompositeConstruct(
  6245. typeTranslator.translateType(argType), ips);
  6246. // If the 'ip' is not a float type, the AST will not contain a CastExpr
  6247. // because this is internal to the intrinsic function. So, in such a
  6248. // case we need to cast manually.
  6249. if (!hlsl::GetHLSLMatElementType(ipType)->isFloatingType())
  6250. ip = castToInt(ip, argType, ipType, ipArg->getExprLoc());
  6251. theBuilder.createStore(ipId, ip);
  6252. return theBuilder.createCompositeConstruct(returnTypeId, fracs);
  6253. }
  6254. }
  6255. emitError("invalid argument type passed to Modf intrinsic function",
  6256. callExpr->getExprLoc());
  6257. return 0;
  6258. }
  6259. uint32_t SPIRVEmitter::processIntrinsicLit(const CallExpr *callExpr) {
  6260. // Signature is: float4 lit(float n_dot_l, float n_dot_h, float m)
  6261. //
  6262. // This function returns a lighting coefficient vector
  6263. // (ambient, diffuse, specular, 1) where:
  6264. // ambient = 1.
  6265. // diffuse = (n_dot_l < 0) ? 0 : n_dot_l
  6266. // specular = (n_dot_l < 0 || n_dot_h < 0) ? 0 : ((n_dot_h) * m)
  6267. const uint32_t glslInstSetId = theBuilder.getGLSLExtInstSet();
  6268. const uint32_t nDotL = doExpr(callExpr->getArg(0));
  6269. const uint32_t nDotH = doExpr(callExpr->getArg(1));
  6270. const uint32_t m = doExpr(callExpr->getArg(2));
  6271. const uint32_t floatType = theBuilder.getFloat32Type();
  6272. const uint32_t boolType = theBuilder.getBoolType();
  6273. const uint32_t floatZero = theBuilder.getConstantFloat32(0);
  6274. const uint32_t floatOne = theBuilder.getConstantFloat32(1);
  6275. const uint32_t retType = typeTranslator.translateType(callExpr->getType());
  6276. const uint32_t diffuse = theBuilder.createExtInst(
  6277. floatType, glslInstSetId, GLSLstd450::GLSLstd450FMax, {floatZero, nDotL});
  6278. const uint32_t min = theBuilder.createExtInst(
  6279. floatType, glslInstSetId, GLSLstd450::GLSLstd450FMin, {nDotL, nDotH});
  6280. const uint32_t isNeg = theBuilder.createBinaryOp(spv::Op::OpFOrdLessThan,
  6281. boolType, min, floatZero);
  6282. const uint32_t mul =
  6283. theBuilder.createBinaryOp(spv::Op::OpFMul, floatType, nDotH, m);
  6284. const uint32_t specular =
  6285. theBuilder.createSelect(floatType, isNeg, floatZero, mul);
  6286. return theBuilder.createCompositeConstruct(
  6287. retType, {floatOne, diffuse, specular, floatOne});
  6288. }
  6289. uint32_t SPIRVEmitter::processIntrinsicFrexp(const CallExpr *callExpr) {
  6290. // Signature is: ret frexp(x, exp)
  6291. // [in] x: the input floating-point value.
  6292. // [out] exp: the calculated exponent.
  6293. // [out] ret: the calculated mantissa.
  6294. // All of the above must be a scalar, vector, or matrix of *float* type.
  6295. // The FrexpStruct SPIR-V instruction returns a struct. The first
  6296. // member is the significand (mantissa) and must be of the same type as the
  6297. // input parameter, and the second member is the exponent and must always be a
  6298. // scalar or vector of 32-bit *integer* type.
  6299. // FrexpStruct {
  6300. // <scalar or vector of int/float> mantissa;
  6301. // <scalar or vector of integers> exponent;
  6302. // }
  6303. const uint32_t glslInstSetId = theBuilder.getGLSLExtInstSet();
  6304. const Expr *arg = callExpr->getArg(0);
  6305. const auto argType = arg->getType();
  6306. const auto intId = theBuilder.getInt32Type();
  6307. const auto returnTypeId = typeTranslator.translateType(callExpr->getType());
  6308. const uint32_t argId = doExpr(arg);
  6309. const uint32_t expId = doExpr(callExpr->getArg(1));
  6310. // For scalar and vector argument types.
  6311. {
  6312. uint32_t elemCount = 1;
  6313. if (TypeTranslator::isScalarType(argType) ||
  6314. TypeTranslator::isVectorType(argType, nullptr, &elemCount)) {
  6315. const auto argTypeId = typeTranslator.translateType(argType);
  6316. const auto expTypeId =
  6317. elemCount == 1 ? intId : theBuilder.getVecType(intId, elemCount);
  6318. const auto frexpStructTypeId = theBuilder.getStructType(
  6319. {argTypeId, expTypeId}, "FrexpStructType", {"mantissa", "exponent"});
  6320. const auto frexp =
  6321. theBuilder.createExtInst(frexpStructTypeId, glslInstSetId,
  6322. GLSLstd450::GLSLstd450FrexpStruct, {argId});
  6323. const auto exponentInt =
  6324. theBuilder.createCompositeExtract(expTypeId, frexp, {1});
  6325. // Since the SPIR-V instruction returns an int, and the intrinsic HLSL
  6326. // expects a float, an conversion must take place before writing the
  6327. // results.
  6328. const auto exponentFloat = theBuilder.createUnaryOp(
  6329. spv::Op::OpConvertSToF, returnTypeId, exponentInt);
  6330. theBuilder.createStore(expId, exponentFloat);
  6331. return theBuilder.createCompositeExtract(argTypeId, frexp, {0});
  6332. }
  6333. }
  6334. // For matrix argument types.
  6335. {
  6336. uint32_t rowCount = 0, colCount = 0;
  6337. if (TypeTranslator::isMxNMatrix(argType, nullptr, &rowCount, &colCount)) {
  6338. const auto floatId = theBuilder.getFloat32Type();
  6339. const auto expTypeId = theBuilder.getVecType(intId, colCount);
  6340. const auto colTypeId = theBuilder.getVecType(floatId, colCount);
  6341. const auto frexpStructTypeId = theBuilder.getStructType(
  6342. {colTypeId, expTypeId}, "FrexpStructType", {"mantissa", "exponent"});
  6343. llvm::SmallVector<uint32_t, 4> exponents;
  6344. llvm::SmallVector<uint32_t, 4> mantissas;
  6345. for (uint32_t i = 0; i < rowCount; ++i) {
  6346. const auto curRow =
  6347. theBuilder.createCompositeExtract(colTypeId, argId, {i});
  6348. const auto frexp = theBuilder.createExtInst(
  6349. frexpStructTypeId, glslInstSetId, GLSLstd450::GLSLstd450FrexpStruct,
  6350. {curRow});
  6351. const auto exponentInt =
  6352. theBuilder.createCompositeExtract(expTypeId, frexp, {1});
  6353. // Since the SPIR-V instruction returns an int, and the intrinsic HLSL
  6354. // expects a float, an conversion must take place before writing the
  6355. // results.
  6356. const auto exponentFloat = theBuilder.createUnaryOp(
  6357. spv::Op::OpConvertSToF, colTypeId, exponentInt);
  6358. exponents.push_back(exponentFloat);
  6359. mantissas.push_back(
  6360. theBuilder.createCompositeExtract(colTypeId, frexp, {0}));
  6361. }
  6362. const auto exponentsResultId =
  6363. theBuilder.createCompositeConstruct(returnTypeId, exponents);
  6364. theBuilder.createStore(expId, exponentsResultId);
  6365. return theBuilder.createCompositeConstruct(returnTypeId, mantissas);
  6366. }
  6367. }
  6368. emitError("invalid argument type passed to Frexp intrinsic function",
  6369. callExpr->getExprLoc());
  6370. return 0;
  6371. }
  6372. uint32_t SPIRVEmitter::processIntrinsicLdexp(const CallExpr *callExpr) {
  6373. // Signature: ret ldexp(x, exp)
  6374. // This function uses the following formula: x * 2^exp.
  6375. // Note that we cannot use GLSL extended instruction Ldexp since it requires
  6376. // the exponent to be an integer (vector) but HLSL takes an float (vector)
  6377. // exponent. So we must calculate the result manually.
  6378. const uint32_t glsl = theBuilder.getGLSLExtInstSet();
  6379. const Expr *x = callExpr->getArg(0);
  6380. const auto paramType = x->getType();
  6381. const uint32_t xId = doExpr(x);
  6382. const uint32_t expId = doExpr(callExpr->getArg(1));
  6383. // For scalar and vector argument types.
  6384. if (TypeTranslator::isScalarType(paramType) ||
  6385. TypeTranslator::isVectorType(paramType)) {
  6386. const auto paramTypeId = typeTranslator.translateType(paramType);
  6387. const auto twoExp = theBuilder.createExtInst(
  6388. paramTypeId, glsl, GLSLstd450::GLSLstd450Exp2, {expId});
  6389. return theBuilder.createBinaryOp(spv::Op::OpFMul, paramTypeId, xId, twoExp);
  6390. }
  6391. // For matrix argument types.
  6392. {
  6393. uint32_t rowCount = 0, colCount = 0;
  6394. if (TypeTranslator::isMxNMatrix(paramType, nullptr, &rowCount, &colCount)) {
  6395. const auto actOnEachVec = [this, glsl, expId](uint32_t index,
  6396. uint32_t vecType,
  6397. uint32_t xRowId) {
  6398. const auto expRowId =
  6399. theBuilder.createCompositeExtract(vecType, expId, {index});
  6400. const auto twoExp = theBuilder.createExtInst(
  6401. vecType, glsl, GLSLstd450::GLSLstd450Exp2, {expRowId});
  6402. return theBuilder.createBinaryOp(spv::Op::OpFMul, vecType, xRowId,
  6403. twoExp);
  6404. };
  6405. return processEachVectorInMatrix(x, xId, actOnEachVec);
  6406. }
  6407. }
  6408. emitError("invalid argument type passed to ldexp intrinsic function",
  6409. callExpr->getExprLoc());
  6410. return 0;
  6411. }
  6412. uint32_t SPIRVEmitter::processIntrinsicDst(const CallExpr *callExpr) {
  6413. // Signature is float4 dst(float4 src0, float4 src1)
  6414. // result.x = 1;
  6415. // result.y = src0.y * src1.y;
  6416. // result.z = src0.z;
  6417. // result.w = src1.w;
  6418. const auto floatId = theBuilder.getFloat32Type();
  6419. const auto arg0Id = doExpr(callExpr->getArg(0));
  6420. const auto arg1Id = doExpr(callExpr->getArg(1));
  6421. const auto arg0y = theBuilder.createCompositeExtract(floatId, arg0Id, {1});
  6422. const auto arg1y = theBuilder.createCompositeExtract(floatId, arg1Id, {1});
  6423. const auto arg0z = theBuilder.createCompositeExtract(floatId, arg0Id, {2});
  6424. const auto arg1w = theBuilder.createCompositeExtract(floatId, arg1Id, {3});
  6425. const auto arg0yMularg1y =
  6426. theBuilder.createBinaryOp(spv::Op::OpFMul, floatId, arg0y, arg1y);
  6427. return theBuilder.createCompositeConstruct(
  6428. typeTranslator.translateType(callExpr->getType()),
  6429. {theBuilder.getConstantFloat32(1.0), arg0yMularg1y, arg0z, arg1w});
  6430. }
  6431. uint32_t SPIRVEmitter::processIntrinsicClip(const CallExpr *callExpr) {
  6432. // Discards the current pixel if the specified value is less than zero.
  6433. // TODO: If the argument can be const folded and evaluated, we could
  6434. // potentially avoid creating a branch. This would be a bit challenging for
  6435. // matrix/vector arguments.
  6436. assert(callExpr->getNumArgs() == 1u);
  6437. const Expr *arg = callExpr->getArg(0);
  6438. const auto argType = arg->getType();
  6439. const auto boolType = theBuilder.getBoolType();
  6440. uint32_t condition = 0;
  6441. // Could not determine the argument as a constant. We need to branch based on
  6442. // the argument. If the argument is a vector/matrix, clipping is done if *any*
  6443. // element of the vector/matrix is less than zero.
  6444. const uint32_t argId = doExpr(arg);
  6445. QualType elemType = {};
  6446. uint32_t elemCount = 0, rowCount = 0, colCount = 0;
  6447. if (TypeTranslator::isScalarType(argType)) {
  6448. const auto zero = getValueZero(argType);
  6449. condition = theBuilder.createBinaryOp(spv::Op::OpFOrdLessThan, boolType,
  6450. argId, zero);
  6451. } else if (TypeTranslator::isVectorType(argType, nullptr, &elemCount)) {
  6452. const auto zero = getValueZero(argType);
  6453. const auto boolVecType = theBuilder.getVecType(boolType, elemCount);
  6454. const auto cmp = theBuilder.createBinaryOp(spv::Op::OpFOrdLessThan,
  6455. boolVecType, argId, zero);
  6456. condition = theBuilder.createUnaryOp(spv::Op::OpAny, boolType, cmp);
  6457. } else if (TypeTranslator::isMxNMatrix(argType, &elemType, &rowCount,
  6458. &colCount)) {
  6459. const uint32_t elemTypeId = typeTranslator.translateType(elemType);
  6460. const uint32_t floatVecType = theBuilder.getVecType(elemTypeId, colCount);
  6461. const uint32_t elemZeroId = getValueZero(elemType);
  6462. llvm::SmallVector<uint32_t, 4> elements(size_t(colCount), elemZeroId);
  6463. const auto zero = theBuilder.getConstantComposite(floatVecType, elements);
  6464. llvm::SmallVector<uint32_t, 4> cmpResults;
  6465. for (uint32_t i = 0; i < rowCount; ++i) {
  6466. const uint32_t lhsVec =
  6467. theBuilder.createCompositeExtract(floatVecType, argId, {i});
  6468. const auto boolColType = theBuilder.getVecType(boolType, colCount);
  6469. const auto cmp = theBuilder.createBinaryOp(spv::Op::OpFOrdLessThan,
  6470. boolColType, lhsVec, zero);
  6471. const auto any = theBuilder.createUnaryOp(spv::Op::OpAny, boolType, cmp);
  6472. cmpResults.push_back(any);
  6473. }
  6474. const auto boolRowType = theBuilder.getVecType(boolType, rowCount);
  6475. const auto results =
  6476. theBuilder.createCompositeConstruct(boolRowType, cmpResults);
  6477. condition = theBuilder.createUnaryOp(spv::Op::OpAny, boolType, results);
  6478. } else {
  6479. emitError("invalid argument type passed to clip intrinsic function",
  6480. callExpr->getExprLoc());
  6481. return 0;
  6482. }
  6483. // Then we need to emit the instruction for the conditional branch.
  6484. const uint32_t thenBB = theBuilder.createBasicBlock("if.true");
  6485. const uint32_t mergeBB = theBuilder.createBasicBlock("if.merge");
  6486. // Create the branch instruction. This will end the current basic block.
  6487. theBuilder.createConditionalBranch(condition, thenBB, mergeBB, mergeBB);
  6488. theBuilder.addSuccessor(thenBB);
  6489. theBuilder.addSuccessor(mergeBB);
  6490. theBuilder.setMergeTarget(mergeBB);
  6491. // Handle the then branch
  6492. theBuilder.setInsertPoint(thenBB);
  6493. theBuilder.createKill();
  6494. theBuilder.addSuccessor(mergeBB);
  6495. // From now on, we'll emit instructions into the merge block.
  6496. theBuilder.setInsertPoint(mergeBB);
  6497. return 0;
  6498. }
  6499. uint32_t SPIRVEmitter::processIntrinsicClamp(const CallExpr *callExpr) {
  6500. // According the HLSL reference: clamp(X, Min, Max) takes 3 arguments. Each
  6501. // one may be int, uint, or float.
  6502. const uint32_t glslInstSetId = theBuilder.getGLSLExtInstSet();
  6503. const QualType returnType = callExpr->getType();
  6504. const uint32_t returnTypeId = typeTranslator.translateType(returnType);
  6505. GLSLstd450 glslOpcode = GLSLstd450::GLSLstd450UClamp;
  6506. if (isFloatOrVecMatOfFloatType(returnType))
  6507. glslOpcode = GLSLstd450::GLSLstd450FClamp;
  6508. else if (isSintOrVecMatOfSintType(returnType))
  6509. glslOpcode = GLSLstd450::GLSLstd450SClamp;
  6510. // Get the function parameters. Expect 3 parameters.
  6511. assert(callExpr->getNumArgs() == 3u);
  6512. const Expr *argX = callExpr->getArg(0);
  6513. const Expr *argMin = callExpr->getArg(1);
  6514. const Expr *argMax = callExpr->getArg(2);
  6515. const uint32_t argXId = doExpr(argX);
  6516. const uint32_t argMinId = doExpr(argMin);
  6517. const uint32_t argMaxId = doExpr(argMax);
  6518. // FClamp, UClamp, and SClamp do not operate on matrices, so we should perform
  6519. // the operation on each vector of the matrix.
  6520. if (TypeTranslator::isMxNMatrix(argX->getType())) {
  6521. const auto actOnEachVec = [this, glslInstSetId, glslOpcode, argMinId,
  6522. argMaxId](uint32_t index, uint32_t vecType,
  6523. uint32_t curRowId) {
  6524. const auto minRowId =
  6525. theBuilder.createCompositeExtract(vecType, argMinId, {index});
  6526. const auto maxRowId =
  6527. theBuilder.createCompositeExtract(vecType, argMaxId, {index});
  6528. return theBuilder.createExtInst(vecType, glslInstSetId, glslOpcode,
  6529. {curRowId, minRowId, maxRowId});
  6530. };
  6531. return processEachVectorInMatrix(argX, argXId, actOnEachVec);
  6532. }
  6533. return theBuilder.createExtInst(returnTypeId, glslInstSetId, glslOpcode,
  6534. {argXId, argMinId, argMaxId});
  6535. }
  6536. uint32_t SPIRVEmitter::processIntrinsicMemoryBarrier(const CallExpr *callExpr,
  6537. bool isDevice,
  6538. bool groupSync,
  6539. bool isAllBarrier) {
  6540. // * DeviceMemoryBarrier =
  6541. // OpMemoryBarrier (memScope=Device,
  6542. // sem=Image|Uniform|AcquireRelease)
  6543. //
  6544. // * DeviceMemoryBarrierWithGroupSync =
  6545. // OpControlBarrier(execScope = Workgroup,
  6546. // memScope=Device,
  6547. // sem=Image|Uniform|AcquireRelease)
  6548. const spv::MemorySemanticsMask deviceMemoryBarrierSema =
  6549. spv::MemorySemanticsMask::ImageMemory |
  6550. spv::MemorySemanticsMask::UniformMemory |
  6551. spv::MemorySemanticsMask::AcquireRelease;
  6552. // * GroupMemoryBarrier =
  6553. // OpMemoryBarrier (memScope=Workgroup,
  6554. // sem = Workgroup|AcquireRelease)
  6555. //
  6556. // * GroupMemoryBarrierWithGroupSync =
  6557. // OpControlBarrier (execScope = Workgroup,
  6558. // memScope = Workgroup,
  6559. // sem = Workgroup|AcquireRelease)
  6560. const spv::MemorySemanticsMask groupMemoryBarrierSema =
  6561. spv::MemorySemanticsMask::WorkgroupMemory |
  6562. spv::MemorySemanticsMask::AcquireRelease;
  6563. // * AllMemoryBarrier =
  6564. // OpMemoryBarrier(memScope = Device,
  6565. // sem = Image|Uniform|Workgroup|AcquireRelease)
  6566. //
  6567. // * AllMemoryBarrierWithGroupSync =
  6568. // OpControlBarrier(execScope = Workgroup,
  6569. // memScope = Device,
  6570. // sem = Image|Uniform|Workgroup|AcquireRelease)
  6571. const spv::MemorySemanticsMask allMemoryBarrierSema =
  6572. spv::MemorySemanticsMask::ImageMemory |
  6573. spv::MemorySemanticsMask::UniformMemory |
  6574. spv::MemorySemanticsMask::WorkgroupMemory |
  6575. spv::MemorySemanticsMask::AtomicCounterMemory |
  6576. spv::MemorySemanticsMask::AcquireRelease;
  6577. // Get <result-id> for execution scope.
  6578. // If present, execution scope is always Workgroup!
  6579. const uint32_t execScopeId =
  6580. groupSync ? theBuilder.getConstantUint32(
  6581. static_cast<uint32_t>(spv::Scope::Workgroup))
  6582. : 0;
  6583. // Get <result-id> for memory scope
  6584. const spv::Scope memScope =
  6585. (isDevice || isAllBarrier) ? spv::Scope::Device : spv::Scope::Workgroup;
  6586. const uint32_t memScopeId =
  6587. theBuilder.getConstantUint32(static_cast<uint32_t>(memScope));
  6588. // Get <result-id> for memory semantics
  6589. const auto memSemaMask = isAllBarrier ? allMemoryBarrierSema
  6590. : isDevice ? deviceMemoryBarrierSema
  6591. : groupMemoryBarrierSema;
  6592. const uint32_t memSema =
  6593. theBuilder.getConstantUint32(static_cast<uint32_t>(memSemaMask));
  6594. theBuilder.createBarrier(execScopeId, memScopeId, memSema);
  6595. return 0;
  6596. }
  6597. uint32_t SPIRVEmitter::processNonFpMatrixTranspose(QualType matType,
  6598. uint32_t matId) {
  6599. // Simplest way is to flatten the matrix construct a new matrix from the
  6600. // flattened elements. (for a mat4x4).
  6601. QualType elemType = {};
  6602. uint32_t numRows = 0, numCols = 0;
  6603. const bool isMat =
  6604. TypeTranslator::isMxNMatrix(matType, &elemType, &numRows, &numCols);
  6605. assert(isMat && !elemType->isFloatingType());
  6606. const auto rowQualType = astContext.getExtVectorType(elemType, numCols);
  6607. const auto colQualType = astContext.getExtVectorType(elemType, numRows);
  6608. const uint32_t rowTypeId = typeTranslator.translateType(rowQualType);
  6609. const uint32_t colTypeId = typeTranslator.translateType(colQualType);
  6610. const uint32_t elemTypeId = typeTranslator.translateType(elemType);
  6611. // You cannot perform a composite construct of an array using a few vectors.
  6612. // The number of constutients passed to OpCompositeConstruct must be equal to
  6613. // the number of array elements.
  6614. llvm::SmallVector<uint32_t, 4> elems;
  6615. for (uint32_t i = 0; i < numRows; ++i)
  6616. for (uint32_t j = 0; j < numCols; ++j)
  6617. elems.push_back(
  6618. theBuilder.createCompositeExtract(elemTypeId, matId, {i, j}));
  6619. llvm::SmallVector<uint32_t, 4> cols;
  6620. for (uint32_t i = 0; i < numCols; ++i) {
  6621. // The elements in the ith vector of the "transposed" array are at offset i,
  6622. // i + <original-vector-size>, ...
  6623. llvm::SmallVector<uint32_t, 4> indexes;
  6624. for (uint32_t j = 0; j < numRows; ++j)
  6625. indexes.push_back(elems[i + (j * numCols)]);
  6626. cols.push_back(theBuilder.createCompositeConstruct(colTypeId, indexes));
  6627. }
  6628. const auto transposeTypeId =
  6629. theBuilder.getArrayType(colTypeId, theBuilder.getConstantUint32(numCols));
  6630. return theBuilder.createCompositeConstruct(transposeTypeId, cols);
  6631. }
  6632. uint32_t SPIRVEmitter::processNonFpDot(uint32_t vec1Id, uint32_t vec2Id,
  6633. uint32_t vecSize, QualType elemType) {
  6634. const auto elemTypeId = typeTranslator.translateType(elemType);
  6635. llvm::SmallVector<uint32_t, 4> muls;
  6636. for (uint32_t i = 0; i < vecSize; ++i) {
  6637. const auto elem1 =
  6638. theBuilder.createCompositeExtract(elemTypeId, vec1Id, {i});
  6639. const auto elem2 =
  6640. theBuilder.createCompositeExtract(elemTypeId, vec2Id, {i});
  6641. muls.push_back(theBuilder.createBinaryOp(translateOp(BO_Mul, elemType),
  6642. elemTypeId, elem1, elem2));
  6643. }
  6644. uint32_t sum = muls[0];
  6645. for (uint32_t i = 1; i < vecSize; ++i) {
  6646. sum = theBuilder.createBinaryOp(translateOp(BO_Add, elemType), elemTypeId,
  6647. sum, muls[i]);
  6648. }
  6649. return sum;
  6650. }
  6651. uint32_t SPIRVEmitter::processNonFpScalarTimesMatrix(QualType scalarType,
  6652. uint32_t scalarId,
  6653. QualType matrixType,
  6654. uint32_t matrixId) {
  6655. assert(TypeTranslator::isScalarType(scalarType));
  6656. QualType elemType = {};
  6657. uint32_t numRows = 0, numCols = 0;
  6658. const bool isMat =
  6659. TypeTranslator::isMxNMatrix(matrixType, &elemType, &numRows, &numCols);
  6660. assert(isMat);
  6661. assert(typeTranslator.isSameType(scalarType, elemType));
  6662. // We need to multiply the scalar by each vector of the matrix.
  6663. // The front-end guarantees that the scalar and matrix element type are
  6664. // the same. For example, if the scalar is a float, the matrix is casted
  6665. // to a float matrix before being passed to mul(). It is also guaranteed
  6666. // that types such as bool are casted to float or int before being
  6667. // passed to mul().
  6668. const auto rowType = astContext.getExtVectorType(elemType, numCols);
  6669. const auto rowTypeId = typeTranslator.translateType(rowType);
  6670. llvm::SmallVector<uint32_t, 4> splat(size_t(numCols), scalarId);
  6671. const auto scalarSplat =
  6672. theBuilder.createCompositeConstruct(rowTypeId, splat);
  6673. llvm::SmallVector<uint32_t, 4> mulRows;
  6674. for (uint32_t row = 0; row < numRows; ++row) {
  6675. const auto rowId =
  6676. theBuilder.createCompositeExtract(rowTypeId, matrixId, {row});
  6677. mulRows.push_back(theBuilder.createBinaryOp(translateOp(BO_Mul, scalarType),
  6678. rowTypeId, rowId, scalarSplat));
  6679. }
  6680. return theBuilder.createCompositeConstruct(
  6681. typeTranslator.translateType(matrixType), mulRows);
  6682. }
  6683. uint32_t SPIRVEmitter::processNonFpVectorTimesMatrix(QualType vecType,
  6684. uint32_t vecId,
  6685. QualType matType,
  6686. uint32_t matId,
  6687. uint32_t matTransposeId) {
  6688. // This function assumes that the vector element type and matrix elemet type
  6689. // are the same.
  6690. QualType vecElemType = {}, matElemType = {};
  6691. uint32_t vecSize = 0, numRows = 0, numCols = 0;
  6692. const bool isVec =
  6693. TypeTranslator::isVectorType(vecType, &vecElemType, &vecSize);
  6694. const bool isMat =
  6695. TypeTranslator::isMxNMatrix(matType, &matElemType, &numRows, &numCols);
  6696. assert(typeTranslator.isSameType(vecElemType, matElemType));
  6697. assert(isVec);
  6698. assert(isMat);
  6699. assert(vecSize == numRows);
  6700. // When processing vector times matrix, the vector is a row vector, and it
  6701. // should be multiplied by the matrix *columns*. The most efficient way to
  6702. // handle this in SPIR-V would be to first transpose the matrix, and then use
  6703. // OpAccessChain.
  6704. if (!matTransposeId)
  6705. matTransposeId = processNonFpMatrixTranspose(matType, matId);
  6706. const auto vecTypeId = typeTranslator.translateType(vecType);
  6707. llvm::SmallVector<uint32_t, 4> resultElems;
  6708. for (uint32_t col = 0; col < numCols; ++col) {
  6709. const auto colId =
  6710. theBuilder.createCompositeExtract(vecTypeId, matTransposeId, {col});
  6711. resultElems.push_back(processNonFpDot(vecId, colId, vecSize, vecElemType));
  6712. }
  6713. return theBuilder.createCompositeConstruct(
  6714. typeTranslator.translateType(
  6715. astContext.getExtVectorType(vecElemType, numCols)),
  6716. resultElems);
  6717. }
  6718. uint32_t SPIRVEmitter::processNonFpMatrixTimesVector(QualType matType,
  6719. uint32_t matId,
  6720. QualType vecType,
  6721. uint32_t vecId) {
  6722. // This function assumes that the vector element type and matrix elemet type
  6723. // are the same.
  6724. QualType vecElemType = {}, matElemType = {};
  6725. uint32_t vecSize = 0, numRows = 0, numCols = 0;
  6726. const bool isVec =
  6727. TypeTranslator::isVectorType(vecType, &vecElemType, &vecSize);
  6728. const bool isMat =
  6729. TypeTranslator::isMxNMatrix(matType, &matElemType, &numRows, &numCols);
  6730. assert(typeTranslator.isSameType(vecElemType, matElemType));
  6731. assert(isVec);
  6732. assert(isMat);
  6733. assert(vecSize == numCols);
  6734. // When processing matrix times vector, the vector is a column vector. So we
  6735. // simply get each row of the matrix and perform a dot product with the
  6736. // vector.
  6737. const auto vecTypeId = typeTranslator.translateType(vecType);
  6738. llvm::SmallVector<uint32_t, 4> resultElems;
  6739. for (uint32_t row = 0; row < numRows; ++row) {
  6740. const auto rowId =
  6741. theBuilder.createCompositeExtract(vecTypeId, matId, {row});
  6742. resultElems.push_back(processNonFpDot(rowId, vecId, vecSize, vecElemType));
  6743. }
  6744. return theBuilder.createCompositeConstruct(
  6745. typeTranslator.translateType(
  6746. astContext.getExtVectorType(vecElemType, numRows)),
  6747. resultElems);
  6748. }
  6749. uint32_t SPIRVEmitter::processNonFpMatrixTimesMatrix(QualType lhsType,
  6750. uint32_t lhsId,
  6751. QualType rhsType,
  6752. uint32_t rhsId) {
  6753. // This function assumes that the vector element type and matrix elemet type
  6754. // are the same.
  6755. QualType lhsElemType = {}, rhsElemType = {};
  6756. uint32_t lhsNumRows = 0, lhsNumCols = 0;
  6757. uint32_t rhsNumRows = 0, rhsNumCols = 0;
  6758. const bool lhsIsMat = TypeTranslator::isMxNMatrix(lhsType, &lhsElemType,
  6759. &lhsNumRows, &lhsNumCols);
  6760. const bool rhsIsMat = TypeTranslator::isMxNMatrix(rhsType, &rhsElemType,
  6761. &rhsNumRows, &rhsNumCols);
  6762. assert(typeTranslator.isSameType(lhsElemType, rhsElemType));
  6763. assert(lhsIsMat && rhsIsMat);
  6764. assert(lhsNumCols == rhsNumRows);
  6765. const uint32_t rhsTranspose = processNonFpMatrixTranspose(rhsType, rhsId);
  6766. const auto vecType = astContext.getExtVectorType(lhsElemType, lhsNumCols);
  6767. const auto vecTypeId = typeTranslator.translateType(vecType);
  6768. llvm::SmallVector<uint32_t, 4> resultRows;
  6769. for (uint32_t row = 0; row < lhsNumRows; ++row) {
  6770. const auto rowId =
  6771. theBuilder.createCompositeExtract(vecTypeId, lhsId, {row});
  6772. resultRows.push_back(processNonFpVectorTimesMatrix(vecType, rowId, rhsType,
  6773. rhsId, rhsTranspose));
  6774. }
  6775. // The resulting matrix will have 'lhsNumRows' rows and 'rhsNumCols' columns.
  6776. const auto elemTypeId = typeTranslator.translateType(lhsElemType);
  6777. const auto resultNumRows = theBuilder.getConstantUint32(lhsNumRows);
  6778. const auto resultColType = theBuilder.getVecType(elemTypeId, rhsNumCols);
  6779. const auto resultType = theBuilder.getArrayType(resultColType, resultNumRows);
  6780. return theBuilder.createCompositeConstruct(resultType, resultRows);
  6781. }
  6782. uint32_t SPIRVEmitter::processIntrinsicMul(const CallExpr *callExpr) {
  6783. const QualType returnType = callExpr->getType();
  6784. const uint32_t returnTypeId =
  6785. typeTranslator.translateType(callExpr->getType());
  6786. // Get the function parameters. Expect 2 parameters.
  6787. assert(callExpr->getNumArgs() == 2u);
  6788. const Expr *arg0 = callExpr->getArg(0);
  6789. const Expr *arg1 = callExpr->getArg(1);
  6790. const QualType arg0Type = arg0->getType();
  6791. const QualType arg1Type = arg1->getType();
  6792. // The HLSL mul() function takes 2 arguments. Each argument may be a scalar,
  6793. // vector, or matrix. The frontend ensures that the two arguments have the
  6794. // same component type. The only allowed component types are int and float.
  6795. // mul(scalar, vector)
  6796. {
  6797. uint32_t elemCount = 0;
  6798. if (TypeTranslator::isScalarType(arg0Type) &&
  6799. TypeTranslator::isVectorType(arg1Type, nullptr, &elemCount)) {
  6800. const uint32_t arg1Id = doExpr(arg1);
  6801. // We can use OpVectorTimesScalar if arguments are floats.
  6802. if (arg0Type->isFloatingType())
  6803. return theBuilder.createBinaryOp(spv::Op::OpVectorTimesScalar,
  6804. returnTypeId, arg1Id, doExpr(arg0));
  6805. // Use OpIMul for integers
  6806. return theBuilder.createBinaryOp(spv::Op::OpIMul, returnTypeId,
  6807. createVectorSplat(arg0, elemCount),
  6808. arg1Id);
  6809. }
  6810. }
  6811. // mul(vector, scalar)
  6812. {
  6813. uint32_t elemCount = 0;
  6814. if (TypeTranslator::isVectorType(arg0Type, nullptr, &elemCount) &&
  6815. TypeTranslator::isScalarType(arg1Type)) {
  6816. const uint32_t arg0Id = doExpr(arg0);
  6817. // We can use OpVectorTimesScalar if arguments are floats.
  6818. if (arg1Type->isFloatingType())
  6819. return theBuilder.createBinaryOp(spv::Op::OpVectorTimesScalar,
  6820. returnTypeId, arg0Id, doExpr(arg1));
  6821. // Use OpIMul for integers
  6822. return theBuilder.createBinaryOp(spv::Op::OpIMul, returnTypeId, arg0Id,
  6823. createVectorSplat(arg1, elemCount));
  6824. }
  6825. }
  6826. // mul(vector, vector)
  6827. if (TypeTranslator::isVectorType(arg0Type) &&
  6828. TypeTranslator::isVectorType(arg1Type))
  6829. return processIntrinsicDot(callExpr);
  6830. // All the following cases require handling arg0 and arg1 expressions first.
  6831. const uint32_t arg0Id = doExpr(arg0);
  6832. const uint32_t arg1Id = doExpr(arg1);
  6833. // mul(scalar, scalar)
  6834. if (TypeTranslator::isScalarType(arg0Type) &&
  6835. TypeTranslator::isScalarType(arg1Type))
  6836. return theBuilder.createBinaryOp(translateOp(BO_Mul, arg0Type),
  6837. returnTypeId, arg0Id, arg1Id);
  6838. // mul(scalar, matrix)
  6839. {
  6840. QualType elemType = {};
  6841. if (TypeTranslator::isScalarType(arg0Type) &&
  6842. TypeTranslator::isMxNMatrix(arg1Type, &elemType)) {
  6843. // OpMatrixTimesScalar can only be used if *both* the matrix element type
  6844. // and the scalar type are float.
  6845. if (arg0Type->isFloatingType() && elemType->isFloatingType())
  6846. return theBuilder.createBinaryOp(spv::Op::OpMatrixTimesScalar,
  6847. returnTypeId, arg1Id, arg0Id);
  6848. else
  6849. return processNonFpScalarTimesMatrix(arg0Type, arg0Id, arg1Type,
  6850. arg1Id);
  6851. }
  6852. }
  6853. // mul(matrix, scalar)
  6854. {
  6855. QualType elemType = {};
  6856. if (TypeTranslator::isScalarType(arg1Type) &&
  6857. TypeTranslator::isMxNMatrix(arg0Type, &elemType)) {
  6858. // OpMatrixTimesScalar can only be used if *both* the matrix element type
  6859. // and the scalar type are float.
  6860. if (arg1Type->isFloatingType() && elemType->isFloatingType())
  6861. return theBuilder.createBinaryOp(spv::Op::OpMatrixTimesScalar,
  6862. returnTypeId, arg0Id, arg1Id);
  6863. else
  6864. return processNonFpScalarTimesMatrix(arg1Type, arg1Id, arg0Type,
  6865. arg0Id);
  6866. }
  6867. }
  6868. // mul(vector, matrix)
  6869. {
  6870. QualType vecElemType = {}, matElemType = {};
  6871. uint32_t elemCount = 0, numRows = 0;
  6872. if (TypeTranslator::isVectorType(arg0Type, &vecElemType, &elemCount) &&
  6873. TypeTranslator::isMxNMatrix(arg1Type, &matElemType, &numRows)) {
  6874. assert(elemCount == numRows);
  6875. if (vecElemType->isFloatingType() && matElemType->isFloatingType())
  6876. return theBuilder.createBinaryOp(spv::Op::OpMatrixTimesVector,
  6877. returnTypeId, arg1Id, arg0Id);
  6878. else
  6879. return processNonFpVectorTimesMatrix(arg0Type, arg0Id, arg1Type,
  6880. arg1Id);
  6881. }
  6882. }
  6883. // mul(matrix, vector)
  6884. {
  6885. QualType vecElemType = {}, matElemType = {};
  6886. uint32_t elemCount = 0, numCols = 0;
  6887. if (TypeTranslator::isMxNMatrix(arg0Type, &matElemType, nullptr,
  6888. &numCols) &&
  6889. TypeTranslator::isVectorType(arg1Type, &vecElemType, &elemCount)) {
  6890. assert(elemCount == numCols);
  6891. if (vecElemType->isFloatingType() && matElemType->isFloatingType())
  6892. return theBuilder.createBinaryOp(spv::Op::OpVectorTimesMatrix,
  6893. returnTypeId, arg1Id, arg0Id);
  6894. else
  6895. return processNonFpMatrixTimesVector(arg0Type, arg0Id, arg1Type,
  6896. arg1Id);
  6897. }
  6898. }
  6899. // mul(matrix, matrix)
  6900. {
  6901. // The front-end ensures that the two matrix element types match.
  6902. QualType elemType = {};
  6903. uint32_t lhsCols = 0, rhsRows = 0;
  6904. if (TypeTranslator::isMxNMatrix(arg0Type, &elemType, nullptr, &lhsCols) &&
  6905. TypeTranslator::isMxNMatrix(arg1Type, nullptr, &rhsRows, nullptr)) {
  6906. assert(lhsCols == rhsRows);
  6907. if (elemType->isFloatingType())
  6908. return theBuilder.createBinaryOp(spv::Op::OpMatrixTimesMatrix,
  6909. returnTypeId, arg1Id, arg0Id);
  6910. else
  6911. return processNonFpMatrixTimesMatrix(arg0Type, arg0Id, arg1Type,
  6912. arg1Id);
  6913. }
  6914. }
  6915. emitError("invalid argument type passed to mul intrinsic function",
  6916. callExpr->getExprLoc());
  6917. return 0;
  6918. }
  6919. uint32_t SPIRVEmitter::processIntrinsicDot(const CallExpr *callExpr) {
  6920. const QualType returnType = callExpr->getType();
  6921. const uint32_t returnTypeId =
  6922. typeTranslator.translateType(callExpr->getType());
  6923. // Get the function parameters. Expect 2 vectors as parameters.
  6924. assert(callExpr->getNumArgs() == 2u);
  6925. const Expr *arg0 = callExpr->getArg(0);
  6926. const Expr *arg1 = callExpr->getArg(1);
  6927. const uint32_t arg0Id = doExpr(arg0);
  6928. const uint32_t arg1Id = doExpr(arg1);
  6929. QualType arg0Type = arg0->getType();
  6930. QualType arg1Type = arg1->getType();
  6931. const size_t vec0Size = hlsl::GetHLSLVecSize(arg0Type);
  6932. const size_t vec1Size = hlsl::GetHLSLVecSize(arg1Type);
  6933. const QualType vec0ComponentType = hlsl::GetHLSLVecElementType(arg0Type);
  6934. const QualType vec1ComponentType = hlsl::GetHLSLVecElementType(arg1Type);
  6935. assert(returnType == vec1ComponentType);
  6936. assert(vec0ComponentType == vec1ComponentType);
  6937. assert(vec0Size == vec1Size);
  6938. assert(vec0Size >= 1 && vec0Size <= 4);
  6939. // According to HLSL reference, the dot function only works on integers
  6940. // and floats.
  6941. assert(returnType->isFloatingType() || returnType->isIntegerType());
  6942. // Special case: dot product of two vectors, each of size 1. That is
  6943. // basically the same as regular multiplication of 2 scalars.
  6944. if (vec0Size == 1) {
  6945. const spv::Op spvOp = translateOp(BO_Mul, arg0Type);
  6946. return theBuilder.createBinaryOp(spvOp, returnTypeId, arg0Id, arg1Id);
  6947. }
  6948. // If the vectors are of type Float, we can use OpDot.
  6949. if (returnType->isFloatingType()) {
  6950. return theBuilder.createBinaryOp(spv::Op::OpDot, returnTypeId, arg0Id,
  6951. arg1Id);
  6952. }
  6953. // Vector component type is Integer (signed or unsigned).
  6954. // Create all instructions necessary to perform a dot product on
  6955. // two integer vectors. SPIR-V OpDot does not support integer vectors.
  6956. // Therefore, we use other SPIR-V instructions (addition and
  6957. // multiplication).
  6958. else {
  6959. uint32_t result = 0;
  6960. llvm::SmallVector<uint32_t, 4> multIds;
  6961. const spv::Op multSpvOp = translateOp(BO_Mul, arg0Type);
  6962. const spv::Op addSpvOp = translateOp(BO_Add, arg0Type);
  6963. // Extract members from the two vectors and multiply them.
  6964. for (unsigned int i = 0; i < vec0Size; ++i) {
  6965. const uint32_t vec0member =
  6966. theBuilder.createCompositeExtract(returnTypeId, arg0Id, {i});
  6967. const uint32_t vec1member =
  6968. theBuilder.createCompositeExtract(returnTypeId, arg1Id, {i});
  6969. const uint32_t multId = theBuilder.createBinaryOp(multSpvOp, returnTypeId,
  6970. vec0member, vec1member);
  6971. multIds.push_back(multId);
  6972. }
  6973. // Add all the multiplications.
  6974. result = multIds[0];
  6975. for (unsigned int i = 1; i < vec0Size; ++i) {
  6976. const uint32_t additionId =
  6977. theBuilder.createBinaryOp(addSpvOp, returnTypeId, result, multIds[i]);
  6978. result = additionId;
  6979. }
  6980. return result;
  6981. }
  6982. }
  6983. uint32_t SPIRVEmitter::processIntrinsicRcp(const CallExpr *callExpr) {
  6984. // 'rcp' takes only 1 argument that is a scalar, vector, or matrix of type
  6985. // float or double.
  6986. assert(callExpr->getNumArgs() == 1u);
  6987. const QualType returnType = callExpr->getType();
  6988. const uint32_t returnTypeId = typeTranslator.translateType(returnType);
  6989. const Expr *arg = callExpr->getArg(0);
  6990. const uint32_t argId = doExpr(arg);
  6991. const QualType argType = arg->getType();
  6992. // For cases with matrix argument.
  6993. QualType elemType = {};
  6994. uint32_t numRows = 0, numCols = 0;
  6995. if (TypeTranslator::isMxNMatrix(argType, &elemType, &numRows, &numCols)) {
  6996. const uint32_t vecOne = getVecValueOne(elemType, numCols);
  6997. const auto actOnEachVec = [this, vecOne](uint32_t /*index*/,
  6998. uint32_t vecType,
  6999. uint32_t curRowId) {
  7000. return theBuilder.createBinaryOp(spv::Op::OpFDiv, vecType, vecOne,
  7001. curRowId);
  7002. };
  7003. return processEachVectorInMatrix(arg, argId, actOnEachVec);
  7004. }
  7005. // For cases with scalar or vector arguments.
  7006. return theBuilder.createBinaryOp(spv::Op::OpFDiv, returnTypeId,
  7007. getValueOne(argType), argId);
  7008. }
  7009. uint32_t SPIRVEmitter::processIntrinsicAllOrAny(const CallExpr *callExpr,
  7010. spv::Op spvOp) {
  7011. // 'all' and 'any' take only 1 parameter.
  7012. assert(callExpr->getNumArgs() == 1u);
  7013. const QualType returnType = callExpr->getType();
  7014. const uint32_t returnTypeId = typeTranslator.translateType(returnType);
  7015. const Expr *arg = callExpr->getArg(0);
  7016. const QualType argType = arg->getType();
  7017. // Handle scalars, vectors of size 1, and 1x1 matrices as arguments.
  7018. // Optimization: can directly cast them to boolean. No need for OpAny/OpAll.
  7019. {
  7020. QualType scalarType = {};
  7021. if (TypeTranslator::isScalarType(argType, &scalarType) &&
  7022. (scalarType->isBooleanType() || scalarType->isFloatingType() ||
  7023. scalarType->isIntegerType()))
  7024. return castToBool(doExpr(arg), argType, returnType);
  7025. }
  7026. // Handle vectors larger than 1, Mx1 matrices, and 1xN matrices as arguments.
  7027. // Cast the vector to a boolean vector, then run OpAny/OpAll on it.
  7028. {
  7029. QualType elemType = {};
  7030. uint32_t size = 0;
  7031. if (TypeTranslator::isVectorType(argType, &elemType, &size)) {
  7032. const QualType castToBoolType =
  7033. astContext.getExtVectorType(returnType, size);
  7034. uint32_t castedToBoolId =
  7035. castToBool(doExpr(arg), argType, castToBoolType);
  7036. return theBuilder.createUnaryOp(spvOp, returnTypeId, castedToBoolId);
  7037. }
  7038. }
  7039. // Handle MxN matrices as arguments.
  7040. {
  7041. QualType elemType = {};
  7042. uint32_t matRowCount = 0, matColCount = 0;
  7043. if (TypeTranslator::isMxNMatrix(argType, &elemType, &matRowCount,
  7044. &matColCount)) {
  7045. uint32_t matrixId = doExpr(arg);
  7046. const uint32_t vecType = typeTranslator.getComponentVectorType(argType);
  7047. llvm::SmallVector<uint32_t, 4> rowResults;
  7048. for (uint32_t i = 0; i < matRowCount; ++i) {
  7049. // Extract the row which is a float vector of size matColCount.
  7050. const uint32_t rowFloatVec =
  7051. theBuilder.createCompositeExtract(vecType, matrixId, {i});
  7052. // Cast the float vector to boolean vector.
  7053. const auto rowFloatQualType =
  7054. astContext.getExtVectorType(elemType, matColCount);
  7055. const auto rowBoolQualType =
  7056. astContext.getExtVectorType(returnType, matColCount);
  7057. const uint32_t rowBoolVec =
  7058. castToBool(rowFloatVec, rowFloatQualType, rowBoolQualType);
  7059. // Perform OpAny/OpAll on the boolean vector.
  7060. rowResults.push_back(
  7061. theBuilder.createUnaryOp(spvOp, returnTypeId, rowBoolVec));
  7062. }
  7063. // Create a new vector that is the concatenation of results of all rows.
  7064. uint32_t boolId = theBuilder.getBoolType();
  7065. uint32_t vecOfBoolsId = theBuilder.getVecType(boolId, matRowCount);
  7066. const uint32_t rowResultsId =
  7067. theBuilder.createCompositeConstruct(vecOfBoolsId, rowResults);
  7068. // Run OpAny/OpAll on the newly-created vector.
  7069. return theBuilder.createUnaryOp(spvOp, returnTypeId, rowResultsId);
  7070. }
  7071. }
  7072. // All types should be handled already.
  7073. llvm_unreachable("Unknown argument type passed to all()/any().");
  7074. return 0;
  7075. }
  7076. uint32_t SPIRVEmitter::processIntrinsicAsType(const CallExpr *callExpr) {
  7077. // This function handles 'asint', 'asuint', 'asfloat', and 'asdouble'.
  7078. // Method 1: ret asint(arg)
  7079. // arg component type = {float, uint}
  7080. // arg template type = {scalar, vector, matrix}
  7081. // ret template type = same as arg template type.
  7082. // ret component type = int
  7083. // Method 2: ret asuint(arg)
  7084. // arg component type = {float, int}
  7085. // arg template type = {scalar, vector, matrix}
  7086. // ret template type = same as arg template type.
  7087. // ret component type = uint
  7088. // Method 3: ret asfloat(arg)
  7089. // arg component type = {float, uint, int}
  7090. // arg template type = {scalar, vector, matrix}
  7091. // ret template type = same as arg template type.
  7092. // ret component type = float
  7093. // Method 4: double asdouble(uint lowbits, uint highbits)
  7094. // Method 5: double2 asdouble(uint2 lowbits, uint2 highbits)
  7095. // Method 6:
  7096. // void asuint(
  7097. // in double value,
  7098. // out uint lowbits,
  7099. // out uint highbits
  7100. // );
  7101. const QualType returnType = callExpr->getType();
  7102. const uint32_t numArgs = callExpr->getNumArgs();
  7103. const uint32_t returnTypeId = typeTranslator.translateType(returnType);
  7104. const Expr *arg0 = callExpr->getArg(0);
  7105. const QualType argType = arg0->getType();
  7106. // Method 3 return type may be the same as arg type, so it would be a no-op.
  7107. if (typeTranslator.isSameType(returnType, argType))
  7108. return doExpr(arg0);
  7109. switch (numArgs) {
  7110. case 1: {
  7111. // Handling Method 1, 2, and 3.
  7112. const auto argId = doExpr(arg0);
  7113. QualType fromElemType = {};
  7114. uint32_t numRows = 0, numCols = 0;
  7115. // For non-matrix arguments (scalar or vector), just do an OpBitCast.
  7116. if (!TypeTranslator::isMxNMatrix(argType, &fromElemType, &numRows,
  7117. &numCols)) {
  7118. return theBuilder.createUnaryOp(spv::Op::OpBitcast, returnTypeId, argId);
  7119. }
  7120. // Input or output type is a matrix.
  7121. const QualType toElemType = hlsl::GetHLSLMatElementType(returnType);
  7122. llvm::SmallVector<uint32_t, 4> castedRows;
  7123. const auto fromVecQualType =
  7124. astContext.getExtVectorType(fromElemType, numCols);
  7125. const auto toVecQualType = astContext.getExtVectorType(toElemType, numCols);
  7126. const auto fromVecTypeId = typeTranslator.translateType(fromVecQualType);
  7127. const auto toVecTypeId = typeTranslator.translateType(toVecQualType);
  7128. for (uint32_t row = 0; row < numRows; ++row) {
  7129. const auto rowId =
  7130. theBuilder.createCompositeExtract(fromVecTypeId, argId, {row});
  7131. castedRows.push_back(
  7132. theBuilder.createUnaryOp(spv::Op::OpBitcast, toVecTypeId, rowId));
  7133. }
  7134. return theBuilder.createCompositeConstruct(returnTypeId, castedRows);
  7135. }
  7136. case 2: {
  7137. const uint32_t lowbits = doExpr(arg0);
  7138. const uint32_t highbits = doExpr(callExpr->getArg(1));
  7139. const uint32_t uintType = theBuilder.getUint32Type();
  7140. const uint32_t doubleType = theBuilder.getFloat64Type();
  7141. // Handling Method 4
  7142. if (argType->isUnsignedIntegerType()) {
  7143. const uint32_t uintVec2Type = theBuilder.getVecType(uintType, 2);
  7144. const uint32_t operand = theBuilder.createCompositeConstruct(
  7145. uintVec2Type, {lowbits, highbits});
  7146. return theBuilder.createUnaryOp(spv::Op::OpBitcast, doubleType, operand);
  7147. }
  7148. // Handling Method 5
  7149. else {
  7150. const uint32_t uintVec4Type = theBuilder.getVecType(uintType, 4);
  7151. const uint32_t doubleVec2Type = theBuilder.getVecType(doubleType, 2);
  7152. const uint32_t operand = theBuilder.createVectorShuffle(
  7153. uintVec4Type, lowbits, highbits, {0, 2, 1, 3});
  7154. return theBuilder.createUnaryOp(spv::Op::OpBitcast, doubleVec2Type,
  7155. operand);
  7156. }
  7157. }
  7158. case 3: {
  7159. // Handling Method 6.
  7160. const uint32_t value = doExpr(arg0);
  7161. const uint32_t lowbits = doExpr(callExpr->getArg(1));
  7162. const uint32_t highbits = doExpr(callExpr->getArg(2));
  7163. const uint32_t uintType = theBuilder.getUint32Type();
  7164. const uint32_t uintVec2Type = theBuilder.getVecType(uintType, 2);
  7165. const uint32_t vecResult =
  7166. theBuilder.createUnaryOp(spv::Op::OpBitcast, uintVec2Type, value);
  7167. theBuilder.createStore(
  7168. lowbits, theBuilder.createCompositeExtract(uintType, vecResult, {0}));
  7169. theBuilder.createStore(
  7170. highbits, theBuilder.createCompositeExtract(uintType, vecResult, {1}));
  7171. return 0;
  7172. }
  7173. default:
  7174. emitError("unrecognized signature for %0 intrinsic function",
  7175. callExpr->getExprLoc())
  7176. << callExpr->getDirectCallee()->getName();
  7177. return 0;
  7178. }
  7179. }
  7180. uint32_t SPIRVEmitter::processD3DCOLORtoUBYTE4(const CallExpr *callExpr) {
  7181. // Should take a float4 and return an int4 by doing:
  7182. // int4 result = input.zyxw * 255.001953;
  7183. // Maximum float precision makes the scaling factor 255.002.
  7184. const auto arg = callExpr->getArg(0);
  7185. const auto argId = doExpr(arg);
  7186. const auto argTypeId = typeTranslator.translateType(arg->getType());
  7187. const auto swizzle =
  7188. theBuilder.createVectorShuffle(argTypeId, argId, argId, {2, 1, 0, 3});
  7189. const auto scaled = theBuilder.createBinaryOp(
  7190. spv::Op::OpVectorTimesScalar, argTypeId, swizzle,
  7191. theBuilder.getConstantFloat32(255.002f));
  7192. return castToInt(scaled, arg->getType(), callExpr->getType(),
  7193. callExpr->getExprLoc());
  7194. }
  7195. uint32_t SPIRVEmitter::processIntrinsicIsFinite(const CallExpr *callExpr) {
  7196. // Since OpIsFinite needs the Kernel capability, translation is instead done
  7197. // using OpIsNan and OpIsInf:
  7198. // isFinite = !(isNan || isInf)
  7199. const auto arg = doExpr(callExpr->getArg(0));
  7200. const auto returnType = typeTranslator.translateType(callExpr->getType());
  7201. const auto isNan =
  7202. theBuilder.createUnaryOp(spv::Op::OpIsNan, returnType, arg);
  7203. const auto isInf =
  7204. theBuilder.createUnaryOp(spv::Op::OpIsInf, returnType, arg);
  7205. const auto isNanOrInf =
  7206. theBuilder.createBinaryOp(spv::Op::OpLogicalOr, returnType, isNan, isInf);
  7207. return theBuilder.createUnaryOp(spv::Op::OpLogicalNot, returnType,
  7208. isNanOrInf);
  7209. }
  7210. uint32_t SPIRVEmitter::processIntrinsicSinCos(const CallExpr *callExpr) {
  7211. // Since there is no sincos equivalent in SPIR-V, we need to perform Sin
  7212. // once and Cos once. We can reuse existing Sine/Cosine handling functions.
  7213. CallExpr *sincosExpr =
  7214. new (astContext) CallExpr(astContext, Stmt::StmtClass::NoStmtClass, {});
  7215. sincosExpr->setType(callExpr->getArg(0)->getType());
  7216. sincosExpr->setNumArgs(astContext, 1);
  7217. sincosExpr->setArg(0, const_cast<Expr *>(callExpr->getArg(0)));
  7218. // Perform Sin and store results in argument 1.
  7219. const uint32_t sin =
  7220. processIntrinsicUsingGLSLInst(sincosExpr, GLSLstd450::GLSLstd450Sin,
  7221. /*actPerRowForMatrices*/ true);
  7222. theBuilder.createStore(doExpr(callExpr->getArg(1)), sin);
  7223. // Perform Cos and store results in argument 2.
  7224. const uint32_t cos =
  7225. processIntrinsicUsingGLSLInst(sincosExpr, GLSLstd450::GLSLstd450Cos,
  7226. /*actPerRowForMatrices*/ true);
  7227. theBuilder.createStore(doExpr(callExpr->getArg(2)), cos);
  7228. return 0;
  7229. }
  7230. uint32_t SPIRVEmitter::processIntrinsicSaturate(const CallExpr *callExpr) {
  7231. const auto *arg = callExpr->getArg(0);
  7232. const auto argId = doExpr(arg);
  7233. const auto argType = arg->getType();
  7234. const uint32_t returnType = typeTranslator.translateType(callExpr->getType());
  7235. const uint32_t glslInstSetId = theBuilder.getGLSLExtInstSet();
  7236. if (argType->isFloatingType()) {
  7237. const uint32_t floatZero = getValueZero(argType);
  7238. const uint32_t floatOne = getValueOne(argType);
  7239. return theBuilder.createExtInst(returnType, glslInstSetId,
  7240. GLSLstd450::GLSLstd450FClamp,
  7241. {argId, floatZero, floatOne});
  7242. }
  7243. QualType elemType = {};
  7244. uint32_t vecSize = 0;
  7245. if (TypeTranslator::isVectorType(argType, &elemType, &vecSize)) {
  7246. const uint32_t vecZero = getVecValueZero(elemType, vecSize);
  7247. const uint32_t vecOne = getVecValueOne(elemType, vecSize);
  7248. return theBuilder.createExtInst(returnType, glslInstSetId,
  7249. GLSLstd450::GLSLstd450FClamp,
  7250. {argId, vecZero, vecOne});
  7251. }
  7252. uint32_t numRows = 0, numCols = 0;
  7253. if (TypeTranslator::isMxNMatrix(argType, &elemType, &numRows, &numCols)) {
  7254. const uint32_t vecZero = getVecValueZero(elemType, numCols);
  7255. const uint32_t vecOne = getVecValueOne(elemType, numCols);
  7256. const auto actOnEachVec = [this, vecZero, vecOne, glslInstSetId](
  7257. uint32_t /*index*/, uint32_t vecType,
  7258. uint32_t curRowId) {
  7259. return theBuilder.createExtInst(vecType, glslInstSetId,
  7260. GLSLstd450::GLSLstd450FClamp,
  7261. {curRowId, vecZero, vecOne});
  7262. };
  7263. return processEachVectorInMatrix(arg, argId, actOnEachVec);
  7264. }
  7265. emitError("invalid argument type passed to saturate intrinsic function",
  7266. callExpr->getExprLoc());
  7267. return 0;
  7268. }
  7269. uint32_t SPIRVEmitter::processIntrinsicFloatSign(const CallExpr *callExpr) {
  7270. // Import the GLSL.std.450 extended instruction set.
  7271. const uint32_t glslInstSetId = theBuilder.getGLSLExtInstSet();
  7272. const Expr *arg = callExpr->getArg(0);
  7273. const QualType returnType = callExpr->getType();
  7274. const QualType argType = arg->getType();
  7275. assert(isFloatOrVecMatOfFloatType(argType));
  7276. const uint32_t argTypeId = typeTranslator.translateType(argType);
  7277. const uint32_t argId = doExpr(arg);
  7278. uint32_t floatSignResultId = 0;
  7279. // For matrices, we can perform the instruction on each vector of the matrix.
  7280. if (TypeTranslator::isMxNMatrix(argType)) {
  7281. const auto actOnEachVec = [this, glslInstSetId](uint32_t /*index*/,
  7282. uint32_t vecType,
  7283. uint32_t curRowId) {
  7284. return theBuilder.createExtInst(vecType, glslInstSetId,
  7285. GLSLstd450::GLSLstd450FSign, {curRowId});
  7286. };
  7287. floatSignResultId = processEachVectorInMatrix(arg, argId, actOnEachVec);
  7288. } else {
  7289. floatSignResultId = theBuilder.createExtInst(
  7290. argTypeId, glslInstSetId, GLSLstd450::GLSLstd450FSign, {argId});
  7291. }
  7292. return castToInt(floatSignResultId, arg->getType(), returnType,
  7293. arg->getExprLoc());
  7294. }
  7295. uint32_t SPIRVEmitter::processIntrinsicF16ToF32(const CallExpr *callExpr) {
  7296. // f16tof32() takes in (vector of) uint and returns (vector of) float.
  7297. // The frontend should guarantee that by inserting implicit casts.
  7298. const uint32_t glsl = theBuilder.getGLSLExtInstSet();
  7299. const uint32_t f32TypeId = theBuilder.getFloat32Type();
  7300. const uint32_t u32TypeId = theBuilder.getUint32Type();
  7301. const uint32_t v2f32TypeId = theBuilder.getVecType(f32TypeId, 2);
  7302. const auto *arg = callExpr->getArg(0);
  7303. const uint32_t argId = doExpr(arg);
  7304. uint32_t elemCount = {};
  7305. if (TypeTranslator::isVectorType(arg->getType(), nullptr, &elemCount)) {
  7306. // The input is a vector. We need to handle each element separately.
  7307. llvm::SmallVector<uint32_t, 4> elements;
  7308. for (uint32_t i = 0; i < elemCount; ++i) {
  7309. const uint32_t srcElem =
  7310. theBuilder.createCompositeExtract(u32TypeId, argId, {i});
  7311. const uint32_t convert = theBuilder.createExtInst(
  7312. v2f32TypeId, glsl, GLSLstd450::GLSLstd450UnpackHalf2x16, srcElem);
  7313. elements.push_back(
  7314. theBuilder.createCompositeExtract(f32TypeId, convert, {0}));
  7315. }
  7316. return theBuilder.createCompositeConstruct(
  7317. theBuilder.getVecType(f32TypeId, elemCount), elements);
  7318. }
  7319. const uint32_t convert = theBuilder.createExtInst(
  7320. v2f32TypeId, glsl, GLSLstd450::GLSLstd450UnpackHalf2x16, argId);
  7321. // f16tof32() converts the float16 stored in the low-half of the uint to
  7322. // a float. So just need to return the first component.
  7323. return theBuilder.createCompositeExtract(f32TypeId, convert, {0});
  7324. }
  7325. uint32_t SPIRVEmitter::processIntrinsicF32ToF16(const CallExpr *callExpr) {
  7326. // f32tof16() takes in (vector of) float and returns (vector of) uint.
  7327. // The frontend should guarantee that by inserting implicit casts.
  7328. const uint32_t glsl = theBuilder.getGLSLExtInstSet();
  7329. const uint32_t f32TypeId = theBuilder.getFloat32Type();
  7330. const uint32_t u32TypeId = theBuilder.getUint32Type();
  7331. const uint32_t v2f32TypeId = theBuilder.getVecType(f32TypeId, 2);
  7332. const uint32_t zero = theBuilder.getConstantFloat32(0);
  7333. const auto *arg = callExpr->getArg(0);
  7334. const uint32_t argId = doExpr(arg);
  7335. uint32_t elemCount = {};
  7336. if (TypeTranslator::isVectorType(arg->getType(), nullptr, &elemCount)) {
  7337. // The input is a vector. We need to handle each element separately.
  7338. llvm::SmallVector<uint32_t, 4> elements;
  7339. for (uint32_t i = 0; i < elemCount; ++i) {
  7340. const uint32_t srcElem =
  7341. theBuilder.createCompositeExtract(f32TypeId, argId, {i});
  7342. const uint32_t srcVec =
  7343. theBuilder.createCompositeConstruct(v2f32TypeId, {srcElem, zero});
  7344. elements.push_back(theBuilder.createExtInst(
  7345. u32TypeId, glsl, GLSLstd450::GLSLstd450PackHalf2x16, srcVec));
  7346. }
  7347. return theBuilder.createCompositeConstruct(
  7348. theBuilder.getVecType(u32TypeId, elemCount), elements);
  7349. }
  7350. // f16tof32() stores the float into the low-half of the uint. So we need
  7351. // to supply another zero to take the other half.
  7352. const uint32_t srcVec =
  7353. theBuilder.createCompositeConstruct(v2f32TypeId, {argId, zero});
  7354. return theBuilder.createExtInst(u32TypeId, glsl,
  7355. GLSLstd450::GLSLstd450PackHalf2x16, srcVec);
  7356. }
  7357. uint32_t SPIRVEmitter::processIntrinsicUsingSpirvInst(
  7358. const CallExpr *callExpr, spv::Op opcode, bool actPerRowForMatrices) {
  7359. // Certain opcodes are only allowed in pixel shader
  7360. if (!shaderModel.IsPS())
  7361. switch (opcode) {
  7362. case spv::Op::OpDPdx:
  7363. case spv::Op::OpDPdy:
  7364. case spv::Op::OpDPdxFine:
  7365. case spv::Op::OpDPdyFine:
  7366. case spv::Op::OpDPdxCoarse:
  7367. case spv::Op::OpDPdyCoarse:
  7368. case spv::Op::OpFwidth:
  7369. case spv::Op::OpFwidthFine:
  7370. case spv::Op::OpFwidthCoarse:
  7371. needsLegalization = true;
  7372. }
  7373. const uint32_t returnType = typeTranslator.translateType(callExpr->getType());
  7374. if (callExpr->getNumArgs() == 1u) {
  7375. const Expr *arg = callExpr->getArg(0);
  7376. const uint32_t argId = doExpr(arg);
  7377. // If the instruction does not operate on matrices, we can perform the
  7378. // instruction on each vector of the matrix.
  7379. if (actPerRowForMatrices && TypeTranslator::isMxNMatrix(arg->getType())) {
  7380. const auto actOnEachVec = [this, opcode](uint32_t /*index*/,
  7381. uint32_t vecType,
  7382. uint32_t curRowId) {
  7383. return theBuilder.createUnaryOp(opcode, vecType, {curRowId});
  7384. };
  7385. return processEachVectorInMatrix(arg, argId, actOnEachVec);
  7386. }
  7387. return theBuilder.createUnaryOp(opcode, returnType, {argId});
  7388. } else if (callExpr->getNumArgs() == 2u) {
  7389. const Expr *arg0 = callExpr->getArg(0);
  7390. const uint32_t arg0Id = doExpr(arg0);
  7391. const uint32_t arg1Id = doExpr(callExpr->getArg(1));
  7392. // If the instruction does not operate on matrices, we can perform the
  7393. // instruction on each vector of the matrix.
  7394. if (actPerRowForMatrices && TypeTranslator::isMxNMatrix(arg0->getType())) {
  7395. const auto actOnEachVec = [this, opcode, arg1Id](uint32_t index,
  7396. uint32_t vecType,
  7397. uint32_t arg0RowId) {
  7398. const uint32_t arg1RowId =
  7399. theBuilder.createCompositeExtract(vecType, arg1Id, {index});
  7400. return theBuilder.createBinaryOp(opcode, vecType, arg0RowId, arg1RowId);
  7401. };
  7402. return processEachVectorInMatrix(arg0, arg0Id, actOnEachVec);
  7403. }
  7404. return theBuilder.createBinaryOp(opcode, returnType, arg0Id, arg1Id);
  7405. }
  7406. emitError("unsupported %0 intrinsic function", callExpr->getExprLoc())
  7407. << cast<DeclRefExpr>(callExpr->getCallee())->getNameInfo().getAsString();
  7408. return 0;
  7409. }
  7410. uint32_t SPIRVEmitter::processIntrinsicUsingGLSLInst(
  7411. const CallExpr *callExpr, GLSLstd450 opcode, bool actPerRowForMatrices) {
  7412. // Import the GLSL.std.450 extended instruction set.
  7413. const uint32_t glslInstSetId = theBuilder.getGLSLExtInstSet();
  7414. const uint32_t returnType = typeTranslator.translateType(callExpr->getType());
  7415. if (callExpr->getNumArgs() == 1u) {
  7416. const Expr *arg = callExpr->getArg(0);
  7417. const uint32_t argId = doExpr(arg);
  7418. // If the instruction does not operate on matrices, we can perform the
  7419. // instruction on each vector of the matrix.
  7420. if (actPerRowForMatrices && TypeTranslator::isMxNMatrix(arg->getType())) {
  7421. const auto actOnEachVec = [this, glslInstSetId,
  7422. opcode](uint32_t /*index*/, uint32_t vecType,
  7423. uint32_t curRowId) {
  7424. return theBuilder.createExtInst(vecType, glslInstSetId, opcode,
  7425. {curRowId});
  7426. };
  7427. return processEachVectorInMatrix(arg, argId, actOnEachVec);
  7428. }
  7429. return theBuilder.createExtInst(returnType, glslInstSetId, opcode, {argId});
  7430. } else if (callExpr->getNumArgs() == 2u) {
  7431. const Expr *arg0 = callExpr->getArg(0);
  7432. const uint32_t arg0Id = doExpr(arg0);
  7433. const uint32_t arg1Id = doExpr(callExpr->getArg(1));
  7434. // If the instruction does not operate on matrices, we can perform the
  7435. // instruction on each vector of the matrix.
  7436. if (actPerRowForMatrices && TypeTranslator::isMxNMatrix(arg0->getType())) {
  7437. const auto actOnEachVec = [this, glslInstSetId, opcode,
  7438. arg1Id](uint32_t index, uint32_t vecType,
  7439. uint32_t arg0RowId) {
  7440. const uint32_t arg1RowId =
  7441. theBuilder.createCompositeExtract(vecType, arg1Id, {index});
  7442. return theBuilder.createExtInst(vecType, glslInstSetId, opcode,
  7443. {arg0RowId, arg1RowId});
  7444. };
  7445. return processEachVectorInMatrix(arg0, arg0Id, actOnEachVec);
  7446. }
  7447. return theBuilder.createExtInst(returnType, glslInstSetId, opcode,
  7448. {arg0Id, arg1Id});
  7449. } else if (callExpr->getNumArgs() == 3u) {
  7450. const Expr *arg0 = callExpr->getArg(0);
  7451. const uint32_t arg0Id = doExpr(arg0);
  7452. const uint32_t arg1Id = doExpr(callExpr->getArg(1));
  7453. const uint32_t arg2Id = doExpr(callExpr->getArg(2));
  7454. // If the instruction does not operate on matrices, we can perform the
  7455. // instruction on each vector of the matrix.
  7456. if (actPerRowForMatrices && TypeTranslator::isMxNMatrix(arg0->getType())) {
  7457. const auto actOnEachVec = [this, glslInstSetId, opcode, arg0Id, arg1Id,
  7458. arg2Id](uint32_t index, uint32_t vecType,
  7459. uint32_t arg0RowId) {
  7460. const uint32_t arg1RowId =
  7461. theBuilder.createCompositeExtract(vecType, arg1Id, {index});
  7462. const uint32_t arg2RowId =
  7463. theBuilder.createCompositeExtract(vecType, arg2Id, {index});
  7464. return theBuilder.createExtInst(vecType, glslInstSetId, opcode,
  7465. {arg0RowId, arg1RowId, arg2RowId});
  7466. };
  7467. return processEachVectorInMatrix(arg0, arg0Id, actOnEachVec);
  7468. }
  7469. return theBuilder.createExtInst(returnType, glslInstSetId, opcode,
  7470. {arg0Id, arg1Id, arg2Id});
  7471. }
  7472. emitError("unsupported %0 intrinsic function", callExpr->getExprLoc())
  7473. << cast<DeclRefExpr>(callExpr->getCallee())->getNameInfo().getAsString();
  7474. return 0;
  7475. }
  7476. uint32_t SPIRVEmitter::processIntrinsicLog10(const CallExpr *callExpr) {
  7477. // Since there is no log10 instruction in SPIR-V, we can use:
  7478. // log10(x) = log2(x) * ( 1 / log2(10) )
  7479. // 1 / log2(10) = 0.30103
  7480. const auto scale = theBuilder.getConstantFloat32(0.30103f);
  7481. const auto log2 =
  7482. processIntrinsicUsingGLSLInst(callExpr, GLSLstd450::GLSLstd450Log2, true);
  7483. const auto returnType = callExpr->getType();
  7484. const auto returnTypeId = typeTranslator.translateType(returnType);
  7485. spv::Op scaleOp = TypeTranslator::isScalarType(returnType)
  7486. ? spv::Op::OpFMul
  7487. : TypeTranslator::isVectorType(returnType)
  7488. ? spv::Op::OpVectorTimesScalar
  7489. : spv::Op::OpMatrixTimesScalar;
  7490. return theBuilder.createBinaryOp(scaleOp, returnTypeId, log2, scale);
  7491. }
  7492. uint32_t SPIRVEmitter::getValueZero(QualType type) {
  7493. {
  7494. QualType scalarType = {};
  7495. if (TypeTranslator::isScalarType(type, &scalarType)) {
  7496. if (scalarType->isSignedIntegerType()) {
  7497. return theBuilder.getConstantInt32(0);
  7498. }
  7499. if (scalarType->isUnsignedIntegerType()) {
  7500. return theBuilder.getConstantUint32(0);
  7501. }
  7502. if (scalarType->isFloatingType()) {
  7503. return theBuilder.getConstantFloat32(0.0);
  7504. }
  7505. }
  7506. }
  7507. {
  7508. QualType elemType = {};
  7509. uint32_t size = {};
  7510. if (TypeTranslator::isVectorType(type, &elemType, &size)) {
  7511. return getVecValueZero(elemType, size);
  7512. }
  7513. }
  7514. {
  7515. QualType elemType = {};
  7516. uint32_t rowCount = 0, colCount = 0;
  7517. if (TypeTranslator::isMxNMatrix(type, &elemType, &rowCount, &colCount)) {
  7518. const auto row = getVecValueZero(elemType, colCount);
  7519. llvm::SmallVector<uint32_t, 4> rows((size_t)rowCount, row);
  7520. return theBuilder.createCompositeConstruct(
  7521. typeTranslator.translateType(type), rows);
  7522. }
  7523. }
  7524. emitError("getting value 0 for type %0 unimplemented", {})
  7525. << type.getAsString();
  7526. return 0;
  7527. }
  7528. uint32_t SPIRVEmitter::getVecValueZero(QualType elemType, uint32_t size) {
  7529. const uint32_t elemZeroId = getValueZero(elemType);
  7530. if (size == 1)
  7531. return elemZeroId;
  7532. llvm::SmallVector<uint32_t, 4> elements(size_t(size), elemZeroId);
  7533. const uint32_t vecType =
  7534. theBuilder.getVecType(typeTranslator.translateType(elemType), size);
  7535. return theBuilder.getConstantComposite(vecType, elements);
  7536. }
  7537. uint32_t SPIRVEmitter::getValueOne(QualType type) {
  7538. {
  7539. QualType scalarType = {};
  7540. if (TypeTranslator::isScalarType(type, &scalarType)) {
  7541. // TODO: Support other types such as short, half, etc.
  7542. if (scalarType->isSignedIntegerType()) {
  7543. return theBuilder.getConstantInt32(1);
  7544. }
  7545. if (scalarType->isUnsignedIntegerType()) {
  7546. return theBuilder.getConstantUint32(1);
  7547. }
  7548. if (scalarType->isSpecificBuiltinType(BuiltinType::LitFloat))
  7549. scalarType = typeTranslator.getIntendedLiteralType(scalarType);
  7550. if (const auto *builtinType = scalarType->getAs<BuiltinType>()) {
  7551. // TODO: Add support for other types that are not covered yet.
  7552. switch (builtinType->getKind()) {
  7553. case BuiltinType::Double:
  7554. return theBuilder.getConstantFloat64(1.0);
  7555. case BuiltinType::Float:
  7556. return theBuilder.getConstantFloat32(1.0);
  7557. }
  7558. }
  7559. }
  7560. }
  7561. {
  7562. QualType elemType = {};
  7563. uint32_t size = {};
  7564. if (TypeTranslator::isVectorType(type, &elemType, &size)) {
  7565. return getVecValueOne(elemType, size);
  7566. }
  7567. }
  7568. emitError("getting value 1 for type %0 unimplemented", {}) << type;
  7569. return 0;
  7570. }
  7571. uint32_t SPIRVEmitter::getVecValueOne(QualType elemType, uint32_t size) {
  7572. const uint32_t elemOneId = getValueOne(elemType);
  7573. if (size == 1)
  7574. return elemOneId;
  7575. llvm::SmallVector<uint32_t, 4> elements(size_t(size), elemOneId);
  7576. const uint32_t vecType =
  7577. theBuilder.getVecType(typeTranslator.translateType(elemType), size);
  7578. return theBuilder.getConstantComposite(vecType, elements);
  7579. }
  7580. uint32_t SPIRVEmitter::getMatElemValueOne(QualType type) {
  7581. assert(hlsl::IsHLSLMatType(type));
  7582. const auto elemType = hlsl::GetHLSLMatElementType(type);
  7583. uint32_t rowCount = 0, colCount = 0;
  7584. hlsl::GetHLSLMatRowColCount(type, rowCount, colCount);
  7585. if (rowCount == 1 && colCount == 1)
  7586. return getValueOne(elemType);
  7587. if (colCount == 1)
  7588. return getVecValueOne(elemType, rowCount);
  7589. return getVecValueOne(elemType, colCount);
  7590. }
  7591. uint32_t SPIRVEmitter::getMaskForBitwidthValue(QualType type) {
  7592. QualType elemType = {};
  7593. uint32_t count = 1;
  7594. if (TypeTranslator::isScalarType(type, &elemType) ||
  7595. TypeTranslator::isVectorType(type, &elemType, &count)) {
  7596. const auto bitwidth = typeTranslator.getElementSpirvBitwidth(elemType);
  7597. uint32_t mask = 0;
  7598. uint32_t elemTypeId = 0;
  7599. switch (bitwidth) {
  7600. case 16:
  7601. mask = theBuilder.getConstantUint16(bitwidth - 1);
  7602. elemTypeId = theBuilder.getUint16Type();
  7603. break;
  7604. case 32:
  7605. mask = theBuilder.getConstantUint32(bitwidth - 1);
  7606. elemTypeId = theBuilder.getUint32Type();
  7607. break;
  7608. case 64:
  7609. mask = theBuilder.getConstantUint64(bitwidth - 1);
  7610. elemTypeId = theBuilder.getUint64Type();
  7611. break;
  7612. default:
  7613. assert(false && "this method only supports 16-, 32-, and 64-bit types");
  7614. }
  7615. if (count == 1)
  7616. return mask;
  7617. const uint32_t typeId = theBuilder.getVecType(elemTypeId, count);
  7618. llvm::SmallVector<uint32_t, 4> elements(size_t(count), mask);
  7619. return theBuilder.getConstantComposite(typeId, elements);
  7620. }
  7621. assert(false && "this method only supports scalars and vectors");
  7622. return 0;
  7623. }
  7624. uint32_t SPIRVEmitter::translateAPValue(const APValue &value,
  7625. const QualType targetType) {
  7626. uint32_t result = 0;
  7627. // Provide a hint to the typeTranslator that if a literal is discovered, its
  7628. // intended usage is targetType.
  7629. TypeTranslator::LiteralTypeHint hint(typeTranslator, targetType);
  7630. if (targetType->isBooleanType()) {
  7631. result = theBuilder.getConstantBool(value.getInt().getBoolValue(),
  7632. isSpecConstantMode);
  7633. } else if (targetType->isIntegerType()) {
  7634. result = translateAPInt(value.getInt(), targetType);
  7635. } else if (targetType->isFloatingType()) {
  7636. result = translateAPFloat(value.getFloat(), targetType);
  7637. } else if (hlsl::IsHLSLVecType(targetType)) {
  7638. const uint32_t vecType = typeTranslator.translateType(targetType);
  7639. const QualType elemType = hlsl::GetHLSLVecElementType(targetType);
  7640. const auto numElements = value.getVectorLength();
  7641. // Special case for vectors of size 1. SPIR-V doesn't support this vector
  7642. // size so we need to translate it to scalar values.
  7643. if (numElements == 1) {
  7644. result = translateAPValue(value.getVectorElt(0), elemType);
  7645. } else {
  7646. llvm::SmallVector<uint32_t, 4> elements;
  7647. for (uint32_t i = 0; i < numElements; ++i) {
  7648. elements.push_back(translateAPValue(value.getVectorElt(i), elemType));
  7649. }
  7650. result = theBuilder.getConstantComposite(vecType, elements);
  7651. }
  7652. }
  7653. if (result)
  7654. return result;
  7655. emitError("APValue of type %0 unimplemented", {}) << value.getKind();
  7656. value.dump();
  7657. return 0;
  7658. }
  7659. uint32_t SPIRVEmitter::translateAPInt(const llvm::APInt &intValue,
  7660. QualType targetType) {
  7661. targetType = typeTranslator.getIntendedLiteralType(targetType);
  7662. const auto targetTypeBitWidth = astContext.getTypeSize(targetType);
  7663. const bool isSigned = targetType->isSignedIntegerType();
  7664. switch (targetTypeBitWidth) {
  7665. case 16: {
  7666. if (spirvOptions.enable16BitTypes) {
  7667. if (isSigned) {
  7668. return theBuilder.getConstantInt16(
  7669. static_cast<int16_t>(intValue.getSExtValue()));
  7670. } else {
  7671. return theBuilder.getConstantUint16(
  7672. static_cast<uint16_t>(intValue.getZExtValue()));
  7673. }
  7674. } else {
  7675. // If enable16BitTypes option is not true, treat as 32-bit integer.
  7676. if (isSigned)
  7677. return theBuilder.getConstantInt32(
  7678. static_cast<int32_t>(intValue.getSExtValue()), isSpecConstantMode);
  7679. else
  7680. return theBuilder.getConstantUint32(
  7681. static_cast<uint32_t>(intValue.getZExtValue()), isSpecConstantMode);
  7682. }
  7683. }
  7684. case 32: {
  7685. if (isSigned) {
  7686. if (!intValue.isSignedIntN(32)) {
  7687. emitError("evaluating integer literal %0 as a 32-bit integer loses "
  7688. "inforamtion",
  7689. {})
  7690. << std::to_string(intValue.getSExtValue());
  7691. return 0;
  7692. }
  7693. return theBuilder.getConstantInt32(
  7694. static_cast<int32_t>(intValue.getSExtValue()), isSpecConstantMode);
  7695. } else {
  7696. if (!intValue.isIntN(32)) {
  7697. emitError("evaluating integer literal %0 as a 32-bit integer loses "
  7698. "inforamtion",
  7699. {})
  7700. << std::to_string(intValue.getZExtValue());
  7701. return 0;
  7702. }
  7703. return theBuilder.getConstantUint32(
  7704. static_cast<uint32_t>(intValue.getZExtValue()), isSpecConstantMode);
  7705. }
  7706. }
  7707. case 64: {
  7708. if (isSigned)
  7709. return theBuilder.getConstantInt64(intValue.getSExtValue());
  7710. else
  7711. return theBuilder.getConstantUint64(intValue.getZExtValue());
  7712. }
  7713. }
  7714. emitError("APInt for target bitwidth %0 unimplemented", {})
  7715. << astContext.getIntWidth(targetType);
  7716. return 0;
  7717. }
  7718. bool SPIRVEmitter::isLiteralLargerThan32Bits(const Expr *expr) {
  7719. if (const auto *intLiteral = dyn_cast<IntegerLiteral>(expr)) {
  7720. const bool isSigned = expr->getType()->isSignedIntegerType();
  7721. const llvm::APInt &value = intLiteral->getValue();
  7722. return (isSigned && !value.isSignedIntN(32)) ||
  7723. (!isSigned && !value.isIntN(32));
  7724. }
  7725. if (const auto *floatLiteral = dyn_cast<FloatingLiteral>(expr)) {
  7726. llvm::APFloat value = floatLiteral->getValue();
  7727. const auto &semantics = value.getSemantics();
  7728. // regular 'half' and 'float' can be represented in 32 bits.
  7729. if (&semantics == &llvm::APFloat::IEEEsingle ||
  7730. &semantics == &llvm::APFloat::IEEEhalf)
  7731. return true;
  7732. // See if 'double' value can be represented in 32 bits without losing info.
  7733. bool losesInfo = false;
  7734. const auto convertStatus =
  7735. value.convert(llvm::APFloat::IEEEsingle,
  7736. llvm::APFloat::rmNearestTiesToEven, &losesInfo);
  7737. if (convertStatus != llvm::APFloat::opOK &&
  7738. convertStatus != llvm::APFloat::opInexact)
  7739. return true;
  7740. }
  7741. return false;
  7742. }
  7743. uint32_t SPIRVEmitter::tryToEvaluateAsInt32(const llvm::APInt &intValue,
  7744. bool isSigned) {
  7745. if (isSigned && intValue.isSignedIntN(32)) {
  7746. return theBuilder.getConstantInt32(
  7747. static_cast<int32_t>(intValue.getSExtValue()));
  7748. }
  7749. if (!isSigned && intValue.isIntN(32)) {
  7750. return theBuilder.getConstantUint32(
  7751. static_cast<uint32_t>(intValue.getZExtValue()));
  7752. }
  7753. // Couldn't evaluate as a 32-bit int without losing information.
  7754. return 0;
  7755. }
  7756. uint32_t SPIRVEmitter::tryToEvaluateAsFloat32(const llvm::APFloat &floatValue) {
  7757. const auto &semantics = floatValue.getSemantics();
  7758. // If the given value is already a 32-bit float, there is no need to convert.
  7759. if (&semantics == &llvm::APFloat::IEEEsingle) {
  7760. return theBuilder.getConstantFloat32(floatValue.convertToFloat(),
  7761. isSpecConstantMode);
  7762. }
  7763. // Try to see if this literal float can be represented in 32-bit.
  7764. // Since the convert function below may modify the fp value, we call it on a
  7765. // temporary copy.
  7766. llvm::APFloat eval = floatValue;
  7767. bool losesInfo = false;
  7768. const auto convertStatus =
  7769. eval.convert(llvm::APFloat::IEEEsingle,
  7770. llvm::APFloat::rmNearestTiesToEven, &losesInfo);
  7771. if (convertStatus == llvm::APFloat::opOK && !losesInfo)
  7772. return theBuilder.getConstantFloat32(eval.convertToFloat());
  7773. // Couldn't evaluate as a 32-bit float without losing information.
  7774. return 0;
  7775. }
  7776. uint32_t SPIRVEmitter::translateAPFloat(llvm::APFloat floatValue,
  7777. QualType targetType) {
  7778. using llvm::APFloat;
  7779. const auto originalValue = floatValue;
  7780. const auto valueBitwidth = APFloat::getSizeInBits(floatValue.getSemantics());
  7781. // Find out the target bitwidth.
  7782. targetType = typeTranslator.getIntendedLiteralType(targetType);
  7783. auto targetBitwidth =
  7784. APFloat::getSizeInBits(astContext.getFloatTypeSemantics(targetType));
  7785. // If 16-bit types are not enabled, treat them as 32-bit float.
  7786. if (targetBitwidth == 16 && !spirvOptions.enable16BitTypes)
  7787. targetBitwidth = 32;
  7788. if (targetBitwidth != valueBitwidth) {
  7789. bool losesInfo = false;
  7790. const llvm::fltSemantics &targetSemantics =
  7791. targetBitwidth == 16
  7792. ? APFloat::IEEEhalf
  7793. : targetBitwidth == 32 ? APFloat::IEEEsingle : APFloat::IEEEdouble;
  7794. const auto status = floatValue.convert(
  7795. targetSemantics, APFloat::roundingMode::rmTowardZero, &losesInfo);
  7796. if (status != APFloat::opStatus::opOK &&
  7797. status != APFloat::opStatus::opInexact) {
  7798. emitError(
  7799. "evaluating float literal %0 at a lower bitwidth loses information",
  7800. {})
  7801. // Converting from 16bit to 32/64-bit won't lose information.
  7802. // So only 32/64-bit values can reach here.
  7803. << std::to_string(valueBitwidth == 32
  7804. ? originalValue.convertToFloat()
  7805. : originalValue.convertToDouble());
  7806. return 0;
  7807. }
  7808. }
  7809. switch (targetBitwidth) {
  7810. case 16:
  7811. return theBuilder.getConstantFloat16(
  7812. static_cast<uint16_t>(floatValue.bitcastToAPInt().getZExtValue()));
  7813. case 32:
  7814. return theBuilder.getConstantFloat32(floatValue.convertToFloat(),
  7815. isSpecConstantMode);
  7816. case 64:
  7817. return theBuilder.getConstantFloat64(floatValue.convertToDouble());
  7818. default:
  7819. break;
  7820. }
  7821. emitError("APFloat for target bitwidth %0 unimplemented", {})
  7822. << targetBitwidth;
  7823. return 0;
  7824. }
  7825. uint32_t SPIRVEmitter::tryToEvaluateAsConst(const Expr *expr) {
  7826. Expr::EvalResult evalResult;
  7827. if (expr->EvaluateAsRValue(evalResult, astContext) &&
  7828. !evalResult.HasSideEffects) {
  7829. return translateAPValue(evalResult.Val, expr->getType());
  7830. }
  7831. return 0;
  7832. }
  7833. spv::ExecutionModel
  7834. SPIRVEmitter::getSpirvShaderStage(const hlsl::ShaderModel &model) {
  7835. // DXIL Models are:
  7836. // Profile (DXIL Model) : HLSL Shader Kind : SPIR-V Shader Stage
  7837. // vs_<version> : Vertex Shader : Vertex Shader
  7838. // hs_<version> : Hull Shader : Tassellation Control Shader
  7839. // ds_<version> : Domain Shader : Tessellation Evaluation Shader
  7840. // gs_<version> : Geometry Shader : Geometry Shader
  7841. // ps_<version> : Pixel Shader : Fragment Shader
  7842. // cs_<version> : Compute Shader : Compute Shader
  7843. switch (model.GetKind()) {
  7844. case hlsl::ShaderModel::Kind::Vertex:
  7845. return spv::ExecutionModel::Vertex;
  7846. case hlsl::ShaderModel::Kind::Hull:
  7847. return spv::ExecutionModel::TessellationControl;
  7848. case hlsl::ShaderModel::Kind::Domain:
  7849. return spv::ExecutionModel::TessellationEvaluation;
  7850. case hlsl::ShaderModel::Kind::Geometry:
  7851. return spv::ExecutionModel::Geometry;
  7852. case hlsl::ShaderModel::Kind::Pixel:
  7853. return spv::ExecutionModel::Fragment;
  7854. case hlsl::ShaderModel::Kind::Compute:
  7855. return spv::ExecutionModel::GLCompute;
  7856. default:
  7857. break;
  7858. }
  7859. llvm_unreachable("unknown shader model");
  7860. }
  7861. void SPIRVEmitter::AddRequiredCapabilitiesForShaderModel() {
  7862. if (shaderModel.IsHS() || shaderModel.IsDS()) {
  7863. theBuilder.requireCapability(spv::Capability::Tessellation);
  7864. } else if (shaderModel.IsGS()) {
  7865. theBuilder.requireCapability(spv::Capability::Geometry);
  7866. } else {
  7867. theBuilder.requireCapability(spv::Capability::Shader);
  7868. }
  7869. }
  7870. bool SPIRVEmitter::processGeometryShaderAttributes(const FunctionDecl *decl,
  7871. uint32_t *arraySize) {
  7872. bool success = true;
  7873. assert(shaderModel.IsGS());
  7874. if (auto *vcAttr = decl->getAttr<HLSLMaxVertexCountAttr>()) {
  7875. theBuilder.addExecutionMode(entryFunctionId,
  7876. spv::ExecutionMode::OutputVertices,
  7877. {static_cast<uint32_t>(vcAttr->getCount())});
  7878. }
  7879. uint32_t invocations = 1;
  7880. if (auto *instanceAttr = decl->getAttr<HLSLInstanceAttr>()) {
  7881. invocations = static_cast<uint32_t>(instanceAttr->getCount());
  7882. }
  7883. theBuilder.addExecutionMode(entryFunctionId, spv::ExecutionMode::Invocations,
  7884. {invocations});
  7885. // Only one primitive type is permitted for the geometry shader.
  7886. bool outPoint = false, outLine = false, outTriangle = false, inPoint = false,
  7887. inLine = false, inTriangle = false, inLineAdj = false,
  7888. inTriangleAdj = false;
  7889. for (const auto *param : decl->params()) {
  7890. // Add an execution mode based on the output stream type. Do not an
  7891. // execution mode more than once.
  7892. if (param->hasAttr<HLSLInOutAttr>()) {
  7893. const auto paramType = param->getType();
  7894. if (hlsl::IsHLSLTriangleStreamType(paramType) && !outTriangle) {
  7895. theBuilder.addExecutionMode(
  7896. entryFunctionId, spv::ExecutionMode::OutputTriangleStrip, {});
  7897. outTriangle = true;
  7898. } else if (hlsl::IsHLSLLineStreamType(paramType) && !outLine) {
  7899. theBuilder.addExecutionMode(entryFunctionId,
  7900. spv::ExecutionMode::OutputLineStrip, {});
  7901. outLine = true;
  7902. } else if (hlsl::IsHLSLPointStreamType(paramType) && !outPoint) {
  7903. theBuilder.addExecutionMode(entryFunctionId,
  7904. spv::ExecutionMode::OutputPoints, {});
  7905. outPoint = true;
  7906. }
  7907. // An output stream parameter will not have the input primitive type
  7908. // attributes, so we can continue to the next parameter.
  7909. continue;
  7910. }
  7911. // Add an execution mode based on the input primitive type. Do not add an
  7912. // execution mode more than once.
  7913. if (param->hasAttr<HLSLPointAttr>() && !inPoint) {
  7914. theBuilder.addExecutionMode(entryFunctionId,
  7915. spv::ExecutionMode::InputPoints, {});
  7916. *arraySize = 1;
  7917. inPoint = true;
  7918. } else if (param->hasAttr<HLSLLineAttr>() && !inLine) {
  7919. theBuilder.addExecutionMode(entryFunctionId,
  7920. spv::ExecutionMode::InputLines, {});
  7921. *arraySize = 2;
  7922. inLine = true;
  7923. } else if (param->hasAttr<HLSLTriangleAttr>() && !inTriangle) {
  7924. theBuilder.addExecutionMode(entryFunctionId,
  7925. spv::ExecutionMode::Triangles, {});
  7926. *arraySize = 3;
  7927. inTriangle = true;
  7928. } else if (param->hasAttr<HLSLLineAdjAttr>() && !inLineAdj) {
  7929. theBuilder.addExecutionMode(entryFunctionId,
  7930. spv::ExecutionMode::InputLinesAdjacency, {});
  7931. *arraySize = 4;
  7932. inLineAdj = true;
  7933. } else if (param->hasAttr<HLSLTriangleAdjAttr>() && !inTriangleAdj) {
  7934. theBuilder.addExecutionMode(
  7935. entryFunctionId, spv::ExecutionMode::InputTrianglesAdjacency, {});
  7936. *arraySize = 6;
  7937. inTriangleAdj = true;
  7938. }
  7939. }
  7940. if (inPoint + inLine + inLineAdj + inTriangle + inTriangleAdj > 1) {
  7941. emitError("only one input primitive type can be specified in the geometry "
  7942. "shader",
  7943. {});
  7944. success = false;
  7945. }
  7946. if (outPoint + outTriangle + outLine > 1) {
  7947. emitError("only one output primitive type can be specified in the geometry "
  7948. "shader",
  7949. {});
  7950. success = false;
  7951. }
  7952. return success;
  7953. }
  7954. void SPIRVEmitter::processPixelShaderAttributes(const FunctionDecl *decl) {
  7955. theBuilder.addExecutionMode(entryFunctionId,
  7956. spv::ExecutionMode::OriginUpperLeft, {});
  7957. if (auto *numThreadsAttr = decl->getAttr<HLSLEarlyDepthStencilAttr>()) {
  7958. theBuilder.addExecutionMode(entryFunctionId,
  7959. spv::ExecutionMode::EarlyFragmentTests, {});
  7960. }
  7961. }
  7962. void SPIRVEmitter::processComputeShaderAttributes(const FunctionDecl *decl) {
  7963. // If not explicitly specified, x, y, and z should be defaulted to 1.
  7964. uint32_t x = 1, y = 1, z = 1;
  7965. if (auto *numThreadsAttr = decl->getAttr<HLSLNumThreadsAttr>()) {
  7966. x = static_cast<uint32_t>(numThreadsAttr->getX());
  7967. y = static_cast<uint32_t>(numThreadsAttr->getY());
  7968. z = static_cast<uint32_t>(numThreadsAttr->getZ());
  7969. }
  7970. theBuilder.addExecutionMode(entryFunctionId, spv::ExecutionMode::LocalSize,
  7971. {x, y, z});
  7972. }
  7973. bool SPIRVEmitter::processTessellationShaderAttributes(
  7974. const FunctionDecl *decl, uint32_t *numOutputControlPoints) {
  7975. assert(shaderModel.IsHS() || shaderModel.IsDS());
  7976. using namespace spv;
  7977. if (auto *domain = decl->getAttr<HLSLDomainAttr>()) {
  7978. const auto domainType = domain->getDomainType().lower();
  7979. const ExecutionMode hsExecMode =
  7980. llvm::StringSwitch<ExecutionMode>(domainType)
  7981. .Case("tri", ExecutionMode::Triangles)
  7982. .Case("quad", ExecutionMode::Quads)
  7983. .Case("isoline", ExecutionMode::Isolines)
  7984. .Default(ExecutionMode::Max);
  7985. if (hsExecMode == ExecutionMode::Max) {
  7986. emitError("unknown domain type specified for entry function",
  7987. domain->getLocation());
  7988. return false;
  7989. }
  7990. theBuilder.addExecutionMode(entryFunctionId, hsExecMode, {});
  7991. }
  7992. // Early return for domain shaders as domain shaders only takes the 'domain'
  7993. // attribute.
  7994. if (shaderModel.IsDS())
  7995. return true;
  7996. if (auto *partitioning = decl->getAttr<HLSLPartitioningAttr>()) {
  7997. const auto scheme = partitioning->getScheme().lower();
  7998. if (scheme == "pow2") {
  7999. emitError("pow2 partitioning scheme is not supported since there is no "
  8000. "equivalent in Vulkan",
  8001. partitioning->getLocation());
  8002. return false;
  8003. }
  8004. const ExecutionMode hsExecMode =
  8005. llvm::StringSwitch<ExecutionMode>(scheme)
  8006. .Case("fractional_even", ExecutionMode::SpacingFractionalEven)
  8007. .Case("fractional_odd", ExecutionMode::SpacingFractionalOdd)
  8008. .Case("integer", ExecutionMode::SpacingEqual)
  8009. .Default(ExecutionMode::Max);
  8010. if (hsExecMode == ExecutionMode::Max) {
  8011. emitError("unknown partitioning scheme in hull shader",
  8012. partitioning->getLocation());
  8013. return false;
  8014. }
  8015. theBuilder.addExecutionMode(entryFunctionId, hsExecMode, {});
  8016. }
  8017. if (auto *outputTopology = decl->getAttr<HLSLOutputTopologyAttr>()) {
  8018. const auto topology = outputTopology->getTopology().lower();
  8019. const ExecutionMode hsExecMode =
  8020. llvm::StringSwitch<ExecutionMode>(topology)
  8021. .Case("point", ExecutionMode::PointMode)
  8022. .Case("triangle_cw", ExecutionMode::VertexOrderCw)
  8023. .Case("triangle_ccw", ExecutionMode::VertexOrderCcw)
  8024. .Default(ExecutionMode::Max);
  8025. // TODO: There is no SPIR-V equivalent for "line" topology. Is it the
  8026. // default?
  8027. if (topology != "line") {
  8028. if (hsExecMode != spv::ExecutionMode::Max) {
  8029. theBuilder.addExecutionMode(entryFunctionId, hsExecMode, {});
  8030. } else {
  8031. emitError("unknown output topology in hull shader",
  8032. outputTopology->getLocation());
  8033. return false;
  8034. }
  8035. }
  8036. }
  8037. if (auto *controlPoints = decl->getAttr<HLSLOutputControlPointsAttr>()) {
  8038. *numOutputControlPoints = controlPoints->getCount();
  8039. theBuilder.addExecutionMode(entryFunctionId,
  8040. spv::ExecutionMode::OutputVertices,
  8041. {*numOutputControlPoints});
  8042. }
  8043. if (auto *pcf = decl->getAttr<HLSLPatchConstantFuncAttr>()) {
  8044. llvm::StringRef pcf_name = pcf->getFunctionName();
  8045. for (auto *decl : astContext.getTranslationUnitDecl()->decls())
  8046. if (auto *funcDecl = dyn_cast<FunctionDecl>(decl))
  8047. if (astContext.IsPatchConstantFunctionDecl(funcDecl) &&
  8048. funcDecl->getName() == pcf_name)
  8049. patchConstFunc = funcDecl;
  8050. }
  8051. return true;
  8052. }
  8053. bool SPIRVEmitter::emitEntryFunctionWrapper(const FunctionDecl *decl,
  8054. const uint32_t entryFuncId) {
  8055. // HS specific attributes
  8056. uint32_t numOutputControlPoints = 0;
  8057. uint32_t outputControlPointIdVal = 0; // SV_OutputControlPointID value
  8058. uint32_t primitiveIdVar = 0; // SV_PrimitiveID variable
  8059. uint32_t viewIdVar = 0; // SV_ViewID variable
  8060. uint32_t hullMainInputPatchParam = 0; // Temporary parameter for InputPatch<>
  8061. // The array size of per-vertex input/output variables
  8062. // Used by HS/DS/GS for the additional arrayness, zero means not an array.
  8063. uint32_t inputArraySize = 0;
  8064. uint32_t outputArraySize = 0;
  8065. // Construct the wrapper function signature.
  8066. const uint32_t voidType = theBuilder.getVoidType();
  8067. const uint32_t funcType = theBuilder.getFunctionType(voidType, {});
  8068. // The wrapper entry function surely does not have pre-assigned <result-id>
  8069. // for it like other functions that got added to the work queue following
  8070. // function calls. And the wrapper is the entry function.
  8071. entryFunctionId =
  8072. theBuilder.beginFunction(funcType, voidType, decl->getName());
  8073. // Note this should happen before using declIdMapper for other tasks.
  8074. declIdMapper.setEntryFunctionId(entryFunctionId);
  8075. // Handle attributes specific to each shader stage
  8076. if (shaderModel.IsPS()) {
  8077. processPixelShaderAttributes(decl);
  8078. } else if (shaderModel.IsCS()) {
  8079. processComputeShaderAttributes(decl);
  8080. } else if (shaderModel.IsHS()) {
  8081. if (!processTessellationShaderAttributes(decl, &numOutputControlPoints))
  8082. return false;
  8083. // The input array size for HS is specified in the InputPatch parameter.
  8084. for (const auto *param : decl->params())
  8085. if (hlsl::IsHLSLInputPatchType(param->getType())) {
  8086. inputArraySize = hlsl::GetHLSLInputPatchCount(param->getType());
  8087. break;
  8088. }
  8089. outputArraySize = numOutputControlPoints;
  8090. } else if (shaderModel.IsDS()) {
  8091. if (!processTessellationShaderAttributes(decl, &numOutputControlPoints))
  8092. return false;
  8093. // The input array size for HS is specified in the OutputPatch parameter.
  8094. for (const auto *param : decl->params())
  8095. if (hlsl::IsHLSLOutputPatchType(param->getType())) {
  8096. inputArraySize = hlsl::GetHLSLOutputPatchCount(param->getType());
  8097. break;
  8098. }
  8099. // The per-vertex output of DS is not an array.
  8100. } else if (shaderModel.IsGS()) {
  8101. if (!processGeometryShaderAttributes(decl, &inputArraySize))
  8102. return false;
  8103. // The per-vertex output of GS is not an array.
  8104. }
  8105. // Go through all parameters and record the declaration of SV_ClipDistance
  8106. // and SV_CullDistance. We need to do this extra step because in HLSL we
  8107. // can declare multiple SV_ClipDistance/SV_CullDistance variables of float
  8108. // or vector of float types, but we can only have one single float array
  8109. // for the ClipDistance/CullDistance builtin. So we need to group all
  8110. // SV_ClipDistance/SV_CullDistance variables into one float array, thus we
  8111. // need to calculate the total size of the array and the offset of each
  8112. // variable within that array.
  8113. // Also go through all parameters to record the semantic strings provided for
  8114. // the builtins in gl_PerVertex.
  8115. for (const auto *param : decl->params()) {
  8116. if (canActAsInParmVar(param))
  8117. if (!declIdMapper.glPerVertex.recordGlPerVertexDeclFacts(param, true))
  8118. return false;
  8119. if (canActAsOutParmVar(param))
  8120. if (!declIdMapper.glPerVertex.recordGlPerVertexDeclFacts(param, false))
  8121. return false;
  8122. }
  8123. // Also consider the SV_ClipDistance/SV_CullDistance in the return type
  8124. if (!declIdMapper.glPerVertex.recordGlPerVertexDeclFacts(decl, false))
  8125. return false;
  8126. // Calculate the total size of the ClipDistance/CullDistance array and the
  8127. // offset of SV_ClipDistance/SV_CullDistance variables within the array.
  8128. declIdMapper.glPerVertex.calculateClipCullDistanceArraySize();
  8129. if (!shaderModel.IsCS()) {
  8130. // Generate the gl_PerVertex structs or stand-alone builtins of
  8131. // Position, ClipDistance, and CullDistance.
  8132. declIdMapper.glPerVertex.generateVars(inputArraySize, outputArraySize);
  8133. }
  8134. // Require the ClipDistance/CullDistance capability if necessary.
  8135. // It is legal to just use the ClipDistance/CullDistance builtin without
  8136. // requiring the ClipDistance/CullDistance capability, as long as we don't
  8137. // read or write the builtin variable.
  8138. // For our CodeGen, that corresponds to not seeing SV_ClipDistance or
  8139. // SV_CullDistance at all. If we see them, we will generate code to read
  8140. // them to initialize temporary variable for calling the source code entry
  8141. // function or write to them after calling the source code entry function.
  8142. declIdMapper.glPerVertex.requireCapabilityIfNecessary();
  8143. // The entry basic block.
  8144. const uint32_t entryLabel = theBuilder.createBasicBlock();
  8145. theBuilder.setInsertPoint(entryLabel);
  8146. // Initialize all global variables at the beginning of the wrapper
  8147. for (const VarDecl *varDecl : toInitGloalVars) {
  8148. const auto varInfo = declIdMapper.getDeclEvalInfo(varDecl);
  8149. if (const auto *init = varDecl->getInit()) {
  8150. storeValue(varInfo, doExpr(init), varDecl->getType());
  8151. // Update counter variable associated with global variables
  8152. tryToAssignCounterVar(varDecl, init);
  8153. }
  8154. // If not explicitly initialized, initialize with their zero values if not
  8155. // resource objects
  8156. else if (!hlsl::IsHLSLResourceType(varDecl->getType())) {
  8157. const auto typeId = typeTranslator.translateType(varDecl->getType());
  8158. theBuilder.createStore(varInfo, theBuilder.getConstantNull(typeId));
  8159. }
  8160. }
  8161. // Create temporary variables for holding function call arguments
  8162. llvm::SmallVector<uint32_t, 4> params;
  8163. for (const auto *param : decl->params()) {
  8164. const auto paramType = param->getType();
  8165. const uint32_t typeId = typeTranslator.translateType(paramType);
  8166. std::string tempVarName = "param.var." + param->getNameAsString();
  8167. const uint32_t tempVar = theBuilder.addFnVar(typeId, tempVarName);
  8168. params.push_back(tempVar);
  8169. // Create the stage input variable for parameter not marked as pure out and
  8170. // initialize the corresponding temporary variable
  8171. // Also do not create input variables for output stream objects of geometry
  8172. // shaders (e.g. TriangleStream) which are required to be marked as 'inout'.
  8173. if (canActAsInParmVar(param)) {
  8174. if (shaderModel.IsHS() && hlsl::IsHLSLInputPatchType(paramType)) {
  8175. // Record the temporary variable holding InputPatch. It may be used
  8176. // later in the patch constant function.
  8177. hullMainInputPatchParam = tempVar;
  8178. }
  8179. uint32_t loadedValue = 0;
  8180. if (!declIdMapper.createStageInputVar(param, &loadedValue, false))
  8181. return false;
  8182. theBuilder.createStore(tempVar, loadedValue);
  8183. // Record the temporary variable holding SV_OutputControlPointID,
  8184. // SV_PrimitiveID, and SV_ViewID. It may be used later in the patch
  8185. // constant function.
  8186. if (hasSemantic(param, hlsl::DXIL::SemanticKind::OutputControlPointID))
  8187. outputControlPointIdVal = loadedValue;
  8188. else if (hasSemantic(param, hlsl::DXIL::SemanticKind::PrimitiveID))
  8189. primitiveIdVar = tempVar;
  8190. else if (hasSemantic(param, hlsl::DXIL::SemanticKind::ViewID))
  8191. viewIdVar = tempVar;
  8192. }
  8193. }
  8194. // Call the original entry function
  8195. const uint32_t retType = typeTranslator.translateType(decl->getReturnType());
  8196. const uint32_t retVal =
  8197. theBuilder.createFunctionCall(retType, entryFuncId, params);
  8198. // Create and write stage output variables for return value. Special case for
  8199. // Hull shaders since they operate differently in 2 ways:
  8200. // 1- Their return value is in fact an array and each invocation should write
  8201. // to the proper offset in the array.
  8202. // 2- The patch constant function must be called *once* after all invocations
  8203. // of the main entry point function is done.
  8204. if (shaderModel.IsHS()) {
  8205. // Create stage output variables out of the return type.
  8206. if (!declIdMapper.createStageOutputVar(decl, numOutputControlPoints,
  8207. outputControlPointIdVal, retVal))
  8208. return false;
  8209. if (!processHSEntryPointOutputAndPCF(
  8210. decl, retType, retVal, numOutputControlPoints,
  8211. outputControlPointIdVal, primitiveIdVar, viewIdVar,
  8212. hullMainInputPatchParam))
  8213. return false;
  8214. } else {
  8215. if (!declIdMapper.createStageOutputVar(decl, retVal, /*forPCF*/ false))
  8216. return false;
  8217. }
  8218. // Create and write stage output variables for parameters marked as
  8219. // out/inout
  8220. for (uint32_t i = 0; i < decl->getNumParams(); ++i) {
  8221. const auto *param = decl->getParamDecl(i);
  8222. if (canActAsOutParmVar(param)) {
  8223. // Load the value from the parameter after function call
  8224. const uint32_t typeId = typeTranslator.translateType(param->getType());
  8225. uint32_t loadedParam = 0;
  8226. // Write back of stage output variables in GS is manually controlled by
  8227. // .Append() intrinsic method. No need to load the parameter since we
  8228. // won't need to write back here.
  8229. if (!shaderModel.IsGS())
  8230. loadedParam = theBuilder.createLoad(typeId, params[i]);
  8231. if (!declIdMapper.createStageOutputVar(param, loadedParam, false))
  8232. return false;
  8233. }
  8234. }
  8235. theBuilder.createReturn();
  8236. theBuilder.endFunction();
  8237. // For Hull shaders, there is no explicit call to the PCF in the HLSL source.
  8238. // We should invoke a translation of the PCF manually.
  8239. if (shaderModel.IsHS())
  8240. doDecl(patchConstFunc);
  8241. return true;
  8242. }
  8243. bool SPIRVEmitter::processHSEntryPointOutputAndPCF(
  8244. const FunctionDecl *hullMainFuncDecl, uint32_t retType, uint32_t retVal,
  8245. uint32_t numOutputControlPoints, uint32_t outputControlPointId,
  8246. uint32_t primitiveId, uint32_t viewId, uint32_t hullMainInputPatch) {
  8247. // This method may only be called for Hull shaders.
  8248. assert(shaderModel.IsHS());
  8249. // For Hull shaders, the real output is an array of size
  8250. // numOutputControlPoints. The results of the main should be written to the
  8251. // correct offset in the array (based on InvocationID).
  8252. if (!numOutputControlPoints) {
  8253. emitError("number of output control points cannot be zero",
  8254. hullMainFuncDecl->getLocation());
  8255. return false;
  8256. }
  8257. // TODO: We should be able to handle cases where the SV_OutputControlPointID
  8258. // is not provided.
  8259. if (!outputControlPointId) {
  8260. emitError(
  8261. "SV_OutputControlPointID semantic must be provided in hull shader",
  8262. hullMainFuncDecl->getLocation());
  8263. return false;
  8264. }
  8265. if (!patchConstFunc) {
  8266. emitError("patch constant function not defined in hull shader",
  8267. hullMainFuncDecl->getLocation());
  8268. return false;
  8269. }
  8270. uint32_t hullMainOutputPatch = 0;
  8271. // If the patch constant function (PCF) takes the result of the Hull main
  8272. // entry point, create a temporary function-scope variable and write the
  8273. // results to it, so it can be passed to the PCF.
  8274. if (patchConstFuncTakesHullOutputPatch(patchConstFunc)) {
  8275. const uint32_t hullMainRetType = theBuilder.getArrayType(
  8276. retType, theBuilder.getConstantUint32(numOutputControlPoints));
  8277. hullMainOutputPatch =
  8278. theBuilder.addFnVar(hullMainRetType, "temp.var.hullMainRetVal");
  8279. const auto tempLocation = theBuilder.createAccessChain(
  8280. theBuilder.getPointerType(retType, spv::StorageClass::Function),
  8281. hullMainOutputPatch, {outputControlPointId});
  8282. theBuilder.createStore(tempLocation, retVal);
  8283. }
  8284. // Now create a barrier before calling the Patch Constant Function (PCF).
  8285. // Flags are:
  8286. // Execution Barrier scope = Workgroup (2)
  8287. // Memory Barrier scope = Device (1)
  8288. // Memory Semantics Barrier scope = None (0)
  8289. theBuilder.createBarrier(theBuilder.getConstantUint32(2),
  8290. theBuilder.getConstantUint32(1),
  8291. theBuilder.getConstantUint32(0));
  8292. // The PCF should be called only once. Therefore, we check the invocationID,
  8293. // and we only allow ID 0 to call the PCF.
  8294. const uint32_t condition = theBuilder.createBinaryOp(
  8295. spv::Op::OpIEqual, theBuilder.getBoolType(), outputControlPointId,
  8296. theBuilder.getConstantUint32(0));
  8297. const uint32_t thenBB = theBuilder.createBasicBlock("if.true");
  8298. const uint32_t mergeBB = theBuilder.createBasicBlock("if.merge");
  8299. theBuilder.createConditionalBranch(condition, thenBB, mergeBB, mergeBB);
  8300. theBuilder.addSuccessor(thenBB);
  8301. theBuilder.addSuccessor(mergeBB);
  8302. theBuilder.setMergeTarget(mergeBB);
  8303. theBuilder.setInsertPoint(thenBB);
  8304. // Call the PCF. Since the function is not explicitly called, we must first
  8305. // register an ID for it.
  8306. const uint32_t pcfId = declIdMapper.getOrRegisterFnResultId(patchConstFunc);
  8307. const uint32_t pcfRetType =
  8308. typeTranslator.translateType(patchConstFunc->getReturnType());
  8309. std::vector<uint32_t> pcfParams;
  8310. // A lambda for creating a stage input variable and its associated temporary
  8311. // variable for function call. Also initializes the temporary variable using
  8312. // the contents loaded from the stage input variable. Returns the <result-id>
  8313. // of the temporary variable.
  8314. const auto createParmVarAndInitFromStageInputVar =
  8315. [this](const ParmVarDecl *param) {
  8316. const uint32_t typeId = typeTranslator.translateType(param->getType());
  8317. std::string tempVarName = "param.var." + param->getNameAsString();
  8318. const uint32_t tempVar = theBuilder.addFnVar(typeId, tempVarName);
  8319. uint32_t loadedValue = 0;
  8320. declIdMapper.createStageInputVar(param, &loadedValue, /*forPCF*/ true);
  8321. theBuilder.createStore(tempVar, loadedValue);
  8322. return tempVar;
  8323. };
  8324. for (const auto *param : patchConstFunc->parameters()) {
  8325. // Note: According to the HLSL reference, the PCF takes an InputPatch of
  8326. // ControlPoints as well as the PatchID (PrimitiveID). This does not
  8327. // necessarily mean that they are present. There is also no requirement
  8328. // for the order of parameters passed to PCF.
  8329. if (hlsl::IsHLSLInputPatchType(param->getType())) {
  8330. pcfParams.push_back(hullMainInputPatch);
  8331. } else if (hlsl::IsHLSLOutputPatchType(param->getType())) {
  8332. pcfParams.push_back(hullMainOutputPatch);
  8333. } else if (hasSemantic(param, hlsl::DXIL::SemanticKind::PrimitiveID)) {
  8334. if (!primitiveId) {
  8335. primitiveId = createParmVarAndInitFromStageInputVar(param);
  8336. }
  8337. pcfParams.push_back(primitiveId);
  8338. } else if (hasSemantic(param, hlsl::DXIL::SemanticKind::ViewID)) {
  8339. if (!viewId) {
  8340. viewId = createParmVarAndInitFromStageInputVar(param);
  8341. }
  8342. pcfParams.push_back(viewId);
  8343. } else {
  8344. emitError("patch constant function parameter '%0' unknown",
  8345. param->getLocation())
  8346. << param->getName();
  8347. }
  8348. }
  8349. const uint32_t pcfResultId =
  8350. theBuilder.createFunctionCall(pcfRetType, pcfId, {pcfParams});
  8351. if (!declIdMapper.createStageOutputVar(patchConstFunc, pcfResultId,
  8352. /*forPCF*/ true))
  8353. return false;
  8354. theBuilder.createBranch(mergeBB);
  8355. theBuilder.addSuccessor(mergeBB);
  8356. theBuilder.setInsertPoint(mergeBB);
  8357. return true;
  8358. }
  8359. bool SPIRVEmitter::allSwitchCasesAreIntegerLiterals(const Stmt *root) {
  8360. if (!root)
  8361. return false;
  8362. const auto *caseStmt = dyn_cast<CaseStmt>(root);
  8363. const auto *compoundStmt = dyn_cast<CompoundStmt>(root);
  8364. if (!caseStmt && !compoundStmt)
  8365. return true;
  8366. if (caseStmt) {
  8367. const Expr *caseExpr = caseStmt->getLHS();
  8368. return caseExpr && caseExpr->isEvaluatable(astContext);
  8369. }
  8370. // Recurse down if facing a compound statement.
  8371. for (auto *st : compoundStmt->body())
  8372. if (!allSwitchCasesAreIntegerLiterals(st))
  8373. return false;
  8374. return true;
  8375. }
  8376. void SPIRVEmitter::discoverAllCaseStmtInSwitchStmt(
  8377. const Stmt *root, uint32_t *defaultBB,
  8378. std::vector<std::pair<uint32_t, uint32_t>> *targets) {
  8379. if (!root)
  8380. return;
  8381. // A switch case can only appear in DefaultStmt, CaseStmt, or
  8382. // CompoundStmt. For the rest, we can just return.
  8383. const auto *defaultStmt = dyn_cast<DefaultStmt>(root);
  8384. const auto *caseStmt = dyn_cast<CaseStmt>(root);
  8385. const auto *compoundStmt = dyn_cast<CompoundStmt>(root);
  8386. if (!defaultStmt && !caseStmt && !compoundStmt)
  8387. return;
  8388. // Recurse down if facing a compound statement.
  8389. if (compoundStmt) {
  8390. for (auto *st : compoundStmt->body())
  8391. discoverAllCaseStmtInSwitchStmt(st, defaultBB, targets);
  8392. return;
  8393. }
  8394. std::string caseLabel;
  8395. uint32_t caseValue = 0;
  8396. if (defaultStmt) {
  8397. // This is the default branch.
  8398. caseLabel = "switch.default";
  8399. } else if (caseStmt) {
  8400. // This is a non-default case.
  8401. // When using OpSwitch, we only allow integer literal cases. e.g:
  8402. // case <literal_integer>: {...; break;}
  8403. const Expr *caseExpr = caseStmt->getLHS();
  8404. assert(caseExpr && caseExpr->isEvaluatable(astContext));
  8405. auto bitWidth = astContext.getIntWidth(caseExpr->getType());
  8406. if (bitWidth != 32)
  8407. emitError(
  8408. "non-32bit integer case value in switch statement unimplemented",
  8409. caseExpr->getExprLoc());
  8410. Expr::EvalResult evalResult;
  8411. caseExpr->EvaluateAsRValue(evalResult, astContext);
  8412. const int64_t value = evalResult.Val.getInt().getSExtValue();
  8413. caseValue = static_cast<uint32_t>(value);
  8414. caseLabel = "switch." + std::string(value < 0 ? "n" : "") +
  8415. llvm::itostr(std::abs(value));
  8416. }
  8417. const uint32_t caseBB = theBuilder.createBasicBlock(caseLabel);
  8418. theBuilder.addSuccessor(caseBB);
  8419. stmtBasicBlock[root] = caseBB;
  8420. // Add all cases to the 'targets' vector.
  8421. if (caseStmt)
  8422. targets->emplace_back(caseValue, caseBB);
  8423. // The default label is not part of the 'targets' vector that is passed
  8424. // to the OpSwitch instruction.
  8425. // If default statement was discovered, return its label via defaultBB.
  8426. if (defaultStmt)
  8427. *defaultBB = caseBB;
  8428. // Process cases nested in other cases. It happens when we have fall through
  8429. // cases. For example:
  8430. // case 1: case 2: ...; break;
  8431. // will result in the CaseSmt for case 2 nested in the one for case 1.
  8432. discoverAllCaseStmtInSwitchStmt(caseStmt ? caseStmt->getSubStmt()
  8433. : defaultStmt->getSubStmt(),
  8434. defaultBB, targets);
  8435. }
  8436. void SPIRVEmitter::flattenSwitchStmtAST(const Stmt *root,
  8437. std::vector<const Stmt *> *flatSwitch) {
  8438. const auto *caseStmt = dyn_cast<CaseStmt>(root);
  8439. const auto *compoundStmt = dyn_cast<CompoundStmt>(root);
  8440. const auto *defaultStmt = dyn_cast<DefaultStmt>(root);
  8441. if (!compoundStmt) {
  8442. flatSwitch->push_back(root);
  8443. }
  8444. if (compoundStmt) {
  8445. for (const auto *st : compoundStmt->body())
  8446. flattenSwitchStmtAST(st, flatSwitch);
  8447. } else if (caseStmt) {
  8448. flattenSwitchStmtAST(caseStmt->getSubStmt(), flatSwitch);
  8449. } else if (defaultStmt) {
  8450. flattenSwitchStmtAST(defaultStmt->getSubStmt(), flatSwitch);
  8451. }
  8452. }
  8453. void SPIRVEmitter::processCaseStmtOrDefaultStmt(const Stmt *stmt) {
  8454. auto *caseStmt = dyn_cast<CaseStmt>(stmt);
  8455. auto *defaultStmt = dyn_cast<DefaultStmt>(stmt);
  8456. assert(caseStmt || defaultStmt);
  8457. uint32_t caseBB = stmtBasicBlock[stmt];
  8458. if (!theBuilder.isCurrentBasicBlockTerminated()) {
  8459. // We are about to handle the case passed in as parameter. If the current
  8460. // basic block is not terminated, it means the previous case is a fall
  8461. // through case. We need to link it to the case to be processed.
  8462. theBuilder.createBranch(caseBB);
  8463. theBuilder.addSuccessor(caseBB);
  8464. }
  8465. theBuilder.setInsertPoint(caseBB);
  8466. doStmt(caseStmt ? caseStmt->getSubStmt() : defaultStmt->getSubStmt());
  8467. }
  8468. void SPIRVEmitter::processSwitchStmtUsingSpirvOpSwitch(
  8469. const SwitchStmt *switchStmt) {
  8470. // First handle the condition variable DeclStmt if one exists.
  8471. // For example: handle 'int a = b' in the following:
  8472. // switch (int a = b) {...}
  8473. if (const auto *condVarDeclStmt = switchStmt->getConditionVariableDeclStmt())
  8474. doDeclStmt(condVarDeclStmt);
  8475. const uint32_t selector = doExpr(switchStmt->getCond());
  8476. // We need a merge block regardless of the number of switch cases.
  8477. // Since OpSwitch always requires a default label, if the switch statement
  8478. // does not have a default branch, we use the merge block as the default
  8479. // target.
  8480. const uint32_t mergeBB = theBuilder.createBasicBlock("switch.merge");
  8481. theBuilder.setMergeTarget(mergeBB);
  8482. breakStack.push(mergeBB);
  8483. uint32_t defaultBB = mergeBB;
  8484. // (literal, labelId) pairs to pass to the OpSwitch instruction.
  8485. std::vector<std::pair<uint32_t, uint32_t>> targets;
  8486. discoverAllCaseStmtInSwitchStmt(switchStmt->getBody(), &defaultBB, &targets);
  8487. // Create the OpSelectionMerge and OpSwitch.
  8488. theBuilder.createSwitch(mergeBB, selector, defaultBB, targets);
  8489. // Handle the switch body.
  8490. doStmt(switchStmt->getBody());
  8491. if (!theBuilder.isCurrentBasicBlockTerminated())
  8492. theBuilder.createBranch(mergeBB);
  8493. theBuilder.setInsertPoint(mergeBB);
  8494. breakStack.pop();
  8495. }
  8496. void SPIRVEmitter::processSwitchStmtUsingIfStmts(const SwitchStmt *switchStmt) {
  8497. std::vector<const Stmt *> flatSwitch;
  8498. flattenSwitchStmtAST(switchStmt->getBody(), &flatSwitch);
  8499. // First handle the condition variable DeclStmt if one exists.
  8500. // For example: handle 'int a = b' in the following:
  8501. // switch (int a = b) {...}
  8502. if (const auto *condVarDeclStmt = switchStmt->getConditionVariableDeclStmt())
  8503. doDeclStmt(condVarDeclStmt);
  8504. // Figure out the indexes of CaseStmts (and DefaultStmt if it exists) in
  8505. // the flattened switch AST.
  8506. // For instance, for the following flat vector:
  8507. // +-----+-----+-----+-----+-----+-----+-----+-----+-----+-------+-----+
  8508. // |Case1|Stmt1|Case2|Stmt2|Break|Case3|Case4|Stmt4|Break|Default|Stmt5|
  8509. // +-----+-----+-----+-----+-----+-----+-----+-----+-----+-------+-----+
  8510. // The indexes are: {0, 2, 5, 6, 9}
  8511. std::vector<uint32_t> caseStmtLocs;
  8512. for (uint32_t i = 0; i < flatSwitch.size(); ++i)
  8513. if (isa<CaseStmt>(flatSwitch[i]) || isa<DefaultStmt>(flatSwitch[i]))
  8514. caseStmtLocs.push_back(i);
  8515. IfStmt *prevIfStmt = nullptr;
  8516. IfStmt *rootIfStmt = nullptr;
  8517. CompoundStmt *defaultBody = nullptr;
  8518. // For each case, start at its index in the vector, and go forward
  8519. // accumulating statements until BreakStmt or end of vector is reached.
  8520. for (auto curCaseIndex : caseStmtLocs) {
  8521. const Stmt *curCase = flatSwitch[curCaseIndex];
  8522. // CompoundStmt to hold all statements for this case.
  8523. CompoundStmt *cs = new (astContext) CompoundStmt(Stmt::EmptyShell());
  8524. // Accumulate all non-case/default/break statements as the body for the
  8525. // current case.
  8526. std::vector<Stmt *> statements;
  8527. for (int i = curCaseIndex + 1;
  8528. i < flatSwitch.size() && !isa<BreakStmt>(flatSwitch[i]); ++i) {
  8529. if (!isa<CaseStmt>(flatSwitch[i]) && !isa<DefaultStmt>(flatSwitch[i]))
  8530. statements.push_back(const_cast<Stmt *>(flatSwitch[i]));
  8531. }
  8532. if (!statements.empty())
  8533. cs->setStmts(astContext, statements.data(), statements.size());
  8534. // For non-default cases, generate the IfStmt that compares the switch
  8535. // value to the case value.
  8536. if (auto *caseStmt = dyn_cast<CaseStmt>(curCase)) {
  8537. IfStmt *curIf = new (astContext) IfStmt(Stmt::EmptyShell());
  8538. BinaryOperator *bo = new (astContext) BinaryOperator(Stmt::EmptyShell());
  8539. bo->setLHS(const_cast<Expr *>(switchStmt->getCond()));
  8540. bo->setRHS(const_cast<Expr *>(caseStmt->getLHS()));
  8541. bo->setOpcode(BO_EQ);
  8542. bo->setType(astContext.getLogicalOperationType());
  8543. curIf->setCond(bo);
  8544. curIf->setThen(cs);
  8545. // No conditional variable associated with this faux if statement.
  8546. curIf->setConditionVariable(astContext, nullptr);
  8547. // Each If statement is the "else" of the previous if statement.
  8548. if (prevIfStmt)
  8549. prevIfStmt->setElse(curIf);
  8550. else
  8551. rootIfStmt = curIf;
  8552. prevIfStmt = curIf;
  8553. } else {
  8554. // Record the DefaultStmt body as it will be used as the body of the
  8555. // "else" block in the if-elseif-...-else pattern.
  8556. defaultBody = cs;
  8557. }
  8558. }
  8559. // If a default case exists, it is the "else" of the last if statement.
  8560. if (prevIfStmt)
  8561. prevIfStmt->setElse(defaultBody);
  8562. // Since all else-if and else statements are the child nodes of the first
  8563. // IfStmt, we only need to call doStmt for the first IfStmt.
  8564. if (rootIfStmt)
  8565. doStmt(rootIfStmt);
  8566. // If there are no CaseStmt and there is only 1 DefaultStmt, there will be
  8567. // no if statements. The switch in that case only executes the body of the
  8568. // default case.
  8569. else if (defaultBody)
  8570. doStmt(defaultBody);
  8571. }
  8572. uint32_t SPIRVEmitter::extractVecFromVec4(uint32_t fromId,
  8573. uint32_t targetVecSize,
  8574. uint32_t targetElemTypeId) {
  8575. assert(targetVecSize > 0 && targetVecSize < 5);
  8576. const uint32_t retType =
  8577. targetVecSize == 1
  8578. ? targetElemTypeId
  8579. : theBuilder.getVecType(targetElemTypeId, targetVecSize);
  8580. switch (targetVecSize) {
  8581. case 1:
  8582. return theBuilder.createCompositeExtract(retType, fromId, {0});
  8583. break;
  8584. case 2:
  8585. return theBuilder.createVectorShuffle(retType, fromId, fromId, {0, 1});
  8586. break;
  8587. case 3:
  8588. return theBuilder.createVectorShuffle(retType, fromId, fromId, {0, 1, 2});
  8589. break;
  8590. case 4:
  8591. return fromId;
  8592. default:
  8593. llvm_unreachable("vector element count must be 1, 2, 3, or 4");
  8594. }
  8595. }
  8596. } // end namespace spirv
  8597. } // end namespace clang