SpirvEmitter.cpp 495 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380
  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 is an implicit variable declaration inside the
  35. // "vk" namespace.
  36. bool isImplicitVarDeclInVkNamespace(const Decl *decl) {
  37. if (!decl)
  38. return false;
  39. if (auto *varDecl = dyn_cast<VarDecl>(decl)) {
  40. // Check whether it is implicitly defined.
  41. if (!decl->isImplicit())
  42. return false;
  43. if (auto *nsDecl = dyn_cast<NamespaceDecl>(varDecl->getDeclContext()))
  44. if (nsDecl->getName().equals("vk"))
  45. return true;
  46. }
  47. return false;
  48. }
  49. // Returns true if the given decl has the given semantic.
  50. bool hasSemantic(const DeclaratorDecl *decl,
  51. hlsl::DXIL::SemanticKind semanticKind) {
  52. using namespace hlsl;
  53. for (auto *annotation : decl->getUnusualAnnotations()) {
  54. if (auto *semanticDecl = dyn_cast<SemanticDecl>(annotation)) {
  55. llvm::StringRef semanticName;
  56. uint32_t semanticIndex = 0;
  57. Semantic::DecomposeNameAndIndex(semanticDecl->SemanticName, &semanticName,
  58. &semanticIndex);
  59. const auto *semantic = Semantic::GetByName(semanticName);
  60. if (semantic->GetKind() == semanticKind)
  61. return true;
  62. }
  63. }
  64. return false;
  65. }
  66. const ParmVarDecl *patchConstFuncTakesHullOutputPatch(FunctionDecl *pcf) {
  67. for (const auto *param : pcf->parameters())
  68. if (hlsl::IsHLSLOutputPatchType(param->getType()))
  69. return param;
  70. return nullptr;
  71. }
  72. inline bool isSpirvMatrixOp(spv::Op opcode) {
  73. return opcode == spv::Op::OpMatrixTimesMatrix ||
  74. opcode == spv::Op::OpMatrixTimesVector ||
  75. opcode == spv::Op::OpMatrixTimesScalar;
  76. }
  77. /// If expr is a (RW)StructuredBuffer.Load(), returns the object and writes
  78. /// index. Otherwiser, returns false.
  79. // TODO: The following doesn't handle Load(int, int) yet. And it is basically a
  80. // duplicate of doCXXMemberCallExpr.
  81. const Expr *isStructuredBufferLoad(const Expr *expr, const Expr **index) {
  82. using namespace hlsl;
  83. if (const auto *indexing = dyn_cast<CXXMemberCallExpr>(expr)) {
  84. const auto *callee = indexing->getDirectCallee();
  85. uint32_t opcode = static_cast<uint32_t>(IntrinsicOp::Num_Intrinsics);
  86. llvm::StringRef group;
  87. if (GetIntrinsicOp(callee, opcode, group)) {
  88. if (static_cast<IntrinsicOp>(opcode) == IntrinsicOp::MOP_Load) {
  89. const auto *object = indexing->getImplicitObjectArgument();
  90. if (isStructuredBuffer(object->getType())) {
  91. *index = indexing->getArg(0);
  92. return indexing->getImplicitObjectArgument();
  93. }
  94. }
  95. }
  96. }
  97. return nullptr;
  98. }
  99. /// Returns true if the given VarDecl will be translated into a SPIR-V variable
  100. /// not in the Private or Function storage class.
  101. inline bool isExternalVar(const VarDecl *var) {
  102. // Class static variables should be put in the Private storage class.
  103. // groupshared variables are allowed to be declared as "static". But we still
  104. // need to put them in the Workgroup storage class. That is, when seeing
  105. // "static groupshared", ignore "static".
  106. return var->hasExternalFormalLinkage()
  107. ? !var->isStaticDataMember()
  108. : (var->getAttr<HLSLGroupSharedAttr>() != nullptr);
  109. }
  110. /// Returns the referenced variable's DeclContext if the given expr is
  111. /// a DeclRefExpr referencing a ConstantBuffer/TextureBuffer. Otherwise,
  112. /// returns nullptr.
  113. const DeclContext *isConstantTextureBufferDeclRef(const Expr *expr) {
  114. if (const auto *declRefExpr = dyn_cast<DeclRefExpr>(expr->IgnoreParenCasts()))
  115. if (const auto *varDecl = dyn_cast<VarDecl>(declRefExpr->getFoundDecl()))
  116. if (isConstantTextureBuffer(varDecl->getType()))
  117. return hlsl::GetHLSLResourceResultType(varDecl->getType())
  118. ->getAs<RecordType>()
  119. ->getDecl();
  120. return nullptr;
  121. }
  122. /// Returns true if
  123. /// * the given expr is an DeclRefExpr referencing a kind of structured or byte
  124. /// buffer and it is non-alias one, or
  125. /// * the given expr is an CallExpr returning a kind of structured or byte
  126. /// buffer.
  127. /// * the given expr is an ArraySubscriptExpr referencing a kind of structured
  128. /// or byte buffer.
  129. ///
  130. /// Note: legalization specific code
  131. bool isReferencingNonAliasStructuredOrByteBuffer(const Expr *expr) {
  132. expr = expr->IgnoreParenCasts();
  133. if (const auto *declRefExpr = dyn_cast<DeclRefExpr>(expr)) {
  134. if (const auto *varDecl = dyn_cast<VarDecl>(declRefExpr->getFoundDecl()))
  135. if (isAKindOfStructuredOrByteBuffer(varDecl->getType()))
  136. return isExternalVar(varDecl);
  137. } else if (const auto *callExpr = dyn_cast<CallExpr>(expr)) {
  138. if (isAKindOfStructuredOrByteBuffer(callExpr->getType()))
  139. return true;
  140. } else if (const auto *arrSubExpr = dyn_cast<ArraySubscriptExpr>(expr)) {
  141. return isReferencingNonAliasStructuredOrByteBuffer(arrSubExpr->getBase());
  142. }
  143. return false;
  144. }
  145. /// Translates atomic HLSL opcodes into the equivalent SPIR-V opcode.
  146. spv::Op translateAtomicHlslOpcodeToSpirvOpcode(hlsl::IntrinsicOp opcode) {
  147. using namespace hlsl;
  148. using namespace spv;
  149. switch (opcode) {
  150. case IntrinsicOp::IOP_InterlockedAdd:
  151. case IntrinsicOp::MOP_InterlockedAdd:
  152. return Op::OpAtomicIAdd;
  153. case IntrinsicOp::IOP_InterlockedAnd:
  154. case IntrinsicOp::MOP_InterlockedAnd:
  155. return Op::OpAtomicAnd;
  156. case IntrinsicOp::IOP_InterlockedOr:
  157. case IntrinsicOp::MOP_InterlockedOr:
  158. return Op::OpAtomicOr;
  159. case IntrinsicOp::IOP_InterlockedXor:
  160. case IntrinsicOp::MOP_InterlockedXor:
  161. return Op::OpAtomicXor;
  162. case IntrinsicOp::IOP_InterlockedUMax:
  163. case IntrinsicOp::MOP_InterlockedUMax:
  164. return Op::OpAtomicUMax;
  165. case IntrinsicOp::IOP_InterlockedUMin:
  166. case IntrinsicOp::MOP_InterlockedUMin:
  167. return Op::OpAtomicUMin;
  168. case IntrinsicOp::IOP_InterlockedMax:
  169. case IntrinsicOp::MOP_InterlockedMax:
  170. return Op::OpAtomicSMax;
  171. case IntrinsicOp::IOP_InterlockedMin:
  172. case IntrinsicOp::MOP_InterlockedMin:
  173. return Op::OpAtomicSMin;
  174. case IntrinsicOp::IOP_InterlockedExchange:
  175. case IntrinsicOp::MOP_InterlockedExchange:
  176. return Op::OpAtomicExchange;
  177. default:
  178. // Only atomic opcodes are relevant.
  179. break;
  180. }
  181. assert(false && "unimplemented hlsl intrinsic opcode");
  182. return Op::Max;
  183. }
  184. // Returns true if the given opcode is an accepted binary opcode in
  185. // OpSpecConstantOp.
  186. bool isAcceptedSpecConstantBinaryOp(spv::Op op) {
  187. switch (op) {
  188. case spv::Op::OpIAdd:
  189. case spv::Op::OpISub:
  190. case spv::Op::OpIMul:
  191. case spv::Op::OpUDiv:
  192. case spv::Op::OpSDiv:
  193. case spv::Op::OpUMod:
  194. case spv::Op::OpSRem:
  195. case spv::Op::OpSMod:
  196. case spv::Op::OpShiftRightLogical:
  197. case spv::Op::OpShiftRightArithmetic:
  198. case spv::Op::OpShiftLeftLogical:
  199. case spv::Op::OpBitwiseOr:
  200. case spv::Op::OpBitwiseXor:
  201. case spv::Op::OpBitwiseAnd:
  202. case spv::Op::OpVectorShuffle:
  203. case spv::Op::OpCompositeExtract:
  204. case spv::Op::OpCompositeInsert:
  205. case spv::Op::OpLogicalOr:
  206. case spv::Op::OpLogicalAnd:
  207. case spv::Op::OpLogicalNot:
  208. case spv::Op::OpLogicalEqual:
  209. case spv::Op::OpLogicalNotEqual:
  210. case spv::Op::OpIEqual:
  211. case spv::Op::OpINotEqual:
  212. case spv::Op::OpULessThan:
  213. case spv::Op::OpSLessThan:
  214. case spv::Op::OpUGreaterThan:
  215. case spv::Op::OpSGreaterThan:
  216. case spv::Op::OpULessThanEqual:
  217. case spv::Op::OpSLessThanEqual:
  218. case spv::Op::OpUGreaterThanEqual:
  219. case spv::Op::OpSGreaterThanEqual:
  220. return true;
  221. default:
  222. // Accepted binary opcodes return true. Anything else is false.
  223. return false;
  224. }
  225. return false;
  226. }
  227. /// Returns true if the given expression is an accepted initializer for a spec
  228. /// constant.
  229. bool isAcceptedSpecConstantInit(const Expr *init) {
  230. // Allow numeric casts
  231. init = init->IgnoreParenCasts();
  232. if (isa<CXXBoolLiteralExpr>(init) || isa<IntegerLiteral>(init) ||
  233. isa<FloatingLiteral>(init))
  234. return true;
  235. // Allow the minus operator which is used to specify negative values
  236. if (const auto *unaryOp = dyn_cast<UnaryOperator>(init))
  237. return unaryOp->getOpcode() == UO_Minus &&
  238. isAcceptedSpecConstantInit(unaryOp->getSubExpr());
  239. return false;
  240. }
  241. /// Returns true if the given function parameter can act as shader stage
  242. /// input parameter.
  243. inline bool canActAsInParmVar(const ParmVarDecl *param) {
  244. // If the parameter has no in/out/inout attribute, it is defaulted to
  245. // an in parameter.
  246. return !param->hasAttr<HLSLOutAttr>() &&
  247. // GS output streams are marked as inout, but it should not be
  248. // used as in parameter.
  249. !hlsl::IsHLSLStreamOutputType(param->getType());
  250. }
  251. /// Returns true if the given function parameter can act as shader stage
  252. /// output parameter.
  253. inline bool canActAsOutParmVar(const ParmVarDecl *param) {
  254. return param->hasAttr<HLSLOutAttr>() || param->hasAttr<HLSLInOutAttr>() ||
  255. hlsl::IsHLSLRayQueryType(param->getType());
  256. }
  257. /// Returns true if the given expression is of builtin type and can be evaluated
  258. /// to a constant zero. Returns false otherwise.
  259. inline bool evaluatesToConstZero(const Expr *expr, ASTContext &astContext) {
  260. const auto type = expr->getType();
  261. if (!type->isBuiltinType())
  262. return false;
  263. Expr::EvalResult evalResult;
  264. if (expr->EvaluateAsRValue(evalResult, astContext) &&
  265. !evalResult.HasSideEffects) {
  266. const auto &val = evalResult.Val;
  267. return ((type->isBooleanType() && !val.getInt().getBoolValue()) ||
  268. (type->isIntegerType() && !val.getInt().getBoolValue()) ||
  269. (type->isFloatingType() && val.getFloat().isZero()));
  270. }
  271. return false;
  272. }
  273. /// Returns the real definition of the callee of the given CallExpr.
  274. ///
  275. /// If we are calling a forward-declared function, callee will be the
  276. /// FunctionDecl for the foward-declared function, not the actual
  277. /// definition. The foward-delcaration and defintion are two completely
  278. /// different AST nodes.
  279. inline const FunctionDecl *getCalleeDefinition(const CallExpr *expr) {
  280. const auto *callee = expr->getDirectCallee();
  281. if (callee->isThisDeclarationADefinition())
  282. return callee;
  283. // We need to update callee to the actual definition here
  284. if (!callee->isDefined(callee))
  285. return nullptr;
  286. return callee;
  287. }
  288. /// Returns the referenced definition. The given expr is expected to be a
  289. /// DeclRefExpr or CallExpr after ignoring casts. Returns nullptr otherwise.
  290. const DeclaratorDecl *getReferencedDef(const Expr *expr) {
  291. if (!expr)
  292. return nullptr;
  293. expr = expr->IgnoreParenCasts();
  294. if (const auto *declRefExpr = dyn_cast<DeclRefExpr>(expr)) {
  295. return dyn_cast_or_null<DeclaratorDecl>(declRefExpr->getDecl());
  296. }
  297. if (const auto *callExpr = dyn_cast<CallExpr>(expr)) {
  298. return getCalleeDefinition(callExpr);
  299. }
  300. return nullptr;
  301. }
  302. /// Returns the number of base classes if this type is a derived class/struct.
  303. /// Returns zero otherwise.
  304. inline uint32_t getNumBaseClasses(QualType type) {
  305. if (const auto *cxxDecl = type->getAsCXXRecordDecl())
  306. return cxxDecl->getNumBases();
  307. return 0;
  308. }
  309. /// Gets the index sequence of casting a derived object to a base object by
  310. /// following the cast chain.
  311. void getBaseClassIndices(const CastExpr *expr,
  312. llvm::SmallVectorImpl<uint32_t> *indices) {
  313. assert(expr->getCastKind() == CK_UncheckedDerivedToBase ||
  314. expr->getCastKind() == CK_HLSLDerivedToBase);
  315. indices->clear();
  316. QualType derivedType = expr->getSubExpr()->getType();
  317. // There are two types of UncheckedDerivedToBase/HLSLDerivedToBase casts:
  318. //
  319. // The first is when a derived object tries to access a member in the base.
  320. // For example: derived.base_member.
  321. // ImplicitCastExpr 'Base' lvalue <UncheckedDerivedToBase (Base)>
  322. // `-DeclRefExpr 'Derived' lvalue Var 0x1f0d9bb2890 'derived' 'Derived'
  323. //
  324. // The second is when a pointer of the dervied is used to access members or
  325. // methods of the base. There are currently no pointers in HLSL, but the
  326. // method defintions can use the "this" pointer.
  327. // For example:
  328. // class Base { float value; };
  329. // class Derviced : Base {
  330. // float4 getBaseValue() { return value; }
  331. // };
  332. //
  333. // In this example, the 'this' pointer (pointing to Derived) is used inside
  334. // 'getBaseValue', which is then cast to a Base pointer:
  335. //
  336. // ImplicitCastExpr 'Base *' <UncheckedDerivedToBase (Base)>
  337. // `-CXXThisExpr 'Derviced *' this
  338. //
  339. // Therefore in order to obtain the derivedDecl below, we must make sure that
  340. // we handle the second case too by using the pointee type.
  341. if (derivedType->isPointerType())
  342. derivedType = derivedType->getPointeeType();
  343. const auto *derivedDecl = derivedType->getAsCXXRecordDecl();
  344. // Go through the base cast chain: for each of the derived to base cast, find
  345. // the index of the base in question in the derived's bases.
  346. for (auto pathIt = expr->path_begin(), pathIe = expr->path_end();
  347. pathIt != pathIe; ++pathIt) {
  348. // The type of the base in question
  349. const auto baseType = (*pathIt)->getType();
  350. uint32_t index = 0;
  351. for (auto baseIt = derivedDecl->bases_begin(),
  352. baseIe = derivedDecl->bases_end();
  353. baseIt != baseIe; ++baseIt, ++index)
  354. if (baseIt->getType() == baseType) {
  355. indices->push_back(index);
  356. break;
  357. }
  358. assert(index < derivedDecl->getNumBases());
  359. // Continue to proceed the next base in the chain
  360. derivedType = baseType;
  361. if (derivedType->isPointerType())
  362. derivedType = derivedType->getPointeeType();
  363. derivedDecl = derivedType->getAsCXXRecordDecl();
  364. }
  365. }
  366. std::string getNamespacePrefix(const Decl *decl) {
  367. std::string nsPrefix = "";
  368. const DeclContext *dc = decl->getDeclContext();
  369. while (dc && !dc->isTranslationUnit()) {
  370. if (const NamespaceDecl *ns = dyn_cast<NamespaceDecl>(dc)) {
  371. if (!ns->isAnonymousNamespace()) {
  372. nsPrefix = ns->getName().str() + "::" + nsPrefix;
  373. }
  374. }
  375. dc = dc->getParent();
  376. }
  377. return nsPrefix;
  378. }
  379. std::string getFnName(const FunctionDecl *fn) {
  380. // Prefix the function name with the struct name if necessary
  381. std::string classOrStructName = "";
  382. if (const auto *memberFn = dyn_cast<CXXMethodDecl>(fn))
  383. if (const auto *st = dyn_cast<CXXRecordDecl>(memberFn->getDeclContext()))
  384. classOrStructName = st->getName().str() + ".";
  385. return getNamespacePrefix(fn) + classOrStructName + fn->getName().str();
  386. }
  387. bool isMemoryObjectDeclaration(SpirvInstruction *inst) {
  388. return isa<SpirvVariable>(inst) || isa<SpirvFunctionParameter>(inst);
  389. }
  390. } // namespace
  391. SpirvEmitter::SpirvEmitter(CompilerInstance &ci)
  392. : theCompilerInstance(ci), astContext(ci.getASTContext()),
  393. diags(ci.getDiagnostics()),
  394. spirvOptions(ci.getCodeGenOpts().SpirvOptions),
  395. entryFunctionName(ci.getCodeGenOpts().HLSLEntryFunction), spvContext(),
  396. featureManager(diags, spirvOptions),
  397. spvBuilder(astContext, spvContext, spirvOptions),
  398. declIdMapper(astContext, spvContext, spvBuilder, *this, featureManager,
  399. spirvOptions),
  400. entryFunction(nullptr), curFunction(nullptr), curThis(nullptr),
  401. seenPushConstantAt(), isSpecConstantMode(false), needsLegalization(false),
  402. beforeHlslLegalization(false), mainSourceFile(nullptr) {
  403. // Get ShaderModel from command line hlsl profile option.
  404. const hlsl::ShaderModel *shaderModel =
  405. hlsl::ShaderModel::GetByName(ci.getCodeGenOpts().HLSLProfile.c_str());
  406. if (shaderModel->GetKind() == hlsl::ShaderModel::Kind::Invalid)
  407. emitError("unknown shader module: %0", {}) << shaderModel->GetName();
  408. if (spirvOptions.invertY && !shaderModel->IsVS() && !shaderModel->IsDS() &&
  409. !shaderModel->IsGS())
  410. emitError("-fvk-invert-y can only be used in VS/DS/GS", {});
  411. if (spirvOptions.useGlLayout && spirvOptions.useDxLayout)
  412. emitError("cannot specify both -fvk-use-dx-layout and -fvk-use-gl-layout",
  413. {});
  414. // Set shader model kind and hlsl major/minor version.
  415. spvContext.setCurrentShaderModelKind(shaderModel->GetKind());
  416. spvContext.setMajorVersion(shaderModel->GetMajor());
  417. spvContext.setMinorVersion(shaderModel->GetMinor());
  418. if (spirvOptions.useDxLayout) {
  419. spirvOptions.cBufferLayoutRule = SpirvLayoutRule::FxcCTBuffer;
  420. spirvOptions.tBufferLayoutRule = SpirvLayoutRule::FxcCTBuffer;
  421. spirvOptions.sBufferLayoutRule = SpirvLayoutRule::FxcSBuffer;
  422. spirvOptions.ampPayloadLayoutRule = SpirvLayoutRule::FxcSBuffer;
  423. } else if (spirvOptions.useGlLayout) {
  424. spirvOptions.cBufferLayoutRule = SpirvLayoutRule::GLSLStd140;
  425. spirvOptions.tBufferLayoutRule = SpirvLayoutRule::GLSLStd430;
  426. spirvOptions.sBufferLayoutRule = SpirvLayoutRule::GLSLStd430;
  427. spirvOptions.ampPayloadLayoutRule = SpirvLayoutRule::GLSLStd430;
  428. } else if (spirvOptions.useScalarLayout) {
  429. spirvOptions.cBufferLayoutRule = SpirvLayoutRule::Scalar;
  430. spirvOptions.tBufferLayoutRule = SpirvLayoutRule::Scalar;
  431. spirvOptions.sBufferLayoutRule = SpirvLayoutRule::Scalar;
  432. spirvOptions.ampPayloadLayoutRule = SpirvLayoutRule::Scalar;
  433. } else {
  434. spirvOptions.cBufferLayoutRule = SpirvLayoutRule::RelaxedGLSLStd140;
  435. spirvOptions.tBufferLayoutRule = SpirvLayoutRule::RelaxedGLSLStd430;
  436. spirvOptions.sBufferLayoutRule = SpirvLayoutRule::RelaxedGLSLStd430;
  437. spirvOptions.ampPayloadLayoutRule = SpirvLayoutRule::RelaxedGLSLStd430;
  438. }
  439. // Set shader module version, source file name, and source file content (if
  440. // needed).
  441. llvm::StringRef source;
  442. std::vector<llvm::StringRef> fileNames;
  443. const auto &inputFiles = ci.getFrontendOpts().Inputs;
  444. // File name
  445. if (spirvOptions.debugInfoFile && !inputFiles.empty()) {
  446. for (const auto &inputFile : inputFiles) {
  447. fileNames.push_back(inputFile.getFile());
  448. }
  449. }
  450. // Source code
  451. if (spirvOptions.debugInfoSource) {
  452. const auto &sm = ci.getSourceManager();
  453. const llvm::MemoryBuffer *mainFile =
  454. sm.getBuffer(sm.getMainFileID(), SourceLocation());
  455. source = StringRef(mainFile->getBufferStart(), mainFile->getBufferSize());
  456. }
  457. mainSourceFile = spvBuilder.setDebugSource(spvContext.getMajorVersion(),
  458. spvContext.getMinorVersion(),
  459. fileNames, source);
  460. // OpenCL.DebugInfo.100 DebugSource
  461. if (spirvOptions.debugInfoRich) {
  462. auto *dbgSrc = spvBuilder.createDebugSource(mainSourceFile->getString());
  463. // spvContext.getDebugInfo().insert() inserts {string key, RichDebugInfo}
  464. // pair and returns {{string key, RichDebugInfo}, true /*Success*/}.
  465. // spvContext.getDebugInfo().insert().first->second is a RichDebugInfo.
  466. auto *richDebugInfo =
  467. &spvContext.getDebugInfo()
  468. .insert(
  469. {mainSourceFile->getString(),
  470. RichDebugInfo(dbgSrc,
  471. spvBuilder.createDebugCompilationUnit(dbgSrc))})
  472. .first->second;
  473. spvContext.pushDebugLexicalScope(richDebugInfo,
  474. richDebugInfo->scopeStack.back());
  475. }
  476. if (spirvOptions.debugInfoTool &&
  477. featureManager.isTargetEnvVulkan1p1OrAbove()) {
  478. // Emit OpModuleProcessed to indicate the commit information.
  479. std::string commitHash =
  480. std::string("dxc-commit-hash: ") + clang::getGitCommitHash();
  481. spvBuilder.addModuleProcessed(commitHash);
  482. // Emit OpModuleProcessed to indicate the command line options that were
  483. // used to generate this module.
  484. if (!spirvOptions.clOptions.empty()) {
  485. // Using this format: "dxc-cl-option: XXXXXX"
  486. std::string clOptionStr = "dxc-cl-option:" + spirvOptions.clOptions;
  487. spvBuilder.addModuleProcessed(clOptionStr);
  488. }
  489. }
  490. }
  491. void SpirvEmitter::HandleTranslationUnit(ASTContext &context) {
  492. // Stop translating if there are errors in previous compilation stages.
  493. if (context.getDiagnostics().hasErrorOccurred())
  494. return;
  495. TranslationUnitDecl *tu = context.getTranslationUnitDecl();
  496. uint32_t numEntryPoints = 0;
  497. // The entry function is the seed of the queue.
  498. for (auto *decl : tu->decls()) {
  499. if (auto *funcDecl = dyn_cast<FunctionDecl>(decl)) {
  500. if (spvContext.isLib()) {
  501. if (const auto *shaderAttr = funcDecl->getAttr<HLSLShaderAttr>()) {
  502. // If we are compiling as a library then add everything that has a
  503. // ShaderAttr.
  504. addFunctionToWorkQueue(getShaderModelKind(shaderAttr->getStage()),
  505. funcDecl, /*isEntryFunction*/ true);
  506. numEntryPoints++;
  507. } else if (funcDecl->getAttr<HLSLExportAttr>()) {
  508. addFunctionToWorkQueue(spvContext.getCurrentShaderModelKind(),
  509. funcDecl, /*isEntryFunction*/ false);
  510. }
  511. } else {
  512. if (funcDecl->getName() == entryFunctionName) {
  513. addFunctionToWorkQueue(spvContext.getCurrentShaderModelKind(),
  514. funcDecl, /*isEntryFunction*/ true);
  515. numEntryPoints++;
  516. }
  517. }
  518. } else {
  519. doDecl(decl);
  520. }
  521. if (context.getDiagnostics().hasErrorOccurred())
  522. return;
  523. }
  524. // Translate all functions reachable from the entry function.
  525. // The queue can grow in the meanwhile; so need to keep evaluating
  526. // workQueue.size().
  527. for (uint32_t i = 0; i < workQueue.size(); ++i) {
  528. const FunctionInfo *curEntryOrCallee = workQueue[i];
  529. spvContext.setCurrentShaderModelKind(curEntryOrCallee->shaderModelKind);
  530. doDecl(curEntryOrCallee->funcDecl);
  531. if (context.getDiagnostics().hasErrorOccurred())
  532. return;
  533. }
  534. // Addressing and memory model are required in a valid SPIR-V module.
  535. spvBuilder.setMemoryModel(spv::AddressingModel::Logical,
  536. spv::MemoryModel::GLSL450);
  537. // Even though the 'workQueue' grows due to the above loop, the first
  538. // 'numEntryPoints' entries in the 'workQueue' are the ones with the HLSL
  539. // 'shader' attribute, and must therefore be entry functions.
  540. assert(numEntryPoints <= workQueue.size());
  541. for (uint32_t i = 0; i < numEntryPoints; ++i) {
  542. // TODO: assign specific StageVars w.r.t. to entry point
  543. const FunctionInfo *entryInfo = workQueue[i];
  544. assert(entryInfo->isEntryFunction);
  545. spvBuilder.addEntryPoint(
  546. getSpirvShaderStage(entryInfo->shaderModelKind),
  547. entryInfo->entryFunction, entryInfo->funcDecl->getName(),
  548. featureManager.isTargetEnvVulkan1p2OrAbove()
  549. ? spvBuilder.getModule()->getVariables()
  550. : llvm::ArrayRef<SpirvVariable *>(declIdMapper.collectStageVars()));
  551. }
  552. // Add Location decorations to stage input/output variables.
  553. if (!declIdMapper.decorateStageIOLocations())
  554. return;
  555. // Add descriptor set and binding decorations to resource variables.
  556. if (!declIdMapper.decorateResourceBindings())
  557. return;
  558. // Add Coherent docrations to resource variables.
  559. if (!declIdMapper.decorateResourceCoherent())
  560. return;
  561. // Output the constructed module.
  562. std::vector<uint32_t> m = spvBuilder.takeModule();
  563. if (!spirvOptions.codeGenHighLevel) {
  564. // In order to flatten composite resources, we must also unroll loops.
  565. // Therefore we should run legalization before optimization.
  566. needsLegalization = needsLegalization ||
  567. declIdMapper.requiresLegalization() ||
  568. spirvOptions.flattenResourceArrays ||
  569. declIdMapper.requiresFlatteningCompositeResources();
  570. // Run legalization passes
  571. if (needsLegalization) {
  572. std::string messages;
  573. if (!spirvToolsLegalize(&m, &messages)) {
  574. emitFatalError("failed to legalize SPIR-V: %0", {}) << messages;
  575. emitNote("please file a bug report on "
  576. "https://github.com/Microsoft/DirectXShaderCompiler/issues "
  577. "with source code if possible",
  578. {});
  579. return;
  580. } else if (!messages.empty()) {
  581. emitWarning("SPIR-V legalization: %0", {}) << messages;
  582. }
  583. }
  584. // Run optimization passes
  585. if (theCompilerInstance.getCodeGenOpts().OptimizationLevel > 0) {
  586. std::string messages;
  587. if (!spirvToolsOptimize(&m, &messages)) {
  588. emitFatalError("failed to optimize SPIR-V: %0", {}) << messages;
  589. emitNote("please file a bug report on "
  590. "https://github.com/Microsoft/DirectXShaderCompiler/issues "
  591. "with source code if possible",
  592. {});
  593. return;
  594. }
  595. }
  596. }
  597. // Validate the generated SPIR-V code
  598. if (!spirvOptions.disableValidation) {
  599. std::string messages;
  600. if (!spirvToolsValidate(&m, &messages)) {
  601. emitFatalError("generated SPIR-V is invalid: %0", {}) << messages;
  602. emitNote("please file a bug report on "
  603. "https://github.com/Microsoft/DirectXShaderCompiler/issues "
  604. "with source code if possible",
  605. {});
  606. return;
  607. }
  608. }
  609. theCompilerInstance.getOutStream()->write(
  610. reinterpret_cast<const char *>(m.data()), m.size() * 4);
  611. }
  612. void SpirvEmitter::doDecl(const Decl *decl) {
  613. if (isa<EmptyDecl>(decl) || isa<TypedefDecl>(decl))
  614. return;
  615. // Implicit decls are lazily created when needed.
  616. if (decl->isImplicit()) {
  617. return;
  618. }
  619. if (const auto *varDecl = dyn_cast<VarDecl>(decl)) {
  620. doVarDecl(varDecl);
  621. } else if (const auto *namespaceDecl = dyn_cast<NamespaceDecl>(decl)) {
  622. for (auto *subDecl : namespaceDecl->decls())
  623. // Note: We only emit functions as they are discovered through the call
  624. // graph starting from the entry-point. We should not emit unused
  625. // functions inside namespaces.
  626. if (!isa<FunctionDecl>(subDecl))
  627. doDecl(subDecl);
  628. } else if (const auto *funcDecl = dyn_cast<FunctionDecl>(decl)) {
  629. doFunctionDecl(funcDecl);
  630. } else if (const auto *bufferDecl = dyn_cast<HLSLBufferDecl>(decl)) {
  631. doHLSLBufferDecl(bufferDecl);
  632. } else if (const auto *recordDecl = dyn_cast<RecordDecl>(decl)) {
  633. doRecordDecl(recordDecl);
  634. } else if (const auto *enumDecl = dyn_cast<EnumDecl>(decl)) {
  635. doEnumDecl(enumDecl);
  636. } else {
  637. emitError("decl type %0 unimplemented", decl->getLocation())
  638. << decl->getDeclKindName();
  639. }
  640. }
  641. RichDebugInfo *
  642. SpirvEmitter::getOrCreateRichDebugInfo(const SourceLocation &loc) {
  643. const StringRef file =
  644. astContext.getSourceManager().getPresumedLoc(loc).getFilename();
  645. auto &debugInfo = spvContext.getDebugInfo();
  646. auto it = debugInfo.find(file);
  647. if (it != debugInfo.end())
  648. return &it->second;
  649. auto *dbgSrc = spvBuilder.createDebugSource(file);
  650. // debugInfo.insert() inserts {string key, RichDebugInfo} pair and
  651. // returns {{string key, RichDebugInfo}, true /*Success*/}.
  652. // debugInfo.insert().first->second is a RichDebugInfo.
  653. return &debugInfo
  654. .insert({file, RichDebugInfo(
  655. dbgSrc, spvBuilder.createDebugCompilationUnit(
  656. dbgSrc))})
  657. .first->second;
  658. }
  659. void SpirvEmitter::doStmt(const Stmt *stmt,
  660. llvm::ArrayRef<const Attr *> attrs) {
  661. if (const auto *compoundStmt = dyn_cast<CompoundStmt>(stmt)) {
  662. if (spirvOptions.debugInfoRich) {
  663. // Any opening of curly braces ('{') starts a CompoundStmt in the AST
  664. // tree. It also means we have a new lexical block!
  665. const auto loc = stmt->getLocStart();
  666. const auto &sm = astContext.getSourceManager();
  667. const uint32_t line = sm.getPresumedLineNumber(loc);
  668. const uint32_t column = sm.getPresumedColumnNumber(loc);
  669. RichDebugInfo *info = getOrCreateRichDebugInfo(loc);
  670. auto *debugLexicalBlock = spvBuilder.createDebugLexicalBlock(
  671. info->source, line, column, info->scopeStack.back());
  672. // Add this lexical block to the stack of lexical scopes.
  673. spvContext.pushDebugLexicalScope(info, debugLexicalBlock);
  674. // Update or add DebugScope.
  675. if (spvBuilder.getInsertPoint()->empty()) {
  676. spvBuilder.getInsertPoint()->updateDebugScope(
  677. new (spvContext) SpirvDebugScope(debugLexicalBlock));
  678. } else if (!spvBuilder.isCurrentBasicBlockTerminated()) {
  679. spvBuilder.createDebugScope(debugLexicalBlock);
  680. }
  681. // Iterate over sub-statements
  682. for (auto *st : compoundStmt->body())
  683. doStmt(st);
  684. // We are done with processing this compound statement. Remove its lexical
  685. // block from the stack of lexical scopes.
  686. spvContext.popDebugLexicalScope(info);
  687. if (!spvBuilder.isCurrentBasicBlockTerminated()) {
  688. spvBuilder.createDebugScope(spvContext.getCurrentLexicalScope());
  689. }
  690. } else {
  691. // Iterate over sub-statements
  692. for (auto *st : compoundStmt->body())
  693. doStmt(st);
  694. }
  695. } else if (const auto *retStmt = dyn_cast<ReturnStmt>(stmt)) {
  696. doReturnStmt(retStmt);
  697. } else if (const auto *declStmt = dyn_cast<DeclStmt>(stmt)) {
  698. doDeclStmt(declStmt);
  699. } else if (const auto *ifStmt = dyn_cast<IfStmt>(stmt)) {
  700. doIfStmt(ifStmt, attrs);
  701. } else if (const auto *switchStmt = dyn_cast<SwitchStmt>(stmt)) {
  702. doSwitchStmt(switchStmt, attrs);
  703. } else if (dyn_cast<CaseStmt>(stmt)) {
  704. processCaseStmtOrDefaultStmt(stmt);
  705. } else if (dyn_cast<DefaultStmt>(stmt)) {
  706. processCaseStmtOrDefaultStmt(stmt);
  707. } else if (const auto *breakStmt = dyn_cast<BreakStmt>(stmt)) {
  708. doBreakStmt(breakStmt);
  709. } else if (const auto *theDoStmt = dyn_cast<DoStmt>(stmt)) {
  710. doDoStmt(theDoStmt, attrs);
  711. } else if (const auto *discardStmt = dyn_cast<DiscardStmt>(stmt)) {
  712. doDiscardStmt(discardStmt);
  713. } else if (const auto *continueStmt = dyn_cast<ContinueStmt>(stmt)) {
  714. doContinueStmt(continueStmt);
  715. } else if (const auto *whileStmt = dyn_cast<WhileStmt>(stmt)) {
  716. doWhileStmt(whileStmt, attrs);
  717. } else if (const auto *forStmt = dyn_cast<ForStmt>(stmt)) {
  718. doForStmt(forStmt, attrs);
  719. } else if (dyn_cast<NullStmt>(stmt)) {
  720. // For the null statement ";". We don't need to do anything.
  721. } else if (const auto *expr = dyn_cast<Expr>(stmt)) {
  722. // All cases for expressions used as statements
  723. doExpr(expr);
  724. } else if (const auto *attrStmt = dyn_cast<AttributedStmt>(stmt)) {
  725. doStmt(attrStmt->getSubStmt(), attrStmt->getAttrs());
  726. } else {
  727. emitError("statement class '%0' unimplemented", stmt->getLocStart())
  728. << stmt->getStmtClassName() << stmt->getSourceRange();
  729. }
  730. }
  731. SpirvInstruction *SpirvEmitter::doExpr(const Expr *expr) {
  732. SpirvInstruction *result = nullptr;
  733. expr = expr->IgnoreParens();
  734. if (const auto *declRefExpr = dyn_cast<DeclRefExpr>(expr)) {
  735. auto *decl = declRefExpr->getDecl();
  736. if (isImplicitVarDeclInVkNamespace(declRefExpr->getDecl())) {
  737. result = doExpr(cast<VarDecl>(decl)->getInit());
  738. } else {
  739. result = declIdMapper.getDeclEvalInfo(decl, expr->getLocStart());
  740. }
  741. } else if (const auto *memberExpr = dyn_cast<MemberExpr>(expr)) {
  742. result = doMemberExpr(memberExpr);
  743. } else if (const auto *castExpr = dyn_cast<CastExpr>(expr)) {
  744. result = doCastExpr(castExpr);
  745. } else if (const auto *initListExpr = dyn_cast<InitListExpr>(expr)) {
  746. result = doInitListExpr(initListExpr);
  747. } else if (const auto *boolLiteral = dyn_cast<CXXBoolLiteralExpr>(expr)) {
  748. result =
  749. spvBuilder.getConstantBool(boolLiteral->getValue(), isSpecConstantMode);
  750. result->setRValue();
  751. } else if (const auto *intLiteral = dyn_cast<IntegerLiteral>(expr)) {
  752. result = translateAPInt(intLiteral->getValue(), expr->getType());
  753. result->setRValue();
  754. } else if (const auto *floatLiteral = dyn_cast<FloatingLiteral>(expr)) {
  755. result = translateAPFloat(floatLiteral->getValue(), expr->getType());
  756. result->setRValue();
  757. } else if (const auto *stringLiteral = dyn_cast<StringLiteral>(expr)) {
  758. result = spvBuilder.getString(stringLiteral->getString());
  759. } else if (const auto *compoundAssignOp =
  760. dyn_cast<CompoundAssignOperator>(expr)) {
  761. // CompoundAssignOperator is a subclass of BinaryOperator. It should be
  762. // checked before BinaryOperator.
  763. result = doCompoundAssignOperator(compoundAssignOp);
  764. } else if (const auto *binOp = dyn_cast<BinaryOperator>(expr)) {
  765. result = doBinaryOperator(binOp);
  766. } else if (const auto *unaryOp = dyn_cast<UnaryOperator>(expr)) {
  767. result = doUnaryOperator(unaryOp);
  768. } else if (const auto *vecElemExpr = dyn_cast<HLSLVectorElementExpr>(expr)) {
  769. result = doHLSLVectorElementExpr(vecElemExpr);
  770. } else if (const auto *matElemExpr = dyn_cast<ExtMatrixElementExpr>(expr)) {
  771. result = doExtMatrixElementExpr(matElemExpr);
  772. } else if (const auto *funcCall = dyn_cast<CallExpr>(expr)) {
  773. result = doCallExpr(funcCall);
  774. } else if (const auto *subscriptExpr = dyn_cast<ArraySubscriptExpr>(expr)) {
  775. result = doArraySubscriptExpr(subscriptExpr);
  776. } else if (const auto *condExpr = dyn_cast<ConditionalOperator>(expr)) {
  777. result = doConditionalOperator(condExpr);
  778. } else if (const auto *defaultArgExpr = dyn_cast<CXXDefaultArgExpr>(expr)) {
  779. result = doExpr(defaultArgExpr->getParam()->getDefaultArg());
  780. } else if (isa<CXXThisExpr>(expr)) {
  781. assert(curThis);
  782. result = curThis;
  783. } else if (isa<CXXConstructExpr>(expr)) {
  784. result = curThis;
  785. } else if (const auto *unaryExpr = dyn_cast<UnaryExprOrTypeTraitExpr>(expr)) {
  786. result = doUnaryExprOrTypeTraitExpr(unaryExpr);
  787. } else {
  788. emitError("expression class '%0' unimplemented", expr->getExprLoc())
  789. << expr->getStmtClassName() << expr->getSourceRange();
  790. }
  791. return result;
  792. }
  793. SpirvInstruction *SpirvEmitter::loadIfGLValue(const Expr *expr) {
  794. // We are trying to load the value here, which is what an LValueToRValue
  795. // implicit cast is intended to do. We can ignore the cast if exists.
  796. expr = expr->IgnoreParenLValueCasts();
  797. return loadIfGLValue(expr, doExpr(expr));
  798. }
  799. SpirvInstruction *SpirvEmitter::loadIfGLValue(const Expr *expr,
  800. SpirvInstruction *info) {
  801. const auto exprType = expr->getType();
  802. // Do nothing if this is already rvalue
  803. if (!info || info->isRValue())
  804. return info;
  805. // Check whether we are trying to load an array of opaque objects as a whole.
  806. // If true, we are likely to copy it as a whole. To assist per-element
  807. // copying, avoid the load here and return the pointer directly.
  808. // TODO: consider moving this hack into SPIRV-Tools as a transformation.
  809. if (isOpaqueArrayType(exprType))
  810. return info;
  811. // Check whether we are trying to load an externally visible structured/byte
  812. // buffer as a whole. If true, it means we are creating alias for it. Avoid
  813. // the load and write the pointer directly to the alias variable then.
  814. //
  815. // Also for the case of alias function returns. If we are trying to load an
  816. // alias function return as a whole, it means we are assigning it to another
  817. // alias variable. Avoid the load and write the pointer directly.
  818. //
  819. // Note: legalization specific code
  820. if (isReferencingNonAliasStructuredOrByteBuffer(expr)) {
  821. return info;
  822. }
  823. if (loadIfAliasVarRef(expr, &info)) {
  824. // We are loading an alias variable as a whole here. This is likely for
  825. // wholesale assignments or function returns. Need to load the pointer.
  826. //
  827. // Note: legalization specific code
  828. return info;
  829. }
  830. SpirvInstruction *loadedInstr = nullptr;
  831. // TODO: Ouch. Very hacky. We need special path to get the value type if
  832. // we are loading a whole ConstantBuffer/TextureBuffer since the normal
  833. // type translation path won't work.
  834. if (const auto *declContext = isConstantTextureBufferDeclRef(expr)) {
  835. loadedInstr = spvBuilder.createLoad(
  836. declIdMapper.getCTBufferPushConstantType(declContext), info,
  837. expr->getExprLoc());
  838. } else {
  839. loadedInstr = spvBuilder.createLoad(exprType, info, expr->getExprLoc());
  840. }
  841. assert(loadedInstr);
  842. // Special-case: According to the SPIR-V Spec: There is no physical size or
  843. // bit pattern defined for boolean type. Therefore an unsigned integer is used
  844. // to represent booleans when layout is required. In such cases, after loading
  845. // the uint, we should perform a comparison.
  846. {
  847. uint32_t vecSize = 1, numRows = 0, numCols = 0;
  848. if (info->getLayoutRule() != SpirvLayoutRule::Void &&
  849. isBoolOrVecMatOfBoolType(exprType)) {
  850. QualType uintType = astContext.UnsignedIntTy;
  851. if (isScalarType(exprType) || isVectorType(exprType, nullptr, &vecSize)) {
  852. const auto fromType =
  853. vecSize == 1 ? uintType
  854. : astContext.getExtVectorType(uintType, vecSize);
  855. loadedInstr =
  856. castToBool(loadedInstr, fromType, exprType, expr->getLocStart());
  857. } else {
  858. const bool isMat = isMxNMatrix(exprType, nullptr, &numRows, &numCols);
  859. assert(isMat);
  860. (void)isMat;
  861. const clang::Type *type = exprType.getCanonicalType().getTypePtr();
  862. const RecordType *RT = cast<RecordType>(type);
  863. const ClassTemplateSpecializationDecl *templateSpecDecl =
  864. cast<ClassTemplateSpecializationDecl>(RT->getDecl());
  865. ClassTemplateDecl *templateDecl =
  866. templateSpecDecl->getSpecializedTemplate();
  867. const auto fromType = getHLSLMatrixType(
  868. astContext, theCompilerInstance.getSema(), templateDecl,
  869. astContext.UnsignedIntTy, numRows, numCols);
  870. loadedInstr =
  871. castToBool(loadedInstr, fromType, exprType, expr->getLocStart());
  872. }
  873. // Now that it is converted to Bool, it has no layout rule.
  874. // This result-id should be evaluated as bool from here on out.
  875. loadedInstr->setLayoutRule(SpirvLayoutRule::Void);
  876. }
  877. }
  878. loadedInstr->setRValue();
  879. return loadedInstr;
  880. }
  881. SpirvInstruction *SpirvEmitter::loadIfAliasVarRef(const Expr *expr) {
  882. auto *instr = doExpr(expr);
  883. loadIfAliasVarRef(expr, &instr);
  884. return instr;
  885. }
  886. bool SpirvEmitter::loadIfAliasVarRef(const Expr *varExpr,
  887. SpirvInstruction **instr) {
  888. assert(instr);
  889. if ((*instr) && (*instr)->containsAliasComponent() &&
  890. isAKindOfStructuredOrByteBuffer(varExpr->getType())) {
  891. // Load the pointer of the aliased-to-variable if the expression has a
  892. // pointer to pointer type.
  893. if (varExpr->isGLValue()) {
  894. *instr = spvBuilder.createLoad(varExpr->getType(), *instr,
  895. varExpr->getExprLoc());
  896. }
  897. return true;
  898. }
  899. return false;
  900. }
  901. SpirvInstruction *SpirvEmitter::castToType(SpirvInstruction *value,
  902. QualType fromType, QualType toType,
  903. SourceLocation srcLoc) {
  904. if (isFloatOrVecMatOfFloatType(toType))
  905. return castToFloat(value, fromType, toType, srcLoc);
  906. // Order matters here. Bool (vector) values will also be considered as uint
  907. // (vector) values. So given a bool (vector) argument, isUintOrVecOfUintType()
  908. // will also return true. We need to check bool before uint. The opposite is
  909. // not true.
  910. if (isBoolOrVecMatOfBoolType(toType))
  911. return castToBool(value, fromType, toType, srcLoc);
  912. if (isSintOrVecMatOfSintType(toType) || isUintOrVecMatOfUintType(toType))
  913. return castToInt(value, fromType, toType, srcLoc);
  914. emitError("casting to type %0 unimplemented", {}) << toType;
  915. return nullptr;
  916. }
  917. void SpirvEmitter::doFunctionDecl(const FunctionDecl *decl) {
  918. // Forward declaration of a function inside another.
  919. if(!decl->isThisDeclarationADefinition()) {
  920. addFunctionToWorkQueue(spvContext.getCurrentShaderModelKind(), decl,
  921. /*isEntryFunction*/ false);
  922. return;
  923. }
  924. // A RAII class for maintaining the current function under traversal.
  925. class FnEnvRAII {
  926. public:
  927. // Creates a new instance which sets fnEnv to the newFn on creation,
  928. // and resets fnEnv to its original value on destruction.
  929. FnEnvRAII(const FunctionDecl **fnEnv, const FunctionDecl *newFn)
  930. : oldFn(*fnEnv), fnSlot(fnEnv) {
  931. *fnEnv = newFn;
  932. }
  933. ~FnEnvRAII() { *fnSlot = oldFn; }
  934. private:
  935. const FunctionDecl *oldFn;
  936. const FunctionDecl **fnSlot;
  937. };
  938. FnEnvRAII fnEnvRAII(&curFunction, decl);
  939. // We are about to start translation for a new function. Clear the break stack
  940. // and the continue stack.
  941. breakStack = std::stack<SpirvBasicBlock *>();
  942. continueStack = std::stack<SpirvBasicBlock *>();
  943. // This will allow the entry-point name to be something like
  944. // myNamespace::myEntrypointFunc.
  945. std::string funcName = getFnName(decl);
  946. std::string debugFuncName = funcName;
  947. SpirvFunction *func = declIdMapper.getOrRegisterFn(decl);
  948. const auto iter = functionInfoMap.find(decl);
  949. if (iter != functionInfoMap.end()) {
  950. const auto &entryInfo = iter->second;
  951. if (entryInfo->isEntryFunction) {
  952. funcName = "src." + funcName;
  953. // Create wrapper for the entry function
  954. if (!emitEntryFunctionWrapper(decl, func))
  955. return;
  956. }
  957. }
  958. const QualType retType =
  959. declIdMapper.getTypeAndCreateCounterForPotentialAliasVar(decl);
  960. spvBuilder.beginFunction(retType, decl->getLocStart(), funcName,
  961. decl->hasAttr<HLSLPreciseAttr>(),
  962. decl->hasAttr<NoInlineAttr>(), func);
  963. auto loc = decl->getLocStart();
  964. RichDebugInfo *info = nullptr;
  965. const auto &sm = astContext.getSourceManager();
  966. if (spirvOptions.debugInfoRich && decl->hasBody()) {
  967. const uint32_t line = sm.getPresumedLineNumber(loc);
  968. const uint32_t column = sm.getPresumedColumnNumber(loc);
  969. info = getOrCreateRichDebugInfo(loc);
  970. auto *source = info->source;
  971. // Note that info->scopeStack.back() is a lexical scope of the function
  972. // caller.
  973. auto *parentScope = info->compilationUnit;
  974. // TODO: figure out the proper flag based on the function decl.
  975. // using FlagIsPublic for now.
  976. uint32_t flags = 3u;
  977. // The line number in the source program at which the function scope begins.
  978. auto scopeLine = sm.getPresumedLineNumber(decl->getBody()->getLocStart());
  979. SpirvDebugFunction *debugFunction = spvBuilder.createDebugFunction(
  980. decl, debugFuncName, source, line, column, parentScope, "", flags,
  981. scopeLine, func);
  982. func->setDebugScope(new (spvContext) SpirvDebugScope(debugFunction));
  983. spvContext.pushDebugLexicalScope(info, debugFunction);
  984. }
  985. bool isNonStaticMemberFn = false;
  986. if (const auto *memberFn = dyn_cast<CXXMethodDecl>(decl)) {
  987. if (!memberFn->isStatic()) {
  988. // For non-static member function, the first parameter should be the
  989. // object on which we are invoking this method.
  990. QualType valueType = memberFn->getThisType(astContext)->getPointeeType();
  991. // Remember the parameter for the 'this' object so later we can handle
  992. // CXXThisExpr correctly.
  993. curThis = spvBuilder.addFnParam(valueType, /*isPrecise*/ false,
  994. decl->getLocStart(), "param.this");
  995. if (isOrContainsAKindOfStructuredOrByteBuffer(valueType)) {
  996. curThis->setContainsAliasComponent(true);
  997. needsLegalization = true;
  998. }
  999. if (spirvOptions.debugInfoRich) {
  1000. // Add DebugLocalVariable information
  1001. const auto &sm = astContext.getSourceManager();
  1002. const uint32_t line = sm.getPresumedLineNumber(loc);
  1003. const uint32_t column = sm.getPresumedColumnNumber(loc);
  1004. if (!info)
  1005. info = getOrCreateRichDebugInfo(loc);
  1006. // TODO: replace this with FlagArtificial|FlagObjectPointer.
  1007. uint32_t flags = (1 << 5) | (1 << 8);
  1008. auto *debugLocalVar = spvBuilder.createDebugLocalVariable(
  1009. valueType, "this", info->source, line, column,
  1010. info->scopeStack.back(), flags, 1);
  1011. spvBuilder.createDebugDeclare(debugLocalVar, curThis);
  1012. }
  1013. isNonStaticMemberFn = true;
  1014. }
  1015. }
  1016. // Create all parameters.
  1017. for (uint32_t i = 0; i < decl->getNumParams(); ++i) {
  1018. const ParmVarDecl *paramDecl = decl->getParamDecl(i);
  1019. if (spvContext.isHS() && decl == patchConstFunc &&
  1020. hlsl::IsHLSLOutputPatchType(paramDecl->getType())) {
  1021. // Since the output patch used in hull shaders is translated to
  1022. // a variable with Output storage class, there is no need
  1023. // to pass the variable as function parameter in SPIR-V.
  1024. continue;
  1025. }
  1026. (void)declIdMapper.createFnParam(paramDecl, i + 1 + isNonStaticMemberFn);
  1027. }
  1028. if (decl->hasBody()) {
  1029. // The entry basic block.
  1030. auto *entryLabel = spvBuilder.createBasicBlock("bb.entry");
  1031. spvBuilder.setInsertPoint(entryLabel);
  1032. // Process all statments in the body.
  1033. doStmt(decl->getBody());
  1034. // We have processed all Stmts in this function and now in the last
  1035. // basic block. Make sure we have a termination instruction.
  1036. if (!spvBuilder.isCurrentBasicBlockTerminated()) {
  1037. const auto retType = decl->getReturnType();
  1038. const auto returnLoc = decl->getBody()->getLocEnd();
  1039. if (retType->isVoidType()) {
  1040. spvBuilder.createReturn(returnLoc);
  1041. } else {
  1042. // If the source code does not provide a proper return value for some
  1043. // control flow path, it's undefined behavior. We just return null
  1044. // value here.
  1045. spvBuilder.createReturnValue(spvBuilder.getConstantNull(retType),
  1046. returnLoc);
  1047. }
  1048. }
  1049. }
  1050. spvBuilder.endFunction();
  1051. if (spirvOptions.debugInfoRich) {
  1052. spvContext.popDebugLexicalScope(info);
  1053. }
  1054. }
  1055. bool SpirvEmitter::validateVKAttributes(const NamedDecl *decl) {
  1056. bool success = true;
  1057. if (const auto *varDecl = dyn_cast<VarDecl>(decl)) {
  1058. const auto varType = varDecl->getType();
  1059. if ((isSubpassInput(varType) || isSubpassInputMS(varType)) &&
  1060. !varDecl->hasAttr<VKInputAttachmentIndexAttr>()) {
  1061. emitError("missing vk::input_attachment_index attribute",
  1062. varDecl->getLocation());
  1063. success = false;
  1064. }
  1065. }
  1066. if (decl->getAttr<VKInputAttachmentIndexAttr>()) {
  1067. if (!spvContext.isPS()) {
  1068. emitError("SubpassInput(MS) only allowed in pixel shader",
  1069. decl->getLocation());
  1070. success = false;
  1071. }
  1072. if (!decl->isExternallyVisible()) {
  1073. emitError("SubpassInput(MS) must be externally visible",
  1074. decl->getLocation());
  1075. success = false;
  1076. }
  1077. // We only allow VKInputAttachmentIndexAttr to be attached to global
  1078. // variables. So it should be fine to cast here.
  1079. const auto elementType =
  1080. hlsl::GetHLSLResourceResultType(cast<VarDecl>(decl)->getType());
  1081. if (!isScalarType(elementType) && !isVectorType(elementType)) {
  1082. emitError(
  1083. "only scalar/vector types allowed as SubpassInput(MS) parameter type",
  1084. decl->getLocation());
  1085. // Return directly to avoid further type processing, which will hit
  1086. // asserts when lowering the type.
  1087. return false;
  1088. }
  1089. }
  1090. // The frontend will make sure that
  1091. // * vk::push_constant applies to global variables of struct type
  1092. // * vk::binding applies to global variables or cbuffers/tbuffers
  1093. // * vk::counter_binding applies to global variables of RW/Append/Consume
  1094. // StructuredBuffer
  1095. // * vk::location applies to function parameters/returns and struct fields
  1096. // So the only case we need to check co-existence is vk::push_constant and
  1097. // vk::binding.
  1098. if (const auto *pcAttr = decl->getAttr<VKPushConstantAttr>()) {
  1099. const auto loc = pcAttr->getLocation();
  1100. if (seenPushConstantAt.isInvalid()) {
  1101. seenPushConstantAt = loc;
  1102. } else {
  1103. // TODO: Actually this is slightly incorrect. The Vulkan spec says:
  1104. // There must be no more than one push constant block statically used
  1105. // per shader entry point.
  1106. // But we are checking whether there are more than one push constant
  1107. // blocks defined. Tracking usage requires more work.
  1108. emitError("cannot have more than one push constant block", loc);
  1109. emitNote("push constant block previously defined here",
  1110. seenPushConstantAt);
  1111. success = false;
  1112. }
  1113. if (decl->hasAttr<VKBindingAttr>()) {
  1114. emitError("vk::push_constant attribute cannot be used together with "
  1115. "vk::binding attribute",
  1116. loc);
  1117. success = false;
  1118. }
  1119. }
  1120. // vk::shader_record_nv is supported only on cbuffer/ConstantBuffer
  1121. if (const auto *srbAttr = decl->getAttr<VKShaderRecordNVAttr>()) {
  1122. const auto loc = srbAttr->getLocation();
  1123. const HLSLBufferDecl *bufDecl = nullptr;
  1124. bool isValidType = false;
  1125. if ((bufDecl = dyn_cast<HLSLBufferDecl>(decl)))
  1126. isValidType = bufDecl->isCBuffer();
  1127. else if ((bufDecl = dyn_cast<HLSLBufferDecl>(decl->getDeclContext())))
  1128. isValidType = bufDecl->isCBuffer();
  1129. else if (isa<VarDecl>(decl))
  1130. isValidType = isConstantBuffer(dyn_cast<VarDecl>(decl)->getType());
  1131. if (!isValidType) {
  1132. emitError(
  1133. "vk::shader_record_nv can be applied only to cbuffer/ConstantBuffer",
  1134. loc);
  1135. success = false;
  1136. }
  1137. if (decl->hasAttr<VKBindingAttr>()) {
  1138. emitError("vk::shader_record_nv attribute cannot be used together with "
  1139. "vk::binding attribute",
  1140. loc);
  1141. success = false;
  1142. }
  1143. }
  1144. // vk::shader_record_ext is supported only on cbuffer/ConstantBuffer
  1145. if (const auto *srbAttr = decl->getAttr<VKShaderRecordEXTAttr>()) {
  1146. const auto loc = srbAttr->getLocation();
  1147. const HLSLBufferDecl *bufDecl = nullptr;
  1148. bool isValidType = false;
  1149. if ((bufDecl = dyn_cast<HLSLBufferDecl>(decl)))
  1150. isValidType = bufDecl->isCBuffer();
  1151. else if ((bufDecl = dyn_cast<HLSLBufferDecl>(decl->getDeclContext())))
  1152. isValidType = bufDecl->isCBuffer();
  1153. else if (isa<VarDecl>(decl))
  1154. isValidType = isConstantBuffer(dyn_cast<VarDecl>(decl)->getType());
  1155. if (!isValidType) {
  1156. emitError(
  1157. "vk::shader_record_ext can be applied only to cbuffer/ConstantBuffer",
  1158. loc);
  1159. success = false;
  1160. }
  1161. if (decl->hasAttr<VKBindingAttr>()) {
  1162. emitError("vk::shader_record_ext attribute cannot be used together with "
  1163. "vk::binding attribute",
  1164. loc);
  1165. success = false;
  1166. }
  1167. }
  1168. return success;
  1169. }
  1170. void SpirvEmitter::doHLSLBufferDecl(const HLSLBufferDecl *bufferDecl) {
  1171. // This is a cbuffer/tbuffer decl.
  1172. // Check and emit warnings for member intializers which are not
  1173. // supported in Vulkan
  1174. for (const auto *member : bufferDecl->decls()) {
  1175. if (const auto *varMember = dyn_cast<VarDecl>(member)) {
  1176. if (!spirvOptions.noWarnIgnoredFeatures) {
  1177. if (const auto *init = varMember->getInit())
  1178. emitWarning("%select{tbuffer|cbuffer}0 member initializer "
  1179. "ignored since no Vulkan equivalent",
  1180. init->getExprLoc())
  1181. << bufferDecl->isCBuffer() << init->getSourceRange();
  1182. }
  1183. // We cannot handle external initialization of column-major matrices now.
  1184. if (isOrContainsNonFpColMajorMatrix(astContext, spirvOptions,
  1185. varMember->getType(), varMember)) {
  1186. emitError("externally initialized non-floating-point column-major "
  1187. "matrices not supported yet",
  1188. varMember->getLocation());
  1189. }
  1190. }
  1191. }
  1192. if (!validateVKAttributes(bufferDecl))
  1193. return;
  1194. if (bufferDecl->hasAttr<VKShaderRecordNVAttr>()) {
  1195. (void)declIdMapper.createShaderRecordBuffer(
  1196. bufferDecl, DeclResultIdMapper::ContextUsageKind::ShaderRecordBufferNV);
  1197. } else if (bufferDecl->hasAttr<VKShaderRecordEXTAttr>()) {
  1198. (void)declIdMapper.createShaderRecordBuffer(
  1199. bufferDecl,
  1200. DeclResultIdMapper::ContextUsageKind::ShaderRecordBufferEXT);
  1201. } else {
  1202. (void)declIdMapper.createCTBuffer(bufferDecl);
  1203. }
  1204. }
  1205. void SpirvEmitter::doRecordDecl(const RecordDecl *recordDecl) {
  1206. // Ignore implict records
  1207. // Somehow we'll have implicit records with:
  1208. // static const int Length = count;
  1209. // that can mess up with the normal CodeGen.
  1210. if (recordDecl->isImplicit())
  1211. return;
  1212. // Handle each static member with inline initializer.
  1213. // Each static member has a corresponding VarDecl inside the
  1214. // RecordDecl. For those defined in the translation unit,
  1215. // their VarDecls do not have initializer.
  1216. for (auto *subDecl : recordDecl->decls())
  1217. if (auto *varDecl = dyn_cast<VarDecl>(subDecl))
  1218. if (varDecl->isStaticDataMember() && varDecl->hasInit())
  1219. doVarDecl(varDecl);
  1220. }
  1221. void SpirvEmitter::doEnumDecl(const EnumDecl *decl) {
  1222. for (auto it = decl->enumerator_begin(); it != decl->enumerator_end(); ++it)
  1223. declIdMapper.createEnumConstant(*it);
  1224. }
  1225. void SpirvEmitter::doVarDecl(const VarDecl *decl) {
  1226. if (!validateVKAttributes(decl))
  1227. return;
  1228. const auto loc = decl->getLocation();
  1229. // HLSL has the 'string' type which can be used for rare purposes such as
  1230. // printf (SPIR-V's DebugPrintf). SPIR-V does not have a 'char' or 'string'
  1231. // type, and therefore any variable of such type should not be created.
  1232. // DeclResultIdMapper maps such decl to an OpString instruction that
  1233. // represents the variable's initializer literal.
  1234. if (isStringType(decl->getType())) {
  1235. declIdMapper.createOrUpdateStringVar(decl);
  1236. return;
  1237. }
  1238. // We cannot handle external initialization of column-major matrices now.
  1239. if (isExternalVar(decl) &&
  1240. isOrContainsNonFpColMajorMatrix(astContext, spirvOptions, decl->getType(),
  1241. decl)) {
  1242. emitError("externally initialized non-floating-point column-major "
  1243. "matrices not supported yet",
  1244. loc);
  1245. }
  1246. // Reject arrays of RW/append/consume structured buffers. They have assoicated
  1247. // counters, which are quite nasty to handle.
  1248. if (decl->getType()->isArrayType()) {
  1249. auto type = decl->getType();
  1250. do {
  1251. type = type->getAsArrayTypeUnsafe()->getElementType();
  1252. } while (type->isArrayType());
  1253. if (isRWAppendConsumeSBuffer(type)) {
  1254. emitError("arrays of RW/append/consume structured buffers unsupported",
  1255. loc);
  1256. return;
  1257. }
  1258. }
  1259. if (decl->hasAttr<VKConstantIdAttr>()) {
  1260. // This is a VarDecl for specialization constant.
  1261. createSpecConstant(decl);
  1262. return;
  1263. }
  1264. if (decl->hasAttr<VKPushConstantAttr>()) {
  1265. // This is a VarDecl for PushConstant block.
  1266. (void)declIdMapper.createPushConstant(decl);
  1267. return;
  1268. }
  1269. if (decl->hasAttr<VKShaderRecordNVAttr>()) {
  1270. (void)declIdMapper.createShaderRecordBuffer(
  1271. decl, DeclResultIdMapper::ContextUsageKind::ShaderRecordBufferNV);
  1272. return;
  1273. }
  1274. if (decl->hasAttr<VKShaderRecordEXTAttr>()) {
  1275. (void)declIdMapper.createShaderRecordBuffer(
  1276. decl, DeclResultIdMapper::ContextUsageKind::ShaderRecordBufferEXT);
  1277. return;
  1278. }
  1279. // We can have VarDecls inside cbuffer/tbuffer. For those VarDecls, we need
  1280. // to emit their cbuffer/tbuffer as a whole and access each individual one
  1281. // using access chains.
  1282. // cbuffers and tbuffers are HLSLBufferDecls
  1283. // ConstantBuffers and TextureBuffers are not HLSLBufferDecls.
  1284. if (const auto *bufferDecl =
  1285. dyn_cast<HLSLBufferDecl>(decl->getDeclContext())) {
  1286. // This is a VarDecl of cbuffer/tbuffer type.
  1287. doHLSLBufferDecl(bufferDecl);
  1288. return;
  1289. }
  1290. if (isConstantTextureBuffer(decl->getType())) {
  1291. // This is a VarDecl of ConstantBuffer/TextureBuffer type.
  1292. (void)declIdMapper.createCTBuffer(decl);
  1293. return;
  1294. }
  1295. SpirvVariable *var = nullptr;
  1296. // The contents in externally visible variables can be updated via the
  1297. // pipeline. They should be handled differently from file and function scope
  1298. // variables.
  1299. // File scope variables (static "global" and "local" variables) belongs to
  1300. // the Private storage class, while function scope variables (normal "local"
  1301. // variables) belongs to the Function storage class.
  1302. if (isExternalVar(decl)) {
  1303. var = declIdMapper.createExternVar(decl);
  1304. } else {
  1305. // We already know the variable is not externally visible here. If it does
  1306. // not have local storage, it should be file scope variable.
  1307. const bool isFileScopeVar = !decl->hasLocalStorage();
  1308. if (isFileScopeVar)
  1309. var = declIdMapper.createFileVar(decl, llvm::None);
  1310. else
  1311. var = declIdMapper.createFnVar(decl, llvm::None);
  1312. // Emit OpStore to initialize the variable
  1313. // TODO: revert back to use OpVariable initializer
  1314. // We should only evaluate the initializer once for a static variable.
  1315. if (isFileScopeVar) {
  1316. if (decl->isStaticLocal()) {
  1317. initOnce(decl->getType(), decl->getName(), var, decl->getInit());
  1318. } else {
  1319. // Defer to initialize these global variables at the beginning of the
  1320. // entry function.
  1321. toInitGloalVars.push_back(decl);
  1322. }
  1323. }
  1324. // Function local variables. Just emit OpStore at the current insert point.
  1325. else if (const Expr *init = decl->getInit()) {
  1326. if (auto *constInit = tryToEvaluateAsConst(init)) {
  1327. spvBuilder.createStore(var, constInit, loc);
  1328. } else {
  1329. storeValue(var, loadIfGLValue(init), decl->getType(), loc);
  1330. }
  1331. // Update counter variable associated with local variables
  1332. tryToAssignCounterVar(decl, init);
  1333. }
  1334. if (!isFileScopeVar && spirvOptions.debugInfoRich) {
  1335. // Add DebugLocalVariable information
  1336. const auto &sm = astContext.getSourceManager();
  1337. const uint32_t line = sm.getPresumedLineNumber(loc);
  1338. const uint32_t column = sm.getPresumedColumnNumber(loc);
  1339. const auto *info = getOrCreateRichDebugInfo(loc);
  1340. // TODO: replace this with FlagIsLocal enum.
  1341. uint32_t flags = 1 << 2;
  1342. auto *debugLocalVar = spvBuilder.createDebugLocalVariable(
  1343. decl->getType(), decl->getName(), info->source, line, column,
  1344. info->scopeStack.back(), flags);
  1345. spvBuilder.createDebugDeclare(debugLocalVar, var);
  1346. }
  1347. // Variables that are not externally visible and of opaque types should
  1348. // request legalization.
  1349. if (!needsLegalization && isOpaqueType(decl->getType()))
  1350. needsLegalization = true;
  1351. }
  1352. // All variables that are of opaque struct types should request legalization.
  1353. if (!needsLegalization && isOpaqueStructType(decl->getType()))
  1354. needsLegalization = true;
  1355. }
  1356. spv::LoopControlMask SpirvEmitter::translateLoopAttribute(const Stmt *stmt,
  1357. const Attr &attr) {
  1358. switch (attr.getKind()) {
  1359. case attr::HLSLLoop:
  1360. case attr::HLSLFastOpt:
  1361. return spv::LoopControlMask::DontUnroll;
  1362. case attr::HLSLUnroll:
  1363. return spv::LoopControlMask::Unroll;
  1364. case attr::HLSLAllowUAVCondition:
  1365. if (!spirvOptions.noWarnIgnoredFeatures) {
  1366. emitWarning("unsupported allow_uav_condition attribute ignored",
  1367. stmt->getLocStart());
  1368. }
  1369. break;
  1370. default:
  1371. llvm_unreachable("found unknown loop attribute");
  1372. }
  1373. return spv::LoopControlMask::MaskNone;
  1374. }
  1375. void SpirvEmitter::doDiscardStmt(const DiscardStmt *discardStmt) {
  1376. assert(!spvBuilder.isCurrentBasicBlockTerminated());
  1377. // The discard statement can only be called from a pixel shader
  1378. if (!spvContext.isPS()) {
  1379. emitError("discard statement may only be used in pixel shaders",
  1380. discardStmt->getLoc());
  1381. return;
  1382. }
  1383. if (featureManager.isExtensionEnabled(
  1384. Extension::EXT_demote_to_helper_invocation)) {
  1385. // SPV_EXT_demote_to_helper_invocation SPIR-V extension provides a new
  1386. // instruction OpDemoteToHelperInvocationEXT allowing shaders to "demote" a
  1387. // fragment shader invocation to behave like a helper invocation for its
  1388. // duration. The demoted invocation will have no further side effects and
  1389. // will not output to the framebuffer, but remains active and can
  1390. // participate in computing derivatives and in subgroup operations. This is
  1391. // a better match for the "discard" instruction in HLSL.
  1392. spvBuilder.createDemoteToHelperInvocationEXT(discardStmt->getLoc());
  1393. } else {
  1394. // Note: if/when the demote behavior becomes part of the core Vulkan spec,
  1395. // we should no longer generate OpKill for 'discard', and always generate
  1396. // the demote behavior.
  1397. spvBuilder.createKill(discardStmt->getLoc());
  1398. // Some statements that alter the control flow (break, continue, return, and
  1399. // discard), require creation of a new basic block to hold any statement
  1400. // that may follow them.
  1401. auto *newBB = spvBuilder.createBasicBlock();
  1402. spvBuilder.setInsertPoint(newBB);
  1403. }
  1404. }
  1405. void SpirvEmitter::doDoStmt(const DoStmt *theDoStmt,
  1406. llvm::ArrayRef<const Attr *> attrs) {
  1407. // do-while loops are composed of:
  1408. //
  1409. // do {
  1410. // <body>
  1411. // } while(<check>);
  1412. //
  1413. // SPIR-V requires loops to have a merge basic block as well as a continue
  1414. // basic block. Even though do-while loops do not have an explicit continue
  1415. // block as in for-loops, we still do need to create a continue block.
  1416. //
  1417. // Since SPIR-V requires structured control flow, we need two more basic
  1418. // blocks, <header> and <merge>. <header> is the block before control flow
  1419. // diverges, and <merge> is the block where control flow subsequently
  1420. // converges. The <check> can be performed in the <continue> basic block.
  1421. // The final CFG should normally be like the following. Exceptions
  1422. // will occur with non-local exits like loop breaks or early returns.
  1423. //
  1424. // +----------+
  1425. // | header | <-----------------------------------+
  1426. // +----------+ |
  1427. // | | (true)
  1428. // v |
  1429. // +------+ +--------------------+ |
  1430. // | body | ----> | continue (<check>) |-----------+
  1431. // +------+ +--------------------+
  1432. // |
  1433. // | (false)
  1434. // +-------+ |
  1435. // | merge | <-------------+
  1436. // +-------+
  1437. //
  1438. // For more details, see "2.11. Structured Control Flow" in the SPIR-V spec.
  1439. const spv::LoopControlMask loopControl =
  1440. attrs.empty() ? spv::LoopControlMask::MaskNone
  1441. : translateLoopAttribute(theDoStmt, *attrs.front());
  1442. // Create basic blocks
  1443. auto *headerBB = spvBuilder.createBasicBlock("do_while.header");
  1444. auto *bodyBB = spvBuilder.createBasicBlock("do_while.body");
  1445. auto *continueBB = spvBuilder.createBasicBlock("do_while.continue");
  1446. auto *mergeBB = spvBuilder.createBasicBlock("do_while.merge");
  1447. // Make sure any continue statements branch to the continue block, and any
  1448. // break statements branch to the merge block.
  1449. continueStack.push(continueBB);
  1450. breakStack.push(mergeBB);
  1451. // Branch from the current insert point to the header block.
  1452. spvBuilder.createBranch(headerBB, theDoStmt->getLocStart());
  1453. spvBuilder.addSuccessor(headerBB);
  1454. // Process the <header> block
  1455. // The header block must always branch to the body.
  1456. spvBuilder.setInsertPoint(headerBB);
  1457. const Stmt *body = theDoStmt->getBody();
  1458. spvBuilder.createBranch(bodyBB,
  1459. body ? body->getLocStart() : theDoStmt->getLocStart(),
  1460. mergeBB, continueBB, loopControl);
  1461. spvBuilder.addSuccessor(bodyBB);
  1462. // The current basic block has OpLoopMerge instruction. We need to set its
  1463. // continue and merge target.
  1464. spvBuilder.setContinueTarget(continueBB);
  1465. spvBuilder.setMergeTarget(mergeBB);
  1466. // Process the <body> block
  1467. spvBuilder.setInsertPoint(bodyBB);
  1468. if (body) {
  1469. doStmt(body);
  1470. }
  1471. if (!spvBuilder.isCurrentBasicBlockTerminated()) {
  1472. spvBuilder.createBranch(continueBB, body ? body->getLocEnd()
  1473. : theDoStmt->getLocStart());
  1474. }
  1475. spvBuilder.addSuccessor(continueBB);
  1476. // Process the <continue> block. The check for whether the loop should
  1477. // continue lies in the continue block.
  1478. // *NOTE*: There's a SPIR-V rule that when a conditional branch is to occur in
  1479. // a continue block of a loop, there should be no OpSelectionMerge. Only an
  1480. // OpBranchConditional must be specified.
  1481. spvBuilder.setInsertPoint(continueBB);
  1482. SpirvInstruction *condition = nullptr;
  1483. if (const Expr *check = theDoStmt->getCond()) {
  1484. condition = doExpr(check);
  1485. } else {
  1486. condition = spvBuilder.getConstantBool(true);
  1487. }
  1488. spvBuilder.createConditionalBranch(condition, headerBB, mergeBB,
  1489. theDoStmt->getLocEnd());
  1490. spvBuilder.addSuccessor(headerBB);
  1491. spvBuilder.addSuccessor(mergeBB);
  1492. // Set insertion point to the <merge> block for subsequent statements
  1493. spvBuilder.setInsertPoint(mergeBB);
  1494. // Done with the current scope's continue block and merge block.
  1495. continueStack.pop();
  1496. breakStack.pop();
  1497. }
  1498. void SpirvEmitter::doContinueStmt(const ContinueStmt *continueStmt) {
  1499. assert(!spvBuilder.isCurrentBasicBlockTerminated());
  1500. auto *continueTargetBB = continueStack.top();
  1501. spvBuilder.createBranch(continueTargetBB, continueStmt->getLocStart());
  1502. spvBuilder.addSuccessor(continueTargetBB);
  1503. // Some statements that alter the control flow (break, continue, return, and
  1504. // discard), require creation of a new basic block to hold any statement that
  1505. // may follow them. For example: StmtB and StmtC below are put inside a new
  1506. // basic block which is unreachable.
  1507. //
  1508. // while (true) {
  1509. // StmtA;
  1510. // continue;
  1511. // StmtB;
  1512. // StmtC;
  1513. // }
  1514. auto *newBB = spvBuilder.createBasicBlock();
  1515. spvBuilder.setInsertPoint(newBB);
  1516. }
  1517. void SpirvEmitter::doWhileStmt(const WhileStmt *whileStmt,
  1518. llvm::ArrayRef<const Attr *> attrs) {
  1519. // While loops are composed of:
  1520. // while (<check>) { <body> }
  1521. //
  1522. // SPIR-V requires loops to have a merge basic block as well as a continue
  1523. // basic block. Even though while loops do not have an explicit continue
  1524. // block as in for-loops, we still do need to create a continue block.
  1525. //
  1526. // Since SPIR-V requires structured control flow, we need two more basic
  1527. // blocks, <header> and <merge>. <header> is the block before control flow
  1528. // diverges, and <merge> is the block where control flow subsequently
  1529. // converges. The <check> block can take the responsibility of the <header>
  1530. // block. The final CFG should normally be like the following. Exceptions
  1531. // will occur with non-local exits like loop breaks or early returns.
  1532. //
  1533. // +----------+
  1534. // | header | <------------------+
  1535. // | (check) | |
  1536. // +----------+ |
  1537. // | |
  1538. // +-------+-------+ |
  1539. // | false | true |
  1540. // | v |
  1541. // | +------+ +------------------+
  1542. // | | body | --> | continue (no-op) |
  1543. // v +------+ +------------------+
  1544. // +-------+
  1545. // | merge |
  1546. // +-------+
  1547. //
  1548. // For more details, see "2.11. Structured Control Flow" in the SPIR-V spec.
  1549. const spv::LoopControlMask loopControl =
  1550. attrs.empty() ? spv::LoopControlMask::MaskNone
  1551. : translateLoopAttribute(whileStmt, *attrs.front());
  1552. // Create basic blocks
  1553. auto *checkBB = spvBuilder.createBasicBlock("while.check");
  1554. auto *bodyBB = spvBuilder.createBasicBlock("while.body");
  1555. auto *continueBB = spvBuilder.createBasicBlock("while.continue");
  1556. auto *mergeBB = spvBuilder.createBasicBlock("while.merge");
  1557. // Make sure any continue statements branch to the continue block, and any
  1558. // break statements branch to the merge block.
  1559. continueStack.push(continueBB);
  1560. breakStack.push(mergeBB);
  1561. // Process the <check> block
  1562. spvBuilder.createBranch(checkBB, whileStmt->getLocStart());
  1563. spvBuilder.addSuccessor(checkBB);
  1564. spvBuilder.setInsertPoint(checkBB);
  1565. // If we have:
  1566. // while (int a = foo()) {...}
  1567. // we should evaluate 'a' by calling 'foo()' every single time the check has
  1568. // to occur.
  1569. if (const auto *condVarDecl = whileStmt->getConditionVariableDeclStmt())
  1570. doStmt(condVarDecl);
  1571. SpirvInstruction *condition = nullptr;
  1572. const Expr *check = whileStmt->getCond();
  1573. if (check) {
  1574. condition = doExpr(check);
  1575. } else {
  1576. condition = spvBuilder.getConstantBool(true);
  1577. }
  1578. spvBuilder.createConditionalBranch(
  1579. condition, bodyBB,
  1580. /*false branch*/ mergeBB, whileStmt->getLocStart(),
  1581. /*merge*/ mergeBB, continueBB, spv::SelectionControlMask::MaskNone,
  1582. loopControl);
  1583. spvBuilder.addSuccessor(bodyBB);
  1584. spvBuilder.addSuccessor(mergeBB);
  1585. // The current basic block has OpLoopMerge instruction. We need to set its
  1586. // continue and merge target.
  1587. spvBuilder.setContinueTarget(continueBB);
  1588. spvBuilder.setMergeTarget(mergeBB);
  1589. // Process the <body> block
  1590. spvBuilder.setInsertPoint(bodyBB);
  1591. const Stmt *body = whileStmt->getBody();
  1592. if (body) {
  1593. doStmt(body);
  1594. }
  1595. if (!spvBuilder.isCurrentBasicBlockTerminated())
  1596. spvBuilder.createBranch(continueBB, whileStmt->getLocEnd());
  1597. spvBuilder.addSuccessor(continueBB);
  1598. // Process the <continue> block. While loops do not have an explicit
  1599. // continue block. The continue block just branches to the <check> block.
  1600. spvBuilder.setInsertPoint(continueBB);
  1601. spvBuilder.createBranch(checkBB, whileStmt->getLocEnd());
  1602. spvBuilder.addSuccessor(checkBB);
  1603. // Set insertion point to the <merge> block for subsequent statements
  1604. spvBuilder.setInsertPoint(mergeBB);
  1605. // Done with the current scope's continue and merge blocks.
  1606. continueStack.pop();
  1607. breakStack.pop();
  1608. }
  1609. void SpirvEmitter::doForStmt(const ForStmt *forStmt,
  1610. llvm::ArrayRef<const Attr *> attrs) {
  1611. // for loops are composed of:
  1612. // for (<init>; <check>; <continue>) <body>
  1613. //
  1614. // To translate a for loop, we'll need to emit all <init> statements
  1615. // in the current basic block, and then have separate basic blocks for
  1616. // <check>, <continue>, and <body>. Besides, since SPIR-V requires
  1617. // structured control flow, we need two more basic blocks, <header>
  1618. // and <merge>. <header> is the block before control flow diverges,
  1619. // while <merge> is the block where control flow subsequently converges.
  1620. // The <check> block can take the responsibility of the <header> block.
  1621. // The final CFG should normally be like the following. Exceptions will
  1622. // occur with non-local exits like loop breaks or early returns.
  1623. // +--------+
  1624. // | init |
  1625. // +--------+
  1626. // |
  1627. // v
  1628. // +----------+
  1629. // | header | <---------------+
  1630. // | (check) | |
  1631. // +----------+ |
  1632. // | |
  1633. // +-------+-------+ |
  1634. // | false | true |
  1635. // | v |
  1636. // | +------+ +----------+
  1637. // | | body | --> | continue |
  1638. // v +------+ +----------+
  1639. // +-------+
  1640. // | merge |
  1641. // +-------+
  1642. //
  1643. // For more details, see "2.11. Structured Control Flow" in the SPIR-V spec.
  1644. const spv::LoopControlMask loopControl =
  1645. attrs.empty() ? spv::LoopControlMask::MaskNone
  1646. : translateLoopAttribute(forStmt, *attrs.front());
  1647. // Create basic blocks
  1648. auto *checkBB = spvBuilder.createBasicBlock("for.check");
  1649. auto *bodyBB = spvBuilder.createBasicBlock("for.body");
  1650. auto *continueBB = spvBuilder.createBasicBlock("for.continue");
  1651. auto *mergeBB = spvBuilder.createBasicBlock("for.merge");
  1652. // Make sure any continue statements branch to the continue block, and any
  1653. // break statements branch to the merge block.
  1654. continueStack.push(continueBB);
  1655. breakStack.push(mergeBB);
  1656. // Process the <init> block
  1657. if (const Stmt *initStmt = forStmt->getInit()) {
  1658. doStmt(initStmt);
  1659. }
  1660. const Expr *check = forStmt->getCond();
  1661. spvBuilder.createBranch(checkBB, check ? check->getLocStart()
  1662. : forStmt->getLocStart());
  1663. spvBuilder.addSuccessor(checkBB);
  1664. // Process the <check> block
  1665. spvBuilder.setInsertPoint(checkBB);
  1666. SpirvInstruction *condition = nullptr;
  1667. if (check) {
  1668. condition = doExpr(check);
  1669. } else {
  1670. condition = spvBuilder.getConstantBool(true);
  1671. }
  1672. const Stmt *body = forStmt->getBody();
  1673. spvBuilder.createConditionalBranch(
  1674. condition, bodyBB,
  1675. /*false branch*/ mergeBB,
  1676. check ? check->getLocEnd()
  1677. : (body ? body->getLocStart() : forStmt->getLocStart()),
  1678. /*merge*/ mergeBB, continueBB, spv::SelectionControlMask::MaskNone,
  1679. loopControl);
  1680. spvBuilder.addSuccessor(bodyBB);
  1681. spvBuilder.addSuccessor(mergeBB);
  1682. // The current basic block has OpLoopMerge instruction. We need to set its
  1683. // continue and merge target.
  1684. spvBuilder.setContinueTarget(continueBB);
  1685. spvBuilder.setMergeTarget(mergeBB);
  1686. // Process the <body> block
  1687. spvBuilder.setInsertPoint(bodyBB);
  1688. if (body) {
  1689. doStmt(body);
  1690. }
  1691. if (!spvBuilder.isCurrentBasicBlockTerminated())
  1692. spvBuilder.createBranch(continueBB, forStmt->getLocEnd());
  1693. spvBuilder.addSuccessor(continueBB);
  1694. // Process the <continue> block
  1695. spvBuilder.setInsertPoint(continueBB);
  1696. if (const Expr *cont = forStmt->getInc()) {
  1697. doExpr(cont);
  1698. }
  1699. // <continue> should jump back to header
  1700. spvBuilder.createBranch(checkBB, forStmt->getLocEnd());
  1701. spvBuilder.addSuccessor(checkBB);
  1702. // Set insertion point to the <merge> block for subsequent statements
  1703. spvBuilder.setInsertPoint(mergeBB);
  1704. // Done with the current scope's continue block and merge block.
  1705. continueStack.pop();
  1706. breakStack.pop();
  1707. }
  1708. void SpirvEmitter::doIfStmt(const IfStmt *ifStmt,
  1709. llvm::ArrayRef<const Attr *> attrs) {
  1710. // if statements are composed of:
  1711. // if (<check>) { <then> } else { <else> }
  1712. //
  1713. // To translate if statements, we'll need to emit the <check> expressions
  1714. // in the current basic block, and then create separate basic blocks for
  1715. // <then> and <else>. Additionally, we'll need a <merge> block as per
  1716. // SPIR-V's structured control flow requirements. Depending whether there
  1717. // exists the else branch, the final CFG should normally be like the
  1718. // following. Exceptions will occur with non-local exits like loop breaks
  1719. // or early returns.
  1720. // +-------+ +-------+
  1721. // | check | | check |
  1722. // +-------+ +-------+
  1723. // | |
  1724. // +-------+-------+ +-----+-----+
  1725. // | true | false | true | false
  1726. // v v or v |
  1727. // +------+ +------+ +------+ |
  1728. // | then | | else | | then | |
  1729. // +------+ +------+ +------+ |
  1730. // | | | v
  1731. // | +-------+ | | +-------+
  1732. // +-> | merge | <-+ +---> | merge |
  1733. // +-------+ +-------+
  1734. { // Try to see if we can const-eval the condition
  1735. bool condition = false;
  1736. if (ifStmt->getCond()->EvaluateAsBooleanCondition(condition, astContext)) {
  1737. if (condition) {
  1738. doStmt(ifStmt->getThen());
  1739. } else if (ifStmt->getElse()) {
  1740. doStmt(ifStmt->getElse());
  1741. }
  1742. return;
  1743. }
  1744. }
  1745. auto selectionControl = spv::SelectionControlMask::MaskNone;
  1746. if (!attrs.empty()) {
  1747. const Attr *attribute = attrs.front();
  1748. switch (attribute->getKind()) {
  1749. case attr::HLSLBranch:
  1750. selectionControl = spv::SelectionControlMask::DontFlatten;
  1751. break;
  1752. case attr::HLSLFlatten:
  1753. selectionControl = spv::SelectionControlMask::Flatten;
  1754. break;
  1755. default:
  1756. // warning emitted in hlsl::ProcessStmtAttributeForHLSL
  1757. break;
  1758. }
  1759. }
  1760. if (const auto *declStmt = ifStmt->getConditionVariableDeclStmt())
  1761. doDeclStmt(declStmt);
  1762. // First emit the instruction for evaluating the condition.
  1763. auto *condition = doExpr(ifStmt->getCond());
  1764. // Then we need to emit the instruction for the conditional branch.
  1765. // We'll need the <label-id> for the then/else/merge block to do so.
  1766. const bool hasElse = ifStmt->getElse() != nullptr;
  1767. auto *thenBB = spvBuilder.createBasicBlock("if.true");
  1768. auto *mergeBB = spvBuilder.createBasicBlock("if.merge");
  1769. auto *elseBB = hasElse ? spvBuilder.createBasicBlock("if.false") : mergeBB;
  1770. // Create the branch instruction. This will end the current basic block.
  1771. const auto *then = ifStmt->getThen();
  1772. spvBuilder.createConditionalBranch(condition, thenBB, elseBB,
  1773. then->getLocStart(), mergeBB,
  1774. /*continue*/ 0, selectionControl);
  1775. spvBuilder.addSuccessor(thenBB);
  1776. spvBuilder.addSuccessor(elseBB);
  1777. // The current basic block has the OpSelectionMerge instruction. We need
  1778. // to record its merge target.
  1779. spvBuilder.setMergeTarget(mergeBB);
  1780. // Handle the then branch
  1781. spvBuilder.setInsertPoint(thenBB);
  1782. doStmt(then);
  1783. if (!spvBuilder.isCurrentBasicBlockTerminated())
  1784. spvBuilder.createBranch(mergeBB, ifStmt->getLocEnd());
  1785. spvBuilder.addSuccessor(mergeBB);
  1786. // Handle the else branch (if exists)
  1787. if (hasElse) {
  1788. spvBuilder.setInsertPoint(elseBB);
  1789. const auto *elseStmt = ifStmt->getElse();
  1790. doStmt(elseStmt);
  1791. if (!spvBuilder.isCurrentBasicBlockTerminated())
  1792. spvBuilder.createBranch(mergeBB, elseStmt->getLocEnd());
  1793. spvBuilder.addSuccessor(mergeBB);
  1794. }
  1795. // From now on, we'll emit instructions into the merge block.
  1796. spvBuilder.setInsertPoint(mergeBB);
  1797. }
  1798. void SpirvEmitter::doReturnStmt(const ReturnStmt *stmt) {
  1799. if (const auto *retVal = stmt->getRetValue()) {
  1800. // Update counter variable associated with function returns
  1801. tryToAssignCounterVar(curFunction, retVal);
  1802. auto *retInfo = loadIfGLValue(retVal);
  1803. if (!retInfo)
  1804. return;
  1805. auto retType = retVal->getType();
  1806. if (retInfo->getLayoutRule() != SpirvLayoutRule::Void &&
  1807. retType->isStructureType()) {
  1808. // We are returning some value from a non-Function storage class. Need to
  1809. // create a temporary variable to "convert" the value to Function storage
  1810. // class and then return.
  1811. auto *tempVar =
  1812. spvBuilder.addFnVar(retType, retVal->getLocEnd(), "temp.var.ret");
  1813. storeValue(tempVar, retInfo, retType, retVal->getLocEnd());
  1814. spvBuilder.createReturnValue(
  1815. spvBuilder.createLoad(retType, tempVar, retVal->getLocEnd()),
  1816. stmt->getReturnLoc());
  1817. } else {
  1818. spvBuilder.createReturnValue(retInfo, stmt->getReturnLoc());
  1819. }
  1820. } else {
  1821. spvBuilder.createReturn(stmt->getReturnLoc());
  1822. }
  1823. // We are translating a ReturnStmt, we should be in some function's body.
  1824. assert(curFunction->hasBody());
  1825. // If this return statement is the last statement in the function, then
  1826. // whe have no more work to do.
  1827. if (cast<CompoundStmt>(curFunction->getBody())->body_back() == stmt)
  1828. return;
  1829. // Some statements that alter the control flow (break, continue, return, and
  1830. // discard), require creation of a new basic block to hold any statement that
  1831. // may follow them. In this case, the newly created basic block will contain
  1832. // any statement that may come after an early return.
  1833. auto *newBB = spvBuilder.createBasicBlock();
  1834. spvBuilder.setInsertPoint(newBB);
  1835. }
  1836. void SpirvEmitter::doBreakStmt(const BreakStmt *breakStmt) {
  1837. assert(!spvBuilder.isCurrentBasicBlockTerminated());
  1838. auto *breakTargetBB = breakStack.top();
  1839. spvBuilder.addSuccessor(breakTargetBB);
  1840. spvBuilder.createBranch(breakTargetBB, breakStmt->getLocStart());
  1841. // Some statements that alter the control flow (break, continue, return, and
  1842. // discard), require creation of a new basic block to hold any statement that
  1843. // may follow them. For example: StmtB and StmtC below are put inside a new
  1844. // basic block which is unreachable.
  1845. //
  1846. // while (true) {
  1847. // StmtA;
  1848. // break;
  1849. // StmtB;
  1850. // StmtC;
  1851. // }
  1852. auto *newBB = spvBuilder.createBasicBlock();
  1853. spvBuilder.setInsertPoint(newBB);
  1854. }
  1855. void SpirvEmitter::doSwitchStmt(const SwitchStmt *switchStmt,
  1856. llvm::ArrayRef<const Attr *> attrs) {
  1857. // Switch statements are composed of:
  1858. // switch (<condition variable>) {
  1859. // <CaseStmt>
  1860. // <CaseStmt>
  1861. // <CaseStmt>
  1862. // <DefaultStmt> (optional)
  1863. // }
  1864. //
  1865. // +-------+
  1866. // | check |
  1867. // +-------+
  1868. // |
  1869. // +-------+-------+----------------+---------------+
  1870. // | 1 | 2 | 3 | (others)
  1871. // v v v v
  1872. // +-------+ +-------------+ +-------+ +------------+
  1873. // | case1 | | case2 | | case3 | ... | default |
  1874. // | | |(fallthrough)|---->| | | (optional) |
  1875. // +-------+ |+------------+ +-------+ +------------+
  1876. // | | |
  1877. // | | |
  1878. // | +-------+ | |
  1879. // | | | <--------------------+ |
  1880. // +-> | merge | |
  1881. // | | <-------------------------------------+
  1882. // +-------+
  1883. // If no attributes are given, or if "forcecase" attribute was provided,
  1884. // we'll do our best to use OpSwitch if possible.
  1885. // If any of the cases compares to a variable (rather than an integer
  1886. // literal), we cannot use OpSwitch because OpSwitch expects literal
  1887. // numbers as parameters.
  1888. const bool isAttrForceCase =
  1889. !attrs.empty() && attrs.front()->getKind() == attr::HLSLForceCase;
  1890. const bool canUseSpirvOpSwitch =
  1891. (attrs.empty() || isAttrForceCase) &&
  1892. allSwitchCasesAreIntegerLiterals(switchStmt->getBody());
  1893. if (isAttrForceCase && !canUseSpirvOpSwitch &&
  1894. !spirvOptions.noWarnIgnoredFeatures) {
  1895. emitWarning("ignored 'forcecase' attribute for the switch statement "
  1896. "since one or more case values are not integer literals",
  1897. switchStmt->getLocStart());
  1898. }
  1899. if (canUseSpirvOpSwitch)
  1900. processSwitchStmtUsingSpirvOpSwitch(switchStmt);
  1901. else
  1902. processSwitchStmtUsingIfStmts(switchStmt);
  1903. }
  1904. SpirvInstruction *
  1905. SpirvEmitter::doArraySubscriptExpr(const ArraySubscriptExpr *expr) {
  1906. llvm::SmallVector<SpirvInstruction *, 4> indices;
  1907. const auto *base = collectArrayStructIndices(
  1908. expr, /*rawIndex*/ false, /*rawIndices*/ nullptr, &indices);
  1909. auto *info = loadIfAliasVarRef(base);
  1910. if (!indices.empty()) {
  1911. info = turnIntoElementPtr(base->getType(), info, expr->getType(), indices,
  1912. base->getExprLoc());
  1913. }
  1914. return info;
  1915. }
  1916. SpirvInstruction *SpirvEmitter::doBinaryOperator(const BinaryOperator *expr) {
  1917. const auto opcode = expr->getOpcode();
  1918. // Handle assignment first since we need to evaluate rhs before lhs.
  1919. // For other binary operations, we need to evaluate lhs before rhs.
  1920. if (opcode == BO_Assign) {
  1921. // Update counter variable associated with lhs of assignments
  1922. tryToAssignCounterVar(expr->getLHS(), expr->getRHS());
  1923. return processAssignment(expr->getLHS(), loadIfGLValue(expr->getRHS()),
  1924. /*isCompoundAssignment=*/false);
  1925. }
  1926. // Try to optimize floatMxN * float and floatN * float case
  1927. if (opcode == BO_Mul) {
  1928. if (auto *result = tryToGenFloatMatrixScale(expr))
  1929. return result;
  1930. if (auto *result = tryToGenFloatVectorScale(expr))
  1931. return result;
  1932. }
  1933. return processBinaryOp(expr->getLHS(), expr->getRHS(), opcode,
  1934. expr->getLHS()->getType(), expr->getType(),
  1935. expr->getSourceRange(), expr->getOperatorLoc());
  1936. }
  1937. SpirvInstruction *SpirvEmitter::doCallExpr(const CallExpr *callExpr) {
  1938. if (const auto *operatorCall = dyn_cast<CXXOperatorCallExpr>(callExpr))
  1939. return doCXXOperatorCallExpr(operatorCall);
  1940. if (const auto *memberCall = dyn_cast<CXXMemberCallExpr>(callExpr))
  1941. return doCXXMemberCallExpr(memberCall);
  1942. // Intrinsic functions such as 'dot' or 'mul'
  1943. if (hlsl::IsIntrinsicOp(callExpr->getDirectCallee())) {
  1944. return processIntrinsicCallExpr(callExpr);
  1945. }
  1946. // Normal standalone functions
  1947. return processCall(callExpr);
  1948. }
  1949. SpirvInstruction *SpirvEmitter::getBaseOfMemberFunction(QualType objectType,
  1950. SpirvInstruction * objInstr,
  1951. const CXXMethodDecl* memberFn,
  1952. SourceLocation loc) {
  1953. // If objectType is different from the parent of memberFn, memberFn should be
  1954. // defined in a base struct/class of objectType. We create OpAccessChain with
  1955. // index 0 while iterating bases of objectType until we find the base with
  1956. // the definition of memberFn.
  1957. if (const auto *ptrType = objectType->getAs<PointerType>()) {
  1958. if (const auto *recordType = ptrType->getPointeeType()->getAs<RecordType>()) {
  1959. const auto *parentDeclOfMemberFn = memberFn->getParent();
  1960. if (recordType->getDecl() != parentDeclOfMemberFn) {
  1961. const auto *cxxRecordDecl = dyn_cast<CXXRecordDecl>(recordType->getDecl());
  1962. auto *zero =
  1963. spvBuilder.getConstantInt(astContext.UnsignedIntTy, llvm::APInt(32, 0));
  1964. for (auto baseItr = cxxRecordDecl->bases_begin(), itrEnd = cxxRecordDecl->bases_end();
  1965. baseItr != itrEnd; baseItr++) {
  1966. const auto *baseType = baseItr->getType()->getAs<RecordType>();
  1967. objectType = astContext.getPointerType(baseType->desugar());
  1968. objInstr = spvBuilder.createAccessChain(objectType,
  1969. objInstr, {zero},
  1970. loc);
  1971. if (baseType->getDecl() == parentDeclOfMemberFn) return objInstr;
  1972. }
  1973. }
  1974. }
  1975. }
  1976. return nullptr;
  1977. }
  1978. SpirvInstruction *SpirvEmitter::processCall(const CallExpr *callExpr) {
  1979. const FunctionDecl *callee = getCalleeDefinition(callExpr);
  1980. // Note that we always want the defintion because Stmts/Exprs in the
  1981. // function body references the parameters in the definition.
  1982. if (!callee) {
  1983. emitError("found undefined function", callExpr->getExprLoc());
  1984. return nullptr;
  1985. }
  1986. const auto paramTypeMatchesArgType = [](QualType paramType,
  1987. QualType argType) {
  1988. if (argType == paramType)
  1989. return true;
  1990. if (const auto *refType = paramType->getAs<ReferenceType>())
  1991. paramType = refType->getPointeeType();
  1992. auto argUnqualifiedType = argType->getUnqualifiedDesugaredType();
  1993. auto paramUnqualifiedType = paramType->getUnqualifiedDesugaredType();
  1994. if (argUnqualifiedType == paramUnqualifiedType)
  1995. return true;
  1996. return false;
  1997. };
  1998. const auto numParams = callee->getNumParams();
  1999. bool isNonStaticMemberCall = false;
  2000. QualType objectType = {}; // Type of the object (if exists)
  2001. SpirvInstruction *objInstr = nullptr; // EvalInfo for the object (if exists)
  2002. llvm::SmallVector<SpirvInstruction *, 4> vars; // Variables for function call
  2003. llvm::SmallVector<bool, 4> isTempVar; // Temporary variable or not
  2004. llvm::SmallVector<SpirvInstruction *, 4> args; // Evaluated arguments
  2005. if (const auto *memberCall = dyn_cast<CXXMemberCallExpr>(callExpr)) {
  2006. const auto *memberFn = cast<CXXMethodDecl>(memberCall->getCalleeDecl());
  2007. isNonStaticMemberCall = !memberFn->isStatic();
  2008. if (isNonStaticMemberCall) {
  2009. // For non-static member calls, evaluate the object and pass it as the
  2010. // first argument.
  2011. const auto *object = memberCall->getImplicitObjectArgument();
  2012. object = object->IgnoreParenNoopCasts(astContext);
  2013. // Update counter variable associated with the implicit object
  2014. tryToAssignCounterVar(getOrCreateDeclForMethodObject(memberFn), object);
  2015. objectType = object->getType();
  2016. objInstr = doExpr(object);
  2017. if (auto *accessToBaseInstr = getBaseOfMemberFunction(objectType, objInstr, memberFn, memberCall->getExprLoc())) {
  2018. objInstr = accessToBaseInstr;
  2019. objectType = accessToBaseInstr->getAstResultType();
  2020. }
  2021. // If not already a variable, we need to create a temporary variable and
  2022. // pass the object pointer to the function. Example:
  2023. // getObject().objectMethod();
  2024. // Also, any parameter passed to the member function must be of Function
  2025. // storage class.
  2026. if (objInstr->isRValue()) {
  2027. args.push_back(createTemporaryVar(
  2028. objectType, getAstTypeName(objectType),
  2029. // May need to load to use as initializer
  2030. loadIfGLValue(object, objInstr), object->getLocStart()));
  2031. } else {
  2032. // Based on SPIR-V spec, function parameter must always be in Function
  2033. // scope. If we pass a non-function scope argument, we need
  2034. // the legalization.
  2035. if (objInstr->getStorageClass() != spv::StorageClass::Function ||
  2036. !isMemoryObjectDeclaration(objInstr))
  2037. beforeHlslLegalization = true;
  2038. args.push_back(objInstr);
  2039. }
  2040. // We do not need to create a new temporary variable for the this
  2041. // object. Use the evaluated argument.
  2042. vars.push_back(args.back());
  2043. isTempVar.push_back(false);
  2044. }
  2045. }
  2046. // Evaluate parameters
  2047. for (uint32_t i = 0; i < numParams; ++i) {
  2048. // We want the argument variable here so that we can write back to it
  2049. // later. We will do the OpLoad of this argument manually. So ingore
  2050. // the LValueToRValue implicit cast here.
  2051. auto *arg = callExpr->getArg(i)->IgnoreParenLValueCasts();
  2052. const auto *param = callee->getParamDecl(i);
  2053. const auto paramType = param->getType();
  2054. // Get the evaluation info if this argument is referencing some variable
  2055. // *as a whole*, in which case we can avoid creating the temporary variable
  2056. // for it if it can act as out parameter.
  2057. SpirvInstruction *argInfo = nullptr;
  2058. if (const auto *declRefExpr = dyn_cast<DeclRefExpr>(arg)) {
  2059. argInfo = declIdMapper.getDeclEvalInfo(declRefExpr->getDecl(),
  2060. arg->getLocStart());
  2061. }
  2062. auto *argInst = doExpr(arg);
  2063. bool isArgGlobalVarWithResourceType =
  2064. argInfo && argInfo->getStorageClass() != spv::StorageClass::Function &&
  2065. isResourceType(paramType);
  2066. // If argInfo is nullptr and argInst is a rvalue, we do not have a proper
  2067. // pointer to pass to the function. we need a temporary variable in that
  2068. // case.
  2069. //
  2070. // If we have an 'out/inout' resource as function argument, we need to
  2071. // create a temporary variable for it because the function definition
  2072. // expects are point-to-pointer argument for resources, which will be
  2073. // resolved by legalization.
  2074. if ((argInfo || (argInst && !argInst->isRValue())) &&
  2075. canActAsOutParmVar(param) && !isArgGlobalVarWithResourceType &&
  2076. paramTypeMatchesArgType(paramType, arg->getType())) {
  2077. // Based on SPIR-V spec, function parameter must be always Function
  2078. // scope. In addition, we must pass memory object declaration argument
  2079. // to function. If we pass an argument that is not function scope
  2080. // or not memory object declaration, we need the legalization.
  2081. if (!argInfo || argInfo->getStorageClass() != spv::StorageClass::Function)
  2082. beforeHlslLegalization = true;
  2083. isTempVar.push_back(false);
  2084. args.push_back(argInst);
  2085. vars.push_back(argInfo ? argInfo : argInst);
  2086. } else {
  2087. // We need to create variables for holding the values to be used as
  2088. // arguments. The variables themselves are of pointer types.
  2089. const QualType varType =
  2090. declIdMapper.getTypeAndCreateCounterForPotentialAliasVar(param);
  2091. const std::string varName = "param.var." + param->getNameAsString();
  2092. // Temporary "param.var.*" variables are used for OpFunctionCall purposes.
  2093. // 'precise' attribute on function parameters only affect computations
  2094. // inside the function, not the variables at the call sites. Therefore, we
  2095. // do not need to mark the "param.var.*" variables as precise.
  2096. const bool isPrecise = false;
  2097. auto *tempVar =
  2098. spvBuilder.addFnVar(varType, arg->getLocStart(), varName, isPrecise);
  2099. vars.push_back(tempVar);
  2100. isTempVar.push_back(true);
  2101. args.push_back(argInst);
  2102. // Update counter variable associated with function parameters
  2103. tryToAssignCounterVar(param, arg);
  2104. // Manually load the argument here
  2105. auto *rhsVal = loadIfGLValue(arg, args.back());
  2106. // The AST does not include cast nodes to and from the function parameter
  2107. // type for 'out' and 'inout' cases. Example:
  2108. //
  2109. // void foo(out half3 param) {...}
  2110. // void main() { float3 arg; foo(arg); }
  2111. //
  2112. // In such cases, we first do a manual cast before passing the argument to
  2113. // the function. And we will cast back the results once the function call
  2114. // has returned.
  2115. if (canActAsOutParmVar(param) &&
  2116. !paramTypeMatchesArgType(paramType, arg->getType())) {
  2117. if (const auto *refType = paramType->getAs<ReferenceType>())
  2118. rhsVal = castToType(rhsVal, arg->getType(), refType->getPointeeType(),
  2119. arg->getLocStart());
  2120. }
  2121. // Initialize the temporary variables using the contents of the arguments
  2122. storeValue(tempVar, rhsVal, paramType, arg->getLocStart());
  2123. }
  2124. }
  2125. if (beforeHlslLegalization)
  2126. needsLegalization = true;
  2127. assert(vars.size() == isTempVar.size());
  2128. assert(vars.size() == args.size());
  2129. // Push the callee into the work queue if it is not there.
  2130. addFunctionToWorkQueue(spvContext.getCurrentShaderModelKind(), callee,
  2131. /*isEntryFunction*/ false);
  2132. const QualType retType =
  2133. declIdMapper.getTypeAndCreateCounterForPotentialAliasVar(callee);
  2134. // Get or forward declare the function <result-id>
  2135. SpirvFunction *func = declIdMapper.getOrRegisterFn(callee);
  2136. auto *retVal = spvBuilder.createFunctionCall(
  2137. retType, func, vars, callExpr->getCallee()->getExprLoc());
  2138. // Go through all parameters and write those marked as out/inout
  2139. for (uint32_t i = 0; i < numParams; ++i) {
  2140. const auto *param = callee->getParamDecl(i);
  2141. const auto paramType = param->getType();
  2142. // If it calls a non-static member function, the object itself is argument
  2143. // 0, and therefore all other argument positions are shifted by 1.
  2144. const uint32_t index = i + isNonStaticMemberCall;
  2145. // Using a resouce as a function parameter is never passed-by-copy. As a
  2146. // result, even if the function parameter is marked as 'out' or 'inout',
  2147. // there is no reason to copy back the results after the function call into
  2148. // the resource.
  2149. if (isTempVar[index] && canActAsOutParmVar(param) &&
  2150. !isResourceType(paramType)) {
  2151. const auto *arg = callExpr->getArg(i);
  2152. SpirvInstruction *value =
  2153. spvBuilder.createLoad(paramType, vars[index], arg->getLocStart());
  2154. // Now we want to assign 'value' to arg. But first, in rare cases when
  2155. // using 'out' or 'inout' where the parameter and argument have a type
  2156. // mismatch, we need to first cast 'value' to the type of 'arg' because
  2157. // the AST will not include a cast node.
  2158. if (!paramTypeMatchesArgType(paramType, arg->getType())) {
  2159. if (const auto *refType = paramType->getAs<ReferenceType>())
  2160. value = castToType(value, refType->getPointeeType(), arg->getType(),
  2161. arg->getLocStart());
  2162. }
  2163. processAssignment(arg, value, false, args[index]);
  2164. }
  2165. }
  2166. return retVal;
  2167. }
  2168. SpirvInstruction *SpirvEmitter::doCastExpr(const CastExpr *expr) {
  2169. const Expr *subExpr = expr->getSubExpr();
  2170. const QualType subExprType = subExpr->getType();
  2171. const QualType toType = expr->getType();
  2172. const auto srcLoc = expr->getExprLoc();
  2173. switch (expr->getCastKind()) {
  2174. case CastKind::CK_LValueToRValue:
  2175. return loadIfGLValue(subExpr);
  2176. case CastKind::CK_NoOp:
  2177. return doExpr(subExpr);
  2178. case CastKind::CK_IntegralCast:
  2179. case CastKind::CK_FloatingToIntegral:
  2180. case CastKind::CK_HLSLCC_IntegralCast:
  2181. case CastKind::CK_HLSLCC_FloatingToIntegral: {
  2182. // Integer literals in the AST are represented using 64bit APInt
  2183. // themselves and then implicitly casted into the expected bitwidth.
  2184. // We need special treatment of integer literals here because generating
  2185. // a 64bit constant and then explicit casting in SPIR-V requires Int64
  2186. // capability. We should avoid introducing unnecessary capabilities to
  2187. // our best.
  2188. if (auto *value = tryToEvaluateAsConst(expr)) {
  2189. value->setRValue();
  2190. return value;
  2191. }
  2192. auto *value = castToInt(loadIfGLValue(subExpr), subExprType, toType,
  2193. subExpr->getLocStart());
  2194. value->setRValue();
  2195. return value;
  2196. }
  2197. case CastKind::CK_FloatingCast:
  2198. case CastKind::CK_IntegralToFloating:
  2199. case CastKind::CK_HLSLCC_FloatingCast:
  2200. case CastKind::CK_HLSLCC_IntegralToFloating: {
  2201. // First try to see if we can do constant folding for floating point
  2202. // numbers like what we are doing for integers in the above.
  2203. if (auto *value = tryToEvaluateAsConst(expr)) {
  2204. value->setRValue();
  2205. return value;
  2206. }
  2207. auto *value = castToFloat(loadIfGLValue(subExpr), subExprType, toType,
  2208. subExpr->getLocStart());
  2209. value->setRValue();
  2210. return value;
  2211. }
  2212. case CastKind::CK_IntegralToBoolean:
  2213. case CastKind::CK_FloatingToBoolean:
  2214. case CastKind::CK_HLSLCC_IntegralToBoolean:
  2215. case CastKind::CK_HLSLCC_FloatingToBoolean: {
  2216. // First try to see if we can do constant folding.
  2217. if (auto *value = tryToEvaluateAsConst(expr)) {
  2218. value->setRValue();
  2219. return value;
  2220. }
  2221. auto *value = castToBool(loadIfGLValue(subExpr), subExprType, toType,
  2222. subExpr->getLocStart());
  2223. value->setRValue();
  2224. return value;
  2225. }
  2226. case CastKind::CK_HLSLVectorSplat: {
  2227. const size_t size = hlsl::GetHLSLVecSize(expr->getType());
  2228. return createVectorSplat(subExpr, size);
  2229. }
  2230. case CastKind::CK_HLSLVectorTruncationCast: {
  2231. const QualType toVecType = toType;
  2232. const QualType elemType = hlsl::GetHLSLVecElementType(toType);
  2233. const auto toSize = hlsl::GetHLSLVecSize(toType);
  2234. auto *composite = doExpr(subExpr);
  2235. llvm::SmallVector<SpirvInstruction *, 4> elements;
  2236. for (uint32_t i = 0; i < toSize; ++i) {
  2237. elements.push_back(spvBuilder.createCompositeExtract(
  2238. elemType, composite, {i}, expr->getExprLoc()));
  2239. }
  2240. auto *value = elements.front();
  2241. if (toSize > 1) {
  2242. value = spvBuilder.createCompositeConstruct(toVecType, elements,
  2243. expr->getExprLoc());
  2244. }
  2245. value->setRValue();
  2246. return value;
  2247. }
  2248. case CastKind::CK_HLSLVectorToScalarCast: {
  2249. // The underlying should already be a vector of size 1.
  2250. assert(hlsl::GetHLSLVecSize(subExprType) == 1);
  2251. return doExpr(subExpr);
  2252. }
  2253. case CastKind::CK_HLSLVectorToMatrixCast: {
  2254. // If target type is already an 1xN matrix type, we just return the
  2255. // underlying vector.
  2256. if (is1xNMatrix(toType))
  2257. return doExpr(subExpr);
  2258. // A vector can have no more than 4 elements. The only remaining case
  2259. // is casting from size-4 vector to size-2-by-2 matrix.
  2260. auto *vec = loadIfGLValue(subExpr);
  2261. QualType elemType = {};
  2262. uint32_t rowCount = 0, colCount = 0;
  2263. const bool isMat = isMxNMatrix(toType, &elemType, &rowCount, &colCount);
  2264. assert(isMat && rowCount == 2 && colCount == 2);
  2265. (void)isMat;
  2266. QualType vec2Type = astContext.getExtVectorType(elemType, 2);
  2267. auto *subVec1 = spvBuilder.createVectorShuffle(vec2Type, vec, vec, {0, 1},
  2268. expr->getLocStart());
  2269. auto *subVec2 = spvBuilder.createVectorShuffle(vec2Type, vec, vec, {2, 3},
  2270. expr->getLocStart());
  2271. auto *mat = spvBuilder.createCompositeConstruct(toType, {subVec1, subVec2},
  2272. expr->getLocStart());
  2273. mat->setRValue();
  2274. return mat;
  2275. }
  2276. case CastKind::CK_HLSLMatrixSplat: {
  2277. // From scalar to matrix
  2278. uint32_t rowCount = 0, colCount = 0;
  2279. hlsl::GetHLSLMatRowColCount(toType, rowCount, colCount);
  2280. // Handle degenerated cases first
  2281. if (rowCount == 1 && colCount == 1)
  2282. return doExpr(subExpr);
  2283. if (colCount == 1)
  2284. return createVectorSplat(subExpr, rowCount);
  2285. const auto vecSplat = createVectorSplat(subExpr, colCount);
  2286. if (rowCount == 1)
  2287. return vecSplat;
  2288. if (isa<SpirvConstant>(vecSplat)) {
  2289. llvm::SmallVector<SpirvConstant *, 4> vectors(
  2290. size_t(rowCount), cast<SpirvConstant>(vecSplat));
  2291. auto *value = spvBuilder.getConstantComposite(toType, vectors);
  2292. value->setRValue();
  2293. return value;
  2294. } else {
  2295. llvm::SmallVector<SpirvInstruction *, 4> vectors(size_t(rowCount),
  2296. vecSplat);
  2297. auto *value = spvBuilder.createCompositeConstruct(toType, vectors,
  2298. expr->getLocEnd());
  2299. value->setRValue();
  2300. return value;
  2301. }
  2302. }
  2303. case CastKind::CK_HLSLMatrixTruncationCast: {
  2304. const QualType srcType = subExprType;
  2305. auto *src = doExpr(subExpr);
  2306. const QualType elemType = hlsl::GetHLSLMatElementType(srcType);
  2307. llvm::SmallVector<uint32_t, 4> indexes;
  2308. // It is possible that the source matrix is in fact a vector.
  2309. // Example 1: Truncate float1x3 --> float1x2.
  2310. // Example 2: Truncate float1x3 --> float1x1.
  2311. // The front-end disallows float1x3 --> float2x1.
  2312. {
  2313. uint32_t srcVecSize = 0, dstVecSize = 0;
  2314. if (isVectorType(srcType, nullptr, &srcVecSize) && isScalarType(toType)) {
  2315. auto *val = spvBuilder.createCompositeExtract(toType, src, {0},
  2316. expr->getLocStart());
  2317. val->setRValue();
  2318. return val;
  2319. }
  2320. if (isVectorType(srcType, nullptr, &srcVecSize) &&
  2321. isVectorType(toType, nullptr, &dstVecSize)) {
  2322. for (uint32_t i = 0; i < dstVecSize; ++i)
  2323. indexes.push_back(i);
  2324. auto *val = spvBuilder.createVectorShuffle(toType, src, src, indexes,
  2325. expr->getLocStart());
  2326. val->setRValue();
  2327. return val;
  2328. }
  2329. }
  2330. uint32_t srcRows = 0, srcCols = 0, dstRows = 0, dstCols = 0;
  2331. hlsl::GetHLSLMatRowColCount(srcType, srcRows, srcCols);
  2332. hlsl::GetHLSLMatRowColCount(toType, dstRows, dstCols);
  2333. const QualType srcRowType = astContext.getExtVectorType(elemType, srcCols);
  2334. const QualType dstRowType = astContext.getExtVectorType(elemType, dstCols);
  2335. // Indexes to pass to OpVectorShuffle
  2336. for (uint32_t i = 0; i < dstCols; ++i)
  2337. indexes.push_back(i);
  2338. llvm::SmallVector<SpirvInstruction *, 4> extractedVecs;
  2339. for (uint32_t row = 0; row < dstRows; ++row) {
  2340. // Extract a row
  2341. SpirvInstruction *rowInstr = spvBuilder.createCompositeExtract(
  2342. srcRowType, src, {row}, expr->getExprLoc());
  2343. // Extract the necessary columns from that row.
  2344. // The front-end ensures dstCols <= srcCols.
  2345. // If dstCols equals srcCols, we can use the whole row directly.
  2346. if (dstCols == 1) {
  2347. rowInstr = spvBuilder.createCompositeExtract(elemType, rowInstr, {0},
  2348. expr->getLocStart());
  2349. } else if (dstCols < srcCols) {
  2350. rowInstr = spvBuilder.createVectorShuffle(
  2351. dstRowType, rowInstr, rowInstr, indexes, expr->getLocStart());
  2352. }
  2353. extractedVecs.push_back(rowInstr);
  2354. }
  2355. auto *val = extractedVecs.front();
  2356. if (extractedVecs.size() > 1) {
  2357. val = spvBuilder.createCompositeConstruct(toType, extractedVecs,
  2358. expr->getExprLoc());
  2359. }
  2360. val->setRValue();
  2361. return val;
  2362. }
  2363. case CastKind::CK_HLSLMatrixToScalarCast: {
  2364. // The underlying should already be a matrix of 1x1.
  2365. assert(is1x1Matrix(subExprType));
  2366. return doExpr(subExpr);
  2367. }
  2368. case CastKind::CK_HLSLMatrixToVectorCast: {
  2369. // If the underlying matrix is Mx1 or 1xM for M in {1, 2,3,4}, we can return
  2370. // the underlying matrix because it'll be evaluated as a vector by default.
  2371. if (is1x1Matrix(subExprType) || is1xNMatrix(subExprType) ||
  2372. isMx1Matrix(subExprType))
  2373. return doExpr(subExpr);
  2374. // A vector can have no more than 4 elements. The only remaining case
  2375. // is casting from a 2x2 matrix to a vector of size 4.
  2376. auto *mat = loadIfGLValue(subExpr);
  2377. QualType elemType = {};
  2378. uint32_t rowCount = 0, colCount = 0, elemCount = 0;
  2379. const bool isMat =
  2380. isMxNMatrix(subExprType, &elemType, &rowCount, &colCount);
  2381. const bool isVec = isVectorType(toType, nullptr, &elemCount);
  2382. assert(isMat && rowCount == 2 && colCount == 2);
  2383. assert(isVec && elemCount == 4);
  2384. (void)isMat;
  2385. (void)isVec;
  2386. QualType vec2Type = astContext.getExtVectorType(elemType, 2);
  2387. auto *row0 = spvBuilder.createCompositeExtract(vec2Type, mat, {0}, srcLoc);
  2388. auto *row1 = spvBuilder.createCompositeExtract(vec2Type, mat, {1}, srcLoc);
  2389. auto *vec = spvBuilder.createVectorShuffle(toType, row0, row1, {0, 1, 2, 3},
  2390. srcLoc);
  2391. vec->setRValue();
  2392. return vec;
  2393. }
  2394. case CastKind::CK_FunctionToPointerDecay:
  2395. // Just need to return the function id
  2396. return doExpr(subExpr);
  2397. case CastKind::CK_FlatConversion: {
  2398. SpirvInstruction *subExprInstr = nullptr;
  2399. QualType evalType = subExprType;
  2400. // Optimization: we can use OpConstantNull for cases where we want to
  2401. // initialize an entire data structure to zeros.
  2402. if (evaluatesToConstZero(subExpr, astContext)) {
  2403. subExprInstr = spvBuilder.getConstantNull(toType);
  2404. subExprInstr->setRValue();
  2405. return subExprInstr;
  2406. }
  2407. // Try to evaluate float literals as float rather than double.
  2408. if (const auto *floatLiteral = dyn_cast<FloatingLiteral>(subExpr)) {
  2409. subExprInstr = tryToEvaluateAsFloat32(floatLiteral->getValue());
  2410. if (subExprInstr)
  2411. evalType = astContext.FloatTy;
  2412. }
  2413. // Evaluate 'literal float' initializer type as float rather than double.
  2414. // TODO: This could result in rounding error if the initializer is a
  2415. // non-literal expression that requires larger than 32 bits and has the
  2416. // 'literal float' type.
  2417. else if (subExprType->isSpecificBuiltinType(BuiltinType::LitFloat)) {
  2418. evalType = astContext.FloatTy;
  2419. }
  2420. // Try to evaluate integer literals as 32-bit int rather than 64-bit int.
  2421. else if (const auto *intLiteral = dyn_cast<IntegerLiteral>(subExpr)) {
  2422. const bool isSigned = subExprType->isSignedIntegerType();
  2423. subExprInstr = tryToEvaluateAsInt32(intLiteral->getValue(), isSigned);
  2424. if (subExprInstr)
  2425. evalType = isSigned ? astContext.IntTy : astContext.UnsignedIntTy;
  2426. }
  2427. // For assigning one array instance to another one with the same array type
  2428. // (regardless of constness and literalness), the rhs will be wrapped in a
  2429. // FlatConversion. Similarly for assigning a struct to another struct with
  2430. // identical members.
  2431. // |- <lhs>
  2432. // `- ImplicitCastExpr <FlatConversion>
  2433. // `- ImplicitCastExpr <LValueToRValue>
  2434. // `- <rhs>
  2435. else if (isSameType(astContext, toType, evalType) ||
  2436. // We can have casts changing the shape but without affecting
  2437. // memory order, e.g., `float4 a[2]; float b[8] = (float[8])a;`.
  2438. // This is also represented as FlatConversion. For such cases, we
  2439. // can rely on the InitListHandler, which can decompse
  2440. // vectors/matrices.
  2441. subExprType->isArrayType()) {
  2442. auto *valInstr =
  2443. InitListHandler(astContext, *this).processCast(toType, subExpr);
  2444. if (valInstr)
  2445. valInstr->setRValue();
  2446. return valInstr;
  2447. }
  2448. // We can have casts changing the shape but without affecting memory order,
  2449. // e.g., `float4 a[2]; float b[8] = (float[8])a;`. This is also represented
  2450. // as FlatConversion. For such cases, we can rely on the InitListHandler,
  2451. // which can decompse vectors/matrices.
  2452. else if (subExprType->isArrayType()) {
  2453. auto *valInstr = InitListHandler(astContext, *this)
  2454. .processCast(expr->getType(), subExpr);
  2455. if (valInstr)
  2456. valInstr->setRValue();
  2457. return valInstr;
  2458. }
  2459. if (!subExprInstr)
  2460. subExprInstr = doExpr(subExpr);
  2461. auto *val = processFlatConversion(toType, evalType, subExprInstr,
  2462. expr->getExprLoc());
  2463. val->setRValue();
  2464. return val;
  2465. }
  2466. case CastKind::CK_UncheckedDerivedToBase:
  2467. case CastKind::CK_HLSLDerivedToBase: {
  2468. // Find the index sequence of the base to which we are casting
  2469. llvm::SmallVector<uint32_t, 4> baseIndices;
  2470. getBaseClassIndices(expr, &baseIndices);
  2471. // Turn them in to SPIR-V constants
  2472. llvm::SmallVector<SpirvInstruction *, 4> baseIndexInstructions(
  2473. baseIndices.size(), nullptr);
  2474. for (uint32_t i = 0; i < baseIndices.size(); ++i)
  2475. baseIndexInstructions[i] = spvBuilder.getConstantInt(
  2476. astContext.UnsignedIntTy, llvm::APInt(32, baseIndices[i]));
  2477. auto *derivedInfo = doExpr(subExpr);
  2478. return turnIntoElementPtr(subExpr->getType(), derivedInfo, expr->getType(),
  2479. baseIndexInstructions, subExpr->getExprLoc());
  2480. }
  2481. case CastKind::CK_ArrayToPointerDecay: {
  2482. // Literal string to const string conversion falls under this category.
  2483. if (hlsl::IsStringLiteralType(subExprType) && hlsl::IsStringType(toType)) {
  2484. return doExpr(subExpr);
  2485. } else {
  2486. emitError("implicit cast kind '%0' unimplemented", expr->getExprLoc())
  2487. << expr->getCastKindName() << expr->getSourceRange();
  2488. expr->dump();
  2489. return 0;
  2490. }
  2491. }
  2492. default:
  2493. emitError("implicit cast kind '%0' unimplemented", expr->getExprLoc())
  2494. << expr->getCastKindName() << expr->getSourceRange();
  2495. expr->dump();
  2496. return 0;
  2497. }
  2498. }
  2499. SpirvInstruction *SpirvEmitter::processFlatConversion(
  2500. const QualType type, const QualType initType, SpirvInstruction *initInstr,
  2501. SourceLocation srcLoc) {
  2502. // When translating ConstantBuffer<T> or TextureBuffer<T> types, we consider
  2503. // the underlying type (T), and therefore we should bypass the FlatConversion
  2504. // node when accessing these types:
  2505. // `-MemberExpr
  2506. // `-ImplicitCastExpr 'const T' lvalue <FlatConversion>
  2507. // `-ArraySubscriptExpr 'ConstantBuffer<T>':'ConstantBuffer<T>' lvalue
  2508. if (isConstantTextureBuffer(initType)) {
  2509. return initInstr;
  2510. }
  2511. // Try to translate the canonical type first
  2512. const auto canonicalType = type.getCanonicalType();
  2513. if (canonicalType != type)
  2514. return processFlatConversion(canonicalType, initType, initInstr, srcLoc);
  2515. // Primitive types
  2516. {
  2517. QualType ty = {};
  2518. if (isScalarType(type, &ty)) {
  2519. if (const auto *builtinType = ty->getAs<BuiltinType>()) {
  2520. switch (builtinType->getKind()) {
  2521. case BuiltinType::Void: {
  2522. emitError("cannot create a constant of void type", srcLoc);
  2523. return 0;
  2524. }
  2525. case BuiltinType::Bool:
  2526. return castToBool(initInstr, initType, ty, srcLoc);
  2527. // Target type is an integer variant.
  2528. case BuiltinType::Int:
  2529. case BuiltinType::Short:
  2530. case BuiltinType::Min12Int:
  2531. case BuiltinType::Min16Int:
  2532. case BuiltinType::Min16UInt:
  2533. case BuiltinType::UShort:
  2534. case BuiltinType::UInt:
  2535. case BuiltinType::Long:
  2536. case BuiltinType::LongLong:
  2537. case BuiltinType::ULong:
  2538. case BuiltinType::ULongLong:
  2539. case BuiltinType::Int8_4Packed:
  2540. case BuiltinType::UInt8_4Packed:
  2541. return castToInt(initInstr, initType, ty, srcLoc);
  2542. // Target type is a float variant.
  2543. case BuiltinType::Double:
  2544. case BuiltinType::Float:
  2545. case BuiltinType::Half:
  2546. case BuiltinType::HalfFloat:
  2547. case BuiltinType::Min10Float:
  2548. case BuiltinType::Min16Float:
  2549. return castToFloat(initInstr, initType, ty, srcLoc);
  2550. default:
  2551. emitError("flat conversion of type %0 unimplemented", srcLoc)
  2552. << builtinType->getTypeClassName();
  2553. return 0;
  2554. }
  2555. }
  2556. }
  2557. }
  2558. // Vector types
  2559. {
  2560. QualType elemType = {};
  2561. uint32_t elemCount = {};
  2562. if (isVectorType(type, &elemType, &elemCount)) {
  2563. auto *elem = processFlatConversion(elemType, initType, initInstr, srcLoc);
  2564. llvm::SmallVector<SpirvInstruction *, 4> constituents(size_t(elemCount),
  2565. elem);
  2566. return spvBuilder.createCompositeConstruct(type, constituents, srcLoc);
  2567. }
  2568. }
  2569. // Matrix types
  2570. {
  2571. QualType elemType = {};
  2572. uint32_t rowCount = 0, colCount = 0;
  2573. if (isMxNMatrix(type, &elemType, &rowCount, &colCount)) {
  2574. // By default HLSL matrices are row major, while SPIR-V matrices are
  2575. // column major. We are mapping what HLSL semantically mean a row into a
  2576. // column here.
  2577. const QualType vecType = astContext.getExtVectorType(elemType, colCount);
  2578. auto *elem = processFlatConversion(elemType, initType, initInstr, srcLoc);
  2579. const llvm::SmallVector<SpirvInstruction *, 4> constituents(
  2580. size_t(colCount), elem);
  2581. auto *col =
  2582. spvBuilder.createCompositeConstruct(vecType, constituents, srcLoc);
  2583. const llvm::SmallVector<SpirvInstruction *, 4> rows(size_t(rowCount),
  2584. col);
  2585. return spvBuilder.createCompositeConstruct(type, rows, srcLoc);
  2586. }
  2587. }
  2588. // Struct type
  2589. if (const auto *structType = type->getAs<RecordType>()) {
  2590. const auto *decl = structType->getDecl();
  2591. llvm::SmallVector<SpirvInstruction *, 4> fields;
  2592. for (const auto *field : decl->fields()) {
  2593. // There is a special case for FlatConversion. If T is a struct with only
  2594. // one member, S, then (T)<an-instance-of-S> is allowed, which essentially
  2595. // constructs a new T instance using the instance of S as its only member.
  2596. // Check whether we are handling that case here first.
  2597. if (field->getType().getCanonicalType() == initType.getCanonicalType()) {
  2598. fields.push_back(initInstr);
  2599. } else {
  2600. fields.push_back(processFlatConversion(field->getType(), initType,
  2601. initInstr, srcLoc));
  2602. }
  2603. }
  2604. return spvBuilder.createCompositeConstruct(type, fields, srcLoc);
  2605. }
  2606. // Array type
  2607. if (const auto *arrayType = astContext.getAsConstantArrayType(type)) {
  2608. const auto size =
  2609. static_cast<uint32_t>(arrayType->getSize().getZExtValue());
  2610. auto *elem = processFlatConversion(arrayType->getElementType(), initType,
  2611. initInstr, srcLoc);
  2612. llvm::SmallVector<SpirvInstruction *, 4> constituents(size_t(size), elem);
  2613. return spvBuilder.createCompositeConstruct(type, constituents, srcLoc);
  2614. }
  2615. emitError("flat conversion of type %0 unimplemented", {})
  2616. << type->getTypeClassName();
  2617. type->dump();
  2618. return 0;
  2619. }
  2620. SpirvInstruction *
  2621. SpirvEmitter::doCompoundAssignOperator(const CompoundAssignOperator *expr) {
  2622. const auto opcode = expr->getOpcode();
  2623. // Try to optimize floatMxN *= float and floatN *= float case
  2624. if (opcode == BO_MulAssign) {
  2625. if (auto *result = tryToGenFloatMatrixScale(expr))
  2626. return result;
  2627. if (auto *result = tryToGenFloatVectorScale(expr))
  2628. return result;
  2629. }
  2630. const auto *rhs = expr->getRHS();
  2631. const auto *lhs = expr->getLHS();
  2632. SpirvInstruction *lhsPtr = nullptr;
  2633. auto *result = processBinaryOp(
  2634. lhs, rhs, opcode, expr->getComputationLHSType(), expr->getType(),
  2635. expr->getSourceRange(), expr->getOperatorLoc(), &lhsPtr);
  2636. return processAssignment(lhs, result, true, lhsPtr);
  2637. }
  2638. SpirvInstruction *
  2639. SpirvEmitter::doConditionalOperator(const ConditionalOperator *expr) {
  2640. const auto type = expr->getType();
  2641. const SourceLocation loc = expr->getExprLoc();
  2642. const Expr *cond = expr->getCond();
  2643. const Expr *falseExpr = expr->getFalseExpr();
  2644. const Expr *trueExpr = expr->getTrueExpr();
  2645. // According to HLSL doc, all sides of the ?: expression are always evaluated.
  2646. // Corner-case: In HLSL, the condition of the ternary operator can be a
  2647. // matrix of booleans which results in selecting between components of two
  2648. // matrices. However, a matrix of booleans is not a valid type in SPIR-V.
  2649. // If the AST has inserted a splat of a scalar/vector to a matrix, we can just
  2650. // use that scalar/vector as an if-clause condition.
  2651. if (auto *cast = dyn_cast<ImplicitCastExpr>(cond))
  2652. if (cast->getCastKind() == CK_HLSLMatrixSplat)
  2653. cond = cast->getSubExpr();
  2654. // If we are selecting between two SampleState objects, none of the three
  2655. // operands has a LValueToRValue implicit cast.
  2656. auto *condition = loadIfGLValue(cond);
  2657. auto *trueBranch = loadIfGLValue(trueExpr);
  2658. auto *falseBranch = loadIfGLValue(falseExpr);
  2659. // Corner-case: In HLSL, the condition of the ternary operator can be a
  2660. // matrix of booleans which results in selecting between components of two
  2661. // matrices. However, a matrix of booleans is not a valid type in SPIR-V.
  2662. // Therefore, we need to perform OpSelect for each row of the matrix.
  2663. {
  2664. QualType condElemType = {}, elemType = {};
  2665. uint32_t rowCount = 0, colCount = 0;
  2666. if (isMxNMatrix(type, &elemType, &rowCount, &colCount) &&
  2667. isMxNMatrix(cond->getType(), &condElemType) &&
  2668. condElemType->isBooleanType()) {
  2669. const auto rowType = astContext.getExtVectorType(elemType, colCount);
  2670. const auto condRowType =
  2671. astContext.getExtVectorType(condElemType, colCount);
  2672. llvm::SmallVector<SpirvInstruction *, 4> rows;
  2673. for (uint32_t i = 0; i < rowCount; ++i) {
  2674. auto *condRow =
  2675. spvBuilder.createCompositeExtract(condRowType, condition, {i}, loc);
  2676. auto *trueRow =
  2677. spvBuilder.createCompositeExtract(rowType, trueBranch, {i}, loc);
  2678. auto *falseRow =
  2679. spvBuilder.createCompositeExtract(rowType, falseBranch, {i}, loc);
  2680. rows.push_back(
  2681. spvBuilder.createSelect(rowType, condRow, trueRow, falseRow, loc));
  2682. }
  2683. auto *result = spvBuilder.createCompositeConstruct(type, rows, loc);
  2684. result->setRValue();
  2685. return result;
  2686. }
  2687. }
  2688. // For cases where the return type is a scalar or a vector, we can use
  2689. // OpSelect to choose between the two. OpSelect's return type must be either
  2690. // scalar or vector.
  2691. if (isScalarType(type) || isVectorType(type)) {
  2692. // The SPIR-V OpSelect instruction must have a selection argument that is
  2693. // the same size as the return type. If the return type is a vector, the
  2694. // selection must be a vector of booleans (one per output component).
  2695. uint32_t count = 0;
  2696. if (isVectorType(expr->getType(), nullptr, &count) &&
  2697. !isVectorType(expr->getCond()->getType())) {
  2698. const llvm::SmallVector<SpirvInstruction *, 4> components(size_t(count),
  2699. condition);
  2700. condition = spvBuilder.createCompositeConstruct(
  2701. astContext.getExtVectorType(astContext.BoolTy, count), components,
  2702. expr->getCond()->getLocEnd());
  2703. }
  2704. auto *value =
  2705. spvBuilder.createSelect(type, condition, trueBranch, falseBranch, loc);
  2706. value->setRValue();
  2707. return value;
  2708. }
  2709. // If we can't use OpSelect, we need to create if-else control flow.
  2710. auto *tempVar = spvBuilder.addFnVar(type, loc, "temp.var.ternary");
  2711. auto *thenBB = spvBuilder.createBasicBlock("if.true");
  2712. auto *mergeBB = spvBuilder.createBasicBlock("if.merge");
  2713. auto *elseBB = spvBuilder.createBasicBlock("if.false");
  2714. // Create the branch instruction. This will end the current basic block.
  2715. spvBuilder.createConditionalBranch(condition, thenBB, elseBB,
  2716. expr->getCond()->getLocEnd(), mergeBB);
  2717. spvBuilder.addSuccessor(thenBB);
  2718. spvBuilder.addSuccessor(elseBB);
  2719. spvBuilder.setMergeTarget(mergeBB);
  2720. // Handle the then branch
  2721. spvBuilder.setInsertPoint(thenBB);
  2722. spvBuilder.createStore(tempVar, trueBranch,
  2723. expr->getTrueExpr()->getLocStart());
  2724. spvBuilder.createBranch(mergeBB, expr->getTrueExpr()->getLocEnd());
  2725. spvBuilder.addSuccessor(mergeBB);
  2726. // Handle the else branch
  2727. spvBuilder.setInsertPoint(elseBB);
  2728. spvBuilder.createStore(tempVar, falseBranch,
  2729. expr->getFalseExpr()->getLocStart());
  2730. spvBuilder.createBranch(mergeBB, expr->getFalseExpr()->getLocEnd());
  2731. spvBuilder.addSuccessor(mergeBB);
  2732. // From now on, emit instructions into the merge block.
  2733. spvBuilder.setInsertPoint(mergeBB);
  2734. auto *result = spvBuilder.createLoad(type, tempVar, expr->getLocEnd());
  2735. result->setRValue();
  2736. return result;
  2737. }
  2738. SpirvInstruction *
  2739. SpirvEmitter::processByteAddressBufferStructuredBufferGetDimensions(
  2740. const CXXMemberCallExpr *expr) {
  2741. const auto *object = expr->getImplicitObjectArgument();
  2742. auto *objectInstr = loadIfAliasVarRef(object);
  2743. const auto type = object->getType();
  2744. const bool isBABuf = isByteAddressBuffer(type) || isRWByteAddressBuffer(type);
  2745. const bool isStructuredBuf = isStructuredBuffer(type) ||
  2746. isAppendStructuredBuffer(type) ||
  2747. isConsumeStructuredBuffer(type);
  2748. assert(isBABuf || isStructuredBuf);
  2749. // (RW)ByteAddressBuffers/(RW)StructuredBuffers are represented as a structure
  2750. // with only one member that is a runtime array. We need to perform
  2751. // OpArrayLength on member 0.
  2752. SpirvInstruction *length = spvBuilder.createArrayLength(
  2753. astContext.UnsignedIntTy, expr->getExprLoc(), objectInstr, 0);
  2754. // For (RW)ByteAddressBuffers, GetDimensions() must return the array length
  2755. // in bytes, but OpArrayLength returns the number of uints in the runtime
  2756. // array. Therefore we must multiply the results by 4.
  2757. if (isBABuf) {
  2758. length = spvBuilder.createBinaryOp(
  2759. spv::Op::OpIMul, astContext.UnsignedIntTy, length,
  2760. // TODO(jaebaek): What line info we should emit for constants?
  2761. spvBuilder.getConstantInt(astContext.UnsignedIntTy,
  2762. llvm::APInt(32, 4u)),
  2763. expr->getExprLoc());
  2764. }
  2765. spvBuilder.createStore(doExpr(expr->getArg(0)), length,
  2766. expr->getArg(0)->getLocStart());
  2767. if (isStructuredBuf) {
  2768. // For (RW)StructuredBuffer, the stride of the runtime array (which is the
  2769. // size of the struct) must also be written to the second argument.
  2770. AlignmentSizeCalculator alignmentCalc(astContext, spirvOptions);
  2771. uint32_t size = 0, stride = 0;
  2772. std::tie(std::ignore, size) =
  2773. alignmentCalc.getAlignmentAndSize(type, spirvOptions.sBufferLayoutRule,
  2774. /*isRowMajor*/ llvm::None, &stride);
  2775. auto *sizeInstr = spvBuilder.getConstantInt(astContext.UnsignedIntTy,
  2776. llvm::APInt(32, size));
  2777. spvBuilder.createStore(doExpr(expr->getArg(1)), sizeInstr,
  2778. expr->getArg(1)->getLocStart());
  2779. }
  2780. return nullptr;
  2781. }
  2782. SpirvInstruction *SpirvEmitter::processRWByteAddressBufferAtomicMethods(
  2783. hlsl::IntrinsicOp opcode, const CXXMemberCallExpr *expr) {
  2784. // The signature of RWByteAddressBuffer atomic methods are largely:
  2785. // void Interlocked*(in UINT dest, in UINT value);
  2786. // void Interlocked*(in UINT dest, in UINT value, out UINT original_value);
  2787. const auto *object = expr->getImplicitObjectArgument();
  2788. auto *objectInfo = loadIfAliasVarRef(object);
  2789. auto *zero =
  2790. spvBuilder.getConstantInt(astContext.UnsignedIntTy, llvm::APInt(32, 0));
  2791. auto *offset = doExpr(expr->getArg(0));
  2792. // Right shift by 2 to convert the byte offset to uint32_t offset
  2793. auto *address = spvBuilder.createBinaryOp(
  2794. spv::Op::OpShiftRightLogical, astContext.UnsignedIntTy, offset,
  2795. spvBuilder.getConstantInt(astContext.UnsignedIntTy, llvm::APInt(32, 2)),
  2796. expr->getExprLoc());
  2797. auto *ptr =
  2798. spvBuilder.createAccessChain(astContext.UnsignedIntTy, objectInfo,
  2799. {zero, address}, object->getLocStart());
  2800. const bool isCompareExchange =
  2801. opcode == hlsl::IntrinsicOp::MOP_InterlockedCompareExchange;
  2802. const bool isCompareStore =
  2803. opcode == hlsl::IntrinsicOp::MOP_InterlockedCompareStore;
  2804. if (isCompareExchange || isCompareStore) {
  2805. auto *comparator = doExpr(expr->getArg(1));
  2806. auto *originalVal = spvBuilder.createAtomicCompareExchange(
  2807. astContext.UnsignedIntTy, ptr, spv::Scope::Device,
  2808. spv::MemorySemanticsMask::MaskNone, spv::MemorySemanticsMask::MaskNone,
  2809. doExpr(expr->getArg(2)), comparator, expr->getCallee()->getExprLoc());
  2810. if (isCompareExchange)
  2811. spvBuilder.createStore(doExpr(expr->getArg(3)), originalVal,
  2812. expr->getArg(3)->getLocStart());
  2813. } else {
  2814. auto *value = doExpr(expr->getArg(1));
  2815. SpirvInstruction *originalVal = spvBuilder.createAtomicOp(
  2816. translateAtomicHlslOpcodeToSpirvOpcode(opcode),
  2817. astContext.UnsignedIntTy, ptr, spv::Scope::Device,
  2818. spv::MemorySemanticsMask::MaskNone, value,
  2819. expr->getCallee()->getExprLoc());
  2820. if (expr->getNumArgs() > 2) {
  2821. originalVal = castToType(originalVal, astContext.UnsignedIntTy,
  2822. expr->getArg(2)->getType(),
  2823. expr->getArg(2)->getLocStart());
  2824. spvBuilder.createStore(doExpr(expr->getArg(2)), originalVal,
  2825. expr->getArg(2)->getLocStart());
  2826. }
  2827. }
  2828. return nullptr;
  2829. }
  2830. SpirvInstruction *
  2831. SpirvEmitter::processGetSamplePosition(const CXXMemberCallExpr *expr) {
  2832. const auto *object = expr->getImplicitObjectArgument()->IgnoreParens();
  2833. auto *sampleCount = spvBuilder.createImageQuery(
  2834. spv::Op::OpImageQuerySamples, astContext.UnsignedIntTy,
  2835. expr->getExprLoc(), loadIfGLValue(object));
  2836. if (!spirvOptions.noWarnEmulatedFeatures)
  2837. emitWarning("GetSamplePosition is emulated using many SPIR-V instructions "
  2838. "due to lack of direct SPIR-V equivalent, so it only supports "
  2839. "standard sample settings with 1, 2, 4, 8, or 16 samples and "
  2840. "will return float2(0, 0) for other cases",
  2841. expr->getCallee()->getExprLoc());
  2842. return emitGetSamplePosition(sampleCount, doExpr(expr->getArg(0)),
  2843. expr->getCallee()->getExprLoc());
  2844. }
  2845. SpirvInstruction *
  2846. SpirvEmitter::processSubpassLoad(const CXXMemberCallExpr *expr) {
  2847. const auto *object = expr->getImplicitObjectArgument()->IgnoreParens();
  2848. SpirvInstruction *sample =
  2849. expr->getNumArgs() == 1 ? doExpr(expr->getArg(0)) : nullptr;
  2850. auto *zero = spvBuilder.getConstantInt(astContext.IntTy, llvm::APInt(32, 0));
  2851. auto *location = spvBuilder.getConstantComposite(
  2852. astContext.getExtVectorType(astContext.IntTy, 2), {zero, zero});
  2853. return processBufferTextureLoad(object, location, /*constOffset*/ 0,
  2854. /*varOffset*/ 0, /*lod*/ sample,
  2855. /*residencyCode*/ 0, expr->getExprLoc());
  2856. }
  2857. SpirvInstruction *
  2858. SpirvEmitter::processBufferTextureGetDimensions(const CXXMemberCallExpr *expr) {
  2859. const auto *object = expr->getImplicitObjectArgument();
  2860. auto *objectInstr = loadIfGLValue(object);
  2861. const auto type = object->getType();
  2862. const auto *recType = type->getAs<RecordType>();
  2863. assert(recType);
  2864. const auto typeName = recType->getDecl()->getName();
  2865. const auto numArgs = expr->getNumArgs();
  2866. const Expr *mipLevel = nullptr, *numLevels = nullptr, *numSamples = nullptr;
  2867. assert(isTexture(type) || isRWTexture(type) || isBuffer(type) ||
  2868. isRWBuffer(type));
  2869. // For Texture1D, arguments are either:
  2870. // a) width
  2871. // b) MipLevel, width, NumLevels
  2872. // For Texture1DArray, arguments are either:
  2873. // a) width, elements
  2874. // b) MipLevel, width, elements, NumLevels
  2875. // For Texture2D, arguments are either:
  2876. // a) width, height
  2877. // b) MipLevel, width, height, NumLevels
  2878. // For Texture2DArray, arguments are either:
  2879. // a) width, height, elements
  2880. // b) MipLevel, width, height, elements, NumLevels
  2881. // For Texture3D, arguments are either:
  2882. // a) width, height, depth
  2883. // b) MipLevel, width, height, depth, NumLevels
  2884. // For Texture2DMS, arguments are: width, height, NumSamples
  2885. // For Texture2DMSArray, arguments are: width, height, elements, NumSamples
  2886. // For TextureCube, arguments are either:
  2887. // a) width, height
  2888. // b) MipLevel, width, height, NumLevels
  2889. // For TextureCubeArray, arguments are either:
  2890. // a) width, height, elements
  2891. // b) MipLevel, width, height, elements, NumLevels
  2892. // Note: SPIR-V Spec requires return type of OpImageQuerySize(Lod) to be a
  2893. // scalar/vector of integers. SPIR-V Spec also requires return type of
  2894. // OpImageQueryLevels and OpImageQuerySamples to be scalar integers.
  2895. // The HLSL methods, however, have overloaded functions which have float
  2896. // output arguments. Since the AST naturally won't have casting AST nodes for
  2897. // such cases, we'll have to perform the cast ourselves.
  2898. const auto storeToOutputArg = [this](const Expr *outputArg,
  2899. SpirvInstruction *id, QualType type) {
  2900. id = castToType(id, type, outputArg->getType(), outputArg->getExprLoc());
  2901. spvBuilder.createStore(doExpr(outputArg), id, outputArg->getLocStart());
  2902. };
  2903. if ((typeName == "Texture1D" && numArgs > 1) ||
  2904. (typeName == "Texture2D" && numArgs > 2) ||
  2905. (typeName == "TextureCube" && numArgs > 2) ||
  2906. (typeName == "Texture3D" && numArgs > 3) ||
  2907. (typeName == "Texture1DArray" && numArgs > 2) ||
  2908. (typeName == "TextureCubeArray" && numArgs > 3) ||
  2909. (typeName == "Texture2DArray" && numArgs > 3)) {
  2910. mipLevel = expr->getArg(0);
  2911. numLevels = expr->getArg(numArgs - 1);
  2912. }
  2913. if (isTextureMS(type)) {
  2914. numSamples = expr->getArg(numArgs - 1);
  2915. }
  2916. uint32_t querySize = numArgs;
  2917. // If numLevels arg is present, mipLevel must also be present. These are not
  2918. // queried via ImageQuerySizeLod.
  2919. if (numLevels)
  2920. querySize -= 2;
  2921. // If numLevels arg is present, mipLevel must also be present.
  2922. else if (numSamples)
  2923. querySize -= 1;
  2924. const QualType resultQualType =
  2925. querySize == 1
  2926. ? astContext.UnsignedIntTy
  2927. : astContext.getExtVectorType(astContext.UnsignedIntTy, querySize);
  2928. // Only Texture types use ImageQuerySizeLod.
  2929. // TextureMS, RWTexture, Buffers, RWBuffers use ImageQuerySize.
  2930. SpirvInstruction *lod = nullptr;
  2931. if (isTexture(type) && !numSamples) {
  2932. if (mipLevel) {
  2933. // For Texture types when mipLevel argument is present.
  2934. lod = doExpr(mipLevel);
  2935. } else {
  2936. // For Texture types when mipLevel argument is omitted.
  2937. lod = spvBuilder.getConstantInt(astContext.IntTy, llvm::APInt(32, 0));
  2938. }
  2939. }
  2940. SpirvInstruction *query =
  2941. lod ? cast<SpirvInstruction>(spvBuilder.createImageQuery(
  2942. spv::Op::OpImageQuerySizeLod, resultQualType,
  2943. expr->getCallee()->getExprLoc(), objectInstr, lod))
  2944. : cast<SpirvInstruction>(spvBuilder.createImageQuery(
  2945. spv::Op::OpImageQuerySize, resultQualType,
  2946. expr->getCallee()->getExprLoc(), objectInstr));
  2947. if (querySize == 1) {
  2948. const uint32_t argIndex = mipLevel ? 1 : 0;
  2949. storeToOutputArg(expr->getArg(argIndex), query, resultQualType);
  2950. } else {
  2951. for (uint32_t i = 0; i < querySize; ++i) {
  2952. const uint32_t argIndex = mipLevel ? i + 1 : i;
  2953. auto *component = spvBuilder.createCompositeExtract(
  2954. astContext.UnsignedIntTy, query, {i},
  2955. expr->getCallee()->getExprLoc());
  2956. // If the first arg is the mipmap level, we must write the results
  2957. // starting from Arg(i+1), not Arg(i).
  2958. storeToOutputArg(expr->getArg(argIndex), component,
  2959. astContext.UnsignedIntTy);
  2960. }
  2961. }
  2962. if (numLevels || numSamples) {
  2963. const Expr *numLevelsSamplesArg = numLevels ? numLevels : numSamples;
  2964. const spv::Op opcode =
  2965. numLevels ? spv::Op::OpImageQueryLevels : spv::Op::OpImageQuerySamples;
  2966. auto *numLevelsSamplesQuery = spvBuilder.createImageQuery(
  2967. opcode, astContext.UnsignedIntTy, expr->getCallee()->getExprLoc(),
  2968. objectInstr);
  2969. storeToOutputArg(numLevelsSamplesArg, numLevelsSamplesQuery,
  2970. astContext.UnsignedIntTy);
  2971. }
  2972. return nullptr;
  2973. }
  2974. SpirvInstruction *
  2975. SpirvEmitter::processTextureLevelOfDetail(const CXXMemberCallExpr *expr,
  2976. bool unclamped) {
  2977. // Possible signatures are as follows:
  2978. // Texture1D(Array).CalculateLevelOfDetail(SamplerState S, float x);
  2979. // Texture2D(Array).CalculateLevelOfDetail(SamplerState S, float2 xy);
  2980. // TextureCube(Array).CalculateLevelOfDetail(SamplerState S, float3 xyz);
  2981. // Texture3D.CalculateLevelOfDetail(SamplerState S, float3 xyz);
  2982. // Return type is always a single float (LOD).
  2983. assert(expr->getNumArgs() == 2u);
  2984. const auto *object = expr->getImplicitObjectArgument();
  2985. auto *objectInfo = loadIfGLValue(object);
  2986. auto *samplerState = doExpr(expr->getArg(0));
  2987. auto *coordinate = doExpr(expr->getArg(1));
  2988. auto *sampledImage = spvBuilder.createSampledImage(
  2989. object->getType(), objectInfo, samplerState, expr->getExprLoc());
  2990. // The result type of OpImageQueryLod must be a float2.
  2991. const QualType queryResultType =
  2992. astContext.getExtVectorType(astContext.FloatTy, 2u);
  2993. auto *query =
  2994. spvBuilder.createImageQuery(spv::Op::OpImageQueryLod, queryResultType,
  2995. expr->getExprLoc(), sampledImage, coordinate);
  2996. // The first component of the float2 contains the mipmap array layer.
  2997. // The second component of the float2 represents the unclamped lod.
  2998. return spvBuilder.createCompositeExtract(astContext.FloatTy, query,
  2999. unclamped ? 1 : 0,
  3000. expr->getCallee()->getExprLoc());
  3001. }
  3002. SpirvInstruction *SpirvEmitter::processTextureGatherRGBACmpRGBA(
  3003. const CXXMemberCallExpr *expr, const bool isCmp, const uint32_t component) {
  3004. // Parameters for .Gather{Red|Green|Blue|Alpha}() are one of the following
  3005. // two sets:
  3006. // * SamplerState s, float2 location, int2 offset
  3007. // * SamplerState s, float2 location, int2 offset0, int2 offset1,
  3008. // int offset2, int2 offset3
  3009. //
  3010. // An additional 'out uint status' parameter can appear in both of the above.
  3011. //
  3012. // Parameters for .GatherCmp{Red|Green|Blue|Alpha}() are one of the following
  3013. // two sets:
  3014. // * SamplerState s, float2 location, float compare_value, int2 offset
  3015. // * SamplerState s, float2 location, float compare_value, int2 offset1,
  3016. // int2 offset2, int2 offset3, int2 offset4
  3017. //
  3018. // An additional 'out uint status' parameter can appear in both of the above.
  3019. //
  3020. // TextureCube's signature is somewhat different from the rest.
  3021. // Parameters for .Gather{Red|Green|Blue|Alpha}() for TextureCube are:
  3022. // * SamplerState s, float2 location, out uint status
  3023. // Parameters for .GatherCmp{Red|Green|Blue|Alpha}() for TextureCube are:
  3024. // * SamplerState s, float2 location, float compare_value, out uint status
  3025. //
  3026. // Return type is always a 4-component vector.
  3027. const FunctionDecl *callee = expr->getDirectCallee();
  3028. const auto numArgs = expr->getNumArgs();
  3029. const auto *imageExpr = expr->getImplicitObjectArgument();
  3030. const auto loc = expr->getCallee()->getExprLoc();
  3031. const QualType imageType = imageExpr->getType();
  3032. const QualType retType = callee->getReturnType();
  3033. // If the last arg is an unsigned integer, it must be the status.
  3034. const bool hasStatusArg =
  3035. expr->getArg(numArgs - 1)->getType()->isUnsignedIntegerType();
  3036. // Subtract 1 for status arg (if it exists), subtract 1 for compare_value (if
  3037. // it exists), and subtract 2 for SamplerState and location.
  3038. const auto numOffsetArgs = numArgs - hasStatusArg - isCmp - 2;
  3039. // No offset args for TextureCube, 1 or 4 offset args for the rest.
  3040. assert(numOffsetArgs == 0 || numOffsetArgs == 1 || numOffsetArgs == 4);
  3041. auto *image = loadIfGLValue(imageExpr);
  3042. auto *sampler = doExpr(expr->getArg(0));
  3043. auto *coordinate = doExpr(expr->getArg(1));
  3044. auto *compareVal = isCmp ? doExpr(expr->getArg(2)) : nullptr;
  3045. // Handle offsets (if any).
  3046. bool needsEmulation = false;
  3047. SpirvInstruction *constOffset = nullptr, *varOffset = nullptr,
  3048. *constOffsets = nullptr;
  3049. if (numOffsetArgs == 1) {
  3050. // The offset arg is not optional.
  3051. handleOffsetInMethodCall(expr, 2 + isCmp, &constOffset, &varOffset);
  3052. } else if (numOffsetArgs == 4) {
  3053. auto *offset0 = tryToEvaluateAsConst(expr->getArg(2 + isCmp));
  3054. auto *offset1 = tryToEvaluateAsConst(expr->getArg(3 + isCmp));
  3055. auto *offset2 = tryToEvaluateAsConst(expr->getArg(4 + isCmp));
  3056. auto *offset3 = tryToEvaluateAsConst(expr->getArg(5 + isCmp));
  3057. // If any of the offsets is not constant, we then need to emulate the call
  3058. // using 4 OpImageGather instructions. Otherwise, we can leverage the
  3059. // ConstOffsets image operand.
  3060. if (offset0 && offset1 && offset2 && offset3) {
  3061. const QualType v2i32 = astContext.getExtVectorType(astContext.IntTy, 2);
  3062. const auto offsetType = astContext.getConstantArrayType(
  3063. v2i32, llvm::APInt(32, 4), clang::ArrayType::Normal, 0);
  3064. constOffsets = spvBuilder.getConstantComposite(
  3065. offsetType, {offset0, offset1, offset2, offset3});
  3066. } else {
  3067. needsEmulation = true;
  3068. }
  3069. }
  3070. auto *status = hasStatusArg ? doExpr(expr->getArg(numArgs - 1)) : nullptr;
  3071. if (needsEmulation) {
  3072. const auto elemType = hlsl::GetHLSLVecElementType(callee->getReturnType());
  3073. SpirvInstruction *texels[4];
  3074. for (uint32_t i = 0; i < 4; ++i) {
  3075. varOffset = doExpr(expr->getArg(2 + isCmp + i));
  3076. auto *gatherRet = spvBuilder.createImageGather(
  3077. retType, imageType, image, sampler, coordinate,
  3078. spvBuilder.getConstantInt(astContext.IntTy,
  3079. llvm::APInt(32, component, true)),
  3080. compareVal,
  3081. /*constOffset*/ nullptr, varOffset, /*constOffsets*/ nullptr,
  3082. /*sampleNumber*/ nullptr, status, loc);
  3083. texels[i] =
  3084. spvBuilder.createCompositeExtract(elemType, gatherRet, {i}, loc);
  3085. }
  3086. return spvBuilder.createCompositeConstruct(
  3087. retType, {texels[0], texels[1], texels[2], texels[3]}, loc);
  3088. }
  3089. return spvBuilder.createImageGather(
  3090. retType, imageType, image, sampler, coordinate,
  3091. spvBuilder.getConstantInt(astContext.IntTy,
  3092. llvm::APInt(32, component, true)),
  3093. compareVal, constOffset, varOffset, constOffsets,
  3094. /*sampleNumber*/ nullptr, status, loc);
  3095. }
  3096. SpirvInstruction *
  3097. SpirvEmitter::processTextureGatherCmp(const CXXMemberCallExpr *expr) {
  3098. // Signature for Texture2D/Texture2DArray:
  3099. //
  3100. // float4 GatherCmp(
  3101. // in SamplerComparisonState s,
  3102. // in float2 location,
  3103. // in float compare_value
  3104. // [,in int2 offset]
  3105. // [,out uint Status]
  3106. // );
  3107. //
  3108. // Signature for TextureCube/TextureCubeArray:
  3109. //
  3110. // float4 GatherCmp(
  3111. // in SamplerComparisonState s,
  3112. // in float2 location,
  3113. // in float compare_value,
  3114. // out uint Status
  3115. // );
  3116. //
  3117. // Other Texture types do not have the GatherCmp method.
  3118. const FunctionDecl *callee = expr->getDirectCallee();
  3119. const auto numArgs = expr->getNumArgs();
  3120. const auto loc = expr->getExprLoc();
  3121. const bool hasStatusArg =
  3122. expr->getArg(numArgs - 1)->getType()->isUnsignedIntegerType();
  3123. const bool hasOffsetArg = (numArgs == 5) || (numArgs == 4 && !hasStatusArg);
  3124. const auto *imageExpr = expr->getImplicitObjectArgument();
  3125. auto *image = loadIfGLValue(imageExpr);
  3126. auto *sampler = doExpr(expr->getArg(0));
  3127. auto *coordinate = doExpr(expr->getArg(1));
  3128. auto *comparator = doExpr(expr->getArg(2));
  3129. SpirvInstruction *constOffset = nullptr, *varOffset = nullptr;
  3130. if (hasOffsetArg)
  3131. handleOffsetInMethodCall(expr, 3, &constOffset, &varOffset);
  3132. const auto retType = callee->getReturnType();
  3133. const auto imageType = imageExpr->getType();
  3134. const auto status =
  3135. hasStatusArg ? doExpr(expr->getArg(numArgs - 1)) : nullptr;
  3136. return spvBuilder.createImageGather(
  3137. retType, imageType, image, sampler, coordinate,
  3138. /*component*/ nullptr, comparator, constOffset, varOffset,
  3139. /*constOffsets*/ nullptr,
  3140. /*sampleNumber*/ nullptr, status, loc);
  3141. }
  3142. SpirvInstruction *SpirvEmitter::processBufferTextureLoad(
  3143. const Expr *object, SpirvInstruction *location,
  3144. SpirvInstruction *constOffset, SpirvInstruction *varOffset,
  3145. SpirvInstruction *lod, SpirvInstruction *residencyCode,
  3146. SourceLocation loc) {
  3147. // Loading for Buffer and RWBuffer translates to an OpImageFetch.
  3148. // The result type of an OpImageFetch must be a vec4 of float or int.
  3149. const auto type = object->getType();
  3150. assert(isBuffer(type) || isRWBuffer(type) || isTexture(type) ||
  3151. isRWTexture(type) || isSubpassInput(type) || isSubpassInputMS(type));
  3152. const bool doFetch = isBuffer(type) || isTexture(type);
  3153. auto *objectInfo = loadIfGLValue(object);
  3154. // For Texture2DMS and Texture2DMSArray, Sample must be used rather than Lod.
  3155. SpirvInstruction *sampleNumber = nullptr;
  3156. if (isTextureMS(type) || isSubpassInputMS(type)) {
  3157. sampleNumber = lod;
  3158. lod = nullptr;
  3159. }
  3160. const auto sampledType = hlsl::GetHLSLResourceResultType(type);
  3161. QualType elemType = sampledType;
  3162. uint32_t elemCount = 1;
  3163. bool isTemplateOverStruct = false;
  3164. // Check whether the template type is a vector type or struct type.
  3165. if (!isVectorType(sampledType, &elemType, &elemCount)) {
  3166. if (sampledType->getAsStructureType()) {
  3167. isTemplateOverStruct = true;
  3168. // For struct type, we need to make sure it can fit into a 4-component
  3169. // vector. Detailed failing reasons will be emitted by the function so
  3170. // we don't need to emit errors here.
  3171. if (!canFitIntoOneRegister(astContext, sampledType, &elemType,
  3172. &elemCount))
  3173. return nullptr;
  3174. }
  3175. }
  3176. {
  3177. // Treat a vector of size 1 the same as a scalar.
  3178. if (hlsl::IsHLSLVecType(elemType) && hlsl::GetHLSLVecSize(elemType) == 1)
  3179. elemType = hlsl::GetHLSLVecElementType(elemType);
  3180. if (!elemType->isFloatingType() && !elemType->isIntegerType()) {
  3181. emitError("loading %0 value unsupported", object->getExprLoc()) << type;
  3182. return nullptr;
  3183. }
  3184. }
  3185. // If residencyCode is nullptr, we are dealing with a Load method with 2
  3186. // arguments which does not return the operation status.
  3187. if (residencyCode && residencyCode->isRValue()) {
  3188. emitError(
  3189. "an lvalue argument should be used for returning the operation status",
  3190. loc);
  3191. return nullptr;
  3192. }
  3193. // OpImageFetch and OpImageRead can only fetch a vector of 4 elements.
  3194. const QualType texelType = astContext.getExtVectorType(elemType, 4u);
  3195. auto *texel = spvBuilder.createImageFetchOrRead(
  3196. doFetch, texelType, type, objectInfo, location, lod, constOffset,
  3197. varOffset, /*constOffsets*/ nullptr, sampleNumber, residencyCode, loc);
  3198. // If the result type is a vec1, vec2, or vec3, some extra processing
  3199. // (extraction) is required.
  3200. auto *retVal = extractVecFromVec4(texel, elemCount, elemType, loc);
  3201. if (isTemplateOverStruct) {
  3202. // Convert to the struct so that we are consistent with types in the AST.
  3203. retVal = convertVectorToStruct(sampledType, elemType, retVal, loc);
  3204. }
  3205. retVal->setRValue();
  3206. return retVal;
  3207. }
  3208. SpirvInstruction *SpirvEmitter::processByteAddressBufferLoadStore(
  3209. const CXXMemberCallExpr *expr, uint32_t numWords, bool doStore) {
  3210. SpirvInstruction *result = nullptr;
  3211. const auto object = expr->getImplicitObjectArgument();
  3212. auto *objectInfo = loadIfAliasVarRef(object);
  3213. assert(numWords >= 1 && numWords <= 4);
  3214. if (doStore) {
  3215. assert(isRWByteAddressBuffer(object->getType()));
  3216. assert(expr->getNumArgs() == 2);
  3217. } else {
  3218. assert(isRWByteAddressBuffer(object->getType()) ||
  3219. isByteAddressBuffer(object->getType()));
  3220. if (expr->getNumArgs() == 2) {
  3221. emitError(
  3222. "(RW)ByteAddressBuffer::Load(in address, out status) not supported",
  3223. expr->getExprLoc());
  3224. return 0;
  3225. }
  3226. }
  3227. const Expr *addressExpr = expr->getArg(0);
  3228. auto *byteAddress = doExpr(addressExpr);
  3229. const QualType addressType = addressExpr->getType();
  3230. // The front-end prevents usage of templated Load2, Load3, Load4, Store2,
  3231. // Store3, Store4 intrinsic functions.
  3232. const bool isTemplatedLoadOrStore =
  3233. (numWords == 1) &&
  3234. (doStore ? !expr->getArg(1)->getType()->isSpecificBuiltinType(
  3235. BuiltinType::UInt)
  3236. : !expr->getType()->isSpecificBuiltinType(BuiltinType::UInt));
  3237. // Do a OpShiftRightLogical by 2 (divide by 4 to get aligned memory
  3238. // access). The AST always casts the address to unsinged integer, so shift
  3239. // by unsinged integer 2.
  3240. auto *constUint2 =
  3241. spvBuilder.getConstantInt(astContext.UnsignedIntTy, llvm::APInt(32, 2));
  3242. SpirvInstruction *address =
  3243. spvBuilder.createBinaryOp(spv::Op::OpShiftRightLogical, addressType,
  3244. byteAddress, constUint2, expr->getExprLoc());
  3245. if (isTemplatedLoadOrStore) {
  3246. // Templated load. Need to (potentially) perform more
  3247. // loads/casts/composite-constructs.
  3248. uint32_t bitOffset = 0;
  3249. if (doStore) {
  3250. auto *values = doExpr(expr->getArg(1));
  3251. RawBufferHandler(*this).processTemplatedStoreToBuffer(
  3252. values, objectInfo, address, expr->getArg(1)->getType(), bitOffset);
  3253. return nullptr;
  3254. } else {
  3255. RawBufferHandler rawBufferHandler(*this);
  3256. return rawBufferHandler.processTemplatedLoadFromBuffer(
  3257. objectInfo, address, expr->getType(), bitOffset);
  3258. }
  3259. }
  3260. // Perform access chain into the RWByteAddressBuffer.
  3261. // First index must be zero (member 0 of the struct is a
  3262. // runtimeArray). The second index passed to OpAccessChain should be
  3263. // the address.
  3264. auto *constUint0 =
  3265. spvBuilder.getConstantInt(astContext.UnsignedIntTy, llvm::APInt(32, 0));
  3266. if (doStore) {
  3267. auto *values = doExpr(expr->getArg(1));
  3268. auto *curStoreAddress = address;
  3269. for (uint32_t wordCounter = 0; wordCounter < numWords; ++wordCounter) {
  3270. // Extract a 32-bit word from the input.
  3271. auto *curValue = numWords == 1
  3272. ? values
  3273. : spvBuilder.createCompositeExtract(
  3274. astContext.UnsignedIntTy, values,
  3275. {wordCounter}, expr->getArg(1)->getExprLoc());
  3276. // Update the output address if necessary.
  3277. if (wordCounter > 0) {
  3278. auto *offset = spvBuilder.getConstantInt(astContext.UnsignedIntTy,
  3279. llvm::APInt(32, wordCounter));
  3280. curStoreAddress =
  3281. spvBuilder.createBinaryOp(spv::Op::OpIAdd, addressType, address,
  3282. offset, expr->getCallee()->getExprLoc());
  3283. }
  3284. // Store the word to the right address at the output.
  3285. auto *storePtr = spvBuilder.createAccessChain(
  3286. astContext.UnsignedIntTy, objectInfo, {constUint0, curStoreAddress},
  3287. object->getLocStart());
  3288. spvBuilder.createStore(storePtr, curValue,
  3289. expr->getCallee()->getExprLoc());
  3290. }
  3291. } else {
  3292. auto *loadPtr = spvBuilder.createAccessChain(
  3293. astContext.UnsignedIntTy, objectInfo, {constUint0, address},
  3294. object->getLocStart());
  3295. result = spvBuilder.createLoad(astContext.UnsignedIntTy, loadPtr,
  3296. expr->getCallee()->getExprLoc());
  3297. if (numWords > 1) {
  3298. // Load word 2, 3, and 4 where necessary. Use OpCompositeConstruct to
  3299. // return a vector result.
  3300. llvm::SmallVector<SpirvInstruction *, 4> values;
  3301. values.push_back(result);
  3302. for (uint32_t wordCounter = 2; wordCounter <= numWords; ++wordCounter) {
  3303. auto *offset = spvBuilder.getConstantInt(
  3304. astContext.UnsignedIntTy, llvm::APInt(32, wordCounter - 1));
  3305. auto *newAddress =
  3306. spvBuilder.createBinaryOp(spv::Op::OpIAdd, addressType, address,
  3307. offset, expr->getCallee()->getExprLoc());
  3308. loadPtr = spvBuilder.createAccessChain(
  3309. astContext.UnsignedIntTy, objectInfo, {constUint0, newAddress},
  3310. object->getLocStart());
  3311. values.push_back(
  3312. spvBuilder.createLoad(astContext.UnsignedIntTy, loadPtr,
  3313. expr->getCallee()->getExprLoc()));
  3314. }
  3315. const QualType resultType =
  3316. astContext.getExtVectorType(addressType, numWords);
  3317. result = spvBuilder.createCompositeConstruct(resultType, values,
  3318. expr->getLocStart());
  3319. result->setRValue();
  3320. }
  3321. }
  3322. return result;
  3323. }
  3324. SpirvInstruction *
  3325. SpirvEmitter::processStructuredBufferLoad(const CXXMemberCallExpr *expr) {
  3326. if (expr->getNumArgs() == 2) {
  3327. emitError(
  3328. "(RW)StructuredBuffer::Load(in location, out status) not supported",
  3329. expr->getExprLoc());
  3330. return 0;
  3331. }
  3332. const auto *buffer = expr->getImplicitObjectArgument();
  3333. auto *info = loadIfAliasVarRef(buffer);
  3334. const QualType structType =
  3335. hlsl::GetHLSLResourceResultType(buffer->getType());
  3336. auto *zero = spvBuilder.getConstantInt(astContext.IntTy, llvm::APInt(32, 0));
  3337. auto *index = doExpr(expr->getArg(0));
  3338. return turnIntoElementPtr(buffer->getType(), info, structType, {zero, index},
  3339. buffer->getExprLoc());
  3340. }
  3341. SpirvInstruction *
  3342. SpirvEmitter::incDecRWACSBufferCounter(const CXXMemberCallExpr *expr,
  3343. bool isInc, bool loadObject) {
  3344. auto *zero =
  3345. spvBuilder.getConstantInt(astContext.UnsignedIntTy, llvm::APInt(32, 0));
  3346. auto *sOne =
  3347. spvBuilder.getConstantInt(astContext.IntTy, llvm::APInt(32, 1, true));
  3348. const auto srcLoc = expr->getCallee()->getExprLoc();
  3349. const auto *object =
  3350. expr->getImplicitObjectArgument()->IgnoreParenNoopCasts(astContext);
  3351. if (loadObject) {
  3352. // We don't need the object's <result-id> here since counter variable is a
  3353. // separate variable. But we still need the side effects of evaluating the
  3354. // object, e.g., if the source code is foo(...).IncrementCounter(), we still
  3355. // want to emit the code for foo(...).
  3356. (void)doExpr(object);
  3357. }
  3358. const auto *counterPair = getFinalACSBufferCounter(object);
  3359. if (!counterPair) {
  3360. emitFatalError("cannot find the associated counter variable",
  3361. object->getExprLoc());
  3362. return nullptr;
  3363. }
  3364. auto *counterPtr = spvBuilder.createAccessChain(
  3365. astContext.IntTy, counterPair->get(spvBuilder, spvContext), {zero},
  3366. srcLoc);
  3367. SpirvInstruction *index = nullptr;
  3368. if (isInc) {
  3369. index = spvBuilder.createAtomicOp(
  3370. spv::Op::OpAtomicIAdd, astContext.IntTy, counterPtr, spv::Scope::Device,
  3371. spv::MemorySemanticsMask::MaskNone, sOne, srcLoc);
  3372. } else {
  3373. // Note that OpAtomicISub returns the value before the subtraction;
  3374. // so we need to do substraction again with OpAtomicISub's return value.
  3375. auto *prev = spvBuilder.createAtomicOp(
  3376. spv::Op::OpAtomicISub, astContext.IntTy, counterPtr, spv::Scope::Device,
  3377. spv::MemorySemanticsMask::MaskNone, sOne, srcLoc);
  3378. index = spvBuilder.createBinaryOp(spv::Op::OpISub, astContext.IntTy, prev,
  3379. sOne, srcLoc);
  3380. }
  3381. return index;
  3382. }
  3383. bool SpirvEmitter::tryToAssignCounterVar(const DeclaratorDecl *dstDecl,
  3384. const Expr *srcExpr) {
  3385. // We are handling associated counters here. Casts should not alter which
  3386. // associated counter to manipulate.
  3387. srcExpr = srcExpr->IgnoreParenCasts();
  3388. // For parameters of forward-declared functions. We must make sure the
  3389. // associated counter variable is created. But for forward-declared functions,
  3390. // the translation of the real definition may not be started yet.
  3391. if (const auto *param = dyn_cast<ParmVarDecl>(dstDecl))
  3392. declIdMapper.createFnParamCounterVar(param);
  3393. // For implicit objects of methods. Similar to the above.
  3394. else if (const auto *thisObject = dyn_cast<ImplicitParamDecl>(dstDecl))
  3395. declIdMapper.createFnParamCounterVar(thisObject);
  3396. // Handle AssocCounter#1 (see CounterVarFields comment)
  3397. if (const auto *dstPair = declIdMapper.getCounterIdAliasPair(dstDecl)) {
  3398. const auto *srcPair = getFinalACSBufferCounter(srcExpr);
  3399. if (!srcPair) {
  3400. emitFatalError("cannot find the associated counter variable",
  3401. srcExpr->getExprLoc());
  3402. return false;
  3403. }
  3404. dstPair->assign(*srcPair, spvBuilder, spvContext);
  3405. return true;
  3406. }
  3407. // Handle AssocCounter#3
  3408. llvm::SmallVector<uint32_t, 4> srcIndices;
  3409. const auto *dstFields = declIdMapper.getCounterVarFields(dstDecl);
  3410. const auto *srcFields = getIntermediateACSBufferCounter(srcExpr, &srcIndices);
  3411. if (dstFields && srcFields) {
  3412. // The destination is a struct whose fields are directly alias resources.
  3413. // But that's not necessarily true for the source, which can be deep
  3414. // nested structs. That means they will have different index "prefixes"
  3415. // for all their fields; while the "prefix" for destination is effectively
  3416. // an empty list (since it is not nested in other structs). We need to
  3417. // strip the index prefix from the source.
  3418. return dstFields->assign(*srcFields, /*dstIndices=*/{}, srcIndices,
  3419. spvBuilder, spvContext);
  3420. }
  3421. // AssocCounter#2 and AssocCounter#4 for the lhs cannot happen since the lhs
  3422. // is a stand-alone decl in this method.
  3423. return false;
  3424. }
  3425. bool SpirvEmitter::tryToAssignCounterVar(const Expr *dstExpr,
  3426. const Expr *srcExpr) {
  3427. dstExpr = dstExpr->IgnoreParenCasts();
  3428. srcExpr = srcExpr->IgnoreParenCasts();
  3429. const auto *dstPair = getFinalACSBufferCounter(dstExpr);
  3430. const auto *srcPair = getFinalACSBufferCounter(srcExpr);
  3431. if ((dstPair == nullptr) != (srcPair == nullptr)) {
  3432. emitFatalError("cannot handle associated counter variable assignment",
  3433. srcExpr->getExprLoc());
  3434. return false;
  3435. }
  3436. // Handle AssocCounter#1 & AssocCounter#2
  3437. if (dstPair && srcPair) {
  3438. dstPair->assign(*srcPair, spvBuilder, spvContext);
  3439. return true;
  3440. }
  3441. // Handle AssocCounter#3 & AssocCounter#4
  3442. llvm::SmallVector<uint32_t, 4> dstIndices;
  3443. llvm::SmallVector<uint32_t, 4> srcIndices;
  3444. const auto *srcFields = getIntermediateACSBufferCounter(srcExpr, &srcIndices);
  3445. const auto *dstFields = getIntermediateACSBufferCounter(dstExpr, &dstIndices);
  3446. if (dstFields && srcFields) {
  3447. return dstFields->assign(*srcFields, dstIndices, srcIndices, spvBuilder,
  3448. spvContext);
  3449. }
  3450. return false;
  3451. }
  3452. const CounterIdAliasPair *
  3453. SpirvEmitter::getFinalACSBufferCounter(const Expr *expr) {
  3454. // AssocCounter#1: referencing some stand-alone variable
  3455. if (const auto *decl = getReferencedDef(expr))
  3456. return declIdMapper.getCounterIdAliasPair(decl);
  3457. // AssocCounter#2: referencing some non-struct field
  3458. llvm::SmallVector<uint32_t, 4> rawIndices;
  3459. const auto *base = collectArrayStructIndices(
  3460. expr, /*rawIndex=*/true, &rawIndices, /*indices*/ nullptr);
  3461. const auto *decl =
  3462. (base && isa<CXXThisExpr>(base))
  3463. ? getOrCreateDeclForMethodObject(cast<CXXMethodDecl>(curFunction))
  3464. : getReferencedDef(base);
  3465. return declIdMapper.getCounterIdAliasPair(decl, &rawIndices);
  3466. }
  3467. const CounterVarFields *SpirvEmitter::getIntermediateACSBufferCounter(
  3468. const Expr *expr, llvm::SmallVector<uint32_t, 4> *rawIndices) {
  3469. const auto *base = collectArrayStructIndices(expr, /*rawIndex=*/true,
  3470. rawIndices, /*indices*/ nullptr);
  3471. const auto *decl =
  3472. (base && isa<CXXThisExpr>(base))
  3473. // Use the decl we created to represent the implicit object
  3474. ? getOrCreateDeclForMethodObject(cast<CXXMethodDecl>(curFunction))
  3475. // Find the referenced decl from the original source code
  3476. : getReferencedDef(base);
  3477. return declIdMapper.getCounterVarFields(decl);
  3478. }
  3479. const ImplicitParamDecl *
  3480. SpirvEmitter::getOrCreateDeclForMethodObject(const CXXMethodDecl *method) {
  3481. const auto found = thisDecls.find(method);
  3482. if (found != thisDecls.end())
  3483. return found->second;
  3484. const std::string name = method->getName().str() + ".this";
  3485. // Create a new identifier to convey the name
  3486. auto &identifier = astContext.Idents.get(name);
  3487. return thisDecls[method] = ImplicitParamDecl::Create(
  3488. astContext, /*DC=*/nullptr, SourceLocation(), &identifier,
  3489. method->getThisType(astContext)->getPointeeType());
  3490. }
  3491. SpirvInstruction *
  3492. SpirvEmitter::processACSBufferAppendConsume(const CXXMemberCallExpr *expr) {
  3493. const bool isAppend = expr->getNumArgs() == 1;
  3494. auto *zero =
  3495. spvBuilder.getConstantInt(astContext.UnsignedIntTy, llvm::APInt(32, 0));
  3496. const auto *object =
  3497. expr->getImplicitObjectArgument()->IgnoreParenNoopCasts(astContext);
  3498. auto *bufferInfo = loadIfAliasVarRef(object);
  3499. auto *index = incDecRWACSBufferCounter(
  3500. expr, isAppend,
  3501. // We have already translated the object in the above. Avoid duplication.
  3502. /*loadObject=*/false);
  3503. auto bufferElemTy = hlsl::GetHLSLResourceResultType(object->getType());
  3504. // If this is a variable to communicate with host e.g., ACSBuffer
  3505. // and its type is bool or vector of bool, its effective type used
  3506. // for SPIRV must be uint not bool. We must convert it to uint here.
  3507. bool needCast = false;
  3508. if (bufferInfo->getLayoutRule() != SpirvLayoutRule::Void &&
  3509. isBoolOrVecOfBoolType(bufferElemTy)) {
  3510. uint32_t vecSize = 1;
  3511. const bool isVec = isVectorType(bufferElemTy, nullptr, &vecSize);
  3512. bufferElemTy =
  3513. isVec ? astContext.getExtVectorType(astContext.UnsignedIntTy, vecSize)
  3514. : astContext.UnsignedIntTy;
  3515. needCast = true;
  3516. }
  3517. bufferInfo = turnIntoElementPtr(object->getType(), bufferInfo, bufferElemTy,
  3518. {zero, index}, object->getExprLoc());
  3519. if (isAppend) {
  3520. // Write out the value
  3521. auto *arg0 = doExpr(expr->getArg(0));
  3522. if (!arg0)
  3523. return nullptr;
  3524. if (!arg0->isRValue()) {
  3525. arg0 = spvBuilder.createLoad(bufferElemTy, arg0,
  3526. expr->getArg(0)->getExprLoc());
  3527. }
  3528. if (needCast &&
  3529. !isSameType(astContext, bufferElemTy, arg0->getAstResultType())) {
  3530. arg0 = castToType(arg0, arg0->getAstResultType(), bufferElemTy,
  3531. expr->getArg(0)->getExprLoc());
  3532. }
  3533. storeValue(bufferInfo, arg0, bufferElemTy, expr->getCallee()->getExprLoc());
  3534. return 0;
  3535. } else {
  3536. // Note that we are returning a pointer (lvalue) here inorder to further
  3537. // acess the fields in this element, e.g., buffer.Consume().a.b. So we
  3538. // cannot forcefully set all normal function calls as returning rvalue.
  3539. return bufferInfo;
  3540. }
  3541. }
  3542. SpirvInstruction *
  3543. SpirvEmitter::processStreamOutputAppend(const CXXMemberCallExpr *expr) {
  3544. // TODO: handle multiple stream-output objects
  3545. const auto *object =
  3546. expr->getImplicitObjectArgument()->IgnoreParenNoopCasts(astContext);
  3547. const auto *stream = cast<DeclRefExpr>(object)->getDecl();
  3548. auto *value = doExpr(expr->getArg(0));
  3549. declIdMapper.writeBackOutputStream(stream, stream->getType(), value);
  3550. spvBuilder.createEmitVertex(expr->getExprLoc());
  3551. return nullptr;
  3552. }
  3553. SpirvInstruction *
  3554. SpirvEmitter::processStreamOutputRestart(const CXXMemberCallExpr *expr) {
  3555. // TODO: handle multiple stream-output objects
  3556. spvBuilder.createEndPrimitive(expr->getExprLoc());
  3557. return 0;
  3558. }
  3559. SpirvInstruction *
  3560. SpirvEmitter::emitGetSamplePosition(SpirvInstruction *sampleCount,
  3561. SpirvInstruction *sampleIndex,
  3562. SourceLocation loc) {
  3563. struct Float2 {
  3564. float x;
  3565. float y;
  3566. };
  3567. static const Float2 pos2[] = {
  3568. {4.0 / 16.0, 4.0 / 16.0},
  3569. {-4.0 / 16.0, -4.0 / 16.0},
  3570. };
  3571. static const Float2 pos4[] = {
  3572. {-2.0 / 16.0, -6.0 / 16.0},
  3573. {6.0 / 16.0, -2.0 / 16.0},
  3574. {-6.0 / 16.0, 2.0 / 16.0},
  3575. {2.0 / 16.0, 6.0 / 16.0},
  3576. };
  3577. static const Float2 pos8[] = {
  3578. {1.0 / 16.0, -3.0 / 16.0}, {-1.0 / 16.0, 3.0 / 16.0},
  3579. {5.0 / 16.0, 1.0 / 16.0}, {-3.0 / 16.0, -5.0 / 16.0},
  3580. {-5.0 / 16.0, 5.0 / 16.0}, {-7.0 / 16.0, -1.0 / 16.0},
  3581. {3.0 / 16.0, 7.0 / 16.0}, {7.0 / 16.0, -7.0 / 16.0},
  3582. };
  3583. static const Float2 pos16[] = {
  3584. {1.0 / 16.0, 1.0 / 16.0}, {-1.0 / 16.0, -3.0 / 16.0},
  3585. {-3.0 / 16.0, 2.0 / 16.0}, {4.0 / 16.0, -1.0 / 16.0},
  3586. {-5.0 / 16.0, -2.0 / 16.0}, {2.0 / 16.0, 5.0 / 16.0},
  3587. {5.0 / 16.0, 3.0 / 16.0}, {3.0 / 16.0, -5.0 / 16.0},
  3588. {-2.0 / 16.0, 6.0 / 16.0}, {0.0 / 16.0, -7.0 / 16.0},
  3589. {-4.0 / 16.0, -6.0 / 16.0}, {-6.0 / 16.0, 4.0 / 16.0},
  3590. {-8.0 / 16.0, 0.0 / 16.0}, {7.0 / 16.0, -4.0 / 16.0},
  3591. {6.0 / 16.0, 7.0 / 16.0}, {-7.0 / 16.0, -8.0 / 16.0},
  3592. };
  3593. // We are emitting the SPIR-V for the following HLSL source code:
  3594. //
  3595. // float2 position;
  3596. //
  3597. // if (count == 2) {
  3598. // position = pos2[index];
  3599. // }
  3600. // else if (count == 4) {
  3601. // position = pos4[index];
  3602. // }
  3603. // else if (count == 8) {
  3604. // position = pos8[index];
  3605. // }
  3606. // else if (count == 16) {
  3607. // position = pos16[index];
  3608. // }
  3609. // else {
  3610. // position = float2(0.0f, 0.0f);
  3611. // }
  3612. const auto v2f32Type = astContext.getExtVectorType(astContext.FloatTy, 2);
  3613. // Creates a SPIR-V function scope variable of type float2[len].
  3614. const auto createArray = [this, v2f32Type, loc](const Float2 *ptr,
  3615. uint32_t len) {
  3616. llvm::SmallVector<SpirvConstant *, 16> components;
  3617. for (uint32_t i = 0; i < len; ++i) {
  3618. auto *x = spvBuilder.getConstantFloat(astContext.FloatTy,
  3619. llvm::APFloat(ptr[i].x));
  3620. auto *y = spvBuilder.getConstantFloat(astContext.FloatTy,
  3621. llvm::APFloat(ptr[i].y));
  3622. components.push_back(spvBuilder.getConstantComposite(v2f32Type, {x, y}));
  3623. }
  3624. const auto arrType = astContext.getConstantArrayType(
  3625. v2f32Type, llvm::APInt(32, len), clang::ArrayType::Normal, 0);
  3626. auto *val = spvBuilder.getConstantComposite(arrType, components);
  3627. const std::string varName =
  3628. "var.GetSamplePosition.data." + std::to_string(len);
  3629. auto *var = spvBuilder.addFnVar(arrType, loc, varName);
  3630. spvBuilder.createStore(var, val, loc);
  3631. return var;
  3632. };
  3633. auto *pos2Arr = createArray(pos2, 2);
  3634. auto *pos4Arr = createArray(pos4, 4);
  3635. auto *pos8Arr = createArray(pos8, 8);
  3636. auto *pos16Arr = createArray(pos16, 16);
  3637. auto *resultVar =
  3638. spvBuilder.addFnVar(v2f32Type, loc, "var.GetSamplePosition.result");
  3639. auto *then2BB = spvBuilder.createBasicBlock("if.GetSamplePosition.then2");
  3640. auto *then4BB = spvBuilder.createBasicBlock("if.GetSamplePosition.then4");
  3641. auto *then8BB = spvBuilder.createBasicBlock("if.GetSamplePosition.then8");
  3642. auto *then16BB = spvBuilder.createBasicBlock("if.GetSamplePosition.then16");
  3643. auto *else2BB = spvBuilder.createBasicBlock("if.GetSamplePosition.else2");
  3644. auto *else4BB = spvBuilder.createBasicBlock("if.GetSamplePosition.else4");
  3645. auto *else8BB = spvBuilder.createBasicBlock("if.GetSamplePosition.else8");
  3646. auto *else16BB = spvBuilder.createBasicBlock("if.GetSamplePosition.else16");
  3647. auto *merge2BB = spvBuilder.createBasicBlock("if.GetSamplePosition.merge2");
  3648. auto *merge4BB = spvBuilder.createBasicBlock("if.GetSamplePosition.merge4");
  3649. auto *merge8BB = spvBuilder.createBasicBlock("if.GetSamplePosition.merge8");
  3650. auto *merge16BB = spvBuilder.createBasicBlock("if.GetSamplePosition.merge16");
  3651. // if (count == 2) {
  3652. const auto check2 = spvBuilder.createBinaryOp(
  3653. spv::Op::OpIEqual, astContext.BoolTy, sampleCount,
  3654. spvBuilder.getConstantInt(astContext.UnsignedIntTy, llvm::APInt(32, 2)),
  3655. loc);
  3656. spvBuilder.createConditionalBranch(check2, then2BB, else2BB, loc, merge2BB);
  3657. spvBuilder.addSuccessor(then2BB);
  3658. spvBuilder.addSuccessor(else2BB);
  3659. spvBuilder.setMergeTarget(merge2BB);
  3660. // position = pos2[index];
  3661. // }
  3662. spvBuilder.setInsertPoint(then2BB);
  3663. auto *ac =
  3664. spvBuilder.createAccessChain(v2f32Type, pos2Arr, {sampleIndex}, loc);
  3665. spvBuilder.createStore(resultVar, spvBuilder.createLoad(v2f32Type, ac, loc),
  3666. loc);
  3667. spvBuilder.createBranch(merge2BB, loc);
  3668. spvBuilder.addSuccessor(merge2BB);
  3669. // else if (count == 4) {
  3670. spvBuilder.setInsertPoint(else2BB);
  3671. const auto check4 = spvBuilder.createBinaryOp(
  3672. spv::Op::OpIEqual, astContext.BoolTy, sampleCount,
  3673. spvBuilder.getConstantInt(astContext.UnsignedIntTy, llvm::APInt(32, 4)),
  3674. loc);
  3675. spvBuilder.createConditionalBranch(check4, then4BB, else4BB, loc, merge4BB);
  3676. spvBuilder.addSuccessor(then4BB);
  3677. spvBuilder.addSuccessor(else4BB);
  3678. spvBuilder.setMergeTarget(merge4BB);
  3679. // position = pos4[index];
  3680. // }
  3681. spvBuilder.setInsertPoint(then4BB);
  3682. ac = spvBuilder.createAccessChain(v2f32Type, pos4Arr, {sampleIndex}, loc);
  3683. spvBuilder.createStore(resultVar, spvBuilder.createLoad(v2f32Type, ac, loc),
  3684. loc);
  3685. spvBuilder.createBranch(merge4BB, loc);
  3686. spvBuilder.addSuccessor(merge4BB);
  3687. // else if (count == 8) {
  3688. spvBuilder.setInsertPoint(else4BB);
  3689. const auto check8 = spvBuilder.createBinaryOp(
  3690. spv::Op::OpIEqual, astContext.BoolTy, sampleCount,
  3691. spvBuilder.getConstantInt(astContext.UnsignedIntTy, llvm::APInt(32, 8)),
  3692. loc);
  3693. spvBuilder.createConditionalBranch(check8, then8BB, else8BB, loc, merge8BB);
  3694. spvBuilder.addSuccessor(then8BB);
  3695. spvBuilder.addSuccessor(else8BB);
  3696. spvBuilder.setMergeTarget(merge8BB);
  3697. // position = pos8[index];
  3698. // }
  3699. spvBuilder.setInsertPoint(then8BB);
  3700. ac = spvBuilder.createAccessChain(v2f32Type, pos8Arr, {sampleIndex}, loc);
  3701. spvBuilder.createStore(resultVar, spvBuilder.createLoad(v2f32Type, ac, loc),
  3702. loc);
  3703. spvBuilder.createBranch(merge8BB, loc);
  3704. spvBuilder.addSuccessor(merge8BB);
  3705. // else if (count == 16) {
  3706. spvBuilder.setInsertPoint(else8BB);
  3707. const auto check16 = spvBuilder.createBinaryOp(
  3708. spv::Op::OpIEqual, astContext.BoolTy, sampleCount,
  3709. spvBuilder.getConstantInt(astContext.UnsignedIntTy, llvm::APInt(32, 16)),
  3710. loc);
  3711. spvBuilder.createConditionalBranch(check16, then16BB, else16BB, loc,
  3712. merge16BB);
  3713. spvBuilder.addSuccessor(then16BB);
  3714. spvBuilder.addSuccessor(else16BB);
  3715. spvBuilder.setMergeTarget(merge16BB);
  3716. // position = pos16[index];
  3717. // }
  3718. spvBuilder.setInsertPoint(then16BB);
  3719. ac = spvBuilder.createAccessChain(v2f32Type, pos16Arr, {sampleIndex}, loc);
  3720. spvBuilder.createStore(resultVar, spvBuilder.createLoad(v2f32Type, ac, loc),
  3721. loc);
  3722. spvBuilder.createBranch(merge16BB, loc);
  3723. spvBuilder.addSuccessor(merge16BB);
  3724. // else {
  3725. // position = float2(0.0f, 0.0f);
  3726. // }
  3727. spvBuilder.setInsertPoint(else16BB);
  3728. auto *zero =
  3729. spvBuilder.getConstantFloat(astContext.FloatTy, llvm::APFloat(0.0f));
  3730. auto *v2f32Zero = spvBuilder.getConstantComposite(v2f32Type, {zero, zero});
  3731. spvBuilder.createStore(resultVar, v2f32Zero, loc);
  3732. spvBuilder.createBranch(merge16BB, loc);
  3733. spvBuilder.addSuccessor(merge16BB);
  3734. spvBuilder.setInsertPoint(merge16BB);
  3735. spvBuilder.createBranch(merge8BB, loc);
  3736. spvBuilder.addSuccessor(merge8BB);
  3737. spvBuilder.setInsertPoint(merge8BB);
  3738. spvBuilder.createBranch(merge4BB, loc);
  3739. spvBuilder.addSuccessor(merge4BB);
  3740. spvBuilder.setInsertPoint(merge4BB);
  3741. spvBuilder.createBranch(merge2BB, loc);
  3742. spvBuilder.addSuccessor(merge2BB);
  3743. spvBuilder.setInsertPoint(merge2BB);
  3744. return spvBuilder.createLoad(v2f32Type, resultVar, loc);
  3745. }
  3746. SpirvInstruction *
  3747. SpirvEmitter::doCXXMemberCallExpr(const CXXMemberCallExpr *expr) {
  3748. const FunctionDecl *callee = expr->getDirectCallee();
  3749. llvm::StringRef group;
  3750. uint32_t opcode = static_cast<uint32_t>(hlsl::IntrinsicOp::Num_Intrinsics);
  3751. if (hlsl::GetIntrinsicOp(callee, opcode, group)) {
  3752. return processIntrinsicMemberCall(expr,
  3753. static_cast<hlsl::IntrinsicOp>(opcode));
  3754. }
  3755. return processCall(expr);
  3756. }
  3757. void SpirvEmitter::handleOffsetInMethodCall(const CXXMemberCallExpr *expr,
  3758. uint32_t index,
  3759. SpirvInstruction **constOffset,
  3760. SpirvInstruction **varOffset) {
  3761. assert(constOffset && varOffset);
  3762. // Ensure the given arg index is not out-of-range.
  3763. assert(index < expr->getNumArgs());
  3764. *constOffset = *varOffset = nullptr; // Initialize both first
  3765. if ((*constOffset = tryToEvaluateAsConst(expr->getArg(index))))
  3766. return; // Constant offset
  3767. else
  3768. *varOffset = doExpr(expr->getArg(index));
  3769. }
  3770. SpirvInstruction *
  3771. SpirvEmitter::processIntrinsicMemberCall(const CXXMemberCallExpr *expr,
  3772. hlsl::IntrinsicOp opcode) {
  3773. using namespace hlsl;
  3774. SpirvInstruction *retVal = nullptr;
  3775. switch (opcode) {
  3776. case IntrinsicOp::MOP_Sample:
  3777. retVal = processTextureSampleGather(expr, /*isSample=*/true);
  3778. break;
  3779. case IntrinsicOp::MOP_Gather:
  3780. retVal = processTextureSampleGather(expr, /*isSample=*/false);
  3781. break;
  3782. case IntrinsicOp::MOP_SampleBias:
  3783. retVal = processTextureSampleBiasLevel(expr, /*isBias=*/true);
  3784. break;
  3785. case IntrinsicOp::MOP_SampleLevel:
  3786. retVal = processTextureSampleBiasLevel(expr, /*isBias=*/false);
  3787. break;
  3788. case IntrinsicOp::MOP_SampleGrad:
  3789. retVal = processTextureSampleGrad(expr);
  3790. break;
  3791. case IntrinsicOp::MOP_SampleCmp:
  3792. retVal = processTextureSampleCmpCmpLevelZero(expr, /*isCmp=*/true);
  3793. break;
  3794. case IntrinsicOp::MOP_SampleCmpLevelZero:
  3795. retVal = processTextureSampleCmpCmpLevelZero(expr, /*isCmp=*/false);
  3796. break;
  3797. case IntrinsicOp::MOP_GatherRed:
  3798. retVal = processTextureGatherRGBACmpRGBA(expr, /*isCmp=*/false, 0);
  3799. break;
  3800. case IntrinsicOp::MOP_GatherGreen:
  3801. retVal = processTextureGatherRGBACmpRGBA(expr, /*isCmp=*/false, 1);
  3802. break;
  3803. case IntrinsicOp::MOP_GatherBlue:
  3804. retVal = processTextureGatherRGBACmpRGBA(expr, /*isCmp=*/false, 2);
  3805. break;
  3806. case IntrinsicOp::MOP_GatherAlpha:
  3807. retVal = processTextureGatherRGBACmpRGBA(expr, /*isCmp=*/false, 3);
  3808. break;
  3809. case IntrinsicOp::MOP_GatherCmp:
  3810. retVal = processTextureGatherCmp(expr);
  3811. break;
  3812. case IntrinsicOp::MOP_GatherCmpRed:
  3813. retVal = processTextureGatherRGBACmpRGBA(expr, /*isCmp=*/true, 0);
  3814. break;
  3815. case IntrinsicOp::MOP_Load:
  3816. return processBufferTextureLoad(expr);
  3817. case IntrinsicOp::MOP_Load2:
  3818. return processByteAddressBufferLoadStore(expr, 2, /*doStore*/ false);
  3819. case IntrinsicOp::MOP_Load3:
  3820. return processByteAddressBufferLoadStore(expr, 3, /*doStore*/ false);
  3821. case IntrinsicOp::MOP_Load4:
  3822. return processByteAddressBufferLoadStore(expr, 4, /*doStore*/ false);
  3823. case IntrinsicOp::MOP_Store:
  3824. return processByteAddressBufferLoadStore(expr, 1, /*doStore*/ true);
  3825. case IntrinsicOp::MOP_Store2:
  3826. return processByteAddressBufferLoadStore(expr, 2, /*doStore*/ true);
  3827. case IntrinsicOp::MOP_Store3:
  3828. return processByteAddressBufferLoadStore(expr, 3, /*doStore*/ true);
  3829. case IntrinsicOp::MOP_Store4:
  3830. return processByteAddressBufferLoadStore(expr, 4, /*doStore*/ true);
  3831. case IntrinsicOp::MOP_GetDimensions:
  3832. retVal = processGetDimensions(expr);
  3833. break;
  3834. case IntrinsicOp::MOP_CalculateLevelOfDetail:
  3835. retVal = processTextureLevelOfDetail(expr, /* unclamped */ false);
  3836. case IntrinsicOp::MOP_CalculateLevelOfDetailUnclamped:
  3837. retVal = processTextureLevelOfDetail(expr, /* unclamped */ true);
  3838. break;
  3839. case IntrinsicOp::MOP_IncrementCounter:
  3840. retVal =
  3841. spvBuilder.createUnaryOp(spv::Op::OpBitcast, astContext.UnsignedIntTy,
  3842. incDecRWACSBufferCounter(expr, /*isInc*/ true),
  3843. expr->getCallee()->getExprLoc());
  3844. break;
  3845. case IntrinsicOp::MOP_DecrementCounter:
  3846. retVal = spvBuilder.createUnaryOp(
  3847. spv::Op::OpBitcast, astContext.UnsignedIntTy,
  3848. incDecRWACSBufferCounter(expr, /*isInc*/ false),
  3849. expr->getCallee()->getExprLoc());
  3850. break;
  3851. case IntrinsicOp::MOP_Append:
  3852. if (hlsl::IsHLSLStreamOutputType(
  3853. expr->getImplicitObjectArgument()->getType()))
  3854. return processStreamOutputAppend(expr);
  3855. else
  3856. return processACSBufferAppendConsume(expr);
  3857. case IntrinsicOp::MOP_Consume:
  3858. return processACSBufferAppendConsume(expr);
  3859. case IntrinsicOp::MOP_RestartStrip:
  3860. retVal = processStreamOutputRestart(expr);
  3861. break;
  3862. case IntrinsicOp::MOP_InterlockedAdd:
  3863. case IntrinsicOp::MOP_InterlockedAnd:
  3864. case IntrinsicOp::MOP_InterlockedOr:
  3865. case IntrinsicOp::MOP_InterlockedXor:
  3866. case IntrinsicOp::MOP_InterlockedUMax:
  3867. case IntrinsicOp::MOP_InterlockedUMin:
  3868. case IntrinsicOp::MOP_InterlockedMax:
  3869. case IntrinsicOp::MOP_InterlockedMin:
  3870. case IntrinsicOp::MOP_InterlockedExchange:
  3871. case IntrinsicOp::MOP_InterlockedCompareExchange:
  3872. case IntrinsicOp::MOP_InterlockedCompareStore:
  3873. retVal = processRWByteAddressBufferAtomicMethods(opcode, expr);
  3874. break;
  3875. case IntrinsicOp::MOP_GetSamplePosition:
  3876. retVal = processGetSamplePosition(expr);
  3877. break;
  3878. case IntrinsicOp::MOP_SubpassLoad:
  3879. retVal = processSubpassLoad(expr);
  3880. break;
  3881. case IntrinsicOp::MOP_GatherCmpGreen:
  3882. case IntrinsicOp::MOP_GatherCmpBlue:
  3883. case IntrinsicOp::MOP_GatherCmpAlpha:
  3884. emitError("no equivalent for %0 intrinsic method in Vulkan",
  3885. expr->getCallee()->getExprLoc())
  3886. << expr->getMethodDecl()->getName();
  3887. return nullptr;
  3888. case IntrinsicOp::MOP_TraceRayInline:
  3889. return processTraceRayInline(expr);
  3890. case IntrinsicOp::MOP_Abort:
  3891. case IntrinsicOp::MOP_CandidateGeometryIndex:
  3892. case IntrinsicOp::MOP_CandidateInstanceContributionToHitGroupIndex:
  3893. case IntrinsicOp::MOP_CandidateInstanceID:
  3894. case IntrinsicOp::MOP_CandidateInstanceIndex:
  3895. case IntrinsicOp::MOP_CandidateObjectRayDirection:
  3896. case IntrinsicOp::MOP_CandidateObjectRayOrigin:
  3897. case IntrinsicOp::MOP_CandidateObjectToWorld3x4:
  3898. case IntrinsicOp::MOP_CandidateObjectToWorld4x3:
  3899. case IntrinsicOp::MOP_CandidatePrimitiveIndex:
  3900. case IntrinsicOp::MOP_CandidateProceduralPrimitiveNonOpaque:
  3901. case IntrinsicOp::MOP_CandidateTriangleBarycentrics:
  3902. case IntrinsicOp::MOP_CandidateTriangleFrontFace:
  3903. case IntrinsicOp::MOP_CandidateTriangleRayT:
  3904. case IntrinsicOp::MOP_CandidateType:
  3905. case IntrinsicOp::MOP_CandidateWorldToObject3x4:
  3906. case IntrinsicOp::MOP_CandidateWorldToObject4x3:
  3907. case IntrinsicOp::MOP_CommitNonOpaqueTriangleHit:
  3908. case IntrinsicOp::MOP_CommitProceduralPrimitiveHit:
  3909. case IntrinsicOp::MOP_CommittedGeometryIndex:
  3910. case IntrinsicOp::MOP_CommittedInstanceContributionToHitGroupIndex:
  3911. case IntrinsicOp::MOP_CommittedInstanceID:
  3912. case IntrinsicOp::MOP_CommittedInstanceIndex:
  3913. case IntrinsicOp::MOP_CommittedObjectRayDirection:
  3914. case IntrinsicOp::MOP_CommittedObjectRayOrigin:
  3915. case IntrinsicOp::MOP_CommittedObjectToWorld3x4:
  3916. case IntrinsicOp::MOP_CommittedObjectToWorld4x3:
  3917. case IntrinsicOp::MOP_CommittedPrimitiveIndex:
  3918. case IntrinsicOp::MOP_CommittedRayT:
  3919. case IntrinsicOp::MOP_CommittedStatus:
  3920. case IntrinsicOp::MOP_CommittedTriangleBarycentrics:
  3921. case IntrinsicOp::MOP_CommittedTriangleFrontFace:
  3922. case IntrinsicOp::MOP_CommittedWorldToObject3x4:
  3923. case IntrinsicOp::MOP_CommittedWorldToObject4x3:
  3924. case IntrinsicOp::MOP_Proceed:
  3925. case IntrinsicOp::MOP_RayFlags:
  3926. case IntrinsicOp::MOP_RayTMin:
  3927. case IntrinsicOp::MOP_WorldRayDirection:
  3928. case IntrinsicOp::MOP_WorldRayOrigin:
  3929. return processRayQueryIntrinsics(expr, opcode);
  3930. default:
  3931. emitError("intrinsic '%0' method unimplemented",
  3932. expr->getCallee()->getExprLoc())
  3933. << expr->getDirectCallee()->getName();
  3934. return nullptr;
  3935. }
  3936. if (retVal)
  3937. retVal->setRValue();
  3938. return retVal;
  3939. }
  3940. SpirvInstruction *SpirvEmitter::createImageSample(
  3941. QualType retType, QualType imageType, SpirvInstruction *image,
  3942. SpirvInstruction *sampler, SpirvInstruction *coordinate,
  3943. SpirvInstruction *compareVal, SpirvInstruction *bias, SpirvInstruction *lod,
  3944. std::pair<SpirvInstruction *, SpirvInstruction *> grad,
  3945. SpirvInstruction *constOffset, SpirvInstruction *varOffset,
  3946. SpirvInstruction *constOffsets, SpirvInstruction *sample,
  3947. SpirvInstruction *minLod, SpirvInstruction *residencyCodeId,
  3948. SourceLocation loc) {
  3949. // SampleDref* instructions in SPIR-V always return a scalar.
  3950. // They also have the correct type in HLSL.
  3951. if (compareVal) {
  3952. return spvBuilder.createImageSample(retType, imageType, image, sampler,
  3953. coordinate, compareVal, bias, lod, grad,
  3954. constOffset, varOffset, constOffsets,
  3955. sample, minLod, residencyCodeId, loc);
  3956. }
  3957. // Non-Dref Sample instructions in SPIR-V must always return a vec4.
  3958. auto texelType = retType;
  3959. QualType elemType = {};
  3960. uint32_t retVecSize = 0;
  3961. if (isVectorType(retType, &elemType, &retVecSize) && retVecSize != 4) {
  3962. texelType = astContext.getExtVectorType(elemType, 4);
  3963. } else if (isScalarType(retType)) {
  3964. retVecSize = 1;
  3965. elemType = retType;
  3966. texelType = astContext.getExtVectorType(retType, 4);
  3967. }
  3968. // The Lod and Grad image operands requires explicit-lod instructions.
  3969. // Otherwise we use implicit-lod instructions.
  3970. const bool isExplicit = lod || (grad.first && grad.second);
  3971. // Implicit-lod instructions are only allowed in pixel shader.
  3972. if (!spvContext.isPS() && !isExplicit)
  3973. emitError("sampling with implicit lod is only allowed in fragment shaders",
  3974. loc);
  3975. auto *retVal = spvBuilder.createImageSample(
  3976. texelType, imageType, image, sampler, coordinate, compareVal, bias, lod,
  3977. grad, constOffset, varOffset, constOffsets, sample, minLod,
  3978. residencyCodeId, loc);
  3979. // Extract smaller vector from the vec4 result if necessary.
  3980. if (texelType != retType) {
  3981. retVal = extractVecFromVec4(retVal, retVecSize, elemType, loc);
  3982. }
  3983. return retVal;
  3984. }
  3985. SpirvInstruction *
  3986. SpirvEmitter::processTextureSampleGather(const CXXMemberCallExpr *expr,
  3987. const bool isSample) {
  3988. // Signatures:
  3989. // For Texture1D, Texture1DArray, Texture2D, Texture2DArray, Texture3D:
  3990. // DXGI_FORMAT Object.Sample(sampler_state S,
  3991. // float Location
  3992. // [, int Offset]
  3993. // [, float Clamp]
  3994. // [, out uint Status]);
  3995. //
  3996. // For TextureCube and TextureCubeArray:
  3997. // DXGI_FORMAT Object.Sample(sampler_state S,
  3998. // float Location
  3999. // [, float Clamp]
  4000. // [, out uint Status]);
  4001. //
  4002. // For Texture2D/Texture2DArray:
  4003. // <Template Type>4 Object.Gather(sampler_state S,
  4004. // float2|3|4 Location,
  4005. // int2 Offset
  4006. // [, uint Status]);
  4007. //
  4008. // For TextureCube/TextureCubeArray:
  4009. // <Template Type>4 Object.Gather(sampler_state S,
  4010. // float2|3|4 Location
  4011. // [, uint Status]);
  4012. //
  4013. // Other Texture types do not have a Gather method.
  4014. const auto numArgs = expr->getNumArgs();
  4015. const auto loc = expr->getExprLoc();
  4016. const bool hasStatusArg =
  4017. expr->getArg(numArgs - 1)->getType()->isUnsignedIntegerType();
  4018. SpirvInstruction *clamp = nullptr;
  4019. if (numArgs > 2 && expr->getArg(2)->getType()->isFloatingType())
  4020. clamp = doExpr(expr->getArg(2));
  4021. else if (numArgs > 3 && expr->getArg(3)->getType()->isFloatingType())
  4022. clamp = doExpr(expr->getArg(3));
  4023. const bool hasClampArg = (clamp != 0);
  4024. const auto status =
  4025. hasStatusArg ? doExpr(expr->getArg(numArgs - 1)) : nullptr;
  4026. // Subtract 1 for status (if it exists), subtract 1 for clamp (if it exists),
  4027. // and subtract 2 for sampler_state and location.
  4028. const bool hasOffsetArg = numArgs - hasStatusArg - hasClampArg - 2 > 0;
  4029. const auto *imageExpr = expr->getImplicitObjectArgument();
  4030. const QualType imageType = imageExpr->getType();
  4031. auto *image = loadIfGLValue(imageExpr);
  4032. auto *sampler = doExpr(expr->getArg(0));
  4033. auto *coordinate = doExpr(expr->getArg(1));
  4034. // .Sample()/.Gather() may have a third optional paramter for offset.
  4035. SpirvInstruction *constOffset = nullptr, *varOffset = nullptr;
  4036. if (hasOffsetArg)
  4037. handleOffsetInMethodCall(expr, 2, &constOffset, &varOffset);
  4038. const auto retType = expr->getDirectCallee()->getReturnType();
  4039. if (isSample) {
  4040. return createImageSample(retType, imageType, image, sampler, coordinate,
  4041. /*compareVal*/ nullptr, /*bias*/ nullptr,
  4042. /*lod*/ nullptr, std::make_pair(nullptr, nullptr),
  4043. constOffset, varOffset,
  4044. /*constOffsets*/ nullptr, /*sampleNumber*/ nullptr,
  4045. /*minLod*/ clamp, status,
  4046. expr->getCallee()->getLocStart());
  4047. } else {
  4048. return spvBuilder.createImageGather(
  4049. retType, imageType, image, sampler, coordinate,
  4050. // .Gather() doc says we return four components of red data.
  4051. spvBuilder.getConstantInt(astContext.IntTy, llvm::APInt(32, 0)),
  4052. /*compareVal*/ nullptr, constOffset, varOffset,
  4053. /*constOffsets*/ nullptr, /*sampleNumber*/ nullptr, status, loc);
  4054. }
  4055. }
  4056. SpirvInstruction *
  4057. SpirvEmitter::processTextureSampleBiasLevel(const CXXMemberCallExpr *expr,
  4058. const bool isBias) {
  4059. // Signatures:
  4060. // For Texture1D, Texture1DArray, Texture2D, Texture2DArray, and Texture3D:
  4061. // DXGI_FORMAT Object.SampleBias(sampler_state S,
  4062. // float Location,
  4063. // float Bias
  4064. // [, int Offset]
  4065. // [, float clamp]
  4066. // [, out uint Status]);
  4067. //
  4068. // For TextureCube and TextureCubeArray:
  4069. // DXGI_FORMAT Object.SampleBias(sampler_state S,
  4070. // float Location,
  4071. // float Bias
  4072. // [, float clamp]
  4073. // [, out uint Status]);
  4074. //
  4075. // For Texture1D, Texture1DArray, Texture2D, Texture2DArray, and Texture3D:
  4076. // DXGI_FORMAT Object.SampleLevel(sampler_state S,
  4077. // float Location,
  4078. // float LOD
  4079. // [, int Offset]
  4080. // [, out uint Status]);
  4081. //
  4082. // For TextureCube and TextureCubeArray:
  4083. // DXGI_FORMAT Object.SampleLevel(sampler_state S,
  4084. // float Location,
  4085. // float LOD
  4086. // [, out uint Status]);
  4087. const auto numArgs = expr->getNumArgs();
  4088. const bool hasStatusArg =
  4089. expr->getArg(numArgs - 1)->getType()->isUnsignedIntegerType();
  4090. auto *status = hasStatusArg ? doExpr(expr->getArg(numArgs - 1)) : nullptr;
  4091. SpirvInstruction *clamp = nullptr;
  4092. // The .SampleLevel() methods do not take the clamp argument.
  4093. if (isBias) {
  4094. if (numArgs > 3 && expr->getArg(3)->getType()->isFloatingType())
  4095. clamp = doExpr(expr->getArg(3));
  4096. else if (numArgs > 4 && expr->getArg(4)->getType()->isFloatingType())
  4097. clamp = doExpr(expr->getArg(4));
  4098. }
  4099. const bool hasClampArg = clamp != nullptr;
  4100. // Subtract 1 for clamp (if it exists), 1 for status (if it exists),
  4101. // and 3 for sampler_state, location, and Bias/LOD.
  4102. const bool hasOffsetArg = numArgs - hasClampArg - hasStatusArg - 3 > 0;
  4103. const auto *imageExpr = expr->getImplicitObjectArgument();
  4104. const QualType imageType = imageExpr->getType();
  4105. auto *image = loadIfGLValue(imageExpr);
  4106. auto *sampler = doExpr(expr->getArg(0));
  4107. auto *coordinate = doExpr(expr->getArg(1));
  4108. SpirvInstruction *lod = nullptr;
  4109. SpirvInstruction *bias = nullptr;
  4110. if (isBias) {
  4111. bias = doExpr(expr->getArg(2));
  4112. } else {
  4113. lod = doExpr(expr->getArg(2));
  4114. }
  4115. // If offset is present in .Bias()/.SampleLevel(), it is the fourth argument.
  4116. SpirvInstruction *constOffset = nullptr, *varOffset = nullptr;
  4117. if (hasOffsetArg)
  4118. handleOffsetInMethodCall(expr, 3, &constOffset, &varOffset);
  4119. const auto retType = expr->getDirectCallee()->getReturnType();
  4120. return createImageSample(
  4121. retType, imageType, image, sampler, coordinate,
  4122. /*compareVal*/ nullptr, bias, lod, std::make_pair(nullptr, nullptr),
  4123. constOffset, varOffset,
  4124. /*constOffsets*/ nullptr, /*sampleNumber*/ nullptr,
  4125. /*minLod*/ clamp, status, expr->getCallee()->getLocStart());
  4126. }
  4127. SpirvInstruction *
  4128. SpirvEmitter::processTextureSampleGrad(const CXXMemberCallExpr *expr) {
  4129. // Signature:
  4130. // For Texture1D, Texture1DArray, Texture2D, Texture2DArray, and Texture3D:
  4131. // DXGI_FORMAT Object.SampleGrad(sampler_state S,
  4132. // float Location,
  4133. // float DDX,
  4134. // float DDY
  4135. // [, int Offset]
  4136. // [, float Clamp]
  4137. // [, out uint Status]);
  4138. //
  4139. // For TextureCube and TextureCubeArray:
  4140. // DXGI_FORMAT Object.SampleGrad(sampler_state S,
  4141. // float Location,
  4142. // float DDX,
  4143. // float DDY
  4144. // [, float Clamp]
  4145. // [, out uint Status]);
  4146. const auto numArgs = expr->getNumArgs();
  4147. const bool hasStatusArg =
  4148. expr->getArg(numArgs - 1)->getType()->isUnsignedIntegerType();
  4149. auto *status = hasStatusArg ? doExpr(expr->getArg(numArgs - 1)) : nullptr;
  4150. SpirvInstruction *clamp = nullptr;
  4151. if (numArgs > 4 && expr->getArg(4)->getType()->isFloatingType())
  4152. clamp = doExpr(expr->getArg(4));
  4153. else if (numArgs > 5 && expr->getArg(5)->getType()->isFloatingType())
  4154. clamp = doExpr(expr->getArg(5));
  4155. const bool hasClampArg = clamp != nullptr;
  4156. // Subtract 1 for clamp (if it exists), 1 for status (if it exists),
  4157. // and 4 for sampler_state, location, DDX, and DDY;
  4158. const bool hasOffsetArg = numArgs - hasClampArg - hasStatusArg - 4 > 0;
  4159. const auto *imageExpr = expr->getImplicitObjectArgument();
  4160. const QualType imageType = imageExpr->getType();
  4161. auto *image = loadIfGLValue(imageExpr);
  4162. auto *sampler = doExpr(expr->getArg(0));
  4163. auto *coordinate = doExpr(expr->getArg(1));
  4164. auto *ddx = doExpr(expr->getArg(2));
  4165. auto *ddy = doExpr(expr->getArg(3));
  4166. // If offset is present in .SampleGrad(), it is the fifth argument.
  4167. SpirvInstruction *constOffset = nullptr, *varOffset = nullptr;
  4168. if (hasOffsetArg)
  4169. handleOffsetInMethodCall(expr, 4, &constOffset, &varOffset);
  4170. const auto retType = expr->getDirectCallee()->getReturnType();
  4171. return createImageSample(
  4172. retType, imageType, image, sampler, coordinate,
  4173. /*compareVal*/ nullptr, /*bias*/ nullptr,
  4174. /*lod*/ nullptr, std::make_pair(ddx, ddy), constOffset, varOffset,
  4175. /*constOffsets*/ nullptr, /*sampleNumber*/ nullptr,
  4176. /*minLod*/ clamp, status, expr->getCallee()->getLocStart());
  4177. }
  4178. SpirvInstruction *
  4179. SpirvEmitter::processTextureSampleCmpCmpLevelZero(const CXXMemberCallExpr *expr,
  4180. const bool isCmp) {
  4181. // .SampleCmp() Signature:
  4182. //
  4183. // For Texture1D, Texture1DArray, Texture2D, Texture2DArray:
  4184. // float Object.SampleCmp(
  4185. // SamplerComparisonState S,
  4186. // float Location,
  4187. // float CompareValue
  4188. // [, int Offset]
  4189. // [, float Clamp]
  4190. // [, out uint Status]
  4191. // );
  4192. //
  4193. // For TextureCube and TextureCubeArray:
  4194. // float Object.SampleCmp(
  4195. // SamplerComparisonState S,
  4196. // float Location,
  4197. // float CompareValue
  4198. // [, float Clamp]
  4199. // [, out uint Status]
  4200. // );
  4201. //
  4202. // .SampleCmpLevelZero() is identical to .SampleCmp() on mipmap level 0 only.
  4203. // It never takes a clamp argument, which is good because lod and clamp may
  4204. // not be used together.
  4205. //
  4206. // .SampleCmpLevelZero() Signature:
  4207. //
  4208. // For Texture1D, Texture1DArray, Texture2D, Texture2DArray:
  4209. // float Object.SampleCmpLevelZero(
  4210. // SamplerComparisonState S,
  4211. // float Location,
  4212. // float CompareValue
  4213. // [, int Offset]
  4214. // [, out uint Status]
  4215. // );
  4216. //
  4217. // For TextureCube and TextureCubeArray:
  4218. // float Object.SampleCmpLevelZero(
  4219. // SamplerComparisonState S,
  4220. // float Location,
  4221. // float CompareValue
  4222. // [, out uint Status]
  4223. // );
  4224. const auto numArgs = expr->getNumArgs();
  4225. const bool hasStatusArg =
  4226. expr->getArg(numArgs - 1)->getType()->isUnsignedIntegerType();
  4227. auto *status = hasStatusArg ? doExpr(expr->getArg(numArgs - 1)) : nullptr;
  4228. SpirvInstruction *clamp = nullptr;
  4229. // The .SampleCmpLevelZero() methods do not take the clamp argument.
  4230. if (isCmp) {
  4231. if (numArgs > 3 && expr->getArg(3)->getType()->isFloatingType())
  4232. clamp = doExpr(expr->getArg(3));
  4233. else if (numArgs > 4 && expr->getArg(4)->getType()->isFloatingType())
  4234. clamp = doExpr(expr->getArg(4));
  4235. }
  4236. const bool hasClampArg = clamp != nullptr;
  4237. // Subtract 1 for clamp (if it exists), 1 for status (if it exists),
  4238. // and 3 for sampler_state, location, and compare_value.
  4239. const bool hasOffsetArg = numArgs - hasClampArg - hasStatusArg - 3 > 0;
  4240. const auto *imageExpr = expr->getImplicitObjectArgument();
  4241. auto *image = loadIfGLValue(imageExpr);
  4242. auto *sampler = doExpr(expr->getArg(0));
  4243. auto *coordinate = doExpr(expr->getArg(1));
  4244. auto *compareVal = doExpr(expr->getArg(2));
  4245. // If offset is present in .SampleCmp(), it will be the fourth argument.
  4246. SpirvInstruction *constOffset = nullptr, *varOffset = nullptr;
  4247. if (hasOffsetArg)
  4248. handleOffsetInMethodCall(expr, 3, &constOffset, &varOffset);
  4249. auto *lod = isCmp ? nullptr
  4250. : spvBuilder.getConstantFloat(astContext.FloatTy,
  4251. llvm::APFloat(0.0f));
  4252. const auto retType = expr->getDirectCallee()->getReturnType();
  4253. const auto imageType = imageExpr->getType();
  4254. return createImageSample(
  4255. retType, imageType, image, sampler, coordinate, compareVal,
  4256. /*bias*/ nullptr, lod, std::make_pair(nullptr, nullptr), constOffset,
  4257. varOffset,
  4258. /*constOffsets*/ nullptr, /*sampleNumber*/ nullptr, /*minLod*/ clamp,
  4259. status, expr->getCallee()->getLocStart());
  4260. }
  4261. SpirvInstruction *
  4262. SpirvEmitter::processBufferTextureLoad(const CXXMemberCallExpr *expr) {
  4263. // Signature:
  4264. // For Texture1D, Texture1DArray, Texture2D, Texture2DArray, Texture3D:
  4265. // ret Object.Load(int Location
  4266. // [, int Offset]
  4267. // [, uint status]);
  4268. //
  4269. // For Texture2DMS and Texture2DMSArray, there is one additional argument:
  4270. // ret Object.Load(int Location
  4271. // [, int SampleIndex]
  4272. // [, int Offset]
  4273. // [, uint status]);
  4274. //
  4275. // For (RW)Buffer, RWTexture1D, RWTexture1DArray, RWTexture2D,
  4276. // RWTexture2DArray, RWTexture3D:
  4277. // ret Object.Load (int Location
  4278. // [, uint status]);
  4279. //
  4280. // Note: (RW)ByteAddressBuffer and (RW)StructuredBuffer types also have Load
  4281. // methods that take an additional Status argument. However, since these types
  4282. // are not represented as OpTypeImage in SPIR-V, we don't have a way of
  4283. // figuring out the Residency Code for them. Therefore having the Status
  4284. // argument for these types is not supported.
  4285. //
  4286. // For (RW)ByteAddressBuffer:
  4287. // ret Object.{Load,Load2,Load3,Load4} (int Location
  4288. // [, uint status]);
  4289. //
  4290. // For (RW)StructuredBuffer:
  4291. // ret Object.Load (int Location
  4292. // [, uint status]);
  4293. //
  4294. const auto *object = expr->getImplicitObjectArgument();
  4295. const auto objectType = object->getType();
  4296. if (isRWByteAddressBuffer(objectType) || isByteAddressBuffer(objectType))
  4297. return processByteAddressBufferLoadStore(expr, 1, /*doStore*/ false);
  4298. if (isStructuredBuffer(objectType))
  4299. return processStructuredBufferLoad(expr);
  4300. const auto numArgs = expr->getNumArgs();
  4301. const auto *locationArg = expr->getArg(0);
  4302. const bool textureMS = isTextureMS(objectType);
  4303. const bool hasStatusArg =
  4304. expr->getArg(numArgs - 1)->getType()->isUnsignedIntegerType();
  4305. auto *status = hasStatusArg ? doExpr(expr->getArg(numArgs - 1)) : nullptr;
  4306. auto loc = expr->getExprLoc();
  4307. if (isBuffer(objectType) || isRWBuffer(objectType) || isRWTexture(objectType))
  4308. return processBufferTextureLoad(object, doExpr(locationArg),
  4309. /*constOffset*/ nullptr,
  4310. /*varOffset*/ nullptr, /*lod*/ nullptr,
  4311. /*residencyCode*/ status, loc);
  4312. // Subtract 1 for status (if it exists), and 1 for sampleIndex (if it exists),
  4313. // and 1 for location.
  4314. const bool hasOffsetArg = numArgs - hasStatusArg - textureMS - 1 > 0;
  4315. if (isTexture(objectType)) {
  4316. // .Load() has a second optional paramter for offset.
  4317. SpirvInstruction *location = doExpr(locationArg);
  4318. SpirvInstruction *constOffset = nullptr, *varOffset = nullptr;
  4319. SpirvInstruction *coordinate = location, *lod = nullptr;
  4320. if (textureMS) {
  4321. // SampleIndex is only available when the Object is of Texture2DMS or
  4322. // Texture2DMSArray types. Under those cases, Offset will be the third
  4323. // parameter (index 2).
  4324. lod = doExpr(expr->getArg(1));
  4325. if (hasOffsetArg)
  4326. handleOffsetInMethodCall(expr, 2, &constOffset, &varOffset);
  4327. } else {
  4328. // For Texture Load() functions, the location parameter is a vector
  4329. // that consists of both the coordinate and the mipmap level (via the
  4330. // last vector element). We need to split it here since the
  4331. // OpImageFetch SPIR-V instruction encodes them as separate arguments.
  4332. splitVecLastElement(locationArg->getType(), location, &coordinate, &lod,
  4333. locationArg->getExprLoc());
  4334. // For textures other than Texture2DMS(Array), offset should be the
  4335. // second parameter (index 1).
  4336. if (hasOffsetArg)
  4337. handleOffsetInMethodCall(expr, 1, &constOffset, &varOffset);
  4338. }
  4339. return processBufferTextureLoad(object, coordinate, constOffset, varOffset,
  4340. lod, status, loc);
  4341. }
  4342. emitError("Load() of the given object type unimplemented",
  4343. object->getExprLoc());
  4344. return nullptr;
  4345. }
  4346. SpirvInstruction *
  4347. SpirvEmitter::processGetDimensions(const CXXMemberCallExpr *expr) {
  4348. const auto objectType = expr->getImplicitObjectArgument()->getType();
  4349. if (isTexture(objectType) || isRWTexture(objectType) ||
  4350. isBuffer(objectType) || isRWBuffer(objectType)) {
  4351. return processBufferTextureGetDimensions(expr);
  4352. } else if (isByteAddressBuffer(objectType) ||
  4353. isRWByteAddressBuffer(objectType) ||
  4354. isStructuredBuffer(objectType) ||
  4355. isAppendStructuredBuffer(objectType) ||
  4356. isConsumeStructuredBuffer(objectType)) {
  4357. return processByteAddressBufferStructuredBufferGetDimensions(expr);
  4358. } else {
  4359. emitError("GetDimensions() of the given object type unimplemented",
  4360. expr->getExprLoc());
  4361. return nullptr;
  4362. }
  4363. }
  4364. SpirvInstruction *
  4365. SpirvEmitter::doCXXOperatorCallExpr(const CXXOperatorCallExpr *expr) {
  4366. { // Handle Buffer/RWBuffer/Texture/RWTexture indexing
  4367. const Expr *baseExpr = nullptr;
  4368. const Expr *indexExpr = nullptr;
  4369. const Expr *lodExpr = nullptr;
  4370. // For Textures, regular indexing (operator[]) uses slice 0.
  4371. if (isBufferTextureIndexing(expr, &baseExpr, &indexExpr)) {
  4372. auto *lod = isTexture(baseExpr->getType())
  4373. ? spvBuilder.getConstantInt(astContext.UnsignedIntTy,
  4374. llvm::APInt(32, 0))
  4375. : nullptr;
  4376. return processBufferTextureLoad(baseExpr, doExpr(indexExpr),
  4377. /*constOffset*/ nullptr,
  4378. /*varOffset*/ nullptr, lod,
  4379. /*residencyCode*/ nullptr,
  4380. expr->getExprLoc());
  4381. }
  4382. // .mips[][] or .sample[][] must use the correct slice.
  4383. if (isTextureMipsSampleIndexing(expr, &baseExpr, &indexExpr, &lodExpr)) {
  4384. auto *lod = doExpr(lodExpr);
  4385. return processBufferTextureLoad(baseExpr, doExpr(indexExpr),
  4386. /*constOffset*/ nullptr,
  4387. /*varOffset*/ nullptr, lod,
  4388. /*residencyCode*/ nullptr,
  4389. expr->getExprLoc());
  4390. }
  4391. }
  4392. llvm::SmallVector<SpirvInstruction *, 4> indices;
  4393. const Expr *baseExpr = collectArrayStructIndices(
  4394. expr, /*rawIndex*/ false, /*rawIndices*/ nullptr, &indices);
  4395. auto base = loadIfAliasVarRef(baseExpr);
  4396. if (indices.empty())
  4397. return base; // For indexing into size-1 vectors and 1xN matrices
  4398. // If we are indexing into a rvalue, to use OpAccessChain, we first need
  4399. // to create a local variable to hold the rvalue.
  4400. //
  4401. // TODO: We can optimize the codegen by emitting OpCompositeExtract if
  4402. // all indices are contant integers.
  4403. if (base->isRValue()) {
  4404. base = createTemporaryVar(baseExpr->getType(), "vector", base,
  4405. baseExpr->getExprLoc());
  4406. }
  4407. return turnIntoElementPtr(baseExpr->getType(), base, expr->getType(), indices,
  4408. baseExpr->getExprLoc());
  4409. }
  4410. SpirvInstruction *
  4411. SpirvEmitter::doExtMatrixElementExpr(const ExtMatrixElementExpr *expr) {
  4412. const Expr *baseExpr = expr->getBase();
  4413. auto *baseInfo = doExpr(baseExpr);
  4414. const auto layoutRule = baseInfo->getLayoutRule();
  4415. const auto elemType = hlsl::GetHLSLMatElementType(baseExpr->getType());
  4416. const auto accessor = expr->getEncodedElementAccess();
  4417. uint32_t rowCount = 0, colCount = 0;
  4418. hlsl::GetHLSLMatRowColCount(baseExpr->getType(), rowCount, colCount);
  4419. // Construct a temporary vector out of all elements accessed:
  4420. // 1. Create access chain for each element using OpAccessChain
  4421. // 2. Load each element using OpLoad
  4422. // 3. Create the vector using OpCompositeConstruct
  4423. llvm::SmallVector<SpirvInstruction *, 4> elements;
  4424. for (uint32_t i = 0; i < accessor.Count; ++i) {
  4425. uint32_t row = 0, col = 0;
  4426. SpirvInstruction *elem = nullptr;
  4427. accessor.GetPosition(i, &row, &col);
  4428. llvm::SmallVector<uint32_t, 2> indices;
  4429. // If the matrix only has one row/column, we are indexing into a vector
  4430. // then. Only one index is needed for such cases.
  4431. if (rowCount > 1)
  4432. indices.push_back(row);
  4433. if (colCount > 1)
  4434. indices.push_back(col);
  4435. if (!baseInfo->isRValue()) {
  4436. llvm::SmallVector<SpirvInstruction *, 2> indexInstructions(indices.size(),
  4437. nullptr);
  4438. for (uint32_t i = 0; i < indices.size(); ++i)
  4439. indexInstructions[i] = spvBuilder.getConstantInt(
  4440. astContext.IntTy, llvm::APInt(32, indices[i], true));
  4441. if (!indices.empty()) {
  4442. assert(!baseInfo->isRValue());
  4443. // Load the element via access chain
  4444. elem = spvBuilder.createAccessChain(
  4445. elemType, baseInfo, indexInstructions, baseExpr->getLocStart());
  4446. } else {
  4447. // The matrix is of size 1x1. No need to use access chain, base should
  4448. // be the source pointer.
  4449. elem = baseInfo;
  4450. }
  4451. elem = spvBuilder.createLoad(elemType, elem, baseExpr->getLocStart());
  4452. } else { // e.g., (mat1 + mat2)._m11
  4453. elem = spvBuilder.createCompositeExtract(elemType, baseInfo, indices,
  4454. baseExpr->getLocStart());
  4455. }
  4456. elements.push_back(elem);
  4457. }
  4458. const auto size = elements.size();
  4459. auto *value = elements.front();
  4460. if (size > 1) {
  4461. value = spvBuilder.createCompositeConstruct(
  4462. astContext.getExtVectorType(elemType, size), elements,
  4463. expr->getLocStart());
  4464. }
  4465. // Note: Special-case: Booleans have no physical layout, and therefore when
  4466. // layout is required booleans are represented as unsigned integers.
  4467. // Therefore, after loading the uint we should convert it boolean.
  4468. if (elemType->isBooleanType() && layoutRule != SpirvLayoutRule::Void) {
  4469. const auto fromType =
  4470. size == 1 ? astContext.UnsignedIntTy
  4471. : astContext.getExtVectorType(astContext.UnsignedIntTy, size);
  4472. const auto toType =
  4473. size == 1 ? astContext.BoolTy
  4474. : astContext.getExtVectorType(astContext.BoolTy, size);
  4475. value = castToBool(value, fromType, toType, expr->getLocStart());
  4476. }
  4477. value->setRValue();
  4478. return value;
  4479. }
  4480. SpirvInstruction *
  4481. SpirvEmitter::doHLSLVectorElementExpr(const HLSLVectorElementExpr *expr) {
  4482. const Expr *baseExpr = nullptr;
  4483. hlsl::VectorMemberAccessPositions accessor;
  4484. condenseVectorElementExpr(expr, &baseExpr, &accessor);
  4485. const QualType baseType = baseExpr->getType();
  4486. assert(hlsl::IsHLSLVecType(baseType));
  4487. const auto baseSize = hlsl::GetHLSLVecSize(baseType);
  4488. const auto accessorSize = static_cast<size_t>(accessor.Count);
  4489. // Depending on the number of elements selected, we emit different
  4490. // instructions.
  4491. // For vectors of size greater than 1, if we are only selecting one element,
  4492. // typical access chain or composite extraction should be fine. But if we
  4493. // are selecting more than one elements, we must resolve to vector specific
  4494. // operations.
  4495. // For size-1 vectors, if we are selecting their single elements multiple
  4496. // times, we need composite construct instructions.
  4497. if (accessorSize == 1) {
  4498. auto *baseInfo = doExpr(baseExpr);
  4499. if (!baseInfo || baseSize == 1) {
  4500. // Selecting one element from a size-1 vector. The underlying vector is
  4501. // already treated as a scalar.
  4502. return baseInfo;
  4503. }
  4504. // If the base is an lvalue, we should emit an access chain instruction
  4505. // so that we can load/store the specified element. For rvalue base,
  4506. // we should use composite extraction. We should check the immediate base
  4507. // instead of the original base here since we can have something like
  4508. // v.xyyz to turn a lvalue v into rvalue.
  4509. const auto type = expr->getType();
  4510. if (!baseInfo->isRValue()) { // E.g., v.x;
  4511. auto *index = spvBuilder.getConstantInt(
  4512. astContext.IntTy, llvm::APInt(32, accessor.Swz0, true));
  4513. // We need a lvalue here. Do not try to load.
  4514. return spvBuilder.createAccessChain(type, baseInfo, {index},
  4515. baseExpr->getLocStart());
  4516. } else { // E.g., (v + w).x;
  4517. // The original base vector may not be a rvalue. Need to load it if
  4518. // it is lvalue since ImplicitCastExpr (LValueToRValue) will be missing
  4519. // for that case.
  4520. SpirvInstruction *result = spvBuilder.createCompositeExtract(
  4521. type, baseInfo, {accessor.Swz0}, baseExpr->getLocStart());
  4522. // Special-case: Booleans in SPIR-V do not have a physical layout. Uint is
  4523. // used to represent them when layout is required.
  4524. if (expr->getType()->isBooleanType() &&
  4525. baseInfo->getLayoutRule() != SpirvLayoutRule::Void)
  4526. result = castToBool(result, astContext.UnsignedIntTy, astContext.BoolTy,
  4527. expr->getLocStart());
  4528. return result;
  4529. }
  4530. }
  4531. if (baseSize == 1) {
  4532. // Selecting more than one element from a size-1 vector, for example,
  4533. // <scalar>.xx. Construct the vector.
  4534. auto *info = loadIfGLValue(baseExpr);
  4535. const auto type = expr->getType();
  4536. llvm::SmallVector<SpirvInstruction *, 4> components(accessorSize, info);
  4537. info = spvBuilder.createCompositeConstruct(type, components,
  4538. expr->getLocStart());
  4539. info->setRValue();
  4540. return info;
  4541. }
  4542. llvm::SmallVector<uint32_t, 4> selectors;
  4543. selectors.resize(accessorSize);
  4544. // Whether we are selecting elements in the original order
  4545. bool originalOrder = baseSize == accessorSize;
  4546. for (uint32_t i = 0; i < accessorSize; ++i) {
  4547. accessor.GetPosition(i, &selectors[i]);
  4548. // We can select more elements than the vector provides. This handles
  4549. // that case too.
  4550. originalOrder &= selectors[i] == i;
  4551. }
  4552. if (originalOrder)
  4553. return doExpr(baseExpr);
  4554. auto *info = loadIfGLValue(baseExpr);
  4555. // Use base for both vectors. But we are only selecting values from the
  4556. // first one.
  4557. return spvBuilder.createVectorShuffle(expr->getType(), info, info, selectors,
  4558. expr->getLocStart());
  4559. }
  4560. SpirvInstruction *SpirvEmitter::doInitListExpr(const InitListExpr *expr) {
  4561. if (auto *id = tryToEvaluateAsConst(expr)) {
  4562. id->setRValue();
  4563. return id;
  4564. }
  4565. auto *result = InitListHandler(astContext, *this).processInit(expr);
  4566. result->setRValue();
  4567. return result;
  4568. }
  4569. SpirvInstruction *SpirvEmitter::doMemberExpr(const MemberExpr *expr) {
  4570. llvm::SmallVector<SpirvInstruction *, 4> indices;
  4571. const Expr *base = collectArrayStructIndices(
  4572. expr, /*rawIndex*/ false, /*rawIndices*/ nullptr, &indices);
  4573. auto *instr = loadIfAliasVarRef(base);
  4574. if (instr && !indices.empty()) {
  4575. instr = turnIntoElementPtr(base->getType(), instr, expr->getType(), indices,
  4576. base->getExprLoc());
  4577. }
  4578. return instr;
  4579. }
  4580. SpirvVariable *SpirvEmitter::createTemporaryVar(QualType type,
  4581. llvm::StringRef name,
  4582. SpirvInstruction *init,
  4583. SourceLocation loc) {
  4584. // We are creating a temporary variable in the Function storage class here,
  4585. // which means it has void layout rule.
  4586. const std::string varName = "temp.var." + name.str();
  4587. auto *var = spvBuilder.addFnVar(type, loc, varName);
  4588. storeValue(var, init, type, loc);
  4589. return var;
  4590. }
  4591. SpirvInstruction *SpirvEmitter::doUnaryOperator(const UnaryOperator *expr) {
  4592. const auto opcode = expr->getOpcode();
  4593. const auto *subExpr = expr->getSubExpr();
  4594. const auto subType = subExpr->getType();
  4595. auto *subValue = doExpr(subExpr);
  4596. switch (opcode) {
  4597. case UO_PreInc:
  4598. case UO_PreDec:
  4599. case UO_PostInc:
  4600. case UO_PostDec: {
  4601. const bool isPre = opcode == UO_PreInc || opcode == UO_PreDec;
  4602. const bool isInc = opcode == UO_PreInc || opcode == UO_PostInc;
  4603. const spv::Op spvOp = translateOp(isInc ? BO_Add : BO_Sub, subType);
  4604. SpirvInstruction *originValue =
  4605. subValue->isRValue()
  4606. ? subValue
  4607. : spvBuilder.createLoad(subType, subValue, subExpr->getLocStart());
  4608. auto *one = hlsl::IsHLSLMatType(subType) ? getMatElemValueOne(subType)
  4609. : getValueOne(subType);
  4610. SpirvInstruction *incValue = nullptr;
  4611. if (isMxNMatrix(subType)) {
  4612. // For matrices, we can only increment/decrement each vector of it.
  4613. const auto actOnEachVec = [this, spvOp, one,
  4614. expr](uint32_t /*index*/, QualType vecType,
  4615. SpirvInstruction *lhsVec) {
  4616. auto *val = spvBuilder.createBinaryOp(spvOp, vecType, lhsVec, one,
  4617. expr->getOperatorLoc());
  4618. val->setRValue();
  4619. return val;
  4620. };
  4621. incValue = processEachVectorInMatrix(subExpr, originValue, actOnEachVec,
  4622. expr->getLocStart());
  4623. } else {
  4624. incValue = spvBuilder.createBinaryOp(spvOp, subType, originValue, one,
  4625. expr->getOperatorLoc());
  4626. }
  4627. // If this is a RWBuffer/RWTexture assignment, OpImageWrite will be used.
  4628. // Otherwise, store using OpStore.
  4629. if (tryToAssignToRWBufferRWTexture(subExpr, incValue)) {
  4630. incValue->setRValue();
  4631. subValue = incValue;
  4632. } else {
  4633. spvBuilder.createStore(subValue, incValue, subExpr->getLocStart());
  4634. }
  4635. // Prefix increment/decrement operator returns a lvalue, while postfix
  4636. // increment/decrement returns a rvalue.
  4637. if (isPre) {
  4638. return subValue;
  4639. } else {
  4640. originValue->setRValue();
  4641. return originValue;
  4642. }
  4643. }
  4644. case UO_Not: {
  4645. subValue = spvBuilder.createUnaryOp(spv::Op::OpNot, subType, subValue,
  4646. expr->getOperatorLoc());
  4647. subValue->setRValue();
  4648. return subValue;
  4649. }
  4650. case UO_LNot: {
  4651. // Parsing will do the necessary casting to make sure we are applying the
  4652. // ! operator on boolean values.
  4653. subValue = spvBuilder.createUnaryOp(spv::Op::OpLogicalNot, subType,
  4654. subValue, expr->getOperatorLoc());
  4655. subValue->setRValue();
  4656. return subValue;
  4657. }
  4658. case UO_Plus:
  4659. // No need to do anything for the prefix + operator.
  4660. return subValue;
  4661. case UO_Minus: {
  4662. // SPIR-V have two opcodes for negating values: OpSNegate and OpFNegate.
  4663. const spv::Op spvOp = isFloatOrVecMatOfFloatType(subType)
  4664. ? spv::Op::OpFNegate
  4665. : spv::Op::OpSNegate;
  4666. if (isMxNMatrix(subType)) {
  4667. // For matrices, we can only negate each vector of it.
  4668. const auto actOnEachVec = [this, spvOp, expr](uint32_t /*index*/,
  4669. QualType vecType,
  4670. SpirvInstruction *lhsVec) {
  4671. return spvBuilder.createUnaryOp(spvOp, vecType, lhsVec,
  4672. expr->getOperatorLoc());
  4673. };
  4674. return processEachVectorInMatrix(subExpr, subValue, actOnEachVec,
  4675. expr->getLocStart());
  4676. } else {
  4677. subValue = spvBuilder.createUnaryOp(spvOp, subType, subValue,
  4678. expr->getOperatorLoc());
  4679. subValue->setRValue();
  4680. return subValue;
  4681. }
  4682. }
  4683. default:
  4684. break;
  4685. }
  4686. emitError("unary operator '%0' unimplemented", expr->getExprLoc())
  4687. << expr->getOpcodeStr(opcode);
  4688. expr->dump();
  4689. return 0;
  4690. }
  4691. spv::Op SpirvEmitter::translateOp(BinaryOperator::Opcode op, QualType type) {
  4692. const bool isSintType = isSintOrVecMatOfSintType(type);
  4693. const bool isUintType = isUintOrVecMatOfUintType(type);
  4694. const bool isFloatType = isFloatOrVecMatOfFloatType(type);
  4695. #define BIN_OP_CASE_INT_FLOAT(kind, intBinOp, floatBinOp) \
  4696. \
  4697. case BO_##kind: { \
  4698. if (isSintType || isUintType) { \
  4699. return spv::Op::Op##intBinOp; \
  4700. } \
  4701. if (isFloatType) { \
  4702. return spv::Op::Op##floatBinOp; \
  4703. } \
  4704. } break
  4705. #define BIN_OP_CASE_SINT_UINT_FLOAT(kind, sintBinOp, uintBinOp, floatBinOp) \
  4706. \
  4707. case BO_##kind: { \
  4708. if (isSintType) { \
  4709. return spv::Op::Op##sintBinOp; \
  4710. } \
  4711. if (isUintType) { \
  4712. return spv::Op::Op##uintBinOp; \
  4713. } \
  4714. if (isFloatType) { \
  4715. return spv::Op::Op##floatBinOp; \
  4716. } \
  4717. } break
  4718. #define BIN_OP_CASE_SINT_UINT(kind, sintBinOp, uintBinOp) \
  4719. \
  4720. case BO_##kind: { \
  4721. if (isSintType) { \
  4722. return spv::Op::Op##sintBinOp; \
  4723. } \
  4724. if (isUintType) { \
  4725. return spv::Op::Op##uintBinOp; \
  4726. } \
  4727. } break
  4728. switch (op) {
  4729. case BO_EQ: {
  4730. if (isBoolOrVecMatOfBoolType(type))
  4731. return spv::Op::OpLogicalEqual;
  4732. if (isSintType || isUintType)
  4733. return spv::Op::OpIEqual;
  4734. if (isFloatType)
  4735. return spv::Op::OpFOrdEqual;
  4736. } break;
  4737. case BO_NE: {
  4738. if (isBoolOrVecMatOfBoolType(type))
  4739. return spv::Op::OpLogicalNotEqual;
  4740. if (isSintType || isUintType)
  4741. return spv::Op::OpINotEqual;
  4742. if (isFloatType)
  4743. return spv::Op::OpFOrdNotEqual;
  4744. } break;
  4745. // According to HLSL doc, all sides of the && and || expression are always
  4746. // evaluated.
  4747. case BO_LAnd:
  4748. return spv::Op::OpLogicalAnd;
  4749. case BO_LOr:
  4750. return spv::Op::OpLogicalOr;
  4751. BIN_OP_CASE_INT_FLOAT(Add, IAdd, FAdd);
  4752. BIN_OP_CASE_INT_FLOAT(AddAssign, IAdd, FAdd);
  4753. BIN_OP_CASE_INT_FLOAT(Sub, ISub, FSub);
  4754. BIN_OP_CASE_INT_FLOAT(SubAssign, ISub, FSub);
  4755. BIN_OP_CASE_INT_FLOAT(Mul, IMul, FMul);
  4756. BIN_OP_CASE_INT_FLOAT(MulAssign, IMul, FMul);
  4757. BIN_OP_CASE_SINT_UINT_FLOAT(Div, SDiv, UDiv, FDiv);
  4758. BIN_OP_CASE_SINT_UINT_FLOAT(DivAssign, SDiv, UDiv, FDiv);
  4759. // According to HLSL spec, "the modulus operator returns the remainder of
  4760. // a division." "The % operator is defined only in cases where either both
  4761. // sides are positive or both sides are negative."
  4762. //
  4763. // In SPIR-V, there are two reminder operations: Op*Rem and Op*Mod. With
  4764. // the former, the sign of a non-0 result comes from Operand 1, while
  4765. // with the latter, from Operand 2.
  4766. //
  4767. // For operands with different signs, technically we can map % to either
  4768. // Op*Rem or Op*Mod since it's undefined behavior. But it is more
  4769. // consistent with C (HLSL starts as a C derivative) and Clang frontend
  4770. // const expression evaluation if we map % to Op*Rem.
  4771. //
  4772. // Note there is no OpURem in SPIR-V.
  4773. BIN_OP_CASE_SINT_UINT_FLOAT(Rem, SRem, UMod, FRem);
  4774. BIN_OP_CASE_SINT_UINT_FLOAT(RemAssign, SRem, UMod, FRem);
  4775. BIN_OP_CASE_SINT_UINT_FLOAT(LT, SLessThan, ULessThan, FOrdLessThan);
  4776. BIN_OP_CASE_SINT_UINT_FLOAT(LE, SLessThanEqual, ULessThanEqual,
  4777. FOrdLessThanEqual);
  4778. BIN_OP_CASE_SINT_UINT_FLOAT(GT, SGreaterThan, UGreaterThan,
  4779. FOrdGreaterThan);
  4780. BIN_OP_CASE_SINT_UINT_FLOAT(GE, SGreaterThanEqual, UGreaterThanEqual,
  4781. FOrdGreaterThanEqual);
  4782. BIN_OP_CASE_SINT_UINT(And, BitwiseAnd, BitwiseAnd);
  4783. BIN_OP_CASE_SINT_UINT(AndAssign, BitwiseAnd, BitwiseAnd);
  4784. BIN_OP_CASE_SINT_UINT(Or, BitwiseOr, BitwiseOr);
  4785. BIN_OP_CASE_SINT_UINT(OrAssign, BitwiseOr, BitwiseOr);
  4786. BIN_OP_CASE_SINT_UINT(Xor, BitwiseXor, BitwiseXor);
  4787. BIN_OP_CASE_SINT_UINT(XorAssign, BitwiseXor, BitwiseXor);
  4788. BIN_OP_CASE_SINT_UINT(Shl, ShiftLeftLogical, ShiftLeftLogical);
  4789. BIN_OP_CASE_SINT_UINT(ShlAssign, ShiftLeftLogical, ShiftLeftLogical);
  4790. BIN_OP_CASE_SINT_UINT(Shr, ShiftRightArithmetic, ShiftRightLogical);
  4791. BIN_OP_CASE_SINT_UINT(ShrAssign, ShiftRightArithmetic, ShiftRightLogical);
  4792. default:
  4793. break;
  4794. }
  4795. #undef BIN_OP_CASE_INT_FLOAT
  4796. #undef BIN_OP_CASE_SINT_UINT_FLOAT
  4797. #undef BIN_OP_CASE_SINT_UINT
  4798. emitError("translating binary operator '%0' unimplemented", {})
  4799. << BinaryOperator::getOpcodeStr(op);
  4800. return spv::Op::OpNop;
  4801. }
  4802. SpirvInstruction *
  4803. SpirvEmitter::processAssignment(const Expr *lhs, SpirvInstruction *rhs,
  4804. const bool isCompoundAssignment,
  4805. SpirvInstruction *lhsPtr) {
  4806. lhs = lhs->IgnoreParenNoopCasts(astContext);
  4807. // Assigning to vector swizzling should be handled differently.
  4808. if (SpirvInstruction *result = tryToAssignToVectorElements(lhs, rhs))
  4809. return result;
  4810. // Assigning to matrix swizzling should be handled differently.
  4811. if (SpirvInstruction *result = tryToAssignToMatrixElements(lhs, rhs))
  4812. return result;
  4813. // Assigning to a RWBuffer/RWTexture should be handled differently.
  4814. if (SpirvInstruction *result = tryToAssignToRWBufferRWTexture(lhs, rhs))
  4815. return result;
  4816. // Assigning to a out attribute or indices object in mesh shader should be
  4817. // handled differently.
  4818. if (SpirvInstruction *result = tryToAssignToMSOutAttrsOrIndices(lhs, rhs))
  4819. return result;
  4820. // Assigning to a 'string' variable. SPIR-V doesn't have a string type, and we
  4821. // do not allow creating or modifying string variables. We do allow use of
  4822. // string literals using OpString.
  4823. if (isStringType(lhs->getType())) {
  4824. emitError("string variables are immutable in SPIR-V.", lhs->getExprLoc());
  4825. return nullptr;
  4826. }
  4827. // Normal assignment procedure
  4828. if (!lhsPtr)
  4829. lhsPtr = doExpr(lhs);
  4830. storeValue(lhsPtr, rhs, lhs->getType(), lhs->getLocStart());
  4831. // Plain assignment returns a rvalue, while compound assignment returns
  4832. // lvalue.
  4833. return isCompoundAssignment ? lhsPtr : rhs;
  4834. }
  4835. void SpirvEmitter::storeValue(SpirvInstruction *lhsPtr,
  4836. SpirvInstruction *rhsVal, QualType lhsValType,
  4837. SourceLocation loc) {
  4838. // Defend against nullptr source or destination so errors can bubble up to the
  4839. // user.
  4840. if (!lhsPtr || !rhsVal)
  4841. return;
  4842. if (const auto *refType = lhsValType->getAs<ReferenceType>())
  4843. lhsValType = refType->getPointeeType();
  4844. QualType matElemType = {};
  4845. const bool lhsIsMat = isMxNMatrix(lhsValType, &matElemType);
  4846. const bool lhsIsFloatMat = lhsIsMat && matElemType->isFloatingType();
  4847. const bool lhsIsNonFpMat = lhsIsMat && !matElemType->isFloatingType();
  4848. if (isScalarType(lhsValType) || isVectorType(lhsValType) || lhsIsFloatMat) {
  4849. // Special-case: According to the SPIR-V Spec: There is no physical size
  4850. // or bit pattern defined for boolean type. Therefore an unsigned integer
  4851. // is used to represent booleans when layout is required. In such cases,
  4852. // we should cast the boolean to uint before creating OpStore.
  4853. if (isBoolOrVecOfBoolType(lhsValType) &&
  4854. lhsPtr->getLayoutRule() != SpirvLayoutRule::Void) {
  4855. uint32_t vecSize = 1;
  4856. const bool isVec = isVectorType(lhsValType, nullptr, &vecSize);
  4857. const auto toType =
  4858. isVec ? astContext.getExtVectorType(astContext.UnsignedIntTy, vecSize)
  4859. : astContext.UnsignedIntTy;
  4860. const auto fromType =
  4861. isVec ? astContext.getExtVectorType(astContext.BoolTy, vecSize)
  4862. : astContext.BoolTy;
  4863. rhsVal = castToInt(rhsVal, fromType, toType, {});
  4864. }
  4865. spvBuilder.createStore(lhsPtr, rhsVal, loc);
  4866. } else if (isOpaqueType(lhsValType)) {
  4867. // Resource types are represented using RecordType in the AST.
  4868. // Handle them before the general RecordType.
  4869. //
  4870. // HLSL allows to put resource types that translating into SPIR-V opaque
  4871. // types in structs, or assign to variables of resource types. These can all
  4872. // result in illegal SPIR-V for Vulkan. We just translate here literally and
  4873. // let SPIRV-Tools opt to do the legalization work.
  4874. //
  4875. // Note: legalization specific code
  4876. if (hlsl::IsHLSLRayQueryType(lhsValType)) {
  4877. emitError("store value of type %0 is unsupported", {}) << lhsValType;
  4878. return;
  4879. }
  4880. spvBuilder.createStore(lhsPtr, rhsVal, loc);
  4881. needsLegalization = true;
  4882. } else if (isAKindOfStructuredOrByteBuffer(lhsValType)) {
  4883. // The rhs should be a pointer and the lhs should be a pointer-to-pointer.
  4884. // Directly store the pointer here and let SPIRV-Tools opt to do the clean
  4885. // up.
  4886. //
  4887. // Note: legalization specific code
  4888. spvBuilder.createStore(lhsPtr, rhsVal, loc);
  4889. needsLegalization = true;
  4890. // For ConstantBuffers/TextureBuffers, we decompose and assign each field
  4891. // recursively like normal structs using the following logic.
  4892. //
  4893. // The frontend forbids declaring ConstantBuffer<T> or TextureBuffer<T>
  4894. // variables as function parameters/returns/variables, but happily accepts
  4895. // assignments/returns from ConstantBuffer<T>/TextureBuffer<T> to function
  4896. // parameters/returns/variables of type T. And ConstantBuffer<T> is not
  4897. // represented differently as struct T.
  4898. } else if (isOpaqueArrayType(lhsValType)) {
  4899. // For opaque array types, we cannot perform OpLoad on the whole array and
  4900. // then write out as a whole; instead, we need to OpLoad each element
  4901. // using access chains. This is to influence later SPIR-V transformations
  4902. // to use access chains to access each opaque object; if we do array
  4903. // wholesale handling here, they will be in the final transformed code.
  4904. // Drivers don't like that.
  4905. // TODO: consider moving this hack into SPIRV-Tools as a transformation.
  4906. assert(!rhsVal->isRValue());
  4907. if (!lhsValType->isConstantArrayType()) {
  4908. spvBuilder.createStore(lhsPtr, rhsVal, loc);
  4909. needsLegalization = true;
  4910. return;
  4911. }
  4912. const auto *arrayType = astContext.getAsConstantArrayType(lhsValType);
  4913. const auto elemType = arrayType->getElementType();
  4914. const auto arraySize =
  4915. static_cast<uint32_t>(arrayType->getSize().getZExtValue());
  4916. // Do separate load of each element via access chain
  4917. llvm::SmallVector<SpirvInstruction *, 8> elements;
  4918. for (uint32_t i = 0; i < arraySize; ++i) {
  4919. auto *subRhsPtr = spvBuilder.createAccessChain(
  4920. elemType, rhsVal,
  4921. {spvBuilder.getConstantInt(astContext.IntTy,
  4922. llvm::APInt(32, i, true))},
  4923. loc);
  4924. elements.push_back(spvBuilder.createLoad(elemType, subRhsPtr, loc));
  4925. }
  4926. // Create a new composite and write out once
  4927. spvBuilder.createStore(
  4928. lhsPtr,
  4929. spvBuilder.createCompositeConstruct(lhsValType, elements,
  4930. rhsVal->getSourceLocation()),
  4931. loc);
  4932. } else if (lhsPtr->getLayoutRule() == rhsVal->getLayoutRule()) {
  4933. // If lhs and rhs has the same memory layout, we should be safe to load
  4934. // from rhs and directly store into lhs and avoid decomposing rhs.
  4935. // Note: this check should happen after those setting needsLegalization.
  4936. // TODO: is this optimization always correct?
  4937. spvBuilder.createStore(lhsPtr, rhsVal, loc);
  4938. } else if (lhsValType->isRecordType() || lhsValType->isConstantArrayType() ||
  4939. lhsIsNonFpMat) {
  4940. spvBuilder.createStore(
  4941. lhsPtr,
  4942. reconstructValue(rhsVal, lhsValType, lhsPtr->getLayoutRule(), loc),
  4943. loc);
  4944. } else {
  4945. emitError("storing value of type %0 unimplemented", {}) << lhsValType;
  4946. }
  4947. }
  4948. SpirvInstruction *SpirvEmitter::reconstructValue(SpirvInstruction *srcVal,
  4949. const QualType valType,
  4950. SpirvLayoutRule dstLR,
  4951. SourceLocation loc) {
  4952. // Lambda for casting scalar or vector of bool<-->uint in cases where one side
  4953. // of the reconstruction (lhs or rhs) has a layout rule.
  4954. const auto handleBooleanLayout = [this, &srcVal, dstLR,
  4955. loc](SpirvInstruction *val,
  4956. QualType valType) {
  4957. // We only need to cast if we have a scalar or vector of booleans.
  4958. if (!isBoolOrVecOfBoolType(valType))
  4959. return val;
  4960. SpirvLayoutRule srcLR = srcVal->getLayoutRule();
  4961. // Source value has a layout rule, and has therefore been represented
  4962. // as a uint. Cast it to boolean before using.
  4963. bool shouldCastToBool =
  4964. srcLR != SpirvLayoutRule::Void && dstLR == SpirvLayoutRule::Void;
  4965. // Destination has a layout rule, and should therefore be represented
  4966. // as a uint. Cast to uint before using.
  4967. bool shouldCastToUint =
  4968. srcLR == SpirvLayoutRule::Void && dstLR != SpirvLayoutRule::Void;
  4969. // No boolean layout issues to take care of.
  4970. if (!shouldCastToBool && !shouldCastToUint)
  4971. return val;
  4972. uint32_t vecSize = 1;
  4973. isVectorType(valType, nullptr, &vecSize);
  4974. QualType boolType =
  4975. vecSize == 1 ? astContext.BoolTy
  4976. : astContext.getExtVectorType(astContext.BoolTy, vecSize);
  4977. QualType uintType =
  4978. vecSize == 1
  4979. ? astContext.UnsignedIntTy
  4980. : astContext.getExtVectorType(astContext.UnsignedIntTy, vecSize);
  4981. if (shouldCastToBool)
  4982. return castToBool(val, uintType, boolType, loc);
  4983. if (shouldCastToUint)
  4984. return castToInt(val, boolType, uintType, loc);
  4985. return val;
  4986. };
  4987. // Lambda for cases where we want to reconstruct an array
  4988. const auto reconstructArray = [this, &srcVal, valType, dstLR,
  4989. loc](uint32_t arraySize,
  4990. QualType arrayElemType) {
  4991. llvm::SmallVector<SpirvInstruction *, 4> elements;
  4992. for (uint32_t i = 0; i < arraySize; ++i) {
  4993. SpirvInstruction *subSrcVal =
  4994. spvBuilder.createCompositeExtract(arrayElemType, srcVal, {i}, loc);
  4995. subSrcVal->setLayoutRule(srcVal->getLayoutRule());
  4996. elements.push_back(
  4997. reconstructValue(subSrcVal, arrayElemType, dstLR, loc));
  4998. }
  4999. auto *result = spvBuilder.createCompositeConstruct(
  5000. valType, elements, srcVal->getSourceLocation());
  5001. result->setLayoutRule(dstLR);
  5002. return result;
  5003. };
  5004. // Constant arrays
  5005. if (const auto *arrayType = astContext.getAsConstantArrayType(valType)) {
  5006. const auto elemType = arrayType->getElementType();
  5007. const auto size =
  5008. static_cast<uint32_t>(arrayType->getSize().getZExtValue());
  5009. return reconstructArray(size, elemType);
  5010. }
  5011. // Non-floating-point matrices
  5012. QualType matElemType = {};
  5013. uint32_t numRows = 0, numCols = 0;
  5014. const bool isNonFpMat =
  5015. isMxNMatrix(valType, &matElemType, &numRows, &numCols) &&
  5016. !matElemType->isFloatingType();
  5017. if (isNonFpMat) {
  5018. // Note: This check should happen before the RecordType check.
  5019. // Non-fp matrices are represented as arrays of vectors in SPIR-V.
  5020. // Each array element is a vector. Get the QualType for the vector.
  5021. const auto elemType = astContext.getExtVectorType(matElemType, numCols);
  5022. return reconstructArray(numRows, elemType);
  5023. }
  5024. // Note: This check should happen before the RecordType check since
  5025. // vector/matrix/resource types are represented as RecordType in the AST.
  5026. if (hlsl::IsHLSLVecMatType(valType) || hlsl::IsHLSLResourceType(valType))
  5027. return handleBooleanLayout(srcVal, valType);
  5028. // Structs
  5029. if (const auto *recordType = valType->getAs<RecordType>()) {
  5030. uint32_t index = 0;
  5031. llvm::SmallVector<SpirvInstruction *, 4> elements;
  5032. // If the struct inherits from other structs, visit the bases.
  5033. const auto *decl = valType->getAsCXXRecordDecl();
  5034. for (auto baseIt = decl->bases_begin(), baseIe = decl->bases_end();
  5035. baseIt != baseIe; ++baseIt, ++index) {
  5036. SpirvInstruction *subSrcVal = spvBuilder.createCompositeExtract(
  5037. baseIt->getType(), srcVal, {index}, loc);
  5038. subSrcVal->setLayoutRule(srcVal->getLayoutRule());
  5039. elements.push_back(
  5040. reconstructValue(subSrcVal, baseIt->getType(), dstLR, loc));
  5041. }
  5042. // Go over struct fields.
  5043. for (const auto *field : recordType->getDecl()->fields()) {
  5044. SpirvInstruction *subSrcVal = spvBuilder.createCompositeExtract(
  5045. field->getType(), srcVal, {index}, loc);
  5046. subSrcVal->setLayoutRule(srcVal->getLayoutRule());
  5047. elements.push_back(
  5048. reconstructValue(subSrcVal, field->getType(), dstLR, loc));
  5049. ++index;
  5050. }
  5051. auto *result = spvBuilder.createCompositeConstruct(
  5052. valType, elements, srcVal->getSourceLocation());
  5053. result->setLayoutRule(dstLR);
  5054. return result;
  5055. }
  5056. return handleBooleanLayout(srcVal, valType);
  5057. }
  5058. SpirvInstruction *SpirvEmitter::processBinaryOp(
  5059. const Expr *lhs, const Expr *rhs, const BinaryOperatorKind opcode,
  5060. const QualType computationType, const QualType resultType,
  5061. SourceRange sourceRange, SourceLocation loc, SpirvInstruction **lhsInfo,
  5062. const spv::Op mandateGenOpcode) {
  5063. const QualType lhsType = lhs->getType();
  5064. const QualType rhsType = rhs->getType();
  5065. // If the operands are of matrix type, we need to dispatch the operation
  5066. // onto each element vector iff the operands are not degenerated matrices
  5067. // and we don't have a matrix specific SPIR-V instruction for the operation.
  5068. if (!isSpirvMatrixOp(mandateGenOpcode) && isMxNMatrix(lhsType)) {
  5069. return processMatrixBinaryOp(lhs, rhs, opcode, sourceRange, loc);
  5070. }
  5071. // Comma operator works differently from other binary operations as there is
  5072. // no SPIR-V instruction for it. For each comma, we must evaluate lhs and rhs
  5073. // respectively, and return the results of rhs.
  5074. if (opcode == BO_Comma) {
  5075. (void)doExpr(lhs);
  5076. return doExpr(rhs);
  5077. }
  5078. SpirvInstruction *rhsVal = nullptr, *lhsPtr = nullptr, *lhsVal = nullptr;
  5079. if (BinaryOperator::isCompoundAssignmentOp(opcode)) {
  5080. // Evalute rhs before lhs
  5081. rhsVal = loadIfGLValue(rhs);
  5082. lhsVal = lhsPtr = doExpr(lhs);
  5083. // This is a compound assignment. We need to load the lhs value if lhs
  5084. // is not already rvalue and does not generate a vector shuffle.
  5085. if (!lhsPtr->isRValue() && !isVectorShuffle(lhs)) {
  5086. lhsVal = loadIfGLValue(lhs, lhsPtr);
  5087. }
  5088. // For a compound assignments, the AST does not have the proper implicit
  5089. // cast if lhs and rhs have different types. So we need to manually cast lhs
  5090. // to the computation type.
  5091. if (computationType != lhsType)
  5092. lhsVal = castToType(lhsVal, lhsType, computationType, lhs->getExprLoc());
  5093. } else {
  5094. // Evalute lhs before rhs
  5095. lhsPtr = doExpr(lhs);
  5096. if (!lhsPtr)
  5097. return nullptr;
  5098. lhsVal = loadIfGLValue(lhs, lhsPtr);
  5099. rhsVal = loadIfGLValue(rhs);
  5100. }
  5101. if (lhsInfo)
  5102. *lhsInfo = lhsPtr;
  5103. const spv::Op spvOp = (mandateGenOpcode == spv::Op::Max)
  5104. ? translateOp(opcode, computationType)
  5105. : mandateGenOpcode;
  5106. switch (opcode) {
  5107. case BO_Shl:
  5108. case BO_Shr:
  5109. case BO_ShlAssign:
  5110. case BO_ShrAssign:
  5111. // We need to cull the RHS to make sure that we are not shifting by an
  5112. // amount that is larger than the bitwidth of the LHS.
  5113. rhsVal = spvBuilder.createBinaryOp(spv::Op::OpBitwiseAnd, computationType,
  5114. rhsVal, getMaskForBitwidthValue(rhsType),
  5115. loc);
  5116. // Fall through
  5117. case BO_Add:
  5118. case BO_Sub:
  5119. case BO_Mul:
  5120. case BO_Div:
  5121. case BO_Rem:
  5122. case BO_LT:
  5123. case BO_LE:
  5124. case BO_GT:
  5125. case BO_GE:
  5126. case BO_EQ:
  5127. case BO_NE:
  5128. case BO_And:
  5129. case BO_Or:
  5130. case BO_Xor:
  5131. case BO_LAnd:
  5132. case BO_LOr:
  5133. case BO_AddAssign:
  5134. case BO_SubAssign:
  5135. case BO_MulAssign:
  5136. case BO_DivAssign:
  5137. case BO_RemAssign:
  5138. case BO_AndAssign:
  5139. case BO_OrAssign:
  5140. case BO_XorAssign: {
  5141. // To evaluate this expression as an OpSpecConstantOp, we need to make sure
  5142. // both operands are constant and at least one of them is a spec constant.
  5143. if (SpirvConstant *lhsValConstant = dyn_cast<SpirvConstant>(lhsVal)) {
  5144. if (SpirvConstant *rhsValConstant = dyn_cast<SpirvConstant>(rhsVal)) {
  5145. if (isAcceptedSpecConstantBinaryOp(spvOp)) {
  5146. if (lhsValConstant->isSpecConstant() ||
  5147. rhsValConstant->isSpecConstant()) {
  5148. auto *val = spvBuilder.createSpecConstantBinaryOp(
  5149. spvOp, resultType, lhsVal, rhsVal, loc);
  5150. val->setRValue();
  5151. return val;
  5152. }
  5153. }
  5154. }
  5155. }
  5156. // Normal binary operation
  5157. SpirvInstruction *val = nullptr;
  5158. if (BinaryOperator::isCompoundAssignmentOp(opcode)) {
  5159. val = spvBuilder.createBinaryOp(spvOp, computationType, lhsVal, rhsVal,
  5160. loc);
  5161. // For a compound assignments, the AST does not have the proper implicit
  5162. // cast if lhs and rhs have different types. So we need to manually cast
  5163. // the result back to lhs' type.
  5164. if (computationType != lhsType)
  5165. val = castToType(val, computationType, lhsType, lhs->getExprLoc());
  5166. } else {
  5167. val = spvBuilder.createBinaryOp(spvOp, resultType, lhsVal, rhsVal, loc);
  5168. }
  5169. val->setRValue();
  5170. // Propagate RelaxedPrecision
  5171. if ((lhsVal && lhsVal->isRelaxedPrecision()) ||
  5172. (rhsVal && rhsVal->isRelaxedPrecision()))
  5173. val->setRelaxedPrecision();
  5174. return val;
  5175. }
  5176. case BO_Assign:
  5177. llvm_unreachable("assignment should not be handled here");
  5178. break;
  5179. case BO_PtrMemD:
  5180. case BO_PtrMemI:
  5181. case BO_Comma:
  5182. // Unimplemented
  5183. break;
  5184. }
  5185. emitError("binary operator '%0' unimplemented", lhs->getExprLoc())
  5186. << BinaryOperator::getOpcodeStr(opcode) << sourceRange;
  5187. return nullptr;
  5188. }
  5189. void SpirvEmitter::initOnce(QualType varType, std::string varName,
  5190. SpirvVariable *var, const Expr *varInit) {
  5191. // For uninitialized resource objects, we do nothing since there is no
  5192. // meaningful zero values for them.
  5193. if (!varInit && hlsl::IsHLSLResourceType(varType))
  5194. return;
  5195. varName = "init.done." + varName;
  5196. auto loc = varInit ? varInit->getLocStart() : SourceLocation();
  5197. // Create a file/module visible variable to hold the initialization state.
  5198. SpirvVariable *initDoneVar = spvBuilder.addModuleVar(
  5199. astContext.BoolTy, spv::StorageClass::Private, /*isPrecise*/ false,
  5200. varName, spvBuilder.getConstantBool(false));
  5201. auto *condition = spvBuilder.createLoad(astContext.BoolTy, initDoneVar, loc);
  5202. auto *todoBB = spvBuilder.createBasicBlock("if.init.todo");
  5203. auto *doneBB = spvBuilder.createBasicBlock("if.init.done");
  5204. // If initDoneVar contains true, we jump to the "done" basic block; otherwise,
  5205. // jump to the "todo" basic block.
  5206. spvBuilder.createConditionalBranch(condition, doneBB, todoBB, loc, doneBB);
  5207. spvBuilder.addSuccessor(todoBB);
  5208. spvBuilder.addSuccessor(doneBB);
  5209. spvBuilder.setMergeTarget(doneBB);
  5210. spvBuilder.setInsertPoint(todoBB);
  5211. // Do initialization and mark done
  5212. if (varInit) {
  5213. var->setStorageClass(spv::StorageClass::Private);
  5214. storeValue(
  5215. // Static function variable are of private storage class
  5216. var, loadIfGLValue(varInit), varInit->getType(), varInit->getLocEnd());
  5217. } else {
  5218. spvBuilder.createStore(var, spvBuilder.getConstantNull(varType), loc);
  5219. }
  5220. spvBuilder.createStore(initDoneVar, spvBuilder.getConstantBool(true), loc);
  5221. spvBuilder.createBranch(doneBB, loc);
  5222. spvBuilder.addSuccessor(doneBB);
  5223. spvBuilder.setInsertPoint(doneBB);
  5224. }
  5225. bool SpirvEmitter::isVectorShuffle(const Expr *expr) {
  5226. // TODO: the following check is essentially duplicated from
  5227. // doHLSLVectorElementExpr. Should unify them.
  5228. if (const auto *vecElemExpr = dyn_cast<HLSLVectorElementExpr>(expr)) {
  5229. const Expr *base = nullptr;
  5230. hlsl::VectorMemberAccessPositions accessor;
  5231. condenseVectorElementExpr(vecElemExpr, &base, &accessor);
  5232. const auto accessorSize = accessor.Count;
  5233. if (accessorSize == 1) {
  5234. // Selecting only one element. OpAccessChain or OpCompositeExtract for
  5235. // such cases.
  5236. return false;
  5237. }
  5238. const auto baseSize = hlsl::GetHLSLVecSize(base->getType());
  5239. if (accessorSize != baseSize)
  5240. return true;
  5241. for (uint32_t i = 0; i < accessorSize; ++i) {
  5242. uint32_t position;
  5243. accessor.GetPosition(i, &position);
  5244. if (position != i)
  5245. return true;
  5246. }
  5247. // Selecting exactly the original vector. No vector shuffle generated.
  5248. return false;
  5249. }
  5250. return false;
  5251. }
  5252. bool SpirvEmitter::isTextureMipsSampleIndexing(const CXXOperatorCallExpr *expr,
  5253. const Expr **base,
  5254. const Expr **location,
  5255. const Expr **lod) {
  5256. if (!expr)
  5257. return false;
  5258. // <object>.mips[][] consists of an outer operator[] and an inner operator[]
  5259. const CXXOperatorCallExpr *outerExpr = expr;
  5260. if (outerExpr->getOperator() != OverloadedOperatorKind::OO_Subscript)
  5261. return false;
  5262. const Expr *arg0 = outerExpr->getArg(0)->IgnoreParenNoopCasts(astContext);
  5263. const CXXOperatorCallExpr *innerExpr = dyn_cast<CXXOperatorCallExpr>(arg0);
  5264. // Must have an inner operator[]
  5265. if (!innerExpr ||
  5266. innerExpr->getOperator() != OverloadedOperatorKind::OO_Subscript) {
  5267. return false;
  5268. }
  5269. const Expr *innerArg0 =
  5270. innerExpr->getArg(0)->IgnoreParenNoopCasts(astContext);
  5271. const MemberExpr *memberExpr = dyn_cast<MemberExpr>(innerArg0);
  5272. if (!memberExpr)
  5273. return false;
  5274. // Must be accessing the member named "mips" or "sample"
  5275. const auto &memberName =
  5276. memberExpr->getMemberNameInfo().getName().getAsString();
  5277. if (memberName != "mips" && memberName != "sample")
  5278. return false;
  5279. const Expr *object = memberExpr->getBase();
  5280. const auto objectType = object->getType();
  5281. if (!isTexture(objectType))
  5282. return false;
  5283. if (base)
  5284. *base = object;
  5285. if (lod)
  5286. *lod = innerExpr->getArg(1);
  5287. if (location)
  5288. *location = outerExpr->getArg(1);
  5289. return true;
  5290. }
  5291. bool SpirvEmitter::isBufferTextureIndexing(const CXXOperatorCallExpr *indexExpr,
  5292. const Expr **base,
  5293. const Expr **index) {
  5294. if (!indexExpr)
  5295. return false;
  5296. // Must be operator[]
  5297. if (indexExpr->getOperator() != OverloadedOperatorKind::OO_Subscript)
  5298. return false;
  5299. const Expr *object = indexExpr->getArg(0);
  5300. const auto objectType = object->getType();
  5301. if (isBuffer(objectType) || isRWBuffer(objectType) || isTexture(objectType) ||
  5302. isRWTexture(objectType)) {
  5303. if (base)
  5304. *base = object;
  5305. if (index)
  5306. *index = indexExpr->getArg(1);
  5307. return true;
  5308. }
  5309. return false;
  5310. }
  5311. void SpirvEmitter::condenseVectorElementExpr(
  5312. const HLSLVectorElementExpr *expr, const Expr **basePtr,
  5313. hlsl::VectorMemberAccessPositions *flattenedAccessor) {
  5314. llvm::SmallVector<hlsl::VectorMemberAccessPositions, 2> accessors;
  5315. *basePtr = expr;
  5316. // Recursively descending until we find the true base vector (the base vector
  5317. // that does not have a base vector). In the meanwhile, collecting accessors
  5318. // in the reverse order.
  5319. // Example: for myVector.yxwz.yxz.xx.yx, the true base is 'myVector'.
  5320. while (const auto *vecElemBase = dyn_cast<HLSLVectorElementExpr>(*basePtr)) {
  5321. accessors.push_back(vecElemBase->getEncodedElementAccess());
  5322. *basePtr = vecElemBase->getBase();
  5323. // We need to skip any number of parentheses around swizzling at any level.
  5324. while (const auto *parenExpr = dyn_cast<ParenExpr>(*basePtr))
  5325. *basePtr = parenExpr->getSubExpr();
  5326. }
  5327. *flattenedAccessor = accessors.back();
  5328. for (int32_t i = accessors.size() - 2; i >= 0; --i) {
  5329. const auto &currentAccessor = accessors[i];
  5330. // Apply the current level of accessor to the flattened accessor of all
  5331. // previous levels of ones.
  5332. hlsl::VectorMemberAccessPositions combinedAccessor;
  5333. for (uint32_t j = 0; j < currentAccessor.Count; ++j) {
  5334. uint32_t currentPosition = 0;
  5335. currentAccessor.GetPosition(j, &currentPosition);
  5336. uint32_t previousPosition = 0;
  5337. flattenedAccessor->GetPosition(currentPosition, &previousPosition);
  5338. combinedAccessor.SetPosition(j, previousPosition);
  5339. }
  5340. combinedAccessor.Count = currentAccessor.Count;
  5341. combinedAccessor.IsValid =
  5342. flattenedAccessor->IsValid && currentAccessor.IsValid;
  5343. *flattenedAccessor = combinedAccessor;
  5344. }
  5345. }
  5346. SpirvInstruction *SpirvEmitter::createVectorSplat(const Expr *scalarExpr,
  5347. uint32_t size) {
  5348. SpirvInstruction *scalarVal = nullptr;
  5349. // Try to evaluate the element as constant first. If successful, then we
  5350. // can generate constant instructions for this vector splat.
  5351. if ((scalarVal = tryToEvaluateAsConst(scalarExpr))) {
  5352. scalarVal->setRValue();
  5353. } else {
  5354. scalarVal = loadIfGLValue(scalarExpr);
  5355. }
  5356. if (!scalarVal || size == 1) {
  5357. // Just return the scalar value for vector splat with size 1.
  5358. // Note that can be used as an lvalue, so we need to carry over
  5359. // the lvalueness for non-constant cases.
  5360. return scalarVal;
  5361. }
  5362. const auto vecType = astContext.getExtVectorType(scalarExpr->getType(), size);
  5363. // TODO: we are saying the constant has Function storage class here.
  5364. // Should find a more meaningful one.
  5365. if (auto *constVal = dyn_cast<SpirvConstant>(scalarVal)) {
  5366. llvm::SmallVector<SpirvConstant *, 4> elements(size_t(size), constVal);
  5367. auto *value = spvBuilder.getConstantComposite(vecType, elements);
  5368. value->setRValue();
  5369. return value;
  5370. } else {
  5371. llvm::SmallVector<SpirvInstruction *, 4> elements(size_t(size), scalarVal);
  5372. auto *value = spvBuilder.createCompositeConstruct(
  5373. vecType, elements, scalarExpr->getLocStart());
  5374. value->setRValue();
  5375. return value;
  5376. }
  5377. }
  5378. void SpirvEmitter::splitVecLastElement(QualType vecType, SpirvInstruction *vec,
  5379. SpirvInstruction **residual,
  5380. SpirvInstruction **lastElement,
  5381. SourceLocation loc) {
  5382. assert(hlsl::IsHLSLVecType(vecType));
  5383. const uint32_t count = hlsl::GetHLSLVecSize(vecType);
  5384. assert(count > 1);
  5385. const QualType elemType = hlsl::GetHLSLVecElementType(vecType);
  5386. if (count == 2) {
  5387. *residual = spvBuilder.createCompositeExtract(elemType, vec, 0, loc);
  5388. } else {
  5389. llvm::SmallVector<uint32_t, 4> indices;
  5390. for (uint32_t i = 0; i < count - 1; ++i)
  5391. indices.push_back(i);
  5392. const QualType type = astContext.getExtVectorType(elemType, count - 1);
  5393. *residual = spvBuilder.createVectorShuffle(type, vec, vec, indices, loc);
  5394. }
  5395. *lastElement =
  5396. spvBuilder.createCompositeExtract(elemType, vec, {count - 1}, loc);
  5397. }
  5398. SpirvInstruction *SpirvEmitter::convertVectorToStruct(QualType structType,
  5399. QualType elemType,
  5400. SpirvInstruction *vector,
  5401. SourceLocation loc) {
  5402. assert(structType->isStructureType());
  5403. const auto *structDecl = structType->getAsStructureType()->getDecl();
  5404. uint32_t vectorIndex = 0;
  5405. uint32_t elemCount = 1;
  5406. llvm::SmallVector<SpirvInstruction *, 4> members;
  5407. for (const auto *field : structDecl->fields()) {
  5408. if (isScalarType(field->getType())) {
  5409. members.push_back(spvBuilder.createCompositeExtract(
  5410. elemType, vector, {vectorIndex++}, loc));
  5411. } else if (isVectorType(field->getType(), nullptr, &elemCount)) {
  5412. llvm::SmallVector<uint32_t, 4> indices;
  5413. for (uint32_t i = 0; i < elemCount; ++i)
  5414. indices.push_back(vectorIndex++);
  5415. members.push_back(spvBuilder.createVectorShuffle(
  5416. astContext.getExtVectorType(elemType, elemCount), vector, vector,
  5417. indices, loc));
  5418. } else {
  5419. assert(false && "unhandled type");
  5420. }
  5421. }
  5422. return spvBuilder.createCompositeConstruct(structType, members,
  5423. vector->getSourceLocation());
  5424. }
  5425. SpirvInstruction *
  5426. SpirvEmitter::tryToGenFloatVectorScale(const BinaryOperator *expr) {
  5427. const QualType type = expr->getType();
  5428. const SourceRange range = expr->getSourceRange();
  5429. QualType elemType = {};
  5430. // We can only translate floatN * float into OpVectorTimesScalar.
  5431. // So the result type must be floatN. Note that float1 is not a valid vector
  5432. // in SPIR-V.
  5433. if (!(isVectorType(type, &elemType) && elemType->isFloatingType()))
  5434. return nullptr;
  5435. const Expr *lhs = expr->getLHS();
  5436. const Expr *rhs = expr->getRHS();
  5437. // Multiplying a float vector with a float scalar will be represented in
  5438. // AST via a binary operation with two float vectors as operands; one of
  5439. // the operand is from an implicit cast with kind CK_HLSLVectorSplat.
  5440. // vector * scalar
  5441. if (hlsl::IsHLSLVecType(lhs->getType())) {
  5442. if (const auto *cast = dyn_cast<ImplicitCastExpr>(rhs)) {
  5443. if (cast->getCastKind() == CK_HLSLVectorSplat) {
  5444. const QualType vecType = expr->getType();
  5445. if (const auto *compoundAssignExpr =
  5446. dyn_cast<CompoundAssignOperator>(expr)) {
  5447. const auto computationType =
  5448. compoundAssignExpr->getComputationLHSType();
  5449. SpirvInstruction *lhsPtr = nullptr;
  5450. auto *result = processBinaryOp(lhs, cast->getSubExpr(),
  5451. expr->getOpcode(), computationType,
  5452. vecType, range, expr->getOperatorLoc(),
  5453. &lhsPtr, spv::Op::OpVectorTimesScalar);
  5454. return processAssignment(lhs, result, true, lhsPtr);
  5455. } else {
  5456. return processBinaryOp(lhs, cast->getSubExpr(), expr->getOpcode(),
  5457. vecType, vecType, range,
  5458. expr->getOperatorLoc(), nullptr,
  5459. spv::Op::OpVectorTimesScalar);
  5460. }
  5461. }
  5462. }
  5463. }
  5464. // scalar * vector
  5465. if (hlsl::IsHLSLVecType(rhs->getType())) {
  5466. if (const auto *cast = dyn_cast<ImplicitCastExpr>(lhs)) {
  5467. if (cast->getCastKind() == CK_HLSLVectorSplat) {
  5468. const QualType vecType = expr->getType();
  5469. // We need to switch the positions of lhs and rhs here because
  5470. // OpVectorTimesScalar requires the first operand to be a vector and
  5471. // the second to be a scalar.
  5472. return processBinaryOp(rhs, cast->getSubExpr(), expr->getOpcode(),
  5473. vecType, vecType, range, expr->getOperatorLoc(),
  5474. nullptr, spv::Op::OpVectorTimesScalar);
  5475. }
  5476. }
  5477. }
  5478. return nullptr;
  5479. }
  5480. SpirvInstruction *
  5481. SpirvEmitter::tryToGenFloatMatrixScale(const BinaryOperator *expr) {
  5482. const QualType type = expr->getType();
  5483. const SourceRange range = expr->getSourceRange();
  5484. // We translate 'floatMxN * float' into OpMatrixTimesScalar.
  5485. // We translate 'floatMx1 * float' and 'float1xN * float' using
  5486. // OpVectorTimesScalar.
  5487. // So the result type can be floatMxN, floatMx1, or float1xN.
  5488. if (!hlsl::IsHLSLMatType(type) ||
  5489. !hlsl::GetHLSLMatElementType(type)->isFloatingType() || is1x1Matrix(type))
  5490. return 0;
  5491. const Expr *lhs = expr->getLHS();
  5492. const Expr *rhs = expr->getRHS();
  5493. const QualType lhsType = lhs->getType();
  5494. const QualType rhsType = rhs->getType();
  5495. const auto selectOpcode = [](const QualType ty) {
  5496. return isMx1Matrix(ty) || is1xNMatrix(ty) ? spv::Op::OpVectorTimesScalar
  5497. : spv::Op::OpMatrixTimesScalar;
  5498. };
  5499. // Multiplying a float matrix with a float scalar will be represented in
  5500. // AST via a binary operation with two float matrices as operands; one of
  5501. // the operand is from an implicit cast with kind CK_HLSLMatrixSplat.
  5502. // matrix * scalar
  5503. if (hlsl::IsHLSLMatType(lhsType)) {
  5504. if (const auto *cast = dyn_cast<ImplicitCastExpr>(rhs)) {
  5505. if (cast->getCastKind() == CK_HLSLMatrixSplat) {
  5506. const QualType matType = expr->getType();
  5507. const spv::Op opcode = selectOpcode(lhsType);
  5508. if (const auto *compoundAssignExpr =
  5509. dyn_cast<CompoundAssignOperator>(expr)) {
  5510. const auto computationType =
  5511. compoundAssignExpr->getComputationLHSType();
  5512. SpirvInstruction *lhsPtr = nullptr;
  5513. auto *result = processBinaryOp(
  5514. lhs, cast->getSubExpr(), expr->getOpcode(), computationType,
  5515. matType, range, expr->getOperatorLoc(), &lhsPtr, opcode);
  5516. return processAssignment(lhs, result, true, lhsPtr);
  5517. } else {
  5518. return processBinaryOp(lhs, cast->getSubExpr(), expr->getOpcode(),
  5519. matType, matType, range,
  5520. expr->getOperatorLoc(), nullptr, opcode);
  5521. }
  5522. }
  5523. }
  5524. }
  5525. // scalar * matrix
  5526. if (hlsl::IsHLSLMatType(rhsType)) {
  5527. if (const auto *cast = dyn_cast<ImplicitCastExpr>(lhs)) {
  5528. if (cast->getCastKind() == CK_HLSLMatrixSplat) {
  5529. const QualType matType = expr->getType();
  5530. const spv::Op opcode = selectOpcode(rhsType);
  5531. // We need to switch the positions of lhs and rhs here because
  5532. // OpMatrixTimesScalar requires the first operand to be a matrix and
  5533. // the second to be a scalar.
  5534. return processBinaryOp(rhs, cast->getSubExpr(), expr->getOpcode(),
  5535. matType, matType, range, expr->getOperatorLoc(),
  5536. nullptr, opcode);
  5537. }
  5538. }
  5539. }
  5540. return nullptr;
  5541. }
  5542. SpirvInstruction *
  5543. SpirvEmitter::tryToAssignToVectorElements(const Expr *lhs,
  5544. SpirvInstruction *rhs) {
  5545. // Assigning to a vector swizzling lhs is tricky if we are neither
  5546. // writing to one element nor all elements in their original order.
  5547. // Under such cases, we need to create a new vector swizzling involving
  5548. // both the lhs and rhs vectors and then write the result of this swizzling
  5549. // into the base vector of lhs.
  5550. // For example, for vec4.yz = vec2, we nee to do the following:
  5551. //
  5552. // %vec4Val = OpLoad %v4float %vec4
  5553. // %vec2Val = OpLoad %v2float %vec2
  5554. // %shuffle = OpVectorShuffle %v4float %vec4Val %vec2Val 0 4 5 3
  5555. // OpStore %vec4 %shuffle
  5556. //
  5557. // When doing the vector shuffle, we use the lhs base vector as the first
  5558. // vector and the rhs vector as the second vector. Therefore, all elements
  5559. // in the second vector will be selected into the shuffle result.
  5560. const auto *lhsExpr = dyn_cast<HLSLVectorElementExpr>(lhs);
  5561. if (!lhsExpr)
  5562. return 0;
  5563. // Special case for <scalar-value>.x, which will have an AST of
  5564. // HLSLVectorElementExpr whose base is an ImplicitCastExpr
  5565. // (CK_HLSLVectorSplat). We just need to assign to <scalar-value>
  5566. // for such case.
  5567. if (const auto *baseCast = dyn_cast<CastExpr>(lhsExpr->getBase()))
  5568. if (baseCast->getCastKind() == CastKind::CK_HLSLVectorSplat &&
  5569. hlsl::GetHLSLVecSize(baseCast->getType()) == 1)
  5570. return processAssignment(baseCast->getSubExpr(), rhs, false);
  5571. const Expr *base = nullptr;
  5572. hlsl::VectorMemberAccessPositions accessor;
  5573. condenseVectorElementExpr(lhsExpr, &base, &accessor);
  5574. const QualType baseType = base->getType();
  5575. assert(hlsl::IsHLSLVecType(baseType));
  5576. const auto baseSize = hlsl::GetHLSLVecSize(baseType);
  5577. const auto accessorSize = accessor.Count;
  5578. // Whether selecting the whole original vector
  5579. bool isSelectOrigin = accessorSize == baseSize;
  5580. // Assigning to one component
  5581. if (accessorSize == 1) {
  5582. if (isBufferTextureIndexing(dyn_cast_or_null<CXXOperatorCallExpr>(base))) {
  5583. // Assigning to one component of a RWBuffer/RWTexture element
  5584. // We need to use OpImageWrite here.
  5585. // Compose the new vector value first
  5586. auto *oldVec = doExpr(base);
  5587. auto *newVec = spvBuilder.createCompositeInsert(
  5588. baseType, oldVec, {accessor.Swz0}, rhs, lhs->getLocStart());
  5589. auto *result = tryToAssignToRWBufferRWTexture(base, newVec);
  5590. assert(result); // Definitely RWBuffer/RWTexture assignment
  5591. (void)result;
  5592. return rhs; // TODO: incorrect for compound assignments
  5593. } else {
  5594. // Assigning to one component of mesh out attribute/indices vector object.
  5595. SpirvInstruction *vecComponent = spvBuilder.getConstantInt(
  5596. astContext.UnsignedIntTy, llvm::APInt(32, accessor.Swz0));
  5597. if (tryToAssignToMSOutAttrsOrIndices(base, rhs, vecComponent))
  5598. return rhs;
  5599. // Assigning to one normal vector component. Nothing special, just fall
  5600. // back to the normal CodeGen path.
  5601. return nullptr;
  5602. }
  5603. }
  5604. if (isSelectOrigin) {
  5605. for (uint32_t i = 0; i < accessorSize; ++i) {
  5606. uint32_t position;
  5607. accessor.GetPosition(i, &position);
  5608. if (position != i)
  5609. isSelectOrigin = false;
  5610. }
  5611. }
  5612. // Assigning to the original vector
  5613. if (isSelectOrigin) {
  5614. // Ignore this HLSLVectorElementExpr and dispatch to base
  5615. return processAssignment(base, rhs, false);
  5616. }
  5617. if (tryToAssignToMSOutAttrsOrIndices(base, rhs, /*vecComponent=*/nullptr,
  5618. /*noWriteBack=*/true)) {
  5619. // Assigning to 'n' components of mesh out attribute/indices vector object.
  5620. const QualType elemType =
  5621. hlsl::GetHLSLVecElementType(rhs->getAstResultType());
  5622. uint32_t i = 0;
  5623. for (; i < accessor.Count; ++i) {
  5624. auto *rhsElem = spvBuilder.createCompositeExtract(elemType, rhs, {i},
  5625. lhs->getLocStart());
  5626. uint32_t position;
  5627. accessor.GetPosition(i, &position);
  5628. SpirvInstruction *vecComponent = spvBuilder.getConstantInt(
  5629. astContext.UnsignedIntTy, llvm::APInt(32, position));
  5630. if (!tryToAssignToMSOutAttrsOrIndices(base, rhsElem, vecComponent))
  5631. break;
  5632. }
  5633. assert(i == accessor.Count);
  5634. return rhs;
  5635. }
  5636. llvm::SmallVector<uint32_t, 4> selectors;
  5637. selectors.resize(baseSize);
  5638. // Assume we are selecting all original elements first.
  5639. for (uint32_t i = 0; i < baseSize; ++i) {
  5640. selectors[i] = i;
  5641. }
  5642. // Now fix up the elements that actually got overwritten by the rhs vector.
  5643. // Since we are using the rhs vector as the second vector, their index
  5644. // should be offset'ed by the size of the lhs base vector.
  5645. for (uint32_t i = 0; i < accessor.Count; ++i) {
  5646. uint32_t position;
  5647. accessor.GetPosition(i, &position);
  5648. selectors[position] = baseSize + i;
  5649. }
  5650. auto *vec1 = doExpr(base);
  5651. auto *vec1Val = vec1->isRValue() ? vec1
  5652. : spvBuilder.createLoad(baseType, vec1,
  5653. base->getLocStart());
  5654. auto *shuffle = spvBuilder.createVectorShuffle(baseType, vec1Val, rhs,
  5655. selectors, lhs->getLocStart());
  5656. if (!tryToAssignToRWBufferRWTexture(base, shuffle))
  5657. spvBuilder.createStore(vec1, shuffle, lhs->getLocStart());
  5658. // TODO: OK, this return value is incorrect for compound assignments, for
  5659. // which cases we should return lvalues. Should at least emit errors if
  5660. // this return value is used (can be checked via ASTContext.getParents).
  5661. return rhs;
  5662. }
  5663. SpirvInstruction *
  5664. SpirvEmitter::tryToAssignToRWBufferRWTexture(const Expr *lhs,
  5665. SpirvInstruction *rhs) {
  5666. const Expr *baseExpr = nullptr;
  5667. const Expr *indexExpr = nullptr;
  5668. const auto lhsExpr = dyn_cast<CXXOperatorCallExpr>(lhs);
  5669. if (isBufferTextureIndexing(lhsExpr, &baseExpr, &indexExpr)) {
  5670. auto *loc = doExpr(indexExpr);
  5671. const QualType imageType = baseExpr->getType();
  5672. auto *baseInfo = doExpr(baseExpr);
  5673. auto *image =
  5674. spvBuilder.createLoad(imageType, baseInfo, baseExpr->getExprLoc());
  5675. spvBuilder.createImageWrite(imageType, image, loc, rhs, lhs->getExprLoc());
  5676. return rhs;
  5677. }
  5678. return nullptr;
  5679. }
  5680. SpirvInstruction *
  5681. SpirvEmitter::tryToAssignToMatrixElements(const Expr *lhs,
  5682. SpirvInstruction *rhs) {
  5683. const auto *lhsExpr = dyn_cast<ExtMatrixElementExpr>(lhs);
  5684. if (!lhsExpr)
  5685. return nullptr;
  5686. const Expr *baseMat = lhsExpr->getBase();
  5687. auto *base = doExpr(baseMat);
  5688. const QualType elemType = hlsl::GetHLSLMatElementType(baseMat->getType());
  5689. uint32_t rowCount = 0, colCount = 0;
  5690. hlsl::GetHLSLMatRowColCount(baseMat->getType(), rowCount, colCount);
  5691. // For each lhs element written to:
  5692. // 1. Extract the corresponding rhs element using OpCompositeExtract
  5693. // 2. Create access chain for the lhs element using OpAccessChain
  5694. // 3. Write using OpStore
  5695. const auto accessor = lhsExpr->getEncodedElementAccess();
  5696. for (uint32_t i = 0; i < accessor.Count; ++i) {
  5697. uint32_t row = 0, col = 0;
  5698. accessor.GetPosition(i, &row, &col);
  5699. llvm::SmallVector<uint32_t, 2> indices;
  5700. // If the matrix only have one row/column, we are indexing into a vector
  5701. // then. Only one index is needed for such cases.
  5702. if (rowCount > 1)
  5703. indices.push_back(row);
  5704. if (colCount > 1)
  5705. indices.push_back(col);
  5706. llvm::SmallVector<SpirvInstruction *, 2> indexInstructions(indices.size(),
  5707. nullptr);
  5708. for (uint32_t i = 0; i < indices.size(); ++i)
  5709. indexInstructions[i] = spvBuilder.getConstantInt(
  5710. astContext.IntTy, llvm::APInt(32, indices[i], true));
  5711. // If we are writing to only one element, the rhs should already be a
  5712. // scalar value.
  5713. auto *rhsElem = rhs;
  5714. if (accessor.Count > 1) {
  5715. rhsElem = spvBuilder.createCompositeExtract(elemType, rhs, {i},
  5716. rhs->getSourceLocation());
  5717. }
  5718. // If the lhs is actually a matrix of size 1x1, we don't need the access
  5719. // chain. base is already the dest pointer.
  5720. auto *lhsElemPtr = base;
  5721. if (!indexInstructions.empty()) {
  5722. assert(!base->isRValue());
  5723. // Load the element via access chain
  5724. lhsElemPtr = spvBuilder.createAccessChain(
  5725. elemType, lhsElemPtr, indexInstructions, lhs->getLocStart());
  5726. }
  5727. spvBuilder.createStore(lhsElemPtr, rhsElem, lhs->getLocStart());
  5728. }
  5729. // TODO: OK, this return value is incorrect for compound assignments, for
  5730. // which cases we should return lvalues. Should at least emit errors if
  5731. // this return value is used (can be checked via ASTContext.getParents).
  5732. return rhs;
  5733. }
  5734. SpirvInstruction *SpirvEmitter::tryToAssignToMSOutAttrsOrIndices(
  5735. const Expr *lhs, SpirvInstruction *rhs, SpirvInstruction *vecComponent,
  5736. bool noWriteBack) {
  5737. // Early exit for non-mesh shaders.
  5738. if (!spvContext.isMS())
  5739. return nullptr;
  5740. llvm::SmallVector<SpirvInstruction *, 4> indices;
  5741. bool isMSOutAttribute = false;
  5742. bool isMSOutAttributeBlock = false;
  5743. bool isMSOutIndices = false;
  5744. const Expr *base = collectArrayStructIndices(lhs, /*rawIndex*/ false,
  5745. /*rawIndices*/ nullptr, &indices,
  5746. &isMSOutAttribute);
  5747. // Expecting at least one array index - early exit.
  5748. if (!base || indices.empty())
  5749. return nullptr;
  5750. const DeclaratorDecl *varDecl = nullptr;
  5751. if (isMSOutAttribute) {
  5752. const MemberExpr *memberExpr = dyn_cast<MemberExpr>(base);
  5753. assert(memberExpr);
  5754. varDecl = cast<DeclaratorDecl>(memberExpr->getMemberDecl());
  5755. } else {
  5756. if (const auto *arg = dyn_cast<DeclRefExpr>(base)) {
  5757. if ((varDecl = dyn_cast<DeclaratorDecl>(arg->getDecl()))) {
  5758. if (varDecl->hasAttr<HLSLIndicesAttr>()) {
  5759. isMSOutIndices = true;
  5760. } else if (varDecl->hasAttr<HLSLVerticesAttr>() ||
  5761. varDecl->hasAttr<HLSLPrimitivesAttr>()) {
  5762. isMSOutAttributeBlock = true;
  5763. }
  5764. }
  5765. }
  5766. }
  5767. // Return if no out attribute or indices object found.
  5768. if (!(isMSOutAttribute || isMSOutAttributeBlock || isMSOutIndices)) {
  5769. return nullptr;
  5770. }
  5771. // For noWriteBack, return without generating write instructions.
  5772. if (noWriteBack) {
  5773. return rhs;
  5774. }
  5775. // Add vecComponent to indices.
  5776. if (vecComponent) {
  5777. indices.push_back(vecComponent);
  5778. }
  5779. if (isMSOutAttribute) {
  5780. assignToMSOutAttribute(varDecl, rhs, indices);
  5781. } else if (isMSOutIndices) {
  5782. assignToMSOutIndices(varDecl, rhs, indices);
  5783. } else {
  5784. assert(isMSOutAttributeBlock);
  5785. QualType type = varDecl->getType();
  5786. assert(isa<ConstantArrayType>(type));
  5787. type = astContext.getAsConstantArrayType(type)->getElementType();
  5788. assert(type->isStructureType());
  5789. // Extract subvalue and assign to its corresponding member attribute.
  5790. const auto *structDecl = type->getAs<RecordType>()->getDecl();
  5791. for (const auto *field : structDecl->fields()) {
  5792. const auto fieldType = field->getType();
  5793. SpirvInstruction *subValue = spvBuilder.createCompositeExtract(
  5794. fieldType, rhs, {getNumBaseClasses(type) + field->getFieldIndex()},
  5795. lhs->getLocStart());
  5796. assignToMSOutAttribute(field, subValue, indices);
  5797. }
  5798. }
  5799. // TODO: OK, this return value is incorrect for compound assignments, for
  5800. // which cases we should return lvalues. Should at least emit errors if
  5801. // this return value is used (can be checked via ASTContext.getParents).
  5802. return rhs;
  5803. }
  5804. void SpirvEmitter::assignToMSOutAttribute(
  5805. const DeclaratorDecl *decl, SpirvInstruction *value,
  5806. const llvm::SmallVector<SpirvInstruction *, 4> &indices) {
  5807. assert(spvContext.isMS() && !indices.empty());
  5808. // Extract attribute index and vecComponent (if any).
  5809. SpirvInstruction *attrIndex = indices.front();
  5810. SpirvInstruction *vecComponent = nullptr;
  5811. if (indices.size() > 1) {
  5812. vecComponent = indices.back();
  5813. }
  5814. auto semanticInfo = declIdMapper.getStageVarSemantic(decl);
  5815. assert(semanticInfo.isValid());
  5816. const auto loc = decl->getLocation();
  5817. // Special handle writes to clip/cull distance attributes.
  5818. if (!declIdMapper.glPerVertex.tryToAccess(
  5819. hlsl::DXIL::SigPointKind::MSOut, semanticInfo.semantic->GetKind(),
  5820. semanticInfo.index, attrIndex, &value, /*noWriteBack=*/false,
  5821. vecComponent, loc)) {
  5822. // All other attribute writes are handled below.
  5823. auto *varInstr = declIdMapper.getStageVarInstruction(decl);
  5824. QualType valueType = value->getAstResultType();
  5825. varInstr = spvBuilder.createAccessChain(valueType, varInstr, indices, loc);
  5826. spvBuilder.createStore(varInstr, value, loc);
  5827. }
  5828. }
  5829. void SpirvEmitter::assignToMSOutIndices(
  5830. const DeclaratorDecl *decl, SpirvInstruction *value,
  5831. const llvm::SmallVector<SpirvInstruction *, 4> &indices) {
  5832. assert(spvContext.isMS() && !indices.empty());
  5833. // Extract vertex index and vecComponent (if any).
  5834. SpirvInstruction *vertIndex = indices.front();
  5835. SpirvInstruction *vecComponent = nullptr;
  5836. if (indices.size() > 1) {
  5837. vecComponent = indices.back();
  5838. }
  5839. auto *var = declIdMapper.getStageVarInstruction(decl);
  5840. const auto *varTypeDecl = astContext.getAsConstantArrayType(decl->getType());
  5841. QualType varType = varTypeDecl->getElementType();
  5842. uint32_t numVertices = 1;
  5843. if (!isVectorType(varType, nullptr, &numVertices)) {
  5844. assert(isScalarType(varType));
  5845. }
  5846. QualType valueType = value->getAstResultType();
  5847. uint32_t numValues = 1;
  5848. if (!isVectorType(valueType, nullptr, &numValues)) {
  5849. assert(isScalarType(valueType));
  5850. }
  5851. const auto loc = decl->getLocation();
  5852. if (numVertices == 1) {
  5853. // for "point" output topology.
  5854. assert(numValues == 1);
  5855. // create accesschain for PrimitiveIndicesNV[vertIndex].
  5856. auto *ptr = spvBuilder.createAccessChain(astContext.UnsignedIntTy, var,
  5857. {vertIndex}, loc);
  5858. // finally create store for PrimitiveIndicesNV[vertIndex] = value.
  5859. spvBuilder.createStore(ptr, value, loc);
  5860. } else {
  5861. // for "line" or "triangle" output topology.
  5862. assert(numVertices == 2 || numVertices == 3);
  5863. // set baseOffset = vertIndex * numVertices.
  5864. auto *baseOffset = spvBuilder.createBinaryOp(
  5865. spv::Op::OpIMul, astContext.UnsignedIntTy, vertIndex,
  5866. spvBuilder.getConstantInt(astContext.UnsignedIntTy,
  5867. llvm::APInt(32, numVertices)),
  5868. loc);
  5869. if (vecComponent) {
  5870. // write an individual vector component of uint2 or uint3.
  5871. assert(numValues == 1);
  5872. // set baseOffset = baseOffset + vecComponent.
  5873. baseOffset =
  5874. spvBuilder.createBinaryOp(spv::Op::OpIAdd, astContext.UnsignedIntTy,
  5875. baseOffset, vecComponent, loc);
  5876. // create accesschain for PrimitiveIndicesNV[baseOffset].
  5877. auto *ptr = spvBuilder.createAccessChain(astContext.UnsignedIntTy, var,
  5878. {baseOffset}, loc);
  5879. // finally create store for PrimitiveIndicesNV[baseOffset] = value.
  5880. spvBuilder.createStore(ptr, value, loc);
  5881. } else {
  5882. // write all vector components of uint2 or uint3.
  5883. assert(numValues == numVertices);
  5884. auto *curOffset = baseOffset;
  5885. for (uint32_t i = 0; i < numValues; ++i) {
  5886. if (i != 0) {
  5887. // set curOffset = baseOffset + i.
  5888. curOffset = spvBuilder.createBinaryOp(
  5889. spv::Op::OpIAdd, astContext.UnsignedIntTy, baseOffset,
  5890. spvBuilder.getConstantInt(astContext.UnsignedIntTy,
  5891. llvm::APInt(32, i)),
  5892. loc);
  5893. }
  5894. // create accesschain for PrimitiveIndicesNV[curOffset].
  5895. auto *ptr = spvBuilder.createAccessChain(astContext.UnsignedIntTy, var,
  5896. {curOffset}, loc);
  5897. // finally create store for PrimitiveIndicesNV[curOffset] = value[i].
  5898. spvBuilder.createStore(ptr,
  5899. spvBuilder.createCompositeExtract(
  5900. astContext.UnsignedIntTy, value, {i}, loc),
  5901. loc);
  5902. }
  5903. }
  5904. }
  5905. }
  5906. SpirvInstruction *SpirvEmitter::processEachVectorInMatrix(
  5907. const Expr *matrix, SpirvInstruction *matrixVal,
  5908. llvm::function_ref<SpirvInstruction *(uint32_t, QualType,
  5909. SpirvInstruction *)>
  5910. actOnEachVector,
  5911. SourceLocation loc) {
  5912. const auto matType = matrix->getType();
  5913. assert(isMxNMatrix(matType));
  5914. const QualType vecType = getComponentVectorType(astContext, matType);
  5915. uint32_t rowCount = 0, colCount = 0;
  5916. hlsl::GetHLSLMatRowColCount(matType, rowCount, colCount);
  5917. llvm::SmallVector<SpirvInstruction *, 4> vectors;
  5918. // Extract each component vector and do operation on it
  5919. for (uint32_t i = 0; i < rowCount; ++i) {
  5920. auto *lhsVec = spvBuilder.createCompositeExtract(vecType, matrixVal, {i},
  5921. matrix->getLocStart());
  5922. vectors.push_back(actOnEachVector(i, vecType, lhsVec));
  5923. }
  5924. // Construct the result matrix
  5925. auto *val = spvBuilder.createCompositeConstruct(matType, vectors, loc);
  5926. val->setRValue();
  5927. return val;
  5928. }
  5929. void SpirvEmitter::createSpecConstant(const VarDecl *varDecl) {
  5930. class SpecConstantEnvRAII {
  5931. public:
  5932. // Creates a new instance which sets mode to true on creation,
  5933. // and resets mode to false on destruction.
  5934. SpecConstantEnvRAII(bool *mode) : modeSlot(mode) { *modeSlot = true; }
  5935. ~SpecConstantEnvRAII() { *modeSlot = false; }
  5936. private:
  5937. bool *modeSlot;
  5938. };
  5939. const QualType varType = varDecl->getType();
  5940. bool hasError = false;
  5941. if (!varDecl->isExternallyVisible()) {
  5942. emitError("specialization constant must be externally visible",
  5943. varDecl->getLocation());
  5944. hasError = true;
  5945. }
  5946. if (const auto *builtinType = varType->getAs<BuiltinType>()) {
  5947. switch (builtinType->getKind()) {
  5948. case BuiltinType::Bool:
  5949. case BuiltinType::Int:
  5950. case BuiltinType::UInt:
  5951. case BuiltinType::Float:
  5952. break;
  5953. default:
  5954. emitError("unsupported specialization constant type",
  5955. varDecl->getLocStart());
  5956. hasError = true;
  5957. }
  5958. }
  5959. const auto *init = varDecl->getInit();
  5960. if (!init) {
  5961. emitError("missing default value for specialization constant",
  5962. varDecl->getLocation());
  5963. hasError = true;
  5964. } else if (!isAcceptedSpecConstantInit(init)) {
  5965. emitError("unsupported specialization constant initializer",
  5966. init->getLocStart())
  5967. << init->getSourceRange();
  5968. hasError = true;
  5969. }
  5970. if (hasError)
  5971. return;
  5972. SpecConstantEnvRAII specConstantEnvRAII(&isSpecConstantMode);
  5973. const auto specConstant = doExpr(init);
  5974. // We are not creating a variable to hold the spec constant, instead, we
  5975. // translate the varDecl directly into the spec constant here.
  5976. spvBuilder.decorateSpecId(
  5977. specConstant, varDecl->getAttr<VKConstantIdAttr>()->getSpecConstId(),
  5978. varDecl->getLocation());
  5979. specConstant->setDebugName(varDecl->getName());
  5980. declIdMapper.registerSpecConstant(varDecl, specConstant);
  5981. }
  5982. SpirvInstruction *
  5983. SpirvEmitter::processMatrixBinaryOp(const Expr *lhs, const Expr *rhs,
  5984. const BinaryOperatorKind opcode,
  5985. SourceRange range, SourceLocation loc) {
  5986. // TODO: some code are duplicated from processBinaryOp. Try to unify them.
  5987. const auto lhsType = lhs->getType();
  5988. assert(isMxNMatrix(lhsType));
  5989. const spv::Op spvOp = translateOp(opcode, lhsType);
  5990. SpirvInstruction *rhsVal = nullptr, *lhsPtr = nullptr, *lhsVal = nullptr;
  5991. if (BinaryOperator::isCompoundAssignmentOp(opcode)) {
  5992. // Evalute rhs before lhs
  5993. rhsVal = doExpr(rhs);
  5994. lhsPtr = doExpr(lhs);
  5995. lhsVal = spvBuilder.createLoad(lhsType, lhsPtr, lhs->getLocStart());
  5996. } else {
  5997. // Evalute lhs before rhs
  5998. lhsVal = lhsPtr = doExpr(lhs);
  5999. rhsVal = doExpr(rhs);
  6000. }
  6001. switch (opcode) {
  6002. case BO_Add:
  6003. case BO_Sub:
  6004. case BO_Mul:
  6005. case BO_Div:
  6006. case BO_Rem:
  6007. case BO_AddAssign:
  6008. case BO_SubAssign:
  6009. case BO_MulAssign:
  6010. case BO_DivAssign:
  6011. case BO_RemAssign: {
  6012. const auto actOnEachVec = [this, spvOp, rhsVal, rhs,
  6013. loc](uint32_t index, QualType vecType,
  6014. SpirvInstruction *lhsVec) {
  6015. // For each vector of lhs, we need to load the corresponding vector of
  6016. // rhs and do the operation on them.
  6017. auto *rhsVec = spvBuilder.createCompositeExtract(vecType, rhsVal, {index},
  6018. rhs->getLocStart());
  6019. auto *val =
  6020. spvBuilder.createBinaryOp(spvOp, vecType, lhsVec, rhsVec, loc);
  6021. val->setRValue();
  6022. return val;
  6023. };
  6024. return processEachVectorInMatrix(lhs, lhsVal, actOnEachVec,
  6025. lhs->getLocStart());
  6026. }
  6027. case BO_Assign:
  6028. llvm_unreachable("assignment should not be handled here");
  6029. default:
  6030. break;
  6031. }
  6032. emitError("binary operator '%0' over matrix type unimplemented",
  6033. lhs->getExprLoc())
  6034. << BinaryOperator::getOpcodeStr(opcode) << range;
  6035. return nullptr;
  6036. }
  6037. const Expr *SpirvEmitter::collectArrayStructIndices(
  6038. const Expr *expr, bool rawIndex,
  6039. llvm::SmallVectorImpl<uint32_t> *rawIndices,
  6040. llvm::SmallVectorImpl<SpirvInstruction *> *indices,
  6041. bool *isMSOutAttribute) {
  6042. assert((rawIndex && rawIndices) || (!rawIndex && indices));
  6043. if (const auto *indexing = dyn_cast<MemberExpr>(expr)) {
  6044. // First check whether this is referring to a static member. If it is, we
  6045. // create a DeclRefExpr for it.
  6046. if (auto *varDecl = dyn_cast<VarDecl>(indexing->getMemberDecl()))
  6047. if (varDecl->isStaticDataMember())
  6048. return DeclRefExpr::Create(
  6049. astContext, NestedNameSpecifierLoc(), SourceLocation(), varDecl,
  6050. /*RefersToEnclosingVariableOrCapture=*/false, SourceLocation(),
  6051. varDecl->getType(), VK_LValue);
  6052. const Expr *base = collectArrayStructIndices(
  6053. indexing->getBase(), rawIndex, rawIndices, indices, isMSOutAttribute);
  6054. if (isMSOutAttribute && base) {
  6055. if (const auto *arg = dyn_cast<DeclRefExpr>(base)) {
  6056. if (const auto *varDecl = dyn_cast<VarDecl>(arg->getDecl())) {
  6057. if (varDecl->hasAttr<HLSLVerticesAttr>() ||
  6058. varDecl->hasAttr<HLSLPrimitivesAttr>()) {
  6059. assert(spvContext.isMS());
  6060. *isMSOutAttribute = true;
  6061. return expr;
  6062. }
  6063. }
  6064. }
  6065. }
  6066. // Append the index of the current level
  6067. const auto *fieldDecl = cast<FieldDecl>(indexing->getMemberDecl());
  6068. assert(fieldDecl);
  6069. // If we are accessing a derived struct, we need to account for the number
  6070. // of base structs, since they are placed as fields at the beginning of the
  6071. // derived struct.
  6072. auto baseType = indexing->getBase()->getType();
  6073. if (baseType->isPointerType()) {
  6074. baseType = baseType->getPointeeType();
  6075. }
  6076. const uint32_t index =
  6077. getNumBaseClasses(baseType) + fieldDecl->getFieldIndex();
  6078. if (rawIndex) {
  6079. rawIndices->push_back(index);
  6080. } else {
  6081. indices->push_back(spvBuilder.getConstantInt(
  6082. astContext.IntTy, llvm::APInt(32, index, true)));
  6083. }
  6084. return base;
  6085. }
  6086. if (const auto *indexing = dyn_cast<ArraySubscriptExpr>(expr)) {
  6087. if (rawIndex)
  6088. return nullptr; // TODO: handle constant array index
  6089. // The base of an ArraySubscriptExpr has a wrapping LValueToRValue implicit
  6090. // cast. We need to ingore it to avoid creating OpLoad.
  6091. const Expr *thisBase = indexing->getBase()->IgnoreParenLValueCasts();
  6092. const Expr *base = collectArrayStructIndices(thisBase, rawIndex, rawIndices,
  6093. indices, isMSOutAttribute);
  6094. // The index into an array must be an integer number.
  6095. const auto *idxExpr = indexing->getIdx();
  6096. const auto idxExprType = idxExpr->getType();
  6097. SpirvInstruction *thisIndex = doExpr(idxExpr);
  6098. if (!idxExprType->isIntegerType() || idxExprType->isBooleanType()) {
  6099. thisIndex = castToInt(thisIndex, idxExprType, astContext.UnsignedIntTy,
  6100. idxExpr->getExprLoc());
  6101. }
  6102. indices->push_back(thisIndex);
  6103. return base;
  6104. }
  6105. if (const auto *indexing = dyn_cast<CXXOperatorCallExpr>(expr))
  6106. if (indexing->getOperator() == OverloadedOperatorKind::OO_Subscript) {
  6107. if (rawIndex)
  6108. return nullptr; // TODO: handle constant array index
  6109. // If this is indexing into resources, we need specific OpImage*
  6110. // instructions for accessing. Return directly to avoid further building
  6111. // up the access chain.
  6112. if (isBufferTextureIndexing(indexing))
  6113. return indexing;
  6114. const Expr *thisBase =
  6115. indexing->getArg(0)->IgnoreParenNoopCasts(astContext);
  6116. const auto thisBaseType = thisBase->getType();
  6117. const Expr *base = collectArrayStructIndices(
  6118. thisBase, rawIndex, rawIndices, indices, isMSOutAttribute);
  6119. if (thisBaseType != base->getType() &&
  6120. isAKindOfStructuredOrByteBuffer(thisBaseType)) {
  6121. // The immediate base is a kind of structured or byte buffer. It should
  6122. // be an alias variable. Break the normal index collecting chain.
  6123. // Return the immediate base as the base so that we can apply other
  6124. // hacks for legalization over it.
  6125. //
  6126. // Note: legalization specific code
  6127. indices->clear();
  6128. base = thisBase;
  6129. }
  6130. // If the base is a StructureType, we need to push an addtional index 0
  6131. // here. This is because we created an additional OpTypeRuntimeArray
  6132. // in the structure.
  6133. if (isStructuredBuffer(thisBaseType))
  6134. indices->push_back(
  6135. spvBuilder.getConstantInt(astContext.IntTy, llvm::APInt(32, 0)));
  6136. if ((hlsl::IsHLSLVecType(thisBaseType) &&
  6137. (hlsl::GetHLSLVecSize(thisBaseType) == 1)) ||
  6138. is1x1Matrix(thisBaseType) || is1xNMatrix(thisBaseType)) {
  6139. // If this is a size-1 vector or 1xN matrix, ignore the index.
  6140. } else {
  6141. indices->push_back(doExpr(indexing->getArg(1)));
  6142. }
  6143. return base;
  6144. }
  6145. {
  6146. const Expr *index = nullptr;
  6147. // TODO: the following is duplicating the logic in doCXXMemberCallExpr.
  6148. if (const auto *object = isStructuredBufferLoad(expr, &index)) {
  6149. if (rawIndex)
  6150. return nullptr; // TODO: handle constant array index
  6151. // For object.Load(index), there should be no more indexing into the
  6152. // object.
  6153. indices->push_back(
  6154. spvBuilder.getConstantInt(astContext.IntTy, llvm::APInt(32, 0)));
  6155. indices->push_back(doExpr(index));
  6156. return object;
  6157. }
  6158. }
  6159. {
  6160. // Indexing into ConstantBuffers and TextureBuffers involves an additional
  6161. // FlatConversion node which casts the handle to the underlying structure
  6162. // type. We can look past the FlatConversion to continue to collect indices.
  6163. // For example: MyConstantBufferArray[0].structMember1
  6164. // `-MemberExpr .structMember1
  6165. // `-ImplicitCastExpr 'const T' lvalue <FlatConversion>
  6166. // `-ArraySubscriptExpr 'ConstantBuffer<T>':'ConstantBuffer<T>' lvalue
  6167. if (auto *castExpr = dyn_cast<ImplicitCastExpr>(expr)) {
  6168. if (castExpr->getCastKind() == CK_FlatConversion) {
  6169. const auto *subExpr = castExpr->getSubExpr();
  6170. const QualType subExprType = subExpr->getType();
  6171. if (isConstantTextureBuffer(subExprType)) {
  6172. return collectArrayStructIndices(subExpr, rawIndex, rawIndices,
  6173. indices, isMSOutAttribute);
  6174. }
  6175. }
  6176. }
  6177. }
  6178. // This the deepest we can go. No more array or struct indexing.
  6179. return expr;
  6180. }
  6181. SpirvInstruction *SpirvEmitter::turnIntoElementPtr(
  6182. QualType baseType, SpirvInstruction *base, QualType elemType,
  6183. const llvm::SmallVector<SpirvInstruction *, 4> &indices,
  6184. SourceLocation loc) {
  6185. // If this is a rvalue, we need a temporary object to hold it
  6186. // so that we can get access chain from it.
  6187. const bool needTempVar = base->isRValue();
  6188. SpirvInstruction *accessChainBase = base;
  6189. if (needTempVar) {
  6190. auto varName = getAstTypeName(baseType);
  6191. const auto var = createTemporaryVar(baseType, varName, base, loc);
  6192. var->setLayoutRule(SpirvLayoutRule::Void);
  6193. var->setStorageClass(spv::StorageClass::Function);
  6194. var->setContainsAliasComponent(base->containsAliasComponent());
  6195. accessChainBase = var;
  6196. }
  6197. base = spvBuilder.createAccessChain(elemType, accessChainBase, indices, loc);
  6198. // Okay, this part seems weird, but it is intended:
  6199. // If the base is originally a rvalue, the whole AST involving the base
  6200. // is consistently set up to handle rvalues. By copying the base into
  6201. // a temporary variable and grab an access chain from it, we are breaking
  6202. // the consistency by turning the base from rvalue into lvalue. Keep in
  6203. // mind that there will be no LValueToRValue casts in the AST for us
  6204. // to rely on to load the access chain if a rvalue is expected. Therefore,
  6205. // we must do the load here. Otherwise, it's up to the consumer of this
  6206. // access chain to do the load, and that can be everywhere.
  6207. if (needTempVar) {
  6208. base = spvBuilder.createLoad(elemType, base, loc);
  6209. }
  6210. return base;
  6211. }
  6212. SpirvInstruction *SpirvEmitter::castToBool(SpirvInstruction *fromVal,
  6213. QualType fromType,
  6214. QualType toBoolType,
  6215. SourceLocation loc) {
  6216. if (isSameType(astContext, fromType, toBoolType))
  6217. return fromVal;
  6218. { // Special case handling for converting to a matrix of booleans.
  6219. QualType elemType = {};
  6220. uint32_t rowCount = 0, colCount = 0;
  6221. if (isMxNMatrix(fromType, &elemType, &rowCount, &colCount)) {
  6222. const auto fromRowQualType =
  6223. astContext.getExtVectorType(elemType, colCount);
  6224. const auto toBoolRowQualType =
  6225. astContext.getExtVectorType(astContext.BoolTy, colCount);
  6226. llvm::SmallVector<SpirvInstruction *, 4> rows;
  6227. for (uint32_t i = 0; i < rowCount; ++i) {
  6228. auto *row = spvBuilder.createCompositeExtract(fromRowQualType, fromVal,
  6229. {i}, loc);
  6230. rows.push_back(
  6231. castToBool(row, fromRowQualType, toBoolRowQualType, loc));
  6232. }
  6233. return spvBuilder.createCompositeConstruct(toBoolType, rows, loc);
  6234. }
  6235. }
  6236. // Converting to bool means comparing with value zero.
  6237. const spv::Op spvOp = translateOp(BO_NE, fromType);
  6238. auto *zeroVal = getValueZero(fromType);
  6239. return spvBuilder.createBinaryOp(spvOp, toBoolType, fromVal, zeroVal, loc);
  6240. }
  6241. SpirvInstruction *SpirvEmitter::castToInt(SpirvInstruction *fromVal,
  6242. QualType fromType, QualType toIntType,
  6243. SourceLocation srcLoc) {
  6244. if (isEnumType(fromType))
  6245. fromType = astContext.IntTy;
  6246. if (isSameType(astContext, fromType, toIntType))
  6247. return fromVal;
  6248. if (isBoolOrVecOfBoolType(fromType)) {
  6249. auto *one = getValueOne(toIntType);
  6250. auto *zero = getValueZero(toIntType);
  6251. return spvBuilder.createSelect(toIntType, fromVal, one, zero, srcLoc);
  6252. }
  6253. if (isSintOrVecOfSintType(fromType) || isUintOrVecOfUintType(fromType)) {
  6254. // First convert the source to the bitwidth of the destination if necessary.
  6255. QualType convertedType = {};
  6256. fromVal =
  6257. convertBitwidth(fromVal, srcLoc, fromType, toIntType, &convertedType);
  6258. // If bitwidth conversion was the only thing we needed to do, we're done.
  6259. if (isSameScalarOrVecType(convertedType, toIntType))
  6260. return fromVal;
  6261. return spvBuilder.createUnaryOp(spv::Op::OpBitcast, toIntType, fromVal,
  6262. srcLoc);
  6263. }
  6264. if (isFloatOrVecOfFloatType(fromType)) {
  6265. // First convert the source to the bitwidth of the destination if necessary.
  6266. fromVal = convertBitwidth(fromVal, srcLoc, fromType, toIntType);
  6267. if (isSintOrVecOfSintType(toIntType)) {
  6268. return spvBuilder.createUnaryOp(spv::Op::OpConvertFToS, toIntType,
  6269. fromVal, srcLoc);
  6270. } else if (isUintOrVecOfUintType(toIntType)) {
  6271. return spvBuilder.createUnaryOp(spv::Op::OpConvertFToU, toIntType,
  6272. fromVal, srcLoc);
  6273. } else {
  6274. emitError("casting from floating point to integer unimplemented", srcLoc);
  6275. }
  6276. }
  6277. {
  6278. QualType elemType = {};
  6279. uint32_t numRows = 0, numCols = 0;
  6280. if (isMxNMatrix(fromType, &elemType, &numRows, &numCols)) {
  6281. // The source matrix and the target matrix must have the same dimensions.
  6282. QualType toElemType = {};
  6283. uint32_t toNumRows = 0, toNumCols = 0;
  6284. const bool isMat =
  6285. isMxNMatrix(toIntType, &toElemType, &toNumRows, &toNumCols);
  6286. assert(isMat && numRows == toNumRows && numCols == toNumCols);
  6287. (void)isMat;
  6288. (void)toNumRows;
  6289. (void)toNumCols;
  6290. // Casting to a matrix of integers: Cast each row and construct a
  6291. // composite.
  6292. llvm::SmallVector<SpirvInstruction *, 4> castedRows;
  6293. const QualType vecType = getComponentVectorType(astContext, fromType);
  6294. const auto fromVecQualType =
  6295. astContext.getExtVectorType(elemType, numCols);
  6296. const auto toIntVecQualType =
  6297. astContext.getExtVectorType(toElemType, numCols);
  6298. for (uint32_t row = 0; row < numRows; ++row) {
  6299. auto *rowId =
  6300. spvBuilder.createCompositeExtract(vecType, fromVal, {row}, srcLoc);
  6301. castedRows.push_back(
  6302. castToInt(rowId, fromVecQualType, toIntVecQualType, srcLoc));
  6303. }
  6304. return spvBuilder.createCompositeConstruct(toIntType, castedRows, srcLoc);
  6305. }
  6306. }
  6307. return nullptr;
  6308. }
  6309. SpirvInstruction *SpirvEmitter::convertBitwidth(SpirvInstruction *fromVal,
  6310. SourceLocation loc,
  6311. QualType fromType,
  6312. QualType toType,
  6313. QualType *resultType) {
  6314. // At the moment, we will not make bitwidth conversions to/from literal int
  6315. // and literal float types because they do not represent the intended SPIR-V
  6316. // bitwidth.
  6317. if (isLitTypeOrVecOfLitType(fromType) || isLitTypeOrVecOfLitType(toType))
  6318. return fromVal;
  6319. const auto fromBitwidth = getElementSpirvBitwidth(
  6320. astContext, fromType, spirvOptions.enable16BitTypes);
  6321. const auto toBitwidth = getElementSpirvBitwidth(
  6322. astContext, toType, spirvOptions.enable16BitTypes);
  6323. if (fromBitwidth == toBitwidth) {
  6324. if (resultType)
  6325. *resultType = fromType;
  6326. return fromVal;
  6327. }
  6328. // We want the 'fromType' with the 'toBitwidth'.
  6329. const QualType targetType =
  6330. getTypeWithCustomBitwidth(astContext, fromType, toBitwidth);
  6331. if (resultType)
  6332. *resultType = targetType;
  6333. if (isFloatOrVecOfFloatType(fromType))
  6334. return spvBuilder.createUnaryOp(spv::Op::OpFConvert, targetType, fromVal,
  6335. loc);
  6336. if (isSintOrVecOfSintType(fromType))
  6337. return spvBuilder.createUnaryOp(spv::Op::OpSConvert, targetType, fromVal,
  6338. loc);
  6339. if (isUintOrVecOfUintType(fromType))
  6340. return spvBuilder.createUnaryOp(spv::Op::OpUConvert, targetType, fromVal,
  6341. loc);
  6342. llvm_unreachable("invalid type passed to convertBitwidth");
  6343. }
  6344. SpirvInstruction *SpirvEmitter::castToFloat(SpirvInstruction *fromVal,
  6345. QualType fromType,
  6346. QualType toFloatType,
  6347. SourceLocation srcLoc) {
  6348. if (isSameType(astContext, fromType, toFloatType))
  6349. return fromVal;
  6350. if (isBoolOrVecOfBoolType(fromType)) {
  6351. auto *one = getValueOne(toFloatType);
  6352. auto *zero = getValueZero(toFloatType);
  6353. return spvBuilder.createSelect(toFloatType, fromVal, one, zero, srcLoc);
  6354. }
  6355. if (isSintOrVecOfSintType(fromType)) {
  6356. // First convert the source to the bitwidth of the destination if necessary.
  6357. fromVal = convertBitwidth(fromVal, srcLoc, fromType, toFloatType);
  6358. return spvBuilder.createUnaryOp(spv::Op::OpConvertSToF, toFloatType,
  6359. fromVal, srcLoc);
  6360. }
  6361. if (isUintOrVecOfUintType(fromType)) {
  6362. // First convert the source to the bitwidth of the destination if necessary.
  6363. fromVal = convertBitwidth(fromVal, srcLoc, fromType, toFloatType);
  6364. return spvBuilder.createUnaryOp(spv::Op::OpConvertUToF, toFloatType,
  6365. fromVal, srcLoc);
  6366. }
  6367. if (isFloatOrVecOfFloatType(fromType)) {
  6368. // This is the case of float to float conversion with different bitwidths.
  6369. return convertBitwidth(fromVal, srcLoc, fromType, toFloatType);
  6370. }
  6371. // Casting matrix types
  6372. {
  6373. QualType elemType = {};
  6374. uint32_t numRows = 0, numCols = 0;
  6375. if (isMxNMatrix(fromType, &elemType, &numRows, &numCols)) {
  6376. // The source matrix and the target matrix must have the same dimensions.
  6377. QualType toElemType = {};
  6378. uint32_t toNumRows = 0, toNumCols = 0;
  6379. const auto isMat =
  6380. isMxNMatrix(toFloatType, &toElemType, &toNumRows, &toNumCols);
  6381. assert(isMat && numRows == toNumRows && numCols == toNumCols);
  6382. (void)isMat;
  6383. (void)toNumRows;
  6384. (void)toNumCols;
  6385. // Casting to a matrix of floats: Cast each row and construct a
  6386. // composite.
  6387. llvm::SmallVector<SpirvInstruction *, 4> castedRows;
  6388. const QualType vecType = getComponentVectorType(astContext, fromType);
  6389. const auto fromVecQualType =
  6390. astContext.getExtVectorType(elemType, numCols);
  6391. const auto toIntVecQualType =
  6392. astContext.getExtVectorType(toElemType, numCols);
  6393. for (uint32_t row = 0; row < numRows; ++row) {
  6394. auto *rowId =
  6395. spvBuilder.createCompositeExtract(vecType, fromVal, {row}, srcLoc);
  6396. castedRows.push_back(
  6397. castToFloat(rowId, fromVecQualType, toIntVecQualType, srcLoc));
  6398. }
  6399. return spvBuilder.createCompositeConstruct(toFloatType, castedRows,
  6400. srcLoc);
  6401. }
  6402. }
  6403. emitError("casting to floating point unimplemented", srcLoc);
  6404. return nullptr;
  6405. }
  6406. SpirvInstruction *
  6407. SpirvEmitter::processIntrinsicCallExpr(const CallExpr *callExpr) {
  6408. const FunctionDecl *callee = callExpr->getDirectCallee();
  6409. const SourceLocation srcLoc = callExpr->getExprLoc();
  6410. assert(hlsl::IsIntrinsicOp(callee) &&
  6411. "doIntrinsicCallExpr was called for a non-intrinsic function.");
  6412. const bool isFloatType = isFloatOrVecMatOfFloatType(callExpr->getType());
  6413. const bool isSintType = isSintOrVecMatOfSintType(callExpr->getType());
  6414. // Figure out which intrinsic function to translate.
  6415. llvm::StringRef group;
  6416. uint32_t opcode = static_cast<uint32_t>(hlsl::IntrinsicOp::Num_Intrinsics);
  6417. hlsl::GetIntrinsicOp(callee, opcode, group);
  6418. GLSLstd450 glslOpcode = GLSLstd450Bad;
  6419. SpirvInstruction *retVal = nullptr;
  6420. #define INTRINSIC_SPIRV_OP_CASE(intrinsicOp, spirvOp, doEachVec) \
  6421. case hlsl::IntrinsicOp::IOP_##intrinsicOp: { \
  6422. retVal = processIntrinsicUsingSpirvInst(callExpr, spv::Op::Op##spirvOp, \
  6423. doEachVec); \
  6424. } break
  6425. #define INTRINSIC_OP_CASE(intrinsicOp, glslOp, doEachVec) \
  6426. case hlsl::IntrinsicOp::IOP_##intrinsicOp: { \
  6427. glslOpcode = GLSLstd450::GLSLstd450##glslOp; \
  6428. retVal = processIntrinsicUsingGLSLInst(callExpr, glslOpcode, doEachVec, \
  6429. srcLoc); \
  6430. } break
  6431. #define INTRINSIC_OP_CASE_INT_FLOAT(intrinsicOp, glslIntOp, glslFloatOp, \
  6432. doEachVec) \
  6433. case hlsl::IntrinsicOp::IOP_##intrinsicOp: { \
  6434. glslOpcode = isFloatType ? GLSLstd450::GLSLstd450##glslFloatOp \
  6435. : GLSLstd450::GLSLstd450##glslIntOp; \
  6436. retVal = processIntrinsicUsingGLSLInst(callExpr, glslOpcode, doEachVec, \
  6437. srcLoc); \
  6438. } break
  6439. #define INTRINSIC_OP_CASE_SINT_UINT(intrinsicOp, glslSintOp, glslUintOp, \
  6440. doEachVec) \
  6441. case hlsl::IntrinsicOp::IOP_##intrinsicOp: { \
  6442. glslOpcode = isSintType ? GLSLstd450::GLSLstd450##glslSintOp \
  6443. : GLSLstd450::GLSLstd450##glslUintOp; \
  6444. retVal = processIntrinsicUsingGLSLInst(callExpr, glslOpcode, doEachVec, \
  6445. srcLoc); \
  6446. } break
  6447. #define INTRINSIC_OP_CASE_SINT_UINT_FLOAT(intrinsicOp, glslSintOp, glslUintOp, \
  6448. glslFloatOp, doEachVec) \
  6449. case hlsl::IntrinsicOp::IOP_##intrinsicOp: { \
  6450. glslOpcode = isFloatType \
  6451. ? GLSLstd450::GLSLstd450##glslFloatOp \
  6452. : isSintType ? GLSLstd450::GLSLstd450##glslSintOp \
  6453. : GLSLstd450::GLSLstd450##glslUintOp; \
  6454. retVal = processIntrinsicUsingGLSLInst(callExpr, glslOpcode, doEachVec, \
  6455. srcLoc); \
  6456. } break
  6457. switch (const auto hlslOpcode = static_cast<hlsl::IntrinsicOp>(opcode)) {
  6458. case hlsl::IntrinsicOp::IOP_InterlockedAdd:
  6459. case hlsl::IntrinsicOp::IOP_InterlockedAnd:
  6460. case hlsl::IntrinsicOp::IOP_InterlockedMax:
  6461. case hlsl::IntrinsicOp::IOP_InterlockedUMax:
  6462. case hlsl::IntrinsicOp::IOP_InterlockedMin:
  6463. case hlsl::IntrinsicOp::IOP_InterlockedUMin:
  6464. case hlsl::IntrinsicOp::IOP_InterlockedOr:
  6465. case hlsl::IntrinsicOp::IOP_InterlockedXor:
  6466. case hlsl::IntrinsicOp::IOP_InterlockedExchange:
  6467. case hlsl::IntrinsicOp::IOP_InterlockedCompareStore:
  6468. case hlsl::IntrinsicOp::IOP_InterlockedCompareExchange:
  6469. retVal = processIntrinsicInterlockedMethod(callExpr, hlslOpcode);
  6470. break;
  6471. case hlsl::IntrinsicOp::IOP_NonUniformResourceIndex:
  6472. retVal = processIntrinsicNonUniformResourceIndex(callExpr);
  6473. break;
  6474. case hlsl::IntrinsicOp::IOP_tex1D:
  6475. case hlsl::IntrinsicOp::IOP_tex1Dbias:
  6476. case hlsl::IntrinsicOp::IOP_tex1Dgrad:
  6477. case hlsl::IntrinsicOp::IOP_tex1Dlod:
  6478. case hlsl::IntrinsicOp::IOP_tex1Dproj:
  6479. case hlsl::IntrinsicOp::IOP_tex2D:
  6480. case hlsl::IntrinsicOp::IOP_tex2Dbias:
  6481. case hlsl::IntrinsicOp::IOP_tex2Dgrad:
  6482. case hlsl::IntrinsicOp::IOP_tex2Dlod:
  6483. case hlsl::IntrinsicOp::IOP_tex2Dproj:
  6484. case hlsl::IntrinsicOp::IOP_tex3D:
  6485. case hlsl::IntrinsicOp::IOP_tex3Dbias:
  6486. case hlsl::IntrinsicOp::IOP_tex3Dgrad:
  6487. case hlsl::IntrinsicOp::IOP_tex3Dlod:
  6488. case hlsl::IntrinsicOp::IOP_tex3Dproj:
  6489. case hlsl::IntrinsicOp::IOP_texCUBE:
  6490. case hlsl::IntrinsicOp::IOP_texCUBEbias:
  6491. case hlsl::IntrinsicOp::IOP_texCUBEgrad:
  6492. case hlsl::IntrinsicOp::IOP_texCUBElod:
  6493. case hlsl::IntrinsicOp::IOP_texCUBEproj: {
  6494. emitError("deprecated %0 intrinsic function will not be supported", srcLoc)
  6495. << callee->getName();
  6496. return nullptr;
  6497. }
  6498. case hlsl::IntrinsicOp::IOP_dot:
  6499. retVal = processIntrinsicDot(callExpr);
  6500. break;
  6501. case hlsl::IntrinsicOp::IOP_GroupMemoryBarrier:
  6502. retVal = processIntrinsicMemoryBarrier(callExpr,
  6503. /*isDevice*/ false,
  6504. /*groupSync*/ false,
  6505. /*isAllBarrier*/ false);
  6506. break;
  6507. case hlsl::IntrinsicOp::IOP_GroupMemoryBarrierWithGroupSync:
  6508. retVal = processIntrinsicMemoryBarrier(callExpr,
  6509. /*isDevice*/ false,
  6510. /*groupSync*/ true,
  6511. /*isAllBarrier*/ false);
  6512. break;
  6513. case hlsl::IntrinsicOp::IOP_DeviceMemoryBarrier:
  6514. retVal = processIntrinsicMemoryBarrier(callExpr, /*isDevice*/ true,
  6515. /*groupSync*/ false,
  6516. /*isAllBarrier*/ false);
  6517. break;
  6518. case hlsl::IntrinsicOp::IOP_DeviceMemoryBarrierWithGroupSync:
  6519. retVal = processIntrinsicMemoryBarrier(callExpr, /*isDevice*/ true,
  6520. /*groupSync*/ true,
  6521. /*isAllBarrier*/ false);
  6522. break;
  6523. case hlsl::IntrinsicOp::IOP_AllMemoryBarrier:
  6524. retVal = processIntrinsicMemoryBarrier(callExpr, /*isDevice*/ true,
  6525. /*groupSync*/ false,
  6526. /*isAllBarrier*/ true);
  6527. break;
  6528. case hlsl::IntrinsicOp::IOP_AllMemoryBarrierWithGroupSync:
  6529. retVal = processIntrinsicMemoryBarrier(callExpr, /*isDevice*/ true,
  6530. /*groupSync*/ true,
  6531. /*isAllBarrier*/ true);
  6532. break;
  6533. case hlsl::IntrinsicOp::IOP_CheckAccessFullyMapped:
  6534. retVal = spvBuilder.createImageSparseTexelsResident(
  6535. doExpr(callExpr->getArg(0)), srcLoc);
  6536. break;
  6537. case hlsl::IntrinsicOp::IOP_mul:
  6538. case hlsl::IntrinsicOp::IOP_umul:
  6539. retVal = processIntrinsicMul(callExpr);
  6540. break;
  6541. case hlsl::IntrinsicOp::IOP_all:
  6542. retVal = processIntrinsicAllOrAny(callExpr, spv::Op::OpAll);
  6543. break;
  6544. case hlsl::IntrinsicOp::IOP_any:
  6545. retVal = processIntrinsicAllOrAny(callExpr, spv::Op::OpAny);
  6546. break;
  6547. case hlsl::IntrinsicOp::IOP_asdouble:
  6548. case hlsl::IntrinsicOp::IOP_asfloat:
  6549. case hlsl::IntrinsicOp::IOP_asint:
  6550. case hlsl::IntrinsicOp::IOP_asuint:
  6551. retVal = processIntrinsicAsType(callExpr);
  6552. break;
  6553. case hlsl::IntrinsicOp::IOP_clip:
  6554. retVal = processIntrinsicClip(callExpr);
  6555. break;
  6556. case hlsl::IntrinsicOp::IOP_dst:
  6557. retVal = processIntrinsicDst(callExpr);
  6558. break;
  6559. case hlsl::IntrinsicOp::IOP_clamp:
  6560. case hlsl::IntrinsicOp::IOP_uclamp:
  6561. retVal = processIntrinsicClamp(callExpr);
  6562. break;
  6563. case hlsl::IntrinsicOp::IOP_frexp:
  6564. retVal = processIntrinsicFrexp(callExpr);
  6565. break;
  6566. case hlsl::IntrinsicOp::IOP_ldexp:
  6567. retVal = processIntrinsicLdexp(callExpr);
  6568. break;
  6569. case hlsl::IntrinsicOp::IOP_lit:
  6570. retVal = processIntrinsicLit(callExpr);
  6571. break;
  6572. case hlsl::IntrinsicOp::IOP_mad:
  6573. case hlsl::IntrinsicOp::IOP_umad:
  6574. retVal = processIntrinsicMad(callExpr);
  6575. break;
  6576. case hlsl::IntrinsicOp::IOP_modf:
  6577. retVal = processIntrinsicModf(callExpr);
  6578. break;
  6579. case hlsl::IntrinsicOp::IOP_msad4:
  6580. retVal = processIntrinsicMsad4(callExpr);
  6581. break;
  6582. case hlsl::IntrinsicOp::IOP_printf:
  6583. retVal = processIntrinsicPrintf(callExpr);
  6584. break;
  6585. case hlsl::IntrinsicOp::IOP_sign: {
  6586. if (isFloatOrVecMatOfFloatType(callExpr->getArg(0)->getType()))
  6587. retVal = processIntrinsicFloatSign(callExpr);
  6588. else
  6589. retVal =
  6590. processIntrinsicUsingGLSLInst(callExpr, GLSLstd450::GLSLstd450SSign,
  6591. /*actPerRowForMatrices*/ true, srcLoc);
  6592. } break;
  6593. case hlsl::IntrinsicOp::IOP_D3DCOLORtoUBYTE4:
  6594. retVal = processD3DCOLORtoUBYTE4(callExpr);
  6595. break;
  6596. case hlsl::IntrinsicOp::IOP_isfinite:
  6597. retVal = processIntrinsicIsFinite(callExpr);
  6598. break;
  6599. case hlsl::IntrinsicOp::IOP_sincos:
  6600. retVal = processIntrinsicSinCos(callExpr);
  6601. break;
  6602. case hlsl::IntrinsicOp::IOP_rcp:
  6603. retVal = processIntrinsicRcp(callExpr);
  6604. break;
  6605. case hlsl::IntrinsicOp::IOP_VkReadClock:
  6606. retVal = processIntrinsicReadClock(callExpr);
  6607. break;
  6608. case hlsl::IntrinsicOp::IOP_saturate:
  6609. retVal = processIntrinsicSaturate(callExpr);
  6610. break;
  6611. case hlsl::IntrinsicOp::IOP_log10:
  6612. retVal = processIntrinsicLog10(callExpr);
  6613. break;
  6614. case hlsl::IntrinsicOp::IOP_f16tof32:
  6615. retVal = processIntrinsicF16ToF32(callExpr);
  6616. break;
  6617. case hlsl::IntrinsicOp::IOP_f32tof16:
  6618. retVal = processIntrinsicF32ToF16(callExpr);
  6619. break;
  6620. case hlsl::IntrinsicOp::IOP_WaveGetLaneCount: {
  6621. featureManager.requestTargetEnv(SPV_ENV_VULKAN_1_1, "WaveGetLaneCount",
  6622. srcLoc);
  6623. const QualType retType = callExpr->getCallReturnType(astContext);
  6624. auto *var =
  6625. declIdMapper.getBuiltinVar(spv::BuiltIn::SubgroupSize, retType, srcLoc);
  6626. retVal = spvBuilder.createLoad(retType, var, srcLoc);
  6627. } break;
  6628. case hlsl::IntrinsicOp::IOP_WaveGetLaneIndex: {
  6629. featureManager.requestTargetEnv(SPV_ENV_VULKAN_1_1, "WaveGetLaneIndex",
  6630. srcLoc);
  6631. const QualType retType = callExpr->getCallReturnType(astContext);
  6632. auto *var = declIdMapper.getBuiltinVar(
  6633. spv::BuiltIn::SubgroupLocalInvocationId, retType, srcLoc);
  6634. retVal = spvBuilder.createLoad(retType, var, srcLoc);
  6635. } break;
  6636. case hlsl::IntrinsicOp::IOP_WaveIsFirstLane:
  6637. retVal = processWaveQuery(callExpr, spv::Op::OpGroupNonUniformElect);
  6638. break;
  6639. case hlsl::IntrinsicOp::IOP_WaveActiveAllTrue:
  6640. retVal = processWaveVote(callExpr, spv::Op::OpGroupNonUniformAll);
  6641. break;
  6642. case hlsl::IntrinsicOp::IOP_WaveActiveAnyTrue:
  6643. retVal = processWaveVote(callExpr, spv::Op::OpGroupNonUniformAny);
  6644. break;
  6645. case hlsl::IntrinsicOp::IOP_WaveActiveBallot:
  6646. retVal = processWaveVote(callExpr, spv::Op::OpGroupNonUniformBallot);
  6647. break;
  6648. case hlsl::IntrinsicOp::IOP_WaveActiveAllEqual:
  6649. retVal = processWaveVote(callExpr, spv::Op::OpGroupNonUniformAllEqual);
  6650. break;
  6651. case hlsl::IntrinsicOp::IOP_WaveActiveCountBits:
  6652. retVal = processWaveCountBits(callExpr, spv::GroupOperation::Reduce);
  6653. break;
  6654. case hlsl::IntrinsicOp::IOP_WaveActiveUSum:
  6655. case hlsl::IntrinsicOp::IOP_WaveActiveSum:
  6656. case hlsl::IntrinsicOp::IOP_WaveActiveUProduct:
  6657. case hlsl::IntrinsicOp::IOP_WaveActiveProduct:
  6658. case hlsl::IntrinsicOp::IOP_WaveActiveUMax:
  6659. case hlsl::IntrinsicOp::IOP_WaveActiveMax:
  6660. case hlsl::IntrinsicOp::IOP_WaveActiveUMin:
  6661. case hlsl::IntrinsicOp::IOP_WaveActiveMin:
  6662. case hlsl::IntrinsicOp::IOP_WaveActiveBitAnd:
  6663. case hlsl::IntrinsicOp::IOP_WaveActiveBitOr:
  6664. case hlsl::IntrinsicOp::IOP_WaveActiveBitXor: {
  6665. const auto retType = callExpr->getCallReturnType(astContext);
  6666. retVal = processWaveReductionOrPrefix(
  6667. callExpr, translateWaveOp(hlslOpcode, retType, srcLoc),
  6668. spv::GroupOperation::Reduce);
  6669. } break;
  6670. case hlsl::IntrinsicOp::IOP_WavePrefixUSum:
  6671. case hlsl::IntrinsicOp::IOP_WavePrefixSum:
  6672. case hlsl::IntrinsicOp::IOP_WavePrefixUProduct:
  6673. case hlsl::IntrinsicOp::IOP_WavePrefixProduct: {
  6674. const auto retType = callExpr->getCallReturnType(astContext);
  6675. retVal = processWaveReductionOrPrefix(
  6676. callExpr, translateWaveOp(hlslOpcode, retType, srcLoc),
  6677. spv::GroupOperation::ExclusiveScan);
  6678. } break;
  6679. case hlsl::IntrinsicOp::IOP_WavePrefixCountBits:
  6680. retVal = processWaveCountBits(callExpr, spv::GroupOperation::ExclusiveScan);
  6681. break;
  6682. case hlsl::IntrinsicOp::IOP_WaveReadLaneAt:
  6683. case hlsl::IntrinsicOp::IOP_WaveReadLaneFirst:
  6684. retVal = processWaveBroadcast(callExpr);
  6685. break;
  6686. case hlsl::IntrinsicOp::IOP_QuadReadAcrossX:
  6687. case hlsl::IntrinsicOp::IOP_QuadReadAcrossY:
  6688. case hlsl::IntrinsicOp::IOP_QuadReadAcrossDiagonal:
  6689. case hlsl::IntrinsicOp::IOP_QuadReadLaneAt:
  6690. retVal = processWaveQuadWideShuffle(callExpr, hlslOpcode);
  6691. break;
  6692. case hlsl::IntrinsicOp::IOP_abort:
  6693. case hlsl::IntrinsicOp::IOP_GetRenderTargetSampleCount:
  6694. case hlsl::IntrinsicOp::IOP_GetRenderTargetSamplePosition: {
  6695. emitError("no equivalent for %0 intrinsic function in Vulkan", srcLoc)
  6696. << callee->getName();
  6697. return 0;
  6698. }
  6699. case hlsl::IntrinsicOp::IOP_transpose: {
  6700. const Expr *mat = callExpr->getArg(0);
  6701. const QualType matType = mat->getType();
  6702. if (isVectorType(matType) || isScalarType(matType)) {
  6703. // A 1xN or Nx1 or 1x1 matrix is a SPIR-V vector/scalar, and its transpose
  6704. // is the vector/scalar itself.
  6705. retVal = doExpr(mat);
  6706. } else {
  6707. if (hlsl::GetHLSLMatElementType(matType)->isFloatingType())
  6708. retVal = processIntrinsicUsingSpirvInst(callExpr, spv::Op::OpTranspose,
  6709. false);
  6710. else
  6711. retVal = processNonFpMatrixTranspose(matType, doExpr(mat), srcLoc);
  6712. }
  6713. break;
  6714. }
  6715. case hlsl::IntrinsicOp::IOP_pack_s8:
  6716. case hlsl::IntrinsicOp::IOP_pack_u8:
  6717. case hlsl::IntrinsicOp::IOP_pack_clamp_s8:
  6718. case hlsl::IntrinsicOp::IOP_pack_clamp_u8: {
  6719. retVal = processIntrinsic8BitPack(callExpr, hlslOpcode);
  6720. break;
  6721. }
  6722. case hlsl::IntrinsicOp::IOP_unpack_s8s16:
  6723. case hlsl::IntrinsicOp::IOP_unpack_s8s32:
  6724. case hlsl::IntrinsicOp::IOP_unpack_u8u16:
  6725. case hlsl::IntrinsicOp::IOP_unpack_u8u32: {
  6726. retVal = processIntrinsic8BitUnpack(callExpr, hlslOpcode);
  6727. break;
  6728. }
  6729. // DXR raytracing intrinsics
  6730. case hlsl::IntrinsicOp::IOP_DispatchRaysDimensions:
  6731. case hlsl::IntrinsicOp::IOP_DispatchRaysIndex:
  6732. case hlsl::IntrinsicOp::IOP_GeometryIndex:
  6733. case hlsl::IntrinsicOp::IOP_HitKind:
  6734. case hlsl::IntrinsicOp::IOP_InstanceIndex:
  6735. case hlsl::IntrinsicOp::IOP_InstanceID:
  6736. case hlsl::IntrinsicOp::IOP_ObjectRayDirection:
  6737. case hlsl::IntrinsicOp::IOP_ObjectRayOrigin:
  6738. case hlsl::IntrinsicOp::IOP_ObjectToWorld3x4:
  6739. case hlsl::IntrinsicOp::IOP_ObjectToWorld4x3:
  6740. case hlsl::IntrinsicOp::IOP_PrimitiveIndex:
  6741. case hlsl::IntrinsicOp::IOP_RayFlags:
  6742. case hlsl::IntrinsicOp::IOP_RayTCurrent:
  6743. case hlsl::IntrinsicOp::IOP_RayTMin:
  6744. case hlsl::IntrinsicOp::IOP_WorldRayDirection:
  6745. case hlsl::IntrinsicOp::IOP_WorldRayOrigin:
  6746. case hlsl::IntrinsicOp::IOP_WorldToObject3x4:
  6747. case hlsl::IntrinsicOp::IOP_WorldToObject4x3: {
  6748. retVal = processRayBuiltins(callExpr, hlslOpcode);
  6749. break;
  6750. }
  6751. case hlsl::IntrinsicOp::IOP_AcceptHitAndEndSearch:
  6752. case hlsl::IntrinsicOp::IOP_IgnoreHit: {
  6753. // Any modifications made to the ray payload in an any hit shader are
  6754. // preserved before calling AcceptHit/IgnoreHit. Write out the results to
  6755. // the payload which is visible only in entry functions
  6756. const auto iter = functionInfoMap.find(curFunction);
  6757. if (iter != functionInfoMap.end()) {
  6758. const auto &entryInfo = iter->second;
  6759. if (entryInfo->isEntryFunction) {
  6760. const auto payloadArg = curFunction->getParamDecl(0);
  6761. const auto payloadArgInst =
  6762. declIdMapper.getDeclEvalInfo(payloadArg, payloadArg->getLocStart());
  6763. auto tempLoad = spvBuilder.createLoad(
  6764. payloadArg->getType(), payloadArgInst, payloadArg->getLocStart());
  6765. spvBuilder.createStore(currentRayPayload, tempLoad,
  6766. callExpr->getExprLoc());
  6767. }
  6768. }
  6769. bool nvRayTracing =
  6770. featureManager.isExtensionEnabled(Extension::NV_ray_tracing);
  6771. if (nvRayTracing) {
  6772. spvBuilder.createRayTracingOpsNV(
  6773. hlslOpcode == hlsl::IntrinsicOp::IOP_AcceptHitAndEndSearch
  6774. ? spv::Op::OpTerminateRayNV
  6775. : spv::Op::OpIgnoreIntersectionNV,
  6776. QualType(), {}, srcLoc);
  6777. } else {
  6778. spvBuilder.createRaytracingTerminateKHR(
  6779. hlslOpcode == hlsl::IntrinsicOp::IOP_AcceptHitAndEndSearch
  6780. ? spv::Op::OpTerminateRayKHR
  6781. : spv::Op::OpIgnoreIntersectionKHR,
  6782. srcLoc);
  6783. // According to the SPIR-V spec, both OpTerminateRayKHR and
  6784. // OpIgnoreIntersectionKHR are termination instructions.
  6785. // The spec also requires that these instructions must be the last
  6786. // instruction in a block.
  6787. // Therefore we need to create a new basic block, and the following
  6788. // instructions will go there.
  6789. auto *newBB = spvBuilder.createBasicBlock();
  6790. spvBuilder.setInsertPoint(newBB);
  6791. }
  6792. break;
  6793. }
  6794. case hlsl::IntrinsicOp::IOP_ReportHit: {
  6795. retVal = processReportHit(callExpr);
  6796. break;
  6797. }
  6798. case hlsl::IntrinsicOp::IOP_TraceRay: {
  6799. processTraceRay(callExpr);
  6800. break;
  6801. }
  6802. case hlsl::IntrinsicOp::IOP_CallShader: {
  6803. processCallShader(callExpr);
  6804. break;
  6805. }
  6806. case hlsl::IntrinsicOp::IOP_DispatchMesh: {
  6807. processDispatchMesh(callExpr);
  6808. break;
  6809. }
  6810. case hlsl::IntrinsicOp::IOP_SetMeshOutputCounts: {
  6811. processMeshOutputCounts(callExpr);
  6812. break;
  6813. }
  6814. INTRINSIC_SPIRV_OP_CASE(ddx, DPdx, true);
  6815. INTRINSIC_SPIRV_OP_CASE(ddx_coarse, DPdxCoarse, false);
  6816. INTRINSIC_SPIRV_OP_CASE(ddx_fine, DPdxFine, false);
  6817. INTRINSIC_SPIRV_OP_CASE(ddy, DPdy, true);
  6818. INTRINSIC_SPIRV_OP_CASE(ddy_coarse, DPdyCoarse, false);
  6819. INTRINSIC_SPIRV_OP_CASE(ddy_fine, DPdyFine, false);
  6820. INTRINSIC_SPIRV_OP_CASE(countbits, BitCount, false);
  6821. INTRINSIC_SPIRV_OP_CASE(isinf, IsInf, true);
  6822. INTRINSIC_SPIRV_OP_CASE(isnan, IsNan, true);
  6823. INTRINSIC_SPIRV_OP_CASE(fmod, FRem, true);
  6824. INTRINSIC_SPIRV_OP_CASE(fwidth, Fwidth, true);
  6825. INTRINSIC_SPIRV_OP_CASE(reversebits, BitReverse, false);
  6826. INTRINSIC_OP_CASE(round, Round, true);
  6827. INTRINSIC_OP_CASE(uabs, SAbs, true);
  6828. INTRINSIC_OP_CASE_INT_FLOAT(abs, SAbs, FAbs, true);
  6829. INTRINSIC_OP_CASE(acos, Acos, true);
  6830. INTRINSIC_OP_CASE(asin, Asin, true);
  6831. INTRINSIC_OP_CASE(atan, Atan, true);
  6832. INTRINSIC_OP_CASE(atan2, Atan2, true);
  6833. INTRINSIC_OP_CASE(ceil, Ceil, true);
  6834. INTRINSIC_OP_CASE(cos, Cos, true);
  6835. INTRINSIC_OP_CASE(cosh, Cosh, true);
  6836. INTRINSIC_OP_CASE(cross, Cross, false);
  6837. INTRINSIC_OP_CASE(degrees, Degrees, true);
  6838. INTRINSIC_OP_CASE(distance, Distance, false);
  6839. INTRINSIC_OP_CASE(determinant, Determinant, false);
  6840. INTRINSIC_OP_CASE(exp, Exp, true);
  6841. INTRINSIC_OP_CASE(exp2, Exp2, true);
  6842. INTRINSIC_OP_CASE_SINT_UINT(firstbithigh, FindSMsb, FindUMsb, false);
  6843. INTRINSIC_OP_CASE_SINT_UINT(ufirstbithigh, FindSMsb, FindUMsb, false);
  6844. INTRINSIC_OP_CASE(faceforward, FaceForward, false);
  6845. INTRINSIC_OP_CASE(firstbitlow, FindILsb, false);
  6846. INTRINSIC_OP_CASE(floor, Floor, true);
  6847. INTRINSIC_OP_CASE(fma, Fma, true);
  6848. INTRINSIC_OP_CASE(frac, Fract, true);
  6849. INTRINSIC_OP_CASE(length, Length, false);
  6850. INTRINSIC_OP_CASE(lerp, FMix, true);
  6851. INTRINSIC_OP_CASE(log, Log, true);
  6852. INTRINSIC_OP_CASE(log2, Log2, true);
  6853. INTRINSIC_OP_CASE_SINT_UINT_FLOAT(max, SMax, UMax, FMax, true);
  6854. INTRINSIC_OP_CASE(umax, UMax, true);
  6855. INTRINSIC_OP_CASE_SINT_UINT_FLOAT(min, SMin, UMin, FMin, true);
  6856. INTRINSIC_OP_CASE(umin, UMin, true);
  6857. INTRINSIC_OP_CASE(normalize, Normalize, false);
  6858. INTRINSIC_OP_CASE(pow, Pow, true);
  6859. INTRINSIC_OP_CASE(radians, Radians, true);
  6860. INTRINSIC_OP_CASE(reflect, Reflect, false);
  6861. INTRINSIC_OP_CASE(refract, Refract, false);
  6862. INTRINSIC_OP_CASE(rsqrt, InverseSqrt, true);
  6863. INTRINSIC_OP_CASE(smoothstep, SmoothStep, true);
  6864. INTRINSIC_OP_CASE(step, Step, true);
  6865. INTRINSIC_OP_CASE(sin, Sin, true);
  6866. INTRINSIC_OP_CASE(sinh, Sinh, true);
  6867. INTRINSIC_OP_CASE(tan, Tan, true);
  6868. INTRINSIC_OP_CASE(tanh, Tanh, true);
  6869. INTRINSIC_OP_CASE(sqrt, Sqrt, true);
  6870. INTRINSIC_OP_CASE(trunc, Trunc, true);
  6871. default:
  6872. emitError("%0 intrinsic function unimplemented", srcLoc)
  6873. << callee->getName();
  6874. return 0;
  6875. }
  6876. #undef INTRINSIC_OP_CASE
  6877. #undef INTRINSIC_OP_CASE_INT_FLOAT
  6878. if (retVal)
  6879. retVal->setRValue();
  6880. return retVal;
  6881. }
  6882. SpirvInstruction *
  6883. SpirvEmitter::processIntrinsicInterlockedMethod(const CallExpr *expr,
  6884. hlsl::IntrinsicOp opcode) {
  6885. // The signature of intrinsic atomic methods are:
  6886. // void Interlocked*(in R dest, in T value);
  6887. // void Interlocked*(in R dest, in T value, out T original_value);
  6888. // Note: ALL Interlocked*() methods are forced to have an unsigned integer
  6889. // 'value'. Meaning, T is forced to be 'unsigned int'. If the provided
  6890. // parameter is not an unsigned integer, the frontend inserts an
  6891. // 'ImplicitCastExpr' to convert it to unsigned integer. OpAtomicIAdd (and
  6892. // other SPIR-V OpAtomic* instructions) require that the pointee in 'dest' to
  6893. // be of the same type as T. This will result in an invalid SPIR-V if 'dest'
  6894. // is a signed integer typed resource such as RWTexture1D<int>. For example,
  6895. // the following OpAtomicIAdd is invalid because the pointee type defined in
  6896. // %1 is a signed integer, while the value passed to atomic add (%3) is an
  6897. // unsigned integer.
  6898. //
  6899. // %_ptr_Image_int = OpTypePointer Image %int
  6900. // %1 = OpImageTexelPointer %_ptr_Image_int %RWTexture1D_int %index %uint_0
  6901. // %2 = OpLoad %int %value
  6902. // %3 = OpBitcast %uint %2 <-------- Inserted by the frontend
  6903. // %4 = OpAtomicIAdd %int %1 %uint_1 %uint_0 %3
  6904. //
  6905. // In such cases, we bypass the forced IntegralCast.
  6906. // Moreover, the frontend does not add a cast AST node to cast uint to int
  6907. // where necessary. To ensure SPIR-V validity, we add that where necessary.
  6908. auto *zero =
  6909. spvBuilder.getConstantInt(astContext.UnsignedIntTy, llvm::APInt(32, 0));
  6910. const auto *dest = expr->getArg(0);
  6911. const auto srcLoc = expr->getExprLoc();
  6912. const auto baseType = dest->getType()->getCanonicalTypeUnqualified();
  6913. if (!baseType->isIntegerType()) {
  6914. emitError("can only perform atomic operations on scalar integer values",
  6915. dest->getLocStart());
  6916. return nullptr;
  6917. }
  6918. const auto doArg = [baseType, this](const CallExpr *callExpr,
  6919. uint32_t argIndex) {
  6920. const Expr *valueExpr = callExpr->getArg(argIndex);
  6921. if (const auto *castExpr = dyn_cast<ImplicitCastExpr>(valueExpr))
  6922. if (castExpr->getCastKind() == CK_IntegralCast &&
  6923. castExpr->getSubExpr()->getType()->getCanonicalTypeUnqualified() ==
  6924. baseType)
  6925. valueExpr = castExpr->getSubExpr();
  6926. auto *argInstr = doExpr(valueExpr);
  6927. if (valueExpr->getType() != baseType)
  6928. argInstr = castToInt(argInstr, valueExpr->getType(), baseType,
  6929. valueExpr->getExprLoc());
  6930. return argInstr;
  6931. };
  6932. const auto writeToOutputArg = [&baseType, dest,
  6933. this](SpirvInstruction *toWrite,
  6934. const CallExpr *callExpr,
  6935. uint32_t outputArgIndex) {
  6936. const auto outputArg = callExpr->getArg(outputArgIndex);
  6937. const auto outputArgType = outputArg->getType();
  6938. if (baseType != outputArgType)
  6939. toWrite =
  6940. castToInt(toWrite, baseType, outputArgType, dest->getLocStart());
  6941. spvBuilder.createStore(doExpr(outputArg), toWrite, callExpr->getExprLoc());
  6942. };
  6943. // If a vector swizzling of a texture is done as an argument of an
  6944. // interlocked method, we need to handle the access to the texture
  6945. // buffer element correctly. For example:
  6946. //
  6947. // InterlockedAdd(myRWTexture[index].r, 1);
  6948. //
  6949. // `-CallExpr
  6950. // |-ImplicitCastExpr
  6951. // | `-DeclRefExpr Function 'InterlockedAdd'
  6952. // | 'void (unsigned int &, unsigned int)'
  6953. // |-HLSLVectorElementExpr 'unsigned int' lvalue vectorcomponent r
  6954. // | `-ImplicitCastExpr 'vector<uint, 1>':'vector<unsigned int, 1>'
  6955. // | <HLSLVectorSplat>
  6956. // | `-CXXOperatorCallExpr 'unsigned int' lvalue
  6957. const auto *cxxOpCall = dyn_cast<CXXOperatorCallExpr>(dest);
  6958. if (const auto *vector = dyn_cast<HLSLVectorElementExpr>(dest)) {
  6959. const Expr *base = vector->getBase();
  6960. cxxOpCall = dyn_cast<CXXOperatorCallExpr>(base);
  6961. if (const auto *cast = dyn_cast<CastExpr>(base)) {
  6962. cxxOpCall = dyn_cast<CXXOperatorCallExpr>(cast->getSubExpr());
  6963. }
  6964. }
  6965. // If the argument is indexing into a texture/buffer, we need to create an
  6966. // OpImageTexelPointer instruction.
  6967. SpirvInstruction *ptr = nullptr;
  6968. if (cxxOpCall) {
  6969. const Expr *base = nullptr;
  6970. const Expr *index = nullptr;
  6971. if (isBufferTextureIndexing(cxxOpCall, &base, &index)) {
  6972. if (hlsl::IsHLSLResourceType(base->getType())) {
  6973. const auto resultTy = hlsl::GetHLSLResourceResultType(base->getType());
  6974. if (!isScalarType(resultTy, nullptr)) {
  6975. emitError("Interlocked operation for texture buffer whose result "
  6976. "type is non-scalar type is not allowed",
  6977. dest->getExprLoc());
  6978. return nullptr;
  6979. }
  6980. }
  6981. auto *baseInstr = doExpr(base);
  6982. if (baseInstr->isRValue()) {
  6983. // OpImageTexelPointer's Image argument must have a type of
  6984. // OpTypePointer with Type OpTypeImage. Need to create a temporary
  6985. // variable if the baseId is an rvalue.
  6986. baseInstr =
  6987. createTemporaryVar(base->getType(), getAstTypeName(base->getType()),
  6988. baseInstr, base->getExprLoc());
  6989. }
  6990. auto *coordInstr = doExpr(index);
  6991. ptr = spvBuilder.createImageTexelPointer(baseType, baseInstr, coordInstr,
  6992. zero, srcLoc);
  6993. }
  6994. }
  6995. if (!ptr) {
  6996. auto *ptrInfo = doExpr(dest);
  6997. const auto sc = ptrInfo->getStorageClass();
  6998. if (sc == spv::StorageClass::Private || sc == spv::StorageClass::Function) {
  6999. emitError("using static variable or function scope variable in "
  7000. "interlocked operation is not allowed",
  7001. dest->getExprLoc());
  7002. return nullptr;
  7003. }
  7004. ptr = ptrInfo;
  7005. }
  7006. const bool isCompareExchange =
  7007. opcode == hlsl::IntrinsicOp::IOP_InterlockedCompareExchange;
  7008. const bool isCompareStore =
  7009. opcode == hlsl::IntrinsicOp::IOP_InterlockedCompareStore;
  7010. if (isCompareExchange || isCompareStore) {
  7011. auto *comparator = doArg(expr, 1);
  7012. auto *valueInstr = doArg(expr, 2);
  7013. auto *originalVal = spvBuilder.createAtomicCompareExchange(
  7014. baseType, ptr, spv::Scope::Device, spv::MemorySemanticsMask::MaskNone,
  7015. spv::MemorySemanticsMask::MaskNone, valueInstr, comparator, srcLoc);
  7016. if (isCompareExchange)
  7017. writeToOutputArg(originalVal, expr, 3);
  7018. } else {
  7019. auto *value = doArg(expr, 1);
  7020. // Since these atomic operations write through the provided pointer, the
  7021. // signed vs. unsigned opcode must be decided based on the pointee type
  7022. // of the first argument. However, the frontend decides the opcode based on
  7023. // the second argument (value). Therefore, the HLSL opcode provided by the
  7024. // frontend may be wrong. Therefore we need the following code to make sure
  7025. // we are using the correct SPIR-V opcode.
  7026. spv::Op atomicOp = translateAtomicHlslOpcodeToSpirvOpcode(opcode);
  7027. if (atomicOp == spv::Op::OpAtomicUMax && baseType->isSignedIntegerType())
  7028. atomicOp = spv::Op::OpAtomicSMax;
  7029. if (atomicOp == spv::Op::OpAtomicSMax && baseType->isUnsignedIntegerType())
  7030. atomicOp = spv::Op::OpAtomicUMax;
  7031. if (atomicOp == spv::Op::OpAtomicUMin && baseType->isSignedIntegerType())
  7032. atomicOp = spv::Op::OpAtomicSMin;
  7033. if (atomicOp == spv::Op::OpAtomicSMin && baseType->isUnsignedIntegerType())
  7034. atomicOp = spv::Op::OpAtomicUMin;
  7035. auto *originalVal = spvBuilder.createAtomicOp(
  7036. atomicOp, baseType, ptr, spv::Scope::Device,
  7037. spv::MemorySemanticsMask::MaskNone, value, srcLoc);
  7038. if (expr->getNumArgs() > 2)
  7039. writeToOutputArg(originalVal, expr, 2);
  7040. }
  7041. return nullptr;
  7042. }
  7043. SpirvInstruction *
  7044. SpirvEmitter::processIntrinsicNonUniformResourceIndex(const CallExpr *expr) {
  7045. auto *index = doExpr(expr->getArg(0));
  7046. // Decorate the expression in NonUniformResourceIndex() with NonUniformEXT.
  7047. // Aside from this, we also need to eventually populate the NonUniformEXT
  7048. // status to the usages of this expression. This is done by the
  7049. // NonUniformVisitor class.
  7050. //
  7051. // The decoration shouldn't be applied to the operand, rather to a copy of the
  7052. // result. Even though applying the decoration to the operand may not be
  7053. // functionally incorrect (since adding NonUniform is more conservative), it
  7054. // could affect performance and isn't the intent of the shader.
  7055. auto *copyInstr =
  7056. spvBuilder.createCopyObject(expr->getType(), index, expr->getExprLoc());
  7057. copyInstr->setNonUniform();
  7058. return copyInstr;
  7059. }
  7060. SpirvInstruction *
  7061. SpirvEmitter::processIntrinsicMsad4(const CallExpr *callExpr) {
  7062. const auto loc = callExpr->getExprLoc();
  7063. if (!spirvOptions.noWarnEmulatedFeatures)
  7064. emitWarning("msad4 intrinsic function is emulated using many SPIR-V "
  7065. "instructions due to lack of direct SPIR-V equivalent",
  7066. loc);
  7067. // Compares a 4-byte reference value and an 8-byte source value and
  7068. // accumulates a vector of 4 sums. Each sum corresponds to the masked sum
  7069. // of absolute differences of a different byte alignment between the
  7070. // reference value and the source value.
  7071. // If we have:
  7072. // uint v0; // reference
  7073. // uint2 v1; // source
  7074. // uint4 v2; // accum
  7075. // uint4 o0; // result of msad4
  7076. // uint4 r0, t0; // temporary values
  7077. //
  7078. // Then msad4(v0, v1, v2) translates to the following SM5 assembly according
  7079. // to fxc:
  7080. // Step 1:
  7081. // ushr r0.xyz, v1.xxxx, l(8, 16, 24, 0)
  7082. // Step 2:
  7083. // [result], [ width ], [ offset ], [ insert ], [ base ]
  7084. // bfi t0.yzw, l(0, 8, 16, 24), l(0, 24, 16, 8), v1.yyyy , r0.xxyz
  7085. // mov t0.x, v1.x
  7086. // Step 3:
  7087. // msad o0.xyzw, v0.xxxx, t0.xyzw, v2.xyzw
  7088. const auto boolType = astContext.BoolTy;
  7089. const auto intType = astContext.IntTy;
  7090. const auto uintType = astContext.UnsignedIntTy;
  7091. const auto uint4Type = astContext.getExtVectorType(uintType, 4);
  7092. auto *reference = doExpr(callExpr->getArg(0));
  7093. auto *source = doExpr(callExpr->getArg(1));
  7094. auto *accum = doExpr(callExpr->getArg(2));
  7095. const auto uint0 =
  7096. spvBuilder.getConstantInt(astContext.UnsignedIntTy, llvm::APInt(32, 0));
  7097. const auto uint8 =
  7098. spvBuilder.getConstantInt(astContext.UnsignedIntTy, llvm::APInt(32, 8));
  7099. const auto uint16 =
  7100. spvBuilder.getConstantInt(astContext.UnsignedIntTy, llvm::APInt(32, 16));
  7101. const auto uint24 =
  7102. spvBuilder.getConstantInt(astContext.UnsignedIntTy, llvm::APInt(32, 24));
  7103. // Step 1.
  7104. auto *v1x = spvBuilder.createCompositeExtract(uintType, source, {0}, loc);
  7105. // r0.x = v1xS8 = v1.x shifted by 8 bits
  7106. auto *v1xS8 = spvBuilder.createBinaryOp(spv::Op::OpShiftLeftLogical, uintType,
  7107. v1x, uint8, loc);
  7108. // r0.y = v1xS16 = v1.x shifted by 16 bits
  7109. auto *v1xS16 = spvBuilder.createBinaryOp(spv::Op::OpShiftLeftLogical,
  7110. uintType, v1x, uint16, loc);
  7111. // r0.z = v1xS24 = v1.x shifted by 24 bits
  7112. auto *v1xS24 = spvBuilder.createBinaryOp(spv::Op::OpShiftLeftLogical,
  7113. uintType, v1x, uint24, loc);
  7114. // Step 2.
  7115. // Do bfi 3 times. DXIL bfi is equivalent to SPIR-V OpBitFieldInsert.
  7116. auto *v1y = spvBuilder.createCompositeExtract(uintType, source, {1}, loc);
  7117. // Note that t0.x = v1.x, nothing we need to do for that.
  7118. auto *t0y =
  7119. spvBuilder.createBitFieldInsert(uintType, /*base*/ v1xS8, /*insert*/ v1y,
  7120. /*offset*/ uint24,
  7121. /*width*/ uint8, loc);
  7122. auto *t0z =
  7123. spvBuilder.createBitFieldInsert(uintType, /*base*/ v1xS16, /*insert*/ v1y,
  7124. /*offset*/ uint16,
  7125. /*width*/ uint16, loc);
  7126. auto *t0w =
  7127. spvBuilder.createBitFieldInsert(uintType, /*base*/ v1xS24, /*insert*/ v1y,
  7128. /*offset*/ uint8,
  7129. /*width*/ uint24, loc);
  7130. // Step 3. MSAD (Masked Sum of Absolute Differences)
  7131. // Now perform MSAD four times.
  7132. // Need to mimic this algorithm in SPIR-V!
  7133. //
  7134. // UINT msad( UINT ref, UINT src, UINT accum )
  7135. // {
  7136. // for (UINT i = 0; i < 4; i++)
  7137. // {
  7138. // BYTE refByte, srcByte, absDiff;
  7139. //
  7140. // refByte = (BYTE)(ref >> (i * 8));
  7141. // if (!refByte)
  7142. // {
  7143. // continue;
  7144. // }
  7145. //
  7146. // srcByte = (BYTE)(src >> (i * 8));
  7147. // if (refByte >= srcByte)
  7148. // {
  7149. // absDiff = refByte - srcByte;
  7150. // }
  7151. // else
  7152. // {
  7153. // absDiff = srcByte - refByte;
  7154. // }
  7155. //
  7156. // // The recommended overflow behavior for MSAD is
  7157. // // to do a 32-bit saturate. This is not
  7158. // // required, however, and wrapping is allowed.
  7159. // // So from an application point of view,
  7160. // // overflow behavior is undefined.
  7161. // if (UINT_MAX - accum < absDiff)
  7162. // {
  7163. // accum = UINT_MAX;
  7164. // break;
  7165. // }
  7166. // accum += absDiff;
  7167. // }
  7168. //
  7169. // return accum;
  7170. // }
  7171. auto *accum0 = spvBuilder.createCompositeExtract(uintType, accum, {0}, loc);
  7172. auto *accum1 = spvBuilder.createCompositeExtract(uintType, accum, {1}, loc);
  7173. auto *accum2 = spvBuilder.createCompositeExtract(uintType, accum, {2}, loc);
  7174. auto *accum3 = spvBuilder.createCompositeExtract(uintType, accum, {3}, loc);
  7175. const llvm::SmallVector<SpirvInstruction *, 4> sources = {v1x, t0y, t0z, t0w};
  7176. llvm::SmallVector<SpirvInstruction *, 4> accums = {accum0, accum1, accum2,
  7177. accum3};
  7178. llvm::SmallVector<SpirvInstruction *, 4> refBytes;
  7179. llvm::SmallVector<SpirvInstruction *, 4> signedRefBytes;
  7180. llvm::SmallVector<SpirvInstruction *, 4> isRefByteZero;
  7181. for (uint32_t i = 0; i < 4; ++i) {
  7182. refBytes.push_back(spvBuilder.createBitFieldExtract(
  7183. uintType, reference, /*offset*/
  7184. spvBuilder.getConstantInt(astContext.UnsignedIntTy,
  7185. llvm::APInt(32, i * 8)),
  7186. /*count*/ uint8, /*isSigned*/ false, loc));
  7187. signedRefBytes.push_back(spvBuilder.createUnaryOp(
  7188. spv::Op::OpBitcast, intType, refBytes.back(), loc));
  7189. isRefByteZero.push_back(spvBuilder.createBinaryOp(
  7190. spv::Op::OpIEqual, boolType, refBytes.back(), uint0, loc));
  7191. }
  7192. for (uint32_t msadNum = 0; msadNum < 4; ++msadNum) {
  7193. for (uint32_t byteCount = 0; byteCount < 4; ++byteCount) {
  7194. // 'count' is always 8 because we are extracting 8 bits out of 32.
  7195. auto *srcByte = spvBuilder.createBitFieldExtract(
  7196. uintType, sources[msadNum],
  7197. /*offset*/
  7198. spvBuilder.getConstantInt(astContext.UnsignedIntTy,
  7199. llvm::APInt(32, 8 * byteCount)),
  7200. /*count*/ uint8, /*isSigned*/ false, loc);
  7201. auto *signedSrcByte =
  7202. spvBuilder.createUnaryOp(spv::Op::OpBitcast, intType, srcByte, loc);
  7203. auto *sub = spvBuilder.createBinaryOp(spv::Op::OpISub, intType,
  7204. signedRefBytes[byteCount],
  7205. signedSrcByte, loc);
  7206. auto *absSub = spvBuilder.createGLSLExtInst(
  7207. intType, GLSLstd450::GLSLstd450SAbs, {sub}, loc);
  7208. auto *diff = spvBuilder.createSelect(
  7209. uintType, isRefByteZero[byteCount], uint0,
  7210. spvBuilder.createUnaryOp(spv::Op::OpBitcast, uintType, absSub, loc),
  7211. loc);
  7212. // As pointed out by the DXIL reference above, it is *not* required to
  7213. // saturate the output to UINT_MAX in case of overflow. Wrapping around is
  7214. // also allowed. For simplicity, we will wrap around at this point.
  7215. accums[msadNum] = spvBuilder.createBinaryOp(spv::Op::OpIAdd, uintType,
  7216. accums[msadNum], diff, loc);
  7217. }
  7218. }
  7219. return spvBuilder.createCompositeConstruct(uint4Type, accums, loc);
  7220. }
  7221. SpirvInstruction *SpirvEmitter::processWaveQuery(const CallExpr *callExpr,
  7222. spv::Op opcode) {
  7223. // Signatures:
  7224. // bool WaveIsFirstLane()
  7225. // uint WaveGetLaneCount()
  7226. // uint WaveGetLaneIndex()
  7227. assert(callExpr->getNumArgs() == 0);
  7228. featureManager.requestTargetEnv(SPV_ENV_VULKAN_1_1, "Wave Operation",
  7229. callExpr->getExprLoc());
  7230. const QualType retType = callExpr->getCallReturnType(astContext);
  7231. return spvBuilder.createGroupNonUniformElect(
  7232. opcode, retType, spv::Scope::Subgroup, callExpr->getExprLoc());
  7233. }
  7234. SpirvInstruction *SpirvEmitter::processWaveVote(const CallExpr *callExpr,
  7235. spv::Op opcode) {
  7236. // Signatures:
  7237. // bool WaveActiveAnyTrue( bool expr )
  7238. // bool WaveActiveAllTrue( bool expr )
  7239. // bool uint4 WaveActiveBallot( bool expr )
  7240. assert(callExpr->getNumArgs() == 1);
  7241. featureManager.requestTargetEnv(SPV_ENV_VULKAN_1_1, "Wave Operation",
  7242. callExpr->getExprLoc());
  7243. auto *predicate = doExpr(callExpr->getArg(0));
  7244. const QualType retType = callExpr->getCallReturnType(astContext);
  7245. return spvBuilder.createGroupNonUniformUnaryOp(
  7246. callExpr->getExprLoc(), opcode, retType, spv::Scope::Subgroup, predicate);
  7247. }
  7248. spv::Op SpirvEmitter::translateWaveOp(hlsl::IntrinsicOp op, QualType type,
  7249. SourceLocation srcLoc) {
  7250. const bool isSintType = isSintOrVecMatOfSintType(type);
  7251. const bool isUintType = isUintOrVecMatOfUintType(type);
  7252. const bool isFloatType = isFloatOrVecMatOfFloatType(type);
  7253. #define WAVE_OP_CASE_INT(kind, intWaveOp) \
  7254. \
  7255. case hlsl::IntrinsicOp::IOP_Wave##kind: { \
  7256. if (isSintType || isUintType) { \
  7257. return spv::Op::OpGroupNonUniform##intWaveOp; \
  7258. } \
  7259. } break
  7260. #define WAVE_OP_CASE_INT_FLOAT(kind, intWaveOp, floatWaveOp) \
  7261. \
  7262. case hlsl::IntrinsicOp::IOP_Wave##kind: { \
  7263. if (isSintType || isUintType) { \
  7264. return spv::Op::OpGroupNonUniform##intWaveOp; \
  7265. } \
  7266. if (isFloatType) { \
  7267. return spv::Op::OpGroupNonUniform##floatWaveOp; \
  7268. } \
  7269. } break
  7270. #define WAVE_OP_CASE_SINT_UINT_FLOAT(kind, sintWaveOp, uintWaveOp, \
  7271. floatWaveOp) \
  7272. \
  7273. case hlsl::IntrinsicOp::IOP_Wave##kind: { \
  7274. if (isSintType) { \
  7275. return spv::Op::OpGroupNonUniform##sintWaveOp; \
  7276. } \
  7277. if (isUintType) { \
  7278. return spv::Op::OpGroupNonUniform##uintWaveOp; \
  7279. } \
  7280. if (isFloatType) { \
  7281. return spv::Op::OpGroupNonUniform##floatWaveOp; \
  7282. } \
  7283. } break
  7284. switch (op) {
  7285. WAVE_OP_CASE_INT_FLOAT(ActiveUSum, IAdd, FAdd);
  7286. WAVE_OP_CASE_INT_FLOAT(ActiveSum, IAdd, FAdd);
  7287. WAVE_OP_CASE_INT_FLOAT(ActiveUProduct, IMul, FMul);
  7288. WAVE_OP_CASE_INT_FLOAT(ActiveProduct, IMul, FMul);
  7289. WAVE_OP_CASE_INT_FLOAT(PrefixUSum, IAdd, FAdd);
  7290. WAVE_OP_CASE_INT_FLOAT(PrefixSum, IAdd, FAdd);
  7291. WAVE_OP_CASE_INT_FLOAT(PrefixUProduct, IMul, FMul);
  7292. WAVE_OP_CASE_INT_FLOAT(PrefixProduct, IMul, FMul);
  7293. WAVE_OP_CASE_INT(ActiveBitAnd, BitwiseAnd);
  7294. WAVE_OP_CASE_INT(ActiveBitOr, BitwiseOr);
  7295. WAVE_OP_CASE_INT(ActiveBitXor, BitwiseXor);
  7296. WAVE_OP_CASE_SINT_UINT_FLOAT(ActiveUMax, SMax, UMax, FMax);
  7297. WAVE_OP_CASE_SINT_UINT_FLOAT(ActiveMax, SMax, UMax, FMax);
  7298. WAVE_OP_CASE_SINT_UINT_FLOAT(ActiveUMin, SMin, UMin, FMin);
  7299. WAVE_OP_CASE_SINT_UINT_FLOAT(ActiveMin, SMin, UMin, FMin);
  7300. default:
  7301. // Only Simple Wave Ops are handled here.
  7302. break;
  7303. }
  7304. #undef WAVE_OP_CASE_INT_FLOAT
  7305. #undef WAVE_OP_CASE_INT
  7306. #undef WAVE_OP_CASE_SINT_UINT_FLOAT
  7307. emitError("translating wave operator '%0' unimplemented", srcLoc)
  7308. << static_cast<uint32_t>(op);
  7309. return spv::Op::OpNop;
  7310. }
  7311. SpirvInstruction *
  7312. SpirvEmitter::processWaveCountBits(const CallExpr *callExpr,
  7313. spv::GroupOperation groupOp) {
  7314. // Signatures:
  7315. // uint WaveActiveCountBits(bool bBit)
  7316. // uint WavePrefixCountBits(Bool bBit)
  7317. assert(callExpr->getNumArgs() == 1);
  7318. featureManager.requestTargetEnv(SPV_ENV_VULKAN_1_1, "Wave Operation",
  7319. callExpr->getExprLoc());
  7320. auto *predicate = doExpr(callExpr->getArg(0));
  7321. const auto srcLoc = callExpr->getExprLoc();
  7322. const QualType u32Type = astContext.UnsignedIntTy;
  7323. const QualType v4u32Type = astContext.getExtVectorType(u32Type, 4);
  7324. const QualType retType = callExpr->getCallReturnType(astContext);
  7325. auto *ballot = spvBuilder.createGroupNonUniformUnaryOp(
  7326. srcLoc, spv::Op::OpGroupNonUniformBallot, v4u32Type, spv::Scope::Subgroup,
  7327. predicate);
  7328. return spvBuilder.createGroupNonUniformUnaryOp(
  7329. srcLoc, spv::Op::OpGroupNonUniformBallotBitCount, retType,
  7330. spv::Scope::Subgroup, ballot,
  7331. llvm::Optional<spv::GroupOperation>(groupOp));
  7332. }
  7333. SpirvInstruction *SpirvEmitter::processWaveReductionOrPrefix(
  7334. const CallExpr *callExpr, spv::Op opcode, spv::GroupOperation groupOp) {
  7335. // Signatures:
  7336. // bool WaveActiveAllEqual( <type> expr )
  7337. // <type> WaveActiveSum( <type> expr )
  7338. // <type> WaveActiveProduct( <type> expr )
  7339. // <int_type> WaveActiveBitAnd( <int_type> expr )
  7340. // <int_type> WaveActiveBitOr( <int_type> expr )
  7341. // <int_type> WaveActiveBitXor( <int_type> expr )
  7342. // <type> WaveActiveMin( <type> expr)
  7343. // <type> WaveActiveMax( <type> expr)
  7344. //
  7345. // <type> WavePrefixProduct(<type> value)
  7346. // <type> WavePrefixSum(<type> value)
  7347. assert(callExpr->getNumArgs() == 1);
  7348. featureManager.requestTargetEnv(SPV_ENV_VULKAN_1_1, "Wave Operation",
  7349. callExpr->getExprLoc());
  7350. auto *predicate = doExpr(callExpr->getArg(0));
  7351. const QualType retType = callExpr->getCallReturnType(astContext);
  7352. return spvBuilder.createGroupNonUniformUnaryOp(
  7353. callExpr->getExprLoc(), opcode, retType, spv::Scope::Subgroup, predicate,
  7354. llvm::Optional<spv::GroupOperation>(groupOp));
  7355. }
  7356. SpirvInstruction *SpirvEmitter::processWaveBroadcast(const CallExpr *callExpr) {
  7357. // Signatures:
  7358. // <type> WaveReadLaneFirst(<type> expr)
  7359. // <type> WaveReadLaneAt(<type> expr, uint laneIndex)
  7360. const auto numArgs = callExpr->getNumArgs();
  7361. const auto srcLoc = callExpr->getExprLoc();
  7362. assert(numArgs == 1 || numArgs == 2);
  7363. featureManager.requestTargetEnv(SPV_ENV_VULKAN_1_1, "Wave Operation",
  7364. callExpr->getExprLoc());
  7365. auto *value = doExpr(callExpr->getArg(0));
  7366. const QualType retType = callExpr->getCallReturnType(astContext);
  7367. if (numArgs == 2)
  7368. // WaveReadLaneAt is in fact not a broadcast operation (even though its name
  7369. // might incorrectly suggest so). The proper mapping to SPIR-V for
  7370. // it is OpGroupNonUniformShuffle, *not* OpGroupNonUniformBroadcast.
  7371. return spvBuilder.createGroupNonUniformBinaryOp(
  7372. spv::Op::OpGroupNonUniformShuffle, retType, spv::Scope::Subgroup, value,
  7373. doExpr(callExpr->getArg(1)), srcLoc);
  7374. else
  7375. return spvBuilder.createGroupNonUniformUnaryOp(
  7376. srcLoc, spv::Op::OpGroupNonUniformBroadcastFirst, retType,
  7377. spv::Scope::Subgroup, value);
  7378. }
  7379. SpirvInstruction *
  7380. SpirvEmitter::processWaveQuadWideShuffle(const CallExpr *callExpr,
  7381. hlsl::IntrinsicOp op) {
  7382. // Signatures:
  7383. // <type> QuadReadAcrossX(<type> localValue)
  7384. // <type> QuadReadAcrossY(<type> localValue)
  7385. // <type> QuadReadAcrossDiagonal(<type> localValue)
  7386. // <type> QuadReadLaneAt(<type> sourceValue, uint quadLaneID)
  7387. assert(callExpr->getNumArgs() == 1 || callExpr->getNumArgs() == 2);
  7388. featureManager.requestTargetEnv(SPV_ENV_VULKAN_1_1, "Wave Operation",
  7389. callExpr->getExprLoc());
  7390. auto *value = doExpr(callExpr->getArg(0));
  7391. const auto srcLoc = callExpr->getExprLoc();
  7392. const QualType retType = callExpr->getCallReturnType(astContext);
  7393. SpirvInstruction *target = nullptr;
  7394. spv::Op opcode = spv::Op::OpGroupNonUniformQuadSwap;
  7395. switch (op) {
  7396. case hlsl::IntrinsicOp::IOP_QuadReadAcrossX:
  7397. target =
  7398. spvBuilder.getConstantInt(astContext.UnsignedIntTy, llvm::APInt(32, 0));
  7399. break;
  7400. case hlsl::IntrinsicOp::IOP_QuadReadAcrossY:
  7401. target =
  7402. spvBuilder.getConstantInt(astContext.UnsignedIntTy, llvm::APInt(32, 1));
  7403. break;
  7404. case hlsl::IntrinsicOp::IOP_QuadReadAcrossDiagonal:
  7405. target =
  7406. spvBuilder.getConstantInt(astContext.UnsignedIntTy, llvm::APInt(32, 2));
  7407. break;
  7408. case hlsl::IntrinsicOp::IOP_QuadReadLaneAt:
  7409. target = doExpr(callExpr->getArg(1));
  7410. opcode = spv::Op::OpGroupNonUniformQuadBroadcast;
  7411. break;
  7412. default:
  7413. llvm_unreachable("case should not appear here");
  7414. }
  7415. return spvBuilder.createGroupNonUniformBinaryOp(
  7416. opcode, retType, spv::Scope::Subgroup, value, target, srcLoc);
  7417. }
  7418. SpirvInstruction *SpirvEmitter::processIntrinsicModf(const CallExpr *callExpr) {
  7419. // Signature is: ret modf(x, ip)
  7420. // [in] x: the input floating-point value.
  7421. // [out] ip: the integer portion of x.
  7422. // [out] ret: the fractional portion of x.
  7423. // All of the above must be a scalar, vector, or matrix with the same
  7424. // component types. Component types can be float or int.
  7425. // The ModfStruct SPIR-V instruction returns a struct. The first member is the
  7426. // fractional part and the second member is the integer portion.
  7427. // ModfStruct {
  7428. // <scalar or vector of float> frac;
  7429. // <scalar or vector of float> ip;
  7430. // }
  7431. // Note if the input number (x) is not a float (i.e. 'x' is an int), it is
  7432. // automatically converted to float before modf is invoked. Sadly, the 'ip'
  7433. // argument is not treated the same way. Therefore, in such cases we'll have
  7434. // to manually convert the float result into int.
  7435. const Expr *arg = callExpr->getArg(0);
  7436. const Expr *ipArg = callExpr->getArg(1);
  7437. const auto loc = callExpr->getLocStart();
  7438. const auto argType = arg->getType();
  7439. const auto ipType = ipArg->getType();
  7440. const auto returnType = callExpr->getType();
  7441. auto *argInstr = doExpr(arg);
  7442. // For scalar and vector argument types.
  7443. {
  7444. if (isScalarType(argType) || isVectorType(argType)) {
  7445. // The struct members *must* have the same type.
  7446. const auto modfStructType = spvContext.getHybridStructType(
  7447. {HybridStructType::FieldInfo(argType, "frac"),
  7448. HybridStructType::FieldInfo(argType, "ip")},
  7449. "ModfStructType");
  7450. auto *modf = spvBuilder.createGLSLExtInst(
  7451. modfStructType, GLSLstd450::GLSLstd450ModfStruct, {argInstr}, loc);
  7452. SpirvInstruction *ip =
  7453. spvBuilder.createCompositeExtract(argType, modf, {1}, loc);
  7454. // This will do nothing if the input number (x) and the ip are both of the
  7455. // same type. Otherwise, it will convert the ip into int as necessary.
  7456. ip = castToInt(ip, argType, ipType, ipArg->getLocStart());
  7457. processAssignment(ipArg, ip, false, nullptr);
  7458. return spvBuilder.createCompositeExtract(argType, modf, {0}, loc);
  7459. }
  7460. }
  7461. // For matrix argument types.
  7462. {
  7463. uint32_t rowCount = 0, colCount = 0;
  7464. QualType elemType = {};
  7465. if (isMxNMatrix(argType, &elemType, &rowCount, &colCount)) {
  7466. const auto colType = astContext.getExtVectorType(elemType, colCount);
  7467. const auto modfStructType = spvContext.getHybridStructType(
  7468. {HybridStructType::FieldInfo(colType, "frac"),
  7469. HybridStructType::FieldInfo(colType, "ip")},
  7470. "ModfStructType");
  7471. llvm::SmallVector<SpirvInstruction *, 4> fracs;
  7472. llvm::SmallVector<SpirvInstruction *, 4> ips;
  7473. for (uint32_t i = 0; i < rowCount; ++i) {
  7474. auto *curRow =
  7475. spvBuilder.createCompositeExtract(colType, argInstr, {i}, loc);
  7476. auto *modf = spvBuilder.createGLSLExtInst(
  7477. modfStructType, GLSLstd450::GLSLstd450ModfStruct, {curRow}, loc);
  7478. ips.push_back(
  7479. spvBuilder.createCompositeExtract(colType, modf, {1}, loc));
  7480. fracs.push_back(
  7481. spvBuilder.createCompositeExtract(colType, modf, {0}, loc));
  7482. }
  7483. SpirvInstruction *ip =
  7484. spvBuilder.createCompositeConstruct(argType, ips, loc);
  7485. // If the 'ip' is not a float type, the AST will not contain a CastExpr
  7486. // because this is internal to the intrinsic function. So, in such a
  7487. // case we need to cast manually.
  7488. if (!hlsl::GetHLSLMatElementType(ipType)->isFloatingType())
  7489. ip = castToInt(ip, argType, ipType, ipArg->getLocStart());
  7490. processAssignment(ipArg, ip, false, nullptr);
  7491. return spvBuilder.createCompositeConstruct(returnType, fracs, loc);
  7492. }
  7493. }
  7494. emitError("invalid argument type passed to Modf intrinsic function",
  7495. callExpr->getExprLoc());
  7496. return nullptr;
  7497. }
  7498. SpirvInstruction *SpirvEmitter::processIntrinsicMad(const CallExpr *callExpr) {
  7499. // Signature is: ret mad(a,b,c)
  7500. // All of the above must be a scalar, vector, or matrix with the same
  7501. // component types. Component types can be float or int.
  7502. // The return value is equal to "a * b + c"
  7503. // In the case of float arguments, we can use the GLSL extended instruction
  7504. // set's Fma instruction with NoContraction decoration. In the case of integer
  7505. // arguments, we'll have to manually perform an OpIMul followed by an OpIAdd
  7506. // (We should also apply NoContraction decoration to these two instructions to
  7507. // get precise arithmetic).
  7508. // TODO: We currently don't propagate the NoContraction decoration.
  7509. const auto loc = callExpr->getLocStart();
  7510. const Expr *arg0 = callExpr->getArg(0);
  7511. const Expr *arg1 = callExpr->getArg(1);
  7512. const Expr *arg2 = callExpr->getArg(2);
  7513. // All arguments and the return type are the same.
  7514. const auto argType = arg0->getType();
  7515. auto *arg0Instr = doExpr(arg0);
  7516. auto *arg1Instr = doExpr(arg1);
  7517. auto *arg2Instr = doExpr(arg2);
  7518. auto arg0Loc = arg0->getLocStart();
  7519. auto arg1Loc = arg1->getLocStart();
  7520. auto arg2Loc = arg2->getLocStart();
  7521. // For floating point arguments, we can use the extended instruction set's Fma
  7522. // instruction. Sadly we can't simply call processIntrinsicUsingGLSLInst
  7523. // because we need to specifically decorate the Fma instruction with
  7524. // NoContraction decoration.
  7525. if (isFloatOrVecMatOfFloatType(argType)) {
  7526. // For matrix cases, operate on each row of the matrix.
  7527. if (isMxNMatrix(arg0->getType())) {
  7528. const auto actOnEachVec = [this, loc, arg1Instr, arg2Instr, arg1Loc,
  7529. arg2Loc](uint32_t index, QualType vecType,
  7530. SpirvInstruction *arg0Row) {
  7531. auto *arg1Row = spvBuilder.createCompositeExtract(vecType, arg1Instr,
  7532. {index}, arg1Loc);
  7533. auto *arg2Row = spvBuilder.createCompositeExtract(vecType, arg2Instr,
  7534. {index}, arg2Loc);
  7535. auto *fma = spvBuilder.createGLSLExtInst(
  7536. vecType, GLSLstd450Fma, {arg0Row, arg1Row, arg2Row}, loc);
  7537. spvBuilder.decorateNoContraction(fma, loc);
  7538. return fma;
  7539. };
  7540. return processEachVectorInMatrix(arg0, arg0Instr, actOnEachVec, loc);
  7541. }
  7542. // Non-matrix cases
  7543. auto *fma = spvBuilder.createGLSLExtInst(
  7544. argType, GLSLstd450Fma, {arg0Instr, arg1Instr, arg2Instr}, loc);
  7545. spvBuilder.decorateNoContraction(fma, loc);
  7546. return fma;
  7547. }
  7548. // For scalar and vector argument types.
  7549. {
  7550. if (isScalarType(argType) || isVectorType(argType)) {
  7551. auto *mul = spvBuilder.createBinaryOp(spv::Op::OpIMul, argType, arg0Instr,
  7552. arg1Instr, loc);
  7553. auto *add = spvBuilder.createBinaryOp(spv::Op::OpIAdd, argType, mul,
  7554. arg2Instr, loc);
  7555. spvBuilder.decorateNoContraction(mul, loc);
  7556. spvBuilder.decorateNoContraction(add, loc);
  7557. return add;
  7558. }
  7559. }
  7560. // For matrix argument types.
  7561. {
  7562. uint32_t rowCount = 0, colCount = 0;
  7563. QualType elemType = {};
  7564. if (isMxNMatrix(argType, &elemType, &rowCount, &colCount)) {
  7565. const auto colType = astContext.getExtVectorType(elemType, colCount);
  7566. llvm::SmallVector<SpirvInstruction *, 4> resultRows;
  7567. for (uint32_t i = 0; i < rowCount; ++i) {
  7568. auto *rowArg0 =
  7569. spvBuilder.createCompositeExtract(colType, arg0Instr, {i}, arg0Loc);
  7570. auto *rowArg1 =
  7571. spvBuilder.createCompositeExtract(colType, arg1Instr, {i}, arg1Loc);
  7572. auto *rowArg2 =
  7573. spvBuilder.createCompositeExtract(colType, arg2Instr, {i}, arg2Loc);
  7574. auto *mul = spvBuilder.createBinaryOp(spv::Op::OpIMul, colType, rowArg0,
  7575. rowArg1, loc);
  7576. auto *add = spvBuilder.createBinaryOp(spv::Op::OpIAdd, colType, mul,
  7577. rowArg2, loc);
  7578. spvBuilder.decorateNoContraction(mul, loc);
  7579. spvBuilder.decorateNoContraction(add, loc);
  7580. resultRows.push_back(add);
  7581. }
  7582. return spvBuilder.createCompositeConstruct(argType, resultRows, loc);
  7583. }
  7584. }
  7585. emitError("invalid argument type passed to mad intrinsic function",
  7586. callExpr->getExprLoc());
  7587. return 0;
  7588. }
  7589. SpirvInstruction *SpirvEmitter::processIntrinsicLit(const CallExpr *callExpr) {
  7590. // Signature is: float4 lit(float n_dot_l, float n_dot_h, float m)
  7591. //
  7592. // This function returns a lighting coefficient vector
  7593. // (ambient, diffuse, specular, 1) where:
  7594. // ambient = 1.
  7595. // diffuse = (n_dot_l < 0) ? 0 : n_dot_l
  7596. // specular = (n_dot_l < 0 || n_dot_h < 0) ? 0 : ((n_dot_h) * m)
  7597. auto *nDotL = doExpr(callExpr->getArg(0));
  7598. auto *nDotH = doExpr(callExpr->getArg(1));
  7599. auto *m = doExpr(callExpr->getArg(2));
  7600. const auto loc = callExpr->getExprLoc();
  7601. const QualType floatType = astContext.FloatTy;
  7602. const QualType boolType = astContext.BoolTy;
  7603. SpirvInstruction *floatZero =
  7604. spvBuilder.getConstantFloat(astContext.FloatTy, llvm::APFloat(0.0f));
  7605. SpirvInstruction *floatOne =
  7606. spvBuilder.getConstantFloat(astContext.FloatTy, llvm::APFloat(1.0f));
  7607. const QualType retType = callExpr->getType();
  7608. auto *diffuse = spvBuilder.createGLSLExtInst(
  7609. floatType, GLSLstd450::GLSLstd450FMax, {floatZero, nDotL}, loc);
  7610. auto *min = spvBuilder.createGLSLExtInst(
  7611. floatType, GLSLstd450::GLSLstd450FMin, {nDotL, nDotH}, loc);
  7612. auto *isNeg = spvBuilder.createBinaryOp(spv::Op::OpFOrdLessThan, boolType,
  7613. min, floatZero, loc);
  7614. auto *mul =
  7615. spvBuilder.createBinaryOp(spv::Op::OpFMul, floatType, nDotH, m, loc);
  7616. auto *specular =
  7617. spvBuilder.createSelect(floatType, isNeg, floatZero, mul, loc);
  7618. return spvBuilder.createCompositeConstruct(
  7619. retType, {floatOne, diffuse, specular, floatOne}, callExpr->getLocEnd());
  7620. }
  7621. SpirvInstruction *
  7622. SpirvEmitter::processIntrinsicFrexp(const CallExpr *callExpr) {
  7623. // Signature is: ret frexp(x, exp)
  7624. // [in] x: the input floating-point value.
  7625. // [out] exp: the calculated exponent.
  7626. // [out] ret: the calculated mantissa.
  7627. // All of the above must be a scalar, vector, or matrix of *float* type.
  7628. // The FrexpStruct SPIR-V instruction returns a struct. The first
  7629. // member is the significand (mantissa) and must be of the same type as the
  7630. // input parameter, and the second member is the exponent and must always be a
  7631. // scalar or vector of 32-bit *integer* type.
  7632. // FrexpStruct {
  7633. // <scalar or vector of int/float> mantissa;
  7634. // <scalar or vector of integers> exponent;
  7635. // }
  7636. const Expr *arg = callExpr->getArg(0);
  7637. const auto argType = arg->getType();
  7638. const auto returnType = callExpr->getType();
  7639. const auto loc = callExpr->getExprLoc();
  7640. auto *argInstr = doExpr(arg);
  7641. auto *expInstr = doExpr(callExpr->getArg(1));
  7642. // For scalar and vector argument types.
  7643. {
  7644. uint32_t elemCount = 1;
  7645. if (isScalarType(argType) || isVectorType(argType, nullptr, &elemCount)) {
  7646. const QualType expType =
  7647. elemCount == 1
  7648. ? astContext.IntTy
  7649. : astContext.getExtVectorType(astContext.IntTy, elemCount);
  7650. const auto *frexpStructType = spvContext.getHybridStructType(
  7651. {HybridStructType::FieldInfo(argType, "mantissa"),
  7652. HybridStructType::FieldInfo(expType, "exponent")},
  7653. "FrexpStructType");
  7654. auto *frexp = spvBuilder.createGLSLExtInst(
  7655. frexpStructType, GLSLstd450::GLSLstd450FrexpStruct, {argInstr}, loc);
  7656. auto *exponentInt =
  7657. spvBuilder.createCompositeExtract(expType, frexp, {1}, loc);
  7658. // Since the SPIR-V instruction returns an int, and the intrinsic HLSL
  7659. // expects a float, an conversion must take place before writing the
  7660. // results.
  7661. auto *exponentFloat = spvBuilder.createUnaryOp(
  7662. spv::Op::OpConvertSToF, returnType, exponentInt, loc);
  7663. spvBuilder.createStore(expInstr, exponentFloat, loc);
  7664. return spvBuilder.createCompositeExtract(argType, frexp, {0}, loc);
  7665. }
  7666. }
  7667. // For matrix argument types.
  7668. {
  7669. uint32_t rowCount = 0, colCount = 0;
  7670. if (isMxNMatrix(argType, nullptr, &rowCount, &colCount)) {
  7671. const auto expType =
  7672. astContext.getExtVectorType(astContext.IntTy, colCount);
  7673. const auto colType =
  7674. astContext.getExtVectorType(astContext.FloatTy, colCount);
  7675. const auto *frexpStructType = spvContext.getHybridStructType(
  7676. {HybridStructType::FieldInfo(colType, "mantissa"),
  7677. HybridStructType::FieldInfo(expType, "exponent")},
  7678. "FrexpStructType");
  7679. llvm::SmallVector<SpirvInstruction *, 4> exponents;
  7680. llvm::SmallVector<SpirvInstruction *, 4> mantissas;
  7681. for (uint32_t i = 0; i < rowCount; ++i) {
  7682. auto *curRow = spvBuilder.createCompositeExtract(colType, argInstr, {i},
  7683. arg->getLocStart());
  7684. auto *frexp = spvBuilder.createGLSLExtInst(
  7685. frexpStructType, GLSLstd450::GLSLstd450FrexpStruct, {curRow}, loc);
  7686. auto *exponentInt =
  7687. spvBuilder.createCompositeExtract(expType, frexp, {1}, loc);
  7688. // Since the SPIR-V instruction returns an int, and the intrinsic HLSL
  7689. // expects a float, an conversion must take place before writing the
  7690. // results.
  7691. auto *exponentFloat = spvBuilder.createUnaryOp(
  7692. spv::Op::OpConvertSToF, colType, exponentInt, loc);
  7693. exponents.push_back(exponentFloat);
  7694. mantissas.push_back(
  7695. spvBuilder.createCompositeExtract(colType, frexp, {0}, loc));
  7696. }
  7697. auto *exponentsResult =
  7698. spvBuilder.createCompositeConstruct(returnType, exponents, loc);
  7699. spvBuilder.createStore(expInstr, exponentsResult, loc);
  7700. return spvBuilder.createCompositeConstruct(returnType, mantissas,
  7701. callExpr->getLocEnd());
  7702. }
  7703. }
  7704. emitError("invalid argument type passed to Frexp intrinsic function",
  7705. callExpr->getExprLoc());
  7706. return nullptr;
  7707. }
  7708. SpirvInstruction *
  7709. SpirvEmitter::processIntrinsicLdexp(const CallExpr *callExpr) {
  7710. // Signature: ret ldexp(x, exp)
  7711. // This function uses the following formula: x * 2^exp.
  7712. // Note that we cannot use GLSL extended instruction Ldexp since it requires
  7713. // the exponent to be an integer (vector) but HLSL takes an float (vector)
  7714. // exponent. So we must calculate the result manually.
  7715. const Expr *x = callExpr->getArg(0);
  7716. const auto paramType = x->getType();
  7717. auto *xInstr = doExpr(x);
  7718. auto *expInstr = doExpr(callExpr->getArg(1));
  7719. const auto loc = callExpr->getLocStart();
  7720. const auto arg1Loc = callExpr->getArg(1)->getLocStart();
  7721. // For scalar and vector argument types.
  7722. if (isScalarType(paramType) || isVectorType(paramType)) {
  7723. const auto twoExp = spvBuilder.createGLSLExtInst(
  7724. paramType, GLSLstd450::GLSLstd450Exp2, {expInstr}, loc);
  7725. return spvBuilder.createBinaryOp(spv::Op::OpFMul, paramType, xInstr, twoExp,
  7726. loc);
  7727. }
  7728. // For matrix argument types.
  7729. {
  7730. uint32_t rowCount = 0, colCount = 0;
  7731. if (isMxNMatrix(paramType, nullptr, &rowCount, &colCount)) {
  7732. const auto actOnEachVec = [this, loc, expInstr,
  7733. arg1Loc](uint32_t index, QualType vecType,
  7734. SpirvInstruction *xRowInstr) {
  7735. auto *expRowInstr = spvBuilder.createCompositeExtract(vecType, expInstr,
  7736. {index}, arg1Loc);
  7737. auto *twoExp = spvBuilder.createGLSLExtInst(
  7738. vecType, GLSLstd450::GLSLstd450Exp2, {expRowInstr}, loc);
  7739. return spvBuilder.createBinaryOp(spv::Op::OpFMul, vecType, xRowInstr,
  7740. twoExp, loc);
  7741. };
  7742. return processEachVectorInMatrix(x, xInstr, actOnEachVec, loc);
  7743. }
  7744. }
  7745. emitError("invalid argument type passed to ldexp intrinsic function",
  7746. callExpr->getExprLoc());
  7747. return nullptr;
  7748. }
  7749. SpirvInstruction *SpirvEmitter::processIntrinsicDst(const CallExpr *callExpr) {
  7750. // Signature is float4 dst(float4 src0, float4 src1)
  7751. // result.x = 1;
  7752. // result.y = src0.y * src1.y;
  7753. // result.z = src0.z;
  7754. // result.w = src1.w;
  7755. const QualType f32 = astContext.FloatTy;
  7756. auto *arg0Id = doExpr(callExpr->getArg(0));
  7757. auto *arg1Id = doExpr(callExpr->getArg(1));
  7758. auto arg0Loc = callExpr->getArg(0)->getLocStart();
  7759. auto arg1Loc = callExpr->getArg(1)->getLocStart();
  7760. auto *arg0y = spvBuilder.createCompositeExtract(f32, arg0Id, {1}, arg0Loc);
  7761. auto *arg1y = spvBuilder.createCompositeExtract(f32, arg1Id, {1}, arg1Loc);
  7762. auto *arg0z = spvBuilder.createCompositeExtract(f32, arg0Id, {2}, arg0Loc);
  7763. auto *arg1w = spvBuilder.createCompositeExtract(f32, arg1Id, {3}, arg1Loc);
  7764. auto loc = callExpr->getLocEnd();
  7765. auto *arg0yMularg1y =
  7766. spvBuilder.createBinaryOp(spv::Op::OpFMul, f32, arg0y, arg1y, loc);
  7767. return spvBuilder.createCompositeConstruct(
  7768. callExpr->getType(),
  7769. {spvBuilder.getConstantFloat(astContext.FloatTy, llvm::APFloat(1.0f)),
  7770. arg0yMularg1y, arg0z, arg1w},
  7771. loc);
  7772. }
  7773. SpirvInstruction *SpirvEmitter::processIntrinsicClip(const CallExpr *callExpr) {
  7774. // Discards the current pixel if the specified value is less than zero.
  7775. // TODO: If the argument can be const folded and evaluated, we could
  7776. // potentially avoid creating a branch. This would be a bit challenging for
  7777. // matrix/vector arguments.
  7778. assert(callExpr->getNumArgs() == 1u);
  7779. const Expr *arg = callExpr->getArg(0);
  7780. const auto loc = callExpr->getExprLoc();
  7781. const auto argType = arg->getType();
  7782. const auto boolType = astContext.BoolTy;
  7783. SpirvInstruction *condition = nullptr;
  7784. // Could not determine the argument as a constant. We need to branch based on
  7785. // the argument. If the argument is a vector/matrix, clipping is done if *any*
  7786. // element of the vector/matrix is less than zero.
  7787. auto *argInstr = doExpr(arg);
  7788. QualType elemType = {};
  7789. uint32_t elemCount = 0, rowCount = 0, colCount = 0;
  7790. if (isScalarType(argType)) {
  7791. auto *zero = getValueZero(argType);
  7792. condition = spvBuilder.createBinaryOp(spv::Op::OpFOrdLessThan, boolType,
  7793. argInstr, zero, loc);
  7794. } else if (isVectorType(argType, nullptr, &elemCount)) {
  7795. auto *zero = getValueZero(argType);
  7796. const QualType boolVecType =
  7797. astContext.getExtVectorType(boolType, elemCount);
  7798. auto *cmp = spvBuilder.createBinaryOp(spv::Op::OpFOrdLessThan, boolVecType,
  7799. argInstr, zero, loc);
  7800. condition = spvBuilder.createUnaryOp(spv::Op::OpAny, boolType, cmp, loc);
  7801. } else if (isMxNMatrix(argType, &elemType, &rowCount, &colCount)) {
  7802. const auto floatVecType = astContext.getExtVectorType(elemType, colCount);
  7803. auto *elemZero = getValueZero(elemType);
  7804. llvm::SmallVector<SpirvConstant *, 4> elements(size_t(colCount), elemZero);
  7805. auto *zero = spvBuilder.getConstantComposite(floatVecType, elements);
  7806. llvm::SmallVector<SpirvInstruction *, 4> cmpResults;
  7807. for (uint32_t i = 0; i < rowCount; ++i) {
  7808. auto *lhsVec =
  7809. spvBuilder.createCompositeExtract(floatVecType, argInstr, {i}, loc);
  7810. const auto boolColType = astContext.getExtVectorType(boolType, colCount);
  7811. auto *cmp = spvBuilder.createBinaryOp(spv::Op::OpFOrdLessThan,
  7812. boolColType, lhsVec, zero, loc);
  7813. auto *any = spvBuilder.createUnaryOp(spv::Op::OpAny, boolType, cmp, loc);
  7814. cmpResults.push_back(any);
  7815. }
  7816. const auto boolRowType = astContext.getExtVectorType(boolType, rowCount);
  7817. auto *results =
  7818. spvBuilder.createCompositeConstruct(boolRowType, cmpResults, loc);
  7819. condition =
  7820. spvBuilder.createUnaryOp(spv::Op::OpAny, boolType, results, loc);
  7821. } else {
  7822. emitError("invalid argument type passed to clip intrinsic function", loc);
  7823. return nullptr;
  7824. }
  7825. // Then we need to emit the instruction for the conditional branch.
  7826. auto *thenBB = spvBuilder.createBasicBlock("if.true");
  7827. auto *mergeBB = spvBuilder.createBasicBlock("if.merge");
  7828. // Create the branch instruction. This will end the current basic block.
  7829. spvBuilder.createConditionalBranch(condition, thenBB, mergeBB, loc, mergeBB);
  7830. spvBuilder.addSuccessor(thenBB);
  7831. spvBuilder.addSuccessor(mergeBB);
  7832. spvBuilder.setMergeTarget(mergeBB);
  7833. // Handle the then branch
  7834. spvBuilder.setInsertPoint(thenBB);
  7835. spvBuilder.createKill(loc);
  7836. spvBuilder.addSuccessor(mergeBB);
  7837. // From now on, we'll emit instructions into the merge block.
  7838. spvBuilder.setInsertPoint(mergeBB);
  7839. return nullptr;
  7840. }
  7841. SpirvInstruction *
  7842. SpirvEmitter::processIntrinsicClamp(const CallExpr *callExpr) {
  7843. // According the HLSL reference: clamp(X, Min, Max) takes 3 arguments. Each
  7844. // one may be int, uint, or float.
  7845. const QualType returnType = callExpr->getType();
  7846. GLSLstd450 glslOpcode = GLSLstd450::GLSLstd450UClamp;
  7847. if (isFloatOrVecMatOfFloatType(returnType))
  7848. glslOpcode = GLSLstd450::GLSLstd450FClamp;
  7849. else if (isSintOrVecMatOfSintType(returnType))
  7850. glslOpcode = GLSLstd450::GLSLstd450SClamp;
  7851. // Get the function parameters. Expect 3 parameters.
  7852. assert(callExpr->getNumArgs() == 3u);
  7853. const Expr *argX = callExpr->getArg(0);
  7854. const Expr *argMin = callExpr->getArg(1);
  7855. const Expr *argMax = callExpr->getArg(2);
  7856. const auto loc = callExpr->getExprLoc();
  7857. auto *argXInstr = doExpr(argX);
  7858. auto *argMinInstr = doExpr(argMin);
  7859. auto *argMaxInstr = doExpr(argMax);
  7860. const auto argMinLoc = argMin->getLocStart();
  7861. const auto argMaxLoc = argMax->getLocStart();
  7862. // FClamp, UClamp, and SClamp do not operate on matrices, so we should perform
  7863. // the operation on each vector of the matrix.
  7864. if (isMxNMatrix(argX->getType())) {
  7865. const auto actOnEachVec =
  7866. [this, loc, glslOpcode, argMinInstr, argMaxInstr, argMinLoc, argMaxLoc](
  7867. uint32_t index, QualType vecType, SpirvInstruction *curRow) {
  7868. auto *minRowInstr = spvBuilder.createCompositeExtract(
  7869. vecType, argMinInstr, {index}, argMinLoc);
  7870. auto *maxRowInstr = spvBuilder.createCompositeExtract(
  7871. vecType, argMaxInstr, {index}, argMaxLoc);
  7872. return spvBuilder.createGLSLExtInst(
  7873. vecType, glslOpcode, {curRow, minRowInstr, maxRowInstr}, loc);
  7874. };
  7875. return processEachVectorInMatrix(argX, argXInstr, actOnEachVec, loc);
  7876. }
  7877. return spvBuilder.createGLSLExtInst(
  7878. returnType, glslOpcode, {argXInstr, argMinInstr, argMaxInstr}, loc);
  7879. }
  7880. SpirvInstruction *
  7881. SpirvEmitter::processIntrinsicMemoryBarrier(const CallExpr *callExpr,
  7882. bool isDevice, bool groupSync,
  7883. bool isAllBarrier) {
  7884. // * DeviceMemoryBarrier =
  7885. // OpMemoryBarrier (memScope=Device,
  7886. // sem=Image|Uniform|AcquireRelease)
  7887. //
  7888. // * DeviceMemoryBarrierWithGroupSync =
  7889. // OpControlBarrier(execScope = Workgroup,
  7890. // memScope=Device,
  7891. // sem=Image|Uniform|AcquireRelease)
  7892. const spv::MemorySemanticsMask deviceMemoryBarrierSema =
  7893. spv::MemorySemanticsMask::ImageMemory |
  7894. spv::MemorySemanticsMask::UniformMemory |
  7895. spv::MemorySemanticsMask::AcquireRelease;
  7896. // * GroupMemoryBarrier =
  7897. // OpMemoryBarrier (memScope=Workgroup,
  7898. // sem = Workgroup|AcquireRelease)
  7899. //
  7900. // * GroupMemoryBarrierWithGroupSync =
  7901. // OpControlBarrier (execScope = Workgroup,
  7902. // memScope = Workgroup,
  7903. // sem = Workgroup|AcquireRelease)
  7904. const spv::MemorySemanticsMask groupMemoryBarrierSema =
  7905. spv::MemorySemanticsMask::WorkgroupMemory |
  7906. spv::MemorySemanticsMask::AcquireRelease;
  7907. // * AllMemoryBarrier =
  7908. // OpMemoryBarrier(memScope = Device,
  7909. // sem = Image|Uniform|Workgroup|AcquireRelease)
  7910. //
  7911. // * AllMemoryBarrierWithGroupSync =
  7912. // OpControlBarrier(execScope = Workgroup,
  7913. // memScope = Device,
  7914. // sem = Image|Uniform|Workgroup|AcquireRelease)
  7915. const spv::MemorySemanticsMask allMemoryBarrierSema =
  7916. spv::MemorySemanticsMask::ImageMemory |
  7917. spv::MemorySemanticsMask::UniformMemory |
  7918. spv::MemorySemanticsMask::WorkgroupMemory |
  7919. spv::MemorySemanticsMask::AcquireRelease;
  7920. // Get <result-id> for execution scope.
  7921. // If present, execution scope is always Workgroup!
  7922. llvm::Optional<spv::Scope> execScope = llvm::None;
  7923. if (groupSync) {
  7924. execScope = spv::Scope::Workgroup;
  7925. }
  7926. // Get <result-id> for memory scope
  7927. const spv::Scope memScope =
  7928. (isDevice || isAllBarrier) ? spv::Scope::Device : spv::Scope::Workgroup;
  7929. // Get <result-id> for memory semantics
  7930. const auto memSemaMask = isAllBarrier ? allMemoryBarrierSema
  7931. : isDevice ? deviceMemoryBarrierSema
  7932. : groupMemoryBarrierSema;
  7933. spvBuilder.createBarrier(memScope, memSemaMask, execScope,
  7934. callExpr->getExprLoc());
  7935. return nullptr;
  7936. }
  7937. SpirvInstruction *SpirvEmitter::processNonFpMatrixTranspose(
  7938. QualType matType, SpirvInstruction *matrix, SourceLocation loc) {
  7939. // Simplest way is to flatten the matrix construct a new matrix from the
  7940. // flattened elements. (for a mat4x4).
  7941. QualType elemType = {};
  7942. uint32_t numRows = 0, numCols = 0;
  7943. const bool isMat = isMxNMatrix(matType, &elemType, &numRows, &numCols);
  7944. assert(isMat && !elemType->isFloatingType());
  7945. (void)isMat;
  7946. const auto colQualType = astContext.getExtVectorType(elemType, numRows);
  7947. // You cannot perform a composite construct of an array using a few vectors.
  7948. // The number of constutients passed to OpCompositeConstruct must be equal to
  7949. // the number of array elements.
  7950. llvm::SmallVector<SpirvInstruction *, 4> elems;
  7951. for (uint32_t i = 0; i < numRows; ++i)
  7952. for (uint32_t j = 0; j < numCols; ++j)
  7953. elems.push_back(
  7954. spvBuilder.createCompositeExtract(elemType, matrix, {i, j}, loc));
  7955. llvm::SmallVector<SpirvInstruction *, 4> cols;
  7956. for (uint32_t i = 0; i < numCols; ++i) {
  7957. // The elements in the ith vector of the "transposed" array are at offset i,
  7958. // i + <original-vector-size>, ...
  7959. llvm::SmallVector<SpirvInstruction *, 4> indexes;
  7960. for (uint32_t j = 0; j < numRows; ++j)
  7961. indexes.push_back(elems[i + (j * numCols)]);
  7962. cols.push_back(
  7963. spvBuilder.createCompositeConstruct(colQualType, indexes, loc));
  7964. }
  7965. auto transposeType = astContext.getConstantArrayType(
  7966. colQualType, llvm::APInt(32, numCols), clang::ArrayType::Normal, 0);
  7967. return spvBuilder.createCompositeConstruct(transposeType, cols, loc);
  7968. }
  7969. SpirvInstruction *SpirvEmitter::processNonFpDot(SpirvInstruction *vec1Id,
  7970. SpirvInstruction *vec2Id,
  7971. uint32_t vecSize,
  7972. QualType elemType,
  7973. SourceLocation loc) {
  7974. llvm::SmallVector<SpirvInstruction *, 4> muls;
  7975. for (uint32_t i = 0; i < vecSize; ++i) {
  7976. auto *elem1 = spvBuilder.createCompositeExtract(elemType, vec1Id, {i}, loc);
  7977. auto *elem2 = spvBuilder.createCompositeExtract(elemType, vec2Id, {i}, loc);
  7978. muls.push_back(spvBuilder.createBinaryOp(translateOp(BO_Mul, elemType),
  7979. elemType, elem1, elem2, loc));
  7980. }
  7981. SpirvInstruction *sum = muls[0];
  7982. for (uint32_t i = 1; i < vecSize; ++i) {
  7983. sum = spvBuilder.createBinaryOp(translateOp(BO_Add, elemType), elemType,
  7984. sum, muls[i], loc);
  7985. }
  7986. return sum;
  7987. }
  7988. SpirvInstruction *SpirvEmitter::processNonFpScalarTimesMatrix(
  7989. QualType scalarType, SpirvInstruction *scalar, QualType matrixType,
  7990. SpirvInstruction *matrix, SourceLocation loc) {
  7991. assert(isScalarType(scalarType));
  7992. QualType elemType = {};
  7993. uint32_t numRows = 0, numCols = 0;
  7994. const bool isMat = isMxNMatrix(matrixType, &elemType, &numRows, &numCols);
  7995. assert(isMat);
  7996. assert(isSameType(astContext, scalarType, elemType));
  7997. (void)isMat;
  7998. // We need to multiply the scalar by each vector of the matrix.
  7999. // The front-end guarantees that the scalar and matrix element type are
  8000. // the same. For example, if the scalar is a float, the matrix is casted
  8001. // to a float matrix before being passed to mul(). It is also guaranteed
  8002. // that types such as bool are casted to float or int before being
  8003. // passed to mul().
  8004. const auto rowType = astContext.getExtVectorType(elemType, numCols);
  8005. llvm::SmallVector<SpirvInstruction *, 4> splat(size_t(numCols), scalar);
  8006. auto *scalarSplat = spvBuilder.createCompositeConstruct(rowType, splat, loc);
  8007. llvm::SmallVector<SpirvInstruction *, 4> mulRows;
  8008. for (uint32_t row = 0; row < numRows; ++row) {
  8009. auto *rowInstr =
  8010. spvBuilder.createCompositeExtract(rowType, matrix, {row}, loc);
  8011. mulRows.push_back(spvBuilder.createBinaryOp(
  8012. translateOp(BO_Mul, scalarType), rowType, rowInstr, scalarSplat, loc));
  8013. }
  8014. return spvBuilder.createCompositeConstruct(matrixType, mulRows, loc);
  8015. }
  8016. SpirvInstruction *SpirvEmitter::processNonFpVectorTimesMatrix(
  8017. QualType vecType, SpirvInstruction *vector, QualType matType,
  8018. SpirvInstruction *matrix, SourceLocation loc,
  8019. SpirvInstruction *matrixTranspose) {
  8020. // This function assumes that the vector element type and matrix elemet type
  8021. // are the same.
  8022. QualType vecElemType = {}, matElemType = {};
  8023. uint32_t vecSize = 0, numRows = 0, numCols = 0;
  8024. const bool isVec = isVectorType(vecType, &vecElemType, &vecSize);
  8025. const bool isMat = isMxNMatrix(matType, &matElemType, &numRows, &numCols);
  8026. assert(isSameType(astContext, vecElemType, matElemType));
  8027. assert(isVec);
  8028. assert(isMat);
  8029. assert(vecSize == numRows);
  8030. (void)isVec;
  8031. (void)isMat;
  8032. // When processing vector times matrix, the vector is a row vector, and it
  8033. // should be multiplied by the matrix *columns*. The most efficient way to
  8034. // handle this in SPIR-V would be to first transpose the matrix, and then use
  8035. // OpAccessChain.
  8036. if (!matrixTranspose)
  8037. matrixTranspose = processNonFpMatrixTranspose(matType, matrix, loc);
  8038. llvm::SmallVector<SpirvInstruction *, 4> resultElems;
  8039. for (uint32_t col = 0; col < numCols; ++col) {
  8040. auto *colInstr =
  8041. spvBuilder.createCompositeExtract(vecType, matrixTranspose, {col}, loc);
  8042. resultElems.push_back(
  8043. processNonFpDot(vector, colInstr, vecSize, vecElemType, loc));
  8044. }
  8045. return spvBuilder.createCompositeConstruct(
  8046. astContext.getExtVectorType(vecElemType, numCols), resultElems, loc);
  8047. }
  8048. SpirvInstruction *SpirvEmitter::processNonFpMatrixTimesVector(
  8049. QualType matType, SpirvInstruction *matrix, QualType vecType,
  8050. SpirvInstruction *vector, SourceLocation loc) {
  8051. // This function assumes that the vector element type and matrix elemet type
  8052. // are the same.
  8053. QualType vecElemType = {}, matElemType = {};
  8054. uint32_t vecSize = 0, numRows = 0, numCols = 0;
  8055. const bool isVec = isVectorType(vecType, &vecElemType, &vecSize);
  8056. const bool isMat = isMxNMatrix(matType, &matElemType, &numRows, &numCols);
  8057. assert(isSameType(astContext, vecElemType, matElemType));
  8058. assert(isVec);
  8059. assert(isMat);
  8060. assert(vecSize == numCols);
  8061. (void)isVec;
  8062. (void)isMat;
  8063. // When processing matrix times vector, the vector is a column vector. So we
  8064. // simply get each row of the matrix and perform a dot product with the
  8065. // vector.
  8066. llvm::SmallVector<SpirvInstruction *, 4> resultElems;
  8067. for (uint32_t row = 0; row < numRows; ++row) {
  8068. auto *rowInstr =
  8069. spvBuilder.createCompositeExtract(vecType, matrix, {row}, loc);
  8070. resultElems.push_back(
  8071. processNonFpDot(rowInstr, vector, vecSize, vecElemType, loc));
  8072. }
  8073. return spvBuilder.createCompositeConstruct(
  8074. astContext.getExtVectorType(vecElemType, numRows), resultElems, loc);
  8075. }
  8076. SpirvInstruction *SpirvEmitter::processNonFpMatrixTimesMatrix(
  8077. QualType lhsType, SpirvInstruction *lhs, QualType rhsType,
  8078. SpirvInstruction *rhs, SourceLocation loc) {
  8079. // This function assumes that the vector element type and matrix elemet type
  8080. // are the same.
  8081. QualType lhsElemType = {}, rhsElemType = {};
  8082. uint32_t lhsNumRows = 0, lhsNumCols = 0;
  8083. uint32_t rhsNumRows = 0, rhsNumCols = 0;
  8084. const bool lhsIsMat =
  8085. isMxNMatrix(lhsType, &lhsElemType, &lhsNumRows, &lhsNumCols);
  8086. const bool rhsIsMat =
  8087. isMxNMatrix(rhsType, &rhsElemType, &rhsNumRows, &rhsNumCols);
  8088. assert(isSameType(astContext, lhsElemType, rhsElemType));
  8089. assert(lhsIsMat && rhsIsMat);
  8090. assert(lhsNumCols == rhsNumRows);
  8091. (void)rhsIsMat;
  8092. (void)lhsIsMat;
  8093. auto *rhsTranspose = processNonFpMatrixTranspose(rhsType, rhs, loc);
  8094. const auto vecType = astContext.getExtVectorType(lhsElemType, lhsNumCols);
  8095. llvm::SmallVector<SpirvInstruction *, 4> resultRows;
  8096. for (uint32_t row = 0; row < lhsNumRows; ++row) {
  8097. auto *rowInstr =
  8098. spvBuilder.createCompositeExtract(vecType, lhs, {row}, loc);
  8099. resultRows.push_back(processNonFpVectorTimesMatrix(
  8100. vecType, rowInstr, rhsType, rhs, loc, rhsTranspose));
  8101. }
  8102. // The resulting matrix will have 'lhsNumRows' rows and 'rhsNumCols' columns.
  8103. const auto resultColType =
  8104. astContext.getExtVectorType(lhsElemType, rhsNumCols);
  8105. const auto resultType = astContext.getConstantArrayType(
  8106. resultColType, llvm::APInt(32, lhsNumRows), clang::ArrayType::Normal, 0);
  8107. return spvBuilder.createCompositeConstruct(resultType, resultRows, loc);
  8108. }
  8109. SpirvInstruction *SpirvEmitter::processIntrinsicMul(const CallExpr *callExpr) {
  8110. const QualType returnType = callExpr->getType();
  8111. // Get the function parameters. Expect 2 parameters.
  8112. assert(callExpr->getNumArgs() == 2u);
  8113. const Expr *arg0 = callExpr->getArg(0);
  8114. const Expr *arg1 = callExpr->getArg(1);
  8115. const QualType arg0Type = arg0->getType();
  8116. const QualType arg1Type = arg1->getType();
  8117. auto loc = callExpr->getExprLoc();
  8118. // The HLSL mul() function takes 2 arguments. Each argument may be a scalar,
  8119. // vector, or matrix. The frontend ensures that the two arguments have the
  8120. // same component type. The only allowed component types are int and float.
  8121. // mul(scalar, vector)
  8122. {
  8123. uint32_t elemCount = 0;
  8124. if (isScalarType(arg0Type) && isVectorType(arg1Type, nullptr, &elemCount)) {
  8125. auto *arg1Id = doExpr(arg1);
  8126. // We can use OpVectorTimesScalar if arguments are floats.
  8127. if (arg0Type->isFloatingType())
  8128. return spvBuilder.createBinaryOp(spv::Op::OpVectorTimesScalar,
  8129. returnType, arg1Id, doExpr(arg0), loc);
  8130. // Use OpIMul for integers
  8131. return spvBuilder.createBinaryOp(spv::Op::OpIMul, returnType,
  8132. createVectorSplat(arg0, elemCount),
  8133. arg1Id, loc);
  8134. }
  8135. }
  8136. // mul(vector, scalar)
  8137. {
  8138. uint32_t elemCount = 0;
  8139. if (isVectorType(arg0Type, nullptr, &elemCount) && isScalarType(arg1Type)) {
  8140. auto *arg0Id = doExpr(arg0);
  8141. // We can use OpVectorTimesScalar if arguments are floats.
  8142. if (arg1Type->isFloatingType())
  8143. return spvBuilder.createBinaryOp(spv::Op::OpVectorTimesScalar,
  8144. returnType, arg0Id, doExpr(arg1), loc);
  8145. // Use OpIMul for integers
  8146. return spvBuilder.createBinaryOp(spv::Op::OpIMul, returnType, arg0Id,
  8147. createVectorSplat(arg1, elemCount), loc);
  8148. }
  8149. }
  8150. // mul(vector, vector)
  8151. if (isVectorType(arg0Type) && isVectorType(arg1Type)) {
  8152. // mul( Mat(1xM), Mat(Mx1) ) results in a scalar (same as dot product)
  8153. if (isScalarType(returnType)) {
  8154. return processIntrinsicDot(callExpr);
  8155. }
  8156. // mul( Mat(Mx1), Mat(1xN) ) results in a MxN matrix.
  8157. QualType elemType = {};
  8158. uint32_t numRows = 0;
  8159. if (isMxNMatrix(returnType, &elemType, &numRows)) {
  8160. llvm::SmallVector<SpirvInstruction *, 4> rows;
  8161. auto *arg0Id = doExpr(arg0);
  8162. auto *arg1Id = doExpr(arg1);
  8163. for (uint32_t i = 0; i < numRows; ++i) {
  8164. auto *scalar =
  8165. spvBuilder.createCompositeExtract(elemType, arg0Id, {i}, loc);
  8166. rows.push_back(spvBuilder.createBinaryOp(
  8167. spv::Op::OpVectorTimesScalar, arg1Type, arg1Id, scalar, loc));
  8168. }
  8169. return spvBuilder.createCompositeConstruct(returnType, rows, loc);
  8170. }
  8171. llvm_unreachable("bad arguments passed to mul");
  8172. }
  8173. // All the following cases require handling arg0 and arg1 expressions first.
  8174. auto *arg0Id = doExpr(arg0);
  8175. auto *arg1Id = doExpr(arg1);
  8176. // mul(scalar, scalar)
  8177. if (isScalarType(arg0Type) && isScalarType(arg1Type))
  8178. return spvBuilder.createBinaryOp(translateOp(BO_Mul, arg0Type), returnType,
  8179. arg0Id, arg1Id, loc);
  8180. // mul(scalar, matrix)
  8181. {
  8182. QualType elemType = {};
  8183. if (isScalarType(arg0Type) && isMxNMatrix(arg1Type, &elemType)) {
  8184. // OpMatrixTimesScalar can only be used if *both* the matrix element type
  8185. // and the scalar type are float.
  8186. if (arg0Type->isFloatingType() && elemType->isFloatingType())
  8187. return spvBuilder.createBinaryOp(spv::Op::OpMatrixTimesScalar,
  8188. returnType, arg1Id, arg0Id, loc);
  8189. else
  8190. return processNonFpScalarTimesMatrix(arg0Type, arg0Id, arg1Type, arg1Id,
  8191. callExpr->getExprLoc());
  8192. }
  8193. }
  8194. // mul(matrix, scalar)
  8195. {
  8196. QualType elemType = {};
  8197. if (isScalarType(arg1Type) && isMxNMatrix(arg0Type, &elemType)) {
  8198. // OpMatrixTimesScalar can only be used if *both* the matrix element type
  8199. // and the scalar type are float.
  8200. if (arg1Type->isFloatingType() && elemType->isFloatingType())
  8201. return spvBuilder.createBinaryOp(spv::Op::OpMatrixTimesScalar,
  8202. returnType, arg0Id, arg1Id, loc);
  8203. else
  8204. return processNonFpScalarTimesMatrix(arg1Type, arg1Id, arg0Type, arg0Id,
  8205. callExpr->getExprLoc());
  8206. }
  8207. }
  8208. // mul(vector, matrix)
  8209. {
  8210. QualType vecElemType = {}, matElemType = {};
  8211. uint32_t elemCount = 0, numRows = 0;
  8212. if (isVectorType(arg0Type, &vecElemType, &elemCount) &&
  8213. isMxNMatrix(arg1Type, &matElemType, &numRows)) {
  8214. assert(elemCount == numRows);
  8215. if (vecElemType->isFloatingType() && matElemType->isFloatingType())
  8216. return spvBuilder.createBinaryOp(spv::Op::OpMatrixTimesVector,
  8217. returnType, arg1Id, arg0Id, loc);
  8218. else
  8219. return processNonFpVectorTimesMatrix(arg0Type, arg0Id, arg1Type, arg1Id,
  8220. callExpr->getExprLoc());
  8221. }
  8222. }
  8223. // mul(matrix, vector)
  8224. {
  8225. QualType vecElemType = {}, matElemType = {};
  8226. uint32_t elemCount = 0, numCols = 0;
  8227. if (isMxNMatrix(arg0Type, &matElemType, nullptr, &numCols) &&
  8228. isVectorType(arg1Type, &vecElemType, &elemCount)) {
  8229. assert(elemCount == numCols);
  8230. if (vecElemType->isFloatingType() && matElemType->isFloatingType())
  8231. return spvBuilder.createBinaryOp(spv::Op::OpVectorTimesMatrix,
  8232. returnType, arg1Id, arg0Id, loc);
  8233. else
  8234. return processNonFpMatrixTimesVector(arg0Type, arg0Id, arg1Type, arg1Id,
  8235. callExpr->getExprLoc());
  8236. }
  8237. }
  8238. // mul(matrix, matrix)
  8239. {
  8240. // The front-end ensures that the two matrix element types match.
  8241. QualType elemType = {};
  8242. uint32_t lhsCols = 0, rhsRows = 0;
  8243. if (isMxNMatrix(arg0Type, &elemType, nullptr, &lhsCols) &&
  8244. isMxNMatrix(arg1Type, nullptr, &rhsRows, nullptr)) {
  8245. assert(lhsCols == rhsRows);
  8246. if (elemType->isFloatingType())
  8247. return spvBuilder.createBinaryOp(spv::Op::OpMatrixTimesMatrix,
  8248. returnType, arg1Id, arg0Id, loc);
  8249. else
  8250. return processNonFpMatrixTimesMatrix(arg0Type, arg0Id, arg1Type, arg1Id,
  8251. callExpr->getExprLoc());
  8252. }
  8253. }
  8254. emitError("invalid argument type passed to mul intrinsic function",
  8255. callExpr->getExprLoc());
  8256. return nullptr;
  8257. }
  8258. SpirvInstruction *
  8259. SpirvEmitter::processIntrinsicPrintf(const CallExpr *callExpr) {
  8260. // C99, s6.5.2.2/6: "If the expression that denotes the called function has a
  8261. // type that does not include a prototype, the integer promotions are
  8262. // performed on each argument, and arguments that have type float are promoted
  8263. // to double. These are called the default argument promotions."
  8264. // C++: All the variadic parameters undergo default promotions before they're
  8265. // received by the function.
  8266. //
  8267. // Therefore by default floating point arguments will be evaluated as double
  8268. // by this function.
  8269. //
  8270. // TODO: We may want to change this behavior for SPIR-V.
  8271. const auto returnType = callExpr->getType();
  8272. const auto numArgs = callExpr->getNumArgs();
  8273. const auto loc = callExpr->getExprLoc();
  8274. assert(numArgs >= 1u);
  8275. llvm::SmallVector<SpirvInstruction *, 4> args;
  8276. for (uint32_t argIndex = 0; argIndex < numArgs; ++argIndex)
  8277. args.push_back(doExpr(callExpr->getArg(argIndex)));
  8278. return spvBuilder.createNonSemanticDebugPrintfExtInst(
  8279. returnType, NonSemanticDebugPrintfDebugPrintf, args, loc);
  8280. }
  8281. SpirvInstruction *SpirvEmitter::processIntrinsicDot(const CallExpr *callExpr) {
  8282. // Get the function parameters. Expect 2 vectors as parameters.
  8283. assert(callExpr->getNumArgs() == 2u);
  8284. const Expr *arg0 = callExpr->getArg(0);
  8285. const Expr *arg1 = callExpr->getArg(1);
  8286. auto *arg0Id = doExpr(arg0);
  8287. auto *arg1Id = doExpr(arg1);
  8288. QualType arg0Type = arg0->getType();
  8289. QualType arg1Type = arg1->getType();
  8290. uint32_t vec0Size = 0, vec1Size = 0;
  8291. QualType vec0ComponentType = {}, vec1ComponentType = {};
  8292. QualType returnType = {};
  8293. const bool arg0isScalarOrVec =
  8294. isScalarOrVectorType(arg0Type, &vec0ComponentType, &vec0Size);
  8295. const bool arg1isScalarOrVec =
  8296. isScalarOrVectorType(arg1Type, &vec1ComponentType, &vec1Size);
  8297. const bool returnIsScalar = isScalarType(callExpr->getType(), &returnType);
  8298. // Each argument should either be a vector or a scalar
  8299. assert(arg0isScalarOrVec && arg1isScalarOrVec);
  8300. // The result type must be a scalar.
  8301. assert(returnIsScalar);
  8302. // The element type of each argument and the return type must be the same.
  8303. assert(returnType == vec1ComponentType);
  8304. assert(vec0ComponentType == vec1ComponentType);
  8305. // The size of the two arguments must be equal.
  8306. assert(vec0Size == vec1Size);
  8307. // Acceptable vector sizes are 1,2,3,4.
  8308. assert(vec0Size >= 1 && vec0Size <= 4);
  8309. (void)arg0isScalarOrVec;
  8310. (void)arg1isScalarOrVec;
  8311. (void)returnIsScalar;
  8312. (void)vec0ComponentType;
  8313. (void)vec1ComponentType;
  8314. (void)vec1Size;
  8315. auto loc = callExpr->getLocStart();
  8316. // According to HLSL reference, the dot function only works on integers
  8317. // and floats.
  8318. assert(returnType->isFloatingType() || returnType->isIntegerType());
  8319. // Special case: dot product of two vectors, each of size 1. That is
  8320. // basically the same as regular multiplication of 2 scalars.
  8321. if (vec0Size == 1) {
  8322. const spv::Op spvOp = translateOp(BO_Mul, arg0Type);
  8323. return spvBuilder.createBinaryOp(spvOp, returnType, arg0Id, arg1Id, loc);
  8324. }
  8325. // If the vectors are of type Float, we can use OpDot.
  8326. if (returnType->isFloatingType()) {
  8327. return spvBuilder.createBinaryOp(spv::Op::OpDot, returnType, arg0Id, arg1Id,
  8328. loc);
  8329. }
  8330. // Vector component type is Integer (signed or unsigned).
  8331. // Create all instructions necessary to perform a dot product on
  8332. // two integer vectors. SPIR-V OpDot does not support integer vectors.
  8333. // Therefore, we use other SPIR-V instructions (addition and
  8334. // multiplication).
  8335. else {
  8336. SpirvInstruction *result = nullptr;
  8337. llvm::SmallVector<SpirvInstruction *, 4> multIds;
  8338. const spv::Op multSpvOp = translateOp(BO_Mul, arg0Type);
  8339. const spv::Op addSpvOp = translateOp(BO_Add, arg0Type);
  8340. // Extract members from the two vectors and multiply them.
  8341. for (unsigned int i = 0; i < vec0Size; ++i) {
  8342. auto *vec0member = spvBuilder.createCompositeExtract(
  8343. returnType, arg0Id, {i}, arg0->getLocStart());
  8344. auto *vec1member = spvBuilder.createCompositeExtract(
  8345. returnType, arg1Id, {i}, arg1->getLocStart());
  8346. auto *multId = spvBuilder.createBinaryOp(multSpvOp, returnType,
  8347. vec0member, vec1member, loc);
  8348. multIds.push_back(multId);
  8349. }
  8350. // Add all the multiplications.
  8351. result = multIds[0];
  8352. for (unsigned int i = 1; i < vec0Size; ++i) {
  8353. auto *additionId = spvBuilder.createBinaryOp(addSpvOp, returnType, result,
  8354. multIds[i], loc);
  8355. result = additionId;
  8356. }
  8357. return result;
  8358. }
  8359. }
  8360. SpirvInstruction *SpirvEmitter::processIntrinsicRcp(const CallExpr *callExpr) {
  8361. // 'rcp' takes only 1 argument that is a scalar, vector, or matrix of type
  8362. // float or double.
  8363. assert(callExpr->getNumArgs() == 1u);
  8364. const QualType returnType = callExpr->getType();
  8365. const Expr *arg = callExpr->getArg(0);
  8366. auto *argId = doExpr(arg);
  8367. const QualType argType = arg->getType();
  8368. auto loc = callExpr->getLocStart();
  8369. // For cases with matrix argument.
  8370. QualType elemType = {};
  8371. uint32_t numRows = 0, numCols = 0;
  8372. if (isMxNMatrix(argType, &elemType, &numRows, &numCols)) {
  8373. auto *vecOne = getVecValueOne(elemType, numCols);
  8374. const auto actOnEachVec = [this, vecOne, loc](uint32_t /*index*/,
  8375. QualType vecType,
  8376. SpirvInstruction *curRow) {
  8377. return spvBuilder.createBinaryOp(spv::Op::OpFDiv, vecType, vecOne, curRow,
  8378. loc);
  8379. };
  8380. return processEachVectorInMatrix(arg, argId, actOnEachVec, loc);
  8381. }
  8382. // For cases with scalar or vector arguments.
  8383. return spvBuilder.createBinaryOp(spv::Op::OpFDiv, returnType,
  8384. getValueOne(argType), argId, loc);
  8385. }
  8386. SpirvInstruction *
  8387. SpirvEmitter::processIntrinsicReadClock(const CallExpr *callExpr) {
  8388. auto *scope = doExpr(callExpr->getArg(0));
  8389. assert(scope->getAstResultType()->isIntegerType());
  8390. return spvBuilder.createReadClock(scope, callExpr->getExprLoc());
  8391. }
  8392. SpirvInstruction *
  8393. SpirvEmitter::processIntrinsicAllOrAny(const CallExpr *callExpr,
  8394. spv::Op spvOp) {
  8395. // 'all' and 'any' take only 1 parameter.
  8396. assert(callExpr->getNumArgs() == 1u);
  8397. const QualType returnType = callExpr->getType();
  8398. const Expr *arg = callExpr->getArg(0);
  8399. const QualType argType = arg->getType();
  8400. const auto loc = callExpr->getExprLoc();
  8401. // Handle scalars, vectors of size 1, and 1x1 matrices as arguments.
  8402. // Optimization: can directly cast them to boolean. No need for OpAny/OpAll.
  8403. {
  8404. QualType scalarType = {};
  8405. if (isScalarType(argType, &scalarType) &&
  8406. (scalarType->isBooleanType() || scalarType->isFloatingType() ||
  8407. scalarType->isIntegerType()))
  8408. return castToBool(doExpr(arg), argType, returnType, loc);
  8409. }
  8410. // Handle vectors larger than 1, Mx1 matrices, and 1xN matrices as arguments.
  8411. // Cast the vector to a boolean vector, then run OpAny/OpAll on it.
  8412. {
  8413. QualType elemType = {};
  8414. uint32_t size = 0;
  8415. if (isVectorType(argType, &elemType, &size)) {
  8416. const QualType castToBoolType =
  8417. astContext.getExtVectorType(returnType, size);
  8418. auto *castedToBool =
  8419. castToBool(doExpr(arg), argType, castToBoolType, loc);
  8420. return spvBuilder.createUnaryOp(spvOp, returnType, castedToBool, loc);
  8421. }
  8422. }
  8423. // Handle MxN matrices as arguments.
  8424. {
  8425. QualType elemType = {};
  8426. uint32_t matRowCount = 0, matColCount = 0;
  8427. if (isMxNMatrix(argType, &elemType, &matRowCount, &matColCount)) {
  8428. auto *matrix = doExpr(arg);
  8429. const QualType vecType = getComponentVectorType(astContext, argType);
  8430. llvm::SmallVector<SpirvInstruction *, 4> rowResults;
  8431. for (uint32_t i = 0; i < matRowCount; ++i) {
  8432. // Extract the row which is a float vector of size matColCount.
  8433. auto *rowFloatVec = spvBuilder.createCompositeExtract(
  8434. vecType, matrix, {i}, arg->getLocStart());
  8435. // Cast the float vector to boolean vector.
  8436. const auto rowFloatQualType =
  8437. astContext.getExtVectorType(elemType, matColCount);
  8438. const auto rowBoolQualType =
  8439. astContext.getExtVectorType(returnType, matColCount);
  8440. auto *rowBoolVec = castToBool(rowFloatVec, rowFloatQualType,
  8441. rowBoolQualType, arg->getLocStart());
  8442. // Perform OpAny/OpAll on the boolean vector.
  8443. rowResults.push_back(
  8444. spvBuilder.createUnaryOp(spvOp, returnType, rowBoolVec, loc));
  8445. }
  8446. // Create a new vector that is the concatenation of results of all rows.
  8447. const QualType vecOfBools =
  8448. astContext.getExtVectorType(astContext.BoolTy, matRowCount);
  8449. auto *row =
  8450. spvBuilder.createCompositeConstruct(vecOfBools, rowResults, loc);
  8451. // Run OpAny/OpAll on the newly-created vector.
  8452. return spvBuilder.createUnaryOp(spvOp, returnType, row, loc);
  8453. }
  8454. }
  8455. // All types should be handled already.
  8456. llvm_unreachable("Unknown argument type passed to all()/any().");
  8457. return nullptr;
  8458. }
  8459. SpirvInstruction *
  8460. SpirvEmitter::processIntrinsicAsType(const CallExpr *callExpr) {
  8461. // This function handles 'asint', 'asuint', 'asfloat', and 'asdouble'.
  8462. // Method 1: ret asint(arg)
  8463. // arg component type = {float, uint}
  8464. // arg template type = {scalar, vector, matrix}
  8465. // ret template type = same as arg template type.
  8466. // ret component type = int
  8467. // Method 2: ret asuint(arg)
  8468. // arg component type = {float, int}
  8469. // arg template type = {scalar, vector, matrix}
  8470. // ret template type = same as arg template type.
  8471. // ret component type = uint
  8472. // Method 3: ret asfloat(arg)
  8473. // arg component type = {float, uint, int}
  8474. // arg template type = {scalar, vector, matrix}
  8475. // ret template type = same as arg template type.
  8476. // ret component type = float
  8477. // Method 4: double asdouble(uint lowbits, uint highbits)
  8478. // Method 5: double2 asdouble(uint2 lowbits, uint2 highbits)
  8479. // Method 6:
  8480. // void asuint(
  8481. // in double value,
  8482. // out uint lowbits,
  8483. // out uint highbits
  8484. // );
  8485. const QualType returnType = callExpr->getType();
  8486. const uint32_t numArgs = callExpr->getNumArgs();
  8487. const Expr *arg0 = callExpr->getArg(0);
  8488. const QualType argType = arg0->getType();
  8489. const auto loc = callExpr->getExprLoc();
  8490. // Method 3 return type may be the same as arg type, so it would be a no-op.
  8491. if (isSameType(astContext, returnType, argType))
  8492. return doExpr(arg0);
  8493. switch (numArgs) {
  8494. case 1: {
  8495. // Handling Method 1, 2, and 3.
  8496. auto *argInstr = doExpr(arg0);
  8497. QualType fromElemType = {};
  8498. uint32_t numRows = 0, numCols = 0;
  8499. // For non-matrix arguments (scalar or vector), just do an OpBitCast.
  8500. if (!isMxNMatrix(argType, &fromElemType, &numRows, &numCols)) {
  8501. return spvBuilder.createUnaryOp(spv::Op::OpBitcast, returnType, argInstr,
  8502. loc);
  8503. }
  8504. // Input or output type is a matrix.
  8505. const QualType toElemType = hlsl::GetHLSLMatElementType(returnType);
  8506. llvm::SmallVector<SpirvInstruction *, 4> castedRows;
  8507. const auto fromVecType = astContext.getExtVectorType(fromElemType, numCols);
  8508. const auto toVecType = astContext.getExtVectorType(toElemType, numCols);
  8509. for (uint32_t row = 0; row < numRows; ++row) {
  8510. auto *rowInstr = spvBuilder.createCompositeExtract(
  8511. fromVecType, argInstr, {row}, arg0->getLocStart());
  8512. castedRows.push_back(spvBuilder.createUnaryOp(spv::Op::OpBitcast,
  8513. toVecType, rowInstr, loc));
  8514. }
  8515. return spvBuilder.createCompositeConstruct(returnType, castedRows, loc);
  8516. }
  8517. case 2: {
  8518. auto *lowbits = doExpr(arg0);
  8519. auto *highbits = doExpr(callExpr->getArg(1));
  8520. const auto uintType = astContext.UnsignedIntTy;
  8521. const auto doubleType = astContext.DoubleTy;
  8522. // Handling Method 4
  8523. if (argType->isUnsignedIntegerType()) {
  8524. const auto uintVec2Type = astContext.getExtVectorType(uintType, 2);
  8525. auto *operand = spvBuilder.createCompositeConstruct(
  8526. uintVec2Type, {lowbits, highbits}, loc);
  8527. return spvBuilder.createUnaryOp(spv::Op::OpBitcast, doubleType, operand,
  8528. loc);
  8529. }
  8530. // Handling Method 5
  8531. else {
  8532. const auto uintVec4Type = astContext.getExtVectorType(uintType, 4);
  8533. const auto doubleVec2Type = astContext.getExtVectorType(doubleType, 2);
  8534. auto *operand = spvBuilder.createVectorShuffle(
  8535. uintVec4Type, lowbits, highbits, {0, 2, 1, 3}, loc);
  8536. return spvBuilder.createUnaryOp(spv::Op::OpBitcast, doubleVec2Type,
  8537. operand, loc);
  8538. }
  8539. }
  8540. case 3: {
  8541. // Handling Method 6.
  8542. auto *value = doExpr(arg0);
  8543. auto *lowbits = doExpr(callExpr->getArg(1));
  8544. auto *highbits = doExpr(callExpr->getArg(2));
  8545. const auto uintType = astContext.UnsignedIntTy;
  8546. const auto uintVec2Type = astContext.getExtVectorType(uintType, 2);
  8547. auto *vecResult =
  8548. spvBuilder.createUnaryOp(spv::Op::OpBitcast, uintVec2Type, value, loc);
  8549. spvBuilder.createStore(lowbits,
  8550. spvBuilder.createCompositeExtract(
  8551. uintType, vecResult, {0}, arg0->getLocStart()),
  8552. loc);
  8553. spvBuilder.createStore(highbits,
  8554. spvBuilder.createCompositeExtract(
  8555. uintType, vecResult, {1}, arg0->getLocStart()),
  8556. loc);
  8557. return nullptr;
  8558. }
  8559. default:
  8560. emitError("unrecognized signature for %0 intrinsic function", loc)
  8561. << callExpr->getDirectCallee()->getName();
  8562. return nullptr;
  8563. }
  8564. }
  8565. SpirvInstruction *
  8566. SpirvEmitter::processD3DCOLORtoUBYTE4(const CallExpr *callExpr) {
  8567. // Should take a float4 and return an int4 by doing:
  8568. // int4 result = input.zyxw * 255.001953;
  8569. // Maximum float precision makes the scaling factor 255.002.
  8570. const auto arg = callExpr->getArg(0);
  8571. auto *argId = doExpr(arg);
  8572. const auto argType = arg->getType();
  8573. auto loc = callExpr->getLocStart();
  8574. auto *swizzle =
  8575. spvBuilder.createVectorShuffle(argType, argId, argId, {2, 1, 0, 3}, loc);
  8576. auto *scaled = spvBuilder.createBinaryOp(
  8577. spv::Op::OpVectorTimesScalar, argType, swizzle,
  8578. spvBuilder.getConstantFloat(astContext.FloatTy, llvm::APFloat(255.002f)),
  8579. loc);
  8580. return castToInt(scaled, arg->getType(), callExpr->getType(), loc);
  8581. }
  8582. SpirvInstruction *
  8583. SpirvEmitter::processIntrinsicIsFinite(const CallExpr *callExpr) {
  8584. // Since OpIsFinite needs the Kernel capability, translation is instead done
  8585. // using OpIsNan and OpIsInf:
  8586. // isFinite = !(isNan || isInf)
  8587. const auto arg = doExpr(callExpr->getArg(0));
  8588. const auto returnType = callExpr->getType();
  8589. const auto loc = callExpr->getExprLoc();
  8590. const auto isNan =
  8591. spvBuilder.createUnaryOp(spv::Op::OpIsNan, returnType, arg, loc);
  8592. const auto isInf =
  8593. spvBuilder.createUnaryOp(spv::Op::OpIsInf, returnType, arg, loc);
  8594. const auto isNanOrInf = spvBuilder.createBinaryOp(
  8595. spv::Op::OpLogicalOr, returnType, isNan, isInf, loc);
  8596. return spvBuilder.createUnaryOp(spv::Op::OpLogicalNot, returnType, isNanOrInf,
  8597. loc);
  8598. }
  8599. SpirvInstruction *
  8600. SpirvEmitter::processIntrinsicSinCos(const CallExpr *callExpr) {
  8601. // Since there is no sincos equivalent in SPIR-V, we need to perform Sin
  8602. // once and Cos once. We can reuse existing Sine/Cosine handling functions.
  8603. CallExpr *sincosExpr =
  8604. new (astContext) CallExpr(astContext, Stmt::StmtClass::NoStmtClass, {});
  8605. sincosExpr->setType(callExpr->getArg(0)->getType());
  8606. sincosExpr->setNumArgs(astContext, 1);
  8607. sincosExpr->setArg(0, const_cast<Expr *>(callExpr->getArg(0)));
  8608. const auto srcLoc = callExpr->getExprLoc();
  8609. // Perform Sin and store results in argument 1.
  8610. auto *sin =
  8611. processIntrinsicUsingGLSLInst(sincosExpr, GLSLstd450::GLSLstd450Sin,
  8612. /*actPerRowForMatrices*/ true, srcLoc);
  8613. spvBuilder.createStore(doExpr(callExpr->getArg(1)), sin, srcLoc);
  8614. // Perform Cos and store results in argument 2.
  8615. auto *cos =
  8616. processIntrinsicUsingGLSLInst(sincosExpr, GLSLstd450::GLSLstd450Cos,
  8617. /*actPerRowForMatrices*/ true, srcLoc);
  8618. spvBuilder.createStore(doExpr(callExpr->getArg(2)), cos, srcLoc);
  8619. return nullptr;
  8620. }
  8621. SpirvInstruction *
  8622. SpirvEmitter::processIntrinsicSaturate(const CallExpr *callExpr) {
  8623. const auto *arg = callExpr->getArg(0);
  8624. const auto loc = callExpr->getExprLoc();
  8625. auto *argId = doExpr(arg);
  8626. const auto argType = arg->getType();
  8627. const QualType returnType = callExpr->getType();
  8628. QualType elemType = {};
  8629. uint32_t vecSize = 0;
  8630. if (isScalarType(argType, &elemType)) {
  8631. auto *floatZero = getValueZero(elemType);
  8632. auto *floatOne = getValueOne(elemType);
  8633. return spvBuilder.createGLSLExtInst(returnType,
  8634. GLSLstd450::GLSLstd450FClamp,
  8635. {argId, floatZero, floatOne}, loc);
  8636. }
  8637. if (isVectorType(argType, &elemType, &vecSize)) {
  8638. auto *vecZero = getVecValueZero(elemType, vecSize);
  8639. auto *vecOne = getVecValueOne(elemType, vecSize);
  8640. return spvBuilder.createGLSLExtInst(returnType,
  8641. GLSLstd450::GLSLstd450FClamp,
  8642. {argId, vecZero, vecOne}, loc);
  8643. }
  8644. uint32_t numRows = 0, numCols = 0;
  8645. if (isMxNMatrix(argType, &elemType, &numRows, &numCols)) {
  8646. auto *vecZero = getVecValueZero(elemType, numCols);
  8647. auto *vecOne = getVecValueOne(elemType, numCols);
  8648. const auto actOnEachVec = [this, loc, vecZero,
  8649. vecOne](uint32_t /*index*/, QualType vecType,
  8650. SpirvInstruction *curRow) {
  8651. return spvBuilder.createGLSLExtInst(vecType, GLSLstd450::GLSLstd450FClamp,
  8652. {curRow, vecZero, vecOne}, loc);
  8653. };
  8654. return processEachVectorInMatrix(arg, argId, actOnEachVec, loc);
  8655. }
  8656. emitError("invalid argument type passed to saturate intrinsic function",
  8657. callExpr->getExprLoc());
  8658. return nullptr;
  8659. }
  8660. SpirvInstruction *
  8661. SpirvEmitter::processIntrinsicFloatSign(const CallExpr *callExpr) {
  8662. // Import the GLSL.std.450 extended instruction set.
  8663. const Expr *arg = callExpr->getArg(0);
  8664. const auto loc = callExpr->getExprLoc();
  8665. const QualType returnType = callExpr->getType();
  8666. const QualType argType = arg->getType();
  8667. assert(isFloatOrVecMatOfFloatType(argType));
  8668. auto *argId = doExpr(arg);
  8669. SpirvInstruction *floatSign = nullptr;
  8670. // For matrices, we can perform the instruction on each vector of the matrix.
  8671. if (isMxNMatrix(argType)) {
  8672. const auto actOnEachVec = [this, loc](uint32_t /*index*/, QualType vecType,
  8673. SpirvInstruction *curRow) {
  8674. return spvBuilder.createGLSLExtInst(vecType, GLSLstd450::GLSLstd450FSign,
  8675. {curRow}, loc);
  8676. };
  8677. floatSign = processEachVectorInMatrix(arg, argId, actOnEachVec, loc);
  8678. } else {
  8679. floatSign = spvBuilder.createGLSLExtInst(
  8680. argType, GLSLstd450::GLSLstd450FSign, {argId}, loc);
  8681. }
  8682. return castToInt(floatSign, arg->getType(), returnType, arg->getLocStart());
  8683. }
  8684. SpirvInstruction *
  8685. SpirvEmitter::processIntrinsicF16ToF32(const CallExpr *callExpr) {
  8686. // f16tof32() takes in (vector of) uint and returns (vector of) float.
  8687. // The frontend should guarantee that by inserting implicit casts.
  8688. const QualType f32Type = astContext.FloatTy;
  8689. const QualType u32Type = astContext.UnsignedIntTy;
  8690. const QualType v2f32Type = astContext.getExtVectorType(f32Type, 2);
  8691. const auto loc = callExpr->getExprLoc();
  8692. const auto *arg = callExpr->getArg(0);
  8693. auto *argId = doExpr(arg);
  8694. uint32_t elemCount = {};
  8695. if (isVectorType(arg->getType(), nullptr, &elemCount)) {
  8696. // The input is a vector. We need to handle each element separately.
  8697. llvm::SmallVector<SpirvInstruction *, 4> elements;
  8698. for (uint32_t i = 0; i < elemCount; ++i) {
  8699. auto *srcElem = spvBuilder.createCompositeExtract(u32Type, argId, {i},
  8700. arg->getLocStart());
  8701. auto *convert = spvBuilder.createGLSLExtInst(
  8702. v2f32Type, GLSLstd450::GLSLstd450UnpackHalf2x16, srcElem, loc);
  8703. elements.push_back(
  8704. spvBuilder.createCompositeExtract(f32Type, convert, {0}, loc));
  8705. }
  8706. return spvBuilder.createCompositeConstruct(
  8707. astContext.getExtVectorType(f32Type, elemCount), elements, loc);
  8708. }
  8709. auto *convert = spvBuilder.createGLSLExtInst(
  8710. v2f32Type, GLSLstd450::GLSLstd450UnpackHalf2x16, argId, loc);
  8711. // f16tof32() converts the float16 stored in the low-half of the uint to
  8712. // a float. So just need to return the first component.
  8713. return spvBuilder.createCompositeExtract(f32Type, convert, {0}, loc);
  8714. }
  8715. SpirvInstruction *
  8716. SpirvEmitter::processIntrinsicF32ToF16(const CallExpr *callExpr) {
  8717. // f32tof16() takes in (vector of) float and returns (vector of) uint.
  8718. // The frontend should guarantee that by inserting implicit casts.
  8719. const QualType f32Type = astContext.FloatTy;
  8720. const QualType u32Type = astContext.UnsignedIntTy;
  8721. const QualType v2f32Type = astContext.getExtVectorType(f32Type, 2);
  8722. auto *zero = spvBuilder.getConstantFloat(f32Type, llvm::APFloat(0.0f));
  8723. const auto loc = callExpr->getExprLoc();
  8724. const auto *arg = callExpr->getArg(0);
  8725. auto *argId = doExpr(arg);
  8726. uint32_t elemCount = {};
  8727. if (isVectorType(arg->getType(), nullptr, &elemCount)) {
  8728. // The input is a vector. We need to handle each element separately.
  8729. llvm::SmallVector<SpirvInstruction *, 4> elements;
  8730. for (uint32_t i = 0; i < elemCount; ++i) {
  8731. auto *srcElem = spvBuilder.createCompositeExtract(f32Type, argId, {i},
  8732. arg->getLocStart());
  8733. auto *srcVec =
  8734. spvBuilder.createCompositeConstruct(v2f32Type, {srcElem, zero}, loc);
  8735. elements.push_back(spvBuilder.createGLSLExtInst(
  8736. u32Type, GLSLstd450::GLSLstd450PackHalf2x16, srcVec, loc));
  8737. }
  8738. return spvBuilder.createCompositeConstruct(
  8739. astContext.getExtVectorType(u32Type, elemCount), elements, loc);
  8740. }
  8741. // f16tof32() stores the float into the low-half of the uint. So we need
  8742. // to supply another zero to take the other half.
  8743. auto *srcVec =
  8744. spvBuilder.createCompositeConstruct(v2f32Type, {argId, zero}, loc);
  8745. return spvBuilder.createGLSLExtInst(
  8746. u32Type, GLSLstd450::GLSLstd450PackHalf2x16, srcVec, loc);
  8747. }
  8748. SpirvInstruction *SpirvEmitter::processIntrinsicUsingSpirvInst(
  8749. const CallExpr *callExpr, spv::Op opcode, bool actPerRowForMatrices) {
  8750. // Certain opcodes are only allowed in pixel shader
  8751. if (!spvContext.isPS())
  8752. switch (opcode) {
  8753. case spv::Op::OpDPdx:
  8754. case spv::Op::OpDPdy:
  8755. case spv::Op::OpDPdxFine:
  8756. case spv::Op::OpDPdyFine:
  8757. case spv::Op::OpDPdxCoarse:
  8758. case spv::Op::OpDPdyCoarse:
  8759. case spv::Op::OpFwidth:
  8760. case spv::Op::OpFwidthFine:
  8761. case spv::Op::OpFwidthCoarse:
  8762. needsLegalization = true;
  8763. break;
  8764. default:
  8765. // Only the given opcodes need legalization. Anything else should preserve
  8766. // previous.
  8767. break;
  8768. }
  8769. const auto loc = callExpr->getExprLoc();
  8770. const QualType returnType = callExpr->getType();
  8771. if (callExpr->getNumArgs() == 1u) {
  8772. const Expr *arg = callExpr->getArg(0);
  8773. auto *argId = doExpr(arg);
  8774. // If the instruction does not operate on matrices, we can perform the
  8775. // instruction on each vector of the matrix.
  8776. if (actPerRowForMatrices && isMxNMatrix(arg->getType())) {
  8777. const auto actOnEachVec = [this, opcode, loc](uint32_t /*index*/,
  8778. QualType vecType,
  8779. SpirvInstruction *curRow) {
  8780. return spvBuilder.createUnaryOp(opcode, vecType, curRow, loc);
  8781. };
  8782. return processEachVectorInMatrix(arg, argId, actOnEachVec, loc);
  8783. }
  8784. return spvBuilder.createUnaryOp(opcode, returnType, argId, loc);
  8785. } else if (callExpr->getNumArgs() == 2u) {
  8786. const Expr *arg0 = callExpr->getArg(0);
  8787. auto *arg0Id = doExpr(arg0);
  8788. auto *arg1Id = doExpr(callExpr->getArg(1));
  8789. const auto arg1Loc = callExpr->getArg(1)->getLocStart();
  8790. // If the instruction does not operate on matrices, we can perform the
  8791. // instruction on each vector of the matrix.
  8792. if (actPerRowForMatrices && isMxNMatrix(arg0->getType())) {
  8793. const auto actOnEachVec = [this, opcode, arg1Id, loc,
  8794. arg1Loc](uint32_t index, QualType vecType,
  8795. SpirvInstruction *arg0Row) {
  8796. auto *arg1Row = spvBuilder.createCompositeExtract(vecType, arg1Id,
  8797. {index}, arg1Loc);
  8798. return spvBuilder.createBinaryOp(opcode, vecType, arg0Row, arg1Row,
  8799. loc);
  8800. };
  8801. return processEachVectorInMatrix(arg0, arg0Id, actOnEachVec, loc);
  8802. }
  8803. return spvBuilder.createBinaryOp(opcode, returnType, arg0Id, arg1Id, loc);
  8804. }
  8805. emitError("unsupported %0 intrinsic function", loc)
  8806. << cast<DeclRefExpr>(callExpr->getCallee())->getNameInfo().getAsString();
  8807. return nullptr;
  8808. }
  8809. SpirvInstruction *SpirvEmitter::processIntrinsicUsingGLSLInst(
  8810. const CallExpr *callExpr, GLSLstd450 opcode, bool actPerRowForMatrices,
  8811. SourceLocation loc) {
  8812. // Import the GLSL.std.450 extended instruction set.
  8813. const QualType returnType = callExpr->getType();
  8814. if (callExpr->getNumArgs() == 1u) {
  8815. const Expr *arg = callExpr->getArg(0);
  8816. auto *argInstr = doExpr(arg);
  8817. // If the instruction does not operate on matrices, we can perform the
  8818. // instruction on each vector of the matrix.
  8819. if (actPerRowForMatrices && isMxNMatrix(arg->getType())) {
  8820. const auto actOnEachVec = [this, loc,
  8821. opcode](uint32_t /*index*/, QualType vecType,
  8822. SpirvInstruction *curRowInstr) {
  8823. return spvBuilder.createGLSLExtInst(vecType, opcode, {curRowInstr},
  8824. loc);
  8825. };
  8826. return processEachVectorInMatrix(arg, argInstr, actOnEachVec, loc);
  8827. }
  8828. return spvBuilder.createGLSLExtInst(returnType, opcode, {argInstr}, loc);
  8829. } else if (callExpr->getNumArgs() == 2u) {
  8830. const Expr *arg0 = callExpr->getArg(0);
  8831. auto *arg0Instr = doExpr(arg0);
  8832. auto *arg1Instr = doExpr(callExpr->getArg(1));
  8833. const auto arg1Loc = callExpr->getArg(1)->getLocStart();
  8834. // If the instruction does not operate on matrices, we can perform the
  8835. // instruction on each vector of the matrix.
  8836. if (actPerRowForMatrices && isMxNMatrix(arg0->getType())) {
  8837. const auto actOnEachVec = [this, loc, opcode, arg1Instr,
  8838. arg1Loc](uint32_t index, QualType vecType,
  8839. SpirvInstruction *arg0RowInstr) {
  8840. auto *arg1RowInstr = spvBuilder.createCompositeExtract(
  8841. vecType, arg1Instr, {index}, arg1Loc);
  8842. return spvBuilder.createGLSLExtInst(vecType, opcode,
  8843. {arg0RowInstr, arg1RowInstr}, loc);
  8844. };
  8845. return processEachVectorInMatrix(arg0, arg0Instr, actOnEachVec, loc);
  8846. }
  8847. return spvBuilder.createGLSLExtInst(returnType, opcode,
  8848. {arg0Instr, arg1Instr}, loc);
  8849. } else if (callExpr->getNumArgs() == 3u) {
  8850. const Expr *arg0 = callExpr->getArg(0);
  8851. auto *arg0Instr = doExpr(arg0);
  8852. auto *arg1Instr = doExpr(callExpr->getArg(1));
  8853. auto *arg2Instr = doExpr(callExpr->getArg(2));
  8854. auto arg1Loc = callExpr->getArg(1)->getLocStart();
  8855. auto arg2Loc = callExpr->getArg(2)->getLocStart();
  8856. // If the instruction does not operate on matrices, we can perform the
  8857. // instruction on each vector of the matrix.
  8858. if (actPerRowForMatrices && isMxNMatrix(arg0->getType())) {
  8859. const auto actOnEachVec = [this, loc, opcode, arg1Instr, arg2Instr,
  8860. arg1Loc,
  8861. arg2Loc](uint32_t index, QualType vecType,
  8862. SpirvInstruction *arg0RowInstr) {
  8863. auto *arg1RowInstr = spvBuilder.createCompositeExtract(
  8864. vecType, arg1Instr, {index}, arg1Loc);
  8865. auto *arg2RowInstr = spvBuilder.createCompositeExtract(
  8866. vecType, arg2Instr, {index}, arg2Loc);
  8867. return spvBuilder.createGLSLExtInst(
  8868. vecType, opcode, {arg0RowInstr, arg1RowInstr, arg2RowInstr}, loc);
  8869. };
  8870. return processEachVectorInMatrix(arg0, arg0Instr, actOnEachVec, loc);
  8871. }
  8872. return spvBuilder.createGLSLExtInst(returnType, opcode,
  8873. {arg0Instr, arg1Instr, arg2Instr}, loc);
  8874. }
  8875. emitError("unsupported %0 intrinsic function", callExpr->getExprLoc())
  8876. << cast<DeclRefExpr>(callExpr->getCallee())->getNameInfo().getAsString();
  8877. return nullptr;
  8878. }
  8879. SpirvInstruction *
  8880. SpirvEmitter::processIntrinsicLog10(const CallExpr *callExpr) {
  8881. // Since there is no log10 instruction in SPIR-V, we can use:
  8882. // log10(x) = log2(x) * ( 1 / log2(10) )
  8883. // 1 / log2(10) = 0.30103
  8884. auto loc = callExpr->getExprLoc();
  8885. auto *scale =
  8886. spvBuilder.getConstantFloat(astContext.FloatTy, llvm::APFloat(0.30103f));
  8887. auto *log2 = processIntrinsicUsingGLSLInst(
  8888. callExpr, GLSLstd450::GLSLstd450Log2, true, loc);
  8889. const auto returnType = callExpr->getType();
  8890. spv::Op scaleOp = isScalarType(returnType)
  8891. ? spv::Op::OpFMul
  8892. : isVectorType(returnType)
  8893. ? spv::Op::OpVectorTimesScalar
  8894. : spv::Op::OpMatrixTimesScalar;
  8895. return spvBuilder.createBinaryOp(scaleOp, returnType, log2, scale, loc);
  8896. }
  8897. SpirvInstruction *
  8898. SpirvEmitter::processIntrinsic8BitPack(const CallExpr *callExpr,
  8899. hlsl::IntrinsicOp op) {
  8900. const auto loc = callExpr->getExprLoc();
  8901. assert(op == hlsl::IntrinsicOp::IOP_pack_s8 ||
  8902. op == hlsl::IntrinsicOp::IOP_pack_u8 ||
  8903. op == hlsl::IntrinsicOp::IOP_pack_clamp_s8 ||
  8904. op == hlsl::IntrinsicOp::IOP_pack_clamp_u8);
  8905. // Here's the signature for the pack intrinsic operations:
  8906. //
  8907. // uint8_t4_packed pack_u8(uint32_t4 unpackedVal);
  8908. // uint8_t4_packed pack_u8(uint16_t4 unpackedVal);
  8909. // int8_t4_packed pack_s8(int32_t4 unpackedVal);
  8910. // int8_t4_packed pack_s8(int16_t4 unpackedVal);
  8911. //
  8912. // These functions take a vec4 of 16-bit or 32-bit integers as input. For each
  8913. // element of the vec4, they pick the lower 8 bits, and drop the other bits.
  8914. // The result is four 8-bit values (32 bits in total) which are packed in an
  8915. // unsigned uint32_t.
  8916. //
  8917. //
  8918. // Here's the signature for the pack_clamp intrinsic operations:
  8919. //
  8920. // uint8_t4_packed pack_clamp_u8(int32_t4 val); // Pack and Clamp [0, 255]
  8921. // uint8_t4_packed pack_clamp_u8(int16_t4 val); // Pack and Clamp [0, 255]
  8922. //
  8923. // int8_t4_packed pack_clamp_s8(int32_t4 val); // Pack and Clamp [-128, 127]
  8924. // int8_t4_packed pack_clamp_s8(int16_t4 val); // Pack and Clamp [-128, 127]
  8925. //
  8926. // These functions take a vec4 of 16-bit or 32-bit integers as input. For each
  8927. // element of the vec4, they first clamp the value to a range (depending on
  8928. // the signedness) then pick the lower 8 bits, and drop the other bits.
  8929. // The result is four 8-bit values (32 bits in total) which are packed in an
  8930. // unsigned uint32_t.
  8931. //
  8932. // Note: uint8_t4_packed and int8_t4_packed are NOT vector types! They are
  8933. // both scalar 32-bit unsigned integer types where each byte represents one
  8934. // value.
  8935. //
  8936. // Note: In pack_clamp_{s|u}8 intrinsics, an input of 0x100 will be turned
  8937. // into 0xFF, not 0x00. Therefore, it is important to perform a clamp first,
  8938. // and then a truncation.
  8939. // Steps:
  8940. // Use GLSL extended instruction set's clamp (only for clamp instructions).
  8941. // Use OpUConvert/OpSConvert to truncate each element of the vec4 to 8 bits.
  8942. // Use OpBitcast to make a 32-bit uint out of the new vec4.
  8943. auto *arg = callExpr->getArg(0);
  8944. const auto argType = arg->getType();
  8945. SpirvInstruction *argInstr = doExpr(arg);
  8946. QualType elemType = {};
  8947. uint32_t elemCount = 0;
  8948. (void)isVectorType(argType, &elemType, &elemCount);
  8949. const bool isSigned = elemType->isSignedIntegerType();
  8950. assert(elemCount == 4);
  8951. const bool doesClamp = op == hlsl::IntrinsicOp::IOP_pack_clamp_s8 ||
  8952. op == hlsl::IntrinsicOp::IOP_pack_clamp_u8;
  8953. if (doesClamp) {
  8954. const auto bitwidth = getElementSpirvBitwidth(
  8955. astContext, elemType, spirvOptions.enable16BitTypes);
  8956. int32_t clampMin = op == hlsl::IntrinsicOp::IOP_pack_clamp_u8 ? 0 : -128;
  8957. int32_t clampMax = op == hlsl::IntrinsicOp::IOP_pack_clamp_u8 ? 255 : 127;
  8958. auto *minInstr = spvBuilder.getConstantInt(
  8959. elemType, llvm::APInt(bitwidth, clampMin, isSigned));
  8960. auto *maxInstr = spvBuilder.getConstantInt(
  8961. elemType, llvm::APInt(bitwidth, clampMax, isSigned));
  8962. auto *minVec = spvBuilder.getConstantComposite(
  8963. argType, {minInstr, minInstr, minInstr, minInstr});
  8964. auto *maxVec = spvBuilder.getConstantComposite(
  8965. argType, {maxInstr, maxInstr, maxInstr, maxInstr});
  8966. auto clampOp = isSigned ? GLSLstd450SClamp : GLSLstd450UClamp;
  8967. argInstr = spvBuilder.createGLSLExtInst(argType, clampOp,
  8968. {argInstr, minVec, maxVec}, loc);
  8969. }
  8970. if (isSigned) {
  8971. QualType v4Int8Type =
  8972. astContext.getExtVectorType(astContext.SignedCharTy, 4);
  8973. auto *bytesVecInstr = spvBuilder.createUnaryOp(spv::Op::OpSConvert,
  8974. v4Int8Type, argInstr, loc);
  8975. return spvBuilder.createUnaryOp(
  8976. spv::Op::OpBitcast, astContext.Int8_4PackedTy, bytesVecInstr, loc);
  8977. } else {
  8978. QualType v4Uint8Type =
  8979. astContext.getExtVectorType(astContext.UnsignedCharTy, 4);
  8980. auto *bytesVecInstr = spvBuilder.createUnaryOp(spv::Op::OpUConvert,
  8981. v4Uint8Type, argInstr, loc);
  8982. return spvBuilder.createUnaryOp(
  8983. spv::Op::OpBitcast, astContext.UInt8_4PackedTy, bytesVecInstr, loc);
  8984. }
  8985. }
  8986. SpirvInstruction *
  8987. SpirvEmitter::processIntrinsic8BitUnpack(const CallExpr *callExpr,
  8988. hlsl::IntrinsicOp op) {
  8989. const auto loc = callExpr->getExprLoc();
  8990. assert(op == hlsl::IntrinsicOp::IOP_unpack_s8s16 ||
  8991. op == hlsl::IntrinsicOp::IOP_unpack_s8s32 ||
  8992. op == hlsl::IntrinsicOp::IOP_unpack_u8u16 ||
  8993. op == hlsl::IntrinsicOp::IOP_unpack_u8u32);
  8994. // Here's the signature for the pack intrinsic operations:
  8995. //
  8996. // int16_t4 unpack_s8s16(int8_t4_packed packedVal); // Sign Extended
  8997. // uint16_t4 unpack_u8u16(uint8_t4_packed packedVal); // Non-Sign Extended
  8998. // int32_t4 unpack_s8s32(int8_t4_packed packedVal); // Sign Extended
  8999. // uint32_t4 unpack_u8u32(uint8_t4_packed packedVal); // Non-Sign Extended
  9000. //
  9001. // These functions take a 32-bit unsigned integer as input (where each byte of
  9002. // the input represents one value, i.e. it's packed). They first unpack the
  9003. // 32-bit integer to a vector of 4 bytes. Then for each element of the vec4,
  9004. // they zero-extend or sign-extend the byte in order to achieve a 16-bit or
  9005. // 32-bit vector of integers.
  9006. //
  9007. // Note: uint8_t4_packed and int8_t4_packed are NOT vector types! They are
  9008. // both scalar 32-bit unsigned integer types where each byte represents one
  9009. // value.
  9010. // Steps:
  9011. // Use OpBitcast to make a vec4 of bytes from a 32-bit value.
  9012. // Use OpUConvert/OpSConvert to zero-extend/sign-extend each element of the
  9013. // vec4 to 16 or 32 bits.
  9014. auto *arg = callExpr->getArg(0);
  9015. SpirvInstruction *argInstr = doExpr(arg);
  9016. const bool isSigned = op == hlsl::IntrinsicOp::IOP_unpack_s8s16 ||
  9017. op == hlsl::IntrinsicOp::IOP_unpack_s8s32;
  9018. QualType resultType = {};
  9019. if (op == hlsl::IntrinsicOp::IOP_unpack_s8s16 ||
  9020. op == hlsl::IntrinsicOp::IOP_unpack_u8u16) {
  9021. resultType = astContext.getExtVectorType(
  9022. isSigned ? astContext.ShortTy : astContext.UnsignedShortTy, 4);
  9023. } else {
  9024. resultType = astContext.getExtVectorType(
  9025. isSigned ? astContext.IntTy : astContext.UnsignedIntTy, 4);
  9026. }
  9027. if (isSigned) {
  9028. QualType v4Int8Type =
  9029. astContext.getExtVectorType(astContext.SignedCharTy, 4);
  9030. auto *bytesVecInstr =
  9031. spvBuilder.createUnaryOp(spv::Op::OpBitcast, v4Int8Type, argInstr, loc);
  9032. return spvBuilder.createUnaryOp(spv::Op::OpSConvert, resultType,
  9033. bytesVecInstr, loc);
  9034. } else {
  9035. QualType v4Uint8Type =
  9036. astContext.getExtVectorType(astContext.UnsignedCharTy, 4);
  9037. auto *bytesVecInstr = spvBuilder.createUnaryOp(spv::Op::OpBitcast,
  9038. v4Uint8Type, argInstr, loc);
  9039. return spvBuilder.createUnaryOp(spv::Op::OpUConvert, resultType,
  9040. bytesVecInstr, loc);
  9041. }
  9042. }
  9043. SpirvInstruction *SpirvEmitter::processRayBuiltins(const CallExpr *callExpr,
  9044. hlsl::IntrinsicOp op) {
  9045. bool nvRayTracing =
  9046. featureManager.isExtensionEnabled(Extension::NV_ray_tracing);
  9047. spv::BuiltIn builtin = spv::BuiltIn::Max;
  9048. bool transposeMatrix = false;
  9049. const auto loc = callExpr->getExprLoc();
  9050. switch (op) {
  9051. case hlsl::IntrinsicOp::IOP_DispatchRaysDimensions:
  9052. builtin = spv::BuiltIn::LaunchSizeNV;
  9053. break;
  9054. case hlsl::IntrinsicOp::IOP_DispatchRaysIndex:
  9055. builtin = spv::BuiltIn::LaunchIdNV;
  9056. break;
  9057. case hlsl::IntrinsicOp::IOP_RayTCurrent:
  9058. if (nvRayTracing)
  9059. builtin = spv::BuiltIn::HitTNV;
  9060. else
  9061. builtin = spv::BuiltIn::RayTmaxKHR;
  9062. break;
  9063. case hlsl::IntrinsicOp::IOP_RayTMin:
  9064. builtin = spv::BuiltIn::RayTminNV;
  9065. break;
  9066. case hlsl::IntrinsicOp::IOP_HitKind:
  9067. builtin = spv::BuiltIn::HitKindNV;
  9068. break;
  9069. case hlsl::IntrinsicOp::IOP_WorldRayDirection:
  9070. builtin = spv::BuiltIn::WorldRayDirectionNV;
  9071. break;
  9072. case hlsl::IntrinsicOp::IOP_WorldRayOrigin:
  9073. builtin = spv::BuiltIn::WorldRayOriginNV;
  9074. break;
  9075. case hlsl::IntrinsicOp::IOP_ObjectRayDirection:
  9076. builtin = spv::BuiltIn::ObjectRayDirectionNV;
  9077. break;
  9078. case hlsl::IntrinsicOp::IOP_ObjectRayOrigin:
  9079. builtin = spv::BuiltIn::ObjectRayOriginNV;
  9080. break;
  9081. case hlsl::IntrinsicOp::IOP_GeometryIndex:
  9082. featureManager.requestExtension(Extension::KHR_ray_tracing,
  9083. "GeometryIndex()", loc);
  9084. builtin = spv::BuiltIn::RayGeometryIndexKHR;
  9085. break;
  9086. case hlsl::IntrinsicOp::IOP_InstanceIndex:
  9087. builtin = spv::BuiltIn::InstanceId;
  9088. break;
  9089. case hlsl::IntrinsicOp::IOP_PrimitiveIndex:
  9090. builtin = spv::BuiltIn::PrimitiveId;
  9091. break;
  9092. case hlsl::IntrinsicOp::IOP_InstanceID:
  9093. builtin = spv::BuiltIn::InstanceCustomIndexNV;
  9094. break;
  9095. case hlsl::IntrinsicOp::IOP_RayFlags:
  9096. builtin = spv::BuiltIn::IncomingRayFlagsNV;
  9097. break;
  9098. case hlsl::IntrinsicOp::IOP_ObjectToWorld3x4:
  9099. transposeMatrix = true;
  9100. case hlsl::IntrinsicOp::IOP_ObjectToWorld4x3:
  9101. builtin = spv::BuiltIn::ObjectToWorldNV;
  9102. break;
  9103. case hlsl::IntrinsicOp::IOP_WorldToObject3x4:
  9104. transposeMatrix = true;
  9105. case hlsl::IntrinsicOp::IOP_WorldToObject4x3:
  9106. builtin = spv::BuiltIn::WorldToObjectNV;
  9107. break;
  9108. default:
  9109. emitError("ray intrinsic function unimplemented", loc);
  9110. return nullptr;
  9111. }
  9112. QualType builtinType = callExpr->getType();
  9113. if (transposeMatrix) {
  9114. // DXR defines ObjectToWorld3x4, WorldToObject3x4 as transposed matrices.
  9115. // SPIR-V has only non tranposed variant defined as a builtin
  9116. // So perform read of original non transposed builtin and perform transpose.
  9117. assert(hlsl::IsHLSLMatType(builtinType) && "Builtin should be matrix");
  9118. const clang::Type *type = builtinType.getCanonicalType().getTypePtr();
  9119. const RecordType *RT = cast<RecordType>(type);
  9120. const ClassTemplateSpecializationDecl *templateSpecDecl =
  9121. cast<ClassTemplateSpecializationDecl>(RT->getDecl());
  9122. ClassTemplateDecl *templateDecl =
  9123. templateSpecDecl->getSpecializedTemplate();
  9124. builtinType = getHLSLMatrixType(astContext, theCompilerInstance.getSema(),
  9125. templateDecl, astContext.FloatTy, 4, 3);
  9126. }
  9127. SpirvInstruction *retVal =
  9128. declIdMapper.getBuiltinVar(builtin, builtinType, loc);
  9129. retVal = spvBuilder.createLoad(builtinType, retVal, loc);
  9130. if (transposeMatrix)
  9131. retVal = spvBuilder.createUnaryOp(spv::Op::OpTranspose, callExpr->getType(),
  9132. retVal, loc);
  9133. return retVal;
  9134. }
  9135. SpirvInstruction *SpirvEmitter::processReportHit(const CallExpr *callExpr) {
  9136. SpirvInstruction *hitAttributeStageVar = nullptr;
  9137. const VarDecl *hitAttributeArg = nullptr;
  9138. QualType hitAttributeType;
  9139. const auto args = callExpr->getArgs();
  9140. if (callExpr->getNumArgs() != 3) {
  9141. emitError("invalid number of arguments to ReportHit",
  9142. callExpr->getExprLoc());
  9143. }
  9144. // HLSL Function :
  9145. // template<typename hitAttr>
  9146. // ReportHit(in float, in uint, in hitAttr)
  9147. if (const auto *implCastExpr = dyn_cast<CastExpr>(callExpr->getArg(2))) {
  9148. if (const auto *arg = dyn_cast<DeclRefExpr>(implCastExpr->getSubExpr())) {
  9149. if (const auto *varDecl = dyn_cast<VarDecl>(arg->getDecl())) {
  9150. hitAttributeType = varDecl->getType();
  9151. hitAttributeArg = varDecl;
  9152. // Check if same type of hit attribute stage variable was already
  9153. // created, if so re-use
  9154. const auto iter = hitAttributeMap.find(hitAttributeType);
  9155. if (iter == hitAttributeMap.end()) {
  9156. hitAttributeStageVar = declIdMapper.createRayTracingNVStageVar(
  9157. spv::StorageClass::HitAttributeNV, varDecl);
  9158. hitAttributeMap[hitAttributeType] = hitAttributeStageVar;
  9159. } else {
  9160. hitAttributeStageVar = iter->second;
  9161. }
  9162. }
  9163. }
  9164. }
  9165. assert(hitAttributeStageVar && hitAttributeArg);
  9166. // Copy argument to stage variable
  9167. const auto hitAttributeArgInst =
  9168. declIdMapper.getDeclEvalInfo(hitAttributeArg, callExpr->getExprLoc());
  9169. auto tempLoad =
  9170. spvBuilder.createLoad(hitAttributeArg->getType(), hitAttributeArgInst,
  9171. hitAttributeArg->getLocStart());
  9172. spvBuilder.createStore(hitAttributeStageVar, tempLoad,
  9173. callExpr->getExprLoc());
  9174. // SPIR-V Instruction :
  9175. // bool OpReportIntersection(<id> float Hit, <id> uint HitKind)
  9176. llvm::SmallVector<SpirvInstruction *, 4> reportHitArgs;
  9177. reportHitArgs.push_back(doExpr(args[0])); // Hit
  9178. reportHitArgs.push_back(doExpr(args[1])); // HitKind
  9179. return spvBuilder.createRayTracingOpsNV(spv::Op::OpReportIntersectionNV,
  9180. astContext.BoolTy, reportHitArgs,
  9181. callExpr->getExprLoc());
  9182. }
  9183. void SpirvEmitter::processCallShader(const CallExpr *callExpr) {
  9184. bool nvRayTracing =
  9185. featureManager.isExtensionEnabled(Extension::NV_ray_tracing);
  9186. SpirvInstruction *callDataLocInst = nullptr;
  9187. SpirvInstruction *callDataStageVar = nullptr;
  9188. const VarDecl *callDataArg = nullptr;
  9189. QualType callDataType;
  9190. const auto args = callExpr->getArgs();
  9191. if (callExpr->getNumArgs() != 2) {
  9192. emitError("invalid number of arguments to CallShader",
  9193. callExpr->getExprLoc());
  9194. }
  9195. // HLSL Func :
  9196. // template<typename CallData>
  9197. // void CallShader(in int sbtIndex, inout CallData arg)
  9198. if (const auto *implCastExpr = dyn_cast<CastExpr>(args[1])) {
  9199. if (const auto *arg = dyn_cast<DeclRefExpr>(implCastExpr->getSubExpr())) {
  9200. if (const auto *varDecl = dyn_cast<VarDecl>(arg->getDecl())) {
  9201. callDataType = varDecl->getType();
  9202. callDataArg = varDecl;
  9203. // Check if same type of callable data stage variable was already
  9204. // created, if so re-use
  9205. const auto callDataPair = callDataMap.find(callDataType);
  9206. if (callDataPair == callDataMap.end()) {
  9207. int numCallDataVars = callDataMap.size();
  9208. callDataStageVar = declIdMapper.createRayTracingNVStageVar(
  9209. spv::StorageClass::CallableDataNV, varDecl);
  9210. // Decorate unique location id for each created stage var
  9211. spvBuilder.decorateLocation(callDataStageVar, numCallDataVars);
  9212. callDataLocInst = spvBuilder.getConstantInt(
  9213. astContext.UnsignedIntTy, llvm::APInt(32, numCallDataVars));
  9214. callDataMap[callDataType] =
  9215. std::make_pair(callDataStageVar, callDataLocInst);
  9216. } else {
  9217. callDataStageVar = callDataPair->second.first;
  9218. callDataLocInst = callDataPair->second.second;
  9219. }
  9220. }
  9221. }
  9222. }
  9223. assert(callDataStageVar && callDataArg);
  9224. // Copy argument to stage variable
  9225. const auto callDataArgInst =
  9226. declIdMapper.getDeclEvalInfo(callDataArg, callExpr->getExprLoc());
  9227. auto tempLoad = spvBuilder.createLoad(callDataArg->getType(), callDataArgInst,
  9228. callDataArg->getLocStart());
  9229. spvBuilder.createStore(callDataStageVar, tempLoad, callExpr->getExprLoc());
  9230. // SPIR-V Instruction
  9231. // void OpExecuteCallable(<id> int SBT Index, <id> uint Callable Data Location
  9232. // Id)
  9233. llvm::SmallVector<SpirvInstruction *, 2> callShaderArgs;
  9234. callShaderArgs.push_back(doExpr(args[0]));
  9235. if (nvRayTracing) {
  9236. callShaderArgs.push_back(callDataLocInst);
  9237. spvBuilder.createRayTracingOpsNV(spv::Op::OpExecuteCallableNV, QualType(),
  9238. callShaderArgs, callExpr->getExprLoc());
  9239. } else {
  9240. callShaderArgs.push_back(callDataStageVar);
  9241. spvBuilder.createRayTracingOpsNV(spv::Op::OpExecuteCallableKHR, QualType(),
  9242. callShaderArgs, callExpr->getExprLoc());
  9243. }
  9244. // Copy data back to argument
  9245. tempLoad = spvBuilder.createLoad(callDataArg->getType(), callDataStageVar,
  9246. callDataArg->getLocStart());
  9247. spvBuilder.createStore(callDataArgInst, tempLoad, callExpr->getExprLoc());
  9248. return;
  9249. }
  9250. void SpirvEmitter::processTraceRay(const CallExpr *callExpr) {
  9251. bool nvRayTracing =
  9252. featureManager.isExtensionEnabled(Extension::NV_ray_tracing);
  9253. SpirvInstruction *rayPayloadLocInst = nullptr;
  9254. SpirvInstruction *rayPayloadStageVar = nullptr;
  9255. const VarDecl *rayPayloadArg = nullptr;
  9256. QualType rayPayloadType;
  9257. const auto args = callExpr->getArgs();
  9258. if (callExpr->getNumArgs() != 8) {
  9259. emitError("invalid number of arguments to TraceRay",
  9260. callExpr->getExprLoc());
  9261. }
  9262. // HLSL Func
  9263. // template<typename RayPayload>
  9264. // void TraceRay(RaytracingAccelerationStructure rs,
  9265. // uint rayflags,
  9266. // uint InstanceInclusionMask
  9267. // uint RayContributionToHitGroupIndex,
  9268. // uint MultiplierForGeometryContributionToHitGroupIndex,
  9269. // uint MissShaderIndex,
  9270. // RayDesc ray,
  9271. // inout RayPayload p)
  9272. // where RayDesc = {float3 origin, float tMin, float3 direction, float tMax}
  9273. if (const auto *implCastExpr = dyn_cast<CastExpr>(args[7])) {
  9274. if (const auto *arg = dyn_cast<DeclRefExpr>(implCastExpr->getSubExpr())) {
  9275. if (const auto *varDecl = dyn_cast<VarDecl>(arg->getDecl())) {
  9276. rayPayloadType = varDecl->getType();
  9277. rayPayloadArg = varDecl;
  9278. const auto rayPayloadPair = rayPayloadMap.find(rayPayloadType);
  9279. // Check if same type of rayPayload stage variable was already
  9280. // created, if so re-use
  9281. if (rayPayloadPair == rayPayloadMap.end()) {
  9282. int numPayloadVars = rayPayloadMap.size();
  9283. rayPayloadStageVar = declIdMapper.createRayTracingNVStageVar(
  9284. spv::StorageClass::RayPayloadNV, varDecl);
  9285. // Decorate unique location id for each created stage var
  9286. spvBuilder.decorateLocation(rayPayloadStageVar, numPayloadVars);
  9287. rayPayloadLocInst = spvBuilder.getConstantInt(
  9288. astContext.UnsignedIntTy, llvm::APInt(32, numPayloadVars));
  9289. rayPayloadMap[rayPayloadType] =
  9290. std::make_pair(rayPayloadStageVar, rayPayloadLocInst);
  9291. } else {
  9292. rayPayloadStageVar = rayPayloadPair->second.first;
  9293. rayPayloadLocInst = rayPayloadPair->second.second;
  9294. }
  9295. }
  9296. }
  9297. }
  9298. assert(rayPayloadStageVar && rayPayloadArg);
  9299. const auto floatType = astContext.FloatTy;
  9300. const auto vecType = astContext.getExtVectorType(astContext.FloatTy, 3);
  9301. // Extract the ray description to match SPIR-V
  9302. SpirvInstruction *rayDescArg = doExpr(args[6]);
  9303. const auto loc = args[6]->getLocStart();
  9304. const auto origin =
  9305. spvBuilder.createCompositeExtract(vecType, rayDescArg, {0}, loc);
  9306. const auto tMin =
  9307. spvBuilder.createCompositeExtract(floatType, rayDescArg, {1}, loc);
  9308. const auto direction =
  9309. spvBuilder.createCompositeExtract(vecType, rayDescArg, {2}, loc);
  9310. const auto tMax =
  9311. spvBuilder.createCompositeExtract(floatType, rayDescArg, {3}, loc);
  9312. // Copy argument to stage variable
  9313. const auto rayPayloadArgInst =
  9314. declIdMapper.getDeclEvalInfo(rayPayloadArg, rayPayloadArg->getLocStart());
  9315. auto tempLoad =
  9316. spvBuilder.createLoad(rayPayloadArg->getType(), rayPayloadArgInst,
  9317. rayPayloadArg->getLocStart());
  9318. spvBuilder.createStore(rayPayloadStageVar, tempLoad, callExpr->getExprLoc());
  9319. // SPIR-V Instruction
  9320. // void OpTraceNV ( <id> AccelerationStructureNV acStruct,
  9321. // <id> uint Ray Flags,
  9322. // <id> uint Cull Mask,
  9323. // <id> uint SBT Offset,
  9324. // <id> uint SBT Stride,
  9325. // <id> uint Miss Index,
  9326. // <id> vec4 Ray Origin,
  9327. // <id> float Ray Tmin,
  9328. // <id> vec3 Ray Direction,
  9329. // <id> float Ray Tmax,
  9330. // <id> uint RayPayload number)
  9331. llvm::SmallVector<SpirvInstruction *, 8> traceArgs;
  9332. for (int ii = 0; ii < 6; ii++) {
  9333. traceArgs.push_back(doExpr(args[ii]));
  9334. }
  9335. traceArgs.push_back(origin);
  9336. traceArgs.push_back(tMin);
  9337. traceArgs.push_back(direction);
  9338. traceArgs.push_back(tMax);
  9339. if (nvRayTracing) {
  9340. traceArgs.push_back(rayPayloadLocInst);
  9341. spvBuilder.createRayTracingOpsNV(spv::Op::OpTraceNV, QualType(), traceArgs,
  9342. callExpr->getExprLoc());
  9343. } else {
  9344. traceArgs.push_back(rayPayloadStageVar);
  9345. spvBuilder.createRayTracingOpsNV(spv::Op::OpTraceRayKHR, QualType(),
  9346. traceArgs, callExpr->getExprLoc());
  9347. }
  9348. // Copy arguments back to stage variable
  9349. tempLoad = spvBuilder.createLoad(rayPayloadArg->getType(), rayPayloadStageVar,
  9350. rayPayloadArg->getLocStart());
  9351. spvBuilder.createStore(rayPayloadArgInst, tempLoad, callExpr->getExprLoc());
  9352. return;
  9353. }
  9354. void SpirvEmitter::processDispatchMesh(const CallExpr *callExpr) {
  9355. // HLSL Func - void DispatchMesh(uint ThreadGroupCountX,
  9356. // uint ThreadGroupCountY,
  9357. // uint ThreadGroupCountZ,
  9358. // groupshared <structType> MeshPayload);
  9359. assert(callExpr->getNumArgs() == 4);
  9360. const auto args = callExpr->getArgs();
  9361. const auto loc = callExpr->getExprLoc();
  9362. // 1) create a barrier GroupMemoryBarrierWithGroupSync().
  9363. processIntrinsicMemoryBarrier(callExpr,
  9364. /*isDevice*/ false,
  9365. /*groupSync*/ true,
  9366. /*isAllBarrier*/ false);
  9367. // 2) set TaskCountNV = threadX * threadY * threadZ.
  9368. auto *threadX = doExpr(args[0]);
  9369. auto *threadY = doExpr(args[1]);
  9370. auto *threadZ = doExpr(args[2]);
  9371. auto *var = declIdMapper.getBuiltinVar(spv::BuiltIn::TaskCountNV,
  9372. astContext.UnsignedIntTy, loc);
  9373. auto *taskCount = spvBuilder.createBinaryOp(
  9374. spv::Op::OpIMul, astContext.UnsignedIntTy, threadX,
  9375. spvBuilder.createBinaryOp(spv::Op::OpIMul, astContext.UnsignedIntTy,
  9376. threadY, threadZ, loc),
  9377. loc);
  9378. spvBuilder.createStore(var, taskCount, loc);
  9379. // 3) create PerTaskNV out attribute block and store MeshPayload info.
  9380. const auto *sigPoint =
  9381. hlsl::SigPoint::GetSigPoint(hlsl::DXIL::SigPointKind::MSOut);
  9382. spv::StorageClass sc = spv::StorageClass::Output;
  9383. auto *payloadArg = doExpr(args[3]);
  9384. bool isValid = false;
  9385. if (const auto *implCastExpr = dyn_cast<CastExpr>(args[3])) {
  9386. if (const auto *arg = dyn_cast<DeclRefExpr>(implCastExpr->getSubExpr())) {
  9387. if (const auto *paramDecl = dyn_cast<VarDecl>(arg->getDecl())) {
  9388. if (paramDecl->hasAttr<HLSLGroupSharedAttr>()) {
  9389. isValid = declIdMapper.createPayloadStageVars(
  9390. sigPoint, sc, paramDecl, /*asInput=*/false, paramDecl->getType(),
  9391. "out.var", &payloadArg);
  9392. }
  9393. }
  9394. }
  9395. }
  9396. if (!isValid) {
  9397. emitError("expected groupshared object as argument to DispatchMesh()",
  9398. args[3]->getExprLoc());
  9399. }
  9400. }
  9401. void SpirvEmitter::processMeshOutputCounts(const CallExpr *callExpr) {
  9402. // HLSL Func - void SetMeshOutputCounts(uint numVertices, uint numPrimitives);
  9403. assert(callExpr->getNumArgs() == 2);
  9404. const auto args = callExpr->getArgs();
  9405. const auto loc = callExpr->getExprLoc();
  9406. auto *var = declIdMapper.getBuiltinVar(spv::BuiltIn::PrimitiveCountNV,
  9407. astContext.UnsignedIntTy, loc);
  9408. spvBuilder.createStore(var, doExpr(args[1]), loc);
  9409. }
  9410. SpirvConstant *SpirvEmitter::getValueZero(QualType type) {
  9411. {
  9412. QualType scalarType = {};
  9413. if (isScalarType(type, &scalarType)) {
  9414. if (scalarType->isBooleanType()) {
  9415. return spvBuilder.getConstantBool(false);
  9416. }
  9417. if (scalarType->isIntegerType()) {
  9418. return spvBuilder.getConstantInt(scalarType, llvm::APInt(32, 0));
  9419. }
  9420. if (scalarType->isFloatingType()) {
  9421. return spvBuilder.getConstantFloat(scalarType, llvm::APFloat(0.0f));
  9422. }
  9423. }
  9424. }
  9425. {
  9426. QualType elemType = {};
  9427. uint32_t size = {};
  9428. if (isVectorType(type, &elemType, &size)) {
  9429. return getVecValueZero(elemType, size);
  9430. }
  9431. }
  9432. {
  9433. QualType elemType = {};
  9434. uint32_t rowCount = 0, colCount = 0;
  9435. if (isMxNMatrix(type, &elemType, &rowCount, &colCount)) {
  9436. auto *row = getVecValueZero(elemType, colCount);
  9437. llvm::SmallVector<SpirvConstant *, 4> rows((size_t)rowCount, row);
  9438. return spvBuilder.getConstantComposite(type, rows);
  9439. }
  9440. }
  9441. emitError("getting value 0 for type %0 unimplemented", {})
  9442. << type.getAsString();
  9443. return nullptr;
  9444. }
  9445. SpirvConstant *SpirvEmitter::getVecValueZero(QualType elemType, uint32_t size) {
  9446. auto *elemZeroId = getValueZero(elemType);
  9447. if (size == 1)
  9448. return elemZeroId;
  9449. llvm::SmallVector<SpirvConstant *, 4> elements(size_t(size), elemZeroId);
  9450. const QualType vecType = astContext.getExtVectorType(elemType, size);
  9451. return spvBuilder.getConstantComposite(vecType, elements);
  9452. }
  9453. SpirvConstant *SpirvEmitter::getValueOne(QualType type) {
  9454. {
  9455. QualType scalarType = {};
  9456. if (isScalarType(type, &scalarType)) {
  9457. if (scalarType->isBooleanType()) {
  9458. return spvBuilder.getConstantBool(true);
  9459. }
  9460. if (scalarType->isIntegerType()) {
  9461. return spvBuilder.getConstantInt(scalarType, llvm::APInt(32, 1));
  9462. }
  9463. if (scalarType->isFloatingType()) {
  9464. return spvBuilder.getConstantFloat(scalarType, llvm::APFloat(1.0f));
  9465. }
  9466. }
  9467. }
  9468. {
  9469. QualType elemType = {};
  9470. uint32_t size = {};
  9471. if (isVectorType(type, &elemType, &size)) {
  9472. return getVecValueOne(elemType, size);
  9473. }
  9474. }
  9475. emitError("getting value 1 for type %0 unimplemented", {}) << type;
  9476. return 0;
  9477. }
  9478. SpirvConstant *SpirvEmitter::getVecValueOne(QualType elemType, uint32_t size) {
  9479. auto *elemOne = getValueOne(elemType);
  9480. if (size == 1)
  9481. return elemOne;
  9482. llvm::SmallVector<SpirvConstant *, 4> elements(size_t(size), elemOne);
  9483. const QualType vecType = astContext.getExtVectorType(elemType, size);
  9484. return spvBuilder.getConstantComposite(vecType, elements);
  9485. }
  9486. SpirvConstant *SpirvEmitter::getMatElemValueOne(QualType type) {
  9487. assert(hlsl::IsHLSLMatType(type));
  9488. const auto elemType = hlsl::GetHLSLMatElementType(type);
  9489. uint32_t rowCount = 0, colCount = 0;
  9490. hlsl::GetHLSLMatRowColCount(type, rowCount, colCount);
  9491. if (rowCount == 1 && colCount == 1)
  9492. return getValueOne(elemType);
  9493. if (colCount == 1)
  9494. return getVecValueOne(elemType, rowCount);
  9495. return getVecValueOne(elemType, colCount);
  9496. }
  9497. SpirvConstant *SpirvEmitter::getMaskForBitwidthValue(QualType type) {
  9498. QualType elemType = {};
  9499. uint32_t count = 1;
  9500. if (isScalarType(type, &elemType) || isVectorType(type, &elemType, &count)) {
  9501. const auto bitwidth = getElementSpirvBitwidth(
  9502. astContext, elemType, spirvOptions.enable16BitTypes);
  9503. SpirvConstant *mask = spvBuilder.getConstantInt(
  9504. elemType,
  9505. llvm::APInt(bitwidth, bitwidth - 1, elemType->isSignedIntegerType()));
  9506. if (count == 1)
  9507. return mask;
  9508. const QualType resultType = astContext.getExtVectorType(elemType, count);
  9509. llvm::SmallVector<SpirvConstant *, 4> elements(size_t(count), mask);
  9510. return spvBuilder.getConstantComposite(resultType, elements);
  9511. }
  9512. assert(false && "this method only supports scalars and vectors");
  9513. return nullptr;
  9514. }
  9515. SpirvConstant *SpirvEmitter::translateAPValue(const APValue &value,
  9516. const QualType targetType) {
  9517. SpirvConstant *result = nullptr;
  9518. if (targetType->isBooleanType()) {
  9519. result = spvBuilder.getConstantBool(value.getInt().getBoolValue(),
  9520. isSpecConstantMode);
  9521. } else if (targetType->isIntegerType()) {
  9522. result = translateAPInt(value.getInt(), targetType);
  9523. } else if (targetType->isFloatingType()) {
  9524. result = translateAPFloat(value.getFloat(), targetType);
  9525. } else if (hlsl::IsHLSLVecType(targetType)) {
  9526. const QualType elemType = hlsl::GetHLSLVecElementType(targetType);
  9527. const auto numElements = value.getVectorLength();
  9528. // Special case for vectors of size 1. SPIR-V doesn't support this vector
  9529. // size so we need to translate it to scalar values.
  9530. if (numElements == 1) {
  9531. result = translateAPValue(value.getVectorElt(0), elemType);
  9532. } else {
  9533. llvm::SmallVector<SpirvConstant *, 4> elements;
  9534. for (uint32_t i = 0; i < numElements; ++i) {
  9535. elements.push_back(translateAPValue(value.getVectorElt(i), elemType));
  9536. }
  9537. result = spvBuilder.getConstantComposite(targetType, elements);
  9538. }
  9539. }
  9540. if (result)
  9541. return result;
  9542. emitError("APValue of type %0 unimplemented", {}) << value.getKind();
  9543. value.dump();
  9544. return 0;
  9545. }
  9546. SpirvConstant *SpirvEmitter::translateAPInt(const llvm::APInt &intValue,
  9547. QualType targetType) {
  9548. return spvBuilder.getConstantInt(targetType, intValue, isSpecConstantMode);
  9549. }
  9550. bool SpirvEmitter::isLiteralLargerThan32Bits(const Expr *expr) {
  9551. if (const auto *intLiteral = dyn_cast<IntegerLiteral>(expr)) {
  9552. const bool isSigned = expr->getType()->isSignedIntegerType();
  9553. const llvm::APInt &value = intLiteral->getValue();
  9554. return (isSigned && !value.isSignedIntN(32)) ||
  9555. (!isSigned && !value.isIntN(32));
  9556. }
  9557. if (const auto *floatLiteral = dyn_cast<FloatingLiteral>(expr)) {
  9558. llvm::APFloat value = floatLiteral->getValue();
  9559. const auto &semantics = value.getSemantics();
  9560. // regular 'half' and 'float' can be represented in 32 bits.
  9561. if (&semantics == &llvm::APFloat::IEEEsingle ||
  9562. &semantics == &llvm::APFloat::IEEEhalf)
  9563. return true;
  9564. // See if 'double' value can be represented in 32 bits without losing info.
  9565. bool losesInfo = false;
  9566. const auto convertStatus =
  9567. value.convert(llvm::APFloat::IEEEsingle,
  9568. llvm::APFloat::rmNearestTiesToEven, &losesInfo);
  9569. if (convertStatus != llvm::APFloat::opOK &&
  9570. convertStatus != llvm::APFloat::opInexact)
  9571. return true;
  9572. }
  9573. return false;
  9574. }
  9575. SpirvConstant *SpirvEmitter::tryToEvaluateAsInt32(const llvm::APInt &intValue,
  9576. bool isSigned) {
  9577. if (isSigned && intValue.isSignedIntN(32)) {
  9578. return spvBuilder.getConstantInt(astContext.IntTy, intValue);
  9579. }
  9580. if (!isSigned && intValue.isIntN(32)) {
  9581. return spvBuilder.getConstantInt(astContext.UnsignedIntTy, intValue);
  9582. }
  9583. // Couldn't evaluate as a 32-bit int without losing information.
  9584. return nullptr;
  9585. }
  9586. SpirvConstant *
  9587. SpirvEmitter::tryToEvaluateAsFloat32(const llvm::APFloat &floatValue) {
  9588. const auto &semantics = floatValue.getSemantics();
  9589. // If the given value is already a 32-bit float, there is no need to convert.
  9590. if (&semantics == &llvm::APFloat::IEEEsingle) {
  9591. return spvBuilder.getConstantFloat(astContext.FloatTy, floatValue,
  9592. isSpecConstantMode);
  9593. }
  9594. // Try to see if this literal float can be represented in 32-bit.
  9595. // Since the convert function below may modify the fp value, we call it on a
  9596. // temporary copy.
  9597. llvm::APFloat eval = floatValue;
  9598. bool losesInfo = false;
  9599. const auto convertStatus =
  9600. eval.convert(llvm::APFloat::IEEEsingle,
  9601. llvm::APFloat::rmNearestTiesToEven, &losesInfo);
  9602. if (convertStatus == llvm::APFloat::opOK && !losesInfo)
  9603. return spvBuilder.getConstantFloat(astContext.FloatTy,
  9604. llvm::APFloat(eval.convertToFloat()));
  9605. // Couldn't evaluate as a 32-bit float without losing information.
  9606. return nullptr;
  9607. }
  9608. SpirvConstant *SpirvEmitter::translateAPFloat(llvm::APFloat floatValue,
  9609. QualType targetType) {
  9610. return spvBuilder.getConstantFloat(targetType, floatValue,
  9611. isSpecConstantMode);
  9612. }
  9613. SpirvConstant *SpirvEmitter::tryToEvaluateAsConst(const Expr *expr) {
  9614. Expr::EvalResult evalResult;
  9615. if (expr->EvaluateAsRValue(evalResult, astContext) &&
  9616. !evalResult.HasSideEffects) {
  9617. return translateAPValue(evalResult.Val, expr->getType());
  9618. }
  9619. return nullptr;
  9620. }
  9621. hlsl::ShaderModel::Kind SpirvEmitter::getShaderModelKind(StringRef stageName) {
  9622. hlsl::ShaderModel::Kind smk;
  9623. switch (stageName[0]) {
  9624. case 'c':
  9625. switch (stageName[1]) {
  9626. case 'o':
  9627. smk = hlsl::ShaderModel::Kind::Compute;
  9628. break;
  9629. case 'l':
  9630. smk = hlsl::ShaderModel::Kind::ClosestHit;
  9631. break;
  9632. case 'a':
  9633. smk = hlsl::ShaderModel::Kind::Callable;
  9634. break;
  9635. default:
  9636. smk = hlsl::ShaderModel::Kind::Invalid;
  9637. break;
  9638. }
  9639. break;
  9640. case 'v':
  9641. smk = hlsl::ShaderModel::Kind::Vertex;
  9642. break;
  9643. case 'h':
  9644. smk = hlsl::ShaderModel::Kind::Hull;
  9645. break;
  9646. case 'd':
  9647. smk = hlsl::ShaderModel::Kind::Domain;
  9648. break;
  9649. case 'g':
  9650. smk = hlsl::ShaderModel::Kind::Geometry;
  9651. break;
  9652. case 'p':
  9653. smk = hlsl::ShaderModel::Kind::Pixel;
  9654. break;
  9655. case 'r':
  9656. smk = hlsl::ShaderModel::Kind::RayGeneration;
  9657. break;
  9658. case 'i':
  9659. smk = hlsl::ShaderModel::Kind::Intersection;
  9660. break;
  9661. case 'a':
  9662. switch (stageName[1]) {
  9663. case 'm':
  9664. smk = hlsl::ShaderModel::Kind::Amplification;
  9665. break;
  9666. case 'n':
  9667. smk = hlsl::ShaderModel::Kind::AnyHit;
  9668. break;
  9669. }
  9670. break;
  9671. case 'm':
  9672. switch (stageName[1]) {
  9673. case 'e':
  9674. smk = hlsl::ShaderModel::Kind::Mesh;
  9675. break;
  9676. case 'i':
  9677. smk = hlsl::ShaderModel::Kind::Miss;
  9678. break;
  9679. }
  9680. break;
  9681. default:
  9682. smk = hlsl::ShaderModel::Kind::Invalid;
  9683. break;
  9684. }
  9685. if (smk == hlsl::ShaderModel::Kind::Invalid) {
  9686. llvm_unreachable("unknown stage name");
  9687. }
  9688. return smk;
  9689. }
  9690. spv::ExecutionModel
  9691. SpirvEmitter::getSpirvShaderStage(hlsl::ShaderModel::Kind smk) {
  9692. switch (smk) {
  9693. case hlsl::ShaderModel::Kind::Vertex:
  9694. return spv::ExecutionModel::Vertex;
  9695. case hlsl::ShaderModel::Kind::Hull:
  9696. return spv::ExecutionModel::TessellationControl;
  9697. case hlsl::ShaderModel::Kind::Domain:
  9698. return spv::ExecutionModel::TessellationEvaluation;
  9699. case hlsl::ShaderModel::Kind::Geometry:
  9700. return spv::ExecutionModel::Geometry;
  9701. case hlsl::ShaderModel::Kind::Pixel:
  9702. return spv::ExecutionModel::Fragment;
  9703. case hlsl::ShaderModel::Kind::Compute:
  9704. return spv::ExecutionModel::GLCompute;
  9705. case hlsl::ShaderModel::Kind::RayGeneration:
  9706. return spv::ExecutionModel::RayGenerationNV;
  9707. case hlsl::ShaderModel::Kind::Intersection:
  9708. return spv::ExecutionModel::IntersectionNV;
  9709. case hlsl::ShaderModel::Kind::AnyHit:
  9710. return spv::ExecutionModel::AnyHitNV;
  9711. case hlsl::ShaderModel::Kind::ClosestHit:
  9712. return spv::ExecutionModel::ClosestHitNV;
  9713. case hlsl::ShaderModel::Kind::Miss:
  9714. return spv::ExecutionModel::MissNV;
  9715. case hlsl::ShaderModel::Kind::Callable:
  9716. return spv::ExecutionModel::CallableNV;
  9717. case hlsl::ShaderModel::Kind::Mesh:
  9718. return spv::ExecutionModel::MeshNV;
  9719. case hlsl::ShaderModel::Kind::Amplification:
  9720. return spv::ExecutionModel::TaskNV;
  9721. default:
  9722. llvm_unreachable("invalid shader model kind");
  9723. break;
  9724. }
  9725. }
  9726. bool SpirvEmitter::processGeometryShaderAttributes(const FunctionDecl *decl,
  9727. uint32_t *arraySize) {
  9728. bool success = true;
  9729. assert(spvContext.isGS());
  9730. if (auto *vcAttr = decl->getAttr<HLSLMaxVertexCountAttr>()) {
  9731. spvBuilder.addExecutionMode(
  9732. entryFunction, spv::ExecutionMode::OutputVertices,
  9733. {static_cast<uint32_t>(vcAttr->getCount())}, decl->getLocation());
  9734. }
  9735. uint32_t invocations = 1;
  9736. if (auto *instanceAttr = decl->getAttr<HLSLInstanceAttr>()) {
  9737. invocations = static_cast<uint32_t>(instanceAttr->getCount());
  9738. }
  9739. spvBuilder.addExecutionMode(entryFunction, spv::ExecutionMode::Invocations,
  9740. {invocations}, decl->getLocation());
  9741. // Only one primitive type is permitted for the geometry shader.
  9742. bool outPoint = false, outLine = false, outTriangle = false, inPoint = false,
  9743. inLine = false, inTriangle = false, inLineAdj = false,
  9744. inTriangleAdj = false;
  9745. for (const auto *param : decl->params()) {
  9746. // Add an execution mode based on the output stream type. Do not an
  9747. // execution mode more than once.
  9748. if (param->hasAttr<HLSLInOutAttr>()) {
  9749. const auto paramType = param->getType();
  9750. if (hlsl::IsHLSLTriangleStreamType(paramType) && !outTriangle) {
  9751. spvBuilder.addExecutionMode(entryFunction,
  9752. spv::ExecutionMode::OutputTriangleStrip, {},
  9753. param->getLocation());
  9754. outTriangle = true;
  9755. } else if (hlsl::IsHLSLLineStreamType(paramType) && !outLine) {
  9756. spvBuilder.addExecutionMode(entryFunction,
  9757. spv::ExecutionMode::OutputLineStrip, {},
  9758. param->getLocation());
  9759. outLine = true;
  9760. } else if (hlsl::IsHLSLPointStreamType(paramType) && !outPoint) {
  9761. spvBuilder.addExecutionMode(entryFunction,
  9762. spv::ExecutionMode::OutputPoints, {},
  9763. param->getLocation());
  9764. outPoint = true;
  9765. }
  9766. // An output stream parameter will not have the input primitive type
  9767. // attributes, so we can continue to the next parameter.
  9768. continue;
  9769. }
  9770. // Add an execution mode based on the input primitive type. Do not add an
  9771. // execution mode more than once.
  9772. if (param->hasAttr<HLSLPointAttr>() && !inPoint) {
  9773. spvBuilder.addExecutionMode(entryFunction,
  9774. spv::ExecutionMode::InputPoints, {},
  9775. param->getLocation());
  9776. *arraySize = 1;
  9777. inPoint = true;
  9778. } else if (param->hasAttr<HLSLLineAttr>() && !inLine) {
  9779. spvBuilder.addExecutionMode(entryFunction, spv::ExecutionMode::InputLines,
  9780. {}, param->getLocation());
  9781. *arraySize = 2;
  9782. inLine = true;
  9783. } else if (param->hasAttr<HLSLTriangleAttr>() && !inTriangle) {
  9784. spvBuilder.addExecutionMode(entryFunction, spv::ExecutionMode::Triangles,
  9785. {}, param->getLocation());
  9786. *arraySize = 3;
  9787. inTriangle = true;
  9788. } else if (param->hasAttr<HLSLLineAdjAttr>() && !inLineAdj) {
  9789. spvBuilder.addExecutionMode(entryFunction,
  9790. spv::ExecutionMode::InputLinesAdjacency, {},
  9791. param->getLocation());
  9792. *arraySize = 4;
  9793. inLineAdj = true;
  9794. } else if (param->hasAttr<HLSLTriangleAdjAttr>() && !inTriangleAdj) {
  9795. spvBuilder.addExecutionMode(entryFunction,
  9796. spv::ExecutionMode::InputTrianglesAdjacency,
  9797. {}, param->getLocation());
  9798. *arraySize = 6;
  9799. inTriangleAdj = true;
  9800. }
  9801. }
  9802. if (inPoint + inLine + inLineAdj + inTriangle + inTriangleAdj > 1) {
  9803. emitError("only one input primitive type can be specified in the geometry "
  9804. "shader",
  9805. {});
  9806. success = false;
  9807. }
  9808. if (outPoint + outTriangle + outLine > 1) {
  9809. emitError("only one output primitive type can be specified in the geometry "
  9810. "shader",
  9811. {});
  9812. success = false;
  9813. }
  9814. return success;
  9815. }
  9816. void SpirvEmitter::processPixelShaderAttributes(const FunctionDecl *decl) {
  9817. spvBuilder.addExecutionMode(entryFunction,
  9818. spv::ExecutionMode::OriginUpperLeft, {},
  9819. decl->getLocation());
  9820. if (decl->getAttr<HLSLEarlyDepthStencilAttr>()) {
  9821. spvBuilder.addExecutionMode(entryFunction,
  9822. spv::ExecutionMode::EarlyFragmentTests, {},
  9823. decl->getLocation());
  9824. }
  9825. if (decl->getAttr<VKPostDepthCoverageAttr>()) {
  9826. spvBuilder.addExecutionMode(entryFunction,
  9827. spv::ExecutionMode::PostDepthCoverage, {},
  9828. decl->getLocation());
  9829. }
  9830. }
  9831. void SpirvEmitter::processComputeShaderAttributes(const FunctionDecl *decl) {
  9832. // If not explicitly specified, x, y, and z should be defaulted to 1.
  9833. uint32_t x = 1, y = 1, z = 1;
  9834. if (auto *numThreadsAttr = decl->getAttr<HLSLNumThreadsAttr>()) {
  9835. x = static_cast<uint32_t>(numThreadsAttr->getX());
  9836. y = static_cast<uint32_t>(numThreadsAttr->getY());
  9837. z = static_cast<uint32_t>(numThreadsAttr->getZ());
  9838. } else {
  9839. emitError("thread group size [numthreads(x,y,z)] is missing from the "
  9840. "entry-point function",
  9841. decl->getLocation());
  9842. return;
  9843. }
  9844. spvBuilder.addExecutionMode(entryFunction, spv::ExecutionMode::LocalSize,
  9845. {x, y, z}, decl->getLocation());
  9846. }
  9847. bool SpirvEmitter::processTessellationShaderAttributes(
  9848. const FunctionDecl *decl, uint32_t *numOutputControlPoints) {
  9849. assert(spvContext.isHS() || spvContext.isDS());
  9850. using namespace spv;
  9851. if (auto *domain = decl->getAttr<HLSLDomainAttr>()) {
  9852. const auto domainType = domain->getDomainType().lower();
  9853. const ExecutionMode hsExecMode =
  9854. llvm::StringSwitch<ExecutionMode>(domainType)
  9855. .Case("tri", ExecutionMode::Triangles)
  9856. .Case("quad", ExecutionMode::Quads)
  9857. .Case("isoline", ExecutionMode::Isolines)
  9858. .Default(ExecutionMode::Max);
  9859. if (hsExecMode == ExecutionMode::Max) {
  9860. emitError("unknown domain type specified for entry function",
  9861. domain->getLocation());
  9862. return false;
  9863. }
  9864. spvBuilder.addExecutionMode(entryFunction, hsExecMode, {},
  9865. decl->getLocation());
  9866. }
  9867. // Early return for domain shaders as domain shaders only takes the 'domain'
  9868. // attribute.
  9869. if (spvContext.isDS())
  9870. return true;
  9871. if (auto *partitioning = decl->getAttr<HLSLPartitioningAttr>()) {
  9872. const auto scheme = partitioning->getScheme().lower();
  9873. if (scheme == "pow2") {
  9874. emitError("pow2 partitioning scheme is not supported since there is no "
  9875. "equivalent in Vulkan",
  9876. partitioning->getLocation());
  9877. return false;
  9878. }
  9879. const ExecutionMode hsExecMode =
  9880. llvm::StringSwitch<ExecutionMode>(scheme)
  9881. .Case("fractional_even", ExecutionMode::SpacingFractionalEven)
  9882. .Case("fractional_odd", ExecutionMode::SpacingFractionalOdd)
  9883. .Case("integer", ExecutionMode::SpacingEqual)
  9884. .Default(ExecutionMode::Max);
  9885. if (hsExecMode == ExecutionMode::Max) {
  9886. emitError("unknown partitioning scheme in hull shader",
  9887. partitioning->getLocation());
  9888. return false;
  9889. }
  9890. spvBuilder.addExecutionMode(entryFunction, hsExecMode, {},
  9891. decl->getLocation());
  9892. }
  9893. if (auto *outputTopology = decl->getAttr<HLSLOutputTopologyAttr>()) {
  9894. const auto topology = outputTopology->getTopology().lower();
  9895. const ExecutionMode hsExecMode =
  9896. llvm::StringSwitch<ExecutionMode>(topology)
  9897. .Case("point", ExecutionMode::PointMode)
  9898. .Case("triangle_cw", ExecutionMode::VertexOrderCw)
  9899. .Case("triangle_ccw", ExecutionMode::VertexOrderCcw)
  9900. .Default(ExecutionMode::Max);
  9901. // TODO: There is no SPIR-V equivalent for "line" topology. Is it the
  9902. // default?
  9903. if (topology != "line") {
  9904. if (hsExecMode != spv::ExecutionMode::Max) {
  9905. spvBuilder.addExecutionMode(entryFunction, hsExecMode, {},
  9906. decl->getLocation());
  9907. } else {
  9908. emitError("unknown output topology in hull shader",
  9909. outputTopology->getLocation());
  9910. return false;
  9911. }
  9912. }
  9913. }
  9914. if (auto *controlPoints = decl->getAttr<HLSLOutputControlPointsAttr>()) {
  9915. *numOutputControlPoints = controlPoints->getCount();
  9916. spvBuilder.addExecutionMode(entryFunction,
  9917. spv::ExecutionMode::OutputVertices,
  9918. {*numOutputControlPoints}, decl->getLocation());
  9919. }
  9920. if (auto *pcf = decl->getAttr<HLSLPatchConstantFuncAttr>()) {
  9921. llvm::StringRef pcf_name = pcf->getFunctionName();
  9922. for (auto *decl : astContext.getTranslationUnitDecl()->decls())
  9923. if (auto *funcDecl = dyn_cast<FunctionDecl>(decl))
  9924. if (astContext.IsPatchConstantFunctionDecl(funcDecl) &&
  9925. funcDecl->getName() == pcf_name)
  9926. patchConstFunc = funcDecl;
  9927. }
  9928. return true;
  9929. }
  9930. bool SpirvEmitter::emitEntryFunctionWrapperForRayTracing(
  9931. const FunctionDecl *decl, SpirvFunction *entryFuncInstr) {
  9932. // The entry basic block.
  9933. auto *entryLabel = spvBuilder.createBasicBlock();
  9934. spvBuilder.setInsertPoint(entryLabel);
  9935. // Initialize all global variables at the beginning of the wrapper
  9936. for (const VarDecl *varDecl : toInitGloalVars) {
  9937. const auto varInfo =
  9938. declIdMapper.getDeclEvalInfo(varDecl, varDecl->getLocation());
  9939. if (const auto *init = varDecl->getInit()) {
  9940. storeValue(varInfo, loadIfGLValue(init), varDecl->getType(),
  9941. init->getLocStart());
  9942. // Update counter variable associated with global variables
  9943. tryToAssignCounterVar(varDecl, init);
  9944. }
  9945. // If not explicitly initialized, initialize with their zero values if not
  9946. // resource objects
  9947. else if (!hlsl::IsHLSLResourceType(varDecl->getType())) {
  9948. auto *nullValue = spvBuilder.getConstantNull(varDecl->getType());
  9949. spvBuilder.createStore(varInfo, nullValue, varDecl->getLocation());
  9950. }
  9951. }
  9952. // Create temporary variables for holding function call arguments
  9953. llvm::SmallVector<SpirvInstruction *, 4> params;
  9954. llvm::SmallVector<QualType, 4> paramTypes;
  9955. llvm::SmallVector<SpirvInstruction *, 4> stageVars;
  9956. hlsl::ShaderModel::Kind sKind = spvContext.getCurrentShaderModelKind();
  9957. for (uint32_t i = 0; i < decl->getNumParams(); i++) {
  9958. const auto param = decl->getParamDecl(i);
  9959. const auto paramType = param->getType();
  9960. std::string tempVarName = "param.var." + param->getNameAsString();
  9961. auto *tempVar =
  9962. spvBuilder.addFnVar(paramType, param->getLocation(), tempVarName,
  9963. param->hasAttr<HLSLPreciseAttr>());
  9964. SpirvVariable *curStageVar = nullptr;
  9965. params.push_back(tempVar);
  9966. paramTypes.push_back(paramType);
  9967. // Order of arguments is fixed
  9968. // Any-Hit/Closest-Hit : Arg 0 = rayPayload(inout), Arg1 = attribute(in)
  9969. // Miss : Arg 0 = rayPayload(inout)
  9970. // Callable : Arg 0 = callable data(inout)
  9971. // Raygeneration/Intersection : No Args allowed
  9972. if (sKind == hlsl::ShaderModel::Kind::RayGeneration) {
  9973. assert("Raygeneration shaders have no arguments of entry function");
  9974. } else if (sKind == hlsl::ShaderModel::Kind::Intersection) {
  9975. assert("Intersection shaders have no arguments of entry function");
  9976. } else if (sKind == hlsl::ShaderModel::Kind::ClosestHit ||
  9977. sKind == hlsl::ShaderModel::Kind::AnyHit) {
  9978. // Generate rayPayloadInNV and hitAttributeNV stage variables
  9979. if (i == 0) {
  9980. // First argument is always rayPayload
  9981. curStageVar = declIdMapper.createRayTracingNVStageVar(
  9982. spv::StorageClass::IncomingRayPayloadNV, param);
  9983. currentRayPayload = curStageVar;
  9984. } else {
  9985. // Second argument is always attribute
  9986. curStageVar = declIdMapper.createRayTracingNVStageVar(
  9987. spv::StorageClass::HitAttributeNV, param);
  9988. }
  9989. } else if (sKind == hlsl::ShaderModel::Kind::Miss) {
  9990. // Generate rayPayloadInNV stage variable
  9991. // First and only argument is rayPayload
  9992. curStageVar = declIdMapper.createRayTracingNVStageVar(
  9993. spv::StorageClass::IncomingRayPayloadNV, param);
  9994. } else if (sKind == hlsl::ShaderModel::Kind::Callable) {
  9995. curStageVar = declIdMapper.createRayTracingNVStageVar(
  9996. spv::StorageClass::IncomingCallableDataNV, param);
  9997. }
  9998. if (curStageVar != nullptr) {
  9999. stageVars.push_back(curStageVar);
  10000. // Copy data to temporary
  10001. auto *tempLoadInst =
  10002. spvBuilder.createLoad(paramType, curStageVar, param->getLocation());
  10003. spvBuilder.createStore(tempVar, tempLoadInst, param->getLocation());
  10004. }
  10005. }
  10006. // Call the original entry function
  10007. const QualType retType = decl->getReturnType();
  10008. spvBuilder.createFunctionCall(retType, entryFuncInstr, params,
  10009. decl->getLocStart());
  10010. // Write certain output variables back
  10011. if (sKind == hlsl::ShaderModel::Kind::ClosestHit ||
  10012. sKind == hlsl::ShaderModel::Kind::AnyHit ||
  10013. sKind == hlsl::ShaderModel::Kind::Miss ||
  10014. sKind == hlsl::ShaderModel::Kind::Callable) {
  10015. // Write back results to IncomingRayPayloadNV/IncomingCallableDataNV
  10016. auto *tempLoad = spvBuilder.createLoad(paramTypes[0], params[0],
  10017. decl->getBody()->getLocEnd());
  10018. spvBuilder.createStore(stageVars[0], tempLoad,
  10019. decl->getBody()->getLocEnd());
  10020. }
  10021. spvBuilder.createReturn(decl->getBody()->getLocEnd());
  10022. spvBuilder.endFunction();
  10023. return true;
  10024. }
  10025. bool SpirvEmitter::processMeshOrAmplificationShaderAttributes(
  10026. const FunctionDecl *decl, uint32_t *outVerticesArraySize) {
  10027. if (auto *numThreadsAttr = decl->getAttr<HLSLNumThreadsAttr>()) {
  10028. uint32_t x, y, z;
  10029. x = static_cast<uint32_t>(numThreadsAttr->getX());
  10030. y = static_cast<uint32_t>(numThreadsAttr->getY());
  10031. z = static_cast<uint32_t>(numThreadsAttr->getZ());
  10032. spvBuilder.addExecutionMode(entryFunction, spv::ExecutionMode::LocalSize,
  10033. {x, y, z}, decl->getLocation());
  10034. }
  10035. // Early return for amplification shaders as they only take the 'numthreads'
  10036. // attribute.
  10037. if (spvContext.isAS())
  10038. return true;
  10039. spv::ExecutionMode outputPrimitive = spv::ExecutionMode::Max;
  10040. if (auto *outputTopology = decl->getAttr<HLSLOutputTopologyAttr>()) {
  10041. const auto topology = outputTopology->getTopology().lower();
  10042. outputPrimitive =
  10043. llvm::StringSwitch<spv::ExecutionMode>(topology)
  10044. .Case("point", spv::ExecutionMode::OutputPoints)
  10045. .Case("line", spv::ExecutionMode::OutputLinesNV)
  10046. .Case("triangle", spv::ExecutionMode::OutputTrianglesNV);
  10047. if (outputPrimitive != spv::ExecutionMode::Max) {
  10048. spvBuilder.addExecutionMode(entryFunction, outputPrimitive, {},
  10049. decl->getLocation());
  10050. } else {
  10051. emitError("unknown output topology in mesh shader",
  10052. outputTopology->getLocation());
  10053. return false;
  10054. }
  10055. }
  10056. uint32_t numVertices = 0;
  10057. uint32_t numIndices = 0;
  10058. uint32_t numPrimitives = 0;
  10059. bool payloadDeclSeen = false;
  10060. for (uint32_t i = 0; i < decl->getNumParams(); i++) {
  10061. const auto param = decl->getParamDecl(i);
  10062. const auto paramType = param->getType();
  10063. const auto paramLoc = param->getLocation();
  10064. if (param->hasAttr<HLSLVerticesAttr>() ||
  10065. param->hasAttr<HLSLIndicesAttr>() ||
  10066. param->hasAttr<HLSLPrimitivesAttr>()) {
  10067. uint32_t arraySize = 0;
  10068. if (const auto *arrayType =
  10069. astContext.getAsConstantArrayType(paramType)) {
  10070. const auto eleType =
  10071. arrayType->getElementType()->getCanonicalTypeUnqualified();
  10072. if (param->hasAttr<HLSLIndicesAttr>()) {
  10073. switch (outputPrimitive) {
  10074. case spv::ExecutionMode::OutputPoints:
  10075. if (eleType != astContext.UnsignedIntTy) {
  10076. emitError("expected 1D array of uint type", paramLoc);
  10077. return false;
  10078. }
  10079. break;
  10080. case spv::ExecutionMode::OutputLinesNV: {
  10081. QualType baseType;
  10082. uint32_t length;
  10083. if (!isVectorType(eleType, &baseType, &length) ||
  10084. baseType != astContext.UnsignedIntTy || length != 2) {
  10085. emitError("expected 1D array of uint2 type", paramLoc);
  10086. return false;
  10087. }
  10088. break;
  10089. }
  10090. case spv::ExecutionMode::OutputTrianglesNV: {
  10091. QualType baseType;
  10092. uint32_t length;
  10093. if (!isVectorType(eleType, &baseType, &length) ||
  10094. baseType != astContext.UnsignedIntTy || length != 3) {
  10095. emitError("expected 1D array of uint3 type", paramLoc);
  10096. return false;
  10097. }
  10098. break;
  10099. }
  10100. default:
  10101. assert(false && "unexpected spirv execution mode");
  10102. }
  10103. } else if (!eleType->isStructureType()) {
  10104. // vertices/primitives objects
  10105. emitError("expected 1D array of struct type", paramLoc);
  10106. return false;
  10107. }
  10108. arraySize = static_cast<uint32_t>(arrayType->getSize().getZExtValue());
  10109. } else {
  10110. emitError("expected 1D array of indices/vertices/primitives object",
  10111. paramLoc);
  10112. return false;
  10113. }
  10114. if (param->hasAttr<HLSLVerticesAttr>()) {
  10115. if (numVertices != 0) {
  10116. emitError("only one object with 'vertices' modifier is allowed",
  10117. paramLoc);
  10118. return false;
  10119. }
  10120. numVertices = arraySize;
  10121. } else if (param->hasAttr<HLSLIndicesAttr>()) {
  10122. if (numIndices != 0) {
  10123. emitError("only one object with 'indices' modifier is allowed",
  10124. paramLoc);
  10125. return false;
  10126. }
  10127. numIndices = arraySize;
  10128. } else if (param->hasAttr<HLSLPrimitivesAttr>()) {
  10129. if (numPrimitives != 0) {
  10130. emitError("only one object with 'primitives' modifier is allowed",
  10131. paramLoc);
  10132. return false;
  10133. }
  10134. numPrimitives = arraySize;
  10135. }
  10136. } else if (param->hasAttr<HLSLPayloadAttr>()) {
  10137. if (payloadDeclSeen) {
  10138. emitError("only one object with 'payload' modifier is allowed",
  10139. paramLoc);
  10140. return false;
  10141. }
  10142. payloadDeclSeen = true;
  10143. if (!paramType->isStructureType()) {
  10144. emitError("expected payload of struct type", paramLoc);
  10145. return false;
  10146. }
  10147. }
  10148. }
  10149. // Vertex attribute array is a mandatory param to mesh entry function.
  10150. if (numVertices != 0) {
  10151. *outVerticesArraySize = numVertices;
  10152. spvBuilder.addExecutionMode(
  10153. entryFunction, spv::ExecutionMode::OutputVertices,
  10154. {static_cast<uint32_t>(numVertices)}, decl->getLocation());
  10155. } else {
  10156. emitError("expected vertices object declaration", decl->getLocation());
  10157. return false;
  10158. }
  10159. // Vertex indices array is a mandatory param to mesh entry function.
  10160. if (numIndices != 0) {
  10161. spvBuilder.addExecutionMode(
  10162. entryFunction, spv::ExecutionMode::OutputPrimitivesNV,
  10163. {static_cast<uint32_t>(numIndices)}, decl->getLocation());
  10164. // Primitive attribute array is an optional param to mesh entry function,
  10165. // but the array size should match the indices array.
  10166. if (numPrimitives != 0 && numPrimitives != numIndices) {
  10167. emitError("array size of primitives object should match 'indices' object",
  10168. decl->getLocation());
  10169. return false;
  10170. }
  10171. } else {
  10172. emitError("expected indices object declaration", decl->getLocation());
  10173. return false;
  10174. }
  10175. return true;
  10176. }
  10177. bool SpirvEmitter::emitEntryFunctionWrapper(const FunctionDecl *decl,
  10178. SpirvFunction *entryFuncInstr) {
  10179. // HS specific attributes
  10180. uint32_t numOutputControlPoints = 0;
  10181. SpirvInstruction *outputControlPointIdVal =
  10182. nullptr; // SV_OutputControlPointID value
  10183. SpirvInstruction *primitiveIdVar = nullptr; // SV_PrimitiveID variable
  10184. SpirvInstruction *viewIdVar = nullptr; // SV_ViewID variable
  10185. SpirvInstruction *hullMainInputPatchParam =
  10186. nullptr; // Temporary parameter for InputPatch<>
  10187. // The array size of per-vertex input/output variables
  10188. // Used by HS/DS/GS for the additional arrayness, zero means not an array.
  10189. uint32_t inputArraySize = 0;
  10190. uint32_t outputArraySize = 0;
  10191. // The wrapper entry function surely does not have pre-assigned <result-id>
  10192. // for it like other functions that got added to the work queue following
  10193. // function calls. And the wrapper is the entry function.
  10194. entryFunction = spvBuilder.beginFunction(
  10195. astContext.VoidTy, decl->getLocStart(), decl->getName());
  10196. // Specify that entryFunction is an entry function wrapper.
  10197. entryFunction->setEntryFunctionWrapper();
  10198. // Note this should happen before using declIdMapper for other tasks.
  10199. declIdMapper.setEntryFunction(entryFunction);
  10200. // Set entryFunction for current entry point.
  10201. auto iter = functionInfoMap.find(decl);
  10202. assert(iter != functionInfoMap.end());
  10203. auto &entryInfo = iter->second;
  10204. assert(entryInfo->isEntryFunction);
  10205. entryInfo->entryFunction = entryFunction;
  10206. if (spvContext.isRay()) {
  10207. return emitEntryFunctionWrapperForRayTracing(decl, entryFuncInstr);
  10208. }
  10209. // Handle attributes specific to each shader stage
  10210. if (spvContext.isPS()) {
  10211. processPixelShaderAttributes(decl);
  10212. } else if (spvContext.isCS()) {
  10213. processComputeShaderAttributes(decl);
  10214. } else if (spvContext.isHS()) {
  10215. if (!processTessellationShaderAttributes(decl, &numOutputControlPoints))
  10216. return false;
  10217. // The input array size for HS is specified in the InputPatch parameter.
  10218. for (const auto *param : decl->params())
  10219. if (hlsl::IsHLSLInputPatchType(param->getType())) {
  10220. inputArraySize = hlsl::GetHLSLInputPatchCount(param->getType());
  10221. break;
  10222. }
  10223. outputArraySize = numOutputControlPoints;
  10224. } else if (spvContext.isDS()) {
  10225. if (!processTessellationShaderAttributes(decl, &numOutputControlPoints))
  10226. return false;
  10227. // The input array size for HS is specified in the OutputPatch parameter.
  10228. for (const auto *param : decl->params())
  10229. if (hlsl::IsHLSLOutputPatchType(param->getType())) {
  10230. inputArraySize = hlsl::GetHLSLOutputPatchCount(param->getType());
  10231. break;
  10232. }
  10233. // The per-vertex output of DS is not an array.
  10234. } else if (spvContext.isGS()) {
  10235. if (!processGeometryShaderAttributes(decl, &inputArraySize))
  10236. return false;
  10237. // The per-vertex output of GS is not an array.
  10238. } else if (spvContext.isMS() || spvContext.isAS()) {
  10239. if (!processMeshOrAmplificationShaderAttributes(decl, &outputArraySize))
  10240. return false;
  10241. }
  10242. // Go through all parameters and record the declaration of SV_ClipDistance
  10243. // and SV_CullDistance. We need to do this extra step because in HLSL we
  10244. // can declare multiple SV_ClipDistance/SV_CullDistance variables of float
  10245. // or vector of float types, but we can only have one single float array
  10246. // for the ClipDistance/CullDistance builtin. So we need to group all
  10247. // SV_ClipDistance/SV_CullDistance variables into one float array, thus we
  10248. // need to calculate the total size of the array and the offset of each
  10249. // variable within that array.
  10250. // Also go through all parameters to record the semantic strings provided for
  10251. // the builtins in gl_PerVertex.
  10252. for (const auto *param : decl->params()) {
  10253. if (canActAsInParmVar(param))
  10254. if (!declIdMapper.glPerVertex.recordGlPerVertexDeclFacts(param, true))
  10255. return false;
  10256. if (canActAsOutParmVar(param))
  10257. if (!declIdMapper.glPerVertex.recordGlPerVertexDeclFacts(param, false))
  10258. return false;
  10259. }
  10260. // Also consider the SV_ClipDistance/SV_CullDistance in the return type
  10261. if (!declIdMapper.glPerVertex.recordGlPerVertexDeclFacts(decl, false))
  10262. return false;
  10263. // Calculate the total size of the ClipDistance/CullDistance array and the
  10264. // offset of SV_ClipDistance/SV_CullDistance variables within the array.
  10265. declIdMapper.glPerVertex.calculateClipCullDistanceArraySize();
  10266. if (!spvContext.isCS() && !spvContext.isAS()) {
  10267. // Generate stand-alone builtins of Position, ClipDistance, and
  10268. // CullDistance, which belongs to gl_PerVertex.
  10269. declIdMapper.glPerVertex.generateVars(inputArraySize, outputArraySize);
  10270. }
  10271. // The entry basic block.
  10272. auto *entryLabel = spvBuilder.createBasicBlock();
  10273. spvBuilder.setInsertPoint(entryLabel);
  10274. // Initialize all global variables at the beginning of the wrapper
  10275. for (const VarDecl *varDecl : toInitGloalVars) {
  10276. // SPIR-V does not have string variables
  10277. if (isStringType(varDecl->getType()))
  10278. continue;
  10279. const auto varInfo =
  10280. declIdMapper.getDeclEvalInfo(varDecl, varDecl->getLocation());
  10281. if (const auto *init = varDecl->getInit()) {
  10282. storeValue(varInfo, loadIfGLValue(init), varDecl->getType(),
  10283. init->getLocStart());
  10284. // Update counter variable associated with global variables
  10285. tryToAssignCounterVar(varDecl, init);
  10286. }
  10287. // If not explicitly initialized, initialize with their zero values if not
  10288. // resource objects
  10289. else if (!hlsl::IsHLSLResourceType(varDecl->getType())) {
  10290. auto *nullValue = spvBuilder.getConstantNull(varDecl->getType());
  10291. spvBuilder.createStore(varInfo, nullValue, varDecl->getLocation());
  10292. }
  10293. }
  10294. // Create temporary variables for holding function call arguments
  10295. llvm::SmallVector<SpirvInstruction *, 4> params;
  10296. for (const auto *param : decl->params()) {
  10297. const auto paramType = param->getType();
  10298. std::string tempVarName = "param.var." + param->getNameAsString();
  10299. auto *tempVar =
  10300. spvBuilder.addFnVar(paramType, param->getLocation(), tempVarName,
  10301. param->hasAttr<HLSLPreciseAttr>());
  10302. params.push_back(tempVar);
  10303. // Create the stage input variable for parameter not marked as pure out and
  10304. // initialize the corresponding temporary variable
  10305. // Also do not create input variables for output stream objects of geometry
  10306. // shaders (e.g. TriangleStream) which are required to be marked as 'inout'.
  10307. if (canActAsInParmVar(param)) {
  10308. if (spvContext.isHS() && hlsl::IsHLSLInputPatchType(paramType)) {
  10309. // Record the temporary variable holding InputPatch. It may be used
  10310. // later in the patch constant function.
  10311. hullMainInputPatchParam = tempVar;
  10312. }
  10313. SpirvInstruction *loadedValue = nullptr;
  10314. if (!declIdMapper.createStageInputVar(param, &loadedValue, false))
  10315. return false;
  10316. // Only initialize the temporary variable if the parameter is indeed used.
  10317. if (param->isUsed()) {
  10318. spvBuilder.createStore(tempVar, loadedValue, param->getLocation());
  10319. }
  10320. // Record the temporary variable holding SV_OutputControlPointID,
  10321. // SV_PrimitiveID, and SV_ViewID. It may be used later in the patch
  10322. // constant function.
  10323. if (hasSemantic(param, hlsl::DXIL::SemanticKind::OutputControlPointID))
  10324. outputControlPointIdVal = loadedValue;
  10325. else if (hasSemantic(param, hlsl::DXIL::SemanticKind::PrimitiveID))
  10326. primitiveIdVar = tempVar;
  10327. else if (hasSemantic(param, hlsl::DXIL::SemanticKind::ViewID))
  10328. viewIdVar = tempVar;
  10329. }
  10330. }
  10331. // Call the original entry function
  10332. const QualType retType = decl->getReturnType();
  10333. auto *retVal = spvBuilder.createFunctionCall(retType, entryFuncInstr, params,
  10334. decl->getLocStart());
  10335. // Create and write stage output variables for return value. Special case for
  10336. // Hull shaders since they operate differently in 2 ways:
  10337. // 1- Their return value is in fact an array and each invocation should write
  10338. // to the proper offset in the array.
  10339. // 2- The patch constant function must be called *once* after all invocations
  10340. // of the main entry point function is done.
  10341. if (spvContext.isHS()) {
  10342. // Create stage output variables out of the return type.
  10343. if (!declIdMapper.createStageOutputVar(decl, numOutputControlPoints,
  10344. outputControlPointIdVal, retVal))
  10345. return false;
  10346. if (!processHSEntryPointOutputAndPCF(
  10347. decl, retType, retVal, numOutputControlPoints,
  10348. outputControlPointIdVal, primitiveIdVar, viewIdVar,
  10349. hullMainInputPatchParam))
  10350. return false;
  10351. } else {
  10352. if (!declIdMapper.createStageOutputVar(decl, retVal, /*forPCF*/ false))
  10353. return false;
  10354. }
  10355. // Create and write stage output variables for parameters marked as
  10356. // out/inout
  10357. for (uint32_t i = 0; i < decl->getNumParams(); ++i) {
  10358. const auto *param = decl->getParamDecl(i);
  10359. if (canActAsOutParmVar(param)) {
  10360. // Load the value from the parameter after function call
  10361. SpirvInstruction *loadedParam = nullptr;
  10362. // No need to write back the value if the parameter is not used at all in
  10363. // the original entry function.
  10364. //
  10365. // Write back of stage output variables in GS is manually controlled by
  10366. // .Append() intrinsic method. No need to load the parameter since we
  10367. // won't need to write back here.
  10368. if (param->isUsed() && !spvContext.isGS())
  10369. loadedParam = spvBuilder.createLoad(param->getType(), params[i],
  10370. param->getLocStart());
  10371. if (!declIdMapper.createStageOutputVar(param, loadedParam, false))
  10372. return false;
  10373. }
  10374. }
  10375. // To prevent spirv-opt from removing all debug info, we emit at least
  10376. // a single OpLine to specify the end of the shader. This SourceLocation
  10377. // will provide the information.
  10378. spvBuilder.createReturn(decl->getLocEnd());
  10379. spvBuilder.endFunction();
  10380. // For Hull shaders, there is no explicit call to the PCF in the HLSL source.
  10381. // We should invoke a translation of the PCF manually.
  10382. if (spvContext.isHS())
  10383. doDecl(patchConstFunc);
  10384. return true;
  10385. }
  10386. bool SpirvEmitter::processHSEntryPointOutputAndPCF(
  10387. const FunctionDecl *hullMainFuncDecl, QualType retType,
  10388. SpirvInstruction *retVal, uint32_t numOutputControlPoints,
  10389. SpirvInstruction *outputControlPointId, SpirvInstruction *primitiveId,
  10390. SpirvInstruction *viewId, SpirvInstruction *hullMainInputPatch) {
  10391. // This method may only be called for Hull shaders.
  10392. assert(spvContext.isHS());
  10393. auto loc = hullMainFuncDecl->getLocation();
  10394. auto locEnd = hullMainFuncDecl->getLocEnd();
  10395. // For Hull shaders, the real output is an array of size
  10396. // numOutputControlPoints. The results of the main should be written to the
  10397. // correct offset in the array (based on InvocationID).
  10398. if (!numOutputControlPoints) {
  10399. emitError("number of output control points cannot be zero", loc);
  10400. return false;
  10401. }
  10402. // TODO: We should be able to handle cases where the SV_OutputControlPointID
  10403. // is not provided.
  10404. if (!outputControlPointId) {
  10405. emitError(
  10406. "SV_OutputControlPointID semantic must be provided in hull shader",
  10407. loc);
  10408. return false;
  10409. }
  10410. if (!patchConstFunc) {
  10411. emitError("patch constant function not defined in hull shader", loc);
  10412. return false;
  10413. }
  10414. SpirvInstruction *hullMainOutputPatch = nullptr;
  10415. // If the patch constant function (PCF) takes the result of the Hull main
  10416. // entry point, create a temporary function-scope variable and write the
  10417. // results to it, so it can be passed to the PCF.
  10418. if (const auto *param = patchConstFuncTakesHullOutputPatch(patchConstFunc)) {
  10419. hullMainOutputPatch = declIdMapper.createHullMainOutputPatch(
  10420. param, retType, numOutputControlPoints);
  10421. auto *tempLocation = spvBuilder.createAccessChain(
  10422. retType, hullMainOutputPatch, {outputControlPointId}, locEnd);
  10423. spvBuilder.createStore(tempLocation, retVal, locEnd);
  10424. }
  10425. // Now create a barrier before calling the Patch Constant Function (PCF).
  10426. // Flags are:
  10427. // Execution Barrier scope = Workgroup (2)
  10428. // Memory Barrier scope = Invocation (4)
  10429. // Memory Semantics Barrier scope = None (0)
  10430. spvBuilder.createBarrier(spv::Scope::Invocation,
  10431. spv::MemorySemanticsMask::MaskNone,
  10432. spv::Scope::Workgroup, {});
  10433. // The PCF should be called only once. Therefore, we check the invocationID,
  10434. // and we only allow ID 0 to call the PCF.
  10435. auto *condition = spvBuilder.createBinaryOp(
  10436. spv::Op::OpIEqual, astContext.BoolTy, outputControlPointId,
  10437. spvBuilder.getConstantInt(astContext.UnsignedIntTy, llvm::APInt(32, 0)),
  10438. loc);
  10439. auto *thenBB = spvBuilder.createBasicBlock("if.true");
  10440. auto *mergeBB = spvBuilder.createBasicBlock("if.merge");
  10441. spvBuilder.createConditionalBranch(condition, thenBB, mergeBB, loc, mergeBB);
  10442. spvBuilder.addSuccessor(thenBB);
  10443. spvBuilder.addSuccessor(mergeBB);
  10444. spvBuilder.setMergeTarget(mergeBB);
  10445. spvBuilder.setInsertPoint(thenBB);
  10446. // Call the PCF. Since the function is not explicitly called, we must first
  10447. // register an ID for it.
  10448. SpirvFunction *pcfId = declIdMapper.getOrRegisterFn(patchConstFunc);
  10449. const QualType pcfRetType = patchConstFunc->getReturnType();
  10450. std::vector<SpirvInstruction *> pcfParams;
  10451. // A lambda for creating a stage input variable and its associated temporary
  10452. // variable for function call. Also initializes the temporary variable using
  10453. // the contents loaded from the stage input variable. Returns the <result-id>
  10454. // of the temporary variable.
  10455. const auto createParmVarAndInitFromStageInputVar =
  10456. [this](const ParmVarDecl *param) {
  10457. const QualType type = param->getType();
  10458. std::string tempVarName = "param.var." + param->getNameAsString();
  10459. auto paramLoc = param->getLocation();
  10460. auto *tempVar = spvBuilder.addFnVar(type, paramLoc, tempVarName,
  10461. param->hasAttr<HLSLPreciseAttr>());
  10462. SpirvInstruction *loadedValue = nullptr;
  10463. declIdMapper.createStageInputVar(param, &loadedValue, /*forPCF*/ true);
  10464. spvBuilder.createStore(tempVar, loadedValue, paramLoc);
  10465. return tempVar;
  10466. };
  10467. for (const auto *param : patchConstFunc->parameters()) {
  10468. // Note: According to the HLSL reference, the PCF takes an InputPatch of
  10469. // ControlPoints as well as the PatchID (PrimitiveID). This does not
  10470. // necessarily mean that they are present. There is also no requirement
  10471. // for the order of parameters passed to PCF.
  10472. if (hlsl::IsHLSLInputPatchType(param->getType())) {
  10473. pcfParams.push_back(hullMainInputPatch);
  10474. } else if (hlsl::IsHLSLOutputPatchType(param->getType())) {
  10475. // Since the output patch used in hull shaders is translated to
  10476. // a variable with Workgroup storage class, there is no need
  10477. // to pass the variable as function parameter in SPIR-V.
  10478. continue;
  10479. } else if (hasSemantic(param, hlsl::DXIL::SemanticKind::PrimitiveID)) {
  10480. if (!primitiveId) {
  10481. primitiveId = createParmVarAndInitFromStageInputVar(param);
  10482. }
  10483. pcfParams.push_back(primitiveId);
  10484. } else if (hasSemantic(param, hlsl::DXIL::SemanticKind::ViewID)) {
  10485. if (!viewId) {
  10486. viewId = createParmVarAndInitFromStageInputVar(param);
  10487. }
  10488. pcfParams.push_back(viewId);
  10489. } else {
  10490. emitError("patch constant function parameter '%0' unknown",
  10491. param->getLocation())
  10492. << param->getName();
  10493. }
  10494. }
  10495. auto *pcfResultId = spvBuilder.createFunctionCall(
  10496. pcfRetType, pcfId, {pcfParams}, hullMainFuncDecl->getLocStart());
  10497. if (!declIdMapper.createStageOutputVar(patchConstFunc, pcfResultId,
  10498. /*forPCF*/ true))
  10499. return false;
  10500. spvBuilder.createBranch(mergeBB, locEnd);
  10501. spvBuilder.addSuccessor(mergeBB);
  10502. spvBuilder.setInsertPoint(mergeBB);
  10503. return true;
  10504. }
  10505. bool SpirvEmitter::allSwitchCasesAreIntegerLiterals(const Stmt *root) {
  10506. if (!root)
  10507. return false;
  10508. const auto *caseStmt = dyn_cast<CaseStmt>(root);
  10509. const auto *compoundStmt = dyn_cast<CompoundStmt>(root);
  10510. if (!caseStmt && !compoundStmt)
  10511. return true;
  10512. if (caseStmt) {
  10513. const Expr *caseExpr = caseStmt->getLHS();
  10514. return caseExpr && caseExpr->isEvaluatable(astContext);
  10515. }
  10516. // Recurse down if facing a compound statement.
  10517. for (auto *st : compoundStmt->body())
  10518. if (!allSwitchCasesAreIntegerLiterals(st))
  10519. return false;
  10520. return true;
  10521. }
  10522. void SpirvEmitter::discoverAllCaseStmtInSwitchStmt(
  10523. const Stmt *root, SpirvBasicBlock **defaultBB,
  10524. std::vector<std::pair<uint32_t, SpirvBasicBlock *>> *targets) {
  10525. if (!root)
  10526. return;
  10527. // A switch case can only appear in DefaultStmt, CaseStmt, or
  10528. // CompoundStmt. For the rest, we can just return.
  10529. const auto *defaultStmt = dyn_cast<DefaultStmt>(root);
  10530. const auto *caseStmt = dyn_cast<CaseStmt>(root);
  10531. const auto *compoundStmt = dyn_cast<CompoundStmt>(root);
  10532. if (!defaultStmt && !caseStmt && !compoundStmt)
  10533. return;
  10534. // Recurse down if facing a compound statement.
  10535. if (compoundStmt) {
  10536. for (auto *st : compoundStmt->body())
  10537. discoverAllCaseStmtInSwitchStmt(st, defaultBB, targets);
  10538. return;
  10539. }
  10540. std::string caseLabel;
  10541. uint32_t caseValue = 0;
  10542. if (defaultStmt) {
  10543. // This is the default branch.
  10544. caseLabel = "switch.default";
  10545. } else if (caseStmt) {
  10546. // This is a non-default case.
  10547. // When using OpSwitch, we only allow integer literal cases. e.g:
  10548. // case <literal_integer>: {...; break;}
  10549. const Expr *caseExpr = caseStmt->getLHS();
  10550. assert(caseExpr && caseExpr->isEvaluatable(astContext));
  10551. auto bitWidth = astContext.getIntWidth(caseExpr->getType());
  10552. if (bitWidth != 32)
  10553. emitError(
  10554. "non-32bit integer case value in switch statement unimplemented",
  10555. caseExpr->getExprLoc());
  10556. Expr::EvalResult evalResult;
  10557. caseExpr->EvaluateAsRValue(evalResult, astContext);
  10558. const int64_t value = evalResult.Val.getInt().getSExtValue();
  10559. caseValue = static_cast<uint32_t>(value);
  10560. caseLabel = "switch." + std::string(value < 0 ? "n" : "") +
  10561. llvm::itostr(std::abs(value));
  10562. }
  10563. auto *caseBB = spvBuilder.createBasicBlock(caseLabel);
  10564. spvBuilder.addSuccessor(caseBB);
  10565. stmtBasicBlock[root] = caseBB;
  10566. // Add all cases to the 'targets' vector.
  10567. if (caseStmt)
  10568. targets->emplace_back(caseValue, caseBB);
  10569. // The default label is not part of the 'targets' vector that is passed
  10570. // to the OpSwitch instruction.
  10571. // If default statement was discovered, return its label via defaultBB.
  10572. if (defaultStmt)
  10573. *defaultBB = caseBB;
  10574. // Process cases nested in other cases. It happens when we have fall through
  10575. // cases. For example:
  10576. // case 1: case 2: ...; break;
  10577. // will result in the CaseSmt for case 2 nested in the one for case 1.
  10578. discoverAllCaseStmtInSwitchStmt(caseStmt ? caseStmt->getSubStmt()
  10579. : defaultStmt->getSubStmt(),
  10580. defaultBB, targets);
  10581. }
  10582. void SpirvEmitter::flattenSwitchStmtAST(const Stmt *root,
  10583. std::vector<const Stmt *> *flatSwitch) {
  10584. const auto *caseStmt = dyn_cast<CaseStmt>(root);
  10585. const auto *compoundStmt = dyn_cast<CompoundStmt>(root);
  10586. const auto *defaultStmt = dyn_cast<DefaultStmt>(root);
  10587. if (!compoundStmt) {
  10588. flatSwitch->push_back(root);
  10589. }
  10590. if (compoundStmt) {
  10591. for (const auto *st : compoundStmt->body())
  10592. flattenSwitchStmtAST(st, flatSwitch);
  10593. } else if (caseStmt) {
  10594. flattenSwitchStmtAST(caseStmt->getSubStmt(), flatSwitch);
  10595. } else if (defaultStmt) {
  10596. flattenSwitchStmtAST(defaultStmt->getSubStmt(), flatSwitch);
  10597. }
  10598. }
  10599. void SpirvEmitter::processCaseStmtOrDefaultStmt(const Stmt *stmt) {
  10600. auto *caseStmt = dyn_cast<CaseStmt>(stmt);
  10601. auto *defaultStmt = dyn_cast<DefaultStmt>(stmt);
  10602. assert(caseStmt || defaultStmt);
  10603. auto *caseBB = stmtBasicBlock[stmt];
  10604. if (!spvBuilder.isCurrentBasicBlockTerminated()) {
  10605. // We are about to handle the case passed in as parameter. If the current
  10606. // basic block is not terminated, it means the previous case is a fall
  10607. // through case. We need to link it to the case to be processed.
  10608. spvBuilder.createBranch(caseBB, stmt->getLocStart());
  10609. spvBuilder.addSuccessor(caseBB);
  10610. }
  10611. spvBuilder.setInsertPoint(caseBB);
  10612. doStmt(caseStmt ? caseStmt->getSubStmt() : defaultStmt->getSubStmt());
  10613. }
  10614. void SpirvEmitter::processSwitchStmtUsingSpirvOpSwitch(
  10615. const SwitchStmt *switchStmt) {
  10616. const SourceLocation srcLoc = switchStmt->getSwitchLoc();
  10617. // First handle the condition variable DeclStmt if one exists.
  10618. // For example: handle 'int a = b' in the following:
  10619. // switch (int a = b) {...}
  10620. if (const auto *condVarDeclStmt = switchStmt->getConditionVariableDeclStmt())
  10621. doDeclStmt(condVarDeclStmt);
  10622. auto *selector = doExpr(switchStmt->getCond());
  10623. // We need a merge block regardless of the number of switch cases.
  10624. // Since OpSwitch always requires a default label, if the switch statement
  10625. // does not have a default branch, we use the merge block as the default
  10626. // target.
  10627. auto *mergeBB = spvBuilder.createBasicBlock("switch.merge");
  10628. spvBuilder.setMergeTarget(mergeBB);
  10629. breakStack.push(mergeBB);
  10630. auto *defaultBB = mergeBB;
  10631. // (literal, labelId) pairs to pass to the OpSwitch instruction.
  10632. std::vector<std::pair<uint32_t, SpirvBasicBlock *>> targets;
  10633. discoverAllCaseStmtInSwitchStmt(switchStmt->getBody(), &defaultBB, &targets);
  10634. // Create the OpSelectionMerge and OpSwitch.
  10635. spvBuilder.createSwitch(mergeBB, selector, defaultBB, targets, srcLoc);
  10636. // Handle the switch body.
  10637. doStmt(switchStmt->getBody());
  10638. if (!spvBuilder.isCurrentBasicBlockTerminated())
  10639. spvBuilder.createBranch(mergeBB, switchStmt->getLocEnd());
  10640. spvBuilder.setInsertPoint(mergeBB);
  10641. breakStack.pop();
  10642. }
  10643. void SpirvEmitter::processSwitchStmtUsingIfStmts(const SwitchStmt *switchStmt) {
  10644. std::vector<const Stmt *> flatSwitch;
  10645. flattenSwitchStmtAST(switchStmt->getBody(), &flatSwitch);
  10646. // First handle the condition variable DeclStmt if one exists.
  10647. // For example: handle 'int a = b' in the following:
  10648. // switch (int a = b) {...}
  10649. if (const auto *condVarDeclStmt = switchStmt->getConditionVariableDeclStmt())
  10650. doDeclStmt(condVarDeclStmt);
  10651. // Figure out the indexes of CaseStmts (and DefaultStmt if it exists) in
  10652. // the flattened switch AST.
  10653. // For instance, for the following flat vector:
  10654. // +-----+-----+-----+-----+-----+-----+-----+-----+-----+-------+-----+
  10655. // |Case1|Stmt1|Case2|Stmt2|Break|Case3|Case4|Stmt4|Break|Default|Stmt5|
  10656. // +-----+-----+-----+-----+-----+-----+-----+-----+-----+-------+-----+
  10657. // The indexes are: {0, 2, 5, 6, 9}
  10658. std::vector<uint32_t> caseStmtLocs;
  10659. for (uint32_t i = 0; i < flatSwitch.size(); ++i)
  10660. if (isa<CaseStmt>(flatSwitch[i]) || isa<DefaultStmt>(flatSwitch[i]))
  10661. caseStmtLocs.push_back(i);
  10662. IfStmt *prevIfStmt = nullptr;
  10663. IfStmt *rootIfStmt = nullptr;
  10664. CompoundStmt *defaultBody = nullptr;
  10665. // For each case, start at its index in the vector, and go forward
  10666. // accumulating statements until BreakStmt or end of vector is reached.
  10667. for (auto curCaseIndex : caseStmtLocs) {
  10668. const Stmt *curCase = flatSwitch[curCaseIndex];
  10669. // CompoundStmt to hold all statements for this case.
  10670. CompoundStmt *cs = new (astContext) CompoundStmt(Stmt::EmptyShell());
  10671. // Accumulate all non-case/default/break statements as the body for the
  10672. // current case.
  10673. std::vector<Stmt *> statements;
  10674. for (unsigned i = curCaseIndex + 1;
  10675. i < flatSwitch.size() && !isa<BreakStmt>(flatSwitch[i]); ++i) {
  10676. if (!isa<CaseStmt>(flatSwitch[i]) && !isa<DefaultStmt>(flatSwitch[i]))
  10677. statements.push_back(const_cast<Stmt *>(flatSwitch[i]));
  10678. }
  10679. if (!statements.empty())
  10680. cs->setStmts(astContext, statements.data(), statements.size());
  10681. // For non-default cases, generate the IfStmt that compares the switch
  10682. // value to the case value.
  10683. if (auto *caseStmt = dyn_cast<CaseStmt>(curCase)) {
  10684. IfStmt *curIf = new (astContext) IfStmt(Stmt::EmptyShell());
  10685. BinaryOperator *bo = new (astContext) BinaryOperator(Stmt::EmptyShell());
  10686. bo->setLHS(const_cast<Expr *>(switchStmt->getCond()));
  10687. bo->setRHS(const_cast<Expr *>(caseStmt->getLHS()));
  10688. bo->setOpcode(BO_EQ);
  10689. bo->setType(astContext.getLogicalOperationType());
  10690. curIf->setCond(bo);
  10691. curIf->setThen(cs);
  10692. // No conditional variable associated with this faux if statement.
  10693. curIf->setConditionVariable(astContext, nullptr);
  10694. // Each If statement is the "else" of the previous if statement.
  10695. if (prevIfStmt)
  10696. prevIfStmt->setElse(curIf);
  10697. else
  10698. rootIfStmt = curIf;
  10699. prevIfStmt = curIf;
  10700. } else {
  10701. // Record the DefaultStmt body as it will be used as the body of the
  10702. // "else" block in the if-elseif-...-else pattern.
  10703. defaultBody = cs;
  10704. }
  10705. }
  10706. // If a default case exists, it is the "else" of the last if statement.
  10707. if (prevIfStmt)
  10708. prevIfStmt->setElse(defaultBody);
  10709. // Since all else-if and else statements are the child nodes of the first
  10710. // IfStmt, we only need to call doStmt for the first IfStmt.
  10711. if (rootIfStmt)
  10712. doStmt(rootIfStmt);
  10713. // If there are no CaseStmt and there is only 1 DefaultStmt, there will be
  10714. // no if statements. The switch in that case only executes the body of the
  10715. // default case.
  10716. else if (defaultBody)
  10717. doStmt(defaultBody);
  10718. }
  10719. SpirvInstruction *SpirvEmitter::extractVecFromVec4(SpirvInstruction *from,
  10720. uint32_t targetVecSize,
  10721. QualType targetElemType,
  10722. SourceLocation loc) {
  10723. assert(targetVecSize > 0 && targetVecSize < 5);
  10724. const QualType retType =
  10725. targetVecSize == 1
  10726. ? targetElemType
  10727. : astContext.getExtVectorType(targetElemType, targetVecSize);
  10728. switch (targetVecSize) {
  10729. case 1:
  10730. return spvBuilder.createCompositeExtract(retType, from, {0}, loc);
  10731. break;
  10732. case 2:
  10733. return spvBuilder.createVectorShuffle(retType, from, from, {0, 1}, loc);
  10734. break;
  10735. case 3:
  10736. return spvBuilder.createVectorShuffle(retType, from, from, {0, 1, 2}, loc);
  10737. break;
  10738. case 4:
  10739. return from;
  10740. default:
  10741. llvm_unreachable("vector element count must be 1, 2, 3, or 4");
  10742. }
  10743. }
  10744. void SpirvEmitter::addFunctionToWorkQueue(hlsl::DXIL::ShaderKind shaderKind,
  10745. const clang::FunctionDecl *fnDecl,
  10746. bool isEntryFunction) {
  10747. // Only update the workQueue and the function info map if the given
  10748. // FunctionDecl hasn't been added already.
  10749. if (functionInfoMap.find(fnDecl) == functionInfoMap.end()) {
  10750. // Note: The function is just discovered and is being added to the
  10751. // workQueue, therefore it does not have the entryFunction SPIR-V
  10752. // instruction yet (use nullptr).
  10753. auto *fnInfo = new (spvContext) FunctionInfo(
  10754. shaderKind, fnDecl, /*entryFunction*/ nullptr, isEntryFunction);
  10755. functionInfoMap[fnDecl] = fnInfo;
  10756. workQueue.push_back(fnInfo);
  10757. }
  10758. }
  10759. SpirvInstruction *
  10760. SpirvEmitter::processTraceRayInline(const CXXMemberCallExpr *expr) {
  10761. const auto object = expr->getImplicitObjectArgument();
  10762. uint32_t templateFlags = hlsl::GetHLSLResourceTemplateUInt(object->getType());
  10763. const auto constFlags = spvBuilder.getConstantInt(
  10764. astContext.UnsignedIntTy, llvm::APInt(32, templateFlags));
  10765. SpirvInstruction *rayqueryObj = loadIfAliasVarRef(object);
  10766. const auto args = expr->getArgs();
  10767. if (expr->getNumArgs() != 4) {
  10768. emitError("invalid number of arguments to RayQueryInitialize",
  10769. expr->getExprLoc());
  10770. }
  10771. // HLSL Func
  10772. // void RayQuery::TraceRayInline(
  10773. // RaytracingAccelerationStructure AccelerationStructure,
  10774. // uint RayFlags,
  10775. // uint InstanceInclusionMask,
  10776. // RayDesc Ray);
  10777. // void OpRayQueryInitializeKHR ( <id> RayQuery,
  10778. // <id> Acceleration Structure
  10779. // <id> RayFlags
  10780. // <id> CullMask
  10781. // <id> RayOrigin
  10782. // <id> RayTmin
  10783. // <id> RayDirection
  10784. // <id> Ray Tmax)
  10785. const auto accelStructure = doExpr(args[0]);
  10786. SpirvInstruction *rayFlags = nullptr;
  10787. if ((rayFlags = tryToEvaluateAsConst(args[1]))) {
  10788. rayFlags->setRValue();
  10789. } else {
  10790. rayFlags = doExpr(args[1]);
  10791. }
  10792. if (auto constFlags = dyn_cast<SpirvConstantInteger>(rayFlags)) {
  10793. auto interRayFlags = constFlags->getValue().getZExtValue();
  10794. templateFlags |= interRayFlags;
  10795. }
  10796. bool hasCullFlags =
  10797. templateFlags & (uint32_t(hlsl::DXIL::RayFlag::SkipTriangles) |
  10798. uint32_t(hlsl::DXIL::RayFlag::SkipProceduralPrimitives));
  10799. auto loc = args[1]->getLocStart();
  10800. rayFlags =
  10801. spvBuilder.createBinaryOp(spv::Op::OpBitwiseOr, astContext.UnsignedIntTy,
  10802. constFlags, rayFlags, loc);
  10803. const auto cullMask = doExpr(args[2]);
  10804. // Extract the ray description to match SPIR-V
  10805. const auto floatType = astContext.FloatTy;
  10806. const auto vecType = astContext.getExtVectorType(astContext.FloatTy, 3);
  10807. SpirvInstruction *rayDescArg = doExpr(args[3]);
  10808. loc = args[3]->getLocStart();
  10809. const auto origin =
  10810. spvBuilder.createCompositeExtract(vecType, rayDescArg, {0}, loc);
  10811. const auto tMin =
  10812. spvBuilder.createCompositeExtract(floatType, rayDescArg, {1}, loc);
  10813. const auto direction =
  10814. spvBuilder.createCompositeExtract(vecType, rayDescArg, {2}, loc);
  10815. const auto tMax =
  10816. spvBuilder.createCompositeExtract(floatType, rayDescArg, {3}, loc);
  10817. llvm::SmallVector<SpirvInstruction *, 8> traceArgs = {
  10818. rayqueryObj, accelStructure, rayFlags, cullMask,
  10819. origin, tMin, direction, tMax};
  10820. return spvBuilder.createRayQueryOpsKHR(spv::Op::OpRayQueryInitializeKHR,
  10821. QualType(), traceArgs, hasCullFlags,
  10822. expr->getExprLoc());
  10823. }
  10824. SpirvInstruction *
  10825. SpirvEmitter::processRayQueryIntrinsics(const CXXMemberCallExpr *expr,
  10826. hlsl::IntrinsicOp opcode) {
  10827. const auto object = expr->getImplicitObjectArgument();
  10828. SpirvInstruction *rayqueryObj = loadIfAliasVarRef(object);
  10829. const auto args = expr->getArgs();
  10830. llvm::SmallVector<SpirvInstruction *, 8> traceArgs;
  10831. traceArgs.push_back(rayqueryObj);
  10832. for (uint32_t i = 0; i < expr->getNumArgs(); ++i) {
  10833. traceArgs.push_back(doExpr(args[i]));
  10834. }
  10835. spv::Op spvCode = spv::Op::Max;
  10836. QualType exprType = expr->getType();
  10837. exprType = exprType->isVoidType() ? QualType() : exprType;
  10838. const auto candidateIntersection =
  10839. spvBuilder.getConstantInt(astContext.UnsignedIntTy, llvm::APInt(32, 0));
  10840. const auto committedIntersection =
  10841. spvBuilder.getConstantInt(astContext.UnsignedIntTy, llvm::APInt(32, 1));
  10842. bool transposeMatrix = false;
  10843. bool logicalNot = false;
  10844. using namespace hlsl;
  10845. switch (opcode) {
  10846. case IntrinsicOp::MOP_Proceed:
  10847. spvCode = spv::Op::OpRayQueryProceedKHR;
  10848. break;
  10849. case IntrinsicOp::MOP_Abort:
  10850. spvCode = spv::Op::OpRayQueryTerminateKHR;
  10851. exprType = QualType();
  10852. break;
  10853. case IntrinsicOp::MOP_CandidateGeometryIndex:
  10854. traceArgs.push_back(candidateIntersection);
  10855. spvCode = spv::Op::OpRayQueryGetIntersectionGeometryIndexKHR;
  10856. break;
  10857. case IntrinsicOp::MOP_CandidateInstanceContributionToHitGroupIndex:
  10858. traceArgs.push_back(candidateIntersection);
  10859. spvCode = spv::Op::
  10860. OpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffsetKHR;
  10861. break;
  10862. case IntrinsicOp::MOP_CandidateInstanceID:
  10863. traceArgs.push_back(candidateIntersection);
  10864. spvCode = spv::Op::OpRayQueryGetIntersectionInstanceCustomIndexKHR;
  10865. break;
  10866. case IntrinsicOp::MOP_CandidateInstanceIndex:
  10867. traceArgs.push_back(candidateIntersection);
  10868. spvCode = spv::Op::OpRayQueryGetIntersectionInstanceIdKHR;
  10869. break;
  10870. case IntrinsicOp::MOP_CandidateObjectRayDirection:
  10871. traceArgs.push_back(candidateIntersection);
  10872. spvCode = spv::Op::OpRayQueryGetIntersectionObjectRayDirectionKHR;
  10873. break;
  10874. case IntrinsicOp::MOP_CandidateObjectRayOrigin:
  10875. traceArgs.push_back(candidateIntersection);
  10876. spvCode = spv::Op::OpRayQueryGetIntersectionObjectRayOriginKHR;
  10877. break;
  10878. case IntrinsicOp::MOP_CandidateObjectToWorld3x4:
  10879. spvCode = spv::Op::OpRayQueryGetIntersectionObjectToWorldKHR;
  10880. traceArgs.push_back(candidateIntersection);
  10881. transposeMatrix = true;
  10882. break;
  10883. case IntrinsicOp::MOP_CandidateObjectToWorld4x3:
  10884. spvCode = spv::Op::OpRayQueryGetIntersectionObjectToWorldKHR;
  10885. traceArgs.push_back(candidateIntersection);
  10886. break;
  10887. case IntrinsicOp::MOP_CandidatePrimitiveIndex:
  10888. traceArgs.push_back(candidateIntersection);
  10889. spvCode = spv::Op::OpRayQueryGetIntersectionPrimitiveIndexKHR;
  10890. break;
  10891. case IntrinsicOp::MOP_CandidateProceduralPrimitiveNonOpaque:
  10892. spvCode = spv::Op::OpRayQueryGetIntersectionCandidateAABBOpaqueKHR;
  10893. logicalNot = true;
  10894. break;
  10895. case IntrinsicOp::MOP_CandidateTriangleBarycentrics:
  10896. traceArgs.push_back(candidateIntersection);
  10897. spvCode = spv::Op::OpRayQueryGetIntersectionBarycentricsKHR;
  10898. break;
  10899. case IntrinsicOp::MOP_CandidateTriangleFrontFace:
  10900. traceArgs.push_back(candidateIntersection);
  10901. spvCode = spv::Op::OpRayQueryGetIntersectionFrontFaceKHR;
  10902. break;
  10903. case IntrinsicOp::MOP_CandidateTriangleRayT:
  10904. traceArgs.push_back(candidateIntersection);
  10905. spvCode = spv::Op::OpRayQueryGetIntersectionTKHR;
  10906. break;
  10907. case IntrinsicOp::MOP_CandidateType:
  10908. spvCode = spv::Op::OpRayQueryGetIntersectionTypeKHR;
  10909. traceArgs.push_back(candidateIntersection);
  10910. break;
  10911. case IntrinsicOp::MOP_CandidateWorldToObject4x3:
  10912. spvCode = spv::Op::OpRayQueryGetIntersectionWorldToObjectKHR;
  10913. traceArgs.push_back(candidateIntersection);
  10914. break;
  10915. case IntrinsicOp::MOP_CandidateWorldToObject3x4:
  10916. spvCode = spv::Op::OpRayQueryGetIntersectionWorldToObjectKHR;
  10917. traceArgs.push_back(candidateIntersection);
  10918. transposeMatrix = true;
  10919. break;
  10920. case IntrinsicOp::MOP_CommitNonOpaqueTriangleHit:
  10921. spvCode = spv::Op::OpRayQueryConfirmIntersectionKHR;
  10922. exprType = QualType();
  10923. break;
  10924. case IntrinsicOp::MOP_CommitProceduralPrimitiveHit:
  10925. spvCode = spv::Op::OpRayQueryGenerateIntersectionKHR;
  10926. exprType = QualType();
  10927. break;
  10928. case IntrinsicOp::MOP_CommittedGeometryIndex:
  10929. spvCode = spv::Op::OpRayQueryGetIntersectionGeometryIndexKHR;
  10930. traceArgs.push_back(committedIntersection);
  10931. break;
  10932. case IntrinsicOp::MOP_CommittedInstanceContributionToHitGroupIndex:
  10933. spvCode = spv::Op::
  10934. OpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffsetKHR;
  10935. traceArgs.push_back(committedIntersection);
  10936. break;
  10937. case IntrinsicOp::MOP_CommittedInstanceID:
  10938. spvCode = spv::Op::OpRayQueryGetIntersectionInstanceCustomIndexKHR;
  10939. traceArgs.push_back(committedIntersection);
  10940. break;
  10941. case IntrinsicOp::MOP_CommittedInstanceIndex:
  10942. spvCode = spv::Op::OpRayQueryGetIntersectionInstanceIdKHR;
  10943. traceArgs.push_back(committedIntersection);
  10944. break;
  10945. case IntrinsicOp::MOP_CommittedObjectRayDirection:
  10946. spvCode = spv::Op::OpRayQueryGetIntersectionObjectRayDirectionKHR;
  10947. traceArgs.push_back(committedIntersection);
  10948. break;
  10949. case IntrinsicOp::MOP_CommittedObjectRayOrigin:
  10950. spvCode = spv::Op::OpRayQueryGetIntersectionObjectRayOriginKHR;
  10951. traceArgs.push_back(committedIntersection);
  10952. break;
  10953. case IntrinsicOp::MOP_CommittedObjectToWorld3x4:
  10954. spvCode = spv::Op::OpRayQueryGetIntersectionObjectToWorldKHR;
  10955. traceArgs.push_back(committedIntersection);
  10956. transposeMatrix = true;
  10957. break;
  10958. case IntrinsicOp::MOP_CommittedObjectToWorld4x3:
  10959. spvCode = spv::Op::OpRayQueryGetIntersectionObjectToWorldKHR;
  10960. traceArgs.push_back(committedIntersection);
  10961. break;
  10962. case IntrinsicOp::MOP_CommittedPrimitiveIndex:
  10963. spvCode = spv::Op::OpRayQueryGetIntersectionPrimitiveIndexKHR;
  10964. traceArgs.push_back(committedIntersection);
  10965. break;
  10966. case IntrinsicOp::MOP_CommittedRayT:
  10967. spvCode = spv::Op::OpRayQueryGetIntersectionTKHR;
  10968. traceArgs.push_back(committedIntersection);
  10969. break;
  10970. case IntrinsicOp::MOP_CommittedStatus:
  10971. spvCode = spv::Op::OpRayQueryGetIntersectionTypeKHR;
  10972. traceArgs.push_back(committedIntersection);
  10973. break;
  10974. case IntrinsicOp::MOP_CommittedTriangleBarycentrics:
  10975. spvCode = spv::Op::OpRayQueryGetIntersectionBarycentricsKHR;
  10976. traceArgs.push_back(committedIntersection);
  10977. break;
  10978. case IntrinsicOp::MOP_CommittedTriangleFrontFace:
  10979. spvCode = spv::Op::OpRayQueryGetIntersectionFrontFaceKHR;
  10980. traceArgs.push_back(committedIntersection);
  10981. break;
  10982. case IntrinsicOp::MOP_CommittedWorldToObject3x4:
  10983. spvCode = spv::Op::OpRayQueryGetIntersectionWorldToObjectKHR;
  10984. traceArgs.push_back(committedIntersection);
  10985. transposeMatrix = true;
  10986. break;
  10987. case IntrinsicOp::MOP_CommittedWorldToObject4x3:
  10988. spvCode = spv::Op::OpRayQueryGetIntersectionWorldToObjectKHR;
  10989. traceArgs.push_back(committedIntersection);
  10990. break;
  10991. case IntrinsicOp::MOP_RayFlags:
  10992. spvCode = spv::Op::OpRayQueryGetRayFlagsKHR;
  10993. break;
  10994. case IntrinsicOp::MOP_RayTMin:
  10995. spvCode = spv::Op::OpRayQueryGetRayTMinKHR;
  10996. break;
  10997. case IntrinsicOp::MOP_WorldRayDirection:
  10998. spvCode = spv::Op::OpRayQueryGetWorldRayDirectionKHR;
  10999. break;
  11000. case IntrinsicOp::MOP_WorldRayOrigin:
  11001. spvCode = spv::Op::OpRayQueryGetWorldRayOriginKHR;
  11002. break;
  11003. default:
  11004. emitError("intrinsic '%0' method unimplemented",
  11005. expr->getCallee()->getExprLoc())
  11006. << expr->getDirectCallee()->getName();
  11007. return nullptr;
  11008. }
  11009. if (transposeMatrix) {
  11010. assert(hlsl::IsHLSLMatType(exprType) && "intrinsic should be matrix");
  11011. const clang::Type *type = exprType.getCanonicalType().getTypePtr();
  11012. const RecordType *RT = cast<RecordType>(type);
  11013. const ClassTemplateSpecializationDecl *templateSpecDecl =
  11014. cast<ClassTemplateSpecializationDecl>(RT->getDecl());
  11015. ClassTemplateDecl *templateDecl =
  11016. templateSpecDecl->getSpecializedTemplate();
  11017. exprType = getHLSLMatrixType(astContext, theCompilerInstance.getSema(),
  11018. templateDecl, astContext.FloatTy, 4, 3);
  11019. }
  11020. const auto loc = expr->getExprLoc();
  11021. SpirvInstruction *retVal =
  11022. spvBuilder.createRayQueryOpsKHR(spvCode, exprType, traceArgs, false, loc);
  11023. if (transposeMatrix) {
  11024. retVal = spvBuilder.createUnaryOp(spv::Op::OpTranspose, expr->getType(),
  11025. retVal, loc);
  11026. }
  11027. if (logicalNot) {
  11028. retVal = spvBuilder.createUnaryOp(spv::Op::OpLogicalNot, expr->getType(),
  11029. retVal, loc);
  11030. }
  11031. retVal->setRValue();
  11032. return retVal;
  11033. }
  11034. bool SpirvEmitter::spirvToolsValidate(std::vector<uint32_t> *mod,
  11035. std::string *messages) {
  11036. spvtools::SpirvTools tools(featureManager.getTargetEnv());
  11037. tools.SetMessageConsumer(
  11038. [messages](spv_message_level_t /*level*/, const char * /*source*/,
  11039. const spv_position_t & /*position*/,
  11040. const char *message) { *messages += message; });
  11041. spvtools::ValidatorOptions options;
  11042. options.SetBeforeHlslLegalization(needsLegalization ||
  11043. declIdMapper.requiresLegalization());
  11044. // GL: strict block layout rules
  11045. // VK: relaxed block layout rules
  11046. // DX: Skip block layout rules
  11047. if (spirvOptions.useScalarLayout || spirvOptions.useDxLayout) {
  11048. options.SetScalarBlockLayout(true);
  11049. } else if (spirvOptions.useGlLayout) {
  11050. // spirv-val by default checks this.
  11051. } else {
  11052. options.SetRelaxBlockLayout(true);
  11053. }
  11054. return tools.Validate(mod->data(), mod->size(), options);
  11055. }
  11056. bool SpirvEmitter::spirvToolsOptimize(std::vector<uint32_t> *mod,
  11057. std::string *messages) {
  11058. spvtools::Optimizer optimizer(featureManager.getTargetEnv());
  11059. optimizer.SetMessageConsumer(
  11060. [messages](spv_message_level_t /*level*/, const char * /*source*/,
  11061. const spv_position_t & /*position*/,
  11062. const char *message) { *messages += message; });
  11063. spvtools::OptimizerOptions options;
  11064. options.set_run_validator(false);
  11065. if (spirvOptions.optConfig.empty()) {
  11066. // Add performance passes.
  11067. optimizer.RegisterPerformancePasses();
  11068. // Add compact ID pass.
  11069. optimizer.RegisterPass(spvtools::CreateCompactIdsPass());
  11070. } else {
  11071. // Command line options use llvm::SmallVector and llvm::StringRef, whereas
  11072. // SPIR-V optimizer uses std::vector and std::string.
  11073. std::vector<std::string> stdFlags;
  11074. for (const auto &f : spirvOptions.optConfig)
  11075. stdFlags.push_back(f.str());
  11076. if (!optimizer.RegisterPassesFromFlags(stdFlags))
  11077. return false;
  11078. }
  11079. return optimizer.Run(mod->data(), mod->size(), mod, options);
  11080. }
  11081. bool SpirvEmitter::spirvToolsLegalize(std::vector<uint32_t> *mod,
  11082. std::string *messages) {
  11083. spvtools::Optimizer optimizer(featureManager.getTargetEnv());
  11084. optimizer.SetMessageConsumer(
  11085. [messages](spv_message_level_t /*level*/, const char * /*source*/,
  11086. const spv_position_t & /*position*/,
  11087. const char *message) { *messages += message; });
  11088. spvtools::OptimizerOptions options;
  11089. options.set_run_validator(false);
  11090. optimizer.RegisterLegalizationPasses();
  11091. // Add flattening of resources if needed.
  11092. if (spirvOptions.flattenResourceArrays ||
  11093. declIdMapper.requiresFlatteningCompositeResources()) {
  11094. optimizer.RegisterPass(spvtools::CreateDescriptorScalarReplacementPass());
  11095. // ADCE should be run after desc_sroa in order to remove potentially
  11096. // illegal types such as structures containing opaque types.
  11097. optimizer.RegisterPass(spvtools::CreateAggressiveDCEPass());
  11098. }
  11099. optimizer.RegisterPass(spvtools::CreateReplaceInvalidOpcodePass());
  11100. optimizer.RegisterPass(spvtools::CreateCompactIdsPass());
  11101. return optimizer.Run(mod->data(), mod->size(), mod, options);
  11102. }
  11103. SpirvInstruction *
  11104. SpirvEmitter::doUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *expr) {
  11105. // TODO: We support only `sizeof()`. Support other kinds.
  11106. if (expr->getKind() != clang::UnaryExprOrTypeTrait::UETT_SizeOf) {
  11107. emitError("expression class '%0' unimplemented", expr->getExprLoc())
  11108. << expr->getStmtClassName();
  11109. return nullptr;
  11110. }
  11111. if (auto *constExpr = tryToEvaluateAsConst(expr)) {
  11112. constExpr->setRValue();
  11113. return constExpr;
  11114. }
  11115. AlignmentSizeCalculator alignmentCalc(astContext, spirvOptions);
  11116. uint32_t size = 0, stride = 0;
  11117. std::tie(std::ignore, size) = alignmentCalc.getAlignmentAndSize(
  11118. expr->getArgumentType(), SpirvLayoutRule::Scalar,
  11119. /*isRowMajor*/ llvm::None, &stride);
  11120. auto *sizeConst = spvBuilder.getConstantInt(astContext.UnsignedIntTy,
  11121. llvm::APInt(32, size));
  11122. sizeConst->setRValue();
  11123. return sizeConst;
  11124. }
  11125. } // end namespace spirv
  11126. } // end namespace clang