SpirvEmitter.cpp 465 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681
  1. //===------- SpirvEmitter.cpp - 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 "AlignmentSizeCalculator.h"
  15. #include "RawBufferMethods.h"
  16. #include "dxc/HlslIntrinsicOp.h"
  17. #include "spirv-tools/optimizer.hpp"
  18. #include "clang/SPIRV/AstTypeProbe.h"
  19. #include "clang/Sema/Sema.h"
  20. #include "llvm/ADT/StringExtras.h"
  21. #include "InitListHandler.h"
  22. #include "dxc/DXIL/DxilConstants.h"
  23. #ifdef SUPPORT_QUERY_GIT_COMMIT_INFO
  24. #include "clang/Basic/Version.h"
  25. #else
  26. namespace clang {
  27. uint32_t getGitCommitCount() { return 0; }
  28. const char *getGitCommitHash() { return "<unknown-hash>"; }
  29. } // namespace clang
  30. #endif // SUPPORT_QUERY_GIT_COMMIT_INFO
  31. namespace clang {
  32. namespace spirv {
  33. namespace {
  34. // Returns true if the given decl has the given semantic.
  35. bool hasSemantic(const DeclaratorDecl *decl,
  36. hlsl::DXIL::SemanticKind semanticKind) {
  37. using namespace hlsl;
  38. for (auto *annotation : decl->getUnusualAnnotations()) {
  39. if (auto *semanticDecl = dyn_cast<SemanticDecl>(annotation)) {
  40. llvm::StringRef semanticName;
  41. uint32_t semanticIndex = 0;
  42. Semantic::DecomposeNameAndIndex(semanticDecl->SemanticName, &semanticName,
  43. &semanticIndex);
  44. const auto *semantic = Semantic::GetByName(semanticName);
  45. if (semantic->GetKind() == semanticKind)
  46. return true;
  47. }
  48. }
  49. return false;
  50. }
  51. bool patchConstFuncTakesHullOutputPatch(FunctionDecl *pcf) {
  52. for (const auto *param : pcf->parameters())
  53. if (hlsl::IsHLSLOutputPatchType(param->getType()))
  54. return true;
  55. return false;
  56. }
  57. inline bool isSpirvMatrixOp(spv::Op opcode) {
  58. return opcode == spv::Op::OpMatrixTimesMatrix ||
  59. opcode == spv::Op::OpMatrixTimesVector ||
  60. opcode == spv::Op::OpMatrixTimesScalar;
  61. }
  62. /// If expr is a (RW)StructuredBuffer.Load(), returns the object and writes
  63. /// index. Otherwiser, returns false.
  64. // TODO: The following doesn't handle Load(int, int) yet. And it is basically a
  65. // duplicate of doCXXMemberCallExpr.
  66. const Expr *isStructuredBufferLoad(const Expr *expr, const Expr **index) {
  67. using namespace hlsl;
  68. if (const auto *indexing = dyn_cast<CXXMemberCallExpr>(expr)) {
  69. const auto *callee = indexing->getDirectCallee();
  70. uint32_t opcode = static_cast<uint32_t>(IntrinsicOp::Num_Intrinsics);
  71. llvm::StringRef group;
  72. if (GetIntrinsicOp(callee, opcode, group)) {
  73. if (static_cast<IntrinsicOp>(opcode) == IntrinsicOp::MOP_Load) {
  74. const auto *object = indexing->getImplicitObjectArgument();
  75. if (isStructuredBuffer(object->getType())) {
  76. *index = indexing->getArg(0);
  77. return indexing->getImplicitObjectArgument();
  78. }
  79. }
  80. }
  81. }
  82. return nullptr;
  83. }
  84. /// Returns true if the given VarDecl will be translated into a SPIR-V variable
  85. /// not in the Private or Function storage class.
  86. inline bool isExternalVar(const VarDecl *var) {
  87. // Class static variables should be put in the Private storage class.
  88. // groupshared variables are allowed to be declared as "static". But we still
  89. // need to put them in the Workgroup storage class. That is, when seeing
  90. // "static groupshared", ignore "static".
  91. return var->hasExternalFormalLinkage()
  92. ? !var->isStaticDataMember()
  93. : (var->getAttr<HLSLGroupSharedAttr>() != nullptr);
  94. }
  95. /// Returns the referenced variable's DeclContext if the given expr is
  96. /// a DeclRefExpr referencing a ConstantBuffer/TextureBuffer. Otherwise,
  97. /// returns nullptr.
  98. const DeclContext *isConstantTextureBufferDeclRef(const Expr *expr) {
  99. if (const auto *declRefExpr = dyn_cast<DeclRefExpr>(expr->IgnoreParenCasts()))
  100. if (const auto *varDecl = dyn_cast<VarDecl>(declRefExpr->getFoundDecl()))
  101. if (isConstantTextureBuffer(varDecl))
  102. return varDecl->getType()->getAs<RecordType>()->getDecl();
  103. return nullptr;
  104. }
  105. /// Returns true if
  106. /// * the given expr is an DeclRefExpr referencing a kind of structured or byte
  107. /// buffer and it is non-alias one, or
  108. /// * the given expr is an CallExpr returning a kind of structured or byte
  109. /// buffer.
  110. /// * the given expr is an ArraySubscriptExpr referencing a kind of structured
  111. /// or byte buffer.
  112. ///
  113. /// Note: legalization specific code
  114. bool isReferencingNonAliasStructuredOrByteBuffer(const Expr *expr) {
  115. expr = expr->IgnoreParenCasts();
  116. if (const auto *declRefExpr = dyn_cast<DeclRefExpr>(expr)) {
  117. if (const auto *varDecl = dyn_cast<VarDecl>(declRefExpr->getFoundDecl()))
  118. if (isAKindOfStructuredOrByteBuffer(varDecl->getType()))
  119. return isExternalVar(varDecl);
  120. } else if (const auto *callExpr = dyn_cast<CallExpr>(expr)) {
  121. if (isAKindOfStructuredOrByteBuffer(callExpr->getType()))
  122. return true;
  123. } else if (const auto *arrSubExpr = dyn_cast<ArraySubscriptExpr>(expr)) {
  124. return isReferencingNonAliasStructuredOrByteBuffer(arrSubExpr->getBase());
  125. }
  126. return false;
  127. }
  128. bool spirvToolsLegalize(spv_target_env env, std::vector<uint32_t> *mod,
  129. std::string *messages) {
  130. spvtools::Optimizer optimizer(env);
  131. optimizer.SetMessageConsumer(
  132. [messages](spv_message_level_t /*level*/, const char * /*source*/,
  133. const spv_position_t & /*position*/,
  134. const char *message) { *messages += message; });
  135. spvtools::OptimizerOptions options;
  136. options.set_run_validator(false);
  137. optimizer.RegisterLegalizationPasses();
  138. optimizer.RegisterPass(spvtools::CreateReplaceInvalidOpcodePass());
  139. optimizer.RegisterPass(spvtools::CreateCompactIdsPass());
  140. return optimizer.Run(mod->data(), mod->size(), mod, options);
  141. }
  142. bool spirvToolsOptimize(spv_target_env env, std::vector<uint32_t> *mod,
  143. clang::spirv::SpirvCodeGenOptions &spirvOptions,
  144. std::string *messages) {
  145. spvtools::Optimizer optimizer(env);
  146. optimizer.SetMessageConsumer(
  147. [messages](spv_message_level_t /*level*/, const char * /*source*/,
  148. const spv_position_t & /*position*/,
  149. const char *message) { *messages += message; });
  150. spvtools::OptimizerOptions options;
  151. options.set_run_validator(false);
  152. if (spirvOptions.optConfig.empty()) {
  153. optimizer.RegisterPerformancePasses();
  154. if (spirvOptions.flattenResourceArrays)
  155. optimizer.RegisterPass(spvtools::CreateDescriptorScalarReplacementPass());
  156. optimizer.RegisterPass(spvtools::CreateCompactIdsPass());
  157. } else {
  158. // Command line options use llvm::SmallVector and llvm::StringRef, whereas
  159. // SPIR-V optimizer uses std::vector and std::string.
  160. std::vector<std::string> stdFlags;
  161. for (const auto &f : spirvOptions.optConfig)
  162. stdFlags.push_back(f.str());
  163. if (!optimizer.RegisterPassesFromFlags(stdFlags))
  164. return false;
  165. }
  166. return optimizer.Run(mod->data(), mod->size(), mod, options);
  167. }
  168. bool spirvToolsValidate(spv_target_env env, const SpirvCodeGenOptions &opts,
  169. bool beforeHlslLegalization, std::vector<uint32_t> *mod,
  170. std::string *messages) {
  171. spvtools::SpirvTools tools(env);
  172. tools.SetMessageConsumer(
  173. [messages](spv_message_level_t /*level*/, const char * /*source*/,
  174. const spv_position_t & /*position*/,
  175. const char *message) { *messages += message; });
  176. spvtools::ValidatorOptions options;
  177. options.SetBeforeHlslLegalization(beforeHlslLegalization);
  178. // GL: strict block layout rules
  179. // VK: relaxed block layout rules
  180. // DX: Skip block layout rules
  181. if (opts.useScalarLayout || opts.useDxLayout) {
  182. options.SetScalarBlockLayout(true);
  183. } else if (opts.useGlLayout) {
  184. // spirv-val by default checks this.
  185. } else {
  186. options.SetRelaxBlockLayout(true);
  187. }
  188. return tools.Validate(mod->data(), mod->size(), options);
  189. }
  190. /// Translates atomic HLSL opcodes into the equivalent SPIR-V opcode.
  191. spv::Op translateAtomicHlslOpcodeToSpirvOpcode(hlsl::IntrinsicOp opcode) {
  192. using namespace hlsl;
  193. using namespace spv;
  194. switch (opcode) {
  195. case IntrinsicOp::IOP_InterlockedAdd:
  196. case IntrinsicOp::MOP_InterlockedAdd:
  197. return Op::OpAtomicIAdd;
  198. case IntrinsicOp::IOP_InterlockedAnd:
  199. case IntrinsicOp::MOP_InterlockedAnd:
  200. return Op::OpAtomicAnd;
  201. case IntrinsicOp::IOP_InterlockedOr:
  202. case IntrinsicOp::MOP_InterlockedOr:
  203. return Op::OpAtomicOr;
  204. case IntrinsicOp::IOP_InterlockedXor:
  205. case IntrinsicOp::MOP_InterlockedXor:
  206. return Op::OpAtomicXor;
  207. case IntrinsicOp::IOP_InterlockedUMax:
  208. case IntrinsicOp::MOP_InterlockedUMax:
  209. return Op::OpAtomicUMax;
  210. case IntrinsicOp::IOP_InterlockedUMin:
  211. case IntrinsicOp::MOP_InterlockedUMin:
  212. return Op::OpAtomicUMin;
  213. case IntrinsicOp::IOP_InterlockedMax:
  214. case IntrinsicOp::MOP_InterlockedMax:
  215. return Op::OpAtomicSMax;
  216. case IntrinsicOp::IOP_InterlockedMin:
  217. case IntrinsicOp::MOP_InterlockedMin:
  218. return Op::OpAtomicSMin;
  219. case IntrinsicOp::IOP_InterlockedExchange:
  220. case IntrinsicOp::MOP_InterlockedExchange:
  221. return Op::OpAtomicExchange;
  222. default:
  223. // Only atomic opcodes are relevant.
  224. break;
  225. }
  226. assert(false && "unimplemented hlsl intrinsic opcode");
  227. return Op::Max;
  228. }
  229. // Returns true if the given opcode is an accepted binary opcode in
  230. // OpSpecConstantOp.
  231. bool isAcceptedSpecConstantBinaryOp(spv::Op op) {
  232. switch (op) {
  233. case spv::Op::OpIAdd:
  234. case spv::Op::OpISub:
  235. case spv::Op::OpIMul:
  236. case spv::Op::OpUDiv:
  237. case spv::Op::OpSDiv:
  238. case spv::Op::OpUMod:
  239. case spv::Op::OpSRem:
  240. case spv::Op::OpSMod:
  241. case spv::Op::OpShiftRightLogical:
  242. case spv::Op::OpShiftRightArithmetic:
  243. case spv::Op::OpShiftLeftLogical:
  244. case spv::Op::OpBitwiseOr:
  245. case spv::Op::OpBitwiseXor:
  246. case spv::Op::OpBitwiseAnd:
  247. case spv::Op::OpVectorShuffle:
  248. case spv::Op::OpCompositeExtract:
  249. case spv::Op::OpCompositeInsert:
  250. case spv::Op::OpLogicalOr:
  251. case spv::Op::OpLogicalAnd:
  252. case spv::Op::OpLogicalNot:
  253. case spv::Op::OpLogicalEqual:
  254. case spv::Op::OpLogicalNotEqual:
  255. case spv::Op::OpIEqual:
  256. case spv::Op::OpINotEqual:
  257. case spv::Op::OpULessThan:
  258. case spv::Op::OpSLessThan:
  259. case spv::Op::OpUGreaterThan:
  260. case spv::Op::OpSGreaterThan:
  261. case spv::Op::OpULessThanEqual:
  262. case spv::Op::OpSLessThanEqual:
  263. case spv::Op::OpUGreaterThanEqual:
  264. case spv::Op::OpSGreaterThanEqual:
  265. return true;
  266. default:
  267. // Accepted binary opcodes return true. Anything else is false.
  268. return false;
  269. }
  270. return false;
  271. }
  272. /// Returns true if the given expression is an accepted initializer for a spec
  273. /// constant.
  274. bool isAcceptedSpecConstantInit(const Expr *init) {
  275. // Allow numeric casts
  276. init = init->IgnoreParenCasts();
  277. if (isa<CXXBoolLiteralExpr>(init) || isa<IntegerLiteral>(init) ||
  278. isa<FloatingLiteral>(init))
  279. return true;
  280. // Allow the minus operator which is used to specify negative values
  281. if (const auto *unaryOp = dyn_cast<UnaryOperator>(init))
  282. return unaryOp->getOpcode() == UO_Minus &&
  283. isAcceptedSpecConstantInit(unaryOp->getSubExpr());
  284. return false;
  285. }
  286. /// Returns true if the given function parameter can act as shader stage
  287. /// input parameter.
  288. inline bool canActAsInParmVar(const ParmVarDecl *param) {
  289. // If the parameter has no in/out/inout attribute, it is defaulted to
  290. // an in parameter.
  291. return !param->hasAttr<HLSLOutAttr>() &&
  292. // GS output streams are marked as inout, but it should not be
  293. // used as in parameter.
  294. !hlsl::IsHLSLStreamOutputType(param->getType());
  295. }
  296. /// Returns true if the given function parameter can act as shader stage
  297. /// output parameter.
  298. inline bool canActAsOutParmVar(const ParmVarDecl *param) {
  299. return param->hasAttr<HLSLOutAttr>() || param->hasAttr<HLSLInOutAttr>() ||
  300. hlsl::IsHLSLRayQueryType(param->getType());
  301. }
  302. /// Returns true if the given expression is of builtin type and can be evaluated
  303. /// to a constant zero. Returns false otherwise.
  304. inline bool evaluatesToConstZero(const Expr *expr, ASTContext &astContext) {
  305. const auto type = expr->getType();
  306. if (!type->isBuiltinType())
  307. return false;
  308. Expr::EvalResult evalResult;
  309. if (expr->EvaluateAsRValue(evalResult, astContext) &&
  310. !evalResult.HasSideEffects) {
  311. const auto &val = evalResult.Val;
  312. return ((type->isBooleanType() && !val.getInt().getBoolValue()) ||
  313. (type->isIntegerType() && !val.getInt().getBoolValue()) ||
  314. (type->isFloatingType() && val.getFloat().isZero()));
  315. }
  316. return false;
  317. }
  318. /// Returns the HLSLBufferDecl if the given VarDecl is inside a cbuffer/tbuffer.
  319. /// Returns nullptr otherwise, including varDecl is a ConstantBuffer or
  320. /// TextureBuffer itself.
  321. inline const HLSLBufferDecl *getCTBufferContext(const VarDecl *varDecl) {
  322. if (const auto *bufferDecl =
  323. dyn_cast<HLSLBufferDecl>(varDecl->getDeclContext()))
  324. // Filter ConstantBuffer/TextureBuffer
  325. if (!bufferDecl->isConstantBufferView())
  326. return bufferDecl;
  327. return nullptr;
  328. }
  329. /// Returns the real definition of the callee of the given CallExpr.
  330. ///
  331. /// If we are calling a forward-declared function, callee will be the
  332. /// FunctionDecl for the foward-declared function, not the actual
  333. /// definition. The foward-delcaration and defintion are two completely
  334. /// different AST nodes.
  335. inline const FunctionDecl *getCalleeDefinition(const CallExpr *expr) {
  336. const auto *callee = expr->getDirectCallee();
  337. if (callee->isThisDeclarationADefinition())
  338. return callee;
  339. // We need to update callee to the actual definition here
  340. if (!callee->isDefined(callee))
  341. return nullptr;
  342. return callee;
  343. }
  344. /// Returns the referenced definition. The given expr is expected to be a
  345. /// DeclRefExpr or CallExpr after ignoring casts. Returns nullptr otherwise.
  346. const DeclaratorDecl *getReferencedDef(const Expr *expr) {
  347. if (!expr)
  348. return nullptr;
  349. expr = expr->IgnoreParenCasts();
  350. if (const auto *declRefExpr = dyn_cast<DeclRefExpr>(expr)) {
  351. return dyn_cast_or_null<DeclaratorDecl>(declRefExpr->getDecl());
  352. }
  353. if (const auto *callExpr = dyn_cast<CallExpr>(expr)) {
  354. return getCalleeDefinition(callExpr);
  355. }
  356. return nullptr;
  357. }
  358. /// Returns the number of base classes if this type is a derived class/struct.
  359. /// Returns zero otherwise.
  360. inline uint32_t getNumBaseClasses(QualType type) {
  361. if (const auto *cxxDecl = type->getAsCXXRecordDecl())
  362. return cxxDecl->getNumBases();
  363. return 0;
  364. }
  365. /// Gets the index sequence of casting a derived object to a base object by
  366. /// following the cast chain.
  367. void getBaseClassIndices(const CastExpr *expr,
  368. llvm::SmallVectorImpl<uint32_t> *indices) {
  369. assert(expr->getCastKind() == CK_UncheckedDerivedToBase ||
  370. expr->getCastKind() == CK_HLSLDerivedToBase);
  371. indices->clear();
  372. QualType derivedType = expr->getSubExpr()->getType();
  373. const auto *derivedDecl = derivedType->getAsCXXRecordDecl();
  374. // Go through the base cast chain: for each of the derived to base cast, find
  375. // the index of the base in question in the derived's bases.
  376. for (auto pathIt = expr->path_begin(), pathIe = expr->path_end();
  377. pathIt != pathIe; ++pathIt) {
  378. // The type of the base in question
  379. const auto baseType = (*pathIt)->getType();
  380. uint32_t index = 0;
  381. for (auto baseIt = derivedDecl->bases_begin(),
  382. baseIe = derivedDecl->bases_end();
  383. baseIt != baseIe; ++baseIt, ++index)
  384. if (baseIt->getType() == baseType) {
  385. indices->push_back(index);
  386. break;
  387. }
  388. assert(index < derivedDecl->getNumBases());
  389. // Continue to proceed the next base in the chain
  390. derivedType = baseType;
  391. derivedDecl = derivedType->getAsCXXRecordDecl();
  392. }
  393. }
  394. std::string getNamespacePrefix(const Decl *decl) {
  395. std::string nsPrefix = "";
  396. const DeclContext *dc = decl->getDeclContext();
  397. while (dc && !dc->isTranslationUnit()) {
  398. if (const NamespaceDecl *ns = dyn_cast<NamespaceDecl>(dc)) {
  399. if (!ns->isAnonymousNamespace()) {
  400. nsPrefix = ns->getName().str() + "::" + nsPrefix;
  401. }
  402. }
  403. dc = dc->getParent();
  404. }
  405. return nsPrefix;
  406. }
  407. std::string getFnName(const FunctionDecl *fn) {
  408. // Prefix the function name with the struct name if necessary
  409. std::string classOrStructName = "";
  410. if (const auto *memberFn = dyn_cast<CXXMethodDecl>(fn))
  411. if (const auto *st = dyn_cast<CXXRecordDecl>(memberFn->getDeclContext()))
  412. classOrStructName = st->getName().str() + ".";
  413. return getNamespacePrefix(fn) + classOrStructName + fn->getName().str();
  414. }
  415. } // namespace
  416. SpirvEmitter::SpirvEmitter(CompilerInstance &ci)
  417. : theCompilerInstance(ci), astContext(ci.getASTContext()),
  418. diags(ci.getDiagnostics()),
  419. spirvOptions(ci.getCodeGenOpts().SpirvOptions),
  420. entryFunctionName(ci.getCodeGenOpts().HLSLEntryFunction), spvContext(),
  421. featureManager(diags, spirvOptions),
  422. spvBuilder(astContext, spvContext, spirvOptions),
  423. declIdMapper(astContext, spvContext, spvBuilder, *this, featureManager,
  424. spirvOptions),
  425. entryFunction(nullptr), curFunction(nullptr), curThis(nullptr),
  426. seenPushConstantAt(), isSpecConstantMode(false), needsLegalization(false),
  427. beforeHlslLegalization(false), mainSourceFile(nullptr) {
  428. // Get ShaderModel from command line hlsl profile option.
  429. const hlsl::ShaderModel *shaderModel =
  430. hlsl::ShaderModel::GetByName(ci.getCodeGenOpts().HLSLProfile.c_str());
  431. if (shaderModel->GetKind() == hlsl::ShaderModel::Kind::Invalid)
  432. emitError("unknown shader module: %0", {}) << shaderModel->GetName();
  433. if (spirvOptions.invertY && !shaderModel->IsVS() && !shaderModel->IsDS() &&
  434. !shaderModel->IsGS())
  435. emitError("-fvk-invert-y can only be used in VS/DS/GS", {});
  436. if (spirvOptions.useGlLayout && spirvOptions.useDxLayout)
  437. emitError("cannot specify both -fvk-use-dx-layout and -fvk-use-gl-layout",
  438. {});
  439. // Set shader model kind and hlsl major/minor version.
  440. spvContext.setCurrentShaderModelKind(shaderModel->GetKind());
  441. spvContext.setMajorVersion(shaderModel->GetMajor());
  442. spvContext.setMinorVersion(shaderModel->GetMinor());
  443. if (spirvOptions.useDxLayout) {
  444. spirvOptions.cBufferLayoutRule = SpirvLayoutRule::FxcCTBuffer;
  445. spirvOptions.tBufferLayoutRule = SpirvLayoutRule::FxcCTBuffer;
  446. spirvOptions.sBufferLayoutRule = SpirvLayoutRule::FxcSBuffer;
  447. spirvOptions.ampPayloadLayoutRule = SpirvLayoutRule::FxcSBuffer;
  448. } else if (spirvOptions.useGlLayout) {
  449. spirvOptions.cBufferLayoutRule = SpirvLayoutRule::GLSLStd140;
  450. spirvOptions.tBufferLayoutRule = SpirvLayoutRule::GLSLStd430;
  451. spirvOptions.sBufferLayoutRule = SpirvLayoutRule::GLSLStd430;
  452. spirvOptions.ampPayloadLayoutRule = SpirvLayoutRule::GLSLStd430;
  453. } else if (spirvOptions.useScalarLayout) {
  454. spirvOptions.cBufferLayoutRule = SpirvLayoutRule::Scalar;
  455. spirvOptions.tBufferLayoutRule = SpirvLayoutRule::Scalar;
  456. spirvOptions.sBufferLayoutRule = SpirvLayoutRule::Scalar;
  457. spirvOptions.ampPayloadLayoutRule = SpirvLayoutRule::Scalar;
  458. } else {
  459. spirvOptions.cBufferLayoutRule = SpirvLayoutRule::RelaxedGLSLStd140;
  460. spirvOptions.tBufferLayoutRule = SpirvLayoutRule::RelaxedGLSLStd430;
  461. spirvOptions.sBufferLayoutRule = SpirvLayoutRule::RelaxedGLSLStd430;
  462. spirvOptions.ampPayloadLayoutRule = SpirvLayoutRule::RelaxedGLSLStd430;
  463. }
  464. // Set shader module version, source file name, and source file content (if
  465. // needed).
  466. llvm::StringRef source = "";
  467. std::vector<llvm::StringRef> fileNames;
  468. const auto &inputFiles = ci.getFrontendOpts().Inputs;
  469. // File name
  470. if (spirvOptions.debugInfoFile && !inputFiles.empty()) {
  471. for (const auto &inputFile : inputFiles) {
  472. fileNames.push_back(inputFile.getFile());
  473. }
  474. }
  475. // Source code
  476. if (spirvOptions.debugInfoSource) {
  477. const auto &sm = ci.getSourceManager();
  478. const llvm::MemoryBuffer *mainFile =
  479. sm.getBuffer(sm.getMainFileID(), SourceLocation());
  480. source = StringRef(mainFile->getBufferStart(), mainFile->getBufferSize());
  481. }
  482. mainSourceFile = spvBuilder.setDebugSource(spvContext.getMajorVersion(),
  483. spvContext.getMinorVersion(),
  484. fileNames, source);
  485. if (spirvOptions.debugInfoTool &&
  486. spirvOptions.targetEnv.compare("vulkan1.1") >= 0) {
  487. // Emit OpModuleProcessed to indicate the commit information.
  488. std::string commitHash =
  489. std::string("dxc-commit-hash: ") + clang::getGitCommitHash();
  490. spvBuilder.addModuleProcessed(commitHash);
  491. // Emit OpModuleProcessed to indicate the command line options that were
  492. // used to generate this module.
  493. if (!spirvOptions.clOptions.empty()) {
  494. // Using this format: "dxc-cl-option: XXXXXX"
  495. std::string clOptionStr = "dxc-cl-option:" + spirvOptions.clOptions;
  496. spvBuilder.addModuleProcessed(clOptionStr);
  497. }
  498. }
  499. }
  500. void SpirvEmitter::HandleTranslationUnit(ASTContext &context) {
  501. // Stop translating if there are errors in previous compilation stages.
  502. if (context.getDiagnostics().hasErrorOccurred())
  503. return;
  504. TranslationUnitDecl *tu = context.getTranslationUnitDecl();
  505. uint32_t numEntryPoints = 0;
  506. // The entry function is the seed of the queue.
  507. for (auto *decl : tu->decls()) {
  508. if (auto *funcDecl = dyn_cast<FunctionDecl>(decl)) {
  509. if (spvContext.isLib()) {
  510. if (const auto *shaderAttr = funcDecl->getAttr<HLSLShaderAttr>()) {
  511. // If we are compiling as a library then add everything that has a
  512. // ShaderAttr.
  513. addFunctionToWorkQueue(getShaderModelKind(shaderAttr->getStage()),
  514. funcDecl, /*isEntryFunction*/ true);
  515. numEntryPoints++;
  516. }
  517. } else {
  518. if (funcDecl->getName() == entryFunctionName) {
  519. addFunctionToWorkQueue(spvContext.getCurrentShaderModelKind(),
  520. funcDecl, /*isEntryFunction*/ true);
  521. numEntryPoints++;
  522. }
  523. }
  524. } else {
  525. doDecl(decl);
  526. }
  527. if (context.getDiagnostics().hasErrorOccurred())
  528. return;
  529. }
  530. // Translate all functions reachable from the entry function.
  531. // The queue can grow in the meanwhile; so need to keep evaluating
  532. // workQueue.size().
  533. for (uint32_t i = 0; i < workQueue.size(); ++i) {
  534. const FunctionInfo *curEntryOrCallee = workQueue[i];
  535. spvContext.setCurrentShaderModelKind(curEntryOrCallee->shaderModelKind);
  536. doDecl(curEntryOrCallee->funcDecl);
  537. if (context.getDiagnostics().hasErrorOccurred())
  538. return;
  539. }
  540. const spv_target_env targetEnv = featureManager.getTargetEnv();
  541. // Addressing and memory model are required in a valid SPIR-V module.
  542. spvBuilder.setMemoryModel(spv::AddressingModel::Logical,
  543. spv::MemoryModel::GLSL450);
  544. // Even though the 'workQueue' grows due to the above loop, the first
  545. // 'numEntryPoints' entries in the 'workQueue' are the ones with the HLSL
  546. // 'shader' attribute, and must therefore be entry functions.
  547. assert(numEntryPoints <= workQueue.size());
  548. for (uint32_t i = 0; i < numEntryPoints; ++i) {
  549. // TODO: assign specific StageVars w.r.t. to entry point
  550. const FunctionInfo *entryInfo = workQueue[i];
  551. assert(entryInfo->isEntryFunction);
  552. spvBuilder.addEntryPoint(
  553. getSpirvShaderStage(entryInfo->shaderModelKind),
  554. entryInfo->entryFunction, entryInfo->funcDecl->getName(),
  555. targetEnv == SPV_ENV_VULKAN_1_2
  556. ? spvBuilder.getModule()->getVariables()
  557. : llvm::ArrayRef<SpirvVariable *>(declIdMapper.collectStageVars()));
  558. }
  559. // Add Location decorations to stage input/output variables.
  560. if (!declIdMapper.decorateStageIOLocations())
  561. return;
  562. // Add descriptor set and binding decorations to resource variables.
  563. if (!declIdMapper.decorateResourceBindings())
  564. return;
  565. // Output the constructed module.
  566. std::vector<uint32_t> m = spvBuilder.takeModule();
  567. if (!spirvOptions.codeGenHighLevel) {
  568. // In order to flatten resource arrays, we must also unroll loops. Therefore
  569. // we should run legalization before optimization.
  570. needsLegalization = needsLegalization || spirvOptions.flattenResourceArrays;
  571. // Run legalization passes
  572. if (needsLegalization || declIdMapper.requiresLegalization()) {
  573. std::string messages;
  574. if (!spirvToolsLegalize(targetEnv, &m, &messages)) {
  575. emitFatalError("failed to legalize SPIR-V: %0", {}) << messages;
  576. emitNote("please file a bug report on "
  577. "https://github.com/Microsoft/DirectXShaderCompiler/issues "
  578. "with source code if possible",
  579. {});
  580. return;
  581. } else if (!messages.empty()) {
  582. emitWarning("SPIR-V legalization: %0", {}) << messages;
  583. }
  584. }
  585. // Run optimization passes
  586. if (theCompilerInstance.getCodeGenOpts().OptimizationLevel > 0) {
  587. std::string messages;
  588. if (!spirvToolsOptimize(targetEnv, &m, spirvOptions, &messages)) {
  589. emitFatalError("failed to optimize SPIR-V: %0", {}) << messages;
  590. emitNote("please file a bug report on "
  591. "https://github.com/Microsoft/DirectXShaderCompiler/issues "
  592. "with source code if possible",
  593. {});
  594. return;
  595. }
  596. }
  597. }
  598. // Validate the generated SPIR-V code
  599. if (!spirvOptions.disableValidation) {
  600. std::string messages;
  601. if (!spirvToolsValidate(targetEnv, spirvOptions,
  602. needsLegalization ||
  603. declIdMapper.requiresLegalization(),
  604. &m, &messages)) {
  605. emitFatalError("generated SPIR-V is invalid: %0", {}) << messages;
  606. emitNote("please file a bug report on "
  607. "https://github.com/Microsoft/DirectXShaderCompiler/issues "
  608. "with source code if possible",
  609. {});
  610. return;
  611. }
  612. }
  613. theCompilerInstance.getOutStream()->write(
  614. reinterpret_cast<const char *>(m.data()), m.size() * 4);
  615. }
  616. void SpirvEmitter::doDecl(const Decl *decl) {
  617. if (isa<EmptyDecl>(decl) || isa<TypedefDecl>(decl))
  618. return;
  619. if (decl->isImplicit()) {
  620. doImplicitDecl(decl);
  621. return;
  622. }
  623. if (const auto *varDecl = dyn_cast<VarDecl>(decl)) {
  624. // We can have VarDecls inside cbuffer/tbuffer. For those VarDecls, we need
  625. // to emit their cbuffer/tbuffer as a whole and access each individual one
  626. // using access chains.
  627. if (const auto *bufferDecl = getCTBufferContext(varDecl)) {
  628. doHLSLBufferDecl(bufferDecl);
  629. } else {
  630. doVarDecl(varDecl);
  631. }
  632. } else if (const auto *namespaceDecl = dyn_cast<NamespaceDecl>(decl)) {
  633. for (auto *subDecl : namespaceDecl->decls())
  634. // Note: We only emit functions as they are discovered through the call
  635. // graph starting from the entry-point. We should not emit unused
  636. // functions inside namespaces.
  637. if (!isa<FunctionDecl>(subDecl))
  638. doDecl(subDecl);
  639. } else if (const auto *funcDecl = dyn_cast<FunctionDecl>(decl)) {
  640. doFunctionDecl(funcDecl);
  641. } else if (const auto *bufferDecl = dyn_cast<HLSLBufferDecl>(decl)) {
  642. doHLSLBufferDecl(bufferDecl);
  643. } else if (const auto *recordDecl = dyn_cast<RecordDecl>(decl)) {
  644. doRecordDecl(recordDecl);
  645. } else if (const auto *enumDecl = dyn_cast<EnumDecl>(decl)) {
  646. doEnumDecl(enumDecl);
  647. } else {
  648. emitError("decl type %0 unimplemented", decl->getLocation())
  649. << decl->getDeclKindName();
  650. }
  651. }
  652. void SpirvEmitter::doStmt(const Stmt *stmt,
  653. llvm::ArrayRef<const Attr *> attrs) {
  654. if (const auto *compoundStmt = dyn_cast<CompoundStmt>(stmt)) {
  655. for (auto *st : compoundStmt->body())
  656. doStmt(st);
  657. } else if (const auto *retStmt = dyn_cast<ReturnStmt>(stmt)) {
  658. doReturnStmt(retStmt);
  659. } else if (const auto *declStmt = dyn_cast<DeclStmt>(stmt)) {
  660. doDeclStmt(declStmt);
  661. } else if (const auto *ifStmt = dyn_cast<IfStmt>(stmt)) {
  662. doIfStmt(ifStmt, attrs);
  663. } else if (const auto *switchStmt = dyn_cast<SwitchStmt>(stmt)) {
  664. doSwitchStmt(switchStmt, attrs);
  665. } else if (dyn_cast<CaseStmt>(stmt)) {
  666. processCaseStmtOrDefaultStmt(stmt);
  667. } else if (dyn_cast<DefaultStmt>(stmt)) {
  668. processCaseStmtOrDefaultStmt(stmt);
  669. } else if (const auto *breakStmt = dyn_cast<BreakStmt>(stmt)) {
  670. doBreakStmt(breakStmt);
  671. } else if (const auto *theDoStmt = dyn_cast<DoStmt>(stmt)) {
  672. doDoStmt(theDoStmt, attrs);
  673. } else if (const auto *discardStmt = dyn_cast<DiscardStmt>(stmt)) {
  674. doDiscardStmt(discardStmt);
  675. } else if (const auto *continueStmt = dyn_cast<ContinueStmt>(stmt)) {
  676. doContinueStmt(continueStmt);
  677. } else if (const auto *whileStmt = dyn_cast<WhileStmt>(stmt)) {
  678. doWhileStmt(whileStmt, attrs);
  679. } else if (const auto *forStmt = dyn_cast<ForStmt>(stmt)) {
  680. doForStmt(forStmt, attrs);
  681. } else if (dyn_cast<NullStmt>(stmt)) {
  682. // For the null statement ";". We don't need to do anything.
  683. } else if (const auto *expr = dyn_cast<Expr>(stmt)) {
  684. // All cases for expressions used as statements
  685. doExpr(expr);
  686. } else if (const auto *attrStmt = dyn_cast<AttributedStmt>(stmt)) {
  687. doStmt(attrStmt->getSubStmt(), attrStmt->getAttrs());
  688. } else {
  689. emitError("statement class '%0' unimplemented", stmt->getLocStart())
  690. << stmt->getStmtClassName() << stmt->getSourceRange();
  691. }
  692. }
  693. SpirvInstruction *SpirvEmitter::doExpr(const Expr *expr) {
  694. SpirvInstruction *result = nullptr;
  695. expr = expr->IgnoreParens();
  696. if (const auto *declRefExpr = dyn_cast<DeclRefExpr>(expr)) {
  697. result = declIdMapper.getDeclEvalInfo(declRefExpr->getDecl(),
  698. expr->getLocStart());
  699. } else if (const auto *memberExpr = dyn_cast<MemberExpr>(expr)) {
  700. result = doMemberExpr(memberExpr);
  701. } else if (const auto *castExpr = dyn_cast<CastExpr>(expr)) {
  702. result = doCastExpr(castExpr);
  703. } else if (const auto *initListExpr = dyn_cast<InitListExpr>(expr)) {
  704. result = doInitListExpr(initListExpr);
  705. } else if (const auto *boolLiteral = dyn_cast<CXXBoolLiteralExpr>(expr)) {
  706. result =
  707. spvBuilder.getConstantBool(boolLiteral->getValue(), isSpecConstantMode);
  708. result->setRValue();
  709. } else if (const auto *intLiteral = dyn_cast<IntegerLiteral>(expr)) {
  710. result = translateAPInt(intLiteral->getValue(), expr->getType());
  711. result->setRValue();
  712. } else if (const auto *floatLiteral = dyn_cast<FloatingLiteral>(expr)) {
  713. result = translateAPFloat(floatLiteral->getValue(), expr->getType());
  714. result->setRValue();
  715. } else if (const auto *stringLiteral = dyn_cast<StringLiteral>(expr)) {
  716. result = spvBuilder.getString(stringLiteral->getString());
  717. } else if (const auto *compoundAssignOp =
  718. dyn_cast<CompoundAssignOperator>(expr)) {
  719. // CompoundAssignOperator is a subclass of BinaryOperator. It should be
  720. // checked before BinaryOperator.
  721. result = doCompoundAssignOperator(compoundAssignOp);
  722. } else if (const auto *binOp = dyn_cast<BinaryOperator>(expr)) {
  723. result = doBinaryOperator(binOp);
  724. } else if (const auto *unaryOp = dyn_cast<UnaryOperator>(expr)) {
  725. result = doUnaryOperator(unaryOp);
  726. } else if (const auto *vecElemExpr = dyn_cast<HLSLVectorElementExpr>(expr)) {
  727. result = doHLSLVectorElementExpr(vecElemExpr);
  728. } else if (const auto *matElemExpr = dyn_cast<ExtMatrixElementExpr>(expr)) {
  729. result = doExtMatrixElementExpr(matElemExpr);
  730. } else if (const auto *funcCall = dyn_cast<CallExpr>(expr)) {
  731. result = doCallExpr(funcCall);
  732. } else if (const auto *subscriptExpr = dyn_cast<ArraySubscriptExpr>(expr)) {
  733. result = doArraySubscriptExpr(subscriptExpr);
  734. } else if (const auto *condExpr = dyn_cast<ConditionalOperator>(expr)) {
  735. result = doConditionalOperator(condExpr);
  736. } else if (const auto *defaultArgExpr = dyn_cast<CXXDefaultArgExpr>(expr)) {
  737. result = doExpr(defaultArgExpr->getParam()->getDefaultArg());
  738. } else if (isa<CXXThisExpr>(expr)) {
  739. assert(curThis);
  740. result = curThis;
  741. } else if (isa<CXXConstructExpr>(expr)) {
  742. result = curThis;
  743. } else {
  744. emitError("expression class '%0' unimplemented", expr->getExprLoc())
  745. << expr->getStmtClassName() << expr->getSourceRange();
  746. }
  747. return result;
  748. }
  749. SpirvInstruction *SpirvEmitter::loadIfGLValue(const Expr *expr) {
  750. // We are trying to load the value here, which is what an LValueToRValue
  751. // implicit cast is intended to do. We can ignore the cast if exists.
  752. expr = expr->IgnoreParenLValueCasts();
  753. return loadIfGLValue(expr, doExpr(expr));
  754. }
  755. SpirvInstruction *SpirvEmitter::loadIfGLValue(const Expr *expr,
  756. SpirvInstruction *info) {
  757. const auto exprType = expr->getType();
  758. // Do nothing if this is already rvalue
  759. if (!info || info->isRValue())
  760. return info;
  761. // Check whether we are trying to load an array of opaque objects as a whole.
  762. // If true, we are likely to copy it as a whole. To assist per-element
  763. // copying, avoid the load here and return the pointer directly.
  764. // TODO: consider moving this hack into SPIRV-Tools as a transformation.
  765. if (isOpaqueArrayType(exprType))
  766. return info;
  767. // Check whether we are trying to load an externally visible structured/byte
  768. // buffer as a whole. If true, it means we are creating alias for it. Avoid
  769. // the load and write the pointer directly to the alias variable then.
  770. //
  771. // Also for the case of alias function returns. If we are trying to load an
  772. // alias function return as a whole, it means we are assigning it to another
  773. // alias variable. Avoid the load and write the pointer directly.
  774. //
  775. // Note: legalization specific code
  776. if (isReferencingNonAliasStructuredOrByteBuffer(expr)) {
  777. return info;
  778. }
  779. if (loadIfAliasVarRef(expr, &info)) {
  780. // We are loading an alias variable as a whole here. This is likely for
  781. // wholesale assignments or function returns. Need to load the pointer.
  782. //
  783. // Note: legalization specific code
  784. return info;
  785. }
  786. SpirvInstruction *loadedInstr = nullptr;
  787. // TODO: Ouch. Very hacky. We need special path to get the value type if
  788. // we are loading a whole ConstantBuffer/TextureBuffer since the normal
  789. // type translation path won't work.
  790. if (const auto *declContext = isConstantTextureBufferDeclRef(expr)) {
  791. loadedInstr = spvBuilder.createLoad(
  792. declIdMapper.getCTBufferPushConstantType(declContext), info,
  793. expr->getExprLoc());
  794. } else {
  795. loadedInstr = spvBuilder.createLoad(exprType, info, expr->getExprLoc());
  796. }
  797. assert(loadedInstr);
  798. // Special-case: According to the SPIR-V Spec: There is no physical size or
  799. // bit pattern defined for boolean type. Therefore an unsigned integer is used
  800. // to represent booleans when layout is required. In such cases, after loading
  801. // the uint, we should perform a comparison.
  802. {
  803. uint32_t vecSize = 1, numRows = 0, numCols = 0;
  804. if (info->getLayoutRule() != SpirvLayoutRule::Void &&
  805. isBoolOrVecMatOfBoolType(exprType)) {
  806. QualType uintType = astContext.UnsignedIntTy;
  807. if (isScalarType(exprType) || isVectorType(exprType, nullptr, &vecSize)) {
  808. const auto fromType =
  809. vecSize == 1 ? uintType
  810. : astContext.getExtVectorType(uintType, vecSize);
  811. loadedInstr =
  812. castToBool(loadedInstr, fromType, exprType, expr->getLocStart());
  813. } else {
  814. const bool isMat = isMxNMatrix(exprType, nullptr, &numRows, &numCols);
  815. assert(isMat);
  816. (void)isMat;
  817. const clang::Type *type = exprType.getCanonicalType().getTypePtr();
  818. const RecordType *RT = cast<RecordType>(type);
  819. const ClassTemplateSpecializationDecl *templateSpecDecl =
  820. cast<ClassTemplateSpecializationDecl>(RT->getDecl());
  821. ClassTemplateDecl *templateDecl =
  822. templateSpecDecl->getSpecializedTemplate();
  823. const auto fromType = getHLSLMatrixType(
  824. astContext, theCompilerInstance.getSema(), templateDecl,
  825. astContext.UnsignedIntTy, numRows, numCols);
  826. loadedInstr =
  827. castToBool(loadedInstr, fromType, exprType, expr->getLocStart());
  828. }
  829. // Now that it is converted to Bool, it has no layout rule.
  830. // This result-id should be evaluated as bool from here on out.
  831. loadedInstr->setLayoutRule(SpirvLayoutRule::Void);
  832. }
  833. }
  834. loadedInstr->setRValue();
  835. return loadedInstr;
  836. }
  837. SpirvInstruction *SpirvEmitter::loadIfAliasVarRef(const Expr *expr) {
  838. auto *instr = doExpr(expr);
  839. loadIfAliasVarRef(expr, &instr);
  840. return instr;
  841. }
  842. bool SpirvEmitter::loadIfAliasVarRef(const Expr *varExpr,
  843. SpirvInstruction **instr) {
  844. assert(instr);
  845. if ((*instr) && (*instr)->containsAliasComponent() &&
  846. isAKindOfStructuredOrByteBuffer(varExpr->getType())) {
  847. // Load the pointer of the aliased-to-variable if the expression has a
  848. // pointer to pointer type.
  849. if (varExpr->isGLValue()) {
  850. *instr = spvBuilder.createLoad(varExpr->getType(), *instr,
  851. varExpr->getExprLoc());
  852. }
  853. return true;
  854. }
  855. return false;
  856. }
  857. SpirvInstruction *SpirvEmitter::castToType(SpirvInstruction *value,
  858. QualType fromType, QualType toType,
  859. SourceLocation srcLoc) {
  860. if (isFloatOrVecMatOfFloatType(toType))
  861. return castToFloat(value, fromType, toType, srcLoc);
  862. // Order matters here. Bool (vector) values will also be considered as uint
  863. // (vector) values. So given a bool (vector) argument, isUintOrVecOfUintType()
  864. // will also return true. We need to check bool before uint. The opposite is
  865. // not true.
  866. if (isBoolOrVecMatOfBoolType(toType))
  867. return castToBool(value, fromType, toType, srcLoc);
  868. if (isSintOrVecMatOfSintType(toType) || isUintOrVecMatOfUintType(toType))
  869. return castToInt(value, fromType, toType, srcLoc);
  870. emitError("casting to type %0 unimplemented", {}) << toType;
  871. return nullptr;
  872. }
  873. void SpirvEmitter::doFunctionDecl(const FunctionDecl *decl) {
  874. assert(decl->isThisDeclarationADefinition());
  875. // A RAII class for maintaining the current function under traversal.
  876. class FnEnvRAII {
  877. public:
  878. // Creates a new instance which sets fnEnv to the newFn on creation,
  879. // and resets fnEnv to its original value on destruction.
  880. FnEnvRAII(const FunctionDecl **fnEnv, const FunctionDecl *newFn)
  881. : oldFn(*fnEnv), fnSlot(fnEnv) {
  882. *fnEnv = newFn;
  883. }
  884. ~FnEnvRAII() { *fnSlot = oldFn; }
  885. private:
  886. const FunctionDecl *oldFn;
  887. const FunctionDecl **fnSlot;
  888. };
  889. FnEnvRAII fnEnvRAII(&curFunction, decl);
  890. // We are about to start translation for a new function. Clear the break stack
  891. // and the continue stack.
  892. breakStack = std::stack<SpirvBasicBlock *>();
  893. continueStack = std::stack<SpirvBasicBlock *>();
  894. // This will allow the entry-point name to be something like
  895. // myNamespace::myEntrypointFunc.
  896. std::string funcName = getFnName(decl);
  897. SpirvFunction *func = declIdMapper.getOrRegisterFn(decl);
  898. const auto iter = functionInfoMap.find(decl);
  899. if (iter != functionInfoMap.end()) {
  900. const auto &entryInfo = iter->second;
  901. if (entryInfo->isEntryFunction) {
  902. funcName = "src." + funcName;
  903. // Create wrapper for the entry function
  904. if (!emitEntryFunctionWrapper(decl, func))
  905. return;
  906. }
  907. }
  908. const QualType retType =
  909. declIdMapper.getTypeAndCreateCounterForPotentialAliasVar(decl);
  910. // Construct the function signature.
  911. llvm::SmallVector<QualType, 4> paramTypes;
  912. bool isNonStaticMemberFn = false;
  913. if (const auto *memberFn = dyn_cast<CXXMethodDecl>(decl)) {
  914. isNonStaticMemberFn = !memberFn->isStatic();
  915. if (isNonStaticMemberFn) {
  916. // For non-static member function, the first parameter should be the
  917. // object on which we are invoking this method.
  918. const QualType valueType =
  919. memberFn->getThisType(astContext)->getPointeeType();
  920. paramTypes.push_back(valueType);
  921. }
  922. }
  923. for (const auto *param : decl->params()) {
  924. const QualType valueType =
  925. declIdMapper.getTypeAndCreateCounterForPotentialAliasVar(param);
  926. paramTypes.push_back(valueType);
  927. }
  928. spvBuilder.beginFunction(retType, paramTypes, decl->getLocStart(), funcName,
  929. decl->hasAttr<HLSLPreciseAttr>(), func);
  930. if (isNonStaticMemberFn) {
  931. // Remember the parameter for the 'this' object so later we can handle
  932. // CXXThisExpr correctly.
  933. curThis = spvBuilder.addFnParam(paramTypes[0], /*isPrecise*/ false,
  934. decl->getLocStart(), "param.this");
  935. if (isOrContainsAKindOfStructuredOrByteBuffer(paramTypes[0])) {
  936. curThis->setContainsAliasComponent(true);
  937. needsLegalization = true;
  938. }
  939. }
  940. // Create all parameters.
  941. for (uint32_t i = 0; i < decl->getNumParams(); ++i) {
  942. const ParmVarDecl *paramDecl = decl->getParamDecl(i);
  943. (void)declIdMapper.createFnParam(paramDecl);
  944. }
  945. if (decl->hasBody()) {
  946. // The entry basic block.
  947. auto *entryLabel = spvBuilder.createBasicBlock("bb.entry");
  948. spvBuilder.setInsertPoint(entryLabel);
  949. // Process all statments in the body.
  950. doStmt(decl->getBody());
  951. // We have processed all Stmts in this function and now in the last
  952. // basic block. Make sure we have a termination instruction.
  953. if (!spvBuilder.isCurrentBasicBlockTerminated()) {
  954. const auto retType = decl->getReturnType();
  955. const auto returnLoc = decl->getBody()->getLocEnd();
  956. if (retType->isVoidType()) {
  957. spvBuilder.createReturn(returnLoc);
  958. } else {
  959. // If the source code does not provide a proper return value for some
  960. // control flow path, it's undefined behavior. We just return null
  961. // value here.
  962. spvBuilder.createReturnValue(spvBuilder.getConstantNull(retType),
  963. returnLoc);
  964. }
  965. }
  966. }
  967. spvBuilder.endFunction();
  968. }
  969. bool SpirvEmitter::validateVKAttributes(const NamedDecl *decl) {
  970. bool success = true;
  971. if (const auto *varDecl = dyn_cast<VarDecl>(decl)) {
  972. const auto varType = varDecl->getType();
  973. if ((isSubpassInput(varType) || isSubpassInputMS(varType)) &&
  974. !varDecl->hasAttr<VKInputAttachmentIndexAttr>()) {
  975. emitError("missing vk::input_attachment_index attribute",
  976. varDecl->getLocation());
  977. success = false;
  978. }
  979. }
  980. if (decl->getAttr<VKInputAttachmentIndexAttr>()) {
  981. if (!spvContext.isPS()) {
  982. emitError("SubpassInput(MS) only allowed in pixel shader",
  983. decl->getLocation());
  984. success = false;
  985. }
  986. if (!decl->isExternallyVisible()) {
  987. emitError("SubpassInput(MS) must be externally visible",
  988. decl->getLocation());
  989. success = false;
  990. }
  991. // We only allow VKInputAttachmentIndexAttr to be attached to global
  992. // variables. So it should be fine to cast here.
  993. const auto elementType =
  994. hlsl::GetHLSLResourceResultType(cast<VarDecl>(decl)->getType());
  995. if (!isScalarType(elementType) && !isVectorType(elementType)) {
  996. emitError(
  997. "only scalar/vector types allowed as SubpassInput(MS) parameter type",
  998. decl->getLocation());
  999. // Return directly to avoid further type processing, which will hit
  1000. // asserts when lowering the type.
  1001. return false;
  1002. }
  1003. }
  1004. // The frontend will make sure that
  1005. // * vk::push_constant applies to global variables of struct type
  1006. // * vk::binding applies to global variables or cbuffers/tbuffers
  1007. // * vk::counter_binding applies to global variables of RW/Append/Consume
  1008. // StructuredBuffer
  1009. // * vk::location applies to function parameters/returns and struct fields
  1010. // So the only case we need to check co-existence is vk::push_constant and
  1011. // vk::binding.
  1012. if (const auto *pcAttr = decl->getAttr<VKPushConstantAttr>()) {
  1013. const auto loc = pcAttr->getLocation();
  1014. if (seenPushConstantAt.isInvalid()) {
  1015. seenPushConstantAt = loc;
  1016. } else {
  1017. // TODO: Actually this is slightly incorrect. The Vulkan spec says:
  1018. // There must be no more than one push constant block statically used
  1019. // per shader entry point.
  1020. // But we are checking whether there are more than one push constant
  1021. // blocks defined. Tracking usage requires more work.
  1022. emitError("cannot have more than one push constant block", loc);
  1023. emitNote("push constant block previously defined here",
  1024. seenPushConstantAt);
  1025. success = false;
  1026. }
  1027. if (decl->hasAttr<VKBindingAttr>()) {
  1028. emitError("vk::push_constant attribute cannot be used together with "
  1029. "vk::binding attribute",
  1030. loc);
  1031. success = false;
  1032. }
  1033. }
  1034. // vk::shader_record_nv is supported only on cbuffer/ConstantBuffer
  1035. if (const auto *srbAttr = decl->getAttr<VKShaderRecordNVAttr>()) {
  1036. const auto loc = srbAttr->getLocation();
  1037. const HLSLBufferDecl *bufDecl = nullptr;
  1038. bool isValidType = false;
  1039. if (bufDecl = dyn_cast<HLSLBufferDecl>(decl))
  1040. isValidType = bufDecl->isCBuffer();
  1041. else if (bufDecl = dyn_cast<HLSLBufferDecl>(decl->getDeclContext()))
  1042. isValidType = bufDecl->isCBuffer();
  1043. if (!isValidType) {
  1044. emitError(
  1045. "vk::shader_record_nv can be applied only to cbuffer/ConstantBuffer",
  1046. loc);
  1047. success = false;
  1048. }
  1049. if (decl->hasAttr<VKBindingAttr>()) {
  1050. emitError("vk::shader_record_nv attribute cannot be used together with "
  1051. "vk::binding attribute",
  1052. loc);
  1053. success = false;
  1054. }
  1055. }
  1056. return success;
  1057. }
  1058. void SpirvEmitter::doHLSLBufferDecl(const HLSLBufferDecl *bufferDecl) {
  1059. // This is a cbuffer/tbuffer decl.
  1060. // Check and emit warnings for member intializers which are not
  1061. // supported in Vulkan
  1062. for (const auto *member : bufferDecl->decls()) {
  1063. if (const auto *varMember = dyn_cast<VarDecl>(member)) {
  1064. if (!spirvOptions.noWarnIgnoredFeatures) {
  1065. if (const auto *init = varMember->getInit())
  1066. emitWarning("%select{tbuffer|cbuffer}0 member initializer "
  1067. "ignored since no Vulkan equivalent",
  1068. init->getExprLoc())
  1069. << bufferDecl->isCBuffer() << init->getSourceRange();
  1070. }
  1071. // We cannot handle external initialization of column-major matrices now.
  1072. if (isOrContainsNonFpColMajorMatrix(astContext, spirvOptions,
  1073. varMember->getType(), varMember)) {
  1074. emitError("externally initialized non-floating-point column-major "
  1075. "matrices not supported yet",
  1076. varMember->getLocation());
  1077. }
  1078. }
  1079. }
  1080. if (!validateVKAttributes(bufferDecl))
  1081. return;
  1082. if (bufferDecl->hasAttr<VKShaderRecordNVAttr>()) {
  1083. (void)declIdMapper.createShaderRecordBufferNV(bufferDecl);
  1084. } else {
  1085. (void)declIdMapper.createCTBuffer(bufferDecl);
  1086. }
  1087. }
  1088. void SpirvEmitter::doImplicitDecl(const Decl *decl) {
  1089. // We only handle specific implicit declaration for raytracing
  1090. // which are RayFlag/HitKind constant unsigned integers
  1091. // Ignore others
  1092. if (spvContext.isLib() || spvContext.isRay()) {
  1093. const VarDecl *implDecl = dyn_cast<VarDecl>(decl);
  1094. if (implDecl && (implDecl->getName().startswith(StringRef("RAY_FLAG")) ||
  1095. implDecl->getName().startswith(StringRef("HIT_KIND")))) {
  1096. (void)declIdMapper.createRayTracingNVImplicitVar(implDecl);
  1097. }
  1098. }
  1099. }
  1100. void SpirvEmitter::doRecordDecl(const RecordDecl *recordDecl) {
  1101. // Ignore implict records
  1102. // Somehow we'll have implicit records with:
  1103. // static const int Length = count;
  1104. // that can mess up with the normal CodeGen.
  1105. if (recordDecl->isImplicit())
  1106. return;
  1107. // Handle each static member with inline initializer.
  1108. // Each static member has a corresponding VarDecl inside the
  1109. // RecordDecl. For those defined in the translation unit,
  1110. // their VarDecls do not have initializer.
  1111. for (auto *subDecl : recordDecl->decls())
  1112. if (auto *varDecl = dyn_cast<VarDecl>(subDecl))
  1113. if (varDecl->isStaticDataMember() && varDecl->hasInit())
  1114. doVarDecl(varDecl);
  1115. }
  1116. void SpirvEmitter::doEnumDecl(const EnumDecl *decl) {
  1117. for (auto it = decl->enumerator_begin(); it != decl->enumerator_end(); ++it)
  1118. declIdMapper.createEnumConstant(*it);
  1119. }
  1120. void SpirvEmitter::doVarDecl(const VarDecl *decl) {
  1121. if (!validateVKAttributes(decl))
  1122. return;
  1123. // HLSL has the 'string' type which can be used for rare purposes such as
  1124. // printf (SPIR-V's DebugPrintf). SPIR-V does not have a 'char' or 'string'
  1125. // type, and therefore any variable of such type should not be created.
  1126. // DeclResultIdMapper maps such decl to an OpString instruction that
  1127. // represents the variable's initializer literal.
  1128. if (isStringType(decl->getType())) {
  1129. declIdMapper.createOrUpdateStringVar(decl);
  1130. return;
  1131. }
  1132. // We cannot handle external initialization of column-major matrices now.
  1133. if (isExternalVar(decl) &&
  1134. isOrContainsNonFpColMajorMatrix(astContext, spirvOptions, decl->getType(),
  1135. decl)) {
  1136. emitError("externally initialized non-floating-point column-major "
  1137. "matrices not supported yet",
  1138. decl->getLocation());
  1139. }
  1140. // Reject arrays of RW/append/consume structured buffers. They have assoicated
  1141. // counters, which are quite nasty to handle.
  1142. if (decl->getType()->isArrayType()) {
  1143. auto type = decl->getType();
  1144. do {
  1145. type = type->getAsArrayTypeUnsafe()->getElementType();
  1146. } while (type->isArrayType());
  1147. if (isRWAppendConsumeSBuffer(type)) {
  1148. emitError("arrays of RW/append/consume structured buffers unsupported",
  1149. decl->getLocation());
  1150. return;
  1151. }
  1152. }
  1153. if (decl->hasAttr<VKConstantIdAttr>()) {
  1154. // This is a VarDecl for specialization constant.
  1155. createSpecConstant(decl);
  1156. return;
  1157. }
  1158. if (decl->hasAttr<VKPushConstantAttr>()) {
  1159. // This is a VarDecl for PushConstant block.
  1160. (void)declIdMapper.createPushConstant(decl);
  1161. return;
  1162. }
  1163. if (decl->hasAttr<VKShaderRecordNVAttr>()) {
  1164. (void)declIdMapper.createShaderRecordBufferNV(decl);
  1165. return;
  1166. }
  1167. if (isa<HLSLBufferDecl>(decl->getDeclContext())) {
  1168. // This is a VarDecl of a ConstantBuffer/TextureBuffer type.
  1169. (void)declIdMapper.createCTBuffer(decl);
  1170. return;
  1171. }
  1172. SpirvVariable *var = nullptr;
  1173. // The contents in externally visible variables can be updated via the
  1174. // pipeline. They should be handled differently from file and function scope
  1175. // variables.
  1176. // File scope variables (static "global" and "local" variables) belongs to
  1177. // the Private storage class, while function scope variables (normal "local"
  1178. // variables) belongs to the Function storage class.
  1179. if (isExternalVar(decl)) {
  1180. var = declIdMapper.createExternVar(decl);
  1181. } else {
  1182. // We already know the variable is not externally visible here. If it does
  1183. // not have local storage, it should be file scope variable.
  1184. const bool isFileScopeVar = !decl->hasLocalStorage();
  1185. if (isFileScopeVar)
  1186. var = declIdMapper.createFileVar(decl, llvm::None);
  1187. else
  1188. var = declIdMapper.createFnVar(decl, llvm::None);
  1189. // Emit OpStore to initialize the variable
  1190. // TODO: revert back to use OpVariable initializer
  1191. // We should only evaluate the initializer once for a static variable.
  1192. if (isFileScopeVar) {
  1193. if (decl->isStaticLocal()) {
  1194. initOnce(decl->getType(), decl->getName(), var, decl->getInit());
  1195. } else {
  1196. // Defer to initialize these global variables at the beginning of the
  1197. // entry function.
  1198. toInitGloalVars.push_back(decl);
  1199. }
  1200. }
  1201. // Function local variables. Just emit OpStore at the current insert point.
  1202. else if (const Expr *init = decl->getInit()) {
  1203. if (auto *constInit = tryToEvaluateAsConst(init)) {
  1204. spvBuilder.createStore(var, constInit, decl->getLocation());
  1205. } else {
  1206. storeValue(var, loadIfGLValue(init), decl->getType(),
  1207. decl->getLocation());
  1208. }
  1209. // Update counter variable associated with local variables
  1210. tryToAssignCounterVar(decl, init);
  1211. }
  1212. // Variables that are not externally visible and of opaque types should
  1213. // request legalization.
  1214. if (!needsLegalization && isOpaqueType(decl->getType()))
  1215. needsLegalization = true;
  1216. }
  1217. // All variables that are of opaque struct types should request legalization.
  1218. if (!needsLegalization && isOpaqueStructType(decl->getType()))
  1219. needsLegalization = true;
  1220. }
  1221. spv::LoopControlMask SpirvEmitter::translateLoopAttribute(const Stmt *stmt,
  1222. const Attr &attr) {
  1223. switch (attr.getKind()) {
  1224. case attr::HLSLLoop:
  1225. case attr::HLSLFastOpt:
  1226. return spv::LoopControlMask::DontUnroll;
  1227. case attr::HLSLUnroll:
  1228. return spv::LoopControlMask::Unroll;
  1229. case attr::HLSLAllowUAVCondition:
  1230. if (!spirvOptions.noWarnIgnoredFeatures) {
  1231. emitWarning("unsupported allow_uav_condition attribute ignored",
  1232. stmt->getLocStart());
  1233. }
  1234. break;
  1235. default:
  1236. llvm_unreachable("found unknown loop attribute");
  1237. }
  1238. return spv::LoopControlMask::MaskNone;
  1239. }
  1240. void SpirvEmitter::doDiscardStmt(const DiscardStmt *discardStmt) {
  1241. assert(!spvBuilder.isCurrentBasicBlockTerminated());
  1242. // The discard statement can only be called from a pixel shader
  1243. if (!spvContext.isPS()) {
  1244. emitError("discard statement may only be used in pixel shaders",
  1245. discardStmt->getLoc());
  1246. return;
  1247. }
  1248. // SPV_EXT_demote_to_helper_invocation SPIR-V extension provides a new
  1249. // instruction OpDemoteToHelperInvocationEXT allowing shaders to "demote" a
  1250. // fragment shader invocation to behave like a helper invocation for its
  1251. // duration. The demoted invocation will have no further side effects and will
  1252. // not output to the framebuffer, but remains active and can participate in
  1253. // computing derivatives and in subgroup operations. This is a better match
  1254. // for the "discard" instruction in HLSL.
  1255. spvBuilder.createDemoteToHelperInvocationEXT(discardStmt->getLoc());
  1256. }
  1257. void SpirvEmitter::doDoStmt(const DoStmt *theDoStmt,
  1258. llvm::ArrayRef<const Attr *> attrs) {
  1259. // do-while loops are composed of:
  1260. //
  1261. // do {
  1262. // <body>
  1263. // } while(<check>);
  1264. //
  1265. // SPIR-V requires loops to have a merge basic block as well as a continue
  1266. // basic block. Even though do-while loops do not have an explicit continue
  1267. // block as in for-loops, we still do need to create a continue block.
  1268. //
  1269. // Since SPIR-V requires structured control flow, we need two more basic
  1270. // blocks, <header> and <merge>. <header> is the block before control flow
  1271. // diverges, and <merge> is the block where control flow subsequently
  1272. // converges. The <check> can be performed in the <continue> basic block.
  1273. // The final CFG should normally be like the following. Exceptions
  1274. // will occur with non-local exits like loop breaks or early returns.
  1275. //
  1276. // +----------+
  1277. // | header | <-----------------------------------+
  1278. // +----------+ |
  1279. // | | (true)
  1280. // v |
  1281. // +------+ +--------------------+ |
  1282. // | body | ----> | continue (<check>) |-----------+
  1283. // +------+ +--------------------+
  1284. // |
  1285. // | (false)
  1286. // +-------+ |
  1287. // | merge | <-------------+
  1288. // +-------+
  1289. //
  1290. // For more details, see "2.11. Structured Control Flow" in the SPIR-V spec.
  1291. const spv::LoopControlMask loopControl =
  1292. attrs.empty() ? spv::LoopControlMask::MaskNone
  1293. : translateLoopAttribute(theDoStmt, *attrs.front());
  1294. // Create basic blocks
  1295. auto *headerBB = spvBuilder.createBasicBlock("do_while.header");
  1296. auto *bodyBB = spvBuilder.createBasicBlock("do_while.body");
  1297. auto *continueBB = spvBuilder.createBasicBlock("do_while.continue");
  1298. auto *mergeBB = spvBuilder.createBasicBlock("do_while.merge");
  1299. // Make sure any continue statements branch to the continue block, and any
  1300. // break statements branch to the merge block.
  1301. continueStack.push(continueBB);
  1302. breakStack.push(mergeBB);
  1303. // Branch from the current insert point to the header block.
  1304. spvBuilder.createBranch(headerBB, theDoStmt->getLocStart());
  1305. spvBuilder.addSuccessor(headerBB);
  1306. // Process the <header> block
  1307. // The header block must always branch to the body.
  1308. spvBuilder.setInsertPoint(headerBB);
  1309. const Stmt *body = theDoStmt->getBody();
  1310. spvBuilder.createBranch(bodyBB,
  1311. body ? body->getLocStart() : theDoStmt->getLocStart(),
  1312. mergeBB, continueBB, loopControl);
  1313. spvBuilder.addSuccessor(bodyBB);
  1314. // The current basic block has OpLoopMerge instruction. We need to set its
  1315. // continue and merge target.
  1316. spvBuilder.setContinueTarget(continueBB);
  1317. spvBuilder.setMergeTarget(mergeBB);
  1318. // Process the <body> block
  1319. spvBuilder.setInsertPoint(bodyBB);
  1320. if (body) {
  1321. doStmt(body);
  1322. }
  1323. if (!spvBuilder.isCurrentBasicBlockTerminated()) {
  1324. spvBuilder.createBranch(continueBB, body ? body->getLocEnd()
  1325. : theDoStmt->getLocStart());
  1326. }
  1327. spvBuilder.addSuccessor(continueBB);
  1328. // Process the <continue> block. The check for whether the loop should
  1329. // continue lies in the continue block.
  1330. // *NOTE*: There's a SPIR-V rule that when a conditional branch is to occur in
  1331. // a continue block of a loop, there should be no OpSelectionMerge. Only an
  1332. // OpBranchConditional must be specified.
  1333. spvBuilder.setInsertPoint(continueBB);
  1334. SpirvInstruction *condition = nullptr;
  1335. if (const Expr *check = theDoStmt->getCond()) {
  1336. condition = doExpr(check);
  1337. } else {
  1338. condition = spvBuilder.getConstantBool(true);
  1339. }
  1340. spvBuilder.createConditionalBranch(condition, headerBB, mergeBB,
  1341. theDoStmt->getLocEnd());
  1342. spvBuilder.addSuccessor(headerBB);
  1343. spvBuilder.addSuccessor(mergeBB);
  1344. // Set insertion point to the <merge> block for subsequent statements
  1345. spvBuilder.setInsertPoint(mergeBB);
  1346. // Done with the current scope's continue block and merge block.
  1347. continueStack.pop();
  1348. breakStack.pop();
  1349. }
  1350. void SpirvEmitter::doContinueStmt(const ContinueStmt *continueStmt) {
  1351. assert(!spvBuilder.isCurrentBasicBlockTerminated());
  1352. auto *continueTargetBB = continueStack.top();
  1353. spvBuilder.createBranch(continueTargetBB, continueStmt->getLocStart());
  1354. spvBuilder.addSuccessor(continueTargetBB);
  1355. // Some statements that alter the control flow (break, continue, return, and
  1356. // discard), require creation of a new basic block to hold any statement that
  1357. // may follow them. For example: StmtB and StmtC below are put inside a new
  1358. // basic block which is unreachable.
  1359. //
  1360. // while (true) {
  1361. // StmtA;
  1362. // continue;
  1363. // StmtB;
  1364. // StmtC;
  1365. // }
  1366. auto *newBB = spvBuilder.createBasicBlock();
  1367. spvBuilder.setInsertPoint(newBB);
  1368. }
  1369. void SpirvEmitter::doWhileStmt(const WhileStmt *whileStmt,
  1370. llvm::ArrayRef<const Attr *> attrs) {
  1371. // While loops are composed of:
  1372. // while (<check>) { <body> }
  1373. //
  1374. // SPIR-V requires loops to have a merge basic block as well as a continue
  1375. // basic block. Even though while loops do not have an explicit continue
  1376. // block as in for-loops, we still do need to create a continue block.
  1377. //
  1378. // Since SPIR-V requires structured control flow, we need two more basic
  1379. // blocks, <header> and <merge>. <header> is the block before control flow
  1380. // diverges, and <merge> is the block where control flow subsequently
  1381. // converges. The <check> block can take the responsibility of the <header>
  1382. // block. The final CFG should normally be like the following. Exceptions
  1383. // will occur with non-local exits like loop breaks or early returns.
  1384. //
  1385. // +----------+
  1386. // | header | <------------------+
  1387. // | (check) | |
  1388. // +----------+ |
  1389. // | |
  1390. // +-------+-------+ |
  1391. // | false | true |
  1392. // | v |
  1393. // | +------+ +------------------+
  1394. // | | body | --> | continue (no-op) |
  1395. // v +------+ +------------------+
  1396. // +-------+
  1397. // | merge |
  1398. // +-------+
  1399. //
  1400. // For more details, see "2.11. Structured Control Flow" in the SPIR-V spec.
  1401. const spv::LoopControlMask loopControl =
  1402. attrs.empty() ? spv::LoopControlMask::MaskNone
  1403. : translateLoopAttribute(whileStmt, *attrs.front());
  1404. // Create basic blocks
  1405. auto *checkBB = spvBuilder.createBasicBlock("while.check");
  1406. auto *bodyBB = spvBuilder.createBasicBlock("while.body");
  1407. auto *continueBB = spvBuilder.createBasicBlock("while.continue");
  1408. auto *mergeBB = spvBuilder.createBasicBlock("while.merge");
  1409. // Make sure any continue statements branch to the continue block, and any
  1410. // break statements branch to the merge block.
  1411. continueStack.push(continueBB);
  1412. breakStack.push(mergeBB);
  1413. // Process the <check> block
  1414. spvBuilder.createBranch(checkBB, whileStmt->getLocStart());
  1415. spvBuilder.addSuccessor(checkBB);
  1416. spvBuilder.setInsertPoint(checkBB);
  1417. // If we have:
  1418. // while (int a = foo()) {...}
  1419. // we should evaluate 'a' by calling 'foo()' every single time the check has
  1420. // to occur.
  1421. if (const auto *condVarDecl = whileStmt->getConditionVariableDeclStmt())
  1422. doStmt(condVarDecl);
  1423. SpirvInstruction *condition = nullptr;
  1424. const Expr *check = whileStmt->getCond();
  1425. if (check) {
  1426. condition = doExpr(check);
  1427. } else {
  1428. condition = spvBuilder.getConstantBool(true);
  1429. }
  1430. spvBuilder.createConditionalBranch(
  1431. condition, bodyBB,
  1432. /*false branch*/ mergeBB, whileStmt->getLocStart(),
  1433. /*merge*/ mergeBB, continueBB, spv::SelectionControlMask::MaskNone,
  1434. loopControl);
  1435. spvBuilder.addSuccessor(bodyBB);
  1436. spvBuilder.addSuccessor(mergeBB);
  1437. // The current basic block has OpLoopMerge instruction. We need to set its
  1438. // continue and merge target.
  1439. spvBuilder.setContinueTarget(continueBB);
  1440. spvBuilder.setMergeTarget(mergeBB);
  1441. // Process the <body> block
  1442. spvBuilder.setInsertPoint(bodyBB);
  1443. const Stmt *body = whileStmt->getBody();
  1444. if (body) {
  1445. doStmt(body);
  1446. }
  1447. if (!spvBuilder.isCurrentBasicBlockTerminated())
  1448. spvBuilder.createBranch(continueBB, whileStmt->getLocEnd());
  1449. spvBuilder.addSuccessor(continueBB);
  1450. // Process the <continue> block. While loops do not have an explicit
  1451. // continue block. The continue block just branches to the <check> block.
  1452. spvBuilder.setInsertPoint(continueBB);
  1453. spvBuilder.createBranch(checkBB, whileStmt->getLocEnd());
  1454. spvBuilder.addSuccessor(checkBB);
  1455. // Set insertion point to the <merge> block for subsequent statements
  1456. spvBuilder.setInsertPoint(mergeBB);
  1457. // Done with the current scope's continue and merge blocks.
  1458. continueStack.pop();
  1459. breakStack.pop();
  1460. }
  1461. void SpirvEmitter::doForStmt(const ForStmt *forStmt,
  1462. llvm::ArrayRef<const Attr *> attrs) {
  1463. // for loops are composed of:
  1464. // for (<init>; <check>; <continue>) <body>
  1465. //
  1466. // To translate a for loop, we'll need to emit all <init> statements
  1467. // in the current basic block, and then have separate basic blocks for
  1468. // <check>, <continue>, and <body>. Besides, since SPIR-V requires
  1469. // structured control flow, we need two more basic blocks, <header>
  1470. // and <merge>. <header> is the block before control flow diverges,
  1471. // while <merge> is the block where control flow subsequently converges.
  1472. // The <check> block can take the responsibility of the <header> block.
  1473. // The final CFG should normally be like the following. Exceptions will
  1474. // occur with non-local exits like loop breaks or early returns.
  1475. // +--------+
  1476. // | init |
  1477. // +--------+
  1478. // |
  1479. // v
  1480. // +----------+
  1481. // | header | <---------------+
  1482. // | (check) | |
  1483. // +----------+ |
  1484. // | |
  1485. // +-------+-------+ |
  1486. // | false | true |
  1487. // | v |
  1488. // | +------+ +----------+
  1489. // | | body | --> | continue |
  1490. // v +------+ +----------+
  1491. // +-------+
  1492. // | merge |
  1493. // +-------+
  1494. //
  1495. // For more details, see "2.11. Structured Control Flow" in the SPIR-V spec.
  1496. const spv::LoopControlMask loopControl =
  1497. attrs.empty() ? spv::LoopControlMask::MaskNone
  1498. : translateLoopAttribute(forStmt, *attrs.front());
  1499. // Create basic blocks
  1500. auto *checkBB = spvBuilder.createBasicBlock("for.check");
  1501. auto *bodyBB = spvBuilder.createBasicBlock("for.body");
  1502. auto *continueBB = spvBuilder.createBasicBlock("for.continue");
  1503. auto *mergeBB = spvBuilder.createBasicBlock("for.merge");
  1504. // Make sure any continue statements branch to the continue block, and any
  1505. // break statements branch to the merge block.
  1506. continueStack.push(continueBB);
  1507. breakStack.push(mergeBB);
  1508. // Process the <init> block
  1509. if (const Stmt *initStmt = forStmt->getInit()) {
  1510. doStmt(initStmt);
  1511. }
  1512. const Expr *check = forStmt->getCond();
  1513. spvBuilder.createBranch(checkBB, check ? check->getLocStart()
  1514. : forStmt->getLocStart());
  1515. spvBuilder.addSuccessor(checkBB);
  1516. // Process the <check> block
  1517. spvBuilder.setInsertPoint(checkBB);
  1518. SpirvInstruction *condition = nullptr;
  1519. if (check) {
  1520. condition = doExpr(check);
  1521. } else {
  1522. condition = spvBuilder.getConstantBool(true);
  1523. }
  1524. const Stmt *body = forStmt->getBody();
  1525. spvBuilder.createConditionalBranch(
  1526. condition, bodyBB,
  1527. /*false branch*/ mergeBB,
  1528. check ? check->getLocEnd()
  1529. : (body ? body->getLocStart() : forStmt->getLocStart()),
  1530. /*merge*/ mergeBB, continueBB, spv::SelectionControlMask::MaskNone,
  1531. loopControl);
  1532. spvBuilder.addSuccessor(bodyBB);
  1533. spvBuilder.addSuccessor(mergeBB);
  1534. // The current basic block has OpLoopMerge instruction. We need to set its
  1535. // continue and merge target.
  1536. spvBuilder.setContinueTarget(continueBB);
  1537. spvBuilder.setMergeTarget(mergeBB);
  1538. // Process the <body> block
  1539. spvBuilder.setInsertPoint(bodyBB);
  1540. if (body) {
  1541. doStmt(body);
  1542. }
  1543. if (!spvBuilder.isCurrentBasicBlockTerminated())
  1544. spvBuilder.createBranch(continueBB, forStmt->getLocEnd());
  1545. spvBuilder.addSuccessor(continueBB);
  1546. // Process the <continue> block
  1547. spvBuilder.setInsertPoint(continueBB);
  1548. if (const Expr *cont = forStmt->getInc()) {
  1549. doExpr(cont);
  1550. }
  1551. // <continue> should jump back to header
  1552. spvBuilder.createBranch(checkBB, forStmt->getLocEnd());
  1553. spvBuilder.addSuccessor(checkBB);
  1554. // Set insertion point to the <merge> block for subsequent statements
  1555. spvBuilder.setInsertPoint(mergeBB);
  1556. // Done with the current scope's continue block and merge block.
  1557. continueStack.pop();
  1558. breakStack.pop();
  1559. }
  1560. void SpirvEmitter::doIfStmt(const IfStmt *ifStmt,
  1561. llvm::ArrayRef<const Attr *> attrs) {
  1562. // if statements are composed of:
  1563. // if (<check>) { <then> } else { <else> }
  1564. //
  1565. // To translate if statements, we'll need to emit the <check> expressions
  1566. // in the current basic block, and then create separate basic blocks for
  1567. // <then> and <else>. Additionally, we'll need a <merge> block as per
  1568. // SPIR-V's structured control flow requirements. Depending whether there
  1569. // exists the else branch, the final CFG should normally be like the
  1570. // following. Exceptions will occur with non-local exits like loop breaks
  1571. // or early returns.
  1572. // +-------+ +-------+
  1573. // | check | | check |
  1574. // +-------+ +-------+
  1575. // | |
  1576. // +-------+-------+ +-----+-----+
  1577. // | true | false | true | false
  1578. // v v or v |
  1579. // +------+ +------+ +------+ |
  1580. // | then | | else | | then | |
  1581. // +------+ +------+ +------+ |
  1582. // | | | v
  1583. // | +-------+ | | +-------+
  1584. // +-> | merge | <-+ +---> | merge |
  1585. // +-------+ +-------+
  1586. { // Try to see if we can const-eval the condition
  1587. bool condition = false;
  1588. if (ifStmt->getCond()->EvaluateAsBooleanCondition(condition, astContext)) {
  1589. if (condition) {
  1590. doStmt(ifStmt->getThen());
  1591. } else if (ifStmt->getElse()) {
  1592. doStmt(ifStmt->getElse());
  1593. }
  1594. return;
  1595. }
  1596. }
  1597. auto selectionControl = spv::SelectionControlMask::MaskNone;
  1598. if (!attrs.empty()) {
  1599. const Attr *attribute = attrs.front();
  1600. switch (attribute->getKind()) {
  1601. case attr::HLSLBranch:
  1602. selectionControl = spv::SelectionControlMask::DontFlatten;
  1603. break;
  1604. case attr::HLSLFlatten:
  1605. selectionControl = spv::SelectionControlMask::Flatten;
  1606. break;
  1607. default:
  1608. if (!spirvOptions.noWarnIgnoredFeatures) {
  1609. emitWarning("unknown if statement attribute '%0' ignored",
  1610. attribute->getLocation())
  1611. << attribute->getSpelling();
  1612. }
  1613. break;
  1614. }
  1615. }
  1616. if (const auto *declStmt = ifStmt->getConditionVariableDeclStmt())
  1617. doDeclStmt(declStmt);
  1618. // First emit the instruction for evaluating the condition.
  1619. auto *condition = doExpr(ifStmt->getCond());
  1620. // Then we need to emit the instruction for the conditional branch.
  1621. // We'll need the <label-id> for the then/else/merge block to do so.
  1622. const bool hasElse = ifStmt->getElse() != nullptr;
  1623. auto *thenBB = spvBuilder.createBasicBlock("if.true");
  1624. auto *mergeBB = spvBuilder.createBasicBlock("if.merge");
  1625. auto *elseBB = hasElse ? spvBuilder.createBasicBlock("if.false") : mergeBB;
  1626. // Create the branch instruction. This will end the current basic block.
  1627. const auto *then = ifStmt->getThen();
  1628. spvBuilder.createConditionalBranch(condition, thenBB, elseBB,
  1629. then->getLocStart(), mergeBB,
  1630. /*continue*/ 0, selectionControl);
  1631. spvBuilder.addSuccessor(thenBB);
  1632. spvBuilder.addSuccessor(elseBB);
  1633. // The current basic block has the OpSelectionMerge instruction. We need
  1634. // to record its merge target.
  1635. spvBuilder.setMergeTarget(mergeBB);
  1636. // Handle the then branch
  1637. spvBuilder.setInsertPoint(thenBB);
  1638. doStmt(then);
  1639. if (!spvBuilder.isCurrentBasicBlockTerminated())
  1640. spvBuilder.createBranch(mergeBB, ifStmt->getLocEnd());
  1641. spvBuilder.addSuccessor(mergeBB);
  1642. // Handle the else branch (if exists)
  1643. if (hasElse) {
  1644. spvBuilder.setInsertPoint(elseBB);
  1645. const auto *elseStmt = ifStmt->getElse();
  1646. doStmt(elseStmt);
  1647. if (!spvBuilder.isCurrentBasicBlockTerminated())
  1648. spvBuilder.createBranch(mergeBB, elseStmt->getLocEnd());
  1649. spvBuilder.addSuccessor(mergeBB);
  1650. }
  1651. // From now on, we'll emit instructions into the merge block.
  1652. spvBuilder.setInsertPoint(mergeBB);
  1653. }
  1654. void SpirvEmitter::doReturnStmt(const ReturnStmt *stmt) {
  1655. if (const auto *retVal = stmt->getRetValue()) {
  1656. // Update counter variable associated with function returns
  1657. tryToAssignCounterVar(curFunction, retVal);
  1658. auto *retInfo = loadIfGLValue(retVal);
  1659. if (!retInfo)
  1660. return;
  1661. auto retType = retVal->getType();
  1662. if (retInfo->getStorageClass() != spv::StorageClass::Function &&
  1663. retType->isStructureType()) {
  1664. // We are returning some value from a non-Function storage class. Need to
  1665. // create a temporary variable to "convert" the value to Function storage
  1666. // class and then return.
  1667. auto *tempVar =
  1668. spvBuilder.addFnVar(retType, retVal->getLocEnd(), "temp.var.ret");
  1669. storeValue(tempVar, retInfo, retType, retVal->getLocEnd());
  1670. spvBuilder.createReturnValue(
  1671. spvBuilder.createLoad(retType, tempVar, retVal->getLocEnd()),
  1672. stmt->getReturnLoc());
  1673. } else {
  1674. spvBuilder.createReturnValue(retInfo, stmt->getReturnLoc());
  1675. }
  1676. } else {
  1677. spvBuilder.createReturn(stmt->getReturnLoc());
  1678. }
  1679. // We are translating a ReturnStmt, we should be in some function's body.
  1680. assert(curFunction->hasBody());
  1681. // If this return statement is the last statement in the function, then
  1682. // whe have no more work to do.
  1683. if (cast<CompoundStmt>(curFunction->getBody())->body_back() == stmt)
  1684. return;
  1685. // Some statements that alter the control flow (break, continue, return, and
  1686. // discard), require creation of a new basic block to hold any statement that
  1687. // may follow them. In this case, the newly created basic block will contain
  1688. // any statement that may come after an early return.
  1689. auto *newBB = spvBuilder.createBasicBlock();
  1690. spvBuilder.setInsertPoint(newBB);
  1691. }
  1692. void SpirvEmitter::doBreakStmt(const BreakStmt *breakStmt) {
  1693. assert(!spvBuilder.isCurrentBasicBlockTerminated());
  1694. auto *breakTargetBB = breakStack.top();
  1695. spvBuilder.addSuccessor(breakTargetBB);
  1696. spvBuilder.createBranch(breakTargetBB, breakStmt->getLocStart());
  1697. // Some statements that alter the control flow (break, continue, return, and
  1698. // discard), require creation of a new basic block to hold any statement that
  1699. // may follow them. For example: StmtB and StmtC below are put inside a new
  1700. // basic block which is unreachable.
  1701. //
  1702. // while (true) {
  1703. // StmtA;
  1704. // break;
  1705. // StmtB;
  1706. // StmtC;
  1707. // }
  1708. auto *newBB = spvBuilder.createBasicBlock();
  1709. spvBuilder.setInsertPoint(newBB);
  1710. }
  1711. void SpirvEmitter::doSwitchStmt(const SwitchStmt *switchStmt,
  1712. llvm::ArrayRef<const Attr *> attrs) {
  1713. // Switch statements are composed of:
  1714. // switch (<condition variable>) {
  1715. // <CaseStmt>
  1716. // <CaseStmt>
  1717. // <CaseStmt>
  1718. // <DefaultStmt> (optional)
  1719. // }
  1720. //
  1721. // +-------+
  1722. // | check |
  1723. // +-------+
  1724. // |
  1725. // +-------+-------+----------------+---------------+
  1726. // | 1 | 2 | 3 | (others)
  1727. // v v v v
  1728. // +-------+ +-------------+ +-------+ +------------+
  1729. // | case1 | | case2 | | case3 | ... | default |
  1730. // | | |(fallthrough)|---->| | | (optional) |
  1731. // +-------+ |+------------+ +-------+ +------------+
  1732. // | | |
  1733. // | | |
  1734. // | +-------+ | |
  1735. // | | | <--------------------+ |
  1736. // +-> | merge | |
  1737. // | | <-------------------------------------+
  1738. // +-------+
  1739. // If no attributes are given, or if "forcecase" attribute was provided,
  1740. // we'll do our best to use OpSwitch if possible.
  1741. // If any of the cases compares to a variable (rather than an integer
  1742. // literal), we cannot use OpSwitch because OpSwitch expects literal
  1743. // numbers as parameters.
  1744. const bool isAttrForceCase =
  1745. !attrs.empty() && attrs.front()->getKind() == attr::HLSLForceCase;
  1746. const bool canUseSpirvOpSwitch =
  1747. (attrs.empty() || isAttrForceCase) &&
  1748. allSwitchCasesAreIntegerLiterals(switchStmt->getBody());
  1749. if (isAttrForceCase && !canUseSpirvOpSwitch &&
  1750. !spirvOptions.noWarnIgnoredFeatures) {
  1751. emitWarning("ignored 'forcecase' attribute for the switch statement "
  1752. "since one or more case values are not integer literals",
  1753. switchStmt->getLocStart());
  1754. }
  1755. if (canUseSpirvOpSwitch)
  1756. processSwitchStmtUsingSpirvOpSwitch(switchStmt);
  1757. else
  1758. processSwitchStmtUsingIfStmts(switchStmt);
  1759. }
  1760. SpirvInstruction *
  1761. SpirvEmitter::doArraySubscriptExpr(const ArraySubscriptExpr *expr) {
  1762. llvm::SmallVector<SpirvInstruction *, 4> indices;
  1763. const auto *base = collectArrayStructIndices(
  1764. expr, /*rawIndex*/ false, /*rawIndices*/ nullptr, &indices);
  1765. auto *info = loadIfAliasVarRef(base);
  1766. if (!indices.empty()) {
  1767. info = turnIntoElementPtr(base->getType(), info, expr->getType(), indices,
  1768. base->getExprLoc());
  1769. }
  1770. return info;
  1771. }
  1772. SpirvInstruction *SpirvEmitter::doBinaryOperator(const BinaryOperator *expr) {
  1773. const auto opcode = expr->getOpcode();
  1774. // Handle assignment first since we need to evaluate rhs before lhs.
  1775. // For other binary operations, we need to evaluate lhs before rhs.
  1776. if (opcode == BO_Assign) {
  1777. // Update counter variable associated with lhs of assignments
  1778. tryToAssignCounterVar(expr->getLHS(), expr->getRHS());
  1779. return processAssignment(expr->getLHS(), loadIfGLValue(expr->getRHS()),
  1780. /*isCompoundAssignment=*/false);
  1781. }
  1782. // Try to optimize floatMxN * float and floatN * float case
  1783. if (opcode == BO_Mul) {
  1784. if (auto *result = tryToGenFloatMatrixScale(expr))
  1785. return result;
  1786. if (auto *result = tryToGenFloatVectorScale(expr))
  1787. return result;
  1788. }
  1789. return processBinaryOp(expr->getLHS(), expr->getRHS(), opcode,
  1790. expr->getLHS()->getType(), expr->getType(),
  1791. expr->getSourceRange(), expr->getOperatorLoc());
  1792. }
  1793. SpirvInstruction *SpirvEmitter::doCallExpr(const CallExpr *callExpr) {
  1794. if (const auto *operatorCall = dyn_cast<CXXOperatorCallExpr>(callExpr))
  1795. return doCXXOperatorCallExpr(operatorCall);
  1796. if (const auto *memberCall = dyn_cast<CXXMemberCallExpr>(callExpr))
  1797. return doCXXMemberCallExpr(memberCall);
  1798. // Intrinsic functions such as 'dot' or 'mul'
  1799. if (hlsl::IsIntrinsicOp(callExpr->getDirectCallee())) {
  1800. return processIntrinsicCallExpr(callExpr);
  1801. }
  1802. // Normal standalone functions
  1803. return processCall(callExpr);
  1804. }
  1805. SpirvInstruction *SpirvEmitter::processCall(const CallExpr *callExpr) {
  1806. const FunctionDecl *callee = getCalleeDefinition(callExpr);
  1807. // Note that we always want the defintion because Stmts/Exprs in the
  1808. // function body references the parameters in the definition.
  1809. if (!callee) {
  1810. emitError("found undefined function", callExpr->getExprLoc());
  1811. return nullptr;
  1812. }
  1813. const auto paramTypeMatchesArgType = [](QualType paramType,
  1814. QualType argType) {
  1815. if (argType == paramType)
  1816. return true;
  1817. if (const auto *refType = paramType->getAs<ReferenceType>())
  1818. paramType = refType->getPointeeType();
  1819. auto argUnqualifiedType = argType->getUnqualifiedDesugaredType();
  1820. auto paramUnqualifiedType = paramType->getUnqualifiedDesugaredType();
  1821. if (argUnqualifiedType == paramUnqualifiedType)
  1822. return true;
  1823. return false;
  1824. };
  1825. const auto numParams = callee->getNumParams();
  1826. bool isNonStaticMemberCall = false;
  1827. QualType objectType = {}; // Type of the object (if exists)
  1828. SpirvInstruction *objInstr = nullptr; // EvalInfo for the object (if exists)
  1829. llvm::SmallVector<SpirvInstruction *, 4> vars; // Variables for function call
  1830. llvm::SmallVector<bool, 4> isTempVar; // Temporary variable or not
  1831. llvm::SmallVector<SpirvInstruction *, 4> args; // Evaluated arguments
  1832. if (const auto *memberCall = dyn_cast<CXXMemberCallExpr>(callExpr)) {
  1833. const auto *memberFn = cast<CXXMethodDecl>(memberCall->getCalleeDecl());
  1834. isNonStaticMemberCall = !memberFn->isStatic();
  1835. if (isNonStaticMemberCall) {
  1836. // For non-static member calls, evaluate the object and pass it as the
  1837. // first argument.
  1838. const auto *object = memberCall->getImplicitObjectArgument();
  1839. object = object->IgnoreParenNoopCasts(astContext);
  1840. // Update counter variable associated with the implicit object
  1841. tryToAssignCounterVar(getOrCreateDeclForMethodObject(memberFn), object);
  1842. objectType = object->getType();
  1843. objInstr = doExpr(object);
  1844. // If not already a variable, we need to create a temporary variable and
  1845. // pass the object pointer to the function. Example:
  1846. // getObject().objectMethod();
  1847. // Also, any parameter passed to the member function must be of Function
  1848. // storage class.
  1849. if (objInstr->isRValue()) {
  1850. args.push_back(createTemporaryVar(
  1851. objectType, getAstTypeName(objectType),
  1852. // May need to load to use as initializer
  1853. loadIfGLValue(object, objInstr), object->getLocStart()));
  1854. } else {
  1855. // Based on SPIR-V spec, function parameter must always be in Function
  1856. // scope. If we pass a non-function scope argument, we need
  1857. // the legalization.
  1858. if (objInstr->getStorageClass() != spv::StorageClass::Function)
  1859. beforeHlslLegalization = true;
  1860. args.push_back(objInstr);
  1861. }
  1862. // We do not need to create a new temporary variable for the this
  1863. // object. Use the evaluated argument.
  1864. vars.push_back(args.back());
  1865. isTempVar.push_back(false);
  1866. }
  1867. }
  1868. // Evaluate parameters
  1869. for (uint32_t i = 0; i < numParams; ++i) {
  1870. // We want the argument variable here so that we can write back to it
  1871. // later. We will do the OpLoad of this argument manually. So ingore
  1872. // the LValueToRValue implicit cast here.
  1873. auto *arg = callExpr->getArg(i)->IgnoreParenLValueCasts();
  1874. const auto *param = callee->getParamDecl(i);
  1875. // Get the evaluation info if this argument is referencing some variable
  1876. // *as a whole*, in which case we can avoid creating the temporary variable
  1877. // for it if it can act as out parameter.
  1878. SpirvInstruction *argInfo = nullptr;
  1879. if (const auto *declRefExpr = dyn_cast<DeclRefExpr>(arg)) {
  1880. argInfo = declIdMapper.getDeclEvalInfo(declRefExpr->getDecl(),
  1881. arg->getLocStart());
  1882. }
  1883. auto *argInst = doExpr(arg);
  1884. auto argType = arg->getType();
  1885. // If argInfo is nullptr and argInst is a rvalue, we do not have a proper
  1886. // pointer to pass to the function. we need a temporary variable in that
  1887. // case.
  1888. if ((argInfo || (argInst && !argInst->isRValue())) &&
  1889. canActAsOutParmVar(param) &&
  1890. paramTypeMatchesArgType(param->getType(), arg->getType())) {
  1891. // Based on SPIR-V spec, function parameter must be always Function
  1892. // scope. In addition, we must pass memory object declaration argument
  1893. // to function. If we pass an argument that is not function scope
  1894. // or not memory object declaration, we need the legalization.
  1895. if (!argInfo || argInfo->getStorageClass() != spv::StorageClass::Function)
  1896. beforeHlslLegalization = true;
  1897. isTempVar.push_back(false);
  1898. args.push_back(argInst);
  1899. vars.push_back(argInfo ? argInfo : argInst);
  1900. } else {
  1901. // We need to create variables for holding the values to be used as
  1902. // arguments. The variables themselves are of pointer types.
  1903. const QualType varType =
  1904. declIdMapper.getTypeAndCreateCounterForPotentialAliasVar(param);
  1905. const std::string varName = "param.var." + param->getNameAsString();
  1906. // Temporary "param.var.*" variables are used for OpFunctionCall purposes.
  1907. // 'precise' attribute on function parameters only affect computations
  1908. // inside the function, not the variables at the call sites. Therefore, we
  1909. // do not need to mark the "param.var.*" variables as precise.
  1910. const bool isPrecise = false;
  1911. auto *tempVar =
  1912. spvBuilder.addFnVar(varType, arg->getLocStart(), varName, isPrecise);
  1913. vars.push_back(tempVar);
  1914. isTempVar.push_back(true);
  1915. args.push_back(argInst);
  1916. // Update counter variable associated with function parameters
  1917. tryToAssignCounterVar(param, arg);
  1918. // Manually load the argument here
  1919. auto *rhsVal = loadIfGLValue(arg, args.back());
  1920. // The AST does not include cast nodes to and from the function parameter
  1921. // type for 'out' and 'inout' cases. Example:
  1922. //
  1923. // void foo(out half3 param) {...}
  1924. // void main() { float3 arg; foo(arg); }
  1925. //
  1926. // In such cases, we first do a manual cast before passing the argument to
  1927. // the function. And we will cast back the results once the function call
  1928. // has returned.
  1929. if (canActAsOutParmVar(param) &&
  1930. !paramTypeMatchesArgType(param->getType(), arg->getType())) {
  1931. auto paramType = param->getType();
  1932. if (const auto *refType = paramType->getAs<ReferenceType>())
  1933. paramType = refType->getPointeeType();
  1934. rhsVal =
  1935. castToType(rhsVal, arg->getType(), paramType, arg->getLocStart());
  1936. }
  1937. // Initialize the temporary variables using the contents of the arguments
  1938. storeValue(tempVar, rhsVal, param->getType(), arg->getLocStart());
  1939. }
  1940. }
  1941. if (beforeHlslLegalization)
  1942. needsLegalization = true;
  1943. assert(vars.size() == isTempVar.size());
  1944. assert(vars.size() == args.size());
  1945. // Push the callee into the work queue if it is not there.
  1946. addFunctionToWorkQueue(spvContext.getCurrentShaderModelKind(), callee,
  1947. /*isEntryFunction*/ false);
  1948. const QualType retType =
  1949. declIdMapper.getTypeAndCreateCounterForPotentialAliasVar(callee);
  1950. // Get or forward declare the function <result-id>
  1951. SpirvFunction *func = declIdMapper.getOrRegisterFn(callee);
  1952. auto *retVal = spvBuilder.createFunctionCall(
  1953. retType, func, vars, callExpr->getCallee()->getExprLoc());
  1954. // Go through all parameters and write those marked as out/inout
  1955. for (uint32_t i = 0; i < numParams; ++i) {
  1956. const auto *param = callee->getParamDecl(i);
  1957. // If it calls a non-static member function, the object itself is argument
  1958. // 0, and therefore all other argument positions are shifted by 1.
  1959. const uint32_t index = i + isNonStaticMemberCall;
  1960. if (isTempVar[index] && canActAsOutParmVar(param)) {
  1961. const auto *arg = callExpr->getArg(i);
  1962. SpirvInstruction *value = spvBuilder.createLoad(
  1963. param->getType(), vars[index], arg->getLocStart());
  1964. // Now we want to assign 'value' to arg. But first, in rare cases when
  1965. // using 'out' or 'inout' where the parameter and argument have a type
  1966. // mismatch, we need to first cast 'value' to the type of 'arg' because
  1967. // the AST will not include a cast node.
  1968. if (!paramTypeMatchesArgType(param->getType(), arg->getType())) {
  1969. auto paramType = param->getType();
  1970. if (const auto *refType = paramType->getAs<ReferenceType>())
  1971. paramType = refType->getPointeeType();
  1972. value =
  1973. castToType(value, paramType, arg->getType(), arg->getLocStart());
  1974. }
  1975. processAssignment(arg, value, false, args[index]);
  1976. }
  1977. }
  1978. return retVal;
  1979. }
  1980. SpirvInstruction *SpirvEmitter::doCastExpr(const CastExpr *expr) {
  1981. const Expr *subExpr = expr->getSubExpr();
  1982. const QualType subExprType = subExpr->getType();
  1983. const QualType toType = expr->getType();
  1984. const auto srcLoc = expr->getExprLoc();
  1985. switch (expr->getCastKind()) {
  1986. case CastKind::CK_LValueToRValue:
  1987. return loadIfGLValue(subExpr);
  1988. case CastKind::CK_NoOp:
  1989. return doExpr(subExpr);
  1990. case CastKind::CK_IntegralCast:
  1991. case CastKind::CK_FloatingToIntegral:
  1992. case CastKind::CK_HLSLCC_IntegralCast:
  1993. case CastKind::CK_HLSLCC_FloatingToIntegral: {
  1994. // Integer literals in the AST are represented using 64bit APInt
  1995. // themselves and then implicitly casted into the expected bitwidth.
  1996. // We need special treatment of integer literals here because generating
  1997. // a 64bit constant and then explicit casting in SPIR-V requires Int64
  1998. // capability. We should avoid introducing unnecessary capabilities to
  1999. // our best.
  2000. if (auto *value = tryToEvaluateAsConst(expr)) {
  2001. value->setRValue();
  2002. return value;
  2003. }
  2004. auto *value = castToInt(loadIfGLValue(subExpr), subExprType, toType,
  2005. subExpr->getLocStart());
  2006. value->setRValue();
  2007. return value;
  2008. }
  2009. case CastKind::CK_FloatingCast:
  2010. case CastKind::CK_IntegralToFloating:
  2011. case CastKind::CK_HLSLCC_FloatingCast:
  2012. case CastKind::CK_HLSLCC_IntegralToFloating: {
  2013. // First try to see if we can do constant folding for floating point
  2014. // numbers like what we are doing for integers in the above.
  2015. if (auto *value = tryToEvaluateAsConst(expr)) {
  2016. value->setRValue();
  2017. return value;
  2018. }
  2019. auto *value = castToFloat(loadIfGLValue(subExpr), subExprType, toType,
  2020. subExpr->getLocStart());
  2021. value->setRValue();
  2022. return value;
  2023. }
  2024. case CastKind::CK_IntegralToBoolean:
  2025. case CastKind::CK_FloatingToBoolean:
  2026. case CastKind::CK_HLSLCC_IntegralToBoolean:
  2027. case CastKind::CK_HLSLCC_FloatingToBoolean: {
  2028. // First try to see if we can do constant folding.
  2029. if (auto *value = tryToEvaluateAsConst(expr)) {
  2030. value->setRValue();
  2031. return value;
  2032. }
  2033. auto *value = castToBool(loadIfGLValue(subExpr), subExprType, toType,
  2034. subExpr->getLocStart());
  2035. value->setRValue();
  2036. return value;
  2037. }
  2038. case CastKind::CK_HLSLVectorSplat: {
  2039. const size_t size = hlsl::GetHLSLVecSize(expr->getType());
  2040. return createVectorSplat(subExpr, size);
  2041. }
  2042. case CastKind::CK_HLSLVectorTruncationCast: {
  2043. const QualType toVecType = toType;
  2044. const QualType elemType = hlsl::GetHLSLVecElementType(toType);
  2045. const auto toSize = hlsl::GetHLSLVecSize(toType);
  2046. auto *composite = doExpr(subExpr);
  2047. llvm::SmallVector<SpirvInstruction *, 4> elements;
  2048. for (uint32_t i = 0; i < toSize; ++i) {
  2049. elements.push_back(spvBuilder.createCompositeExtract(
  2050. elemType, composite, {i}, expr->getExprLoc()));
  2051. }
  2052. auto *value = elements.front();
  2053. if (toSize > 1) {
  2054. value = spvBuilder.createCompositeConstruct(toVecType, elements,
  2055. expr->getExprLoc());
  2056. }
  2057. value->setRValue();
  2058. return value;
  2059. }
  2060. case CastKind::CK_HLSLVectorToScalarCast: {
  2061. // The underlying should already be a vector of size 1.
  2062. assert(hlsl::GetHLSLVecSize(subExprType) == 1);
  2063. return doExpr(subExpr);
  2064. }
  2065. case CastKind::CK_HLSLVectorToMatrixCast: {
  2066. // If target type is already an 1xN matrix type, we just return the
  2067. // underlying vector.
  2068. if (is1xNMatrix(toType))
  2069. return doExpr(subExpr);
  2070. // A vector can have no more than 4 elements. The only remaining case
  2071. // is casting from size-4 vector to size-2-by-2 matrix.
  2072. auto *vec = loadIfGLValue(subExpr);
  2073. QualType elemType = {};
  2074. uint32_t rowCount = 0, colCount = 0;
  2075. const bool isMat = isMxNMatrix(toType, &elemType, &rowCount, &colCount);
  2076. assert(isMat && rowCount == 2 && colCount == 2);
  2077. (void)isMat;
  2078. QualType vec2Type = astContext.getExtVectorType(elemType, 2);
  2079. auto *subVec1 = spvBuilder.createVectorShuffle(vec2Type, vec, vec, {0, 1},
  2080. expr->getLocStart());
  2081. auto *subVec2 = spvBuilder.createVectorShuffle(vec2Type, vec, vec, {2, 3},
  2082. expr->getLocStart());
  2083. auto *mat = spvBuilder.createCompositeConstruct(toType, {subVec1, subVec2},
  2084. expr->getLocStart());
  2085. mat->setRValue();
  2086. return mat;
  2087. }
  2088. case CastKind::CK_HLSLMatrixSplat: {
  2089. // From scalar to matrix
  2090. uint32_t rowCount = 0, colCount = 0;
  2091. hlsl::GetHLSLMatRowColCount(toType, rowCount, colCount);
  2092. // Handle degenerated cases first
  2093. if (rowCount == 1 && colCount == 1)
  2094. return doExpr(subExpr);
  2095. if (colCount == 1)
  2096. return createVectorSplat(subExpr, rowCount);
  2097. const auto vecSplat = createVectorSplat(subExpr, colCount);
  2098. if (rowCount == 1)
  2099. return vecSplat;
  2100. if (isa<SpirvConstant>(vecSplat)) {
  2101. llvm::SmallVector<SpirvConstant *, 4> vectors(
  2102. size_t(rowCount), cast<SpirvConstant>(vecSplat));
  2103. auto *value = spvBuilder.getConstantComposite(toType, vectors);
  2104. value->setRValue();
  2105. return value;
  2106. } else {
  2107. llvm::SmallVector<SpirvInstruction *, 4> vectors(size_t(rowCount),
  2108. vecSplat);
  2109. auto *value = spvBuilder.createCompositeConstruct(toType, vectors,
  2110. expr->getLocEnd());
  2111. value->setRValue();
  2112. return value;
  2113. }
  2114. }
  2115. case CastKind::CK_HLSLMatrixTruncationCast: {
  2116. const QualType srcType = subExprType;
  2117. auto *src = doExpr(subExpr);
  2118. const QualType elemType = hlsl::GetHLSLMatElementType(srcType);
  2119. llvm::SmallVector<uint32_t, 4> indexes;
  2120. // It is possible that the source matrix is in fact a vector.
  2121. // For example: Truncate float1x3 --> float1x2.
  2122. // The front-end disallows float1x3 --> float2x1.
  2123. {
  2124. uint32_t srcVecSize = 0, dstVecSize = 0;
  2125. if (isVectorType(srcType, nullptr, &srcVecSize) &&
  2126. isVectorType(toType, nullptr, &dstVecSize)) {
  2127. for (uint32_t i = 0; i < dstVecSize; ++i)
  2128. indexes.push_back(i);
  2129. auto *val = spvBuilder.createVectorShuffle(toType, src, src, indexes,
  2130. expr->getLocStart());
  2131. val->setRValue();
  2132. return val;
  2133. }
  2134. }
  2135. uint32_t srcRows = 0, srcCols = 0, dstRows = 0, dstCols = 0;
  2136. hlsl::GetHLSLMatRowColCount(srcType, srcRows, srcCols);
  2137. hlsl::GetHLSLMatRowColCount(toType, dstRows, dstCols);
  2138. const QualType srcRowType = astContext.getExtVectorType(elemType, srcCols);
  2139. const QualType dstRowType = astContext.getExtVectorType(elemType, dstCols);
  2140. // Indexes to pass to OpVectorShuffle
  2141. for (uint32_t i = 0; i < dstCols; ++i)
  2142. indexes.push_back(i);
  2143. llvm::SmallVector<SpirvInstruction *, 4> extractedVecs;
  2144. for (uint32_t row = 0; row < dstRows; ++row) {
  2145. // Extract a row
  2146. SpirvInstruction *rowInstr = spvBuilder.createCompositeExtract(
  2147. srcRowType, src, {row}, expr->getExprLoc());
  2148. // Extract the necessary columns from that row.
  2149. // The front-end ensures dstCols <= srcCols.
  2150. // If dstCols equals srcCols, we can use the whole row directly.
  2151. if (dstCols == 1) {
  2152. rowInstr = spvBuilder.createCompositeExtract(elemType, rowInstr, {0},
  2153. expr->getLocStart());
  2154. } else if (dstCols < srcCols) {
  2155. rowInstr = spvBuilder.createVectorShuffle(
  2156. dstRowType, rowInstr, rowInstr, indexes, expr->getLocStart());
  2157. }
  2158. extractedVecs.push_back(rowInstr);
  2159. }
  2160. auto *val = extractedVecs.front();
  2161. if (extractedVecs.size() > 1) {
  2162. val = spvBuilder.createCompositeConstruct(toType, extractedVecs,
  2163. expr->getExprLoc());
  2164. }
  2165. val->setRValue();
  2166. return val;
  2167. }
  2168. case CastKind::CK_HLSLMatrixToScalarCast: {
  2169. // The underlying should already be a matrix of 1x1.
  2170. assert(is1x1Matrix(subExprType));
  2171. return doExpr(subExpr);
  2172. }
  2173. case CastKind::CK_HLSLMatrixToVectorCast: {
  2174. // If the underlying matrix is Mx1 or 1xM for M in {1, 2,3,4}, we can return
  2175. // the underlying matrix because it'll be evaluated as a vector by default.
  2176. if (is1x1Matrix(subExprType) || is1xNMatrix(subExprType) ||
  2177. isMx1Matrix(subExprType))
  2178. return doExpr(subExpr);
  2179. // A vector can have no more than 4 elements. The only remaining case
  2180. // is casting from a 2x2 matrix to a vector of size 4.
  2181. auto *mat = loadIfGLValue(subExpr);
  2182. QualType elemType = {};
  2183. uint32_t rowCount = 0, colCount = 0, elemCount = 0;
  2184. const bool isMat =
  2185. isMxNMatrix(subExprType, &elemType, &rowCount, &colCount);
  2186. const bool isVec = isVectorType(toType, nullptr, &elemCount);
  2187. assert(isMat && rowCount == 2 && colCount == 2);
  2188. assert(isVec && elemCount == 4);
  2189. (void)isMat;
  2190. (void)isVec;
  2191. QualType vec2Type = astContext.getExtVectorType(elemType, 2);
  2192. auto *row0 = spvBuilder.createCompositeExtract(vec2Type, mat, {0}, srcLoc);
  2193. auto *row1 = spvBuilder.createCompositeExtract(vec2Type, mat, {1}, srcLoc);
  2194. auto *vec = spvBuilder.createVectorShuffle(toType, row0, row1, {0, 1, 2, 3},
  2195. srcLoc);
  2196. vec->setRValue();
  2197. return vec;
  2198. }
  2199. case CastKind::CK_FunctionToPointerDecay:
  2200. // Just need to return the function id
  2201. return doExpr(subExpr);
  2202. case CastKind::CK_FlatConversion: {
  2203. SpirvInstruction *subExprInstr = nullptr;
  2204. QualType evalType = subExprType;
  2205. // Optimization: we can use OpConstantNull for cases where we want to
  2206. // initialize an entire data structure to zeros.
  2207. if (evaluatesToConstZero(subExpr, astContext)) {
  2208. subExprInstr = spvBuilder.getConstantNull(toType);
  2209. subExprInstr->setRValue();
  2210. return subExprInstr;
  2211. }
  2212. // Try to evaluate float literals as float rather than double.
  2213. if (const auto *floatLiteral = dyn_cast<FloatingLiteral>(subExpr)) {
  2214. subExprInstr = tryToEvaluateAsFloat32(floatLiteral->getValue());
  2215. if (subExprInstr)
  2216. evalType = astContext.FloatTy;
  2217. }
  2218. // Evaluate 'literal float' initializer type as float rather than double.
  2219. // TODO: This could result in rounding error if the initializer is a
  2220. // non-literal expression that requires larger than 32 bits and has the
  2221. // 'literal float' type.
  2222. else if (subExprType->isSpecificBuiltinType(BuiltinType::LitFloat)) {
  2223. evalType = astContext.FloatTy;
  2224. }
  2225. // Try to evaluate integer literals as 32-bit int rather than 64-bit int.
  2226. else if (const auto *intLiteral = dyn_cast<IntegerLiteral>(subExpr)) {
  2227. const bool isSigned = subExprType->isSignedIntegerType();
  2228. subExprInstr = tryToEvaluateAsInt32(intLiteral->getValue(), isSigned);
  2229. if (subExprInstr)
  2230. evalType = isSigned ? astContext.IntTy : astContext.UnsignedIntTy;
  2231. }
  2232. // For assigning one array instance to another one with the same array type
  2233. // (regardless of constness and literalness), the rhs will be wrapped in a
  2234. // FlatConversion. Similarly for assigning a struct to another struct with
  2235. // identical members.
  2236. // |- <lhs>
  2237. // `- ImplicitCastExpr <FlatConversion>
  2238. // `- ImplicitCastExpr <LValueToRValue>
  2239. // `- <rhs>
  2240. else if (isSameType(astContext, toType, evalType) ||
  2241. // We can have casts changing the shape but without affecting
  2242. // memory order, e.g., `float4 a[2]; float b[8] = (float[8])a;`.
  2243. // This is also represented as FlatConversion. For such cases, we
  2244. // can rely on the InitListHandler, which can decompse
  2245. // vectors/matrices.
  2246. subExprType->isArrayType()) {
  2247. auto *valInstr =
  2248. InitListHandler(astContext, *this).processCast(toType, subExpr);
  2249. if (valInstr)
  2250. valInstr->setRValue();
  2251. return valInstr;
  2252. }
  2253. // We can have casts changing the shape but without affecting memory order,
  2254. // e.g., `float4 a[2]; float b[8] = (float[8])a;`. This is also represented
  2255. // as FlatConversion. For such cases, we can rely on the InitListHandler,
  2256. // which can decompse vectors/matrices.
  2257. else if (subExprType->isArrayType()) {
  2258. auto *valInstr = InitListHandler(astContext, *this)
  2259. .processCast(expr->getType(), subExpr);
  2260. if (valInstr)
  2261. valInstr->setRValue();
  2262. return valInstr;
  2263. }
  2264. if (!subExprInstr)
  2265. subExprInstr = doExpr(subExpr);
  2266. auto *val = processFlatConversion(toType, evalType, subExprInstr,
  2267. expr->getExprLoc());
  2268. val->setRValue();
  2269. return val;
  2270. }
  2271. case CastKind::CK_UncheckedDerivedToBase:
  2272. case CastKind::CK_HLSLDerivedToBase: {
  2273. // Find the index sequence of the base to which we are casting
  2274. llvm::SmallVector<uint32_t, 4> baseIndices;
  2275. getBaseClassIndices(expr, &baseIndices);
  2276. // Turn them in to SPIR-V constants
  2277. llvm::SmallVector<SpirvInstruction *, 4> baseIndexInstructions(
  2278. baseIndices.size(), nullptr);
  2279. for (uint32_t i = 0; i < baseIndices.size(); ++i)
  2280. baseIndexInstructions[i] = spvBuilder.getConstantInt(
  2281. astContext.UnsignedIntTy, llvm::APInt(32, baseIndices[i]));
  2282. auto *derivedInfo = doExpr(subExpr);
  2283. return turnIntoElementPtr(subExpr->getType(), derivedInfo, expr->getType(),
  2284. baseIndexInstructions, subExpr->getExprLoc());
  2285. }
  2286. case CastKind::CK_ArrayToPointerDecay: {
  2287. // Literal string to const string conversion falls under this category.
  2288. if (hlsl::IsStringLiteralType(subExprType) && hlsl::IsStringType(toType)) {
  2289. return doExpr(subExpr);
  2290. } else {
  2291. emitError("implicit cast kind '%0' unimplemented", expr->getExprLoc())
  2292. << expr->getCastKindName() << expr->getSourceRange();
  2293. expr->dump();
  2294. return 0;
  2295. }
  2296. }
  2297. default:
  2298. emitError("implicit cast kind '%0' unimplemented", expr->getExprLoc())
  2299. << expr->getCastKindName() << expr->getSourceRange();
  2300. expr->dump();
  2301. return 0;
  2302. }
  2303. }
  2304. SpirvInstruction *SpirvEmitter::processFlatConversion(
  2305. const QualType type, const QualType initType, SpirvInstruction *initInstr,
  2306. SourceLocation srcLoc) {
  2307. // Try to translate the canonical type first
  2308. const auto canonicalType = type.getCanonicalType();
  2309. if (canonicalType != type)
  2310. return processFlatConversion(canonicalType, initType, initInstr, srcLoc);
  2311. // Primitive types
  2312. {
  2313. QualType ty = {};
  2314. if (isScalarType(type, &ty)) {
  2315. if (const auto *builtinType = ty->getAs<BuiltinType>()) {
  2316. switch (builtinType->getKind()) {
  2317. case BuiltinType::Void: {
  2318. emitError("cannot create a constant of void type", srcLoc);
  2319. return 0;
  2320. }
  2321. case BuiltinType::Bool:
  2322. return castToBool(initInstr, initType, ty, srcLoc);
  2323. // Target type is an integer variant.
  2324. case BuiltinType::Int:
  2325. case BuiltinType::Short:
  2326. case BuiltinType::Min12Int:
  2327. case BuiltinType::Min16Int:
  2328. case BuiltinType::Min16UInt:
  2329. case BuiltinType::UShort:
  2330. case BuiltinType::UInt:
  2331. case BuiltinType::Long:
  2332. case BuiltinType::LongLong:
  2333. case BuiltinType::ULong:
  2334. case BuiltinType::ULongLong:
  2335. return castToInt(initInstr, initType, ty, srcLoc);
  2336. // Target type is a float variant.
  2337. case BuiltinType::Double:
  2338. case BuiltinType::Float:
  2339. case BuiltinType::Half:
  2340. case BuiltinType::HalfFloat:
  2341. case BuiltinType::Min10Float:
  2342. case BuiltinType::Min16Float:
  2343. return castToFloat(initInstr, initType, ty, srcLoc);
  2344. default:
  2345. emitError("flat conversion of type %0 unimplemented", srcLoc)
  2346. << builtinType->getTypeClassName();
  2347. return 0;
  2348. }
  2349. }
  2350. }
  2351. }
  2352. // Vector types
  2353. {
  2354. QualType elemType = {};
  2355. uint32_t elemCount = {};
  2356. if (isVectorType(type, &elemType, &elemCount)) {
  2357. auto *elem = processFlatConversion(elemType, initType, initInstr, srcLoc);
  2358. llvm::SmallVector<SpirvInstruction *, 4> constituents(size_t(elemCount),
  2359. elem);
  2360. return spvBuilder.createCompositeConstruct(type, constituents, srcLoc);
  2361. }
  2362. }
  2363. // Matrix types
  2364. {
  2365. QualType elemType = {};
  2366. uint32_t rowCount = 0, colCount = 0;
  2367. if (isMxNMatrix(type, &elemType, &rowCount, &colCount)) {
  2368. // By default HLSL matrices are row major, while SPIR-V matrices are
  2369. // column major. We are mapping what HLSL semantically mean a row into a
  2370. // column here.
  2371. const QualType vecType = astContext.getExtVectorType(elemType, colCount);
  2372. auto *elem = processFlatConversion(elemType, initType, initInstr, srcLoc);
  2373. const llvm::SmallVector<SpirvInstruction *, 4> constituents(
  2374. size_t(colCount), elem);
  2375. auto *col =
  2376. spvBuilder.createCompositeConstruct(vecType, constituents, srcLoc);
  2377. const llvm::SmallVector<SpirvInstruction *, 4> rows(size_t(rowCount),
  2378. col);
  2379. return spvBuilder.createCompositeConstruct(type, rows, srcLoc);
  2380. }
  2381. }
  2382. // Struct type
  2383. if (const auto *structType = type->getAs<RecordType>()) {
  2384. const auto *decl = structType->getDecl();
  2385. llvm::SmallVector<SpirvInstruction *, 4> fields;
  2386. for (const auto *field : decl->fields()) {
  2387. // There is a special case for FlatConversion. If T is a struct with only
  2388. // one member, S, then (T)<an-instance-of-S> is allowed, which essentially
  2389. // constructs a new T instance using the instance of S as its only member.
  2390. // Check whether we are handling that case here first.
  2391. if (field->getType().getCanonicalType() == initType.getCanonicalType()) {
  2392. fields.push_back(initInstr);
  2393. } else {
  2394. fields.push_back(processFlatConversion(field->getType(), initType,
  2395. initInstr, srcLoc));
  2396. }
  2397. }
  2398. return spvBuilder.createCompositeConstruct(type, fields, srcLoc);
  2399. }
  2400. // Array type
  2401. if (const auto *arrayType = astContext.getAsConstantArrayType(type)) {
  2402. const auto size =
  2403. static_cast<uint32_t>(arrayType->getSize().getZExtValue());
  2404. auto *elem = processFlatConversion(arrayType->getElementType(), initType,
  2405. initInstr, srcLoc);
  2406. llvm::SmallVector<SpirvInstruction *, 4> constituents(size_t(size), elem);
  2407. return spvBuilder.createCompositeConstruct(type, constituents, srcLoc);
  2408. }
  2409. emitError("flat conversion of type %0 unimplemented", {})
  2410. << type->getTypeClassName();
  2411. type->dump();
  2412. return 0;
  2413. }
  2414. SpirvInstruction *
  2415. SpirvEmitter::doCompoundAssignOperator(const CompoundAssignOperator *expr) {
  2416. const auto opcode = expr->getOpcode();
  2417. // Try to optimize floatMxN *= float and floatN *= float case
  2418. if (opcode == BO_MulAssign) {
  2419. if (auto *result = tryToGenFloatMatrixScale(expr))
  2420. return result;
  2421. if (auto *result = tryToGenFloatVectorScale(expr))
  2422. return result;
  2423. }
  2424. const auto *rhs = expr->getRHS();
  2425. const auto *lhs = expr->getLHS();
  2426. SpirvInstruction *lhsPtr = nullptr;
  2427. auto *result = processBinaryOp(
  2428. lhs, rhs, opcode, expr->getComputationLHSType(), expr->getType(),
  2429. expr->getSourceRange(), expr->getOperatorLoc(), &lhsPtr);
  2430. return processAssignment(lhs, result, true, lhsPtr);
  2431. }
  2432. SpirvInstruction *
  2433. SpirvEmitter::doConditionalOperator(const ConditionalOperator *expr) {
  2434. const auto type = expr->getType();
  2435. const SourceLocation loc = expr->getExprLoc();
  2436. // According to HLSL doc, all sides of the ?: expression are always evaluated.
  2437. // If we are selecting between two SampleState objects, none of the three
  2438. // operands has a LValueToRValue implicit cast.
  2439. auto *condition = loadIfGLValue(expr->getCond());
  2440. auto *trueBranch = loadIfGLValue(expr->getTrueExpr());
  2441. auto *falseBranch = loadIfGLValue(expr->getFalseExpr());
  2442. // For cases where the return type is a scalar or a vector, we can use
  2443. // OpSelect to choose between the two. OpSelect's return type must be either
  2444. // scalar or vector.
  2445. if (isScalarType(type) || isVectorType(type)) {
  2446. // The SPIR-V OpSelect instruction must have a selection argument that is
  2447. // the same size as the return type. If the return type is a vector, the
  2448. // selection must be a vector of booleans (one per output component).
  2449. uint32_t count = 0;
  2450. if (isVectorType(expr->getType(), nullptr, &count) &&
  2451. !isVectorType(expr->getCond()->getType())) {
  2452. const llvm::SmallVector<SpirvInstruction *, 4> components(size_t(count),
  2453. condition);
  2454. condition = spvBuilder.createCompositeConstruct(
  2455. astContext.getExtVectorType(astContext.BoolTy, count), components,
  2456. expr->getCond()->getLocEnd());
  2457. }
  2458. auto *value =
  2459. spvBuilder.createSelect(type, condition, trueBranch, falseBranch, loc);
  2460. value->setRValue();
  2461. return value;
  2462. }
  2463. // If we can't use OpSelect, we need to create if-else control flow.
  2464. auto *tempVar = spvBuilder.addFnVar(type, loc, "temp.var.ternary");
  2465. auto *thenBB = spvBuilder.createBasicBlock("if.true");
  2466. auto *mergeBB = spvBuilder.createBasicBlock("if.merge");
  2467. auto *elseBB = spvBuilder.createBasicBlock("if.false");
  2468. // Create the branch instruction. This will end the current basic block.
  2469. spvBuilder.createConditionalBranch(condition, thenBB, elseBB,
  2470. expr->getCond()->getLocEnd(), mergeBB);
  2471. spvBuilder.addSuccessor(thenBB);
  2472. spvBuilder.addSuccessor(elseBB);
  2473. spvBuilder.setMergeTarget(mergeBB);
  2474. // Handle the then branch
  2475. spvBuilder.setInsertPoint(thenBB);
  2476. spvBuilder.createStore(tempVar, trueBranch,
  2477. expr->getTrueExpr()->getLocStart());
  2478. spvBuilder.createBranch(mergeBB, expr->getTrueExpr()->getLocEnd());
  2479. spvBuilder.addSuccessor(mergeBB);
  2480. // Handle the else branch
  2481. spvBuilder.setInsertPoint(elseBB);
  2482. spvBuilder.createStore(tempVar, falseBranch,
  2483. expr->getFalseExpr()->getLocStart());
  2484. spvBuilder.createBranch(mergeBB, expr->getFalseExpr()->getLocEnd());
  2485. spvBuilder.addSuccessor(mergeBB);
  2486. // From now on, emit instructions into the merge block.
  2487. spvBuilder.setInsertPoint(mergeBB);
  2488. auto *result = spvBuilder.createLoad(type, tempVar, expr->getLocEnd());
  2489. result->setRValue();
  2490. return result;
  2491. }
  2492. SpirvInstruction *
  2493. SpirvEmitter::processByteAddressBufferStructuredBufferGetDimensions(
  2494. const CXXMemberCallExpr *expr) {
  2495. const auto *object = expr->getImplicitObjectArgument();
  2496. auto *objectInstr = loadIfAliasVarRef(object);
  2497. const auto type = object->getType();
  2498. const bool isBABuf = isByteAddressBuffer(type) || isRWByteAddressBuffer(type);
  2499. const bool isStructuredBuf = isStructuredBuffer(type) ||
  2500. isAppendStructuredBuffer(type) ||
  2501. isConsumeStructuredBuffer(type);
  2502. assert(isBABuf || isStructuredBuf);
  2503. // (RW)ByteAddressBuffers/(RW)StructuredBuffers are represented as a structure
  2504. // with only one member that is a runtime array. We need to perform
  2505. // OpArrayLength on member 0.
  2506. SpirvInstruction *length = spvBuilder.createArrayLength(
  2507. astContext.UnsignedIntTy, expr->getExprLoc(), objectInstr, 0);
  2508. // For (RW)ByteAddressBuffers, GetDimensions() must return the array length
  2509. // in bytes, but OpArrayLength returns the number of uints in the runtime
  2510. // array. Therefore we must multiply the results by 4.
  2511. if (isBABuf) {
  2512. length = spvBuilder.createBinaryOp(
  2513. spv::Op::OpIMul, astContext.UnsignedIntTy, length,
  2514. // TODO(jaebaek): What line info we should emit for constants?
  2515. spvBuilder.getConstantInt(astContext.UnsignedIntTy,
  2516. llvm::APInt(32, 4u)),
  2517. expr->getExprLoc());
  2518. }
  2519. spvBuilder.createStore(doExpr(expr->getArg(0)), length,
  2520. expr->getArg(0)->getLocStart());
  2521. if (isStructuredBuf) {
  2522. // For (RW)StructuredBuffer, the stride of the runtime array (which is the
  2523. // size of the struct) must also be written to the second argument.
  2524. AlignmentSizeCalculator alignmentCalc(astContext, spirvOptions);
  2525. uint32_t size = 0, stride = 0;
  2526. std::tie(std::ignore, size) =
  2527. alignmentCalc.getAlignmentAndSize(type, spirvOptions.sBufferLayoutRule,
  2528. /*isRowMajor*/ llvm::None, &stride);
  2529. auto *sizeInstr = spvBuilder.getConstantInt(astContext.UnsignedIntTy,
  2530. llvm::APInt(32, size));
  2531. spvBuilder.createStore(doExpr(expr->getArg(1)), sizeInstr,
  2532. expr->getArg(1)->getLocStart());
  2533. }
  2534. return nullptr;
  2535. }
  2536. SpirvInstruction *SpirvEmitter::processRWByteAddressBufferAtomicMethods(
  2537. hlsl::IntrinsicOp opcode, const CXXMemberCallExpr *expr) {
  2538. // The signature of RWByteAddressBuffer atomic methods are largely:
  2539. // void Interlocked*(in UINT dest, in UINT value);
  2540. // void Interlocked*(in UINT dest, in UINT value, out UINT original_value);
  2541. const auto *object = expr->getImplicitObjectArgument();
  2542. auto *objectInfo = loadIfAliasVarRef(object);
  2543. auto *zero =
  2544. spvBuilder.getConstantInt(astContext.UnsignedIntTy, llvm::APInt(32, 0));
  2545. auto *offset = doExpr(expr->getArg(0));
  2546. // Right shift by 2 to convert the byte offset to uint32_t offset
  2547. auto *address = spvBuilder.createBinaryOp(
  2548. spv::Op::OpShiftRightLogical, astContext.UnsignedIntTy, offset,
  2549. spvBuilder.getConstantInt(astContext.UnsignedIntTy, llvm::APInt(32, 2)),
  2550. expr->getExprLoc());
  2551. auto *ptr =
  2552. spvBuilder.createAccessChain(astContext.UnsignedIntTy, objectInfo,
  2553. {zero, address}, object->getLocStart());
  2554. const bool isCompareExchange =
  2555. opcode == hlsl::IntrinsicOp::MOP_InterlockedCompareExchange;
  2556. const bool isCompareStore =
  2557. opcode == hlsl::IntrinsicOp::MOP_InterlockedCompareStore;
  2558. if (isCompareExchange || isCompareStore) {
  2559. auto *comparator = doExpr(expr->getArg(1));
  2560. auto *originalVal = spvBuilder.createAtomicCompareExchange(
  2561. astContext.UnsignedIntTy, ptr, spv::Scope::Device,
  2562. spv::MemorySemanticsMask::MaskNone, spv::MemorySemanticsMask::MaskNone,
  2563. doExpr(expr->getArg(2)), comparator, expr->getCallee()->getExprLoc());
  2564. if (isCompareExchange)
  2565. spvBuilder.createStore(doExpr(expr->getArg(3)), originalVal,
  2566. expr->getArg(3)->getLocStart());
  2567. } else {
  2568. auto *value = doExpr(expr->getArg(1));
  2569. SpirvInstruction *originalVal = spvBuilder.createAtomicOp(
  2570. translateAtomicHlslOpcodeToSpirvOpcode(opcode),
  2571. astContext.UnsignedIntTy, ptr, spv::Scope::Device,
  2572. spv::MemorySemanticsMask::MaskNone, value,
  2573. expr->getCallee()->getExprLoc());
  2574. if (expr->getNumArgs() > 2) {
  2575. originalVal = castToType(originalVal, astContext.UnsignedIntTy,
  2576. expr->getArg(2)->getType(),
  2577. expr->getArg(2)->getLocStart());
  2578. spvBuilder.createStore(doExpr(expr->getArg(2)), originalVal,
  2579. expr->getArg(2)->getLocStart());
  2580. }
  2581. }
  2582. return nullptr;
  2583. }
  2584. SpirvInstruction *
  2585. SpirvEmitter::processGetSamplePosition(const CXXMemberCallExpr *expr) {
  2586. const auto *object = expr->getImplicitObjectArgument()->IgnoreParens();
  2587. auto *sampleCount = spvBuilder.createImageQuery(
  2588. spv::Op::OpImageQuerySamples, astContext.UnsignedIntTy,
  2589. expr->getExprLoc(), loadIfGLValue(object));
  2590. if (!spirvOptions.noWarnEmulatedFeatures)
  2591. emitWarning("GetSamplePosition is emulated using many SPIR-V instructions "
  2592. "due to lack of direct SPIR-V equivalent, so it only supports "
  2593. "standard sample settings with 1, 2, 4, 8, or 16 samples and "
  2594. "will return float2(0, 0) for other cases",
  2595. expr->getCallee()->getExprLoc());
  2596. return emitGetSamplePosition(sampleCount, doExpr(expr->getArg(0)),
  2597. expr->getCallee()->getExprLoc());
  2598. }
  2599. SpirvInstruction *
  2600. SpirvEmitter::processSubpassLoad(const CXXMemberCallExpr *expr) {
  2601. const auto *object = expr->getImplicitObjectArgument()->IgnoreParens();
  2602. SpirvInstruction *sample =
  2603. expr->getNumArgs() == 1 ? doExpr(expr->getArg(0)) : nullptr;
  2604. auto *zero = spvBuilder.getConstantInt(astContext.IntTy, llvm::APInt(32, 0));
  2605. auto *location = spvBuilder.getConstantComposite(
  2606. astContext.getExtVectorType(astContext.IntTy, 2), {zero, zero});
  2607. return processBufferTextureLoad(object, location, /*constOffset*/ 0,
  2608. /*varOffset*/ 0, /*lod*/ sample,
  2609. /*residencyCode*/ 0, expr->getExprLoc());
  2610. }
  2611. SpirvInstruction *
  2612. SpirvEmitter::processBufferTextureGetDimensions(const CXXMemberCallExpr *expr) {
  2613. const auto *object = expr->getImplicitObjectArgument();
  2614. auto *objectInstr = loadIfGLValue(object);
  2615. const auto type = object->getType();
  2616. const auto *recType = type->getAs<RecordType>();
  2617. assert(recType);
  2618. const auto typeName = recType->getDecl()->getName();
  2619. const auto numArgs = expr->getNumArgs();
  2620. const Expr *mipLevel = nullptr, *numLevels = nullptr, *numSamples = nullptr;
  2621. assert(isTexture(type) || isRWTexture(type) || isBuffer(type) ||
  2622. isRWBuffer(type));
  2623. // For Texture1D, arguments are either:
  2624. // a) width
  2625. // b) MipLevel, width, NumLevels
  2626. // For Texture1DArray, arguments are either:
  2627. // a) width, elements
  2628. // b) MipLevel, width, elements, NumLevels
  2629. // For Texture2D, arguments are either:
  2630. // a) width, height
  2631. // b) MipLevel, width, height, NumLevels
  2632. // For Texture2DArray, arguments are either:
  2633. // a) width, height, elements
  2634. // b) MipLevel, width, height, elements, NumLevels
  2635. // For Texture3D, arguments are either:
  2636. // a) width, height, depth
  2637. // b) MipLevel, width, height, depth, NumLevels
  2638. // For Texture2DMS, arguments are: width, height, NumSamples
  2639. // For Texture2DMSArray, arguments are: width, height, elements, NumSamples
  2640. // For TextureCube, arguments are either:
  2641. // a) width, height
  2642. // b) MipLevel, width, height, NumLevels
  2643. // For TextureCubeArray, arguments are either:
  2644. // a) width, height, elements
  2645. // b) MipLevel, width, height, elements, NumLevels
  2646. // Note: SPIR-V Spec requires return type of OpImageQuerySize(Lod) to be a
  2647. // scalar/vector of integers. SPIR-V Spec also requires return type of
  2648. // OpImageQueryLevels and OpImageQuerySamples to be scalar integers.
  2649. // The HLSL methods, however, have overloaded functions which have float
  2650. // output arguments. Since the AST naturally won't have casting AST nodes for
  2651. // such cases, we'll have to perform the cast ourselves.
  2652. const auto storeToOutputArg = [this](const Expr *outputArg,
  2653. SpirvInstruction *id, QualType type) {
  2654. id = castToType(id, type, outputArg->getType(), outputArg->getExprLoc());
  2655. spvBuilder.createStore(doExpr(outputArg), id, outputArg->getLocStart());
  2656. };
  2657. if ((typeName == "Texture1D" && numArgs > 1) ||
  2658. (typeName == "Texture2D" && numArgs > 2) ||
  2659. (typeName == "TextureCube" && numArgs > 2) ||
  2660. (typeName == "Texture3D" && numArgs > 3) ||
  2661. (typeName == "Texture1DArray" && numArgs > 2) ||
  2662. (typeName == "TextureCubeArray" && numArgs > 3) ||
  2663. (typeName == "Texture2DArray" && numArgs > 3)) {
  2664. mipLevel = expr->getArg(0);
  2665. numLevels = expr->getArg(numArgs - 1);
  2666. }
  2667. if (isTextureMS(type)) {
  2668. numSamples = expr->getArg(numArgs - 1);
  2669. }
  2670. uint32_t querySize = numArgs;
  2671. // If numLevels arg is present, mipLevel must also be present. These are not
  2672. // queried via ImageQuerySizeLod.
  2673. if (numLevels)
  2674. querySize -= 2;
  2675. // If numLevels arg is present, mipLevel must also be present.
  2676. else if (numSamples)
  2677. querySize -= 1;
  2678. const QualType resultQualType =
  2679. querySize == 1
  2680. ? astContext.UnsignedIntTy
  2681. : astContext.getExtVectorType(astContext.UnsignedIntTy, querySize);
  2682. // Only Texture types use ImageQuerySizeLod.
  2683. // TextureMS, RWTexture, Buffers, RWBuffers use ImageQuerySize.
  2684. SpirvInstruction *lod = nullptr;
  2685. if (isTexture(type) && !numSamples) {
  2686. if (mipLevel) {
  2687. // For Texture types when mipLevel argument is present.
  2688. lod = doExpr(mipLevel);
  2689. } else {
  2690. // For Texture types when mipLevel argument is omitted.
  2691. lod = spvBuilder.getConstantInt(astContext.IntTy, llvm::APInt(32, 0));
  2692. }
  2693. }
  2694. SpirvInstruction *query =
  2695. lod ? cast<SpirvInstruction>(spvBuilder.createImageQuery(
  2696. spv::Op::OpImageQuerySizeLod, resultQualType,
  2697. expr->getCallee()->getExprLoc(), objectInstr, lod))
  2698. : cast<SpirvInstruction>(spvBuilder.createImageQuery(
  2699. spv::Op::OpImageQuerySize, resultQualType,
  2700. expr->getCallee()->getExprLoc(), objectInstr));
  2701. if (querySize == 1) {
  2702. const uint32_t argIndex = mipLevel ? 1 : 0;
  2703. storeToOutputArg(expr->getArg(argIndex), query, resultQualType);
  2704. } else {
  2705. for (uint32_t i = 0; i < querySize; ++i) {
  2706. const uint32_t argIndex = mipLevel ? i + 1 : i;
  2707. auto *component = spvBuilder.createCompositeExtract(
  2708. astContext.UnsignedIntTy, query, {i},
  2709. expr->getCallee()->getExprLoc());
  2710. // If the first arg is the mipmap level, we must write the results
  2711. // starting from Arg(i+1), not Arg(i).
  2712. storeToOutputArg(expr->getArg(argIndex), component,
  2713. astContext.UnsignedIntTy);
  2714. }
  2715. }
  2716. if (numLevels || numSamples) {
  2717. const Expr *numLevelsSamplesArg = numLevels ? numLevels : numSamples;
  2718. const spv::Op opcode =
  2719. numLevels ? spv::Op::OpImageQueryLevels : spv::Op::OpImageQuerySamples;
  2720. auto *numLevelsSamplesQuery = spvBuilder.createImageQuery(
  2721. opcode, astContext.UnsignedIntTy, expr->getCallee()->getExprLoc(),
  2722. objectInstr);
  2723. storeToOutputArg(numLevelsSamplesArg, numLevelsSamplesQuery,
  2724. astContext.UnsignedIntTy);
  2725. }
  2726. return nullptr;
  2727. }
  2728. SpirvInstruction *
  2729. SpirvEmitter::processTextureLevelOfDetail(const CXXMemberCallExpr *expr,
  2730. bool unclamped) {
  2731. // Possible signatures are as follows:
  2732. // Texture1D(Array).CalculateLevelOfDetail(SamplerState S, float x);
  2733. // Texture2D(Array).CalculateLevelOfDetail(SamplerState S, float2 xy);
  2734. // TextureCube(Array).CalculateLevelOfDetail(SamplerState S, float3 xyz);
  2735. // Texture3D.CalculateLevelOfDetail(SamplerState S, float3 xyz);
  2736. // Return type is always a single float (LOD).
  2737. assert(expr->getNumArgs() == 2u);
  2738. const auto *object = expr->getImplicitObjectArgument();
  2739. auto *objectInfo = loadIfGLValue(object);
  2740. auto *samplerState = doExpr(expr->getArg(0));
  2741. auto *coordinate = doExpr(expr->getArg(1));
  2742. auto *sampledImage = spvBuilder.createSampledImage(
  2743. object->getType(), objectInfo, samplerState, expr->getExprLoc());
  2744. // The result type of OpImageQueryLod must be a float2.
  2745. const QualType queryResultType =
  2746. astContext.getExtVectorType(astContext.FloatTy, 2u);
  2747. auto *query =
  2748. spvBuilder.createImageQuery(spv::Op::OpImageQueryLod, queryResultType,
  2749. expr->getExprLoc(), sampledImage, coordinate);
  2750. // The first component of the float2 contains the mipmap array layer.
  2751. // The second component of the float2 represents the unclamped lod.
  2752. return spvBuilder.createCompositeExtract(astContext.FloatTy, query,
  2753. unclamped ? 1 : 0,
  2754. expr->getCallee()->getExprLoc());
  2755. }
  2756. SpirvInstruction *SpirvEmitter::processTextureGatherRGBACmpRGBA(
  2757. const CXXMemberCallExpr *expr, const bool isCmp, const uint32_t component) {
  2758. // Parameters for .Gather{Red|Green|Blue|Alpha}() are one of the following
  2759. // two sets:
  2760. // * SamplerState s, float2 location, int2 offset
  2761. // * SamplerState s, float2 location, int2 offset0, int2 offset1,
  2762. // int offset2, int2 offset3
  2763. //
  2764. // An additional 'out uint status' parameter can appear in both of the above.
  2765. //
  2766. // Parameters for .GatherCmp{Red|Green|Blue|Alpha}() are one of the following
  2767. // two sets:
  2768. // * SamplerState s, float2 location, float compare_value, int2 offset
  2769. // * SamplerState s, float2 location, float compare_value, int2 offset1,
  2770. // int2 offset2, int2 offset3, int2 offset4
  2771. //
  2772. // An additional 'out uint status' parameter can appear in both of the above.
  2773. //
  2774. // TextureCube's signature is somewhat different from the rest.
  2775. // Parameters for .Gather{Red|Green|Blue|Alpha}() for TextureCube are:
  2776. // * SamplerState s, float2 location, out uint status
  2777. // Parameters for .GatherCmp{Red|Green|Blue|Alpha}() for TextureCube are:
  2778. // * SamplerState s, float2 location, float compare_value, out uint status
  2779. //
  2780. // Return type is always a 4-component vector.
  2781. const FunctionDecl *callee = expr->getDirectCallee();
  2782. const auto numArgs = expr->getNumArgs();
  2783. const auto *imageExpr = expr->getImplicitObjectArgument();
  2784. const auto loc = expr->getCallee()->getExprLoc();
  2785. const QualType imageType = imageExpr->getType();
  2786. const QualType retType = callee->getReturnType();
  2787. // If the last arg is an unsigned integer, it must be the status.
  2788. const bool hasStatusArg =
  2789. expr->getArg(numArgs - 1)->getType()->isUnsignedIntegerType();
  2790. // Subtract 1 for status arg (if it exists), subtract 1 for compare_value (if
  2791. // it exists), and subtract 2 for SamplerState and location.
  2792. const auto numOffsetArgs = numArgs - hasStatusArg - isCmp - 2;
  2793. // No offset args for TextureCube, 1 or 4 offset args for the rest.
  2794. assert(numOffsetArgs == 0 || numOffsetArgs == 1 || numOffsetArgs == 4);
  2795. auto *image = loadIfGLValue(imageExpr);
  2796. auto *sampler = doExpr(expr->getArg(0));
  2797. auto *coordinate = doExpr(expr->getArg(1));
  2798. auto *compareVal = isCmp ? doExpr(expr->getArg(2)) : nullptr;
  2799. // Handle offsets (if any).
  2800. bool needsEmulation = false;
  2801. SpirvInstruction *constOffset = nullptr, *varOffset = nullptr,
  2802. *constOffsets = nullptr;
  2803. if (numOffsetArgs == 1) {
  2804. // The offset arg is not optional.
  2805. handleOffsetInMethodCall(expr, 2 + isCmp, &constOffset, &varOffset);
  2806. } else if (numOffsetArgs == 4) {
  2807. auto *offset0 = tryToEvaluateAsConst(expr->getArg(2 + isCmp));
  2808. auto *offset1 = tryToEvaluateAsConst(expr->getArg(3 + isCmp));
  2809. auto *offset2 = tryToEvaluateAsConst(expr->getArg(4 + isCmp));
  2810. auto *offset3 = tryToEvaluateAsConst(expr->getArg(5 + isCmp));
  2811. // If any of the offsets is not constant, we then need to emulate the call
  2812. // using 4 OpImageGather instructions. Otherwise, we can leverage the
  2813. // ConstOffsets image operand.
  2814. if (offset0 && offset1 && offset2 && offset3) {
  2815. const QualType v2i32 = astContext.getExtVectorType(astContext.IntTy, 2);
  2816. const auto offsetType = astContext.getConstantArrayType(
  2817. v2i32, llvm::APInt(32, 4), clang::ArrayType::Normal, 0);
  2818. constOffsets = spvBuilder.getConstantComposite(
  2819. offsetType, {offset0, offset1, offset2, offset3});
  2820. } else {
  2821. needsEmulation = true;
  2822. }
  2823. }
  2824. auto *status = hasStatusArg ? doExpr(expr->getArg(numArgs - 1)) : nullptr;
  2825. if (needsEmulation) {
  2826. const auto elemType = hlsl::GetHLSLVecElementType(callee->getReturnType());
  2827. SpirvInstruction *texels[4];
  2828. for (uint32_t i = 0; i < 4; ++i) {
  2829. varOffset = doExpr(expr->getArg(2 + isCmp + i));
  2830. auto *gatherRet = spvBuilder.createImageGather(
  2831. retType, imageType, image, sampler, coordinate,
  2832. spvBuilder.getConstantInt(astContext.IntTy,
  2833. llvm::APInt(32, component, true)),
  2834. compareVal,
  2835. /*constOffset*/ nullptr, varOffset, /*constOffsets*/ nullptr,
  2836. /*sampleNumber*/ nullptr, status, loc);
  2837. texels[i] =
  2838. spvBuilder.createCompositeExtract(elemType, gatherRet, {i}, loc);
  2839. }
  2840. return spvBuilder.createCompositeConstruct(
  2841. retType, {texels[0], texels[1], texels[2], texels[3]}, loc);
  2842. }
  2843. return spvBuilder.createImageGather(
  2844. retType, imageType, image, sampler, coordinate,
  2845. spvBuilder.getConstantInt(astContext.IntTy,
  2846. llvm::APInt(32, component, true)),
  2847. compareVal, constOffset, varOffset, constOffsets,
  2848. /*sampleNumber*/ nullptr, status, loc);
  2849. }
  2850. SpirvInstruction *
  2851. SpirvEmitter::processTextureGatherCmp(const CXXMemberCallExpr *expr) {
  2852. // Signature for Texture2D/Texture2DArray:
  2853. //
  2854. // float4 GatherCmp(
  2855. // in SamplerComparisonState s,
  2856. // in float2 location,
  2857. // in float compare_value
  2858. // [,in int2 offset]
  2859. // [,out uint Status]
  2860. // );
  2861. //
  2862. // Signature for TextureCube/TextureCubeArray:
  2863. //
  2864. // float4 GatherCmp(
  2865. // in SamplerComparisonState s,
  2866. // in float2 location,
  2867. // in float compare_value,
  2868. // out uint Status
  2869. // );
  2870. //
  2871. // Other Texture types do not have the GatherCmp method.
  2872. const FunctionDecl *callee = expr->getDirectCallee();
  2873. const auto numArgs = expr->getNumArgs();
  2874. const auto loc = expr->getExprLoc();
  2875. const bool hasStatusArg =
  2876. expr->getArg(numArgs - 1)->getType()->isUnsignedIntegerType();
  2877. const bool hasOffsetArg = (numArgs == 5) || (numArgs == 4 && !hasStatusArg);
  2878. const auto *imageExpr = expr->getImplicitObjectArgument();
  2879. auto *image = loadIfGLValue(imageExpr);
  2880. auto *sampler = doExpr(expr->getArg(0));
  2881. auto *coordinate = doExpr(expr->getArg(1));
  2882. auto *comparator = doExpr(expr->getArg(2));
  2883. SpirvInstruction *constOffset = nullptr, *varOffset = nullptr;
  2884. if (hasOffsetArg)
  2885. handleOffsetInMethodCall(expr, 3, &constOffset, &varOffset);
  2886. const auto retType = callee->getReturnType();
  2887. const auto imageType = imageExpr->getType();
  2888. const auto status =
  2889. hasStatusArg ? doExpr(expr->getArg(numArgs - 1)) : nullptr;
  2890. return spvBuilder.createImageGather(
  2891. retType, imageType, image, sampler, coordinate,
  2892. /*component*/ nullptr, comparator, constOffset, varOffset,
  2893. /*constOffsets*/ nullptr,
  2894. /*sampleNumber*/ nullptr, status, loc);
  2895. }
  2896. SpirvInstruction *SpirvEmitter::processBufferTextureLoad(
  2897. const Expr *object, SpirvInstruction *location,
  2898. SpirvInstruction *constOffset, SpirvInstruction *varOffset,
  2899. SpirvInstruction *lod, SpirvInstruction *residencyCode,
  2900. SourceLocation loc) {
  2901. // Loading for Buffer and RWBuffer translates to an OpImageFetch.
  2902. // The result type of an OpImageFetch must be a vec4 of float or int.
  2903. const auto type = object->getType();
  2904. assert(isBuffer(type) || isRWBuffer(type) || isTexture(type) ||
  2905. isRWTexture(type) || isSubpassInput(type) || isSubpassInputMS(type));
  2906. const bool doFetch = isBuffer(type) || isTexture(type);
  2907. auto *objectInfo = loadIfGLValue(object);
  2908. // For Texture2DMS and Texture2DMSArray, Sample must be used rather than Lod.
  2909. SpirvInstruction *sampleNumber = nullptr;
  2910. if (isTextureMS(type) || isSubpassInputMS(type)) {
  2911. sampleNumber = lod;
  2912. lod = nullptr;
  2913. }
  2914. const auto sampledType = hlsl::GetHLSLResourceResultType(type);
  2915. QualType elemType = sampledType;
  2916. uint32_t elemCount = 1;
  2917. bool isTemplateOverStruct = false;
  2918. // Check whether the template type is a vector type or struct type.
  2919. if (!isVectorType(sampledType, &elemType, &elemCount)) {
  2920. if (sampledType->getAsStructureType()) {
  2921. isTemplateOverStruct = true;
  2922. // For struct type, we need to make sure it can fit into a 4-component
  2923. // vector. Detailed failing reasons will be emitted by the function so
  2924. // we don't need to emit errors here.
  2925. if (!canFitIntoOneRegister(astContext, sampledType, &elemType,
  2926. &elemCount))
  2927. return nullptr;
  2928. }
  2929. }
  2930. if (!elemType->isFloatingType() && !elemType->isIntegerType()) {
  2931. emitError("loading %0 value unsupported", object->getExprLoc()) << type;
  2932. return nullptr;
  2933. }
  2934. // OpImageFetch and OpImageRead can only fetch a vector of 4 elements.
  2935. const QualType texelType = astContext.getExtVectorType(elemType, 4u);
  2936. auto *texel = spvBuilder.createImageFetchOrRead(
  2937. doFetch, texelType, type, objectInfo, location, lod, constOffset,
  2938. varOffset, /*constOffsets*/ nullptr, sampleNumber, residencyCode, loc);
  2939. // If the result type is a vec1, vec2, or vec3, some extra processing
  2940. // (extraction) is required.
  2941. auto *retVal = extractVecFromVec4(texel, elemCount, elemType, loc);
  2942. if (isTemplateOverStruct) {
  2943. // Convert to the struct so that we are consistent with types in the AST.
  2944. retVal = convertVectorToStruct(sampledType, elemType, retVal, loc);
  2945. }
  2946. retVal->setRValue();
  2947. return retVal;
  2948. }
  2949. SpirvInstruction *SpirvEmitter::processByteAddressBufferLoadStore(
  2950. const CXXMemberCallExpr *expr, uint32_t numWords, bool doStore) {
  2951. SpirvInstruction *result = nullptr;
  2952. const auto object = expr->getImplicitObjectArgument();
  2953. auto *objectInfo = loadIfAliasVarRef(object);
  2954. assert(numWords >= 1 && numWords <= 4);
  2955. if (doStore) {
  2956. assert(isRWByteAddressBuffer(object->getType()));
  2957. assert(expr->getNumArgs() == 2);
  2958. } else {
  2959. assert(isRWByteAddressBuffer(object->getType()) ||
  2960. isByteAddressBuffer(object->getType()));
  2961. if (expr->getNumArgs() == 2) {
  2962. emitError(
  2963. "(RW)ByteAddressBuffer::Load(in address, out status) not supported",
  2964. expr->getExprLoc());
  2965. return 0;
  2966. }
  2967. }
  2968. const Expr *addressExpr = expr->getArg(0);
  2969. auto *byteAddress = doExpr(addressExpr);
  2970. const QualType addressType = addressExpr->getType();
  2971. // The front-end prevents usage of templated Load2, Load3, Load4, Store2,
  2972. // Store3, Store4 intrinsic functions.
  2973. const bool isTemplatedLoadOrStore =
  2974. (numWords == 1) &&
  2975. (doStore ? !expr->getArg(1)->getType()->isSpecificBuiltinType(
  2976. BuiltinType::UInt)
  2977. : !expr->getType()->isSpecificBuiltinType(BuiltinType::UInt));
  2978. // Do a OpShiftRightLogical by 2 (divide by 4 to get aligned memory
  2979. // access). The AST always casts the address to unsinged integer, so shift
  2980. // by unsinged integer 2.
  2981. auto *constUint2 =
  2982. spvBuilder.getConstantInt(astContext.UnsignedIntTy, llvm::APInt(32, 2));
  2983. SpirvInstruction *address =
  2984. spvBuilder.createBinaryOp(spv::Op::OpShiftRightLogical, addressType,
  2985. byteAddress, constUint2, expr->getExprLoc());
  2986. if (isTemplatedLoadOrStore) {
  2987. // Templated load. Need to (potentially) perform more
  2988. // loads/casts/composite-constructs.
  2989. uint32_t bitOffset = 0;
  2990. if (doStore) {
  2991. auto *values = doExpr(expr->getArg(1));
  2992. RawBufferHandler(*this).processTemplatedStoreToBuffer(
  2993. values, objectInfo, address, expr->getArg(1)->getType(), bitOffset);
  2994. return nullptr;
  2995. } else {
  2996. RawBufferHandler rawBufferHandler(*this);
  2997. return rawBufferHandler.processTemplatedLoadFromBuffer(
  2998. objectInfo, address, expr->getType(), bitOffset);
  2999. }
  3000. }
  3001. // Perform access chain into the RWByteAddressBuffer.
  3002. // First index must be zero (member 0 of the struct is a
  3003. // runtimeArray). The second index passed to OpAccessChain should be
  3004. // the address.
  3005. auto *constUint0 =
  3006. spvBuilder.getConstantInt(astContext.UnsignedIntTy, llvm::APInt(32, 0));
  3007. if (doStore) {
  3008. auto *values = doExpr(expr->getArg(1));
  3009. auto *curStoreAddress = address;
  3010. for (uint32_t wordCounter = 0; wordCounter < numWords; ++wordCounter) {
  3011. // Extract a 32-bit word from the input.
  3012. auto *curValue = numWords == 1
  3013. ? values
  3014. : spvBuilder.createCompositeExtract(
  3015. astContext.UnsignedIntTy, values,
  3016. {wordCounter}, expr->getArg(1)->getExprLoc());
  3017. // Update the output address if necessary.
  3018. if (wordCounter > 0) {
  3019. auto *offset = spvBuilder.getConstantInt(astContext.UnsignedIntTy,
  3020. llvm::APInt(32, wordCounter));
  3021. curStoreAddress =
  3022. spvBuilder.createBinaryOp(spv::Op::OpIAdd, addressType, address,
  3023. offset, expr->getCallee()->getExprLoc());
  3024. }
  3025. // Store the word to the right address at the output.
  3026. auto *storePtr = spvBuilder.createAccessChain(
  3027. astContext.UnsignedIntTy, objectInfo, {constUint0, curStoreAddress},
  3028. object->getLocStart());
  3029. spvBuilder.createStore(storePtr, curValue,
  3030. expr->getCallee()->getExprLoc());
  3031. }
  3032. } else {
  3033. auto *loadPtr = spvBuilder.createAccessChain(
  3034. astContext.UnsignedIntTy, objectInfo, {constUint0, address},
  3035. object->getLocStart());
  3036. result = spvBuilder.createLoad(astContext.UnsignedIntTy, loadPtr,
  3037. expr->getCallee()->getExprLoc());
  3038. if (numWords > 1) {
  3039. // Load word 2, 3, and 4 where necessary. Use OpCompositeConstruct to
  3040. // return a vector result.
  3041. llvm::SmallVector<SpirvInstruction *, 4> values;
  3042. values.push_back(result);
  3043. for (uint32_t wordCounter = 2; wordCounter <= numWords; ++wordCounter) {
  3044. auto *offset = spvBuilder.getConstantInt(
  3045. astContext.UnsignedIntTy, llvm::APInt(32, wordCounter - 1));
  3046. auto *newAddress =
  3047. spvBuilder.createBinaryOp(spv::Op::OpIAdd, addressType, address,
  3048. offset, expr->getCallee()->getExprLoc());
  3049. loadPtr = spvBuilder.createAccessChain(
  3050. astContext.UnsignedIntTy, objectInfo, {constUint0, newAddress},
  3051. object->getLocStart());
  3052. values.push_back(
  3053. spvBuilder.createLoad(astContext.UnsignedIntTy, loadPtr,
  3054. expr->getCallee()->getExprLoc()));
  3055. }
  3056. const QualType resultType =
  3057. astContext.getExtVectorType(addressType, numWords);
  3058. result = spvBuilder.createCompositeConstruct(resultType, values,
  3059. expr->getLocStart());
  3060. result->setRValue();
  3061. }
  3062. }
  3063. return result;
  3064. }
  3065. SpirvInstruction *
  3066. SpirvEmitter::processStructuredBufferLoad(const CXXMemberCallExpr *expr) {
  3067. if (expr->getNumArgs() == 2) {
  3068. emitError(
  3069. "(RW)StructuredBuffer::Load(in location, out status) not supported",
  3070. expr->getExprLoc());
  3071. return 0;
  3072. }
  3073. const auto *buffer = expr->getImplicitObjectArgument();
  3074. auto *info = loadIfAliasVarRef(buffer);
  3075. const QualType structType =
  3076. hlsl::GetHLSLResourceResultType(buffer->getType());
  3077. auto *zero = spvBuilder.getConstantInt(astContext.IntTy, llvm::APInt(32, 0));
  3078. auto *index = doExpr(expr->getArg(0));
  3079. return turnIntoElementPtr(buffer->getType(), info, structType, {zero, index},
  3080. buffer->getExprLoc());
  3081. }
  3082. SpirvInstruction *
  3083. SpirvEmitter::incDecRWACSBufferCounter(const CXXMemberCallExpr *expr,
  3084. bool isInc, bool loadObject) {
  3085. auto *zero =
  3086. spvBuilder.getConstantInt(astContext.UnsignedIntTy, llvm::APInt(32, 0));
  3087. auto *sOne =
  3088. spvBuilder.getConstantInt(astContext.IntTy, llvm::APInt(32, 1, true));
  3089. const auto srcLoc = expr->getCallee()->getExprLoc();
  3090. const auto *object =
  3091. expr->getImplicitObjectArgument()->IgnoreParenNoopCasts(astContext);
  3092. if (loadObject) {
  3093. // We don't need the object's <result-id> here since counter variable is a
  3094. // separate variable. But we still need the side effects of evaluating the
  3095. // object, e.g., if the source code is foo(...).IncrementCounter(), we still
  3096. // want to emit the code for foo(...).
  3097. (void)doExpr(object);
  3098. }
  3099. const auto *counterPair = getFinalACSBufferCounter(object);
  3100. if (!counterPair) {
  3101. emitFatalError("cannot find the associated counter variable",
  3102. object->getExprLoc());
  3103. return nullptr;
  3104. }
  3105. auto *counterPtr = spvBuilder.createAccessChain(
  3106. astContext.IntTy, counterPair->get(spvBuilder, spvContext), {zero},
  3107. srcLoc);
  3108. SpirvInstruction *index = nullptr;
  3109. if (isInc) {
  3110. index = spvBuilder.createAtomicOp(
  3111. spv::Op::OpAtomicIAdd, astContext.IntTy, counterPtr, spv::Scope::Device,
  3112. spv::MemorySemanticsMask::MaskNone, sOne, srcLoc);
  3113. } else {
  3114. // Note that OpAtomicISub returns the value before the subtraction;
  3115. // so we need to do substraction again with OpAtomicISub's return value.
  3116. auto *prev = spvBuilder.createAtomicOp(
  3117. spv::Op::OpAtomicISub, astContext.IntTy, counterPtr, spv::Scope::Device,
  3118. spv::MemorySemanticsMask::MaskNone, sOne, srcLoc);
  3119. index = spvBuilder.createBinaryOp(spv::Op::OpISub, astContext.IntTy, prev,
  3120. sOne, srcLoc);
  3121. }
  3122. return index;
  3123. }
  3124. bool SpirvEmitter::tryToAssignCounterVar(const DeclaratorDecl *dstDecl,
  3125. const Expr *srcExpr) {
  3126. // We are handling associated counters here. Casts should not alter which
  3127. // associated counter to manipulate.
  3128. srcExpr = srcExpr->IgnoreParenCasts();
  3129. // For parameters of forward-declared functions. We must make sure the
  3130. // associated counter variable is created. But for forward-declared functions,
  3131. // the translation of the real definition may not be started yet.
  3132. if (const auto *param = dyn_cast<ParmVarDecl>(dstDecl))
  3133. declIdMapper.createFnParamCounterVar(param);
  3134. // For implicit objects of methods. Similar to the above.
  3135. else if (const auto *thisObject = dyn_cast<ImplicitParamDecl>(dstDecl))
  3136. declIdMapper.createFnParamCounterVar(thisObject);
  3137. // Handle AssocCounter#1 (see CounterVarFields comment)
  3138. if (const auto *dstPair = declIdMapper.getCounterIdAliasPair(dstDecl)) {
  3139. const auto *srcPair = getFinalACSBufferCounter(srcExpr);
  3140. if (!srcPair) {
  3141. emitFatalError("cannot find the associated counter variable",
  3142. srcExpr->getExprLoc());
  3143. return false;
  3144. }
  3145. dstPair->assign(*srcPair, spvBuilder, spvContext);
  3146. return true;
  3147. }
  3148. // Handle AssocCounter#3
  3149. llvm::SmallVector<uint32_t, 4> srcIndices;
  3150. const auto *dstFields = declIdMapper.getCounterVarFields(dstDecl);
  3151. const auto *srcFields = getIntermediateACSBufferCounter(srcExpr, &srcIndices);
  3152. if (dstFields && srcFields) {
  3153. // The destination is a struct whose fields are directly alias resources.
  3154. // But that's not necessarily true for the source, which can be deep
  3155. // nested structs. That means they will have different index "prefixes"
  3156. // for all their fields; while the "prefix" for destination is effectively
  3157. // an empty list (since it is not nested in other structs). We need to
  3158. // strip the index prefix from the source.
  3159. return dstFields->assign(*srcFields, /*dstIndices=*/{}, srcIndices,
  3160. spvBuilder, spvContext);
  3161. }
  3162. // AssocCounter#2 and AssocCounter#4 for the lhs cannot happen since the lhs
  3163. // is a stand-alone decl in this method.
  3164. return false;
  3165. }
  3166. bool SpirvEmitter::tryToAssignCounterVar(const Expr *dstExpr,
  3167. const Expr *srcExpr) {
  3168. dstExpr = dstExpr->IgnoreParenCasts();
  3169. srcExpr = srcExpr->IgnoreParenCasts();
  3170. const auto *dstPair = getFinalACSBufferCounter(dstExpr);
  3171. const auto *srcPair = getFinalACSBufferCounter(srcExpr);
  3172. if ((dstPair == nullptr) != (srcPair == nullptr)) {
  3173. emitFatalError("cannot handle associated counter variable assignment",
  3174. srcExpr->getExprLoc());
  3175. return false;
  3176. }
  3177. // Handle AssocCounter#1 & AssocCounter#2
  3178. if (dstPair && srcPair) {
  3179. dstPair->assign(*srcPair, spvBuilder, spvContext);
  3180. return true;
  3181. }
  3182. // Handle AssocCounter#3 & AssocCounter#4
  3183. llvm::SmallVector<uint32_t, 4> dstIndices;
  3184. llvm::SmallVector<uint32_t, 4> srcIndices;
  3185. const auto *srcFields = getIntermediateACSBufferCounter(srcExpr, &srcIndices);
  3186. const auto *dstFields = getIntermediateACSBufferCounter(dstExpr, &dstIndices);
  3187. if (dstFields && srcFields) {
  3188. return dstFields->assign(*srcFields, dstIndices, srcIndices, spvBuilder,
  3189. spvContext);
  3190. }
  3191. return false;
  3192. }
  3193. const CounterIdAliasPair *
  3194. SpirvEmitter::getFinalACSBufferCounter(const Expr *expr) {
  3195. // AssocCounter#1: referencing some stand-alone variable
  3196. if (const auto *decl = getReferencedDef(expr))
  3197. return declIdMapper.getCounterIdAliasPair(decl);
  3198. // AssocCounter#2: referencing some non-struct field
  3199. llvm::SmallVector<uint32_t, 4> rawIndices;
  3200. const auto *base = collectArrayStructIndices(
  3201. expr, /*rawIndex=*/true, &rawIndices, /*indices*/ nullptr);
  3202. const auto *decl =
  3203. (base && isa<CXXThisExpr>(base))
  3204. ? getOrCreateDeclForMethodObject(cast<CXXMethodDecl>(curFunction))
  3205. : getReferencedDef(base);
  3206. return declIdMapper.getCounterIdAliasPair(decl, &rawIndices);
  3207. }
  3208. const CounterVarFields *SpirvEmitter::getIntermediateACSBufferCounter(
  3209. const Expr *expr, llvm::SmallVector<uint32_t, 4> *rawIndices) {
  3210. const auto *base = collectArrayStructIndices(expr, /*rawIndex=*/true,
  3211. rawIndices, /*indices*/ nullptr);
  3212. const auto *decl =
  3213. (base && isa<CXXThisExpr>(base))
  3214. // Use the decl we created to represent the implicit object
  3215. ? getOrCreateDeclForMethodObject(cast<CXXMethodDecl>(curFunction))
  3216. // Find the referenced decl from the original source code
  3217. : getReferencedDef(base);
  3218. return declIdMapper.getCounterVarFields(decl);
  3219. }
  3220. const ImplicitParamDecl *
  3221. SpirvEmitter::getOrCreateDeclForMethodObject(const CXXMethodDecl *method) {
  3222. const auto found = thisDecls.find(method);
  3223. if (found != thisDecls.end())
  3224. return found->second;
  3225. const std::string name = method->getName().str() + ".this";
  3226. // Create a new identifier to convey the name
  3227. auto &identifier = astContext.Idents.get(name);
  3228. return thisDecls[method] = ImplicitParamDecl::Create(
  3229. astContext, /*DC=*/nullptr, SourceLocation(), &identifier,
  3230. method->getThisType(astContext)->getPointeeType());
  3231. }
  3232. SpirvInstruction *
  3233. SpirvEmitter::processACSBufferAppendConsume(const CXXMemberCallExpr *expr) {
  3234. const bool isAppend = expr->getNumArgs() == 1;
  3235. auto *zero =
  3236. spvBuilder.getConstantInt(astContext.UnsignedIntTy, llvm::APInt(32, 0));
  3237. const auto *object =
  3238. expr->getImplicitObjectArgument()->IgnoreParenNoopCasts(astContext);
  3239. auto *bufferInfo = loadIfAliasVarRef(object);
  3240. auto *index = incDecRWACSBufferCounter(
  3241. expr, isAppend,
  3242. // We have already translated the object in the above. Avoid duplication.
  3243. /*loadObject=*/false);
  3244. auto bufferElemTy = hlsl::GetHLSLResourceResultType(object->getType());
  3245. // If this is a variable to communicate with host e.g., ACSBuffer
  3246. // and its type is bool or vector of bool, its effective type used
  3247. // for SPIRV must be uint not bool. We must convert it to uint here.
  3248. bool needCast = false;
  3249. if (bufferInfo->getLayoutRule() != SpirvLayoutRule::Void &&
  3250. isBoolOrVecOfBoolType(bufferElemTy)) {
  3251. uint32_t vecSize = 1;
  3252. const bool isVec = isVectorType(bufferElemTy, nullptr, &vecSize);
  3253. bufferElemTy =
  3254. isVec ? astContext.getExtVectorType(astContext.UnsignedIntTy, vecSize)
  3255. : astContext.UnsignedIntTy;
  3256. needCast = true;
  3257. }
  3258. bufferInfo = turnIntoElementPtr(object->getType(), bufferInfo, bufferElemTy,
  3259. {zero, index}, object->getExprLoc());
  3260. if (isAppend) {
  3261. // Write out the value
  3262. auto *arg0 = doExpr(expr->getArg(0));
  3263. if (!arg0)
  3264. return nullptr;
  3265. if (!arg0->isRValue()) {
  3266. arg0 = spvBuilder.createLoad(bufferElemTy, arg0,
  3267. expr->getArg(0)->getExprLoc());
  3268. }
  3269. if (needCast &&
  3270. !isSameType(astContext, bufferElemTy, arg0->getAstResultType())) {
  3271. arg0 = castToType(arg0, arg0->getAstResultType(), bufferElemTy,
  3272. expr->getArg(0)->getExprLoc());
  3273. }
  3274. storeValue(bufferInfo, arg0, bufferElemTy, expr->getCallee()->getExprLoc());
  3275. return 0;
  3276. } else {
  3277. // Note that we are returning a pointer (lvalue) here inorder to further
  3278. // acess the fields in this element, e.g., buffer.Consume().a.b. So we
  3279. // cannot forcefully set all normal function calls as returning rvalue.
  3280. return bufferInfo;
  3281. }
  3282. }
  3283. SpirvInstruction *
  3284. SpirvEmitter::processStreamOutputAppend(const CXXMemberCallExpr *expr) {
  3285. // TODO: handle multiple stream-output objects
  3286. const auto *object =
  3287. expr->getImplicitObjectArgument()->IgnoreParenNoopCasts(astContext);
  3288. const auto *stream = cast<DeclRefExpr>(object)->getDecl();
  3289. auto *value = doExpr(expr->getArg(0));
  3290. declIdMapper.writeBackOutputStream(stream, stream->getType(), value);
  3291. spvBuilder.createEmitVertex(expr->getExprLoc());
  3292. return nullptr;
  3293. }
  3294. SpirvInstruction *
  3295. SpirvEmitter::processStreamOutputRestart(const CXXMemberCallExpr *expr) {
  3296. // TODO: handle multiple stream-output objects
  3297. spvBuilder.createEndPrimitive(expr->getExprLoc());
  3298. return 0;
  3299. }
  3300. SpirvInstruction *
  3301. SpirvEmitter::emitGetSamplePosition(SpirvInstruction *sampleCount,
  3302. SpirvInstruction *sampleIndex,
  3303. SourceLocation loc) {
  3304. struct Float2 {
  3305. float x;
  3306. float y;
  3307. };
  3308. static const Float2 pos2[] = {
  3309. {4.0 / 16.0, 4.0 / 16.0},
  3310. {-4.0 / 16.0, -4.0 / 16.0},
  3311. };
  3312. static const Float2 pos4[] = {
  3313. {-2.0 / 16.0, -6.0 / 16.0},
  3314. {6.0 / 16.0, -2.0 / 16.0},
  3315. {-6.0 / 16.0, 2.0 / 16.0},
  3316. {2.0 / 16.0, 6.0 / 16.0},
  3317. };
  3318. static const Float2 pos8[] = {
  3319. {1.0 / 16.0, -3.0 / 16.0}, {-1.0 / 16.0, 3.0 / 16.0},
  3320. {5.0 / 16.0, 1.0 / 16.0}, {-3.0 / 16.0, -5.0 / 16.0},
  3321. {-5.0 / 16.0, 5.0 / 16.0}, {-7.0 / 16.0, -1.0 / 16.0},
  3322. {3.0 / 16.0, 7.0 / 16.0}, {7.0 / 16.0, -7.0 / 16.0},
  3323. };
  3324. static const Float2 pos16[] = {
  3325. {1.0 / 16.0, 1.0 / 16.0}, {-1.0 / 16.0, -3.0 / 16.0},
  3326. {-3.0 / 16.0, 2.0 / 16.0}, {4.0 / 16.0, -1.0 / 16.0},
  3327. {-5.0 / 16.0, -2.0 / 16.0}, {2.0 / 16.0, 5.0 / 16.0},
  3328. {5.0 / 16.0, 3.0 / 16.0}, {3.0 / 16.0, -5.0 / 16.0},
  3329. {-2.0 / 16.0, 6.0 / 16.0}, {0.0 / 16.0, -7.0 / 16.0},
  3330. {-4.0 / 16.0, -6.0 / 16.0}, {-6.0 / 16.0, 4.0 / 16.0},
  3331. {-8.0 / 16.0, 0.0 / 16.0}, {7.0 / 16.0, -4.0 / 16.0},
  3332. {6.0 / 16.0, 7.0 / 16.0}, {-7.0 / 16.0, -8.0 / 16.0},
  3333. };
  3334. // We are emitting the SPIR-V for the following HLSL source code:
  3335. //
  3336. // float2 position;
  3337. //
  3338. // if (count == 2) {
  3339. // position = pos2[index];
  3340. // }
  3341. // else if (count == 4) {
  3342. // position = pos4[index];
  3343. // }
  3344. // else if (count == 8) {
  3345. // position = pos8[index];
  3346. // }
  3347. // else if (count == 16) {
  3348. // position = pos16[index];
  3349. // }
  3350. // else {
  3351. // position = float2(0.0f, 0.0f);
  3352. // }
  3353. const auto v2f32Type = astContext.getExtVectorType(astContext.FloatTy, 2);
  3354. // Creates a SPIR-V function scope variable of type float2[len].
  3355. const auto createArray = [this, v2f32Type, loc](const Float2 *ptr,
  3356. uint32_t len) {
  3357. llvm::SmallVector<SpirvConstant *, 16> components;
  3358. for (uint32_t i = 0; i < len; ++i) {
  3359. auto *x = spvBuilder.getConstantFloat(astContext.FloatTy,
  3360. llvm::APFloat(ptr[i].x));
  3361. auto *y = spvBuilder.getConstantFloat(astContext.FloatTy,
  3362. llvm::APFloat(ptr[i].y));
  3363. components.push_back(spvBuilder.getConstantComposite(v2f32Type, {x, y}));
  3364. }
  3365. const auto arrType = astContext.getConstantArrayType(
  3366. v2f32Type, llvm::APInt(32, len), clang::ArrayType::Normal, 0);
  3367. auto *val = spvBuilder.getConstantComposite(arrType, components);
  3368. const std::string varName =
  3369. "var.GetSamplePosition.data." + std::to_string(len);
  3370. auto *var = spvBuilder.addFnVar(arrType, loc, varName);
  3371. spvBuilder.createStore(var, val, loc);
  3372. return var;
  3373. };
  3374. auto *pos2Arr = createArray(pos2, 2);
  3375. auto *pos4Arr = createArray(pos4, 4);
  3376. auto *pos8Arr = createArray(pos8, 8);
  3377. auto *pos16Arr = createArray(pos16, 16);
  3378. auto *resultVar =
  3379. spvBuilder.addFnVar(v2f32Type, loc, "var.GetSamplePosition.result");
  3380. auto *then2BB = spvBuilder.createBasicBlock("if.GetSamplePosition.then2");
  3381. auto *then4BB = spvBuilder.createBasicBlock("if.GetSamplePosition.then4");
  3382. auto *then8BB = spvBuilder.createBasicBlock("if.GetSamplePosition.then8");
  3383. auto *then16BB = spvBuilder.createBasicBlock("if.GetSamplePosition.then16");
  3384. auto *else2BB = spvBuilder.createBasicBlock("if.GetSamplePosition.else2");
  3385. auto *else4BB = spvBuilder.createBasicBlock("if.GetSamplePosition.else4");
  3386. auto *else8BB = spvBuilder.createBasicBlock("if.GetSamplePosition.else8");
  3387. auto *else16BB = spvBuilder.createBasicBlock("if.GetSamplePosition.else16");
  3388. auto *merge2BB = spvBuilder.createBasicBlock("if.GetSamplePosition.merge2");
  3389. auto *merge4BB = spvBuilder.createBasicBlock("if.GetSamplePosition.merge4");
  3390. auto *merge8BB = spvBuilder.createBasicBlock("if.GetSamplePosition.merge8");
  3391. auto *merge16BB = spvBuilder.createBasicBlock("if.GetSamplePosition.merge16");
  3392. // if (count == 2) {
  3393. const auto check2 = spvBuilder.createBinaryOp(
  3394. spv::Op::OpIEqual, astContext.BoolTy, sampleCount,
  3395. spvBuilder.getConstantInt(astContext.UnsignedIntTy, llvm::APInt(32, 2)),
  3396. loc);
  3397. spvBuilder.createConditionalBranch(check2, then2BB, else2BB, loc, merge2BB);
  3398. spvBuilder.addSuccessor(then2BB);
  3399. spvBuilder.addSuccessor(else2BB);
  3400. spvBuilder.setMergeTarget(merge2BB);
  3401. // position = pos2[index];
  3402. // }
  3403. spvBuilder.setInsertPoint(then2BB);
  3404. auto *ac =
  3405. spvBuilder.createAccessChain(v2f32Type, pos2Arr, {sampleIndex}, loc);
  3406. spvBuilder.createStore(resultVar, spvBuilder.createLoad(v2f32Type, ac, loc),
  3407. loc);
  3408. spvBuilder.createBranch(merge2BB, loc);
  3409. spvBuilder.addSuccessor(merge2BB);
  3410. // else if (count == 4) {
  3411. spvBuilder.setInsertPoint(else2BB);
  3412. const auto check4 = spvBuilder.createBinaryOp(
  3413. spv::Op::OpIEqual, astContext.BoolTy, sampleCount,
  3414. spvBuilder.getConstantInt(astContext.UnsignedIntTy, llvm::APInt(32, 4)),
  3415. loc);
  3416. spvBuilder.createConditionalBranch(check4, then4BB, else4BB, loc, merge4BB);
  3417. spvBuilder.addSuccessor(then4BB);
  3418. spvBuilder.addSuccessor(else4BB);
  3419. spvBuilder.setMergeTarget(merge4BB);
  3420. // position = pos4[index];
  3421. // }
  3422. spvBuilder.setInsertPoint(then4BB);
  3423. ac = spvBuilder.createAccessChain(v2f32Type, pos4Arr, {sampleIndex}, loc);
  3424. spvBuilder.createStore(resultVar, spvBuilder.createLoad(v2f32Type, ac, loc),
  3425. loc);
  3426. spvBuilder.createBranch(merge4BB, loc);
  3427. spvBuilder.addSuccessor(merge4BB);
  3428. // else if (count == 8) {
  3429. spvBuilder.setInsertPoint(else4BB);
  3430. const auto check8 = spvBuilder.createBinaryOp(
  3431. spv::Op::OpIEqual, astContext.BoolTy, sampleCount,
  3432. spvBuilder.getConstantInt(astContext.UnsignedIntTy, llvm::APInt(32, 8)),
  3433. loc);
  3434. spvBuilder.createConditionalBranch(check8, then8BB, else8BB, loc, merge8BB);
  3435. spvBuilder.addSuccessor(then8BB);
  3436. spvBuilder.addSuccessor(else8BB);
  3437. spvBuilder.setMergeTarget(merge8BB);
  3438. // position = pos8[index];
  3439. // }
  3440. spvBuilder.setInsertPoint(then8BB);
  3441. ac = spvBuilder.createAccessChain(v2f32Type, pos8Arr, {sampleIndex}, loc);
  3442. spvBuilder.createStore(resultVar, spvBuilder.createLoad(v2f32Type, ac, loc),
  3443. loc);
  3444. spvBuilder.createBranch(merge8BB, loc);
  3445. spvBuilder.addSuccessor(merge8BB);
  3446. // else if (count == 16) {
  3447. spvBuilder.setInsertPoint(else8BB);
  3448. const auto check16 = spvBuilder.createBinaryOp(
  3449. spv::Op::OpIEqual, astContext.BoolTy, sampleCount,
  3450. spvBuilder.getConstantInt(astContext.UnsignedIntTy, llvm::APInt(32, 16)),
  3451. loc);
  3452. spvBuilder.createConditionalBranch(check16, then16BB, else16BB, loc,
  3453. merge16BB);
  3454. spvBuilder.addSuccessor(then16BB);
  3455. spvBuilder.addSuccessor(else16BB);
  3456. spvBuilder.setMergeTarget(merge16BB);
  3457. // position = pos16[index];
  3458. // }
  3459. spvBuilder.setInsertPoint(then16BB);
  3460. ac = spvBuilder.createAccessChain(v2f32Type, pos16Arr, {sampleIndex}, loc);
  3461. spvBuilder.createStore(resultVar, spvBuilder.createLoad(v2f32Type, ac, loc),
  3462. loc);
  3463. spvBuilder.createBranch(merge16BB, loc);
  3464. spvBuilder.addSuccessor(merge16BB);
  3465. // else {
  3466. // position = float2(0.0f, 0.0f);
  3467. // }
  3468. spvBuilder.setInsertPoint(else16BB);
  3469. auto *zero =
  3470. spvBuilder.getConstantFloat(astContext.FloatTy, llvm::APFloat(0.0f));
  3471. auto *v2f32Zero = spvBuilder.getConstantComposite(v2f32Type, {zero, zero});
  3472. spvBuilder.createStore(resultVar, v2f32Zero, loc);
  3473. spvBuilder.createBranch(merge16BB, loc);
  3474. spvBuilder.addSuccessor(merge16BB);
  3475. spvBuilder.setInsertPoint(merge16BB);
  3476. spvBuilder.createBranch(merge8BB, loc);
  3477. spvBuilder.addSuccessor(merge8BB);
  3478. spvBuilder.setInsertPoint(merge8BB);
  3479. spvBuilder.createBranch(merge4BB, loc);
  3480. spvBuilder.addSuccessor(merge4BB);
  3481. spvBuilder.setInsertPoint(merge4BB);
  3482. spvBuilder.createBranch(merge2BB, loc);
  3483. spvBuilder.addSuccessor(merge2BB);
  3484. spvBuilder.setInsertPoint(merge2BB);
  3485. return spvBuilder.createLoad(v2f32Type, resultVar, loc);
  3486. }
  3487. SpirvInstruction *
  3488. SpirvEmitter::doCXXMemberCallExpr(const CXXMemberCallExpr *expr) {
  3489. const FunctionDecl *callee = expr->getDirectCallee();
  3490. llvm::StringRef group;
  3491. uint32_t opcode = static_cast<uint32_t>(hlsl::IntrinsicOp::Num_Intrinsics);
  3492. if (hlsl::GetIntrinsicOp(callee, opcode, group)) {
  3493. return processIntrinsicMemberCall(expr,
  3494. static_cast<hlsl::IntrinsicOp>(opcode));
  3495. }
  3496. return processCall(expr);
  3497. }
  3498. void SpirvEmitter::handleOffsetInMethodCall(const CXXMemberCallExpr *expr,
  3499. uint32_t index,
  3500. SpirvInstruction **constOffset,
  3501. SpirvInstruction **varOffset) {
  3502. assert(constOffset && varOffset);
  3503. // Ensure the given arg index is not out-of-range.
  3504. assert(index < expr->getNumArgs());
  3505. *constOffset = *varOffset = nullptr; // Initialize both first
  3506. if ((*constOffset = tryToEvaluateAsConst(expr->getArg(index))))
  3507. return; // Constant offset
  3508. else
  3509. *varOffset = doExpr(expr->getArg(index));
  3510. }
  3511. SpirvInstruction *
  3512. SpirvEmitter::processIntrinsicMemberCall(const CXXMemberCallExpr *expr,
  3513. hlsl::IntrinsicOp opcode) {
  3514. using namespace hlsl;
  3515. SpirvInstruction *retVal = nullptr;
  3516. switch (opcode) {
  3517. case IntrinsicOp::MOP_Sample:
  3518. retVal = processTextureSampleGather(expr, /*isSample=*/true);
  3519. break;
  3520. case IntrinsicOp::MOP_Gather:
  3521. retVal = processTextureSampleGather(expr, /*isSample=*/false);
  3522. break;
  3523. case IntrinsicOp::MOP_SampleBias:
  3524. retVal = processTextureSampleBiasLevel(expr, /*isBias=*/true);
  3525. break;
  3526. case IntrinsicOp::MOP_SampleLevel:
  3527. retVal = processTextureSampleBiasLevel(expr, /*isBias=*/false);
  3528. break;
  3529. case IntrinsicOp::MOP_SampleGrad:
  3530. retVal = processTextureSampleGrad(expr);
  3531. break;
  3532. case IntrinsicOp::MOP_SampleCmp:
  3533. retVal = processTextureSampleCmpCmpLevelZero(expr, /*isCmp=*/true);
  3534. break;
  3535. case IntrinsicOp::MOP_SampleCmpLevelZero:
  3536. retVal = processTextureSampleCmpCmpLevelZero(expr, /*isCmp=*/false);
  3537. break;
  3538. case IntrinsicOp::MOP_GatherRed:
  3539. retVal = processTextureGatherRGBACmpRGBA(expr, /*isCmp=*/false, 0);
  3540. break;
  3541. case IntrinsicOp::MOP_GatherGreen:
  3542. retVal = processTextureGatherRGBACmpRGBA(expr, /*isCmp=*/false, 1);
  3543. break;
  3544. case IntrinsicOp::MOP_GatherBlue:
  3545. retVal = processTextureGatherRGBACmpRGBA(expr, /*isCmp=*/false, 2);
  3546. break;
  3547. case IntrinsicOp::MOP_GatherAlpha:
  3548. retVal = processTextureGatherRGBACmpRGBA(expr, /*isCmp=*/false, 3);
  3549. break;
  3550. case IntrinsicOp::MOP_GatherCmp:
  3551. retVal = processTextureGatherCmp(expr);
  3552. break;
  3553. case IntrinsicOp::MOP_GatherCmpRed:
  3554. retVal = processTextureGatherRGBACmpRGBA(expr, /*isCmp=*/true, 0);
  3555. break;
  3556. case IntrinsicOp::MOP_Load:
  3557. return processBufferTextureLoad(expr);
  3558. case IntrinsicOp::MOP_Load2:
  3559. return processByteAddressBufferLoadStore(expr, 2, /*doStore*/ false);
  3560. case IntrinsicOp::MOP_Load3:
  3561. return processByteAddressBufferLoadStore(expr, 3, /*doStore*/ false);
  3562. case IntrinsicOp::MOP_Load4:
  3563. return processByteAddressBufferLoadStore(expr, 4, /*doStore*/ false);
  3564. case IntrinsicOp::MOP_Store:
  3565. return processByteAddressBufferLoadStore(expr, 1, /*doStore*/ true);
  3566. case IntrinsicOp::MOP_Store2:
  3567. return processByteAddressBufferLoadStore(expr, 2, /*doStore*/ true);
  3568. case IntrinsicOp::MOP_Store3:
  3569. return processByteAddressBufferLoadStore(expr, 3, /*doStore*/ true);
  3570. case IntrinsicOp::MOP_Store4:
  3571. return processByteAddressBufferLoadStore(expr, 4, /*doStore*/ true);
  3572. case IntrinsicOp::MOP_GetDimensions:
  3573. retVal = processGetDimensions(expr);
  3574. break;
  3575. case IntrinsicOp::MOP_CalculateLevelOfDetail:
  3576. retVal = processTextureLevelOfDetail(expr, /* unclamped */ false);
  3577. case IntrinsicOp::MOP_CalculateLevelOfDetailUnclamped:
  3578. retVal = processTextureLevelOfDetail(expr, /* unclamped */ true);
  3579. break;
  3580. case IntrinsicOp::MOP_IncrementCounter:
  3581. retVal =
  3582. spvBuilder.createUnaryOp(spv::Op::OpBitcast, astContext.UnsignedIntTy,
  3583. incDecRWACSBufferCounter(expr, /*isInc*/ true),
  3584. expr->getCallee()->getExprLoc());
  3585. break;
  3586. case IntrinsicOp::MOP_DecrementCounter:
  3587. retVal = spvBuilder.createUnaryOp(
  3588. spv::Op::OpBitcast, astContext.UnsignedIntTy,
  3589. incDecRWACSBufferCounter(expr, /*isInc*/ false),
  3590. expr->getCallee()->getExprLoc());
  3591. break;
  3592. case IntrinsicOp::MOP_Append:
  3593. if (hlsl::IsHLSLStreamOutputType(
  3594. expr->getImplicitObjectArgument()->getType()))
  3595. return processStreamOutputAppend(expr);
  3596. else
  3597. return processACSBufferAppendConsume(expr);
  3598. case IntrinsicOp::MOP_Consume:
  3599. return processACSBufferAppendConsume(expr);
  3600. case IntrinsicOp::MOP_RestartStrip:
  3601. retVal = processStreamOutputRestart(expr);
  3602. break;
  3603. case IntrinsicOp::MOP_InterlockedAdd:
  3604. case IntrinsicOp::MOP_InterlockedAnd:
  3605. case IntrinsicOp::MOP_InterlockedOr:
  3606. case IntrinsicOp::MOP_InterlockedXor:
  3607. case IntrinsicOp::MOP_InterlockedUMax:
  3608. case IntrinsicOp::MOP_InterlockedUMin:
  3609. case IntrinsicOp::MOP_InterlockedMax:
  3610. case IntrinsicOp::MOP_InterlockedMin:
  3611. case IntrinsicOp::MOP_InterlockedExchange:
  3612. case IntrinsicOp::MOP_InterlockedCompareExchange:
  3613. case IntrinsicOp::MOP_InterlockedCompareStore:
  3614. retVal = processRWByteAddressBufferAtomicMethods(opcode, expr);
  3615. break;
  3616. case IntrinsicOp::MOP_GetSamplePosition:
  3617. retVal = processGetSamplePosition(expr);
  3618. break;
  3619. case IntrinsicOp::MOP_SubpassLoad:
  3620. retVal = processSubpassLoad(expr);
  3621. break;
  3622. case IntrinsicOp::MOP_GatherCmpGreen:
  3623. case IntrinsicOp::MOP_GatherCmpBlue:
  3624. case IntrinsicOp::MOP_GatherCmpAlpha:
  3625. emitError("no equivalent for %0 intrinsic method in Vulkan",
  3626. expr->getCallee()->getExprLoc())
  3627. << expr->getMethodDecl()->getName();
  3628. return nullptr;
  3629. case IntrinsicOp::MOP_TraceRayInline:
  3630. return processTraceRayInline(expr);
  3631. case IntrinsicOp::MOP_Abort:
  3632. case IntrinsicOp::MOP_CandidateGeometryIndex:
  3633. case IntrinsicOp::MOP_CandidateInstanceContributionToHitGroupIndex:
  3634. case IntrinsicOp::MOP_CandidateInstanceID:
  3635. case IntrinsicOp::MOP_CandidateInstanceIndex:
  3636. case IntrinsicOp::MOP_CandidateObjectRayDirection:
  3637. case IntrinsicOp::MOP_CandidateObjectRayOrigin:
  3638. case IntrinsicOp::MOP_CandidateObjectToWorld3x4:
  3639. case IntrinsicOp::MOP_CandidateObjectToWorld4x3:
  3640. case IntrinsicOp::MOP_CandidatePrimitiveIndex:
  3641. case IntrinsicOp::MOP_CandidateProceduralPrimitiveNonOpaque:
  3642. case IntrinsicOp::MOP_CandidateTriangleBarycentrics:
  3643. case IntrinsicOp::MOP_CandidateTriangleFrontFace:
  3644. case IntrinsicOp::MOP_CandidateTriangleRayT:
  3645. case IntrinsicOp::MOP_CandidateType:
  3646. case IntrinsicOp::MOP_CandidateWorldToObject3x4:
  3647. case IntrinsicOp::MOP_CandidateWorldToObject4x3:
  3648. case IntrinsicOp::MOP_CommitNonOpaqueTriangleHit:
  3649. case IntrinsicOp::MOP_CommitProceduralPrimitiveHit:
  3650. case IntrinsicOp::MOP_CommittedGeometryIndex:
  3651. case IntrinsicOp::MOP_CommittedInstanceContributionToHitGroupIndex:
  3652. case IntrinsicOp::MOP_CommittedInstanceID:
  3653. case IntrinsicOp::MOP_CommittedInstanceIndex:
  3654. case IntrinsicOp::MOP_CommittedObjectRayDirection:
  3655. case IntrinsicOp::MOP_CommittedObjectRayOrigin:
  3656. case IntrinsicOp::MOP_CommittedObjectToWorld3x4:
  3657. case IntrinsicOp::MOP_CommittedObjectToWorld4x3:
  3658. case IntrinsicOp::MOP_CommittedPrimitiveIndex:
  3659. case IntrinsicOp::MOP_CommittedRayT:
  3660. case IntrinsicOp::MOP_CommittedStatus:
  3661. case IntrinsicOp::MOP_CommittedTriangleBarycentrics:
  3662. case IntrinsicOp::MOP_CommittedTriangleFrontFace:
  3663. case IntrinsicOp::MOP_CommittedWorldToObject3x4:
  3664. case IntrinsicOp::MOP_CommittedWorldToObject4x3:
  3665. case IntrinsicOp::MOP_Proceed:
  3666. case IntrinsicOp::MOP_RayFlags:
  3667. case IntrinsicOp::MOP_RayTMin:
  3668. case IntrinsicOp::MOP_WorldRayDirection:
  3669. case IntrinsicOp::MOP_WorldRayOrigin:
  3670. return processRayQueryIntrinsics(expr, opcode);
  3671. default:
  3672. emitError("intrinsic '%0' method unimplemented",
  3673. expr->getCallee()->getExprLoc())
  3674. << expr->getDirectCallee()->getName();
  3675. return nullptr;
  3676. }
  3677. if (retVal)
  3678. retVal->setRValue();
  3679. return retVal;
  3680. }
  3681. SpirvInstruction *SpirvEmitter::createImageSample(
  3682. QualType retType, QualType imageType, SpirvInstruction *image,
  3683. SpirvInstruction *sampler, SpirvInstruction *coordinate,
  3684. SpirvInstruction *compareVal, SpirvInstruction *bias, SpirvInstruction *lod,
  3685. std::pair<SpirvInstruction *, SpirvInstruction *> grad,
  3686. SpirvInstruction *constOffset, SpirvInstruction *varOffset,
  3687. SpirvInstruction *constOffsets, SpirvInstruction *sample,
  3688. SpirvInstruction *minLod, SpirvInstruction *residencyCodeId,
  3689. SourceLocation loc) {
  3690. // SampleDref* instructions in SPIR-V always return a scalar.
  3691. // They also have the correct type in HLSL.
  3692. if (compareVal) {
  3693. return spvBuilder.createImageSample(retType, imageType, image, sampler,
  3694. coordinate, compareVal, bias, lod, grad,
  3695. constOffset, varOffset, constOffsets,
  3696. sample, minLod, residencyCodeId, loc);
  3697. }
  3698. // Non-Dref Sample instructions in SPIR-V must always return a vec4.
  3699. auto texelType = retType;
  3700. QualType elemType = {};
  3701. uint32_t retVecSize = 0;
  3702. if (isVectorType(retType, &elemType, &retVecSize) && retVecSize != 4) {
  3703. texelType = astContext.getExtVectorType(elemType, 4);
  3704. } else if (isScalarType(retType)) {
  3705. retVecSize = 1;
  3706. elemType = retType;
  3707. texelType = astContext.getExtVectorType(retType, 4);
  3708. }
  3709. // The Lod and Grad image operands requires explicit-lod instructions.
  3710. // Otherwise we use implicit-lod instructions.
  3711. const bool isExplicit = lod || (grad.first && grad.second);
  3712. // Implicit-lod instructions are only allowed in pixel shader.
  3713. if (!spvContext.isPS() && !isExplicit)
  3714. needsLegalization = true;
  3715. auto *retVal = spvBuilder.createImageSample(
  3716. texelType, imageType, image, sampler, coordinate, compareVal, bias, lod,
  3717. grad, constOffset, varOffset, constOffsets, sample, minLod,
  3718. residencyCodeId, loc);
  3719. // Extract smaller vector from the vec4 result if necessary.
  3720. if (texelType != retType) {
  3721. retVal = extractVecFromVec4(retVal, retVecSize, elemType, loc);
  3722. }
  3723. return retVal;
  3724. }
  3725. SpirvInstruction *
  3726. SpirvEmitter::processTextureSampleGather(const CXXMemberCallExpr *expr,
  3727. const bool isSample) {
  3728. // Signatures:
  3729. // For Texture1D, Texture1DArray, Texture2D, Texture2DArray, Texture3D:
  3730. // DXGI_FORMAT Object.Sample(sampler_state S,
  3731. // float Location
  3732. // [, int Offset]
  3733. // [, float Clamp]
  3734. // [, out uint Status]);
  3735. //
  3736. // For TextureCube and TextureCubeArray:
  3737. // DXGI_FORMAT Object.Sample(sampler_state S,
  3738. // float Location
  3739. // [, float Clamp]
  3740. // [, out uint Status]);
  3741. //
  3742. // For Texture2D/Texture2DArray:
  3743. // <Template Type>4 Object.Gather(sampler_state S,
  3744. // float2|3|4 Location,
  3745. // int2 Offset
  3746. // [, uint Status]);
  3747. //
  3748. // For TextureCube/TextureCubeArray:
  3749. // <Template Type>4 Object.Gather(sampler_state S,
  3750. // float2|3|4 Location
  3751. // [, uint Status]);
  3752. //
  3753. // Other Texture types do not have a Gather method.
  3754. const auto numArgs = expr->getNumArgs();
  3755. const auto loc = expr->getExprLoc();
  3756. const bool hasStatusArg =
  3757. expr->getArg(numArgs - 1)->getType()->isUnsignedIntegerType();
  3758. SpirvInstruction *clamp = nullptr;
  3759. if (numArgs > 2 && expr->getArg(2)->getType()->isFloatingType())
  3760. clamp = doExpr(expr->getArg(2));
  3761. else if (numArgs > 3 && expr->getArg(3)->getType()->isFloatingType())
  3762. clamp = doExpr(expr->getArg(3));
  3763. const bool hasClampArg = (clamp != 0);
  3764. const auto status =
  3765. hasStatusArg ? doExpr(expr->getArg(numArgs - 1)) : nullptr;
  3766. // Subtract 1 for status (if it exists), subtract 1 for clamp (if it exists),
  3767. // and subtract 2 for sampler_state and location.
  3768. const bool hasOffsetArg = numArgs - hasStatusArg - hasClampArg - 2 > 0;
  3769. const auto *imageExpr = expr->getImplicitObjectArgument();
  3770. const QualType imageType = imageExpr->getType();
  3771. auto *image = loadIfGLValue(imageExpr);
  3772. auto *sampler = doExpr(expr->getArg(0));
  3773. auto *coordinate = doExpr(expr->getArg(1));
  3774. // .Sample()/.Gather() may have a third optional paramter for offset.
  3775. SpirvInstruction *constOffset = nullptr, *varOffset = nullptr;
  3776. if (hasOffsetArg)
  3777. handleOffsetInMethodCall(expr, 2, &constOffset, &varOffset);
  3778. const auto retType = expr->getDirectCallee()->getReturnType();
  3779. if (isSample) {
  3780. return createImageSample(retType, imageType, image, sampler, coordinate,
  3781. /*compareVal*/ nullptr, /*bias*/ nullptr,
  3782. /*lod*/ nullptr, std::make_pair(nullptr, nullptr),
  3783. constOffset, varOffset,
  3784. /*constOffsets*/ nullptr, /*sampleNumber*/ nullptr,
  3785. /*minLod*/ clamp, status,
  3786. expr->getCallee()->getLocStart());
  3787. } else {
  3788. return spvBuilder.createImageGather(
  3789. retType, imageType, image, sampler, coordinate,
  3790. // .Gather() doc says we return four components of red data.
  3791. spvBuilder.getConstantInt(astContext.IntTy, llvm::APInt(32, 0)),
  3792. /*compareVal*/ nullptr, constOffset, varOffset,
  3793. /*constOffsets*/ nullptr, /*sampleNumber*/ nullptr, status, loc);
  3794. }
  3795. }
  3796. SpirvInstruction *
  3797. SpirvEmitter::processTextureSampleBiasLevel(const CXXMemberCallExpr *expr,
  3798. const bool isBias) {
  3799. // Signatures:
  3800. // For Texture1D, Texture1DArray, Texture2D, Texture2DArray, and Texture3D:
  3801. // DXGI_FORMAT Object.SampleBias(sampler_state S,
  3802. // float Location,
  3803. // float Bias
  3804. // [, int Offset]
  3805. // [, float clamp]
  3806. // [, out uint Status]);
  3807. //
  3808. // For TextureCube and TextureCubeArray:
  3809. // DXGI_FORMAT Object.SampleBias(sampler_state S,
  3810. // float Location,
  3811. // float Bias
  3812. // [, float clamp]
  3813. // [, out uint Status]);
  3814. //
  3815. // For Texture1D, Texture1DArray, Texture2D, Texture2DArray, and Texture3D:
  3816. // DXGI_FORMAT Object.SampleLevel(sampler_state S,
  3817. // float Location,
  3818. // float LOD
  3819. // [, int Offset]
  3820. // [, out uint Status]);
  3821. //
  3822. // For TextureCube and TextureCubeArray:
  3823. // DXGI_FORMAT Object.SampleLevel(sampler_state S,
  3824. // float Location,
  3825. // float LOD
  3826. // [, out uint Status]);
  3827. const auto numArgs = expr->getNumArgs();
  3828. const bool hasStatusArg =
  3829. expr->getArg(numArgs - 1)->getType()->isUnsignedIntegerType();
  3830. auto *status = hasStatusArg ? doExpr(expr->getArg(numArgs - 1)) : nullptr;
  3831. SpirvInstruction *clamp = nullptr;
  3832. // The .SampleLevel() methods do not take the clamp argument.
  3833. if (isBias) {
  3834. if (numArgs > 3 && expr->getArg(3)->getType()->isFloatingType())
  3835. clamp = doExpr(expr->getArg(3));
  3836. else if (numArgs > 4 && expr->getArg(4)->getType()->isFloatingType())
  3837. clamp = doExpr(expr->getArg(4));
  3838. }
  3839. const bool hasClampArg = clamp != nullptr;
  3840. // Subtract 1 for clamp (if it exists), 1 for status (if it exists),
  3841. // and 3 for sampler_state, location, and Bias/LOD.
  3842. const bool hasOffsetArg = numArgs - hasClampArg - hasStatusArg - 3 > 0;
  3843. const auto *imageExpr = expr->getImplicitObjectArgument();
  3844. const QualType imageType = imageExpr->getType();
  3845. auto *image = loadIfGLValue(imageExpr);
  3846. auto *sampler = doExpr(expr->getArg(0));
  3847. auto *coordinate = doExpr(expr->getArg(1));
  3848. SpirvInstruction *lod = nullptr;
  3849. SpirvInstruction *bias = nullptr;
  3850. if (isBias) {
  3851. bias = doExpr(expr->getArg(2));
  3852. } else {
  3853. lod = doExpr(expr->getArg(2));
  3854. }
  3855. // If offset is present in .Bias()/.SampleLevel(), it is the fourth argument.
  3856. SpirvInstruction *constOffset = nullptr, *varOffset = nullptr;
  3857. if (hasOffsetArg)
  3858. handleOffsetInMethodCall(expr, 3, &constOffset, &varOffset);
  3859. const auto retType = expr->getDirectCallee()->getReturnType();
  3860. return createImageSample(
  3861. retType, imageType, image, sampler, coordinate,
  3862. /*compareVal*/ nullptr, bias, lod, std::make_pair(nullptr, nullptr),
  3863. constOffset, varOffset,
  3864. /*constOffsets*/ nullptr, /*sampleNumber*/ nullptr,
  3865. /*minLod*/ clamp, status, expr->getCallee()->getLocStart());
  3866. }
  3867. SpirvInstruction *
  3868. SpirvEmitter::processTextureSampleGrad(const CXXMemberCallExpr *expr) {
  3869. // Signature:
  3870. // For Texture1D, Texture1DArray, Texture2D, Texture2DArray, and Texture3D:
  3871. // DXGI_FORMAT Object.SampleGrad(sampler_state S,
  3872. // float Location,
  3873. // float DDX,
  3874. // float DDY
  3875. // [, int Offset]
  3876. // [, float Clamp]
  3877. // [, out uint Status]);
  3878. //
  3879. // For TextureCube and TextureCubeArray:
  3880. // DXGI_FORMAT Object.SampleGrad(sampler_state S,
  3881. // float Location,
  3882. // float DDX,
  3883. // float DDY
  3884. // [, float Clamp]
  3885. // [, out uint Status]);
  3886. const auto numArgs = expr->getNumArgs();
  3887. const bool hasStatusArg =
  3888. expr->getArg(numArgs - 1)->getType()->isUnsignedIntegerType();
  3889. auto *status = hasStatusArg ? doExpr(expr->getArg(numArgs - 1)) : nullptr;
  3890. SpirvInstruction *clamp = nullptr;
  3891. if (numArgs > 4 && expr->getArg(4)->getType()->isFloatingType())
  3892. clamp = doExpr(expr->getArg(4));
  3893. else if (numArgs > 5 && expr->getArg(5)->getType()->isFloatingType())
  3894. clamp = doExpr(expr->getArg(5));
  3895. const bool hasClampArg = clamp != nullptr;
  3896. // Subtract 1 for clamp (if it exists), 1 for status (if it exists),
  3897. // and 4 for sampler_state, location, DDX, and DDY;
  3898. const bool hasOffsetArg = numArgs - hasClampArg - hasStatusArg - 4 > 0;
  3899. const auto *imageExpr = expr->getImplicitObjectArgument();
  3900. const QualType imageType = imageExpr->getType();
  3901. auto *image = loadIfGLValue(imageExpr);
  3902. auto *sampler = doExpr(expr->getArg(0));
  3903. auto *coordinate = doExpr(expr->getArg(1));
  3904. auto *ddx = doExpr(expr->getArg(2));
  3905. auto *ddy = doExpr(expr->getArg(3));
  3906. // If offset is present in .SampleGrad(), it is the fifth argument.
  3907. SpirvInstruction *constOffset = nullptr, *varOffset = nullptr;
  3908. if (hasOffsetArg)
  3909. handleOffsetInMethodCall(expr, 4, &constOffset, &varOffset);
  3910. const auto retType = expr->getDirectCallee()->getReturnType();
  3911. return createImageSample(
  3912. retType, imageType, image, sampler, coordinate,
  3913. /*compareVal*/ nullptr, /*bias*/ nullptr,
  3914. /*lod*/ nullptr, std::make_pair(ddx, ddy), constOffset, varOffset,
  3915. /*constOffsets*/ nullptr, /*sampleNumber*/ nullptr,
  3916. /*minLod*/ clamp, status, expr->getCallee()->getLocStart());
  3917. }
  3918. SpirvInstruction *
  3919. SpirvEmitter::processTextureSampleCmpCmpLevelZero(const CXXMemberCallExpr *expr,
  3920. const bool isCmp) {
  3921. // .SampleCmp() Signature:
  3922. //
  3923. // For Texture1D, Texture1DArray, Texture2D, Texture2DArray:
  3924. // float Object.SampleCmp(
  3925. // SamplerComparisonState S,
  3926. // float Location,
  3927. // float CompareValue
  3928. // [, int Offset]
  3929. // [, float Clamp]
  3930. // [, out uint Status]
  3931. // );
  3932. //
  3933. // For TextureCube and TextureCubeArray:
  3934. // float Object.SampleCmp(
  3935. // SamplerComparisonState S,
  3936. // float Location,
  3937. // float CompareValue
  3938. // [, float Clamp]
  3939. // [, out uint Status]
  3940. // );
  3941. //
  3942. // .SampleCmpLevelZero() is identical to .SampleCmp() on mipmap level 0 only.
  3943. // It never takes a clamp argument, which is good because lod and clamp may
  3944. // not be used together.
  3945. //
  3946. // .SampleCmpLevelZero() Signature:
  3947. //
  3948. // For Texture1D, Texture1DArray, Texture2D, Texture2DArray:
  3949. // float Object.SampleCmpLevelZero(
  3950. // SamplerComparisonState S,
  3951. // float Location,
  3952. // float CompareValue
  3953. // [, int Offset]
  3954. // [, out uint Status]
  3955. // );
  3956. //
  3957. // For TextureCube and TextureCubeArray:
  3958. // float Object.SampleCmpLevelZero(
  3959. // SamplerComparisonState S,
  3960. // float Location,
  3961. // float CompareValue
  3962. // [, out uint Status]
  3963. // );
  3964. const auto numArgs = expr->getNumArgs();
  3965. const bool hasStatusArg =
  3966. expr->getArg(numArgs - 1)->getType()->isUnsignedIntegerType();
  3967. auto *status = hasStatusArg ? doExpr(expr->getArg(numArgs - 1)) : nullptr;
  3968. SpirvInstruction *clamp = nullptr;
  3969. // The .SampleCmpLevelZero() methods do not take the clamp argument.
  3970. if (isCmp) {
  3971. if (numArgs > 3 && expr->getArg(3)->getType()->isFloatingType())
  3972. clamp = doExpr(expr->getArg(3));
  3973. else if (numArgs > 4 && expr->getArg(4)->getType()->isFloatingType())
  3974. clamp = doExpr(expr->getArg(4));
  3975. }
  3976. const bool hasClampArg = clamp != nullptr;
  3977. // Subtract 1 for clamp (if it exists), 1 for status (if it exists),
  3978. // and 3 for sampler_state, location, and compare_value.
  3979. const bool hasOffsetArg = numArgs - hasClampArg - hasStatusArg - 3 > 0;
  3980. const auto *imageExpr = expr->getImplicitObjectArgument();
  3981. auto *image = loadIfGLValue(imageExpr);
  3982. auto *sampler = doExpr(expr->getArg(0));
  3983. auto *coordinate = doExpr(expr->getArg(1));
  3984. auto *compareVal = doExpr(expr->getArg(2));
  3985. // If offset is present in .SampleCmp(), it will be the fourth argument.
  3986. SpirvInstruction *constOffset = nullptr, *varOffset = nullptr;
  3987. if (hasOffsetArg)
  3988. handleOffsetInMethodCall(expr, 3, &constOffset, &varOffset);
  3989. auto *lod = isCmp ? nullptr
  3990. : spvBuilder.getConstantFloat(astContext.FloatTy,
  3991. llvm::APFloat(0.0f));
  3992. const auto retType = expr->getDirectCallee()->getReturnType();
  3993. const auto imageType = imageExpr->getType();
  3994. return createImageSample(
  3995. retType, imageType, image, sampler, coordinate, compareVal,
  3996. /*bias*/ nullptr, lod, std::make_pair(nullptr, nullptr), constOffset,
  3997. varOffset,
  3998. /*constOffsets*/ nullptr, /*sampleNumber*/ nullptr, /*minLod*/ clamp,
  3999. status, expr->getCallee()->getLocStart());
  4000. }
  4001. SpirvInstruction *
  4002. SpirvEmitter::processBufferTextureLoad(const CXXMemberCallExpr *expr) {
  4003. // Signature:
  4004. // For Texture1D, Texture1DArray, Texture2D, Texture2DArray, Texture3D:
  4005. // ret Object.Load(int Location
  4006. // [, int Offset]
  4007. // [, uint status]);
  4008. //
  4009. // For Texture2DMS and Texture2DMSArray, there is one additional argument:
  4010. // ret Object.Load(int Location
  4011. // [, int SampleIndex]
  4012. // [, int Offset]
  4013. // [, uint status]);
  4014. //
  4015. // For (RW)Buffer, RWTexture1D, RWTexture1DArray, RWTexture2D,
  4016. // RWTexture2DArray, RWTexture3D:
  4017. // ret Object.Load (int Location
  4018. // [, uint status]);
  4019. //
  4020. // Note: (RW)ByteAddressBuffer and (RW)StructuredBuffer types also have Load
  4021. // methods that take an additional Status argument. However, since these types
  4022. // are not represented as OpTypeImage in SPIR-V, we don't have a way of
  4023. // figuring out the Residency Code for them. Therefore having the Status
  4024. // argument for these types is not supported.
  4025. //
  4026. // For (RW)ByteAddressBuffer:
  4027. // ret Object.{Load,Load2,Load3,Load4} (int Location
  4028. // [, uint status]);
  4029. //
  4030. // For (RW)StructuredBuffer:
  4031. // ret Object.Load (int Location
  4032. // [, uint status]);
  4033. //
  4034. const auto *object = expr->getImplicitObjectArgument();
  4035. const auto objectType = object->getType();
  4036. if (isRWByteAddressBuffer(objectType) || isByteAddressBuffer(objectType))
  4037. return processByteAddressBufferLoadStore(expr, 1, /*doStore*/ false);
  4038. if (isStructuredBuffer(objectType))
  4039. return processStructuredBufferLoad(expr);
  4040. const auto numArgs = expr->getNumArgs();
  4041. const auto *locationArg = expr->getArg(0);
  4042. const bool textureMS = isTextureMS(objectType);
  4043. const bool hasStatusArg =
  4044. expr->getArg(numArgs - 1)->getType()->isUnsignedIntegerType();
  4045. auto *status = hasStatusArg ? doExpr(expr->getArg(numArgs - 1)) : nullptr;
  4046. auto loc = expr->getExprLoc();
  4047. if (isBuffer(objectType) || isRWBuffer(objectType) || isRWTexture(objectType))
  4048. return processBufferTextureLoad(object, doExpr(locationArg),
  4049. /*constOffset*/ nullptr,
  4050. /*varOffset*/ nullptr, /*lod*/ nullptr,
  4051. /*residencyCode*/ status, loc);
  4052. // Subtract 1 for status (if it exists), and 1 for sampleIndex (if it exists),
  4053. // and 1 for location.
  4054. const bool hasOffsetArg = numArgs - hasStatusArg - textureMS - 1 > 0;
  4055. if (isTexture(objectType)) {
  4056. // .Load() has a second optional paramter for offset.
  4057. SpirvInstruction *location = doExpr(locationArg);
  4058. SpirvInstruction *constOffset = nullptr, *varOffset = nullptr;
  4059. SpirvInstruction *coordinate = location, *lod = nullptr;
  4060. if (textureMS) {
  4061. // SampleIndex is only available when the Object is of Texture2DMS or
  4062. // Texture2DMSArray types. Under those cases, Offset will be the third
  4063. // parameter (index 2).
  4064. lod = doExpr(expr->getArg(1));
  4065. if (hasOffsetArg)
  4066. handleOffsetInMethodCall(expr, 2, &constOffset, &varOffset);
  4067. } else {
  4068. // For Texture Load() functions, the location parameter is a vector
  4069. // that consists of both the coordinate and the mipmap level (via the
  4070. // last vector element). We need to split it here since the
  4071. // OpImageFetch SPIR-V instruction encodes them as separate arguments.
  4072. splitVecLastElement(locationArg->getType(), location, &coordinate, &lod,
  4073. locationArg->getExprLoc());
  4074. // For textures other than Texture2DMS(Array), offset should be the
  4075. // second parameter (index 1).
  4076. if (hasOffsetArg)
  4077. handleOffsetInMethodCall(expr, 1, &constOffset, &varOffset);
  4078. }
  4079. return processBufferTextureLoad(object, coordinate, constOffset, varOffset,
  4080. lod, status, loc);
  4081. }
  4082. emitError("Load() of the given object type unimplemented",
  4083. object->getExprLoc());
  4084. return nullptr;
  4085. }
  4086. SpirvInstruction *
  4087. SpirvEmitter::processGetDimensions(const CXXMemberCallExpr *expr) {
  4088. const auto objectType = expr->getImplicitObjectArgument()->getType();
  4089. if (isTexture(objectType) || isRWTexture(objectType) ||
  4090. isBuffer(objectType) || isRWBuffer(objectType)) {
  4091. return processBufferTextureGetDimensions(expr);
  4092. } else if (isByteAddressBuffer(objectType) ||
  4093. isRWByteAddressBuffer(objectType) ||
  4094. isStructuredBuffer(objectType) ||
  4095. isAppendStructuredBuffer(objectType) ||
  4096. isConsumeStructuredBuffer(objectType)) {
  4097. return processByteAddressBufferStructuredBufferGetDimensions(expr);
  4098. } else {
  4099. emitError("GetDimensions() of the given object type unimplemented",
  4100. expr->getExprLoc());
  4101. return nullptr;
  4102. }
  4103. }
  4104. SpirvInstruction *
  4105. SpirvEmitter::doCXXOperatorCallExpr(const CXXOperatorCallExpr *expr) {
  4106. { // Handle Buffer/RWBuffer/Texture/RWTexture indexing
  4107. const Expr *baseExpr = nullptr;
  4108. const Expr *indexExpr = nullptr;
  4109. const Expr *lodExpr = nullptr;
  4110. // For Textures, regular indexing (operator[]) uses slice 0.
  4111. if (isBufferTextureIndexing(expr, &baseExpr, &indexExpr)) {
  4112. auto *lod = isTexture(baseExpr->getType())
  4113. ? spvBuilder.getConstantInt(astContext.UnsignedIntTy,
  4114. llvm::APInt(32, 0))
  4115. : nullptr;
  4116. return processBufferTextureLoad(baseExpr, doExpr(indexExpr),
  4117. /*constOffset*/ nullptr,
  4118. /*varOffset*/ nullptr, lod,
  4119. /*residencyCode*/ nullptr,
  4120. expr->getExprLoc());
  4121. }
  4122. // .mips[][] or .sample[][] must use the correct slice.
  4123. if (isTextureMipsSampleIndexing(expr, &baseExpr, &indexExpr, &lodExpr)) {
  4124. auto *lod = doExpr(lodExpr);
  4125. return processBufferTextureLoad(baseExpr, doExpr(indexExpr),
  4126. /*constOffset*/ nullptr,
  4127. /*varOffset*/ nullptr, lod,
  4128. /*residencyCode*/ nullptr,
  4129. expr->getExprLoc());
  4130. }
  4131. }
  4132. llvm::SmallVector<SpirvInstruction *, 4> indices;
  4133. const Expr *baseExpr = collectArrayStructIndices(
  4134. expr, /*rawIndex*/ false, /*rawIndices*/ nullptr, &indices);
  4135. auto base = loadIfAliasVarRef(baseExpr);
  4136. if (indices.empty())
  4137. return base; // For indexing into size-1 vectors and 1xN matrices
  4138. // If we are indexing into a rvalue, to use OpAccessChain, we first need
  4139. // to create a local variable to hold the rvalue.
  4140. //
  4141. // TODO: We can optimize the codegen by emitting OpCompositeExtract if
  4142. // all indices are contant integers.
  4143. if (base->isRValue()) {
  4144. base = createTemporaryVar(baseExpr->getType(), "vector", base,
  4145. baseExpr->getExprLoc());
  4146. }
  4147. return turnIntoElementPtr(baseExpr->getType(), base, expr->getType(), indices,
  4148. baseExpr->getExprLoc());
  4149. }
  4150. SpirvInstruction *
  4151. SpirvEmitter::doExtMatrixElementExpr(const ExtMatrixElementExpr *expr) {
  4152. const Expr *baseExpr = expr->getBase();
  4153. auto *baseInfo = doExpr(baseExpr);
  4154. const auto layoutRule = baseInfo->getLayoutRule();
  4155. const auto elemType = hlsl::GetHLSLMatElementType(baseExpr->getType());
  4156. const auto accessor = expr->getEncodedElementAccess();
  4157. uint32_t rowCount = 0, colCount = 0;
  4158. hlsl::GetHLSLMatRowColCount(baseExpr->getType(), rowCount, colCount);
  4159. // Construct a temporary vector out of all elements accessed:
  4160. // 1. Create access chain for each element using OpAccessChain
  4161. // 2. Load each element using OpLoad
  4162. // 3. Create the vector using OpCompositeConstruct
  4163. llvm::SmallVector<SpirvInstruction *, 4> elements;
  4164. for (uint32_t i = 0; i < accessor.Count; ++i) {
  4165. uint32_t row = 0, col = 0;
  4166. SpirvInstruction *elem = nullptr;
  4167. accessor.GetPosition(i, &row, &col);
  4168. llvm::SmallVector<uint32_t, 2> indices;
  4169. // If the matrix only has one row/column, we are indexing into a vector
  4170. // then. Only one index is needed for such cases.
  4171. if (rowCount > 1)
  4172. indices.push_back(row);
  4173. if (colCount > 1)
  4174. indices.push_back(col);
  4175. if (!baseInfo->isRValue()) {
  4176. llvm::SmallVector<SpirvInstruction *, 2> indexInstructions(indices.size(),
  4177. nullptr);
  4178. for (uint32_t i = 0; i < indices.size(); ++i)
  4179. indexInstructions[i] = spvBuilder.getConstantInt(
  4180. astContext.IntTy, llvm::APInt(32, indices[i], true));
  4181. if (!indices.empty()) {
  4182. assert(!baseInfo->isRValue());
  4183. // Load the element via access chain
  4184. elem = spvBuilder.createAccessChain(
  4185. elemType, baseInfo, indexInstructions, baseExpr->getLocStart());
  4186. } else {
  4187. // The matrix is of size 1x1. No need to use access chain, base should
  4188. // be the source pointer.
  4189. elem = baseInfo;
  4190. }
  4191. elem = spvBuilder.createLoad(elemType, elem, baseExpr->getLocStart());
  4192. } else { // e.g., (mat1 + mat2)._m11
  4193. elem = spvBuilder.createCompositeExtract(elemType, baseInfo, indices,
  4194. baseExpr->getLocStart());
  4195. }
  4196. elements.push_back(elem);
  4197. }
  4198. const auto size = elements.size();
  4199. auto *value = elements.front();
  4200. if (size > 1) {
  4201. value = spvBuilder.createCompositeConstruct(
  4202. astContext.getExtVectorType(elemType, size), elements,
  4203. expr->getLocStart());
  4204. }
  4205. // Note: Special-case: Booleans have no physical layout, and therefore when
  4206. // layout is required booleans are represented as unsigned integers.
  4207. // Therefore, after loading the uint we should convert it boolean.
  4208. if (elemType->isBooleanType() && layoutRule != SpirvLayoutRule::Void) {
  4209. const auto fromType =
  4210. size == 1 ? astContext.UnsignedIntTy
  4211. : astContext.getExtVectorType(astContext.UnsignedIntTy, size);
  4212. const auto toType =
  4213. size == 1 ? astContext.BoolTy
  4214. : astContext.getExtVectorType(astContext.BoolTy, size);
  4215. value = castToBool(value, fromType, toType, expr->getLocStart());
  4216. }
  4217. value->setRValue();
  4218. return value;
  4219. }
  4220. SpirvInstruction *
  4221. SpirvEmitter::doHLSLVectorElementExpr(const HLSLVectorElementExpr *expr) {
  4222. const Expr *baseExpr = nullptr;
  4223. hlsl::VectorMemberAccessPositions accessor;
  4224. condenseVectorElementExpr(expr, &baseExpr, &accessor);
  4225. const QualType baseType = baseExpr->getType();
  4226. assert(hlsl::IsHLSLVecType(baseType));
  4227. const auto baseSize = hlsl::GetHLSLVecSize(baseType);
  4228. const auto accessorSize = static_cast<size_t>(accessor.Count);
  4229. // Depending on the number of elements selected, we emit different
  4230. // instructions.
  4231. // For vectors of size greater than 1, if we are only selecting one element,
  4232. // typical access chain or composite extraction should be fine. But if we
  4233. // are selecting more than one elements, we must resolve to vector specific
  4234. // operations.
  4235. // For size-1 vectors, if we are selecting their single elements multiple
  4236. // times, we need composite construct instructions.
  4237. if (accessorSize == 1) {
  4238. auto *baseInfo = doExpr(baseExpr);
  4239. if (!baseInfo || baseSize == 1) {
  4240. // Selecting one element from a size-1 vector. The underlying vector is
  4241. // already treated as a scalar.
  4242. return baseInfo;
  4243. }
  4244. // If the base is an lvalue, we should emit an access chain instruction
  4245. // so that we can load/store the specified element. For rvalue base,
  4246. // we should use composite extraction. We should check the immediate base
  4247. // instead of the original base here since we can have something like
  4248. // v.xyyz to turn a lvalue v into rvalue.
  4249. const auto type = expr->getType();
  4250. if (!baseInfo->isRValue()) { // E.g., v.x;
  4251. auto *index = spvBuilder.getConstantInt(
  4252. astContext.IntTy, llvm::APInt(32, accessor.Swz0, true));
  4253. // We need a lvalue here. Do not try to load.
  4254. return spvBuilder.createAccessChain(type, baseInfo, {index},
  4255. baseExpr->getLocStart());
  4256. } else { // E.g., (v + w).x;
  4257. // The original base vector may not be a rvalue. Need to load it if
  4258. // it is lvalue since ImplicitCastExpr (LValueToRValue) will be missing
  4259. // for that case.
  4260. SpirvInstruction *result = spvBuilder.createCompositeExtract(
  4261. type, baseInfo, {accessor.Swz0}, baseExpr->getLocStart());
  4262. // Special-case: Booleans in SPIR-V do not have a physical layout. Uint is
  4263. // used to represent them when layout is required.
  4264. if (expr->getType()->isBooleanType() &&
  4265. baseInfo->getLayoutRule() != SpirvLayoutRule::Void)
  4266. result = castToBool(result, astContext.UnsignedIntTy, astContext.BoolTy,
  4267. expr->getLocStart());
  4268. return result;
  4269. }
  4270. }
  4271. if (baseSize == 1) {
  4272. // Selecting more than one element from a size-1 vector, for example,
  4273. // <scalar>.xx. Construct the vector.
  4274. auto *info = loadIfGLValue(baseExpr);
  4275. const auto type = expr->getType();
  4276. llvm::SmallVector<SpirvInstruction *, 4> components(accessorSize, info);
  4277. info = spvBuilder.createCompositeConstruct(type, components,
  4278. expr->getLocStart());
  4279. info->setRValue();
  4280. return info;
  4281. }
  4282. llvm::SmallVector<uint32_t, 4> selectors;
  4283. selectors.resize(accessorSize);
  4284. // Whether we are selecting elements in the original order
  4285. bool originalOrder = baseSize == accessorSize;
  4286. for (uint32_t i = 0; i < accessorSize; ++i) {
  4287. accessor.GetPosition(i, &selectors[i]);
  4288. // We can select more elements than the vector provides. This handles
  4289. // that case too.
  4290. originalOrder &= selectors[i] == i;
  4291. }
  4292. if (originalOrder)
  4293. return doExpr(baseExpr);
  4294. auto *info = loadIfGLValue(baseExpr);
  4295. // Use base for both vectors. But we are only selecting values from the
  4296. // first one.
  4297. return spvBuilder.createVectorShuffle(expr->getType(), info, info, selectors,
  4298. expr->getLocStart());
  4299. }
  4300. SpirvInstruction *SpirvEmitter::doInitListExpr(const InitListExpr *expr) {
  4301. if (auto *id = tryToEvaluateAsConst(expr)) {
  4302. id->setRValue();
  4303. return id;
  4304. }
  4305. auto *result = InitListHandler(astContext, *this).processInit(expr);
  4306. result->setRValue();
  4307. return result;
  4308. }
  4309. SpirvInstruction *SpirvEmitter::doMemberExpr(const MemberExpr *expr) {
  4310. llvm::SmallVector<SpirvInstruction *, 4> indices;
  4311. const Expr *base = collectArrayStructIndices(
  4312. expr, /*rawIndex*/ false, /*rawIndices*/ nullptr, &indices);
  4313. auto *instr = loadIfAliasVarRef(base);
  4314. if (instr && !indices.empty()) {
  4315. instr = turnIntoElementPtr(base->getType(), instr, expr->getType(), indices,
  4316. base->getExprLoc());
  4317. }
  4318. return instr;
  4319. }
  4320. SpirvVariable *SpirvEmitter::createTemporaryVar(QualType type,
  4321. llvm::StringRef name,
  4322. SpirvInstruction *init,
  4323. SourceLocation loc) {
  4324. // We are creating a temporary variable in the Function storage class here,
  4325. // which means it has void layout rule.
  4326. const std::string varName = "temp.var." + name.str();
  4327. auto *var = spvBuilder.addFnVar(type, loc, varName);
  4328. storeValue(var, init, type, loc);
  4329. return var;
  4330. }
  4331. SpirvInstruction *SpirvEmitter::doUnaryOperator(const UnaryOperator *expr) {
  4332. const auto opcode = expr->getOpcode();
  4333. const auto *subExpr = expr->getSubExpr();
  4334. const auto subType = subExpr->getType();
  4335. auto *subValue = doExpr(subExpr);
  4336. switch (opcode) {
  4337. case UO_PreInc:
  4338. case UO_PreDec:
  4339. case UO_PostInc:
  4340. case UO_PostDec: {
  4341. const bool isPre = opcode == UO_PreInc || opcode == UO_PreDec;
  4342. const bool isInc = opcode == UO_PreInc || opcode == UO_PostInc;
  4343. const spv::Op spvOp = translateOp(isInc ? BO_Add : BO_Sub, subType);
  4344. SpirvInstruction *originValue =
  4345. subValue->isRValue()
  4346. ? subValue
  4347. : spvBuilder.createLoad(subType, subValue, subExpr->getLocStart());
  4348. auto *one = hlsl::IsHLSLMatType(subType) ? getMatElemValueOne(subType)
  4349. : getValueOne(subType);
  4350. SpirvInstruction *incValue = nullptr;
  4351. if (isMxNMatrix(subType)) {
  4352. // For matrices, we can only increment/decrement each vector of it.
  4353. const auto actOnEachVec = [this, spvOp, one,
  4354. expr](uint32_t /*index*/, QualType vecType,
  4355. SpirvInstruction *lhsVec) {
  4356. auto *val = spvBuilder.createBinaryOp(spvOp, vecType, lhsVec, one,
  4357. expr->getOperatorLoc());
  4358. val->setRValue();
  4359. return val;
  4360. };
  4361. incValue = processEachVectorInMatrix(subExpr, originValue, actOnEachVec,
  4362. expr->getLocStart());
  4363. } else {
  4364. incValue = spvBuilder.createBinaryOp(spvOp, subType, originValue, one,
  4365. expr->getOperatorLoc());
  4366. }
  4367. // If this is a RWBuffer/RWTexture assignment, OpImageWrite will be used.
  4368. // Otherwise, store using OpStore.
  4369. if (tryToAssignToRWBufferRWTexture(subExpr, incValue)) {
  4370. incValue->setRValue();
  4371. subValue = incValue;
  4372. } else {
  4373. spvBuilder.createStore(subValue, incValue, subExpr->getLocStart());
  4374. }
  4375. // Prefix increment/decrement operator returns a lvalue, while postfix
  4376. // increment/decrement returns a rvalue.
  4377. if (isPre) {
  4378. return subValue;
  4379. } else {
  4380. originValue->setRValue();
  4381. return originValue;
  4382. }
  4383. }
  4384. case UO_Not: {
  4385. subValue = spvBuilder.createUnaryOp(spv::Op::OpNot, subType, subValue,
  4386. expr->getOperatorLoc());
  4387. subValue->setRValue();
  4388. return subValue;
  4389. }
  4390. case UO_LNot: {
  4391. // Parsing will do the necessary casting to make sure we are applying the
  4392. // ! operator on boolean values.
  4393. subValue = spvBuilder.createUnaryOp(spv::Op::OpLogicalNot, subType,
  4394. subValue, expr->getOperatorLoc());
  4395. subValue->setRValue();
  4396. return subValue;
  4397. }
  4398. case UO_Plus:
  4399. // No need to do anything for the prefix + operator.
  4400. return subValue;
  4401. case UO_Minus: {
  4402. // SPIR-V have two opcodes for negating values: OpSNegate and OpFNegate.
  4403. const spv::Op spvOp = isFloatOrVecOfFloatType(subType) ? spv::Op::OpFNegate
  4404. : spv::Op::OpSNegate;
  4405. subValue = spvBuilder.createUnaryOp(spvOp, subType, subValue,
  4406. expr->getOperatorLoc());
  4407. subValue->setRValue();
  4408. return subValue;
  4409. }
  4410. default:
  4411. break;
  4412. }
  4413. emitError("unary operator '%0' unimplemented", expr->getExprLoc())
  4414. << expr->getOpcodeStr(opcode);
  4415. expr->dump();
  4416. return 0;
  4417. }
  4418. spv::Op SpirvEmitter::translateOp(BinaryOperator::Opcode op, QualType type) {
  4419. const bool isSintType = isSintOrVecMatOfSintType(type);
  4420. const bool isUintType = isUintOrVecMatOfUintType(type);
  4421. const bool isFloatType = isFloatOrVecMatOfFloatType(type);
  4422. #define BIN_OP_CASE_INT_FLOAT(kind, intBinOp, floatBinOp) \
  4423. \
  4424. case BO_##kind: { \
  4425. if (isSintType || isUintType) { \
  4426. return spv::Op::Op##intBinOp; \
  4427. } \
  4428. if (isFloatType) { \
  4429. return spv::Op::Op##floatBinOp; \
  4430. } \
  4431. } break
  4432. #define BIN_OP_CASE_SINT_UINT_FLOAT(kind, sintBinOp, uintBinOp, floatBinOp) \
  4433. \
  4434. case BO_##kind: { \
  4435. if (isSintType) { \
  4436. return spv::Op::Op##sintBinOp; \
  4437. } \
  4438. if (isUintType) { \
  4439. return spv::Op::Op##uintBinOp; \
  4440. } \
  4441. if (isFloatType) { \
  4442. return spv::Op::Op##floatBinOp; \
  4443. } \
  4444. } break
  4445. #define BIN_OP_CASE_SINT_UINT(kind, sintBinOp, uintBinOp) \
  4446. \
  4447. case BO_##kind: { \
  4448. if (isSintType) { \
  4449. return spv::Op::Op##sintBinOp; \
  4450. } \
  4451. if (isUintType) { \
  4452. return spv::Op::Op##uintBinOp; \
  4453. } \
  4454. } break
  4455. switch (op) {
  4456. case BO_EQ: {
  4457. if (isBoolOrVecMatOfBoolType(type))
  4458. return spv::Op::OpLogicalEqual;
  4459. if (isSintType || isUintType)
  4460. return spv::Op::OpIEqual;
  4461. if (isFloatType)
  4462. return spv::Op::OpFOrdEqual;
  4463. } break;
  4464. case BO_NE: {
  4465. if (isBoolOrVecMatOfBoolType(type))
  4466. return spv::Op::OpLogicalNotEqual;
  4467. if (isSintType || isUintType)
  4468. return spv::Op::OpINotEqual;
  4469. if (isFloatType)
  4470. return spv::Op::OpFOrdNotEqual;
  4471. } break;
  4472. // According to HLSL doc, all sides of the && and || expression are always
  4473. // evaluated.
  4474. case BO_LAnd:
  4475. return spv::Op::OpLogicalAnd;
  4476. case BO_LOr:
  4477. return spv::Op::OpLogicalOr;
  4478. BIN_OP_CASE_INT_FLOAT(Add, IAdd, FAdd);
  4479. BIN_OP_CASE_INT_FLOAT(AddAssign, IAdd, FAdd);
  4480. BIN_OP_CASE_INT_FLOAT(Sub, ISub, FSub);
  4481. BIN_OP_CASE_INT_FLOAT(SubAssign, ISub, FSub);
  4482. BIN_OP_CASE_INT_FLOAT(Mul, IMul, FMul);
  4483. BIN_OP_CASE_INT_FLOAT(MulAssign, IMul, FMul);
  4484. BIN_OP_CASE_SINT_UINT_FLOAT(Div, SDiv, UDiv, FDiv);
  4485. BIN_OP_CASE_SINT_UINT_FLOAT(DivAssign, SDiv, UDiv, FDiv);
  4486. // According to HLSL spec, "the modulus operator returns the remainder of
  4487. // a division." "The % operator is defined only in cases where either both
  4488. // sides are positive or both sides are negative."
  4489. //
  4490. // In SPIR-V, there are two reminder operations: Op*Rem and Op*Mod. With
  4491. // the former, the sign of a non-0 result comes from Operand 1, while
  4492. // with the latter, from Operand 2.
  4493. //
  4494. // For operands with different signs, technically we can map % to either
  4495. // Op*Rem or Op*Mod since it's undefined behavior. But it is more
  4496. // consistent with C (HLSL starts as a C derivative) and Clang frontend
  4497. // const expression evaluation if we map % to Op*Rem.
  4498. //
  4499. // Note there is no OpURem in SPIR-V.
  4500. BIN_OP_CASE_SINT_UINT_FLOAT(Rem, SRem, UMod, FRem);
  4501. BIN_OP_CASE_SINT_UINT_FLOAT(RemAssign, SRem, UMod, FRem);
  4502. BIN_OP_CASE_SINT_UINT_FLOAT(LT, SLessThan, ULessThan, FOrdLessThan);
  4503. BIN_OP_CASE_SINT_UINT_FLOAT(LE, SLessThanEqual, ULessThanEqual,
  4504. FOrdLessThanEqual);
  4505. BIN_OP_CASE_SINT_UINT_FLOAT(GT, SGreaterThan, UGreaterThan,
  4506. FOrdGreaterThan);
  4507. BIN_OP_CASE_SINT_UINT_FLOAT(GE, SGreaterThanEqual, UGreaterThanEqual,
  4508. FOrdGreaterThanEqual);
  4509. BIN_OP_CASE_SINT_UINT(And, BitwiseAnd, BitwiseAnd);
  4510. BIN_OP_CASE_SINT_UINT(AndAssign, BitwiseAnd, BitwiseAnd);
  4511. BIN_OP_CASE_SINT_UINT(Or, BitwiseOr, BitwiseOr);
  4512. BIN_OP_CASE_SINT_UINT(OrAssign, BitwiseOr, BitwiseOr);
  4513. BIN_OP_CASE_SINT_UINT(Xor, BitwiseXor, BitwiseXor);
  4514. BIN_OP_CASE_SINT_UINT(XorAssign, BitwiseXor, BitwiseXor);
  4515. BIN_OP_CASE_SINT_UINT(Shl, ShiftLeftLogical, ShiftLeftLogical);
  4516. BIN_OP_CASE_SINT_UINT(ShlAssign, ShiftLeftLogical, ShiftLeftLogical);
  4517. BIN_OP_CASE_SINT_UINT(Shr, ShiftRightArithmetic, ShiftRightLogical);
  4518. BIN_OP_CASE_SINT_UINT(ShrAssign, ShiftRightArithmetic, ShiftRightLogical);
  4519. default:
  4520. break;
  4521. }
  4522. #undef BIN_OP_CASE_INT_FLOAT
  4523. #undef BIN_OP_CASE_SINT_UINT_FLOAT
  4524. #undef BIN_OP_CASE_SINT_UINT
  4525. emitError("translating binary operator '%0' unimplemented", {})
  4526. << BinaryOperator::getOpcodeStr(op);
  4527. return spv::Op::OpNop;
  4528. }
  4529. SpirvInstruction *
  4530. SpirvEmitter::processAssignment(const Expr *lhs, SpirvInstruction *rhs,
  4531. const bool isCompoundAssignment,
  4532. SpirvInstruction *lhsPtr) {
  4533. lhs = lhs->IgnoreParenNoopCasts(astContext);
  4534. // Assigning to vector swizzling should be handled differently.
  4535. if (SpirvInstruction *result = tryToAssignToVectorElements(lhs, rhs))
  4536. return result;
  4537. // Assigning to matrix swizzling should be handled differently.
  4538. if (SpirvInstruction *result = tryToAssignToMatrixElements(lhs, rhs))
  4539. return result;
  4540. // Assigning to a RWBuffer/RWTexture should be handled differently.
  4541. if (SpirvInstruction *result = tryToAssignToRWBufferRWTexture(lhs, rhs))
  4542. return result;
  4543. // Assigning to a out attribute or indices object in mesh shader should be
  4544. // handled differently.
  4545. if (SpirvInstruction *result = tryToAssignToMSOutAttrsOrIndices(lhs, rhs))
  4546. return result;
  4547. // Assigning to a 'string' variable. SPIR-V doesn't have a string type, and we
  4548. // do not allow creating or modifying string variables. We do allow use of
  4549. // string literals using OpString.
  4550. if (isStringType(lhs->getType())) {
  4551. emitError("string variables are immutable in SPIR-V.", lhs->getExprLoc());
  4552. return nullptr;
  4553. }
  4554. // Normal assignment procedure
  4555. if (!lhsPtr)
  4556. lhsPtr = doExpr(lhs);
  4557. storeValue(lhsPtr, rhs, lhs->getType(), lhs->getLocStart());
  4558. // Plain assignment returns a rvalue, while compound assignment returns
  4559. // lvalue.
  4560. return isCompoundAssignment ? lhsPtr : rhs;
  4561. }
  4562. void SpirvEmitter::storeValue(SpirvInstruction *lhsPtr,
  4563. SpirvInstruction *rhsVal, QualType lhsValType,
  4564. SourceLocation loc) {
  4565. // Defend against nullptr source or destination so errors can bubble up to the
  4566. // user.
  4567. if (!lhsPtr || !rhsVal)
  4568. return;
  4569. if (const auto *refType = lhsValType->getAs<ReferenceType>())
  4570. lhsValType = refType->getPointeeType();
  4571. QualType matElemType = {};
  4572. const bool lhsIsMat = isMxNMatrix(lhsValType, &matElemType);
  4573. const bool lhsIsFloatMat = lhsIsMat && matElemType->isFloatingType();
  4574. const bool lhsIsNonFpMat = lhsIsMat && !matElemType->isFloatingType();
  4575. if (isScalarType(lhsValType) || isVectorType(lhsValType) || lhsIsFloatMat) {
  4576. // Special-case: According to the SPIR-V Spec: There is no physical size
  4577. // or bit pattern defined for boolean type. Therefore an unsigned integer
  4578. // is used to represent booleans when layout is required. In such cases,
  4579. // we should cast the boolean to uint before creating OpStore.
  4580. if (isBoolOrVecOfBoolType(lhsValType) &&
  4581. lhsPtr->getLayoutRule() != SpirvLayoutRule::Void) {
  4582. uint32_t vecSize = 1;
  4583. const bool isVec = isVectorType(lhsValType, nullptr, &vecSize);
  4584. const auto toType =
  4585. isVec ? astContext.getExtVectorType(astContext.UnsignedIntTy, vecSize)
  4586. : astContext.UnsignedIntTy;
  4587. const auto fromType =
  4588. isVec ? astContext.getExtVectorType(astContext.BoolTy, vecSize)
  4589. : astContext.BoolTy;
  4590. rhsVal = castToInt(rhsVal, fromType, toType, {});
  4591. }
  4592. spvBuilder.createStore(lhsPtr, rhsVal, loc);
  4593. } else if (isOpaqueType(lhsValType)) {
  4594. // Resource types are represented using RecordType in the AST.
  4595. // Handle them before the general RecordType.
  4596. //
  4597. // HLSL allows to put resource types that translating into SPIR-V opaque
  4598. // types in structs, or assign to variables of resource types. These can all
  4599. // result in illegal SPIR-V for Vulkan. We just translate here literally and
  4600. // let SPIRV-Tools opt to do the legalization work.
  4601. //
  4602. // Note: legalization specific code
  4603. if (hlsl::IsHLSLRayQueryType(lhsValType)) {
  4604. emitError("store value of type %0 is unsupported", {}) << lhsValType;
  4605. return;
  4606. }
  4607. spvBuilder.createStore(lhsPtr, rhsVal, loc);
  4608. needsLegalization = true;
  4609. } else if (isAKindOfStructuredOrByteBuffer(lhsValType)) {
  4610. // The rhs should be a pointer and the lhs should be a pointer-to-pointer.
  4611. // Directly store the pointer here and let SPIRV-Tools opt to do the clean
  4612. // up.
  4613. //
  4614. // Note: legalization specific code
  4615. spvBuilder.createStore(lhsPtr, rhsVal, loc);
  4616. needsLegalization = true;
  4617. // For ConstantBuffers/TextureBuffers, we decompose and assign each field
  4618. // recursively like normal structs using the following logic.
  4619. //
  4620. // The frontend forbids declaring ConstantBuffer<T> or TextureBuffer<T>
  4621. // variables as function parameters/returns/variables, but happily accepts
  4622. // assignments/returns from ConstantBuffer<T>/TextureBuffer<T> to function
  4623. // parameters/returns/variables of type T. And ConstantBuffer<T> is not
  4624. // represented differently as struct T.
  4625. } else if (isOpaqueArrayType(lhsValType)) {
  4626. // For opaque array types, we cannot perform OpLoad on the whole array and
  4627. // then write out as a whole; instead, we need to OpLoad each element
  4628. // using access chains. This is to influence later SPIR-V transformations
  4629. // to use access chains to access each opaque object; if we do array
  4630. // wholesale handling here, they will be in the final transformed code.
  4631. // Drivers don't like that.
  4632. // TODO: consider moving this hack into SPIRV-Tools as a transformation.
  4633. assert(lhsValType->isConstantArrayType());
  4634. assert(!rhsVal->isRValue());
  4635. const auto *arrayType = astContext.getAsConstantArrayType(lhsValType);
  4636. const auto elemType = arrayType->getElementType();
  4637. const auto arraySize =
  4638. static_cast<uint32_t>(arrayType->getSize().getZExtValue());
  4639. // Do separate load of each element via access chain
  4640. llvm::SmallVector<SpirvInstruction *, 8> elements;
  4641. for (uint32_t i = 0; i < arraySize; ++i) {
  4642. auto *subRhsPtr = spvBuilder.createAccessChain(
  4643. elemType, rhsVal,
  4644. {spvBuilder.getConstantInt(astContext.IntTy,
  4645. llvm::APInt(32, i, true))},
  4646. loc);
  4647. elements.push_back(spvBuilder.createLoad(elemType, subRhsPtr, loc));
  4648. }
  4649. // Create a new composite and write out once
  4650. spvBuilder.createStore(
  4651. lhsPtr,
  4652. spvBuilder.createCompositeConstruct(lhsValType, elements,
  4653. rhsVal->getSourceLocation()),
  4654. loc);
  4655. } else if (lhsPtr->getLayoutRule() == rhsVal->getLayoutRule()) {
  4656. // If lhs and rhs has the same memory layout, we should be safe to load
  4657. // from rhs and directly store into lhs and avoid decomposing rhs.
  4658. // Note: this check should happen after those setting needsLegalization.
  4659. // TODO: is this optimization always correct?
  4660. spvBuilder.createStore(lhsPtr, rhsVal, loc);
  4661. } else if (lhsValType->isRecordType() || lhsValType->isConstantArrayType() ||
  4662. lhsIsNonFpMat) {
  4663. spvBuilder.createStore(
  4664. lhsPtr,
  4665. reconstructValue(rhsVal, lhsValType, lhsPtr->getLayoutRule(), loc),
  4666. loc);
  4667. } else {
  4668. emitError("storing value of type %0 unimplemented", {}) << lhsValType;
  4669. }
  4670. }
  4671. SpirvInstruction *SpirvEmitter::reconstructValue(SpirvInstruction *srcVal,
  4672. const QualType valType,
  4673. SpirvLayoutRule dstLR,
  4674. SourceLocation loc) {
  4675. // Lambda for casting scalar or vector of bool<-->uint in cases where one side
  4676. // of the reconstruction (lhs or rhs) has a layout rule.
  4677. const auto handleBooleanLayout = [this, &srcVal, dstLR,
  4678. loc](SpirvInstruction *val,
  4679. QualType valType) {
  4680. // We only need to cast if we have a scalar or vector of booleans.
  4681. if (!isBoolOrVecOfBoolType(valType))
  4682. return val;
  4683. SpirvLayoutRule srcLR = srcVal->getLayoutRule();
  4684. // Source value has a layout rule, and has therefore been represented
  4685. // as a uint. Cast it to boolean before using.
  4686. bool shouldCastToBool =
  4687. srcLR != SpirvLayoutRule::Void && dstLR == SpirvLayoutRule::Void;
  4688. // Destination has a layout rule, and should therefore be represented
  4689. // as a uint. Cast to uint before using.
  4690. bool shouldCastToUint =
  4691. srcLR == SpirvLayoutRule::Void && dstLR != SpirvLayoutRule::Void;
  4692. // No boolean layout issues to take care of.
  4693. if (!shouldCastToBool && !shouldCastToUint)
  4694. return val;
  4695. uint32_t vecSize = 1;
  4696. isVectorType(valType, nullptr, &vecSize);
  4697. QualType boolType =
  4698. vecSize == 1 ? astContext.BoolTy
  4699. : astContext.getExtVectorType(astContext.BoolTy, vecSize);
  4700. QualType uintType =
  4701. vecSize == 1
  4702. ? astContext.UnsignedIntTy
  4703. : astContext.getExtVectorType(astContext.UnsignedIntTy, vecSize);
  4704. if (shouldCastToBool)
  4705. return castToBool(val, uintType, boolType, loc);
  4706. if (shouldCastToUint)
  4707. return castToInt(val, boolType, uintType, loc);
  4708. return val;
  4709. };
  4710. // Lambda for cases where we want to reconstruct an array
  4711. const auto reconstructArray = [this, &srcVal, valType, dstLR,
  4712. loc](uint32_t arraySize,
  4713. QualType arrayElemType) {
  4714. llvm::SmallVector<SpirvInstruction *, 4> elements;
  4715. for (uint32_t i = 0; i < arraySize; ++i) {
  4716. SpirvInstruction *subSrcVal =
  4717. spvBuilder.createCompositeExtract(arrayElemType, srcVal, {i}, loc);
  4718. subSrcVal->setLayoutRule(srcVal->getLayoutRule());
  4719. elements.push_back(
  4720. reconstructValue(subSrcVal, arrayElemType, dstLR, loc));
  4721. }
  4722. auto *result = spvBuilder.createCompositeConstruct(
  4723. valType, elements, srcVal->getSourceLocation());
  4724. result->setLayoutRule(dstLR);
  4725. return result;
  4726. };
  4727. // Constant arrays
  4728. if (const auto *arrayType = astContext.getAsConstantArrayType(valType)) {
  4729. const auto elemType = arrayType->getElementType();
  4730. const auto size =
  4731. static_cast<uint32_t>(arrayType->getSize().getZExtValue());
  4732. return reconstructArray(size, elemType);
  4733. }
  4734. // Non-floating-point matrices
  4735. QualType matElemType = {};
  4736. uint32_t numRows = 0, numCols = 0;
  4737. const bool isNonFpMat =
  4738. isMxNMatrix(valType, &matElemType, &numRows, &numCols) &&
  4739. !matElemType->isFloatingType();
  4740. if (isNonFpMat) {
  4741. // Note: This check should happen before the RecordType check.
  4742. // Non-fp matrices are represented as arrays of vectors in SPIR-V.
  4743. // Each array element is a vector. Get the QualType for the vector.
  4744. const auto elemType = astContext.getExtVectorType(matElemType, numCols);
  4745. return reconstructArray(numRows, elemType);
  4746. }
  4747. // Note: This check should happen before the RecordType check since
  4748. // vector/matrix/resource types are represented as RecordType in the AST.
  4749. if (hlsl::IsHLSLVecMatType(valType) || hlsl::IsHLSLResourceType(valType))
  4750. return handleBooleanLayout(srcVal, valType);
  4751. // Structs
  4752. if (const auto *recordType = valType->getAs<RecordType>()) {
  4753. uint32_t index = 0;
  4754. llvm::SmallVector<SpirvInstruction *, 4> elements;
  4755. for (const auto *field : recordType->getDecl()->fields()) {
  4756. SpirvInstruction *subSrcVal = spvBuilder.createCompositeExtract(
  4757. field->getType(), srcVal, {index}, loc);
  4758. subSrcVal->setLayoutRule(srcVal->getLayoutRule());
  4759. elements.push_back(
  4760. reconstructValue(subSrcVal, field->getType(), dstLR, loc));
  4761. ++index;
  4762. }
  4763. auto *result = spvBuilder.createCompositeConstruct(
  4764. valType, elements, srcVal->getSourceLocation());
  4765. result->setLayoutRule(dstLR);
  4766. return result;
  4767. }
  4768. return handleBooleanLayout(srcVal, valType);
  4769. }
  4770. SpirvInstruction *SpirvEmitter::processBinaryOp(
  4771. const Expr *lhs, const Expr *rhs, const BinaryOperatorKind opcode,
  4772. const QualType computationType, const QualType resultType,
  4773. SourceRange sourceRange, SourceLocation loc, SpirvInstruction **lhsInfo,
  4774. const spv::Op mandateGenOpcode) {
  4775. const QualType lhsType = lhs->getType();
  4776. const QualType rhsType = rhs->getType();
  4777. // If the operands are of matrix type, we need to dispatch the operation
  4778. // onto each element vector iff the operands are not degenerated matrices
  4779. // and we don't have a matrix specific SPIR-V instruction for the operation.
  4780. if (!isSpirvMatrixOp(mandateGenOpcode) && isMxNMatrix(lhsType)) {
  4781. return processMatrixBinaryOp(lhs, rhs, opcode, sourceRange, loc);
  4782. }
  4783. // Comma operator works differently from other binary operations as there is
  4784. // no SPIR-V instruction for it. For each comma, we must evaluate lhs and rhs
  4785. // respectively, and return the results of rhs.
  4786. if (opcode == BO_Comma) {
  4787. (void)doExpr(lhs);
  4788. return doExpr(rhs);
  4789. }
  4790. SpirvInstruction *rhsVal = nullptr, *lhsPtr = nullptr, *lhsVal = nullptr;
  4791. if (BinaryOperator::isCompoundAssignmentOp(opcode)) {
  4792. // Evalute rhs before lhs
  4793. rhsVal = loadIfGLValue(rhs);
  4794. lhsVal = lhsPtr = doExpr(lhs);
  4795. // This is a compound assignment. We need to load the lhs value if lhs
  4796. // is not already rvalue and does not generate a vector shuffle.
  4797. if (!lhsPtr->isRValue() && !isVectorShuffle(lhs)) {
  4798. lhsVal = loadIfGLValue(lhs, lhsPtr);
  4799. }
  4800. // For a compound assignments, the AST does not have the proper implicit
  4801. // cast if lhs and rhs have different types. So we need to manually cast lhs
  4802. // to the computation type.
  4803. if (computationType != lhsType)
  4804. lhsVal = castToType(lhsVal, lhsType, computationType, lhs->getExprLoc());
  4805. } else {
  4806. // Evalute lhs before rhs
  4807. lhsPtr = doExpr(lhs);
  4808. lhsVal = loadIfGLValue(lhs, lhsPtr);
  4809. rhsVal = loadIfGLValue(rhs);
  4810. }
  4811. if (lhsInfo)
  4812. *lhsInfo = lhsPtr;
  4813. const spv::Op spvOp = (mandateGenOpcode == spv::Op::Max)
  4814. ? translateOp(opcode, computationType)
  4815. : mandateGenOpcode;
  4816. switch (opcode) {
  4817. case BO_Shl:
  4818. case BO_Shr:
  4819. case BO_ShlAssign:
  4820. case BO_ShrAssign:
  4821. // We need to cull the RHS to make sure that we are not shifting by an
  4822. // amount that is larger than the bitwidth of the LHS.
  4823. rhsVal = spvBuilder.createBinaryOp(spv::Op::OpBitwiseAnd, computationType,
  4824. rhsVal, getMaskForBitwidthValue(rhsType),
  4825. loc);
  4826. // Fall through
  4827. case BO_Add:
  4828. case BO_Sub:
  4829. case BO_Mul:
  4830. case BO_Div:
  4831. case BO_Rem:
  4832. case BO_LT:
  4833. case BO_LE:
  4834. case BO_GT:
  4835. case BO_GE:
  4836. case BO_EQ:
  4837. case BO_NE:
  4838. case BO_And:
  4839. case BO_Or:
  4840. case BO_Xor:
  4841. case BO_LAnd:
  4842. case BO_LOr:
  4843. case BO_AddAssign:
  4844. case BO_SubAssign:
  4845. case BO_MulAssign:
  4846. case BO_DivAssign:
  4847. case BO_RemAssign:
  4848. case BO_AndAssign:
  4849. case BO_OrAssign:
  4850. case BO_XorAssign: {
  4851. // To evaluate this expression as an OpSpecConstantOp, we need to make sure
  4852. // both operands are constant and at least one of them is a spec constant.
  4853. if (SpirvConstant *lhsValConstant = dyn_cast<SpirvConstant>(lhsVal)) {
  4854. if (SpirvConstant *rhsValConstant = dyn_cast<SpirvConstant>(rhsVal)) {
  4855. if (isAcceptedSpecConstantBinaryOp(spvOp)) {
  4856. if (lhsValConstant->isSpecConstant() ||
  4857. rhsValConstant->isSpecConstant()) {
  4858. auto *val = spvBuilder.createSpecConstantBinaryOp(
  4859. spvOp, resultType, lhsVal, rhsVal, loc);
  4860. val->setRValue();
  4861. return val;
  4862. }
  4863. }
  4864. }
  4865. }
  4866. // Normal binary operation
  4867. SpirvInstruction *val = nullptr;
  4868. if (BinaryOperator::isCompoundAssignmentOp(opcode)) {
  4869. val = spvBuilder.createBinaryOp(spvOp, computationType, lhsVal, rhsVal,
  4870. loc);
  4871. // For a compound assignments, the AST does not have the proper implicit
  4872. // cast if lhs and rhs have different types. So we need to manually cast
  4873. // the result back to lhs' type.
  4874. if (computationType != lhsType)
  4875. val = castToType(val, computationType, lhsType, lhs->getExprLoc());
  4876. } else {
  4877. val = spvBuilder.createBinaryOp(spvOp, resultType, lhsVal, rhsVal, loc);
  4878. }
  4879. val->setRValue();
  4880. // Propagate RelaxedPrecision
  4881. if (lhsVal->isRelaxedPrecision() || rhsVal->isRelaxedPrecision())
  4882. val->setRelaxedPrecision();
  4883. return val;
  4884. }
  4885. case BO_Assign:
  4886. llvm_unreachable("assignment should not be handled here");
  4887. break;
  4888. case BO_PtrMemD:
  4889. case BO_PtrMemI:
  4890. case BO_Comma:
  4891. // Unimplemented
  4892. break;
  4893. }
  4894. emitError("binary operator '%0' unimplemented", lhs->getExprLoc())
  4895. << BinaryOperator::getOpcodeStr(opcode) << sourceRange;
  4896. return nullptr;
  4897. }
  4898. void SpirvEmitter::initOnce(QualType varType, std::string varName,
  4899. SpirvVariable *var, const Expr *varInit) {
  4900. // For uninitialized resource objects, we do nothing since there is no
  4901. // meaningful zero values for them.
  4902. if (!varInit && hlsl::IsHLSLResourceType(varType))
  4903. return;
  4904. varName = "init.done." + varName;
  4905. auto loc = varInit ? varInit->getLocStart() : SourceLocation();
  4906. // Create a file/module visible variable to hold the initialization state.
  4907. SpirvVariable *initDoneVar = spvBuilder.addModuleVar(
  4908. astContext.BoolTy, spv::StorageClass::Private, /*isPrecise*/ false,
  4909. varName, spvBuilder.getConstantBool(false));
  4910. auto *condition = spvBuilder.createLoad(astContext.BoolTy, initDoneVar, loc);
  4911. auto *todoBB = spvBuilder.createBasicBlock("if.init.todo");
  4912. auto *doneBB = spvBuilder.createBasicBlock("if.init.done");
  4913. // If initDoneVar contains true, we jump to the "done" basic block; otherwise,
  4914. // jump to the "todo" basic block.
  4915. spvBuilder.createConditionalBranch(condition, doneBB, todoBB, loc, doneBB);
  4916. spvBuilder.addSuccessor(todoBB);
  4917. spvBuilder.addSuccessor(doneBB);
  4918. spvBuilder.setMergeTarget(doneBB);
  4919. spvBuilder.setInsertPoint(todoBB);
  4920. // Do initialization and mark done
  4921. if (varInit) {
  4922. var->setStorageClass(spv::StorageClass::Private);
  4923. storeValue(
  4924. // Static function variable are of private storage class
  4925. var, loadIfGLValue(varInit), varInit->getType(), varInit->getLocEnd());
  4926. } else {
  4927. spvBuilder.createStore(var, spvBuilder.getConstantNull(varType), loc);
  4928. }
  4929. spvBuilder.createStore(initDoneVar, spvBuilder.getConstantBool(true), loc);
  4930. spvBuilder.createBranch(doneBB, loc);
  4931. spvBuilder.addSuccessor(doneBB);
  4932. spvBuilder.setInsertPoint(doneBB);
  4933. }
  4934. bool SpirvEmitter::isVectorShuffle(const Expr *expr) {
  4935. // TODO: the following check is essentially duplicated from
  4936. // doHLSLVectorElementExpr. Should unify them.
  4937. if (const auto *vecElemExpr = dyn_cast<HLSLVectorElementExpr>(expr)) {
  4938. const Expr *base = nullptr;
  4939. hlsl::VectorMemberAccessPositions accessor;
  4940. condenseVectorElementExpr(vecElemExpr, &base, &accessor);
  4941. const auto accessorSize = accessor.Count;
  4942. if (accessorSize == 1) {
  4943. // Selecting only one element. OpAccessChain or OpCompositeExtract for
  4944. // such cases.
  4945. return false;
  4946. }
  4947. const auto baseSize = hlsl::GetHLSLVecSize(base->getType());
  4948. if (accessorSize != baseSize)
  4949. return true;
  4950. for (uint32_t i = 0; i < accessorSize; ++i) {
  4951. uint32_t position;
  4952. accessor.GetPosition(i, &position);
  4953. if (position != i)
  4954. return true;
  4955. }
  4956. // Selecting exactly the original vector. No vector shuffle generated.
  4957. return false;
  4958. }
  4959. return false;
  4960. }
  4961. bool SpirvEmitter::isTextureMipsSampleIndexing(const CXXOperatorCallExpr *expr,
  4962. const Expr **base,
  4963. const Expr **location,
  4964. const Expr **lod) {
  4965. if (!expr)
  4966. return false;
  4967. // <object>.mips[][] consists of an outer operator[] and an inner operator[]
  4968. const CXXOperatorCallExpr *outerExpr = expr;
  4969. if (outerExpr->getOperator() != OverloadedOperatorKind::OO_Subscript)
  4970. return false;
  4971. const Expr *arg0 = outerExpr->getArg(0)->IgnoreParenNoopCasts(astContext);
  4972. const CXXOperatorCallExpr *innerExpr = dyn_cast<CXXOperatorCallExpr>(arg0);
  4973. // Must have an inner operator[]
  4974. if (!innerExpr ||
  4975. innerExpr->getOperator() != OverloadedOperatorKind::OO_Subscript) {
  4976. return false;
  4977. }
  4978. const Expr *innerArg0 =
  4979. innerExpr->getArg(0)->IgnoreParenNoopCasts(astContext);
  4980. const MemberExpr *memberExpr = dyn_cast<MemberExpr>(innerArg0);
  4981. if (!memberExpr)
  4982. return false;
  4983. // Must be accessing the member named "mips" or "sample"
  4984. const auto &memberName =
  4985. memberExpr->getMemberNameInfo().getName().getAsString();
  4986. if (memberName != "mips" && memberName != "sample")
  4987. return false;
  4988. const Expr *object = memberExpr->getBase();
  4989. const auto objectType = object->getType();
  4990. if (!isTexture(objectType))
  4991. return false;
  4992. if (base)
  4993. *base = object;
  4994. if (lod)
  4995. *lod = innerExpr->getArg(1);
  4996. if (location)
  4997. *location = outerExpr->getArg(1);
  4998. return true;
  4999. }
  5000. bool SpirvEmitter::isBufferTextureIndexing(const CXXOperatorCallExpr *indexExpr,
  5001. const Expr **base,
  5002. const Expr **index) {
  5003. if (!indexExpr)
  5004. return false;
  5005. // Must be operator[]
  5006. if (indexExpr->getOperator() != OverloadedOperatorKind::OO_Subscript)
  5007. return false;
  5008. const Expr *object = indexExpr->getArg(0);
  5009. const auto objectType = object->getType();
  5010. if (isBuffer(objectType) || isRWBuffer(objectType) || isTexture(objectType) ||
  5011. isRWTexture(objectType)) {
  5012. if (base)
  5013. *base = object;
  5014. if (index)
  5015. *index = indexExpr->getArg(1);
  5016. return true;
  5017. }
  5018. return false;
  5019. }
  5020. void SpirvEmitter::condenseVectorElementExpr(
  5021. const HLSLVectorElementExpr *expr, const Expr **basePtr,
  5022. hlsl::VectorMemberAccessPositions *flattenedAccessor) {
  5023. llvm::SmallVector<hlsl::VectorMemberAccessPositions, 2> accessors;
  5024. *basePtr = expr;
  5025. // Recursively descending until we find the true base vector (the base vector
  5026. // that does not have a base vector). In the meanwhile, collecting accessors
  5027. // in the reverse order.
  5028. // Example: for myVector.yxwz.yxz.xx.yx, the true base is 'myVector'.
  5029. while (const auto *vecElemBase = dyn_cast<HLSLVectorElementExpr>(*basePtr)) {
  5030. accessors.push_back(vecElemBase->getEncodedElementAccess());
  5031. *basePtr = vecElemBase->getBase();
  5032. // We need to skip any number of parentheses around swizzling at any level.
  5033. while (const auto *parenExpr = dyn_cast<ParenExpr>(*basePtr))
  5034. *basePtr = parenExpr->getSubExpr();
  5035. }
  5036. *flattenedAccessor = accessors.back();
  5037. for (int32_t i = accessors.size() - 2; i >= 0; --i) {
  5038. const auto &currentAccessor = accessors[i];
  5039. // Apply the current level of accessor to the flattened accessor of all
  5040. // previous levels of ones.
  5041. hlsl::VectorMemberAccessPositions combinedAccessor;
  5042. for (uint32_t j = 0; j < currentAccessor.Count; ++j) {
  5043. uint32_t currentPosition = 0;
  5044. currentAccessor.GetPosition(j, &currentPosition);
  5045. uint32_t previousPosition = 0;
  5046. flattenedAccessor->GetPosition(currentPosition, &previousPosition);
  5047. combinedAccessor.SetPosition(j, previousPosition);
  5048. }
  5049. combinedAccessor.Count = currentAccessor.Count;
  5050. combinedAccessor.IsValid =
  5051. flattenedAccessor->IsValid && currentAccessor.IsValid;
  5052. *flattenedAccessor = combinedAccessor;
  5053. }
  5054. }
  5055. SpirvInstruction *SpirvEmitter::createVectorSplat(const Expr *scalarExpr,
  5056. uint32_t size) {
  5057. SpirvInstruction *scalarVal = nullptr;
  5058. // Try to evaluate the element as constant first. If successful, then we
  5059. // can generate constant instructions for this vector splat.
  5060. if ((scalarVal = tryToEvaluateAsConst(scalarExpr))) {
  5061. scalarVal->setRValue();
  5062. } else {
  5063. scalarVal = loadIfGLValue(scalarExpr);
  5064. }
  5065. if (!scalarVal || size == 1) {
  5066. // Just return the scalar value for vector splat with size 1.
  5067. // Note that can be used as an lvalue, so we need to carry over
  5068. // the lvalueness for non-constant cases.
  5069. return scalarVal;
  5070. }
  5071. const auto vecType = astContext.getExtVectorType(scalarExpr->getType(), size);
  5072. // TODO: we are saying the constant has Function storage class here.
  5073. // Should find a more meaningful one.
  5074. if (auto *constVal = dyn_cast<SpirvConstant>(scalarVal)) {
  5075. llvm::SmallVector<SpirvConstant *, 4> elements(size_t(size), constVal);
  5076. auto *value = spvBuilder.getConstantComposite(vecType, elements);
  5077. value->setRValue();
  5078. return value;
  5079. } else {
  5080. llvm::SmallVector<SpirvInstruction *, 4> elements(size_t(size), scalarVal);
  5081. auto *value = spvBuilder.createCompositeConstruct(
  5082. vecType, elements, scalarExpr->getLocStart());
  5083. value->setRValue();
  5084. return value;
  5085. }
  5086. }
  5087. void SpirvEmitter::splitVecLastElement(QualType vecType, SpirvInstruction *vec,
  5088. SpirvInstruction **residual,
  5089. SpirvInstruction **lastElement,
  5090. SourceLocation loc) {
  5091. assert(hlsl::IsHLSLVecType(vecType));
  5092. const uint32_t count = hlsl::GetHLSLVecSize(vecType);
  5093. assert(count > 1);
  5094. const QualType elemType = hlsl::GetHLSLVecElementType(vecType);
  5095. if (count == 2) {
  5096. *residual = spvBuilder.createCompositeExtract(elemType, vec, 0, loc);
  5097. } else {
  5098. llvm::SmallVector<uint32_t, 4> indices;
  5099. for (uint32_t i = 0; i < count - 1; ++i)
  5100. indices.push_back(i);
  5101. const QualType type = astContext.getExtVectorType(elemType, count - 1);
  5102. *residual = spvBuilder.createVectorShuffle(type, vec, vec, indices, loc);
  5103. }
  5104. *lastElement =
  5105. spvBuilder.createCompositeExtract(elemType, vec, {count - 1}, loc);
  5106. }
  5107. SpirvInstruction *SpirvEmitter::convertVectorToStruct(QualType structType,
  5108. QualType elemType,
  5109. SpirvInstruction *vector,
  5110. SourceLocation loc) {
  5111. assert(structType->isStructureType());
  5112. const auto *structDecl = structType->getAsStructureType()->getDecl();
  5113. uint32_t vectorIndex = 0;
  5114. uint32_t elemCount = 1;
  5115. llvm::SmallVector<SpirvInstruction *, 4> members;
  5116. for (const auto *field : structDecl->fields()) {
  5117. if (isScalarType(field->getType())) {
  5118. members.push_back(spvBuilder.createCompositeExtract(
  5119. elemType, vector, {vectorIndex++}, loc));
  5120. } else if (isVectorType(field->getType(), nullptr, &elemCount)) {
  5121. llvm::SmallVector<uint32_t, 4> indices;
  5122. for (uint32_t i = 0; i < elemCount; ++i)
  5123. indices.push_back(vectorIndex++);
  5124. members.push_back(spvBuilder.createVectorShuffle(
  5125. astContext.getExtVectorType(elemType, elemCount), vector, vector,
  5126. indices, loc));
  5127. } else {
  5128. assert(false && "unhandled type");
  5129. }
  5130. }
  5131. return spvBuilder.createCompositeConstruct(structType, members,
  5132. vector->getSourceLocation());
  5133. }
  5134. SpirvInstruction *
  5135. SpirvEmitter::tryToGenFloatVectorScale(const BinaryOperator *expr) {
  5136. const QualType type = expr->getType();
  5137. const SourceRange range = expr->getSourceRange();
  5138. QualType elemType = {};
  5139. // We can only translate floatN * float into OpVectorTimesScalar.
  5140. // So the result type must be floatN. Note that float1 is not a valid vector
  5141. // in SPIR-V.
  5142. if (!(isVectorType(type, &elemType) && elemType->isFloatingType()))
  5143. return nullptr;
  5144. const Expr *lhs = expr->getLHS();
  5145. const Expr *rhs = expr->getRHS();
  5146. // Multiplying a float vector with a float scalar will be represented in
  5147. // AST via a binary operation with two float vectors as operands; one of
  5148. // the operand is from an implicit cast with kind CK_HLSLVectorSplat.
  5149. // vector * scalar
  5150. if (hlsl::IsHLSLVecType(lhs->getType())) {
  5151. if (const auto *cast = dyn_cast<ImplicitCastExpr>(rhs)) {
  5152. if (cast->getCastKind() == CK_HLSLVectorSplat) {
  5153. const QualType vecType = expr->getType();
  5154. if (isa<CompoundAssignOperator>(expr)) {
  5155. SpirvInstruction *lhsPtr = nullptr;
  5156. auto *result =
  5157. processBinaryOp(lhs, cast->getSubExpr(), expr->getOpcode(),
  5158. vecType, vecType, range, expr->getOperatorLoc(),
  5159. &lhsPtr, spv::Op::OpVectorTimesScalar);
  5160. return processAssignment(lhs, result, true, lhsPtr);
  5161. } else {
  5162. return processBinaryOp(lhs, cast->getSubExpr(), expr->getOpcode(),
  5163. vecType, vecType, range,
  5164. expr->getOperatorLoc(), nullptr,
  5165. spv::Op::OpVectorTimesScalar);
  5166. }
  5167. }
  5168. }
  5169. }
  5170. // scalar * vector
  5171. if (hlsl::IsHLSLVecType(rhs->getType())) {
  5172. if (const auto *cast = dyn_cast<ImplicitCastExpr>(lhs)) {
  5173. if (cast->getCastKind() == CK_HLSLVectorSplat) {
  5174. const QualType vecType = expr->getType();
  5175. // We need to switch the positions of lhs and rhs here because
  5176. // OpVectorTimesScalar requires the first operand to be a vector and
  5177. // the second to be a scalar.
  5178. return processBinaryOp(rhs, cast->getSubExpr(), expr->getOpcode(),
  5179. vecType, vecType, range, expr->getOperatorLoc(),
  5180. nullptr, spv::Op::OpVectorTimesScalar);
  5181. }
  5182. }
  5183. }
  5184. return nullptr;
  5185. }
  5186. SpirvInstruction *
  5187. SpirvEmitter::tryToGenFloatMatrixScale(const BinaryOperator *expr) {
  5188. const QualType type = expr->getType();
  5189. const SourceRange range = expr->getSourceRange();
  5190. // We translate 'floatMxN * float' into OpMatrixTimesScalar.
  5191. // We translate 'floatMx1 * float' and 'float1xN * float' using
  5192. // OpVectorTimesScalar.
  5193. // So the result type can be floatMxN, floatMx1, or float1xN.
  5194. if (!hlsl::IsHLSLMatType(type) ||
  5195. !hlsl::GetHLSLMatElementType(type)->isFloatingType() || is1x1Matrix(type))
  5196. return 0;
  5197. const Expr *lhs = expr->getLHS();
  5198. const Expr *rhs = expr->getRHS();
  5199. const QualType lhsType = lhs->getType();
  5200. const QualType rhsType = rhs->getType();
  5201. const auto selectOpcode = [](const QualType ty) {
  5202. return isMx1Matrix(ty) || is1xNMatrix(ty) ? spv::Op::OpVectorTimesScalar
  5203. : spv::Op::OpMatrixTimesScalar;
  5204. };
  5205. // Multiplying a float matrix with a float scalar will be represented in
  5206. // AST via a binary operation with two float matrices as operands; one of
  5207. // the operand is from an implicit cast with kind CK_HLSLMatrixSplat.
  5208. // matrix * scalar
  5209. if (hlsl::IsHLSLMatType(lhsType)) {
  5210. if (const auto *cast = dyn_cast<ImplicitCastExpr>(rhs)) {
  5211. if (cast->getCastKind() == CK_HLSLMatrixSplat) {
  5212. const QualType matType = expr->getType();
  5213. const spv::Op opcode = selectOpcode(lhsType);
  5214. if (isa<CompoundAssignOperator>(expr)) {
  5215. SpirvInstruction *lhsPtr = nullptr;
  5216. auto *result = processBinaryOp(
  5217. lhs, cast->getSubExpr(), expr->getOpcode(), matType, matType,
  5218. range, expr->getOperatorLoc(), &lhsPtr, opcode);
  5219. return processAssignment(lhs, result, true, lhsPtr);
  5220. } else {
  5221. return processBinaryOp(lhs, cast->getSubExpr(), expr->getOpcode(),
  5222. matType, matType, range,
  5223. expr->getOperatorLoc(), nullptr, opcode);
  5224. }
  5225. }
  5226. }
  5227. }
  5228. // scalar * matrix
  5229. if (hlsl::IsHLSLMatType(rhsType)) {
  5230. if (const auto *cast = dyn_cast<ImplicitCastExpr>(lhs)) {
  5231. if (cast->getCastKind() == CK_HLSLMatrixSplat) {
  5232. const QualType matType = expr->getType();
  5233. const spv::Op opcode = selectOpcode(rhsType);
  5234. // We need to switch the positions of lhs and rhs here because
  5235. // OpMatrixTimesScalar requires the first operand to be a matrix and
  5236. // the second to be a scalar.
  5237. return processBinaryOp(rhs, cast->getSubExpr(), expr->getOpcode(),
  5238. matType, matType, range, expr->getOperatorLoc(),
  5239. nullptr, opcode);
  5240. }
  5241. }
  5242. }
  5243. return nullptr;
  5244. }
  5245. SpirvInstruction *
  5246. SpirvEmitter::tryToAssignToVectorElements(const Expr *lhs,
  5247. SpirvInstruction *rhs) {
  5248. // Assigning to a vector swizzling lhs is tricky if we are neither
  5249. // writing to one element nor all elements in their original order.
  5250. // Under such cases, we need to create a new vector swizzling involving
  5251. // both the lhs and rhs vectors and then write the result of this swizzling
  5252. // into the base vector of lhs.
  5253. // For example, for vec4.yz = vec2, we nee to do the following:
  5254. //
  5255. // %vec4Val = OpLoad %v4float %vec4
  5256. // %vec2Val = OpLoad %v2float %vec2
  5257. // %shuffle = OpVectorShuffle %v4float %vec4Val %vec2Val 0 4 5 3
  5258. // OpStore %vec4 %shuffle
  5259. //
  5260. // When doing the vector shuffle, we use the lhs base vector as the first
  5261. // vector and the rhs vector as the second vector. Therefore, all elements
  5262. // in the second vector will be selected into the shuffle result.
  5263. const auto *lhsExpr = dyn_cast<HLSLVectorElementExpr>(lhs);
  5264. if (!lhsExpr)
  5265. return 0;
  5266. // Special case for <scalar-value>.x, which will have an AST of
  5267. // HLSLVectorElementExpr whose base is an ImplicitCastExpr
  5268. // (CK_HLSLVectorSplat). We just need to assign to <scalar-value>
  5269. // for such case.
  5270. if (const auto *baseCast = dyn_cast<CastExpr>(lhsExpr->getBase()))
  5271. if (baseCast->getCastKind() == CastKind::CK_HLSLVectorSplat &&
  5272. hlsl::GetHLSLVecSize(baseCast->getType()) == 1)
  5273. return processAssignment(baseCast->getSubExpr(), rhs, false);
  5274. const Expr *base = nullptr;
  5275. hlsl::VectorMemberAccessPositions accessor;
  5276. condenseVectorElementExpr(lhsExpr, &base, &accessor);
  5277. const QualType baseType = base->getType();
  5278. assert(hlsl::IsHLSLVecType(baseType));
  5279. const auto baseSize = hlsl::GetHLSLVecSize(baseType);
  5280. const auto accessorSize = accessor.Count;
  5281. // Whether selecting the whole original vector
  5282. bool isSelectOrigin = accessorSize == baseSize;
  5283. // Assigning to one component
  5284. if (accessorSize == 1) {
  5285. if (isBufferTextureIndexing(dyn_cast_or_null<CXXOperatorCallExpr>(base))) {
  5286. // Assigning to one component of a RWBuffer/RWTexture element
  5287. // We need to use OpImageWrite here.
  5288. // Compose the new vector value first
  5289. auto *oldVec = doExpr(base);
  5290. auto *newVec = spvBuilder.createCompositeInsert(
  5291. baseType, oldVec, {accessor.Swz0}, rhs, lhs->getLocStart());
  5292. auto *result = tryToAssignToRWBufferRWTexture(base, newVec);
  5293. assert(result); // Definitely RWBuffer/RWTexture assignment
  5294. (void)result;
  5295. return rhs; // TODO: incorrect for compound assignments
  5296. } else {
  5297. // Assigning to one component of mesh out attribute/indices vector object.
  5298. SpirvInstruction *vecComponent = spvBuilder.getConstantInt(
  5299. astContext.UnsignedIntTy, llvm::APInt(32, accessor.Swz0));
  5300. if (tryToAssignToMSOutAttrsOrIndices(base, rhs, vecComponent))
  5301. return rhs;
  5302. // Assigning to one normal vector component. Nothing special, just fall
  5303. // back to the normal CodeGen path.
  5304. return nullptr;
  5305. }
  5306. }
  5307. if (isSelectOrigin) {
  5308. for (uint32_t i = 0; i < accessorSize; ++i) {
  5309. uint32_t position;
  5310. accessor.GetPosition(i, &position);
  5311. if (position != i)
  5312. isSelectOrigin = false;
  5313. }
  5314. }
  5315. // Assigning to the original vector
  5316. if (isSelectOrigin) {
  5317. // Ignore this HLSLVectorElementExpr and dispatch to base
  5318. return processAssignment(base, rhs, false);
  5319. }
  5320. if (tryToAssignToMSOutAttrsOrIndices(base, rhs, /*vecComponent=*/nullptr,
  5321. /*noWriteBack=*/true)) {
  5322. // Assigning to 'n' components of mesh out attribute/indices vector object.
  5323. const QualType elemType =
  5324. hlsl::GetHLSLVecElementType(rhs->getAstResultType());
  5325. uint32_t i = 0;
  5326. for (; i < accessor.Count; ++i) {
  5327. auto *rhsElem = spvBuilder.createCompositeExtract(elemType, rhs, {i},
  5328. lhs->getLocStart());
  5329. uint32_t position;
  5330. accessor.GetPosition(i, &position);
  5331. SpirvInstruction *vecComponent = spvBuilder.getConstantInt(
  5332. astContext.UnsignedIntTy, llvm::APInt(32, position));
  5333. if (!tryToAssignToMSOutAttrsOrIndices(base, rhsElem, vecComponent))
  5334. break;
  5335. }
  5336. assert(i == accessor.Count);
  5337. return rhs;
  5338. }
  5339. llvm::SmallVector<uint32_t, 4> selectors;
  5340. selectors.resize(baseSize);
  5341. // Assume we are selecting all original elements first.
  5342. for (uint32_t i = 0; i < baseSize; ++i) {
  5343. selectors[i] = i;
  5344. }
  5345. // Now fix up the elements that actually got overwritten by the rhs vector.
  5346. // Since we are using the rhs vector as the second vector, their index
  5347. // should be offset'ed by the size of the lhs base vector.
  5348. for (uint32_t i = 0; i < accessor.Count; ++i) {
  5349. uint32_t position;
  5350. accessor.GetPosition(i, &position);
  5351. selectors[position] = baseSize + i;
  5352. }
  5353. auto *vec1 = doExpr(base);
  5354. auto *vec1Val = vec1->isRValue() ? vec1
  5355. : spvBuilder.createLoad(baseType, vec1,
  5356. base->getLocStart());
  5357. auto *shuffle = spvBuilder.createVectorShuffle(baseType, vec1Val, rhs,
  5358. selectors, lhs->getLocStart());
  5359. if (!tryToAssignToRWBufferRWTexture(base, shuffle))
  5360. spvBuilder.createStore(vec1, shuffle, lhs->getLocStart());
  5361. // TODO: OK, this return value is incorrect for compound assignments, for
  5362. // which cases we should return lvalues. Should at least emit errors if
  5363. // this return value is used (can be checked via ASTContext.getParents).
  5364. return rhs;
  5365. }
  5366. SpirvInstruction *
  5367. SpirvEmitter::tryToAssignToRWBufferRWTexture(const Expr *lhs,
  5368. SpirvInstruction *rhs) {
  5369. const Expr *baseExpr = nullptr;
  5370. const Expr *indexExpr = nullptr;
  5371. const auto lhsExpr = dyn_cast<CXXOperatorCallExpr>(lhs);
  5372. if (isBufferTextureIndexing(lhsExpr, &baseExpr, &indexExpr)) {
  5373. auto *loc = doExpr(indexExpr);
  5374. const QualType imageType = baseExpr->getType();
  5375. auto *baseInfo = doExpr(baseExpr);
  5376. auto *image =
  5377. spvBuilder.createLoad(imageType, baseInfo, baseExpr->getExprLoc());
  5378. spvBuilder.createImageWrite(imageType, image, loc, rhs, lhs->getExprLoc());
  5379. return rhs;
  5380. }
  5381. return nullptr;
  5382. }
  5383. SpirvInstruction *
  5384. SpirvEmitter::tryToAssignToMatrixElements(const Expr *lhs,
  5385. SpirvInstruction *rhs) {
  5386. const auto *lhsExpr = dyn_cast<ExtMatrixElementExpr>(lhs);
  5387. if (!lhsExpr)
  5388. return nullptr;
  5389. const Expr *baseMat = lhsExpr->getBase();
  5390. auto *base = doExpr(baseMat);
  5391. const QualType elemType = hlsl::GetHLSLMatElementType(baseMat->getType());
  5392. uint32_t rowCount = 0, colCount = 0;
  5393. hlsl::GetHLSLMatRowColCount(baseMat->getType(), rowCount, colCount);
  5394. // For each lhs element written to:
  5395. // 1. Extract the corresponding rhs element using OpCompositeExtract
  5396. // 2. Create access chain for the lhs element using OpAccessChain
  5397. // 3. Write using OpStore
  5398. const auto accessor = lhsExpr->getEncodedElementAccess();
  5399. for (uint32_t i = 0; i < accessor.Count; ++i) {
  5400. uint32_t row = 0, col = 0;
  5401. accessor.GetPosition(i, &row, &col);
  5402. llvm::SmallVector<uint32_t, 2> indices;
  5403. // If the matrix only have one row/column, we are indexing into a vector
  5404. // then. Only one index is needed for such cases.
  5405. if (rowCount > 1)
  5406. indices.push_back(row);
  5407. if (colCount > 1)
  5408. indices.push_back(col);
  5409. llvm::SmallVector<SpirvInstruction *, 2> indexInstructions(indices.size(),
  5410. nullptr);
  5411. for (uint32_t i = 0; i < indices.size(); ++i)
  5412. indexInstructions[i] = spvBuilder.getConstantInt(
  5413. astContext.IntTy, llvm::APInt(32, indices[i], true));
  5414. // If we are writing to only one element, the rhs should already be a
  5415. // scalar value.
  5416. auto *rhsElem = rhs;
  5417. if (accessor.Count > 1) {
  5418. rhsElem = spvBuilder.createCompositeExtract(elemType, rhs, {i},
  5419. rhs->getSourceLocation());
  5420. }
  5421. // If the lhs is actually a matrix of size 1x1, we don't need the access
  5422. // chain. base is already the dest pointer.
  5423. auto *lhsElemPtr = base;
  5424. if (!indexInstructions.empty()) {
  5425. assert(!base->isRValue());
  5426. // Load the element via access chain
  5427. lhsElemPtr = spvBuilder.createAccessChain(
  5428. elemType, lhsElemPtr, indexInstructions, lhs->getLocStart());
  5429. }
  5430. spvBuilder.createStore(lhsElemPtr, rhsElem, lhs->getLocStart());
  5431. }
  5432. // TODO: OK, this return value is incorrect for compound assignments, for
  5433. // which cases we should return lvalues. Should at least emit errors if
  5434. // this return value is used (can be checked via ASTContext.getParents).
  5435. return rhs;
  5436. }
  5437. SpirvInstruction *SpirvEmitter::tryToAssignToMSOutAttrsOrIndices(
  5438. const Expr *lhs, SpirvInstruction *rhs, SpirvInstruction *vecComponent,
  5439. bool noWriteBack) {
  5440. // Early exit for non-mesh shaders.
  5441. if (!spvContext.isMS())
  5442. return nullptr;
  5443. llvm::SmallVector<SpirvInstruction *, 4> indices;
  5444. bool isMSOutAttribute = false;
  5445. bool isMSOutAttributeBlock = false;
  5446. bool isMSOutIndices = false;
  5447. const Expr *base = collectArrayStructIndices(lhs, /*rawIndex*/ false,
  5448. /*rawIndices*/ nullptr, &indices,
  5449. &isMSOutAttribute);
  5450. // Expecting at least one array index - early exit.
  5451. if (!base || indices.empty())
  5452. return nullptr;
  5453. const DeclaratorDecl *varDecl = nullptr;
  5454. if (isMSOutAttribute) {
  5455. const MemberExpr *memberExpr = dyn_cast<MemberExpr>(base);
  5456. assert(memberExpr);
  5457. varDecl = cast<DeclaratorDecl>(memberExpr->getMemberDecl());
  5458. } else {
  5459. if (const auto *arg = dyn_cast<DeclRefExpr>(base)) {
  5460. if (varDecl = dyn_cast<DeclaratorDecl>(arg->getDecl())) {
  5461. if (varDecl->hasAttr<HLSLIndicesAttr>()) {
  5462. isMSOutIndices = true;
  5463. } else if (varDecl->hasAttr<HLSLVerticesAttr>() ||
  5464. varDecl->hasAttr<HLSLPrimitivesAttr>()) {
  5465. isMSOutAttributeBlock = true;
  5466. }
  5467. }
  5468. }
  5469. }
  5470. // Return if no out attribute or indices object found.
  5471. if (!(isMSOutAttribute || isMSOutAttributeBlock || isMSOutIndices)) {
  5472. return nullptr;
  5473. }
  5474. // For noWriteBack, return without generating write instructions.
  5475. if (noWriteBack) {
  5476. return rhs;
  5477. }
  5478. // Add vecComponent to indices.
  5479. if (vecComponent) {
  5480. indices.push_back(vecComponent);
  5481. }
  5482. if (isMSOutAttribute) {
  5483. assignToMSOutAttribute(varDecl, rhs, indices);
  5484. } else if (isMSOutIndices) {
  5485. assignToMSOutIndices(varDecl, rhs, indices);
  5486. } else {
  5487. assert(isMSOutAttributeBlock);
  5488. QualType type = varDecl->getType();
  5489. assert(isa<ConstantArrayType>(type));
  5490. type = astContext.getAsConstantArrayType(type)->getElementType();
  5491. assert(type->isStructureType());
  5492. // Extract subvalue and assign to its corresponding member attribute.
  5493. const auto *structDecl = type->getAs<RecordType>()->getDecl();
  5494. for (const auto *field : structDecl->fields()) {
  5495. const auto fieldType = field->getType();
  5496. SpirvInstruction *subValue = spvBuilder.createCompositeExtract(
  5497. fieldType, rhs, {getNumBaseClasses(type) + field->getFieldIndex()},
  5498. lhs->getLocStart());
  5499. assignToMSOutAttribute(field, subValue, indices);
  5500. }
  5501. }
  5502. // TODO: OK, this return value is incorrect for compound assignments, for
  5503. // which cases we should return lvalues. Should at least emit errors if
  5504. // this return value is used (can be checked via ASTContext.getParents).
  5505. return rhs;
  5506. }
  5507. void SpirvEmitter::assignToMSOutAttribute(
  5508. const DeclaratorDecl *decl, SpirvInstruction *value,
  5509. const llvm::SmallVector<SpirvInstruction *, 4> &indices) {
  5510. assert(spvContext.isMS() && !indices.empty());
  5511. // Extract attribute index and vecComponent (if any).
  5512. SpirvInstruction *attrIndex = indices.front();
  5513. SpirvInstruction *vecComponent = nullptr;
  5514. if (indices.size() > 1) {
  5515. vecComponent = indices.back();
  5516. }
  5517. auto semanticInfo = declIdMapper.getStageVarSemantic(decl);
  5518. assert(semanticInfo.isValid());
  5519. const auto loc = decl->getLocation();
  5520. // Special handle writes to clip/cull distance attributes.
  5521. if (!declIdMapper.glPerVertex.tryToAccess(
  5522. hlsl::DXIL::SigPointKind::MSOut, semanticInfo.semantic->GetKind(),
  5523. semanticInfo.index, attrIndex, &value, /*noWriteBack=*/false,
  5524. vecComponent, loc)) {
  5525. // All other attribute writes are handled below.
  5526. auto *varInstr = declIdMapper.getStageVarInstruction(decl);
  5527. QualType valueType = value->getAstResultType();
  5528. varInstr = spvBuilder.createAccessChain(valueType, varInstr, indices, loc);
  5529. spvBuilder.createStore(varInstr, value, loc);
  5530. }
  5531. }
  5532. void SpirvEmitter::assignToMSOutIndices(
  5533. const DeclaratorDecl *decl, SpirvInstruction *value,
  5534. const llvm::SmallVector<SpirvInstruction *, 4> &indices) {
  5535. assert(spvContext.isMS() && !indices.empty());
  5536. // Extract vertex index and vecComponent (if any).
  5537. SpirvInstruction *vertIndex = indices.front();
  5538. SpirvInstruction *vecComponent = nullptr;
  5539. if (indices.size() > 1) {
  5540. vecComponent = indices.back();
  5541. }
  5542. auto *var = declIdMapper.getStageVarInstruction(decl);
  5543. const auto *varTypeDecl = astContext.getAsConstantArrayType(decl->getType());
  5544. QualType varType = varTypeDecl->getElementType();
  5545. uint32_t numVertices = 1;
  5546. if (!isVectorType(varType, nullptr, &numVertices)) {
  5547. assert(isScalarType(varType));
  5548. }
  5549. QualType valueType = value->getAstResultType();
  5550. uint32_t numValues = 1;
  5551. if (!isVectorType(valueType, nullptr, &numValues)) {
  5552. assert(isScalarType(valueType));
  5553. }
  5554. const auto loc = decl->getLocation();
  5555. if (numVertices == 1) {
  5556. // for "point" output topology.
  5557. assert(numValues == 1);
  5558. // create accesschain for PrimitiveIndicesNV[vertIndex].
  5559. auto *ptr = spvBuilder.createAccessChain(astContext.UnsignedIntTy, var,
  5560. {vertIndex}, loc);
  5561. // finally create store for PrimitiveIndicesNV[vertIndex] = value.
  5562. spvBuilder.createStore(ptr, value, loc);
  5563. } else {
  5564. // for "line" or "triangle" output topology.
  5565. assert(numVertices == 2 || numVertices == 3);
  5566. // set baseOffset = vertIndex * numVertices.
  5567. auto *baseOffset = spvBuilder.createBinaryOp(
  5568. spv::Op::OpIMul, astContext.UnsignedIntTy, vertIndex,
  5569. spvBuilder.getConstantInt(astContext.UnsignedIntTy,
  5570. llvm::APInt(32, numVertices)),
  5571. loc);
  5572. if (vecComponent) {
  5573. // write an individual vector component of uint2 or uint3.
  5574. assert(numValues == 1);
  5575. // set baseOffset = baseOffset + vecComponent.
  5576. baseOffset =
  5577. spvBuilder.createBinaryOp(spv::Op::OpIAdd, astContext.UnsignedIntTy,
  5578. baseOffset, vecComponent, loc);
  5579. // create accesschain for PrimitiveIndicesNV[baseOffset].
  5580. auto *ptr = spvBuilder.createAccessChain(astContext.UnsignedIntTy, var,
  5581. {baseOffset}, loc);
  5582. // finally create store for PrimitiveIndicesNV[baseOffset] = value.
  5583. spvBuilder.createStore(ptr, value, loc);
  5584. } else {
  5585. // write all vector components of uint2 or uint3.
  5586. assert(numValues == numVertices);
  5587. auto *curOffset = baseOffset;
  5588. for (uint32_t i = 0; i < numValues; ++i) {
  5589. if (i != 0) {
  5590. // set curOffset = baseOffset + i.
  5591. curOffset = spvBuilder.createBinaryOp(
  5592. spv::Op::OpIAdd, astContext.UnsignedIntTy, baseOffset,
  5593. spvBuilder.getConstantInt(astContext.UnsignedIntTy,
  5594. llvm::APInt(32, i)),
  5595. loc);
  5596. }
  5597. // create accesschain for PrimitiveIndicesNV[curOffset].
  5598. auto *ptr = spvBuilder.createAccessChain(astContext.UnsignedIntTy, var,
  5599. {curOffset}, loc);
  5600. // finally create store for PrimitiveIndicesNV[curOffset] = value[i].
  5601. spvBuilder.createStore(ptr,
  5602. spvBuilder.createCompositeExtract(
  5603. astContext.UnsignedIntTy, value, {i}, loc),
  5604. loc);
  5605. }
  5606. }
  5607. }
  5608. }
  5609. SpirvInstruction *SpirvEmitter::processEachVectorInMatrix(
  5610. const Expr *matrix, SpirvInstruction *matrixVal,
  5611. llvm::function_ref<SpirvInstruction *(uint32_t, QualType,
  5612. SpirvInstruction *)>
  5613. actOnEachVector,
  5614. SourceLocation loc) {
  5615. const auto matType = matrix->getType();
  5616. assert(isMxNMatrix(matType));
  5617. const QualType vecType = getComponentVectorType(astContext, matType);
  5618. uint32_t rowCount = 0, colCount = 0;
  5619. hlsl::GetHLSLMatRowColCount(matType, rowCount, colCount);
  5620. llvm::SmallVector<SpirvInstruction *, 4> vectors;
  5621. // Extract each component vector and do operation on it
  5622. for (uint32_t i = 0; i < rowCount; ++i) {
  5623. auto *lhsVec = spvBuilder.createCompositeExtract(vecType, matrixVal, {i},
  5624. matrix->getLocStart());
  5625. vectors.push_back(actOnEachVector(i, vecType, lhsVec));
  5626. }
  5627. // Construct the result matrix
  5628. auto *val = spvBuilder.createCompositeConstruct(matType, vectors, loc);
  5629. val->setRValue();
  5630. return val;
  5631. }
  5632. void SpirvEmitter::createSpecConstant(const VarDecl *varDecl) {
  5633. class SpecConstantEnvRAII {
  5634. public:
  5635. // Creates a new instance which sets mode to true on creation,
  5636. // and resets mode to false on destruction.
  5637. SpecConstantEnvRAII(bool *mode) : modeSlot(mode) { *modeSlot = true; }
  5638. ~SpecConstantEnvRAII() { *modeSlot = false; }
  5639. private:
  5640. bool *modeSlot;
  5641. };
  5642. const QualType varType = varDecl->getType();
  5643. bool hasError = false;
  5644. if (!varDecl->isExternallyVisible()) {
  5645. emitError("specialization constant must be externally visible",
  5646. varDecl->getLocation());
  5647. hasError = true;
  5648. }
  5649. if (const auto *builtinType = varType->getAs<BuiltinType>()) {
  5650. switch (builtinType->getKind()) {
  5651. case BuiltinType::Bool:
  5652. case BuiltinType::Int:
  5653. case BuiltinType::UInt:
  5654. case BuiltinType::Float:
  5655. break;
  5656. default:
  5657. emitError("unsupported specialization constant type",
  5658. varDecl->getLocStart());
  5659. hasError = true;
  5660. }
  5661. }
  5662. const auto *init = varDecl->getInit();
  5663. if (!init) {
  5664. emitError("missing default value for specialization constant",
  5665. varDecl->getLocation());
  5666. hasError = true;
  5667. } else if (!isAcceptedSpecConstantInit(init)) {
  5668. emitError("unsupported specialization constant initializer",
  5669. init->getLocStart())
  5670. << init->getSourceRange();
  5671. hasError = true;
  5672. }
  5673. if (hasError)
  5674. return;
  5675. SpecConstantEnvRAII specConstantEnvRAII(&isSpecConstantMode);
  5676. const auto specConstant = doExpr(init);
  5677. // We are not creating a variable to hold the spec constant, instead, we
  5678. // translate the varDecl directly into the spec constant here.
  5679. spvBuilder.decorateSpecId(
  5680. specConstant, varDecl->getAttr<VKConstantIdAttr>()->getSpecConstId(),
  5681. varDecl->getLocation());
  5682. specConstant->setDebugName(varDecl->getName());
  5683. declIdMapper.registerSpecConstant(varDecl, specConstant);
  5684. }
  5685. SpirvInstruction *
  5686. SpirvEmitter::processMatrixBinaryOp(const Expr *lhs, const Expr *rhs,
  5687. const BinaryOperatorKind opcode,
  5688. SourceRange range, SourceLocation loc) {
  5689. // TODO: some code are duplicated from processBinaryOp. Try to unify them.
  5690. const auto lhsType = lhs->getType();
  5691. assert(isMxNMatrix(lhsType));
  5692. const spv::Op spvOp = translateOp(opcode, lhsType);
  5693. SpirvInstruction *rhsVal = nullptr, *lhsPtr = nullptr, *lhsVal = nullptr;
  5694. if (BinaryOperator::isCompoundAssignmentOp(opcode)) {
  5695. // Evalute rhs before lhs
  5696. rhsVal = doExpr(rhs);
  5697. lhsPtr = doExpr(lhs);
  5698. lhsVal = spvBuilder.createLoad(lhsType, lhsPtr, lhs->getLocStart());
  5699. } else {
  5700. // Evalute lhs before rhs
  5701. lhsVal = lhsPtr = doExpr(lhs);
  5702. rhsVal = doExpr(rhs);
  5703. }
  5704. switch (opcode) {
  5705. case BO_Add:
  5706. case BO_Sub:
  5707. case BO_Mul:
  5708. case BO_Div:
  5709. case BO_Rem:
  5710. case BO_AddAssign:
  5711. case BO_SubAssign:
  5712. case BO_MulAssign:
  5713. case BO_DivAssign:
  5714. case BO_RemAssign: {
  5715. const auto actOnEachVec = [this, spvOp, rhsVal, rhs,
  5716. loc](uint32_t index, QualType vecType,
  5717. SpirvInstruction *lhsVec) {
  5718. // For each vector of lhs, we need to load the corresponding vector of
  5719. // rhs and do the operation on them.
  5720. auto *rhsVec = spvBuilder.createCompositeExtract(vecType, rhsVal, {index},
  5721. rhs->getLocStart());
  5722. auto *val =
  5723. spvBuilder.createBinaryOp(spvOp, vecType, lhsVec, rhsVec, loc);
  5724. val->setRValue();
  5725. return val;
  5726. };
  5727. return processEachVectorInMatrix(lhs, lhsVal, actOnEachVec,
  5728. lhs->getLocStart());
  5729. }
  5730. case BO_Assign:
  5731. llvm_unreachable("assignment should not be handled here");
  5732. default:
  5733. break;
  5734. }
  5735. emitError("binary operator '%0' over matrix type unimplemented",
  5736. lhs->getExprLoc())
  5737. << BinaryOperator::getOpcodeStr(opcode) << range;
  5738. return nullptr;
  5739. }
  5740. const Expr *SpirvEmitter::collectArrayStructIndices(
  5741. const Expr *expr, bool rawIndex,
  5742. llvm::SmallVectorImpl<uint32_t> *rawIndices,
  5743. llvm::SmallVectorImpl<SpirvInstruction *> *indices,
  5744. bool *isMSOutAttribute) {
  5745. assert((rawIndex && rawIndices) || (!rawIndex && indices));
  5746. if (const auto *indexing = dyn_cast<MemberExpr>(expr)) {
  5747. // First check whether this is referring to a static member. If it is, we
  5748. // create a DeclRefExpr for it.
  5749. if (auto *varDecl = dyn_cast<VarDecl>(indexing->getMemberDecl()))
  5750. if (varDecl->isStaticDataMember())
  5751. return DeclRefExpr::Create(
  5752. astContext, NestedNameSpecifierLoc(), SourceLocation(), varDecl,
  5753. /*RefersToEnclosingVariableOrCapture=*/false, SourceLocation(),
  5754. varDecl->getType(), VK_LValue);
  5755. const Expr *base = collectArrayStructIndices(
  5756. indexing->getBase()->IgnoreParenNoopCasts(astContext), rawIndex,
  5757. rawIndices, indices, isMSOutAttribute);
  5758. if (isMSOutAttribute && base) {
  5759. if (const auto *arg = dyn_cast<DeclRefExpr>(base)) {
  5760. if (const auto *varDecl = dyn_cast<VarDecl>(arg->getDecl())) {
  5761. if (varDecl->hasAttr<HLSLVerticesAttr>() ||
  5762. varDecl->hasAttr<HLSLPrimitivesAttr>()) {
  5763. assert(spvContext.isMS());
  5764. *isMSOutAttribute = true;
  5765. return expr;
  5766. }
  5767. }
  5768. }
  5769. }
  5770. // Append the index of the current level
  5771. const auto *fieldDecl = cast<FieldDecl>(indexing->getMemberDecl());
  5772. assert(fieldDecl);
  5773. // If we are accessing a derived struct, we need to account for the number
  5774. // of base structs, since they are placed as fields at the beginning of the
  5775. // derived struct.
  5776. auto baseType = indexing->getBase()->getType();
  5777. if (baseType->isPointerType()) {
  5778. baseType = baseType->getPointeeType();
  5779. }
  5780. const uint32_t index =
  5781. getNumBaseClasses(baseType) + fieldDecl->getFieldIndex();
  5782. if (rawIndex) {
  5783. rawIndices->push_back(index);
  5784. } else {
  5785. indices->push_back(spvBuilder.getConstantInt(
  5786. astContext.IntTy, llvm::APInt(32, index, true)));
  5787. }
  5788. return base;
  5789. }
  5790. if (const auto *indexing = dyn_cast<ArraySubscriptExpr>(expr)) {
  5791. if (rawIndex)
  5792. return nullptr; // TODO: handle constant array index
  5793. // The base of an ArraySubscriptExpr has a wrapping LValueToRValue implicit
  5794. // cast. We need to ingore it to avoid creating OpLoad.
  5795. const Expr *thisBase = indexing->getBase()->IgnoreParenLValueCasts();
  5796. const Expr *base = collectArrayStructIndices(thisBase, rawIndex, rawIndices,
  5797. indices, isMSOutAttribute);
  5798. // The index into an array must be an integer number.
  5799. const auto *idxExpr = indexing->getIdx();
  5800. const auto idxExprType = idxExpr->getType();
  5801. SpirvInstruction *thisIndex = doExpr(idxExpr);
  5802. if (!idxExprType->isIntegerType() || idxExprType->isBooleanType()) {
  5803. thisIndex = castToInt(thisIndex, idxExprType, astContext.UnsignedIntTy,
  5804. idxExpr->getExprLoc());
  5805. }
  5806. indices->push_back(thisIndex);
  5807. return base;
  5808. }
  5809. if (const auto *indexing = dyn_cast<CXXOperatorCallExpr>(expr))
  5810. if (indexing->getOperator() == OverloadedOperatorKind::OO_Subscript) {
  5811. if (rawIndex)
  5812. return nullptr; // TODO: handle constant array index
  5813. // If this is indexing into resources, we need specific OpImage*
  5814. // instructions for accessing. Return directly to avoid further building
  5815. // up the access chain.
  5816. if (isBufferTextureIndexing(indexing))
  5817. return indexing;
  5818. const Expr *thisBase =
  5819. indexing->getArg(0)->IgnoreParenNoopCasts(astContext);
  5820. const auto thisBaseType = thisBase->getType();
  5821. const Expr *base = collectArrayStructIndices(
  5822. thisBase, rawIndex, rawIndices, indices, isMSOutAttribute);
  5823. if (thisBaseType != base->getType() &&
  5824. isAKindOfStructuredOrByteBuffer(thisBaseType)) {
  5825. // The immediate base is a kind of structured or byte buffer. It should
  5826. // be an alias variable. Break the normal index collecting chain.
  5827. // Return the immediate base as the base so that we can apply other
  5828. // hacks for legalization over it.
  5829. //
  5830. // Note: legalization specific code
  5831. indices->clear();
  5832. base = thisBase;
  5833. }
  5834. // If the base is a StructureType, we need to push an addtional index 0
  5835. // here. This is because we created an additional OpTypeRuntimeArray
  5836. // in the structure.
  5837. if (isStructuredBuffer(thisBaseType))
  5838. indices->push_back(
  5839. spvBuilder.getConstantInt(astContext.IntTy, llvm::APInt(32, 0)));
  5840. if ((hlsl::IsHLSLVecType(thisBaseType) &&
  5841. (hlsl::GetHLSLVecSize(thisBaseType) == 1)) ||
  5842. is1x1Matrix(thisBaseType) || is1xNMatrix(thisBaseType)) {
  5843. // If this is a size-1 vector or 1xN matrix, ignore the index.
  5844. } else {
  5845. indices->push_back(doExpr(indexing->getArg(1)));
  5846. }
  5847. return base;
  5848. }
  5849. {
  5850. const Expr *index = nullptr;
  5851. // TODO: the following is duplicating the logic in doCXXMemberCallExpr.
  5852. if (const auto *object = isStructuredBufferLoad(expr, &index)) {
  5853. if (rawIndex)
  5854. return nullptr; // TODO: handle constant array index
  5855. // For object.Load(index), there should be no more indexing into the
  5856. // object.
  5857. indices->push_back(
  5858. spvBuilder.getConstantInt(astContext.IntTy, llvm::APInt(32, 0)));
  5859. indices->push_back(doExpr(index));
  5860. return object;
  5861. }
  5862. }
  5863. // This the deepest we can go. No more array or struct indexing.
  5864. return expr;
  5865. }
  5866. SpirvInstruction *SpirvEmitter::turnIntoElementPtr(
  5867. QualType baseType, SpirvInstruction *base, QualType elemType,
  5868. const llvm::SmallVector<SpirvInstruction *, 4> &indices,
  5869. SourceLocation loc) {
  5870. // If this is a rvalue, we need a temporary object to hold it
  5871. // so that we can get access chain from it.
  5872. const bool needTempVar = base->isRValue();
  5873. SpirvInstruction *accessChainBase = base;
  5874. if (needTempVar) {
  5875. auto varName = getAstTypeName(baseType);
  5876. const auto var = createTemporaryVar(baseType, varName, base, loc);
  5877. var->setLayoutRule(SpirvLayoutRule::Void);
  5878. var->setStorageClass(spv::StorageClass::Function);
  5879. var->setContainsAliasComponent(base->containsAliasComponent());
  5880. accessChainBase = var;
  5881. }
  5882. base = spvBuilder.createAccessChain(elemType, accessChainBase, indices, loc);
  5883. // Okay, this part seems weird, but it is intended:
  5884. // If the base is originally a rvalue, the whole AST involving the base
  5885. // is consistently set up to handle rvalues. By copying the base into
  5886. // a temporary variable and grab an access chain from it, we are breaking
  5887. // the consistency by turning the base from rvalue into lvalue. Keep in
  5888. // mind that there will be no LValueToRValue casts in the AST for us
  5889. // to rely on to load the access chain if a rvalue is expected. Therefore,
  5890. // we must do the load here. Otherwise, it's up to the consumer of this
  5891. // access chain to do the load, and that can be everywhere.
  5892. if (needTempVar) {
  5893. base = spvBuilder.createLoad(elemType, base, loc);
  5894. }
  5895. return base;
  5896. }
  5897. SpirvInstruction *SpirvEmitter::castToBool(SpirvInstruction *fromVal,
  5898. QualType fromType,
  5899. QualType toBoolType,
  5900. SourceLocation loc) {
  5901. if (isSameType(astContext, fromType, toBoolType))
  5902. return fromVal;
  5903. { // Special case handling for converting to a matrix of booleans.
  5904. QualType elemType = {};
  5905. uint32_t rowCount = 0, colCount = 0;
  5906. if (isMxNMatrix(fromType, &elemType, &rowCount, &colCount)) {
  5907. const auto fromRowQualType =
  5908. astContext.getExtVectorType(elemType, colCount);
  5909. const auto toBoolRowQualType =
  5910. astContext.getExtVectorType(astContext.BoolTy, colCount);
  5911. llvm::SmallVector<SpirvInstruction *, 4> rows;
  5912. for (uint32_t i = 0; i < rowCount; ++i) {
  5913. auto *row = spvBuilder.createCompositeExtract(fromRowQualType, fromVal,
  5914. {i}, loc);
  5915. rows.push_back(
  5916. castToBool(row, fromRowQualType, toBoolRowQualType, loc));
  5917. }
  5918. return spvBuilder.createCompositeConstruct(toBoolType, rows, loc);
  5919. }
  5920. }
  5921. // Converting to bool means comparing with value zero.
  5922. const spv::Op spvOp = translateOp(BO_NE, fromType);
  5923. auto *zeroVal = getValueZero(fromType);
  5924. return spvBuilder.createBinaryOp(spvOp, toBoolType, fromVal, zeroVal, loc);
  5925. }
  5926. SpirvInstruction *SpirvEmitter::castToInt(SpirvInstruction *fromVal,
  5927. QualType fromType, QualType toIntType,
  5928. SourceLocation srcLoc) {
  5929. if (isEnumType(fromType))
  5930. fromType = astContext.IntTy;
  5931. if (isSameType(astContext, fromType, toIntType))
  5932. return fromVal;
  5933. if (isBoolOrVecOfBoolType(fromType)) {
  5934. auto *one = getValueOne(toIntType);
  5935. auto *zero = getValueZero(toIntType);
  5936. return spvBuilder.createSelect(toIntType, fromVal, one, zero, srcLoc);
  5937. }
  5938. if (isSintOrVecOfSintType(fromType) || isUintOrVecOfUintType(fromType)) {
  5939. // First convert the source to the bitwidth of the destination if necessary.
  5940. QualType convertedType = {};
  5941. fromVal =
  5942. convertBitwidth(fromVal, srcLoc, fromType, toIntType, &convertedType);
  5943. // If bitwidth conversion was the only thing we needed to do, we're done.
  5944. if (isSameScalarOrVecType(convertedType, toIntType))
  5945. return fromVal;
  5946. return spvBuilder.createUnaryOp(spv::Op::OpBitcast, toIntType, fromVal,
  5947. srcLoc);
  5948. }
  5949. if (isFloatOrVecOfFloatType(fromType)) {
  5950. // First convert the source to the bitwidth of the destination if necessary.
  5951. fromVal = convertBitwidth(fromVal, srcLoc, fromType, toIntType);
  5952. if (isSintOrVecOfSintType(toIntType)) {
  5953. return spvBuilder.createUnaryOp(spv::Op::OpConvertFToS, toIntType,
  5954. fromVal, srcLoc);
  5955. } else if (isUintOrVecOfUintType(toIntType)) {
  5956. return spvBuilder.createUnaryOp(spv::Op::OpConvertFToU, toIntType,
  5957. fromVal, srcLoc);
  5958. } else {
  5959. emitError("casting from floating point to integer unimplemented", srcLoc);
  5960. }
  5961. }
  5962. {
  5963. QualType elemType = {};
  5964. uint32_t numRows = 0, numCols = 0;
  5965. if (isMxNMatrix(fromType, &elemType, &numRows, &numCols)) {
  5966. // The source matrix and the target matrix must have the same dimensions.
  5967. QualType toElemType = {};
  5968. uint32_t toNumRows = 0, toNumCols = 0;
  5969. const bool isMat =
  5970. isMxNMatrix(toIntType, &toElemType, &toNumRows, &toNumCols);
  5971. assert(isMat && numRows == toNumRows && numCols == toNumCols);
  5972. (void)isMat;
  5973. (void)toNumRows;
  5974. (void)toNumCols;
  5975. // Casting to a matrix of integers: Cast each row and construct a
  5976. // composite.
  5977. llvm::SmallVector<SpirvInstruction *, 4> castedRows;
  5978. const QualType vecType = getComponentVectorType(astContext, fromType);
  5979. const auto fromVecQualType =
  5980. astContext.getExtVectorType(elemType, numCols);
  5981. const auto toIntVecQualType =
  5982. astContext.getExtVectorType(toElemType, numCols);
  5983. for (uint32_t row = 0; row < numRows; ++row) {
  5984. auto *rowId =
  5985. spvBuilder.createCompositeExtract(vecType, fromVal, {row}, srcLoc);
  5986. castedRows.push_back(
  5987. castToInt(rowId, fromVecQualType, toIntVecQualType, srcLoc));
  5988. }
  5989. return spvBuilder.createCompositeConstruct(toIntType, castedRows, srcLoc);
  5990. }
  5991. }
  5992. return nullptr;
  5993. }
  5994. SpirvInstruction *SpirvEmitter::convertBitwidth(SpirvInstruction *fromVal,
  5995. SourceLocation loc,
  5996. QualType fromType,
  5997. QualType toType,
  5998. QualType *resultType) {
  5999. // At the moment, we will not make bitwidth conversions to/from literal int
  6000. // and literal float types because they do not represent the intended SPIR-V
  6001. // bitwidth.
  6002. if (isLitTypeOrVecOfLitType(fromType) || isLitTypeOrVecOfLitType(toType))
  6003. return fromVal;
  6004. const auto fromBitwidth = getElementSpirvBitwidth(
  6005. astContext, fromType, spirvOptions.enable16BitTypes);
  6006. const auto toBitwidth = getElementSpirvBitwidth(
  6007. astContext, toType, spirvOptions.enable16BitTypes);
  6008. if (fromBitwidth == toBitwidth) {
  6009. if (resultType)
  6010. *resultType = fromType;
  6011. return fromVal;
  6012. }
  6013. // We want the 'fromType' with the 'toBitwidth'.
  6014. const QualType targetType =
  6015. getTypeWithCustomBitwidth(astContext, fromType, toBitwidth);
  6016. if (resultType)
  6017. *resultType = targetType;
  6018. if (isFloatOrVecOfFloatType(fromType))
  6019. return spvBuilder.createUnaryOp(spv::Op::OpFConvert, targetType, fromVal,
  6020. loc);
  6021. if (isSintOrVecOfSintType(fromType))
  6022. return spvBuilder.createUnaryOp(spv::Op::OpSConvert, targetType, fromVal,
  6023. loc);
  6024. if (isUintOrVecOfUintType(fromType))
  6025. return spvBuilder.createUnaryOp(spv::Op::OpUConvert, targetType, fromVal,
  6026. loc);
  6027. llvm_unreachable("invalid type passed to convertBitwidth");
  6028. }
  6029. SpirvInstruction *SpirvEmitter::castToFloat(SpirvInstruction *fromVal,
  6030. QualType fromType,
  6031. QualType toFloatType,
  6032. SourceLocation srcLoc) {
  6033. if (isSameType(astContext, fromType, toFloatType))
  6034. return fromVal;
  6035. if (isBoolOrVecOfBoolType(fromType)) {
  6036. auto *one = getValueOne(toFloatType);
  6037. auto *zero = getValueZero(toFloatType);
  6038. return spvBuilder.createSelect(toFloatType, fromVal, one, zero, srcLoc);
  6039. }
  6040. if (isSintOrVecOfSintType(fromType)) {
  6041. // First convert the source to the bitwidth of the destination if necessary.
  6042. fromVal = convertBitwidth(fromVal, srcLoc, fromType, toFloatType);
  6043. return spvBuilder.createUnaryOp(spv::Op::OpConvertSToF, toFloatType,
  6044. fromVal, srcLoc);
  6045. }
  6046. if (isUintOrVecOfUintType(fromType)) {
  6047. // First convert the source to the bitwidth of the destination if necessary.
  6048. fromVal = convertBitwidth(fromVal, srcLoc, fromType, toFloatType);
  6049. return spvBuilder.createUnaryOp(spv::Op::OpConvertUToF, toFloatType,
  6050. fromVal, srcLoc);
  6051. }
  6052. if (isFloatOrVecOfFloatType(fromType)) {
  6053. // This is the case of float to float conversion with different bitwidths.
  6054. return convertBitwidth(fromVal, srcLoc, fromType, toFloatType);
  6055. }
  6056. // Casting matrix types
  6057. {
  6058. QualType elemType = {};
  6059. uint32_t numRows = 0, numCols = 0;
  6060. if (isMxNMatrix(fromType, &elemType, &numRows, &numCols)) {
  6061. // The source matrix and the target matrix must have the same dimensions.
  6062. QualType toElemType = {};
  6063. uint32_t toNumRows = 0, toNumCols = 0;
  6064. const auto isMat =
  6065. isMxNMatrix(toFloatType, &toElemType, &toNumRows, &toNumCols);
  6066. assert(isMat && numRows == toNumRows && numCols == toNumCols);
  6067. (void)isMat;
  6068. (void)toNumRows;
  6069. (void)toNumCols;
  6070. // Casting to a matrix of floats: Cast each row and construct a
  6071. // composite.
  6072. llvm::SmallVector<SpirvInstruction *, 4> castedRows;
  6073. const QualType vecType = getComponentVectorType(astContext, fromType);
  6074. const auto fromVecQualType =
  6075. astContext.getExtVectorType(elemType, numCols);
  6076. const auto toIntVecQualType =
  6077. astContext.getExtVectorType(toElemType, numCols);
  6078. for (uint32_t row = 0; row < numRows; ++row) {
  6079. auto *rowId =
  6080. spvBuilder.createCompositeExtract(vecType, fromVal, {row}, srcLoc);
  6081. castedRows.push_back(
  6082. castToFloat(rowId, fromVecQualType, toIntVecQualType, srcLoc));
  6083. }
  6084. return spvBuilder.createCompositeConstruct(toFloatType, castedRows,
  6085. srcLoc);
  6086. }
  6087. }
  6088. emitError("casting to floating point unimplemented", srcLoc);
  6089. return nullptr;
  6090. }
  6091. SpirvInstruction *
  6092. SpirvEmitter::processIntrinsicCallExpr(const CallExpr *callExpr) {
  6093. const FunctionDecl *callee = callExpr->getDirectCallee();
  6094. const SourceLocation srcLoc = callExpr->getExprLoc();
  6095. assert(hlsl::IsIntrinsicOp(callee) &&
  6096. "doIntrinsicCallExpr was called for a non-intrinsic function.");
  6097. const bool isFloatType = isFloatOrVecMatOfFloatType(callExpr->getType());
  6098. const bool isSintType = isSintOrVecMatOfSintType(callExpr->getType());
  6099. // Figure out which intrinsic function to translate.
  6100. llvm::StringRef group;
  6101. uint32_t opcode = static_cast<uint32_t>(hlsl::IntrinsicOp::Num_Intrinsics);
  6102. hlsl::GetIntrinsicOp(callee, opcode, group);
  6103. GLSLstd450 glslOpcode = GLSLstd450Bad;
  6104. SpirvInstruction *retVal = nullptr;
  6105. #define INTRINSIC_SPIRV_OP_CASE(intrinsicOp, spirvOp, doEachVec) \
  6106. case hlsl::IntrinsicOp::IOP_##intrinsicOp: { \
  6107. retVal = processIntrinsicUsingSpirvInst(callExpr, spv::Op::Op##spirvOp, \
  6108. doEachVec); \
  6109. } break
  6110. #define INTRINSIC_OP_CASE(intrinsicOp, glslOp, doEachVec) \
  6111. case hlsl::IntrinsicOp::IOP_##intrinsicOp: { \
  6112. glslOpcode = GLSLstd450::GLSLstd450##glslOp; \
  6113. retVal = processIntrinsicUsingGLSLInst(callExpr, glslOpcode, doEachVec, \
  6114. srcLoc); \
  6115. } break
  6116. #define INTRINSIC_OP_CASE_INT_FLOAT(intrinsicOp, glslIntOp, glslFloatOp, \
  6117. doEachVec) \
  6118. case hlsl::IntrinsicOp::IOP_##intrinsicOp: { \
  6119. glslOpcode = isFloatType ? GLSLstd450::GLSLstd450##glslFloatOp \
  6120. : GLSLstd450::GLSLstd450##glslIntOp; \
  6121. retVal = processIntrinsicUsingGLSLInst(callExpr, glslOpcode, doEachVec, \
  6122. srcLoc); \
  6123. } break
  6124. #define INTRINSIC_OP_CASE_SINT_UINT(intrinsicOp, glslSintOp, glslUintOp, \
  6125. doEachVec) \
  6126. case hlsl::IntrinsicOp::IOP_##intrinsicOp: { \
  6127. glslOpcode = isSintType ? GLSLstd450::GLSLstd450##glslSintOp \
  6128. : GLSLstd450::GLSLstd450##glslUintOp; \
  6129. retVal = processIntrinsicUsingGLSLInst(callExpr, glslOpcode, doEachVec, \
  6130. srcLoc); \
  6131. } break
  6132. #define INTRINSIC_OP_CASE_SINT_UINT_FLOAT(intrinsicOp, glslSintOp, glslUintOp, \
  6133. glslFloatOp, doEachVec) \
  6134. case hlsl::IntrinsicOp::IOP_##intrinsicOp: { \
  6135. glslOpcode = isFloatType \
  6136. ? GLSLstd450::GLSLstd450##glslFloatOp \
  6137. : isSintType ? GLSLstd450::GLSLstd450##glslSintOp \
  6138. : GLSLstd450::GLSLstd450##glslUintOp; \
  6139. retVal = processIntrinsicUsingGLSLInst(callExpr, glslOpcode, doEachVec, \
  6140. srcLoc); \
  6141. } break
  6142. switch (const auto hlslOpcode = static_cast<hlsl::IntrinsicOp>(opcode)) {
  6143. case hlsl::IntrinsicOp::IOP_InterlockedAdd:
  6144. case hlsl::IntrinsicOp::IOP_InterlockedAnd:
  6145. case hlsl::IntrinsicOp::IOP_InterlockedMax:
  6146. case hlsl::IntrinsicOp::IOP_InterlockedUMax:
  6147. case hlsl::IntrinsicOp::IOP_InterlockedMin:
  6148. case hlsl::IntrinsicOp::IOP_InterlockedUMin:
  6149. case hlsl::IntrinsicOp::IOP_InterlockedOr:
  6150. case hlsl::IntrinsicOp::IOP_InterlockedXor:
  6151. case hlsl::IntrinsicOp::IOP_InterlockedExchange:
  6152. case hlsl::IntrinsicOp::IOP_InterlockedCompareStore:
  6153. case hlsl::IntrinsicOp::IOP_InterlockedCompareExchange:
  6154. retVal = processIntrinsicInterlockedMethod(callExpr, hlslOpcode);
  6155. break;
  6156. case hlsl::IntrinsicOp::IOP_NonUniformResourceIndex:
  6157. retVal = processIntrinsicNonUniformResourceIndex(callExpr);
  6158. break;
  6159. case hlsl::IntrinsicOp::IOP_tex1D:
  6160. case hlsl::IntrinsicOp::IOP_tex1Dbias:
  6161. case hlsl::IntrinsicOp::IOP_tex1Dgrad:
  6162. case hlsl::IntrinsicOp::IOP_tex1Dlod:
  6163. case hlsl::IntrinsicOp::IOP_tex1Dproj:
  6164. case hlsl::IntrinsicOp::IOP_tex2D:
  6165. case hlsl::IntrinsicOp::IOP_tex2Dbias:
  6166. case hlsl::IntrinsicOp::IOP_tex2Dgrad:
  6167. case hlsl::IntrinsicOp::IOP_tex2Dlod:
  6168. case hlsl::IntrinsicOp::IOP_tex2Dproj:
  6169. case hlsl::IntrinsicOp::IOP_tex3D:
  6170. case hlsl::IntrinsicOp::IOP_tex3Dbias:
  6171. case hlsl::IntrinsicOp::IOP_tex3Dgrad:
  6172. case hlsl::IntrinsicOp::IOP_tex3Dlod:
  6173. case hlsl::IntrinsicOp::IOP_tex3Dproj:
  6174. case hlsl::IntrinsicOp::IOP_texCUBE:
  6175. case hlsl::IntrinsicOp::IOP_texCUBEbias:
  6176. case hlsl::IntrinsicOp::IOP_texCUBEgrad:
  6177. case hlsl::IntrinsicOp::IOP_texCUBElod:
  6178. case hlsl::IntrinsicOp::IOP_texCUBEproj: {
  6179. emitError("deprecated %0 intrinsic function will not be supported", srcLoc)
  6180. << callee->getName();
  6181. return nullptr;
  6182. }
  6183. case hlsl::IntrinsicOp::IOP_dot:
  6184. retVal = processIntrinsicDot(callExpr);
  6185. break;
  6186. case hlsl::IntrinsicOp::IOP_GroupMemoryBarrier:
  6187. retVal = processIntrinsicMemoryBarrier(callExpr,
  6188. /*isDevice*/ false,
  6189. /*groupSync*/ false,
  6190. /*isAllBarrier*/ false);
  6191. break;
  6192. case hlsl::IntrinsicOp::IOP_GroupMemoryBarrierWithGroupSync:
  6193. retVal = processIntrinsicMemoryBarrier(callExpr,
  6194. /*isDevice*/ false,
  6195. /*groupSync*/ true,
  6196. /*isAllBarrier*/ false);
  6197. break;
  6198. case hlsl::IntrinsicOp::IOP_DeviceMemoryBarrier:
  6199. retVal = processIntrinsicMemoryBarrier(callExpr, /*isDevice*/ true,
  6200. /*groupSync*/ false,
  6201. /*isAllBarrier*/ false);
  6202. break;
  6203. case hlsl::IntrinsicOp::IOP_DeviceMemoryBarrierWithGroupSync:
  6204. retVal = processIntrinsicMemoryBarrier(callExpr, /*isDevice*/ true,
  6205. /*groupSync*/ true,
  6206. /*isAllBarrier*/ false);
  6207. break;
  6208. case hlsl::IntrinsicOp::IOP_AllMemoryBarrier:
  6209. retVal = processIntrinsicMemoryBarrier(callExpr, /*isDevice*/ true,
  6210. /*groupSync*/ false,
  6211. /*isAllBarrier*/ true);
  6212. break;
  6213. case hlsl::IntrinsicOp::IOP_AllMemoryBarrierWithGroupSync:
  6214. retVal = processIntrinsicMemoryBarrier(callExpr, /*isDevice*/ true,
  6215. /*groupSync*/ true,
  6216. /*isAllBarrier*/ true);
  6217. break;
  6218. case hlsl::IntrinsicOp::IOP_CheckAccessFullyMapped:
  6219. retVal = spvBuilder.createImageSparseTexelsResident(
  6220. doExpr(callExpr->getArg(0)), srcLoc);
  6221. break;
  6222. case hlsl::IntrinsicOp::IOP_mul:
  6223. case hlsl::IntrinsicOp::IOP_umul:
  6224. retVal = processIntrinsicMul(callExpr);
  6225. break;
  6226. case hlsl::IntrinsicOp::IOP_all:
  6227. retVal = processIntrinsicAllOrAny(callExpr, spv::Op::OpAll);
  6228. break;
  6229. case hlsl::IntrinsicOp::IOP_any:
  6230. retVal = processIntrinsicAllOrAny(callExpr, spv::Op::OpAny);
  6231. break;
  6232. case hlsl::IntrinsicOp::IOP_asdouble:
  6233. case hlsl::IntrinsicOp::IOP_asfloat:
  6234. case hlsl::IntrinsicOp::IOP_asint:
  6235. case hlsl::IntrinsicOp::IOP_asuint:
  6236. retVal = processIntrinsicAsType(callExpr);
  6237. break;
  6238. case hlsl::IntrinsicOp::IOP_clip:
  6239. retVal = processIntrinsicClip(callExpr);
  6240. break;
  6241. case hlsl::IntrinsicOp::IOP_dst:
  6242. retVal = processIntrinsicDst(callExpr);
  6243. break;
  6244. case hlsl::IntrinsicOp::IOP_clamp:
  6245. case hlsl::IntrinsicOp::IOP_uclamp:
  6246. retVal = processIntrinsicClamp(callExpr);
  6247. break;
  6248. case hlsl::IntrinsicOp::IOP_frexp:
  6249. retVal = processIntrinsicFrexp(callExpr);
  6250. break;
  6251. case hlsl::IntrinsicOp::IOP_ldexp:
  6252. retVal = processIntrinsicLdexp(callExpr);
  6253. break;
  6254. case hlsl::IntrinsicOp::IOP_lit:
  6255. retVal = processIntrinsicLit(callExpr);
  6256. break;
  6257. case hlsl::IntrinsicOp::IOP_mad:
  6258. case hlsl::IntrinsicOp::IOP_umad:
  6259. retVal = processIntrinsicMad(callExpr);
  6260. break;
  6261. case hlsl::IntrinsicOp::IOP_modf:
  6262. retVal = processIntrinsicModf(callExpr);
  6263. break;
  6264. case hlsl::IntrinsicOp::IOP_msad4:
  6265. retVal = processIntrinsicMsad4(callExpr);
  6266. break;
  6267. case hlsl::IntrinsicOp::IOP_printf:
  6268. retVal = processIntrinsicPrintf(callExpr);
  6269. break;
  6270. case hlsl::IntrinsicOp::IOP_sign: {
  6271. if (isFloatOrVecMatOfFloatType(callExpr->getArg(0)->getType()))
  6272. retVal = processIntrinsicFloatSign(callExpr);
  6273. else
  6274. retVal =
  6275. processIntrinsicUsingGLSLInst(callExpr, GLSLstd450::GLSLstd450SSign,
  6276. /*actPerRowForMatrices*/ true, srcLoc);
  6277. } break;
  6278. case hlsl::IntrinsicOp::IOP_D3DCOLORtoUBYTE4:
  6279. retVal = processD3DCOLORtoUBYTE4(callExpr);
  6280. break;
  6281. case hlsl::IntrinsicOp::IOP_isfinite:
  6282. retVal = processIntrinsicIsFinite(callExpr);
  6283. break;
  6284. case hlsl::IntrinsicOp::IOP_sincos:
  6285. retVal = processIntrinsicSinCos(callExpr);
  6286. break;
  6287. case hlsl::IntrinsicOp::IOP_rcp:
  6288. retVal = processIntrinsicRcp(callExpr);
  6289. break;
  6290. case hlsl::IntrinsicOp::IOP_saturate:
  6291. retVal = processIntrinsicSaturate(callExpr);
  6292. break;
  6293. case hlsl::IntrinsicOp::IOP_log10:
  6294. retVal = processIntrinsicLog10(callExpr);
  6295. break;
  6296. case hlsl::IntrinsicOp::IOP_f16tof32:
  6297. retVal = processIntrinsicF16ToF32(callExpr);
  6298. break;
  6299. case hlsl::IntrinsicOp::IOP_f32tof16:
  6300. retVal = processIntrinsicF32ToF16(callExpr);
  6301. break;
  6302. case hlsl::IntrinsicOp::IOP_WaveGetLaneCount: {
  6303. featureManager.requestTargetEnv(SPV_ENV_VULKAN_1_1, "WaveGetLaneCount",
  6304. srcLoc);
  6305. const QualType retType = callExpr->getCallReturnType(astContext);
  6306. auto *var =
  6307. declIdMapper.getBuiltinVar(spv::BuiltIn::SubgroupSize, retType, srcLoc);
  6308. retVal = spvBuilder.createLoad(retType, var, srcLoc);
  6309. } break;
  6310. case hlsl::IntrinsicOp::IOP_WaveGetLaneIndex: {
  6311. featureManager.requestTargetEnv(SPV_ENV_VULKAN_1_1, "WaveGetLaneIndex",
  6312. srcLoc);
  6313. const QualType retType = callExpr->getCallReturnType(astContext);
  6314. auto *var = declIdMapper.getBuiltinVar(
  6315. spv::BuiltIn::SubgroupLocalInvocationId, retType, srcLoc);
  6316. retVal = spvBuilder.createLoad(retType, var, srcLoc);
  6317. } break;
  6318. case hlsl::IntrinsicOp::IOP_WaveIsFirstLane:
  6319. retVal = processWaveQuery(callExpr, spv::Op::OpGroupNonUniformElect);
  6320. break;
  6321. case hlsl::IntrinsicOp::IOP_WaveActiveAllTrue:
  6322. retVal = processWaveVote(callExpr, spv::Op::OpGroupNonUniformAll);
  6323. break;
  6324. case hlsl::IntrinsicOp::IOP_WaveActiveAnyTrue:
  6325. retVal = processWaveVote(callExpr, spv::Op::OpGroupNonUniformAny);
  6326. break;
  6327. case hlsl::IntrinsicOp::IOP_WaveActiveBallot:
  6328. retVal = processWaveVote(callExpr, spv::Op::OpGroupNonUniformBallot);
  6329. break;
  6330. case hlsl::IntrinsicOp::IOP_WaveActiveAllEqual:
  6331. retVal = processWaveVote(callExpr, spv::Op::OpGroupNonUniformAllEqual);
  6332. break;
  6333. case hlsl::IntrinsicOp::IOP_WaveActiveCountBits:
  6334. retVal = processWaveCountBits(callExpr, spv::GroupOperation::Reduce);
  6335. break;
  6336. case hlsl::IntrinsicOp::IOP_WaveActiveUSum:
  6337. case hlsl::IntrinsicOp::IOP_WaveActiveSum:
  6338. case hlsl::IntrinsicOp::IOP_WaveActiveUProduct:
  6339. case hlsl::IntrinsicOp::IOP_WaveActiveProduct:
  6340. case hlsl::IntrinsicOp::IOP_WaveActiveUMax:
  6341. case hlsl::IntrinsicOp::IOP_WaveActiveMax:
  6342. case hlsl::IntrinsicOp::IOP_WaveActiveUMin:
  6343. case hlsl::IntrinsicOp::IOP_WaveActiveMin:
  6344. case hlsl::IntrinsicOp::IOP_WaveActiveBitAnd:
  6345. case hlsl::IntrinsicOp::IOP_WaveActiveBitOr:
  6346. case hlsl::IntrinsicOp::IOP_WaveActiveBitXor: {
  6347. const auto retType = callExpr->getCallReturnType(astContext);
  6348. retVal = processWaveReductionOrPrefix(
  6349. callExpr, translateWaveOp(hlslOpcode, retType, srcLoc),
  6350. spv::GroupOperation::Reduce);
  6351. } break;
  6352. case hlsl::IntrinsicOp::IOP_WavePrefixUSum:
  6353. case hlsl::IntrinsicOp::IOP_WavePrefixSum:
  6354. case hlsl::IntrinsicOp::IOP_WavePrefixUProduct:
  6355. case hlsl::IntrinsicOp::IOP_WavePrefixProduct: {
  6356. const auto retType = callExpr->getCallReturnType(astContext);
  6357. retVal = processWaveReductionOrPrefix(
  6358. callExpr, translateWaveOp(hlslOpcode, retType, srcLoc),
  6359. spv::GroupOperation::ExclusiveScan);
  6360. } break;
  6361. case hlsl::IntrinsicOp::IOP_WavePrefixCountBits:
  6362. retVal = processWaveCountBits(callExpr, spv::GroupOperation::ExclusiveScan);
  6363. break;
  6364. case hlsl::IntrinsicOp::IOP_WaveReadLaneAt:
  6365. case hlsl::IntrinsicOp::IOP_WaveReadLaneFirst:
  6366. retVal = processWaveBroadcast(callExpr);
  6367. break;
  6368. case hlsl::IntrinsicOp::IOP_QuadReadAcrossX:
  6369. case hlsl::IntrinsicOp::IOP_QuadReadAcrossY:
  6370. case hlsl::IntrinsicOp::IOP_QuadReadAcrossDiagonal:
  6371. case hlsl::IntrinsicOp::IOP_QuadReadLaneAt:
  6372. retVal = processWaveQuadWideShuffle(callExpr, hlslOpcode);
  6373. break;
  6374. case hlsl::IntrinsicOp::IOP_abort:
  6375. case hlsl::IntrinsicOp::IOP_GetRenderTargetSampleCount:
  6376. case hlsl::IntrinsicOp::IOP_GetRenderTargetSamplePosition: {
  6377. emitError("no equivalent for %0 intrinsic function in Vulkan", srcLoc)
  6378. << callee->getName();
  6379. return 0;
  6380. }
  6381. case hlsl::IntrinsicOp::IOP_transpose: {
  6382. const Expr *mat = callExpr->getArg(0);
  6383. const QualType matType = mat->getType();
  6384. if (hlsl::GetHLSLMatElementType(matType)->isFloatingType())
  6385. retVal =
  6386. processIntrinsicUsingSpirvInst(callExpr, spv::Op::OpTranspose, false);
  6387. else
  6388. retVal = processNonFpMatrixTranspose(matType, doExpr(mat), srcLoc);
  6389. break;
  6390. }
  6391. // DXR raytracing intrinsics
  6392. case hlsl::IntrinsicOp::IOP_DispatchRaysDimensions:
  6393. case hlsl::IntrinsicOp::IOP_DispatchRaysIndex:
  6394. case hlsl::IntrinsicOp::IOP_GeometryIndex:
  6395. case hlsl::IntrinsicOp::IOP_HitKind:
  6396. case hlsl::IntrinsicOp::IOP_InstanceIndex:
  6397. case hlsl::IntrinsicOp::IOP_InstanceID:
  6398. case hlsl::IntrinsicOp::IOP_ObjectRayDirection:
  6399. case hlsl::IntrinsicOp::IOP_ObjectRayOrigin:
  6400. case hlsl::IntrinsicOp::IOP_ObjectToWorld3x4:
  6401. case hlsl::IntrinsicOp::IOP_ObjectToWorld4x3:
  6402. case hlsl::IntrinsicOp::IOP_PrimitiveIndex:
  6403. case hlsl::IntrinsicOp::IOP_RayFlags:
  6404. case hlsl::IntrinsicOp::IOP_RayTCurrent:
  6405. case hlsl::IntrinsicOp::IOP_RayTMin:
  6406. case hlsl::IntrinsicOp::IOP_WorldRayDirection:
  6407. case hlsl::IntrinsicOp::IOP_WorldRayOrigin:
  6408. case hlsl::IntrinsicOp::IOP_WorldToObject3x4:
  6409. case hlsl::IntrinsicOp::IOP_WorldToObject4x3: {
  6410. retVal = processRayBuiltins(callExpr, hlslOpcode);
  6411. break;
  6412. }
  6413. case hlsl::IntrinsicOp::IOP_AcceptHitAndEndSearch:
  6414. case hlsl::IntrinsicOp::IOP_IgnoreHit: {
  6415. // Any modifications made to the ray payload in an any hit shader are
  6416. // preserved before calling AcceptHit/IgnoreHit. Write out the results to
  6417. // the payload which is visible only in entry functions
  6418. const auto iter = functionInfoMap.find(curFunction);
  6419. if (iter != functionInfoMap.end()) {
  6420. const auto &entryInfo = iter->second;
  6421. if (entryInfo->isEntryFunction) {
  6422. const auto payloadArg = curFunction->getParamDecl(0);
  6423. const auto payloadArgInst =
  6424. declIdMapper.getDeclEvalInfo(payloadArg, payloadArg->getLocStart());
  6425. auto tempLoad = spvBuilder.createLoad(
  6426. payloadArg->getType(), payloadArgInst, payloadArg->getLocStart());
  6427. spvBuilder.createStore(currentRayPayload, tempLoad,
  6428. callExpr->getExprLoc());
  6429. }
  6430. }
  6431. spvBuilder.createRayTracingOpsNV(
  6432. hlslOpcode == hlsl::IntrinsicOp ::IOP_AcceptHitAndEndSearch
  6433. ? spv::Op::OpTerminateRayNV
  6434. : spv::Op::OpIgnoreIntersectionNV,
  6435. QualType(), {}, srcLoc);
  6436. break;
  6437. }
  6438. case hlsl::IntrinsicOp::IOP_ReportHit: {
  6439. retVal = processReportHit(callExpr);
  6440. break;
  6441. }
  6442. case hlsl::IntrinsicOp::IOP_TraceRay: {
  6443. processTraceRay(callExpr);
  6444. break;
  6445. }
  6446. case hlsl::IntrinsicOp::IOP_CallShader: {
  6447. processCallShader(callExpr);
  6448. break;
  6449. }
  6450. case hlsl::IntrinsicOp::IOP_DispatchMesh: {
  6451. processDispatchMesh(callExpr);
  6452. break;
  6453. }
  6454. case hlsl::IntrinsicOp::IOP_SetMeshOutputCounts: {
  6455. processMeshOutputCounts(callExpr);
  6456. break;
  6457. }
  6458. INTRINSIC_SPIRV_OP_CASE(ddx, DPdx, true);
  6459. INTRINSIC_SPIRV_OP_CASE(ddx_coarse, DPdxCoarse, false);
  6460. INTRINSIC_SPIRV_OP_CASE(ddx_fine, DPdxFine, false);
  6461. INTRINSIC_SPIRV_OP_CASE(ddy, DPdy, true);
  6462. INTRINSIC_SPIRV_OP_CASE(ddy_coarse, DPdyCoarse, false);
  6463. INTRINSIC_SPIRV_OP_CASE(ddy_fine, DPdyFine, false);
  6464. INTRINSIC_SPIRV_OP_CASE(countbits, BitCount, false);
  6465. INTRINSIC_SPIRV_OP_CASE(isinf, IsInf, true);
  6466. INTRINSIC_SPIRV_OP_CASE(isnan, IsNan, true);
  6467. INTRINSIC_SPIRV_OP_CASE(fmod, FMod, true);
  6468. INTRINSIC_SPIRV_OP_CASE(fwidth, Fwidth, true);
  6469. INTRINSIC_SPIRV_OP_CASE(reversebits, BitReverse, false);
  6470. INTRINSIC_OP_CASE(round, Round, true);
  6471. INTRINSIC_OP_CASE(uabs, SAbs, true);
  6472. INTRINSIC_OP_CASE_INT_FLOAT(abs, SAbs, FAbs, true);
  6473. INTRINSIC_OP_CASE(acos, Acos, true);
  6474. INTRINSIC_OP_CASE(asin, Asin, true);
  6475. INTRINSIC_OP_CASE(atan, Atan, true);
  6476. INTRINSIC_OP_CASE(atan2, Atan2, true);
  6477. INTRINSIC_OP_CASE(ceil, Ceil, true);
  6478. INTRINSIC_OP_CASE(cos, Cos, true);
  6479. INTRINSIC_OP_CASE(cosh, Cosh, true);
  6480. INTRINSIC_OP_CASE(cross, Cross, false);
  6481. INTRINSIC_OP_CASE(degrees, Degrees, true);
  6482. INTRINSIC_OP_CASE(distance, Distance, false);
  6483. INTRINSIC_OP_CASE(determinant, Determinant, false);
  6484. INTRINSIC_OP_CASE(exp, Exp, true);
  6485. INTRINSIC_OP_CASE(exp2, Exp2, true);
  6486. INTRINSIC_OP_CASE_SINT_UINT(firstbithigh, FindSMsb, FindUMsb, false);
  6487. INTRINSIC_OP_CASE_SINT_UINT(ufirstbithigh, FindSMsb, FindUMsb, false);
  6488. INTRINSIC_OP_CASE(faceforward, FaceForward, false);
  6489. INTRINSIC_OP_CASE(firstbitlow, FindILsb, false);
  6490. INTRINSIC_OP_CASE(floor, Floor, true);
  6491. INTRINSIC_OP_CASE(fma, Fma, true);
  6492. INTRINSIC_OP_CASE(frac, Fract, true);
  6493. INTRINSIC_OP_CASE(length, Length, false);
  6494. INTRINSIC_OP_CASE(lerp, FMix, true);
  6495. INTRINSIC_OP_CASE(log, Log, true);
  6496. INTRINSIC_OP_CASE(log2, Log2, true);
  6497. INTRINSIC_OP_CASE_SINT_UINT_FLOAT(max, SMax, UMax, FMax, true);
  6498. INTRINSIC_OP_CASE(umax, UMax, true);
  6499. INTRINSIC_OP_CASE_SINT_UINT_FLOAT(min, SMin, UMin, FMin, true);
  6500. INTRINSIC_OP_CASE(umin, UMin, true);
  6501. INTRINSIC_OP_CASE(normalize, Normalize, false);
  6502. INTRINSIC_OP_CASE(pow, Pow, true);
  6503. INTRINSIC_OP_CASE(radians, Radians, true);
  6504. INTRINSIC_OP_CASE(reflect, Reflect, false);
  6505. INTRINSIC_OP_CASE(refract, Refract, false);
  6506. INTRINSIC_OP_CASE(rsqrt, InverseSqrt, true);
  6507. INTRINSIC_OP_CASE(smoothstep, SmoothStep, true);
  6508. INTRINSIC_OP_CASE(step, Step, true);
  6509. INTRINSIC_OP_CASE(sin, Sin, true);
  6510. INTRINSIC_OP_CASE(sinh, Sinh, true);
  6511. INTRINSIC_OP_CASE(tan, Tan, true);
  6512. INTRINSIC_OP_CASE(tanh, Tanh, true);
  6513. INTRINSIC_OP_CASE(sqrt, Sqrt, true);
  6514. INTRINSIC_OP_CASE(trunc, Trunc, true);
  6515. default:
  6516. emitError("%0 intrinsic function unimplemented", srcLoc)
  6517. << callee->getName();
  6518. return 0;
  6519. }
  6520. #undef INTRINSIC_OP_CASE
  6521. #undef INTRINSIC_OP_CASE_INT_FLOAT
  6522. if (retVal)
  6523. retVal->setRValue();
  6524. return retVal;
  6525. }
  6526. SpirvInstruction *
  6527. SpirvEmitter::processIntrinsicInterlockedMethod(const CallExpr *expr,
  6528. hlsl::IntrinsicOp opcode) {
  6529. // The signature of intrinsic atomic methods are:
  6530. // void Interlocked*(in R dest, in T value);
  6531. // void Interlocked*(in R dest, in T value, out T original_value);
  6532. // Note: ALL Interlocked*() methods are forced to have an unsigned integer
  6533. // 'value'. Meaning, T is forced to be 'unsigned int'. If the provided
  6534. // parameter is not an unsigned integer, the frontend inserts an
  6535. // 'ImplicitCastExpr' to convert it to unsigned integer. OpAtomicIAdd (and
  6536. // other SPIR-V OpAtomic* instructions) require that the pointee in 'dest' to
  6537. // be of the same type as T. This will result in an invalid SPIR-V if 'dest'
  6538. // is a signed integer typed resource such as RWTexture1D<int>. For example,
  6539. // the following OpAtomicIAdd is invalid because the pointee type defined in
  6540. // %1 is a signed integer, while the value passed to atomic add (%3) is an
  6541. // unsigned integer.
  6542. //
  6543. // %_ptr_Image_int = OpTypePointer Image %int
  6544. // %1 = OpImageTexelPointer %_ptr_Image_int %RWTexture1D_int %index %uint_0
  6545. // %2 = OpLoad %int %value
  6546. // %3 = OpBitcast %uint %2 <-------- Inserted by the frontend
  6547. // %4 = OpAtomicIAdd %int %1 %uint_1 %uint_0 %3
  6548. //
  6549. // In such cases, we bypass the forced IntegralCast.
  6550. // Moreover, the frontend does not add a cast AST node to cast uint to int
  6551. // where necessary. To ensure SPIR-V validity, we add that where necessary.
  6552. auto *zero =
  6553. spvBuilder.getConstantInt(astContext.UnsignedIntTy, llvm::APInt(32, 0));
  6554. const auto *dest = expr->getArg(0);
  6555. const auto srcLoc = expr->getExprLoc();
  6556. const auto baseType = dest->getType()->getCanonicalTypeUnqualified();
  6557. if (!baseType->isIntegerType()) {
  6558. emitError("can only perform atomic operations on scalar integer values",
  6559. dest->getLocStart());
  6560. return nullptr;
  6561. }
  6562. const auto doArg = [baseType, this](const CallExpr *callExpr,
  6563. uint32_t argIndex) {
  6564. const Expr *valueExpr = callExpr->getArg(argIndex);
  6565. if (const auto *castExpr = dyn_cast<ImplicitCastExpr>(valueExpr))
  6566. if (castExpr->getCastKind() == CK_IntegralCast &&
  6567. castExpr->getSubExpr()->getType() == baseType)
  6568. valueExpr = castExpr->getSubExpr();
  6569. auto *argInstr = doExpr(valueExpr);
  6570. if (valueExpr->getType() != baseType)
  6571. argInstr = castToInt(argInstr, valueExpr->getType(), baseType,
  6572. valueExpr->getExprLoc());
  6573. return argInstr;
  6574. };
  6575. const auto writeToOutputArg = [&baseType, dest,
  6576. this](SpirvInstruction *toWrite,
  6577. const CallExpr *callExpr,
  6578. uint32_t outputArgIndex) {
  6579. const auto outputArg = callExpr->getArg(outputArgIndex);
  6580. const auto outputArgType = outputArg->getType();
  6581. if (baseType != outputArgType)
  6582. toWrite =
  6583. castToInt(toWrite, baseType, outputArgType, dest->getLocStart());
  6584. spvBuilder.createStore(doExpr(outputArg), toWrite, callExpr->getExprLoc());
  6585. };
  6586. // If a vector swizzling of a texture is done as an argument of an
  6587. // interlocked method, we need to handle the access to the texture
  6588. // buffer element correctly. For example:
  6589. //
  6590. // InterlockedAdd(myRWTexture[index].r, 1);
  6591. //
  6592. // `-CallExpr
  6593. // |-ImplicitCastExpr
  6594. // | `-DeclRefExpr Function 'InterlockedAdd'
  6595. // | 'void (unsigned int &, unsigned int)'
  6596. // |-HLSLVectorElementExpr 'unsigned int' lvalue vectorcomponent r
  6597. // | `-ImplicitCastExpr 'vector<uint, 1>':'vector<unsigned int, 1>'
  6598. // | <HLSLVectorSplat>
  6599. // | `-CXXOperatorCallExpr 'unsigned int' lvalue
  6600. const auto *cxxOpCall = dyn_cast<CXXOperatorCallExpr>(dest);
  6601. if (const auto *vector = dyn_cast<HLSLVectorElementExpr>(dest)) {
  6602. const Expr *base = vector->getBase();
  6603. cxxOpCall = dyn_cast<CXXOperatorCallExpr>(base);
  6604. if (const auto *cast = dyn_cast<CastExpr>(base)) {
  6605. cxxOpCall = dyn_cast<CXXOperatorCallExpr>(cast->getSubExpr());
  6606. }
  6607. }
  6608. // If the argument is indexing into a texture/buffer, we need to create an
  6609. // OpImageTexelPointer instruction.
  6610. SpirvInstruction *ptr = nullptr;
  6611. if (cxxOpCall) {
  6612. const Expr *base = nullptr;
  6613. const Expr *index = nullptr;
  6614. if (isBufferTextureIndexing(cxxOpCall, &base, &index)) {
  6615. if (hlsl::IsHLSLResourceType(base->getType())) {
  6616. const auto resultTy = hlsl::GetHLSLResourceResultType(base->getType());
  6617. if (!isScalarType(resultTy, nullptr)) {
  6618. emitError("Interlocked operation for texture buffer whose result "
  6619. "type is non-scalar type is not allowed",
  6620. dest->getExprLoc());
  6621. return nullptr;
  6622. }
  6623. }
  6624. auto *baseInstr = doExpr(base);
  6625. if (baseInstr->isRValue()) {
  6626. // OpImageTexelPointer's Image argument must have a type of
  6627. // OpTypePointer with Type OpTypeImage. Need to create a temporary
  6628. // variable if the baseId is an rvalue.
  6629. baseInstr =
  6630. createTemporaryVar(base->getType(), getAstTypeName(base->getType()),
  6631. baseInstr, base->getExprLoc());
  6632. }
  6633. auto *coordInstr = doExpr(index);
  6634. ptr = spvBuilder.createImageTexelPointer(baseType, baseInstr, coordInstr,
  6635. zero, srcLoc);
  6636. }
  6637. }
  6638. if (!ptr) {
  6639. auto *ptrInfo = doExpr(dest);
  6640. const auto sc = ptrInfo->getStorageClass();
  6641. if (sc == spv::StorageClass::Private || sc == spv::StorageClass::Function) {
  6642. emitError("using static variable or function scope variable in "
  6643. "interlocked operation is not allowed",
  6644. dest->getExprLoc());
  6645. return nullptr;
  6646. }
  6647. ptr = ptrInfo;
  6648. }
  6649. const bool isCompareExchange =
  6650. opcode == hlsl::IntrinsicOp::IOP_InterlockedCompareExchange;
  6651. const bool isCompareStore =
  6652. opcode == hlsl::IntrinsicOp::IOP_InterlockedCompareStore;
  6653. if (isCompareExchange || isCompareStore) {
  6654. auto *comparator = doArg(expr, 1);
  6655. auto *valueInstr = doArg(expr, 2);
  6656. auto *originalVal = spvBuilder.createAtomicCompareExchange(
  6657. baseType, ptr, spv::Scope::Device, spv::MemorySemanticsMask::MaskNone,
  6658. spv::MemorySemanticsMask::MaskNone, valueInstr, comparator, srcLoc);
  6659. if (isCompareExchange)
  6660. writeToOutputArg(originalVal, expr, 3);
  6661. } else {
  6662. auto *value = doArg(expr, 1);
  6663. // Since these atomic operations write through the provided pointer, the
  6664. // signed vs. unsigned opcode must be decided based on the pointee type
  6665. // of the first argument. However, the frontend decides the opcode based on
  6666. // the second argument (value). Therefore, the HLSL opcode provided by the
  6667. // frontend may be wrong. Therefore we need the following code to make sure
  6668. // we are using the correct SPIR-V opcode.
  6669. spv::Op atomicOp = translateAtomicHlslOpcodeToSpirvOpcode(opcode);
  6670. if (atomicOp == spv::Op::OpAtomicUMax && baseType->isSignedIntegerType())
  6671. atomicOp = spv::Op::OpAtomicSMax;
  6672. if (atomicOp == spv::Op::OpAtomicSMax && baseType->isUnsignedIntegerType())
  6673. atomicOp = spv::Op::OpAtomicUMax;
  6674. if (atomicOp == spv::Op::OpAtomicUMin && baseType->isSignedIntegerType())
  6675. atomicOp = spv::Op::OpAtomicSMin;
  6676. if (atomicOp == spv::Op::OpAtomicSMin && baseType->isUnsignedIntegerType())
  6677. atomicOp = spv::Op::OpAtomicUMin;
  6678. auto *originalVal = spvBuilder.createAtomicOp(
  6679. atomicOp, baseType, ptr, spv::Scope::Device,
  6680. spv::MemorySemanticsMask::MaskNone, value, srcLoc);
  6681. if (expr->getNumArgs() > 2)
  6682. writeToOutputArg(originalVal, expr, 2);
  6683. }
  6684. return nullptr;
  6685. }
  6686. SpirvInstruction *
  6687. SpirvEmitter::processIntrinsicNonUniformResourceIndex(const CallExpr *expr) {
  6688. auto *index = doExpr(expr->getArg(0));
  6689. // Decorate the expression in NonUniformResourceIndex() with NonUniformEXT.
  6690. // Aside from this, we also need to eventually populate the NonUniformEXT
  6691. // status to the usages of this expression. This is done by the
  6692. // NonUniformVisitor class.
  6693. //
  6694. // The decoration shouldn't be applied to the operand, rather to a copy of the
  6695. // result. Even though applying the decoration to the operand may not be
  6696. // functionally incorrect (since adding NonUniform is more conservative), it
  6697. // could affect performance and isn't the intent of the shader.
  6698. auto *copyInstr =
  6699. spvBuilder.createCopyObject(expr->getType(), index, expr->getExprLoc());
  6700. copyInstr->setNonUniform();
  6701. return copyInstr;
  6702. }
  6703. SpirvInstruction *
  6704. SpirvEmitter::processIntrinsicMsad4(const CallExpr *callExpr) {
  6705. const auto loc = callExpr->getExprLoc();
  6706. if (!spirvOptions.noWarnEmulatedFeatures)
  6707. emitWarning("msad4 intrinsic function is emulated using many SPIR-V "
  6708. "instructions due to lack of direct SPIR-V equivalent",
  6709. loc);
  6710. // Compares a 4-byte reference value and an 8-byte source value and
  6711. // accumulates a vector of 4 sums. Each sum corresponds to the masked sum
  6712. // of absolute differences of a different byte alignment between the
  6713. // reference value and the source value.
  6714. // If we have:
  6715. // uint v0; // reference
  6716. // uint2 v1; // source
  6717. // uint4 v2; // accum
  6718. // uint4 o0; // result of msad4
  6719. // uint4 r0, t0; // temporary values
  6720. //
  6721. // Then msad4(v0, v1, v2) translates to the following SM5 assembly according
  6722. // to fxc:
  6723. // Step 1:
  6724. // ushr r0.xyz, v1.xxxx, l(8, 16, 24, 0)
  6725. // Step 2:
  6726. // [result], [ width ], [ offset ], [ insert ], [ base ]
  6727. // bfi t0.yzw, l(0, 8, 16, 24), l(0, 24, 16, 8), v1.yyyy , r0.xxyz
  6728. // mov t0.x, v1.x
  6729. // Step 3:
  6730. // msad o0.xyzw, v0.xxxx, t0.xyzw, v2.xyzw
  6731. const auto boolType = astContext.BoolTy;
  6732. const auto intType = astContext.IntTy;
  6733. const auto uintType = astContext.UnsignedIntTy;
  6734. const auto uint4Type = astContext.getExtVectorType(uintType, 4);
  6735. auto *reference = doExpr(callExpr->getArg(0));
  6736. auto *source = doExpr(callExpr->getArg(1));
  6737. auto *accum = doExpr(callExpr->getArg(2));
  6738. const auto uint0 =
  6739. spvBuilder.getConstantInt(astContext.UnsignedIntTy, llvm::APInt(32, 0));
  6740. const auto uint8 =
  6741. spvBuilder.getConstantInt(astContext.UnsignedIntTy, llvm::APInt(32, 8));
  6742. const auto uint16 =
  6743. spvBuilder.getConstantInt(astContext.UnsignedIntTy, llvm::APInt(32, 16));
  6744. const auto uint24 =
  6745. spvBuilder.getConstantInt(astContext.UnsignedIntTy, llvm::APInt(32, 24));
  6746. // Step 1.
  6747. auto *v1x = spvBuilder.createCompositeExtract(uintType, source, {0}, loc);
  6748. // r0.x = v1xS8 = v1.x shifted by 8 bits
  6749. auto *v1xS8 = spvBuilder.createBinaryOp(spv::Op::OpShiftLeftLogical, uintType,
  6750. v1x, uint8, loc);
  6751. // r0.y = v1xS16 = v1.x shifted by 16 bits
  6752. auto *v1xS16 = spvBuilder.createBinaryOp(spv::Op::OpShiftLeftLogical,
  6753. uintType, v1x, uint16, loc);
  6754. // r0.z = v1xS24 = v1.x shifted by 24 bits
  6755. auto *v1xS24 = spvBuilder.createBinaryOp(spv::Op::OpShiftLeftLogical,
  6756. uintType, v1x, uint24, loc);
  6757. // Step 2.
  6758. // Do bfi 3 times. DXIL bfi is equivalent to SPIR-V OpBitFieldInsert.
  6759. auto *v1y = spvBuilder.createCompositeExtract(uintType, source, {1}, loc);
  6760. // Note that t0.x = v1.x, nothing we need to do for that.
  6761. auto *t0y =
  6762. spvBuilder.createBitFieldInsert(uintType, /*base*/ v1xS8, /*insert*/ v1y,
  6763. /*offset*/ uint24,
  6764. /*width*/ uint8, loc);
  6765. auto *t0z =
  6766. spvBuilder.createBitFieldInsert(uintType, /*base*/ v1xS16, /*insert*/ v1y,
  6767. /*offset*/ uint16,
  6768. /*width*/ uint16, loc);
  6769. auto *t0w =
  6770. spvBuilder.createBitFieldInsert(uintType, /*base*/ v1xS24, /*insert*/ v1y,
  6771. /*offset*/ uint8,
  6772. /*width*/ uint24, loc);
  6773. // Step 3. MSAD (Masked Sum of Absolute Differences)
  6774. // Now perform MSAD four times.
  6775. // Need to mimic this algorithm in SPIR-V!
  6776. //
  6777. // UINT msad( UINT ref, UINT src, UINT accum )
  6778. // {
  6779. // for (UINT i = 0; i < 4; i++)
  6780. // {
  6781. // BYTE refByte, srcByte, absDiff;
  6782. //
  6783. // refByte = (BYTE)(ref >> (i * 8));
  6784. // if (!refByte)
  6785. // {
  6786. // continue;
  6787. // }
  6788. //
  6789. // srcByte = (BYTE)(src >> (i * 8));
  6790. // if (refByte >= srcByte)
  6791. // {
  6792. // absDiff = refByte - srcByte;
  6793. // }
  6794. // else
  6795. // {
  6796. // absDiff = srcByte - refByte;
  6797. // }
  6798. //
  6799. // // The recommended overflow behavior for MSAD is
  6800. // // to do a 32-bit saturate. This is not
  6801. // // required, however, and wrapping is allowed.
  6802. // // So from an application point of view,
  6803. // // overflow behavior is undefined.
  6804. // if (UINT_MAX - accum < absDiff)
  6805. // {
  6806. // accum = UINT_MAX;
  6807. // break;
  6808. // }
  6809. // accum += absDiff;
  6810. // }
  6811. //
  6812. // return accum;
  6813. // }
  6814. auto *accum0 = spvBuilder.createCompositeExtract(uintType, accum, {0}, loc);
  6815. auto *accum1 = spvBuilder.createCompositeExtract(uintType, accum, {1}, loc);
  6816. auto *accum2 = spvBuilder.createCompositeExtract(uintType, accum, {2}, loc);
  6817. auto *accum3 = spvBuilder.createCompositeExtract(uintType, accum, {3}, loc);
  6818. const llvm::SmallVector<SpirvInstruction *, 4> sources = {v1x, t0y, t0z, t0w};
  6819. llvm::SmallVector<SpirvInstruction *, 4> accums = {accum0, accum1, accum2,
  6820. accum3};
  6821. llvm::SmallVector<SpirvInstruction *, 4> refBytes;
  6822. llvm::SmallVector<SpirvInstruction *, 4> signedRefBytes;
  6823. llvm::SmallVector<SpirvInstruction *, 4> isRefByteZero;
  6824. for (uint32_t i = 0; i < 4; ++i) {
  6825. refBytes.push_back(spvBuilder.createBitFieldExtract(
  6826. uintType, reference, /*offset*/
  6827. spvBuilder.getConstantInt(astContext.UnsignedIntTy,
  6828. llvm::APInt(32, i * 8)),
  6829. /*count*/ uint8, /*isSigned*/ false, loc));
  6830. signedRefBytes.push_back(spvBuilder.createUnaryOp(
  6831. spv::Op::OpBitcast, intType, refBytes.back(), loc));
  6832. isRefByteZero.push_back(spvBuilder.createBinaryOp(
  6833. spv::Op::OpIEqual, boolType, refBytes.back(), uint0, loc));
  6834. }
  6835. for (uint32_t msadNum = 0; msadNum < 4; ++msadNum) {
  6836. for (uint32_t byteCount = 0; byteCount < 4; ++byteCount) {
  6837. // 'count' is always 8 because we are extracting 8 bits out of 32.
  6838. auto *srcByte = spvBuilder.createBitFieldExtract(
  6839. uintType, sources[msadNum],
  6840. /*offset*/
  6841. spvBuilder.getConstantInt(astContext.UnsignedIntTy,
  6842. llvm::APInt(32, 8 * byteCount)),
  6843. /*count*/ uint8, /*isSigned*/ false, loc);
  6844. auto *signedSrcByte =
  6845. spvBuilder.createUnaryOp(spv::Op::OpBitcast, intType, srcByte, loc);
  6846. auto *sub = spvBuilder.createBinaryOp(spv::Op::OpISub, intType,
  6847. signedRefBytes[byteCount],
  6848. signedSrcByte, loc);
  6849. auto *absSub = spvBuilder.createGLSLExtInst(
  6850. intType, GLSLstd450::GLSLstd450SAbs, {sub}, loc);
  6851. auto *diff = spvBuilder.createSelect(
  6852. uintType, isRefByteZero[byteCount], uint0,
  6853. spvBuilder.createUnaryOp(spv::Op::OpBitcast, uintType, absSub, loc),
  6854. loc);
  6855. // As pointed out by the DXIL reference above, it is *not* required to
  6856. // saturate the output to UINT_MAX in case of overflow. Wrapping around is
  6857. // also allowed. For simplicity, we will wrap around at this point.
  6858. accums[msadNum] = spvBuilder.createBinaryOp(spv::Op::OpIAdd, uintType,
  6859. accums[msadNum], diff, loc);
  6860. }
  6861. }
  6862. return spvBuilder.createCompositeConstruct(uint4Type, accums, loc);
  6863. }
  6864. SpirvInstruction *SpirvEmitter::processWaveQuery(const CallExpr *callExpr,
  6865. spv::Op opcode) {
  6866. // Signatures:
  6867. // bool WaveIsFirstLane()
  6868. // uint WaveGetLaneCount()
  6869. // uint WaveGetLaneIndex()
  6870. assert(callExpr->getNumArgs() == 0);
  6871. featureManager.requestTargetEnv(SPV_ENV_VULKAN_1_1, "Wave Operation",
  6872. callExpr->getExprLoc());
  6873. const QualType retType = callExpr->getCallReturnType(astContext);
  6874. return spvBuilder.createGroupNonUniformElect(
  6875. opcode, retType, spv::Scope::Subgroup, callExpr->getExprLoc());
  6876. }
  6877. SpirvInstruction *SpirvEmitter::processWaveVote(const CallExpr *callExpr,
  6878. spv::Op opcode) {
  6879. // Signatures:
  6880. // bool WaveActiveAnyTrue( bool expr )
  6881. // bool WaveActiveAllTrue( bool expr )
  6882. // bool uint4 WaveActiveBallot( bool expr )
  6883. assert(callExpr->getNumArgs() == 1);
  6884. featureManager.requestTargetEnv(SPV_ENV_VULKAN_1_1, "Wave Operation",
  6885. callExpr->getExprLoc());
  6886. auto *predicate = doExpr(callExpr->getArg(0));
  6887. const QualType retType = callExpr->getCallReturnType(astContext);
  6888. return spvBuilder.createGroupNonUniformUnaryOp(
  6889. callExpr->getExprLoc(), opcode, retType, spv::Scope::Subgroup, predicate);
  6890. }
  6891. spv::Op SpirvEmitter::translateWaveOp(hlsl::IntrinsicOp op, QualType type,
  6892. SourceLocation srcLoc) {
  6893. const bool isSintType = isSintOrVecMatOfSintType(type);
  6894. const bool isUintType = isUintOrVecMatOfUintType(type);
  6895. const bool isFloatType = isFloatOrVecMatOfFloatType(type);
  6896. #define WAVE_OP_CASE_INT(kind, intWaveOp) \
  6897. \
  6898. case hlsl::IntrinsicOp::IOP_Wave##kind: { \
  6899. if (isSintType || isUintType) { \
  6900. return spv::Op::OpGroupNonUniform##intWaveOp; \
  6901. } \
  6902. } break
  6903. #define WAVE_OP_CASE_INT_FLOAT(kind, intWaveOp, floatWaveOp) \
  6904. \
  6905. case hlsl::IntrinsicOp::IOP_Wave##kind: { \
  6906. if (isSintType || isUintType) { \
  6907. return spv::Op::OpGroupNonUniform##intWaveOp; \
  6908. } \
  6909. if (isFloatType) { \
  6910. return spv::Op::OpGroupNonUniform##floatWaveOp; \
  6911. } \
  6912. } break
  6913. #define WAVE_OP_CASE_SINT_UINT_FLOAT(kind, sintWaveOp, uintWaveOp, \
  6914. floatWaveOp) \
  6915. \
  6916. case hlsl::IntrinsicOp::IOP_Wave##kind: { \
  6917. if (isSintType) { \
  6918. return spv::Op::OpGroupNonUniform##sintWaveOp; \
  6919. } \
  6920. if (isUintType) { \
  6921. return spv::Op::OpGroupNonUniform##uintWaveOp; \
  6922. } \
  6923. if (isFloatType) { \
  6924. return spv::Op::OpGroupNonUniform##floatWaveOp; \
  6925. } \
  6926. } break
  6927. switch (op) {
  6928. WAVE_OP_CASE_INT_FLOAT(ActiveUSum, IAdd, FAdd);
  6929. WAVE_OP_CASE_INT_FLOAT(ActiveSum, IAdd, FAdd);
  6930. WAVE_OP_CASE_INT_FLOAT(ActiveUProduct, IMul, FMul);
  6931. WAVE_OP_CASE_INT_FLOAT(ActiveProduct, IMul, FMul);
  6932. WAVE_OP_CASE_INT_FLOAT(PrefixUSum, IAdd, FAdd);
  6933. WAVE_OP_CASE_INT_FLOAT(PrefixSum, IAdd, FAdd);
  6934. WAVE_OP_CASE_INT_FLOAT(PrefixUProduct, IMul, FMul);
  6935. WAVE_OP_CASE_INT_FLOAT(PrefixProduct, IMul, FMul);
  6936. WAVE_OP_CASE_INT(ActiveBitAnd, BitwiseAnd);
  6937. WAVE_OP_CASE_INT(ActiveBitOr, BitwiseOr);
  6938. WAVE_OP_CASE_INT(ActiveBitXor, BitwiseXor);
  6939. WAVE_OP_CASE_SINT_UINT_FLOAT(ActiveUMax, SMax, UMax, FMax);
  6940. WAVE_OP_CASE_SINT_UINT_FLOAT(ActiveMax, SMax, UMax, FMax);
  6941. WAVE_OP_CASE_SINT_UINT_FLOAT(ActiveUMin, SMin, UMin, FMin);
  6942. WAVE_OP_CASE_SINT_UINT_FLOAT(ActiveMin, SMin, UMin, FMin);
  6943. default:
  6944. // Only Simple Wave Ops are handled here.
  6945. break;
  6946. }
  6947. #undef WAVE_OP_CASE_INT_FLOAT
  6948. #undef WAVE_OP_CASE_INT
  6949. #undef WAVE_OP_CASE_SINT_UINT_FLOAT
  6950. emitError("translating wave operator '%0' unimplemented", srcLoc)
  6951. << static_cast<uint32_t>(op);
  6952. return spv::Op::OpNop;
  6953. }
  6954. SpirvInstruction *
  6955. SpirvEmitter::processWaveCountBits(const CallExpr *callExpr,
  6956. spv::GroupOperation groupOp) {
  6957. // Signatures:
  6958. // uint WaveActiveCountBits(bool bBit)
  6959. // uint WavePrefixCountBits(Bool bBit)
  6960. assert(callExpr->getNumArgs() == 1);
  6961. featureManager.requestTargetEnv(SPV_ENV_VULKAN_1_1, "Wave Operation",
  6962. callExpr->getExprLoc());
  6963. auto *predicate = doExpr(callExpr->getArg(0));
  6964. const auto srcLoc = callExpr->getExprLoc();
  6965. const QualType u32Type = astContext.UnsignedIntTy;
  6966. const QualType v4u32Type = astContext.getExtVectorType(u32Type, 4);
  6967. const QualType retType = callExpr->getCallReturnType(astContext);
  6968. auto *ballot = spvBuilder.createGroupNonUniformUnaryOp(
  6969. srcLoc, spv::Op::OpGroupNonUniformBallot, v4u32Type, spv::Scope::Subgroup,
  6970. predicate);
  6971. return spvBuilder.createGroupNonUniformUnaryOp(
  6972. srcLoc, spv::Op::OpGroupNonUniformBallotBitCount, retType,
  6973. spv::Scope::Subgroup, ballot,
  6974. llvm::Optional<spv::GroupOperation>(groupOp));
  6975. }
  6976. SpirvInstruction *SpirvEmitter::processWaveReductionOrPrefix(
  6977. const CallExpr *callExpr, spv::Op opcode, spv::GroupOperation groupOp) {
  6978. // Signatures:
  6979. // bool WaveActiveAllEqual( <type> expr )
  6980. // <type> WaveActiveSum( <type> expr )
  6981. // <type> WaveActiveProduct( <type> expr )
  6982. // <int_type> WaveActiveBitAnd( <int_type> expr )
  6983. // <int_type> WaveActiveBitOr( <int_type> expr )
  6984. // <int_type> WaveActiveBitXor( <int_type> expr )
  6985. // <type> WaveActiveMin( <type> expr)
  6986. // <type> WaveActiveMax( <type> expr)
  6987. //
  6988. // <type> WavePrefixProduct(<type> value)
  6989. // <type> WavePrefixSum(<type> value)
  6990. assert(callExpr->getNumArgs() == 1);
  6991. featureManager.requestTargetEnv(SPV_ENV_VULKAN_1_1, "Wave Operation",
  6992. callExpr->getExprLoc());
  6993. auto *predicate = doExpr(callExpr->getArg(0));
  6994. const QualType retType = callExpr->getCallReturnType(astContext);
  6995. return spvBuilder.createGroupNonUniformUnaryOp(
  6996. callExpr->getExprLoc(), opcode, retType, spv::Scope::Subgroup, predicate,
  6997. llvm::Optional<spv::GroupOperation>(groupOp));
  6998. }
  6999. SpirvInstruction *SpirvEmitter::processWaveBroadcast(const CallExpr *callExpr) {
  7000. // Signatures:
  7001. // <type> WaveReadLaneFirst(<type> expr)
  7002. // <type> WaveReadLaneAt(<type> expr, uint laneIndex)
  7003. const auto numArgs = callExpr->getNumArgs();
  7004. const auto srcLoc = callExpr->getExprLoc();
  7005. assert(numArgs == 1 || numArgs == 2);
  7006. featureManager.requestTargetEnv(SPV_ENV_VULKAN_1_1, "Wave Operation",
  7007. callExpr->getExprLoc());
  7008. auto *value = doExpr(callExpr->getArg(0));
  7009. const QualType retType = callExpr->getCallReturnType(astContext);
  7010. if (numArgs == 2)
  7011. return spvBuilder.createGroupNonUniformBinaryOp(
  7012. spv::Op::OpGroupNonUniformBroadcast, retType, spv::Scope::Subgroup,
  7013. value, doExpr(callExpr->getArg(1)), srcLoc);
  7014. else
  7015. return spvBuilder.createGroupNonUniformUnaryOp(
  7016. srcLoc, spv::Op::OpGroupNonUniformBroadcastFirst, retType,
  7017. spv::Scope::Subgroup, value);
  7018. }
  7019. SpirvInstruction *
  7020. SpirvEmitter::processWaveQuadWideShuffle(const CallExpr *callExpr,
  7021. hlsl::IntrinsicOp op) {
  7022. // Signatures:
  7023. // <type> QuadReadAcrossX(<type> localValue)
  7024. // <type> QuadReadAcrossY(<type> localValue)
  7025. // <type> QuadReadAcrossDiagonal(<type> localValue)
  7026. // <type> QuadReadLaneAt(<type> sourceValue, uint quadLaneID)
  7027. assert(callExpr->getNumArgs() == 1 || callExpr->getNumArgs() == 2);
  7028. featureManager.requestTargetEnv(SPV_ENV_VULKAN_1_1, "Wave Operation",
  7029. callExpr->getExprLoc());
  7030. auto *value = doExpr(callExpr->getArg(0));
  7031. const auto srcLoc = callExpr->getExprLoc();
  7032. const QualType retType = callExpr->getCallReturnType(astContext);
  7033. SpirvInstruction *target = nullptr;
  7034. spv::Op opcode = spv::Op::OpGroupNonUniformQuadSwap;
  7035. switch (op) {
  7036. case hlsl::IntrinsicOp::IOP_QuadReadAcrossX:
  7037. target =
  7038. spvBuilder.getConstantInt(astContext.UnsignedIntTy, llvm::APInt(32, 0));
  7039. break;
  7040. case hlsl::IntrinsicOp::IOP_QuadReadAcrossY:
  7041. target =
  7042. spvBuilder.getConstantInt(astContext.UnsignedIntTy, llvm::APInt(32, 1));
  7043. break;
  7044. case hlsl::IntrinsicOp::IOP_QuadReadAcrossDiagonal:
  7045. target =
  7046. spvBuilder.getConstantInt(astContext.UnsignedIntTy, llvm::APInt(32, 2));
  7047. break;
  7048. case hlsl::IntrinsicOp::IOP_QuadReadLaneAt:
  7049. target = doExpr(callExpr->getArg(1));
  7050. opcode = spv::Op::OpGroupNonUniformQuadBroadcast;
  7051. break;
  7052. default:
  7053. llvm_unreachable("case should not appear here");
  7054. }
  7055. return spvBuilder.createGroupNonUniformBinaryOp(
  7056. opcode, retType, spv::Scope::Subgroup, value, target, srcLoc);
  7057. }
  7058. SpirvInstruction *SpirvEmitter::processIntrinsicModf(const CallExpr *callExpr) {
  7059. // Signature is: ret modf(x, ip)
  7060. // [in] x: the input floating-point value.
  7061. // [out] ip: the integer portion of x.
  7062. // [out] ret: the fractional portion of x.
  7063. // All of the above must be a scalar, vector, or matrix with the same
  7064. // component types. Component types can be float or int.
  7065. // The ModfStruct SPIR-V instruction returns a struct. The first member is the
  7066. // fractional part and the second member is the integer portion.
  7067. // ModfStruct {
  7068. // <scalar or vector of float> frac;
  7069. // <scalar or vector of float> ip;
  7070. // }
  7071. // Note if the input number (x) is not a float (i.e. 'x' is an int), it is
  7072. // automatically converted to float before modf is invoked. Sadly, the 'ip'
  7073. // argument is not treated the same way. Therefore, in such cases we'll have
  7074. // to manually convert the float result into int.
  7075. const Expr *arg = callExpr->getArg(0);
  7076. const Expr *ipArg = callExpr->getArg(1);
  7077. const auto loc = callExpr->getLocStart();
  7078. const auto argType = arg->getType();
  7079. const auto ipType = ipArg->getType();
  7080. const auto returnType = callExpr->getType();
  7081. auto *argInstr = doExpr(arg);
  7082. // For scalar and vector argument types.
  7083. {
  7084. if (isScalarType(argType) || isVectorType(argType)) {
  7085. // The struct members *must* have the same type.
  7086. const auto modfStructType = spvContext.getHybridStructType(
  7087. {HybridStructType::FieldInfo(argType, "frac"),
  7088. HybridStructType::FieldInfo(argType, "ip")},
  7089. "ModfStructType");
  7090. auto *modf = spvBuilder.createGLSLExtInst(
  7091. modfStructType, GLSLstd450::GLSLstd450ModfStruct, {argInstr}, loc);
  7092. SpirvInstruction *ip =
  7093. spvBuilder.createCompositeExtract(argType, modf, {1}, loc);
  7094. // This will do nothing if the input number (x) and the ip are both of the
  7095. // same type. Otherwise, it will convert the ip into int as necessary.
  7096. ip = castToInt(ip, argType, ipType, ipArg->getLocStart());
  7097. processAssignment(ipArg, ip, false, nullptr);
  7098. return spvBuilder.createCompositeExtract(argType, modf, {0}, loc);
  7099. }
  7100. }
  7101. // For matrix argument types.
  7102. {
  7103. uint32_t rowCount = 0, colCount = 0;
  7104. QualType elemType = {};
  7105. if (isMxNMatrix(argType, &elemType, &rowCount, &colCount)) {
  7106. const auto colType = astContext.getExtVectorType(elemType, colCount);
  7107. const auto modfStructType = spvContext.getHybridStructType(
  7108. {HybridStructType::FieldInfo(colType, "frac"),
  7109. HybridStructType::FieldInfo(colType, "ip")},
  7110. "ModfStructType");
  7111. llvm::SmallVector<SpirvInstruction *, 4> fracs;
  7112. llvm::SmallVector<SpirvInstruction *, 4> ips;
  7113. for (uint32_t i = 0; i < rowCount; ++i) {
  7114. auto *curRow =
  7115. spvBuilder.createCompositeExtract(colType, argInstr, {i}, loc);
  7116. auto *modf = spvBuilder.createGLSLExtInst(
  7117. modfStructType, GLSLstd450::GLSLstd450ModfStruct, {curRow}, loc);
  7118. ips.push_back(
  7119. spvBuilder.createCompositeExtract(colType, modf, {1}, loc));
  7120. fracs.push_back(
  7121. spvBuilder.createCompositeExtract(colType, modf, {0}, loc));
  7122. }
  7123. SpirvInstruction *ip =
  7124. spvBuilder.createCompositeConstruct(argType, ips, loc);
  7125. // If the 'ip' is not a float type, the AST will not contain a CastExpr
  7126. // because this is internal to the intrinsic function. So, in such a
  7127. // case we need to cast manually.
  7128. if (!hlsl::GetHLSLMatElementType(ipType)->isFloatingType())
  7129. ip = castToInt(ip, argType, ipType, ipArg->getLocStart());
  7130. processAssignment(ipArg, ip, false, nullptr);
  7131. return spvBuilder.createCompositeConstruct(returnType, fracs, loc);
  7132. }
  7133. }
  7134. emitError("invalid argument type passed to Modf intrinsic function",
  7135. callExpr->getExprLoc());
  7136. return nullptr;
  7137. }
  7138. SpirvInstruction *SpirvEmitter::processIntrinsicMad(const CallExpr *callExpr) {
  7139. // Signature is: ret mad(a,b,c)
  7140. // All of the above must be a scalar, vector, or matrix with the same
  7141. // component types. Component types can be float or int.
  7142. // The return value is equal to "a * b + c"
  7143. // In the case of float arguments, we can use the GLSL extended instruction
  7144. // set's Fma instruction with NoContraction decoration. In the case of integer
  7145. // arguments, we'll have to manually perform an OpIMul followed by an OpIAdd
  7146. // (We should also apply NoContraction decoration to these two instructions to
  7147. // get precise arithmetic).
  7148. // TODO: We currently don't propagate the NoContraction decoration.
  7149. const auto loc = callExpr->getLocStart();
  7150. const Expr *arg0 = callExpr->getArg(0);
  7151. const Expr *arg1 = callExpr->getArg(1);
  7152. const Expr *arg2 = callExpr->getArg(2);
  7153. // All arguments and the return type are the same.
  7154. const auto argType = arg0->getType();
  7155. auto *arg0Instr = doExpr(arg0);
  7156. auto *arg1Instr = doExpr(arg1);
  7157. auto *arg2Instr = doExpr(arg2);
  7158. auto arg0Loc = arg0->getLocStart();
  7159. auto arg1Loc = arg1->getLocStart();
  7160. auto arg2Loc = arg2->getLocStart();
  7161. // For floating point arguments, we can use the extended instruction set's Fma
  7162. // instruction. Sadly we can't simply call processIntrinsicUsingGLSLInst
  7163. // because we need to specifically decorate the Fma instruction with
  7164. // NoContraction decoration.
  7165. if (isFloatOrVecMatOfFloatType(argType)) {
  7166. // For matrix cases, operate on each row of the matrix.
  7167. if (isMxNMatrix(arg0->getType())) {
  7168. const auto actOnEachVec = [this, loc, arg1Instr, arg2Instr, arg1Loc,
  7169. arg2Loc](uint32_t index, QualType vecType,
  7170. SpirvInstruction *arg0Row) {
  7171. auto *arg1Row = spvBuilder.createCompositeExtract(vecType, arg1Instr,
  7172. {index}, arg1Loc);
  7173. auto *arg2Row = spvBuilder.createCompositeExtract(vecType, arg2Instr,
  7174. {index}, arg2Loc);
  7175. auto *fma = spvBuilder.createGLSLExtInst(
  7176. vecType, GLSLstd450Fma, {arg0Row, arg1Row, arg2Row}, loc);
  7177. spvBuilder.decorateNoContraction(fma, loc);
  7178. return fma;
  7179. };
  7180. return processEachVectorInMatrix(arg0, arg0Instr, actOnEachVec, loc);
  7181. }
  7182. // Non-matrix cases
  7183. auto *fma = spvBuilder.createGLSLExtInst(
  7184. argType, GLSLstd450Fma, {arg0Instr, arg1Instr, arg2Instr}, loc);
  7185. spvBuilder.decorateNoContraction(fma, loc);
  7186. return fma;
  7187. }
  7188. // For scalar and vector argument types.
  7189. {
  7190. if (isScalarType(argType) || isVectorType(argType)) {
  7191. auto *mul = spvBuilder.createBinaryOp(spv::Op::OpIMul, argType, arg0Instr,
  7192. arg1Instr, loc);
  7193. auto *add = spvBuilder.createBinaryOp(spv::Op::OpIAdd, argType, mul,
  7194. arg2Instr, loc);
  7195. spvBuilder.decorateNoContraction(mul, loc);
  7196. spvBuilder.decorateNoContraction(add, loc);
  7197. return add;
  7198. }
  7199. }
  7200. // For matrix argument types.
  7201. {
  7202. uint32_t rowCount = 0, colCount = 0;
  7203. QualType elemType = {};
  7204. if (isMxNMatrix(argType, &elemType, &rowCount, &colCount)) {
  7205. const auto colType = astContext.getExtVectorType(elemType, colCount);
  7206. llvm::SmallVector<SpirvInstruction *, 4> resultRows;
  7207. for (uint32_t i = 0; i < rowCount; ++i) {
  7208. auto *rowArg0 =
  7209. spvBuilder.createCompositeExtract(colType, arg0Instr, {i}, arg0Loc);
  7210. auto *rowArg1 =
  7211. spvBuilder.createCompositeExtract(colType, arg1Instr, {i}, arg1Loc);
  7212. auto *rowArg2 =
  7213. spvBuilder.createCompositeExtract(colType, arg2Instr, {i}, arg2Loc);
  7214. auto *mul = spvBuilder.createBinaryOp(spv::Op::OpIMul, colType, rowArg0,
  7215. rowArg1, loc);
  7216. auto *add = spvBuilder.createBinaryOp(spv::Op::OpIAdd, colType, mul,
  7217. rowArg2, loc);
  7218. spvBuilder.decorateNoContraction(mul, loc);
  7219. spvBuilder.decorateNoContraction(add, loc);
  7220. resultRows.push_back(add);
  7221. }
  7222. return spvBuilder.createCompositeConstruct(argType, resultRows, loc);
  7223. }
  7224. }
  7225. emitError("invalid argument type passed to mad intrinsic function",
  7226. callExpr->getExprLoc());
  7227. return 0;
  7228. }
  7229. SpirvInstruction *SpirvEmitter::processIntrinsicLit(const CallExpr *callExpr) {
  7230. // Signature is: float4 lit(float n_dot_l, float n_dot_h, float m)
  7231. //
  7232. // This function returns a lighting coefficient vector
  7233. // (ambient, diffuse, specular, 1) where:
  7234. // ambient = 1.
  7235. // diffuse = (n_dot_l < 0) ? 0 : n_dot_l
  7236. // specular = (n_dot_l < 0 || n_dot_h < 0) ? 0 : ((n_dot_h) * m)
  7237. auto *nDotL = doExpr(callExpr->getArg(0));
  7238. auto *nDotH = doExpr(callExpr->getArg(1));
  7239. auto *m = doExpr(callExpr->getArg(2));
  7240. const auto loc = callExpr->getExprLoc();
  7241. const QualType floatType = astContext.FloatTy;
  7242. const QualType boolType = astContext.BoolTy;
  7243. SpirvInstruction *floatZero =
  7244. spvBuilder.getConstantFloat(astContext.FloatTy, llvm::APFloat(0.0f));
  7245. SpirvInstruction *floatOne =
  7246. spvBuilder.getConstantFloat(astContext.FloatTy, llvm::APFloat(1.0f));
  7247. const QualType retType = callExpr->getType();
  7248. auto *diffuse = spvBuilder.createGLSLExtInst(
  7249. floatType, GLSLstd450::GLSLstd450FMax, {floatZero, nDotL}, loc);
  7250. auto *min = spvBuilder.createGLSLExtInst(
  7251. floatType, GLSLstd450::GLSLstd450FMin, {nDotL, nDotH}, loc);
  7252. auto *isNeg = spvBuilder.createBinaryOp(spv::Op::OpFOrdLessThan, boolType,
  7253. min, floatZero, loc);
  7254. auto *mul =
  7255. spvBuilder.createBinaryOp(spv::Op::OpFMul, floatType, nDotH, m, loc);
  7256. auto *specular =
  7257. spvBuilder.createSelect(floatType, isNeg, floatZero, mul, loc);
  7258. return spvBuilder.createCompositeConstruct(
  7259. retType, {floatOne, diffuse, specular, floatOne}, callExpr->getLocEnd());
  7260. }
  7261. SpirvInstruction *
  7262. SpirvEmitter::processIntrinsicFrexp(const CallExpr *callExpr) {
  7263. // Signature is: ret frexp(x, exp)
  7264. // [in] x: the input floating-point value.
  7265. // [out] exp: the calculated exponent.
  7266. // [out] ret: the calculated mantissa.
  7267. // All of the above must be a scalar, vector, or matrix of *float* type.
  7268. // The FrexpStruct SPIR-V instruction returns a struct. The first
  7269. // member is the significand (mantissa) and must be of the same type as the
  7270. // input parameter, and the second member is the exponent and must always be a
  7271. // scalar or vector of 32-bit *integer* type.
  7272. // FrexpStruct {
  7273. // <scalar or vector of int/float> mantissa;
  7274. // <scalar or vector of integers> exponent;
  7275. // }
  7276. const Expr *arg = callExpr->getArg(0);
  7277. const auto argType = arg->getType();
  7278. const auto returnType = callExpr->getType();
  7279. const auto loc = callExpr->getExprLoc();
  7280. auto *argInstr = doExpr(arg);
  7281. auto *expInstr = doExpr(callExpr->getArg(1));
  7282. // For scalar and vector argument types.
  7283. {
  7284. uint32_t elemCount = 1;
  7285. if (isScalarType(argType) || isVectorType(argType, nullptr, &elemCount)) {
  7286. const QualType expType =
  7287. elemCount == 1
  7288. ? astContext.IntTy
  7289. : astContext.getExtVectorType(astContext.IntTy, elemCount);
  7290. const auto *frexpStructType = spvContext.getHybridStructType(
  7291. {HybridStructType::FieldInfo(argType, "mantissa"),
  7292. HybridStructType::FieldInfo(expType, "exponent")},
  7293. "FrexpStructType");
  7294. auto *frexp = spvBuilder.createGLSLExtInst(
  7295. frexpStructType, GLSLstd450::GLSLstd450FrexpStruct, {argInstr}, loc);
  7296. auto *exponentInt =
  7297. spvBuilder.createCompositeExtract(expType, frexp, {1}, loc);
  7298. // Since the SPIR-V instruction returns an int, and the intrinsic HLSL
  7299. // expects a float, an conversion must take place before writing the
  7300. // results.
  7301. auto *exponentFloat = spvBuilder.createUnaryOp(
  7302. spv::Op::OpConvertSToF, returnType, exponentInt, loc);
  7303. spvBuilder.createStore(expInstr, exponentFloat, loc);
  7304. return spvBuilder.createCompositeExtract(argType, frexp, {0}, loc);
  7305. }
  7306. }
  7307. // For matrix argument types.
  7308. {
  7309. uint32_t rowCount = 0, colCount = 0;
  7310. if (isMxNMatrix(argType, nullptr, &rowCount, &colCount)) {
  7311. const auto expType =
  7312. astContext.getExtVectorType(astContext.IntTy, colCount);
  7313. const auto colType =
  7314. astContext.getExtVectorType(astContext.FloatTy, colCount);
  7315. const auto *frexpStructType = spvContext.getHybridStructType(
  7316. {HybridStructType::FieldInfo(colType, "mantissa"),
  7317. HybridStructType::FieldInfo(expType, "exponent")},
  7318. "FrexpStructType");
  7319. llvm::SmallVector<SpirvInstruction *, 4> exponents;
  7320. llvm::SmallVector<SpirvInstruction *, 4> mantissas;
  7321. for (uint32_t i = 0; i < rowCount; ++i) {
  7322. auto *curRow = spvBuilder.createCompositeExtract(colType, argInstr, {i},
  7323. arg->getLocStart());
  7324. auto *frexp = spvBuilder.createGLSLExtInst(
  7325. frexpStructType, GLSLstd450::GLSLstd450FrexpStruct, {curRow}, loc);
  7326. auto *exponentInt =
  7327. spvBuilder.createCompositeExtract(expType, frexp, {1}, loc);
  7328. // Since the SPIR-V instruction returns an int, and the intrinsic HLSL
  7329. // expects a float, an conversion must take place before writing the
  7330. // results.
  7331. auto *exponentFloat = spvBuilder.createUnaryOp(
  7332. spv::Op::OpConvertSToF, colType, exponentInt, loc);
  7333. exponents.push_back(exponentFloat);
  7334. mantissas.push_back(
  7335. spvBuilder.createCompositeExtract(colType, frexp, {0}, loc));
  7336. }
  7337. auto *exponentsResult =
  7338. spvBuilder.createCompositeConstruct(returnType, exponents, loc);
  7339. spvBuilder.createStore(expInstr, exponentsResult, loc);
  7340. return spvBuilder.createCompositeConstruct(returnType, mantissas,
  7341. callExpr->getLocEnd());
  7342. }
  7343. }
  7344. emitError("invalid argument type passed to Frexp intrinsic function",
  7345. callExpr->getExprLoc());
  7346. return nullptr;
  7347. }
  7348. SpirvInstruction *
  7349. SpirvEmitter::processIntrinsicLdexp(const CallExpr *callExpr) {
  7350. // Signature: ret ldexp(x, exp)
  7351. // This function uses the following formula: x * 2^exp.
  7352. // Note that we cannot use GLSL extended instruction Ldexp since it requires
  7353. // the exponent to be an integer (vector) but HLSL takes an float (vector)
  7354. // exponent. So we must calculate the result manually.
  7355. const Expr *x = callExpr->getArg(0);
  7356. const auto paramType = x->getType();
  7357. auto *xInstr = doExpr(x);
  7358. auto *expInstr = doExpr(callExpr->getArg(1));
  7359. const auto loc = callExpr->getLocStart();
  7360. const auto arg1Loc = callExpr->getArg(1)->getLocStart();
  7361. // For scalar and vector argument types.
  7362. if (isScalarType(paramType) || isVectorType(paramType)) {
  7363. const auto twoExp = spvBuilder.createGLSLExtInst(
  7364. paramType, GLSLstd450::GLSLstd450Exp2, {expInstr}, loc);
  7365. return spvBuilder.createBinaryOp(spv::Op::OpFMul, paramType, xInstr, twoExp,
  7366. loc);
  7367. }
  7368. // For matrix argument types.
  7369. {
  7370. uint32_t rowCount = 0, colCount = 0;
  7371. if (isMxNMatrix(paramType, nullptr, &rowCount, &colCount)) {
  7372. const auto actOnEachVec = [this, loc, expInstr,
  7373. arg1Loc](uint32_t index, QualType vecType,
  7374. SpirvInstruction *xRowInstr) {
  7375. auto *expRowInstr = spvBuilder.createCompositeExtract(vecType, expInstr,
  7376. {index}, arg1Loc);
  7377. auto *twoExp = spvBuilder.createGLSLExtInst(
  7378. vecType, GLSLstd450::GLSLstd450Exp2, {expRowInstr}, loc);
  7379. return spvBuilder.createBinaryOp(spv::Op::OpFMul, vecType, xRowInstr,
  7380. twoExp, loc);
  7381. };
  7382. return processEachVectorInMatrix(x, xInstr, actOnEachVec, loc);
  7383. }
  7384. }
  7385. emitError("invalid argument type passed to ldexp intrinsic function",
  7386. callExpr->getExprLoc());
  7387. return nullptr;
  7388. }
  7389. SpirvInstruction *SpirvEmitter::processIntrinsicDst(const CallExpr *callExpr) {
  7390. // Signature is float4 dst(float4 src0, float4 src1)
  7391. // result.x = 1;
  7392. // result.y = src0.y * src1.y;
  7393. // result.z = src0.z;
  7394. // result.w = src1.w;
  7395. const QualType f32 = astContext.FloatTy;
  7396. auto *arg0Id = doExpr(callExpr->getArg(0));
  7397. auto *arg1Id = doExpr(callExpr->getArg(1));
  7398. auto arg0Loc = callExpr->getArg(0)->getLocStart();
  7399. auto arg1Loc = callExpr->getArg(1)->getLocStart();
  7400. auto *arg0y = spvBuilder.createCompositeExtract(f32, arg0Id, {1}, arg0Loc);
  7401. auto *arg1y = spvBuilder.createCompositeExtract(f32, arg1Id, {1}, arg1Loc);
  7402. auto *arg0z = spvBuilder.createCompositeExtract(f32, arg0Id, {2}, arg0Loc);
  7403. auto *arg1w = spvBuilder.createCompositeExtract(f32, arg1Id, {3}, arg1Loc);
  7404. auto loc = callExpr->getLocEnd();
  7405. auto *arg0yMularg1y =
  7406. spvBuilder.createBinaryOp(spv::Op::OpFMul, f32, arg0y, arg1y, loc);
  7407. return spvBuilder.createCompositeConstruct(
  7408. callExpr->getType(),
  7409. {spvBuilder.getConstantFloat(astContext.FloatTy, llvm::APFloat(1.0f)),
  7410. arg0yMularg1y, arg0z, arg1w},
  7411. loc);
  7412. }
  7413. SpirvInstruction *SpirvEmitter::processIntrinsicClip(const CallExpr *callExpr) {
  7414. // Discards the current pixel if the specified value is less than zero.
  7415. // TODO: If the argument can be const folded and evaluated, we could
  7416. // potentially avoid creating a branch. This would be a bit challenging for
  7417. // matrix/vector arguments.
  7418. assert(callExpr->getNumArgs() == 1u);
  7419. const Expr *arg = callExpr->getArg(0);
  7420. const auto loc = callExpr->getExprLoc();
  7421. const auto argType = arg->getType();
  7422. const auto boolType = astContext.BoolTy;
  7423. SpirvInstruction *condition = nullptr;
  7424. // Could not determine the argument as a constant. We need to branch based on
  7425. // the argument. If the argument is a vector/matrix, clipping is done if *any*
  7426. // element of the vector/matrix is less than zero.
  7427. auto *argInstr = doExpr(arg);
  7428. QualType elemType = {};
  7429. uint32_t elemCount = 0, rowCount = 0, colCount = 0;
  7430. if (isScalarType(argType)) {
  7431. auto *zero = getValueZero(argType);
  7432. condition = spvBuilder.createBinaryOp(spv::Op::OpFOrdLessThan, boolType,
  7433. argInstr, zero, loc);
  7434. } else if (isVectorType(argType, nullptr, &elemCount)) {
  7435. auto *zero = getValueZero(argType);
  7436. const QualType boolVecType =
  7437. astContext.getExtVectorType(boolType, elemCount);
  7438. auto *cmp = spvBuilder.createBinaryOp(spv::Op::OpFOrdLessThan, boolVecType,
  7439. argInstr, zero, loc);
  7440. condition = spvBuilder.createUnaryOp(spv::Op::OpAny, boolType, cmp, loc);
  7441. } else if (isMxNMatrix(argType, &elemType, &rowCount, &colCount)) {
  7442. const auto floatVecType = astContext.getExtVectorType(elemType, colCount);
  7443. auto *elemZero = getValueZero(elemType);
  7444. llvm::SmallVector<SpirvConstant *, 4> elements(size_t(colCount), elemZero);
  7445. auto *zero = spvBuilder.getConstantComposite(floatVecType, elements);
  7446. llvm::SmallVector<SpirvInstruction *, 4> cmpResults;
  7447. for (uint32_t i = 0; i < rowCount; ++i) {
  7448. auto *lhsVec =
  7449. spvBuilder.createCompositeExtract(floatVecType, argInstr, {i}, loc);
  7450. const auto boolColType = astContext.getExtVectorType(boolType, colCount);
  7451. auto *cmp = spvBuilder.createBinaryOp(spv::Op::OpFOrdLessThan,
  7452. boolColType, lhsVec, zero, loc);
  7453. auto *any = spvBuilder.createUnaryOp(spv::Op::OpAny, boolType, cmp, loc);
  7454. cmpResults.push_back(any);
  7455. }
  7456. const auto boolRowType = astContext.getExtVectorType(boolType, rowCount);
  7457. auto *results =
  7458. spvBuilder.createCompositeConstruct(boolRowType, cmpResults, loc);
  7459. condition =
  7460. spvBuilder.createUnaryOp(spv::Op::OpAny, boolType, results, loc);
  7461. } else {
  7462. emitError("invalid argument type passed to clip intrinsic function", loc);
  7463. return nullptr;
  7464. }
  7465. // Then we need to emit the instruction for the conditional branch.
  7466. auto *thenBB = spvBuilder.createBasicBlock("if.true");
  7467. auto *mergeBB = spvBuilder.createBasicBlock("if.merge");
  7468. // Create the branch instruction. This will end the current basic block.
  7469. spvBuilder.createConditionalBranch(condition, thenBB, mergeBB, loc, mergeBB);
  7470. spvBuilder.addSuccessor(thenBB);
  7471. spvBuilder.addSuccessor(mergeBB);
  7472. spvBuilder.setMergeTarget(mergeBB);
  7473. // Handle the then branch
  7474. spvBuilder.setInsertPoint(thenBB);
  7475. spvBuilder.createKill(loc);
  7476. spvBuilder.addSuccessor(mergeBB);
  7477. // From now on, we'll emit instructions into the merge block.
  7478. spvBuilder.setInsertPoint(mergeBB);
  7479. return nullptr;
  7480. }
  7481. SpirvInstruction *
  7482. SpirvEmitter::processIntrinsicClamp(const CallExpr *callExpr) {
  7483. // According the HLSL reference: clamp(X, Min, Max) takes 3 arguments. Each
  7484. // one may be int, uint, or float.
  7485. const QualType returnType = callExpr->getType();
  7486. GLSLstd450 glslOpcode = GLSLstd450::GLSLstd450UClamp;
  7487. if (isFloatOrVecMatOfFloatType(returnType))
  7488. glslOpcode = GLSLstd450::GLSLstd450FClamp;
  7489. else if (isSintOrVecMatOfSintType(returnType))
  7490. glslOpcode = GLSLstd450::GLSLstd450SClamp;
  7491. // Get the function parameters. Expect 3 parameters.
  7492. assert(callExpr->getNumArgs() == 3u);
  7493. const Expr *argX = callExpr->getArg(0);
  7494. const Expr *argMin = callExpr->getArg(1);
  7495. const Expr *argMax = callExpr->getArg(2);
  7496. const auto loc = callExpr->getExprLoc();
  7497. auto *argXInstr = doExpr(argX);
  7498. auto *argMinInstr = doExpr(argMin);
  7499. auto *argMaxInstr = doExpr(argMax);
  7500. const auto argMinLoc = argMin->getLocStart();
  7501. const auto argMaxLoc = argMax->getLocStart();
  7502. // FClamp, UClamp, and SClamp do not operate on matrices, so we should perform
  7503. // the operation on each vector of the matrix.
  7504. if (isMxNMatrix(argX->getType())) {
  7505. const auto actOnEachVec =
  7506. [this, loc, glslOpcode, argMinInstr, argMaxInstr, argMinLoc, argMaxLoc](
  7507. uint32_t index, QualType vecType, SpirvInstruction *curRow) {
  7508. auto *minRowInstr = spvBuilder.createCompositeExtract(
  7509. vecType, argMinInstr, {index}, argMinLoc);
  7510. auto *maxRowInstr = spvBuilder.createCompositeExtract(
  7511. vecType, argMaxInstr, {index}, argMaxLoc);
  7512. return spvBuilder.createGLSLExtInst(
  7513. vecType, glslOpcode, {curRow, minRowInstr, maxRowInstr}, loc);
  7514. };
  7515. return processEachVectorInMatrix(argX, argXInstr, actOnEachVec, loc);
  7516. }
  7517. return spvBuilder.createGLSLExtInst(
  7518. returnType, glslOpcode, {argXInstr, argMinInstr, argMaxInstr}, loc);
  7519. }
  7520. SpirvInstruction *
  7521. SpirvEmitter::processIntrinsicMemoryBarrier(const CallExpr *callExpr,
  7522. bool isDevice, bool groupSync,
  7523. bool isAllBarrier) {
  7524. // * DeviceMemoryBarrier =
  7525. // OpMemoryBarrier (memScope=Device,
  7526. // sem=Image|Uniform|AcquireRelease)
  7527. //
  7528. // * DeviceMemoryBarrierWithGroupSync =
  7529. // OpControlBarrier(execScope = Workgroup,
  7530. // memScope=Device,
  7531. // sem=Image|Uniform|AcquireRelease)
  7532. const spv::MemorySemanticsMask deviceMemoryBarrierSema =
  7533. spv::MemorySemanticsMask::ImageMemory |
  7534. spv::MemorySemanticsMask::UniformMemory |
  7535. spv::MemorySemanticsMask::AcquireRelease;
  7536. // * GroupMemoryBarrier =
  7537. // OpMemoryBarrier (memScope=Workgroup,
  7538. // sem = Workgroup|AcquireRelease)
  7539. //
  7540. // * GroupMemoryBarrierWithGroupSync =
  7541. // OpControlBarrier (execScope = Workgroup,
  7542. // memScope = Workgroup,
  7543. // sem = Workgroup|AcquireRelease)
  7544. const spv::MemorySemanticsMask groupMemoryBarrierSema =
  7545. spv::MemorySemanticsMask::WorkgroupMemory |
  7546. spv::MemorySemanticsMask::AcquireRelease;
  7547. // * AllMemoryBarrier =
  7548. // OpMemoryBarrier(memScope = Device,
  7549. // sem = Image|Uniform|Workgroup|AcquireRelease)
  7550. //
  7551. // * AllMemoryBarrierWithGroupSync =
  7552. // OpControlBarrier(execScope = Workgroup,
  7553. // memScope = Device,
  7554. // sem = Image|Uniform|Workgroup|AcquireRelease)
  7555. const spv::MemorySemanticsMask allMemoryBarrierSema =
  7556. spv::MemorySemanticsMask::ImageMemory |
  7557. spv::MemorySemanticsMask::UniformMemory |
  7558. spv::MemorySemanticsMask::WorkgroupMemory |
  7559. spv::MemorySemanticsMask::AcquireRelease;
  7560. // Get <result-id> for execution scope.
  7561. // If present, execution scope is always Workgroup!
  7562. llvm::Optional<spv::Scope> execScope = llvm::None;
  7563. if (groupSync) {
  7564. execScope = spv::Scope::Workgroup;
  7565. }
  7566. // Get <result-id> for memory scope
  7567. const spv::Scope memScope =
  7568. (isDevice || isAllBarrier) ? spv::Scope::Device : spv::Scope::Workgroup;
  7569. // Get <result-id> for memory semantics
  7570. const auto memSemaMask = isAllBarrier ? allMemoryBarrierSema
  7571. : isDevice ? deviceMemoryBarrierSema
  7572. : groupMemoryBarrierSema;
  7573. spvBuilder.createBarrier(memScope, memSemaMask, execScope,
  7574. callExpr->getExprLoc());
  7575. return nullptr;
  7576. }
  7577. SpirvInstruction *SpirvEmitter::processNonFpMatrixTranspose(
  7578. QualType matType, SpirvInstruction *matrix, SourceLocation loc) {
  7579. // Simplest way is to flatten the matrix construct a new matrix from the
  7580. // flattened elements. (for a mat4x4).
  7581. QualType elemType = {};
  7582. uint32_t numRows = 0, numCols = 0;
  7583. const bool isMat = isMxNMatrix(matType, &elemType, &numRows, &numCols);
  7584. assert(isMat && !elemType->isFloatingType());
  7585. (void)isMat;
  7586. const auto colQualType = astContext.getExtVectorType(elemType, numRows);
  7587. // You cannot perform a composite construct of an array using a few vectors.
  7588. // The number of constutients passed to OpCompositeConstruct must be equal to
  7589. // the number of array elements.
  7590. llvm::SmallVector<SpirvInstruction *, 4> elems;
  7591. for (uint32_t i = 0; i < numRows; ++i)
  7592. for (uint32_t j = 0; j < numCols; ++j)
  7593. elems.push_back(
  7594. spvBuilder.createCompositeExtract(elemType, matrix, {i, j}, loc));
  7595. llvm::SmallVector<SpirvInstruction *, 4> cols;
  7596. for (uint32_t i = 0; i < numCols; ++i) {
  7597. // The elements in the ith vector of the "transposed" array are at offset i,
  7598. // i + <original-vector-size>, ...
  7599. llvm::SmallVector<SpirvInstruction *, 4> indexes;
  7600. for (uint32_t j = 0; j < numRows; ++j)
  7601. indexes.push_back(elems[i + (j * numCols)]);
  7602. cols.push_back(
  7603. spvBuilder.createCompositeConstruct(colQualType, indexes, loc));
  7604. }
  7605. auto transposeType = astContext.getConstantArrayType(
  7606. colQualType, llvm::APInt(32, numCols), clang::ArrayType::Normal, 0);
  7607. return spvBuilder.createCompositeConstruct(transposeType, cols, loc);
  7608. }
  7609. SpirvInstruction *SpirvEmitter::processNonFpDot(SpirvInstruction *vec1Id,
  7610. SpirvInstruction *vec2Id,
  7611. uint32_t vecSize,
  7612. QualType elemType,
  7613. SourceLocation loc) {
  7614. llvm::SmallVector<SpirvInstruction *, 4> muls;
  7615. for (uint32_t i = 0; i < vecSize; ++i) {
  7616. auto *elem1 = spvBuilder.createCompositeExtract(elemType, vec1Id, {i}, loc);
  7617. auto *elem2 = spvBuilder.createCompositeExtract(elemType, vec2Id, {i}, loc);
  7618. muls.push_back(spvBuilder.createBinaryOp(translateOp(BO_Mul, elemType),
  7619. elemType, elem1, elem2, loc));
  7620. }
  7621. SpirvInstruction *sum = muls[0];
  7622. for (uint32_t i = 1; i < vecSize; ++i) {
  7623. sum = spvBuilder.createBinaryOp(translateOp(BO_Add, elemType), elemType,
  7624. sum, muls[i], loc);
  7625. }
  7626. return sum;
  7627. }
  7628. SpirvInstruction *SpirvEmitter::processNonFpScalarTimesMatrix(
  7629. QualType scalarType, SpirvInstruction *scalar, QualType matrixType,
  7630. SpirvInstruction *matrix, SourceLocation loc) {
  7631. assert(isScalarType(scalarType));
  7632. QualType elemType = {};
  7633. uint32_t numRows = 0, numCols = 0;
  7634. const bool isMat = isMxNMatrix(matrixType, &elemType, &numRows, &numCols);
  7635. assert(isMat);
  7636. assert(isSameType(astContext, scalarType, elemType));
  7637. (void)isMat;
  7638. // We need to multiply the scalar by each vector of the matrix.
  7639. // The front-end guarantees that the scalar and matrix element type are
  7640. // the same. For example, if the scalar is a float, the matrix is casted
  7641. // to a float matrix before being passed to mul(). It is also guaranteed
  7642. // that types such as bool are casted to float or int before being
  7643. // passed to mul().
  7644. const auto rowType = astContext.getExtVectorType(elemType, numCols);
  7645. llvm::SmallVector<SpirvInstruction *, 4> splat(size_t(numCols), scalar);
  7646. auto *scalarSplat = spvBuilder.createCompositeConstruct(rowType, splat, loc);
  7647. llvm::SmallVector<SpirvInstruction *, 4> mulRows;
  7648. for (uint32_t row = 0; row < numRows; ++row) {
  7649. auto *rowInstr =
  7650. spvBuilder.createCompositeExtract(rowType, matrix, {row}, loc);
  7651. mulRows.push_back(spvBuilder.createBinaryOp(
  7652. translateOp(BO_Mul, scalarType), rowType, rowInstr, scalarSplat, loc));
  7653. }
  7654. return spvBuilder.createCompositeConstruct(matrixType, mulRows, loc);
  7655. }
  7656. SpirvInstruction *SpirvEmitter::processNonFpVectorTimesMatrix(
  7657. QualType vecType, SpirvInstruction *vector, QualType matType,
  7658. SpirvInstruction *matrix, SourceLocation loc,
  7659. SpirvInstruction *matrixTranspose) {
  7660. // This function assumes that the vector element type and matrix elemet type
  7661. // are the same.
  7662. QualType vecElemType = {}, matElemType = {};
  7663. uint32_t vecSize = 0, numRows = 0, numCols = 0;
  7664. const bool isVec = isVectorType(vecType, &vecElemType, &vecSize);
  7665. const bool isMat = isMxNMatrix(matType, &matElemType, &numRows, &numCols);
  7666. assert(isSameType(astContext, vecElemType, matElemType));
  7667. assert(isVec);
  7668. assert(isMat);
  7669. assert(vecSize == numRows);
  7670. (void)isVec;
  7671. (void)isMat;
  7672. // When processing vector times matrix, the vector is a row vector, and it
  7673. // should be multiplied by the matrix *columns*. The most efficient way to
  7674. // handle this in SPIR-V would be to first transpose the matrix, and then use
  7675. // OpAccessChain.
  7676. if (!matrixTranspose)
  7677. matrixTranspose = processNonFpMatrixTranspose(matType, matrix, loc);
  7678. llvm::SmallVector<SpirvInstruction *, 4> resultElems;
  7679. for (uint32_t col = 0; col < numCols; ++col) {
  7680. auto *colInstr =
  7681. spvBuilder.createCompositeExtract(vecType, matrixTranspose, {col}, loc);
  7682. resultElems.push_back(
  7683. processNonFpDot(vector, colInstr, vecSize, vecElemType, loc));
  7684. }
  7685. return spvBuilder.createCompositeConstruct(
  7686. astContext.getExtVectorType(vecElemType, numCols), resultElems, loc);
  7687. }
  7688. SpirvInstruction *SpirvEmitter::processNonFpMatrixTimesVector(
  7689. QualType matType, SpirvInstruction *matrix, QualType vecType,
  7690. SpirvInstruction *vector, SourceLocation loc) {
  7691. // This function assumes that the vector element type and matrix elemet type
  7692. // are the same.
  7693. QualType vecElemType = {}, matElemType = {};
  7694. uint32_t vecSize = 0, numRows = 0, numCols = 0;
  7695. const bool isVec = isVectorType(vecType, &vecElemType, &vecSize);
  7696. const bool isMat = isMxNMatrix(matType, &matElemType, &numRows, &numCols);
  7697. assert(isSameType(astContext, vecElemType, matElemType));
  7698. assert(isVec);
  7699. assert(isMat);
  7700. assert(vecSize == numCols);
  7701. (void)isVec;
  7702. (void)isMat;
  7703. // When processing matrix times vector, the vector is a column vector. So we
  7704. // simply get each row of the matrix and perform a dot product with the
  7705. // vector.
  7706. llvm::SmallVector<SpirvInstruction *, 4> resultElems;
  7707. for (uint32_t row = 0; row < numRows; ++row) {
  7708. auto *rowInstr =
  7709. spvBuilder.createCompositeExtract(vecType, matrix, {row}, loc);
  7710. resultElems.push_back(
  7711. processNonFpDot(rowInstr, vector, vecSize, vecElemType, loc));
  7712. }
  7713. return spvBuilder.createCompositeConstruct(
  7714. astContext.getExtVectorType(vecElemType, numRows), resultElems, loc);
  7715. }
  7716. SpirvInstruction *SpirvEmitter::processNonFpMatrixTimesMatrix(
  7717. QualType lhsType, SpirvInstruction *lhs, QualType rhsType,
  7718. SpirvInstruction *rhs, SourceLocation loc) {
  7719. // This function assumes that the vector element type and matrix elemet type
  7720. // are the same.
  7721. QualType lhsElemType = {}, rhsElemType = {};
  7722. uint32_t lhsNumRows = 0, lhsNumCols = 0;
  7723. uint32_t rhsNumRows = 0, rhsNumCols = 0;
  7724. const bool lhsIsMat =
  7725. isMxNMatrix(lhsType, &lhsElemType, &lhsNumRows, &lhsNumCols);
  7726. const bool rhsIsMat =
  7727. isMxNMatrix(rhsType, &rhsElemType, &rhsNumRows, &rhsNumCols);
  7728. assert(isSameType(astContext, lhsElemType, rhsElemType));
  7729. assert(lhsIsMat && rhsIsMat);
  7730. assert(lhsNumCols == rhsNumRows);
  7731. (void)rhsIsMat;
  7732. (void)lhsIsMat;
  7733. auto *rhsTranspose = processNonFpMatrixTranspose(rhsType, rhs, loc);
  7734. const auto vecType = astContext.getExtVectorType(lhsElemType, lhsNumCols);
  7735. llvm::SmallVector<SpirvInstruction *, 4> resultRows;
  7736. for (uint32_t row = 0; row < lhsNumRows; ++row) {
  7737. auto *rowInstr =
  7738. spvBuilder.createCompositeExtract(vecType, lhs, {row}, loc);
  7739. resultRows.push_back(processNonFpVectorTimesMatrix(
  7740. vecType, rowInstr, rhsType, rhs, loc, rhsTranspose));
  7741. }
  7742. // The resulting matrix will have 'lhsNumRows' rows and 'rhsNumCols' columns.
  7743. const auto resultColType =
  7744. astContext.getExtVectorType(lhsElemType, rhsNumCols);
  7745. const auto resultType = astContext.getConstantArrayType(
  7746. resultColType, llvm::APInt(32, lhsNumRows), clang::ArrayType::Normal, 0);
  7747. return spvBuilder.createCompositeConstruct(resultType, resultRows, loc);
  7748. }
  7749. SpirvInstruction *SpirvEmitter::processIntrinsicMul(const CallExpr *callExpr) {
  7750. const QualType returnType = callExpr->getType();
  7751. // Get the function parameters. Expect 2 parameters.
  7752. assert(callExpr->getNumArgs() == 2u);
  7753. const Expr *arg0 = callExpr->getArg(0);
  7754. const Expr *arg1 = callExpr->getArg(1);
  7755. const QualType arg0Type = arg0->getType();
  7756. const QualType arg1Type = arg1->getType();
  7757. auto loc = callExpr->getExprLoc();
  7758. // The HLSL mul() function takes 2 arguments. Each argument may be a scalar,
  7759. // vector, or matrix. The frontend ensures that the two arguments have the
  7760. // same component type. The only allowed component types are int and float.
  7761. // mul(scalar, vector)
  7762. {
  7763. uint32_t elemCount = 0;
  7764. if (isScalarType(arg0Type) && isVectorType(arg1Type, nullptr, &elemCount)) {
  7765. auto *arg1Id = doExpr(arg1);
  7766. // We can use OpVectorTimesScalar if arguments are floats.
  7767. if (arg0Type->isFloatingType())
  7768. return spvBuilder.createBinaryOp(spv::Op::OpVectorTimesScalar,
  7769. returnType, arg1Id, doExpr(arg0), loc);
  7770. // Use OpIMul for integers
  7771. return spvBuilder.createBinaryOp(spv::Op::OpIMul, returnType,
  7772. createVectorSplat(arg0, elemCount),
  7773. arg1Id, loc);
  7774. }
  7775. }
  7776. // mul(vector, scalar)
  7777. {
  7778. uint32_t elemCount = 0;
  7779. if (isVectorType(arg0Type, nullptr, &elemCount) && isScalarType(arg1Type)) {
  7780. auto *arg0Id = doExpr(arg0);
  7781. // We can use OpVectorTimesScalar if arguments are floats.
  7782. if (arg1Type->isFloatingType())
  7783. return spvBuilder.createBinaryOp(spv::Op::OpVectorTimesScalar,
  7784. returnType, arg0Id, doExpr(arg1), loc);
  7785. // Use OpIMul for integers
  7786. return spvBuilder.createBinaryOp(spv::Op::OpIMul, returnType, arg0Id,
  7787. createVectorSplat(arg1, elemCount), loc);
  7788. }
  7789. }
  7790. // mul(vector, vector)
  7791. if (isVectorType(arg0Type) && isVectorType(arg1Type))
  7792. return processIntrinsicDot(callExpr);
  7793. // All the following cases require handling arg0 and arg1 expressions first.
  7794. auto *arg0Id = doExpr(arg0);
  7795. auto *arg1Id = doExpr(arg1);
  7796. // mul(scalar, scalar)
  7797. if (isScalarType(arg0Type) && isScalarType(arg1Type))
  7798. return spvBuilder.createBinaryOp(translateOp(BO_Mul, arg0Type), returnType,
  7799. arg0Id, arg1Id, loc);
  7800. // mul(scalar, matrix)
  7801. {
  7802. QualType elemType = {};
  7803. if (isScalarType(arg0Type) && isMxNMatrix(arg1Type, &elemType)) {
  7804. // OpMatrixTimesScalar can only be used if *both* the matrix element type
  7805. // and the scalar type are float.
  7806. if (arg0Type->isFloatingType() && elemType->isFloatingType())
  7807. return spvBuilder.createBinaryOp(spv::Op::OpMatrixTimesScalar,
  7808. returnType, arg1Id, arg0Id, loc);
  7809. else
  7810. return processNonFpScalarTimesMatrix(arg0Type, arg0Id, arg1Type, arg1Id,
  7811. callExpr->getExprLoc());
  7812. }
  7813. }
  7814. // mul(matrix, scalar)
  7815. {
  7816. QualType elemType = {};
  7817. if (isScalarType(arg1Type) && isMxNMatrix(arg0Type, &elemType)) {
  7818. // OpMatrixTimesScalar can only be used if *both* the matrix element type
  7819. // and the scalar type are float.
  7820. if (arg1Type->isFloatingType() && elemType->isFloatingType())
  7821. return spvBuilder.createBinaryOp(spv::Op::OpMatrixTimesScalar,
  7822. returnType, arg0Id, arg1Id, loc);
  7823. else
  7824. return processNonFpScalarTimesMatrix(arg1Type, arg1Id, arg0Type, arg0Id,
  7825. callExpr->getExprLoc());
  7826. }
  7827. }
  7828. // mul(vector, matrix)
  7829. {
  7830. QualType vecElemType = {}, matElemType = {};
  7831. uint32_t elemCount = 0, numRows = 0;
  7832. if (isVectorType(arg0Type, &vecElemType, &elemCount) &&
  7833. isMxNMatrix(arg1Type, &matElemType, &numRows)) {
  7834. assert(elemCount == numRows);
  7835. if (vecElemType->isFloatingType() && matElemType->isFloatingType())
  7836. return spvBuilder.createBinaryOp(spv::Op::OpMatrixTimesVector,
  7837. returnType, arg1Id, arg0Id, loc);
  7838. else
  7839. return processNonFpVectorTimesMatrix(arg0Type, arg0Id, arg1Type, arg1Id,
  7840. callExpr->getExprLoc());
  7841. }
  7842. }
  7843. // mul(matrix, vector)
  7844. {
  7845. QualType vecElemType = {}, matElemType = {};
  7846. uint32_t elemCount = 0, numCols = 0;
  7847. if (isMxNMatrix(arg0Type, &matElemType, nullptr, &numCols) &&
  7848. isVectorType(arg1Type, &vecElemType, &elemCount)) {
  7849. assert(elemCount == numCols);
  7850. if (vecElemType->isFloatingType() && matElemType->isFloatingType())
  7851. return spvBuilder.createBinaryOp(spv::Op::OpVectorTimesMatrix,
  7852. returnType, arg1Id, arg0Id, loc);
  7853. else
  7854. return processNonFpMatrixTimesVector(arg0Type, arg0Id, arg1Type, arg1Id,
  7855. callExpr->getExprLoc());
  7856. }
  7857. }
  7858. // mul(matrix, matrix)
  7859. {
  7860. // The front-end ensures that the two matrix element types match.
  7861. QualType elemType = {};
  7862. uint32_t lhsCols = 0, rhsRows = 0;
  7863. if (isMxNMatrix(arg0Type, &elemType, nullptr, &lhsCols) &&
  7864. isMxNMatrix(arg1Type, nullptr, &rhsRows, nullptr)) {
  7865. assert(lhsCols == rhsRows);
  7866. if (elemType->isFloatingType())
  7867. return spvBuilder.createBinaryOp(spv::Op::OpMatrixTimesMatrix,
  7868. returnType, arg1Id, arg0Id, loc);
  7869. else
  7870. return processNonFpMatrixTimesMatrix(arg0Type, arg0Id, arg1Type, arg1Id,
  7871. callExpr->getExprLoc());
  7872. }
  7873. }
  7874. emitError("invalid argument type passed to mul intrinsic function",
  7875. callExpr->getExprLoc());
  7876. return nullptr;
  7877. }
  7878. SpirvInstruction *
  7879. SpirvEmitter::processIntrinsicPrintf(const CallExpr *callExpr) {
  7880. // C99, s6.5.2.2/6: "If the expression that denotes the called function has a
  7881. // type that does not include a prototype, the integer promotions are
  7882. // performed on each argument, and arguments that have type float are promoted
  7883. // to double. These are called the default argument promotions."
  7884. // C++: All the variadic parameters undergo default promotions before they're
  7885. // received by the function.
  7886. //
  7887. // Therefore by default floating point arguments will be evaluated as double
  7888. // by this function.
  7889. //
  7890. // TODO: We may want to change this behavior for SPIR-V.
  7891. const auto returnType = callExpr->getType();
  7892. const auto numArgs = callExpr->getNumArgs();
  7893. const auto loc = callExpr->getExprLoc();
  7894. assert(numArgs >= 1u);
  7895. llvm::SmallVector<SpirvInstruction *, 4> args;
  7896. for (uint32_t argIndex = 0; argIndex < numArgs; ++argIndex)
  7897. args.push_back(doExpr(callExpr->getArg(argIndex)));
  7898. return spvBuilder.createNonSemanticDebugPrintfExtInst(
  7899. returnType, NonSemanticDebugPrintfDebugPrintf, args, loc);
  7900. }
  7901. SpirvInstruction *SpirvEmitter::processIntrinsicDot(const CallExpr *callExpr) {
  7902. const QualType returnType = callExpr->getType();
  7903. // Get the function parameters. Expect 2 vectors as parameters.
  7904. assert(callExpr->getNumArgs() == 2u);
  7905. const Expr *arg0 = callExpr->getArg(0);
  7906. const Expr *arg1 = callExpr->getArg(1);
  7907. auto *arg0Id = doExpr(arg0);
  7908. auto *arg1Id = doExpr(arg1);
  7909. QualType arg0Type = arg0->getType();
  7910. QualType arg1Type = arg1->getType();
  7911. const size_t vec0Size = hlsl::GetHLSLVecSize(arg0Type);
  7912. const size_t vec1Size = hlsl::GetHLSLVecSize(arg1Type);
  7913. const QualType vec0ComponentType = hlsl::GetHLSLVecElementType(arg0Type);
  7914. const QualType vec1ComponentType = hlsl::GetHLSLVecElementType(arg1Type);
  7915. assert(returnType == vec1ComponentType);
  7916. assert(vec0ComponentType == vec1ComponentType);
  7917. assert(vec0Size == vec1Size);
  7918. assert(vec0Size >= 1 && vec0Size <= 4);
  7919. (void)vec0ComponentType;
  7920. (void)vec1ComponentType;
  7921. (void)vec1Size;
  7922. auto loc = callExpr->getLocStart();
  7923. // According to HLSL reference, the dot function only works on integers
  7924. // and floats.
  7925. assert(returnType->isFloatingType() || returnType->isIntegerType());
  7926. // Special case: dot product of two vectors, each of size 1. That is
  7927. // basically the same as regular multiplication of 2 scalars.
  7928. if (vec0Size == 1) {
  7929. const spv::Op spvOp = translateOp(BO_Mul, arg0Type);
  7930. return spvBuilder.createBinaryOp(spvOp, returnType, arg0Id, arg1Id, loc);
  7931. }
  7932. // If the vectors are of type Float, we can use OpDot.
  7933. if (returnType->isFloatingType()) {
  7934. return spvBuilder.createBinaryOp(spv::Op::OpDot, returnType, arg0Id, arg1Id,
  7935. loc);
  7936. }
  7937. // Vector component type is Integer (signed or unsigned).
  7938. // Create all instructions necessary to perform a dot product on
  7939. // two integer vectors. SPIR-V OpDot does not support integer vectors.
  7940. // Therefore, we use other SPIR-V instructions (addition and
  7941. // multiplication).
  7942. else {
  7943. SpirvInstruction *result = nullptr;
  7944. llvm::SmallVector<SpirvInstruction *, 4> multIds;
  7945. const spv::Op multSpvOp = translateOp(BO_Mul, arg0Type);
  7946. const spv::Op addSpvOp = translateOp(BO_Add, arg0Type);
  7947. // Extract members from the two vectors and multiply them.
  7948. for (unsigned int i = 0; i < vec0Size; ++i) {
  7949. auto *vec0member = spvBuilder.createCompositeExtract(
  7950. returnType, arg0Id, {i}, arg0->getLocStart());
  7951. auto *vec1member = spvBuilder.createCompositeExtract(
  7952. returnType, arg1Id, {i}, arg1->getLocStart());
  7953. auto *multId = spvBuilder.createBinaryOp(multSpvOp, returnType,
  7954. vec0member, vec1member, loc);
  7955. multIds.push_back(multId);
  7956. }
  7957. // Add all the multiplications.
  7958. result = multIds[0];
  7959. for (unsigned int i = 1; i < vec0Size; ++i) {
  7960. auto *additionId = spvBuilder.createBinaryOp(addSpvOp, returnType, result,
  7961. multIds[i], loc);
  7962. result = additionId;
  7963. }
  7964. return result;
  7965. }
  7966. }
  7967. SpirvInstruction *SpirvEmitter::processIntrinsicRcp(const CallExpr *callExpr) {
  7968. // 'rcp' takes only 1 argument that is a scalar, vector, or matrix of type
  7969. // float or double.
  7970. assert(callExpr->getNumArgs() == 1u);
  7971. const QualType returnType = callExpr->getType();
  7972. const Expr *arg = callExpr->getArg(0);
  7973. auto *argId = doExpr(arg);
  7974. const QualType argType = arg->getType();
  7975. auto loc = callExpr->getLocStart();
  7976. // For cases with matrix argument.
  7977. QualType elemType = {};
  7978. uint32_t numRows = 0, numCols = 0;
  7979. if (isMxNMatrix(argType, &elemType, &numRows, &numCols)) {
  7980. auto *vecOne = getVecValueOne(elemType, numCols);
  7981. const auto actOnEachVec = [this, vecOne, loc](uint32_t /*index*/,
  7982. QualType vecType,
  7983. SpirvInstruction *curRow) {
  7984. return spvBuilder.createBinaryOp(spv::Op::OpFDiv, vecType, vecOne, curRow,
  7985. loc);
  7986. };
  7987. return processEachVectorInMatrix(arg, argId, actOnEachVec, loc);
  7988. }
  7989. // For cases with scalar or vector arguments.
  7990. return spvBuilder.createBinaryOp(spv::Op::OpFDiv, returnType,
  7991. getValueOne(argType), argId, loc);
  7992. }
  7993. SpirvInstruction *
  7994. SpirvEmitter::processIntrinsicAllOrAny(const CallExpr *callExpr,
  7995. spv::Op spvOp) {
  7996. // 'all' and 'any' take only 1 parameter.
  7997. assert(callExpr->getNumArgs() == 1u);
  7998. const QualType returnType = callExpr->getType();
  7999. const Expr *arg = callExpr->getArg(0);
  8000. const QualType argType = arg->getType();
  8001. const auto loc = callExpr->getExprLoc();
  8002. // Handle scalars, vectors of size 1, and 1x1 matrices as arguments.
  8003. // Optimization: can directly cast them to boolean. No need for OpAny/OpAll.
  8004. {
  8005. QualType scalarType = {};
  8006. if (isScalarType(argType, &scalarType) &&
  8007. (scalarType->isBooleanType() || scalarType->isFloatingType() ||
  8008. scalarType->isIntegerType()))
  8009. return castToBool(doExpr(arg), argType, returnType, loc);
  8010. }
  8011. // Handle vectors larger than 1, Mx1 matrices, and 1xN matrices as arguments.
  8012. // Cast the vector to a boolean vector, then run OpAny/OpAll on it.
  8013. {
  8014. QualType elemType = {};
  8015. uint32_t size = 0;
  8016. if (isVectorType(argType, &elemType, &size)) {
  8017. const QualType castToBoolType =
  8018. astContext.getExtVectorType(returnType, size);
  8019. auto *castedToBool =
  8020. castToBool(doExpr(arg), argType, castToBoolType, loc);
  8021. return spvBuilder.createUnaryOp(spvOp, returnType, castedToBool, loc);
  8022. }
  8023. }
  8024. // Handle MxN matrices as arguments.
  8025. {
  8026. QualType elemType = {};
  8027. uint32_t matRowCount = 0, matColCount = 0;
  8028. if (isMxNMatrix(argType, &elemType, &matRowCount, &matColCount)) {
  8029. auto *matrix = doExpr(arg);
  8030. const QualType vecType = getComponentVectorType(astContext, argType);
  8031. llvm::SmallVector<SpirvInstruction *, 4> rowResults;
  8032. for (uint32_t i = 0; i < matRowCount; ++i) {
  8033. // Extract the row which is a float vector of size matColCount.
  8034. auto *rowFloatVec = spvBuilder.createCompositeExtract(
  8035. vecType, matrix, {i}, arg->getLocStart());
  8036. // Cast the float vector to boolean vector.
  8037. const auto rowFloatQualType =
  8038. astContext.getExtVectorType(elemType, matColCount);
  8039. const auto rowBoolQualType =
  8040. astContext.getExtVectorType(returnType, matColCount);
  8041. auto *rowBoolVec = castToBool(rowFloatVec, rowFloatQualType,
  8042. rowBoolQualType, arg->getLocStart());
  8043. // Perform OpAny/OpAll on the boolean vector.
  8044. rowResults.push_back(
  8045. spvBuilder.createUnaryOp(spvOp, returnType, rowBoolVec, loc));
  8046. }
  8047. // Create a new vector that is the concatenation of results of all rows.
  8048. const QualType vecOfBools =
  8049. astContext.getExtVectorType(astContext.BoolTy, matRowCount);
  8050. auto *row =
  8051. spvBuilder.createCompositeConstruct(vecOfBools, rowResults, loc);
  8052. // Run OpAny/OpAll on the newly-created vector.
  8053. return spvBuilder.createUnaryOp(spvOp, returnType, row, loc);
  8054. }
  8055. }
  8056. // All types should be handled already.
  8057. llvm_unreachable("Unknown argument type passed to all()/any().");
  8058. return nullptr;
  8059. }
  8060. SpirvInstruction *
  8061. SpirvEmitter::processIntrinsicAsType(const CallExpr *callExpr) {
  8062. // This function handles 'asint', 'asuint', 'asfloat', and 'asdouble'.
  8063. // Method 1: ret asint(arg)
  8064. // arg component type = {float, uint}
  8065. // arg template type = {scalar, vector, matrix}
  8066. // ret template type = same as arg template type.
  8067. // ret component type = int
  8068. // Method 2: ret asuint(arg)
  8069. // arg component type = {float, int}
  8070. // arg template type = {scalar, vector, matrix}
  8071. // ret template type = same as arg template type.
  8072. // ret component type = uint
  8073. // Method 3: ret asfloat(arg)
  8074. // arg component type = {float, uint, int}
  8075. // arg template type = {scalar, vector, matrix}
  8076. // ret template type = same as arg template type.
  8077. // ret component type = float
  8078. // Method 4: double asdouble(uint lowbits, uint highbits)
  8079. // Method 5: double2 asdouble(uint2 lowbits, uint2 highbits)
  8080. // Method 6:
  8081. // void asuint(
  8082. // in double value,
  8083. // out uint lowbits,
  8084. // out uint highbits
  8085. // );
  8086. const QualType returnType = callExpr->getType();
  8087. const uint32_t numArgs = callExpr->getNumArgs();
  8088. const Expr *arg0 = callExpr->getArg(0);
  8089. const QualType argType = arg0->getType();
  8090. const auto loc = callExpr->getExprLoc();
  8091. // Method 3 return type may be the same as arg type, so it would be a no-op.
  8092. if (isSameType(astContext, returnType, argType))
  8093. return doExpr(arg0);
  8094. switch (numArgs) {
  8095. case 1: {
  8096. // Handling Method 1, 2, and 3.
  8097. auto *argInstr = doExpr(arg0);
  8098. QualType fromElemType = {};
  8099. uint32_t numRows = 0, numCols = 0;
  8100. // For non-matrix arguments (scalar or vector), just do an OpBitCast.
  8101. if (!isMxNMatrix(argType, &fromElemType, &numRows, &numCols)) {
  8102. return spvBuilder.createUnaryOp(spv::Op::OpBitcast, returnType, argInstr,
  8103. loc);
  8104. }
  8105. // Input or output type is a matrix.
  8106. const QualType toElemType = hlsl::GetHLSLMatElementType(returnType);
  8107. llvm::SmallVector<SpirvInstruction *, 4> castedRows;
  8108. const auto fromVecType = astContext.getExtVectorType(fromElemType, numCols);
  8109. const auto toVecType = astContext.getExtVectorType(toElemType, numCols);
  8110. for (uint32_t row = 0; row < numRows; ++row) {
  8111. auto *rowInstr = spvBuilder.createCompositeExtract(
  8112. fromVecType, argInstr, {row}, arg0->getLocStart());
  8113. castedRows.push_back(spvBuilder.createUnaryOp(spv::Op::OpBitcast,
  8114. toVecType, rowInstr, loc));
  8115. }
  8116. return spvBuilder.createCompositeConstruct(returnType, castedRows, loc);
  8117. }
  8118. case 2: {
  8119. auto *lowbits = doExpr(arg0);
  8120. auto *highbits = doExpr(callExpr->getArg(1));
  8121. const auto uintType = astContext.UnsignedIntTy;
  8122. const auto doubleType = astContext.DoubleTy;
  8123. // Handling Method 4
  8124. if (argType->isUnsignedIntegerType()) {
  8125. const auto uintVec2Type = astContext.getExtVectorType(uintType, 2);
  8126. auto *operand = spvBuilder.createCompositeConstruct(
  8127. uintVec2Type, {lowbits, highbits}, loc);
  8128. return spvBuilder.createUnaryOp(spv::Op::OpBitcast, doubleType, operand,
  8129. loc);
  8130. }
  8131. // Handling Method 5
  8132. else {
  8133. const auto uintVec4Type = astContext.getExtVectorType(uintType, 4);
  8134. const auto doubleVec2Type = astContext.getExtVectorType(doubleType, 2);
  8135. auto *operand = spvBuilder.createVectorShuffle(
  8136. uintVec4Type, lowbits, highbits, {0, 2, 1, 3}, loc);
  8137. return spvBuilder.createUnaryOp(spv::Op::OpBitcast, doubleVec2Type,
  8138. operand, loc);
  8139. }
  8140. }
  8141. case 3: {
  8142. // Handling Method 6.
  8143. auto *value = doExpr(arg0);
  8144. auto *lowbits = doExpr(callExpr->getArg(1));
  8145. auto *highbits = doExpr(callExpr->getArg(2));
  8146. const auto uintType = astContext.UnsignedIntTy;
  8147. const auto uintVec2Type = astContext.getExtVectorType(uintType, 2);
  8148. auto *vecResult =
  8149. spvBuilder.createUnaryOp(spv::Op::OpBitcast, uintVec2Type, value, loc);
  8150. spvBuilder.createStore(lowbits,
  8151. spvBuilder.createCompositeExtract(
  8152. uintType, vecResult, {0}, arg0->getLocStart()),
  8153. loc);
  8154. spvBuilder.createStore(highbits,
  8155. spvBuilder.createCompositeExtract(
  8156. uintType, vecResult, {1}, arg0->getLocStart()),
  8157. loc);
  8158. return nullptr;
  8159. }
  8160. default:
  8161. emitError("unrecognized signature for %0 intrinsic function", loc)
  8162. << callExpr->getDirectCallee()->getName();
  8163. return nullptr;
  8164. }
  8165. }
  8166. SpirvInstruction *
  8167. SpirvEmitter::processD3DCOLORtoUBYTE4(const CallExpr *callExpr) {
  8168. // Should take a float4 and return an int4 by doing:
  8169. // int4 result = input.zyxw * 255.001953;
  8170. // Maximum float precision makes the scaling factor 255.002.
  8171. const auto arg = callExpr->getArg(0);
  8172. auto *argId = doExpr(arg);
  8173. const auto argType = arg->getType();
  8174. auto loc = callExpr->getLocStart();
  8175. auto *swizzle =
  8176. spvBuilder.createVectorShuffle(argType, argId, argId, {2, 1, 0, 3}, loc);
  8177. auto *scaled = spvBuilder.createBinaryOp(
  8178. spv::Op::OpVectorTimesScalar, argType, swizzle,
  8179. spvBuilder.getConstantFloat(astContext.FloatTy, llvm::APFloat(255.002f)),
  8180. loc);
  8181. return castToInt(scaled, arg->getType(), callExpr->getType(), loc);
  8182. }
  8183. SpirvInstruction *
  8184. SpirvEmitter::processIntrinsicIsFinite(const CallExpr *callExpr) {
  8185. // Since OpIsFinite needs the Kernel capability, translation is instead done
  8186. // using OpIsNan and OpIsInf:
  8187. // isFinite = !(isNan || isInf)
  8188. const auto arg = doExpr(callExpr->getArg(0));
  8189. const auto returnType = callExpr->getType();
  8190. const auto loc = callExpr->getExprLoc();
  8191. const auto isNan =
  8192. spvBuilder.createUnaryOp(spv::Op::OpIsNan, returnType, arg, loc);
  8193. const auto isInf =
  8194. spvBuilder.createUnaryOp(spv::Op::OpIsInf, returnType, arg, loc);
  8195. const auto isNanOrInf = spvBuilder.createBinaryOp(
  8196. spv::Op::OpLogicalOr, returnType, isNan, isInf, loc);
  8197. return spvBuilder.createUnaryOp(spv::Op::OpLogicalNot, returnType, isNanOrInf,
  8198. loc);
  8199. }
  8200. SpirvInstruction *
  8201. SpirvEmitter::processIntrinsicSinCos(const CallExpr *callExpr) {
  8202. // Since there is no sincos equivalent in SPIR-V, we need to perform Sin
  8203. // once and Cos once. We can reuse existing Sine/Cosine handling functions.
  8204. CallExpr *sincosExpr =
  8205. new (astContext) CallExpr(astContext, Stmt::StmtClass::NoStmtClass, {});
  8206. sincosExpr->setType(callExpr->getArg(0)->getType());
  8207. sincosExpr->setNumArgs(astContext, 1);
  8208. sincosExpr->setArg(0, const_cast<Expr *>(callExpr->getArg(0)));
  8209. const auto srcLoc = callExpr->getExprLoc();
  8210. // Perform Sin and store results in argument 1.
  8211. auto *sin =
  8212. processIntrinsicUsingGLSLInst(sincosExpr, GLSLstd450::GLSLstd450Sin,
  8213. /*actPerRowForMatrices*/ true, srcLoc);
  8214. spvBuilder.createStore(doExpr(callExpr->getArg(1)), sin, srcLoc);
  8215. // Perform Cos and store results in argument 2.
  8216. auto *cos =
  8217. processIntrinsicUsingGLSLInst(sincosExpr, GLSLstd450::GLSLstd450Cos,
  8218. /*actPerRowForMatrices*/ true, srcLoc);
  8219. spvBuilder.createStore(doExpr(callExpr->getArg(2)), cos, srcLoc);
  8220. return nullptr;
  8221. }
  8222. SpirvInstruction *
  8223. SpirvEmitter::processIntrinsicSaturate(const CallExpr *callExpr) {
  8224. const auto *arg = callExpr->getArg(0);
  8225. const auto loc = callExpr->getExprLoc();
  8226. auto *argId = doExpr(arg);
  8227. const auto argType = arg->getType();
  8228. const QualType returnType = callExpr->getType();
  8229. QualType elemType = {};
  8230. uint32_t vecSize = 0;
  8231. if (isScalarType(argType, &elemType)) {
  8232. auto *floatZero = getValueZero(elemType);
  8233. auto *floatOne = getValueOne(elemType);
  8234. return spvBuilder.createGLSLExtInst(returnType,
  8235. GLSLstd450::GLSLstd450FClamp,
  8236. {argId, floatZero, floatOne}, loc);
  8237. }
  8238. if (isVectorType(argType, &elemType, &vecSize)) {
  8239. auto *vecZero = getVecValueZero(elemType, vecSize);
  8240. auto *vecOne = getVecValueOne(elemType, vecSize);
  8241. return spvBuilder.createGLSLExtInst(returnType,
  8242. GLSLstd450::GLSLstd450FClamp,
  8243. {argId, vecZero, vecOne}, loc);
  8244. }
  8245. uint32_t numRows = 0, numCols = 0;
  8246. if (isMxNMatrix(argType, &elemType, &numRows, &numCols)) {
  8247. auto *vecZero = getVecValueZero(elemType, numCols);
  8248. auto *vecOne = getVecValueOne(elemType, numCols);
  8249. const auto actOnEachVec = [this, loc, vecZero,
  8250. vecOne](uint32_t /*index*/, QualType vecType,
  8251. SpirvInstruction *curRow) {
  8252. return spvBuilder.createGLSLExtInst(vecType, GLSLstd450::GLSLstd450FClamp,
  8253. {curRow, vecZero, vecOne}, loc);
  8254. };
  8255. return processEachVectorInMatrix(arg, argId, actOnEachVec, loc);
  8256. }
  8257. emitError("invalid argument type passed to saturate intrinsic function",
  8258. callExpr->getExprLoc());
  8259. return nullptr;
  8260. }
  8261. SpirvInstruction *
  8262. SpirvEmitter::processIntrinsicFloatSign(const CallExpr *callExpr) {
  8263. // Import the GLSL.std.450 extended instruction set.
  8264. const Expr *arg = callExpr->getArg(0);
  8265. const auto loc = callExpr->getExprLoc();
  8266. const QualType returnType = callExpr->getType();
  8267. const QualType argType = arg->getType();
  8268. assert(isFloatOrVecMatOfFloatType(argType));
  8269. auto *argId = doExpr(arg);
  8270. SpirvInstruction *floatSign = nullptr;
  8271. // For matrices, we can perform the instruction on each vector of the matrix.
  8272. if (isMxNMatrix(argType)) {
  8273. const auto actOnEachVec = [this, loc](uint32_t /*index*/, QualType vecType,
  8274. SpirvInstruction *curRow) {
  8275. return spvBuilder.createGLSLExtInst(vecType, GLSLstd450::GLSLstd450FSign,
  8276. {curRow}, loc);
  8277. };
  8278. floatSign = processEachVectorInMatrix(arg, argId, actOnEachVec, loc);
  8279. } else {
  8280. floatSign = spvBuilder.createGLSLExtInst(
  8281. argType, GLSLstd450::GLSLstd450FSign, {argId}, loc);
  8282. }
  8283. return castToInt(floatSign, arg->getType(), returnType, arg->getLocStart());
  8284. }
  8285. SpirvInstruction *
  8286. SpirvEmitter::processIntrinsicF16ToF32(const CallExpr *callExpr) {
  8287. // f16tof32() takes in (vector of) uint and returns (vector of) float.
  8288. // The frontend should guarantee that by inserting implicit casts.
  8289. const QualType f32Type = astContext.FloatTy;
  8290. const QualType u32Type = astContext.UnsignedIntTy;
  8291. const QualType v2f32Type = astContext.getExtVectorType(f32Type, 2);
  8292. const auto loc = callExpr->getExprLoc();
  8293. const auto *arg = callExpr->getArg(0);
  8294. auto *argId = doExpr(arg);
  8295. uint32_t elemCount = {};
  8296. if (isVectorType(arg->getType(), nullptr, &elemCount)) {
  8297. // The input is a vector. We need to handle each element separately.
  8298. llvm::SmallVector<SpirvInstruction *, 4> elements;
  8299. for (uint32_t i = 0; i < elemCount; ++i) {
  8300. auto *srcElem = spvBuilder.createCompositeExtract(u32Type, argId, {i},
  8301. arg->getLocStart());
  8302. auto *convert = spvBuilder.createGLSLExtInst(
  8303. v2f32Type, GLSLstd450::GLSLstd450UnpackHalf2x16, srcElem, loc);
  8304. elements.push_back(
  8305. spvBuilder.createCompositeExtract(f32Type, convert, {0}, loc));
  8306. }
  8307. return spvBuilder.createCompositeConstruct(
  8308. astContext.getExtVectorType(f32Type, elemCount), elements, loc);
  8309. }
  8310. auto *convert = spvBuilder.createGLSLExtInst(
  8311. v2f32Type, GLSLstd450::GLSLstd450UnpackHalf2x16, argId, loc);
  8312. // f16tof32() converts the float16 stored in the low-half of the uint to
  8313. // a float. So just need to return the first component.
  8314. return spvBuilder.createCompositeExtract(f32Type, convert, {0}, loc);
  8315. }
  8316. SpirvInstruction *
  8317. SpirvEmitter::processIntrinsicF32ToF16(const CallExpr *callExpr) {
  8318. // f32tof16() takes in (vector of) float and returns (vector of) uint.
  8319. // The frontend should guarantee that by inserting implicit casts.
  8320. const QualType f32Type = astContext.FloatTy;
  8321. const QualType u32Type = astContext.UnsignedIntTy;
  8322. const QualType v2f32Type = astContext.getExtVectorType(f32Type, 2);
  8323. auto *zero = spvBuilder.getConstantFloat(f32Type, llvm::APFloat(0.0f));
  8324. const auto loc = callExpr->getExprLoc();
  8325. const auto *arg = callExpr->getArg(0);
  8326. auto *argId = doExpr(arg);
  8327. uint32_t elemCount = {};
  8328. if (isVectorType(arg->getType(), nullptr, &elemCount)) {
  8329. // The input is a vector. We need to handle each element separately.
  8330. llvm::SmallVector<SpirvInstruction *, 4> elements;
  8331. for (uint32_t i = 0; i < elemCount; ++i) {
  8332. auto *srcElem = spvBuilder.createCompositeExtract(f32Type, argId, {i},
  8333. arg->getLocStart());
  8334. auto *srcVec =
  8335. spvBuilder.createCompositeConstruct(v2f32Type, {srcElem, zero}, loc);
  8336. elements.push_back(spvBuilder.createGLSLExtInst(
  8337. u32Type, GLSLstd450::GLSLstd450PackHalf2x16, srcVec, loc));
  8338. }
  8339. return spvBuilder.createCompositeConstruct(
  8340. astContext.getExtVectorType(u32Type, elemCount), elements, loc);
  8341. }
  8342. // f16tof32() stores the float into the low-half of the uint. So we need
  8343. // to supply another zero to take the other half.
  8344. auto *srcVec =
  8345. spvBuilder.createCompositeConstruct(v2f32Type, {argId, zero}, loc);
  8346. return spvBuilder.createGLSLExtInst(
  8347. u32Type, GLSLstd450::GLSLstd450PackHalf2x16, srcVec, loc);
  8348. }
  8349. SpirvInstruction *SpirvEmitter::processIntrinsicUsingSpirvInst(
  8350. const CallExpr *callExpr, spv::Op opcode, bool actPerRowForMatrices) {
  8351. // Certain opcodes are only allowed in pixel shader
  8352. if (!spvContext.isPS())
  8353. switch (opcode) {
  8354. case spv::Op::OpDPdx:
  8355. case spv::Op::OpDPdy:
  8356. case spv::Op::OpDPdxFine:
  8357. case spv::Op::OpDPdyFine:
  8358. case spv::Op::OpDPdxCoarse:
  8359. case spv::Op::OpDPdyCoarse:
  8360. case spv::Op::OpFwidth:
  8361. case spv::Op::OpFwidthFine:
  8362. case spv::Op::OpFwidthCoarse:
  8363. needsLegalization = true;
  8364. break;
  8365. default:
  8366. // Only the given opcodes need legalization. Anything else should preserve
  8367. // previous.
  8368. break;
  8369. }
  8370. const auto loc = callExpr->getExprLoc();
  8371. const QualType returnType = callExpr->getType();
  8372. if (callExpr->getNumArgs() == 1u) {
  8373. const Expr *arg = callExpr->getArg(0);
  8374. auto *argId = doExpr(arg);
  8375. // If the instruction does not operate on matrices, we can perform the
  8376. // instruction on each vector of the matrix.
  8377. if (actPerRowForMatrices && isMxNMatrix(arg->getType())) {
  8378. const auto actOnEachVec = [this, opcode, loc](uint32_t /*index*/,
  8379. QualType vecType,
  8380. SpirvInstruction *curRow) {
  8381. return spvBuilder.createUnaryOp(opcode, vecType, curRow, loc);
  8382. };
  8383. return processEachVectorInMatrix(arg, argId, actOnEachVec, loc);
  8384. }
  8385. return spvBuilder.createUnaryOp(opcode, returnType, argId, loc);
  8386. } else if (callExpr->getNumArgs() == 2u) {
  8387. const Expr *arg0 = callExpr->getArg(0);
  8388. auto *arg0Id = doExpr(arg0);
  8389. auto *arg1Id = doExpr(callExpr->getArg(1));
  8390. const auto arg1Loc = callExpr->getArg(1)->getLocStart();
  8391. // If the instruction does not operate on matrices, we can perform the
  8392. // instruction on each vector of the matrix.
  8393. if (actPerRowForMatrices && isMxNMatrix(arg0->getType())) {
  8394. const auto actOnEachVec = [this, opcode, arg1Id, loc,
  8395. arg1Loc](uint32_t index, QualType vecType,
  8396. SpirvInstruction *arg0Row) {
  8397. auto *arg1Row = spvBuilder.createCompositeExtract(vecType, arg1Id,
  8398. {index}, arg1Loc);
  8399. return spvBuilder.createBinaryOp(opcode, vecType, arg0Row, arg1Row,
  8400. loc);
  8401. };
  8402. return processEachVectorInMatrix(arg0, arg0Id, actOnEachVec, loc);
  8403. }
  8404. return spvBuilder.createBinaryOp(opcode, returnType, arg0Id, arg1Id, loc);
  8405. }
  8406. emitError("unsupported %0 intrinsic function", loc)
  8407. << cast<DeclRefExpr>(callExpr->getCallee())->getNameInfo().getAsString();
  8408. return nullptr;
  8409. }
  8410. SpirvInstruction *SpirvEmitter::processIntrinsicUsingGLSLInst(
  8411. const CallExpr *callExpr, GLSLstd450 opcode, bool actPerRowForMatrices,
  8412. SourceLocation loc) {
  8413. // Import the GLSL.std.450 extended instruction set.
  8414. const QualType returnType = callExpr->getType();
  8415. if (callExpr->getNumArgs() == 1u) {
  8416. const Expr *arg = callExpr->getArg(0);
  8417. auto *argInstr = doExpr(arg);
  8418. // If the instruction does not operate on matrices, we can perform the
  8419. // instruction on each vector of the matrix.
  8420. if (actPerRowForMatrices && isMxNMatrix(arg->getType())) {
  8421. const auto actOnEachVec = [this, loc,
  8422. opcode](uint32_t /*index*/, QualType vecType,
  8423. SpirvInstruction *curRowInstr) {
  8424. return spvBuilder.createGLSLExtInst(vecType, opcode, {curRowInstr},
  8425. loc);
  8426. };
  8427. return processEachVectorInMatrix(arg, argInstr, actOnEachVec, loc);
  8428. }
  8429. return spvBuilder.createGLSLExtInst(returnType, opcode, {argInstr}, loc);
  8430. } else if (callExpr->getNumArgs() == 2u) {
  8431. const Expr *arg0 = callExpr->getArg(0);
  8432. auto *arg0Instr = doExpr(arg0);
  8433. auto *arg1Instr = doExpr(callExpr->getArg(1));
  8434. const auto arg1Loc = callExpr->getArg(1)->getLocStart();
  8435. // If the instruction does not operate on matrices, we can perform the
  8436. // instruction on each vector of the matrix.
  8437. if (actPerRowForMatrices && isMxNMatrix(arg0->getType())) {
  8438. const auto actOnEachVec = [this, loc, opcode, arg1Instr,
  8439. arg1Loc](uint32_t index, QualType vecType,
  8440. SpirvInstruction *arg0RowInstr) {
  8441. auto *arg1RowInstr = spvBuilder.createCompositeExtract(
  8442. vecType, arg1Instr, {index}, arg1Loc);
  8443. return spvBuilder.createGLSLExtInst(vecType, opcode,
  8444. {arg0RowInstr, arg1RowInstr}, loc);
  8445. };
  8446. return processEachVectorInMatrix(arg0, arg0Instr, actOnEachVec, loc);
  8447. }
  8448. return spvBuilder.createGLSLExtInst(returnType, opcode,
  8449. {arg0Instr, arg1Instr}, loc);
  8450. } else if (callExpr->getNumArgs() == 3u) {
  8451. const Expr *arg0 = callExpr->getArg(0);
  8452. auto *arg0Instr = doExpr(arg0);
  8453. auto *arg1Instr = doExpr(callExpr->getArg(1));
  8454. auto *arg2Instr = doExpr(callExpr->getArg(2));
  8455. auto arg1Loc = callExpr->getArg(1)->getLocStart();
  8456. auto arg2Loc = callExpr->getArg(2)->getLocStart();
  8457. // If the instruction does not operate on matrices, we can perform the
  8458. // instruction on each vector of the matrix.
  8459. if (actPerRowForMatrices && isMxNMatrix(arg0->getType())) {
  8460. const auto actOnEachVec = [this, loc, opcode, arg1Instr, arg2Instr,
  8461. arg1Loc,
  8462. arg2Loc](uint32_t index, QualType vecType,
  8463. SpirvInstruction *arg0RowInstr) {
  8464. auto *arg1RowInstr = spvBuilder.createCompositeExtract(
  8465. vecType, arg1Instr, {index}, arg1Loc);
  8466. auto *arg2RowInstr = spvBuilder.createCompositeExtract(
  8467. vecType, arg2Instr, {index}, arg2Loc);
  8468. return spvBuilder.createGLSLExtInst(
  8469. vecType, opcode, {arg0RowInstr, arg1RowInstr, arg2RowInstr}, loc);
  8470. };
  8471. return processEachVectorInMatrix(arg0, arg0Instr, actOnEachVec, loc);
  8472. }
  8473. return spvBuilder.createGLSLExtInst(returnType, opcode,
  8474. {arg0Instr, arg1Instr, arg2Instr}, loc);
  8475. }
  8476. emitError("unsupported %0 intrinsic function", callExpr->getExprLoc())
  8477. << cast<DeclRefExpr>(callExpr->getCallee())->getNameInfo().getAsString();
  8478. return nullptr;
  8479. }
  8480. SpirvInstruction *
  8481. SpirvEmitter::processIntrinsicLog10(const CallExpr *callExpr) {
  8482. // Since there is no log10 instruction in SPIR-V, we can use:
  8483. // log10(x) = log2(x) * ( 1 / log2(10) )
  8484. // 1 / log2(10) = 0.30103
  8485. auto loc = callExpr->getExprLoc();
  8486. auto *scale =
  8487. spvBuilder.getConstantFloat(astContext.FloatTy, llvm::APFloat(0.30103f));
  8488. auto *log2 = processIntrinsicUsingGLSLInst(
  8489. callExpr, GLSLstd450::GLSLstd450Log2, true, loc);
  8490. const auto returnType = callExpr->getType();
  8491. spv::Op scaleOp = isScalarType(returnType)
  8492. ? spv::Op::OpFMul
  8493. : isVectorType(returnType)
  8494. ? spv::Op::OpVectorTimesScalar
  8495. : spv::Op::OpMatrixTimesScalar;
  8496. return spvBuilder.createBinaryOp(scaleOp, returnType, log2, scale, loc);
  8497. }
  8498. SpirvInstruction *SpirvEmitter::processRayBuiltins(const CallExpr *callExpr,
  8499. hlsl::IntrinsicOp op) {
  8500. spv::BuiltIn builtin = spv::BuiltIn::Max;
  8501. bool transposeMatrix = false;
  8502. const auto loc = callExpr->getExprLoc();
  8503. switch (op) {
  8504. case hlsl::IntrinsicOp::IOP_DispatchRaysDimensions:
  8505. builtin = spv::BuiltIn::LaunchSizeNV;
  8506. break;
  8507. case hlsl::IntrinsicOp::IOP_DispatchRaysIndex:
  8508. builtin = spv::BuiltIn::LaunchIdNV;
  8509. break;
  8510. case hlsl::IntrinsicOp::IOP_RayTCurrent:
  8511. builtin = spv::BuiltIn::HitTNV;
  8512. break;
  8513. case hlsl::IntrinsicOp::IOP_RayTMin:
  8514. builtin = spv::BuiltIn::RayTminNV;
  8515. break;
  8516. case hlsl::IntrinsicOp::IOP_HitKind:
  8517. builtin = spv::BuiltIn::HitKindNV;
  8518. break;
  8519. case hlsl::IntrinsicOp::IOP_WorldRayDirection:
  8520. builtin = spv::BuiltIn::WorldRayDirectionNV;
  8521. break;
  8522. case hlsl::IntrinsicOp::IOP_WorldRayOrigin:
  8523. builtin = spv::BuiltIn::WorldRayOriginNV;
  8524. break;
  8525. case hlsl::IntrinsicOp::IOP_ObjectRayDirection:
  8526. builtin = spv::BuiltIn::ObjectRayDirectionNV;
  8527. break;
  8528. case hlsl::IntrinsicOp::IOP_ObjectRayOrigin:
  8529. builtin = spv::BuiltIn::ObjectRayOriginNV;
  8530. break;
  8531. case hlsl::IntrinsicOp::IOP_GeometryIndex:
  8532. featureManager.requestExtension(Extension::KHR_ray_tracing,
  8533. "GeometryIndex()", loc);
  8534. builtin = spv::BuiltIn::RayGeometryIndexKHR;
  8535. break;
  8536. case hlsl::IntrinsicOp::IOP_InstanceIndex:
  8537. builtin = spv::BuiltIn::InstanceId;
  8538. break;
  8539. case hlsl::IntrinsicOp::IOP_PrimitiveIndex:
  8540. builtin = spv::BuiltIn::PrimitiveId;
  8541. break;
  8542. case hlsl::IntrinsicOp::IOP_InstanceID:
  8543. builtin = spv::BuiltIn::InstanceCustomIndexNV;
  8544. break;
  8545. case hlsl::IntrinsicOp::IOP_RayFlags:
  8546. builtin = spv::BuiltIn::IncomingRayFlagsNV;
  8547. break;
  8548. case hlsl::IntrinsicOp::IOP_ObjectToWorld3x4:
  8549. transposeMatrix = true;
  8550. case hlsl::IntrinsicOp::IOP_ObjectToWorld4x3:
  8551. builtin = spv::BuiltIn::ObjectToWorldNV;
  8552. break;
  8553. case hlsl::IntrinsicOp::IOP_WorldToObject3x4:
  8554. transposeMatrix = true;
  8555. case hlsl::IntrinsicOp::IOP_WorldToObject4x3:
  8556. builtin = spv::BuiltIn::WorldToObjectNV;
  8557. break;
  8558. default:
  8559. emitError("ray intrinsic function unimplemented", loc);
  8560. return nullptr;
  8561. }
  8562. QualType builtinType = callExpr->getType();
  8563. if (transposeMatrix) {
  8564. // DXR defines ObjectToWorld3x4, WorldToObject3x4 as transposed matrices.
  8565. // SPIR-V has only non tranposed variant defined as a builtin
  8566. // So perform read of original non transposed builtin and perform transpose.
  8567. assert(hlsl::IsHLSLMatType(builtinType) && "Builtin should be matrix");
  8568. const clang::Type *type = builtinType.getCanonicalType().getTypePtr();
  8569. const RecordType *RT = cast<RecordType>(type);
  8570. const ClassTemplateSpecializationDecl *templateSpecDecl =
  8571. cast<ClassTemplateSpecializationDecl>(RT->getDecl());
  8572. ClassTemplateDecl *templateDecl =
  8573. templateSpecDecl->getSpecializedTemplate();
  8574. builtinType = getHLSLMatrixType(astContext, theCompilerInstance.getSema(),
  8575. templateDecl, astContext.FloatTy, 4, 3);
  8576. }
  8577. SpirvInstruction *retVal =
  8578. declIdMapper.getBuiltinVar(builtin, builtinType, loc);
  8579. retVal = spvBuilder.createLoad(builtinType, retVal, loc);
  8580. if (transposeMatrix)
  8581. retVal = spvBuilder.createUnaryOp(spv::Op::OpTranspose, callExpr->getType(),
  8582. retVal, loc);
  8583. return retVal;
  8584. }
  8585. SpirvInstruction *SpirvEmitter::processReportHit(const CallExpr *callExpr) {
  8586. SpirvInstruction *hitAttributeStageVar = nullptr;
  8587. const VarDecl *hitAttributeArg = nullptr;
  8588. QualType hitAttributeType;
  8589. const auto args = callExpr->getArgs();
  8590. if (callExpr->getNumArgs() != 3) {
  8591. emitError("invalid number of arguments to ReportHit",
  8592. callExpr->getExprLoc());
  8593. }
  8594. // HLSL Function :
  8595. // template<typename hitAttr>
  8596. // ReportHit(in float, in uint, in hitAttr)
  8597. if (const auto *implCastExpr = dyn_cast<CastExpr>(callExpr->getArg(2))) {
  8598. if (const auto *arg = dyn_cast<DeclRefExpr>(implCastExpr->getSubExpr())) {
  8599. if (const auto *varDecl = dyn_cast<VarDecl>(arg->getDecl())) {
  8600. hitAttributeType = varDecl->getType();
  8601. hitAttributeArg = varDecl;
  8602. // Check if same type of hit attribute stage variable was already
  8603. // created, if so re-use
  8604. const auto iter = hitAttributeMap.find(hitAttributeType);
  8605. if (iter == hitAttributeMap.end()) {
  8606. hitAttributeStageVar = declIdMapper.createRayTracingNVStageVar(
  8607. spv::StorageClass::HitAttributeNV, varDecl);
  8608. hitAttributeMap[hitAttributeType] = hitAttributeStageVar;
  8609. } else {
  8610. hitAttributeStageVar = iter->second;
  8611. }
  8612. }
  8613. }
  8614. }
  8615. assert(hitAttributeStageVar && hitAttributeArg);
  8616. // Copy argument to stage variable
  8617. const auto hitAttributeArgInst =
  8618. declIdMapper.getDeclEvalInfo(hitAttributeArg, callExpr->getExprLoc());
  8619. auto tempLoad =
  8620. spvBuilder.createLoad(hitAttributeArg->getType(), hitAttributeArgInst,
  8621. hitAttributeArg->getLocStart());
  8622. spvBuilder.createStore(hitAttributeStageVar, tempLoad,
  8623. callExpr->getExprLoc());
  8624. // SPIR-V Instruction :
  8625. // bool OpReportIntersection(<id> float Hit, <id> uint HitKind)
  8626. llvm::SmallVector<SpirvInstruction *, 4> reportHitArgs;
  8627. reportHitArgs.push_back(doExpr(args[0])); // Hit
  8628. reportHitArgs.push_back(doExpr(args[1])); // HitKind
  8629. return spvBuilder.createRayTracingOpsNV(spv::Op::OpReportIntersectionNV,
  8630. astContext.BoolTy, reportHitArgs,
  8631. callExpr->getExprLoc());
  8632. }
  8633. void SpirvEmitter::processCallShader(const CallExpr *callExpr) {
  8634. SpirvInstruction *callDataLocInst = nullptr;
  8635. SpirvInstruction *callDataStageVar = nullptr;
  8636. const VarDecl *callDataArg = nullptr;
  8637. QualType callDataType;
  8638. const auto args = callExpr->getArgs();
  8639. if (callExpr->getNumArgs() != 2) {
  8640. emitError("invalid number of arguments to CallShader",
  8641. callExpr->getExprLoc());
  8642. }
  8643. // HLSL Func :
  8644. // template<typename CallData>
  8645. // void CallShader(in int sbtIndex, inout CallData arg)
  8646. if (const auto *implCastExpr = dyn_cast<CastExpr>(args[1])) {
  8647. if (const auto *arg = dyn_cast<DeclRefExpr>(implCastExpr->getSubExpr())) {
  8648. if (const auto *varDecl = dyn_cast<VarDecl>(arg->getDecl())) {
  8649. callDataType = varDecl->getType();
  8650. callDataArg = varDecl;
  8651. // Check if same type of callable data stage variable was already
  8652. // created, if so re-use
  8653. const auto callDataPair = callDataMap.find(callDataType);
  8654. if (callDataPair == callDataMap.end()) {
  8655. int numCallDataVars = callDataMap.size();
  8656. callDataStageVar = declIdMapper.createRayTracingNVStageVar(
  8657. spv::StorageClass::CallableDataNV, varDecl);
  8658. // Decorate unique location id for each created stage var
  8659. spvBuilder.decorateLocation(callDataStageVar, numCallDataVars);
  8660. callDataLocInst = spvBuilder.getConstantInt(
  8661. astContext.UnsignedIntTy, llvm::APInt(32, numCallDataVars));
  8662. callDataMap[callDataType] =
  8663. std::make_pair(callDataStageVar, callDataLocInst);
  8664. } else {
  8665. callDataStageVar = callDataPair->second.first;
  8666. callDataLocInst = callDataPair->second.second;
  8667. }
  8668. }
  8669. }
  8670. }
  8671. assert(callDataStageVar && callDataArg);
  8672. // Copy argument to stage variable
  8673. const auto callDataArgInst =
  8674. declIdMapper.getDeclEvalInfo(callDataArg, callExpr->getExprLoc());
  8675. auto tempLoad = spvBuilder.createLoad(callDataArg->getType(), callDataArgInst,
  8676. callDataArg->getLocStart());
  8677. spvBuilder.createStore(callDataStageVar, tempLoad, callExpr->getExprLoc());
  8678. // SPIR-V Instruction
  8679. // void OpExecuteCallable(<id> int SBT Index, <id> uint Callable Data Location
  8680. // Id)
  8681. llvm::SmallVector<SpirvInstruction *, 2> callShaderArgs;
  8682. callShaderArgs.push_back(doExpr(args[0]));
  8683. callShaderArgs.push_back(callDataLocInst);
  8684. spvBuilder.createRayTracingOpsNV(spv::Op::OpExecuteCallableNV, QualType(),
  8685. callShaderArgs, callExpr->getExprLoc());
  8686. // Copy data back to argument
  8687. tempLoad = spvBuilder.createLoad(callDataArg->getType(), callDataStageVar,
  8688. callDataArg->getLocStart());
  8689. spvBuilder.createStore(callDataArgInst, tempLoad, callExpr->getExprLoc());
  8690. return;
  8691. }
  8692. void SpirvEmitter::processTraceRay(const CallExpr *callExpr) {
  8693. SpirvInstruction *rayPayloadLocInst = nullptr;
  8694. SpirvInstruction *rayPayloadStageVar = nullptr;
  8695. const VarDecl *rayPayloadArg = nullptr;
  8696. QualType rayPayloadType;
  8697. const auto args = callExpr->getArgs();
  8698. if (callExpr->getNumArgs() != 8) {
  8699. emitError("invalid number of arguments to TraceRay",
  8700. callExpr->getExprLoc());
  8701. }
  8702. // HLSL Func
  8703. // template<typename RayPayload>
  8704. // void TraceRay(RaytracingAccelerationStructure rs,
  8705. // uint rayflags,
  8706. // uint InstanceInclusionMask
  8707. // uint RayContributionToHitGroupIndex,
  8708. // uint MultiplierForGeometryContributionToHitGroupIndex,
  8709. // uint MissShaderIndex,
  8710. // RayDesc ray,
  8711. // inout RayPayload p)
  8712. // where RayDesc = {float3 origin, float tMin, float3 direction, float tMax}
  8713. if (const auto *implCastExpr = dyn_cast<CastExpr>(args[7])) {
  8714. if (const auto *arg = dyn_cast<DeclRefExpr>(implCastExpr->getSubExpr())) {
  8715. if (const auto *varDecl = dyn_cast<VarDecl>(arg->getDecl())) {
  8716. rayPayloadType = varDecl->getType();
  8717. rayPayloadArg = varDecl;
  8718. const auto rayPayloadPair = rayPayloadMap.find(rayPayloadType);
  8719. // Check if same type of rayPayload stage variable was already
  8720. // created, if so re-use
  8721. if (rayPayloadPair == rayPayloadMap.end()) {
  8722. int numPayloadVars = rayPayloadMap.size();
  8723. rayPayloadStageVar = declIdMapper.createRayTracingNVStageVar(
  8724. spv::StorageClass::RayPayloadNV, varDecl);
  8725. // Decorate unique location id for each created stage var
  8726. spvBuilder.decorateLocation(rayPayloadStageVar, numPayloadVars);
  8727. rayPayloadLocInst = spvBuilder.getConstantInt(
  8728. astContext.UnsignedIntTy, llvm::APInt(32, numPayloadVars));
  8729. rayPayloadMap[rayPayloadType] =
  8730. std::make_pair(rayPayloadStageVar, rayPayloadLocInst);
  8731. } else {
  8732. rayPayloadStageVar = rayPayloadPair->second.first;
  8733. rayPayloadLocInst = rayPayloadPair->second.second;
  8734. }
  8735. }
  8736. }
  8737. }
  8738. assert(rayPayloadStageVar && rayPayloadArg);
  8739. const auto floatType = astContext.FloatTy;
  8740. const auto vecType = astContext.getExtVectorType(astContext.FloatTy, 3);
  8741. // Extract the ray description to match SPIR-V
  8742. SpirvInstruction *rayDescArg = doExpr(args[6]);
  8743. const auto loc = args[6]->getLocStart();
  8744. const auto origin =
  8745. spvBuilder.createCompositeExtract(vecType, rayDescArg, {0}, loc);
  8746. const auto tMin =
  8747. spvBuilder.createCompositeExtract(floatType, rayDescArg, {1}, loc);
  8748. const auto direction =
  8749. spvBuilder.createCompositeExtract(vecType, rayDescArg, {2}, loc);
  8750. const auto tMax =
  8751. spvBuilder.createCompositeExtract(floatType, rayDescArg, {3}, loc);
  8752. // Copy argument to stage variable
  8753. const auto rayPayloadArgInst =
  8754. declIdMapper.getDeclEvalInfo(rayPayloadArg, rayPayloadArg->getLocStart());
  8755. auto tempLoad =
  8756. spvBuilder.createLoad(rayPayloadArg->getType(), rayPayloadArgInst,
  8757. rayPayloadArg->getLocStart());
  8758. spvBuilder.createStore(rayPayloadStageVar, tempLoad, callExpr->getExprLoc());
  8759. // SPIR-V Instruction
  8760. // void OpTraceNV ( <id> AccelerationStructureNV acStruct,
  8761. // <id> uint Ray Flags,
  8762. // <id> uint Cull Mask,
  8763. // <id> uint SBT Offset,
  8764. // <id> uint SBT Stride,
  8765. // <id> uint Miss Index,
  8766. // <id> vec4 Ray Origin,
  8767. // <id> float Ray Tmin,
  8768. // <id> vec3 Ray Direction,
  8769. // <id> float Ray Tmax,
  8770. // <id> uint RayPayload number)
  8771. llvm::SmallVector<SpirvInstruction *, 8> traceArgs;
  8772. for (int ii = 0; ii < 6; ii++) {
  8773. traceArgs.push_back(doExpr(args[ii]));
  8774. }
  8775. traceArgs.push_back(origin);
  8776. traceArgs.push_back(tMin);
  8777. traceArgs.push_back(direction);
  8778. traceArgs.push_back(tMax);
  8779. traceArgs.push_back(rayPayloadLocInst);
  8780. spvBuilder.createRayTracingOpsNV(spv::Op::OpTraceNV, QualType(), traceArgs,
  8781. callExpr->getExprLoc());
  8782. // Copy arguments back to stage variable
  8783. tempLoad = spvBuilder.createLoad(rayPayloadArg->getType(), rayPayloadStageVar,
  8784. rayPayloadArg->getLocStart());
  8785. spvBuilder.createStore(rayPayloadArgInst, tempLoad, callExpr->getExprLoc());
  8786. return;
  8787. }
  8788. void SpirvEmitter::processDispatchMesh(const CallExpr *callExpr) {
  8789. // HLSL Func - void DispatchMesh(uint ThreadGroupCountX,
  8790. // uint ThreadGroupCountY,
  8791. // uint ThreadGroupCountZ,
  8792. // groupshared <structType> MeshPayload);
  8793. assert(callExpr->getNumArgs() == 4);
  8794. const auto args = callExpr->getArgs();
  8795. const auto loc = callExpr->getExprLoc();
  8796. // 1) create a barrier GroupMemoryBarrierWithGroupSync().
  8797. processIntrinsicMemoryBarrier(callExpr,
  8798. /*isDevice*/ false,
  8799. /*groupSync*/ true,
  8800. /*isAllBarrier*/ false);
  8801. // 2) set TaskCountNV = threadX * threadY * threadZ.
  8802. auto *threadX = doExpr(args[0]);
  8803. auto *threadY = doExpr(args[1]);
  8804. auto *threadZ = doExpr(args[2]);
  8805. auto *var = declIdMapper.getBuiltinVar(spv::BuiltIn::TaskCountNV,
  8806. astContext.UnsignedIntTy, loc);
  8807. auto *taskCount = spvBuilder.createBinaryOp(
  8808. spv::Op::OpIMul, astContext.UnsignedIntTy, threadX,
  8809. spvBuilder.createBinaryOp(spv::Op::OpIMul, astContext.UnsignedIntTy,
  8810. threadY, threadZ, loc),
  8811. loc);
  8812. spvBuilder.createStore(var, taskCount, loc);
  8813. // 3) create PerTaskNV out attribute block and store MeshPayload info.
  8814. const auto *sigPoint =
  8815. hlsl::SigPoint::GetSigPoint(hlsl::DXIL::SigPointKind::MSOut);
  8816. spv::StorageClass sc = spv::StorageClass::Output;
  8817. auto *payloadArg = doExpr(args[3]);
  8818. bool isValid = false;
  8819. if (const auto *implCastExpr = dyn_cast<CastExpr>(args[3])) {
  8820. if (const auto *arg = dyn_cast<DeclRefExpr>(implCastExpr->getSubExpr())) {
  8821. if (const auto *paramDecl = dyn_cast<VarDecl>(arg->getDecl())) {
  8822. if (paramDecl->hasAttr<HLSLGroupSharedAttr>()) {
  8823. isValid = declIdMapper.createPayloadStageVars(
  8824. sigPoint, sc, paramDecl, /*asInput=*/false, paramDecl->getType(),
  8825. "out.var", &payloadArg);
  8826. }
  8827. }
  8828. }
  8829. }
  8830. if (!isValid) {
  8831. emitError("expected groupshared object as argument to DispatchMesh()",
  8832. args[3]->getExprLoc());
  8833. }
  8834. }
  8835. void SpirvEmitter::processMeshOutputCounts(const CallExpr *callExpr) {
  8836. // HLSL Func - void SetMeshOutputCounts(uint numVertices, uint numPrimitives);
  8837. assert(callExpr->getNumArgs() == 2);
  8838. const auto args = callExpr->getArgs();
  8839. const auto loc = callExpr->getExprLoc();
  8840. auto *var = declIdMapper.getBuiltinVar(spv::BuiltIn::PrimitiveCountNV,
  8841. astContext.UnsignedIntTy, loc);
  8842. spvBuilder.createStore(var, doExpr(args[1]), loc);
  8843. }
  8844. SpirvConstant *SpirvEmitter::getValueZero(QualType type) {
  8845. {
  8846. QualType scalarType = {};
  8847. if (isScalarType(type, &scalarType)) {
  8848. if (scalarType->isBooleanType()) {
  8849. return spvBuilder.getConstantBool(false);
  8850. }
  8851. if (scalarType->isIntegerType()) {
  8852. return spvBuilder.getConstantInt(scalarType, llvm::APInt(32, 0));
  8853. }
  8854. if (scalarType->isFloatingType()) {
  8855. return spvBuilder.getConstantFloat(scalarType, llvm::APFloat(0.0f));
  8856. }
  8857. }
  8858. }
  8859. {
  8860. QualType elemType = {};
  8861. uint32_t size = {};
  8862. if (isVectorType(type, &elemType, &size)) {
  8863. return getVecValueZero(elemType, size);
  8864. }
  8865. }
  8866. {
  8867. QualType elemType = {};
  8868. uint32_t rowCount = 0, colCount = 0;
  8869. if (isMxNMatrix(type, &elemType, &rowCount, &colCount)) {
  8870. auto *row = getVecValueZero(elemType, colCount);
  8871. llvm::SmallVector<SpirvConstant *, 4> rows((size_t)rowCount, row);
  8872. return spvBuilder.getConstantComposite(type, rows);
  8873. }
  8874. }
  8875. emitError("getting value 0 for type %0 unimplemented", {})
  8876. << type.getAsString();
  8877. return nullptr;
  8878. }
  8879. SpirvConstant *SpirvEmitter::getVecValueZero(QualType elemType, uint32_t size) {
  8880. auto *elemZeroId = getValueZero(elemType);
  8881. if (size == 1)
  8882. return elemZeroId;
  8883. llvm::SmallVector<SpirvConstant *, 4> elements(size_t(size), elemZeroId);
  8884. const QualType vecType = astContext.getExtVectorType(elemType, size);
  8885. return spvBuilder.getConstantComposite(vecType, elements);
  8886. }
  8887. SpirvConstant *SpirvEmitter::getValueOne(QualType type) {
  8888. {
  8889. QualType scalarType = {};
  8890. if (isScalarType(type, &scalarType)) {
  8891. if (scalarType->isBooleanType()) {
  8892. return spvBuilder.getConstantBool(true);
  8893. }
  8894. if (scalarType->isIntegerType()) {
  8895. return spvBuilder.getConstantInt(scalarType, llvm::APInt(32, 1));
  8896. }
  8897. if (scalarType->isFloatingType()) {
  8898. return spvBuilder.getConstantFloat(scalarType, llvm::APFloat(1.0f));
  8899. }
  8900. }
  8901. }
  8902. {
  8903. QualType elemType = {};
  8904. uint32_t size = {};
  8905. if (isVectorType(type, &elemType, &size)) {
  8906. return getVecValueOne(elemType, size);
  8907. }
  8908. }
  8909. emitError("getting value 1 for type %0 unimplemented", {}) << type;
  8910. return 0;
  8911. }
  8912. SpirvConstant *SpirvEmitter::getVecValueOne(QualType elemType, uint32_t size) {
  8913. auto *elemOne = getValueOne(elemType);
  8914. if (size == 1)
  8915. return elemOne;
  8916. llvm::SmallVector<SpirvConstant *, 4> elements(size_t(size), elemOne);
  8917. const QualType vecType = astContext.getExtVectorType(elemType, size);
  8918. return spvBuilder.getConstantComposite(vecType, elements);
  8919. }
  8920. SpirvConstant *SpirvEmitter::getMatElemValueOne(QualType type) {
  8921. assert(hlsl::IsHLSLMatType(type));
  8922. const auto elemType = hlsl::GetHLSLMatElementType(type);
  8923. uint32_t rowCount = 0, colCount = 0;
  8924. hlsl::GetHLSLMatRowColCount(type, rowCount, colCount);
  8925. if (rowCount == 1 && colCount == 1)
  8926. return getValueOne(elemType);
  8927. if (colCount == 1)
  8928. return getVecValueOne(elemType, rowCount);
  8929. return getVecValueOne(elemType, colCount);
  8930. }
  8931. SpirvConstant *SpirvEmitter::getMaskForBitwidthValue(QualType type) {
  8932. QualType elemType = {};
  8933. uint32_t count = 1;
  8934. if (isScalarType(type, &elemType) || isVectorType(type, &elemType, &count)) {
  8935. const auto bitwidth = getElementSpirvBitwidth(
  8936. astContext, elemType, spirvOptions.enable16BitTypes);
  8937. SpirvConstant *mask = spvBuilder.getConstantInt(
  8938. elemType,
  8939. llvm::APInt(bitwidth, bitwidth - 1, elemType->isSignedIntegerType()));
  8940. if (count == 1)
  8941. return mask;
  8942. const QualType resultType = astContext.getExtVectorType(elemType, count);
  8943. llvm::SmallVector<SpirvConstant *, 4> elements(size_t(count), mask);
  8944. return spvBuilder.getConstantComposite(resultType, elements);
  8945. }
  8946. assert(false && "this method only supports scalars and vectors");
  8947. return nullptr;
  8948. }
  8949. SpirvConstant *SpirvEmitter::translateAPValue(const APValue &value,
  8950. const QualType targetType) {
  8951. SpirvConstant *result = nullptr;
  8952. if (targetType->isBooleanType()) {
  8953. result = spvBuilder.getConstantBool(value.getInt().getBoolValue(),
  8954. isSpecConstantMode);
  8955. } else if (targetType->isIntegerType()) {
  8956. result = translateAPInt(value.getInt(), targetType);
  8957. } else if (targetType->isFloatingType()) {
  8958. result = translateAPFloat(value.getFloat(), targetType);
  8959. } else if (hlsl::IsHLSLVecType(targetType)) {
  8960. const QualType elemType = hlsl::GetHLSLVecElementType(targetType);
  8961. const auto numElements = value.getVectorLength();
  8962. // Special case for vectors of size 1. SPIR-V doesn't support this vector
  8963. // size so we need to translate it to scalar values.
  8964. if (numElements == 1) {
  8965. result = translateAPValue(value.getVectorElt(0), elemType);
  8966. } else {
  8967. llvm::SmallVector<SpirvConstant *, 4> elements;
  8968. for (uint32_t i = 0; i < numElements; ++i) {
  8969. elements.push_back(translateAPValue(value.getVectorElt(i), elemType));
  8970. }
  8971. result = spvBuilder.getConstantComposite(targetType, elements);
  8972. }
  8973. }
  8974. if (result)
  8975. return result;
  8976. emitError("APValue of type %0 unimplemented", {}) << value.getKind();
  8977. value.dump();
  8978. return 0;
  8979. }
  8980. SpirvConstant *SpirvEmitter::translateAPInt(const llvm::APInt &intValue,
  8981. QualType targetType) {
  8982. return spvBuilder.getConstantInt(targetType, intValue, isSpecConstantMode);
  8983. }
  8984. bool SpirvEmitter::isLiteralLargerThan32Bits(const Expr *expr) {
  8985. if (const auto *intLiteral = dyn_cast<IntegerLiteral>(expr)) {
  8986. const bool isSigned = expr->getType()->isSignedIntegerType();
  8987. const llvm::APInt &value = intLiteral->getValue();
  8988. return (isSigned && !value.isSignedIntN(32)) ||
  8989. (!isSigned && !value.isIntN(32));
  8990. }
  8991. if (const auto *floatLiteral = dyn_cast<FloatingLiteral>(expr)) {
  8992. llvm::APFloat value = floatLiteral->getValue();
  8993. const auto &semantics = value.getSemantics();
  8994. // regular 'half' and 'float' can be represented in 32 bits.
  8995. if (&semantics == &llvm::APFloat::IEEEsingle ||
  8996. &semantics == &llvm::APFloat::IEEEhalf)
  8997. return true;
  8998. // See if 'double' value can be represented in 32 bits without losing info.
  8999. bool losesInfo = false;
  9000. const auto convertStatus =
  9001. value.convert(llvm::APFloat::IEEEsingle,
  9002. llvm::APFloat::rmNearestTiesToEven, &losesInfo);
  9003. if (convertStatus != llvm::APFloat::opOK &&
  9004. convertStatus != llvm::APFloat::opInexact)
  9005. return true;
  9006. }
  9007. return false;
  9008. }
  9009. SpirvConstant *SpirvEmitter::tryToEvaluateAsInt32(const llvm::APInt &intValue,
  9010. bool isSigned) {
  9011. if (isSigned && intValue.isSignedIntN(32)) {
  9012. return spvBuilder.getConstantInt(astContext.IntTy, intValue);
  9013. }
  9014. if (!isSigned && intValue.isIntN(32)) {
  9015. return spvBuilder.getConstantInt(astContext.UnsignedIntTy, intValue);
  9016. }
  9017. // Couldn't evaluate as a 32-bit int without losing information.
  9018. return nullptr;
  9019. }
  9020. SpirvConstant *
  9021. SpirvEmitter::tryToEvaluateAsFloat32(const llvm::APFloat &floatValue) {
  9022. const auto &semantics = floatValue.getSemantics();
  9023. // If the given value is already a 32-bit float, there is no need to convert.
  9024. if (&semantics == &llvm::APFloat::IEEEsingle) {
  9025. return spvBuilder.getConstantFloat(astContext.FloatTy, floatValue,
  9026. isSpecConstantMode);
  9027. }
  9028. // Try to see if this literal float can be represented in 32-bit.
  9029. // Since the convert function below may modify the fp value, we call it on a
  9030. // temporary copy.
  9031. llvm::APFloat eval = floatValue;
  9032. bool losesInfo = false;
  9033. const auto convertStatus =
  9034. eval.convert(llvm::APFloat::IEEEsingle,
  9035. llvm::APFloat::rmNearestTiesToEven, &losesInfo);
  9036. if (convertStatus == llvm::APFloat::opOK && !losesInfo)
  9037. return spvBuilder.getConstantFloat(astContext.FloatTy,
  9038. llvm::APFloat(eval.convertToFloat()));
  9039. // Couldn't evaluate as a 32-bit float without losing information.
  9040. return nullptr;
  9041. }
  9042. SpirvConstant *SpirvEmitter::translateAPFloat(llvm::APFloat floatValue,
  9043. QualType targetType) {
  9044. return spvBuilder.getConstantFloat(targetType, floatValue,
  9045. isSpecConstantMode);
  9046. }
  9047. SpirvConstant *SpirvEmitter::tryToEvaluateAsConst(const Expr *expr) {
  9048. Expr::EvalResult evalResult;
  9049. if (expr->EvaluateAsRValue(evalResult, astContext) &&
  9050. !evalResult.HasSideEffects) {
  9051. return translateAPValue(evalResult.Val, expr->getType());
  9052. }
  9053. return nullptr;
  9054. }
  9055. hlsl::ShaderModel::Kind SpirvEmitter::getShaderModelKind(StringRef stageName) {
  9056. hlsl::ShaderModel::Kind smk;
  9057. switch (stageName[0]) {
  9058. case 'c':
  9059. switch (stageName[1]) {
  9060. case 'o':
  9061. smk = hlsl::ShaderModel::Kind::Compute;
  9062. break;
  9063. case 'l':
  9064. smk = hlsl::ShaderModel::Kind::ClosestHit;
  9065. break;
  9066. case 'a':
  9067. smk = hlsl::ShaderModel::Kind::Callable;
  9068. break;
  9069. default:
  9070. smk = hlsl::ShaderModel::Kind::Invalid;
  9071. break;
  9072. }
  9073. break;
  9074. case 'v':
  9075. smk = hlsl::ShaderModel::Kind::Vertex;
  9076. break;
  9077. case 'h':
  9078. smk = hlsl::ShaderModel::Kind::Hull;
  9079. break;
  9080. case 'd':
  9081. smk = hlsl::ShaderModel::Kind::Domain;
  9082. break;
  9083. case 'g':
  9084. smk = hlsl::ShaderModel::Kind::Geometry;
  9085. break;
  9086. case 'p':
  9087. smk = hlsl::ShaderModel::Kind::Pixel;
  9088. break;
  9089. case 'r':
  9090. smk = hlsl::ShaderModel::Kind::RayGeneration;
  9091. break;
  9092. case 'i':
  9093. smk = hlsl::ShaderModel::Kind::Intersection;
  9094. break;
  9095. case 'a':
  9096. switch (stageName[1]) {
  9097. case 'm':
  9098. smk = hlsl::ShaderModel::Kind::Amplification;
  9099. break;
  9100. case 'n':
  9101. smk = hlsl::ShaderModel::Kind::AnyHit;
  9102. break;
  9103. }
  9104. break;
  9105. case 'm':
  9106. switch (stageName[1]) {
  9107. case 'e':
  9108. smk = hlsl::ShaderModel::Kind::Mesh;
  9109. break;
  9110. case 'i':
  9111. smk = hlsl::ShaderModel::Kind::Miss;
  9112. break;
  9113. }
  9114. break;
  9115. default:
  9116. smk = hlsl::ShaderModel::Kind::Invalid;
  9117. break;
  9118. }
  9119. if (smk == hlsl::ShaderModel::Kind::Invalid) {
  9120. llvm_unreachable("unknown stage name");
  9121. }
  9122. return smk;
  9123. }
  9124. spv::ExecutionModel
  9125. SpirvEmitter::getSpirvShaderStage(hlsl::ShaderModel::Kind smk) {
  9126. switch (smk) {
  9127. case hlsl::ShaderModel::Kind::Vertex:
  9128. return spv::ExecutionModel::Vertex;
  9129. case hlsl::ShaderModel::Kind::Hull:
  9130. return spv::ExecutionModel::TessellationControl;
  9131. case hlsl::ShaderModel::Kind::Domain:
  9132. return spv::ExecutionModel::TessellationEvaluation;
  9133. case hlsl::ShaderModel::Kind::Geometry:
  9134. return spv::ExecutionModel::Geometry;
  9135. case hlsl::ShaderModel::Kind::Pixel:
  9136. return spv::ExecutionModel::Fragment;
  9137. case hlsl::ShaderModel::Kind::Compute:
  9138. return spv::ExecutionModel::GLCompute;
  9139. case hlsl::ShaderModel::Kind::RayGeneration:
  9140. return spv::ExecutionModel::RayGenerationNV;
  9141. case hlsl::ShaderModel::Kind::Intersection:
  9142. return spv::ExecutionModel::IntersectionNV;
  9143. case hlsl::ShaderModel::Kind::AnyHit:
  9144. return spv::ExecutionModel::AnyHitNV;
  9145. case hlsl::ShaderModel::Kind::ClosestHit:
  9146. return spv::ExecutionModel::ClosestHitNV;
  9147. case hlsl::ShaderModel::Kind::Miss:
  9148. return spv::ExecutionModel::MissNV;
  9149. case hlsl::ShaderModel::Kind::Callable:
  9150. return spv::ExecutionModel::CallableNV;
  9151. case hlsl::ShaderModel::Kind::Mesh:
  9152. return spv::ExecutionModel::MeshNV;
  9153. case hlsl::ShaderModel::Kind::Amplification:
  9154. return spv::ExecutionModel::TaskNV;
  9155. default:
  9156. llvm_unreachable("invalid shader model kind");
  9157. break;
  9158. }
  9159. }
  9160. bool SpirvEmitter::processGeometryShaderAttributes(const FunctionDecl *decl,
  9161. uint32_t *arraySize) {
  9162. bool success = true;
  9163. assert(spvContext.isGS());
  9164. if (auto *vcAttr = decl->getAttr<HLSLMaxVertexCountAttr>()) {
  9165. spvBuilder.addExecutionMode(
  9166. entryFunction, spv::ExecutionMode::OutputVertices,
  9167. {static_cast<uint32_t>(vcAttr->getCount())}, decl->getLocation());
  9168. }
  9169. uint32_t invocations = 1;
  9170. if (auto *instanceAttr = decl->getAttr<HLSLInstanceAttr>()) {
  9171. invocations = static_cast<uint32_t>(instanceAttr->getCount());
  9172. }
  9173. spvBuilder.addExecutionMode(entryFunction, spv::ExecutionMode::Invocations,
  9174. {invocations}, decl->getLocation());
  9175. // Only one primitive type is permitted for the geometry shader.
  9176. bool outPoint = false, outLine = false, outTriangle = false, inPoint = false,
  9177. inLine = false, inTriangle = false, inLineAdj = false,
  9178. inTriangleAdj = false;
  9179. for (const auto *param : decl->params()) {
  9180. // Add an execution mode based on the output stream type. Do not an
  9181. // execution mode more than once.
  9182. if (param->hasAttr<HLSLInOutAttr>()) {
  9183. const auto paramType = param->getType();
  9184. if (hlsl::IsHLSLTriangleStreamType(paramType) && !outTriangle) {
  9185. spvBuilder.addExecutionMode(entryFunction,
  9186. spv::ExecutionMode::OutputTriangleStrip, {},
  9187. param->getLocation());
  9188. outTriangle = true;
  9189. } else if (hlsl::IsHLSLLineStreamType(paramType) && !outLine) {
  9190. spvBuilder.addExecutionMode(entryFunction,
  9191. spv::ExecutionMode::OutputLineStrip, {},
  9192. param->getLocation());
  9193. outLine = true;
  9194. } else if (hlsl::IsHLSLPointStreamType(paramType) && !outPoint) {
  9195. spvBuilder.addExecutionMode(entryFunction,
  9196. spv::ExecutionMode::OutputPoints, {},
  9197. param->getLocation());
  9198. outPoint = true;
  9199. }
  9200. // An output stream parameter will not have the input primitive type
  9201. // attributes, so we can continue to the next parameter.
  9202. continue;
  9203. }
  9204. // Add an execution mode based on the input primitive type. Do not add an
  9205. // execution mode more than once.
  9206. if (param->hasAttr<HLSLPointAttr>() && !inPoint) {
  9207. spvBuilder.addExecutionMode(entryFunction,
  9208. spv::ExecutionMode::InputPoints, {},
  9209. param->getLocation());
  9210. *arraySize = 1;
  9211. inPoint = true;
  9212. } else if (param->hasAttr<HLSLLineAttr>() && !inLine) {
  9213. spvBuilder.addExecutionMode(entryFunction, spv::ExecutionMode::InputLines,
  9214. {}, param->getLocation());
  9215. *arraySize = 2;
  9216. inLine = true;
  9217. } else if (param->hasAttr<HLSLTriangleAttr>() && !inTriangle) {
  9218. spvBuilder.addExecutionMode(entryFunction, spv::ExecutionMode::Triangles,
  9219. {}, param->getLocation());
  9220. *arraySize = 3;
  9221. inTriangle = true;
  9222. } else if (param->hasAttr<HLSLLineAdjAttr>() && !inLineAdj) {
  9223. spvBuilder.addExecutionMode(entryFunction,
  9224. spv::ExecutionMode::InputLinesAdjacency, {},
  9225. param->getLocation());
  9226. *arraySize = 4;
  9227. inLineAdj = true;
  9228. } else if (param->hasAttr<HLSLTriangleAdjAttr>() && !inTriangleAdj) {
  9229. spvBuilder.addExecutionMode(entryFunction,
  9230. spv::ExecutionMode::InputTrianglesAdjacency,
  9231. {}, param->getLocation());
  9232. *arraySize = 6;
  9233. inTriangleAdj = true;
  9234. }
  9235. }
  9236. if (inPoint + inLine + inLineAdj + inTriangle + inTriangleAdj > 1) {
  9237. emitError("only one input primitive type can be specified in the geometry "
  9238. "shader",
  9239. {});
  9240. success = false;
  9241. }
  9242. if (outPoint + outTriangle + outLine > 1) {
  9243. emitError("only one output primitive type can be specified in the geometry "
  9244. "shader",
  9245. {});
  9246. success = false;
  9247. }
  9248. return success;
  9249. }
  9250. void SpirvEmitter::processPixelShaderAttributes(const FunctionDecl *decl) {
  9251. spvBuilder.addExecutionMode(entryFunction,
  9252. spv::ExecutionMode::OriginUpperLeft, {},
  9253. decl->getLocation());
  9254. if (decl->getAttr<HLSLEarlyDepthStencilAttr>()) {
  9255. spvBuilder.addExecutionMode(entryFunction,
  9256. spv::ExecutionMode::EarlyFragmentTests, {},
  9257. decl->getLocation());
  9258. }
  9259. if (decl->getAttr<VKPostDepthCoverageAttr>()) {
  9260. spvBuilder.addExecutionMode(entryFunction,
  9261. spv::ExecutionMode::PostDepthCoverage, {},
  9262. decl->getLocation());
  9263. }
  9264. }
  9265. void SpirvEmitter::processComputeShaderAttributes(const FunctionDecl *decl) {
  9266. // If not explicitly specified, x, y, and z should be defaulted to 1.
  9267. uint32_t x = 1, y = 1, z = 1;
  9268. if (auto *numThreadsAttr = decl->getAttr<HLSLNumThreadsAttr>()) {
  9269. x = static_cast<uint32_t>(numThreadsAttr->getX());
  9270. y = static_cast<uint32_t>(numThreadsAttr->getY());
  9271. z = static_cast<uint32_t>(numThreadsAttr->getZ());
  9272. } else {
  9273. emitError("thread group size [numthreads(x,y,z)] is missing from the "
  9274. "entry-point function",
  9275. decl->getLocation());
  9276. return;
  9277. }
  9278. spvBuilder.addExecutionMode(entryFunction, spv::ExecutionMode::LocalSize,
  9279. {x, y, z}, decl->getLocation());
  9280. }
  9281. bool SpirvEmitter::processTessellationShaderAttributes(
  9282. const FunctionDecl *decl, uint32_t *numOutputControlPoints) {
  9283. assert(spvContext.isHS() || spvContext.isDS());
  9284. using namespace spv;
  9285. if (auto *domain = decl->getAttr<HLSLDomainAttr>()) {
  9286. const auto domainType = domain->getDomainType().lower();
  9287. const ExecutionMode hsExecMode =
  9288. llvm::StringSwitch<ExecutionMode>(domainType)
  9289. .Case("tri", ExecutionMode::Triangles)
  9290. .Case("quad", ExecutionMode::Quads)
  9291. .Case("isoline", ExecutionMode::Isolines)
  9292. .Default(ExecutionMode::Max);
  9293. if (hsExecMode == ExecutionMode::Max) {
  9294. emitError("unknown domain type specified for entry function",
  9295. domain->getLocation());
  9296. return false;
  9297. }
  9298. spvBuilder.addExecutionMode(entryFunction, hsExecMode, {},
  9299. decl->getLocation());
  9300. }
  9301. // Early return for domain shaders as domain shaders only takes the 'domain'
  9302. // attribute.
  9303. if (spvContext.isDS())
  9304. return true;
  9305. if (auto *partitioning = decl->getAttr<HLSLPartitioningAttr>()) {
  9306. const auto scheme = partitioning->getScheme().lower();
  9307. if (scheme == "pow2") {
  9308. emitError("pow2 partitioning scheme is not supported since there is no "
  9309. "equivalent in Vulkan",
  9310. partitioning->getLocation());
  9311. return false;
  9312. }
  9313. const ExecutionMode hsExecMode =
  9314. llvm::StringSwitch<ExecutionMode>(scheme)
  9315. .Case("fractional_even", ExecutionMode::SpacingFractionalEven)
  9316. .Case("fractional_odd", ExecutionMode::SpacingFractionalOdd)
  9317. .Case("integer", ExecutionMode::SpacingEqual)
  9318. .Default(ExecutionMode::Max);
  9319. if (hsExecMode == ExecutionMode::Max) {
  9320. emitError("unknown partitioning scheme in hull shader",
  9321. partitioning->getLocation());
  9322. return false;
  9323. }
  9324. spvBuilder.addExecutionMode(entryFunction, hsExecMode, {},
  9325. decl->getLocation());
  9326. }
  9327. if (auto *outputTopology = decl->getAttr<HLSLOutputTopologyAttr>()) {
  9328. const auto topology = outputTopology->getTopology().lower();
  9329. const ExecutionMode hsExecMode =
  9330. llvm::StringSwitch<ExecutionMode>(topology)
  9331. .Case("point", ExecutionMode::PointMode)
  9332. .Case("triangle_cw", ExecutionMode::VertexOrderCw)
  9333. .Case("triangle_ccw", ExecutionMode::VertexOrderCcw)
  9334. .Default(ExecutionMode::Max);
  9335. // TODO: There is no SPIR-V equivalent for "line" topology. Is it the
  9336. // default?
  9337. if (topology != "line") {
  9338. if (hsExecMode != spv::ExecutionMode::Max) {
  9339. spvBuilder.addExecutionMode(entryFunction, hsExecMode, {},
  9340. decl->getLocation());
  9341. } else {
  9342. emitError("unknown output topology in hull shader",
  9343. outputTopology->getLocation());
  9344. return false;
  9345. }
  9346. }
  9347. }
  9348. if (auto *controlPoints = decl->getAttr<HLSLOutputControlPointsAttr>()) {
  9349. *numOutputControlPoints = controlPoints->getCount();
  9350. spvBuilder.addExecutionMode(entryFunction,
  9351. spv::ExecutionMode::OutputVertices,
  9352. {*numOutputControlPoints}, decl->getLocation());
  9353. }
  9354. if (auto *pcf = decl->getAttr<HLSLPatchConstantFuncAttr>()) {
  9355. llvm::StringRef pcf_name = pcf->getFunctionName();
  9356. for (auto *decl : astContext.getTranslationUnitDecl()->decls())
  9357. if (auto *funcDecl = dyn_cast<FunctionDecl>(decl))
  9358. if (astContext.IsPatchConstantFunctionDecl(funcDecl) &&
  9359. funcDecl->getName() == pcf_name)
  9360. patchConstFunc = funcDecl;
  9361. }
  9362. return true;
  9363. }
  9364. bool SpirvEmitter::emitEntryFunctionWrapperForRayTracing(
  9365. const FunctionDecl *decl, SpirvFunction *entryFuncInstr) {
  9366. // The entry basic block.
  9367. auto *entryLabel = spvBuilder.createBasicBlock();
  9368. spvBuilder.setInsertPoint(entryLabel);
  9369. // Initialize all global variables at the beginning of the wrapper
  9370. for (const VarDecl *varDecl : toInitGloalVars) {
  9371. const auto varInfo =
  9372. declIdMapper.getDeclEvalInfo(varDecl, varDecl->getLocation());
  9373. if (const auto *init = varDecl->getInit()) {
  9374. storeValue(varInfo, loadIfGLValue(init), varDecl->getType(),
  9375. init->getLocStart());
  9376. // Update counter variable associated with global variables
  9377. tryToAssignCounterVar(varDecl, init);
  9378. }
  9379. // If not explicitly initialized, initialize with their zero values if not
  9380. // resource objects
  9381. else if (!hlsl::IsHLSLResourceType(varDecl->getType())) {
  9382. auto *nullValue = spvBuilder.getConstantNull(varDecl->getType());
  9383. spvBuilder.createStore(varInfo, nullValue, varDecl->getLocation());
  9384. }
  9385. }
  9386. // Create temporary variables for holding function call arguments
  9387. llvm::SmallVector<SpirvInstruction *, 4> params;
  9388. llvm::SmallVector<QualType, 4> paramTypes;
  9389. llvm::SmallVector<SpirvInstruction *, 4> stageVars;
  9390. hlsl::ShaderModel::Kind sKind = spvContext.getCurrentShaderModelKind();
  9391. for (uint32_t i = 0; i < decl->getNumParams(); i++) {
  9392. const auto param = decl->getParamDecl(i);
  9393. const auto paramType = param->getType();
  9394. std::string tempVarName = "param.var." + param->getNameAsString();
  9395. auto *tempVar =
  9396. spvBuilder.addFnVar(paramType, param->getLocation(), tempVarName,
  9397. param->hasAttr<HLSLPreciseAttr>());
  9398. SpirvVariable *curStageVar = nullptr;
  9399. params.push_back(tempVar);
  9400. paramTypes.push_back(paramType);
  9401. // Order of arguments is fixed
  9402. // Any-Hit/Closest-Hit : Arg 0 = rayPayload(inout), Arg1 = attribute(in)
  9403. // Miss : Arg 0 = rayPayload(inout)
  9404. // Callable : Arg 0 = callable data(inout)
  9405. // Raygeneration/Intersection : No Args allowed
  9406. if (sKind == hlsl::ShaderModel::Kind::RayGeneration) {
  9407. assert("Raygeneration shaders have no arguments of entry function");
  9408. } else if (sKind == hlsl::ShaderModel::Kind::Intersection) {
  9409. assert("Intersection shaders have no arguments of entry function");
  9410. } else if (sKind == hlsl::ShaderModel::Kind::ClosestHit ||
  9411. sKind == hlsl::ShaderModel::Kind::AnyHit) {
  9412. // Generate rayPayloadInNV and hitAttributeNV stage variables
  9413. if (i == 0) {
  9414. // First argument is always rayPayload
  9415. curStageVar = declIdMapper.createRayTracingNVStageVar(
  9416. spv::StorageClass::IncomingRayPayloadNV, param);
  9417. currentRayPayload = curStageVar;
  9418. } else {
  9419. // Second argument is always attribute
  9420. curStageVar = declIdMapper.createRayTracingNVStageVar(
  9421. spv::StorageClass::HitAttributeNV, param);
  9422. }
  9423. } else if (sKind == hlsl::ShaderModel::Kind::Miss) {
  9424. // Generate rayPayloadInNV stage variable
  9425. // First and only argument is rayPayload
  9426. curStageVar = declIdMapper.createRayTracingNVStageVar(
  9427. spv::StorageClass::IncomingRayPayloadNV, param);
  9428. } else if (sKind == hlsl::ShaderModel::Kind::Callable) {
  9429. curStageVar = declIdMapper.createRayTracingNVStageVar(
  9430. spv::StorageClass::IncomingCallableDataNV, param);
  9431. }
  9432. if (curStageVar != nullptr) {
  9433. stageVars.push_back(curStageVar);
  9434. // Copy data to temporary
  9435. auto *tempLoadInst =
  9436. spvBuilder.createLoad(paramType, curStageVar, param->getLocation());
  9437. spvBuilder.createStore(tempVar, tempLoadInst, param->getLocation());
  9438. }
  9439. }
  9440. // Call the original entry function
  9441. const QualType retType = decl->getReturnType();
  9442. spvBuilder.createFunctionCall(retType, entryFuncInstr, params,
  9443. decl->getLocStart());
  9444. // Write certain output variables back
  9445. if (sKind == hlsl::ShaderModel::Kind::ClosestHit ||
  9446. sKind == hlsl::ShaderModel::Kind::AnyHit ||
  9447. sKind == hlsl::ShaderModel::Kind::Miss ||
  9448. sKind == hlsl::ShaderModel::Kind::Callable) {
  9449. // Write back results to IncomingRayPayloadNV/IncomingCallableDataNV
  9450. auto *tempLoad = spvBuilder.createLoad(paramTypes[0], params[0],
  9451. decl->getBody()->getLocEnd());
  9452. spvBuilder.createStore(stageVars[0], tempLoad,
  9453. decl->getBody()->getLocEnd());
  9454. }
  9455. spvBuilder.createReturn(decl->getBody()->getLocEnd());
  9456. spvBuilder.endFunction();
  9457. return true;
  9458. }
  9459. bool SpirvEmitter::processMeshOrAmplificationShaderAttributes(
  9460. const FunctionDecl *decl, uint32_t *outVerticesArraySize) {
  9461. if (auto *numThreadsAttr = decl->getAttr<HLSLNumThreadsAttr>()) {
  9462. uint32_t x, y, z;
  9463. x = static_cast<uint32_t>(numThreadsAttr->getX());
  9464. y = static_cast<uint32_t>(numThreadsAttr->getY());
  9465. z = static_cast<uint32_t>(numThreadsAttr->getZ());
  9466. spvBuilder.addExecutionMode(entryFunction, spv::ExecutionMode::LocalSize,
  9467. {x, y, z}, decl->getLocation());
  9468. }
  9469. // Early return for amplification shaders as they only take the 'numthreads'
  9470. // attribute.
  9471. if (spvContext.isAS())
  9472. return true;
  9473. spv::ExecutionMode outputPrimitive = spv::ExecutionMode::Max;
  9474. if (auto *outputTopology = decl->getAttr<HLSLOutputTopologyAttr>()) {
  9475. const auto topology = outputTopology->getTopology().lower();
  9476. outputPrimitive =
  9477. llvm::StringSwitch<spv::ExecutionMode>(topology)
  9478. .Case("point", spv::ExecutionMode::OutputPoints)
  9479. .Case("line", spv::ExecutionMode::OutputLinesNV)
  9480. .Case("triangle", spv::ExecutionMode::OutputTrianglesNV);
  9481. if (outputPrimitive != spv::ExecutionMode::Max) {
  9482. spvBuilder.addExecutionMode(entryFunction, outputPrimitive, {},
  9483. decl->getLocation());
  9484. } else {
  9485. emitError("unknown output topology in mesh shader",
  9486. outputTopology->getLocation());
  9487. return false;
  9488. }
  9489. }
  9490. uint32_t numVertices = 0;
  9491. uint32_t numIndices = 0;
  9492. uint32_t numPrimitives = 0;
  9493. bool payloadDeclSeen = false;
  9494. for (uint32_t i = 0; i < decl->getNumParams(); i++) {
  9495. const auto param = decl->getParamDecl(i);
  9496. const auto paramType = param->getType();
  9497. const auto paramLoc = param->getLocation();
  9498. if (param->hasAttr<HLSLVerticesAttr>() ||
  9499. param->hasAttr<HLSLIndicesAttr>() ||
  9500. param->hasAttr<HLSLPrimitivesAttr>()) {
  9501. uint32_t arraySize = 0;
  9502. if (const auto *arrayType =
  9503. astContext.getAsConstantArrayType(paramType)) {
  9504. const auto eleType =
  9505. arrayType->getElementType()->getCanonicalTypeUnqualified();
  9506. if (param->hasAttr<HLSLIndicesAttr>()) {
  9507. switch (outputPrimitive) {
  9508. case spv::ExecutionMode::OutputPoints:
  9509. if (eleType != astContext.UnsignedIntTy) {
  9510. emitError("expected 1D array of uint type", paramLoc);
  9511. return false;
  9512. }
  9513. break;
  9514. case spv::ExecutionMode::OutputLinesNV: {
  9515. QualType baseType;
  9516. uint32_t length;
  9517. if (!isVectorType(eleType, &baseType, &length) ||
  9518. baseType != astContext.UnsignedIntTy || length != 2) {
  9519. emitError("expected 1D array of uint2 type", paramLoc);
  9520. return false;
  9521. }
  9522. break;
  9523. }
  9524. case spv::ExecutionMode::OutputTrianglesNV: {
  9525. QualType baseType;
  9526. uint32_t length;
  9527. if (!isVectorType(eleType, &baseType, &length) ||
  9528. baseType != astContext.UnsignedIntTy || length != 3) {
  9529. emitError("expected 1D array of uint3 type", paramLoc);
  9530. return false;
  9531. }
  9532. break;
  9533. }
  9534. default:
  9535. assert(false && "unexpected spirv execution mode");
  9536. }
  9537. } else if (!eleType->isStructureType()) {
  9538. // vertices/primitives objects
  9539. emitError("expected 1D array of struct type", paramLoc);
  9540. return false;
  9541. }
  9542. arraySize = static_cast<uint32_t>(arrayType->getSize().getZExtValue());
  9543. } else {
  9544. emitError("expected 1D array of indices/vertices/primitives object",
  9545. paramLoc);
  9546. return false;
  9547. }
  9548. if (param->hasAttr<HLSLVerticesAttr>()) {
  9549. if (numVertices != 0) {
  9550. emitError("only one object with 'vertices' modifier is allowed",
  9551. paramLoc);
  9552. return false;
  9553. }
  9554. numVertices = arraySize;
  9555. } else if (param->hasAttr<HLSLIndicesAttr>()) {
  9556. if (numIndices != 0) {
  9557. emitError("only one object with 'indices' modifier is allowed",
  9558. paramLoc);
  9559. return false;
  9560. }
  9561. numIndices = arraySize;
  9562. } else if (param->hasAttr<HLSLPrimitivesAttr>()) {
  9563. if (numPrimitives != 0) {
  9564. emitError("only one object with 'primitives' modifier is allowed",
  9565. paramLoc);
  9566. return false;
  9567. }
  9568. numPrimitives = arraySize;
  9569. }
  9570. } else if (param->hasAttr<HLSLPayloadAttr>()) {
  9571. if (payloadDeclSeen) {
  9572. emitError("only one object with 'payload' modifier is allowed",
  9573. paramLoc);
  9574. return false;
  9575. }
  9576. payloadDeclSeen = true;
  9577. if (!paramType->isStructureType()) {
  9578. emitError("expected payload of struct type", paramLoc);
  9579. return false;
  9580. }
  9581. }
  9582. }
  9583. // Vertex attribute array is a mandatory param to mesh entry function.
  9584. if (numVertices != 0) {
  9585. *outVerticesArraySize = numVertices;
  9586. spvBuilder.addExecutionMode(
  9587. entryFunction, spv::ExecutionMode::OutputVertices,
  9588. {static_cast<uint32_t>(numVertices)}, decl->getLocation());
  9589. } else {
  9590. emitError("expected vertices object declaration", decl->getLocation());
  9591. return false;
  9592. }
  9593. // Vertex indices array is a mandatory param to mesh entry function.
  9594. if (numIndices != 0) {
  9595. spvBuilder.addExecutionMode(
  9596. entryFunction, spv::ExecutionMode::OutputPrimitivesNV,
  9597. {static_cast<uint32_t>(numIndices)}, decl->getLocation());
  9598. // Primitive attribute array is an optional param to mesh entry function,
  9599. // but the array size should match the indices array.
  9600. if (numPrimitives != 0 && numPrimitives != numIndices) {
  9601. emitError("array size of primitives object should match 'indices' object",
  9602. decl->getLocation());
  9603. return false;
  9604. }
  9605. } else {
  9606. emitError("expected indices object declaration", decl->getLocation());
  9607. return false;
  9608. }
  9609. return true;
  9610. }
  9611. bool SpirvEmitter::emitEntryFunctionWrapper(const FunctionDecl *decl,
  9612. SpirvFunction *entryFuncInstr) {
  9613. // HS specific attributes
  9614. uint32_t numOutputControlPoints = 0;
  9615. SpirvInstruction *outputControlPointIdVal =
  9616. nullptr; // SV_OutputControlPointID value
  9617. SpirvInstruction *primitiveIdVar = nullptr; // SV_PrimitiveID variable
  9618. SpirvInstruction *viewIdVar = nullptr; // SV_ViewID variable
  9619. SpirvInstruction *hullMainInputPatchParam =
  9620. nullptr; // Temporary parameter for InputPatch<>
  9621. // The array size of per-vertex input/output variables
  9622. // Used by HS/DS/GS for the additional arrayness, zero means not an array.
  9623. uint32_t inputArraySize = 0;
  9624. uint32_t outputArraySize = 0;
  9625. // The wrapper entry function surely does not have pre-assigned <result-id>
  9626. // for it like other functions that got added to the work queue following
  9627. // function calls. And the wrapper is the entry function.
  9628. entryFunction =
  9629. spvBuilder.beginFunction(astContext.VoidTy, /* param QualTypes */ {},
  9630. decl->getLocStart(), decl->getName());
  9631. // Note this should happen before using declIdMapper for other tasks.
  9632. declIdMapper.setEntryFunction(entryFunction);
  9633. // Set entryFunction for current entry point.
  9634. auto iter = functionInfoMap.find(decl);
  9635. assert(iter != functionInfoMap.end());
  9636. auto &entryInfo = iter->second;
  9637. assert(entryInfo->isEntryFunction);
  9638. entryInfo->entryFunction = entryFunction;
  9639. if (spvContext.isRay()) {
  9640. return emitEntryFunctionWrapperForRayTracing(decl, entryFuncInstr);
  9641. }
  9642. // Handle attributes specific to each shader stage
  9643. if (spvContext.isPS()) {
  9644. processPixelShaderAttributes(decl);
  9645. } else if (spvContext.isCS()) {
  9646. processComputeShaderAttributes(decl);
  9647. } else if (spvContext.isHS()) {
  9648. if (!processTessellationShaderAttributes(decl, &numOutputControlPoints))
  9649. return false;
  9650. // The input array size for HS is specified in the InputPatch parameter.
  9651. for (const auto *param : decl->params())
  9652. if (hlsl::IsHLSLInputPatchType(param->getType())) {
  9653. inputArraySize = hlsl::GetHLSLInputPatchCount(param->getType());
  9654. break;
  9655. }
  9656. outputArraySize = numOutputControlPoints;
  9657. } else if (spvContext.isDS()) {
  9658. if (!processTessellationShaderAttributes(decl, &numOutputControlPoints))
  9659. return false;
  9660. // The input array size for HS is specified in the OutputPatch parameter.
  9661. for (const auto *param : decl->params())
  9662. if (hlsl::IsHLSLOutputPatchType(param->getType())) {
  9663. inputArraySize = hlsl::GetHLSLOutputPatchCount(param->getType());
  9664. break;
  9665. }
  9666. // The per-vertex output of DS is not an array.
  9667. } else if (spvContext.isGS()) {
  9668. if (!processGeometryShaderAttributes(decl, &inputArraySize))
  9669. return false;
  9670. // The per-vertex output of GS is not an array.
  9671. } else if (spvContext.isMS() || spvContext.isAS()) {
  9672. if (!processMeshOrAmplificationShaderAttributes(decl, &outputArraySize))
  9673. return false;
  9674. }
  9675. // Go through all parameters and record the declaration of SV_ClipDistance
  9676. // and SV_CullDistance. We need to do this extra step because in HLSL we
  9677. // can declare multiple SV_ClipDistance/SV_CullDistance variables of float
  9678. // or vector of float types, but we can only have one single float array
  9679. // for the ClipDistance/CullDistance builtin. So we need to group all
  9680. // SV_ClipDistance/SV_CullDistance variables into one float array, thus we
  9681. // need to calculate the total size of the array and the offset of each
  9682. // variable within that array.
  9683. // Also go through all parameters to record the semantic strings provided for
  9684. // the builtins in gl_PerVertex.
  9685. for (const auto *param : decl->params()) {
  9686. if (canActAsInParmVar(param))
  9687. if (!declIdMapper.glPerVertex.recordGlPerVertexDeclFacts(param, true))
  9688. return false;
  9689. if (canActAsOutParmVar(param))
  9690. if (!declIdMapper.glPerVertex.recordGlPerVertexDeclFacts(param, false))
  9691. return false;
  9692. }
  9693. // Also consider the SV_ClipDistance/SV_CullDistance in the return type
  9694. if (!declIdMapper.glPerVertex.recordGlPerVertexDeclFacts(decl, false))
  9695. return false;
  9696. // Calculate the total size of the ClipDistance/CullDistance array and the
  9697. // offset of SV_ClipDistance/SV_CullDistance variables within the array.
  9698. declIdMapper.glPerVertex.calculateClipCullDistanceArraySize();
  9699. if (!spvContext.isCS() && !spvContext.isAS()) {
  9700. // Generate stand-alone builtins of Position, ClipDistance, and
  9701. // CullDistance, which belongs to gl_PerVertex.
  9702. declIdMapper.glPerVertex.generateVars(inputArraySize, outputArraySize);
  9703. }
  9704. // The entry basic block.
  9705. auto *entryLabel = spvBuilder.createBasicBlock();
  9706. spvBuilder.setInsertPoint(entryLabel);
  9707. // Initialize all global variables at the beginning of the wrapper
  9708. for (const VarDecl *varDecl : toInitGloalVars) {
  9709. // SPIR-V does not have string variables
  9710. if (isStringType(varDecl->getType()))
  9711. continue;
  9712. const auto varInfo =
  9713. declIdMapper.getDeclEvalInfo(varDecl, varDecl->getLocation());
  9714. if (const auto *init = varDecl->getInit()) {
  9715. storeValue(varInfo, loadIfGLValue(init), varDecl->getType(),
  9716. init->getLocStart());
  9717. // Update counter variable associated with global variables
  9718. tryToAssignCounterVar(varDecl, init);
  9719. }
  9720. // If not explicitly initialized, initialize with their zero values if not
  9721. // resource objects
  9722. else if (!hlsl::IsHLSLResourceType(varDecl->getType())) {
  9723. auto *nullValue = spvBuilder.getConstantNull(varDecl->getType());
  9724. spvBuilder.createStore(varInfo, nullValue, varDecl->getLocation());
  9725. }
  9726. }
  9727. // Create temporary variables for holding function call arguments
  9728. llvm::SmallVector<SpirvInstruction *, 4> params;
  9729. for (const auto *param : decl->params()) {
  9730. const auto paramType = param->getType();
  9731. std::string tempVarName = "param.var." + param->getNameAsString();
  9732. auto *tempVar =
  9733. spvBuilder.addFnVar(paramType, param->getLocation(), tempVarName,
  9734. param->hasAttr<HLSLPreciseAttr>());
  9735. params.push_back(tempVar);
  9736. // Create the stage input variable for parameter not marked as pure out and
  9737. // initialize the corresponding temporary variable
  9738. // Also do not create input variables for output stream objects of geometry
  9739. // shaders (e.g. TriangleStream) which are required to be marked as 'inout'.
  9740. if (canActAsInParmVar(param)) {
  9741. if (spvContext.isHS() && hlsl::IsHLSLInputPatchType(paramType)) {
  9742. // Record the temporary variable holding InputPatch. It may be used
  9743. // later in the patch constant function.
  9744. hullMainInputPatchParam = tempVar;
  9745. }
  9746. SpirvInstruction *loadedValue = nullptr;
  9747. if (!declIdMapper.createStageInputVar(param, &loadedValue, false))
  9748. return false;
  9749. // Only initialize the temporary variable if the parameter is indeed used.
  9750. if (param->isUsed()) {
  9751. spvBuilder.createStore(tempVar, loadedValue, param->getLocation());
  9752. }
  9753. // Record the temporary variable holding SV_OutputControlPointID,
  9754. // SV_PrimitiveID, and SV_ViewID. It may be used later in the patch
  9755. // constant function.
  9756. if (hasSemantic(param, hlsl::DXIL::SemanticKind::OutputControlPointID))
  9757. outputControlPointIdVal = loadedValue;
  9758. else if (hasSemantic(param, hlsl::DXIL::SemanticKind::PrimitiveID))
  9759. primitiveIdVar = tempVar;
  9760. else if (hasSemantic(param, hlsl::DXIL::SemanticKind::ViewID))
  9761. viewIdVar = tempVar;
  9762. }
  9763. }
  9764. // Call the original entry function
  9765. const QualType retType = decl->getReturnType();
  9766. auto *retVal = spvBuilder.createFunctionCall(retType, entryFuncInstr, params,
  9767. decl->getLocStart());
  9768. // Create and write stage output variables for return value. Special case for
  9769. // Hull shaders since they operate differently in 2 ways:
  9770. // 1- Their return value is in fact an array and each invocation should write
  9771. // to the proper offset in the array.
  9772. // 2- The patch constant function must be called *once* after all invocations
  9773. // of the main entry point function is done.
  9774. if (spvContext.isHS()) {
  9775. // Create stage output variables out of the return type.
  9776. if (!declIdMapper.createStageOutputVar(decl, numOutputControlPoints,
  9777. outputControlPointIdVal, retVal))
  9778. return false;
  9779. if (!processHSEntryPointOutputAndPCF(
  9780. decl, retType, retVal, numOutputControlPoints,
  9781. outputControlPointIdVal, primitiveIdVar, viewIdVar,
  9782. hullMainInputPatchParam))
  9783. return false;
  9784. } else {
  9785. if (!declIdMapper.createStageOutputVar(decl, retVal, /*forPCF*/ false))
  9786. return false;
  9787. }
  9788. // Create and write stage output variables for parameters marked as
  9789. // out/inout
  9790. for (uint32_t i = 0; i < decl->getNumParams(); ++i) {
  9791. const auto *param = decl->getParamDecl(i);
  9792. if (canActAsOutParmVar(param)) {
  9793. // Load the value from the parameter after function call
  9794. SpirvInstruction *loadedParam = nullptr;
  9795. // No need to write back the value if the parameter is not used at all in
  9796. // the original entry function.
  9797. //
  9798. // Write back of stage output variables in GS is manually controlled by
  9799. // .Append() intrinsic method. No need to load the parameter since we
  9800. // won't need to write back here.
  9801. if (param->isUsed() && !spvContext.isGS())
  9802. loadedParam = spvBuilder.createLoad(param->getType(), params[i],
  9803. param->getLocStart());
  9804. if (!declIdMapper.createStageOutputVar(param, loadedParam, false))
  9805. return false;
  9806. }
  9807. }
  9808. // For wrapper of entry point, it is better not to specify SourceLocation
  9809. // for return statement, because it is not the location of the actual
  9810. // return and emitting the location of the end of entry function makes
  9811. // us confused. It is better to emit debug line just before OpFunctionEnd.
  9812. spvBuilder.createReturn(/* SourceLocation */ {});
  9813. spvBuilder.endFunction();
  9814. // For Hull shaders, there is no explicit call to the PCF in the HLSL source.
  9815. // We should invoke a translation of the PCF manually.
  9816. if (spvContext.isHS())
  9817. doDecl(patchConstFunc);
  9818. return true;
  9819. }
  9820. bool SpirvEmitter::processHSEntryPointOutputAndPCF(
  9821. const FunctionDecl *hullMainFuncDecl, QualType retType,
  9822. SpirvInstruction *retVal, uint32_t numOutputControlPoints,
  9823. SpirvInstruction *outputControlPointId, SpirvInstruction *primitiveId,
  9824. SpirvInstruction *viewId, SpirvInstruction *hullMainInputPatch) {
  9825. // This method may only be called for Hull shaders.
  9826. assert(spvContext.isHS());
  9827. auto loc = hullMainFuncDecl->getLocation();
  9828. auto locEnd = hullMainFuncDecl->getLocEnd();
  9829. // For Hull shaders, the real output is an array of size
  9830. // numOutputControlPoints. The results of the main should be written to the
  9831. // correct offset in the array (based on InvocationID).
  9832. if (!numOutputControlPoints) {
  9833. emitError("number of output control points cannot be zero", loc);
  9834. return false;
  9835. }
  9836. // TODO: We should be able to handle cases where the SV_OutputControlPointID
  9837. // is not provided.
  9838. if (!outputControlPointId) {
  9839. emitError(
  9840. "SV_OutputControlPointID semantic must be provided in hull shader",
  9841. loc);
  9842. return false;
  9843. }
  9844. if (!patchConstFunc) {
  9845. emitError("patch constant function not defined in hull shader", loc);
  9846. return false;
  9847. }
  9848. SpirvInstruction *hullMainOutputPatch = nullptr;
  9849. // If the patch constant function (PCF) takes the result of the Hull main
  9850. // entry point, create a temporary function-scope variable and write the
  9851. // results to it, so it can be passed to the PCF.
  9852. if (patchConstFuncTakesHullOutputPatch(patchConstFunc)) {
  9853. const QualType hullMainRetType = astContext.getConstantArrayType(
  9854. retType, llvm::APInt(32, numOutputControlPoints),
  9855. clang::ArrayType::Normal, 0);
  9856. hullMainOutputPatch =
  9857. spvBuilder.addFnVar(hullMainRetType, locEnd, "temp.var.hullMainRetVal");
  9858. auto *tempLocation = spvBuilder.createAccessChain(
  9859. retType, hullMainOutputPatch, {outputControlPointId}, locEnd);
  9860. spvBuilder.createStore(tempLocation, retVal, locEnd);
  9861. }
  9862. // Now create a barrier before calling the Patch Constant Function (PCF).
  9863. // Flags are:
  9864. // Execution Barrier scope = Workgroup (2)
  9865. // Memory Barrier scope = Invocation (4)
  9866. // Memory Semantics Barrier scope = None (0)
  9867. spvBuilder.createBarrier(spv::Scope::Invocation,
  9868. spv::MemorySemanticsMask::MaskNone,
  9869. spv::Scope::Workgroup, {});
  9870. // The PCF should be called only once. Therefore, we check the invocationID,
  9871. // and we only allow ID 0 to call the PCF.
  9872. auto *condition = spvBuilder.createBinaryOp(
  9873. spv::Op::OpIEqual, astContext.BoolTy, outputControlPointId,
  9874. spvBuilder.getConstantInt(astContext.UnsignedIntTy, llvm::APInt(32, 0)),
  9875. loc);
  9876. auto *thenBB = spvBuilder.createBasicBlock("if.true");
  9877. auto *mergeBB = spvBuilder.createBasicBlock("if.merge");
  9878. spvBuilder.createConditionalBranch(condition, thenBB, mergeBB, loc, mergeBB);
  9879. spvBuilder.addSuccessor(thenBB);
  9880. spvBuilder.addSuccessor(mergeBB);
  9881. spvBuilder.setMergeTarget(mergeBB);
  9882. spvBuilder.setInsertPoint(thenBB);
  9883. // Call the PCF. Since the function is not explicitly called, we must first
  9884. // register an ID for it.
  9885. SpirvFunction *pcfId = declIdMapper.getOrRegisterFn(patchConstFunc);
  9886. const QualType pcfRetType = patchConstFunc->getReturnType();
  9887. std::vector<SpirvInstruction *> pcfParams;
  9888. // A lambda for creating a stage input variable and its associated temporary
  9889. // variable for function call. Also initializes the temporary variable using
  9890. // the contents loaded from the stage input variable. Returns the <result-id>
  9891. // of the temporary variable.
  9892. const auto createParmVarAndInitFromStageInputVar =
  9893. [this](const ParmVarDecl *param) {
  9894. const QualType type = param->getType();
  9895. std::string tempVarName = "param.var." + param->getNameAsString();
  9896. auto paramLoc = param->getLocation();
  9897. auto *tempVar = spvBuilder.addFnVar(type, paramLoc, tempVarName,
  9898. param->hasAttr<HLSLPreciseAttr>());
  9899. SpirvInstruction *loadedValue = nullptr;
  9900. declIdMapper.createStageInputVar(param, &loadedValue, /*forPCF*/ true);
  9901. spvBuilder.createStore(tempVar, loadedValue, paramLoc);
  9902. return tempVar;
  9903. };
  9904. for (const auto *param : patchConstFunc->parameters()) {
  9905. // Note: According to the HLSL reference, the PCF takes an InputPatch of
  9906. // ControlPoints as well as the PatchID (PrimitiveID). This does not
  9907. // necessarily mean that they are present. There is also no requirement
  9908. // for the order of parameters passed to PCF.
  9909. if (hlsl::IsHLSLInputPatchType(param->getType())) {
  9910. pcfParams.push_back(hullMainInputPatch);
  9911. } else if (hlsl::IsHLSLOutputPatchType(param->getType())) {
  9912. pcfParams.push_back(hullMainOutputPatch);
  9913. } else if (hasSemantic(param, hlsl::DXIL::SemanticKind::PrimitiveID)) {
  9914. if (!primitiveId) {
  9915. primitiveId = createParmVarAndInitFromStageInputVar(param);
  9916. }
  9917. pcfParams.push_back(primitiveId);
  9918. } else if (hasSemantic(param, hlsl::DXIL::SemanticKind::ViewID)) {
  9919. if (!viewId) {
  9920. viewId = createParmVarAndInitFromStageInputVar(param);
  9921. }
  9922. pcfParams.push_back(viewId);
  9923. } else {
  9924. emitError("patch constant function parameter '%0' unknown",
  9925. param->getLocation())
  9926. << param->getName();
  9927. }
  9928. }
  9929. auto *pcfResultId = spvBuilder.createFunctionCall(
  9930. pcfRetType, pcfId, {pcfParams}, hullMainFuncDecl->getLocStart());
  9931. if (!declIdMapper.createStageOutputVar(patchConstFunc, pcfResultId,
  9932. /*forPCF*/ true))
  9933. return false;
  9934. spvBuilder.createBranch(mergeBB, locEnd);
  9935. spvBuilder.addSuccessor(mergeBB);
  9936. spvBuilder.setInsertPoint(mergeBB);
  9937. return true;
  9938. }
  9939. bool SpirvEmitter::allSwitchCasesAreIntegerLiterals(const Stmt *root) {
  9940. if (!root)
  9941. return false;
  9942. const auto *caseStmt = dyn_cast<CaseStmt>(root);
  9943. const auto *compoundStmt = dyn_cast<CompoundStmt>(root);
  9944. if (!caseStmt && !compoundStmt)
  9945. return true;
  9946. if (caseStmt) {
  9947. const Expr *caseExpr = caseStmt->getLHS();
  9948. return caseExpr && caseExpr->isEvaluatable(astContext);
  9949. }
  9950. // Recurse down if facing a compound statement.
  9951. for (auto *st : compoundStmt->body())
  9952. if (!allSwitchCasesAreIntegerLiterals(st))
  9953. return false;
  9954. return true;
  9955. }
  9956. void SpirvEmitter::discoverAllCaseStmtInSwitchStmt(
  9957. const Stmt *root, SpirvBasicBlock **defaultBB,
  9958. std::vector<std::pair<uint32_t, SpirvBasicBlock *>> *targets) {
  9959. if (!root)
  9960. return;
  9961. // A switch case can only appear in DefaultStmt, CaseStmt, or
  9962. // CompoundStmt. For the rest, we can just return.
  9963. const auto *defaultStmt = dyn_cast<DefaultStmt>(root);
  9964. const auto *caseStmt = dyn_cast<CaseStmt>(root);
  9965. const auto *compoundStmt = dyn_cast<CompoundStmt>(root);
  9966. if (!defaultStmt && !caseStmt && !compoundStmt)
  9967. return;
  9968. // Recurse down if facing a compound statement.
  9969. if (compoundStmt) {
  9970. for (auto *st : compoundStmt->body())
  9971. discoverAllCaseStmtInSwitchStmt(st, defaultBB, targets);
  9972. return;
  9973. }
  9974. std::string caseLabel;
  9975. uint32_t caseValue = 0;
  9976. if (defaultStmt) {
  9977. // This is the default branch.
  9978. caseLabel = "switch.default";
  9979. } else if (caseStmt) {
  9980. // This is a non-default case.
  9981. // When using OpSwitch, we only allow integer literal cases. e.g:
  9982. // case <literal_integer>: {...; break;}
  9983. const Expr *caseExpr = caseStmt->getLHS();
  9984. assert(caseExpr && caseExpr->isEvaluatable(astContext));
  9985. auto bitWidth = astContext.getIntWidth(caseExpr->getType());
  9986. if (bitWidth != 32)
  9987. emitError(
  9988. "non-32bit integer case value in switch statement unimplemented",
  9989. caseExpr->getExprLoc());
  9990. Expr::EvalResult evalResult;
  9991. caseExpr->EvaluateAsRValue(evalResult, astContext);
  9992. const int64_t value = evalResult.Val.getInt().getSExtValue();
  9993. caseValue = static_cast<uint32_t>(value);
  9994. caseLabel = "switch." + std::string(value < 0 ? "n" : "") +
  9995. llvm::itostr(std::abs(value));
  9996. }
  9997. auto *caseBB = spvBuilder.createBasicBlock(caseLabel);
  9998. spvBuilder.addSuccessor(caseBB);
  9999. stmtBasicBlock[root] = caseBB;
  10000. // Add all cases to the 'targets' vector.
  10001. if (caseStmt)
  10002. targets->emplace_back(caseValue, caseBB);
  10003. // The default label is not part of the 'targets' vector that is passed
  10004. // to the OpSwitch instruction.
  10005. // If default statement was discovered, return its label via defaultBB.
  10006. if (defaultStmt)
  10007. *defaultBB = caseBB;
  10008. // Process cases nested in other cases. It happens when we have fall through
  10009. // cases. For example:
  10010. // case 1: case 2: ...; break;
  10011. // will result in the CaseSmt for case 2 nested in the one for case 1.
  10012. discoverAllCaseStmtInSwitchStmt(caseStmt ? caseStmt->getSubStmt()
  10013. : defaultStmt->getSubStmt(),
  10014. defaultBB, targets);
  10015. }
  10016. void SpirvEmitter::flattenSwitchStmtAST(const Stmt *root,
  10017. std::vector<const Stmt *> *flatSwitch) {
  10018. const auto *caseStmt = dyn_cast<CaseStmt>(root);
  10019. const auto *compoundStmt = dyn_cast<CompoundStmt>(root);
  10020. const auto *defaultStmt = dyn_cast<DefaultStmt>(root);
  10021. if (!compoundStmt) {
  10022. flatSwitch->push_back(root);
  10023. }
  10024. if (compoundStmt) {
  10025. for (const auto *st : compoundStmt->body())
  10026. flattenSwitchStmtAST(st, flatSwitch);
  10027. } else if (caseStmt) {
  10028. flattenSwitchStmtAST(caseStmt->getSubStmt(), flatSwitch);
  10029. } else if (defaultStmt) {
  10030. flattenSwitchStmtAST(defaultStmt->getSubStmt(), flatSwitch);
  10031. }
  10032. }
  10033. void SpirvEmitter::processCaseStmtOrDefaultStmt(const Stmt *stmt) {
  10034. auto *caseStmt = dyn_cast<CaseStmt>(stmt);
  10035. auto *defaultStmt = dyn_cast<DefaultStmt>(stmt);
  10036. assert(caseStmt || defaultStmt);
  10037. auto *caseBB = stmtBasicBlock[stmt];
  10038. if (!spvBuilder.isCurrentBasicBlockTerminated()) {
  10039. // We are about to handle the case passed in as parameter. If the current
  10040. // basic block is not terminated, it means the previous case is a fall
  10041. // through case. We need to link it to the case to be processed.
  10042. spvBuilder.createBranch(caseBB, stmt->getLocStart());
  10043. spvBuilder.addSuccessor(caseBB);
  10044. }
  10045. spvBuilder.setInsertPoint(caseBB);
  10046. doStmt(caseStmt ? caseStmt->getSubStmt() : defaultStmt->getSubStmt());
  10047. }
  10048. void SpirvEmitter::processSwitchStmtUsingSpirvOpSwitch(
  10049. const SwitchStmt *switchStmt) {
  10050. const SourceLocation srcLoc = switchStmt->getSwitchLoc();
  10051. // First handle the condition variable DeclStmt if one exists.
  10052. // For example: handle 'int a = b' in the following:
  10053. // switch (int a = b) {...}
  10054. if (const auto *condVarDeclStmt = switchStmt->getConditionVariableDeclStmt())
  10055. doDeclStmt(condVarDeclStmt);
  10056. auto *selector = doExpr(switchStmt->getCond());
  10057. // We need a merge block regardless of the number of switch cases.
  10058. // Since OpSwitch always requires a default label, if the switch statement
  10059. // does not have a default branch, we use the merge block as the default
  10060. // target.
  10061. auto *mergeBB = spvBuilder.createBasicBlock("switch.merge");
  10062. spvBuilder.setMergeTarget(mergeBB);
  10063. breakStack.push(mergeBB);
  10064. auto *defaultBB = mergeBB;
  10065. // (literal, labelId) pairs to pass to the OpSwitch instruction.
  10066. std::vector<std::pair<uint32_t, SpirvBasicBlock *>> targets;
  10067. discoverAllCaseStmtInSwitchStmt(switchStmt->getBody(), &defaultBB, &targets);
  10068. // Create the OpSelectionMerge and OpSwitch.
  10069. spvBuilder.createSwitch(mergeBB, selector, defaultBB, targets, srcLoc);
  10070. // Handle the switch body.
  10071. doStmt(switchStmt->getBody());
  10072. if (!spvBuilder.isCurrentBasicBlockTerminated())
  10073. spvBuilder.createBranch(mergeBB, switchStmt->getLocEnd());
  10074. spvBuilder.setInsertPoint(mergeBB);
  10075. breakStack.pop();
  10076. }
  10077. void SpirvEmitter::processSwitchStmtUsingIfStmts(const SwitchStmt *switchStmt) {
  10078. std::vector<const Stmt *> flatSwitch;
  10079. flattenSwitchStmtAST(switchStmt->getBody(), &flatSwitch);
  10080. // First handle the condition variable DeclStmt if one exists.
  10081. // For example: handle 'int a = b' in the following:
  10082. // switch (int a = b) {...}
  10083. if (const auto *condVarDeclStmt = switchStmt->getConditionVariableDeclStmt())
  10084. doDeclStmt(condVarDeclStmt);
  10085. // Figure out the indexes of CaseStmts (and DefaultStmt if it exists) in
  10086. // the flattened switch AST.
  10087. // For instance, for the following flat vector:
  10088. // +-----+-----+-----+-----+-----+-----+-----+-----+-----+-------+-----+
  10089. // |Case1|Stmt1|Case2|Stmt2|Break|Case3|Case4|Stmt4|Break|Default|Stmt5|
  10090. // +-----+-----+-----+-----+-----+-----+-----+-----+-----+-------+-----+
  10091. // The indexes are: {0, 2, 5, 6, 9}
  10092. std::vector<uint32_t> caseStmtLocs;
  10093. for (uint32_t i = 0; i < flatSwitch.size(); ++i)
  10094. if (isa<CaseStmt>(flatSwitch[i]) || isa<DefaultStmt>(flatSwitch[i]))
  10095. caseStmtLocs.push_back(i);
  10096. IfStmt *prevIfStmt = nullptr;
  10097. IfStmt *rootIfStmt = nullptr;
  10098. CompoundStmt *defaultBody = nullptr;
  10099. // For each case, start at its index in the vector, and go forward
  10100. // accumulating statements until BreakStmt or end of vector is reached.
  10101. for (auto curCaseIndex : caseStmtLocs) {
  10102. const Stmt *curCase = flatSwitch[curCaseIndex];
  10103. // CompoundStmt to hold all statements for this case.
  10104. CompoundStmt *cs = new (astContext) CompoundStmt(Stmt::EmptyShell());
  10105. // Accumulate all non-case/default/break statements as the body for the
  10106. // current case.
  10107. std::vector<Stmt *> statements;
  10108. for (unsigned i = curCaseIndex + 1;
  10109. i < flatSwitch.size() && !isa<BreakStmt>(flatSwitch[i]); ++i) {
  10110. if (!isa<CaseStmt>(flatSwitch[i]) && !isa<DefaultStmt>(flatSwitch[i]))
  10111. statements.push_back(const_cast<Stmt *>(flatSwitch[i]));
  10112. }
  10113. if (!statements.empty())
  10114. cs->setStmts(astContext, statements.data(), statements.size());
  10115. // For non-default cases, generate the IfStmt that compares the switch
  10116. // value to the case value.
  10117. if (auto *caseStmt = dyn_cast<CaseStmt>(curCase)) {
  10118. IfStmt *curIf = new (astContext) IfStmt(Stmt::EmptyShell());
  10119. BinaryOperator *bo = new (astContext) BinaryOperator(Stmt::EmptyShell());
  10120. bo->setLHS(const_cast<Expr *>(switchStmt->getCond()));
  10121. bo->setRHS(const_cast<Expr *>(caseStmt->getLHS()));
  10122. bo->setOpcode(BO_EQ);
  10123. bo->setType(astContext.getLogicalOperationType());
  10124. curIf->setCond(bo);
  10125. curIf->setThen(cs);
  10126. // No conditional variable associated with this faux if statement.
  10127. curIf->setConditionVariable(astContext, nullptr);
  10128. // Each If statement is the "else" of the previous if statement.
  10129. if (prevIfStmt)
  10130. prevIfStmt->setElse(curIf);
  10131. else
  10132. rootIfStmt = curIf;
  10133. prevIfStmt = curIf;
  10134. } else {
  10135. // Record the DefaultStmt body as it will be used as the body of the
  10136. // "else" block in the if-elseif-...-else pattern.
  10137. defaultBody = cs;
  10138. }
  10139. }
  10140. // If a default case exists, it is the "else" of the last if statement.
  10141. if (prevIfStmt)
  10142. prevIfStmt->setElse(defaultBody);
  10143. // Since all else-if and else statements are the child nodes of the first
  10144. // IfStmt, we only need to call doStmt for the first IfStmt.
  10145. if (rootIfStmt)
  10146. doStmt(rootIfStmt);
  10147. // If there are no CaseStmt and there is only 1 DefaultStmt, there will be
  10148. // no if statements. The switch in that case only executes the body of the
  10149. // default case.
  10150. else if (defaultBody)
  10151. doStmt(defaultBody);
  10152. }
  10153. SpirvInstruction *SpirvEmitter::extractVecFromVec4(SpirvInstruction *from,
  10154. uint32_t targetVecSize,
  10155. QualType targetElemType,
  10156. SourceLocation loc) {
  10157. assert(targetVecSize > 0 && targetVecSize < 5);
  10158. const QualType retType =
  10159. targetVecSize == 1
  10160. ? targetElemType
  10161. : astContext.getExtVectorType(targetElemType, targetVecSize);
  10162. switch (targetVecSize) {
  10163. case 1:
  10164. return spvBuilder.createCompositeExtract(retType, from, {0}, loc);
  10165. break;
  10166. case 2:
  10167. return spvBuilder.createVectorShuffle(retType, from, from, {0, 1}, loc);
  10168. break;
  10169. case 3:
  10170. return spvBuilder.createVectorShuffle(retType, from, from, {0, 1, 2}, loc);
  10171. break;
  10172. case 4:
  10173. return from;
  10174. default:
  10175. llvm_unreachable("vector element count must be 1, 2, 3, or 4");
  10176. }
  10177. }
  10178. void SpirvEmitter::addFunctionToWorkQueue(hlsl::DXIL::ShaderKind shaderKind,
  10179. const clang::FunctionDecl *fnDecl,
  10180. bool isEntryFunction) {
  10181. // Only update the workQueue and the function info map if the given
  10182. // FunctionDecl hasn't been added already.
  10183. if (functionInfoMap.find(fnDecl) == functionInfoMap.end()) {
  10184. // Note: The function is just discovered and is being added to the
  10185. // workQueue, therefore it does not have the entryFunction SPIR-V
  10186. // instruction yet (use nullptr).
  10187. auto *fnInfo = new (spvContext) FunctionInfo(
  10188. shaderKind, fnDecl, /*entryFunction*/ nullptr, isEntryFunction);
  10189. functionInfoMap[fnDecl] = fnInfo;
  10190. workQueue.push_back(fnInfo);
  10191. }
  10192. }
  10193. SpirvInstruction *
  10194. SpirvEmitter::processTraceRayInline(const CXXMemberCallExpr *expr) {
  10195. emitWarning("SPV_KHR_ray_query is currently a provisional extension and might"
  10196. "change in ways that are not backwards compatible",
  10197. expr->getExprLoc());
  10198. const auto object = expr->getImplicitObjectArgument();
  10199. uint32_t templateFlags = hlsl::GetHLSLResourceTemplateUInt(object->getType());
  10200. const auto constFlags = spvBuilder.getConstantInt(
  10201. astContext.UnsignedIntTy, llvm::APInt(32, templateFlags));
  10202. SpirvInstruction *rayqueryObj = loadIfAliasVarRef(object);
  10203. const auto args = expr->getArgs();
  10204. if (expr->getNumArgs() != 4) {
  10205. emitError("invalid number of arguments to RayQueryInitialize",
  10206. expr->getExprLoc());
  10207. }
  10208. // HLSL Func
  10209. // void RayQuery::TraceRayInline(
  10210. // RaytracingAccelerationStructure AccelerationStructure,
  10211. // uint RayFlags,
  10212. // uint InstanceInclusionMask,
  10213. // RayDesc Ray);
  10214. // void OpRayQueryInitializeKHR ( <id> RayQuery,
  10215. // <id> Acceleration Structure
  10216. // <id> RayFlags
  10217. // <id> CullMask
  10218. // <id> RayOrigin
  10219. // <id> RayTmin
  10220. // <id> RayDirection
  10221. // <id> Ray Tmax)
  10222. const auto accelStructure = doExpr(args[0]);
  10223. SpirvInstruction *rayFlags = nullptr;
  10224. if (rayFlags = tryToEvaluateAsConst(args[1])) {
  10225. rayFlags->setRValue();
  10226. } else {
  10227. rayFlags = doExpr(args[1]);
  10228. }
  10229. if (auto constFlags = dyn_cast<SpirvConstantInteger>(rayFlags)) {
  10230. auto interRayFlags = constFlags->getValue().getZExtValue();
  10231. templateFlags |= interRayFlags;
  10232. }
  10233. bool hasCullFlags =
  10234. templateFlags & (uint32_t(hlsl::DXIL::RayFlag::SkipTriangles) |
  10235. uint32_t(hlsl::DXIL::RayFlag::SkipProceduralPrimitives));
  10236. auto loc = args[1]->getLocStart();
  10237. rayFlags =
  10238. spvBuilder.createBinaryOp(spv::Op::OpBitwiseOr, astContext.UnsignedIntTy,
  10239. constFlags, rayFlags, loc);
  10240. const auto cullMask = doExpr(args[2]);
  10241. // Extract the ray description to match SPIR-V
  10242. const auto floatType = astContext.FloatTy;
  10243. const auto vecType = astContext.getExtVectorType(astContext.FloatTy, 3);
  10244. SpirvInstruction *rayDescArg = doExpr(args[3]);
  10245. loc = args[3]->getLocStart();
  10246. const auto origin =
  10247. spvBuilder.createCompositeExtract(vecType, rayDescArg, {0}, loc);
  10248. const auto tMin =
  10249. spvBuilder.createCompositeExtract(floatType, rayDescArg, {1}, loc);
  10250. const auto direction =
  10251. spvBuilder.createCompositeExtract(vecType, rayDescArg, {2}, loc);
  10252. const auto tMax =
  10253. spvBuilder.createCompositeExtract(floatType, rayDescArg, {3}, loc);
  10254. llvm::SmallVector<SpirvInstruction *, 8> traceArgs = {
  10255. rayqueryObj, accelStructure, rayFlags, cullMask,
  10256. origin, tMin, direction, tMax};
  10257. return spvBuilder.createRayQueryOpsKHR(spv::Op::OpRayQueryInitializeKHR,
  10258. QualType(), traceArgs, hasCullFlags,
  10259. expr->getExprLoc());
  10260. }
  10261. SpirvInstruction *
  10262. SpirvEmitter::processRayQueryIntrinsics(const CXXMemberCallExpr *expr,
  10263. hlsl::IntrinsicOp opcode) {
  10264. emitWarning("SPV_KHR_ray_query is currently a provisional extension and might"
  10265. "change in ways that are not backwards compatible",
  10266. expr->getExprLoc());
  10267. const auto object = expr->getImplicitObjectArgument();
  10268. SpirvInstruction *rayqueryObj = loadIfAliasVarRef(object);
  10269. const auto args = expr->getArgs();
  10270. llvm::SmallVector<SpirvInstruction *, 8> traceArgs;
  10271. traceArgs.push_back(rayqueryObj);
  10272. for (uint32_t i = 0; i < expr->getNumArgs(); ++i) {
  10273. traceArgs.push_back(doExpr(args[i]));
  10274. }
  10275. spv::Op spvCode = spv::Op::Max;
  10276. QualType exprType = expr->getType();
  10277. exprType = exprType->isVoidType() ? QualType() : exprType;
  10278. const auto candidateIntersection =
  10279. spvBuilder.getConstantInt(astContext.UnsignedIntTy, llvm::APInt(32, 0));
  10280. const auto committedIntersection =
  10281. spvBuilder.getConstantInt(astContext.UnsignedIntTy, llvm::APInt(32, 1));
  10282. bool transposeMatrix = false;
  10283. bool logicalNot = false;
  10284. using namespace hlsl;
  10285. switch (opcode) {
  10286. case IntrinsicOp::MOP_Proceed:
  10287. spvCode = spv::Op::OpRayQueryProceedKHR;
  10288. break;
  10289. case IntrinsicOp::MOP_Abort:
  10290. spvCode = spv::Op::OpRayQueryTerminateKHR;
  10291. exprType = QualType();
  10292. break;
  10293. case IntrinsicOp::MOP_CandidateGeometryIndex:
  10294. traceArgs.push_back(candidateIntersection);
  10295. spvCode = spv::Op::OpRayQueryGetIntersectionGeometryIndexKHR;
  10296. break;
  10297. case IntrinsicOp::MOP_CandidateInstanceContributionToHitGroupIndex:
  10298. traceArgs.push_back(candidateIntersection);
  10299. spvCode = spv::Op::
  10300. OpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffsetKHR;
  10301. break;
  10302. case IntrinsicOp::MOP_CandidateInstanceID:
  10303. traceArgs.push_back(candidateIntersection);
  10304. spvCode = spv::Op::OpRayQueryGetIntersectionInstanceCustomIndexKHR;
  10305. break;
  10306. case IntrinsicOp::MOP_CandidateInstanceIndex:
  10307. traceArgs.push_back(candidateIntersection);
  10308. spvCode = spv::Op::OpRayQueryGetIntersectionInstanceIdKHR;
  10309. break;
  10310. case IntrinsicOp::MOP_CandidateObjectRayDirection:
  10311. traceArgs.push_back(candidateIntersection);
  10312. spvCode = spv::Op::OpRayQueryGetIntersectionObjectRayDirectionKHR;
  10313. break;
  10314. case IntrinsicOp::MOP_CandidateObjectRayOrigin:
  10315. traceArgs.push_back(candidateIntersection);
  10316. spvCode = spv::Op::OpRayQueryGetIntersectionObjectRayOriginKHR;
  10317. break;
  10318. case IntrinsicOp::MOP_CandidateObjectToWorld3x4:
  10319. spvCode = spv::Op::OpRayQueryGetIntersectionObjectToWorldKHR;
  10320. traceArgs.push_back(candidateIntersection);
  10321. transposeMatrix = true;
  10322. break;
  10323. case IntrinsicOp::MOP_CandidateObjectToWorld4x3:
  10324. spvCode = spv::Op::OpRayQueryGetIntersectionObjectToWorldKHR;
  10325. traceArgs.push_back(candidateIntersection);
  10326. break;
  10327. case IntrinsicOp::MOP_CandidatePrimitiveIndex:
  10328. traceArgs.push_back(candidateIntersection);
  10329. spvCode = spv::Op::OpRayQueryGetIntersectionPrimitiveIndexKHR;
  10330. break;
  10331. case IntrinsicOp::MOP_CandidateProceduralPrimitiveNonOpaque:
  10332. spvCode = spv::Op::OpRayQueryGetIntersectionCandidateAABBOpaqueKHR;
  10333. logicalNot = true;
  10334. break;
  10335. case IntrinsicOp::MOP_CandidateTriangleBarycentrics:
  10336. traceArgs.push_back(candidateIntersection);
  10337. spvCode = spv::Op::OpRayQueryGetIntersectionBarycentricsKHR;
  10338. break;
  10339. case IntrinsicOp::MOP_CandidateTriangleFrontFace:
  10340. traceArgs.push_back(candidateIntersection);
  10341. spvCode = spv::Op::OpRayQueryGetIntersectionFrontFaceKHR;
  10342. break;
  10343. case IntrinsicOp::MOP_CandidateTriangleRayT:
  10344. traceArgs.push_back(candidateIntersection);
  10345. spvCode = spv::Op::OpRayQueryGetIntersectionTKHR;
  10346. break;
  10347. case IntrinsicOp::MOP_CandidateType:
  10348. spvCode = spv::Op::OpRayQueryGetIntersectionTypeKHR;
  10349. traceArgs.push_back(candidateIntersection);
  10350. break;
  10351. case IntrinsicOp::MOP_CandidateWorldToObject4x3:
  10352. spvCode = spv::Op::OpRayQueryGetIntersectionWorldToObjectKHR;
  10353. traceArgs.push_back(candidateIntersection);
  10354. break;
  10355. case IntrinsicOp::MOP_CandidateWorldToObject3x4:
  10356. spvCode = spv::Op::OpRayQueryGetIntersectionWorldToObjectKHR;
  10357. traceArgs.push_back(candidateIntersection);
  10358. transposeMatrix = true;
  10359. break;
  10360. case IntrinsicOp::MOP_CommitNonOpaqueTriangleHit:
  10361. spvCode = spv::Op::OpRayQueryConfirmIntersectionKHR;
  10362. exprType = QualType();
  10363. break;
  10364. case IntrinsicOp::MOP_CommitProceduralPrimitiveHit:
  10365. spvCode = spv::Op::OpRayQueryGenerateIntersectionKHR;
  10366. exprType = QualType();
  10367. break;
  10368. case IntrinsicOp::MOP_CommittedGeometryIndex:
  10369. spvCode = spv::Op::OpRayQueryGetIntersectionGeometryIndexKHR;
  10370. traceArgs.push_back(committedIntersection);
  10371. break;
  10372. case IntrinsicOp::MOP_CommittedInstanceContributionToHitGroupIndex:
  10373. spvCode = spv::Op::
  10374. OpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffsetKHR;
  10375. traceArgs.push_back(committedIntersection);
  10376. break;
  10377. case IntrinsicOp::MOP_CommittedInstanceID:
  10378. spvCode = spv::Op::OpRayQueryGetIntersectionInstanceCustomIndexKHR;
  10379. traceArgs.push_back(committedIntersection);
  10380. break;
  10381. case IntrinsicOp::MOP_CommittedInstanceIndex:
  10382. spvCode = spv::Op::OpRayQueryGetIntersectionInstanceIdKHR;
  10383. traceArgs.push_back(committedIntersection);
  10384. break;
  10385. case IntrinsicOp::MOP_CommittedObjectRayDirection:
  10386. spvCode = spv::Op::OpRayQueryGetIntersectionObjectRayDirectionKHR;
  10387. traceArgs.push_back(committedIntersection);
  10388. break;
  10389. case IntrinsicOp::MOP_CommittedObjectRayOrigin:
  10390. spvCode = spv::Op::OpRayQueryGetIntersectionObjectRayOriginKHR;
  10391. traceArgs.push_back(committedIntersection);
  10392. break;
  10393. case IntrinsicOp::MOP_CommittedObjectToWorld3x4:
  10394. spvCode = spv::Op::OpRayQueryGetIntersectionObjectToWorldKHR;
  10395. traceArgs.push_back(committedIntersection);
  10396. transposeMatrix = true;
  10397. break;
  10398. case IntrinsicOp::MOP_CommittedObjectToWorld4x3:
  10399. spvCode = spv::Op::OpRayQueryGetIntersectionObjectToWorldKHR;
  10400. traceArgs.push_back(committedIntersection);
  10401. break;
  10402. case IntrinsicOp::MOP_CommittedPrimitiveIndex:
  10403. spvCode = spv::Op::OpRayQueryGetIntersectionPrimitiveIndexKHR;
  10404. traceArgs.push_back(committedIntersection);
  10405. break;
  10406. case IntrinsicOp::MOP_CommittedRayT:
  10407. spvCode = spv::Op::OpRayQueryGetIntersectionTKHR;
  10408. traceArgs.push_back(committedIntersection);
  10409. break;
  10410. case IntrinsicOp::MOP_CommittedStatus:
  10411. spvCode = spv::Op::OpRayQueryGetIntersectionTypeKHR;
  10412. traceArgs.push_back(committedIntersection);
  10413. break;
  10414. case IntrinsicOp::MOP_CommittedTriangleBarycentrics:
  10415. spvCode = spv::Op::OpRayQueryGetIntersectionBarycentricsKHR;
  10416. traceArgs.push_back(committedIntersection);
  10417. break;
  10418. case IntrinsicOp::MOP_CommittedTriangleFrontFace:
  10419. spvCode = spv::Op::OpRayQueryGetIntersectionFrontFaceKHR;
  10420. traceArgs.push_back(committedIntersection);
  10421. break;
  10422. case IntrinsicOp::MOP_CommittedWorldToObject3x4:
  10423. spvCode = spv::Op::OpRayQueryGetIntersectionWorldToObjectKHR;
  10424. traceArgs.push_back(committedIntersection);
  10425. transposeMatrix = true;
  10426. break;
  10427. case IntrinsicOp::MOP_CommittedWorldToObject4x3:
  10428. spvCode = spv::Op::OpRayQueryGetIntersectionWorldToObjectKHR;
  10429. traceArgs.push_back(committedIntersection);
  10430. break;
  10431. case IntrinsicOp::MOP_RayFlags:
  10432. spvCode = spv::Op::OpRayQueryGetRayFlagsKHR;
  10433. break;
  10434. case IntrinsicOp::MOP_RayTMin:
  10435. spvCode = spv::Op::OpRayQueryGetRayTMinKHR;
  10436. break;
  10437. case IntrinsicOp::MOP_WorldRayDirection:
  10438. spvCode = spv::Op::OpRayQueryGetWorldRayDirectionKHR;
  10439. break;
  10440. case IntrinsicOp::MOP_WorldRayOrigin:
  10441. spvCode = spv::Op::OpRayQueryGetWorldRayOriginKHR;
  10442. break;
  10443. default:
  10444. emitError("intrinsic '%0' method unimplemented",
  10445. expr->getCallee()->getExprLoc())
  10446. << expr->getDirectCallee()->getName();
  10447. return nullptr;
  10448. }
  10449. if (transposeMatrix) {
  10450. assert(hlsl::IsHLSLMatType(exprType) && "intrinsic should be matrix");
  10451. const clang::Type *type = exprType.getCanonicalType().getTypePtr();
  10452. const RecordType *RT = cast<RecordType>(type);
  10453. const ClassTemplateSpecializationDecl *templateSpecDecl =
  10454. cast<ClassTemplateSpecializationDecl>(RT->getDecl());
  10455. ClassTemplateDecl *templateDecl =
  10456. templateSpecDecl->getSpecializedTemplate();
  10457. const auto retType = exprType;
  10458. exprType = getHLSLMatrixType(astContext, theCompilerInstance.getSema(),
  10459. templateDecl, astContext.FloatTy, 4, 3);
  10460. }
  10461. const auto loc = expr->getExprLoc();
  10462. SpirvInstruction *retVal =
  10463. spvBuilder.createRayQueryOpsKHR(spvCode, exprType, traceArgs, false, loc);
  10464. if (transposeMatrix) {
  10465. retVal = spvBuilder.createUnaryOp(spv::Op::OpTranspose, expr->getType(),
  10466. retVal, loc);
  10467. }
  10468. if (logicalNot) {
  10469. retVal = spvBuilder.createUnaryOp(spv::Op::OpLogicalNot, expr->getType(),
  10470. retVal, loc);
  10471. }
  10472. retVal->setRValue();
  10473. return retVal;
  10474. }
  10475. } // end namespace spirv
  10476. } // end namespace clang