ExecutionTest.cpp 390 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547
  1. ///////////////////////////////////////////////////////////////////////////////
  2. // //
  3. // ExecutionTest.cpp //
  4. // Copyright (C) Microsoft Corporation. All rights reserved. //
  5. // This file is distributed under the University of Illinois Open Source //
  6. // License. See LICENSE.TXT for details. //
  7. // //
  8. // These tests run by executing compiled programs, and thus involve more //
  9. // moving parts, like the runtime and drivers. //
  10. // //
  11. ///////////////////////////////////////////////////////////////////////////////
  12. // We need to keep & fix these warnings to integrate smoothly with HLK
  13. #pragma warning(error: 4100 4146 4242 4244 4267 4701 4389)
  14. #include <algorithm>
  15. #include <memory>
  16. #include <array>
  17. #include <vector>
  18. #include <string>
  19. #include <map>
  20. #include <unordered_set>
  21. #include <strstream>
  22. #include <iomanip>
  23. #include "dxc/Test/CompilationResult.h"
  24. #include "dxc/Test/HLSLTestData.h"
  25. #include <Shlwapi.h>
  26. #include <atlcoll.h>
  27. #include <locale>
  28. #include <algorithm>
  29. #undef _read
  30. #include "WexTestClass.h"
  31. #include "dxc/Test/HlslTestUtils.h"
  32. #include "dxc/Test/DxcTestUtils.h"
  33. #include "dxc/Support/Global.h"
  34. #include "dxc/Support/WinIncludes.h"
  35. #include "dxc/Support/FileIOHelper.h"
  36. #include "dxc/Support/Unicode.h"
  37. //
  38. // d3d12.h and dxgi1_4.h are included in the Windows 10 SDK
  39. // https://msdn.microsoft.com/en-us/library/windows/desktop/dn899120(v=vs.85).aspx
  40. // https://developer.microsoft.com/en-US/windows/downloads/windows-10-sdk
  41. //
  42. #include <d3d12.h>
  43. #include <dxgi1_4.h>
  44. #include <DXGIDebug.h>
  45. #include "dxc/Support/d3dx12.h"
  46. #include <DirectXMath.h>
  47. #include <strsafe.h>
  48. #include <d3dcompiler.h>
  49. #include <wincodec.h>
  50. #include "ShaderOpTest.h"
  51. #pragma comment(lib, "d3dcompiler.lib")
  52. #pragma comment(lib, "windowscodecs.lib")
  53. #pragma comment(lib, "dxguid.lib")
  54. #pragma comment(lib, "version.lib")
  55. // A more recent Windows SDK than currently required is needed for these.
  56. typedef HRESULT(WINAPI *D3D12EnableExperimentalFeaturesFn)(
  57. UINT NumFeatures,
  58. __in_ecount(NumFeatures) const IID* pIIDs,
  59. __in_ecount_opt(NumFeatures) void* pConfigurationStructs,
  60. __in_ecount_opt(NumFeatures) UINT* pConfigurationStructSizes);
  61. static const GUID D3D12ExperimentalShaderModelsID = { /* 76f5573e-f13a-40f5-b297-81ce9e18933f */
  62. 0x76f5573e,
  63. 0xf13a,
  64. 0x40f5,
  65. { 0xb2, 0x97, 0x81, 0xce, 0x9e, 0x18, 0x93, 0x3f }
  66. };
  67. using namespace DirectX;
  68. using namespace hlsl_test;
  69. template <typename TSequence, typename T>
  70. static bool contains(TSequence s, const T &val) {
  71. return std::cend(s) != std::find(std::cbegin(s), std::cend(s), val);
  72. }
  73. template <typename InputIterator, typename T>
  74. static bool contains(InputIterator b, InputIterator e, const T &val) {
  75. return e != std::find(b, e, val);
  76. }
  77. static HRESULT EnableExperimentalShaderModels() {
  78. HMODULE hRuntime = LoadLibraryW(L"d3d12.dll");
  79. if (hRuntime == NULL) {
  80. return HRESULT_FROM_WIN32(GetLastError());
  81. }
  82. D3D12EnableExperimentalFeaturesFn pD3D12EnableExperimentalFeatures =
  83. (D3D12EnableExperimentalFeaturesFn)GetProcAddress(hRuntime, "D3D12EnableExperimentalFeatures");
  84. if (pD3D12EnableExperimentalFeatures == nullptr) {
  85. FreeLibrary(hRuntime);
  86. return HRESULT_FROM_WIN32(GetLastError());
  87. }
  88. HRESULT hr = pD3D12EnableExperimentalFeatures(1, &D3D12ExperimentalShaderModelsID, nullptr, nullptr);
  89. FreeLibrary(hRuntime);
  90. return hr;
  91. }
  92. static HRESULT ReportLiveObjects() {
  93. CComPtr<IDXGIDebug1> pDebug;
  94. IFR(DXGIGetDebugInterface1(0, IID_PPV_ARGS(&pDebug)));
  95. IFR(pDebug->ReportLiveObjects(DXGI_DEBUG_ALL, DXGI_DEBUG_RLO_ALL));
  96. return S_OK;
  97. }
  98. static void WriteInfoQueueMessages(void *pStrCtx, st::OutputStringFn pOutputStrFn, ID3D12InfoQueue *pInfoQueue) {
  99. bool allMessagesOK = true;
  100. UINT64 count = pInfoQueue->GetNumStoredMessages();
  101. CAtlArray<BYTE> message;
  102. for (UINT64 i = 0; i < count; ++i) {
  103. // 'GetMessageA' rather than 'GetMessage' is an artifact of user32 headers.
  104. SIZE_T msgLen = 0;
  105. if (FAILED(pInfoQueue->GetMessageA(i, nullptr, &msgLen))) {
  106. allMessagesOK = false;
  107. continue;
  108. }
  109. if (message.GetCount() < msgLen) {
  110. if (!message.SetCount(msgLen)) {
  111. allMessagesOK = false;
  112. continue;
  113. }
  114. }
  115. D3D12_MESSAGE *pMessage = (D3D12_MESSAGE *)message.GetData();
  116. if (FAILED(pInfoQueue->GetMessageA(i, pMessage, &msgLen))) {
  117. allMessagesOK = false;
  118. continue;
  119. }
  120. CA2W msgW(pMessage->pDescription, CP_ACP);
  121. pOutputStrFn(pStrCtx, msgW.m_psz);
  122. pOutputStrFn(pStrCtx, L"\r\n");
  123. }
  124. if (!allMessagesOK) {
  125. pOutputStrFn(pStrCtx, L"Failed to retrieve some messages.\r\n");
  126. }
  127. }
  128. class CComContext {
  129. private:
  130. bool m_init;
  131. public:
  132. CComContext() : m_init(false) {}
  133. ~CComContext() { Dispose(); }
  134. void Dispose() { if (!m_init) return; m_init = false; CoUninitialize(); }
  135. HRESULT Init() { HRESULT hr = CoInitializeEx(0, COINIT_MULTITHREADED); if (SUCCEEDED(hr)) { m_init = true; } return hr; }
  136. };
  137. static void SavePixelsToFile(LPCVOID pPixels, DXGI_FORMAT format, UINT32 m_width, UINT32 m_height, LPCWSTR pFileName) {
  138. CComContext ctx;
  139. CComPtr<IWICImagingFactory> pFactory;
  140. CComPtr<IWICBitmap> pBitmap;
  141. CComPtr<IWICBitmapEncoder> pEncoder;
  142. CComPtr<IWICBitmapFrameEncode> pFrameEncode;
  143. CComPtr<hlsl::AbstractMemoryStream> pStream;
  144. CComPtr<IMalloc> pMalloc;
  145. struct PF {
  146. DXGI_FORMAT Format;
  147. GUID PixelFormat;
  148. UINT32 PixelSize;
  149. bool operator==(DXGI_FORMAT F) const {
  150. return F == Format;
  151. }
  152. } Vals[] = {
  153. // Add more pixel format mappings as needed.
  154. { DXGI_FORMAT_R8G8B8A8_UNORM, GUID_WICPixelFormat32bppRGBA, 4 }
  155. };
  156. PF *pFormat = std::find(Vals, Vals + _countof(Vals), format);
  157. VERIFY_SUCCEEDED(ctx.Init());
  158. VERIFY_SUCCEEDED(CoCreateInstance(CLSID_WICImagingFactory, NULL, CLSCTX_INPROC_SERVER, IID_IWICImagingFactory, (LPVOID*)&pFactory));
  159. VERIFY_SUCCEEDED(CoGetMalloc(1, &pMalloc));
  160. VERIFY_SUCCEEDED(hlsl::CreateMemoryStream(pMalloc, &pStream));
  161. VERIFY_ARE_NOT_EQUAL(pFormat, Vals + _countof(Vals));
  162. VERIFY_SUCCEEDED(pFactory->CreateBitmapFromMemory(m_width, m_height, pFormat->PixelFormat, m_width * pFormat->PixelSize, m_width * m_height * pFormat->PixelSize, (BYTE *)pPixels, &pBitmap));
  163. VERIFY_SUCCEEDED(pFactory->CreateEncoder(GUID_ContainerFormatBmp, nullptr, &pEncoder));
  164. VERIFY_SUCCEEDED(pEncoder->Initialize(pStream, WICBitmapEncoderNoCache));
  165. VERIFY_SUCCEEDED(pEncoder->CreateNewFrame(&pFrameEncode, nullptr));
  166. VERIFY_SUCCEEDED(pFrameEncode->Initialize(nullptr));
  167. VERIFY_SUCCEEDED(pFrameEncode->WriteSource(pBitmap, nullptr));
  168. VERIFY_SUCCEEDED(pFrameEncode->Commit());
  169. VERIFY_SUCCEEDED(pEncoder->Commit());
  170. hlsl::WriteBinaryFile(pFileName, pStream->GetPtr(), pStream->GetPtrSize());
  171. }
  172. // Checks if the given warp version supports the given operation.
  173. bool IsValidWarpDllVersion(unsigned int minBuildNumber) {
  174. HMODULE pLibrary = LoadLibrary("D3D10Warp.dll");
  175. if (pLibrary) {
  176. char path[MAX_PATH];
  177. DWORD length = GetModuleFileName(pLibrary, path, MAX_PATH);
  178. if (length) {
  179. DWORD dwVerHnd = 0;
  180. DWORD dwVersionInfoSize = GetFileVersionInfoSize(path, &dwVerHnd);
  181. std::unique_ptr<int[]> VffInfo(new int[dwVersionInfoSize]);
  182. if (GetFileVersionInfo(path, NULL, dwVersionInfoSize, VffInfo.get())) {
  183. LPVOID versionInfo;
  184. UINT size;
  185. if (VerQueryValue(VffInfo.get(), "\\", &versionInfo, &size)) {
  186. if (size) {
  187. VS_FIXEDFILEINFO *verInfo = (VS_FIXEDFILEINFO *)versionInfo;
  188. unsigned int warpBuildNumber = verInfo->dwFileVersionLS >> 16 & 0xffff;
  189. if (verInfo->dwSignature == 0xFEEF04BD && warpBuildNumber >= minBuildNumber) {
  190. return true;
  191. }
  192. }
  193. }
  194. }
  195. }
  196. FreeLibrary(pLibrary);
  197. }
  198. return false;
  199. }
  200. #if WDK_NTDDI_VERSION <= NTDDI_WIN10_RS2
  201. #define D3D12_FEATURE_D3D12_OPTIONS3 ((D3D12_FEATURE)21)
  202. #define NTDDI_WIN10_RS3 0x0A000004 /* ABRACADABRA_WIN10_RS2 */
  203. typedef
  204. enum D3D12_COMMAND_LIST_SUPPORT_FLAGS
  205. {
  206. D3D12_COMMAND_LIST_SUPPORT_FLAG_NONE = 0,
  207. D3D12_COMMAND_LIST_SUPPORT_FLAG_DIRECT = (1 << D3D12_COMMAND_LIST_TYPE_DIRECT),
  208. D3D12_COMMAND_LIST_SUPPORT_FLAG_BUNDLE = (1 << D3D12_COMMAND_LIST_TYPE_BUNDLE),
  209. D3D12_COMMAND_LIST_SUPPORT_FLAG_COMPUTE = (1 << D3D12_COMMAND_LIST_TYPE_COMPUTE),
  210. D3D12_COMMAND_LIST_SUPPORT_FLAG_COPY = (1 << D3D12_COMMAND_LIST_TYPE_COPY),
  211. D3D12_COMMAND_LIST_SUPPORT_FLAG_VIDEO_DECODE = (1 << 4),
  212. D3D12_COMMAND_LIST_SUPPORT_FLAG_VIDEO_PROCESS = (1 << 5)
  213. } D3D12_COMMAND_LIST_SUPPORT_FLAGS;
  214. typedef
  215. enum D3D12_VIEW_INSTANCING_TIER
  216. {
  217. D3D12_VIEW_INSTANCING_TIER_NOT_SUPPORTED = 0,
  218. D3D12_VIEW_INSTANCING_TIER_1 = 1,
  219. D3D12_VIEW_INSTANCING_TIER_2 = 2,
  220. D3D12_VIEW_INSTANCING_TIER_3 = 3
  221. } D3D12_VIEW_INSTANCING_TIER;
  222. typedef struct D3D12_FEATURE_DATA_D3D12_OPTIONS3
  223. {
  224. _Out_ BOOL CopyQueueTimestampQueriesSupported;
  225. _Out_ BOOL CastingFullyTypedFormatSupported;
  226. _Out_ DWORD WriteBufferImmediateSupportFlags;
  227. _Out_ D3D12_VIEW_INSTANCING_TIER ViewInstancingTier;
  228. _Out_ BOOL BarycentricsSupported;
  229. } D3D12_FEATURE_DATA_D3D12_OPTIONS3;
  230. #endif
  231. #if WDK_NTDDI_VERSION <= NTDDI_WIN10_RS3
  232. #define D3D12_FEATURE_D3D12_OPTIONS4 ((D3D12_FEATURE)23)
  233. typedef enum D3D12_SHARED_RESOURCE_COMPATIBILITY_TIER
  234. {
  235. D3D12_SHARED_RESOURCE_COMPATIBILITY_TIER_0,
  236. D3D12_SHARED_RESOURCE_COMPATIBILITY_TIER_1,
  237. } D3D12_SHARED_RESOURCE_COMPATIBILITY_TIER;
  238. typedef struct D3D12_FEATURE_DATA_D3D12_OPTIONS4
  239. {
  240. _Out_ BOOL ReservedBufferPlacementSupported;
  241. _Out_ D3D12_SHARED_RESOURCE_COMPATIBILITY_TIER SharedResourceCompatibilityTier;
  242. _Out_ BOOL Native16BitShaderOpsSupported;
  243. } D3D12_FEATURE_DATA_D3D12_OPTIONS4;
  244. #endif
  245. // Virtual class to compute the expected result given a set of inputs
  246. struct TableParameter;
  247. class ExecutionTest {
  248. public:
  249. // By default, ignore these tests, which require a recent build to run properly.
  250. BEGIN_TEST_CLASS(ExecutionTest)
  251. TEST_CLASS_PROPERTY(L"Parallel", L"true")
  252. TEST_CLASS_PROPERTY(L"Ignore", L"true")
  253. TEST_METHOD_PROPERTY(L"Priority", L"0")
  254. END_TEST_CLASS()
  255. TEST_CLASS_SETUP(ExecutionTestClassSetup)
  256. TEST_METHOD(BasicComputeTest);
  257. TEST_METHOD(BasicTriangleTest);
  258. TEST_METHOD(BasicTriangleOpTest);
  259. BEGIN_TEST_METHOD(BasicTriangleOpTestHalf)
  260. TEST_METHOD_PROPERTY(L"Priority", L"2") // Remove this line once warp supports this feature in Shader Model 6.2
  261. END_TEST_METHOD()
  262. TEST_METHOD(OutOfBoundsTest);
  263. TEST_METHOD(SaturateTest);
  264. TEST_METHOD(SignTest);
  265. TEST_METHOD(Int64Test);
  266. TEST_METHOD(LifetimeIntrinsicTest)
  267. TEST_METHOD(WaveIntrinsicsTest);
  268. TEST_METHOD(WaveIntrinsicsDDITest);
  269. TEST_METHOD(WaveIntrinsicsInPSTest);
  270. TEST_METHOD(WaveSizeTest);
  271. TEST_METHOD(PartialDerivTest);
  272. TEST_METHOD(DerivativesTest);
  273. TEST_METHOD(ComputeSampleTest);
  274. TEST_METHOD(AtomicsTest);
  275. TEST_METHOD(Atomics64Test);
  276. TEST_METHOD(AtomicsTyped64Test);
  277. TEST_METHOD(AtomicsShared64Test);
  278. TEST_METHOD(AtomicsFloatTest);
  279. TEST_METHOD(HelperLaneTest);
  280. BEGIN_TEST_METHOD(HelperLaneTestWave)
  281. TEST_METHOD_PROPERTY(L"Priority", L"2") // Remove this line once warp handles this
  282. END_TEST_METHOD()
  283. TEST_METHOD(SignatureResourcesTest)
  284. TEST_METHOD(DynamicResourcesTest)
  285. TEST_METHOD(QuadReadTest)
  286. BEGIN_TEST_METHOD(CBufferTestHalf)
  287. TEST_METHOD_PROPERTY(L"Priority", L"2") // Remove this line once warp supports this feature in Shader Model 6.2
  288. END_TEST_METHOD()
  289. TEST_METHOD(BasicShaderModel61);
  290. BEGIN_TEST_METHOD(BasicShaderModel63)
  291. TEST_METHOD_PROPERTY(L"Priority", L"2") // Remove this line once warp supports this feature in Shader Model 6.3
  292. END_TEST_METHOD()
  293. BEGIN_TEST_METHOD(WaveIntrinsicsActiveIntTest)
  294. TEST_METHOD_PROPERTY(L"DataSource", L"Table:ShaderOpArithTable.xml#WaveIntrinsicsActiveIntTable")
  295. END_TEST_METHOD()
  296. BEGIN_TEST_METHOD(WaveIntrinsicsActiveUintTest)
  297. TEST_METHOD_PROPERTY(L"DataSource", L"Table:ShaderOpArithTable.xml#WaveIntrinsicsActiveUintTable")
  298. END_TEST_METHOD()
  299. BEGIN_TEST_METHOD(WaveIntrinsicsPrefixIntTest)
  300. TEST_METHOD_PROPERTY(L"DataSource", L"Table:ShaderOpArithTable.xml#WaveIntrinsicsPrefixIntTable")
  301. END_TEST_METHOD()
  302. BEGIN_TEST_METHOD(WaveIntrinsicsPrefixUintTest)
  303. TEST_METHOD_PROPERTY(L"DataSource", L"Table:ShaderOpArithTable.xml#WaveIntrinsicsPrefixUintTable")
  304. END_TEST_METHOD()
  305. BEGIN_TEST_METHOD(WaveIntrinsicsSM65IntTest)
  306. TEST_METHOD_PROPERTY(L"DataSource", L"Table:ShaderOpArithTable.xml#WaveIntrinsicsMultiPrefixIntTable")
  307. END_TEST_METHOD()
  308. BEGIN_TEST_METHOD(WaveIntrinsicsSM65UintTest)
  309. TEST_METHOD_PROPERTY(L"DataSource", L"Table:ShaderOpArithTable.xml#WaveIntrinsicsMultiPrefixUintTable")
  310. END_TEST_METHOD()
  311. // TAEF data-driven tests.
  312. BEGIN_TEST_METHOD(UnaryFloatOpTest)
  313. TEST_METHOD_PROPERTY(L"DataSource", L"Table:ShaderOpArithTable.xml#UnaryFloatOpTable")
  314. END_TEST_METHOD()
  315. BEGIN_TEST_METHOD(BinaryFloatOpTest)
  316. TEST_METHOD_PROPERTY(L"DataSource", L"Table:ShaderOpArithTable.xml#BinaryFloatOpTable")
  317. END_TEST_METHOD()
  318. BEGIN_TEST_METHOD(TertiaryFloatOpTest)
  319. TEST_METHOD_PROPERTY(L"DataSource", L"Table:ShaderOpArithTable.xml#TertiaryFloatOpTable")
  320. END_TEST_METHOD()
  321. BEGIN_TEST_METHOD(UnaryHalfOpTest)
  322. TEST_METHOD_PROPERTY(L"DataSource", L"Table:ShaderOpArithTable.xml#UnaryHalfOpTable")
  323. TEST_METHOD_PROPERTY(L"Priority", L"2") // Remove this line once warp supports this feature in Shader Model 6.2
  324. END_TEST_METHOD()
  325. BEGIN_TEST_METHOD(BinaryHalfOpTest)
  326. TEST_METHOD_PROPERTY(L"DataSource", L"Table:ShaderOpArithTable.xml#BinaryHalfOpTable")
  327. TEST_METHOD_PROPERTY(L"Priority", L"2") // Remove this line once warp supports this feature in Shader Model 6.2
  328. END_TEST_METHOD()
  329. BEGIN_TEST_METHOD(TertiaryHalfOpTest)
  330. TEST_METHOD_PROPERTY(L"DataSource", L"Table:ShaderOpArithTable.xml#TertiaryHalfOpTable")
  331. TEST_METHOD_PROPERTY(L"Priority", L"2") // Remove this line once warp supports this feature in Shader Model 6.2
  332. END_TEST_METHOD()
  333. BEGIN_TEST_METHOD(UnaryIntOpTest)
  334. TEST_METHOD_PROPERTY(L"DataSource", L"Table:ShaderOpArithTable.xml#UnaryIntOpTable")
  335. END_TEST_METHOD()
  336. BEGIN_TEST_METHOD(BinaryIntOpTest)
  337. TEST_METHOD_PROPERTY(L"DataSource", L"Table:ShaderOpArithTable.xml#BinaryIntOpTable")
  338. END_TEST_METHOD()
  339. BEGIN_TEST_METHOD(TertiaryIntOpTest)
  340. TEST_METHOD_PROPERTY(L"DataSource", L"Table:ShaderOpArithTable.xml#TertiaryIntOpTable")
  341. END_TEST_METHOD()
  342. BEGIN_TEST_METHOD(UnaryUintOpTest)
  343. TEST_METHOD_PROPERTY(L"DataSource", L"Table:ShaderOpArithTable.xml#UnaryUintOpTable")
  344. END_TEST_METHOD()
  345. BEGIN_TEST_METHOD(BinaryUintOpTest)
  346. TEST_METHOD_PROPERTY(L"DataSource", L"Table:ShaderOpArithTable.xml#BinaryUintOpTable")
  347. END_TEST_METHOD()
  348. BEGIN_TEST_METHOD(TertiaryUintOpTest)
  349. TEST_METHOD_PROPERTY(L"DataSource", L"Table:ShaderOpArithTable.xml#TertiaryUintOpTable")
  350. END_TEST_METHOD()
  351. BEGIN_TEST_METHOD(UnaryInt16OpTest)
  352. TEST_METHOD_PROPERTY(L"DataSource", L"Table:ShaderOpArithTable.xml#UnaryInt16OpTable")
  353. TEST_METHOD_PROPERTY(L"Priority", L"2") // Remove this line once warp supports this feature in Shader Model 6.2
  354. END_TEST_METHOD()
  355. BEGIN_TEST_METHOD(BinaryInt16OpTest)
  356. TEST_METHOD_PROPERTY(L"DataSource", L"Table:ShaderOpArithTable.xml#BinaryInt16OpTable")
  357. TEST_METHOD_PROPERTY(L"Priority", L"2") // Remove this line once warp supports this feature in Shader Model 6.2
  358. END_TEST_METHOD()
  359. BEGIN_TEST_METHOD(TertiaryInt16OpTest)
  360. TEST_METHOD_PROPERTY(L"DataSource", L"Table:ShaderOpArithTable.xml#TertiaryInt16OpTable")
  361. TEST_METHOD_PROPERTY(L"Priority", L"2") // Remove this line once warp supports this feature in Shader Model 6.2
  362. END_TEST_METHOD()
  363. BEGIN_TEST_METHOD(UnaryUint16OpTest)
  364. TEST_METHOD_PROPERTY(L"DataSource", L"Table:ShaderOpArithTable.xml#UnaryUint16OpTable")
  365. TEST_METHOD_PROPERTY(L"Priority", L"2") // Remove this line once warp supports this feature in Shader Model 6.2
  366. END_TEST_METHOD()
  367. BEGIN_TEST_METHOD(BinaryUint16OpTest)
  368. TEST_METHOD_PROPERTY(L"DataSource", L"Table:ShaderOpArithTable.xml#BinaryUint16OpTable")
  369. TEST_METHOD_PROPERTY(L"Priority", L"2") // Remove this line once warp supports this feature in Shader Model 6.2
  370. END_TEST_METHOD()
  371. BEGIN_TEST_METHOD(TertiaryUint16OpTest)
  372. TEST_METHOD_PROPERTY(L"DataSource", L"Table:ShaderOpArithTable.xml#TertiaryUint16OpTable")
  373. TEST_METHOD_PROPERTY(L"Priority", L"2") // Remove this line once warp supports this feature in Shader Model 6.2
  374. END_TEST_METHOD()
  375. BEGIN_TEST_METHOD(DotTest)
  376. TEST_METHOD_PROPERTY(L"DataSource", L"Table:ShaderOpArithTable.xml#DotOpTable")
  377. END_TEST_METHOD()
  378. BEGIN_TEST_METHOD(Dot2AddHalfTest)
  379. TEST_METHOD_PROPERTY(L"DataSource", L"Table:ShaderOpArithTable.xml#Dot2AddHalfOpTable")
  380. END_TEST_METHOD()
  381. BEGIN_TEST_METHOD(Dot4AddI8PackedTest)
  382. TEST_METHOD_PROPERTY(L"DataSource", L"Table:ShaderOpArithTable.xml#Dot4AddI8PackedOpTable")
  383. END_TEST_METHOD()
  384. BEGIN_TEST_METHOD(Dot4AddU8PackedTest)
  385. TEST_METHOD_PROPERTY(L"DataSource", L"Table:ShaderOpArithTable.xml#Dot4AddU8PackedOpTable")
  386. END_TEST_METHOD()
  387. BEGIN_TEST_METHOD(Msad4Test)
  388. TEST_METHOD_PROPERTY(L"DataSource", L"Table:ShaderOpArithTable.xml#Msad4Table")
  389. END_TEST_METHOD()
  390. BEGIN_TEST_METHOD(DenormBinaryFloatOpTest)
  391. TEST_METHOD_PROPERTY(L"DataSource", L"Table:ShaderOpArithTable.xml#DenormBinaryFloatOpTable")
  392. TEST_METHOD_PROPERTY(L"Priority", L"2") // Remove this line once warp supports this feature in Shader Model 6.2
  393. END_TEST_METHOD()
  394. BEGIN_TEST_METHOD(DenormTertiaryFloatOpTest)
  395. TEST_METHOD_PROPERTY(L"DataSource", L"Table:ShaderOpArithTable.xml#DenormTertiaryFloatOpTable")
  396. TEST_METHOD_PROPERTY(L"Priority", L"2") // Remove this line once warp supports this feature in Shader Model 6.2
  397. END_TEST_METHOD()
  398. TEST_METHOD(BarycentricsTest);
  399. TEST_METHOD(ComputeRawBufferLdStI32);
  400. TEST_METHOD(ComputeRawBufferLdStFloat);
  401. BEGIN_TEST_METHOD(ComputeRawBufferLdStI64)
  402. TEST_METHOD_PROPERTY(L"Priority", L"2") // Remove this line once warp supports this feature in Shader Model 6.3
  403. END_TEST_METHOD()
  404. BEGIN_TEST_METHOD(ComputeRawBufferLdStDouble)
  405. TEST_METHOD_PROPERTY(L"Priority", L"2") // Remove this line once warp supports this feature in Shader Model 6.3
  406. END_TEST_METHOD()
  407. BEGIN_TEST_METHOD(ComputeRawBufferLdStI16)
  408. TEST_METHOD_PROPERTY(L"Priority", L"2") // This test is disabled because of a bug in WARP; TODO: enable once the bug is fixed
  409. END_TEST_METHOD()
  410. BEGIN_TEST_METHOD(ComputeRawBufferLdStHalf)
  411. TEST_METHOD_PROPERTY(L"Priority", L"2") // This test is disabled because of a bug in WARP; TODO: enable once the bug is fixed
  412. END_TEST_METHOD()
  413. TEST_METHOD(GraphicsRawBufferLdStI32);
  414. TEST_METHOD(GraphicsRawBufferLdStFloat);
  415. BEGIN_TEST_METHOD(GraphicsRawBufferLdStI64)
  416. TEST_METHOD_PROPERTY(L"Priority", L"2") // Remove this line once warp supports this feature in Shader Model 6.3
  417. END_TEST_METHOD()
  418. BEGIN_TEST_METHOD(GraphicsRawBufferLdStDouble)
  419. TEST_METHOD_PROPERTY(L"Priority", L"2") // Remove this line once warp supports this feature in Shader Model 6.3
  420. END_TEST_METHOD()
  421. BEGIN_TEST_METHOD(GraphicsRawBufferLdStI16)
  422. TEST_METHOD_PROPERTY(L"Priority", L"2") // This test is disabled because of a bug in WARP; TODO: enable once the bug is fixed
  423. END_TEST_METHOD()
  424. BEGIN_TEST_METHOD(GraphicsRawBufferLdStHalf)
  425. TEST_METHOD_PROPERTY(L"Priority", L"2") // This test is disabled because of a bug in WARP; TODO: enable once the bug is fixed
  426. END_TEST_METHOD()
  427. BEGIN_TEST_METHOD(PackUnpackTest)
  428. TEST_METHOD_PROPERTY(L"DataSource", L"Table:ShaderOpArithTable.xml#PackUnpackOpTable")
  429. END_TEST_METHOD()
  430. dxc::DxcDllSupport m_support;
  431. VersionSupportInfo m_ver;
  432. bool m_ExperimentalModeEnabled = false;
  433. const float ClearColor[4] = { 0.0f, 0.2f, 0.4f, 1.0f };
  434. // Do not remove the following line - it is used by TranslateExecutionTest.py
  435. // MARKER: ExecutionTest/DxilConf Shared Implementation Start
  436. // This is defined in d3d.h for Windows 10 Anniversary Edition SDK, but we only
  437. // require the Windows 10 SDK.
  438. typedef enum D3D_SHADER_MODEL {
  439. D3D_SHADER_MODEL_5_1 = 0x51,
  440. D3D_SHADER_MODEL_6_0 = 0x60,
  441. D3D_SHADER_MODEL_6_1 = 0x61,
  442. D3D_SHADER_MODEL_6_2 = 0x62,
  443. D3D_SHADER_MODEL_6_3 = 0x63,
  444. D3D_SHADER_MODEL_6_4 = 0x64,
  445. D3D_SHADER_MODEL_6_5 = 0x65,
  446. D3D_SHADER_MODEL_6_6 = 0x66,
  447. } D3D_SHADER_MODEL;
  448. #if WDK_NTDDI_VERSION == NTDDI_WIN10_RS2
  449. static const D3D_SHADER_MODEL HIGHEST_SHADER_MODEL = D3D_SHADER_MODEL_6_0;
  450. #elif WDK_NTDDI_VERSION == NTDDI_WIN10_RS3
  451. static const D3D_SHADER_MODEL HIGHEST_SHADER_MODEL = D3D_SHADER_MODEL_6_1;
  452. #elif WDK_NTDDI_VERSION == NTDDI_WIN10_RS4
  453. static const D3D_SHADER_MODEL HIGHEST_SHADER_MODEL = D3D_SHADER_MODEL_6_2;
  454. #elif WDK_NTDDI_VERSION == NTDDI_WIN10_RS5
  455. static const D3D_SHADER_MODEL HIGHEST_SHADER_MODEL = D3D_SHADER_MODEL_6_3;
  456. #elif WDK_NTDDI_VERSION == NTDDI_WIN10_19H1
  457. static const D3D_SHADER_MODEL HIGHEST_SHADER_MODEL = D3D_SHADER_MODEL_6_4;
  458. #elif WDK_NTDDI_VERSION == NTDDI_WIN10_VB
  459. static const D3D_SHADER_MODEL HIGHEST_SHADER_MODEL = D3D_SHADER_MODEL_6_5;
  460. #elif WDK_NTDDI_VERSION == NTDDI_WIN10_MN
  461. static const D3D_SHADER_MODEL HIGHEST_SHADER_MODEL = D3D_SHADER_MODEL_6_5;
  462. #elif WDK_NTDDI_VERSION == NTDDI_WIN10_FE
  463. static const D3D_SHADER_MODEL HIGHEST_SHADER_MODEL = D3D_SHADER_MODEL_6_6;
  464. #elif WDK_NTDDI_VERSION == NTDDI_WIN10_CO
  465. static const D3D_SHADER_MODEL HIGHEST_SHADER_MODEL = D3D_SHADER_MODEL_6_6;
  466. #else
  467. static const D3D_SHADER_MODEL HIGHEST_SHADER_MODEL = D3D_SHADER_MODEL_6_6;
  468. #endif
  469. bool UseDxbc() {
  470. #ifdef _HLK_CONF
  471. return false;
  472. #else
  473. return GetTestParamBool(L"DXBC");
  474. #endif
  475. }
  476. bool UseWarpByDefault() {
  477. #ifdef _HLK_CONF
  478. return false;
  479. #else
  480. return true;
  481. #endif
  482. }
  483. bool UseDebugIfaces() {
  484. return true;
  485. }
  486. bool SaveImages() {
  487. return GetTestParamBool(L"SaveImages");
  488. }
  489. void RunResourceTest(ID3D12Device *pDevice, const char *pShader, const wchar_t *sm, bool isDynamic);
  490. template <class T1, class T2>
  491. void WaveIntrinsicsActivePrefixTest(TableParameter *pParameterList,
  492. size_t numParameter, bool isPrefix);
  493. template <typename T>
  494. void WaveIntrinsicsMultiPrefixOpTest(TableParameter *pParameterList,
  495. size_t numParameters);
  496. void BasicTriangleTestSetup(LPCSTR OpName, LPCWSTR FileName, D3D_SHADER_MODEL testModel);
  497. void RunBasicShaderModelTest(D3D_SHADER_MODEL shaderModel);
  498. enum class RawBufferLdStType {
  499. I32,
  500. Float,
  501. I64,
  502. Double,
  503. I16,
  504. Half
  505. };
  506. template <class Ty>
  507. struct RawBufferLdStTestData {
  508. Ty v1, v2[2], v3[3], v4[4];
  509. };
  510. template <class Ty>
  511. struct RawBufferLdStUavData {
  512. RawBufferLdStTestData<Ty> input, output, srvOut;
  513. };
  514. template <class Ty>
  515. void RunComputeRawBufferLdStTest(D3D_SHADER_MODEL shaderModel, RawBufferLdStType dataType,
  516. const char *shaderOpName, const RawBufferLdStTestData<Ty> &testData);
  517. template <class Ty>
  518. void RunGraphicsRawBufferLdStTest(D3D_SHADER_MODEL shaderModel, RawBufferLdStType dataType,
  519. const char *shaderOpName, const RawBufferLdStTestData<Ty> &testData);
  520. template <class Ty>
  521. void VerifyRawBufferLdStTestResults(const std::shared_ptr<st::ShaderOpTest> test, const RawBufferLdStTestData<Ty> &testData);
  522. bool SetupRawBufferLdStTest(D3D_SHADER_MODEL shaderModel, RawBufferLdStType dataType, CComPtr<ID3D12Device> &pDevice,
  523. CComPtr<IStream> &pStream, char *&sTy, char *&additionalOptions);
  524. template <class Ty>
  525. void RunBasicShaderModelTest(CComPtr<ID3D12Device> pDevice, const char *pShaderModelStr, const char *pShader, Ty *pInputDataPairs, unsigned inputDataCount);
  526. template <class Ty>
  527. const wchar_t* BasicShaderModelTest_GetFormatString();
  528. void CompileFromText(LPCSTR pText, LPCWSTR pEntryPoint, LPCWSTR pTargetProfile, ID3DBlob **ppBlob, LPCWSTR *pOptions = nullptr, int numOptions = 0) {
  529. VERIFY_SUCCEEDED(m_support.Initialize());
  530. CComPtr<IDxcCompiler> pCompiler;
  531. CComPtr<IDxcLibrary> pLibrary;
  532. CComPtr<IDxcBlobEncoding> pTextBlob;
  533. CComPtr<IDxcOperationResult> pResult;
  534. HRESULT resultCode;
  535. VERIFY_SUCCEEDED(m_support.CreateInstance(CLSID_DxcCompiler, &pCompiler));
  536. VERIFY_SUCCEEDED(m_support.CreateInstance(CLSID_DxcLibrary, &pLibrary));
  537. VERIFY_SUCCEEDED(pLibrary->CreateBlobWithEncodingFromPinned(pText, (UINT32)strlen(pText), CP_UTF8, &pTextBlob));
  538. VERIFY_SUCCEEDED(pCompiler->Compile(pTextBlob, L"hlsl.hlsl", pEntryPoint, pTargetProfile, pOptions, numOptions, nullptr, 0, nullptr, &pResult));
  539. VERIFY_SUCCEEDED(pResult->GetStatus(&resultCode));
  540. if (FAILED(resultCode)) {
  541. CComPtr<IDxcBlobEncoding> errors;
  542. VERIFY_SUCCEEDED(pResult->GetErrorBuffer(&errors));
  543. #ifndef _HLK_CONF
  544. LogCommentFmt(L"Failed to compile shader: %s", BlobToUtf16(errors).data());
  545. #endif
  546. }
  547. VERIFY_SUCCEEDED(resultCode);
  548. VERIFY_SUCCEEDED(pResult->GetResult((IDxcBlob **)ppBlob));
  549. }
  550. void CreateCommandQueue(ID3D12Device *pDevice, LPCWSTR pName, ID3D12CommandQueue **ppCommandQueue, D3D12_COMMAND_LIST_TYPE type) {
  551. D3D12_COMMAND_QUEUE_DESC queueDesc = {};
  552. queueDesc.Flags = D3D12_COMMAND_QUEUE_FLAG_NONE;
  553. queueDesc.Type = type;
  554. VERIFY_SUCCEEDED(pDevice->CreateCommandQueue(&queueDesc, IID_PPV_ARGS(ppCommandQueue)));
  555. VERIFY_SUCCEEDED((*ppCommandQueue)->SetName(pName));
  556. }
  557. void CreateComputeCommandQueue(ID3D12Device *pDevice, LPCWSTR pName, ID3D12CommandQueue **ppCommandQueue) {
  558. CreateCommandQueue(pDevice, pName, ppCommandQueue, D3D12_COMMAND_LIST_TYPE_COMPUTE);
  559. }
  560. void CreateComputePSO(ID3D12Device *pDevice, ID3D12RootSignature *pRootSignature, LPCSTR pShader, LPCWSTR pTargetProfile, ID3D12PipelineState **ppComputeState, LPCWSTR *pOptions = nullptr, int numOptions = 0) {
  561. CComPtr<ID3DBlob> pComputeShader;
  562. // Load and compile shaders.
  563. if (UseDxbc()) {
  564. #ifndef _HLK_CONF
  565. DXBCFromText(pShader, L"main", pTargetProfile, &pComputeShader);
  566. #endif
  567. }
  568. else {
  569. CompileFromText(pShader, L"main", pTargetProfile, &pComputeShader, pOptions, numOptions);
  570. }
  571. // Describe and create the compute pipeline state object (PSO).
  572. D3D12_COMPUTE_PIPELINE_STATE_DESC computePsoDesc = {};
  573. computePsoDesc.pRootSignature = pRootSignature;
  574. computePsoDesc.CS = CD3DX12_SHADER_BYTECODE(pComputeShader);
  575. VERIFY_SUCCEEDED(pDevice->CreateComputePipelineState(&computePsoDesc, IID_PPV_ARGS(ppComputeState)));
  576. }
  577. bool CreateDevice(_COM_Outptr_ ID3D12Device **ppDevice,
  578. D3D_SHADER_MODEL testModel = D3D_SHADER_MODEL_6_0, bool skipUnsupported = true,
  579. bool enableRayTracing = false) {
  580. if (testModel > HIGHEST_SHADER_MODEL) {
  581. UINT minor = (UINT)testModel & 0x0f;
  582. LogCommentFmt(L"Installed SDK does not support "
  583. L"shader model 6.%1u", minor);
  584. if (skipUnsupported) {
  585. WEX::Logging::Log::Result(WEX::Logging::TestResults::Skipped);
  586. }
  587. return false;
  588. }
  589. const D3D_FEATURE_LEVEL FeatureLevelRequired = enableRayTracing ? D3D_FEATURE_LEVEL_12_0 : D3D_FEATURE_LEVEL_11_0;
  590. CComPtr<IDXGIFactory4> factory;
  591. CComPtr<ID3D12Device> pDevice;
  592. *ppDevice = nullptr;
  593. VERIFY_SUCCEEDED(CreateDXGIFactory1(IID_PPV_ARGS(&factory)));
  594. if (GetTestParamUseWARP(UseWarpByDefault())) {
  595. CComPtr<IDXGIAdapter> warpAdapter;
  596. VERIFY_SUCCEEDED(factory->EnumWarpAdapter(IID_PPV_ARGS(&warpAdapter)));
  597. HRESULT createHR = D3D12CreateDevice(warpAdapter, FeatureLevelRequired,
  598. IID_PPV_ARGS(&pDevice));
  599. if (FAILED(createHR)) {
  600. LogCommentFmt(L"The available version of WARP does not support d3d12.");
  601. if (skipUnsupported) {
  602. WEX::Logging::Log::Result(WEX::Logging::TestResults::Skipped);
  603. }
  604. return false;
  605. }
  606. } else {
  607. CComPtr<IDXGIAdapter1> hardwareAdapter;
  608. WEX::Common::String AdapterValue;
  609. HRESULT hr = WEX::TestExecution::RuntimeParameters::TryGetValue(L"Adapter",
  610. AdapterValue);
  611. if (SUCCEEDED(hr)) {
  612. GetHardwareAdapter(factory, AdapterValue, &hardwareAdapter);
  613. } else {
  614. WEX::Logging::Log::Comment(
  615. L"Using default hardware adapter with D3D12 support.");
  616. }
  617. VERIFY_SUCCEEDED(D3D12CreateDevice(hardwareAdapter, FeatureLevelRequired,
  618. IID_PPV_ARGS(&pDevice)));
  619. }
  620. // retrieve adapter information
  621. LUID adapterID = pDevice->GetAdapterLuid();
  622. CComPtr<IDXGIAdapter> adapter;
  623. factory->EnumAdapterByLuid(adapterID, IID_PPV_ARGS(&adapter));
  624. DXGI_ADAPTER_DESC AdapterDesc;
  625. VERIFY_SUCCEEDED(adapter->GetDesc(&AdapterDesc));
  626. LogCommentFmt(L"Using Adapter:%s", AdapterDesc.Description);
  627. if (pDevice == nullptr)
  628. return false;
  629. if (!UseDxbc()) {
  630. // Check for DXIL support.
  631. typedef struct D3D12_FEATURE_DATA_SHADER_MODEL {
  632. _Inout_ D3D_SHADER_MODEL HighestShaderModel;
  633. } D3D12_FEATURE_DATA_SHADER_MODEL;
  634. const UINT D3D12_FEATURE_SHADER_MODEL = 7;
  635. D3D12_FEATURE_DATA_SHADER_MODEL SMData;
  636. SMData.HighestShaderModel = testModel;
  637. VERIFY_SUCCEEDED(pDevice->CheckFeatureSupport(
  638. (D3D12_FEATURE)D3D12_FEATURE_SHADER_MODEL, &SMData, sizeof(SMData)));
  639. if (SMData.HighestShaderModel < testModel) {
  640. UINT minor = (UINT)testModel & 0x0f;
  641. LogCommentFmt(L"The selected device does not support "
  642. L"shader model 6.%1u", minor);
  643. if (skipUnsupported) {
  644. WEX::Logging::Log::Result(WEX::Logging::TestResults::Skipped);
  645. }
  646. return false;
  647. }
  648. }
  649. if (UseDebugIfaces()) {
  650. CComPtr<ID3D12InfoQueue> pInfoQueue;
  651. if (SUCCEEDED(pDevice->QueryInterface(&pInfoQueue))) {
  652. pInfoQueue->SetMuteDebugOutput(FALSE);
  653. }
  654. }
  655. *ppDevice = pDevice.Detach();
  656. return true;
  657. }
  658. void CreateGraphicsCommandQueue(ID3D12Device *pDevice, ID3D12CommandQueue **ppCommandQueue) {
  659. D3D12_COMMAND_QUEUE_DESC queueDesc = {};
  660. queueDesc.Flags = D3D12_COMMAND_QUEUE_FLAG_NONE;
  661. queueDesc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT;;
  662. VERIFY_SUCCEEDED(pDevice->CreateCommandQueue(&queueDesc, IID_PPV_ARGS(ppCommandQueue)));
  663. }
  664. void CreateGraphicsCommandQueueAndList(
  665. ID3D12Device *pDevice, ID3D12CommandQueue **ppCommandQueue,
  666. ID3D12CommandAllocator **ppAllocator,
  667. ID3D12GraphicsCommandList **ppCommandList, ID3D12PipelineState *pPSO) {
  668. CreateGraphicsCommandQueue(pDevice, ppCommandQueue);
  669. VERIFY_SUCCEEDED(pDevice->CreateCommandAllocator(
  670. D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(ppAllocator)));
  671. VERIFY_SUCCEEDED(pDevice->CreateCommandList(
  672. 0, D3D12_COMMAND_LIST_TYPE_DIRECT, *ppAllocator, pPSO,
  673. IID_PPV_ARGS(ppCommandList)));
  674. }
  675. void CreateGraphicsPSO(ID3D12Device *pDevice,
  676. D3D12_INPUT_LAYOUT_DESC *pInputLayout,
  677. ID3D12RootSignature *pRootSignature, LPCSTR pShaders,
  678. ID3D12PipelineState **ppPSO) {
  679. CComPtr<ID3DBlob> vertexShader;
  680. CComPtr<ID3DBlob> pixelShader;
  681. if (UseDxbc()) {
  682. #ifndef _HLK_CONF
  683. DXBCFromText(pShaders, L"VSMain", L"vs_6_0", &vertexShader);
  684. DXBCFromText(pShaders, L"PSMain", L"ps_6_0", &pixelShader);
  685. #endif
  686. } else {
  687. CompileFromText(pShaders, L"VSMain", L"vs_6_0", &vertexShader);
  688. CompileFromText(pShaders, L"PSMain", L"ps_6_0", &pixelShader);
  689. }
  690. // Describe and create the graphics pipeline state object (PSO).
  691. D3D12_GRAPHICS_PIPELINE_STATE_DESC psoDesc = {};
  692. psoDesc.InputLayout = *pInputLayout;
  693. psoDesc.pRootSignature = pRootSignature;
  694. psoDesc.VS = CD3DX12_SHADER_BYTECODE(vertexShader);
  695. psoDesc.PS = CD3DX12_SHADER_BYTECODE(pixelShader);
  696. psoDesc.RasterizerState = CD3DX12_RASTERIZER_DESC(D3D12_DEFAULT);
  697. psoDesc.BlendState = CD3DX12_BLEND_DESC(D3D12_DEFAULT);
  698. psoDesc.DepthStencilState.DepthEnable = FALSE;
  699. psoDesc.DepthStencilState.StencilEnable = FALSE;
  700. psoDesc.SampleMask = UINT_MAX;
  701. psoDesc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE;
  702. psoDesc.NumRenderTargets = 1;
  703. psoDesc.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM;
  704. psoDesc.SampleDesc.Count = 1;
  705. VERIFY_SUCCEEDED(
  706. pDevice->CreateGraphicsPipelineState(&psoDesc, IID_PPV_ARGS(ppPSO)));
  707. }
  708. void CreateRenderTargetAndReadback(ID3D12Device *pDevice,
  709. ID3D12DescriptorHeap *pHeap, UINT width,
  710. UINT height,
  711. ID3D12Resource **ppRenderTarget,
  712. ID3D12Resource **ppBuffer) {
  713. const DXGI_FORMAT format = DXGI_FORMAT_R8G8B8A8_UNORM;
  714. const size_t formatElementSize = 4;
  715. CComPtr<ID3D12Resource> pRenderTarget;
  716. CComPtr<ID3D12Resource> pBuffer;
  717. CD3DX12_CPU_DESCRIPTOR_HANDLE rtvHandle(
  718. pHeap->GetCPUDescriptorHandleForHeapStart());
  719. CD3DX12_HEAP_PROPERTIES rtHeap(D3D12_HEAP_TYPE_DEFAULT);
  720. CD3DX12_RESOURCE_DESC rtDesc(
  721. CD3DX12_RESOURCE_DESC::Tex2D(format, width, height));
  722. CD3DX12_CLEAR_VALUE rtClearVal(format, ClearColor);
  723. rtDesc.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET;
  724. VERIFY_SUCCEEDED(pDevice->CreateCommittedResource(
  725. &rtHeap, D3D12_HEAP_FLAG_NONE, &rtDesc, D3D12_RESOURCE_STATE_COPY_DEST,
  726. &rtClearVal, IID_PPV_ARGS(&pRenderTarget)));
  727. pDevice->CreateRenderTargetView(pRenderTarget, nullptr, rtvHandle);
  728. // rtvHandle.Offset(1, rtvDescriptorSize); // Not needed for a single
  729. // resource.
  730. CD3DX12_HEAP_PROPERTIES readHeap(D3D12_HEAP_TYPE_READBACK);
  731. CD3DX12_RESOURCE_DESC readDesc(
  732. CD3DX12_RESOURCE_DESC::Buffer(width * height * formatElementSize));
  733. VERIFY_SUCCEEDED(pDevice->CreateCommittedResource(
  734. &readHeap, D3D12_HEAP_FLAG_NONE, &readDesc,
  735. D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS(&pBuffer)));
  736. *ppRenderTarget = pRenderTarget.Detach();
  737. *ppBuffer = pBuffer.Detach();
  738. }
  739. void CreateRootSignatureFromDesc(ID3D12Device *pDevice,
  740. const D3D12_ROOT_SIGNATURE_DESC *pDesc,
  741. ID3D12RootSignature **pRootSig) {
  742. CComPtr<ID3DBlob> signature;
  743. CComPtr<ID3DBlob> error;
  744. VERIFY_SUCCEEDED(D3D12SerializeRootSignature(pDesc, D3D_ROOT_SIGNATURE_VERSION_1, &signature, &error));
  745. VERIFY_SUCCEEDED(pDevice->CreateRootSignature(
  746. 0, signature->GetBufferPointer(), signature->GetBufferSize(),
  747. IID_PPV_ARGS(pRootSig)));
  748. }
  749. void CreateRootSignatureFromRanges(ID3D12Device *pDevice, ID3D12RootSignature **pRootSig,
  750. CD3DX12_DESCRIPTOR_RANGE *resRanges, UINT resCt,
  751. CD3DX12_DESCRIPTOR_RANGE *sampRanges = nullptr, UINT sampCt = 0,
  752. D3D12_ROOT_SIGNATURE_FLAGS flags = D3D12_ROOT_SIGNATURE_FLAG_NONE) {
  753. CD3DX12_ROOT_PARAMETER rootParameters[2];
  754. rootParameters[0].InitAsDescriptorTable(resCt, resRanges, D3D12_SHADER_VISIBILITY_ALL);
  755. rootParameters[1].InitAsDescriptorTable(sampCt, sampRanges, D3D12_SHADER_VISIBILITY_ALL);
  756. CD3DX12_ROOT_SIGNATURE_DESC rootSignatureDesc;
  757. rootSignatureDesc.Init(_countof(rootParameters), rootParameters, 0, nullptr, flags);
  758. CreateRootSignatureFromDesc(pDevice, &rootSignatureDesc, pRootSig);
  759. }
  760. void CreateRtvDescriptorHeap(ID3D12Device *pDevice, UINT numDescriptors,
  761. ID3D12DescriptorHeap **pRtvHeap, UINT *rtvDescriptorSize) {
  762. D3D12_DESCRIPTOR_HEAP_DESC rtvHeapDesc = {};
  763. rtvHeapDesc.NumDescriptors = numDescriptors;
  764. rtvHeapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_RTV;
  765. rtvHeapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_NONE;
  766. VERIFY_SUCCEEDED(
  767. pDevice->CreateDescriptorHeap(&rtvHeapDesc, IID_PPV_ARGS(pRtvHeap)));
  768. if (rtvDescriptorSize != nullptr) {
  769. *rtvDescriptorSize = pDevice->GetDescriptorHandleIncrementSize(
  770. D3D12_DESCRIPTOR_HEAP_TYPE_RTV);
  771. }
  772. }
  773. void CreateTestResources(ID3D12Device *pDevice,
  774. ID3D12GraphicsCommandList *pCommandList, LPCVOID values,
  775. UINT32 valueSizeInBytes, D3D12_RESOURCE_DESC resDesc,
  776. ID3D12Resource **ppResource,
  777. ID3D12Resource **ppUploadResource,
  778. ID3D12Resource **ppReadBuffer = nullptr) {
  779. CComPtr<ID3D12Resource> pResource;
  780. CComPtr<ID3D12Resource> pReadBuffer;
  781. CComPtr<ID3D12Resource> pUploadResource;
  782. D3D12_SUBRESOURCE_DATA transferData;
  783. D3D12_HEAP_PROPERTIES defaultHeapProperties = CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_DEFAULT);
  784. D3D12_HEAP_PROPERTIES uploadHeapProperties = CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_UPLOAD);
  785. D3D12_RESOURCE_DESC uploadBufferDesc = CD3DX12_RESOURCE_DESC::Buffer(valueSizeInBytes);
  786. CD3DX12_HEAP_PROPERTIES readHeap(D3D12_HEAP_TYPE_READBACK);
  787. CD3DX12_RESOURCE_DESC readDesc(CD3DX12_RESOURCE_DESC::Buffer(valueSizeInBytes));
  788. pDevice->GetCopyableFootprints(&resDesc, 0, 1/*mipleveles*/, 0, nullptr, nullptr, nullptr, &uploadBufferDesc.Width);
  789. uploadBufferDesc.Height = 1;
  790. VERIFY_SUCCEEDED(pDevice->CreateCommittedResource(
  791. &defaultHeapProperties,
  792. D3D12_HEAP_FLAG_NONE,
  793. &resDesc,
  794. D3D12_RESOURCE_STATE_COPY_DEST,
  795. nullptr,
  796. IID_PPV_ARGS(&pResource)));
  797. VERIFY_SUCCEEDED(pDevice->CreateCommittedResource(
  798. &uploadHeapProperties,
  799. D3D12_HEAP_FLAG_NONE,
  800. &uploadBufferDesc,
  801. D3D12_RESOURCE_STATE_GENERIC_READ,
  802. nullptr,
  803. IID_PPV_ARGS(&pUploadResource)));
  804. if (ppReadBuffer)
  805. VERIFY_SUCCEEDED(pDevice->CreateCommittedResource(
  806. &readHeap, D3D12_HEAP_FLAG_NONE, &readDesc,
  807. D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS(&pReadBuffer)));
  808. transferData.pData = values;
  809. transferData.RowPitch = valueSizeInBytes/resDesc.Height;
  810. transferData.SlicePitch = valueSizeInBytes;
  811. UpdateSubresources<1>(pCommandList, pResource.p, pUploadResource.p, 0, 0, 1, &transferData);
  812. if (resDesc.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)
  813. RecordTransitionBarrier(pCommandList, pResource, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
  814. else
  815. RecordTransitionBarrier(pCommandList, pResource, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COMMON);
  816. *ppResource = pResource.Detach();
  817. *ppUploadResource = pUploadResource.Detach();
  818. if (ppReadBuffer)
  819. *ppReadBuffer = pReadBuffer.Detach();
  820. }
  821. void CreateTestUavs(ID3D12Device *pDevice,
  822. ID3D12GraphicsCommandList *pCommandList, LPCVOID values,
  823. UINT32 valueSizeInBytes, ID3D12Resource **ppUavResource,
  824. ID3D12Resource **ppUploadResource = nullptr,
  825. ID3D12Resource **ppReadBuffer = nullptr) {
  826. D3D12_RESOURCE_DESC bufferDesc = CD3DX12_RESOURCE_DESC::Buffer(valueSizeInBytes, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS);
  827. CreateTestResources(pDevice, pCommandList, values, valueSizeInBytes, bufferDesc,
  828. ppUavResource, ppUploadResource, ppReadBuffer);
  829. }
  830. // Create and return descriptor heaps for the given device
  831. // with the given number of resources and samples.
  832. // using some reasonable defaults
  833. void CreateDefaultDescHeaps(ID3D12Device *pDevice,
  834. int NumResources, int NumSamplers,
  835. ID3D12DescriptorHeap **ppResHeap, ID3D12DescriptorHeap **ppSampHeap) {
  836. // Describe and create descriptor heaps.
  837. ID3D12DescriptorHeap *pResHeap, *pSampHeap;
  838. D3D12_DESCRIPTOR_HEAP_DESC heapDesc = {};
  839. heapDesc.NumDescriptors = NumResources;
  840. heapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV;
  841. heapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE;
  842. VERIFY_SUCCEEDED(pDevice->CreateDescriptorHeap(&heapDesc, IID_PPV_ARGS(&pResHeap)));
  843. heapDesc.NumDescriptors = NumSamplers;
  844. heapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER;
  845. VERIFY_SUCCEEDED(pDevice->CreateDescriptorHeap(&heapDesc, IID_PPV_ARGS(&pSampHeap)));
  846. *ppResHeap = pResHeap;
  847. *ppSampHeap = pSampHeap;
  848. }
  849. void CreateSRV(ID3D12Device *pDevice, CD3DX12_CPU_DESCRIPTOR_HANDLE &baseHandle,
  850. DXGI_FORMAT format, D3D12_SRV_DIMENSION viewDimension, UINT numElements, UINT stride,
  851. const CComPtr<ID3D12Resource> pResource) {
  852. UINT descriptorSize = pDevice->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV);
  853. // Create SRV
  854. D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc = {};
  855. srvDesc.Format = format;
  856. srvDesc.ViewDimension = viewDimension;
  857. srvDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
  858. switch (viewDimension) {
  859. case D3D12_SRV_DIMENSION_BUFFER:
  860. srvDesc.Buffer.FirstElement = 0;
  861. srvDesc.Buffer.NumElements = numElements;
  862. srvDesc.Buffer.StructureByteStride = stride;
  863. if (format == DXGI_FORMAT_R32_TYPELESS && stride == 0)
  864. srvDesc.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW;
  865. else
  866. srvDesc.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_NONE;
  867. break;
  868. case D3D12_SRV_DIMENSION_TEXTURE1D:
  869. srvDesc.Texture1D.MostDetailedMip = 0;
  870. srvDesc.Texture1D.MipLevels = 1;
  871. srvDesc.Texture1D.ResourceMinLODClamp = 0;
  872. break;
  873. case D3D12_SRV_DIMENSION_TEXTURE2D:
  874. srvDesc.Texture2D.MostDetailedMip = 0;
  875. srvDesc.Texture2D.MipLevels = 1;
  876. srvDesc.Texture2D.PlaneSlice = 0;
  877. srvDesc.Texture2D.ResourceMinLODClamp = 0;
  878. break;
  879. }
  880. pDevice->CreateShaderResourceView(pResource, &srvDesc, baseHandle);
  881. baseHandle.Offset(descriptorSize);
  882. }
  883. void CreateRawSRV(ID3D12Device *pDevice, CD3DX12_CPU_DESCRIPTOR_HANDLE &heapStart,
  884. UINT numElements, const CComPtr<ID3D12Resource> pResource) {
  885. CreateSRV(pDevice, heapStart, DXGI_FORMAT_R32_TYPELESS, D3D12_SRV_DIMENSION_BUFFER, numElements, 0, pResource);
  886. }
  887. void CreateStructSRV(ID3D12Device *pDevice, CD3DX12_CPU_DESCRIPTOR_HANDLE &heapStart,
  888. UINT numElements, UINT stride, const CComPtr<ID3D12Resource> pResource) {
  889. CreateSRV(pDevice, heapStart, DXGI_FORMAT_UNKNOWN, D3D12_SRV_DIMENSION_BUFFER, numElements, stride, pResource);
  890. }
  891. void CreateTypedSRV(ID3D12Device *pDevice, CD3DX12_CPU_DESCRIPTOR_HANDLE &heapStart,
  892. UINT numElements, DXGI_FORMAT format, const CComPtr<ID3D12Resource> pResource) {
  893. CreateSRV(pDevice, heapStart, format, D3D12_SRV_DIMENSION_BUFFER, numElements, 0, pResource);
  894. }
  895. void CreateTex1DSRV(ID3D12Device *pDevice, CD3DX12_CPU_DESCRIPTOR_HANDLE &heapStart,
  896. UINT numElements, DXGI_FORMAT format, const CComPtr<ID3D12Resource> pResource) {
  897. CreateSRV(pDevice, heapStart, format, D3D12_SRV_DIMENSION_TEXTURE1D, numElements, 0, pResource);
  898. }
  899. void CreateTex2DSRV(ID3D12Device *pDevice, CD3DX12_CPU_DESCRIPTOR_HANDLE &heapStart,
  900. UINT numElements, DXGI_FORMAT format, const CComPtr<ID3D12Resource> pResource) {
  901. CreateSRV(pDevice, heapStart, format, D3D12_SRV_DIMENSION_TEXTURE2D, numElements, 0, pResource);
  902. }
  903. void CreateUAV(ID3D12Device *pDevice, CD3DX12_CPU_DESCRIPTOR_HANDLE &baseHandle,
  904. DXGI_FORMAT format, D3D12_UAV_DIMENSION viewDimension, UINT numElements, UINT stride,
  905. const CComPtr<ID3D12Resource> pResource) {
  906. UINT descriptorSize = pDevice->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV);
  907. D3D12_UNORDERED_ACCESS_VIEW_DESC uavDesc = {};
  908. uavDesc.Format = format;
  909. uavDesc.ViewDimension = viewDimension;
  910. switch (viewDimension) {
  911. case D3D12_UAV_DIMENSION_BUFFER:
  912. uavDesc.Buffer.FirstElement = 0;
  913. uavDesc.Buffer.NumElements = numElements;
  914. uavDesc.Buffer.StructureByteStride = stride;
  915. if (format == DXGI_FORMAT_R32_TYPELESS && stride == 0)
  916. uavDesc.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_RAW;
  917. else
  918. uavDesc.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_NONE;
  919. break;
  920. case D3D12_UAV_DIMENSION_TEXTURE1D:
  921. uavDesc.Texture1D.MipSlice = 0;
  922. break;
  923. case D3D12_UAV_DIMENSION_TEXTURE2D:
  924. uavDesc.Texture2D.MipSlice = 0;
  925. uavDesc.Texture2D.PlaneSlice = 0;
  926. break;
  927. }
  928. pDevice->CreateUnorderedAccessView(pResource, nullptr, &uavDesc, baseHandle);
  929. baseHandle.Offset(descriptorSize);
  930. }
  931. void CreateRawUAV(ID3D12Device *pDevice, CD3DX12_CPU_DESCRIPTOR_HANDLE &heapStart,
  932. UINT numElements, const CComPtr<ID3D12Resource> pResource) {
  933. CreateUAV(pDevice, heapStart, DXGI_FORMAT_R32_TYPELESS, D3D12_UAV_DIMENSION_BUFFER, numElements, 0, pResource);
  934. }
  935. void CreateStructUAV(ID3D12Device *pDevice, CD3DX12_CPU_DESCRIPTOR_HANDLE &heapStart,
  936. UINT numElements, UINT stride, const CComPtr<ID3D12Resource> pResource) {
  937. CreateUAV(pDevice, heapStart, DXGI_FORMAT_UNKNOWN, D3D12_UAV_DIMENSION_BUFFER, numElements, stride, pResource);
  938. }
  939. void CreateTypedUAV(ID3D12Device *pDevice, CD3DX12_CPU_DESCRIPTOR_HANDLE &heapStart,
  940. UINT numElements, DXGI_FORMAT format, const CComPtr<ID3D12Resource> pResource) {
  941. CreateUAV(pDevice, heapStart, format, D3D12_UAV_DIMENSION_BUFFER, numElements, 0, pResource);
  942. }
  943. void CreateTex1DUAV(ID3D12Device *pDevice, CD3DX12_CPU_DESCRIPTOR_HANDLE &heapStart,
  944. UINT numElements, DXGI_FORMAT format, const CComPtr<ID3D12Resource> pResource) {
  945. CreateUAV(pDevice, heapStart, format, D3D12_UAV_DIMENSION_TEXTURE1D, numElements, 0, pResource);
  946. }
  947. void CreateTex2DUAV(ID3D12Device *pDevice, CD3DX12_CPU_DESCRIPTOR_HANDLE &heapStart,
  948. UINT numElements, DXGI_FORMAT format, const CComPtr<ID3D12Resource> pResource) {
  949. CreateUAV(pDevice, heapStart, format, D3D12_UAV_DIMENSION_TEXTURE2D, numElements, 0, pResource);
  950. }
  951. // Create Samplers for <pDevice> given the filter and border color information provided
  952. // using some reasonable defaults
  953. void CreateDefaultSamplers(ID3D12Device *pDevice, D3D12_CPU_DESCRIPTOR_HANDLE heapStart,
  954. D3D12_FILTER filters[], float BorderColors[], int NumSamplers) {
  955. CD3DX12_CPU_DESCRIPTOR_HANDLE sampHandle(heapStart);
  956. UINT descriptorSize = pDevice->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER);
  957. D3D12_SAMPLER_DESC sampDesc = {};
  958. sampDesc.Filter = D3D12_FILTER_MIN_MAG_LINEAR_MIP_POINT;
  959. sampDesc.AddressU = D3D12_TEXTURE_ADDRESS_MODE_BORDER;
  960. sampDesc.AddressV = D3D12_TEXTURE_ADDRESS_MODE_BORDER;
  961. sampDesc.AddressW = D3D12_TEXTURE_ADDRESS_MODE_BORDER;
  962. sampDesc.MipLODBias = 0;
  963. sampDesc.MaxAnisotropy = 1;
  964. sampDesc.ComparisonFunc = D3D12_COMPARISON_FUNC_EQUAL;
  965. sampDesc.MinLOD = 0;
  966. sampDesc.MaxLOD = 0;
  967. for (int i = 0; i < NumSamplers; i++) {
  968. sampDesc.Filter = filters[i];
  969. for (int j = 0; j < 4; j++)
  970. sampDesc.BorderColor[j] = BorderColors[i];
  971. pDevice->CreateSampler(&sampDesc, sampHandle);
  972. sampHandle = sampHandle.Offset(descriptorSize);
  973. }
  974. }
  975. template <typename TVertex, int len>
  976. void CreateVertexBuffer(ID3D12Device *pDevice, TVertex(&vertices)[len],
  977. ID3D12Resource **ppVertexBuffer,
  978. D3D12_VERTEX_BUFFER_VIEW *pVertexBufferView) {
  979. size_t vertexBufferSize = sizeof(vertices);
  980. CComPtr<ID3D12Resource> pVertexBuffer;
  981. CD3DX12_HEAP_PROPERTIES heapProps(D3D12_HEAP_TYPE_UPLOAD);
  982. CD3DX12_RESOURCE_DESC bufferDesc(
  983. CD3DX12_RESOURCE_DESC::Buffer(vertexBufferSize));
  984. VERIFY_SUCCEEDED(pDevice->CreateCommittedResource(
  985. &heapProps, D3D12_HEAP_FLAG_NONE, &bufferDesc,
  986. D3D12_RESOURCE_STATE_GENERIC_READ, nullptr,
  987. IID_PPV_ARGS(&pVertexBuffer)));
  988. UINT8 *pVertexDataBegin;
  989. CD3DX12_RANGE readRange(0, 0);
  990. VERIFY_SUCCEEDED(pVertexBuffer->Map(
  991. 0, &readRange, reinterpret_cast<void **>(&pVertexDataBegin)));
  992. memcpy(pVertexDataBegin, vertices, vertexBufferSize);
  993. pVertexBuffer->Unmap(0, nullptr);
  994. // Initialize the vertex buffer view.
  995. pVertexBufferView->BufferLocation = pVertexBuffer->GetGPUVirtualAddress();
  996. pVertexBufferView->StrideInBytes = sizeof(TVertex);
  997. pVertexBufferView->SizeInBytes = (UINT)vertexBufferSize;
  998. *ppVertexBuffer = pVertexBuffer.Detach();
  999. }
  1000. // Requires Anniversary Edition headers, so simplifying things for current setup.
  1001. const UINT D3D12_FEATURE_D3D12_OPTIONS1 = 8;
  1002. struct D3D12_FEATURE_DATA_D3D12_OPTIONS1 {
  1003. BOOL WaveOps;
  1004. UINT WaveLaneCountMin;
  1005. UINT WaveLaneCountMax;
  1006. UINT TotalLaneCount;
  1007. BOOL ExpandedComputeResourceStates;
  1008. BOOL Int64ShaderOps;
  1009. };
  1010. bool DoesDeviceSupportInt64(ID3D12Device *pDevice) {
  1011. D3D12_FEATURE_DATA_D3D12_OPTIONS1 O;
  1012. if (FAILED(pDevice->CheckFeatureSupport((D3D12_FEATURE)D3D12_FEATURE_D3D12_OPTIONS1, &O, sizeof(O))))
  1013. return false;
  1014. return O.Int64ShaderOps != FALSE;
  1015. }
  1016. bool DoesDeviceSupportDouble(ID3D12Device *pDevice) {
  1017. D3D12_FEATURE_DATA_D3D12_OPTIONS O;
  1018. if (FAILED(pDevice->CheckFeatureSupport((D3D12_FEATURE)D3D12_FEATURE_D3D12_OPTIONS, &O, sizeof(O))))
  1019. return false;
  1020. return O.DoublePrecisionFloatShaderOps != FALSE;
  1021. }
  1022. bool DoesDeviceSupportWaveOps(ID3D12Device *pDevice) {
  1023. D3D12_FEATURE_DATA_D3D12_OPTIONS1 O;
  1024. if (FAILED(pDevice->CheckFeatureSupport((D3D12_FEATURE)D3D12_FEATURE_D3D12_OPTIONS1, &O, sizeof(O))))
  1025. return false;
  1026. return O.WaveOps != FALSE;
  1027. }
  1028. bool DoesDeviceSupportBarycentrics(ID3D12Device *pDevice) {
  1029. D3D12_FEATURE_DATA_D3D12_OPTIONS3 O;
  1030. if (FAILED(pDevice->CheckFeatureSupport((D3D12_FEATURE)D3D12_FEATURE_D3D12_OPTIONS3, &O, sizeof(O))))
  1031. return false;
  1032. return O.BarycentricsSupported != FALSE;
  1033. }
  1034. bool DoesDeviceSupportNative16bitOps(ID3D12Device *pDevice) {
  1035. D3D12_FEATURE_DATA_D3D12_OPTIONS4 O;
  1036. if (FAILED(pDevice->CheckFeatureSupport((D3D12_FEATURE)D3D12_FEATURE_D3D12_OPTIONS4, &O, sizeof(O))))
  1037. return false;
  1038. return O.Native16BitShaderOpsSupported != FALSE;
  1039. }
  1040. bool DoesDeviceSupportMeshShaders(ID3D12Device *pDevice) {
  1041. #if defined(NTDDI_WIN10_VB) && WDK_NTDDI_VERSION >= NTDDI_WIN10_VB
  1042. D3D12_FEATURE_DATA_D3D12_OPTIONS7 O7;
  1043. if (FAILED(pDevice->CheckFeatureSupport((D3D12_FEATURE)D3D12_FEATURE_D3D12_OPTIONS7, &O7, sizeof(O7))))
  1044. return false;
  1045. return O7.MeshShaderTier != D3D12_MESH_SHADER_TIER_NOT_SUPPORTED;
  1046. #else
  1047. UNREFERENCED_PARAMETER(pDevice);
  1048. return false;
  1049. #endif
  1050. }
  1051. bool DoesDeviceSupportRayTracing(ID3D12Device *pDevice) {
  1052. #if WDK_NTDDI_VERSION > NTDDI_WIN10_RS4
  1053. D3D12_FEATURE_DATA_D3D12_OPTIONS5 O5;
  1054. if (FAILED(pDevice->CheckFeatureSupport((D3D12_FEATURE)D3D12_FEATURE_D3D12_OPTIONS5, &O5, sizeof(O5))))
  1055. return false;
  1056. return O5.RaytracingTier != D3D12_RAYTRACING_TIER_NOT_SUPPORTED;
  1057. #else
  1058. UNREFERENCED_PARAMETER(pDevice);
  1059. return false;
  1060. #endif
  1061. }
  1062. // Replace with appropriate WDK check when available
  1063. #define SM66_RUNTIME_SUPPORT 0
  1064. bool DoesDeviceSupportMeshAmpDerivatives(ID3D12Device *pDevice) {
  1065. #if SM66_RUNTIME_SUPPORT
  1066. D3D12_FEATURE_DATA_D3D12_OPTIONS7 O7;
  1067. D3D12_FEATURE_DATA_D3D12_OPTIONS9 O9;
  1068. if (FAILED(pDevice->CheckFeatureSupport((D3D12_FEATURE)D3D12_FEATURE_D3D12_OPTIONS7, &O7, sizeof(O7))) ||
  1069. FAILED(pDevice->CheckFeatureSupport((D3D12_FEATURE)D3D12_FEATURE_D3D12_OPTIONS9, &O9, sizeof(O9))))
  1070. return false;
  1071. return O7.MeshShaderTier != D3D12_MESH_SHADER_TIER_NOT_SUPPORTED &&
  1072. O9.DerivativesInMeshAndAmplificationShadersSupported != FALSE;
  1073. #else
  1074. UNREFERENCED_PARAMETER(pDevice);
  1075. return false;
  1076. #endif
  1077. }
  1078. bool DoesDeviceSupportTyped64Atomics(ID3D12Device *pDevice) {
  1079. #if SM66_RUNTIME_SUPPORT
  1080. D3D12_FEATURE_DATA_D3D12_OPTIONS9 O9;
  1081. if (FAILED(pDevice->CheckFeatureSupport((D3D12_FEATURE)D3D12_FEATURE_D3D12_OPTIONS9, &O9, sizeof(O9))))
  1082. return false;
  1083. return O9.AtomicInt64OnTypedResourceSupported != FALSE;
  1084. #else
  1085. UNREFERENCED_PARAMETER(pDevice);
  1086. return false;
  1087. #endif
  1088. }
  1089. bool DoesDeviceSupportShared64Atomics(ID3D12Device *pDevice) {
  1090. #if SM66_RUNTIME_SUPPORT
  1091. D3D12_FEATURE_DATA_D3D12_OPTIONS9 O9;
  1092. if (FAILED(pDevice->CheckFeatureSupport((D3D12_FEATURE)D3D12_FEATURE_D3D12_OPTIONS9, &O9, sizeof(O9))))
  1093. return false;
  1094. return O9.AtomicInt64OnGroupSharedSupported != FALSE;
  1095. #else
  1096. UNREFERENCED_PARAMETER(pDevice);
  1097. return false;
  1098. #endif
  1099. }
  1100. #ifndef _HLK_CONF
  1101. void DXBCFromText(LPCSTR pText, LPCWSTR pEntryPoint, LPCWSTR pTargetProfile, ID3DBlob **ppBlob) {
  1102. CW2A pEntryPointA(pEntryPoint, CP_UTF8);
  1103. CW2A pTargetProfileA(pTargetProfile, CP_UTF8);
  1104. CComPtr<ID3DBlob> pErrors;
  1105. D3D_SHADER_MACRO d3dMacro[2];
  1106. ZeroMemory(d3dMacro, sizeof(d3dMacro));
  1107. d3dMacro[0].Definition = "1";
  1108. d3dMacro[0].Name = "USING_DXBC";
  1109. HRESULT hr = D3DCompile(pText, strlen(pText), "hlsl.hlsl", d3dMacro, nullptr, pEntryPointA, pTargetProfileA, 0, 0, ppBlob, &pErrors);
  1110. if (pErrors != nullptr) {
  1111. CA2W errors((char *)pErrors->GetBufferPointer(), CP_ACP);
  1112. LogCommentFmt(L"Compilation failure: %s", errors.m_szBuffer);
  1113. }
  1114. VERIFY_SUCCEEDED(hr);
  1115. }
  1116. #endif
  1117. HRESULT EnableDebugLayer() {
  1118. // The debug layer does net yet validate DXIL programs that require rewriting,
  1119. // but basic logging should work properly.
  1120. HRESULT hr = S_FALSE;
  1121. if (UseDebugIfaces()) {
  1122. CComPtr<ID3D12Debug> debugController;
  1123. hr = D3D12GetDebugInterface(IID_PPV_ARGS(&debugController));
  1124. if (SUCCEEDED(hr)) {
  1125. debugController->EnableDebugLayer();
  1126. hr = S_OK;
  1127. }
  1128. }
  1129. return hr;
  1130. }
  1131. #ifndef _HLK_CONF
  1132. HRESULT EnableExperimentalMode() {
  1133. if (m_ExperimentalModeEnabled) {
  1134. return S_OK;
  1135. }
  1136. if (!GetTestParamBool(L"ExperimentalShaders")) {
  1137. return S_FALSE;
  1138. }
  1139. HRESULT hr = EnableExperimentalShaderModels();
  1140. if (SUCCEEDED(hr)) {
  1141. m_ExperimentalModeEnabled = true;
  1142. }
  1143. return hr;
  1144. }
  1145. #endif
  1146. struct FenceObj {
  1147. HANDLE m_fenceEvent = NULL;
  1148. CComPtr<ID3D12Fence> m_fence;
  1149. UINT64 m_fenceValue;
  1150. ~FenceObj() {
  1151. if (m_fenceEvent) CloseHandle(m_fenceEvent);
  1152. }
  1153. };
  1154. void InitFenceObj(ID3D12Device *pDevice, FenceObj *pObj) {
  1155. pObj->m_fenceValue = 1;
  1156. VERIFY_SUCCEEDED(pDevice->CreateFence(0, D3D12_FENCE_FLAG_NONE,
  1157. IID_PPV_ARGS(&pObj->m_fence)));
  1158. // Create an event handle to use for frame synchronization.
  1159. pObj->m_fenceEvent = CreateEvent(nullptr, FALSE, FALSE, nullptr);
  1160. if (pObj->m_fenceEvent == nullptr) {
  1161. VERIFY_SUCCEEDED(HRESULT_FROM_WIN32(GetLastError()));
  1162. }
  1163. }
  1164. void ReadHlslDataIntoNewStream(LPCWSTR relativePath, IStream **ppStream) {
  1165. VERIFY_SUCCEEDED(m_support.Initialize());
  1166. CComPtr<IDxcLibrary> pLibrary;
  1167. CComPtr<IDxcBlobEncoding> pBlob;
  1168. CComPtr<IStream> pStream;
  1169. std::wstring path = GetPathToHlslDataFile(relativePath);
  1170. VERIFY_SUCCEEDED(m_support.CreateInstance(CLSID_DxcLibrary, &pLibrary));
  1171. VERIFY_SUCCEEDED(pLibrary->CreateBlobFromFile(path.c_str(), nullptr, &pBlob));
  1172. VERIFY_SUCCEEDED(pLibrary->CreateStreamFromBlobReadOnly(pBlob, &pStream));
  1173. *ppStream = pStream.Detach();
  1174. }
  1175. void RecordRenderAndReadback(ID3D12GraphicsCommandList *pList,
  1176. ID3D12DescriptorHeap *pRtvHeap,
  1177. UINT rtvDescriptorSize,
  1178. UINT instanceCount,
  1179. D3D12_VERTEX_BUFFER_VIEW *pVertexBufferView,
  1180. ID3D12RootSignature *pRootSig,
  1181. ID3D12Resource *pRenderTarget,
  1182. ID3D12Resource *pReadBuffer) {
  1183. D3D12_RESOURCE_DESC rtDesc = pRenderTarget->GetDesc();
  1184. D3D12_VIEWPORT viewport;
  1185. D3D12_RECT scissorRect;
  1186. memset(&viewport, 0, sizeof(viewport));
  1187. viewport.Height = (float)rtDesc.Height;
  1188. viewport.Width = (float)rtDesc.Width;
  1189. viewport.MaxDepth = 1.0f;
  1190. memset(&scissorRect, 0, sizeof(scissorRect));
  1191. scissorRect.right = (long)rtDesc.Width;
  1192. scissorRect.bottom = rtDesc.Height;
  1193. if (pRootSig != nullptr) {
  1194. pList->SetGraphicsRootSignature(pRootSig);
  1195. }
  1196. pList->RSSetViewports(1, &viewport);
  1197. pList->RSSetScissorRects(1, &scissorRect);
  1198. // Indicate that the buffer will be used as a render target.
  1199. RecordTransitionBarrier(pList, pRenderTarget, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_RENDER_TARGET);
  1200. CD3DX12_CPU_DESCRIPTOR_HANDLE rtvHandle(pRtvHeap->GetCPUDescriptorHandleForHeapStart(), 0, rtvDescriptorSize);
  1201. pList->OMSetRenderTargets(1, &rtvHandle, FALSE, nullptr);
  1202. pList->ClearRenderTargetView(rtvHandle, ClearColor, 0, nullptr);
  1203. pList->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
  1204. pList->IASetVertexBuffers(0, 1, pVertexBufferView);
  1205. pList->DrawInstanced(3, instanceCount, 0, 0);
  1206. // Transition to copy source and copy into read-back buffer.
  1207. RecordTransitionBarrier(pList, pRenderTarget, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_COPY_SOURCE);
  1208. // Copy into read-back buffer.
  1209. UINT64 rowPitch = rtDesc.Width * 4;
  1210. if (rowPitch % D3D12_TEXTURE_DATA_PITCH_ALIGNMENT)
  1211. rowPitch += D3D12_TEXTURE_DATA_PITCH_ALIGNMENT - (rowPitch % D3D12_TEXTURE_DATA_PITCH_ALIGNMENT);
  1212. D3D12_PLACED_SUBRESOURCE_FOOTPRINT Footprint;
  1213. Footprint.Offset = 0;
  1214. Footprint.Footprint = CD3DX12_SUBRESOURCE_FOOTPRINT(DXGI_FORMAT_R8G8B8A8_UNORM, (UINT)rtDesc.Width, rtDesc.Height, 1, (UINT)rowPitch);
  1215. CD3DX12_TEXTURE_COPY_LOCATION DstLoc(pReadBuffer, Footprint);
  1216. CD3DX12_TEXTURE_COPY_LOCATION SrcLoc(pRenderTarget, 0);
  1217. pList->CopyTextureRegion(&DstLoc, 0, 0, 0, &SrcLoc, nullptr);
  1218. }
  1219. void RunRWByteBufferComputeTest(ID3D12Device *pDevice, LPCSTR shader, std::vector<uint32_t> &values);
  1220. void RunLifetimeIntrinsicTest(ID3D12Device *pDevice, LPCSTR shader, D3D_SHADER_MODEL shaderModel, bool useLibTarget, LPCWSTR *pOptions, int numOptions, std::vector<uint32_t> &values);
  1221. void RunLifetimeIntrinsicComputeTest(ID3D12Device *pDevice, LPCSTR pShader, CComPtr<ID3D12DescriptorHeap>& pUavHeap, CComPtr<ID3D12RootSignature>& pRootSignature,
  1222. LPCWSTR pTargetProfile, LPCWSTR *pOptions, int numOptions, std::vector<uint32_t> &values);
  1223. void RunLifetimeIntrinsicLibTest(ID3D12Device5 *pDevice, LPCSTR pShader, CComPtr<ID3D12RootSignature>& pRootSignature,
  1224. LPCWSTR pTargetProfile, LPCWSTR *pOptions, int numOptions);
  1225. void SetDescriptorHeap(ID3D12GraphicsCommandList *pCommandList, ID3D12DescriptorHeap *pHeap) {
  1226. ID3D12DescriptorHeap *const pHeaps[1] = { pHeap };
  1227. pCommandList->SetDescriptorHeaps(1, pHeaps);
  1228. }
  1229. void WaitForSignal(ID3D12CommandQueue *pCQ, FenceObj &FO) {
  1230. ::WaitForSignal(pCQ, FO.m_fence, FO.m_fenceEvent, FO.m_fenceValue++);
  1231. }
  1232. };
  1233. #define WAVE_INTRINSIC_DXBC_GUARD \
  1234. "#ifdef USING_DXBC\r\n" \
  1235. "uint WaveGetLaneIndex() { return 1; }\r\n" \
  1236. "uint WaveReadLaneFirst(uint u) { return u; }\r\n" \
  1237. "bool WaveIsFirstLane() { return true; }\r\n" \
  1238. "uint WaveGetLaneCount() { return 1; }\r\n" \
  1239. "uint WaveReadLaneAt(uint n, uint u) { return u; }\r\n" \
  1240. "bool WaveActiveAnyTrue(bool b) { return b; }\r\n" \
  1241. "bool WaveActiveAllTrue(bool b) { return false; }\r\n" \
  1242. "uint WaveActiveAllEqual(uint u) { return u; }\r\n" \
  1243. "uint4 WaveActiveBallot(bool b) { return 1; }\r\n" \
  1244. "uint WaveActiveCountBits(uint u) { return 1; }\r\n" \
  1245. "uint WaveActiveSum(uint u) { return 1; }\r\n" \
  1246. "uint WaveActiveProduct(uint u) { return 1; }\r\n" \
  1247. "uint WaveActiveBitAnd(uint u) { return 1; }\r\n" \
  1248. "uint WaveActiveBitOr(uint u) { return 1; }\r\n" \
  1249. "uint WaveActiveBitXor(uint u) { return 1; }\r\n" \
  1250. "uint WaveActiveMin(uint u) { return 1; }\r\n" \
  1251. "uint WaveActiveMax(uint u) { return 1; }\r\n" \
  1252. "uint WavePrefixCountBits(uint u) { return 1; }\r\n" \
  1253. "uint WavePrefixSum(uint u) { return 1; }\r\n" \
  1254. "uint WavePrefixProduct(uint u) { return 1; }\r\n" \
  1255. "uint QuadReadLaneAt(uint a, uint u) { return 1; }\r\n" \
  1256. "uint QuadReadAcrossX(uint u) { return 1; }\r\n" \
  1257. "uint QuadReadAcrossY(uint u) { return 1; }\r\n" \
  1258. "uint QuadReadAcrossDiagonal(uint u) { return 1; }\r\n" \
  1259. "#endif\r\n"
  1260. static void SetupComputeValuePattern(std::vector<uint32_t> &values,
  1261. size_t count) {
  1262. values.resize(count); // one element per dispatch group, in bytes
  1263. for (size_t i = 0; i < count; ++i) {
  1264. values[i] = (uint32_t)i;
  1265. }
  1266. }
  1267. bool ExecutionTest::ExecutionTestClassSetup() {
  1268. #ifdef _HLK_CONF
  1269. // TODO: Enabling the D3D driver verifier. Check out the logic in the D3DConf_12_Core test.
  1270. VERIFY_SUCCEEDED(m_support.Initialize());
  1271. m_UseWarp = hlsl_test::GetTestParamUseWARP(false);
  1272. m_EnableDebugLayer = hlsl_test::GetTestParamBool(L"DebugLayer");
  1273. if (m_EnableDebugLayer) {
  1274. EnableDebugLayer();
  1275. }
  1276. return true;
  1277. #else
  1278. HRESULT hr = EnableExperimentalMode();
  1279. if (FAILED(hr)) {
  1280. LogCommentFmt(L"Unable to enable shader experimental mode - 0x%08x.", hr);
  1281. }
  1282. else if (hr == S_FALSE) {
  1283. LogCommentFmt(L"Experimental mode not enabled.");
  1284. }
  1285. else {
  1286. LogCommentFmt(L"Experimental mode enabled.");
  1287. }
  1288. hr = EnableDebugLayer();
  1289. if (FAILED(hr)) {
  1290. LogCommentFmt(L"Unable to enable debug layer - 0x%08x.", hr);
  1291. }
  1292. else {
  1293. LogCommentFmt(L"Debug layer enabled.");
  1294. }
  1295. return true;
  1296. #endif
  1297. }
  1298. void ExecutionTest::RunRWByteBufferComputeTest(ID3D12Device *pDevice, LPCSTR pShader, std::vector<uint32_t> &values) {
  1299. static const int DispatchGroupX = 1;
  1300. static const int DispatchGroupY = 1;
  1301. static const int DispatchGroupZ = 1;
  1302. CComPtr<ID3D12GraphicsCommandList> pCommandList;
  1303. CComPtr<ID3D12CommandQueue> pCommandQueue;
  1304. CComPtr<ID3D12DescriptorHeap> pUavHeap;
  1305. CComPtr<ID3D12CommandAllocator> pCommandAllocator;
  1306. UINT uavDescriptorSize;
  1307. FenceObj FO;
  1308. const UINT valueSizeInBytes = (UINT)values.size() * sizeof(uint32_t);
  1309. CreateComputeCommandQueue(pDevice, L"RunRWByteBufferComputeTest Command Queue", &pCommandQueue);
  1310. InitFenceObj(pDevice, &FO);
  1311. // Describe and create a UAV descriptor heap.
  1312. D3D12_DESCRIPTOR_HEAP_DESC heapDesc = {};
  1313. heapDesc.NumDescriptors = 1;
  1314. heapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV;
  1315. heapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE;
  1316. VERIFY_SUCCEEDED(pDevice->CreateDescriptorHeap(&heapDesc, IID_PPV_ARGS(&pUavHeap)));
  1317. uavDescriptorSize = pDevice->GetDescriptorHandleIncrementSize(heapDesc.Type);
  1318. // Create root signature.
  1319. CComPtr<ID3D12RootSignature> pRootSignature;
  1320. {
  1321. CD3DX12_DESCRIPTOR_RANGE ranges[1];
  1322. ranges[0].Init(D3D12_DESCRIPTOR_RANGE_TYPE_UAV, 1, 0, 0, 0);
  1323. CD3DX12_ROOT_PARAMETER rootParameters[1];
  1324. rootParameters[0].InitAsDescriptorTable(1, &ranges[0], D3D12_SHADER_VISIBILITY_ALL);
  1325. CD3DX12_ROOT_SIGNATURE_DESC rootSignatureDesc;
  1326. rootSignatureDesc.Init(_countof(rootParameters), rootParameters, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE);
  1327. CreateRootSignatureFromDesc(pDevice, &rootSignatureDesc, &pRootSignature);
  1328. }
  1329. // Create pipeline state object.
  1330. CComPtr<ID3D12PipelineState> pComputeState;
  1331. CreateComputePSO(pDevice, pRootSignature, pShader, L"cs_6_0", &pComputeState);
  1332. // Create a command allocator and list for compute.
  1333. VERIFY_SUCCEEDED(pDevice->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_COMPUTE, IID_PPV_ARGS(&pCommandAllocator)));
  1334. VERIFY_SUCCEEDED(pDevice->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_COMPUTE, pCommandAllocator, pComputeState, IID_PPV_ARGS(&pCommandList)));
  1335. pCommandList->SetName(L"ExecutionTest::RunRWByteButterComputeTest Command List");
  1336. // Set up UAV resource.
  1337. CComPtr<ID3D12Resource> pUavResource;
  1338. CComPtr<ID3D12Resource> pReadBuffer;
  1339. CComPtr<ID3D12Resource> pUploadResource;
  1340. CreateTestUavs(pDevice, pCommandList, values.data(), valueSizeInBytes, &pUavResource, &pUploadResource, &pReadBuffer);
  1341. VERIFY_SUCCEEDED(pUavResource->SetName(L"RunRWByteBufferComputeText UAV"));
  1342. VERIFY_SUCCEEDED(pReadBuffer->SetName(L"RunRWByteBufferComputeText UAV Read Buffer"));
  1343. VERIFY_SUCCEEDED(pUploadResource->SetName(L"RunRWByteBufferComputeText UAV Upload Buffer"));
  1344. // Close the command list and execute it to perform the GPU setup.
  1345. pCommandList->Close();
  1346. ExecuteCommandList(pCommandQueue, pCommandList);
  1347. WaitForSignal(pCommandQueue, FO);
  1348. VERIFY_SUCCEEDED(pCommandAllocator->Reset());
  1349. VERIFY_SUCCEEDED(pCommandList->Reset(pCommandAllocator, pComputeState));
  1350. // Run the compute shader and copy the results back to readable memory.
  1351. {
  1352. D3D12_UNORDERED_ACCESS_VIEW_DESC uavDesc = {};
  1353. uavDesc.Format = DXGI_FORMAT_R32_TYPELESS;
  1354. uavDesc.ViewDimension = D3D12_UAV_DIMENSION_BUFFER;
  1355. uavDesc.Buffer.FirstElement = 0;
  1356. uavDesc.Buffer.NumElements = (UINT)values.size();
  1357. uavDesc.Buffer.StructureByteStride = 0;
  1358. uavDesc.Buffer.CounterOffsetInBytes = 0;
  1359. uavDesc.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_RAW;
  1360. CD3DX12_CPU_DESCRIPTOR_HANDLE uavHandle(pUavHeap->GetCPUDescriptorHandleForHeapStart());
  1361. CD3DX12_GPU_DESCRIPTOR_HANDLE uavHandleGpu(pUavHeap->GetGPUDescriptorHandleForHeapStart());
  1362. pDevice->CreateUnorderedAccessView(pUavResource, nullptr, &uavDesc, uavHandle);
  1363. SetDescriptorHeap(pCommandList, pUavHeap);
  1364. pCommandList->SetComputeRootSignature(pRootSignature);
  1365. pCommandList->SetComputeRootDescriptorTable(0, uavHandleGpu);
  1366. }
  1367. pCommandList->Dispatch(DispatchGroupX, DispatchGroupY, DispatchGroupZ);
  1368. RecordTransitionBarrier(pCommandList, pUavResource, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE);
  1369. pCommandList->CopyResource(pReadBuffer, pUavResource);
  1370. pCommandList->Close();
  1371. ExecuteCommandList(pCommandQueue, pCommandList);
  1372. WaitForSignal(pCommandQueue, FO);
  1373. {
  1374. MappedData mappedData(pReadBuffer, valueSizeInBytes);
  1375. uint32_t *pData = (uint32_t *)mappedData.data();
  1376. memcpy(values.data(), pData, (size_t)valueSizeInBytes);
  1377. }
  1378. WaitForSignal(pCommandQueue, FO);
  1379. }
  1380. void ExecutionTest::RunLifetimeIntrinsicComputeTest(ID3D12Device *pDevice, LPCSTR pShader, CComPtr<ID3D12DescriptorHeap>& pUavHeap, CComPtr<ID3D12RootSignature>& pRootSignature,
  1381. LPCWSTR pTargetProfile, LPCWSTR *pOptions, int numOptions, std::vector<uint32_t> &values) {
  1382. // Create command queue.
  1383. CComPtr<ID3D12CommandQueue> pCommandQueue;
  1384. CreateComputeCommandQueue(pDevice, L"RunLifetimeIntrinsicTest Command Queue", &pCommandQueue);
  1385. FenceObj FO;
  1386. InitFenceObj(pDevice, &FO);
  1387. // Compile shader "main" and create pipeline state object.
  1388. CComPtr<ID3D12PipelineState> pComputeState;
  1389. CreateComputePSO(pDevice, pRootSignature, pShader, pTargetProfile, &pComputeState, pOptions, numOptions);
  1390. // Create a command allocator and list for compute.
  1391. CComPtr<ID3D12CommandAllocator> pCommandAllocator;
  1392. CComPtr<ID3D12GraphicsCommandList> pCommandList;
  1393. VERIFY_SUCCEEDED(pDevice->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_COMPUTE, IID_PPV_ARGS(&pCommandAllocator)));
  1394. VERIFY_SUCCEEDED(pDevice->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_COMPUTE, pCommandAllocator, pComputeState, IID_PPV_ARGS(&pCommandList)));
  1395. pCommandList->SetName(L"ExecutionTest::RunLifetimeIntrinsicTest Command List");
  1396. // Set up UAV resource.
  1397. const UINT valueSizeInBytes = (UINT)values.size() * sizeof(uint32_t);
  1398. CComPtr<ID3D12Resource> pUavResource;
  1399. CComPtr<ID3D12Resource> pReadBuffer;
  1400. CComPtr<ID3D12Resource> pUploadResource;
  1401. CreateTestUavs(pDevice, pCommandList, values.data(), valueSizeInBytes, &pUavResource, &pUploadResource, &pReadBuffer);
  1402. VERIFY_SUCCEEDED(pUavResource->SetName(L"RunLifetimeIntrinsicTest UAV"));
  1403. VERIFY_SUCCEEDED(pReadBuffer->SetName(L"RunLifetimeIntrinsicTest UAV Read Buffer"));
  1404. VERIFY_SUCCEEDED(pUploadResource->SetName(L"RunLifetimeIntrinsicTest UAV Upload Buffer"));
  1405. // Close the command list and execute it to perform the GPU setup.
  1406. pCommandList->Close();
  1407. ExecuteCommandList(pCommandQueue, pCommandList);
  1408. WaitForSignal(pCommandQueue, FO);
  1409. VERIFY_SUCCEEDED(pCommandAllocator->Reset());
  1410. VERIFY_SUCCEEDED(pCommandList->Reset(pCommandAllocator, pComputeState));
  1411. // Run the compute shader and copy the results back to readable memory.
  1412. {
  1413. D3D12_UNORDERED_ACCESS_VIEW_DESC uavDesc = {};
  1414. uavDesc.Format = DXGI_FORMAT_R32_TYPELESS;
  1415. uavDesc.ViewDimension = D3D12_UAV_DIMENSION_BUFFER;
  1416. uavDesc.Buffer.FirstElement = 0;
  1417. uavDesc.Buffer.NumElements = (UINT)values.size();
  1418. uavDesc.Buffer.StructureByteStride = 0;
  1419. uavDesc.Buffer.CounterOffsetInBytes = 0;
  1420. uavDesc.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_RAW;
  1421. CD3DX12_CPU_DESCRIPTOR_HANDLE uavHandle(pUavHeap->GetCPUDescriptorHandleForHeapStart());
  1422. CD3DX12_GPU_DESCRIPTOR_HANDLE uavHandleGpu(pUavHeap->GetGPUDescriptorHandleForHeapStart());
  1423. pDevice->CreateUnorderedAccessView(pUavResource, nullptr, &uavDesc, uavHandle);
  1424. SetDescriptorHeap(pCommandList, pUavHeap);
  1425. pCommandList->SetComputeRootSignature(pRootSignature);
  1426. pCommandList->SetComputeRootDescriptorTable(0, uavHandleGpu);
  1427. }
  1428. static const int DispatchGroupX = 1;
  1429. static const int DispatchGroupY = 1;
  1430. static const int DispatchGroupZ = 1;
  1431. pCommandList->Dispatch(DispatchGroupX, DispatchGroupY, DispatchGroupZ);
  1432. RecordTransitionBarrier(pCommandList, pUavResource, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE);
  1433. pCommandList->CopyResource(pReadBuffer, pUavResource);
  1434. pCommandList->Close();
  1435. ExecuteCommandList(pCommandQueue, pCommandList);
  1436. WaitForSignal(pCommandQueue, FO);
  1437. {
  1438. MappedData mappedData(pReadBuffer, valueSizeInBytes);
  1439. uint32_t *pData = (uint32_t *)mappedData.data();
  1440. memcpy(values.data(), pData, (size_t)valueSizeInBytes);
  1441. }
  1442. WaitForSignal(pCommandQueue, FO);
  1443. }
  1444. void ExecutionTest::RunLifetimeIntrinsicLibTest(ID3D12Device5 *pDevice, LPCSTR pShader, CComPtr<ID3D12RootSignature>& pRootSignature,
  1445. LPCWSTR pTargetProfile, LPCWSTR *pOptions, int numOptions) {
  1446. // Create command queue.
  1447. CComPtr<ID3D12CommandQueue> pCommandQueue;
  1448. CreateCommandQueue(pDevice, L"RunLifetimeIntrinsicTest Command Queue", &pCommandQueue, D3D12_COMMAND_LIST_TYPE_DIRECT);
  1449. FenceObj FO;
  1450. InitFenceObj(pDevice, &FO);
  1451. // Compile raygen shader.
  1452. CComPtr<ID3DBlob> pShaderLib;
  1453. CompileFromText(pShader, L"RayGen", pTargetProfile, &pShaderLib, pOptions, numOptions);
  1454. // Describe and create the RT pipeline state object (RTPSO).
  1455. CD3DX12_STATE_OBJECT_DESC stateObjectDesc(D3D12_STATE_OBJECT_TYPE_RAYTRACING_PIPELINE);
  1456. auto lib = stateObjectDesc.CreateSubobject<CD3DX12_DXIL_LIBRARY_SUBOBJECT>();
  1457. CD3DX12_SHADER_BYTECODE byteCode(pShaderLib);
  1458. lib->SetDXILLibrary(&byteCode);
  1459. lib->DefineExport(L"RayGen");
  1460. const int payloadCount = 4;
  1461. const int attributeCount = 2;
  1462. const int maxRecursion = 2;
  1463. stateObjectDesc.CreateSubobject<CD3DX12_RAYTRACING_SHADER_CONFIG_SUBOBJECT>()->Config(payloadCount * sizeof(float), attributeCount * sizeof(float));
  1464. stateObjectDesc.CreateSubobject<CD3DX12_RAYTRACING_PIPELINE_CONFIG_SUBOBJECT>()->Config(maxRecursion);
  1465. // Create (local!) root sig subobject and associate with shader.
  1466. auto localRootSigSubObj = stateObjectDesc.CreateSubobject<CD3DX12_LOCAL_ROOT_SIGNATURE_SUBOBJECT>();
  1467. localRootSigSubObj->SetRootSignature(pRootSignature);
  1468. auto x = stateObjectDesc.CreateSubobject<CD3DX12_SUBOBJECT_TO_EXPORTS_ASSOCIATION_SUBOBJECT>();
  1469. x->SetSubobjectToAssociate(*localRootSigSubObj);
  1470. x->AddExport(L"RayGen");
  1471. CComPtr<ID3D12StateObject> pStateObject;
  1472. VERIFY_SUCCEEDED(pDevice->CreateStateObject(stateObjectDesc, IID_PPV_ARGS(&pStateObject)));
  1473. // Create a command allocator and list.
  1474. CComPtr<ID3D12CommandAllocator> pCommandAllocator;
  1475. CComPtr<ID3D12GraphicsCommandList4> pCommandList;
  1476. VERIFY_SUCCEEDED(pDevice->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&pCommandAllocator)));
  1477. VERIFY_SUCCEEDED(pDevice->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, pCommandAllocator, nullptr, IID_PPV_ARGS(&pCommandList)));
  1478. pCommandList->SetPipelineState1(pStateObject);
  1479. pCommandList->SetName(L"ExecutionTest::RunLifetimeIntrinsicTest Command List");
  1480. // Close the command list and execute it to kick-off compilation in the driver.
  1481. // NOTE: We don't care about anything else, so we're not setting up any resources and don't actually execute the shader.
  1482. pCommandList->Close();
  1483. ExecuteCommandList(pCommandQueue, pCommandList);
  1484. WaitForSignal(pCommandQueue, FO);
  1485. }
  1486. void ExecutionTest::RunLifetimeIntrinsicTest(ID3D12Device *pDevice, LPCSTR pShader, D3D_SHADER_MODEL shaderModel, bool useLibTarget,
  1487. LPCWSTR *pOptions, int numOptions, std::vector<uint32_t> &values) {
  1488. LPCWSTR pTargetProfile;
  1489. switch (shaderModel) {
  1490. default: pTargetProfile = useLibTarget ? L"lib_6_3" : L"cs_6_0"; break; // Default to 6.3 for lib, 6.0 otherwise.
  1491. case D3D_SHADER_MODEL_6_0: pTargetProfile = useLibTarget ? L"lib_6_0" : L"cs_6_0"; break;
  1492. case D3D_SHADER_MODEL_6_3: pTargetProfile = useLibTarget ? L"lib_6_3" : L"cs_6_3"; break;
  1493. case D3D_SHADER_MODEL_6_5: pTargetProfile = useLibTarget ? L"lib_6_5" : L"cs_6_5"; break;
  1494. case D3D_SHADER_MODEL_6_6: pTargetProfile = useLibTarget ? L"lib_6_6" : L"cs_6_6"; break;
  1495. }
  1496. // Describe a UAV descriptor heap.
  1497. D3D12_DESCRIPTOR_HEAP_DESC heapDesc = {};
  1498. heapDesc.NumDescriptors = 1;
  1499. heapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV;
  1500. heapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE;
  1501. // Create the UAV descriptor heap.
  1502. CComPtr<ID3D12DescriptorHeap> pUavHeap;
  1503. VERIFY_SUCCEEDED(pDevice->CreateDescriptorHeap(&heapDesc, IID_PPV_ARGS(&pUavHeap)));
  1504. // Create root signature.
  1505. CComPtr<ID3D12RootSignature> pRootSignature;
  1506. {
  1507. CD3DX12_DESCRIPTOR_RANGE ranges[1];
  1508. ranges[0].Init(D3D12_DESCRIPTOR_RANGE_TYPE_UAV, 1, 0, 0, 0);
  1509. CD3DX12_ROOT_PARAMETER rootParameters[1];
  1510. rootParameters[0].InitAsDescriptorTable(1, &ranges[0], D3D12_SHADER_VISIBILITY_ALL);
  1511. CD3DX12_ROOT_SIGNATURE_DESC rootSignatureDesc;
  1512. D3D12_ROOT_SIGNATURE_FLAGS rootSigFlag = useLibTarget ? D3D12_ROOT_SIGNATURE_FLAG_LOCAL_ROOT_SIGNATURE : D3D12_ROOT_SIGNATURE_FLAG_NONE;
  1513. rootSignatureDesc.Init(_countof(rootParameters), rootParameters, 0, nullptr, rootSigFlag);
  1514. CreateRootSignatureFromDesc(pDevice, &rootSignatureDesc, &pRootSignature);
  1515. }
  1516. if (useLibTarget)
  1517. RunLifetimeIntrinsicLibTest(reinterpret_cast<ID3D12Device5*>(pDevice), pShader, pRootSignature, pTargetProfile, pOptions, numOptions);
  1518. else
  1519. RunLifetimeIntrinsicComputeTest(pDevice, pShader, pUavHeap, pRootSignature, pTargetProfile, pOptions, numOptions, values);
  1520. }
  1521. TEST_F(ExecutionTest, LifetimeIntrinsicTest) {
  1522. // The only thing we test here is that existence of lifetime intrinsics or
  1523. // their fallback replacement (store undef or store zeroinitializer) do not
  1524. // cause any issues in the runtime and driver stack.
  1525. // The easiest way to force placement of intrinsics is to create an array in
  1526. // a local scope that is dynamically indexed. It must not be optimized away,
  1527. // so we do some bogus initialization that prevents this. Since all the code
  1528. // is guarded by a conditional that is dynamically always false, the actual
  1529. // effect of the shader is that the same value that was read is written back.
  1530. static const char* pShader = R"(
  1531. RWByteAddressBuffer g_bab : register(u0);
  1532. void fn(uint GI) {
  1533. const uint addr = GI * 4;
  1534. const int val = g_bab.Load(addr);
  1535. int res = val;
  1536. if (val < 0) { // Never true.
  1537. int arr[200];
  1538. for (int i = 0; i < 200; ++i) {
  1539. arr[i] = arr[val - i];
  1540. }
  1541. res += arr[val];
  1542. }
  1543. g_bab.Store(addr, (uint)res);
  1544. }
  1545. [numthreads(8,8,1)]
  1546. void main(uint GI : SV_GroupIndex) {
  1547. fn(GI);
  1548. }
  1549. [shader("raygeneration")]
  1550. void RayGen() {
  1551. const uint d = DispatchRaysIndex().x;
  1552. const uint g = g > 64 ? 63 : g;
  1553. fn(g);
  1554. }
  1555. )";
  1556. static const int NumThreadsX = 8;
  1557. static const int NumThreadsY = 8;
  1558. static const int NumThreadsZ = 1;
  1559. static const int ThreadsPerGroup = NumThreadsX * NumThreadsY * NumThreadsZ;
  1560. static const int DispatchGroupCount = 1;
  1561. // TODO: There's probably a lot of things in the rest of this test that could be stripped away.
  1562. CComPtr<ID3D12Device5> pDevice;
  1563. if (!CreateDevice(reinterpret_cast<ID3D12Device**>(&pDevice), D3D_SHADER_MODEL_6_6, true, true)) {
  1564. WEX::Logging::Log::Comment(L"Lifetime test not run pre 6.6");
  1565. WEX::Logging::Log::Result(WEX::Logging::TestResults::Skipped);
  1566. return;
  1567. }
  1568. std::vector<uint32_t> values;
  1569. SetupComputeValuePattern(values, ThreadsPerGroup * DispatchGroupCount);
  1570. // Run a number of tests for different configurations that will cause
  1571. // lifetime intrinsics to be placed directly, be replaced by a zeroinitializer
  1572. // store, or be replaced by an undef store.
  1573. LPCWSTR pOptions15[] = {L"/validator-version 1.5"};
  1574. LPCWSTR pOptions16[] = {L"/validator-version 1.6", L"/Vd"};
  1575. VERIFY_ARE_EQUAL(values[1], (uint32_t)1);
  1576. // Test regular shader with zeroinitializer store.
  1577. RunLifetimeIntrinsicTest(pDevice, pShader, D3D_SHADER_MODEL_6_0, false, pOptions15, _countof(pOptions15), values);
  1578. VERIFY_ARE_EQUAL(values[1], (uint32_t)1);
  1579. if (DoesDeviceSupportRayTracing(pDevice)) {
  1580. // Test library with zeroinitializer store.
  1581. RunLifetimeIntrinsicTest(pDevice, pShader, D3D_SHADER_MODEL_6_3, true, pOptions15, _countof(pOptions15), values);
  1582. VERIFY_ARE_EQUAL(values[1], (uint32_t)1);
  1583. }
  1584. // Testing SM 6.6 and validator version 1.6 requires experimental shaders
  1585. // being turned on.
  1586. if (!m_ExperimentalModeEnabled)
  1587. return;
  1588. // Test regular shader with undef store.
  1589. RunLifetimeIntrinsicTest(pDevice, pShader, D3D_SHADER_MODEL_6_0, false, pOptions16, _countof(pOptions16), values);
  1590. VERIFY_ARE_EQUAL(values[1], (uint32_t)1);
  1591. if (DoesDeviceSupportRayTracing(pDevice)) {
  1592. // Test library with undef store.
  1593. RunLifetimeIntrinsicTest(pDevice, pShader, D3D_SHADER_MODEL_6_3, true, pOptions16, _countof(pOptions16), values);
  1594. VERIFY_ARE_EQUAL(values[1], (uint32_t)1);
  1595. }
  1596. // Test regular shader with lifetime intrinsics.
  1597. RunLifetimeIntrinsicTest(pDevice, pShader, D3D_SHADER_MODEL_6_5, false, pOptions16, _countof(pOptions16), values); // TODO: Test 6.6 here!
  1598. VERIFY_ARE_EQUAL(values[1], (uint32_t)1);
  1599. if (DoesDeviceSupportRayTracing(pDevice)) {
  1600. // Test library with lifetime intrinsics.
  1601. RunLifetimeIntrinsicTest(pDevice, pShader, D3D_SHADER_MODEL_6_5, true, pOptions16, _countof(pOptions16), values); // TODO: Test 6.6 here!
  1602. VERIFY_ARE_EQUAL(values[1], (uint32_t)1);
  1603. }
  1604. }
  1605. TEST_F(ExecutionTest, BasicComputeTest) {
  1606. #ifndef _HLK_CONF
  1607. //
  1608. // BasicComputeTest is a simple compute shader that can be used as the basis
  1609. // for more interesting compute execution tests.
  1610. // The HLSL is compatible with shader models <=5.1 to allow using the DXBC
  1611. // rendering code paths for comparison.
  1612. //
  1613. static const char pShader[] =
  1614. "RWByteAddressBuffer g_bab : register(u0);\r\n"
  1615. "[numthreads(8,8,1)]\r\n"
  1616. "void main(uint GI : SV_GroupIndex) {"
  1617. " uint addr = GI * 4;\r\n"
  1618. " uint val = g_bab.Load(addr);\r\n"
  1619. " DeviceMemoryBarrierWithGroupSync();\r\n"
  1620. " g_bab.Store(addr, val + 1);\r\n"
  1621. "}";
  1622. static const int NumThreadsX = 8;
  1623. static const int NumThreadsY = 8;
  1624. static const int NumThreadsZ = 1;
  1625. static const int ThreadsPerGroup = NumThreadsX * NumThreadsY * NumThreadsZ;
  1626. static const int DispatchGroupCount = 1;
  1627. CComPtr<ID3D12Device> pDevice;
  1628. if (!CreateDevice(&pDevice))
  1629. return;
  1630. std::vector<uint32_t> values;
  1631. SetupComputeValuePattern(values, ThreadsPerGroup * DispatchGroupCount);
  1632. VERIFY_ARE_EQUAL(values[0], (uint32_t)0);
  1633. RunRWByteBufferComputeTest(pDevice, pShader, values);
  1634. VERIFY_ARE_EQUAL(values[0], (uint32_t)1);
  1635. #endif
  1636. }
  1637. TEST_F(ExecutionTest, BasicTriangleTest) {
  1638. #ifndef _HLK_CONF
  1639. static const UINT FrameCount = 2;
  1640. static const UINT m_width = 320;
  1641. static const UINT m_height = 200;
  1642. static const float m_aspectRatio = static_cast<float>(m_width) / static_cast<float>(m_height);
  1643. struct Vertex {
  1644. XMFLOAT3 position;
  1645. XMFLOAT4 color;
  1646. };
  1647. // Pipeline objects.
  1648. CComPtr<ID3D12Device> pDevice;
  1649. CComPtr<ID3D12Resource> pRenderTarget;
  1650. CComPtr<ID3D12CommandAllocator> pCommandAllocator;
  1651. CComPtr<ID3D12CommandQueue> pCommandQueue;
  1652. CComPtr<ID3D12RootSignature> pRootSig;
  1653. CComPtr<ID3D12DescriptorHeap> pRtvHeap;
  1654. CComPtr<ID3D12PipelineState> pPipelineState;
  1655. CComPtr<ID3D12GraphicsCommandList> pCommandList;
  1656. CComPtr<ID3D12Resource> pReadBuffer;
  1657. UINT rtvDescriptorSize;
  1658. CComPtr<ID3D12Resource> pVertexBuffer;
  1659. D3D12_VERTEX_BUFFER_VIEW vertexBufferView;
  1660. // Synchronization objects.
  1661. FenceObj FO;
  1662. // Shaders.
  1663. static const char pShaders[] =
  1664. "struct PSInput {\r\n"
  1665. " float4 position : SV_POSITION;\r\n"
  1666. " float4 color : COLOR;\r\n"
  1667. "};\r\n\r\n"
  1668. "PSInput VSMain(float4 position : POSITION, float4 color : COLOR) {\r\n"
  1669. " PSInput result;\r\n"
  1670. "\r\n"
  1671. " result.position = position;\r\n"
  1672. " result.color = color;\r\n"
  1673. " return result;\r\n"
  1674. "}\r\n\r\n"
  1675. "float4 PSMain(PSInput input) : SV_TARGET {\r\n"
  1676. " return 1; //input.color;\r\n"
  1677. "};\r\n";
  1678. if (!CreateDevice(&pDevice))
  1679. return;
  1680. struct BasicTestChecker {
  1681. CComPtr<ID3D12Device> m_pDevice;
  1682. CComPtr<ID3D12InfoQueue> m_pInfoQueue;
  1683. bool m_OK = false;
  1684. void SetOK(bool value) { m_OK = value; }
  1685. BasicTestChecker(ID3D12Device *pDevice) : m_pDevice(pDevice) {
  1686. if (FAILED(m_pDevice.QueryInterface(&m_pInfoQueue)))
  1687. return;
  1688. m_pInfoQueue->PushEmptyStorageFilter();
  1689. m_pInfoQueue->PushEmptyRetrievalFilter();
  1690. }
  1691. ~BasicTestChecker() {
  1692. if (!m_OK && m_pInfoQueue != nullptr) {
  1693. UINT64 count = m_pInfoQueue->GetNumStoredMessages();
  1694. bool invalidBytecodeFound = false;
  1695. CAtlArray<BYTE> m_pBytes;
  1696. for (UINT64 i = 0; i < count; ++i) {
  1697. SIZE_T len = 0;
  1698. if (FAILED(m_pInfoQueue->GetMessageA(i, nullptr, &len)))
  1699. continue;
  1700. if (m_pBytes.GetCount() < len && !m_pBytes.SetCount(len))
  1701. continue;
  1702. D3D12_MESSAGE *pMsg = (D3D12_MESSAGE *)m_pBytes.GetData();
  1703. if (FAILED(m_pInfoQueue->GetMessageA(i, pMsg, &len)))
  1704. continue;
  1705. if (pMsg->ID == D3D12_MESSAGE_ID_CREATEVERTEXSHADER_INVALIDSHADERBYTECODE ||
  1706. pMsg->ID == D3D12_MESSAGE_ID_CREATEPIXELSHADER_INVALIDSHADERBYTECODE) {
  1707. invalidBytecodeFound = true;
  1708. break;
  1709. }
  1710. }
  1711. if (invalidBytecodeFound) {
  1712. LogCommentFmt(L"%s", L"Found an invalid bytecode message. This "
  1713. L"typically indicates that experimental mode "
  1714. L"is not set up properly.");
  1715. if (!GetTestParamBool(L"ExperimentalShaders")) {
  1716. LogCommentFmt(L"Note that the ExperimentalShaders test parameter isn't set.");
  1717. }
  1718. }
  1719. else {
  1720. LogCommentFmt(L"Did not find corrupt pixel or vertex shaders in "
  1721. L"queue - dumping complete queue.");
  1722. WriteInfoQueueMessages(nullptr, OutputFn, m_pInfoQueue);
  1723. }
  1724. }
  1725. }
  1726. static void __stdcall OutputFn(void *pCtx, const wchar_t *pMsg) {
  1727. UNREFERENCED_PARAMETER(pCtx);
  1728. LogCommentFmt(L"%s", pMsg);
  1729. }
  1730. };
  1731. BasicTestChecker BTC(pDevice);
  1732. {
  1733. InitFenceObj(pDevice, &FO);
  1734. CreateRtvDescriptorHeap(pDevice, FrameCount, &pRtvHeap, &rtvDescriptorSize);
  1735. CreateRenderTargetAndReadback(pDevice, pRtvHeap, m_width, m_height, &pRenderTarget, &pReadBuffer);
  1736. // Create an empty root signature.
  1737. CD3DX12_ROOT_SIGNATURE_DESC rootSignatureDesc;
  1738. rootSignatureDesc.Init(
  1739. 0, nullptr, 0, nullptr,
  1740. D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT);
  1741. CreateRootSignatureFromDesc(pDevice, &rootSignatureDesc, &pRootSig);
  1742. // Create the pipeline state, which includes compiling and loading shaders.
  1743. // Define the vertex input layout.
  1744. D3D12_INPUT_ELEMENT_DESC inputElementDescs[] = {
  1745. {"POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0,
  1746. D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0},
  1747. {"COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 12,
  1748. D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0}};
  1749. D3D12_INPUT_LAYOUT_DESC InputLayout = { inputElementDescs, _countof(inputElementDescs) };
  1750. CreateGraphicsPSO(pDevice, &InputLayout, pRootSig, pShaders, &pPipelineState);
  1751. CreateGraphicsCommandQueueAndList(pDevice, &pCommandQueue,
  1752. &pCommandAllocator, &pCommandList,
  1753. pPipelineState);
  1754. // Define the geometry for a triangle.
  1755. Vertex triangleVertices[] = {
  1756. { { 0.0f, 0.25f * m_aspectRatio, 0.0f },{ 1.0f, 0.0f, 0.0f, 1.0f } },
  1757. { { 0.25f, -0.25f * m_aspectRatio, 0.0f },{ 0.0f, 1.0f, 0.0f, 1.0f } },
  1758. { { -0.25f, -0.25f * m_aspectRatio, 0.0f },{ 0.0f, 0.0f, 1.0f, 1.0f } } };
  1759. CreateVertexBuffer(pDevice, triangleVertices, &pVertexBuffer, &vertexBufferView);
  1760. WaitForSignal(pCommandQueue, FO);
  1761. }
  1762. // Render and execute the command list.
  1763. RecordRenderAndReadback(pCommandList, pRtvHeap, rtvDescriptorSize, 1,
  1764. &vertexBufferView, pRootSig, pRenderTarget,
  1765. pReadBuffer);
  1766. VERIFY_SUCCEEDED(pCommandList->Close());
  1767. ExecuteCommandList(pCommandQueue, pCommandList);
  1768. // Wait for previous frame.
  1769. WaitForSignal(pCommandQueue, FO);
  1770. // At this point, we've verified that execution succeeded with DXIL.
  1771. BTC.SetOK(true);
  1772. // Read back to CPU and examine contents.
  1773. {
  1774. MappedData data(pReadBuffer, m_width * m_height * 4);
  1775. const uint32_t *pPixels = (uint32_t *)data.data();
  1776. if (SaveImages()) {
  1777. SavePixelsToFile(pPixels, DXGI_FORMAT_R8G8B8A8_UNORM, m_width, m_height, L"basic.bmp");
  1778. }
  1779. uint32_t top = pPixels[m_width / 2]; // Top center.
  1780. uint32_t mid = pPixels[m_width / 2 + m_width * (m_height / 2)]; // Middle center.
  1781. VERIFY_ARE_EQUAL(0xff663300, top); // clear color
  1782. VERIFY_ARE_EQUAL(0xffffffff, mid); // white
  1783. }
  1784. #endif
  1785. }
  1786. TEST_F(ExecutionTest, Int64Test) {
  1787. static const char pShader[] =
  1788. "RWByteAddressBuffer g_bab : register(u0);\r\n"
  1789. "[numthreads(8,8,1)]\r\n"
  1790. "void main(uint GI : SV_GroupIndex) {"
  1791. " uint addr = GI * 4;\r\n"
  1792. " uint val = g_bab.Load(addr);\r\n"
  1793. " uint64_t u64 = val;\r\n"
  1794. " u64 *= val;\r\n"
  1795. " g_bab.Store(addr, (uint)(u64 >> 32));\r\n"
  1796. "}";
  1797. static const int NumThreadsX = 8;
  1798. static const int NumThreadsY = 8;
  1799. static const int NumThreadsZ = 1;
  1800. static const int ThreadsPerGroup = NumThreadsX * NumThreadsY * NumThreadsZ;
  1801. static const int DispatchGroupCount = 1;
  1802. CComPtr<ID3D12Device> pDevice;
  1803. if (!CreateDevice(&pDevice))
  1804. return;
  1805. if (!DoesDeviceSupportInt64(pDevice)) {
  1806. // Optional feature, so it's correct to not support it if declared as such.
  1807. WEX::Logging::Log::Comment(L"Device does not support int64 operations.");
  1808. return;
  1809. }
  1810. std::vector<uint32_t> values;
  1811. SetupComputeValuePattern(values, ThreadsPerGroup * DispatchGroupCount);
  1812. VERIFY_ARE_EQUAL(values[0], (uint32_t)0);
  1813. RunRWByteBufferComputeTest(pDevice, pShader, values);
  1814. VERIFY_ARE_EQUAL(values[0], (uint32_t)0);
  1815. }
  1816. TEST_F(ExecutionTest, SignTest) {
  1817. static const char pShader[] =
  1818. "RWByteAddressBuffer g_bab : register(u0);\r\n"
  1819. "[numthreads(8,1,1)]\r\n"
  1820. "void main(uint GI : SV_GroupIndex) {"
  1821. " uint addr = GI * 4;\r\n"
  1822. " int val = g_bab.Load(addr);\r\n"
  1823. " g_bab.Store(addr, (uint)(sign(val)));\r\n"
  1824. "}";
  1825. static const int NumThreadsX = 8;
  1826. static const int NumThreadsY = 1;
  1827. static const int NumThreadsZ = 1;
  1828. static const int ThreadsPerGroup = NumThreadsX * NumThreadsY * NumThreadsZ;
  1829. static const int DispatchGroupCount = 1;
  1830. CComPtr<ID3D12Device> pDevice;
  1831. if (!CreateDevice(&pDevice))
  1832. return;
  1833. const uint32_t neg1 = (uint32_t)-1;
  1834. uint32_t origValues[] = { (uint32_t)-3, (uint32_t)-2, neg1, 0, 1, 2, 3, 4 };
  1835. std::vector<uint32_t> values(origValues, origValues + _countof(origValues));
  1836. RunRWByteBufferComputeTest(pDevice, pShader, values);
  1837. VERIFY_ARE_EQUAL(values[0], neg1);
  1838. VERIFY_ARE_EQUAL(values[1], neg1);
  1839. VERIFY_ARE_EQUAL(values[2], neg1);
  1840. VERIFY_ARE_EQUAL(values[3], (uint32_t)0);
  1841. VERIFY_ARE_EQUAL(values[4], (uint32_t)1);
  1842. VERIFY_ARE_EQUAL(values[5], (uint32_t)1);
  1843. VERIFY_ARE_EQUAL(values[6], (uint32_t)1);
  1844. VERIFY_ARE_EQUAL(values[7], (uint32_t)1);
  1845. }
  1846. TEST_F(ExecutionTest, WaveIntrinsicsDDITest) {
  1847. #ifndef _HLK_CONF
  1848. CComPtr<ID3D12Device> pDevice;
  1849. if (!CreateDevice(&pDevice))
  1850. return;
  1851. D3D12_FEATURE_DATA_D3D12_OPTIONS1 O;
  1852. if (FAILED(pDevice->CheckFeatureSupport((D3D12_FEATURE)D3D12_FEATURE_D3D12_OPTIONS1, &O, sizeof(O))))
  1853. return;
  1854. bool waveSupported = O.WaveOps;
  1855. UINT laneCountMin = O.WaveLaneCountMin;
  1856. UINT laneCountMax = O.WaveLaneCountMax;
  1857. LogCommentFmt(L"WaveOps %i, WaveLaneCountMin %u, WaveLaneCountMax %u", waveSupported, laneCountMin, laneCountMax);
  1858. VERIFY_IS_TRUE(laneCountMin <= laneCountMax);
  1859. if (waveSupported) {
  1860. VERIFY_IS_TRUE(laneCountMin > 0 && laneCountMax > 0);
  1861. }
  1862. else {
  1863. VERIFY_IS_TRUE(laneCountMin == 0 && laneCountMax == 0);
  1864. }
  1865. #endif
  1866. }
  1867. TEST_F(ExecutionTest, WaveIntrinsicsTest) {
  1868. #ifndef _HLK_CONF
  1869. WEX::TestExecution::SetVerifyOutput verifySettings(WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  1870. struct PerThreadData {
  1871. uint32_t id, flags, laneIndex, laneCount, firstLaneId, preds, firstlaneX, lane1X;
  1872. uint32_t allBC, allSum, allProd, allAND, allOR, allXOR, allMin, allMax;
  1873. uint32_t pfBC, pfSum, pfProd;
  1874. uint32_t ballot[4];
  1875. uint32_t diver; // divergent value, used in calculation
  1876. int32_t i_diver; // divergent value, used in calculation
  1877. int32_t i_allMax, i_allMin, i_allSum, i_allProd;
  1878. int32_t i_pfSum, i_pfProd;
  1879. };
  1880. static const char pShader[] =
  1881. WAVE_INTRINSIC_DXBC_GUARD
  1882. "struct PerThreadData {\r\n"
  1883. " uint id, flags, laneIndex, laneCount, firstLaneId, preds, firstlaneX, lane1X;\r\n"
  1884. " uint allBC, allSum, allProd, allAND, allOR, allXOR, allMin, allMax;\r\n"
  1885. " uint pfBC, pfSum, pfProd;\r\n"
  1886. " uint4 ballot;\r\n"
  1887. " uint diver;\r\n"
  1888. " int i_diver;\r\n"
  1889. " int i_allMax, i_allMin, i_allSum, i_allProd;\r\n"
  1890. " int i_pfSum, i_pfProd;\r\n"
  1891. "};\r\n"
  1892. "RWStructuredBuffer<PerThreadData> g_sb : register(u0);\r\n"
  1893. "[numthreads(8,8,1)]\r\n"
  1894. "void main(uint GI : SV_GroupIndex, uint3 GTID : SV_GroupThreadID) {"
  1895. " PerThreadData pts = g_sb[GI];\r\n"
  1896. " uint diver = GTID.x + 2;\r\n"
  1897. " pts.diver = diver;\r\n"
  1898. " pts.flags = 0;\r\n"
  1899. " pts.preds = 0;\r\n"
  1900. " if (WaveIsFirstLane()) pts.flags |= 1;\r\n"
  1901. " pts.laneIndex = WaveGetLaneIndex();\r\n"
  1902. " pts.laneCount = WaveGetLaneCount();\r\n"
  1903. " pts.firstLaneId = WaveReadLaneFirst(pts.id);\r\n"
  1904. " pts.preds |= ((WaveActiveAnyTrue(diver == 1) ? 1 : 0) << 0);\r\n"
  1905. " pts.preds |= ((WaveActiveAllTrue(diver == 1) ? 1 : 0) << 1);\r\n"
  1906. " pts.preds |= ((WaveActiveAllEqual(diver) ? 1 : 0) << 2);\r\n"
  1907. " pts.preds |= ((WaveActiveAllEqual(GTID.z) ? 1 : 0) << 3);\r\n"
  1908. " pts.preds |= ((WaveActiveAllEqual(WaveReadLaneFirst(diver)) ? 1 : 0) << 4);\r\n"
  1909. " pts.ballot = WaveActiveBallot(diver > 3);\r\n"
  1910. " pts.firstlaneX = WaveReadLaneFirst(GTID.x);\r\n"
  1911. " pts.lane1X = WaveReadLaneAt(GTID.x, 1);\r\n"
  1912. "\r\n"
  1913. " pts.allBC = WaveActiveCountBits(diver > 3);\r\n"
  1914. " pts.allSum = WaveActiveSum(diver);\r\n"
  1915. " pts.allProd = WaveActiveProduct(diver);\r\n"
  1916. " pts.allAND = WaveActiveBitAnd(diver);\r\n"
  1917. " pts.allOR = WaveActiveBitOr(diver);\r\n"
  1918. " pts.allXOR = WaveActiveBitXor(diver);\r\n"
  1919. " pts.allMin = WaveActiveMin(diver);\r\n"
  1920. " pts.allMax = WaveActiveMax(diver);\r\n"
  1921. "\r\n"
  1922. " pts.pfBC = WavePrefixCountBits(diver > 3);\r\n"
  1923. " pts.pfSum = WavePrefixSum(diver);\r\n"
  1924. " pts.pfProd = WavePrefixProduct(diver);\r\n"
  1925. "\r\n"
  1926. " int i_diver = pts.i_diver;\r\n"
  1927. " pts.i_allMax = WaveActiveMax(i_diver);\r\n"
  1928. " pts.i_allMin = WaveActiveMin(i_diver);\r\n"
  1929. " pts.i_allSum = WaveActiveSum(i_diver);\r\n"
  1930. " pts.i_allProd = WaveActiveProduct(i_diver);\r\n"
  1931. " pts.i_pfSum = WavePrefixSum(i_diver);\r\n"
  1932. " pts.i_pfProd = WavePrefixProduct(i_diver);\r\n"
  1933. "\r\n"
  1934. " g_sb[GI] = pts;\r\n"
  1935. "}";
  1936. static const int NumtheadsX = 8;
  1937. static const int NumtheadsY = 8;
  1938. static const int NumtheadsZ = 1;
  1939. static const int ThreadsPerGroup = NumtheadsX * NumtheadsY * NumtheadsZ;
  1940. static const int DispatchGroupCount = 1;
  1941. CComPtr<ID3D12Device> pDevice;
  1942. if (!CreateDevice(&pDevice))
  1943. return;
  1944. if (!DoesDeviceSupportWaveOps(pDevice)) {
  1945. // Optional feature, so it's correct to not support it if declared as such.
  1946. WEX::Logging::Log::Comment(L"Device does not support wave operations.");
  1947. return;
  1948. }
  1949. std::vector<PerThreadData> values;
  1950. values.resize(ThreadsPerGroup * DispatchGroupCount);
  1951. for (size_t i = 0; i < values.size(); ++i) {
  1952. memset(&values[i], 0, sizeof(PerThreadData));
  1953. values[i].id = (uint32_t)i;
  1954. values[i].i_diver = (int)i;
  1955. values[i].i_diver *= (i % 2) ? 1 : -1;
  1956. }
  1957. static const int DispatchGroupX = 1;
  1958. static const int DispatchGroupY = 1;
  1959. static const int DispatchGroupZ = 1;
  1960. CComPtr<ID3D12GraphicsCommandList> pCommandList;
  1961. CComPtr<ID3D12CommandQueue> pCommandQueue;
  1962. CComPtr<ID3D12DescriptorHeap> pUavHeap;
  1963. CComPtr<ID3D12CommandAllocator> pCommandAllocator;
  1964. UINT uavDescriptorSize;
  1965. FenceObj FO;
  1966. bool dxbc = UseDxbc();
  1967. const size_t valueSizeInBytes = values.size() * sizeof(PerThreadData);
  1968. CreateComputeCommandQueue(pDevice, L"WaveIntrinsicsTest Command Queue", &pCommandQueue);
  1969. InitFenceObj(pDevice, &FO);
  1970. // Describe and create a UAV descriptor heap.
  1971. D3D12_DESCRIPTOR_HEAP_DESC heapDesc = {};
  1972. heapDesc.NumDescriptors = 1;
  1973. heapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV;
  1974. heapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE;
  1975. VERIFY_SUCCEEDED(pDevice->CreateDescriptorHeap(&heapDesc, IID_PPV_ARGS(&pUavHeap)));
  1976. uavDescriptorSize = pDevice->GetDescriptorHandleIncrementSize(heapDesc.Type);
  1977. // Create root signature.
  1978. CComPtr<ID3D12RootSignature> pRootSignature;
  1979. {
  1980. CD3DX12_DESCRIPTOR_RANGE ranges[1];
  1981. ranges[0].Init(D3D12_DESCRIPTOR_RANGE_TYPE_UAV, 1, 0, 0, 0);
  1982. CD3DX12_ROOT_PARAMETER rootParameters[1];
  1983. rootParameters[0].InitAsDescriptorTable(1, &ranges[0], D3D12_SHADER_VISIBILITY_ALL);
  1984. CD3DX12_ROOT_SIGNATURE_DESC rootSignatureDesc;
  1985. rootSignatureDesc.Init(_countof(rootParameters), rootParameters, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE);
  1986. CComPtr<ID3DBlob> signature;
  1987. CComPtr<ID3DBlob> error;
  1988. VERIFY_SUCCEEDED(D3D12SerializeRootSignature(&rootSignatureDesc, D3D_ROOT_SIGNATURE_VERSION_1, &signature, &error));
  1989. VERIFY_SUCCEEDED(pDevice->CreateRootSignature(0, signature->GetBufferPointer(), signature->GetBufferSize(), IID_PPV_ARGS(&pRootSignature)));
  1990. }
  1991. // Create pipeline state object.
  1992. CComPtr<ID3D12PipelineState> pComputeState;
  1993. CreateComputePSO(pDevice, pRootSignature, pShader, L"cs_6_0", &pComputeState);
  1994. // Create a command allocator and list for compute.
  1995. VERIFY_SUCCEEDED(pDevice->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_COMPUTE, IID_PPV_ARGS(&pCommandAllocator)));
  1996. VERIFY_SUCCEEDED(pDevice->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_COMPUTE, pCommandAllocator, pComputeState, IID_PPV_ARGS(&pCommandList)));
  1997. // Set up UAV resource.
  1998. CComPtr<ID3D12Resource> pUavResource;
  1999. CComPtr<ID3D12Resource> pReadBuffer;
  2000. CComPtr<ID3D12Resource> pUploadResource;
  2001. CreateTestUavs(pDevice, pCommandList, values.data(), (UINT)valueSizeInBytes, &pUavResource, &pUploadResource, &pReadBuffer);
  2002. // Close the command list and execute it to perform the GPU setup.
  2003. pCommandList->Close();
  2004. ExecuteCommandList(pCommandQueue, pCommandList);
  2005. WaitForSignal(pCommandQueue, FO);
  2006. VERIFY_SUCCEEDED(pCommandAllocator->Reset());
  2007. VERIFY_SUCCEEDED(pCommandList->Reset(pCommandAllocator, pComputeState));
  2008. // Run the compute shader and copy the results back to readable memory.
  2009. {
  2010. D3D12_UNORDERED_ACCESS_VIEW_DESC uavDesc = {};
  2011. uavDesc.Format = DXGI_FORMAT_UNKNOWN;
  2012. uavDesc.ViewDimension = D3D12_UAV_DIMENSION_BUFFER;
  2013. uavDesc.Buffer.FirstElement = 0;
  2014. uavDesc.Buffer.NumElements = (UINT)values.size();
  2015. uavDesc.Buffer.StructureByteStride = sizeof(PerThreadData);
  2016. uavDesc.Buffer.CounterOffsetInBytes = 0;
  2017. uavDesc.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_NONE;
  2018. CD3DX12_CPU_DESCRIPTOR_HANDLE uavHandle(pUavHeap->GetCPUDescriptorHandleForHeapStart());
  2019. CD3DX12_GPU_DESCRIPTOR_HANDLE uavHandleGpu(pUavHeap->GetGPUDescriptorHandleForHeapStart());
  2020. pDevice->CreateUnorderedAccessView(pUavResource, nullptr, &uavDesc, uavHandle);
  2021. SetDescriptorHeap(pCommandList, pUavHeap);
  2022. pCommandList->SetComputeRootSignature(pRootSignature);
  2023. pCommandList->SetComputeRootDescriptorTable(0, uavHandleGpu);
  2024. }
  2025. pCommandList->Dispatch(DispatchGroupX, DispatchGroupY, DispatchGroupZ);
  2026. RecordTransitionBarrier(pCommandList, pUavResource, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE);
  2027. pCommandList->CopyResource(pReadBuffer, pUavResource);
  2028. pCommandList->Close();
  2029. ExecuteCommandList(pCommandQueue, pCommandList);
  2030. WaitForSignal(pCommandQueue, FO);
  2031. {
  2032. MappedData mappedData(pReadBuffer, (UINT)valueSizeInBytes);
  2033. PerThreadData *pData = (PerThreadData *)mappedData.data();
  2034. memcpy(values.data(), pData, valueSizeInBytes);
  2035. // Gather some general data.
  2036. // The 'firstLaneId' captures a unique number per first-lane per wave.
  2037. // Counting the number distinct firstLaneIds gives us the number of waves.
  2038. std::vector<uint32_t> firstLaneIds;
  2039. for (size_t i = 0; i < values.size(); ++i) {
  2040. PerThreadData &pts = values[i];
  2041. uint32_t firstLaneId = pts.firstLaneId;
  2042. if (!contains(firstLaneIds, firstLaneId)) {
  2043. firstLaneIds.push_back(firstLaneId);
  2044. }
  2045. }
  2046. // Waves should cover 4 threads or more.
  2047. LogCommentFmt(L"Found %u distinct lane ids: %u", firstLaneIds.size());
  2048. if (!dxbc) {
  2049. VERIFY_IS_GREATER_THAN_OR_EQUAL(values.size() / 4, firstLaneIds.size());
  2050. }
  2051. // Now, group threads into waves.
  2052. std::map<uint32_t, std::unique_ptr<std::vector<PerThreadData *> > > waves;
  2053. for (size_t i = 0; i < firstLaneIds.size(); ++i) {
  2054. waves[firstLaneIds[i]] = std::make_unique<std::vector<PerThreadData *> >();
  2055. }
  2056. for (size_t i = 0; i < values.size(); ++i) {
  2057. PerThreadData &pts = values[i];
  2058. std::unique_ptr<std::vector<PerThreadData *> > &wave = waves[pts.firstLaneId];
  2059. wave->push_back(&pts);
  2060. }
  2061. // Verify that all the wave values are coherent across the wave.
  2062. for (size_t i = 0; i < values.size(); ++i) {
  2063. PerThreadData &pts = values[i];
  2064. std::unique_ptr<std::vector<PerThreadData *> > &wave = waves[pts.firstLaneId];
  2065. // Sort the lanes by increasing lane ID.
  2066. struct LaneIdOrderPred {
  2067. bool operator()(PerThreadData *a, PerThreadData *b) {
  2068. return a->laneIndex < b->laneIndex;
  2069. }
  2070. };
  2071. std::sort(wave.get()->begin(), wave.get()->end(), LaneIdOrderPred());
  2072. // Verify some interesting properties of the first lane.
  2073. uint32_t pfBC, pfSum, pfProd;
  2074. int32_t i_pfSum, i_pfProd;
  2075. int32_t i_allMax, i_allMin;
  2076. {
  2077. PerThreadData *ptdFirst = wave->front();
  2078. VERIFY_IS_TRUE(0 != (ptdFirst->flags & 1)); // FirstLane sets this bit.
  2079. VERIFY_IS_TRUE(0 == ptdFirst->pfBC);
  2080. VERIFY_IS_TRUE(0 == ptdFirst->pfSum);
  2081. VERIFY_IS_TRUE(1 == ptdFirst->pfProd);
  2082. VERIFY_IS_TRUE(0 == ptdFirst->i_pfSum);
  2083. VERIFY_IS_TRUE(1 == ptdFirst->i_pfProd);
  2084. pfBC = (ptdFirst->diver > 3) ? 1 : 0;
  2085. pfSum = ptdFirst->diver;
  2086. pfProd = ptdFirst->diver;
  2087. i_pfSum = ptdFirst->i_diver;
  2088. i_pfProd = ptdFirst->i_diver;
  2089. i_allMax = i_allMin = ptdFirst->i_diver;
  2090. }
  2091. // Calculate values which take into consideration all lanes.
  2092. uint32_t preds = 0;
  2093. preds |= 1 << 1; // AllTrue starts true, switches to false if needed.
  2094. preds |= 1 << 2; // AllEqual starts true, switches to false if needed.
  2095. preds |= 1 << 3; // WaveActiveAllEqual(GTID.z) is always true
  2096. preds |= 1 << 4; // (WaveActiveAllEqual(WaveReadLaneFirst(diver)) is always true
  2097. uint32_t ballot[4] = { 0, 0, 0, 0 };
  2098. int32_t i_allSum = 0, i_allProd = 1;
  2099. for (size_t n = 0; n < wave->size(); ++n) {
  2100. std::vector<PerThreadData *> &lanes = *wave.get();
  2101. // pts.preds |= ((WaveActiveAnyTrue(diver == 1) ? 1 : 0) << 0);
  2102. if (lanes[n]->diver == 1) preds |= (1 << 0);
  2103. // pts.preds |= ((WaveActiveAllTrue(diver == 1) ? 1 : 0) << 1);
  2104. if (lanes[n]->diver != 1) preds &= ~(1 << 1);
  2105. // pts.preds |= ((WaveActiveAllEqual(diver) ? 1 : 0) << 2);
  2106. if (lanes[0]->diver != lanes[n]->diver) preds &= ~(1 << 2);
  2107. // pts.ballot = WaveActiveBallot(diver > 3);\r\n"
  2108. if (lanes[n]->diver > 3) {
  2109. // This is the uint4 result layout:
  2110. // .x -> bits 0 .. 31
  2111. // .y -> bits 32 .. 63
  2112. // .z -> bits 64 .. 95
  2113. // .w -> bits 96 ..127
  2114. uint32_t component = lanes[n]->laneIndex / 32;
  2115. uint32_t bit = lanes[n]->laneIndex % 32;
  2116. ballot[component] |= 1 << bit;
  2117. }
  2118. i_allMax = std::max(lanes[n]->i_diver, i_allMax);
  2119. i_allMin = std::min(lanes[n]->i_diver, i_allMin);
  2120. i_allProd *= lanes[n]->i_diver;
  2121. i_allSum += lanes[n]->i_diver;
  2122. }
  2123. for (size_t n = 1; n < wave->size(); ++n) {
  2124. // 'All' operations are uniform across the wave.
  2125. std::vector<PerThreadData *> &lanes = *wave.get();
  2126. VERIFY_IS_TRUE(0 == (lanes[n]->flags & 1)); // non-firstlanes do not set this bit
  2127. VERIFY_ARE_EQUAL(lanes[0]->allBC, lanes[n]->allBC);
  2128. VERIFY_ARE_EQUAL(lanes[0]->allSum, lanes[n]->allSum);
  2129. VERIFY_ARE_EQUAL(lanes[0]->allProd, lanes[n]->allProd);
  2130. VERIFY_ARE_EQUAL(lanes[0]->allAND, lanes[n]->allAND);
  2131. VERIFY_ARE_EQUAL(lanes[0]->allOR, lanes[n]->allOR);
  2132. VERIFY_ARE_EQUAL(lanes[0]->allXOR, lanes[n]->allXOR);
  2133. VERIFY_ARE_EQUAL(lanes[0]->allMin, lanes[n]->allMin);
  2134. VERIFY_ARE_EQUAL(lanes[0]->allMax, lanes[n]->allMax);
  2135. VERIFY_ARE_EQUAL(i_allMax, lanes[n]->i_allMax);
  2136. VERIFY_ARE_EQUAL(i_allMin, lanes[n]->i_allMin);
  2137. VERIFY_ARE_EQUAL(i_allProd, lanes[n]->i_allProd);
  2138. VERIFY_ARE_EQUAL(i_allSum, lanes[n]->i_allSum);
  2139. // first-lane reads and uniform reads are uniform across the wave.
  2140. VERIFY_ARE_EQUAL(lanes[0]->firstlaneX, lanes[n]->firstlaneX);
  2141. VERIFY_ARE_EQUAL(lanes[0]->lane1X, lanes[n]->lane1X);
  2142. // the lane count is uniform across the wave.
  2143. VERIFY_ARE_EQUAL(lanes[0]->laneCount, lanes[n]->laneCount);
  2144. // The predicates are uniform across the wave.
  2145. VERIFY_ARE_EQUAL(lanes[n]->preds, preds);
  2146. // the lane index is distinct per thread.
  2147. for (size_t prior = 0; prior < n; ++prior) {
  2148. VERIFY_ARE_NOT_EQUAL(lanes[prior]->laneIndex, lanes[n]->laneIndex);
  2149. }
  2150. // Ballot results are uniform across the wave.
  2151. VERIFY_ARE_EQUAL(0, memcmp(ballot, lanes[n]->ballot, sizeof(ballot)));
  2152. // Keep running total of prefix calculation. Prefix values are exclusive to
  2153. // the executing lane.
  2154. VERIFY_ARE_EQUAL(pfBC, lanes[n]->pfBC);
  2155. VERIFY_ARE_EQUAL(pfSum, lanes[n]->pfSum);
  2156. VERIFY_ARE_EQUAL(pfProd, lanes[n]->pfProd);
  2157. VERIFY_ARE_EQUAL(i_pfSum, lanes[n]->i_pfSum);
  2158. VERIFY_ARE_EQUAL(i_pfProd, lanes[n]->i_pfProd);
  2159. pfBC += (lanes[n]->diver > 3) ? 1 : 0;
  2160. pfSum += lanes[n]->diver;
  2161. pfProd *= lanes[n]->diver;
  2162. i_pfSum += lanes[n]->i_diver;
  2163. i_pfProd *= lanes[n]->i_diver;
  2164. }
  2165. // TODO: add divergent branching and verify that the otherwise uniform values properly diverge
  2166. }
  2167. // Compare each value of each per-thread element.
  2168. for (size_t i = 0; i < values.size(); ++i) {
  2169. PerThreadData &pts = values[i];
  2170. VERIFY_ARE_EQUAL(i, pts.id); // ID is unchanged.
  2171. }
  2172. }
  2173. #endif
  2174. }
  2175. // This test is assuming that the adapter implements WaveReadLaneFirst correctly
  2176. TEST_F(ExecutionTest, WaveIntrinsicsInPSTest) {
  2177. WEX::TestExecution::SetVerifyOutput verifySettings(WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  2178. struct Vertex {
  2179. XMFLOAT3 position;
  2180. };
  2181. struct PerPixelData {
  2182. XMFLOAT4 position;
  2183. uint32_t id, flags, laneIndex, laneCount, firstLaneId, sum1;
  2184. uint32_t id0, id1, id2, id3;
  2185. uint32_t acrossX, acrossY, acrossDiag, quadActiveCount;
  2186. };
  2187. const UINT RTWidth = 128;
  2188. const UINT RTHeight = 128;
  2189. // Shaders.
  2190. static const char pShaders[] =
  2191. WAVE_INTRINSIC_DXBC_GUARD
  2192. "struct PSInput {\r\n"
  2193. " float4 position : SV_POSITION;\r\n"
  2194. "};\r\n\r\n"
  2195. "PSInput VSMain(float4 position : POSITION) {\r\n"
  2196. " PSInput result;\r\n"
  2197. "\r\n"
  2198. " result.position = position;\r\n"
  2199. " return result;\r\n"
  2200. "}\r\n\r\n"
  2201. "uint pos_to_id(float4 pos) { return pos.x * 128 + pos.y; }\r\n"
  2202. "struct PerPixelData {\r\n"
  2203. " float4 position;\r\n"
  2204. " uint id, flags, laneIndex, laneCount, firstLaneId, sum1;\r\n"
  2205. " uint id0, id1, id2, id3;\r\n"
  2206. " uint acrossX, acrossY, acrossDiag, quadActiveCount;\r\n"
  2207. "};\r\n"
  2208. "AppendStructuredBuffer<PerPixelData> g_sb : register(u1);\r\n"
  2209. "float4 PSMain(PSInput input) : SV_TARGET {\r\n"
  2210. " uint one = 1;\r\n"
  2211. " PerPixelData d;\r\n"
  2212. " d.position = input.position;\r\n"
  2213. " d.id = pos_to_id(input.position);\r\n"
  2214. " d.flags = 0;\r\n"
  2215. " if (WaveIsFirstLane()) d.flags |= 1;\r\n"
  2216. " d.laneIndex = WaveGetLaneIndex();\r\n"
  2217. " d.laneCount = WaveGetLaneCount();\r\n"
  2218. " d.firstLaneId = WaveReadLaneFirst(d.id);\r\n"
  2219. " d.sum1 = WaveActiveSum(one);\r\n"
  2220. " d.id0 = QuadReadLaneAt(d.id, 0);\r\n"
  2221. " d.id1 = QuadReadLaneAt(d.id, 1);\r\n"
  2222. " d.id2 = QuadReadLaneAt(d.id, 2);\r\n"
  2223. " d.id3 = QuadReadLaneAt(d.id, 3);\r\n"
  2224. " d.acrossX = QuadReadAcrossX(d.id);\r\n"
  2225. " d.acrossY = QuadReadAcrossY(d.id);\r\n"
  2226. " d.acrossDiag = QuadReadAcrossDiagonal(d.id);\r\n"
  2227. " d.quadActiveCount = one + QuadReadAcrossX(one) + QuadReadAcrossY(one) + QuadReadAcrossDiagonal(one);\r\n"
  2228. " g_sb.Append(d);\r\n"
  2229. " return 1;\r\n"
  2230. "};\r\n";
  2231. CComPtr<ID3D12Device> pDevice;
  2232. CComPtr<ID3D12CommandQueue> pCommandQueue;
  2233. CComPtr<ID3D12DescriptorHeap> pUavHeap, pRtvHeap;
  2234. CComPtr<ID3D12CommandAllocator> pCommandAllocator;
  2235. CComPtr<ID3D12GraphicsCommandList> pCommandList;
  2236. CComPtr<ID3D12PipelineState> pPSO;
  2237. CComPtr<ID3D12Resource> pRenderTarget, pReadBuffer;
  2238. UINT uavDescriptorSize, rtvDescriptorSize;
  2239. CComPtr<ID3D12Resource> pVertexBuffer;
  2240. D3D12_VERTEX_BUFFER_VIEW vertexBufferView;
  2241. if (!CreateDevice(&pDevice))
  2242. return;
  2243. if (!DoesDeviceSupportWaveOps(pDevice)) {
  2244. // Optional feature, so it's correct to not support it if declared as such.
  2245. WEX::Logging::Log::Comment(L"Device does not support wave operations.");
  2246. return;
  2247. }
  2248. FenceObj FO;
  2249. InitFenceObj(pDevice, &FO);
  2250. // Describe and create a UAV descriptor heap.
  2251. D3D12_DESCRIPTOR_HEAP_DESC heapDesc = {};
  2252. heapDesc.NumDescriptors = 1;
  2253. heapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV;
  2254. heapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE;
  2255. VERIFY_SUCCEEDED(pDevice->CreateDescriptorHeap(&heapDesc, IID_PPV_ARGS(&pUavHeap)));
  2256. uavDescriptorSize = pDevice->GetDescriptorHandleIncrementSize(heapDesc.Type);
  2257. CreateRtvDescriptorHeap(pDevice, 1, &pRtvHeap, &rtvDescriptorSize);
  2258. CreateRenderTargetAndReadback(pDevice, pRtvHeap, RTHeight, RTWidth, &pRenderTarget, &pReadBuffer);
  2259. // Create root signature: one UAV.
  2260. CComPtr<ID3D12RootSignature> pRootSignature;
  2261. {
  2262. CD3DX12_DESCRIPTOR_RANGE ranges[1];
  2263. ranges[0].Init(D3D12_DESCRIPTOR_RANGE_TYPE_UAV, 1, 1, 0, 0);
  2264. CD3DX12_ROOT_PARAMETER rootParameters[1];
  2265. rootParameters[0].InitAsDescriptorTable(1, &ranges[0], D3D12_SHADER_VISIBILITY_ALL);
  2266. CD3DX12_ROOT_SIGNATURE_DESC rootSignatureDesc;
  2267. rootSignatureDesc.Init(_countof(rootParameters), rootParameters, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT);
  2268. CreateRootSignatureFromDesc(pDevice, &rootSignatureDesc, &pRootSignature);
  2269. }
  2270. D3D12_INPUT_ELEMENT_DESC elementDesc[] = {
  2271. {"POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0,
  2272. D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0}};
  2273. D3D12_INPUT_LAYOUT_DESC InputLayout = {elementDesc, _countof(elementDesc)};
  2274. CreateGraphicsPSO(pDevice, &InputLayout, pRootSignature, pShaders, &pPSO);
  2275. CreateGraphicsCommandQueueAndList(pDevice, &pCommandQueue, &pCommandAllocator,
  2276. &pCommandList, pPSO);
  2277. // Single triangle covering half the target.
  2278. Vertex vertices[] = {
  2279. { { -1.0f, 1.0f, 0.0f } },
  2280. { { 1.0f, 1.0f, 0.0f } },
  2281. { { -1.0f, -1.0f, 0.0f } } };
  2282. const UINT TriangleCount = _countof(vertices) / 3;
  2283. CreateVertexBuffer(pDevice, vertices, &pVertexBuffer, &vertexBufferView);
  2284. bool dxbc = UseDxbc();
  2285. // Set up UAV resource.
  2286. std::vector<PerPixelData> values;
  2287. values.resize(RTWidth * RTHeight * 2);
  2288. UINT valueSizeInBytes = (UINT)values.size() * sizeof(PerPixelData);
  2289. memset(values.data(), 0, valueSizeInBytes);
  2290. CComPtr<ID3D12Resource> pUavResource;
  2291. CComPtr<ID3D12Resource> pUavReadBuffer;
  2292. CComPtr<ID3D12Resource> pUploadResource;
  2293. CreateTestUavs(pDevice, pCommandList, values.data(), valueSizeInBytes, &pUavResource, &pUploadResource, &pUavReadBuffer);
  2294. // Set up the append counter resource.
  2295. CComPtr<ID3D12Resource> pUavCounterResource;
  2296. CComPtr<ID3D12Resource> pReadCounterBuffer;
  2297. CComPtr<ID3D12Resource> pUploadCounterResource;
  2298. BYTE zero[sizeof(UINT)] = { 0 };
  2299. CreateTestUavs(pDevice, pCommandList, zero, sizeof(zero), &pUavCounterResource, &pUploadCounterResource, &pReadCounterBuffer);
  2300. // Close the command list and execute it to perform the GPU setup.
  2301. pCommandList->Close();
  2302. ExecuteCommandList(pCommandQueue, pCommandList);
  2303. WaitForSignal(pCommandQueue, FO);
  2304. VERIFY_SUCCEEDED(pCommandAllocator->Reset());
  2305. VERIFY_SUCCEEDED(pCommandList->Reset(pCommandAllocator, pPSO));
  2306. pCommandList->SetGraphicsRootSignature(pRootSignature);
  2307. SetDescriptorHeap(pCommandList, pUavHeap);
  2308. {
  2309. D3D12_UNORDERED_ACCESS_VIEW_DESC uavDesc = {};
  2310. uavDesc.Format = DXGI_FORMAT_UNKNOWN;
  2311. uavDesc.ViewDimension = D3D12_UAV_DIMENSION_BUFFER;
  2312. uavDesc.Buffer.FirstElement = 0;
  2313. uavDesc.Buffer.NumElements = (UINT)values.size();
  2314. uavDesc.Buffer.StructureByteStride = sizeof(PerPixelData);
  2315. uavDesc.Buffer.CounterOffsetInBytes = 0;
  2316. uavDesc.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_NONE;
  2317. CD3DX12_CPU_DESCRIPTOR_HANDLE uavHandle(pUavHeap->GetCPUDescriptorHandleForHeapStart());
  2318. CD3DX12_GPU_DESCRIPTOR_HANDLE uavHandleGpu(pUavHeap->GetGPUDescriptorHandleForHeapStart());
  2319. pDevice->CreateUnorderedAccessView(pUavResource, pUavCounterResource, &uavDesc, uavHandle);
  2320. pCommandList->SetGraphicsRootDescriptorTable(0, uavHandleGpu);
  2321. }
  2322. RecordRenderAndReadback(pCommandList, pRtvHeap, rtvDescriptorSize, TriangleCount, &vertexBufferView, nullptr, pRenderTarget, pReadBuffer);
  2323. RecordTransitionBarrier(pCommandList, pUavResource, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE);
  2324. RecordTransitionBarrier(pCommandList, pUavCounterResource, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE);
  2325. pCommandList->CopyResource(pUavReadBuffer, pUavResource);
  2326. pCommandList->CopyResource(pReadCounterBuffer, pUavCounterResource);
  2327. VERIFY_SUCCEEDED(pCommandList->Close());
  2328. LogCommentFmt(L"Rendering to %u by %u", RTWidth, RTHeight);
  2329. ExecuteCommandList(pCommandQueue, pCommandList);
  2330. WaitForSignal(pCommandQueue, FO);
  2331. {
  2332. MappedData data(pReadBuffer, RTWidth * RTHeight * 4);
  2333. const uint32_t *pPixels = (uint32_t *)data.data();
  2334. if (SaveImages()) {
  2335. SavePixelsToFile(pPixels, DXGI_FORMAT_R8G8B8A8_UNORM, RTWidth, RTHeight, L"psintrin.bmp");
  2336. }
  2337. }
  2338. uint32_t appendCount;
  2339. {
  2340. MappedData mappedData(pReadCounterBuffer, sizeof(uint32_t));
  2341. appendCount = *((uint32_t *)mappedData.data());
  2342. LogCommentFmt(L"%u elements in append buffer", appendCount);
  2343. }
  2344. {
  2345. MappedData mappedData(pUavReadBuffer, (UINT32)values.size());
  2346. PerPixelData *pData = (PerPixelData *)mappedData.data();
  2347. memcpy(values.data(), pData, valueSizeInBytes);
  2348. // DXBC is handy to test pipeline setup, but interesting functions are
  2349. // stubbed out, so there is no point in further validation.
  2350. if (dxbc)
  2351. return;
  2352. uint32_t maxActiveLaneCount = 0;
  2353. uint32_t maxLaneCount = 0;
  2354. for (uint32_t i = 0; i < appendCount; ++i) {
  2355. maxActiveLaneCount = std::max(maxActiveLaneCount, values[i].sum1);
  2356. maxLaneCount = std::max(maxLaneCount, values[i].laneCount);
  2357. }
  2358. uint32_t peerOfHelperLanes = 0;
  2359. for (uint32_t i = 0; i < appendCount; ++i) {
  2360. if (values[i].sum1 != maxActiveLaneCount) {
  2361. ++peerOfHelperLanes;
  2362. }
  2363. }
  2364. LogCommentFmt(
  2365. L"Found: %u threads. Waves reported up to %u total lanes, up "
  2366. L"to %u active lanes, and %u threads had helper/inactive lanes.",
  2367. appendCount, maxLaneCount, maxActiveLaneCount, peerOfHelperLanes);
  2368. // Group threads into quad invocations.
  2369. uint32_t singlePixelCount = 0;
  2370. uint32_t multiPixelCount = 0;
  2371. std::unordered_set<uint32_t> ids;
  2372. std::multimap<uint32_t, PerPixelData *> idGroups;
  2373. std::multimap<uint32_t, PerPixelData *> firstIdGroups;
  2374. for (uint32_t i = 0; i < appendCount; ++i) {
  2375. ids.insert(values[i].id);
  2376. idGroups.insert(std::make_pair(values[i].id, &values[i]));
  2377. firstIdGroups.insert(std::make_pair(values[i].firstLaneId, &values[i]));
  2378. }
  2379. for (uint32_t id : ids) {
  2380. if (idGroups.count(id) == 1)
  2381. ++singlePixelCount;
  2382. else
  2383. ++multiPixelCount;
  2384. }
  2385. LogCommentFmt(L"%u pixels were processed by a single thread. %u invocations were for shared pixels.",
  2386. singlePixelCount, multiPixelCount);
  2387. // Multiple threads may have tried to shade the same pixel. (Is this true even if we have only one triangle?)
  2388. // Where every pixel is distinct, it's very straightforward to validate.
  2389. {
  2390. auto cur = firstIdGroups.begin(), end = firstIdGroups.end();
  2391. while (cur != end) {
  2392. bool simpleWave = true;
  2393. uint32_t firstId = (*cur).first;
  2394. auto groupEnd = cur;
  2395. while (groupEnd != end && (*groupEnd).first == firstId) {
  2396. if (idGroups.count((*groupEnd).second->id) > 1)
  2397. simpleWave = false;
  2398. ++groupEnd;
  2399. }
  2400. if (simpleWave) {
  2401. // Break the wave into quads.
  2402. struct QuadData {
  2403. unsigned count;
  2404. PerPixelData *data[4];
  2405. };
  2406. std::map<uint32_t, QuadData> quads;
  2407. for (auto i = cur; i != groupEnd; ++i) {
  2408. // assuming that it is a simple wave, idGroups has a unique id for each entry.
  2409. uint32_t laneId = (*i).second->id;
  2410. uint32_t laneIds[4] = {(*i).second->id0, (*i).second->id1,
  2411. (*i).second->id2, (*i).second->id3};
  2412. // Since this is a simple wave, each lane has an unique id and
  2413. // therefore should not have any ids in there.
  2414. VERIFY_IS_TRUE(quads.find(laneId) == quads.end());
  2415. // check if QuadReadLaneAt is returning same values in a single quad.
  2416. bool newQuad = true;
  2417. for (unsigned quadIndex = 0; quadIndex < 4; ++quadIndex) {
  2418. auto match = quads.find(laneIds[quadIndex]);
  2419. if (match != quads.end()) {
  2420. (*match).second.data[(*match).second.count++] = (*i).second;
  2421. newQuad = false;
  2422. break;
  2423. }
  2424. auto quadMemberData = idGroups.find(laneIds[quadIndex]);
  2425. if (quadMemberData != idGroups.end()) {
  2426. VERIFY_IS_TRUE((*quadMemberData).second->id0 == laneIds[0]);
  2427. VERIFY_IS_TRUE((*quadMemberData).second->id1 == laneIds[1]);
  2428. VERIFY_IS_TRUE((*quadMemberData).second->id2 == laneIds[2]);
  2429. VERIFY_IS_TRUE((*quadMemberData).second->id3 == laneIds[3]);
  2430. }
  2431. }
  2432. if (newQuad) {
  2433. QuadData qdata;
  2434. qdata.count = 1;
  2435. qdata.data[0] = (*i).second;
  2436. quads.insert(std::make_pair(laneId, qdata));
  2437. }
  2438. }
  2439. for (auto quadPair : quads) {
  2440. unsigned count = quadPair.second.count;
  2441. // There could be only one pixel data on the edge of the triangle
  2442. if (count < 2) continue;
  2443. PerPixelData **data = quadPair.second.data;
  2444. bool isTop[4];
  2445. bool isLeft[4];
  2446. PerPixelData helperData;
  2447. memset(&helperData, sizeof(helperData), 0);
  2448. PerPixelData *layout[4]; // tl,tr,bl,br
  2449. memset(layout, sizeof(layout), 0);
  2450. auto fnToLayout = [&](bool top, bool left) -> PerPixelData ** {
  2451. int idx = top ? 0 : 2;
  2452. idx += left ? 0 : 1;
  2453. return &layout[idx];
  2454. };
  2455. auto fnToLayoutData = [&](bool top, bool left) -> PerPixelData * {
  2456. PerPixelData **pResult = fnToLayout(top, left);
  2457. if (*pResult == nullptr) return &helperData;
  2458. return *pResult;
  2459. };
  2460. VERIFY_IS_TRUE(count <= 4);
  2461. if (count == 2) {
  2462. isTop[0] = data[0]->position.y < data[1]->position.y;
  2463. isTop[1] = (data[0]->position.y == data[1]->position.y) ? isTop[0] : !isTop[0];
  2464. isLeft[0] = data[0]->position.x < data[1]->position.x;
  2465. isLeft[1] = (data[0]->position.x == data[1]->position.x) ? isLeft[0] : !isLeft[0];
  2466. }
  2467. else {
  2468. // with at least three samples, we have distinct x and y coordinates.
  2469. float left = std::min(data[0]->position.x, data[1]->position.x);
  2470. left = std::min(data[2]->position.x, left);
  2471. float top = std::min(data[0]->position.y, data[1]->position.y);
  2472. top = std::min(data[2]->position.y, top);
  2473. for (unsigned i = 0; i < count; ++i) {
  2474. isTop[i] = data[i]->position.y == top;
  2475. isLeft[i] = data[i]->position.x == left;
  2476. }
  2477. }
  2478. for (unsigned i = 0; i < count; ++i) {
  2479. *(fnToLayout(isTop[i], isLeft[i])) = data[i];
  2480. }
  2481. // Finally, we have a proper quad reconstructed. Validate.
  2482. for (unsigned i = 0; i < count; ++i) {
  2483. PerPixelData *d = data[i];
  2484. VERIFY_ARE_EQUAL(d->id0, fnToLayoutData(true, true)->id);
  2485. VERIFY_ARE_EQUAL(d->id1, fnToLayoutData(true, false)->id);
  2486. VERIFY_ARE_EQUAL(d->id2, fnToLayoutData(false, true)->id);
  2487. VERIFY_ARE_EQUAL(d->id3, fnToLayoutData(false, false)->id);
  2488. VERIFY_ARE_EQUAL(d->acrossX, fnToLayoutData(isTop[i], !isLeft[i])->id);
  2489. VERIFY_ARE_EQUAL(d->acrossY, fnToLayoutData(!isTop[i], isLeft[i])->id);
  2490. VERIFY_ARE_EQUAL(d->acrossDiag, fnToLayoutData(!isTop[i], !isLeft[i])->id);
  2491. VERIFY_ARE_EQUAL(d->quadActiveCount, count);
  2492. }
  2493. }
  2494. }
  2495. cur = groupEnd;
  2496. }
  2497. }
  2498. // TODO: provide validation for quads where the same pixel was shaded multiple times
  2499. //
  2500. // Consider: for pixels that were shaded multiple times, check whether
  2501. // some grouping of threads into quads satisfies all value requirements.
  2502. }
  2503. }
  2504. struct ShaderOpTestResult {
  2505. st::ShaderOp *ShaderOp;
  2506. std::shared_ptr<st::ShaderOpSet> ShaderOpSet;
  2507. std::shared_ptr<st::ShaderOpTest> Test;
  2508. };
  2509. struct SPrimitives {
  2510. float f_float;
  2511. float f_float2;
  2512. float f_float_o;
  2513. float f_float2_o;
  2514. };
  2515. std::shared_ptr<ShaderOpTestResult>
  2516. RunShaderOpTestAfterParse(ID3D12Device *pDevice, dxc::DxcDllSupport &support,
  2517. LPCSTR pName,
  2518. st::ShaderOpTest::TInitCallbackFn pInitCallback,
  2519. std::shared_ptr<st::ShaderOpSet> ShaderOpSet) {
  2520. st::ShaderOp *pShaderOp;
  2521. if (pName == nullptr) {
  2522. if (ShaderOpSet->ShaderOps.size() != 1) {
  2523. VERIFY_FAIL(L"Expected a single shader operation.");
  2524. }
  2525. pShaderOp = ShaderOpSet->ShaderOps[0].get();
  2526. }
  2527. else {
  2528. pShaderOp = ShaderOpSet->GetShaderOp(pName);
  2529. }
  2530. if (pShaderOp == nullptr) {
  2531. std::string msg = "Unable to find shader op ";
  2532. msg += pName;
  2533. msg += "; available ops";
  2534. const char sep = ':';
  2535. for (auto &pAvailOp : ShaderOpSet->ShaderOps) {
  2536. msg += sep;
  2537. msg += pAvailOp->Name ? pAvailOp->Name : "[n/a]";
  2538. }
  2539. CA2W msgWide(msg.c_str());
  2540. VERIFY_FAIL(msgWide.m_psz);
  2541. }
  2542. // This won't actually be used since we're supplying the device,
  2543. // but let's make it consistent.
  2544. pShaderOp->UseWarpDevice = GetTestParamUseWARP(true);
  2545. std::shared_ptr<st::ShaderOpTest> test = std::make_shared<st::ShaderOpTest>();
  2546. test->SetDxcSupport(&support);
  2547. test->SetInitCallback(pInitCallback);
  2548. test->SetDevice(pDevice);
  2549. test->RunShaderOp(pShaderOp);
  2550. std::shared_ptr<ShaderOpTestResult> result =
  2551. std::make_shared<ShaderOpTestResult>();
  2552. result->ShaderOpSet = ShaderOpSet;
  2553. result->Test = test;
  2554. result->ShaderOp = pShaderOp;
  2555. return result;
  2556. }
  2557. std::shared_ptr<ShaderOpTestResult>
  2558. RunShaderOpTest(ID3D12Device *pDevice, dxc::DxcDllSupport &support,
  2559. IStream *pStream, LPCSTR pName,
  2560. st::ShaderOpTest::TInitCallbackFn pInitCallback) {
  2561. DXASSERT_NOMSG(pStream != nullptr);
  2562. std::shared_ptr<st::ShaderOpSet> ShaderOpSet =
  2563. std::make_shared<st::ShaderOpSet>();
  2564. st::ParseShaderOpSetFromStream(pStream, ShaderOpSet.get());
  2565. return RunShaderOpTestAfterParse(pDevice, support, pName, pInitCallback, ShaderOpSet);
  2566. }
  2567. TEST_F(ExecutionTest, OutOfBoundsTest) {
  2568. WEX::TestExecution::SetVerifyOutput verifySettings(WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  2569. CComPtr<IStream> pStream;
  2570. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  2571. // Single operation test at the moment.
  2572. CComPtr<ID3D12Device> pDevice;
  2573. if (!CreateDevice(&pDevice))
  2574. return;
  2575. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTest(pDevice, m_support, pStream, "OOB", nullptr);
  2576. MappedData data;
  2577. // Read back to CPU and examine contents - should get pure red.
  2578. {
  2579. MappedData data;
  2580. test->Test->GetReadBackData("RTarget", &data);
  2581. const uint32_t *pPixels = (uint32_t *)data.data();
  2582. uint32_t first = *pPixels;
  2583. VERIFY_ARE_EQUAL(0xff0000ff, first); // pure red - only first component is read
  2584. }
  2585. }
  2586. TEST_F(ExecutionTest, SaturateTest) {
  2587. WEX::TestExecution::SetVerifyOutput verifySettings(WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  2588. CComPtr<IStream> pStream;
  2589. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  2590. // Single operation test at the moment.
  2591. CComPtr<ID3D12Device> pDevice;
  2592. if (!CreateDevice(&pDevice))
  2593. return;
  2594. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTest(pDevice, m_support, pStream, "Saturate", nullptr);
  2595. MappedData data;
  2596. test->Test->GetReadBackData("U0", &data);
  2597. const float *pValues = (float *)data.data();
  2598. // Everything is zero except for 1.5f and +Inf, which saturate to 1.0f
  2599. const float ExpectedCases[9] = {
  2600. 0.0f, 0.0f, 0.0f, 0.0f, // -inf, -1.5, -denorm, -0
  2601. 0.0f, 0.0f, 1.0f, 1.0f, // 0, denorm, 1.5f, inf
  2602. 0.0f // nan
  2603. };
  2604. for (size_t i = 0; i < _countof(ExpectedCases); ++i) {
  2605. VERIFY_IS_TRUE(ifdenorm_flushf_eq(*pValues, ExpectedCases[i]));
  2606. ++pValues;
  2607. }
  2608. }
  2609. void ExecutionTest::BasicTriangleTestSetup(LPCSTR ShaderOpName, LPCWSTR FileName, D3D_SHADER_MODEL testModel) {
  2610. #ifdef _HLK_CONF
  2611. UNREFERENCED_PARAMETER(ShaderOpName);
  2612. UNREFERENCED_PARAMETER(FileName);
  2613. UNREFERENCED_PARAMETER(testModel);
  2614. #else
  2615. WEX::TestExecution::SetVerifyOutput verifySettings(WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  2616. CComPtr<IStream> pStream;
  2617. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  2618. // Single operation test at the moment.
  2619. CComPtr<ID3D12Device> pDevice;
  2620. if (!CreateDevice(&pDevice, testModel))
  2621. return;
  2622. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTest(pDevice, m_support, pStream, ShaderOpName, nullptr);
  2623. MappedData data;
  2624. D3D12_RESOURCE_DESC &D = test->ShaderOp->GetResourceByName("RTarget")->Desc;
  2625. UINT width = (UINT)D.Width;
  2626. UINT height = D.Height;
  2627. test->Test->GetReadBackData("RTarget", &data);
  2628. const uint32_t *pPixels = (uint32_t *)data.data();
  2629. if (SaveImages()) {
  2630. SavePixelsToFile(pPixels, DXGI_FORMAT_R8G8B8A8_UNORM, 320, 200, FileName);
  2631. }
  2632. uint32_t top = pPixels[width / 2]; // Top center.
  2633. uint32_t mid = pPixels[width / 2 + width * (height / 2)]; // Middle center.
  2634. VERIFY_ARE_EQUAL(0xff663300, top); // clear color
  2635. VERIFY_ARE_EQUAL(0xffffffff, mid); // white
  2636. // This is the basic validation test for shader operations, so it's good to
  2637. // check this here at least for this one test case.
  2638. data.reset();
  2639. test.reset();
  2640. ReportLiveObjects();
  2641. #endif
  2642. }
  2643. TEST_F(ExecutionTest, BasicTriangleOpTest) {
  2644. BasicTriangleTestSetup("Triangle", L"basic-triangle.bmp", D3D_SHADER_MODEL_6_0);
  2645. }
  2646. TEST_F(ExecutionTest, BasicTriangleOpTestHalf) {
  2647. BasicTriangleTestSetup("TriangleHalf", L"basic-triangle-half.bmp", D3D_SHADER_MODEL_6_2);
  2648. }
  2649. void VerifyDerivResults(const float *pPixels, UINT offsetCenter) {
  2650. // pixel at the center
  2651. float CenterDDXFine = pPixels[offsetCenter];
  2652. float CenterDDYFine = pPixels[offsetCenter + 1];
  2653. float CenterDDXCoarse = pPixels[offsetCenter + 2];
  2654. float CenterDDYCoarse = pPixels[offsetCenter + 3];
  2655. LogCommentFmt(
  2656. L"center ddx_fine: %8f, ddy_fine: %8f, ddx_coarse: %8f, ddy_coarse: %8f",
  2657. CenterDDXFine, CenterDDYFine, CenterDDXCoarse, CenterDDYCoarse);
  2658. // The texture for the 9 pixels in the center should look like the following
  2659. // 256 32 64
  2660. // 2048 256 512
  2661. // 1 .125 .25
  2662. // In D3D12 there is no guarantee of how the adapter is grouping 2x2 pixels
  2663. // So for fine derivatives there can be up to two possible results for the center pixel,
  2664. // while for coarse derivatives there can be up to six possible results.
  2665. int ulpTolerance = 1;
  2666. // 512 - 256 or 2048 - 256
  2667. bool left = CompareFloatULP(CenterDDXFine, -1792.0f, ulpTolerance);
  2668. VERIFY_IS_TRUE(left || CompareFloatULP(CenterDDXFine, 256.0f, ulpTolerance));
  2669. // 256 - 32 or 256 - .125
  2670. bool top = CompareFloatULP(CenterDDYFine, 224.0f, ulpTolerance);
  2671. VERIFY_IS_TRUE(top || CompareFloatULP(CenterDDYFine, -255.875, ulpTolerance));
  2672. if (top && left) {
  2673. VERIFY_IS_TRUE((CompareFloatULP(CenterDDXCoarse, -224.0f, ulpTolerance) ||
  2674. CompareFloatULP(CenterDDXCoarse, -1792.0f, ulpTolerance)) &&
  2675. (CompareFloatULP(CenterDDYCoarse, 224.0f, ulpTolerance) ||
  2676. CompareFloatULP(CenterDDYCoarse, 1792.0f, ulpTolerance)));
  2677. }
  2678. else if (top) { // top right quad
  2679. VERIFY_IS_TRUE((CompareFloatULP(CenterDDXCoarse, 256.0f, ulpTolerance) ||
  2680. CompareFloatULP(CenterDDXCoarse, 32.0f, ulpTolerance)) &&
  2681. (CompareFloatULP(CenterDDYCoarse, 224.0f, ulpTolerance) ||
  2682. CompareFloatULP(CenterDDYCoarse, 448.0f, ulpTolerance)));
  2683. }
  2684. else if (left) { // bottom left quad
  2685. VERIFY_IS_TRUE((CompareFloatULP(CenterDDXCoarse, -1792.0f, ulpTolerance) ||
  2686. CompareFloatULP(CenterDDXCoarse, -.875f, ulpTolerance)) &&
  2687. (CompareFloatULP(CenterDDYCoarse, -2047.0f, ulpTolerance) ||
  2688. CompareFloatULP(CenterDDYCoarse, -255.875f, ulpTolerance)));
  2689. }
  2690. else { // bottom right
  2691. VERIFY_IS_TRUE((CompareFloatULP(CenterDDXCoarse, 256.0f, ulpTolerance) ||
  2692. CompareFloatULP(CenterDDXCoarse, .125f, ulpTolerance)) &&
  2693. (CompareFloatULP(CenterDDYCoarse, -255.875f, ulpTolerance) ||
  2694. CompareFloatULP(CenterDDYCoarse, -511.75f, ulpTolerance)));
  2695. }
  2696. }
  2697. // Rendering two right triangles forming a square and assigning a texture value
  2698. // for each pixel to calculate derivates.
  2699. TEST_F(ExecutionTest, PartialDerivTest) {
  2700. WEX::TestExecution::SetVerifyOutput verifySettings(WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  2701. CComPtr<IStream> pStream;
  2702. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  2703. CComPtr<ID3D12Device> pDevice;
  2704. if (!CreateDevice(&pDevice))
  2705. return;
  2706. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTest(pDevice, m_support, pStream, "DerivFine", nullptr);
  2707. MappedData data;
  2708. D3D12_RESOURCE_DESC &D = test->ShaderOp->GetResourceByName("RTarget")->Desc;
  2709. UINT width = (UINT)D.Width;
  2710. UINT height = D.Height;
  2711. UINT pixelSize = GetByteSizeForFormat(D.Format) / 4;
  2712. test->Test->GetReadBackData("RTarget", &data);
  2713. const float *pPixels = (float *)data.data();
  2714. UINT centerIndex = (UINT64)width * height / 2 - width / 2;
  2715. UINT offsetCenter = centerIndex * pixelSize;
  2716. VerifyDerivResults(pPixels, offsetCenter);
  2717. }
  2718. TEST_F(ExecutionTest, DerivativesTest) {
  2719. WEX::TestExecution::SetVerifyOutput verifySettings(WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  2720. CComPtr<IStream> pStream;
  2721. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  2722. CComPtr<ID3D12Device> pDevice;
  2723. if (!CreateDevice(&pDevice, D3D_SHADER_MODEL_6_6))
  2724. return;
  2725. std::shared_ptr<st::ShaderOpSet> ShaderOpSet =
  2726. std::make_shared<st::ShaderOpSet>();
  2727. st::ParseShaderOpSetFromStream(pStream, ShaderOpSet.get());
  2728. st::ShaderOp *pShaderOp = ShaderOpSet->GetShaderOp("Derivatives");
  2729. LPCSTR CS = pShaderOp->CS;
  2730. struct Dispatch {
  2731. int x, y, z;
  2732. int mx, my, mz;
  2733. };
  2734. std::vector<Dispatch> dispatches =
  2735. {
  2736. {32, 32, 1, 8, 8, 1},
  2737. {64, 4, 1, 64, 2, 1},
  2738. {1, 4, 64, 1, 4, 32},
  2739. {64, 1, 1, 64, 1, 1},
  2740. {1, 64, 1, 1, 64, 1},
  2741. {1, 1, 64, 1, 1, 64},
  2742. {16, 16, 3, 4, 4, 3},
  2743. {32, 3, 8, 8, 3, 2},
  2744. {3, 1, 64, 3, 1, 32}
  2745. };
  2746. char compilerOptions[256];
  2747. for (Dispatch &D : dispatches) {
  2748. UINT width = D.x;
  2749. UINT height = D.y;
  2750. UINT depth = D.z;
  2751. UINT mwidth = D.mx;
  2752. UINT mheight = D.my;
  2753. UINT mdepth = D.mz;
  2754. UINT pixelSize = 4; // always float4
  2755. // format compiler args
  2756. VERIFY_IS_TRUE(sprintf_s(compilerOptions, sizeof(compilerOptions),
  2757. "-D DISPATCHX=%d -D DISPATCHY=%d -D DISPATCHZ=%d "
  2758. "-D MESHDISPATCHX=%d -D MESHDISPATCHY=%d -D MESHDISPATCHZ=%d",
  2759. width, height, depth, mwidth, mheight, mdepth));
  2760. for (st::ShaderOpShader &S : pShaderOp->Shaders)
  2761. S.Arguments = compilerOptions;
  2762. pShaderOp->DispatchX = width;
  2763. pShaderOp->DispatchY = height;
  2764. pShaderOp->DispatchZ = depth;
  2765. // Test Compute Shader
  2766. pShaderOp->CS = CS;
  2767. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTestAfterParse(pDevice, m_support, "Derivatives", nullptr, ShaderOpSet);
  2768. MappedData data;
  2769. test->Test->GetReadBackData("U0", &data);
  2770. const float *pPixels = (float *)data.data();
  2771. // To find roughly the center for compute, divide the pixel count in half,
  2772. // truncate to next lowest power of 16 (4x4), which is the repeating period
  2773. // and then add 10 to reach the point the test expects
  2774. UINT centerIndex = (((UINT64)(width * height * depth)/2) & ~0xF) + 10;
  2775. UINT offsetCenter = centerIndex * pixelSize;
  2776. LogCommentFmt(L"Verifying derivatives in compute shader results");
  2777. VerifyDerivResults(pPixels, offsetCenter);
  2778. if (DoesDeviceSupportMeshAmpDerivatives(pDevice)) {
  2779. // Disable CS so mesh goes forward
  2780. pShaderOp->CS = nullptr;
  2781. test = RunShaderOpTestAfterParse(pDevice, m_support, "Derivatives", nullptr, ShaderOpSet);
  2782. test->Test->GetReadBackData("U1", &data);
  2783. pPixels = (float *)data.data();
  2784. centerIndex = (((UINT64)(mwidth * mheight * mdepth)/2) & ~0xF) + 10;
  2785. offsetCenter = centerIndex * pixelSize;
  2786. LogCommentFmt(L"Verifying derivatives in mesh shader results");
  2787. VerifyDerivResults(pPixels, offsetCenter);
  2788. test->Test->GetReadBackData("U2", &data);
  2789. pPixels = (float *)data.data();
  2790. LogCommentFmt(L"Verifying derivatives in amplification shader results");
  2791. VerifyDerivResults(pPixels, offsetCenter);
  2792. }
  2793. }
  2794. // Final test with not divisible by 4 dispatch size just to make sure it runs
  2795. for (st::ShaderOpShader &S : pShaderOp->Shaders)
  2796. S.Arguments = "-D DISPATCHX=3 -D DISPATCHY=3 -D DISPATCHZ=3 "
  2797. "-D MESHDISPATCHX=3 -D MESHDISPATCHY=3 -D MESHDISPATCHZ=3";
  2798. pShaderOp->DispatchX = 3;
  2799. pShaderOp->DispatchY = 3;
  2800. pShaderOp->DispatchZ = 3;
  2801. // Test Compute Shader
  2802. pShaderOp->CS = CS;
  2803. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTestAfterParse(pDevice, m_support, "Derivatives", nullptr, ShaderOpSet);
  2804. if (DoesDeviceSupportMeshAmpDerivatives(pDevice)) {
  2805. pShaderOp->CS = nullptr;
  2806. test = RunShaderOpTestAfterParse(pDevice, m_support, "Derivatives", nullptr, ShaderOpSet);
  2807. }
  2808. }
  2809. // Verify the results for the quad starting with the given index
  2810. void VerifyQuadReadResults(const UINT *pPixels, UINT quadIndex) {
  2811. for (UINT i = 0; i < 4; i++) {
  2812. UINT ix = quadIndex + i;
  2813. VERIFY_ARE_EQUAL(pPixels[4*ix + 0], ix); // ReadLaneAt own quad index
  2814. VERIFY_ARE_EQUAL(pPixels[4*ix + 1], (ix^1));// ReadAcrossX
  2815. VERIFY_ARE_EQUAL(pPixels[4*ix + 2], (ix^2));// ReadAcrossY
  2816. VERIFY_ARE_EQUAL(pPixels[4*ix + 3], (ix^3));// ReadAcrossDiagonal
  2817. }
  2818. }
  2819. TEST_F(ExecutionTest, QuadReadTest) {
  2820. WEX::TestExecution::SetVerifyOutput verifySettings(WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  2821. CComPtr<IStream> pStream;
  2822. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  2823. CComPtr<ID3D12Device> pDevice;
  2824. if (!CreateDevice(&pDevice))
  2825. return;
  2826. if (GetTestParamUseWARP(UseWarpByDefault())) {
  2827. WEX::Logging::Log::Comment(L"WARP does not support QuadRead in compute shaders.");
  2828. WEX::Logging::Log::Result(WEX::Logging::TestResults::Skipped);
  2829. return;
  2830. }
  2831. std::shared_ptr<st::ShaderOpSet> ShaderOpSet =
  2832. std::make_shared<st::ShaderOpSet>();
  2833. st::ParseShaderOpSetFromStream(pStream, ShaderOpSet.get());
  2834. st::ShaderOp *pShaderOp = ShaderOpSet->GetShaderOp("QuadRead");
  2835. LPCSTR CS = pShaderOp->CS;
  2836. struct Dispatch {
  2837. int x, y, z;
  2838. int mx, my, mz;
  2839. };
  2840. //std::vector<std::tuple<int, int, int, int, int>> dispatches =
  2841. std::vector<Dispatch> dispatches =
  2842. {
  2843. {32, 32, 1, 8, 8, 1},
  2844. {64, 4, 1, 64, 2, 1},
  2845. {1, 4, 64, 1, 4, 32},
  2846. {64, 1, 1, 64, 1, 1},
  2847. {1, 64, 1, 1, 64, 1},
  2848. {1, 1, 64, 1, 1, 64},
  2849. {16, 16, 3, 4, 4, 3},
  2850. {32, 3, 8, 8, 3, 2},
  2851. {3, 1, 64, 3, 1, 32}
  2852. };
  2853. for (Dispatch &D : dispatches) {
  2854. UINT width = D.x;
  2855. UINT height = D.y;
  2856. UINT depth = D.z;
  2857. UINT mwidth = D.mx;
  2858. UINT mheight = D.my;
  2859. UINT mdepth = D.mz;
  2860. // format compiler args
  2861. char compilerOptions[256];
  2862. VERIFY_IS_TRUE(sprintf_s(compilerOptions, sizeof(compilerOptions),
  2863. "-D DISPATCHX=%d -D DISPATCHY=%d -D DISPATCHZ=%d "
  2864. "-D MESHDISPATCHX=%d -D MESHDISPATCHY=%d -D MESHDISPATCHZ=%d",
  2865. width, height, depth, mwidth, mheight, mdepth));
  2866. for (st::ShaderOpShader &S : pShaderOp->Shaders)
  2867. S.Arguments = compilerOptions;
  2868. pShaderOp->DispatchX = width;
  2869. pShaderOp->DispatchY = height;
  2870. pShaderOp->DispatchZ = depth;
  2871. // Test Compute Shader
  2872. pShaderOp->CS = CS;
  2873. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTestAfterParse(pDevice, m_support, "QuadRead", nullptr, ShaderOpSet);
  2874. MappedData data;
  2875. test->Test->GetReadBackData("U0", &data);
  2876. const UINT *pPixels = (UINT *)data.data();
  2877. // To find roughly the center for compute, divide the pixel count in half
  2878. // and truncate to next lowest power of 4 to start at a quad
  2879. UINT offsetCenter = ((UINT64)(width * height * depth)/2) & ~0x3;
  2880. // Test first, second and center quads
  2881. LogCommentFmt(L"Verifying QuadRead* in compute shader results");
  2882. VerifyQuadReadResults(pPixels, 0);
  2883. VerifyQuadReadResults(pPixels, 4);
  2884. VerifyQuadReadResults(pPixels, offsetCenter);
  2885. if (DoesDeviceSupportMeshAmpDerivatives(pDevice)) {
  2886. offsetCenter = ((UINT64)(mwidth * mheight * mdepth)/2) & ~0x3;
  2887. // Disable CS so mesh goes forward
  2888. pShaderOp->CS = nullptr;
  2889. test = RunShaderOpTestAfterParse(pDevice, m_support, "QuadRead", nullptr, ShaderOpSet);
  2890. test->Test->GetReadBackData("U1", &data);
  2891. pPixels = (UINT *)data.data();
  2892. // Test first, second and center quads
  2893. LogCommentFmt(L"Verifying QuadRead* in mesh shader results");
  2894. VerifyQuadReadResults(pPixels, 0);
  2895. VerifyQuadReadResults(pPixels, 4);
  2896. VerifyQuadReadResults(pPixels, offsetCenter);
  2897. test->Test->GetReadBackData("U2", &data);
  2898. pPixels = (UINT *)data.data();
  2899. // Test first, second and center quads
  2900. LogCommentFmt(L"Verifying QuadRead* in amplification shader results");
  2901. VerifyQuadReadResults(pPixels, 0);
  2902. VerifyQuadReadResults(pPixels, 4);
  2903. VerifyQuadReadResults(pPixels, offsetCenter);
  2904. }
  2905. }
  2906. }
  2907. void VerifySampleResults(const UINT *pPixels, UINT width) {
  2908. UINT xlod = 0;
  2909. UINT ylod = 0;
  2910. // Each pixel contains 4 samples and 4 LOD calculations.
  2911. // 2 of these (called 'left' and 'right') have X values that vary and a constant Y
  2912. // 2 others (called 'top' and 'bot') have Y values that vary and a constant X
  2913. // Only of the X variant sample results and one of the Y variant results
  2914. // are actually reported for the pixel.
  2915. // The other 2 serve as "helpers" to the other pixels in the quad.
  2916. // On the left side of the quad, the 'left' samples are reported.
  2917. // Op the top of the quad, the 'top' samples are reported and so on.
  2918. // The varying coordinate values alternate between zero and a
  2919. // value whose magnitude increases with the index.
  2920. // As a result, the LOD level should steadily increas.
  2921. // Due to vagaries of implementation, the same derivatives
  2922. // in both directions might result in different levels for different locations
  2923. // in the quad. So only comparisons between sample results and LOD calculations
  2924. // and ensuring that the LOD increased and reaches the max can be tested reliably.
  2925. for (unsigned i = 0; i < width; i++) {
  2926. // CalculateLOD and Sample from texture with mip levels containing LOD index should match
  2927. VERIFY_ARE_EQUAL(pPixels[4*i + 0], pPixels[4*i + 1]);
  2928. VERIFY_ARE_EQUAL(pPixels[4*i + 2], pPixels[4*i + 3]);
  2929. // Make sure LODs are ever climbing as magnitudes increase
  2930. VERIFY_IS_TRUE(pPixels[4*i] >= xlod);
  2931. xlod = pPixels[4*i];
  2932. VERIFY_IS_TRUE(pPixels[4*i + 2] >= ylod);
  2933. ylod = pPixels[4*i + 2];
  2934. }
  2935. // Make sure we reached the max lod level for both tracks
  2936. VERIFY_ARE_EQUAL(xlod, 6u);
  2937. VERIFY_ARE_EQUAL(ylod, 6u);
  2938. }
  2939. TEST_F(ExecutionTest, ComputeSampleTest) {
  2940. WEX::TestExecution::SetVerifyOutput verifySettings(WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  2941. CComPtr<IStream> pStream;
  2942. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  2943. CComPtr<ID3D12Device> pDevice;
  2944. if (!CreateDevice(&pDevice, D3D_SHADER_MODEL_6_6))
  2945. return;
  2946. std::shared_ptr<st::ShaderOpSet> ShaderOpSet =
  2947. std::make_shared<st::ShaderOpSet>();
  2948. st::ParseShaderOpSetFromStream(pStream, ShaderOpSet.get());
  2949. st::ShaderOp *pShaderOp = ShaderOpSet->GetShaderOp("ComputeSample");
  2950. // Initialize texture with the LOD number in each corresponding mip level
  2951. auto SampleInitFn = [&](LPCSTR Name, std::vector<BYTE> &Data, st::ShaderOp *pShaderOp) {
  2952. UNREFERENCED_PARAMETER(pShaderOp);
  2953. VERIFY_ARE_EQUAL(0, _stricmp(Name, "T0"));
  2954. D3D12_RESOURCE_DESC &texDesc = pShaderOp->GetResourceByName("T0")->Desc;
  2955. UINT texWidth = (UINT)texDesc.Width;
  2956. UINT texHeight = (UINT)texDesc.Height;
  2957. size_t size = sizeof(float) * texWidth * texHeight * 2;
  2958. Data.resize(size);
  2959. float *pPrimitives = (float *)Data.data();
  2960. float lod = 0.0;
  2961. int ix = 0;
  2962. while (texHeight > 0 && texWidth > 0) {
  2963. if(!texHeight) texHeight = 1;
  2964. if(!texWidth) texWidth = 1;
  2965. for (size_t j = 0; j < texHeight; ++j) {
  2966. for (size_t i = 0; i < texWidth; ++i) {
  2967. pPrimitives[ix++] = lod;
  2968. }
  2969. }
  2970. lod += 1.0;
  2971. texHeight >>= 1;
  2972. texWidth >>= 1;
  2973. }
  2974. };
  2975. LPCSTR CS2 = nullptr, AS2 = nullptr, MS2 = nullptr;
  2976. for (st::ShaderOpShader &S : pShaderOp->Shaders) {
  2977. if (!strcmp(S.Name, "CS2")) CS2 = S.Name;
  2978. if (!strcmp(S.Name, "AS2")) AS2 = S.Name;
  2979. if (!strcmp(S.Name, "MS2")) MS2 = S.Name;
  2980. }
  2981. // Test 1D compute shader
  2982. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTestAfterParse(pDevice, m_support, "ComputeSample", SampleInitFn, ShaderOpSet);
  2983. MappedData data;
  2984. test->Test->GetReadBackData("U0", &data);
  2985. const UINT *pPixels = (UINT *)data.data();
  2986. VerifySampleResults(pPixels, 84*4);
  2987. // Test 2D compute shader
  2988. pShaderOp->CS = CS2;
  2989. test = RunShaderOpTestAfterParse(pDevice, m_support, "ComputeSample", SampleInitFn, ShaderOpSet);
  2990. test->Test->GetReadBackData("U0", &data);
  2991. pPixels = (UINT *)data.data();
  2992. VerifySampleResults(pPixels, 84*4);
  2993. if (DoesDeviceSupportMeshAmpDerivatives(pDevice)) {
  2994. // Disable CS so mesh goes forward
  2995. pShaderOp->CS = nullptr;
  2996. test = RunShaderOpTestAfterParse(pDevice, m_support, "ComputeSample", SampleInitFn, ShaderOpSet);
  2997. test->Test->GetReadBackData("U1", &data);
  2998. pPixels = (UINT *)data.data();
  2999. VerifySampleResults(pPixels, 116);
  3000. test->Test->GetReadBackData("U2", &data);
  3001. pPixels = (UINT *)data.data();
  3002. VerifySampleResults(pPixels, 84);
  3003. pShaderOp->AS = AS2;
  3004. pShaderOp->MS = MS2;
  3005. test = RunShaderOpTestAfterParse(pDevice, m_support, "ComputeSample", SampleInitFn, ShaderOpSet);
  3006. test->Test->GetReadBackData("U1", &data);
  3007. pPixels = (UINT *)data.data();
  3008. VerifySampleResults(pPixels, 116);
  3009. test->Test->GetReadBackData("U2", &data);
  3010. pPixels = (UINT *)data.data();
  3011. VerifySampleResults(pPixels, 84);
  3012. }
  3013. }
  3014. // Executing a simple binop to verify shadel model 6.1 support; runs with
  3015. // ShaderModel61.CoreRequirement
  3016. TEST_F(ExecutionTest, BasicShaderModel61) {
  3017. RunBasicShaderModelTest(D3D_SHADER_MODEL_6_1);
  3018. }
  3019. // Executing a simple binop to verify shadel model 6.3 support; runs with
  3020. // ShaderModel63.CoreRequirement
  3021. TEST_F(ExecutionTest, BasicShaderModel63) {
  3022. RunBasicShaderModelTest(D3D_SHADER_MODEL_6_3);
  3023. }
  3024. void ExecutionTest::RunBasicShaderModelTest(D3D_SHADER_MODEL shaderModel) {
  3025. WEX::TestExecution::SetVerifyOutput verifySettings(
  3026. WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  3027. CComPtr<ID3D12Device> pDevice;
  3028. if (!CreateDevice(&pDevice, shaderModel)) {
  3029. return;
  3030. }
  3031. char *pShaderModelStr;
  3032. if (shaderModel == D3D_SHADER_MODEL_6_1) {
  3033. pShaderModelStr = "cs_6_1";
  3034. } else if (shaderModel == D3D_SHADER_MODEL_6_3) {
  3035. pShaderModelStr = "cs_6_3";
  3036. } else {
  3037. DXASSERT_NOMSG("Invalid Shader Model Parameter");
  3038. pShaderModelStr = nullptr;
  3039. }
  3040. const char shaderTemplate[] =
  3041. "struct SBinaryOp { %s input1; %s input2; %s output; };"
  3042. "RWStructuredBuffer<SBinaryOp> g_buf : register(u0);"
  3043. "[numthreads(8,8,1)]"
  3044. "void main(uint GI : SV_GroupIndex) {"
  3045. " SBinaryOp l = g_buf[GI];"
  3046. " l.output = l.input1 + l.input2;"
  3047. " g_buf[GI] = l;"
  3048. "}";
  3049. char shader[sizeof(shaderTemplate) + 50];
  3050. // Run simple shader with float data types
  3051. char* sTy = "float";
  3052. float inputFloatPairs[] = { 1.5f, -2.8f, 3.23e-5f, 6.0f, 181.621f, 14.978f };
  3053. VERIFY_IS_TRUE(sprintf(shader, shaderTemplate, sTy, sTy, sTy) > 0);
  3054. WEX::Logging::Log::Comment(L"BasicShaderModel float");
  3055. RunBasicShaderModelTest<float>(pDevice, pShaderModelStr, shader, inputFloatPairs, sizeof(inputFloatPairs) / (2 * sizeof(float)));
  3056. // Run simple shader with double data types
  3057. if (DoesDeviceSupportDouble(pDevice)) {
  3058. sTy = "double";
  3059. double inputDoublePairs[] = { 1.5891020, -2.8, 3.23e-5, 1 / 3, 181.91621, 14.654978 };
  3060. VERIFY_IS_TRUE(sprintf(shader, shaderTemplate, sTy, sTy, sTy) > 0);
  3061. WEX::Logging::Log::Comment(L"BasicShaderModel double");
  3062. RunBasicShaderModelTest<double>(pDevice, pShaderModelStr, shader, inputDoublePairs, sizeof(inputDoublePairs) / (2 * sizeof(double)));
  3063. }
  3064. else {
  3065. // Optional feature, so it's correct to not support it if declared as such.
  3066. WEX::Logging::Log::Comment(L"Device does not support double operations.");
  3067. }
  3068. // Run simple shader with int64 types
  3069. if (DoesDeviceSupportInt64(pDevice)) {
  3070. sTy = "int64_t";
  3071. int64_t inputInt64Pairs[] = { 1, -100, 6814684, -9814810, 654, 1021248900 };
  3072. VERIFY_IS_TRUE(sprintf(shader, shaderTemplate, sTy, sTy, sTy) > 0);
  3073. WEX::Logging::Log::Comment(L"BasicShaderModel int64_t");
  3074. RunBasicShaderModelTest<int64_t>(pDevice, pShaderModelStr, shader, inputInt64Pairs, sizeof(inputInt64Pairs) / (2 * sizeof(int64_t)));
  3075. }
  3076. else {
  3077. // Optional feature, so it's correct to not support it if declared as such.
  3078. WEX::Logging::Log::Comment(L"Device does not support int64 operations.");
  3079. }
  3080. }
  3081. template <class Ty>
  3082. const wchar_t* ExecutionTest::BasicShaderModelTest_GetFormatString() {
  3083. DXASSERT_NOMSG("Unsupported type");
  3084. return "";
  3085. }
  3086. template <>
  3087. const wchar_t* ExecutionTest::BasicShaderModelTest_GetFormatString<float>() {
  3088. return L"element #%u: input1 = %6.8f, input1 = %6.8f, output = %6.8f, expected = %6.8f";
  3089. }
  3090. template <>
  3091. const wchar_t* ExecutionTest::BasicShaderModelTest_GetFormatString<double>() {
  3092. return BasicShaderModelTest_GetFormatString<float>();
  3093. }
  3094. template <>
  3095. const wchar_t* ExecutionTest::BasicShaderModelTest_GetFormatString<int64_t>() {
  3096. return L"element #%u: input1 = %ld, input1 = %ld, output = %ld, expected = %ld";
  3097. }
  3098. template <class Ty>
  3099. void ExecutionTest::RunBasicShaderModelTest(CComPtr<ID3D12Device> pDevice, const char *pShaderModelStr, const char *pShader,
  3100. Ty *pInputDataPairs, unsigned inputDataCount) {
  3101. struct SBinaryOp {
  3102. Ty input1;
  3103. Ty input2;
  3104. Ty output;
  3105. };
  3106. CComPtr<IStream> pStream;
  3107. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  3108. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTest(
  3109. pDevice, m_support, pStream, "BinaryFPOp",
  3110. // this callbacked is called when the test is creating the resource to run the test
  3111. [&](LPCSTR Name, std::vector<BYTE> &Data, st::ShaderOp *pShaderOp) {
  3112. UNREFERENCED_PARAMETER(Name);
  3113. pShaderOp->Shaders.at(0).Target = pShaderModelStr;
  3114. pShaderOp->Shaders.at(0).Text = pShader;
  3115. size_t size = sizeof(SBinaryOp) * inputDataCount;
  3116. Data.resize(size);
  3117. SBinaryOp *pPrimitives = (SBinaryOp*)Data.data();
  3118. Ty *pIn = pInputDataPairs;
  3119. for (size_t i = 0; i < inputDataCount; i++, pIn += 2) {
  3120. SBinaryOp *p = &pPrimitives[i];
  3121. p->input1 = pIn[0];
  3122. p->input2 = pIn[1];
  3123. }
  3124. });
  3125. VERIFY_SUCCEEDED(S_OK);
  3126. MappedData data;
  3127. test->Test->GetReadBackData("SBinaryFPOp", &data);
  3128. SBinaryOp *pPrimitives = (SBinaryOp*)data.data();
  3129. const wchar_t* formatStr = BasicShaderModelTest_GetFormatString<Ty>();
  3130. Ty *pIn = pInputDataPairs;
  3131. for (unsigned i = 0; i < inputDataCount; i++, pIn += 2) {
  3132. Ty expValue = pIn[0] + pIn[1];
  3133. SBinaryOp *p = &pPrimitives[i];
  3134. LogCommentFmt(formatStr, i, pIn[0], pIn[1], p->output, expValue);
  3135. VERIFY_ARE_EQUAL(p->output, expValue);
  3136. }
  3137. }
  3138. // Resource structure for data-driven tests.
  3139. struct SUnaryFPOp {
  3140. float input;
  3141. float output;
  3142. };
  3143. struct SBinaryFPOp {
  3144. float input1;
  3145. float input2;
  3146. float output1;
  3147. float output2;
  3148. };
  3149. struct STertiaryFPOp {
  3150. float input1;
  3151. float input2;
  3152. float input3;
  3153. float output;
  3154. };
  3155. struct SUnaryHalfOp {
  3156. uint16_t input;
  3157. uint16_t output;
  3158. };
  3159. struct SBinaryHalfOp {
  3160. uint16_t input1;
  3161. uint16_t input2;
  3162. uint16_t output1;
  3163. uint16_t output2;
  3164. };
  3165. struct STertiaryHalfOp {
  3166. uint16_t input1;
  3167. uint16_t input2;
  3168. uint16_t input3;
  3169. uint16_t output;
  3170. };
  3171. struct SUnaryIntOp {
  3172. int input;
  3173. int output;
  3174. };
  3175. struct SUnaryUintOp {
  3176. unsigned int input;
  3177. unsigned int output;
  3178. };
  3179. struct SBinaryIntOp {
  3180. int input1;
  3181. int input2;
  3182. int output1;
  3183. int output2;
  3184. };
  3185. struct STertiaryIntOp {
  3186. int input1;
  3187. int input2;
  3188. int input3;
  3189. int output;
  3190. };
  3191. struct SBinaryUintOp {
  3192. unsigned int input1;
  3193. unsigned int input2;
  3194. unsigned int output1;
  3195. unsigned int output2;
  3196. };
  3197. struct STertiaryUintOp {
  3198. unsigned int input1;
  3199. unsigned int input2;
  3200. unsigned int input3;
  3201. unsigned int output;
  3202. };
  3203. struct SUnaryInt16Op {
  3204. short input;
  3205. short output;
  3206. };
  3207. struct SUnaryUint16Op {
  3208. unsigned short input;
  3209. unsigned short output;
  3210. };
  3211. struct SBinaryInt16Op {
  3212. short input1;
  3213. short input2;
  3214. short output1;
  3215. short output2;
  3216. };
  3217. struct STertiaryInt16Op {
  3218. short input1;
  3219. short input2;
  3220. short input3;
  3221. short output;
  3222. };
  3223. struct SBinaryUint16Op {
  3224. unsigned short input1;
  3225. unsigned short input2;
  3226. unsigned short output1;
  3227. unsigned short output2;
  3228. };
  3229. struct STertiaryUint16Op {
  3230. unsigned short input1;
  3231. unsigned short input2;
  3232. unsigned short input3;
  3233. unsigned short output;
  3234. };
  3235. // representation for HLSL float vectors
  3236. struct SDotOp {
  3237. XMFLOAT4 input1;
  3238. XMFLOAT4 input2;
  3239. float o_dot2;
  3240. float o_dot3;
  3241. float o_dot4;
  3242. };
  3243. struct Half2
  3244. {
  3245. uint16_t x;
  3246. uint16_t y;
  3247. Half2() = default;
  3248. Half2(const Half2&) = default;
  3249. Half2& operator=(const Half2&) = default;
  3250. Half2(Half2&&) = default;
  3251. Half2& operator=(Half2&&) = default;
  3252. constexpr Half2(uint16_t _x, uint16_t _y) : x(_x), y(_y) {}
  3253. explicit Half2(_In_reads_(2) const uint16_t *pArray) : x(pArray[0]), y(pArray[1]) {}
  3254. };
  3255. struct SDot2AddHalfOp {
  3256. Half2 input1;
  3257. Half2 input2;
  3258. float acc;
  3259. float result;
  3260. };
  3261. struct SDot4AddI8PackedOp {
  3262. uint32_t input1;
  3263. uint32_t input2;
  3264. int32_t acc;
  3265. int32_t result;
  3266. };
  3267. struct SDot4AddU8PackedOp {
  3268. uint32_t input1;
  3269. uint32_t input2;
  3270. uint32_t acc;
  3271. uint32_t result;
  3272. };
  3273. struct SMsad4 {
  3274. unsigned int ref;
  3275. XMUINT2 src;
  3276. XMUINT4 accum;
  3277. XMUINT4 result;
  3278. };
  3279. struct SPackUnpackOpOutPacked
  3280. {
  3281. uint32_t packedUint32;
  3282. uint32_t packedInt32;
  3283. uint32_t packedUint16;
  3284. uint32_t packedInt16;
  3285. uint32_t packedClampedUint32;
  3286. uint32_t packedClampedInt32;
  3287. uint32_t packedClampedUint16;
  3288. uint32_t packedClampedInt16;
  3289. };
  3290. struct SPackUnpackOpOutUnpacked {
  3291. std::array<uint32_t, 4> outputUint32;
  3292. std::array<int32_t, 4> outputInt32;
  3293. std::array<uint16_t, 4> outputUint16;
  3294. std::array<int16_t, 4> outputInt16;
  3295. std::array<uint32_t, 4> outputClampedUint32;
  3296. std::array<int32_t, 4> outputClampedInt32;
  3297. std::array<uint16_t, 4> outputClampedUint16;
  3298. std::array<int16_t, 4> outputClampedInt16;
  3299. };
  3300. // Parameter representation for taef data-driven tests
  3301. struct TableParameter {
  3302. LPCWSTR m_name;
  3303. enum TableParameterType {
  3304. INT8,
  3305. INT16,
  3306. INT32,
  3307. UINT,
  3308. FLOAT,
  3309. HALF,
  3310. DOUBLE,
  3311. STRING,
  3312. BOOL,
  3313. INT8_TABLE,
  3314. INT16_TABLE,
  3315. INT32_TABLE,
  3316. FLOAT_TABLE,
  3317. HALF_TABLE,
  3318. DOUBLE_TABLE,
  3319. STRING_TABLE,
  3320. UINT8_TABLE,
  3321. UINT16_TABLE,
  3322. UINT32_TABLE,
  3323. BOOL_TABLE
  3324. };
  3325. TableParameterType m_type;
  3326. bool m_required; // required parameter
  3327. int8_t m_int8;
  3328. int16_t m_int16;
  3329. int m_int32;
  3330. unsigned int m_uint;
  3331. float m_float;
  3332. uint16_t m_half; // no such thing as half type in c++. Use int16 instead
  3333. double m_double;
  3334. bool m_bool;
  3335. WEX::Common::String m_str;
  3336. std::vector<int8_t> m_int8Table;
  3337. std::vector<int16_t> m_int16Table;
  3338. std::vector<int> m_int32Table;
  3339. std::vector<uint8_t> m_uint8Table;
  3340. std::vector<uint16_t> m_uint16Table;
  3341. std::vector<unsigned int> m_uint32Table;
  3342. std::vector<float> m_floatTable;
  3343. std::vector<uint16_t> m_halfTable; // no such thing as half type in c++
  3344. std::vector<double> m_doubleTable;
  3345. std::vector<bool> m_boolTable;
  3346. std::vector<WEX::Common::String> m_StringTable;
  3347. };
  3348. class TableParameterHandler {
  3349. private:
  3350. HRESULT ParseTableRow();
  3351. public:
  3352. TableParameter* m_table;
  3353. size_t m_tableSize;
  3354. TableParameterHandler(TableParameter *pTable, size_t size) : m_table(pTable), m_tableSize(size) {
  3355. clearTableParameter();
  3356. VERIFY_SUCCEEDED(ParseTableRow());
  3357. }
  3358. TableParameter* GetTableParamByName(LPCWSTR name) {
  3359. for (size_t i = 0; i < m_tableSize; ++i) {
  3360. if (_wcsicmp(name, m_table[i].m_name) == 0) {
  3361. return &m_table[i];
  3362. }
  3363. }
  3364. DXASSERT_ARGS(false, "Invalid Table Parameter Name %s", name);
  3365. return nullptr;
  3366. }
  3367. void clearTableParameter() {
  3368. for (size_t i = 0; i < m_tableSize; ++i) {
  3369. m_table[i].m_int32 = 0;
  3370. m_table[i].m_uint = 0;
  3371. m_table[i].m_double = 0;
  3372. m_table[i].m_bool = false;
  3373. m_table[i].m_str = WEX::Common::String();
  3374. }
  3375. }
  3376. template <class T1>
  3377. std::vector<T1> *GetDataArray(LPCWSTR name) {
  3378. return nullptr;
  3379. }
  3380. template <>
  3381. std::vector<int> *GetDataArray(LPCWSTR name) {
  3382. for (size_t i = 0; i < m_tableSize; ++i) {
  3383. if (_wcsicmp(name, m_table[i].m_name) == 0) {
  3384. return &(m_table[i].m_int32Table);
  3385. }
  3386. }
  3387. DXASSERT_ARGS(false, "Invalid Table Parameter Name %s", name);
  3388. return nullptr;
  3389. }
  3390. template <>
  3391. std::vector<int8_t> *GetDataArray(LPCWSTR name) {
  3392. for (size_t i = 0; i < m_tableSize; ++i) {
  3393. if (_wcsicmp(name, m_table[i].m_name) == 0) {
  3394. return &(m_table[i].m_int8Table);
  3395. }
  3396. }
  3397. DXASSERT_ARGS(false, "Invalid Table Parameter Name %s", name);
  3398. return nullptr;
  3399. }
  3400. template <>
  3401. std::vector<int16_t> *GetDataArray(LPCWSTR name) {
  3402. for (size_t i = 0; i < m_tableSize; ++i) {
  3403. if (_wcsicmp(name, m_table[i].m_name) == 0) {
  3404. return &(m_table[i].m_int16Table);
  3405. }
  3406. }
  3407. DXASSERT_ARGS(false, "Invalid Table Parameter Name %s", name);
  3408. return nullptr;
  3409. }
  3410. template <>
  3411. std::vector<unsigned int> *GetDataArray(LPCWSTR name) {
  3412. for (size_t i = 0; i < m_tableSize; ++i) {
  3413. if (_wcsicmp(name, m_table[i].m_name) == 0) {
  3414. return &(m_table[i].m_uint32Table);
  3415. }
  3416. }
  3417. DXASSERT_ARGS(false, "Invalid Table Parameter Name %s", name);
  3418. return nullptr;
  3419. }
  3420. template <>
  3421. std::vector<float> *GetDataArray(LPCWSTR name) {
  3422. for (size_t i = 0; i < m_tableSize; ++i) {
  3423. if (_wcsicmp(name, m_table[i].m_name) == 0) {
  3424. return &(m_table[i].m_floatTable);
  3425. }
  3426. }
  3427. DXASSERT_ARGS(false, "Invalid Table Parameter Name %s", name);
  3428. return nullptr;
  3429. }
  3430. // TODO: uin16_t may be used to represent two different types when we introduce uint16
  3431. template <>
  3432. std::vector<uint16_t> *GetDataArray(LPCWSTR name) {
  3433. for (size_t i = 0; i < m_tableSize; ++i) {
  3434. if (_wcsicmp(name, m_table[i].m_name) == 0) {
  3435. return &(m_table[i].m_halfTable);
  3436. }
  3437. }
  3438. DXASSERT_ARGS(false, "Invalid Table Parameter Name %s", name);
  3439. return nullptr;
  3440. }
  3441. template <>
  3442. std::vector<double> *GetDataArray(LPCWSTR name) {
  3443. for (size_t i = 0; i < m_tableSize; ++i) {
  3444. if (_wcsicmp(name, m_table[i].m_name) == 0) {
  3445. return &(m_table[i].m_doubleTable);
  3446. }
  3447. }
  3448. DXASSERT_ARGS(false, "Invalid Table Parameter Name %s", name);
  3449. return nullptr;
  3450. }
  3451. template <>
  3452. std::vector<bool> *GetDataArray(LPCWSTR name) {
  3453. for (size_t i = 0; i < m_tableSize; ++i) {
  3454. if (_wcsicmp(name, m_table[i].m_name) == 0) {
  3455. return &(m_table[i].m_boolTable);
  3456. }
  3457. }
  3458. DXASSERT_ARGS(false, "Invalid Table Parameter Name %s", name);
  3459. return nullptr;
  3460. }
  3461. };
  3462. static TableParameter UnaryFPOpParameters[] = {
  3463. { L"ShaderOp.Target", TableParameter::STRING, true },
  3464. { L"ShaderOp.Text", TableParameter::STRING, true },
  3465. { L"Validation.Input1", TableParameter::FLOAT_TABLE, true },
  3466. { L"Validation.Expected1", TableParameter::FLOAT_TABLE, true },
  3467. { L"Validation.Type", TableParameter::STRING, true },
  3468. { L"Validation.Tolerance", TableParameter::DOUBLE, true },
  3469. { L"Warp.Version", TableParameter::UINT, false }
  3470. };
  3471. static TableParameter BinaryFPOpParameters[] = {
  3472. { L"ShaderOp.Target", TableParameter::STRING, true },
  3473. { L"ShaderOp.Text", TableParameter::STRING, true },
  3474. { L"Validation.Input1", TableParameter::FLOAT_TABLE, true },
  3475. { L"Validation.Input2", TableParameter::FLOAT_TABLE, true },
  3476. { L"Validation.Expected1", TableParameter::FLOAT_TABLE, true },
  3477. { L"Validation.Expected2", TableParameter::FLOAT_TABLE, false },
  3478. { L"Validation.Type", TableParameter::STRING, true },
  3479. { L"Validation.Tolerance", TableParameter::DOUBLE, true },
  3480. };
  3481. static TableParameter TertiaryFPOpParameters[] = {
  3482. { L"ShaderOp.Target", TableParameter::STRING, true },
  3483. { L"ShaderOp.Text", TableParameter::STRING, true },
  3484. { L"Validation.Input1", TableParameter::FLOAT_TABLE, true },
  3485. { L"Validation.Input2", TableParameter::FLOAT_TABLE, true },
  3486. { L"Validation.Input3", TableParameter::FLOAT_TABLE, true },
  3487. { L"Validation.Expected1", TableParameter::FLOAT_TABLE, true },
  3488. { L"Validation.Type", TableParameter::STRING, true },
  3489. { L"Validation.Tolerance", TableParameter::DOUBLE, true },
  3490. };
  3491. static TableParameter UnaryHalfOpParameters[] = {
  3492. { L"ShaderOp.Target", TableParameter::STRING, true },
  3493. { L"ShaderOp.Text", TableParameter::STRING, true },
  3494. { L"ShaderOp.Arguments", TableParameter::STRING, true },
  3495. { L"Validation.Input1", TableParameter::HALF_TABLE, true },
  3496. { L"Validation.Expected1", TableParameter::HALF_TABLE, true },
  3497. { L"Validation.Type", TableParameter::STRING, true },
  3498. { L"Validation.Tolerance", TableParameter::DOUBLE, true },
  3499. { L"Warp.Version", TableParameter::UINT, false }
  3500. };
  3501. static TableParameter BinaryHalfOpParameters[] = {
  3502. { L"ShaderOp.Target", TableParameter::STRING, true },
  3503. { L"ShaderOp.Text", TableParameter::STRING, true },
  3504. { L"ShaderOp.Arguments", TableParameter::STRING, true },
  3505. { L"Validation.Input1", TableParameter::HALF_TABLE, true },
  3506. { L"Validation.Input2", TableParameter::HALF_TABLE, true },
  3507. { L"Validation.Expected1", TableParameter::HALF_TABLE, true },
  3508. { L"Validation.Expected2", TableParameter::HALF_TABLE, false },
  3509. { L"Validation.Type", TableParameter::STRING, true },
  3510. { L"Validation.Tolerance", TableParameter::DOUBLE, true },
  3511. };
  3512. static TableParameter TertiaryHalfOpParameters[] = {
  3513. { L"ShaderOp.Target", TableParameter::STRING, true },
  3514. { L"ShaderOp.Text", TableParameter::STRING, true },
  3515. { L"ShaderOp.Arguments", TableParameter::STRING, true },
  3516. { L"Validation.Input1", TableParameter::HALF_TABLE, true },
  3517. { L"Validation.Input2", TableParameter::HALF_TABLE, true },
  3518. { L"Validation.Input3", TableParameter::HALF_TABLE, true },
  3519. { L"Validation.Expected1", TableParameter::HALF_TABLE, true },
  3520. { L"Validation.Type", TableParameter::STRING, true },
  3521. { L"Validation.Tolerance", TableParameter::DOUBLE, true },
  3522. };
  3523. static TableParameter UnaryIntOpParameters[] = {
  3524. { L"ShaderOp.Target", TableParameter::STRING, true },
  3525. { L"ShaderOp.Text", TableParameter::STRING, true },
  3526. { L"Validation.Input1", TableParameter::INT32_TABLE, true },
  3527. { L"Validation.Expected1", TableParameter::INT32_TABLE, true },
  3528. { L"Validation.Tolerance", TableParameter::INT32, true },
  3529. };
  3530. static TableParameter UnaryUintOpParameters[] = {
  3531. { L"ShaderOp.Target", TableParameter::STRING, true },
  3532. { L"ShaderOp.Text", TableParameter::STRING, true },
  3533. { L"Validation.Input1", TableParameter::UINT32_TABLE, true },
  3534. { L"Validation.Expected1", TableParameter::UINT32_TABLE, true },
  3535. { L"Validation.Tolerance", TableParameter::INT32, true },
  3536. };
  3537. static TableParameter BinaryIntOpParameters[] = {
  3538. { L"ShaderOp.Target", TableParameter::STRING, true },
  3539. { L"ShaderOp.Text", TableParameter::STRING, true },
  3540. { L"Validation.Input1", TableParameter::INT32_TABLE, true },
  3541. { L"Validation.Input2", TableParameter::INT32_TABLE, true },
  3542. { L"Validation.Expected1", TableParameter::INT32_TABLE, true },
  3543. { L"Validation.Expected2", TableParameter::INT32_TABLE, false },
  3544. { L"Validation.Tolerance", TableParameter::INT32, true },
  3545. };
  3546. static TableParameter TertiaryIntOpParameters[] = {
  3547. { L"ShaderOp.Target", TableParameter::STRING, true },
  3548. { L"ShaderOp.Text", TableParameter::STRING, true },
  3549. { L"Validation.Input1", TableParameter::INT32_TABLE, true },
  3550. { L"Validation.Input2", TableParameter::INT32_TABLE, true },
  3551. { L"Validation.Input3", TableParameter::INT32_TABLE, true },
  3552. { L"Validation.Expected1", TableParameter::INT32_TABLE, true },
  3553. { L"Validation.Tolerance", TableParameter::INT32, true },
  3554. };
  3555. static TableParameter BinaryUintOpParameters[] = {
  3556. { L"ShaderOp.Target", TableParameter::STRING, true },
  3557. { L"ShaderOp.Text", TableParameter::STRING, true },
  3558. { L"Validation.Input1", TableParameter::UINT32_TABLE, true },
  3559. { L"Validation.Input2", TableParameter::UINT32_TABLE, true },
  3560. { L"Validation.Expected1", TableParameter::UINT32_TABLE, true },
  3561. { L"Validation.Expected2", TableParameter::UINT32_TABLE, false },
  3562. { L"Validation.Tolerance", TableParameter::INT32, true },
  3563. };
  3564. static TableParameter TertiaryUintOpParameters[] = {
  3565. { L"ShaderOp.Target", TableParameter::STRING, true },
  3566. { L"ShaderOp.Text", TableParameter::STRING, true },
  3567. { L"Validation.Input1", TableParameter::UINT32_TABLE, true },
  3568. { L"Validation.Input2", TableParameter::UINT32_TABLE, true },
  3569. { L"Validation.Input3", TableParameter::UINT32_TABLE, true },
  3570. { L"Validation.Expected1", TableParameter::UINT32_TABLE, true },
  3571. { L"Validation.Tolerance", TableParameter::INT32, true },
  3572. };
  3573. static TableParameter UnaryInt16OpParameters[] = {
  3574. { L"ShaderOp.Target", TableParameter::STRING, true },
  3575. { L"ShaderOp.Text", TableParameter::STRING, true },
  3576. { L"ShaderOp.Arguments", TableParameter::STRING, true },
  3577. { L"Validation.Input1", TableParameter::INT16_TABLE, true },
  3578. { L"Validation.Expected1", TableParameter::INT16_TABLE, true },
  3579. { L"Validation.Tolerance", TableParameter::INT32, true },
  3580. };
  3581. static TableParameter UnaryUint16OpParameters[] = {
  3582. { L"ShaderOp.Target", TableParameter::STRING, true },
  3583. { L"ShaderOp.Text", TableParameter::STRING, true },
  3584. { L"ShaderOp.Arguments", TableParameter::STRING, true },
  3585. { L"Validation.Input1", TableParameter::UINT16_TABLE, true },
  3586. { L"Validation.Expected1", TableParameter::UINT16_TABLE, true },
  3587. { L"Validation.Tolerance", TableParameter::INT32, true },
  3588. };
  3589. static TableParameter BinaryInt16OpParameters[] = {
  3590. { L"ShaderOp.Target", TableParameter::STRING, true },
  3591. { L"ShaderOp.Text", TableParameter::STRING, true },
  3592. { L"ShaderOp.Arguments", TableParameter::STRING, true },
  3593. { L"Validation.Input1", TableParameter::INT16_TABLE, true },
  3594. { L"Validation.Input2", TableParameter::INT16_TABLE, true },
  3595. { L"Validation.Expected1", TableParameter::INT16_TABLE, true },
  3596. { L"Validation.Expected2", TableParameter::INT16_TABLE, false },
  3597. { L"Validation.Tolerance", TableParameter::INT32, true },
  3598. };
  3599. static TableParameter TertiaryInt16OpParameters[] = {
  3600. { L"ShaderOp.Target", TableParameter::STRING, true },
  3601. { L"ShaderOp.Text", TableParameter::STRING, true },
  3602. { L"ShaderOp.Arguments", TableParameter::STRING, true },
  3603. { L"Validation.Input1", TableParameter::INT16_TABLE, true },
  3604. { L"Validation.Input2", TableParameter::INT16_TABLE, true },
  3605. { L"Validation.Input3", TableParameter::INT16_TABLE, true },
  3606. { L"Validation.Expected1", TableParameter::INT16_TABLE, true },
  3607. { L"Validation.Tolerance", TableParameter::INT32, true },
  3608. };
  3609. static TableParameter BinaryUint16OpParameters[] = {
  3610. { L"ShaderOp.Target", TableParameter::STRING, true },
  3611. { L"ShaderOp.Text", TableParameter::STRING, true },
  3612. { L"ShaderOp.Arguments", TableParameter::STRING, true },
  3613. { L"Validation.Input1", TableParameter::UINT16_TABLE, true },
  3614. { L"Validation.Input2", TableParameter::UINT16_TABLE, true },
  3615. { L"Validation.Expected1", TableParameter::UINT16_TABLE, true },
  3616. { L"Validation.Expected2", TableParameter::UINT16_TABLE, false },
  3617. { L"Validation.Tolerance", TableParameter::INT32, true },
  3618. };
  3619. static TableParameter TertiaryUint16OpParameters[] = {
  3620. { L"ShaderOp.Target", TableParameter::STRING, true },
  3621. { L"ShaderOp.Text", TableParameter::STRING, true },
  3622. { L"ShaderOp.Arguments", TableParameter::STRING, true },
  3623. { L"Validation.Input1", TableParameter::UINT16_TABLE, true },
  3624. { L"Validation.Input2", TableParameter::UINT16_TABLE, true },
  3625. { L"Validation.Input3", TableParameter::UINT16_TABLE, true },
  3626. { L"Validation.Expected1", TableParameter::UINT16_TABLE, true },
  3627. { L"Validation.Tolerance", TableParameter::INT32, true },
  3628. };
  3629. static TableParameter DotOpParameters[] = {
  3630. { L"ShaderOp.Target", TableParameter::STRING, true },
  3631. { L"ShaderOp.Text", TableParameter::STRING, true },
  3632. { L"Validation.Input1", TableParameter::STRING_TABLE, true },
  3633. { L"Validation.Input2", TableParameter::STRING_TABLE, true },
  3634. { L"Validation.Expected1", TableParameter::STRING_TABLE, true },
  3635. { L"Validation.Expected2", TableParameter::STRING_TABLE, true },
  3636. { L"Validation.Expected3", TableParameter::STRING_TABLE, true },
  3637. { L"Validation.Type", TableParameter::STRING, true },
  3638. { L"Validation.Tolerance", TableParameter::DOUBLE, true },
  3639. };
  3640. static TableParameter Dot2AddHalfOpParameters[] = {
  3641. { L"ShaderOp.Target", TableParameter::STRING, true },
  3642. { L"ShaderOp.Text", TableParameter::STRING, true },
  3643. { L"ShaderOp.Arguments", TableParameter::STRING, true },
  3644. { L"Validation.Input1", TableParameter::STRING_TABLE, true },
  3645. { L"Validation.Input2", TableParameter::STRING_TABLE, true },
  3646. { L"Validation.Input3", TableParameter::FLOAT_TABLE, true },
  3647. { L"Validation.Expected1", TableParameter::FLOAT_TABLE, true },
  3648. { L"Validation.Type", TableParameter::STRING, true },
  3649. { L"Validation.Tolerance", TableParameter::DOUBLE, true },
  3650. };
  3651. static TableParameter Dot4AddI8PackedOpParameters[] = {
  3652. { L"ShaderOp.Target", TableParameter::STRING, true },
  3653. { L"ShaderOp.Text", TableParameter::STRING, true },
  3654. { L"Validation.Input1", TableParameter::UINT32_TABLE, true },
  3655. { L"Validation.Input2", TableParameter::UINT32_TABLE, true },
  3656. { L"Validation.Input3", TableParameter::INT32_TABLE, true },
  3657. { L"Validation.Expected1", TableParameter::INT32_TABLE, true },
  3658. };
  3659. static TableParameter Dot4AddU8PackedOpParameters[] = {
  3660. { L"ShaderOp.Target", TableParameter::STRING, true },
  3661. { L"ShaderOp.Text", TableParameter::STRING, true },
  3662. { L"Validation.Input1", TableParameter::UINT32_TABLE, true },
  3663. { L"Validation.Input2", TableParameter::UINT32_TABLE, true },
  3664. { L"Validation.Input3", TableParameter::UINT32_TABLE, true },
  3665. { L"Validation.Expected1", TableParameter::UINT32_TABLE, true },
  3666. };
  3667. static TableParameter Msad4OpParameters[] = {
  3668. { L"ShaderOp.Text", TableParameter::STRING, true },
  3669. { L"Validation.Tolerance", TableParameter::DOUBLE, true },
  3670. { L"Validation.Input1", TableParameter::UINT32_TABLE, true},
  3671. { L"Validation.Input2", TableParameter::STRING_TABLE, true },
  3672. { L"Validation.Input3", TableParameter::STRING_TABLE, true },
  3673. { L"Validation.Expected1", TableParameter::STRING_TABLE, true }
  3674. };
  3675. static TableParameter WaveIntrinsicsActiveIntParameters[] = {
  3676. { L"ShaderOp.Name", TableParameter::STRING, true },
  3677. { L"ShaderOp.Text", TableParameter::STRING, true },
  3678. { L"Validation.NumInputSet", TableParameter::UINT, true },
  3679. { L"Validation.InputSet1", TableParameter::INT32_TABLE, true },
  3680. { L"Validation.InputSet2", TableParameter::INT32_TABLE, false },
  3681. { L"Validation.InputSet3", TableParameter::INT32_TABLE, false },
  3682. { L"Validation.InputSet4", TableParameter::INT32_TABLE, false }
  3683. };
  3684. static TableParameter WaveIntrinsicsPrefixIntParameters[] = {
  3685. { L"ShaderOp.Name", TableParameter::STRING, true },
  3686. { L"ShaderOp.Text", TableParameter::STRING, true },
  3687. { L"Validation.NumInputSet", TableParameter::UINT, true },
  3688. { L"Validation.InputSet1", TableParameter::INT32_TABLE, true },
  3689. { L"Validation.InputSet2", TableParameter::INT32_TABLE, false },
  3690. { L"Validation.InputSet3", TableParameter::INT32_TABLE, false },
  3691. { L"Validation.InputSet4", TableParameter::INT32_TABLE, false }
  3692. };
  3693. static TableParameter WaveIntrinsicsActiveUintParameters[] = {
  3694. { L"ShaderOp.Name", TableParameter::STRING, true },
  3695. { L"ShaderOp.Text", TableParameter::STRING, true },
  3696. { L"Validation.NumInputSet", TableParameter::UINT, true },
  3697. { L"Validation.InputSet1", TableParameter::UINT32_TABLE, true },
  3698. { L"Validation.InputSet2", TableParameter::UINT32_TABLE, false },
  3699. { L"Validation.InputSet3", TableParameter::UINT32_TABLE, false },
  3700. { L"Validation.InputSet4", TableParameter::UINT32_TABLE, false }
  3701. };
  3702. static TableParameter WaveIntrinsicsPrefixUintParameters[] = {
  3703. { L"ShaderOp.Name", TableParameter::STRING, true },
  3704. { L"ShaderOp.Text", TableParameter::STRING, true },
  3705. { L"Validation.NumInputSet", TableParameter::UINT, true },
  3706. { L"Validation.InputSet1", TableParameter::UINT32_TABLE, true },
  3707. { L"Validation.InputSet2", TableParameter::UINT32_TABLE, false },
  3708. { L"Validation.InputSet3", TableParameter::UINT32_TABLE, false },
  3709. { L"Validation.InputSet4", TableParameter::UINT32_TABLE, false }
  3710. };
  3711. static TableParameter WaveIntrinsicsMultiPrefixIntParameters[] = {
  3712. { L"ShaderOp.Name", TableParameter::STRING, true },
  3713. { L"ShaderOp.Target", TableParameter::STRING, true },
  3714. { L"ShaderOp.Text", TableParameter::STRING, true },
  3715. { L"Validation.Keys", TableParameter::INT32_TABLE, true },
  3716. { L"Validation.Values", TableParameter::INT32_TABLE, true },
  3717. };
  3718. static TableParameter WaveIntrinsicsMultiPrefixUintParameters[] = {
  3719. { L"ShaderOp.Name", TableParameter::STRING, true },
  3720. { L"ShaderOp.Target", TableParameter::STRING, true },
  3721. { L"ShaderOp.Text", TableParameter::STRING, true },
  3722. { L"Validation.Keys", TableParameter::UINT32_TABLE, true },
  3723. { L"Validation.Values", TableParameter::UINT32_TABLE, true },
  3724. };
  3725. static TableParameter WaveIntrinsicsActiveBoolParameters[] = {
  3726. { L"ShaderOp.Name", TableParameter::STRING, true },
  3727. { L"ShaderOp.Text", TableParameter::STRING, true },
  3728. { L"Validation.NumInputSet", TableParameter::UINT, true },
  3729. { L"Validation.InputSet1", TableParameter::BOOL_TABLE, true },
  3730. { L"Validation.InputSet2", TableParameter::BOOL_TABLE, false },
  3731. { L"Validation.InputSet3", TableParameter::BOOL_TABLE, false },
  3732. };
  3733. static TableParameter CBufferTestHalfParameters[] = {
  3734. { L"Validation.InputSet", TableParameter::HALF_TABLE, true },
  3735. };
  3736. static TableParameter DenormBinaryFPOpParameters[] = {
  3737. { L"ShaderOp.Target", TableParameter::STRING, true },
  3738. { L"ShaderOp.Text", TableParameter::STRING, true },
  3739. { L"ShaderOp.Arguments", TableParameter::STRING, true },
  3740. { L"Validation.Input1", TableParameter::STRING_TABLE, true },
  3741. { L"Validation.Input2", TableParameter::STRING_TABLE, true },
  3742. { L"Validation.Expected1", TableParameter::STRING_TABLE, true },
  3743. { L"Validation.Expected2", TableParameter::STRING_TABLE, false },
  3744. { L"Validation.Type", TableParameter::STRING, true },
  3745. { L"Validation.Tolerance", TableParameter::DOUBLE, true },
  3746. };
  3747. static TableParameter DenormTertiaryFPOpParameters[] = {
  3748. { L"ShaderOp.Target", TableParameter::STRING, true },
  3749. { L"ShaderOp.Text", TableParameter::STRING, true },
  3750. { L"ShaderOp.Arguments", TableParameter::STRING, true },
  3751. { L"Validation.Input1", TableParameter::STRING_TABLE, true },
  3752. { L"Validation.Input2", TableParameter::STRING_TABLE, true },
  3753. { L"Validation.Input3", TableParameter::STRING_TABLE, true },
  3754. { L"Validation.Expected1", TableParameter::STRING_TABLE, true },
  3755. { L"Validation.Expected2", TableParameter::STRING_TABLE, false },
  3756. { L"Validation.Type", TableParameter::STRING, true },
  3757. { L"Validation.Tolerance", TableParameter::DOUBLE, true },
  3758. };
  3759. static TableParameter PackUnpackOpParameters[] = {
  3760. { L"ShaderOp.Text", TableParameter::STRING, true },
  3761. { L"Validation.Type", TableParameter::STRING, true },
  3762. { L"Validation.Tolerance", TableParameter::UINT, true },
  3763. { L"Validation.Input", TableParameter::UINT32_TABLE, true },
  3764. };
  3765. static bool IsHexString(PCWSTR str, uint16_t *value) {
  3766. std::wstring wString(str);
  3767. wString.erase(std::remove(wString.begin(), wString.end(), L' '), wString.end());
  3768. LPCWSTR wstr = wString.c_str();
  3769. if (wcsncmp(wstr, L"0x", 2) == 0 || wcsncmp(wstr, L"0b", 2) == 0) {
  3770. *value = (uint16_t)wcstol(wstr, NULL, 0);
  3771. return true;
  3772. }
  3773. return false;
  3774. }
  3775. static HRESULT ParseDataToFloat(PCWSTR str, float &value) {
  3776. std::wstring wString(str);
  3777. wString.erase(std::remove(wString.begin(), wString.end(), L' '), wString.end());
  3778. PCWSTR wstr = wString.data();
  3779. if (_wcsicmp(wstr, L"NaN") == 0) {
  3780. value = NAN;
  3781. } else if (_wcsicmp(wstr, L"-inf") == 0) {
  3782. value = -(INFINITY);
  3783. } else if (_wcsicmp(wstr, L"inf") == 0) {
  3784. value = INFINITY;
  3785. } else if (_wcsicmp(wstr, L"-denorm") == 0) {
  3786. value = -(FLT_MIN / 2);
  3787. } else if (_wcsicmp(wstr, L"denorm") == 0) {
  3788. value = FLT_MIN / 2;
  3789. } else if (_wcsicmp(wstr, L"-0.0f") == 0 || _wcsicmp(wstr, L"-0.0") == 0 ||
  3790. _wcsicmp(wstr, L"-0") == 0) {
  3791. value = -0.0f;
  3792. } else if (_wcsicmp(wstr, L"0.0f") == 0 || _wcsicmp(wstr, L"0.0") == 0 ||
  3793. _wcsicmp(wstr, L"0") == 0) {
  3794. value = 0.0f;
  3795. } else if (_wcsnicmp(wstr, L"0x", 2) == 0) { // For hex values, take values literally
  3796. unsigned temp_i = std::stoul(wstr, nullptr, 16);
  3797. value = (float&)temp_i;
  3798. }
  3799. else {
  3800. // evaluate the expression of wstring
  3801. double val = _wtof(wstr);
  3802. if (val == 0) {
  3803. LogErrorFmt(L"Failed to parse parameter %s to float", wstr);
  3804. return E_FAIL;
  3805. }
  3806. value = (float)val;
  3807. }
  3808. return S_OK;
  3809. }
  3810. static HRESULT ParseDataToInt(PCWSTR str, int &value) {
  3811. std::wstring wString(str);
  3812. wString.erase(std::remove(wString.begin(), wString.end(), L' '), wString.end());
  3813. PCWSTR wstr = wString.data();
  3814. // evaluate the expression of string
  3815. if (_wcsicmp(wstr, L"0.0") == 0 || _wcsicmp(wstr, L"0") == 0) {
  3816. value = 0;
  3817. return S_OK;
  3818. }
  3819. int val = _wtoi(wstr);
  3820. if (val == 0) {
  3821. LogErrorFmt(L"Failed to parse parameter %s to int", wstr);
  3822. return E_FAIL;
  3823. }
  3824. value = val;
  3825. return S_OK;
  3826. }
  3827. static HRESULT ParseDataToUint(PCWSTR str, unsigned int &value) {
  3828. std::wstring wString(str);
  3829. wString.erase(std::remove(wString.begin(), wString.end(), L' '), wString.end());
  3830. PCWSTR wstr = wString.data();
  3831. // evaluate the expression of string
  3832. if (_wcsicmp(wstr, L"0") == 0 || _wcsicmp(wstr, L"0x00000000") == 0) {
  3833. value = 0;
  3834. return S_OK;
  3835. }
  3836. wchar_t *end;
  3837. unsigned int val = std::wcstoul(wstr, &end, 0);
  3838. if (val == 0) {
  3839. LogErrorFmt(L"Failed to parse parameter %s to int", wstr);
  3840. return E_FAIL;
  3841. }
  3842. value = val;
  3843. return S_OK;
  3844. }
  3845. static HRESULT ParseDataToVectorFloat(PCWSTR str, float *ptr, size_t count) {
  3846. std::wstring wstr(str);
  3847. size_t curPosition = 0;
  3848. // parse a string of dot product separated by commas
  3849. for (size_t i = 0; i < count; ++i) {
  3850. size_t nextPosition = wstr.find(L",", curPosition);
  3851. if (FAILED(ParseDataToFloat(
  3852. wstr.substr(curPosition, nextPosition - curPosition).data(),
  3853. *(ptr + i)))) {
  3854. return E_FAIL;
  3855. }
  3856. curPosition = nextPosition + 1;
  3857. }
  3858. return S_OK;
  3859. }
  3860. static HRESULT ParseDataToVectorHalf(PCWSTR str, uint16_t *ptr, size_t count) {
  3861. std::wstring wstr(str);
  3862. size_t curPosition = 0;
  3863. // parse a string of dot product separated by commas
  3864. for (size_t i = 0; i < count; ++i) {
  3865. size_t nextPosition = wstr.find(L",", curPosition);
  3866. float floatValue;
  3867. if (FAILED(ParseDataToFloat(
  3868. wstr.substr(curPosition, nextPosition - curPosition).data(), floatValue))) {
  3869. return E_FAIL;
  3870. }
  3871. *(ptr + i) = ConvertFloat32ToFloat16(floatValue);
  3872. curPosition = nextPosition + 1;
  3873. }
  3874. return S_OK;
  3875. }
  3876. static HRESULT ParseDataToVectorUint(PCWSTR str, unsigned int *ptr, size_t count) {
  3877. std::wstring wstr(str);
  3878. size_t curPosition = 0;
  3879. // parse a string of dot product separated by commas
  3880. for (size_t i = 0; i < count; ++i) {
  3881. size_t nextPosition = wstr.find(L",", curPosition);
  3882. if (FAILED(ParseDataToUint(
  3883. wstr.substr(curPosition, nextPosition - curPosition).data(),
  3884. *(ptr + i)))) {
  3885. return E_FAIL;
  3886. }
  3887. curPosition = nextPosition + 1;
  3888. }
  3889. return S_OK;
  3890. }
  3891. HRESULT TableParameterHandler::ParseTableRow() {
  3892. TableParameter *table = m_table;
  3893. for (unsigned int i = 0; i < m_tableSize; ++i) {
  3894. switch (table[i].m_type) {
  3895. case TableParameter::INT8:
  3896. if (FAILED(WEX::TestExecution::TestData::TryGetValue(table[i].m_name,
  3897. table[i].m_int32)) && table[i].m_required) {
  3898. // TryGetValue does not suppport reading from int16
  3899. LogErrorFmt(L"Failed to get %s", table[i].m_name);
  3900. return E_FAIL;
  3901. }
  3902. table[i].m_int8 = (int8_t)(table[i].m_int32);
  3903. break;
  3904. case TableParameter::INT16:
  3905. if (FAILED(WEX::TestExecution::TestData::TryGetValue(table[i].m_name,
  3906. table[i].m_int32)) && table[i].m_required) {
  3907. // TryGetValue does not suppport reading from int16
  3908. LogErrorFmt(L"Failed to get %s", table[i].m_name);
  3909. return E_FAIL;
  3910. }
  3911. table[i].m_int16 = (short)(table[i].m_int32);
  3912. break;
  3913. case TableParameter::INT32:
  3914. if (FAILED(WEX::TestExecution::TestData::TryGetValue(table[i].m_name,
  3915. table[i].m_int32)) && table[i].m_required) {
  3916. LogErrorFmt(L"Failed to get %s", table[i].m_name);
  3917. return E_FAIL;
  3918. }
  3919. break;
  3920. case TableParameter::UINT:
  3921. if (FAILED(WEX::TestExecution::TestData::TryGetValue(table[i].m_name,
  3922. table[i].m_uint)) && table[i].m_required) {
  3923. LogErrorFmt(L"Failed to get %s", table[i].m_name);
  3924. return E_FAIL;
  3925. }
  3926. break;
  3927. case TableParameter::DOUBLE:
  3928. if (FAILED(WEX::TestExecution::TestData::TryGetValue(
  3929. table[i].m_name, table[i].m_double)) && table[i].m_required) {
  3930. LogErrorFmt(L"Failed to get %s", table[i].m_name);
  3931. return E_FAIL;
  3932. }
  3933. break;
  3934. case TableParameter::STRING:
  3935. if (FAILED(WEX::TestExecution::TestData::TryGetValue(table[i].m_name,
  3936. table[i].m_str)) && table[i].m_required) {
  3937. LogErrorFmt(L"Failed to get %s", table[i].m_name);
  3938. return E_FAIL;
  3939. }
  3940. break;
  3941. case TableParameter::BOOL:
  3942. if (FAILED(WEX::TestExecution::TestData::TryGetValue(table[i].m_name,
  3943. table[i].m_str)) && table[i].m_bool) {
  3944. LogErrorFmt(L"Failed to get %s", table[i].m_name);
  3945. return E_FAIL;
  3946. }
  3947. break;
  3948. case TableParameter::INT8_TABLE: {
  3949. WEX::TestExecution::TestDataArray<int> tempTable;
  3950. if (FAILED(WEX::TestExecution::TestData::TryGetValue(
  3951. table[i].m_name, tempTable)) && table[i].m_required) {
  3952. LogErrorFmt(L"Failed to get %s", table[i].m_name);
  3953. return E_FAIL;
  3954. }
  3955. // TryGetValue does not suppport reading from int8
  3956. table[i].m_int8Table.resize(tempTable.GetSize());
  3957. for (size_t j = 0, end = tempTable.GetSize(); j != end; ++j) {
  3958. table[i].m_int8Table[j] = (int8_t)tempTable[j];
  3959. }
  3960. break;
  3961. }
  3962. case TableParameter::INT16_TABLE: {
  3963. WEX::TestExecution::TestDataArray<int> tempTable;
  3964. if (FAILED(WEX::TestExecution::TestData::TryGetValue(
  3965. table[i].m_name, tempTable)) && table[i].m_required) {
  3966. LogErrorFmt(L"Failed to get %s", table[i].m_name);
  3967. return E_FAIL;
  3968. }
  3969. // TryGetValue does not suppport reading from int8
  3970. table[i].m_int16Table.resize(tempTable.GetSize());
  3971. for (size_t j = 0, end = tempTable.GetSize(); j != end; ++j) {
  3972. table[i].m_int16Table[j] = (int16_t)tempTable[j];
  3973. }
  3974. break;
  3975. }case TableParameter::INT32_TABLE: {
  3976. WEX::TestExecution::TestDataArray<int> tempTable;
  3977. if (FAILED(WEX::TestExecution::TestData::TryGetValue(
  3978. table[i].m_name, tempTable)) && table[i].m_required) {
  3979. // TryGetValue does not suppport reading from int8
  3980. LogErrorFmt(L"Failed to get %s", table[i].m_name);
  3981. return E_FAIL;
  3982. }
  3983. table[i].m_int32Table.resize(tempTable.GetSize());
  3984. for (size_t j = 0, end = tempTable.GetSize(); j != end; ++j) {
  3985. table[i].m_int32Table[j] = tempTable[j];
  3986. }
  3987. break;
  3988. }
  3989. case TableParameter::UINT8_TABLE: {
  3990. WEX::TestExecution::TestDataArray<int> tempTable;
  3991. if (FAILED(WEX::TestExecution::TestData::TryGetValue(
  3992. table[i].m_name, tempTable)) && table[i].m_required) {
  3993. LogErrorFmt(L"Failed to get %s", table[i].m_name);
  3994. return E_FAIL;
  3995. }
  3996. // TryGetValue does not suppport reading from int8
  3997. table[i].m_int8Table.resize(tempTable.GetSize());
  3998. for (size_t j = 0, end = tempTable.GetSize(); j != end; ++j) {
  3999. table[i].m_int8Table[j] = (uint8_t)tempTable[j];
  4000. }
  4001. break;
  4002. }
  4003. case TableParameter::UINT16_TABLE: {
  4004. WEX::TestExecution::TestDataArray<int> tempTable;
  4005. if (FAILED(WEX::TestExecution::TestData::TryGetValue(
  4006. table[i].m_name, tempTable)) && table[i].m_required) {
  4007. LogErrorFmt(L"Failed to get %s", table[i].m_name);
  4008. return E_FAIL;
  4009. }
  4010. // TryGetValue does not suppport reading from int8
  4011. table[i].m_uint16Table.resize(tempTable.GetSize());
  4012. for (size_t j = 0, end = tempTable.GetSize(); j != end; ++j) {
  4013. table[i].m_uint16Table[j] = (uint16_t)tempTable[j];
  4014. }
  4015. break;
  4016. }
  4017. case TableParameter::UINT32_TABLE: {
  4018. WEX::TestExecution::TestDataArray<unsigned int> tempTable;
  4019. if (FAILED(WEX::TestExecution::TestData::TryGetValue(
  4020. table[i].m_name, tempTable)) && table[i].m_required) {
  4021. // TryGetValue does not suppport reading from int8
  4022. LogErrorFmt(L"Failed to get %s", table[i].m_name);
  4023. return E_FAIL;
  4024. }
  4025. table[i].m_uint32Table.resize(tempTable.GetSize());
  4026. for (size_t j = 0, end = tempTable.GetSize(); j != end; ++j) {
  4027. table[i].m_uint32Table[j] = tempTable[j];
  4028. }
  4029. break;
  4030. }
  4031. case TableParameter::FLOAT_TABLE: {
  4032. WEX::TestExecution::TestDataArray<WEX::Common::String> tempTable;
  4033. if (FAILED(WEX::TestExecution::TestData::TryGetValue(
  4034. table[i].m_name, tempTable)) && table[i].m_required) {
  4035. // TryGetValue does not suppport reading from int8
  4036. LogErrorFmt(L"Failed to get %s", table[i].m_name);
  4037. return E_FAIL;
  4038. }
  4039. table[i].m_floatTable.resize(tempTable.GetSize());
  4040. for (size_t j = 0, end = tempTable.GetSize(); j != end; ++j) {
  4041. ParseDataToFloat(tempTable[j], table[i].m_floatTable[j]);
  4042. }
  4043. break;
  4044. }
  4045. case TableParameter::HALF_TABLE: {
  4046. WEX::TestExecution::TestDataArray<WEX::Common::String> tempTable;
  4047. if (FAILED(WEX::TestExecution::TestData::TryGetValue(
  4048. table[i].m_name, tempTable)) && table[i].m_required) {
  4049. // TryGetValue does not suppport reading from int8
  4050. LogErrorFmt(L"Failed to get %s", table[i].m_name);
  4051. return E_FAIL;
  4052. }
  4053. table[i].m_halfTable.resize(tempTable.GetSize());
  4054. for (size_t j = 0, end = tempTable.GetSize(); j != end; ++j) {
  4055. uint16_t value = 0;
  4056. if (IsHexString(tempTable[j], &value)) {
  4057. table[i].m_halfTable[j] = value;
  4058. }
  4059. else {
  4060. float val;
  4061. ParseDataToFloat(tempTable[j], val);
  4062. if (isdenorm(val))
  4063. table[i].m_halfTable[j] = signbit(val) ? Float16NegDenorm : Float16PosDenorm;
  4064. else
  4065. table[i].m_halfTable[j] = ConvertFloat32ToFloat16(val);
  4066. }
  4067. }
  4068. break;
  4069. }
  4070. case TableParameter::DOUBLE_TABLE: {
  4071. WEX::TestExecution::TestDataArray<double> tempTable;
  4072. if (FAILED(WEX::TestExecution::TestData::TryGetValue(
  4073. table[i].m_name, tempTable)) && table[i].m_required) {
  4074. // TryGetValue does not suppport reading from int8
  4075. LogErrorFmt(L"Failed to get %s", table[i].m_name);
  4076. return E_FAIL;
  4077. }
  4078. table[i].m_doubleTable.resize(tempTable.GetSize());
  4079. for (size_t j = 0, end = tempTable.GetSize(); j != end; ++j) {
  4080. table[i].m_doubleTable[j] = tempTable[j];
  4081. }
  4082. break;
  4083. }
  4084. case TableParameter::BOOL_TABLE: {
  4085. WEX::TestExecution::TestDataArray<bool> tempTable;
  4086. if (FAILED(WEX::TestExecution::TestData::TryGetValue(
  4087. table[i].m_name, tempTable)) && table[i].m_required) {
  4088. // TryGetValue does not suppport reading from int8
  4089. LogErrorFmt(L"Failed to get %s", table[i].m_name);
  4090. return E_FAIL;
  4091. }
  4092. table[i].m_boolTable.resize(tempTable.GetSize());
  4093. for (size_t j = 0, end = tempTable.GetSize(); j != end; ++j) {
  4094. table[i].m_boolTable[j] = tempTable[j];
  4095. }
  4096. break;
  4097. }
  4098. case TableParameter::STRING_TABLE: {
  4099. WEX::TestExecution::TestDataArray<WEX::Common::String> tempTable;
  4100. if (FAILED(WEX::TestExecution::TestData::TryGetValue(
  4101. table[i].m_name, tempTable)) && table[i].m_required) {
  4102. // TryGetValue does not suppport reading from int8
  4103. LogErrorFmt(L"Failed to get %s", table[i].m_name);
  4104. return E_FAIL;
  4105. }
  4106. table[i].m_StringTable.resize(tempTable.GetSize());
  4107. for (size_t j = 0, end = tempTable.GetSize(); j != end; ++j) {
  4108. table[i].m_StringTable[j] = tempTable[j];
  4109. }
  4110. break;
  4111. }
  4112. default:
  4113. DXASSERT_NOMSG("Invalid Parameter Type");
  4114. }
  4115. if (errno == ERANGE) {
  4116. LogErrorFmt(L"got out of range value for table %s", table[i].m_name);
  4117. return E_FAIL;
  4118. }
  4119. }
  4120. return S_OK;
  4121. }
  4122. static void VerifyOutputWithExpectedValueInt(int output, int ref, int tolerance) {
  4123. VERIFY_IS_TRUE(output - ref <= tolerance && ref - output <= tolerance);
  4124. }
  4125. static void VerifyOutputWithExpectedValueUInt(uint32_t output, uint32_t ref, uint32_t tolerance) {
  4126. VERIFY_IS_TRUE(output - ref <= tolerance && ref - output <= tolerance);
  4127. }
  4128. static void VerifyOutputWithExpectedValueUInt4(XMUINT4 output, XMUINT4 ref) {
  4129. VERIFY_ARE_EQUAL(output.x, ref.x);
  4130. VERIFY_ARE_EQUAL(output.y, ref.y);
  4131. VERIFY_ARE_EQUAL(output.z, ref.z);
  4132. VERIFY_ARE_EQUAL(output.w, ref.w);
  4133. }
  4134. static void VerifyOutputWithExpectedValueFloat(
  4135. float output, float ref, LPCWSTR type, double tolerance,
  4136. hlsl::DXIL::Float32DenormMode mode = hlsl::DXIL::Float32DenormMode::Any) {
  4137. if (_wcsicmp(type, L"Relative") == 0) {
  4138. VERIFY_IS_TRUE(CompareFloatRelativeEpsilon(output, ref, (int)tolerance, mode));
  4139. } else if (_wcsicmp(type, L"Epsilon") == 0) {
  4140. VERIFY_IS_TRUE(CompareFloatEpsilon(output, ref, (float)tolerance, mode));
  4141. } else if (_wcsicmp(type, L"ULP") == 0) {
  4142. VERIFY_IS_TRUE(CompareFloatULP(output, ref, (int)tolerance, mode));
  4143. } else {
  4144. LogErrorFmt(L"Failed to read comparison type %S", type);
  4145. }
  4146. }
  4147. static bool CompareOutputWithExpectedValueFloat(
  4148. float output, float ref, LPCWSTR type, double tolerance,
  4149. hlsl::DXIL::Float32DenormMode mode = hlsl::DXIL::Float32DenormMode::Any) {
  4150. if (_wcsicmp(type, L"Relative") == 0) {
  4151. return CompareFloatRelativeEpsilon(output, ref, (int)tolerance, mode);
  4152. } else if (_wcsicmp(type, L"Epsilon") == 0) {
  4153. return CompareFloatEpsilon(output, ref, (float)tolerance, mode);
  4154. } else if (_wcsicmp(type, L"ULP") == 0) {
  4155. return CompareFloatULP(output, ref, (int)tolerance, mode);
  4156. } else {
  4157. LogErrorFmt(L"Failed to read comparison type %S", type);
  4158. return false;
  4159. }
  4160. }
  4161. static void VerifyOutputWithExpectedValueHalf(
  4162. uint16_t output, uint16_t ref, LPCWSTR type, double tolerance) {
  4163. if (_wcsicmp(type, L"Relative") == 0) {
  4164. VERIFY_IS_TRUE(CompareHalfRelativeEpsilon(output, ref, (int)tolerance));
  4165. }
  4166. else if (_wcsicmp(type, L"Epsilon") == 0) {
  4167. VERIFY_IS_TRUE(CompareHalfEpsilon(output, ref, (float)tolerance));
  4168. }
  4169. else if (_wcsicmp(type, L"ULP") == 0) {
  4170. VERIFY_IS_TRUE(CompareHalfULP(output, ref, (float)tolerance));
  4171. }
  4172. else {
  4173. LogErrorFmt(L"Failed to read comparison type %S", type);
  4174. }
  4175. }
  4176. TEST_F(ExecutionTest, UnaryFloatOpTest) {
  4177. WEX::TestExecution::SetVerifyOutput verifySettings(
  4178. WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  4179. CComPtr<IStream> pStream;
  4180. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  4181. CComPtr<ID3D12Device> pDevice;
  4182. if (!CreateDevice(&pDevice)) {
  4183. return;
  4184. }
  4185. // Read data from the table
  4186. int tableSize = sizeof(UnaryFPOpParameters) / sizeof(TableParameter);
  4187. TableParameterHandler handler(UnaryFPOpParameters, tableSize);
  4188. CW2A Target(handler.GetTableParamByName(L"ShaderOp.Target")->m_str);
  4189. CW2A Text(handler.GetTableParamByName(L"ShaderOp.Text")->m_str);
  4190. unsigned int WarpVersion = handler.GetTableParamByName(L"Warp.Version")->m_uint;
  4191. if (GetTestParamUseWARP(true) && !IsValidWarpDllVersion(WarpVersion)) {
  4192. return;
  4193. }
  4194. std::vector<float> *Validation_Input =
  4195. &(handler.GetTableParamByName(L"Validation.Input1")->m_floatTable);
  4196. std::vector<float> *Validation_Expected =
  4197. &(handler.GetTableParamByName(L"Validation.Expected1")->m_floatTable);
  4198. LPCWSTR Validation_Type = handler.GetTableParamByName(L"Validation.Type")->m_str;
  4199. double Validation_Tolerance = handler.GetTableParamByName(L"Validation.Tolerance")->m_double;
  4200. size_t count = Validation_Input->size();
  4201. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTest(
  4202. pDevice, m_support, pStream, "UnaryFPOp",
  4203. // this callbacked is called when the test
  4204. // is creating the resource to run the test
  4205. [&](LPCSTR Name, std::vector<BYTE> &Data, st::ShaderOp *pShaderOp) {
  4206. VERIFY_IS_TRUE(0 == _stricmp(Name, "SUnaryFPOp"));
  4207. size_t size = sizeof(SUnaryFPOp) * count;
  4208. Data.resize(size);
  4209. SUnaryFPOp *pPrimitives = (SUnaryFPOp *)Data.data();
  4210. for (size_t i = 0; i < count; ++i) {
  4211. SUnaryFPOp *p = &pPrimitives[i];
  4212. p->input = (*Validation_Input)[i % Validation_Input->size()];
  4213. }
  4214. // use shader from data table
  4215. pShaderOp->Shaders.at(0).Target = Target.m_psz;
  4216. pShaderOp->Shaders.at(0).Text = Text.m_psz;
  4217. });
  4218. MappedData data;
  4219. test->Test->GetReadBackData("SUnaryFPOp", &data);
  4220. SUnaryFPOp *pPrimitives = (SUnaryFPOp*)data.data();
  4221. WEX::TestExecution::DisableVerifyExceptions dve;
  4222. for (unsigned i = 0; i < count; ++i) {
  4223. SUnaryFPOp *p = &pPrimitives[i];
  4224. float val = (*Validation_Expected)[i % Validation_Expected->size()];
  4225. LogCommentFmt(
  4226. L"element #%u, input = %6.8f, output = %6.8f, expected = %6.8f", i,
  4227. p->input, p->output, val);
  4228. VerifyOutputWithExpectedValueFloat(p->output, val, Validation_Type, Validation_Tolerance);
  4229. }
  4230. }
  4231. TEST_F(ExecutionTest, BinaryFloatOpTest) {
  4232. WEX::TestExecution::SetVerifyOutput verifySettings(
  4233. WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  4234. CComPtr<IStream> pStream;
  4235. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  4236. CComPtr<ID3D12Device> pDevice;
  4237. if (!CreateDevice(&pDevice)) {
  4238. return;
  4239. }
  4240. // Read data from the table
  4241. int tableSize = sizeof(BinaryFPOpParameters) / sizeof(TableParameter);
  4242. TableParameterHandler handler(BinaryFPOpParameters, tableSize);
  4243. CW2A Target(handler.GetTableParamByName(L"ShaderOp.Target")->m_str);
  4244. CW2A Text(handler.GetTableParamByName(L"ShaderOp.Text")->m_str);
  4245. std::vector<float> *Validation_Input1 =
  4246. &(handler.GetTableParamByName(L"Validation.Input1")->m_floatTable);
  4247. std::vector<float> *Validation_Input2 =
  4248. &(handler.GetTableParamByName(L"Validation.Input2")->m_floatTable);
  4249. std::vector<float> *Validation_Expected1 =
  4250. &(handler.GetTableParamByName(L"Validation.Expected1")->m_floatTable);
  4251. std::vector<float> *Validation_Expected2 =
  4252. &(handler.GetTableParamByName(L"Validation.Expected2")->m_floatTable);
  4253. LPCWSTR Validation_Type = handler.GetTableParamByName(L"Validation.Type")->m_str;
  4254. double Validation_Tolerance = handler.GetTableParamByName(L"Validation.Tolerance")->m_double;
  4255. size_t count = Validation_Input1->size();
  4256. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTest(
  4257. pDevice, m_support, pStream, "BinaryFPOp",
  4258. // this callbacked is called when the test
  4259. // is creating the resource to run the test
  4260. [&](LPCSTR Name, std::vector<BYTE> &Data, st::ShaderOp *pShaderOp) {
  4261. VERIFY_IS_TRUE(0 == _stricmp(Name, "SBinaryFPOp"));
  4262. size_t size = sizeof(SBinaryFPOp) * count;
  4263. Data.resize(size);
  4264. SBinaryFPOp *pPrimitives = (SBinaryFPOp *)Data.data();
  4265. for (size_t i = 0; i < count; ++i) {
  4266. SBinaryFPOp *p = &pPrimitives[i];
  4267. p->input1 = (*Validation_Input1)[i % Validation_Input1->size()];
  4268. p->input2 = (*Validation_Input2)[i % Validation_Input2->size()];
  4269. }
  4270. // use shader from data table
  4271. pShaderOp->Shaders.at(0).Target = Target.m_psz;
  4272. pShaderOp->Shaders.at(0).Text = Text.m_psz;
  4273. });
  4274. MappedData data;
  4275. test->Test->GetReadBackData("SBinaryFPOp", &data);
  4276. SBinaryFPOp *pPrimitives = (SBinaryFPOp *)data.data();
  4277. WEX::TestExecution::DisableVerifyExceptions dve;
  4278. unsigned numExpected = Validation_Expected2->size() == 0 ? 1 : 2;
  4279. if (numExpected == 2) {
  4280. for (unsigned i = 0; i < count; ++i) {
  4281. SBinaryFPOp *p = &pPrimitives[i];
  4282. float val1 = (*Validation_Expected1)[i % Validation_Expected1->size()];
  4283. float val2 = (*Validation_Expected2)[i % Validation_Expected2->size()];
  4284. LogCommentFmt(L"element #%u, input1 = %6.8f, input2 = %6.8f, output1 = "
  4285. L"%6.8f, expected1 = %6.8f, output2 = %6.8f, expected2 = %6.8f",
  4286. i, p->input1, p->input2, p->output1, val1, p->output2,
  4287. val2);
  4288. VerifyOutputWithExpectedValueFloat(p->output1, val1, Validation_Type,
  4289. Validation_Tolerance);
  4290. VerifyOutputWithExpectedValueFloat(p->output2, val2, Validation_Type,
  4291. Validation_Tolerance);
  4292. }
  4293. }
  4294. else if (numExpected == 1) {
  4295. for (unsigned i = 0; i < count; ++i) {
  4296. SBinaryFPOp *p = &pPrimitives[i];
  4297. float val1 = (*Validation_Expected1)[i % Validation_Expected1->size()];
  4298. LogCommentFmt(L"element #%u, input1 = %6.8f, input2 = %6.8f, output1 = "
  4299. L"%6.8f, expected1 = %6.8f",
  4300. i, p->input1, p->input2, p->output1, val1);
  4301. VerifyOutputWithExpectedValueFloat(p->output1, val1, Validation_Type,
  4302. Validation_Tolerance);
  4303. }
  4304. }
  4305. else {
  4306. LogErrorFmt(L"Unexpected number of expected values for operation %i", numExpected);
  4307. }
  4308. }
  4309. TEST_F(ExecutionTest, TertiaryFloatOpTest) {
  4310. WEX::TestExecution::SetVerifyOutput verifySettings(
  4311. WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  4312. CComPtr<IStream> pStream;
  4313. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  4314. CComPtr<ID3D12Device> pDevice;
  4315. if (!CreateDevice(&pDevice)) {
  4316. return;
  4317. }
  4318. // Read data from the table
  4319. int tableSize = sizeof(TertiaryFPOpParameters) / sizeof(TableParameter);
  4320. TableParameterHandler handler(TertiaryFPOpParameters, tableSize);
  4321. CW2A Target(handler.GetTableParamByName(L"ShaderOp.Target")->m_str);
  4322. CW2A Text(handler.GetTableParamByName(L"ShaderOp.Text")->m_str);
  4323. std::vector<float> *Validation_Input1 =
  4324. &(handler.GetTableParamByName(L"Validation.Input1")->m_floatTable);
  4325. std::vector<float> *Validation_Input2 =
  4326. &(handler.GetTableParamByName(L"Validation.Input2")->m_floatTable);
  4327. std::vector<float> *Validation_Input3 =
  4328. &(handler.GetTableParamByName(L"Validation.Input3")->m_floatTable);
  4329. std::vector<float> *Validation_Expected =
  4330. &(handler.GetTableParamByName(L"Validation.Expected1")->m_floatTable);
  4331. LPCWSTR Validation_Type = handler.GetTableParamByName(L"Validation.Type")->m_str;
  4332. double Validation_Tolerance = handler.GetTableParamByName(L"Validation.Tolerance")->m_double;
  4333. size_t count = Validation_Input1->size();
  4334. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTest(
  4335. pDevice, m_support, pStream, "TertiaryFPOp",
  4336. // this callbacked is called when the test
  4337. // is creating the resource to run the test
  4338. [&](LPCSTR Name, std::vector<BYTE> &Data, st::ShaderOp *pShaderOp) {
  4339. VERIFY_IS_TRUE(0 == _stricmp(Name, "STertiaryFPOp"));
  4340. size_t size = sizeof(STertiaryFPOp) * count;
  4341. Data.resize(size);
  4342. STertiaryFPOp *pPrimitives = (STertiaryFPOp *)Data.data();
  4343. for (size_t i = 0; i < count; ++i) {
  4344. STertiaryFPOp *p = &pPrimitives[i];
  4345. p->input1 = (*Validation_Input1)[i % Validation_Input1->size()];
  4346. p->input2 = (*Validation_Input2)[i % Validation_Input2->size()];
  4347. p->input3 = (*Validation_Input3)[i % Validation_Input3->size()];
  4348. }
  4349. // use shader from data table
  4350. pShaderOp->Shaders.at(0).Target = Target.m_psz;
  4351. pShaderOp->Shaders.at(0).Text = Text.m_psz;
  4352. });
  4353. MappedData data;
  4354. test->Test->GetReadBackData("STertiaryFPOp", &data);
  4355. STertiaryFPOp *pPrimitives = (STertiaryFPOp *)data.data();
  4356. WEX::TestExecution::DisableVerifyExceptions dve;
  4357. for (unsigned i = 0; i < count; ++i) {
  4358. STertiaryFPOp *p = &pPrimitives[i];
  4359. float val = (*Validation_Expected)[i % Validation_Expected->size()];
  4360. LogCommentFmt(L"element #%u, input1 = %6.8f, input2 = %6.8f, input3 = %6.8f, output1 = "
  4361. L"%6.8f, expected = %6.8f",
  4362. i, p->input1, p->input2, p->input3, p->output, val);
  4363. VerifyOutputWithExpectedValueFloat(p->output, val, Validation_Type,
  4364. Validation_Tolerance);
  4365. }
  4366. }
  4367. TEST_F(ExecutionTest, UnaryHalfOpTest) {
  4368. WEX::TestExecution::SetVerifyOutput verifySettings(
  4369. WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  4370. CComPtr<IStream> pStream;
  4371. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  4372. CComPtr<ID3D12Device> pDevice;
  4373. if (!CreateDevice(&pDevice, D3D_SHADER_MODEL::D3D_SHADER_MODEL_6_2)) {
  4374. return;
  4375. }
  4376. if (!DoesDeviceSupportNative16bitOps(pDevice)) {
  4377. WEX::Logging::Log::Comment(L"Device does not support native 16-bit operations.");
  4378. WEX::Logging::Log::Result(WEX::Logging::TestResults::Skipped);
  4379. return;
  4380. }
  4381. // Read data from the table
  4382. int tableSize = sizeof(UnaryHalfOpParameters) / sizeof(TableParameter);
  4383. TableParameterHandler handler(UnaryHalfOpParameters, tableSize);
  4384. CW2A Target(handler.GetTableParamByName(L"ShaderOp.Target")->m_str);
  4385. CW2A Text(handler.GetTableParamByName(L"ShaderOp.Text")->m_str);
  4386. CW2A Arguments(handler.GetTableParamByName(L"ShaderOp.Arguments")->m_str);
  4387. unsigned int WarpVersion = handler.GetTableParamByName(L"Warp.Version")->m_uint;
  4388. if (GetTestParamUseWARP(true) && !IsValidWarpDllVersion(WarpVersion)) {
  4389. return;
  4390. }
  4391. std::vector<uint16_t> *Validation_Input =
  4392. &(handler.GetTableParamByName(L"Validation.Input1")->m_halfTable);
  4393. std::vector<uint16_t> *Validation_Expected =
  4394. &(handler.GetTableParamByName(L"Validation.Expected1")->m_halfTable);
  4395. LPCWSTR Validation_Type = handler.GetTableParamByName(L"Validation.Type")->m_str;
  4396. double Validation_Tolerance = handler.GetTableParamByName(L"Validation.Tolerance")->m_double;
  4397. size_t count = Validation_Input->size();
  4398. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTest(
  4399. pDevice, m_support, pStream, "UnaryFPOp",
  4400. // this callbacked is called when the test
  4401. // is creating the resource to run the test
  4402. [&](LPCSTR Name, std::vector<BYTE> &Data, st::ShaderOp *pShaderOp) {
  4403. VERIFY_IS_TRUE(0 == _stricmp(Name, "SUnaryFPOp"));
  4404. size_t size = sizeof(SUnaryHalfOp) * count;
  4405. Data.resize(size);
  4406. SUnaryHalfOp *pPrimitives = (SUnaryHalfOp *)Data.data();
  4407. for (size_t i = 0; i < count; ++i) {
  4408. SUnaryHalfOp *p = &pPrimitives[i];
  4409. p->input = (*Validation_Input)[i % Validation_Input->size()];
  4410. }
  4411. // use shader from data table
  4412. pShaderOp->Shaders.at(0).Target = Target.m_psz;
  4413. pShaderOp->Shaders.at(0).Text = Text.m_psz;
  4414. pShaderOp->Shaders.at(0).Arguments = Arguments.m_psz;
  4415. });
  4416. MappedData data;
  4417. test->Test->GetReadBackData("SUnaryFPOp", &data);
  4418. SUnaryHalfOp *pPrimitives = (SUnaryHalfOp*)data.data();
  4419. WEX::TestExecution::DisableVerifyExceptions dve;
  4420. for (unsigned i = 0; i < count; ++i) {
  4421. SUnaryHalfOp *p = &pPrimitives[i];
  4422. uint16_t expected = (*Validation_Expected)[i % Validation_Input->size()];
  4423. LogCommentFmt(L"element #%u, input = %6.8f(0x%04x), output = "
  4424. L"%6.8f(0x%04x), expected = %6.8f(0x%04x)",
  4425. i, ConvertFloat16ToFloat32(p->input), p->input,
  4426. ConvertFloat16ToFloat32(p->output), p->output,
  4427. ConvertFloat16ToFloat32(expected), expected);
  4428. VerifyOutputWithExpectedValueHalf(p->output, expected, Validation_Type, Validation_Tolerance);
  4429. }
  4430. }
  4431. TEST_F(ExecutionTest, BinaryHalfOpTest) {
  4432. WEX::TestExecution::SetVerifyOutput verifySettings(
  4433. WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  4434. CComPtr<IStream> pStream;
  4435. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  4436. CComPtr<ID3D12Device> pDevice;
  4437. if (!CreateDevice(&pDevice, D3D_SHADER_MODEL::D3D_SHADER_MODEL_6_2)) {
  4438. return;
  4439. }
  4440. if (!DoesDeviceSupportNative16bitOps(pDevice)) {
  4441. WEX::Logging::Log::Comment(L"Device does not support native 16-bit operations.");
  4442. WEX::Logging::Log::Result(WEX::Logging::TestResults::Skipped);
  4443. return;
  4444. }
  4445. // Read data from the table
  4446. int tableSize = sizeof(BinaryHalfOpParameters) / sizeof(TableParameter);
  4447. TableParameterHandler handler(BinaryHalfOpParameters, tableSize);
  4448. CW2A Target(handler.GetTableParamByName(L"ShaderOp.Target")->m_str);
  4449. CW2A Text(handler.GetTableParamByName(L"ShaderOp.Text")->m_str);
  4450. CW2A Arguments(handler.GetTableParamByName(L"ShaderOp.Arguments")->m_str);
  4451. std::vector<uint16_t> *Validation_Input1 =
  4452. &(handler.GetTableParamByName(L"Validation.Input1")->m_halfTable);
  4453. std::vector<uint16_t> *Validation_Input2 =
  4454. &(handler.GetTableParamByName(L"Validation.Input2")->m_halfTable);
  4455. std::vector<uint16_t> *Validation_Expected1 =
  4456. &(handler.GetTableParamByName(L"Validation.Expected1")->m_halfTable);
  4457. std::vector<uint16_t> *Validation_Expected2 =
  4458. &(handler.GetTableParamByName(L"Validation.Expected2")->m_halfTable);
  4459. LPCWSTR Validation_Type = handler.GetTableParamByName(L"Validation.Type")->m_str;
  4460. double Validation_Tolerance = handler.GetTableParamByName(L"Validation.Tolerance")->m_double;
  4461. size_t count = Validation_Input1->size();
  4462. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTest(
  4463. pDevice, m_support, pStream, "BinaryFPOp",
  4464. // this callbacked is called when the test
  4465. // is creating the resource to run the test
  4466. [&](LPCSTR Name, std::vector<BYTE> &Data, st::ShaderOp *pShaderOp) {
  4467. VERIFY_IS_TRUE(0 == _stricmp(Name, "SBinaryFPOp"));
  4468. size_t size = sizeof(SBinaryHalfOp) * count;
  4469. Data.resize(size);
  4470. SBinaryHalfOp *pPrimitives = (SBinaryHalfOp *)Data.data();
  4471. for (size_t i = 0; i < count; ++i) {
  4472. SBinaryHalfOp *p = &pPrimitives[i];
  4473. p->input1 = (*Validation_Input1)[i % Validation_Input1->size()];
  4474. p->input2 = (*Validation_Input2)[i % Validation_Input2->size()];
  4475. }
  4476. // use shader from data table
  4477. pShaderOp->Shaders.at(0).Target = Target.m_psz;
  4478. pShaderOp->Shaders.at(0).Text = Text.m_psz;
  4479. pShaderOp->Shaders.at(0).Arguments = Arguments.m_psz;
  4480. });
  4481. MappedData data;
  4482. test->Test->GetReadBackData("SBinaryFPOp", &data);
  4483. SBinaryHalfOp *pPrimitives = (SBinaryHalfOp *)data.data();
  4484. WEX::TestExecution::DisableVerifyExceptions dve;
  4485. unsigned numExpected = Validation_Expected2->size() == 0 ? 1 : 2;
  4486. if (numExpected == 2) {
  4487. for (unsigned i = 0; i < count; ++i) {
  4488. SBinaryHalfOp *p = &pPrimitives[i];
  4489. uint16_t expected1 = (*Validation_Expected1)[i % Validation_Input1->size()];
  4490. uint16_t expected2 = (*Validation_Expected2)[i % Validation_Input2->size()];
  4491. LogCommentFmt(L"element #%u, input1 = %6.8f(0x%04x), input2 = %6.8f(0x%04x), output1 = "
  4492. L"%6.8f(0x%04x), expected1 = %6.8f(0x%04x), output2 = %6.8f(0x%04x), expected2 = %6.8f(0x%04x)",
  4493. i, ConvertFloat16ToFloat32(p->input1), p->input1,
  4494. ConvertFloat16ToFloat32(p->input2), p->input2,
  4495. ConvertFloat16ToFloat32(p->output1), p->output1,
  4496. ConvertFloat16ToFloat32(p->output2), p->output2,
  4497. ConvertFloat16ToFloat32(expected1), expected1,
  4498. ConvertFloat16ToFloat32(expected2), expected2);
  4499. VerifyOutputWithExpectedValueHalf(p->output1, expected1, Validation_Type, Validation_Tolerance);
  4500. VerifyOutputWithExpectedValueHalf(p->output2, expected2, Validation_Type, Validation_Tolerance);
  4501. }
  4502. }
  4503. else if (numExpected == 1) {
  4504. for (unsigned i = 0; i < count; ++i) {
  4505. uint16_t expected = (*Validation_Expected1)[i % Validation_Input1->size()];
  4506. SBinaryHalfOp *p = &pPrimitives[i];
  4507. LogCommentFmt(L"element #%u, input = %6.8f(0x%04x), output = "
  4508. L"%6.8f(0x%04x), expected = %6.8f(0x%04x)",
  4509. i, ConvertFloat16ToFloat32(p->input1), p->input1,
  4510. ConvertFloat16ToFloat32(p->output1), p->output1,
  4511. ConvertFloat16ToFloat32(expected), expected);
  4512. VerifyOutputWithExpectedValueHalf(p->output1, expected, Validation_Type, Validation_Tolerance);
  4513. }
  4514. }
  4515. else {
  4516. LogErrorFmt(L"Unexpected number of expected values for operation %i", numExpected);
  4517. }
  4518. }
  4519. TEST_F(ExecutionTest, TertiaryHalfOpTest) {
  4520. WEX::TestExecution::SetVerifyOutput verifySettings(
  4521. WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  4522. CComPtr<IStream> pStream;
  4523. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  4524. CComPtr<ID3D12Device> pDevice;
  4525. if (!CreateDevice(&pDevice, D3D_SHADER_MODEL::D3D_SHADER_MODEL_6_2)) {
  4526. return;
  4527. }
  4528. if (!DoesDeviceSupportNative16bitOps(pDevice)) {
  4529. WEX::Logging::Log::Comment(L"Device does not support native 16-bit operations.");
  4530. WEX::Logging::Log::Result(WEX::Logging::TestResults::Skipped);
  4531. return;
  4532. }
  4533. // Read data from the table
  4534. int tableSize = sizeof(TertiaryHalfOpParameters) / sizeof(TableParameter);
  4535. TableParameterHandler handler(TertiaryHalfOpParameters, tableSize);
  4536. CW2A Target(handler.GetTableParamByName(L"ShaderOp.Target")->m_str);
  4537. CW2A Text(handler.GetTableParamByName(L"ShaderOp.Text")->m_str);
  4538. CW2A Arguments(handler.GetTableParamByName(L"ShaderOp.Arguments")->m_str);
  4539. std::vector<uint16_t> *Validation_Input1 =
  4540. &(handler.GetTableParamByName(L"Validation.Input1")->m_halfTable);
  4541. std::vector<uint16_t> *Validation_Input2 =
  4542. &(handler.GetTableParamByName(L"Validation.Input2")->m_halfTable);
  4543. std::vector<uint16_t> *Validation_Input3 =
  4544. &(handler.GetTableParamByName(L"Validation.Input3")->m_halfTable);
  4545. std::vector<uint16_t> *Validation_Expected =
  4546. &(handler.GetTableParamByName(L"Validation.Expected1")->m_halfTable);
  4547. LPCWSTR Validation_Type = handler.GetTableParamByName(L"Validation.Type")->m_str;
  4548. double Validation_Tolerance = handler.GetTableParamByName(L"Validation.Tolerance")->m_double;
  4549. size_t count = Validation_Input1->size();
  4550. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTest(
  4551. pDevice, m_support, pStream, "TertiaryFPOp",
  4552. // this callbacked is called when the test
  4553. // is creating the resource to run the test
  4554. [&](LPCSTR Name, std::vector<BYTE> &Data, st::ShaderOp *pShaderOp) {
  4555. VERIFY_IS_TRUE(0 == _stricmp(Name, "STertiaryFPOp"));
  4556. size_t size = sizeof(STertiaryHalfOp) * count;
  4557. Data.resize(size);
  4558. STertiaryHalfOp *pPrimitives = (STertiaryHalfOp *)Data.data();
  4559. for (size_t i = 0; i < count; ++i) {
  4560. STertiaryHalfOp *p = &pPrimitives[i];
  4561. p->input1 = (*Validation_Input1)[i % Validation_Input1->size()];
  4562. p->input2 = (*Validation_Input2)[i % Validation_Input2->size()];
  4563. p->input3 = (*Validation_Input3)[i % Validation_Input3->size()];
  4564. }
  4565. // use shader from data table
  4566. pShaderOp->Shaders.at(0).Target = Target.m_psz;
  4567. pShaderOp->Shaders.at(0).Text = Text.m_psz;
  4568. pShaderOp->Shaders.at(0).Arguments = Arguments.m_psz;
  4569. });
  4570. MappedData data;
  4571. test->Test->GetReadBackData("STertiaryFPOp", &data);
  4572. STertiaryHalfOp *pPrimitives = (STertiaryHalfOp *)data.data();
  4573. WEX::TestExecution::DisableVerifyExceptions dve;
  4574. for (unsigned i = 0; i < count; ++i) {
  4575. STertiaryHalfOp *p = &pPrimitives[i];
  4576. uint16_t expected = (*Validation_Expected)[i % Validation_Expected->size()];
  4577. LogCommentFmt(L"element #%u, input1 = %6.8f(0x%04x), input2 = %6.8f(0x%04x), input3 = %6.8f(0x%04x), output = "
  4578. L"%6.8f(0x%04x), expected = %6.8f(0x%04x)",
  4579. i, ConvertFloat16ToFloat32(p->input1), p->input1,
  4580. ConvertFloat16ToFloat32(p->input2), p->input2,
  4581. ConvertFloat16ToFloat32(p->input3), p->input3,
  4582. ConvertFloat16ToFloat32(p->output), p->output,
  4583. ConvertFloat16ToFloat32(expected), expected);
  4584. VerifyOutputWithExpectedValueHalf(p->output, expected, Validation_Type, Validation_Tolerance);
  4585. }
  4586. }
  4587. TEST_F(ExecutionTest, UnaryIntOpTest) {
  4588. WEX::TestExecution::SetVerifyOutput verifySettings(
  4589. WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  4590. CComPtr<IStream> pStream;
  4591. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  4592. CComPtr<ID3D12Device> pDevice;
  4593. if (!CreateDevice(&pDevice)) {
  4594. return;
  4595. }
  4596. // Read data from the table
  4597. int tableSize = sizeof(UnaryIntOpParameters) / sizeof(TableParameter);
  4598. TableParameterHandler handler(UnaryIntOpParameters, tableSize);
  4599. CW2A Target(handler.GetTableParamByName(L"ShaderOp.Target")->m_str);
  4600. CW2A Text(handler.GetTableParamByName(L"ShaderOp.Text")->m_str);
  4601. std::vector<int> *Validation_Input =
  4602. &handler.GetTableParamByName(L"Validation.Input1")->m_int32Table;
  4603. std::vector<int> *Validation_Expected =
  4604. &handler.GetTableParamByName(L"Validation.Expected1")->m_int32Table;
  4605. int Validation_Tolerance = handler.GetTableParamByName(L"Validation.Tolerance")->m_int32;
  4606. size_t count = Validation_Input->size();
  4607. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTest(
  4608. pDevice, m_support, pStream, "UnaryIntOp",
  4609. // this callbacked is called when the test
  4610. // is creating the resource to run the test
  4611. [&](LPCSTR Name, std::vector<BYTE> &Data, st::ShaderOp *pShaderOp) {
  4612. VERIFY_IS_TRUE(0 == _stricmp(Name, "SUnaryIntOp"));
  4613. size_t size = sizeof(SUnaryIntOp) * count;
  4614. Data.resize(size);
  4615. SUnaryIntOp *pPrimitives = (SUnaryIntOp *)Data.data();
  4616. for (size_t i = 0; i < count; ++i) {
  4617. SUnaryIntOp *p = &pPrimitives[i];
  4618. int val = (*Validation_Input)[i % Validation_Input->size()];
  4619. p->input = val;
  4620. }
  4621. // use shader data table
  4622. pShaderOp->Shaders.at(0).Target = Target.m_psz;
  4623. pShaderOp->Shaders.at(0).Text = Text.m_psz;
  4624. });
  4625. MappedData data;
  4626. test->Test->GetReadBackData("SUnaryIntOp", &data);
  4627. SUnaryIntOp *pPrimitives = (SUnaryIntOp *)data.data();
  4628. WEX::TestExecution::DisableVerifyExceptions dve;
  4629. for (unsigned i = 0; i < count; ++i) {
  4630. SUnaryIntOp *p = &pPrimitives[i];
  4631. int val = (*Validation_Expected)[i % Validation_Expected->size()];
  4632. LogCommentFmt(L"element #%u, input = %11i(0x%08x), output = %11i(0x%08x), "
  4633. L"expected = %11i(0x%08x)",
  4634. i, p->input, p->input, p->output, p->output, val, val);
  4635. VerifyOutputWithExpectedValueInt(p->output, val, Validation_Tolerance);
  4636. }
  4637. }
  4638. TEST_F(ExecutionTest, UnaryUintOpTest) {
  4639. WEX::TestExecution::SetVerifyOutput verifySettings(
  4640. WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  4641. CComPtr<IStream> pStream;
  4642. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  4643. CComPtr<ID3D12Device> pDevice;
  4644. if (!CreateDevice(&pDevice)) {
  4645. return;
  4646. }
  4647. // Read data from the table
  4648. int tableSize = sizeof(UnaryUintOpParameters) / sizeof(TableParameter);
  4649. TableParameterHandler handler(UnaryUintOpParameters, tableSize);
  4650. CW2A Target(handler.GetTableParamByName(L"ShaderOp.Target")->m_str);
  4651. CW2A Text(handler.GetTableParamByName(L"ShaderOp.Text")->m_str);
  4652. std::vector<unsigned int> *Validation_Input =
  4653. &handler.GetTableParamByName(L"Validation.Input1")->m_uint32Table;
  4654. std::vector<unsigned int> *Validation_Expected =
  4655. &handler.GetTableParamByName(L"Validation.Expected1")->m_uint32Table;
  4656. int Validation_Tolerance = handler.GetTableParamByName(L"Validation.Tolerance")->m_int32;
  4657. size_t count = Validation_Input->size();
  4658. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTest(
  4659. pDevice, m_support, pStream, "UnaryUintOp",
  4660. // this callbacked is called when the test
  4661. // is creating the resource to run the test
  4662. [&](LPCSTR Name, std::vector<BYTE> &Data, st::ShaderOp *pShaderOp) {
  4663. VERIFY_IS_TRUE(0 == _stricmp(Name, "SUnaryUintOp"));
  4664. size_t size = sizeof(SUnaryUintOp) * count;
  4665. Data.resize(size);
  4666. SUnaryUintOp *pPrimitives = (SUnaryUintOp *)Data.data();
  4667. for (size_t i = 0; i < count; ++i) {
  4668. SUnaryUintOp *p = &pPrimitives[i];
  4669. unsigned int val = (*Validation_Input)[i % Validation_Input->size()];
  4670. p->input = val;
  4671. }
  4672. // use shader data table
  4673. pShaderOp->Shaders.at(0).Target = Target.m_psz;
  4674. pShaderOp->Shaders.at(0).Text = Text.m_psz;
  4675. });
  4676. MappedData data;
  4677. test->Test->GetReadBackData("SUnaryUintOp", &data);
  4678. SUnaryUintOp *pPrimitives = (SUnaryUintOp *)data.data();
  4679. WEX::TestExecution::DisableVerifyExceptions dve;
  4680. for (unsigned i = 0; i < count; ++i) {
  4681. SUnaryUintOp *p = &pPrimitives[i];
  4682. unsigned int val = (*Validation_Expected)[i % Validation_Expected->size()];
  4683. LogCommentFmt(L"element #%u, input = %11u(0x%08x), output = %11u(0x%08x), "
  4684. L"expected = %11u(0x%08x)",
  4685. i, p->input, p->input, p->output, p->output, val, val);
  4686. VerifyOutputWithExpectedValueInt(p->output, val, Validation_Tolerance);
  4687. }
  4688. }
  4689. TEST_F(ExecutionTest, BinaryIntOpTest) {
  4690. WEX::TestExecution::SetVerifyOutput verifySettings(
  4691. WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  4692. CComPtr<IStream> pStream;
  4693. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  4694. CComPtr<ID3D12Device> pDevice;
  4695. if (!CreateDevice(&pDevice)) {
  4696. return;
  4697. }
  4698. // Read data from the table
  4699. size_t tableSize = sizeof(BinaryIntOpParameters) / sizeof(TableParameter);
  4700. TableParameterHandler handler(BinaryIntOpParameters, tableSize);
  4701. CW2A Target(handler.GetTableParamByName(L"ShaderOp.Target")->m_str);
  4702. CW2A Text(handler.GetTableParamByName(L"ShaderOp.Text")->m_str);
  4703. std::vector<int> *Validation_Input1 =
  4704. &handler.GetTableParamByName(L"Validation.Input1")->m_int32Table;
  4705. std::vector<int> *Validation_Input2 =
  4706. &handler.GetTableParamByName(L"Validation.Input2")->m_int32Table;
  4707. std::vector<int> *Validation_Expected1 =
  4708. &handler.GetTableParamByName(L"Validation.Expected1")->m_int32Table;
  4709. std::vector<int> *Validation_Expected2 =
  4710. &handler.GetTableParamByName(L"Validation.Expected2")->m_int32Table;
  4711. int Validation_Tolerance = handler.GetTableParamByName(L"Validation.Tolerance")->m_int32;
  4712. size_t count = Validation_Input1->size();
  4713. size_t numExpected = Validation_Expected2->size() == 0 ? 1 : 2;
  4714. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTest(
  4715. pDevice, m_support, pStream, "BinaryIntOp",
  4716. // this callbacked is called when the test
  4717. // is creating the resource to run the test
  4718. [&](LPCSTR Name, std::vector<BYTE> &Data, st::ShaderOp *pShaderOp) {
  4719. VERIFY_IS_TRUE(0 == _stricmp(Name, "SBinaryIntOp"));
  4720. size_t size = sizeof(SBinaryIntOp) * count;
  4721. Data.resize(size);
  4722. SBinaryIntOp *pPrimitives = (SBinaryIntOp *)Data.data();
  4723. for (size_t i = 0; i < count; ++i) {
  4724. SBinaryIntOp *p = &pPrimitives[i];
  4725. int val1 = (*Validation_Input1)[i % Validation_Input1->size()];
  4726. int val2 = (*Validation_Input2)[i % Validation_Input2->size()];
  4727. p->input1 = val1;
  4728. p->input2 = val2;
  4729. }
  4730. // use shader from data table
  4731. pShaderOp->Shaders.at(0).Target = Target.m_psz;
  4732. pShaderOp->Shaders.at(0).Text = Text.m_psz;
  4733. });
  4734. MappedData data;
  4735. test->Test->GetReadBackData("SBinaryIntOp", &data);
  4736. SBinaryIntOp *pPrimitives = (SBinaryIntOp *)data.data();
  4737. WEX::TestExecution::DisableVerifyExceptions dve;
  4738. if (numExpected == 2) {
  4739. for (unsigned i = 0; i < count; ++i) {
  4740. SBinaryIntOp *p = &pPrimitives[i];
  4741. int val1 = (*Validation_Expected1)[i % Validation_Expected1->size()];
  4742. int val2 = (*Validation_Expected2)[i % Validation_Expected2->size()];
  4743. LogCommentFmt(L"element #%u, input1 = %11i(0x%08x), input2 = "
  4744. L"%11i(0x%08x), output1 = "
  4745. L"%11i(0x%08x), expected1 = %11i(0x%08x), output2 = "
  4746. L"%11i(0x%08x), expected2 = %11i(0x%08x)",
  4747. i, p->input1, p->input1, p->input2, p->input2, p->output1,
  4748. p->output1, val1, val1, p->output2, p->output2, val2,
  4749. val2);
  4750. VerifyOutputWithExpectedValueInt(p->output1, val1, Validation_Tolerance);
  4751. VerifyOutputWithExpectedValueInt(p->output2, val2, Validation_Tolerance);
  4752. }
  4753. }
  4754. else if (numExpected == 1) {
  4755. for (unsigned i = 0; i < count; ++i) {
  4756. SBinaryIntOp *p = &pPrimitives[i];
  4757. int val1 = (*Validation_Expected1)[i % Validation_Expected1->size()];
  4758. LogCommentFmt(L"element #%u, input1 = %11i(0x%08x), input2 = "
  4759. L"%11i(0x%08x), output = "
  4760. L"%11i(0x%08x), expected = %11i(0x%08x)", i,
  4761. p->input1, p->input1, p->input2, p->input2,
  4762. p->output1, p->output1, val1, val1);
  4763. VerifyOutputWithExpectedValueInt(p->output1, val1, Validation_Tolerance);
  4764. }
  4765. }
  4766. else {
  4767. LogErrorFmt(L"Unexpected number of expected values for operation %i", numExpected);
  4768. }
  4769. }
  4770. TEST_F(ExecutionTest, TertiaryIntOpTest) {
  4771. WEX::TestExecution::SetVerifyOutput verifySettings(
  4772. WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  4773. CComPtr<IStream> pStream;
  4774. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  4775. CComPtr<ID3D12Device> pDevice;
  4776. if (!CreateDevice(&pDevice)) {
  4777. return;
  4778. }
  4779. // Read data from the table
  4780. size_t tableSize = sizeof(TertiaryIntOpParameters) / sizeof(TableParameter);
  4781. TableParameterHandler handler(TertiaryIntOpParameters, tableSize);
  4782. CW2A Target(handler.GetTableParamByName(L"ShaderOp.Target")->m_str);
  4783. CW2A Text(handler.GetTableParamByName(L"ShaderOp.Text")->m_str);
  4784. std::vector<int> *Validation_Input1 =
  4785. &handler.GetTableParamByName(L"Validation.Input1")->m_int32Table;
  4786. std::vector<int> *Validation_Input2 =
  4787. &handler.GetTableParamByName(L"Validation.Input2")->m_int32Table;
  4788. std::vector<int> *Validation_Input3 =
  4789. &handler.GetTableParamByName(L"Validation.Input3")->m_int32Table;
  4790. std::vector<int> *Validation_Expected =
  4791. &handler.GetTableParamByName(L"Validation.Expected1")->m_int32Table;
  4792. int Validation_Tolerance = handler.GetTableParamByName(L"Validation.Tolerance")->m_int32;
  4793. size_t count = Validation_Input1->size();
  4794. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTest(
  4795. pDevice, m_support, pStream, "TertiaryIntOp",
  4796. // this callbacked is called when the test
  4797. // is creating the resource to run the test
  4798. [&](LPCSTR Name, std::vector<BYTE> &Data, st::ShaderOp *pShaderOp) {
  4799. VERIFY_IS_TRUE(0 == _stricmp(Name, "STertiaryIntOp"));
  4800. size_t size = sizeof(STertiaryIntOp) * count;
  4801. Data.resize(size);
  4802. STertiaryIntOp *pPrimitives = (STertiaryIntOp *)Data.data();
  4803. for (size_t i = 0; i < count; ++i) {
  4804. STertiaryIntOp *p = &pPrimitives[i];
  4805. int val1 = (*Validation_Input1)[i % Validation_Input1->size()];
  4806. int val2 = (*Validation_Input2)[i % Validation_Input2->size()];
  4807. int val3 = (*Validation_Input3)[i % Validation_Input3->size()];
  4808. p->input1 = val1;
  4809. p->input2 = val2;
  4810. p->input3 = val3;
  4811. }
  4812. // use shader from data table
  4813. pShaderOp->Shaders.at(0).Target = Target.m_psz;
  4814. pShaderOp->Shaders.at(0).Text = Text.m_psz;
  4815. });
  4816. MappedData data;
  4817. test->Test->GetReadBackData("STertiaryIntOp", &data);
  4818. STertiaryIntOp *pPrimitives = (STertiaryIntOp *)data.data();
  4819. WEX::TestExecution::DisableVerifyExceptions dve;
  4820. for (unsigned i = 0; i < count; ++i) {
  4821. STertiaryIntOp *p = &pPrimitives[i];
  4822. int val1 = (*Validation_Expected)[i % Validation_Expected->size()];
  4823. LogCommentFmt(L"element #%u, input1 = %11i(0x%08x), input2 = "
  4824. L"%11i(0x%08x), input3= %11i(0x%08x), output = "
  4825. L"%11i(0x%08x), expected = %11i(0x%08x)",
  4826. i, p->input1, p->input1, p->input2, p->input2,
  4827. p->input3, p->input3, p->output, p->output, val1,
  4828. val1);
  4829. VerifyOutputWithExpectedValueInt(p->output, val1, Validation_Tolerance);
  4830. }
  4831. }
  4832. TEST_F(ExecutionTest, BinaryUintOpTest) {
  4833. WEX::TestExecution::SetVerifyOutput verifySettings(
  4834. WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  4835. CComPtr<IStream> pStream;
  4836. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  4837. CComPtr<ID3D12Device> pDevice;
  4838. if (!CreateDevice(&pDevice)) {
  4839. return;
  4840. }
  4841. // Read data from the table
  4842. size_t tableSize = sizeof(BinaryUintOpParameters) / sizeof(TableParameter);
  4843. TableParameterHandler handler(BinaryUintOpParameters, tableSize);
  4844. CW2A Target(handler.GetTableParamByName(L"ShaderOp.Target")->m_str);
  4845. CW2A Text(handler.GetTableParamByName(L"ShaderOp.Text")->m_str);
  4846. std::vector<unsigned int> *Validation_Input1 =
  4847. &handler.GetTableParamByName(L"Validation.Input1")->m_uint32Table;
  4848. std::vector<unsigned int> *Validation_Input2 =
  4849. &handler.GetTableParamByName(L"Validation.Input2")->m_uint32Table;
  4850. std::vector<unsigned int> *Validation_Expected1 =
  4851. &handler.GetTableParamByName(L"Validation.Expected1")->m_uint32Table;
  4852. std::vector<unsigned int> *Validation_Expected2 =
  4853. &handler.GetTableParamByName(L"Validation.Expected2")->m_uint32Table;
  4854. int Validation_Tolerance = handler.GetTableParamByName(L"Validation.Tolerance")->m_int32;
  4855. size_t count = Validation_Input1->size();
  4856. int numExpected = Validation_Expected2->size() == 0 ? 1 : 2;
  4857. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTest(
  4858. pDevice, m_support, pStream, "BinaryUintOp",
  4859. // this callbacked is called when the test
  4860. // is creating the resource to run the test
  4861. [&](LPCSTR Name, std::vector<BYTE> &Data, st::ShaderOp *pShaderOp) {
  4862. VERIFY_IS_TRUE(0 == _stricmp(Name, "SBinaryUintOp"));
  4863. size_t size = sizeof(SBinaryUintOp) * count;
  4864. Data.resize(size);
  4865. SBinaryUintOp *pPrimitives = (SBinaryUintOp *)Data.data();
  4866. for (size_t i = 0; i < count; ++i) {
  4867. SBinaryUintOp *p = &pPrimitives[i];
  4868. unsigned int val1 = (*Validation_Input1)[i % Validation_Input1->size()];
  4869. unsigned int val2 = (*Validation_Input2)[i % Validation_Input2->size()];
  4870. p->input1 = val1;
  4871. p->input2 = val2;
  4872. }
  4873. // use shader from data table
  4874. pShaderOp->Shaders.at(0).Target = Target.m_psz;
  4875. pShaderOp->Shaders.at(0).Text = Text.m_psz;
  4876. });
  4877. MappedData data;
  4878. test->Test->GetReadBackData("SBinaryUintOp", &data);
  4879. SBinaryUintOp *pPrimitives = (SBinaryUintOp *)data.data();
  4880. WEX::TestExecution::DisableVerifyExceptions dve;
  4881. if (numExpected == 2) {
  4882. for (unsigned i = 0; i < count; ++i) {
  4883. SBinaryUintOp *p = &pPrimitives[i];
  4884. unsigned int val1 = (*Validation_Expected1)[i % Validation_Expected1->size()];
  4885. unsigned int val2 = (*Validation_Expected2)[i % Validation_Expected2->size()];
  4886. LogCommentFmt(L"element #%u, input1 = %11u(0x%08x), input2 = "
  4887. L"%11u(0x%08x), output1 = "
  4888. L"%11u(0x%08x), expected1 = %11u(0x%08x), output2 = "
  4889. L"%11u(0x%08x), expected2 = %11u(0x%08x)",
  4890. i, p->input1, p->input1, p->input2, p->input2, p->output1,
  4891. p->output1, val1, val1, p->output2, p->output2, val2,
  4892. val2);
  4893. VerifyOutputWithExpectedValueInt(p->output1, val1, Validation_Tolerance);
  4894. VerifyOutputWithExpectedValueInt(p->output2, val2, Validation_Tolerance);
  4895. }
  4896. }
  4897. else if (numExpected == 1) {
  4898. for (unsigned i = 0; i < count; ++i) {
  4899. SBinaryUintOp *p = &pPrimitives[i];
  4900. unsigned int val1 = (*Validation_Expected1)[i % Validation_Expected1->size()];
  4901. LogCommentFmt(L"element #%u, input1 = %11u(0x%08x), input2 = "
  4902. L"%11u(0x%08x), output = "
  4903. L"%11u(0x%08x), expected = %11u(0x%08x)", i,
  4904. p->input1, p->input1, p->input2, p->input2,
  4905. p->output1, p->output1, val1, val1);
  4906. VerifyOutputWithExpectedValueInt(p->output1, val1, Validation_Tolerance);
  4907. }
  4908. }
  4909. else {
  4910. LogErrorFmt(L"Unexpected number of expected values for operation %i", numExpected);
  4911. }
  4912. }
  4913. TEST_F(ExecutionTest, TertiaryUintOpTest) {
  4914. WEX::TestExecution::SetVerifyOutput verifySettings(
  4915. WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  4916. CComPtr<IStream> pStream;
  4917. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  4918. CComPtr<ID3D12Device> pDevice;
  4919. if (!CreateDevice(&pDevice)) {
  4920. return;
  4921. }
  4922. // Read data from the table
  4923. size_t tableSize = sizeof(TertiaryUintOpParameters) / sizeof(TableParameter);
  4924. TableParameterHandler handler(TertiaryUintOpParameters, tableSize);
  4925. CW2A Target(handler.GetTableParamByName(L"ShaderOp.Target")->m_str);
  4926. CW2A Text(handler.GetTableParamByName(L"ShaderOp.Text")->m_str);
  4927. std::vector<unsigned int> *Validation_Input1 =
  4928. &handler.GetTableParamByName(L"Validation.Input1")->m_uint32Table;
  4929. std::vector<unsigned int> *Validation_Input2 =
  4930. &handler.GetTableParamByName(L"Validation.Input2")->m_uint32Table;
  4931. std::vector<unsigned int> *Validation_Input3 =
  4932. &handler.GetTableParamByName(L"Validation.Input3")->m_uint32Table;
  4933. std::vector<unsigned int> *Validation_Expected =
  4934. &handler.GetTableParamByName(L"Validation.Expected1")->m_uint32Table;
  4935. int Validation_Tolerance = handler.GetTableParamByName(L"Validation.Tolerance")->m_int32;
  4936. size_t count = Validation_Input1->size();
  4937. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTest(
  4938. pDevice, m_support, pStream, "TertiaryUintOp",
  4939. // this callbacked is called when the test
  4940. // is creating the resource to run the test
  4941. [&](LPCSTR Name, std::vector<BYTE> &Data, st::ShaderOp *pShaderOp) {
  4942. VERIFY_IS_TRUE(0 == _stricmp(Name, "STertiaryUintOp"));
  4943. size_t size = sizeof(STertiaryUintOp) * count;
  4944. Data.resize(size);
  4945. STertiaryUintOp *pPrimitives = (STertiaryUintOp *)Data.data();
  4946. for (size_t i = 0; i < count; ++i) {
  4947. STertiaryUintOp *p = &pPrimitives[i];
  4948. unsigned int val1 = (*Validation_Input1)[i % Validation_Input1->size()];
  4949. unsigned int val2 = (*Validation_Input2)[i % Validation_Input2->size()];
  4950. unsigned int val3 = (*Validation_Input3)[i % Validation_Input3->size()];
  4951. p->input1 = val1;
  4952. p->input2 = val2;
  4953. p->input3 = val3;
  4954. }
  4955. // use shader from data table
  4956. pShaderOp->Shaders.at(0).Target = Target.m_psz;
  4957. pShaderOp->Shaders.at(0).Text = Text.m_psz;
  4958. });
  4959. MappedData data;
  4960. test->Test->GetReadBackData("STertiaryUintOp", &data);
  4961. STertiaryUintOp *pPrimitives = (STertiaryUintOp *)data.data();
  4962. WEX::TestExecution::DisableVerifyExceptions dve;
  4963. for (unsigned i = 0; i < count; ++i) {
  4964. STertiaryUintOp *p = &pPrimitives[i];
  4965. unsigned int val1 = (*Validation_Expected)[i % Validation_Expected->size()];
  4966. LogCommentFmt(L"element #%u, input1 = %11u(0x%08x), input2 = "
  4967. L"%11u(0x%08x), input3 = %11u(0x%08x), output = "
  4968. L"%11u(0x%08x), expected = %11u(0x%08x)", i,
  4969. p->input1, p->input1, p->input2, p->input2, p->input3, p->input3,
  4970. p->output, p->output, val1, val1);
  4971. VerifyOutputWithExpectedValueInt(p->output, val1, Validation_Tolerance);
  4972. }
  4973. }
  4974. // 16 bit integer type tests
  4975. TEST_F(ExecutionTest, UnaryInt16OpTest) {
  4976. WEX::TestExecution::SetVerifyOutput verifySettings(
  4977. WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  4978. CComPtr<IStream> pStream;
  4979. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  4980. CComPtr<ID3D12Device> pDevice;
  4981. if (!CreateDevice(&pDevice, D3D_SHADER_MODEL::D3D_SHADER_MODEL_6_2)) {
  4982. return;
  4983. }
  4984. if (!DoesDeviceSupportNative16bitOps(pDevice)) {
  4985. WEX::Logging::Log::Comment(L"Device does not support native 16-bit operations.");
  4986. WEX::Logging::Log::Result(WEX::Logging::TestResults::Skipped);
  4987. return;
  4988. }
  4989. // Read data from the table
  4990. int tableSize = sizeof(UnaryInt16OpParameters) / sizeof(TableParameter);
  4991. TableParameterHandler handler(UnaryInt16OpParameters, tableSize);
  4992. CW2A Target(handler.GetTableParamByName(L"ShaderOp.Target")->m_str);
  4993. CW2A Text(handler.GetTableParamByName(L"ShaderOp.Text")->m_str);
  4994. CW2A Arguments(handler.GetTableParamByName(L"ShaderOp.Arguments")->m_str);
  4995. std::vector<short> *Validation_Input =
  4996. &handler.GetTableParamByName(L"Validation.Input1")->m_int16Table;
  4997. std::vector<short> *Validation_Expected =
  4998. &handler.GetTableParamByName(L"Validation.Expected1")->m_int16Table;
  4999. int Validation_Tolerance = handler.GetTableParamByName(L"Validation.Tolerance")->m_int32;
  5000. size_t count = Validation_Input->size();
  5001. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTest(
  5002. pDevice, m_support, pStream, "UnaryIntOp",
  5003. // this callbacked is called when the test
  5004. // is creating the resource to run the test
  5005. [&](LPCSTR Name, std::vector<BYTE> &Data, st::ShaderOp *pShaderOp) {
  5006. VERIFY_IS_TRUE(0 == _stricmp(Name, "SUnaryIntOp"));
  5007. size_t size = sizeof(SUnaryInt16Op) * count;
  5008. Data.resize(size);
  5009. SUnaryInt16Op *pPrimitives = (SUnaryInt16Op *)Data.data();
  5010. for (size_t i = 0; i < count; ++i) {
  5011. SUnaryInt16Op *p = &pPrimitives[i];
  5012. p->input = (*Validation_Input)[i % Validation_Input->size()];
  5013. }
  5014. // use shader data table
  5015. pShaderOp->Shaders.at(0).Target = Target.m_psz;
  5016. pShaderOp->Shaders.at(0).Text = Text.m_psz;
  5017. pShaderOp->Shaders.at(0).Arguments = Arguments.m_psz;
  5018. });
  5019. MappedData data;
  5020. test->Test->GetReadBackData("SUnaryIntOp", &data);
  5021. SUnaryInt16Op *pPrimitives = (SUnaryInt16Op *)data.data();
  5022. WEX::TestExecution::DisableVerifyExceptions dve;
  5023. for (unsigned i = 0; i < count; ++i) {
  5024. SUnaryInt16Op *p = &pPrimitives[i];
  5025. short val = (*Validation_Expected)[i % Validation_Expected->size()];
  5026. LogCommentFmt(L"element #%u, input = %5hi(0x%08x), output = %5hi(0x%08x), "
  5027. L"expected = %5hi(0x%08x)",
  5028. i, p->input, p->input, p->output, p->output, val, val);
  5029. VerifyOutputWithExpectedValueInt(p->output, val, Validation_Tolerance);
  5030. }
  5031. }
  5032. TEST_F(ExecutionTest, UnaryUint16OpTest) {
  5033. WEX::TestExecution::SetVerifyOutput verifySettings(
  5034. WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  5035. CComPtr<IStream> pStream;
  5036. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  5037. CComPtr<ID3D12Device> pDevice;
  5038. if (!CreateDevice(&pDevice, D3D_SHADER_MODEL::D3D_SHADER_MODEL_6_2)) {
  5039. return;
  5040. }
  5041. if (!DoesDeviceSupportNative16bitOps(pDevice)) {
  5042. WEX::Logging::Log::Comment(L"Device does not support native 16-bit operations.");
  5043. WEX::Logging::Log::Result(WEX::Logging::TestResults::Skipped);
  5044. return;
  5045. }
  5046. // Read data from the table
  5047. int tableSize = sizeof(UnaryUint16OpParameters) / sizeof(TableParameter);
  5048. TableParameterHandler handler(UnaryUint16OpParameters, tableSize);
  5049. CW2A Target(handler.GetTableParamByName(L"ShaderOp.Target")->m_str);
  5050. CW2A Text(handler.GetTableParamByName(L"ShaderOp.Text")->m_str);
  5051. CW2A Arguments(handler.GetTableParamByName(L"ShaderOp.Arguments")->m_str);
  5052. std::vector<unsigned short> *Validation_Input =
  5053. &handler.GetTableParamByName(L"Validation.Input1")->m_uint16Table;
  5054. std::vector<unsigned short> *Validation_Expected =
  5055. &handler.GetTableParamByName(L"Validation.Expected1")->m_uint16Table;
  5056. int Validation_Tolerance = handler.GetTableParamByName(L"Validation.Tolerance")->m_int32;
  5057. size_t count = Validation_Input->size();
  5058. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTest(
  5059. pDevice, m_support, pStream, "UnaryUintOp",
  5060. // this callbacked is called when the test
  5061. // is creating the resource to run the test
  5062. [&](LPCSTR Name, std::vector<BYTE> &Data, st::ShaderOp *pShaderOp) {
  5063. VERIFY_IS_TRUE(0 == _stricmp(Name, "SUnaryUintOp"));
  5064. size_t size = sizeof(SUnaryUint16Op) * count;
  5065. Data.resize(size);
  5066. SUnaryUint16Op *pPrimitives = (SUnaryUint16Op *)Data.data();
  5067. for (size_t i = 0; i < count; ++i) {
  5068. SUnaryUint16Op *p = &pPrimitives[i];
  5069. p->input = (*Validation_Input)[i % Validation_Input->size()];
  5070. }
  5071. // use shader data table
  5072. pShaderOp->Shaders.at(0).Target = Target.m_psz;
  5073. pShaderOp->Shaders.at(0).Text = Text.m_psz;
  5074. pShaderOp->Shaders.at(0).Arguments = Arguments.m_psz;
  5075. });
  5076. MappedData data;
  5077. test->Test->GetReadBackData("SUnaryUintOp", &data);
  5078. SUnaryUint16Op *pPrimitives = (SUnaryUint16Op *)data.data();
  5079. WEX::TestExecution::DisableVerifyExceptions dve;
  5080. for (unsigned i = 0; i < count; ++i) {
  5081. SUnaryUint16Op *p = &pPrimitives[i];
  5082. unsigned short val = (*Validation_Expected)[i % Validation_Expected->size()];
  5083. LogCommentFmt(L"element #%u, input = %5hu(0x%08x), output = %5hu(0x%08x), "
  5084. L"expected = %5hu(0x%08x)",
  5085. i, p->input, p->input, p->output, p->output, val, val);
  5086. VerifyOutputWithExpectedValueInt(p->output, val, Validation_Tolerance);
  5087. }
  5088. }
  5089. TEST_F(ExecutionTest, BinaryInt16OpTest) {
  5090. WEX::TestExecution::SetVerifyOutput verifySettings(
  5091. WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  5092. CComPtr<IStream> pStream;
  5093. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  5094. CComPtr<ID3D12Device> pDevice;
  5095. if (!CreateDevice(&pDevice, D3D_SHADER_MODEL::D3D_SHADER_MODEL_6_2)) {
  5096. return;
  5097. }
  5098. if (!DoesDeviceSupportNative16bitOps(pDevice)) {
  5099. WEX::Logging::Log::Comment(L"Device does not support native 16-bit operations.");
  5100. WEX::Logging::Log::Result(WEX::Logging::TestResults::Skipped);
  5101. return;
  5102. }
  5103. // Read data from the table
  5104. size_t tableSize = sizeof(BinaryInt16OpParameters) / sizeof(TableParameter);
  5105. TableParameterHandler handler(BinaryInt16OpParameters, tableSize);
  5106. CW2A Target(handler.GetTableParamByName(L"ShaderOp.Target")->m_str);
  5107. CW2A Text(handler.GetTableParamByName(L"ShaderOp.Text")->m_str);
  5108. CW2A Arguments(handler.GetTableParamByName(L"ShaderOp.Arguments")->m_str);
  5109. std::vector<short> *Validation_Input1 =
  5110. &handler.GetTableParamByName(L"Validation.Input1")->m_int16Table;
  5111. std::vector<short> *Validation_Input2 =
  5112. &handler.GetTableParamByName(L"Validation.Input2")->m_int16Table;
  5113. std::vector<short> *Validation_Expected1 =
  5114. &handler.GetTableParamByName(L"Validation.Expected1")->m_int16Table;
  5115. std::vector<short> *Validation_Expected2 =
  5116. &handler.GetTableParamByName(L"Validation.Expected2")->m_int16Table;
  5117. int Validation_Tolerance = handler.GetTableParamByName(L"Validation.Tolerance")->m_int32;
  5118. size_t count = Validation_Input1->size();
  5119. size_t numExpected = Validation_Expected2->size() == 0 ? 1 : 2;
  5120. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTest(
  5121. pDevice, m_support, pStream, "BinaryIntOp",
  5122. // this callbacked is called when the test
  5123. // is creating the resource to run the test
  5124. [&](LPCSTR Name, std::vector<BYTE> &Data, st::ShaderOp *pShaderOp) {
  5125. VERIFY_IS_TRUE(0 == _stricmp(Name, "SBinaryIntOp"));
  5126. size_t size = sizeof(SBinaryInt16Op) * count;
  5127. Data.resize(size);
  5128. SBinaryInt16Op *pPrimitives = (SBinaryInt16Op *)Data.data();
  5129. for (size_t i = 0; i < count; ++i) {
  5130. SBinaryInt16Op *p = &pPrimitives[i];
  5131. p->input1 = (*Validation_Input1)[i % Validation_Input1->size()];
  5132. p->input2 = (*Validation_Input2)[i % Validation_Input2->size()];
  5133. }
  5134. // use shader from data table
  5135. pShaderOp->Shaders.at(0).Target = Target.m_psz;
  5136. pShaderOp->Shaders.at(0).Text = Text.m_psz;
  5137. pShaderOp->Shaders.at(0).Arguments = Arguments.m_psz;
  5138. });
  5139. MappedData data;
  5140. test->Test->GetReadBackData("SBinaryIntOp", &data);
  5141. SBinaryInt16Op *pPrimitives = (SBinaryInt16Op *)data.data();
  5142. WEX::TestExecution::DisableVerifyExceptions dve;
  5143. if (numExpected == 2) {
  5144. for (unsigned i = 0; i < count; ++i) {
  5145. SBinaryInt16Op *p = &pPrimitives[i];
  5146. short val1 = (*Validation_Expected1)[i % Validation_Expected1->size()];
  5147. short val2 = (*Validation_Expected2)[i % Validation_Expected2->size()];
  5148. LogCommentFmt(L"element #%u, input1 = %5hi(0x%08x), input2 = "
  5149. L"%5hi(0x%08x), output1 = "
  5150. L"%5hi(0x%08x), expected1 = %5hi(0x%08x), output2 = "
  5151. L"%5hi(0x%08x), expected2 = %5hi(0x%08x)",
  5152. i, p->input1, p->input1, p->input2, p->input2, p->output1,
  5153. p->output1, val1, val1, p->output2, p->output2, val2,
  5154. val2);
  5155. VerifyOutputWithExpectedValueInt(p->output1, val1, Validation_Tolerance);
  5156. VerifyOutputWithExpectedValueInt(p->output2, val2, Validation_Tolerance);
  5157. }
  5158. }
  5159. else if (numExpected == 1) {
  5160. for (unsigned i = 0; i < count; ++i) {
  5161. SBinaryInt16Op *p = &pPrimitives[i];
  5162. short val1 = (*Validation_Expected1)[i % Validation_Expected1->size()];
  5163. LogCommentFmt(L"element #%u, input1 = %5hi(0x%08x), input2 = "
  5164. L"%5hi(0x%08x), output = "
  5165. L"%5hi(0x%08x), expected = %5hi(0x%08x)", i,
  5166. p->input1, p->input1, p->input2, p->input2,
  5167. p->output1, p->output1, val1, val1);
  5168. VerifyOutputWithExpectedValueInt(p->output1, val1, Validation_Tolerance);
  5169. }
  5170. }
  5171. else {
  5172. LogErrorFmt(L"Unexpected number of expected values for operation %i", numExpected);
  5173. }
  5174. }
  5175. TEST_F(ExecutionTest, TertiaryInt16OpTest) {
  5176. WEX::TestExecution::SetVerifyOutput verifySettings(
  5177. WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  5178. CComPtr<IStream> pStream;
  5179. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  5180. CComPtr<ID3D12Device> pDevice;
  5181. if (!CreateDevice(&pDevice, D3D_SHADER_MODEL::D3D_SHADER_MODEL_6_2)) {
  5182. return;
  5183. }
  5184. if (!DoesDeviceSupportNative16bitOps(pDevice)) {
  5185. WEX::Logging::Log::Comment(L"Device does not support native 16-bit operations.");
  5186. WEX::Logging::Log::Result(WEX::Logging::TestResults::Skipped);
  5187. return;
  5188. }
  5189. // Read data from the table
  5190. size_t tableSize = sizeof(TertiaryInt16OpParameters) / sizeof(TableParameter);
  5191. TableParameterHandler handler(TertiaryInt16OpParameters, tableSize);
  5192. CW2A Target(handler.GetTableParamByName(L"ShaderOp.Target")->m_str);
  5193. CW2A Text(handler.GetTableParamByName(L"ShaderOp.Text")->m_str);
  5194. CW2A Arguments(handler.GetTableParamByName(L"ShaderOp.Arguments")->m_str);
  5195. std::vector<short> *Validation_Input1 =
  5196. &handler.GetTableParamByName(L"Validation.Input1")->m_int16Table;
  5197. std::vector<short> *Validation_Input2 =
  5198. &handler.GetTableParamByName(L"Validation.Input2")->m_int16Table;
  5199. std::vector<short> *Validation_Input3 =
  5200. &handler.GetTableParamByName(L"Validation.Input3")->m_int16Table;
  5201. std::vector<short> *Validation_Expected =
  5202. &handler.GetTableParamByName(L"Validation.Expected1")->m_int16Table;
  5203. int Validation_Tolerance = handler.GetTableParamByName(L"Validation.Tolerance")->m_int32;
  5204. size_t count = Validation_Input1->size();
  5205. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTest(
  5206. pDevice, m_support, pStream, "TertiaryIntOp",
  5207. // this callbacked is called when the test
  5208. // is creating the resource to run the test
  5209. [&](LPCSTR Name, std::vector<BYTE> &Data, st::ShaderOp *pShaderOp) {
  5210. VERIFY_IS_TRUE(0 == _stricmp(Name, "STertiaryIntOp"));
  5211. size_t size = sizeof(STertiaryInt16Op) * count;
  5212. Data.resize(size);
  5213. STertiaryInt16Op *pPrimitives = (STertiaryInt16Op *)Data.data();
  5214. for (size_t i = 0; i < count; ++i) {
  5215. STertiaryInt16Op *p = &pPrimitives[i];
  5216. p->input1 = (*Validation_Input1)[i % Validation_Input1->size()];
  5217. p->input2 = (*Validation_Input2)[i % Validation_Input2->size()];
  5218. p->input3 = (*Validation_Input3)[i % Validation_Input3->size()];
  5219. }
  5220. // use shader from data table
  5221. pShaderOp->Shaders.at(0).Target = Target.m_psz;
  5222. pShaderOp->Shaders.at(0).Text = Text.m_psz;
  5223. pShaderOp->Shaders.at(0).Arguments = Arguments.m_psz;
  5224. });
  5225. MappedData data;
  5226. test->Test->GetReadBackData("STertiaryIntOp", &data);
  5227. STertiaryInt16Op *pPrimitives = (STertiaryInt16Op *)data.data();
  5228. WEX::TestExecution::DisableVerifyExceptions dve;
  5229. for (unsigned i = 0; i < count; ++i) {
  5230. STertiaryInt16Op *p = &pPrimitives[i];
  5231. short val1 = (*Validation_Expected)[i % Validation_Expected->size()];
  5232. LogCommentFmt(L"element #%u, input1 = %11i(0x%08x), input2 = "
  5233. L"%11i(0x%08x), input3= %11i(0x%08x), output = "
  5234. L"%11i(0x%08x), expected = %11i(0x%08x)",
  5235. i, p->input1, p->input1, p->input2, p->input2,
  5236. p->input3, p->input3, p->output, p->output, val1,
  5237. val1);
  5238. VerifyOutputWithExpectedValueInt(p->output, val1, Validation_Tolerance);
  5239. }
  5240. }
  5241. TEST_F(ExecutionTest, BinaryUint16OpTest) {
  5242. WEX::TestExecution::SetVerifyOutput verifySettings(
  5243. WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  5244. CComPtr<IStream> pStream;
  5245. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  5246. CComPtr<ID3D12Device> pDevice;
  5247. if (!CreateDevice(&pDevice, D3D_SHADER_MODEL::D3D_SHADER_MODEL_6_2)) {
  5248. return;
  5249. }
  5250. if (!DoesDeviceSupportNative16bitOps(pDevice)) {
  5251. WEX::Logging::Log::Comment(L"Device does not support native 16-bit operations.");
  5252. WEX::Logging::Log::Result(WEX::Logging::TestResults::Skipped);
  5253. return;
  5254. }
  5255. // Read data from the table
  5256. size_t tableSize = sizeof(BinaryUint16OpParameters) / sizeof(TableParameter);
  5257. TableParameterHandler handler(BinaryUint16OpParameters, tableSize);
  5258. CW2A Target(handler.GetTableParamByName(L"ShaderOp.Target")->m_str);
  5259. CW2A Text(handler.GetTableParamByName(L"ShaderOp.Text")->m_str);
  5260. CW2A Arguments(handler.GetTableParamByName(L"ShaderOp.Arguments")->m_str);
  5261. std::vector<unsigned short> *Validation_Input1 =
  5262. &handler.GetTableParamByName(L"Validation.Input1")->m_uint16Table;
  5263. std::vector<unsigned short> *Validation_Input2 =
  5264. &handler.GetTableParamByName(L"Validation.Input2")->m_uint16Table;
  5265. std::vector<unsigned short> *Validation_Expected1 =
  5266. &handler.GetTableParamByName(L"Validation.Expected1")->m_uint16Table;
  5267. std::vector<unsigned short> *Validation_Expected2 =
  5268. &handler.GetTableParamByName(L"Validation.Expected2")->m_uint16Table;
  5269. int Validation_Tolerance = handler.GetTableParamByName(L"Validation.Tolerance")->m_int32;
  5270. size_t count = Validation_Input1->size();
  5271. int numExpected = Validation_Expected2->size() == 0 ? 1 : 2;
  5272. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTest(
  5273. pDevice, m_support, pStream, "BinaryUintOp",
  5274. // this callbacked is called when the test
  5275. // is creating the resource to run the test
  5276. [&](LPCSTR Name, std::vector<BYTE> &Data, st::ShaderOp *pShaderOp) {
  5277. VERIFY_IS_TRUE(0 == _stricmp(Name, "SBinaryUintOp"));
  5278. size_t size = sizeof(SBinaryUint16Op) * count;
  5279. Data.resize(size);
  5280. SBinaryUint16Op *pPrimitives = (SBinaryUint16Op *)Data.data();
  5281. for (size_t i = 0; i < count; ++i) {
  5282. SBinaryUint16Op *p = &pPrimitives[i];
  5283. p->input1 = (*Validation_Input1)[i % Validation_Input1->size()];
  5284. p->input2 = (*Validation_Input2)[i % Validation_Input2->size()];
  5285. }
  5286. // use shader from data table
  5287. pShaderOp->Shaders.at(0).Target = Target.m_psz;
  5288. pShaderOp->Shaders.at(0).Text = Text.m_psz;
  5289. pShaderOp->Shaders.at(0).Arguments = Arguments.m_psz;
  5290. });
  5291. MappedData data;
  5292. test->Test->GetReadBackData("SBinaryUintOp", &data);
  5293. SBinaryUint16Op *pPrimitives = (SBinaryUint16Op *)data.data();
  5294. WEX::TestExecution::DisableVerifyExceptions dve;
  5295. if (numExpected == 2) {
  5296. for (unsigned i = 0; i < count; ++i) {
  5297. SBinaryUint16Op *p = &pPrimitives[i];
  5298. unsigned short val1 = (*Validation_Expected1)[i % Validation_Expected1->size()];
  5299. unsigned short val2 = (*Validation_Expected2)[i % Validation_Expected2->size()];
  5300. LogCommentFmt(L"element #%u, input1 = %5hu(0x%08x), input2 = "
  5301. L"%5hu(0x%08x), output1 = "
  5302. L"%5hu(0x%08x), expected1 = %5hu(0x%08x), output2 = "
  5303. L"%5hu(0x%08x), expected2 = %5hu(0x%08x)",
  5304. i, p->input1, p->input1, p->input2, p->input2, p->output1,
  5305. p->output1, val1, val1, p->output2, p->output2, val2,
  5306. val2);
  5307. VerifyOutputWithExpectedValueInt(p->output1, val1, Validation_Tolerance);
  5308. VerifyOutputWithExpectedValueInt(p->output2, val2, Validation_Tolerance);
  5309. }
  5310. }
  5311. else if (numExpected == 1) {
  5312. for (unsigned i = 0; i < count; ++i) {
  5313. SBinaryUint16Op *p = &pPrimitives[i];
  5314. unsigned short val1 = (*Validation_Expected1)[i % Validation_Expected1->size()];
  5315. LogCommentFmt(L"element #%u, input1 = %5hu(0x%08x), input2 = "
  5316. L"%5hu(0x%08x), output = "
  5317. L"%5hu(0x%08x), expected = %5hu(0x%08x)", i,
  5318. p->input1, p->input1, p->input2, p->input2,
  5319. p->output1, p->output1, val1, val1);
  5320. VerifyOutputWithExpectedValueInt(p->output1, val1, Validation_Tolerance);
  5321. }
  5322. }
  5323. else {
  5324. LogErrorFmt(L"Unexpected number of expected values for operation %i", numExpected);
  5325. }
  5326. }
  5327. TEST_F(ExecutionTest, TertiaryUint16OpTest) {
  5328. WEX::TestExecution::SetVerifyOutput verifySettings(
  5329. WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  5330. CComPtr<IStream> pStream;
  5331. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  5332. CComPtr<ID3D12Device> pDevice;
  5333. if (!CreateDevice(&pDevice, D3D_SHADER_MODEL::D3D_SHADER_MODEL_6_2)) {
  5334. return;
  5335. }
  5336. if (!DoesDeviceSupportNative16bitOps(pDevice)) {
  5337. WEX::Logging::Log::Comment(L"Device does not support native 16-bit operations.");
  5338. WEX::Logging::Log::Result(WEX::Logging::TestResults::Skipped);
  5339. return;
  5340. }
  5341. // Read data from the table
  5342. size_t tableSize = sizeof(TertiaryUint16OpParameters) / sizeof(TableParameter);
  5343. TableParameterHandler handler(TertiaryUint16OpParameters, tableSize);
  5344. CW2A Target(handler.GetTableParamByName(L"ShaderOp.Target")->m_str);
  5345. CW2A Text(handler.GetTableParamByName(L"ShaderOp.Text")->m_str);
  5346. CW2A Arguments(handler.GetTableParamByName(L"ShaderOp.Arguments")->m_str);
  5347. std::vector<unsigned short> *Validation_Input1 =
  5348. &handler.GetTableParamByName(L"Validation.Input1")->m_uint16Table;
  5349. std::vector<unsigned short> *Validation_Input2 =
  5350. &handler.GetTableParamByName(L"Validation.Input2")->m_uint16Table;
  5351. std::vector<unsigned short> *Validation_Input3 =
  5352. &handler.GetTableParamByName(L"Validation.Input3")->m_uint16Table;
  5353. std::vector<unsigned short> *Validation_Expected =
  5354. &handler.GetTableParamByName(L"Validation.Expected1")->m_uint16Table;
  5355. int Validation_Tolerance = handler.GetTableParamByName(L"Validation.Tolerance")->m_int32;
  5356. size_t count = Validation_Input1->size();
  5357. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTest(
  5358. pDevice, m_support, pStream, "TertiaryUintOp",
  5359. // this callbacked is called when the test
  5360. // is creating the resource to run the test
  5361. [&](LPCSTR Name, std::vector<BYTE> &Data, st::ShaderOp *pShaderOp) {
  5362. VERIFY_IS_TRUE(0 == _stricmp(Name, "STertiaryUintOp"));
  5363. size_t size = sizeof(STertiaryUint16Op) * count;
  5364. Data.resize(size);
  5365. STertiaryUint16Op *pPrimitives = (STertiaryUint16Op *)Data.data();
  5366. for (size_t i = 0; i < count; ++i) {
  5367. STertiaryUint16Op *p = &pPrimitives[i];
  5368. p->input1 = (*Validation_Input1)[i % Validation_Input1->size()];
  5369. p->input2 = (*Validation_Input2)[i % Validation_Input2->size()];
  5370. p->input3 = (*Validation_Input3)[i % Validation_Input3->size()];
  5371. }
  5372. // use shader from data table
  5373. pShaderOp->Shaders.at(0).Target = Target.m_psz;
  5374. pShaderOp->Shaders.at(0).Text = Text.m_psz;
  5375. pShaderOp->Shaders.at(0).Arguments = Arguments.m_psz;
  5376. });
  5377. MappedData data;
  5378. test->Test->GetReadBackData("STertiaryUintOp", &data);
  5379. STertiaryUint16Op *pPrimitives = (STertiaryUint16Op *)data.data();
  5380. WEX::TestExecution::DisableVerifyExceptions dve;
  5381. for (unsigned i = 0; i < count; ++i) {
  5382. STertiaryUint16Op *p = &pPrimitives[i];
  5383. unsigned short val1 = (*Validation_Expected)[i % Validation_Expected->size()];
  5384. LogCommentFmt(L"element #%u, input1 = %5hu(0x%08x), input2 = "
  5385. L"%5hu(0x%08x), input3 = %5hu(0x%08x), output = "
  5386. L"%5hu(0x%08x), expected = %5hu(0x%08x)", i,
  5387. p->input1, p->input1, p->input2, p->input2, p->input3, p->input3,
  5388. p->output, p->output, val1, val1);
  5389. VerifyOutputWithExpectedValueInt(p->output, val1, Validation_Tolerance);
  5390. }
  5391. }
  5392. TEST_F(ExecutionTest, DotTest) {
  5393. WEX::TestExecution::SetVerifyOutput verifySettings(
  5394. WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  5395. CComPtr<IStream> pStream;
  5396. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  5397. CComPtr<ID3D12Device> pDevice;
  5398. if (!CreateDevice(&pDevice)) {
  5399. return;
  5400. }
  5401. int tableSize = sizeof(DotOpParameters) / sizeof(TableParameter);
  5402. TableParameterHandler handler(DotOpParameters, tableSize);
  5403. CW2A Target(handler.GetTableParamByName(L"ShaderOp.Target")->m_str);
  5404. CW2A Text(handler.GetTableParamByName(L"ShaderOp.Text")->m_str);
  5405. std::vector<WEX::Common::String> *Validation_Input1 =
  5406. &handler.GetTableParamByName(L"Validation.Input1")->m_StringTable;
  5407. std::vector<WEX::Common::String> *Validation_Input2 =
  5408. &handler.GetTableParamByName(L"Validation.Input2")->m_StringTable;
  5409. std::vector<WEX::Common::String> *Validation_dot2 =
  5410. &handler.GetTableParamByName(L"Validation.Expected1")->m_StringTable;
  5411. std::vector<WEX::Common::String> *Validation_dot3 =
  5412. &handler.GetTableParamByName(L"Validation.Expected2")->m_StringTable;
  5413. std::vector<WEX::Common::String> *Validation_dot4 =
  5414. &handler.GetTableParamByName(L"Validation.Expected3")->m_StringTable;
  5415. PCWSTR Validation_type = handler.GetTableParamByName(L"Validation.Type")->m_str;
  5416. double tolerance = handler.GetTableParamByName(L"Validation.Tolerance")->m_double;
  5417. size_t count = Validation_Input1->size();
  5418. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTest(
  5419. pDevice, m_support, pStream, "DotOp",
  5420. // this callbacked is called when the test
  5421. // is creating the resource to run the test
  5422. [&](LPCSTR Name, std::vector<BYTE> &Data, st::ShaderOp *pShaderOp) {
  5423. VERIFY_IS_TRUE(0 == _stricmp(Name, "SDotOp"));
  5424. size_t size = sizeof(SDotOp) * count;
  5425. Data.resize(size);
  5426. SDotOp *pPrimitives = (SDotOp*)Data.data();
  5427. for (size_t i = 0; i < count; ++i) {
  5428. SDotOp *p = &pPrimitives[i];
  5429. XMFLOAT4 val1,val2;
  5430. VERIFY_SUCCEEDED(ParseDataToVectorFloat((*Validation_Input1)[i],
  5431. (float *)&val1, 4));
  5432. VERIFY_SUCCEEDED(ParseDataToVectorFloat((*Validation_Input2)[i],
  5433. (float *)&val2, 4));
  5434. p->input1 = val1;
  5435. p->input2 = val2;
  5436. }
  5437. // use shader from data table
  5438. pShaderOp->Shaders.at(0).Target = Target.m_psz;
  5439. pShaderOp->Shaders.at(0).Text = Text.m_psz;
  5440. });
  5441. MappedData data;
  5442. test->Test->GetReadBackData("SDotOp", &data);
  5443. SDotOp *pPrimitives = (SDotOp*)data.data();
  5444. WEX::TestExecution::DisableVerifyExceptions dve;
  5445. for (size_t i = 0; i < count; ++i) {
  5446. SDotOp *p = &pPrimitives[i];
  5447. float dot2, dot3, dot4;
  5448. VERIFY_SUCCEEDED(ParseDataToFloat((*Validation_dot2)[i], dot2));
  5449. VERIFY_SUCCEEDED(ParseDataToFloat((*Validation_dot3)[i], dot3));
  5450. VERIFY_SUCCEEDED(ParseDataToFloat((*Validation_dot4)[i], dot4));
  5451. LogCommentFmt(
  5452. L"element #%u, input1 = (%f, %f, %f, %f), input2 = (%f, %f, "
  5453. L"%f, %f), \n dot2 = %f, dot2_expected = %f, dot3 = %f, "
  5454. L"dot3_expected = %f, dot4 = %f, dot4_expected = %f",
  5455. i, p->input1.x, p->input1.y, p->input1.z, p->input1.w, p->input2.x,
  5456. p->input2.y, p->input2.z, p->input2.w, p->o_dot2, dot2, p->o_dot3, dot3,
  5457. p->o_dot4, dot4);
  5458. VerifyOutputWithExpectedValueFloat(p->o_dot2, dot2, Validation_type,
  5459. tolerance);
  5460. VerifyOutputWithExpectedValueFloat(p->o_dot3, dot3, Validation_type,
  5461. tolerance);
  5462. VerifyOutputWithExpectedValueFloat(p->o_dot4, dot4, Validation_type,
  5463. tolerance);
  5464. }
  5465. }
  5466. TEST_F(ExecutionTest, Dot2AddHalfTest) {
  5467. WEX::TestExecution::SetVerifyOutput verifySettings(
  5468. WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  5469. CComPtr<IStream> pStream;
  5470. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  5471. CComPtr<ID3D12Device> pDevice;
  5472. if (!CreateDevice(&pDevice, D3D_SHADER_MODEL::D3D_SHADER_MODEL_6_4, false)) {
  5473. return;
  5474. }
  5475. if (!DoesDeviceSupportNative16bitOps(pDevice)) {
  5476. WEX::Logging::Log::Comment(L"Device does not support native 16-bit operations.");
  5477. WEX::Logging::Log::Result(WEX::Logging::TestResults::Skipped);
  5478. return;
  5479. }
  5480. int tableSize = sizeof(Dot2AddHalfOpParameters) / sizeof(TableParameter);
  5481. TableParameterHandler handler(Dot2AddHalfOpParameters, tableSize);
  5482. CW2A Target(handler.GetTableParamByName(L"ShaderOp.Target")->m_str);
  5483. CW2A Text(handler.GetTableParamByName(L"ShaderOp.Text")->m_str);
  5484. CW2A Arguments(handler.GetTableParamByName(L"ShaderOp.Arguments")->m_str);
  5485. std::vector<WEX::Common::String> *validation_input1 =
  5486. &handler.GetTableParamByName(L"Validation.Input1")->m_StringTable;
  5487. std::vector<WEX::Common::String> *validation_input2 =
  5488. &handler.GetTableParamByName(L"Validation.Input2")->m_StringTable;
  5489. std::vector<float> *validation_acc = &handler.GetTableParamByName(L"Validation.Input3")->m_floatTable;
  5490. std::vector<float> *validation_result = &handler.GetTableParamByName(L"Validation.Expected1")->m_floatTable;
  5491. PCWSTR Validation_type = handler.GetTableParamByName(L"Validation.Type")->m_str;
  5492. double tolerance = handler.GetTableParamByName(L"Validation.Tolerance")->m_double;
  5493. size_t count = validation_input1->size();
  5494. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTest(
  5495. pDevice, m_support, pStream, "Dot2AddHalfOp",
  5496. // this callback is called when the test
  5497. // is creating the resource to run the test
  5498. [&](LPCSTR Name, std::vector<BYTE> &Data, st::ShaderOp *pShaderOp) {
  5499. VERIFY_IS_TRUE(0 == _stricmp(Name, "SDot2AddHalfOp"));
  5500. size_t size = sizeof(SDot2AddHalfOp) * count;
  5501. Data.resize(size);
  5502. SDot2AddHalfOp *pPrimitives = (SDot2AddHalfOp*)Data.data();
  5503. for (size_t i = 0; i < count; ++i) {
  5504. SDot2AddHalfOp *p = &pPrimitives[i];
  5505. Half2 val1,val2;
  5506. VERIFY_SUCCEEDED(ParseDataToVectorHalf((*validation_input1)[i],
  5507. (uint16_t *)&val1, 2));
  5508. VERIFY_SUCCEEDED(ParseDataToVectorHalf((*validation_input2)[i],
  5509. (uint16_t *)&val2, 2));
  5510. p->input1 = val1;
  5511. p->input2 = val2;
  5512. p->acc = (*validation_acc)[i];
  5513. }
  5514. // use shader from data table
  5515. pShaderOp->Shaders.at(0).Target = Target.m_psz;
  5516. pShaderOp->Shaders.at(0).Text = Text.m_psz;
  5517. pShaderOp->Shaders.at(0).Arguments = Arguments.m_psz;
  5518. });
  5519. MappedData data;
  5520. test->Test->GetReadBackData("SDot2AddHalfOp", &data);
  5521. SDot2AddHalfOp *pPrimitives = (SDot2AddHalfOp*)data.data();
  5522. WEX::TestExecution::DisableVerifyExceptions dve;
  5523. for (size_t i = 0; i < count; ++i) {
  5524. SDot2AddHalfOp *p = &pPrimitives[i];
  5525. float expectedResult = (*validation_result)[i];
  5526. float input1x = ConvertFloat16ToFloat32(p->input1.x);
  5527. float input1y = ConvertFloat16ToFloat32(p->input1.y);
  5528. float input2x = ConvertFloat16ToFloat32(p->input2.x);
  5529. float input2y = ConvertFloat16ToFloat32(p->input2.y);
  5530. LogCommentFmt(
  5531. L"element #%u, input1 = (%f, %f), input2 = (%f, %f), acc = %f\n"
  5532. L"result = %f, result_expected = %f",
  5533. i, input1x, input1y, input2x, input2y, p->acc, p->result, expectedResult);
  5534. VerifyOutputWithExpectedValueFloat(p->result, expectedResult, Validation_type, tolerance);
  5535. }
  5536. }
  5537. TEST_F(ExecutionTest, Dot4AddI8PackedTest) {
  5538. WEX::TestExecution::SetVerifyOutput verifySettings(
  5539. WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  5540. CComPtr<IStream> pStream;
  5541. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  5542. CComPtr<ID3D12Device> pDevice;
  5543. if (!CreateDevice(&pDevice, D3D_SHADER_MODEL::D3D_SHADER_MODEL_6_4, false)) {
  5544. return;
  5545. }
  5546. int tableSize = sizeof(Dot4AddI8PackedOpParameters) / sizeof(TableParameter);
  5547. TableParameterHandler handler(Dot4AddI8PackedOpParameters, tableSize);
  5548. CW2A Target(handler.GetTableParamByName(L"ShaderOp.Target")->m_str);
  5549. CW2A Text(handler.GetTableParamByName(L"ShaderOp.Text")->m_str);
  5550. std::vector<uint32_t> *validation_input1 = &handler.GetTableParamByName(L"Validation.Input1")->m_uint32Table;
  5551. std::vector<uint32_t> *validation_input2 = &handler.GetTableParamByName(L"Validation.Input2")->m_uint32Table;
  5552. std::vector<int32_t> *validation_acc = &handler.GetTableParamByName(L"Validation.Input3")->m_int32Table;
  5553. std::vector<int32_t> *validation_result = &handler.GetTableParamByName(L"Validation.Expected1")->m_int32Table;
  5554. size_t count = validation_input1->size();
  5555. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTest(
  5556. pDevice, m_support, pStream, "Dot4AddI8PackedOp",
  5557. // this callback is called when the test
  5558. // is creating the resource to run the test
  5559. [&](LPCSTR Name, std::vector<BYTE> &Data, st::ShaderOp *pShaderOp) {
  5560. VERIFY_IS_TRUE(0 == _stricmp(Name, "SDot4AddI8PackedOp"));
  5561. size_t size = sizeof(SDot4AddI8PackedOp) * count;
  5562. Data.resize(size);
  5563. SDot4AddI8PackedOp *pPrimitives = (SDot4AddI8PackedOp*)Data.data();
  5564. for (size_t i = 0; i < count; ++i) {
  5565. SDot4AddI8PackedOp *p = &pPrimitives[i];
  5566. p->input1 = (*validation_input1)[i];
  5567. p->input2 = (*validation_input2)[i];
  5568. p->acc = (*validation_acc)[i];
  5569. }
  5570. // use shader from data table
  5571. pShaderOp->Shaders.at(0).Target = Target.m_psz;
  5572. pShaderOp->Shaders.at(0).Text = Text.m_psz;
  5573. });
  5574. MappedData data;
  5575. test->Test->GetReadBackData("SDot4AddI8PackedOp", &data);
  5576. SDot4AddI8PackedOp *pPrimitives = (SDot4AddI8PackedOp*)data.data();
  5577. WEX::TestExecution::DisableVerifyExceptions dve;
  5578. for (size_t i = 0; i < count; ++i) {
  5579. SDot4AddI8PackedOp *p = &pPrimitives[i];
  5580. int32_t expectedResult = (*validation_result)[i];
  5581. LogCommentFmt(
  5582. L"element #%u, input1 = %u, input2 = %u, acc = %d \n"
  5583. L"result = %d, result_expected = %d",
  5584. i, p->input1, p->input2, p->acc, p->result, expectedResult);
  5585. VerifyOutputWithExpectedValueInt(p->result, expectedResult, 0);
  5586. }
  5587. }
  5588. TEST_F(ExecutionTest, Dot4AddU8PackedTest) {
  5589. WEX::TestExecution::SetVerifyOutput verifySettings(
  5590. WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  5591. CComPtr<IStream> pStream;
  5592. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  5593. CComPtr<ID3D12Device> pDevice;
  5594. if (!CreateDevice(&pDevice, D3D_SHADER_MODEL::D3D_SHADER_MODEL_6_4, false)) {
  5595. return;
  5596. }
  5597. int tableSize = sizeof(Dot4AddU8PackedOpParameters) / sizeof(TableParameter);
  5598. TableParameterHandler handler(Dot4AddU8PackedOpParameters, tableSize);
  5599. CW2A Target(handler.GetTableParamByName(L"ShaderOp.Target")->m_str);
  5600. CW2A Text(handler.GetTableParamByName(L"ShaderOp.Text")->m_str);
  5601. std::vector<uint32_t> *validation_input1 = &handler.GetTableParamByName(L"Validation.Input1")->m_uint32Table;
  5602. std::vector<uint32_t> *validation_input2 = &handler.GetTableParamByName(L"Validation.Input2")->m_uint32Table;
  5603. std::vector<uint32_t> *validation_acc = &handler.GetTableParamByName(L"Validation.Input3")->m_uint32Table;
  5604. std::vector<uint32_t> *validation_result = &handler.GetTableParamByName(L"Validation.Expected1")->m_uint32Table;
  5605. size_t count = validation_input1->size();
  5606. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTest(
  5607. pDevice, m_support, pStream, "Dot4AddU8PackedOp",
  5608. // this callback is called when the test
  5609. // is creating the resource to run the test
  5610. [&](LPCSTR Name, std::vector<BYTE> &Data, st::ShaderOp *pShaderOp) {
  5611. VERIFY_IS_TRUE(0 == _stricmp(Name, "SDot4AddU8PackedOp"));
  5612. size_t size = sizeof(SDot4AddU8PackedOp) * count;
  5613. Data.resize(size);
  5614. SDot4AddU8PackedOp *pPrimitives = (SDot4AddU8PackedOp*)Data.data();
  5615. for (size_t i = 0; i < count; ++i) {
  5616. SDot4AddU8PackedOp *p = &pPrimitives[i];
  5617. p->input1 = (*validation_input1)[i];
  5618. p->input2 = (*validation_input2)[i];
  5619. p->acc = (*validation_acc)[i];
  5620. }
  5621. // use shader from data table
  5622. pShaderOp->Shaders.at(0).Target = Target.m_psz;
  5623. pShaderOp->Shaders.at(0).Text = Text.m_psz;
  5624. });
  5625. MappedData data;
  5626. test->Test->GetReadBackData("SDot4AddU8PackedOp", &data);
  5627. SDot4AddU8PackedOp *pPrimitives = (SDot4AddU8PackedOp*)data.data();
  5628. WEX::TestExecution::DisableVerifyExceptions dve;
  5629. for (size_t i = 0; i < count; ++i) {
  5630. SDot4AddU8PackedOp *p = &pPrimitives[i];
  5631. uint32_t expectedResult = (*validation_result)[i];
  5632. LogCommentFmt(
  5633. L"element #%u, input1 = %u, input2 = %u, acc = %u \n"
  5634. L"result = %u, result_expected = %u, ",
  5635. i, p->input1, p->input2, p->acc, p->result, expectedResult);
  5636. VerifyOutputWithExpectedValueUInt(p->result, expectedResult, 0);
  5637. }
  5638. }
  5639. TEST_F(ExecutionTest, Msad4Test) {
  5640. WEX::TestExecution::SetVerifyOutput verifySettings(
  5641. WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  5642. CComPtr<IStream> pStream;
  5643. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  5644. CComPtr<ID3D12Device> pDevice;
  5645. if (!CreateDevice(&pDevice)) {
  5646. return;
  5647. }
  5648. size_t tableSize = sizeof(Msad4OpParameters) / sizeof(TableParameter);
  5649. TableParameterHandler handler(Msad4OpParameters, tableSize);
  5650. CW2A Text(handler.GetTableParamByName(L"ShaderOp.Text")->m_str);
  5651. double tolerance = handler.GetTableParamByName(L"Validation.Tolerance")->m_double;
  5652. std::vector<unsigned int> *Validation_Reference =
  5653. &handler.GetTableParamByName(L"Validation.Input1")->m_uint32Table;
  5654. std::vector<WEX::Common::String> *Validation_Source =
  5655. &handler.GetTableParamByName(L"Validation.Input2")->m_StringTable;
  5656. std::vector<WEX::Common::String> *Validation_Accum =
  5657. &handler.GetTableParamByName(L"Validation.Input3")->m_StringTable;
  5658. std::vector<WEX::Common::String> *Validation_Expected =
  5659. &handler.GetTableParamByName(L"Validation.Expected1")->m_StringTable;
  5660. size_t count = Validation_Expected->size();
  5661. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTest(
  5662. pDevice, m_support, pStream, "Msad4",
  5663. // this callbacked is called when the test
  5664. // is creating the resource to run the test
  5665. [&](LPCSTR Name, std::vector<BYTE> &Data, st::ShaderOp *pShaderOp) {
  5666. VERIFY_IS_TRUE(0 == _stricmp(Name, "SMsad4"));
  5667. size_t size = sizeof(SMsad4) * count;
  5668. Data.resize(size);
  5669. SMsad4 *pPrimitives = (SMsad4*)Data.data();
  5670. for (size_t i = 0; i < count; ++i) {
  5671. SMsad4 *p = &pPrimitives[i];
  5672. XMUINT2 src;
  5673. XMUINT4 accum;
  5674. VERIFY_SUCCEEDED(ParseDataToVectorUint((*Validation_Source)[i], (unsigned int*)&src, 2));
  5675. VERIFY_SUCCEEDED(ParseDataToVectorUint((*Validation_Accum)[i], (unsigned int*)&accum, 4));
  5676. p->ref = (*Validation_Reference)[i];
  5677. p->src = src;
  5678. p->accum = accum;
  5679. }
  5680. // use shader from data table
  5681. pShaderOp->Shaders.at(0).Text = Text.m_psz;
  5682. });
  5683. MappedData data;
  5684. test->Test->GetReadBackData("SMsad4", &data);
  5685. SMsad4 *pPrimitives = (SMsad4*)data.data();
  5686. WEX::TestExecution::DisableVerifyExceptions dve;
  5687. for (size_t i = 0; i < count; ++i) {
  5688. SMsad4 *p = &pPrimitives[i];
  5689. XMUINT4 result;
  5690. VERIFY_SUCCEEDED(ParseDataToVectorUint((*Validation_Expected)[i],
  5691. (unsigned int *)&result, 4));
  5692. LogCommentFmt(
  5693. L"element #%u, ref = %u(0x%08x), src = %u(0x%08x), %u(0x%08x), "
  5694. L"accum = %u(0x%08x), %u(0x%08x), %u(0x%08x), %u(0x%08x),\n"
  5695. L"result = %u(0x%08x), %u(0x%08x), %u(0x%08x), %u(0x%08x),\n"
  5696. L"expected = %u(0x%08x), %u(0x%08x), %u(0x%08x), %u(0x%08x)", i,
  5697. p->ref, p->ref, p->src.x, p->src.x, p->src.y, p->src.y, p->accum.x,
  5698. p->accum.x, p->accum.y, p->accum.y, p->accum.z, p->accum.z,
  5699. p->accum.w, p->accum.w, p->result.x, p->result.x, p->result.y,
  5700. p->result.y, p->result.z, p->result.z, p->result.w, p->result.w,
  5701. result.x, result.x, result.y, result.y, result.z, result.z,
  5702. result.w, result.w);
  5703. int toleranceInt = (int)tolerance;
  5704. VerifyOutputWithExpectedValueInt(p->result.x, result.x, toleranceInt);
  5705. VerifyOutputWithExpectedValueInt(p->result.y, result.y, toleranceInt);
  5706. VerifyOutputWithExpectedValueInt(p->result.z, result.z, toleranceInt);
  5707. VerifyOutputWithExpectedValueInt(p->result.w, result.w, toleranceInt);
  5708. }
  5709. }
  5710. TEST_F(ExecutionTest, DenormBinaryFloatOpTest) {
  5711. WEX::TestExecution::SetVerifyOutput verifySettings(
  5712. WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  5713. CComPtr<IStream> pStream;
  5714. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  5715. CComPtr<ID3D12Device> pDevice;
  5716. if (!CreateDevice(&pDevice, D3D_SHADER_MODEL::D3D_SHADER_MODEL_6_2)) {
  5717. return;
  5718. }
  5719. // Read data from the table
  5720. int tableSize = sizeof(DenormBinaryFPOpParameters) / sizeof(TableParameter);
  5721. TableParameterHandler handler(DenormBinaryFPOpParameters, tableSize);
  5722. CW2A Target(handler.GetTableParamByName(L"ShaderOp.Target")->m_str);
  5723. CW2A Text(handler.GetTableParamByName(L"ShaderOp.Text")->m_str);
  5724. CW2A Arguments(handler.GetTableParamByName(L"ShaderOp.Arguments")->m_str);
  5725. std::vector<WEX::Common::String> *Validation_Input1 =
  5726. &(handler.GetTableParamByName(L"Validation.Input1")->m_StringTable);
  5727. std::vector<WEX::Common::String> *Validation_Input2 =
  5728. &(handler.GetTableParamByName(L"Validation.Input2")->m_StringTable);
  5729. std::vector<WEX::Common::String> *Validation_Expected1 =
  5730. &(handler.GetTableParamByName(L"Validation.Expected1")->m_StringTable);
  5731. // two expected outputs for any mode
  5732. std::vector<WEX::Common::String> *Validation_Expected2 =
  5733. &(handler.GetTableParamByName(L"Validation.Expected2")->m_StringTable);
  5734. LPCWSTR Validation_Type = handler.GetTableParamByName(L"Validation.Type")->m_str;
  5735. double Validation_Tolerance = handler.GetTableParamByName(L"Validation.Tolerance")->m_double;
  5736. size_t count = Validation_Input1->size();
  5737. using namespace hlsl::DXIL;
  5738. Float32DenormMode mode = Float32DenormMode::Any;
  5739. if (strcmp(Arguments.m_psz, "-denorm preserve") == 0) {
  5740. mode = Float32DenormMode::Preserve;
  5741. }
  5742. else if (strcmp(Arguments.m_psz, "-denorm ftz") == 0) {
  5743. mode = Float32DenormMode::FTZ;
  5744. }
  5745. if (mode == Float32DenormMode::Any) {
  5746. DXASSERT(Validation_Expected2->size() == Validation_Expected1->size(),
  5747. "must have same number of expected values");
  5748. }
  5749. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTest(
  5750. pDevice, m_support, pStream, "BinaryFPOp",
  5751. // this callbacked is called when the test
  5752. // is creating the resource to run the test
  5753. [&](LPCSTR Name, std::vector<BYTE> &Data, st::ShaderOp *pShaderOp) {
  5754. VERIFY_IS_TRUE(0 == _stricmp(Name, "SBinaryFPOp"));
  5755. size_t size = sizeof(SBinaryFPOp) * count;
  5756. Data.resize(size);
  5757. SBinaryFPOp *pPrimitives = (SBinaryFPOp *)Data.data();
  5758. for (size_t i = 0; i < count; ++i) {
  5759. SBinaryFPOp *p = &pPrimitives[i];
  5760. PCWSTR str1 = (*Validation_Input1)[i % Validation_Input1->size()];
  5761. PCWSTR str2 = (*Validation_Input2)[i % Validation_Input2->size()];
  5762. float val1, val2;
  5763. VERIFY_SUCCEEDED(ParseDataToFloat(str1, val1));
  5764. VERIFY_SUCCEEDED(ParseDataToFloat(str2, val2));
  5765. p->input1 = val1;
  5766. p->input2 = val2;
  5767. }
  5768. // use shader from data table
  5769. pShaderOp->Shaders.at(0).Target = Target.m_psz;
  5770. pShaderOp->Shaders.at(0).Text = Text.m_psz;
  5771. pShaderOp->Shaders.at(0).Arguments = Arguments.m_psz;
  5772. });
  5773. MappedData data;
  5774. test->Test->GetReadBackData("SBinaryFPOp", &data);
  5775. SBinaryFPOp *pPrimitives = (SBinaryFPOp *)data.data();
  5776. WEX::TestExecution::DisableVerifyExceptions dve;
  5777. for (unsigned i = 0; i < count; ++i) {
  5778. SBinaryFPOp *p = &pPrimitives[i];
  5779. if (mode == Float32DenormMode::Any) {
  5780. LPCWSTR str1 = (*Validation_Expected1)[i % Validation_Expected1->size()];
  5781. LPCWSTR str2 = (*Validation_Expected2)[i % Validation_Expected2->size()];
  5782. float val1;
  5783. float val2;
  5784. VERIFY_SUCCEEDED(ParseDataToFloat(str1, val1));
  5785. VERIFY_SUCCEEDED(ParseDataToFloat(str2, val2));
  5786. LogCommentFmt(L"element #%u, input1 = %6.8f, input2 = %6.8f, output = "
  5787. L"%6.8f, expected = %6.8f(%x) or %6.8f(%x)",
  5788. i, p->input1, p->input2, p->output1, val1, *(int *)&val1, val2, *(int *)&val2);
  5789. VERIFY_IS_TRUE(
  5790. CompareOutputWithExpectedValueFloat(
  5791. p->output1, val1, Validation_Type, Validation_Tolerance, mode) ||
  5792. CompareOutputWithExpectedValueFloat(
  5793. p->output1, val2, Validation_Type, Validation_Tolerance, mode));
  5794. }
  5795. else {
  5796. LPCWSTR str1 = (*Validation_Expected1)[i % Validation_Expected1->size()];
  5797. float val1;
  5798. VERIFY_SUCCEEDED(ParseDataToFloat(str1, val1));
  5799. LogCommentFmt(L"element #%u, input1 = %6.8f, input2 = %6.8f, output = "
  5800. L"%6.8f, expected = %6.8f(%a)",
  5801. i, p->input1, p->input2, p->output1, val1, *(int *)&val1);
  5802. VerifyOutputWithExpectedValueFloat(p->output1, val1, Validation_Type,
  5803. Validation_Tolerance, mode);
  5804. }
  5805. }
  5806. }
  5807. TEST_F(ExecutionTest, DenormTertiaryFloatOpTest) {
  5808. WEX::TestExecution::SetVerifyOutput verifySettings(
  5809. WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  5810. CComPtr<IStream> pStream;
  5811. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  5812. CComPtr<ID3D12Device> pDevice;
  5813. if (!CreateDevice(&pDevice, D3D_SHADER_MODEL::D3D_SHADER_MODEL_6_2)) {
  5814. return;
  5815. }
  5816. // Read data from the table
  5817. int tableSize = sizeof(DenormTertiaryFPOpParameters) / sizeof(TableParameter);
  5818. TableParameterHandler handler(DenormTertiaryFPOpParameters, tableSize);
  5819. CW2A Target(handler.GetTableParamByName(L"ShaderOp.Target")->m_str);
  5820. CW2A Text(handler.GetTableParamByName(L"ShaderOp.Text")->m_str);
  5821. CW2A Arguments(handler.GetTableParamByName(L"ShaderOp.Arguments")->m_str);
  5822. std::vector<WEX::Common::String> *Validation_Input1 =
  5823. &(handler.GetTableParamByName(L"Validation.Input1")->m_StringTable);
  5824. std::vector<WEX::Common::String> *Validation_Input2 =
  5825. &(handler.GetTableParamByName(L"Validation.Input2")->m_StringTable);
  5826. std::vector<WEX::Common::String> *Validation_Input3 =
  5827. &(handler.GetTableParamByName(L"Validation.Input3")->m_StringTable);
  5828. std::vector<WEX::Common::String> *Validation_Expected1 =
  5829. &(handler.GetTableParamByName(L"Validation.Expected1")->m_StringTable);
  5830. // two expected outputs for any mode
  5831. std::vector<WEX::Common::String> *Validation_Expected2 =
  5832. &(handler.GetTableParamByName(L"Validation.Expected2")->m_StringTable);
  5833. LPCWSTR Validation_Type = handler.GetTableParamByName(L"Validation.Type")->m_str;
  5834. double Validation_Tolerance = handler.GetTableParamByName(L"Validation.Tolerance")->m_double;
  5835. size_t count = Validation_Input1->size();
  5836. using namespace hlsl::DXIL;
  5837. Float32DenormMode mode = Float32DenormMode::Any;
  5838. if (strcmp(Arguments.m_psz, "-denorm preserve") == 0) {
  5839. mode = Float32DenormMode::Preserve;
  5840. }
  5841. else if (strcmp(Arguments.m_psz, "-denorm ftz") == 0) {
  5842. mode = Float32DenormMode::FTZ;
  5843. }
  5844. if (mode == Float32DenormMode::Any) {
  5845. DXASSERT(Validation_Expected2->size() == Validation_Expected1->size(),
  5846. "must have same number of expected values");
  5847. }
  5848. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTest(
  5849. pDevice, m_support, pStream, "TertiaryFPOp",
  5850. // this callbacked is called when the test
  5851. // is creating the resource to run the test
  5852. [&](LPCSTR Name, std::vector<BYTE> &Data, st::ShaderOp *pShaderOp) {
  5853. VERIFY_IS_TRUE(0 == _stricmp(Name, "STertiaryFPOp"));
  5854. size_t size = sizeof(STertiaryFPOp) * count;
  5855. Data.resize(size);
  5856. STertiaryFPOp *pPrimitives = (STertiaryFPOp *)Data.data();
  5857. for (size_t i = 0; i < count; ++i) {
  5858. STertiaryFPOp *p = &pPrimitives[i];
  5859. PCWSTR str1 = (*Validation_Input1)[i % Validation_Input1->size()];
  5860. PCWSTR str2 = (*Validation_Input2)[i % Validation_Input2->size()];
  5861. PCWSTR str3 = (*Validation_Input3)[i % Validation_Input3->size()];
  5862. float val1, val2, val3;
  5863. VERIFY_SUCCEEDED(ParseDataToFloat(str1, val1));
  5864. VERIFY_SUCCEEDED(ParseDataToFloat(str2, val2));
  5865. VERIFY_SUCCEEDED(ParseDataToFloat(str3, val3));
  5866. p->input1 = val1;
  5867. p->input2 = val2;
  5868. p->input3 = val3;
  5869. }
  5870. // use shader from data table
  5871. pShaderOp->Shaders.at(0).Target = Target.m_psz;
  5872. pShaderOp->Shaders.at(0).Text = Text.m_psz;
  5873. pShaderOp->Shaders.at(0).Arguments = Arguments.m_psz;
  5874. });
  5875. MappedData data;
  5876. test->Test->GetReadBackData("STertiaryFPOp", &data);
  5877. STertiaryFPOp *pPrimitives = (STertiaryFPOp *)data.data();
  5878. WEX::TestExecution::DisableVerifyExceptions dve;
  5879. for (unsigned i = 0; i < count; ++i) {
  5880. STertiaryFPOp *p = &pPrimitives[i];
  5881. if (mode == Float32DenormMode::Any) {
  5882. LPCWSTR str1 = (*Validation_Expected1)[i % Validation_Expected1->size()];
  5883. LPCWSTR str2 = (*Validation_Expected2)[i % Validation_Expected2->size()];
  5884. float val1;
  5885. float val2;
  5886. VERIFY_SUCCEEDED(ParseDataToFloat(str1, val1));
  5887. VERIFY_SUCCEEDED(ParseDataToFloat(str2, val2));
  5888. LogCommentFmt(L"element #%u, input1 = %6.8f, input2 = %6.8f, input3 = %6.8f, output = "
  5889. L"%6.8f, expected = %6.8f(%x) or %6.8f(%x)",
  5890. i, p->input1, p->input2, p->input3, p->output, val1, *(int *)&val1, val2, *(int *)&val2);
  5891. VERIFY_IS_TRUE(
  5892. CompareOutputWithExpectedValueFloat(
  5893. p->output, val1, Validation_Type, Validation_Tolerance, mode) ||
  5894. CompareOutputWithExpectedValueFloat(
  5895. p->output, val2, Validation_Type, Validation_Tolerance, mode));
  5896. }
  5897. else {
  5898. LPCWSTR str1 = (*Validation_Expected1)[i % Validation_Expected1->size()];
  5899. float val1;
  5900. VERIFY_SUCCEEDED(ParseDataToFloat(str1, val1));
  5901. LogCommentFmt(L"element #%u, input1 = %6.8f, input2 = %6.8f, input3 = %6.8f, output = "
  5902. L"%6.8f, expected = %6.8f(%a)",
  5903. i, p->input1, p->input2, p->input3, p->output, val1, *(int *)&val1);
  5904. VerifyOutputWithExpectedValueFloat(p->output, val1, Validation_Type,
  5905. Validation_Tolerance, mode);
  5906. }
  5907. }
  5908. }
  5909. // Setup for wave intrinsics tests
  5910. enum class ShaderOpKind {
  5911. WaveSum,
  5912. WaveProduct,
  5913. WaveActiveMax,
  5914. WaveActiveMin,
  5915. WaveCountBits,
  5916. WaveActiveAllEqual,
  5917. WaveActiveAnyTrue,
  5918. WaveActiveAllTrue,
  5919. WaveActiveBitOr,
  5920. WaveActiveBitAnd,
  5921. WaveActiveBitXor,
  5922. ShaderOpInvalid
  5923. };
  5924. struct ShaderOpKindPair {
  5925. LPCWSTR name;
  5926. ShaderOpKind kind;
  5927. };
  5928. static ShaderOpKindPair ShaderOpKindTable[] = {
  5929. { L"WaveActiveSum", ShaderOpKind::WaveSum },
  5930. { L"WaveActiveUSum", ShaderOpKind::WaveSum },
  5931. { L"WaveActiveProduct", ShaderOpKind::WaveProduct },
  5932. { L"WaveActiveUProduct", ShaderOpKind::WaveProduct },
  5933. { L"WaveActiveMax", ShaderOpKind::WaveActiveMax },
  5934. { L"WaveActiveUMax", ShaderOpKind::WaveActiveMax },
  5935. { L"WaveActiveMin", ShaderOpKind::WaveActiveMin },
  5936. { L"WaveActiveUMin", ShaderOpKind::WaveActiveMin },
  5937. { L"WaveActiveCountBits", ShaderOpKind::WaveCountBits },
  5938. { L"WaveActiveAllEqual", ShaderOpKind::WaveActiveAllEqual },
  5939. { L"WaveActiveAnyTrue", ShaderOpKind::WaveActiveAnyTrue },
  5940. { L"WaveActiveAllTrue", ShaderOpKind::WaveActiveAllTrue },
  5941. { L"WaveActiveBitOr", ShaderOpKind::WaveActiveBitOr },
  5942. { L"WaveActiveBitAnd", ShaderOpKind::WaveActiveBitAnd },
  5943. { L"WaveActiveBitXor", ShaderOpKind::WaveActiveBitXor },
  5944. { L"WavePrefixSum", ShaderOpKind::WaveSum },
  5945. { L"WavePrefixUSum", ShaderOpKind::WaveSum },
  5946. { L"WavePrefixProduct", ShaderOpKind::WaveProduct },
  5947. { L"WavePrefixUProduct", ShaderOpKind::WaveProduct },
  5948. { L"WavePrefixMax", ShaderOpKind::WaveActiveMax },
  5949. { L"WavePrefixUMax", ShaderOpKind::WaveActiveMax },
  5950. { L"WavePrefixMin", ShaderOpKind::WaveActiveMin },
  5951. { L"WavePrefixUMin", ShaderOpKind::WaveActiveMin },
  5952. { L"WavePrefixCountBits", ShaderOpKind::WaveCountBits }
  5953. };
  5954. ShaderOpKind GetShaderOpKind(LPCWSTR str) {
  5955. for (size_t i = 0; i < sizeof(ShaderOpKindTable)/sizeof(ShaderOpKindPair); ++i) {
  5956. if (_wcsicmp(ShaderOpKindTable[i].name, str) == 0) {
  5957. return ShaderOpKindTable[i].kind;
  5958. }
  5959. }
  5960. DXASSERT_ARGS(false, "Invalid ShaderOp name: %s", str);
  5961. return ShaderOpKind::ShaderOpInvalid;
  5962. }
  5963. template <typename InType, typename OutType, ShaderOpKind kind>
  5964. struct computeExpected {
  5965. OutType operator()(const std::vector<InType> &inputs,
  5966. const std::vector<int> &masks, int maskValue,
  5967. unsigned int index) {
  5968. return 0;
  5969. }
  5970. };
  5971. template <typename InType, typename OutType>
  5972. struct computeExpected<InType, OutType, ShaderOpKind::WaveSum> {
  5973. OutType operator()(const std::vector<InType> &inputs,
  5974. const std::vector<int> &masks, int maskValue,
  5975. unsigned int index) {
  5976. OutType sum = 0;
  5977. for (size_t i = 0; i < index; ++i) {
  5978. if (masks.at(i) == maskValue) {
  5979. sum += inputs.at(i);
  5980. }
  5981. }
  5982. return sum;
  5983. }
  5984. };
  5985. template <typename InType, typename OutType>
  5986. struct computeExpected<InType, OutType, ShaderOpKind::WaveProduct> {
  5987. OutType operator()(const std::vector<InType> &inputs,
  5988. const std::vector<int> &masks, int maskValue,
  5989. unsigned int index) {
  5990. OutType prod = 1;
  5991. for (size_t i = 0; i < index; ++i) {
  5992. if (masks.at(i) == maskValue) {
  5993. prod *= inputs.at(i);
  5994. }
  5995. }
  5996. return prod;
  5997. }
  5998. };
  5999. template <typename InType, typename OutType>
  6000. struct computeExpected<InType, OutType, ShaderOpKind::WaveActiveMax> {
  6001. OutType operator()(const std::vector<InType> &inputs,
  6002. const std::vector<int> &masks, int maskValue,
  6003. unsigned int index) {
  6004. OutType maximum = std::numeric_limits<OutType>::min();
  6005. for (size_t i = 0; i < index; ++i) {
  6006. if (masks.at(i) == maskValue && inputs.at(i) > maximum)
  6007. maximum = inputs.at(i);
  6008. }
  6009. return maximum;
  6010. }
  6011. };
  6012. template <typename InType, typename OutType>
  6013. struct computeExpected<InType, OutType, ShaderOpKind::WaveActiveMin> {
  6014. OutType operator()(const std::vector<InType> &inputs,
  6015. const std::vector<int> &masks, int maskValue,
  6016. unsigned int index) {
  6017. OutType minimum = std::numeric_limits<OutType>::max();
  6018. for (size_t i = 0; i < index; ++i) {
  6019. if (masks.at(i) == maskValue && inputs.at(i) < minimum)
  6020. minimum = inputs.at(i);
  6021. }
  6022. return minimum;
  6023. }
  6024. };
  6025. template <typename InType, typename OutType>
  6026. struct computeExpected<InType, OutType, ShaderOpKind::WaveCountBits> {
  6027. OutType operator()(const std::vector<InType> &inputs,
  6028. const std::vector<int> &masks, int maskValue,
  6029. unsigned int index) {
  6030. OutType count = 0;
  6031. for (size_t i = 0; i < index; ++i) {
  6032. if (masks.at(i) == maskValue && inputs.at(i) > 3) {
  6033. count++;
  6034. }
  6035. }
  6036. return count;
  6037. }
  6038. };
  6039. // In HLSL, boolean is represented in a 4 byte (uint32) format,
  6040. // So we cannot use c++ bool type to represent bool in HLSL
  6041. // HLSL returns 0 for false and 1 for true
  6042. template <typename InType, typename OutType>
  6043. struct computeExpected<InType, OutType, ShaderOpKind::WaveActiveAnyTrue> {
  6044. OutType operator()(const std::vector<InType> &inputs,
  6045. const std::vector<int> &masks, int maskValue,
  6046. unsigned int index) {
  6047. for (size_t i = 0; i < index; ++i) {
  6048. if (masks.at(i) == maskValue && inputs.at(i) != 0) {
  6049. return 1;
  6050. }
  6051. }
  6052. return 0;
  6053. }
  6054. };
  6055. template <typename InType, typename OutType>
  6056. struct computeExpected<InType, OutType, ShaderOpKind::WaveActiveAllTrue> {
  6057. OutType operator()(const std::vector<InType> &inputs,
  6058. const std::vector<int> &masks, int maskValue,
  6059. unsigned int index) {
  6060. for (size_t i = 0; i < index; ++i) {
  6061. if (masks.at(i) == maskValue && inputs.at(i) == 0) {
  6062. return 0;
  6063. }
  6064. }
  6065. return 1;
  6066. }
  6067. };
  6068. template <typename InType, typename OutType>
  6069. struct computeExpected<InType, OutType, ShaderOpKind::WaveActiveAllEqual> {
  6070. OutType operator()(const std::vector<InType> &inputs,
  6071. const std::vector<int> &masks, int maskValue,
  6072. unsigned int index) {
  6073. const InType *val = nullptr;
  6074. for (size_t i = 0; i < index; ++i) {
  6075. if (masks.at(i) == maskValue) {
  6076. if (val && *val != inputs.at(i)) {
  6077. return 0;
  6078. }
  6079. val = &inputs.at(i);
  6080. }
  6081. }
  6082. return 1;
  6083. }
  6084. };
  6085. template <typename InType, typename OutType>
  6086. struct computeExpected<InType, OutType, ShaderOpKind::WaveActiveBitOr> {
  6087. OutType operator()(const std::vector<InType> &inputs,
  6088. const std::vector<int> &masks, int maskValue,
  6089. unsigned int index) {
  6090. OutType bits = 0x00000000;
  6091. for (size_t i = 0; i < index; ++i) {
  6092. if (masks.at(i) == maskValue) {
  6093. bits |= inputs.at(i);
  6094. }
  6095. }
  6096. return bits;
  6097. }
  6098. };
  6099. template <typename InType, typename OutType>
  6100. struct computeExpected<InType, OutType, ShaderOpKind::WaveActiveBitAnd> {
  6101. OutType operator()(const std::vector<InType> &inputs,
  6102. const std::vector<int> &masks, int maskValue,
  6103. unsigned int index) {
  6104. OutType bits = 0xffffffff;
  6105. for (size_t i = 0; i < index; ++i) {
  6106. if (masks.at(i) == maskValue) {
  6107. bits &= inputs.at(i);
  6108. }
  6109. }
  6110. return bits;
  6111. }
  6112. };
  6113. template <typename InType, typename OutType>
  6114. struct computeExpected<InType, OutType, ShaderOpKind::WaveActiveBitXor> {
  6115. OutType operator()(const std::vector<InType> &inputs,
  6116. const std::vector<int> &masks, int maskValue,
  6117. unsigned int index) {
  6118. OutType bits = 0x00000000;
  6119. for (size_t i = 0; i < index; ++i) {
  6120. if (masks.at(i) == maskValue) {
  6121. bits ^= inputs.at(i);
  6122. }
  6123. }
  6124. return bits;
  6125. }
  6126. };
  6127. // Mask functions used to control active lanes
  6128. static int MaskAll(int i) {
  6129. UNREFERENCED_PARAMETER(i);
  6130. return 1;
  6131. }
  6132. static int MaskEveryOther(int i) {
  6133. return i % 2 == 0 ? 1 : 0;
  6134. }
  6135. static int MaskEveryThird(int i) {
  6136. return i % 3 == 0 ? 1 : 0;
  6137. }
  6138. typedef int(*MaskFunction)(int);
  6139. static MaskFunction MaskFunctionTable[] = {
  6140. MaskAll, MaskEveryOther, MaskEveryThird
  6141. };
  6142. template <typename InType, typename OutType>
  6143. static OutType computeExpectedWithShaderOp(const std::vector<InType> &inputs,
  6144. const std::vector<int> &masks,
  6145. int maskValue, unsigned int index,
  6146. LPCWSTR str) {
  6147. ShaderOpKind kind = GetShaderOpKind(str);
  6148. switch (kind) {
  6149. case ShaderOpKind::WaveSum:
  6150. return computeExpected<InType, OutType, ShaderOpKind::WaveSum>()(inputs, masks, maskValue, index);
  6151. case ShaderOpKind::WaveProduct:
  6152. return computeExpected<InType, OutType, ShaderOpKind::WaveProduct>()(inputs, masks, maskValue, index);
  6153. case ShaderOpKind::WaveActiveMax:
  6154. return computeExpected<InType, OutType, ShaderOpKind::WaveActiveMax>()(inputs, masks, maskValue, index);
  6155. case ShaderOpKind::WaveActiveMin:
  6156. return computeExpected<InType, OutType, ShaderOpKind::WaveActiveMin>()(inputs, masks, maskValue, index);
  6157. case ShaderOpKind::WaveCountBits:
  6158. return computeExpected<InType, OutType, ShaderOpKind::WaveCountBits>()(inputs, masks, maskValue, index);
  6159. case ShaderOpKind::WaveActiveBitOr:
  6160. return computeExpected<InType, OutType, ShaderOpKind::WaveActiveBitOr>()(inputs, masks, maskValue, index);
  6161. case ShaderOpKind::WaveActiveBitAnd:
  6162. return computeExpected<InType, OutType, ShaderOpKind::WaveActiveBitAnd>()(inputs, masks, maskValue, index);
  6163. case ShaderOpKind::WaveActiveBitXor:
  6164. return computeExpected<InType, OutType, ShaderOpKind::WaveActiveBitXor>()(inputs, masks, maskValue, index);
  6165. case ShaderOpKind::WaveActiveAnyTrue:
  6166. return computeExpected<InType, OutType, ShaderOpKind::WaveActiveAnyTrue>()(inputs, masks, maskValue, index);
  6167. case ShaderOpKind::WaveActiveAllTrue:
  6168. return computeExpected<InType, OutType, ShaderOpKind::WaveActiveAllTrue>()(inputs, masks, maskValue, index);
  6169. case ShaderOpKind::WaveActiveAllEqual:
  6170. return computeExpected<InType, OutType, ShaderOpKind::WaveActiveAllEqual>()(inputs, masks, maskValue, index);
  6171. default:
  6172. DXASSERT_ARGS(false, "Invalid ShaderOp Name: %s", str);
  6173. return (OutType) 0;
  6174. }
  6175. };
  6176. // A framework for testing individual wave intrinsics tests.
  6177. // This test case is assuming that functions 1) WaveIsFirstLane and 2) WaveGetLaneIndex are correct for all lanes.
  6178. template <class T1, class T2>
  6179. void ExecutionTest::WaveIntrinsicsActivePrefixTest(
  6180. TableParameter *pParameterList, size_t numParameter, bool isPrefix) {
  6181. WEX::TestExecution::SetVerifyOutput verifySettings(WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  6182. // Resource representation for compute shader
  6183. // firstLaneId is used to group different waves
  6184. // laneIndex is used to identify lane within the wave.
  6185. // Lane ids are not necessarily in same order as thread ids.
  6186. struct PerThreadData {
  6187. unsigned firstLaneId;
  6188. unsigned laneIndex;
  6189. int mask;
  6190. T1 input;
  6191. T2 output;
  6192. };
  6193. unsigned int NumThreadsX = 8;
  6194. unsigned int NumThreadsY = 12;
  6195. unsigned int NumThreadsZ = 1;
  6196. static const unsigned int ThreadsPerGroup = NumThreadsX * NumThreadsY * NumThreadsZ;
  6197. static const unsigned int DispatchGroupCount = 1;
  6198. static const unsigned int ThreadCount = ThreadsPerGroup * DispatchGroupCount;
  6199. CComPtr<IStream> pStream;
  6200. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  6201. CComPtr<ID3D12Device> pDevice;
  6202. if (!CreateDevice(&pDevice)) {
  6203. return;
  6204. }
  6205. if (!DoesDeviceSupportWaveOps(pDevice)) {
  6206. // Optional feature, so it's correct to not support it if declared as such.
  6207. WEX::Logging::Log::Comment(L"Device does not support wave operations.");
  6208. return;
  6209. }
  6210. TableParameterHandler handler(pParameterList, numParameter);
  6211. unsigned int numInputSet = handler.GetTableParamByName(L"Validation.NumInputSet")->m_uint;
  6212. // Obtain the list of input lists
  6213. std::vector<std::vector<T1>*> InputDataList;
  6214. for (unsigned int i = 0;
  6215. i < numInputSet; ++i) {
  6216. std::wstring inputName = L"Validation.InputSet";
  6217. inputName.append(std::to_wstring(i + 1));
  6218. InputDataList.push_back(handler.GetDataArray<T1>(inputName.data()));
  6219. }
  6220. CW2A Text(handler.GetTableParamByName(L"ShaderOp.text")->m_str);
  6221. std::shared_ptr<st::ShaderOpSet> ShaderOpSet = std::make_shared<st::ShaderOpSet>();
  6222. st::ParseShaderOpSetFromStream(pStream, ShaderOpSet.get());
  6223. // Running compute shader for each input set with different masks
  6224. for (size_t setIndex = 0; setIndex < numInputSet; ++setIndex) {
  6225. for (size_t maskIndex = 0; maskIndex < sizeof(MaskFunctionTable) / sizeof(MaskFunction); ++maskIndex) {
  6226. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTestAfterParse(
  6227. pDevice, m_support, "WaveIntrinsicsOp",
  6228. // this callbacked is called when the test
  6229. // is creating the resource to run the test
  6230. [&](LPCSTR Name, std::vector<BYTE> &Data, st::ShaderOp *pShaderOp) {
  6231. VERIFY_IS_TRUE(0 == _stricmp(Name, "SWaveIntrinsicsOp"));
  6232. size_t size = sizeof(PerThreadData) * ThreadCount;
  6233. Data.resize(size);
  6234. PerThreadData *pPrimitives = (PerThreadData*)Data.data();
  6235. // 4 different inputs for each operation test
  6236. size_t index = 0;
  6237. std::vector<T1> *IntList = InputDataList[setIndex];
  6238. while (index < ThreadCount) {
  6239. PerThreadData *p = &pPrimitives[index];
  6240. p->firstLaneId = 0xFFFFBFFF;
  6241. p->laneIndex = 0xFFFFBFFF;
  6242. p->mask = MaskFunctionTable[maskIndex]((int)index);
  6243. p->input = (*IntList)[index % IntList->size()];
  6244. p->output = 0xFFFFBFFF;
  6245. index++;
  6246. }
  6247. // use shader from data table
  6248. pShaderOp->Shaders.at(0).Text = Text.m_psz;
  6249. }, ShaderOpSet);
  6250. // Check the value
  6251. MappedData data;
  6252. test->Test->GetReadBackData("SWaveIntrinsicsOp", &data);
  6253. PerThreadData *pPrimitives = (PerThreadData*)data.data();
  6254. WEX::TestExecution::DisableVerifyExceptions dve;
  6255. // Grouping data by waves
  6256. std::vector<int> firstLaneIds;
  6257. for (size_t i = 0; i < ThreadCount; ++i) {
  6258. PerThreadData *p = &pPrimitives[i];
  6259. int firstLaneId = p->firstLaneId;
  6260. if (!contains(firstLaneIds, firstLaneId)) {
  6261. firstLaneIds.push_back(firstLaneId);
  6262. }
  6263. }
  6264. std::map<int, std::unique_ptr<std::vector<PerThreadData *>>> waves;
  6265. for (size_t i = 0; i < firstLaneIds.size(); ++i) {
  6266. waves[firstLaneIds.at(i)] = std::make_unique<std::vector<PerThreadData*>>();
  6267. }
  6268. for (size_t i = 0; i < ThreadCount; ++i) {
  6269. PerThreadData *p = &pPrimitives[i];
  6270. waves[p->firstLaneId].get()->push_back(p);
  6271. }
  6272. // validate for each wave
  6273. for (size_t i = 0; i < firstLaneIds.size(); ++i) {
  6274. // collect inputs and masks for a given wave
  6275. std::vector<PerThreadData *> *waveData = waves[firstLaneIds.at(i)].get();
  6276. std::vector<T1> inputList(waveData->size());
  6277. std::vector<int> maskList(waveData->size(), -1);
  6278. std::vector<T2> outputList(waveData->size());
  6279. // sort inputList and masklist by lane id. input for each lane can be computed for its group index
  6280. for (size_t j = 0, end = waveData->size(); j < end; ++j) {
  6281. unsigned laneID = waveData->at(j)->laneIndex;
  6282. // ensure that each lane ID is unique and within the range
  6283. VERIFY_IS_TRUE(0 <= laneID && laneID < waveData->size());
  6284. VERIFY_IS_TRUE(maskList.at(laneID) == -1);
  6285. maskList.at(laneID) = waveData->at(j)->mask;
  6286. inputList.at(laneID) = waveData->at(j)->input;
  6287. outputList.at(laneID) = waveData->at(j)->output;
  6288. }
  6289. std::wstring inputStr = L"Wave Inputs: ";
  6290. std::wstring maskStr = L"Wave Masks: ";
  6291. std::wstring outputStr = L"Wave Outputs: ";
  6292. // append input string and mask string in lane id order
  6293. for (size_t j = 0, end = waveData->size(); j < end; ++j) {
  6294. maskStr.append(std::to_wstring(maskList.at(j)));
  6295. maskStr.append(L" ");
  6296. inputStr.append(std::to_wstring(inputList.at(j)));
  6297. inputStr.append(L" ");
  6298. outputStr.append(std::to_wstring(outputList.at(j)));
  6299. outputStr.append(L" ");
  6300. }
  6301. LogCommentFmt(inputStr.data());
  6302. LogCommentFmt(maskStr.data());
  6303. LogCommentFmt(outputStr.data());
  6304. LogCommentFmt(L"\n");
  6305. // Compute expected output for a given inputs, masks, and index
  6306. for (size_t laneIndex = 0, laneEnd = inputList.size(); laneIndex < laneEnd; ++laneIndex) {
  6307. T2 expected;
  6308. // WaveActive is equivalent to WavePrefix lane # lane count
  6309. unsigned index = isPrefix ? (unsigned)laneIndex : (unsigned)inputList.size();
  6310. if (maskList.at(laneIndex) == 1) {
  6311. expected = computeExpectedWithShaderOp<T1, T2>(
  6312. inputList, maskList, 1, index,
  6313. handler.GetTableParamByName(L"ShaderOp.Name")->m_str);
  6314. }
  6315. else {
  6316. expected = computeExpectedWithShaderOp<T1, T2>(
  6317. inputList, maskList, 0, index,
  6318. handler.GetTableParamByName(L"ShaderOp.Name")->m_str);
  6319. }
  6320. // TODO: use different comparison for floating point inputs
  6321. bool equal = outputList.at(laneIndex) == expected;
  6322. if (!equal) {
  6323. LogCommentFmt(L"lane%d: %4d, Expected : %4d", laneIndex, outputList.at(laneIndex), expected);
  6324. }
  6325. VERIFY_IS_TRUE(equal);
  6326. }
  6327. }
  6328. }
  6329. }
  6330. }
  6331. static const unsigned int MinWarpVersionForWaveIntrinsics = 16202;
  6332. TEST_F(ExecutionTest, WaveIntrinsicsActiveIntTest) {
  6333. if (GetTestParamUseWARP(true) &&
  6334. !IsValidWarpDllVersion(MinWarpVersionForWaveIntrinsics)) {
  6335. return;
  6336. }
  6337. WaveIntrinsicsActivePrefixTest<int, int>(
  6338. WaveIntrinsicsActiveIntParameters,
  6339. sizeof(WaveIntrinsicsActiveIntParameters) / sizeof(TableParameter),
  6340. /*isPrefix*/ false);
  6341. }
  6342. TEST_F(ExecutionTest, WaveIntrinsicsActiveUintTest) {
  6343. if (GetTestParamUseWARP(true) &&
  6344. !IsValidWarpDllVersion(MinWarpVersionForWaveIntrinsics)) {
  6345. return;
  6346. }
  6347. WaveIntrinsicsActivePrefixTest<unsigned int, unsigned int>(
  6348. WaveIntrinsicsActiveUintParameters,
  6349. sizeof(WaveIntrinsicsActiveUintParameters) / sizeof(TableParameter),
  6350. /*isPrefix*/ false);
  6351. }
  6352. TEST_F(ExecutionTest, WaveIntrinsicsPrefixIntTest) {
  6353. if (GetTestParamUseWARP(true) &&
  6354. !IsValidWarpDllVersion(MinWarpVersionForWaveIntrinsics)) {
  6355. return;
  6356. }
  6357. WaveIntrinsicsActivePrefixTest<int, int>(
  6358. WaveIntrinsicsPrefixIntParameters,
  6359. sizeof(WaveIntrinsicsPrefixIntParameters) / sizeof(TableParameter),
  6360. /*isPrefix*/ true);
  6361. }
  6362. TEST_F(ExecutionTest, WaveIntrinsicsPrefixUintTest) {
  6363. if (GetTestParamUseWARP(true) &&
  6364. !IsValidWarpDllVersion(MinWarpVersionForWaveIntrinsics)) {
  6365. return;
  6366. }
  6367. WaveIntrinsicsActivePrefixTest<unsigned int, unsigned int>(
  6368. WaveIntrinsicsPrefixUintParameters,
  6369. sizeof(WaveIntrinsicsPrefixUintParameters) / sizeof(TableParameter),
  6370. /*isPrefix*/ true);
  6371. }
  6372. template <typename T>
  6373. static T GetWaveMultiPrefixInitialAccumValue(LPCWSTR testName) {
  6374. if (_wcsicmp(testName, L"WaveMultiPrefixProduct") == 0 ||
  6375. _wcsicmp(testName, L"WaveMultiPrefixUProduct") == 0) {
  6376. return static_cast<T>(1);
  6377. } else if (_wcsicmp(testName, L"WaveMultiPrefixSum") == 0 ||
  6378. _wcsicmp(testName, L"WaveMultiPrefixUSum") == 0 ||
  6379. _wcsicmp(testName, L"WaveMultiPrefixBitOr") == 0 ||
  6380. _wcsicmp(testName, L"WaveMultiPrefixUBitOr") == 0 ||
  6381. _wcsicmp(testName, L"WaveMultiPrefixBitXor") == 0 ||
  6382. _wcsicmp(testName, L"WaveMultiPrefixUBitXor") == 0 ||
  6383. _wcsicmp(testName, L"WaveMultiPrefixCountBits") == 0 ||
  6384. _wcsicmp(testName, L"WaveMultiPrefixUCountBits") == 0) {
  6385. return static_cast<T>(0);
  6386. } else if (_wcsicmp(testName, L"WaveMultiPrefixBitAnd") == 0 ||
  6387. _wcsicmp(testName, L"WaveMultiPrefixUBitAnd") == 0) {
  6388. return static_cast<T>(-1);
  6389. } else {
  6390. return static_cast<T>(0);
  6391. }
  6392. }
  6393. template <typename T>
  6394. std::function<T(T, T)> GetWaveMultiPrefixReferenceFunction(LPCWSTR testName) {
  6395. if (_wcsicmp(testName, L"WaveMultiPrefixProduct") == 0 ||
  6396. _wcsicmp(testName, L"WaveMultiPrefixUProduct") == 0) {
  6397. return [] (T lhs, T rhs) -> T { return lhs * rhs; };
  6398. } else if (_wcsicmp(testName, L"WaveMultiPrefixSum") == 0 ||
  6399. _wcsicmp(testName, L"WaveMultiPrefixUSum") == 0) {
  6400. return [] (T lhs, T rhs) -> T { return lhs + rhs; };
  6401. } else if (_wcsicmp(testName, L"WaveMultiPrefixBitAnd") == 0 ||
  6402. _wcsicmp(testName, L"WaveMultiPrefixUBitAnd") == 0) {
  6403. return [] (T lhs, T rhs) -> T { return lhs & rhs; };
  6404. } else if (_wcsicmp(testName, L"WaveMultiPrefixBitOr") == 0 ||
  6405. _wcsicmp(testName, L"WaveMultiPrefixUBitOr") == 0) {
  6406. return [] (T lhs, T rhs) -> T { return lhs | rhs; };
  6407. } else if (_wcsicmp(testName, L"WaveMultiPrefixBitXor") == 0 ||
  6408. _wcsicmp(testName, L"WaveMultiPrefixUBitXor") == 0) {
  6409. return [] (T lhs, T rhs) -> T { return lhs ^ rhs; };
  6410. } else if (_wcsicmp(testName, L"WaveMultiPrefixCountBits") == 0 ||
  6411. _wcsicmp(testName, L"WaveMultiPrefixUCountBits") == 0) {
  6412. // For CountBits, each lane contributes a boolean value. The test input is
  6413. // a zero or non-zero integer. If the input is a non-zero value then the
  6414. // condition is true, thus we contribute one to the bit count.
  6415. return [] (T lhs, T rhs) -> T { return lhs + (rhs ? 1 : 0); };
  6416. } else {
  6417. return [] (T lhs, T rhs) -> T { UNREFERENCED_PARAMETER(lhs); UNREFERENCED_PARAMETER(rhs); return 0; };
  6418. }
  6419. }
  6420. template <class T>
  6421. void
  6422. ExecutionTest::WaveIntrinsicsMultiPrefixOpTest(TableParameter *pParameterList,
  6423. size_t numParameters) {
  6424. WEX::TestExecution::SetVerifyOutput
  6425. verifySettings(WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  6426. struct PerThreadData {
  6427. uint32_t key;
  6428. uint32_t firstLaneId;
  6429. uint32_t laneId;
  6430. uint32_t mask;
  6431. T value;
  6432. T result;
  6433. };
  6434. constexpr size_t NumThreadsX = 8;
  6435. constexpr size_t NumThreadsY = 12;
  6436. constexpr size_t NumThreadsZ = 1;
  6437. constexpr size_t ThreadsPerGroup = NumThreadsX * NumThreadsY * NumThreadsZ;
  6438. constexpr size_t DispatchGroupSize = 1;
  6439. constexpr size_t ThreadCount = ThreadsPerGroup * DispatchGroupSize;
  6440. CComPtr<IStream> pStream;
  6441. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  6442. CComPtr<ID3D12Device> pDevice;
  6443. if (!CreateDevice(&pDevice, D3D_SHADER_MODEL_6_5)) {
  6444. return;
  6445. }
  6446. if (!DoesDeviceSupportWaveOps(pDevice)) {
  6447. // Optional feature, so it's correct to not support it if declared as such.
  6448. WEX::Logging::Log::Comment(L"Device does not support wave operations.");
  6449. return;
  6450. }
  6451. std::shared_ptr<st::ShaderOpSet>
  6452. ShaderOpSet = std::make_shared<st::ShaderOpSet>();
  6453. st::ParseShaderOpSetFromStream(pStream, ShaderOpSet.get());
  6454. TableParameterHandler handler(pParameterList, numParameters);
  6455. CW2A shaderSource(handler.GetTableParamByName(L"ShaderOp.Text")->m_str);
  6456. CW2A shaderProfile(handler.GetTableParamByName(L"ShaderOp.Target")->m_str);
  6457. auto testName = handler.GetTableParamByName(L"ShaderOp.Name")->m_str;
  6458. std::vector<T> *keys = handler.GetDataArray<T>(L"Validation.Keys");
  6459. std::vector<T> *values = handler.GetDataArray<T>(L"Validation.Values");
  6460. for (size_t maskIndex = 0; maskIndex < _countof(MaskFunctionTable); ++maskIndex) {
  6461. std::shared_ptr<ShaderOpTestResult> test =
  6462. RunShaderOpTestAfterParse(pDevice, m_support, "WaveIntrinsicsOp",
  6463. [&] (LPCSTR name, std::vector<BYTE> &data, st::ShaderOp *pShaderOp) {
  6464. UNREFERENCED_PARAMETER(name);
  6465. const size_t dataSize = sizeof(PerThreadData) * ThreadCount;
  6466. data.resize(dataSize);
  6467. PerThreadData *pThreadData = reinterpret_cast<PerThreadData *>(data.data());
  6468. for (size_t i = 0; i != ThreadCount; ++i) {
  6469. pThreadData[i].key = keys->at(i % keys->size());
  6470. pThreadData[i].value = values->at(i % values->size());
  6471. pThreadData[i].firstLaneId = 0xdeadbeef;
  6472. pThreadData[i].laneId = 0xdeadbeef;
  6473. pThreadData[i].mask = MaskFunctionTable[maskIndex]((int)i);
  6474. pThreadData[i].result = 0xdeadbeef;
  6475. }
  6476. pShaderOp->Shaders.at(0).Text = shaderSource;
  6477. pShaderOp->Shaders.at(0).Target = shaderProfile;
  6478. }, ShaderOpSet);
  6479. MappedData mappedData;
  6480. test->Test->GetReadBackData("SWaveIntrinsicsOp", &mappedData);
  6481. PerThreadData *resultData = reinterpret_cast<PerThreadData *>(mappedData.data());
  6482. // Partition our data into waves
  6483. std::map<uint32_t, std::vector<PerThreadData *>> waves;
  6484. for (size_t i = 0, e = ThreadCount; i != e; ++i) {
  6485. PerThreadData *elt = &resultData[i];
  6486. // Basic sanity checks
  6487. VERIFY_IS_TRUE(elt->firstLaneId != 0xdeadbeef);
  6488. VERIFY_IS_TRUE(elt->laneId != 0xdeadbeef);
  6489. waves[elt->firstLaneId].push_back(elt);
  6490. }
  6491. // Verify each wave
  6492. auto refFn = GetWaveMultiPrefixReferenceFunction<T>(testName);
  6493. for (auto &w : waves) {
  6494. std::vector<PerThreadData *> &waveData = w.second;
  6495. struct {
  6496. bool operator()(PerThreadData *a, PerThreadData *b) const {
  6497. return (a->laneId < b->laneId);
  6498. }
  6499. } compare;
  6500. // Need to sort based on the lane id
  6501. std::sort(waveData.begin(), waveData.end(), compare);
  6502. LogCommentFmt(L"LaneId Mask Key Value Result Expected");
  6503. LogCommentFmt(L"-------- -------- -------- -------- -------- --------");
  6504. for (size_t i = 0, e = waveData.size(); i != e; ++i) {
  6505. PerThreadData *data = waveData[i];
  6506. // Compute prefix operation over each previous lane element that has the
  6507. // same key value, and is part of the same active thread group
  6508. T accum = GetWaveMultiPrefixInitialAccumValue<T>(testName);
  6509. for (unsigned j = 0; j < i; ++j) {
  6510. if (waveData[j]->key == data->key && waveData[j]->mask == data->mask) {
  6511. accum = refFn(accum, waveData[j]->value);
  6512. }
  6513. }
  6514. LogCommentFmt(L"%08X %08X %08X %08X %08X %08X", data->laneId, data->mask, data->key, data->value, data->result, accum);
  6515. VERIFY_IS_TRUE(accum == data->result);
  6516. }
  6517. LogCommentFmt(L"\n");
  6518. }
  6519. }
  6520. }
  6521. TEST_F(ExecutionTest, WaveIntrinsicsSM65IntTest) {
  6522. WaveIntrinsicsMultiPrefixOpTest<int>(WaveIntrinsicsMultiPrefixIntParameters,
  6523. _countof(WaveIntrinsicsMultiPrefixIntParameters));
  6524. }
  6525. TEST_F(ExecutionTest, WaveIntrinsicsSM65UintTest) {
  6526. WaveIntrinsicsMultiPrefixOpTest<unsigned>(WaveIntrinsicsMultiPrefixUintParameters,
  6527. _countof(WaveIntrinsicsMultiPrefixUintParameters));
  6528. }
  6529. TEST_F(ExecutionTest, CBufferTestHalf) {
  6530. WEX::TestExecution::SetVerifyOutput verifySettings(WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  6531. CComPtr<IStream> pStream;
  6532. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  6533. // Single operation test at the moment.
  6534. CComPtr<ID3D12Device> pDevice;
  6535. if (!CreateDevice(&pDevice, D3D_SHADER_MODEL_6_2))
  6536. return;
  6537. if (!DoesDeviceSupportNative16bitOps(pDevice)) {
  6538. WEX::Logging::Log::Comment(L"Device does not support native 16-bit operations.");
  6539. WEX::Logging::Log::Result(WEX::Logging::TestResults::Skipped);
  6540. return;
  6541. }
  6542. uint16_t InputData[] = { 0x3F80, 0x3F00, 0x3D80, 0x7BFF };
  6543. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTest(pDevice, m_support, pStream, "CBufferTestHalf",
  6544. [&](LPCSTR Name, std::vector<BYTE> &Data, st::ShaderOp *pShaderOp) {
  6545. UNREFERENCED_PARAMETER(pShaderOp);
  6546. VERIFY_IS_TRUE(0 == _stricmp(Name, "CB0"));
  6547. // use shader from data table.
  6548. Data.resize(sizeof(InputData));
  6549. uint16_t *pData = (uint16_t *)Data.data();
  6550. for (size_t i = 0; i < 4; ++i, ++pData) {
  6551. *pData = InputData[i];
  6552. }
  6553. });
  6554. {
  6555. MappedData data;
  6556. test->Test->GetReadBackData("RTarget", &data);
  6557. const uint16_t *pPixels = (uint16_t *)data.data();
  6558. for (int i = 0; i < 4; ++i) {
  6559. uint16_t output = *(pPixels + i);
  6560. float outputFloat = ConvertFloat16ToFloat32(output);
  6561. float inputFloat = ConvertFloat16ToFloat32(InputData[i]);
  6562. LogCommentFmt(L"element #%u: input = %6.8f(0x%04x), output = %6.8f(0x%04x)",
  6563. i, inputFloat, InputData[i], outputFloat, output);
  6564. VERIFY_ARE_EQUAL(inputFloat, outputFloat);
  6565. }
  6566. }
  6567. }
  6568. TEST_F(ExecutionTest, BarycentricsTest) {
  6569. WEX::TestExecution::SetVerifyOutput verifySettings(WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  6570. CComPtr<IStream> pStream;
  6571. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  6572. CComPtr<ID3D12Device> pDevice;
  6573. if (!CreateDevice(&pDevice, D3D_SHADER_MODEL_6_1))
  6574. return;
  6575. if (!DoesDeviceSupportBarycentrics(pDevice)) {
  6576. WEX::Logging::Log::Comment(L"Device does not support barycentrics.");
  6577. WEX::Logging::Log::Result(WEX::Logging::TestResults::Skipped);
  6578. return;
  6579. }
  6580. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTest(pDevice, m_support, pStream, "Barycentrics", nullptr);
  6581. MappedData data;
  6582. D3D12_RESOURCE_DESC &D = test->ShaderOp->GetResourceByName("RTarget")->Desc;
  6583. UINT width = (UINT)D.Width;
  6584. UINT height = D.Height;
  6585. UINT pixelSize = GetByteSizeForFormat(D.Format);
  6586. test->Test->GetReadBackData("RTarget", &data);
  6587. //const uint8_t *pPixels = (uint8_t *)data.data();
  6588. const float *pPixels = (float *)data.data();
  6589. // Get the vertex of barycentric coordinate using VBuffer
  6590. MappedData triangleData;
  6591. test->Test->GetReadBackData("VBuffer", &triangleData);
  6592. const float *pTriangleData = (float*)triangleData.data();
  6593. // get the size of the input data
  6594. unsigned triangleVertexSizeInFloat = 0;
  6595. for (auto element : test->ShaderOp->InputElements)
  6596. triangleVertexSizeInFloat += GetByteSizeForFormat(element.Format) / 4;
  6597. XMFLOAT2 p0(pTriangleData[0], pTriangleData[1]);
  6598. XMFLOAT2 p1(pTriangleData[triangleVertexSizeInFloat], pTriangleData[triangleVertexSizeInFloat + 1]);
  6599. XMFLOAT2 p2(pTriangleData[triangleVertexSizeInFloat * 2], pTriangleData[triangleVertexSizeInFloat * 2 + 1]);
  6600. XMFLOAT3 barycentricWeights[4] = {
  6601. XMFLOAT3(0.3333f, 0.3333f, 0.3333f),
  6602. XMFLOAT3(0.5f, 0.25f, 0.25f),
  6603. XMFLOAT3(0.25f, 0.5f, 0.25f),
  6604. XMFLOAT3(0.25f, 0.25f, 0.50f)
  6605. };
  6606. float tolerance = 0.001f;
  6607. for (unsigned i = 0; i < sizeof(barycentricWeights) / sizeof(XMFLOAT3); ++i) {
  6608. float w0 = barycentricWeights[i].x;
  6609. float w1 = barycentricWeights[i].y;
  6610. float w2 = barycentricWeights[i].z;
  6611. float x1 = w0 * p0.x + w1 * p1.x + w2 * p2.x;
  6612. float y1 = w0 * p0.y + w1 * p1.y + w2 * p2.y;
  6613. // map from x1 y1 to rtv pixels
  6614. int pixelX = (int)((x1 + 1) * (width - 1) / 2);
  6615. int pixelY = (int)((1 - y1) * (height - 1) / 2);
  6616. int offset = pixelSize * (pixelX + pixelY * width) / sizeof(pPixels[0]);
  6617. LogCommentFmt(L"location %u %u, value %f, %f, %f", pixelX, pixelY, pPixels[offset], pPixels[offset + 1], pPixels[offset + 2]);
  6618. VERIFY_IS_TRUE(CompareFloatEpsilon(pPixels[offset], w0, tolerance));
  6619. VERIFY_IS_TRUE(CompareFloatEpsilon(pPixels[offset + 1], w1, tolerance));
  6620. VERIFY_IS_TRUE(CompareFloatEpsilon(pPixels[offset + 2], w2, tolerance));
  6621. }
  6622. //SavePixelsToFile(pPixels, DXGI_FORMAT_R32G32B32A32_FLOAT, width, height, L"barycentric.bmp");
  6623. }
  6624. static const char RawBufferTestShaderDeclarations[] =
  6625. "// Note: COMPONENT_TYPE and COMPONENT_SIZE will be defined via compiler option -D\r\n"
  6626. "typedef COMPONENT_TYPE scalar; \r\n"
  6627. "typedef vector<COMPONENT_TYPE, 2> vector2; \r\n"
  6628. "typedef vector<COMPONENT_TYPE, 3> vector3; \r\n"
  6629. "typedef vector<COMPONENT_TYPE, 4> vector4; \r\n"
  6630. "\r\n"
  6631. "struct TestData { \r\n"
  6632. " scalar v1; \r\n"
  6633. " vector2 v2; \r\n"
  6634. " vector3 v3; \r\n"
  6635. " vector4 v4; \r\n"
  6636. "}; \r\n"
  6637. "\r\n"
  6638. "struct UavData {\r\n"
  6639. " TestData input; \r\n"
  6640. " TestData output; \r\n"
  6641. " TestData srvOut; \r\n"
  6642. "}; \r\n"
  6643. "\r\n"
  6644. "ByteAddressBuffer srv0 : register(t0); \r\n"
  6645. "StructuredBuffer<TestData> srv1 : register(t1); \r\n"
  6646. "ByteAddressBuffer srv2 : register(t2); \r\n"
  6647. "StructuredBuffer<TestData> srv3 : register(t3); \r\n"
  6648. "\r\n"
  6649. "RWByteAddressBuffer uav0 : register(u0); \r\n"
  6650. "RWStructuredBuffer<UavData> uav1 : register(u1); \r\n"
  6651. "RWByteAddressBuffer uav2 : register(u2); \r\n"
  6652. "RWStructuredBuffer<UavData> uav3 : register(u3); \r\n";
  6653. static const char RawBufferTestShaderBody[] =
  6654. " // offset of 'out' in 'UavData'\r\n"
  6655. " const int out_offset = COMPONENT_SIZE * 10; \r\n"
  6656. "\r\n"
  6657. " // offset of 'srv_out' in 'UavData'\r\n"
  6658. " const int srv_out_offset = COMPONENT_SIZE * 10 * 2; \r\n"
  6659. "\r\n"
  6660. " // offsets within the 'Data' struct\r\n"
  6661. " const int v1_offset = 0; \r\n"
  6662. " const int v2_offset = COMPONENT_SIZE; \r\n"
  6663. " const int v3_offset = COMPONENT_SIZE * 3; \r\n"
  6664. " const int v4_offset = COMPONENT_SIZE * 6; \r\n"
  6665. "\r\n"
  6666. " uav0.Store(srv_out_offset + v1_offset, srv0.Load<scalar>(v1_offset)); \r\n"
  6667. " uav0.Store(srv_out_offset + v2_offset, srv0.Load<vector2>(v2_offset)); \r\n"
  6668. " uav0.Store(srv_out_offset + v3_offset, srv0.Load<vector3>(v3_offset)); \r\n"
  6669. " uav0.Store(srv_out_offset + v4_offset, srv0.Load<vector4>(v4_offset)); \r\n"
  6670. "\r\n"
  6671. " uav1[0].srvOut.v1 = srv1[0].v1; \r\n"
  6672. " uav1[0].srvOut.v2 = srv1[0].v2; \r\n"
  6673. " uav1[0].srvOut.v3 = srv1[0].v3; \r\n"
  6674. " uav1[0].srvOut.v4 = srv1[0].v4; \r\n"
  6675. "\r\n"
  6676. " uav2.Store(srv_out_offset + v1_offset, srv2.Load<scalar>(v1_offset)); \r\n"
  6677. " uav2.Store(srv_out_offset + v2_offset, srv2.Load<vector2>(v2_offset)); \r\n"
  6678. " uav2.Store(srv_out_offset + v3_offset, srv2.Load<vector3>(v3_offset)); \r\n"
  6679. " uav2.Store(srv_out_offset + v4_offset, srv2.Load<vector4>(v4_offset)); \r\n"
  6680. "\r\n"
  6681. " uav3[0].srvOut.v1 = srv3[0].v1; \r\n"
  6682. " uav3[0].srvOut.v2 = srv3[0].v2; \r\n"
  6683. " uav3[0].srvOut.v3 = srv3[0].v3; \r\n"
  6684. " uav3[0].srvOut.v4 = srv3[0].v4; \r\n"
  6685. "\r\n"
  6686. " uav0.Store(out_offset + v1_offset, uav0.Load<scalar>(v1_offset)); \r\n"
  6687. " uav0.Store(out_offset + v2_offset, uav0.Load<vector2>(v2_offset)); \r\n"
  6688. " uav0.Store(out_offset + v3_offset, uav0.Load<vector3>(v3_offset)); \r\n"
  6689. " uav0.Store(out_offset + v4_offset, uav0.Load<vector4>(v4_offset)); \r\n"
  6690. "\r\n"
  6691. " uav1[0].output.v1 = uav1[0].input.v1; \r\n"
  6692. " uav1[0].output.v2 = uav1[0].input.v2; \r\n"
  6693. " uav1[0].output.v3 = uav1[0].input.v3; \r\n"
  6694. " uav1[0].output.v4 = uav1[0].input.v4; \r\n"
  6695. "\r\n"
  6696. " uav2.Store(out_offset + v1_offset, uav2.Load<scalar>(v1_offset)); \r\n"
  6697. " uav2.Store(out_offset + v2_offset, uav2.Load<vector2>(v2_offset)); \r\n"
  6698. " uav2.Store(out_offset + v3_offset, uav2.Load<vector3>(v3_offset)); \r\n"
  6699. " uav2.Store(out_offset + v4_offset, uav2.Load<vector4>(v4_offset)); \r\n"
  6700. "\r\n"
  6701. " uav3[0].output.v1 = uav3[0].input.v1; \r\n"
  6702. " uav3[0].output.v2 = uav3[0].input.v2; \r\n"
  6703. " uav3[0].output.v3 = uav3[0].input.v3; \r\n"
  6704. " uav3[0].output.v4 = uav3[0].input.v4; \r\n";
  6705. static const char RawBufferTestComputeShaderTemplate[] =
  6706. "%s\r\n" // <- RawBufferTestShaderDeclarations
  6707. "[numthreads(1, 1, 1)]\r\n"
  6708. "void main(uint GI : SV_GroupIndex) {\r\n"
  6709. "%s\r\n" // <- RawBufferTestShaderBody
  6710. "};";
  6711. static const char RawBufferTestGraphicsPixelShaderTemplate[] =
  6712. "%s\r\n" // <- RawBufferTestShaderDeclarations
  6713. "struct PSInput { \r\n"
  6714. " float4 pos : SV_POSITION; \r\n"
  6715. "}; \r\n"
  6716. "uint4 main(PSInput input) : SV_TARGET{ \r\n"
  6717. " if (input.pos.x + input.pos.y == 1.0f) { // pixel { 0.5, 0.5, 0 } \r\n"
  6718. "%s\r\n" // <- RawBufferTestShaderBody
  6719. " } \r\n"
  6720. " return uint4(1, 2, 3, 4); \r\n"
  6721. "};";
  6722. TEST_F(ExecutionTest, ComputeRawBufferLdStI32) {
  6723. RawBufferLdStTestData<int32_t> data = { { 1 }, { 2, -1 }, { 256, -10517, 980 }, { 465, 13, -89, MAXUINT32 / 2 } };
  6724. RunComputeRawBufferLdStTest<int32_t>(D3D_SHADER_MODEL_6_2, RawBufferLdStType::I32, "ComputeRawBufferLdSt32Bit", data);
  6725. }
  6726. TEST_F(ExecutionTest, ComputeRawBufferLdStFloat) {
  6727. RawBufferLdStTestData<float> data = { { 3e-10f }, { 1.5f, -1.99988f }, { 256.0f, -105.17f, 980.0f }, { 465.1652f, -1.5694e2f, -0.8543e-2f, 1333.5f } };
  6728. RunComputeRawBufferLdStTest<float>(D3D_SHADER_MODEL_6_2, RawBufferLdStType::Float, "ComputeRawBufferLdSt32Bit", data);
  6729. }
  6730. TEST_F(ExecutionTest, ComputeRawBufferLdStI64) {
  6731. RawBufferLdStTestData<int64_t> data = { { 1 }, { 2, -1 }, { 256, -105171532, 980 }, { 465, 13, -89, MAXUINT64 / 2 } };
  6732. RunComputeRawBufferLdStTest<int64_t>(D3D_SHADER_MODEL_6_3, RawBufferLdStType::I64, "ComputeRawBufferLdSt64Bit", data);
  6733. }
  6734. TEST_F(ExecutionTest, ComputeRawBufferLdStDouble) {
  6735. RawBufferLdStTestData<double> data = { { 3e-10 }, { 1.5, -1.99988 }, { 256.0, -105.17, 980.0 }, { 465.1652, -1.5694e2, -0.8543e-2, 1333.5 } };
  6736. RunComputeRawBufferLdStTest<double>(D3D_SHADER_MODEL_6_3, RawBufferLdStType::I64, "ComputeRawBufferLdSt64Bit", data);
  6737. }
  6738. TEST_F(ExecutionTest, ComputeRawBufferLdStI16) {
  6739. RawBufferLdStTestData<int16_t> data = { { 1 }, { 2, -1 }, { 256, -10517, 980 }, { 465, 13, -89, MAXUINT16 / 2 } };
  6740. RunComputeRawBufferLdStTest<int16_t>(D3D_SHADER_MODEL_6_2, RawBufferLdStType::I16, "ComputeRawBufferLdSt16Bit", data);
  6741. }
  6742. TEST_F(ExecutionTest, ComputeRawBufferLdStHalf) {
  6743. RawBufferLdStTestData<float> floatData = { { 3e-10f }, { 1.5f, -1.99988f }, { 256.0f, 105.17f, 980.0f }, { 465.1652f, -1.5694e2f, -0.8543e-2f, 1333.5f } };
  6744. RawBufferLdStTestData<uint16_t> halfData;
  6745. for (int i = 0; i < sizeof(floatData)/sizeof(float); i++) {
  6746. ((uint16_t*)&halfData)[i] = ConvertFloat32ToFloat16(((float*)&floatData)[i]);
  6747. }
  6748. RunComputeRawBufferLdStTest<uint16_t>(D3D_SHADER_MODEL_6_2, RawBufferLdStType::Half, "ComputeRawBufferLdSt16Bit", halfData);
  6749. }
  6750. TEST_F(ExecutionTest, GraphicsRawBufferLdStI32) {
  6751. RawBufferLdStTestData<int32_t> data = { { 1 }, { 2, -1 }, { 256, -10517, 980 }, { 465, 13, -89, MAXUINT32 / 2 } };
  6752. RunGraphicsRawBufferLdStTest<int32_t>(D3D_SHADER_MODEL_6_2, RawBufferLdStType::I32, "GraphicsRawBufferLdSt32Bit", data);
  6753. }
  6754. TEST_F(ExecutionTest, GraphicsRawBufferLdStFloat) {
  6755. RawBufferLdStTestData<float> data = { { 3e-10f }, { 1.5f, -1.99988f }, { 256.0f, -105.17f, 980.0f }, { 465.1652f, -1.5694e2f, -0.8543e-2f, 1333.5f } };
  6756. RunGraphicsRawBufferLdStTest<float>(D3D_SHADER_MODEL_6_2, RawBufferLdStType::Float, "GraphicsRawBufferLdSt32Bit", data);
  6757. }
  6758. TEST_F(ExecutionTest, GraphicsRawBufferLdStI64) {
  6759. RawBufferLdStTestData<int64_t> data = { { 1 }, { 2, -1 }, { 256, -105171532, 980 }, { 465, 13, -89, MAXUINT64 / 2 } };
  6760. RunGraphicsRawBufferLdStTest<int64_t>(D3D_SHADER_MODEL_6_3, RawBufferLdStType::I64, "GraphicsRawBufferLdSt64Bit", data);
  6761. }
  6762. TEST_F(ExecutionTest, GraphicsRawBufferLdStDouble) {
  6763. RawBufferLdStTestData<double> data = { { 3e-10 }, { 1.5, -1.99988 }, { 256.0, -105.17, 980.0 }, { 465.1652, -1.5694e2, -0.8543e-2, 1333.5 } };
  6764. RunGraphicsRawBufferLdStTest<double>(D3D_SHADER_MODEL_6_3, RawBufferLdStType::Double, "GraphicsRawBufferLdSt64Bit", data);
  6765. }
  6766. TEST_F(ExecutionTest, GraphicsRawBufferLdStI16) {
  6767. RawBufferLdStTestData<int16_t> data = { { 1 }, { 2, -1 }, { 256, -10517, 980 }, { 465, 13, -89, MAXUINT16 / 2 } };
  6768. RunGraphicsRawBufferLdStTest<int16_t>(D3D_SHADER_MODEL_6_2, RawBufferLdStType::I16, "GraphicsRawBufferLdSt16Bit", data);
  6769. }
  6770. TEST_F(ExecutionTest, GraphicsRawBufferLdStHalf) {
  6771. RawBufferLdStTestData<float> floatData = { { 3e-10f }, { 1.5f, -1.99988f }, { 256.0f, 105.17f, 0.0f }, { 465.1652f, -1.5694e2f, -0.8543e-2f, 1333.5f } };
  6772. RawBufferLdStTestData<uint16_t> halfData;
  6773. for (int i = 0; i < sizeof(floatData) / sizeof(float); i++) {
  6774. ((uint16_t*)&halfData)[i] = ConvertFloat32ToFloat16(((float*)&floatData)[i]);
  6775. }
  6776. RunGraphicsRawBufferLdStTest<uint16_t>(D3D_SHADER_MODEL_6_2, RawBufferLdStType::Half, "GraphicsRawBufferLdSt16Bit", halfData);
  6777. }
  6778. bool ExecutionTest::SetupRawBufferLdStTest(D3D_SHADER_MODEL shaderModel, RawBufferLdStType dataType,
  6779. CComPtr<ID3D12Device> &pDevice, CComPtr<IStream> &pStream,
  6780. char *&sTy, char *&additionalOptions) {
  6781. if (!CreateDevice(&pDevice, shaderModel)) {
  6782. return false;
  6783. }
  6784. additionalOptions = "";
  6785. switch (dataType) {
  6786. case RawBufferLdStType::I64:
  6787. if (!DoesDeviceSupportInt64(pDevice)) {
  6788. WEX::Logging::Log::Comment(L"Device does not support int64 operations.");
  6789. WEX::Logging::Log::Result(WEX::Logging::TestResults::Skipped);
  6790. return false;
  6791. }
  6792. sTy = "int64_t";
  6793. break;
  6794. case RawBufferLdStType::Double:
  6795. if (!DoesDeviceSupportDouble(pDevice)) {
  6796. WEX::Logging::Log::Comment(L"Device does not support double operations.");
  6797. WEX::Logging::Log::Result(WEX::Logging::TestResults::Skipped);
  6798. return false;
  6799. }
  6800. sTy = "double";
  6801. break;
  6802. case RawBufferLdStType::I16:
  6803. case RawBufferLdStType::Half:
  6804. if (!DoesDeviceSupportNative16bitOps(pDevice)) {
  6805. WEX::Logging::Log::Comment(L"Device does not support native 16-bit operations.");
  6806. WEX::Logging::Log::Result(WEX::Logging::TestResults::Skipped);
  6807. return false;
  6808. }
  6809. additionalOptions = "-enable-16bit-types";
  6810. sTy = (dataType == RawBufferLdStType::I16 ? "int16_t" : "half");
  6811. break;
  6812. case RawBufferLdStType::I32:
  6813. sTy = "int32_t";
  6814. break;
  6815. case RawBufferLdStType::Float:
  6816. sTy = "float";
  6817. break;
  6818. default:
  6819. DXASSERT_NOMSG("Invalid RawBufferLdStType");
  6820. }
  6821. // read shader config
  6822. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  6823. return true;
  6824. }
  6825. template <class Ty>
  6826. void ExecutionTest::VerifyRawBufferLdStTestResults(const std::shared_ptr<st::ShaderOpTest> test, const RawBufferLdStTestData<Ty> &testData) {
  6827. // read buffers back & verify expected values
  6828. static const int UavBufferCount = 4;
  6829. char bufferName[11] = "UAVBufferX";
  6830. for (unsigned i = 0; i < UavBufferCount; i++) {
  6831. MappedData dataUav;
  6832. RawBufferLdStUavData<Ty> *pOutData;
  6833. bufferName[sizeof(bufferName) - 2] = (char)(i + '0');
  6834. test->GetReadBackData(bufferName, &dataUav);
  6835. VERIFY_ARE_EQUAL(sizeof(RawBufferLdStUavData<Ty>), dataUav.size());
  6836. pOutData = (RawBufferLdStUavData<Ty> *)dataUav.data();
  6837. LogCommentFmt(L"Verifying UAVBuffer%d Load -> UAVBuffer%d Store", i, i);
  6838. // scalar
  6839. VERIFY_ARE_EQUAL(pOutData->output.v1, testData.v1);
  6840. // vector 2
  6841. VERIFY_ARE_EQUAL(pOutData->output.v2[0], testData.v2[0]);
  6842. VERIFY_ARE_EQUAL(pOutData->output.v2[1], testData.v2[1]);
  6843. // vector 3
  6844. VERIFY_ARE_EQUAL(pOutData->output.v3[0], testData.v3[0]);
  6845. VERIFY_ARE_EQUAL(pOutData->output.v3[1], testData.v3[1]);
  6846. VERIFY_ARE_EQUAL(pOutData->output.v3[2], testData.v3[2]);
  6847. // vector 4
  6848. VERIFY_ARE_EQUAL(pOutData->output.v4[0], testData.v4[0]);
  6849. VERIFY_ARE_EQUAL(pOutData->output.v4[1], testData.v4[1]);
  6850. VERIFY_ARE_EQUAL(pOutData->output.v4[2], testData.v4[2]);
  6851. VERIFY_ARE_EQUAL(pOutData->output.v4[3], testData.v4[3]);
  6852. // verify SRV Store
  6853. LogCommentFmt(L"Verifying SRVBuffer%d Load -> UAVBuffer%d Store", i, i);
  6854. // scalar
  6855. VERIFY_ARE_EQUAL(pOutData->srvOut.v1, testData.v1);
  6856. // vector 2
  6857. VERIFY_ARE_EQUAL(pOutData->srvOut.v2[0], testData.v2[0]);
  6858. VERIFY_ARE_EQUAL(pOutData->srvOut.v2[1], testData.v2[1]);
  6859. // vector 3
  6860. VERIFY_ARE_EQUAL(pOutData->srvOut.v3[0], testData.v3[0]);
  6861. VERIFY_ARE_EQUAL(pOutData->srvOut.v3[1], testData.v3[1]);
  6862. VERIFY_ARE_EQUAL(pOutData->srvOut.v3[2], testData.v3[2]);
  6863. // vector 4
  6864. VERIFY_ARE_EQUAL(pOutData->srvOut.v4[0], testData.v4[0]);
  6865. VERIFY_ARE_EQUAL(pOutData->srvOut.v4[1], testData.v4[1]);
  6866. VERIFY_ARE_EQUAL(pOutData->srvOut.v4[2], testData.v4[2]);
  6867. VERIFY_ARE_EQUAL(pOutData->srvOut.v4[3], testData.v4[3]);
  6868. }
  6869. }
  6870. template <class Ty>
  6871. void ExecutionTest::RunComputeRawBufferLdStTest(D3D_SHADER_MODEL shaderModel, RawBufferLdStType dataType,
  6872. const char *shaderOpName, const RawBufferLdStTestData<Ty> &testData) {
  6873. WEX::TestExecution::SetVerifyOutput verifySettings(WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  6874. CComPtr<ID3D12Device> pDevice;
  6875. CComPtr<IStream> pStream;
  6876. char *sTy = nullptr, *additionalOptions = nullptr;
  6877. if (!SetupRawBufferLdStTest(shaderModel, dataType, pDevice, pStream, sTy, additionalOptions)) {
  6878. return;
  6879. }
  6880. // format shader source
  6881. char rawBufferTestShaderText[sizeof(RawBufferTestComputeShaderTemplate) + sizeof(RawBufferTestShaderDeclarations) + sizeof(RawBufferTestShaderBody)];
  6882. VERIFY_IS_TRUE(sprintf_s(rawBufferTestShaderText, sizeof(rawBufferTestShaderText),
  6883. RawBufferTestComputeShaderTemplate, RawBufferTestShaderDeclarations, RawBufferTestShaderBody) != -1);
  6884. // format compiler args
  6885. char compilerOptions[256];
  6886. VERIFY_IS_TRUE(sprintf_s(compilerOptions, sizeof(compilerOptions), "-D COMPONENT_TYPE=%s -D COMPONENT_SIZE=%d %s", sTy, (int)sizeof(Ty), additionalOptions) != -1);
  6887. // run the shader
  6888. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTest(pDevice, m_support, pStream, shaderOpName,
  6889. [&](LPCSTR Name, std::vector<BYTE> &Data, st::ShaderOp *pShaderOp) {
  6890. VERIFY_IS_TRUE(((0 == strncmp(Name, "SRVBuffer", 9)) || (0 == strncmp(Name, "UAVBuffer", 9))) &&
  6891. (Name[9] >= '0' && Name[9] <= '3'));
  6892. pShaderOp->Shaders.at(0).Arguments = compilerOptions;
  6893. pShaderOp->Shaders.at(0).Text = rawBufferTestShaderText;
  6894. VERIFY_IS_TRUE(sizeof(RawBufferLdStTestData<Ty>) <= Data.size());
  6895. RawBufferLdStTestData<Ty> *pInData = (RawBufferLdStTestData<Ty>*)Data.data();
  6896. memcpy(pInData, &testData, sizeof(RawBufferLdStTestData<Ty>));
  6897. });
  6898. // verify expected values
  6899. VerifyRawBufferLdStTestResults<Ty>(test->Test, testData);
  6900. }
  6901. template <class Ty>
  6902. void ExecutionTest::RunGraphicsRawBufferLdStTest(D3D_SHADER_MODEL shaderModel, RawBufferLdStType dataType,
  6903. const char *shaderOpName, const RawBufferLdStTestData<Ty> &testData) {
  6904. WEX::TestExecution::SetVerifyOutput verifySettings(WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  6905. CComPtr<ID3D12Device> pDevice;
  6906. CComPtr<IStream> pStream;
  6907. char *sTy = nullptr, *additionalOptions = nullptr;
  6908. if (!SetupRawBufferLdStTest(shaderModel, dataType, pDevice, pStream, sTy, additionalOptions)) {
  6909. return;
  6910. }
  6911. // format shader source
  6912. char rawBufferTestPixelShaderText[sizeof(RawBufferTestGraphicsPixelShaderTemplate) + sizeof(RawBufferTestShaderDeclarations) + sizeof(RawBufferTestShaderBody)];
  6913. VERIFY_IS_TRUE(sprintf_s(rawBufferTestPixelShaderText, sizeof(rawBufferTestPixelShaderText),
  6914. RawBufferTestGraphicsPixelShaderTemplate, RawBufferTestShaderDeclarations, RawBufferTestShaderBody) != -1);
  6915. // format compiler args
  6916. char compilerOptions[256];
  6917. VERIFY_IS_TRUE(sprintf_s(compilerOptions, sizeof(compilerOptions), "-D COMPONENT_TYPE=%s -D COMPONENT_SIZE=%d %s", sTy, (int)sizeof(Ty), additionalOptions) != -1);
  6918. // run the shader
  6919. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTest(pDevice, m_support, pStream, shaderOpName,
  6920. [&](LPCSTR Name, std::vector<BYTE> &Data, st::ShaderOp *pShaderOp) {
  6921. VERIFY_IS_TRUE(((0 == strncmp(Name, "SRVBuffer", 9)) || (0 == strncmp(Name, "UAVBuffer", 9))) &&
  6922. (Name[9] >= '0' && Name[9] <= '3'));
  6923. // pixel shader is at index 1, vertex shader at index 0
  6924. pShaderOp->Shaders.at(1).Arguments = compilerOptions;
  6925. pShaderOp->Shaders.at(1).Text = rawBufferTestPixelShaderText;
  6926. VERIFY_IS_TRUE(sizeof(RawBufferLdStTestData<Ty>) <= Data.size());
  6927. RawBufferLdStTestData<Ty> *pInData = (RawBufferLdStTestData<Ty>*)Data.data();
  6928. memcpy(pInData, &testData, sizeof(RawBufferLdStTestData<Ty>));
  6929. });
  6930. // verify expected values
  6931. VerifyRawBufferLdStTestResults<Ty>(test->Test, testData);
  6932. }
  6933. template<typename T>
  6934. uint32_t pack(std::array<T, 4> unpackedVals)
  6935. {
  6936. uint32_t dst = 0;
  6937. constexpr uint32_t bitMask = 0xFF;
  6938. for (uint32_t i = 0U; i < 4U; ++i)
  6939. {
  6940. dst |= (unpackedVals[i] & bitMask) << (i * 8);
  6941. }
  6942. return dst;
  6943. }
  6944. template <typename T>
  6945. uint32_t pack_clamp_u8(std::array<T, 4> unpackedVals)
  6946. {
  6947. int32_t clamp_min = std::numeric_limits<uint8_t>::min();
  6948. int32_t clamp_max = std::numeric_limits<uint8_t>::max();
  6949. uint32_t dst = 0;
  6950. for (uint32_t i = 0U; i < 4U; ++i)
  6951. {
  6952. int32_t clamped = std::min(std::max((int32_t)unpackedVals[i], clamp_min), clamp_max);
  6953. dst |= ((uint8_t)clamped) << (i * 8);
  6954. }
  6955. return dst;
  6956. }
  6957. template <typename T>
  6958. uint32_t pack_clamp_s8(std::array<T, 4> unpackedVals)
  6959. {
  6960. int32_t clamp_min = std::numeric_limits<int8_t>::min();
  6961. int32_t clamp_max = std::numeric_limits<int8_t>::max();
  6962. uint32_t dst = 0;
  6963. for (uint32_t i = 0U; i < 4U; ++i)
  6964. {
  6965. int32_t clamped = std::min(std::max((int32_t)unpackedVals[i], clamp_min), clamp_max);
  6966. dst |= ((uint8_t)clamped) << (i * 8);
  6967. }
  6968. return dst;
  6969. }
  6970. template<typename T>
  6971. std::array<T, 4> unpack_u(uint32_t packedVal)
  6972. {
  6973. std::array<T, 4> ret;
  6974. ret[0] = (uint8_t)((packedVal & 0x000000FF) >> 0 );
  6975. ret[1] = (uint8_t)((packedVal & 0x0000FF00) >> 8 );
  6976. ret[2] = (uint8_t)((packedVal & 0x00FF0000) >> 16);
  6977. ret[3] = (uint8_t)((packedVal & 0xFF000000) >> 24);
  6978. return ret;
  6979. }
  6980. template<typename T>
  6981. std::array<T, 4> unpack_s(uint32_t packedVal)
  6982. {
  6983. std::array<T, 4> ret;
  6984. ret[0] = (int8_t)((packedVal & 0x000000FF) >> 0 );
  6985. ret[1] = (int8_t)((packedVal & 0x0000FF00) >> 8 );
  6986. ret[2] = (int8_t)((packedVal & 0x00FF0000) >> 16);
  6987. ret[3] = (int8_t)((packedVal & 0xFF000000) >> 24);
  6988. return ret;
  6989. }
  6990. TEST_F(ExecutionTest, PackUnpackTest) {
  6991. WEX::TestExecution::SetVerifyOutput verifySettings(
  6992. WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  6993. CComPtr<IStream> pStream;
  6994. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  6995. CComPtr<ID3D12Device> pDevice;
  6996. #ifdef PACKUNPACK_PLACEHOLDER
  6997. string args = "-enable-16bit-types -DPACKUNPACK_PLACEHOLDER";
  6998. string target = "cs_6_2";
  6999. if (!CreateDevice(&pDevice)) {
  7000. return;
  7001. }
  7002. #else
  7003. string args = "-enable-16bit-types";
  7004. string target = "cs_6_6";
  7005. if (!CreateDevice(&pDevice, D3D_SHADER_MODEL_6_6)) {
  7006. return;
  7007. }
  7008. #endif
  7009. int tableSize = sizeof(PackUnpackOpParameters) / sizeof(TableParameter);
  7010. TableParameterHandler handler(PackUnpackOpParameters, tableSize);
  7011. CW2A Text(handler.GetTableParamByName(L"ShaderOp.Text")->m_str);
  7012. std::vector<uint32_t> *validation_input = &handler.GetTableParamByName(L"Validation.Input")->m_uint32Table;
  7013. uint32_t validation_tolerance = handler.GetTableParamByName(L"Validation.Tolerance")->m_uint;
  7014. size_t count = validation_input->size();
  7015. std::vector<SPackUnpackOpOutPacked> expectedPacked(count / 4);
  7016. std::vector<SPackUnpackOpOutUnpacked> expectedUnpacked(count / 4);
  7017. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTest(
  7018. pDevice, m_support, pStream, "PackUnpackOp",
  7019. // this callback is called when the test
  7020. // is creating the resource to run the test
  7021. [&](LPCSTR Name, std::vector<BYTE> &Data, st::ShaderOp *pShaderOp) {
  7022. if (0 == _stricmp(Name, "g_bufIn"))
  7023. {
  7024. size_t size = sizeof(uint32_t) * 4 * count;
  7025. Data.resize(size);
  7026. uint32_t *pPrimitives = (uint32_t*)Data.data();
  7027. for (size_t i = 0; i < count / 4; ++i) {
  7028. uint32_t *p = &pPrimitives[i * 4];
  7029. uint32_t x = (*validation_input)[i * 4 + 0];
  7030. uint32_t y = (*validation_input)[i * 4 + 1];
  7031. uint32_t z = (*validation_input)[i * 4 + 2];
  7032. uint32_t w = (*validation_input)[i * 4 + 3];
  7033. p[0] = x;
  7034. p[1] = y;
  7035. p[2] = z;
  7036. p[3] = w;
  7037. std::array<uint32_t, 4> inputUint32 = { x, y, z, w };
  7038. std::array<int32_t, 4> inputInt32 = { (int32_t)x, (int32_t)y, (int32_t)z, (int32_t)w };
  7039. std::array<uint16_t, 4> inputUint16 = { (uint16_t)x, (uint16_t)y, (uint16_t)z, (uint16_t)w };
  7040. std::array<int16_t, 4> inputInt16 = { (int16_t)x, (int16_t)y, (int16_t)z, (int16_t)w };
  7041. // Pack unclamped
  7042. expectedPacked[i].packedUint32 = pack(inputUint32);
  7043. expectedPacked[i].packedInt32 = pack(inputInt32);
  7044. expectedPacked[i].packedUint16 = pack(inputUint16);
  7045. expectedPacked[i].packedInt16 = pack(inputInt16);
  7046. // pack clamped
  7047. expectedPacked[i].packedClampedUint32 = pack_clamp_u8(inputInt32);
  7048. expectedPacked[i].packedClampedInt32 = pack_clamp_s8(inputInt32);
  7049. expectedPacked[i].packedClampedUint16 = pack_clamp_u8(inputInt16);
  7050. expectedPacked[i].packedClampedInt16 = pack_clamp_s8(inputInt16);
  7051. // unpack
  7052. expectedUnpacked[i].outputUint32 = unpack_u<uint32_t>(expectedPacked[i].packedUint32);
  7053. expectedUnpacked[i].outputInt32 = unpack_s<int32_t >(expectedPacked[i].packedInt32 );
  7054. expectedUnpacked[i].outputUint16 = unpack_u<uint16_t>(expectedPacked[i].packedUint16);
  7055. expectedUnpacked[i].outputInt16 = unpack_s<int16_t >(expectedPacked[i].packedInt16 );
  7056. expectedUnpacked[i].outputClampedUint32 = unpack_u<uint32_t>(expectedPacked[i].packedClampedUint32);
  7057. expectedUnpacked[i].outputClampedInt32 = unpack_s<int32_t >(expectedPacked[i].packedClampedInt32 );
  7058. expectedUnpacked[i].outputClampedUint16 = unpack_u<uint16_t>(expectedPacked[i].packedClampedUint16);
  7059. expectedUnpacked[i].outputClampedInt16 = unpack_s<int16_t >(expectedPacked[i].packedClampedInt16 );
  7060. }
  7061. }
  7062. else
  7063. {
  7064. std::fill(Data.begin(), Data.end(), (BYTE)0);
  7065. }
  7066. // use shader from data table
  7067. pShaderOp->Shaders.at(0).Target = target.c_str();
  7068. pShaderOp->Shaders.at(0).Text = Text.m_psz;
  7069. pShaderOp->Shaders.at(0).Arguments = args.c_str();
  7070. });
  7071. MappedData packedData;
  7072. test->Test->GetReadBackData("g_bufOutPacked", &packedData);
  7073. SPackUnpackOpOutPacked *readBackPacked = (SPackUnpackOpOutPacked *)packedData.data();
  7074. MappedData unpackedData;
  7075. test->Test->GetReadBackData("g_bufOutPackedUnpacked", &unpackedData);
  7076. SPackUnpackOpOutUnpacked *readBackUnpacked = (SPackUnpackOpOutUnpacked *)unpackedData.data();
  7077. for (size_t i = 0; i < count / 4; ++i)
  7078. {
  7079. VerifyOutputWithExpectedValueUInt(readBackPacked[i].packedUint32, expectedPacked[i].packedUint32, validation_tolerance);
  7080. VerifyOutputWithExpectedValueInt (readBackPacked[i].packedInt32 , expectedPacked[i].packedInt32 , validation_tolerance);
  7081. VerifyOutputWithExpectedValueUInt(readBackPacked[i].packedUint16, expectedPacked[i].packedUint16, validation_tolerance);
  7082. VerifyOutputWithExpectedValueInt (readBackPacked[i].packedInt16 , expectedPacked[i].packedInt16 , validation_tolerance);
  7083. VerifyOutputWithExpectedValueUInt(readBackPacked[i].packedClampedUint32, expectedPacked[i].packedClampedUint32, validation_tolerance);
  7084. VerifyOutputWithExpectedValueInt (readBackPacked[i].packedClampedInt32 , expectedPacked[i].packedClampedInt32 , validation_tolerance);
  7085. VerifyOutputWithExpectedValueUInt(readBackPacked[i].packedClampedUint16, expectedPacked[i].packedClampedUint16, validation_tolerance);
  7086. VerifyOutputWithExpectedValueInt (readBackPacked[i].packedClampedInt16 , expectedPacked[i].packedClampedInt16 , validation_tolerance);
  7087. for (uint32_t j = 0; j < 4; ++j)
  7088. {
  7089. VerifyOutputWithExpectedValueUInt(readBackUnpacked[i].outputUint32[j], expectedUnpacked[i].outputUint32[j], validation_tolerance);
  7090. VerifyOutputWithExpectedValueInt (readBackUnpacked[i].outputInt32 [j], expectedUnpacked[i].outputInt32 [j], validation_tolerance);
  7091. VerifyOutputWithExpectedValueUInt(readBackUnpacked[i].outputUint16[j], expectedUnpacked[i].outputUint16[j], validation_tolerance);
  7092. VerifyOutputWithExpectedValueInt (readBackUnpacked[i].outputInt16 [j], expectedUnpacked[i].outputInt16 [j], validation_tolerance);
  7093. VerifyOutputWithExpectedValueUInt(readBackUnpacked[i].outputClampedUint32[j], expectedUnpacked[i].outputClampedUint32[j], validation_tolerance);
  7094. VerifyOutputWithExpectedValueInt (readBackUnpacked[i].outputClampedInt32 [j], expectedUnpacked[i].outputClampedInt32 [j], validation_tolerance);
  7095. VerifyOutputWithExpectedValueUInt(readBackUnpacked[i].outputClampedUint16[j], expectedUnpacked[i].outputClampedUint16[j], validation_tolerance);
  7096. VerifyOutputWithExpectedValueInt (readBackUnpacked[i].outputClampedInt16 [j], expectedUnpacked[i].outputClampedInt16 [j], validation_tolerance);
  7097. }
  7098. }
  7099. }
  7100. // This test expects a <pShader> that retrieves a signal value from each of a few
  7101. // resources that are initialized here. <isDynamic> determines if it uses the
  7102. // 6.6 Dynamic Resources feature.
  7103. // Values are read back from the result UAV and compared to the expected signals
  7104. void ExecutionTest::RunResourceTest(ID3D12Device *pDevice, const char *pShader,
  7105. const wchar_t *sm, bool isDynamic) {
  7106. WEX::TestExecution::SetVerifyOutput verifySettings(WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  7107. const int NumSRVs = 3;
  7108. const int NumUAVs = 4;
  7109. const int NumResources = NumSRVs + NumUAVs;
  7110. const int NumSamplers = 2;
  7111. const int valueSize = 16;
  7112. static const int DispatchGroupX = 1;
  7113. static const int DispatchGroupY = 1;
  7114. static const int DispatchGroupZ = 1;
  7115. CComPtr<ID3D12GraphicsCommandList> pCommandList;
  7116. CComPtr<ID3D12CommandQueue> pCommandQueue;
  7117. CComPtr<ID3D12CommandAllocator> pCommandAllocator;
  7118. FenceObj FO;
  7119. UINT valueSizeInBytes = valueSize * sizeof(float);
  7120. CreateComputeCommandQueue(pDevice, L"DynamicResourcesTest Command Queue", &pCommandQueue);
  7121. InitFenceObj(pDevice, &FO);
  7122. // Create root signature.
  7123. CComPtr<ID3D12RootSignature> pRootSignature;
  7124. if (!isDynamic) {
  7125. // Not dynamic, create a range for each resource and from them, the root signature
  7126. CD3DX12_DESCRIPTOR_RANGE ranges[NumResources];
  7127. CD3DX12_DESCRIPTOR_RANGE srange[NumSamplers];
  7128. for (int i = 0; i < NumSRVs; i++)
  7129. ranges[i].Init(D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, i, 0);
  7130. for (int i = NumSRVs; i < NumResources; i++)
  7131. ranges[i].Init(D3D12_DESCRIPTOR_RANGE_TYPE_UAV, 1, i - NumSRVs, 0);
  7132. for (int i = 0; i < NumSamplers; i++)
  7133. srange[i].Init(D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER, 1, i, 0);
  7134. CreateRootSignatureFromRanges(pDevice, &pRootSignature, ranges, NumResources, srange, NumSamplers);
  7135. } else {
  7136. // Dynamic just requires the flags indicating that the builtin arrays should be accessible
  7137. #if !defined(D3D12_ROOT_SIGNATURE_FLAG_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED)
  7138. #define D3D12_ROOT_SIGNATURE_FLAG_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED (D3D12_ROOT_SIGNATURE_FLAGS)0x400
  7139. #define D3D12_ROOT_SIGNATURE_FLAG_SAMPLER_HEAP_DIRECTLY_INDEXED (D3D12_ROOT_SIGNATURE_FLAGS)0x800
  7140. #endif
  7141. CD3DX12_ROOT_SIGNATURE_DESC rootSignatureDesc;
  7142. rootSignatureDesc.Init(0, nullptr, 0, nullptr,
  7143. D3D12_ROOT_SIGNATURE_FLAG_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED |
  7144. D3D12_ROOT_SIGNATURE_FLAG_SAMPLER_HEAP_DIRECTLY_INDEXED);
  7145. CreateRootSignatureFromDesc(pDevice, &rootSignatureDesc, &pRootSignature);
  7146. }
  7147. // Create pipeline state object.
  7148. CComPtr<ID3D12PipelineState> pComputeState;
  7149. CreateComputePSO(pDevice, pRootSignature, pShader, sm, &pComputeState);
  7150. // Create a command allocator and list for compute.
  7151. VERIFY_SUCCEEDED(pDevice->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_COMPUTE, IID_PPV_ARGS(&pCommandAllocator)));
  7152. VERIFY_SUCCEEDED(pDevice->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_COMPUTE, pCommandAllocator, pComputeState, IID_PPV_ARGS(&pCommandList)));
  7153. // Set up SRV resources
  7154. CComPtr<ID3D12Resource> pSRVResources[NumSRVs];
  7155. CComPtr<ID3D12Resource> pUAVResources[NumUAVs];
  7156. CComPtr<ID3D12Resource> pUploadResources[NumResources];
  7157. {
  7158. D3D12_RESOURCE_DESC bufDesc = CD3DX12_RESOURCE_DESC::Buffer(valueSizeInBytes);
  7159. float values[valueSize];
  7160. for (int i = 0; i < NumSRVs - 1; i++) {
  7161. for (int j = 0; j < valueSize; j++)
  7162. values[j] = 10.0f + i;
  7163. CreateTestResources(pDevice, pCommandList, values, valueSizeInBytes, bufDesc,
  7164. &pSRVResources[i], &pUploadResources[i]);
  7165. }
  7166. D3D12_RESOURCE_DESC tex2dDesc = CD3DX12_RESOURCE_DESC::Tex2D(DXGI_FORMAT_R32_FLOAT, 4, 4);
  7167. for (int j = 0; j < valueSize; j++)
  7168. values[j] = 10.0 + (NumSRVs - 1);
  7169. CreateTestResources(pDevice, pCommandList, values, valueSizeInBytes, tex2dDesc,
  7170. &pSRVResources[NumSRVs - 1], &pUploadResources[NumSRVs - 1]);
  7171. }
  7172. // Set up UAV resources
  7173. CComPtr<ID3D12Resource> pReadBuffer;
  7174. float values[valueSize];
  7175. for (int i = 0; i < NumUAVs - 2; i++) {
  7176. for (int j = 0; j < valueSize; j++)
  7177. values[j] = 20.0f + i;
  7178. CreateTestUavs(pDevice, pCommandList, values, valueSizeInBytes,
  7179. &pUAVResources[i], &pUploadResources[NumSRVs + i]);
  7180. }
  7181. for (int j = 0; j < valueSize; j++)
  7182. values[j] = 20.0 + (NumUAVs - 1);
  7183. CreateTestUavs(pDevice, pCommandList, values, valueSizeInBytes,
  7184. &pUAVResources[NumUAVs - 2], &pUploadResources[NumResources - 2], &pReadBuffer);
  7185. for (int j = 0; j < valueSize; j++)
  7186. values[j] = 20.0 + (NumUAVs - 2);
  7187. D3D12_RESOURCE_DESC tex1dDesc = CD3DX12_RESOURCE_DESC::Tex1D(DXGI_FORMAT_R32_FLOAT, valueSize, 1, 0, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS);
  7188. CreateTestResources(pDevice, pCommandList, values, valueSizeInBytes, tex1dDesc,
  7189. &pUAVResources[NumUAVs - 1], &pUploadResources[NumResources - 1]);
  7190. // Close the command list and execute it to perform the GPU setup.
  7191. pCommandList->Close();
  7192. ExecuteCommandList(pCommandQueue, pCommandList);
  7193. WaitForSignal(pCommandQueue, FO);
  7194. VERIFY_SUCCEEDED(pCommandAllocator->Reset());
  7195. VERIFY_SUCCEEDED(pCommandList->Reset(pCommandAllocator, pComputeState));
  7196. CComPtr<ID3D12DescriptorHeap> pResHeap;
  7197. CComPtr<ID3D12DescriptorHeap> pSampHeap;
  7198. CreateDefaultDescHeaps(pDevice, NumSRVs + NumUAVs, NumSamplers, &pResHeap, &pSampHeap);
  7199. // Create Rootsignature and descriptor tables
  7200. {
  7201. ID3D12DescriptorHeap *descHeaps[2] = {pResHeap, pSampHeap};
  7202. pCommandList->SetDescriptorHeaps(2, descHeaps);
  7203. pCommandList->SetComputeRootSignature(pRootSignature);
  7204. if (!isDynamic) {
  7205. // Only non-dynamic resources require descriptortables
  7206. pCommandList->SetComputeRootDescriptorTable(0, pResHeap->GetGPUDescriptorHandleForHeapStart());
  7207. pCommandList->SetComputeRootDescriptorTable(1, pSampHeap->GetGPUDescriptorHandleForHeapStart());
  7208. }
  7209. }
  7210. CD3DX12_CPU_DESCRIPTOR_HANDLE baseHandle(pResHeap->GetCPUDescriptorHandleForHeapStart());
  7211. // Create SRVs
  7212. CreateRawSRV(pDevice, baseHandle, valueSize, pSRVResources[0]);
  7213. CreateStructSRV(pDevice, baseHandle, valueSize, sizeof(float), pSRVResources[1]);
  7214. CreateTex2DSRV(pDevice, baseHandle, valueSize, DXGI_FORMAT_R32_FLOAT, pSRVResources[2]);
  7215. // Create UAVs
  7216. CreateRawUAV(pDevice, baseHandle, valueSize, pUAVResources[0]);
  7217. CreateStructUAV(pDevice, baseHandle, valueSize, sizeof(float), pUAVResources[1]);
  7218. CreateTypedUAV(pDevice, baseHandle, valueSize, DXGI_FORMAT_R32_FLOAT, pUAVResources[2]);
  7219. CreateTex1DUAV(pDevice, baseHandle, valueSize, DXGI_FORMAT_R32_FLOAT, pUAVResources[3]);
  7220. D3D12_FILTER filters[] = {D3D12_FILTER_MIN_MAG_LINEAR_MIP_POINT, D3D12_FILTER_COMPARISON_MIN_MAG_LINEAR_MIP_POINT};
  7221. float borderColors[] = {30.0, 31.0};
  7222. CreateDefaultSamplers(pDevice, pSampHeap->GetCPUDescriptorHandleForHeapStart(),
  7223. filters, borderColors, NumSamplers);
  7224. // Run the compute shader and copy the results back to readable memory.
  7225. pCommandList->Dispatch(DispatchGroupX, DispatchGroupY, DispatchGroupZ);
  7226. RecordTransitionBarrier(pCommandList, pUAVResources[NumUAVs - 2], D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE);
  7227. pCommandList->CopyResource(pReadBuffer, pUAVResources[NumUAVs - 2]);
  7228. pCommandList->Close();
  7229. ExecuteCommandList(pCommandQueue, pCommandList);
  7230. WaitForSignal(pCommandQueue, FO);
  7231. MappedData data(pReadBuffer, valueSize*sizeof(float));
  7232. const float *pData = (float*)data.data();
  7233. LogCommentFmt(L"Verify bound resources are properly selected");
  7234. VERIFY_ARE_EQUAL(pData[0], 10);
  7235. VERIFY_ARE_EQUAL(pData[1], 11);
  7236. VERIFY_ARE_EQUAL(pData[2], 12);
  7237. VERIFY_ARE_EQUAL(pData[3], 20);
  7238. VERIFY_ARE_EQUAL(pData[4], 21);
  7239. VERIFY_ARE_EQUAL(pData[5], 22);
  7240. VERIFY_ARE_EQUAL(pData[6], 30);
  7241. VERIFY_ARE_EQUAL(pData[7], 1); // samplecmp 1 means it matched 31
  7242. }
  7243. TEST_F(ExecutionTest, SignatureResourcesTest) {
  7244. std::string pShader =
  7245. "ByteAddressBuffer g_rawBuf : register(t0);\n"
  7246. "StructuredBuffer<float> g_structBuf : register(t1);\n"
  7247. "Texture2D<float> g_tex : register(t2);\n"
  7248. "RWByteAddressBuffer g_rwRawBuf : register(u0);\n"
  7249. "RWStructuredBuffer<float> g_rwStructBuf : register(u1);\n"
  7250. "RWBuffer<float> g_result : register(u2);\n"
  7251. "RWTexture1D<float> g_rwTex : register(u3);\n"
  7252. "SamplerState g_samp : register(s0);\n"
  7253. "SamplerComparisonState g_sampCmp : register(s1);\n"
  7254. "[NumThreads(1, 1, 1)]\n"
  7255. "void main(uint ix : SV_GroupIndex) {\n"
  7256. " g_result[0] = g_rawBuf.Load<float>(0);\n"
  7257. " g_result[1] = g_structBuf.Load(0);\n"
  7258. " g_result[2] = g_tex.Load(0);\n"
  7259. " g_result[3] = g_rwRawBuf.Load<float>(0);\n"
  7260. " g_result[4] = g_rwStructBuf.Load(0);\n"
  7261. " g_result[5] = g_rwTex.Load(0);\n"
  7262. " g_result[6] = g_tex.SampleLevel(g_samp, -0.5, 0);\n"
  7263. " g_result[7] = g_tex.SampleCmpLevelZero(g_sampCmp, -0.5, 31.0);\n"
  7264. "}\n";
  7265. CComPtr<ID3D12Device> pDevice;
  7266. if (!CreateDevice(&pDevice, D3D_SHADER_MODEL_6_6))
  7267. return;
  7268. RunResourceTest(pDevice, pShader.c_str(), L"cs_6_6", /*isDynamic*/false);
  7269. }
  7270. TEST_F(ExecutionTest, DynamicResourcesTest) {
  7271. static const char pShader[] =
  7272. "static ByteAddressBuffer g_rawBuf = ResourceDescriptorHeap[0];\n"
  7273. "static StructuredBuffer<float> g_structBuf = ResourceDescriptorHeap[1];\n"
  7274. "static Texture2D<float> g_tex = ResourceDescriptorHeap[2];\n"
  7275. "static RWByteAddressBuffer g_rwRawBuf = ResourceDescriptorHeap[3];\n"
  7276. "static RWStructuredBuffer<float> g_rwStructBuf = ResourceDescriptorHeap[4];\n"
  7277. "static RWBuffer<float> g_result = ResourceDescriptorHeap[5];\n"
  7278. "static RWTexture1D<float> g_rwTex = ResourceDescriptorHeap[6];\n"
  7279. "static SamplerState g_samp = SamplerDescriptorHeap[0];\n"
  7280. "static SamplerComparisonState g_sampCmp = SamplerDescriptorHeap[1];\n"
  7281. "[NumThreads(1, 1, 1)]\n"
  7282. "void main(uint ix : SV_GroupIndex) {\n"
  7283. " g_result[0] = g_rawBuf.Load<float>(0);\n"
  7284. " g_result[1] = g_structBuf.Load(0);\n"
  7285. " g_result[2] = g_tex.Load(0);\n"
  7286. " g_result[3] = g_rwRawBuf.Load<float>(0);\n"
  7287. " g_result[4] = g_rwStructBuf.Load(0);\n"
  7288. " g_result[5] = g_rwTex.Load(0);\n"
  7289. " g_result[6] = g_tex.SampleLevel(g_samp, -0.5, 0);\n"
  7290. " g_result[7] = g_tex.SampleCmpLevelZero(g_sampCmp, -0.5, 31.0);\n"
  7291. "}\n";
  7292. CComPtr<ID3D12Device> pDevice;
  7293. if (!CreateDevice(&pDevice, D3D_SHADER_MODEL_6_6))
  7294. return;
  7295. RunResourceTest(pDevice, pShader, L"cs_6_6", /*isDynamic*/true);
  7296. }
  7297. #define MAX_WAVESIZE 128
  7298. #define strinfigy2(arg) #arg
  7299. #define strinfigy(arg) strinfigy2(arg)
  7300. void ExecutionTest::WaveSizeTest() {
  7301. WEX::TestExecution::SetVerifyOutput verifySettings(WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  7302. CComPtr<ID3D12Device> pDevice;
  7303. if (!CreateDevice(&pDevice, D3D_SHADER_MODEL_6_6)) {
  7304. return;
  7305. }
  7306. // Check Wave support
  7307. if (!DoesDeviceSupportWaveOps(pDevice)) {
  7308. // Optional feature, so it's correct to not support it if declared as such.
  7309. WEX::Logging::Log::Comment(L"Device does not support wave operations.");
  7310. return;
  7311. }
  7312. // Get supported wave sizes
  7313. D3D12_FEATURE_DATA_D3D12_OPTIONS1 waveOpts;
  7314. VERIFY_SUCCEEDED(pDevice->CheckFeatureSupport((D3D12_FEATURE)D3D12_FEATURE_D3D12_OPTIONS1, &waveOpts, sizeof(waveOpts)));
  7315. UINT minWaveSize = waveOpts.WaveLaneCountMin;
  7316. UINT maxWaveSize = waveOpts.WaveLaneCountMax;
  7317. DXASSERT_NOMSG(minWaveSize <= maxWaveSize);
  7318. DXASSERT((minWaveSize & (minWaveSize - 1)) == 0, "must be a power of 2");
  7319. DXASSERT((maxWaveSize & (maxWaveSize - 1)) == 0, "must be a power of 2");
  7320. // read shader config
  7321. CComPtr<IStream> pStream;
  7322. std::shared_ptr<st::ShaderOpSet> ShaderOpSet = std::make_shared<st::ShaderOpSet>();
  7323. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  7324. st::ParseShaderOpSetFromStream(pStream, ShaderOpSet.get());
  7325. // format shader source
  7326. const char waveSizeTestShader[] =
  7327. "struct TestData { \r\n"
  7328. " uint count; \r\n"
  7329. "}; \r\n"
  7330. "RWStructuredBuffer<TestData> data : register(u0); \r\n"
  7331. "\r\n"
  7332. "// Note: WAVESIZE will be defined via compiler option -D\r\n"
  7333. "[wavesize(WAVESIZE)]\r\n"
  7334. "[numthreads(" strinfigy(MAX_WAVESIZE) "*2,1,1)]\r\n"
  7335. "void main(uint3 tid : SV_DispatchThreadID ) { \r\n"
  7336. " data[tid.x].count = WaveActiveSum(1); \r\n"
  7337. "}\r\n";
  7338. struct WaveSizeTestData {
  7339. uint32_t count;
  7340. };
  7341. for (UINT waveSize = minWaveSize; waveSize <= maxWaveSize; waveSize *= 2) {
  7342. // format compiler args
  7343. char compilerOptions[32];
  7344. VERIFY_IS_TRUE(sprintf_s(compilerOptions, sizeof(compilerOptions), "-D WAVESIZE=%d", waveSize) != -1);
  7345. // run the shader
  7346. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTestAfterParse(pDevice, m_support, "WaveSizeTest",
  7347. [&](LPCSTR Name, std::vector<BYTE> &Data, st::ShaderOp *pShaderOp) {
  7348. VERIFY_IS_TRUE((0 == strncmp(Name, "UAVBuffer0", 10)));
  7349. pShaderOp->Shaders.at(0).Arguments = compilerOptions;
  7350. pShaderOp->Shaders.at(0).Text = waveSizeTestShader;
  7351. VERIFY_IS_TRUE(sizeof(WaveSizeTestData)*MAX_WAVESIZE <= Data.size());
  7352. WaveSizeTestData *pInData = (WaveSizeTestData *)Data.data();
  7353. memset(&pInData, sizeof(WaveSizeTestData)*MAX_WAVESIZE, 0);
  7354. }, ShaderOpSet);
  7355. // verify expected values
  7356. MappedData dataUav;
  7357. WaveSizeTestData *pOutData;
  7358. test->Test->GetReadBackData("UAVBuffer0", &dataUav);
  7359. VERIFY_ARE_EQUAL(sizeof(WaveSizeTestData)*MAX_WAVESIZE, dataUav.size());
  7360. pOutData = (WaveSizeTestData*)dataUav.data();
  7361. LogCommentFmt(L"Verifying test result for wave size %d", waveSize);
  7362. for (unsigned i = 0; i < MAX_WAVESIZE; i++) {
  7363. if (!VERIFY_ARE_EQUAL(pOutData[i].count, waveSize))
  7364. break;
  7365. }
  7366. }
  7367. }
  7368. // Atomic operation testing
  7369. // Atomic tests take a single integer index as input and contort it into some
  7370. // kind of interesting contributor to the operation in question.
  7371. // So each vertex, pixel, thread, or other will have a unique index that produces
  7372. // a contributing value to the calculation which is stored in a small resource
  7373. // For arithmetic or bitwise operations, each contributor accumulates to the same
  7374. // location in the resource indexed by the operation type. Addition is in index 0
  7375. // umin/umax are in 1 and 2 and so on.
  7376. // To make sure that the most significant bits are involved in the calculation,
  7377. // particularly in the case of 64-bit values, each contributing value is duplicated
  7378. // to the lower and upper halves of the value. There is an exception to this when
  7379. // addition exceeds the available size and also for compare and exchange explained below.
  7380. // For compare and exchange operations, 64 output locations are shared by the various lanes.
  7381. // Each lane attempts to write to a location that is shared with several others.
  7382. // The first one to write to it determines its contents, which will be the lane index <ix>
  7383. // in the upper bits and the output location index in the lower bits.
  7384. // This ensures that the compare operations consider the upper bits in the comparison.
  7385. // The initial compare store is followed by a compare exchange that compares for the
  7386. // value the current lane would have assigned there. Finally, the output of the cmpxchg
  7387. // is used to determine if the current lane should perform the final unconditional exchange.
  7388. // The values are verified by checking the lower bits for the matching location index
  7389. // and ensuring that the upper bits undergoing the same transformation result in the location index.
  7390. // For lane index <ix> the location is calculated and final result assigned as if by this code:
  7391. // g_outputBuf[(ix/3)%64] = (ix << shBits) | ((ix/3)%64);
  7392. bool AtomicResultMatches(const BYTE *uResults, uint64_t gold, size_t size) {
  7393. if (memcmp(uResults, &gold, size)) {
  7394. if (size == 4)
  7395. LogCommentFmt(L" value %d is not %d", ((uint32_t*)uResults)[0], (uint32_t)gold);
  7396. else
  7397. LogCommentFmt(L" value %lld is not %lld", ((uint64_t*)uResults)[0], gold);
  7398. return false;
  7399. }
  7400. return true;
  7401. }
  7402. // Used to duplicate the lower half bits into the upper half bits of an integer
  7403. // To verify that the full value is being considered, many tests duplicate the results into the upper half
  7404. #define SHIFT(val, bits) (((val)&((1ULL<<(bits))-1ULL)) | ((val) << (bits)))
  7405. // Symbolic constants for the results
  7406. #define ADD_IDX 0
  7407. #define UMIN_IDX 1
  7408. #define UMAX_IDX 2
  7409. #define AND_IDX 3
  7410. #define OR_IDX 4
  7411. #define XOR_IDX 5
  7412. #define SMIN_IDX 0
  7413. #define SMAX_IDX 1
  7414. // Verify results for atomic operations. <uResults> and <sResults> are pointers to
  7415. // the readback resource sections containing unsigned and signed integers respectively.
  7416. // <pXchg> is a poiner to the readback resource containing the results of the compare
  7417. // and exchange operations tests. <stride> is the number of bytes between results for
  7418. // all of the results pointers. <maxIdx> is the number of indices that went into the results
  7419. // which is used to determine what the results should be. <bitSize> is the size in bits of
  7420. // the produced results, either 32 or 64.
  7421. void VerifyAtomicResults(const BYTE *uResults, const BYTE *sResults,
  7422. const BYTE *pXchg, size_t stride, size_t maxIdx, size_t bitSize) {
  7423. // Each atomic test performs the test on the value in the lower half
  7424. // and also duplicated in the upper half of the value. The SHIFT macros account for this.
  7425. // This is to verify that the upper bits are considered
  7426. size_t shBits = bitSize/2;
  7427. size_t byteSize = bitSize/8;
  7428. // Test ADD Operation
  7429. // ADD just sums all the indices. The result should the sum of the highest and lowest indices
  7430. // multiplied by half the number of sums.
  7431. size_t addResult = (maxIdx)*(maxIdx-1)/2;
  7432. LogCommentFmt(L"Verifying %d-bit integer atomic add", bitSize);
  7433. // For 32-bit values, the sum exceeds the 16 bit limit, so we can't duplicate
  7434. // That's fine, the duplication is really for 64-bit values.
  7435. if (bitSize < 64)
  7436. VERIFY_IS_TRUE(AtomicResultMatches(uResults + stride*ADD_IDX, addResult, byteSize));
  7437. else
  7438. VERIFY_IS_TRUE(AtomicResultMatches(uResults + stride*ADD_IDX, SHIFT(addResult, shBits), byteSize));
  7439. // Test MIN and MAX Operations
  7440. // The result of a simple min and max of any sequence of indices would be fairly uninteresting
  7441. // and certain erroneous behavior might mistakenly produce the correct results.
  7442. // To make it interesting, the contributing values will change depending on the evenness of the index.
  7443. // On an even index, min and max operate on the bitflipped index. For signed compares, this is
  7444. // interpretted as a negative value and for unsigned, a very high value.
  7445. // For unsigned min/max, index 0 will be bitflipped to ~0, which is interpretted as the maximum
  7446. // Because zero is manipulated, this leaves 1 as the lowest value.
  7447. LogCommentFmt(L"Verifying %d-bit integer atomic umin", bitSize);
  7448. VERIFY_IS_TRUE(AtomicResultMatches(uResults + stride*UMIN_IDX, SHIFT(1ULL, shBits), byteSize)); // UMin
  7449. LogCommentFmt(L"Verifying %d-bit integer atomic umax", bitSize);
  7450. VERIFY_IS_TRUE(AtomicResultMatches(uResults + stride*UMAX_IDX, ~0ULL, byteSize)); // UMax
  7451. // For signed min/max, the index just before the last will be bitflipped (maxIndex is always even).
  7452. // This is interpretted as -maxIndex and will be the lowest
  7453. // The maxIndex will be unaltered and interpretted as the highest.
  7454. LogCommentFmt(L"Verifying %d-bit integer atomic smin", bitSize);
  7455. VERIFY_IS_TRUE(AtomicResultMatches(sResults + stride*SMIN_IDX, SHIFT(-((int)maxIdx-1), shBits), byteSize)); // SMin
  7456. LogCommentFmt(L"Verifying %d-bit integer atomic smax", bitSize);
  7457. VERIFY_IS_TRUE(AtomicResultMatches(sResults + stride*SMAX_IDX, SHIFT(maxIdx-1, shBits), byteSize)); // SMax
  7458. // Test AND and OR operations.
  7459. // For AND operations, all indices are bitflipped and ANDed to the previous result.
  7460. // This means that the highest bits, which are never set by the contributing indices will be set
  7461. // for all the indices, so they will be set in the final result.
  7462. // For OR operations, the indices are ORed to the previous result unaltered
  7463. // This means that any bit that is set in any index will be set in the final OR result.
  7464. // In practice, this means that the cumulative result of the AND and OR operations
  7465. // are bitflipped versions of each other.
  7466. // Finding the most significant set bit by the max index or next power of two (pot)
  7467. // gives us the pivot point for these results
  7468. size_t nextPot = 1ULL << (bitSize - 1);
  7469. for (;nextPot && !((maxIdx-1) & (nextPot)); nextPot >>= 1) {}
  7470. nextPot <<= 1;
  7471. LogCommentFmt(L"Verifying %d-bit integer atomic and", bitSize);
  7472. VERIFY_IS_TRUE(AtomicResultMatches(uResults + stride*AND_IDX, ~SHIFT(nextPot-1, shBits), byteSize)); // And
  7473. LogCommentFmt(L"Verifying %d-bit integer atomic or", bitSize);
  7474. VERIFY_IS_TRUE(AtomicResultMatches(uResults + stride*OR_IDX, SHIFT(nextPot-1, shBits), byteSize)); // Or
  7475. // Test XOR operation
  7476. // For XOR operations, a 1 is shifted by the number of spaces equal to the index and XORed
  7477. // to the previous result. Because this would rapidely shift off the end of the value,
  7478. // giving undefined and uninteresting results, the index is moduloed to a value that will
  7479. // fit within the type size.
  7480. // Because many of the tests use total numbers of lanes that can be evenly divisible by 32 or 64,
  7481. // these values aren't used for the modulo since the expected result might be zero,
  7482. // which could be encountered through erroneous behavior.
  7483. // Instead, one less than the type size in bits is used for the modulo.
  7484. // Even though we don't know the actual order these operations are performed,
  7485. // indices that make up a contiguous sequence of 31 or 63 values can be thought of as one of a series of "passes".
  7486. // Each "pass" sets or clears the bits depending on what's already there.
  7487. // if the number of the pass is odd, the bits are being unset and all above the mod position should be set.
  7488. // If even, the bits are in the process of being set and bits below the mod position should be set.
  7489. size_t xorResult = ((1ULL<<((maxIdx)%(bitSize-1))) -1);
  7490. if (((maxIdx/(bitSize-1))&1)) {
  7491. xorResult ^= ~0ULL;
  7492. // The XOR above may set uninvolved upper bits, messing up the compare. So AND off the uninvolved bits.
  7493. xorResult &= ((1ULL<<(bitSize-1)) - 1);
  7494. }
  7495. LogCommentFmt(L"Verifying %d-bit integer atomic xor", bitSize);
  7496. VERIFY_IS_TRUE(AtomicResultMatches(uResults + stride*XOR_IDX, xorResult, byteSize));
  7497. // Test CMP/XCHG Operations
  7498. // This tests CompareStore, CompareExchange, and Exchange operations.
  7499. // Unlike above, every lane isn't contributing to the same resource location
  7500. // Instead, every lane competes with a few others to update the same resource location.
  7501. // The first lane to find the contents of their location uninitialized will
  7502. // update it. To verify that upper bits are considered in the comparison and
  7503. // in the assignment, the value stored in the lowest bits is the location index.
  7504. // This ensures that part will be the same for each of the competing lanes.
  7505. // The uppermost bits are updated with the index of the lane that got there first.
  7506. // Subsequent calls to CompareExchange will verify this value matches and alter
  7507. // the content slightly. Finally, a simple check of the output value to what
  7508. // the current lane would expect and a call to exchange will update the value once more
  7509. // To verify this has gone through properly, the upper portion is converted as
  7510. // if to calculate the location index and compared with the location index.
  7511. // It could be the index of any of several lanes that assign to that location,
  7512. // but this ensures that it is not any lane outside of that group.
  7513. // The lower bits are compared to the location index as well.
  7514. LogCommentFmt(L"Verifying %d-bit integer atomic cmp/xchg results", bitSize);
  7515. for (size_t i = 0; i < 64; i++) {
  7516. uint64_t val = *((uint64_t*)(pXchg + i*stride));
  7517. // Verify lower bits match location index exactly
  7518. VERIFY_ARE_EQUAL(i, val & ((1ULL << shBits) - 1ULL));
  7519. // Verify that upper bits contain original index that transforms to location index
  7520. VERIFY_ARE_EQUAL(((val >> shBits)/3)%64, i);
  7521. }
  7522. }
  7523. void VerifyAtomicsRawTest(std::shared_ptr<ShaderOpTestResult> test,
  7524. size_t maxIdx, size_t bitSize) {
  7525. size_t stride = 8;
  7526. // struct mirroring that in the shader
  7527. struct AtomicStuff {
  7528. float prepad[2][3];
  7529. UINT uintEl[4];
  7530. int sintEl[4];
  7531. struct useless {
  7532. uint32_t unused[3];
  7533. } postpad;
  7534. float last;
  7535. };
  7536. MappedData uintData, xchgData;
  7537. test->Test->GetReadBackData("U0", &uintData);
  7538. test->Test->GetReadBackData("U1", &xchgData);
  7539. const AtomicStuff *pStruct = (AtomicStuff *)uintData.data();
  7540. const AtomicStuff *pStrXchg = (AtomicStuff *)xchgData.data();
  7541. LogCommentFmt(L"Verifying %d-bit integer atomic operations on RWStructuredBuffer resource", bitSize);
  7542. VerifyAtomicResults((const BYTE*)&(pStruct[0].uintEl[2]), (const BYTE*)&(pStruct[1].sintEl[2]),
  7543. (const BYTE*)&(pStrXchg[0].uintEl[2]), sizeof(AtomicStuff), maxIdx, bitSize);
  7544. const BYTE *pUint = nullptr;
  7545. const BYTE *pXchg = nullptr;
  7546. test->Test->GetReadBackData("U2", &uintData);
  7547. test->Test->GetReadBackData("U3", &xchgData);
  7548. pUint = (BYTE *)uintData.data();
  7549. pXchg = (BYTE *)xchgData.data();
  7550. LogCommentFmt(L"Verifying %d-bit integer atomic operations on RWByteAddressBuffer resource", bitSize);
  7551. VerifyAtomicResults(pUint, pUint + stride*6,
  7552. pXchg, stride, maxIdx, bitSize);
  7553. }
  7554. void VerifyAtomicsTypedTest(std::shared_ptr<ShaderOpTestResult> test,
  7555. size_t maxIdx, size_t bitSize) {
  7556. size_t stride = 8;
  7557. MappedData uintData, sintData, xchgData;
  7558. const BYTE *pUint = nullptr;
  7559. const BYTE *pSint = nullptr;
  7560. const BYTE *pXchg = nullptr;
  7561. // Typed resources can't share between 32 and 64 bits
  7562. if (bitSize == 32) {
  7563. test->Test->GetReadBackData("U4", &uintData);
  7564. test->Test->GetReadBackData("U5", &sintData);
  7565. test->Test->GetReadBackData("U6", &xchgData);
  7566. } else {
  7567. test->Test->GetReadBackData("U12", &uintData);
  7568. test->Test->GetReadBackData("U13", &sintData);
  7569. test->Test->GetReadBackData("U14", &xchgData);
  7570. }
  7571. pUint = (BYTE *)uintData.data();
  7572. pSint = (BYTE *)sintData.data();
  7573. pXchg = (BYTE *)xchgData.data();
  7574. LogCommentFmt(L"Verifying %d-bit integer atomic operations on RWBuffer resource", bitSize);
  7575. VerifyAtomicResults(pUint, pSint + stride, pXchg, stride, maxIdx, bitSize);
  7576. // Typed resources can't share between 32 and 64 bits
  7577. if (bitSize == 32) {
  7578. test->Test->GetReadBackData("U7", &uintData);
  7579. test->Test->GetReadBackData("U8", &sintData);
  7580. test->Test->GetReadBackData("U9", &xchgData);
  7581. } else {
  7582. test->Test->GetReadBackData("U15", &uintData);
  7583. test->Test->GetReadBackData("U16", &sintData);
  7584. test->Test->GetReadBackData("U17", &xchgData);
  7585. }
  7586. pUint = (BYTE *)uintData.data();
  7587. pSint = (BYTE *)sintData.data();
  7588. pXchg = (BYTE *)xchgData.data();
  7589. LogCommentFmt(L"Verifying %d-bit integer atomic operations on RWTexture resource", bitSize);
  7590. VerifyAtomicResults(pUint, pSint + stride, pXchg, stride, maxIdx, bitSize);
  7591. }
  7592. void VerifyAtomicsSharedTest(std::shared_ptr<ShaderOpTestResult> test,
  7593. size_t maxIdx, size_t bitSize) {
  7594. size_t stride = 8;
  7595. MappedData uintData, xchgData;
  7596. const BYTE *pUint = nullptr;
  7597. const BYTE *pXchg = nullptr;
  7598. test->Test->GetReadBackData("U10", &uintData);
  7599. test->Test->GetReadBackData("U11", &xchgData);
  7600. pUint = (BYTE *)uintData.data();
  7601. pXchg = (BYTE *)xchgData.data();
  7602. LogCommentFmt(L"Verifying %d-bit integer atomic operations on groupshared variables", bitSize);
  7603. VerifyAtomicResults(pUint, pUint + stride*6,
  7604. pXchg, stride, maxIdx, bitSize);
  7605. }
  7606. void VerifyAtomicsTest(std::shared_ptr<ShaderOpTestResult> test,
  7607. size_t maxIdx, size_t bitSize) {
  7608. VerifyAtomicsRawTest(test, maxIdx, bitSize);
  7609. VerifyAtomicsTypedTest(test, maxIdx, bitSize);
  7610. }
  7611. TEST_F(ExecutionTest, AtomicsTest) {
  7612. WEX::TestExecution::SetVerifyOutput verifySettings(WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  7613. CComPtr<IStream> pStream;
  7614. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  7615. CComPtr<ID3D12Device> pDevice;
  7616. if (!CreateDevice(&pDevice))
  7617. return;
  7618. std::shared_ptr<st::ShaderOpSet> ShaderOpSet =
  7619. std::make_shared<st::ShaderOpSet>();
  7620. st::ParseShaderOpSetFromStream(pStream, ShaderOpSet.get());
  7621. st::ShaderOp *pShaderOp = ShaderOpSet->GetShaderOp("Atomics");
  7622. // Test compute shader
  7623. LogCommentFmt(L"Verifying 32-bit integer atomic operations in compute shader");
  7624. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTestAfterParse(pDevice, m_support, "Atomics", nullptr, ShaderOpSet);
  7625. VerifyAtomicsTest(test, 32*32, 32);
  7626. VerifyAtomicsSharedTest(test, 32*32, 32);
  7627. // Test mesh shader if available
  7628. pShaderOp->CS = nullptr;
  7629. if (DoesDeviceSupportMeshShaders(pDevice)) {
  7630. LogCommentFmt(L"Verifying 32-bit integer atomic operations in amp/mesh/pixel shaders");
  7631. test = RunShaderOpTestAfterParse(pDevice, m_support, "Atomics", nullptr, ShaderOpSet);
  7632. VerifyAtomicsTest(test, 8*8*2 + 8*8*2 + 64*64, 32);
  7633. VerifyAtomicsSharedTest(test, 8*8*2 + 8*8*2, 32);
  7634. }
  7635. // Test Vertex + Pixel shader
  7636. pShaderOp->MS = nullptr;
  7637. LogCommentFmt(L"Verifying 32-bit integer atomic operations in vert/pixel shaders");
  7638. test = RunShaderOpTestAfterParse(pDevice, m_support, "Atomics", nullptr, ShaderOpSet);
  7639. VerifyAtomicsTest(test, 64*64+6, 32);
  7640. }
  7641. TEST_F(ExecutionTest, Atomics64Test) {
  7642. WEX::TestExecution::SetVerifyOutput verifySettings(WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  7643. CComPtr<IStream> pStream;
  7644. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  7645. CComPtr<ID3D12Device> pDevice;
  7646. if (!CreateDevice(&pDevice, D3D_SHADER_MODEL_6_6))
  7647. return;
  7648. std::shared_ptr<st::ShaderOpSet> ShaderOpSet =
  7649. std::make_shared<st::ShaderOpSet>();
  7650. st::ParseShaderOpSetFromStream(pStream, ShaderOpSet.get());
  7651. st::ShaderOp *pShaderOp = ShaderOpSet->GetShaderOp("Atomics");
  7652. // Reassign shader stages to 64-bit versions
  7653. // Collect 64-bit shaders
  7654. LPCSTR CS64 = nullptr, VS64 = nullptr, PS64 = nullptr;
  7655. LPCSTR AS64 = nullptr, MS64 = nullptr;
  7656. for (st::ShaderOpShader &S : pShaderOp->Shaders) {
  7657. if (!strcmp(S.Name, "CS64")) CS64 = S.Name;
  7658. if (!strcmp(S.Name, "VS64")) VS64 = S.Name;
  7659. if (!strcmp(S.Name, "PS64")) PS64 = S.Name;
  7660. if (!strcmp(S.Name, "AS64")) AS64 = S.Name;
  7661. if (!strcmp(S.Name, "MS64")) MS64 = S.Name;
  7662. }
  7663. pShaderOp->CS = CS64;
  7664. pShaderOp->VS = VS64;
  7665. pShaderOp->PS = PS64;
  7666. pShaderOp->AS = AS64;
  7667. pShaderOp->MS = MS64;
  7668. // Test compute shader
  7669. LogCommentFmt(L"Verifying 64-bit integer atomic operations on raw buffers in compute shader");
  7670. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTestAfterParse(pDevice, m_support, "Atomics", nullptr, ShaderOpSet);
  7671. VerifyAtomicsRawTest(test, 32*32, 64);
  7672. // Test mesh shader if available
  7673. pShaderOp->CS = nullptr;
  7674. if (DoesDeviceSupportMeshShaders(pDevice)) {
  7675. LogCommentFmt(L"Verifying 64-bit integer atomic operations on raw buffers in amp/mesh/pixel shader");
  7676. test = RunShaderOpTestAfterParse(pDevice, m_support, "Atomics", nullptr, ShaderOpSet);
  7677. VerifyAtomicsRawTest(test, 8*8*2 + 8*8*2 + 64*64, 64);
  7678. }
  7679. // Test Vertex + Pixel shader
  7680. pShaderOp->MS = nullptr;
  7681. LogCommentFmt(L"Verifying 64-bit integer atomic operations on raw buffers in vert/pixel shader");
  7682. test = RunShaderOpTestAfterParse(pDevice, m_support, "Atomics", nullptr, ShaderOpSet);
  7683. VerifyAtomicsRawTest(test, 64*64+6, 64);
  7684. }
  7685. TEST_F(ExecutionTest, AtomicsTyped64Test) {
  7686. WEX::TestExecution::SetVerifyOutput verifySettings(WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  7687. CComPtr<IStream> pStream;
  7688. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  7689. CComPtr<ID3D12Device> pDevice;
  7690. if (!CreateDevice(&pDevice, D3D_SHADER_MODEL_6_6))
  7691. return;
  7692. if (!DoesDeviceSupportInt64(pDevice)) {
  7693. WEX::Logging::Log::Comment(L"Device does not support int64 operations.");
  7694. WEX::Logging::Log::Result(WEX::Logging::TestResults::Skipped);
  7695. return;
  7696. }
  7697. if (!DoesDeviceSupportTyped64Atomics(pDevice)) {
  7698. WEX::Logging::Log::Comment(L"Device does not support int64 atomic operations on typed resources.");
  7699. WEX::Logging::Log::Result(WEX::Logging::TestResults::Skipped);
  7700. return;
  7701. }
  7702. std::shared_ptr<st::ShaderOpSet> ShaderOpSet =
  7703. std::make_shared<st::ShaderOpSet>();
  7704. st::ParseShaderOpSetFromStream(pStream, ShaderOpSet.get());
  7705. st::ShaderOp *pShaderOp = ShaderOpSet->GetShaderOp("Atomics");
  7706. // Reassign shader stages to 64-bit versions
  7707. // Collect 64-bit shaders
  7708. LPCSTR CS64 = nullptr, VS64 = nullptr, PS64 = nullptr;
  7709. LPCSTR AS64 = nullptr, MS64 = nullptr;
  7710. for (st::ShaderOpShader &S : pShaderOp->Shaders) {
  7711. if (!strcmp(S.Name, "CSTY64")) CS64 = S.Name;
  7712. if (!strcmp(S.Name, "VSTY64")) VS64 = S.Name;
  7713. if (!strcmp(S.Name, "PSTY64")) PS64 = S.Name;
  7714. if (!strcmp(S.Name, "ASTY64")) AS64 = S.Name;
  7715. if (!strcmp(S.Name, "MSTY64")) MS64 = S.Name;
  7716. }
  7717. pShaderOp->CS = CS64;
  7718. pShaderOp->VS = VS64;
  7719. pShaderOp->PS = PS64;
  7720. pShaderOp->AS = AS64;
  7721. pShaderOp->MS = MS64;
  7722. // Test compute shader
  7723. LogCommentFmt(L"Verifying 64-bit integer atomic operations on typed resources in compute shader");
  7724. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTestAfterParse(pDevice, m_support, "Atomics", nullptr, ShaderOpSet);
  7725. VerifyAtomicsTypedTest(test, 32*32, 64);
  7726. // Test mesh shader if available
  7727. pShaderOp->CS = nullptr;
  7728. if (DoesDeviceSupportMeshShaders(pDevice)) {
  7729. LogCommentFmt(L"Verifying 64-bit integer atomic operations on typed resources in amp/mesh/pixel shader");
  7730. test = RunShaderOpTestAfterParse(pDevice, m_support, "Atomics", nullptr, ShaderOpSet);
  7731. VerifyAtomicsTypedTest(test, 8*8*2 + 8*8*2 + 64*64, 64);
  7732. }
  7733. // Test Vertex + Pixel shader
  7734. pShaderOp->MS = nullptr;
  7735. LogCommentFmt(L"Verifying 64-bit integer atomic operations on typed resources in vert/pixel shader");
  7736. test = RunShaderOpTestAfterParse(pDevice, m_support, "Atomics", nullptr, ShaderOpSet);
  7737. VerifyAtomicsTypedTest(test, 64*64+6, 64);
  7738. }
  7739. TEST_F(ExecutionTest, AtomicsShared64Test) {
  7740. WEX::TestExecution::SetVerifyOutput verifySettings(WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  7741. CComPtr<IStream> pStream;
  7742. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  7743. CComPtr<ID3D12Device> pDevice;
  7744. if (!CreateDevice(&pDevice, D3D_SHADER_MODEL_6_6))
  7745. return;
  7746. if (!DoesDeviceSupportInt64(pDevice)) {
  7747. WEX::Logging::Log::Comment(L"Device does not support int64 operations.");
  7748. WEX::Logging::Log::Result(WEX::Logging::TestResults::Skipped);
  7749. return;
  7750. }
  7751. if (!DoesDeviceSupportShared64Atomics(pDevice)) {
  7752. WEX::Logging::Log::Comment(L"Device does not support int64 atomic operations on groupshared variables.");
  7753. WEX::Logging::Log::Result(WEX::Logging::TestResults::Skipped);
  7754. return;
  7755. }
  7756. std::shared_ptr<st::ShaderOpSet> ShaderOpSet =
  7757. std::make_shared<st::ShaderOpSet>();
  7758. st::ParseShaderOpSetFromStream(pStream, ShaderOpSet.get());
  7759. st::ShaderOp *pShaderOp = ShaderOpSet->GetShaderOp("Atomics");
  7760. // Reassign shader stages to 64-bit versions
  7761. // Collect 64-bit shaders
  7762. LPCSTR CS64 = nullptr, PS64 = nullptr;
  7763. LPCSTR AS64 = nullptr, MS64 = nullptr;
  7764. for (st::ShaderOpShader &S : pShaderOp->Shaders) {
  7765. if (!strcmp(S.Name, "CSSH64")) CS64 = S.Name;
  7766. if (!strcmp(S.Name, "CSSH64")) CS64 = S.Name;
  7767. if (!strcmp(S.Name, "PS64")) PS64 = S.Name;
  7768. if (!strcmp(S.Name, "ASSH64")) AS64 = S.Name;
  7769. if (!strcmp(S.Name, "MSSH64")) MS64 = S.Name;
  7770. }
  7771. pShaderOp->CS = CS64;
  7772. pShaderOp->PS = PS64;
  7773. pShaderOp->AS = AS64;
  7774. pShaderOp->MS = MS64;
  7775. LogCommentFmt(L"Verifying 64-bit integer atomic operations on groupshared variables in compute shader");
  7776. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTestAfterParse(pDevice, m_support, "Atomics", nullptr, ShaderOpSet);
  7777. VerifyAtomicsSharedTest(test, 32*32, 64);
  7778. // Test mesh shader if available
  7779. pShaderOp->CS = nullptr;
  7780. if (DoesDeviceSupportMeshShaders(pDevice)) {
  7781. LogCommentFmt(L"Verifying 64-bit integer atomic operations on groupshared variables in amp/mesh/pixel shader");
  7782. test = RunShaderOpTestAfterParse(pDevice, m_support, "Atomics", nullptr, ShaderOpSet);
  7783. VerifyAtomicsSharedTest(test, 8*8*2 + 8*8*2, 64);
  7784. }
  7785. }
  7786. // Float Atomics
  7787. // These operations are almost the same as for the 32-bit and 64-bit integer tests
  7788. // The difference is that there is no need to verify the upper bits.
  7789. // So there is no storing of different parts in upper and lower halves.
  7790. // Additionally, the only operations that are supported on floats
  7791. // are compare and exchange operations. So that's all that is tested here.
  7792. // Just as above, a number of lanes are assigned the same output value.
  7793. // Unlike above, one location is needed for the result of the special NaN test
  7794. // For this reason, the conversion is reduced by one and shifted by one to leave
  7795. // the zero-indexed location available.
  7796. // Verify results for a particular set of atomics results
  7797. void VerifyAtomicFloatResults(const float *results) {
  7798. // The first entry is for NaN to ensure that compares between NaNs succeed
  7799. // The sentinal value is 0.123, for which this compare is sufficient.
  7800. VERIFY_IS_TRUE(results[0] >= 0.120 && results[0] < 0.125);
  7801. // Start at 1 because 0 is just for NaN tests
  7802. for (size_t i = 1; i < 64; i++) {
  7803. VERIFY_ARE_EQUAL((int(results[i])/3)%63 + 1, (int)i);
  7804. }
  7805. }
  7806. void VerifyAtomicsFloatSharedTest(std::shared_ptr<ShaderOpTestResult> test) {
  7807. MappedData Data;
  7808. const float *pData = nullptr;
  7809. test->Test->GetReadBackData("U4", &Data);
  7810. pData = (float *)Data.data();
  7811. LogCommentFmt(L"Verifying float cmp/xchg atomic operations on groupshared variables");
  7812. VerifyAtomicFloatResults(pData);
  7813. }
  7814. void VerifyAtomicsFloatTest(std::shared_ptr<ShaderOpTestResult> test) {
  7815. // struct mirroring that in the shader
  7816. struct AtomicStuff {
  7817. float prepad[2][3];
  7818. float fltEl[2];
  7819. struct useless {
  7820. uint32_t unused[3];
  7821. } postpad;
  7822. };
  7823. // Test Compute Shader
  7824. MappedData Data;
  7825. const float *pData = nullptr;
  7826. test->Test->GetReadBackData("U0", &Data);
  7827. const AtomicStuff *pStructData = (AtomicStuff *)Data.data();
  7828. LogCommentFmt(L"Verifying float cmp/xchg atomic operations on RWStructuredBuffer resources");
  7829. VERIFY_IS_TRUE(pStructData[0].fltEl[1] >= 0.120 && pStructData[0].fltEl[1] < 0.125);
  7830. for (size_t i = 1; i < 64; i++) {
  7831. VERIFY_ARE_EQUAL((int(pStructData[i].fltEl[1])/3)%63 + 1, (int)i);
  7832. }
  7833. test->Test->GetReadBackData("U1", &Data);
  7834. pData = (float *)Data.data();
  7835. LogCommentFmt(L"Verifying float cmp/xchg atomic operations on RWByteAddressBuffer resources");
  7836. VerifyAtomicFloatResults(pData);
  7837. test->Test->GetReadBackData("U2", &Data);
  7838. pData = (float *)Data.data();
  7839. LogCommentFmt(L"Verifying float cmp/xchg atomic operations on RWBuffer resources");
  7840. VerifyAtomicFloatResults(pData);
  7841. test->Test->GetReadBackData("U3", &Data);
  7842. pData = (float *)Data.data();
  7843. LogCommentFmt(L"Verifying float cmp/xchg atomic operations on RWTexture resources");
  7844. VerifyAtomicFloatResults(pData);
  7845. }
  7846. TEST_F(ExecutionTest, AtomicsFloatTest) {
  7847. WEX::TestExecution::SetVerifyOutput verifySettings(WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  7848. CComPtr<IStream> pStream;
  7849. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  7850. CComPtr<ID3D12Device> pDevice;
  7851. if (!CreateDevice(&pDevice))
  7852. return;
  7853. std::shared_ptr<st::ShaderOpSet> ShaderOpSet =
  7854. std::make_shared<st::ShaderOpSet>();
  7855. st::ParseShaderOpSetFromStream(pStream, ShaderOpSet.get());
  7856. st::ShaderOp *pShaderOp = ShaderOpSet->GetShaderOp("FloatAtomics");
  7857. // Test compute shader
  7858. LogCommentFmt(L"Verifying float cmp/xchg atomic operations in compute shader");
  7859. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTestAfterParse(pDevice, m_support, "FloatAtomics", nullptr, ShaderOpSet);
  7860. VerifyAtomicsFloatTest(test);
  7861. VerifyAtomicsFloatSharedTest(test);
  7862. // Test mesh shader if available
  7863. pShaderOp->CS = nullptr;
  7864. if (DoesDeviceSupportMeshShaders(pDevice)) {
  7865. LogCommentFmt(L"Verifying float cmp/xchg atomic operations in amp/mesh/pixel shaders");
  7866. test = RunShaderOpTestAfterParse(pDevice, m_support, "FloatAtomics", nullptr, ShaderOpSet);
  7867. VerifyAtomicsFloatTest(test);
  7868. VerifyAtomicsFloatSharedTest(test);
  7869. }
  7870. // Test Vertex + Pixel shader
  7871. pShaderOp->MS = nullptr;
  7872. LogCommentFmt(L"Verifying float cmp/xchg atomic operations in vert/pixel shaders");
  7873. test = RunShaderOpTestAfterParse(pDevice, m_support, "FloatAtomics", nullptr, ShaderOpSet);
  7874. VerifyAtomicsFloatTest(test);
  7875. }
  7876. // The IsHelperLane test renders 3-pixel triangle into 16x16 render target restricted
  7877. // to 2x2 viewport alligned at (0,0) which guarantees it will run in a single quad.
  7878. //
  7879. // Pixels to be rendered*
  7880. // (0,0)* (0,1)*
  7881. // (1,0) (1,1)*
  7882. //
  7883. // Pixel (1,0) is not rendered and is in helper lane.
  7884. //
  7885. // Each thread will use ddx_fine and ddy_fine to read the IsHelperLane() values from other threads.
  7886. // The bottom right pixel will write the results into the UAV buffer.
  7887. //
  7888. // Then the top level pixel (0,0) is discarded and the process above is repeated.
  7889. //
  7890. // Runs with shader models 6.0 and 6.6 to test both the HLSL built-in IsHelperLane fallback
  7891. // function (sm <= 6.5) and the IsHelperLane intrisics (sm >= 6.6).
  7892. //
  7893. TEST_F(ExecutionTest, HelperLaneTest) {
  7894. WEX::TestExecution::SetVerifyOutput verifySettings(WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  7895. CComPtr<IStream> pStream;
  7896. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  7897. std::shared_ptr<st::ShaderOpSet> ShaderOpSet = std::make_shared<st::ShaderOpSet>();
  7898. st::ParseShaderOpSetFromStream(pStream, ShaderOpSet.get());
  7899. #ifdef ISHELPERLANE_PLACEHOLDER
  7900. string args = "-DISHELPERLANE_PLACEHOLDER";
  7901. #else
  7902. string args = "";
  7903. #endif
  7904. D3D_SHADER_MODEL TestShaderModels[] = { D3D_SHADER_MODEL_6_0, D3D_SHADER_MODEL_6_6 };
  7905. for (unsigned i = 0; i < _countof(TestShaderModels); i++) {
  7906. D3D_SHADER_MODEL sm = TestShaderModels[i];
  7907. LogCommentFmt(L"Verifying IsHelperLane in shader model 6.%1u", ((UINT)sm & 0x0f));
  7908. CComPtr<ID3D12Device> pDevice;
  7909. if (!CreateDevice(&pDevice, sm, false /* skipUnsupported */))
  7910. continue;
  7911. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTestAfterParse(pDevice, m_support, "HelperLaneTestNoWave",
  7912. // this callbacked is called when the test is creating the resource to run the test
  7913. [&](LPCSTR Name, std::vector<BYTE>& Data, st::ShaderOp* pShaderOp) {
  7914. VERIFY_IS_TRUE(0 == _stricmp(Name, "UAVBuffer0"));
  7915. std::fill(Data.begin(), Data.end(), (BYTE)0xCC);
  7916. pShaderOp->Shaders.at(0).Arguments = args.c_str();
  7917. pShaderOp->Shaders.at(1).Arguments = args.c_str();
  7918. }, ShaderOpSet);
  7919. struct HelperLaneTestResult {
  7920. int32_t is_helper_00;
  7921. int32_t is_helper_10;
  7922. int32_t is_helper_01;
  7923. int32_t is_helper_11;
  7924. };
  7925. MappedData uavData;
  7926. test->Test->GetReadBackData("UAVBuffer0", &uavData);
  7927. HelperLaneTestResult* pTestResults = (HelperLaneTestResult*)uavData.data();
  7928. MappedData renderData;
  7929. test->Test->GetReadBackData("RTarget", &renderData);
  7930. const uint32_t* pPixels = (uint32_t*)renderData.data();
  7931. // before discard
  7932. VERIFY_ARE_EQUAL(pTestResults[0].is_helper_00, 0);
  7933. VERIFY_ARE_EQUAL(pTestResults[0].is_helper_10, 0);
  7934. VERIFY_ARE_EQUAL(pTestResults[0].is_helper_01, 1);
  7935. VERIFY_ARE_EQUAL(pTestResults[0].is_helper_11, 0);
  7936. // after discard
  7937. VERIFY_ARE_EQUAL(pTestResults[1].is_helper_00, 1);
  7938. VERIFY_ARE_EQUAL(pTestResults[1].is_helper_10, 0);
  7939. VERIFY_ARE_EQUAL(pTestResults[1].is_helper_01, 1);
  7940. VERIFY_ARE_EQUAL(pTestResults[1].is_helper_11, 0);
  7941. UNREFERENCED_PARAMETER(pPixels);
  7942. }
  7943. }
  7944. struct HelperLaneWaveTestResult60 {
  7945. // 6.0 wave ops
  7946. int32_t anyTrue;
  7947. int32_t allTrue;
  7948. XMUINT4 ballot;
  7949. int32_t waterfallLoopCount;
  7950. int32_t allEqual;
  7951. int32_t countBits;
  7952. int32_t sum;
  7953. int32_t product;
  7954. int32_t bitAnd;
  7955. int32_t bitOr;
  7956. int32_t bitXor;
  7957. int32_t min;
  7958. int32_t max;
  7959. int32_t prefixCountBits;
  7960. int32_t prefixProduct;
  7961. int32_t prefixSum;
  7962. };
  7963. struct HelperLaneQuadTestResult {
  7964. int32_t is_helper_this;
  7965. int32_t is_helper_across_X;
  7966. int32_t is_helper_across_Y;
  7967. int32_t is_helper_across_Diag;
  7968. };
  7969. struct HelperLaneWaveTestResult65 {
  7970. // 6.5 wave ops
  7971. XMUINT4 match;
  7972. int32_t mpCountBits;
  7973. int32_t mpSum;
  7974. int32_t mpProduct;
  7975. int32_t mpBitAnd;
  7976. int32_t mpBitOr;
  7977. int32_t mpBitXor;
  7978. };
  7979. struct HelperLaneWaveTestResult {
  7980. HelperLaneWaveTestResult60 sm60;
  7981. HelperLaneQuadTestResult sm60_quad;
  7982. HelperLaneWaveTestResult65 sm65;
  7983. };
  7984. struct foo { int32_t a; int32_t b; int32_t c; };
  7985. struct bar { foo f; int32_t d; XMUINT4 g; };
  7986. foo f = {1, 2, 3};
  7987. bar b = { { 1, 2, 3 }, 0, { 1, 2, 3, 4 } };
  7988. HelperLaneWaveTestResult HelperLane_CS_ExpectedResults = {
  7989. // HelperLaneWaveTestResult60
  7990. { 0, 1, { 0x7, 0, 0, 0 }, 3, 1, 3, 12, 64, 1, 0, 0, 10, 1, 2, 16, 4 },
  7991. // HelperLaneQuadTestResult
  7992. { 0, 0, 0, 0 },
  7993. // HelperLaneWaveTestResult65
  7994. { {0x7, 0, 0, 0}, 2, 4, 16, 1, 0, 0 }
  7995. };
  7996. HelperLaneWaveTestResult HelperLane_VS_ExpectedResults = HelperLane_CS_ExpectedResults;
  7997. HelperLaneWaveTestResult HelperLane_PS_ExpectedResults = {
  7998. // HelperLaneWaveTestResult60
  7999. { 0, 1, { 0xB, 0, 0, 0 }, 3, 1, 3, 12, 64, 1, 0, 0, 10, 1, 2, 16, 4 },
  8000. // HelperLaneQuadTestResult
  8001. { 0, 1, 0, 0 },
  8002. // HelperLaneWaveTestResult65
  8003. { {0xB, 0, 0, 0}, 2, 4, 16, 1, 0, 0 }
  8004. };
  8005. HelperLaneWaveTestResult HelperLane_PSAfterDiscard_ExpectedResults = {
  8006. // HelperLaneWaveTestResult60
  8007. { 0, 1, { 0xA, 0, 0, 0 }, 2, 1, 2, 8, 16, 1, 0, 0, 10, 1, 1, 4, 2 },
  8008. // HelperLaneQuadTestResult
  8009. { 0, 1, 0, 1 },
  8010. // HelperLaneWaveTestResult65
  8011. { {0xA, 0, 0, 0}, 1, 2, 4, 1, 0, 0 }
  8012. };
  8013. bool HelperLaneResultLogAndVerify(const wchar_t* testDesc, uint32_t expectedValue, uint32_t actualValue) {
  8014. bool matches = (expectedValue == actualValue);
  8015. LogCommentFmt(L"%s%s, expected = %u, actual = %u", matches ? L" - " : L"FAILED: ", testDesc, expectedValue, actualValue);
  8016. return matches;
  8017. }
  8018. bool HelperLaneResultLogAndVerify(const wchar_t* testDesc, XMUINT4 expectedValue, XMUINT4 actualValue) {
  8019. bool matches = (expectedValue.x == actualValue.x && expectedValue.y == actualValue.y &&
  8020. expectedValue.z == actualValue.z && expectedValue.w == actualValue.w);
  8021. LogCommentFmt(L"%s%s, expected = (0x%X,0x%X,0x%X,0x%X), actual = (0x%X,0x%X,0x%X,0x%X)", matches ? L" - " : L"FAILED: ", testDesc,
  8022. expectedValue.x, expectedValue.y, expectedValue.z, expectedValue.w, actualValue.x, actualValue.y, actualValue.z, actualValue.w);
  8023. return matches;
  8024. }
  8025. bool VerifyHelperLaneWaveResults(ExecutionTest::D3D_SHADER_MODEL sm, HelperLaneWaveTestResult& testResults, HelperLaneWaveTestResult& expectedResults, bool verifyQuads) {
  8026. bool passed = true;
  8027. {
  8028. HelperLaneWaveTestResult60& tr60 = testResults.sm60;
  8029. HelperLaneWaveTestResult60& tr60exp = expectedResults.sm60;
  8030. passed &= HelperLaneResultLogAndVerify(L"WaveActiveAnyTrue(IsHelperLane())", tr60exp.anyTrue, tr60.anyTrue);
  8031. passed &= HelperLaneResultLogAndVerify(L"WaveActiveAllTrue(!IsHelperLane())", tr60exp.allTrue, tr60.allTrue);
  8032. passed &= HelperLaneResultLogAndVerify(L"WaveActiveBallot(true) has exactly 3 bits set", tr60exp.ballot, tr60.ballot);
  8033. passed &= HelperLaneResultLogAndVerify(L"!WaveReadLaneFirst(IsHelperLane()) && WaveIsFirstLane() in a waterfall loop", tr60exp.waterfallLoopCount, tr60.waterfallLoopCount);
  8034. passed &= HelperLaneResultLogAndVerify(L"WaveActiveAllEqual(IsHelperLane())", tr60exp.allEqual, tr60.allEqual);
  8035. passed &= HelperLaneResultLogAndVerify(L"WaveActiveCountBits(true)", tr60exp.countBits, tr60.countBits);
  8036. passed &= HelperLaneResultLogAndVerify(L"WaveActiveSum(4)", tr60exp.sum, tr60.sum);
  8037. passed &= HelperLaneResultLogAndVerify(L"WaveActiveProduct(4)", tr60exp.product, tr60.product);
  8038. passed &= HelperLaneResultLogAndVerify(L"WaveActiveBitAnd(!IsHelperLane())", tr60exp.bitAnd, tr60.bitAnd);
  8039. passed &= HelperLaneResultLogAndVerify(L"WaveActiveBitOr(IsHelperLane())", tr60exp.bitOr, tr60.bitOr);
  8040. passed &= HelperLaneResultLogAndVerify(L"WaveActiveBitXor(IsHelperLane())", tr60exp.bitXor, tr60.bitXor);
  8041. passed &= HelperLaneResultLogAndVerify(L"WaveActiveMin(IsHelperLane() ? 1 : 10)", tr60exp.min, tr60.min);
  8042. passed &= HelperLaneResultLogAndVerify(L"WaveActiveMax(IsHelperLane() ? 10 : 1)", tr60exp.max, tr60.max);
  8043. passed &= HelperLaneResultLogAndVerify(L"WavePrefixCountBits(1)", tr60exp.prefixCountBits, tr60.prefixCountBits);
  8044. passed &= HelperLaneResultLogAndVerify(L"WavePrefixProduct(4)", tr60exp.prefixProduct, tr60.prefixProduct);
  8045. passed &= HelperLaneResultLogAndVerify(L"WavePrefixSum(2)", tr60exp.prefixSum, tr60.prefixSum);
  8046. }
  8047. if (verifyQuads) {
  8048. HelperLaneQuadTestResult& quad_tr = testResults.sm60_quad;
  8049. HelperLaneQuadTestResult& quad_tr_exp = expectedResults.sm60_quad;
  8050. passed &= HelperLaneResultLogAndVerify(L"QuadReadAcross* - lane 3 / pixel (1,1) - IsHelperLane()", quad_tr_exp.is_helper_this, quad_tr.is_helper_this);
  8051. passed &= HelperLaneResultLogAndVerify(L"QuadReadAcross* - lane 2 / pixel (0,1) - IsHelperLane()", quad_tr_exp.is_helper_across_X, quad_tr.is_helper_across_X);
  8052. passed &= HelperLaneResultLogAndVerify(L"QuadReadAcross* - lane 1 / pixel (1,0) - IsHelperLane()", quad_tr_exp.is_helper_across_Y, quad_tr.is_helper_across_Y);
  8053. passed &= HelperLaneResultLogAndVerify(L"QuadReadAcross* - lane 0 / pixel (0,0) - IsHelperLane()", quad_tr_exp.is_helper_across_Diag, quad_tr.is_helper_across_Diag);
  8054. }
  8055. if (sm >= D3D_SHADER_MODEL_6_5) {
  8056. HelperLaneWaveTestResult65& tr65 = testResults.sm65;
  8057. HelperLaneWaveTestResult65& tr65exp = expectedResults.sm65;
  8058. passed &= HelperLaneResultLogAndVerify(L"WaveMatch(true) has exactly 3 bits set", tr65exp.match, tr65.match);
  8059. passed &= HelperLaneResultLogAndVerify(L"WaveMultiPrefixCountBits(1, no_masked_bits)", tr65exp.mpCountBits, tr65.mpCountBits);
  8060. passed &= HelperLaneResultLogAndVerify(L"WaveMultiPrefixSum(2, no_masked_bits)", tr65exp.mpSum, tr65.mpSum);
  8061. passed &= HelperLaneResultLogAndVerify(L"WaveMultiPrefixProduct(4, no_masked_bits)", tr65exp.mpProduct, tr65.mpProduct);
  8062. passed &= HelperLaneResultLogAndVerify(L"WaveMultiPrefixAnd(IsHelperLane() ? 0 : 1, no_masked_bits)", tr65exp.mpBitAnd, tr65.mpBitAnd);
  8063. passed &= HelperLaneResultLogAndVerify(L"WaveMultiPrefixOr(IsHelperLane() ? 1 : 0, no_masked_bits)", tr65exp.mpBitOr, tr65.mpBitOr);
  8064. passed &= HelperLaneResultLogAndVerify(L"verify WaveMultiPrefixXor(IsHelperLane() ? 1 : 0, no_masked_bits)", tr65exp.mpBitXor, tr65.mpBitXor);
  8065. }
  8066. return passed;
  8067. }
  8068. void CleanUAVBuffer0Buffer(LPCSTR BufferName, std::vector<BYTE>& Data, st::ShaderOp* pShaderOp) {
  8069. UNREFERENCED_PARAMETER(pShaderOp);
  8070. VERIFY_IS_TRUE(0 == _stricmp(BufferName, "UAVBuffer0"));
  8071. std::fill(Data.begin(), Data.end(), (BYTE)0xCC);
  8072. }
  8073. //
  8074. // The IsHelperLane test that use Wave intrinsics to verify IsHelperLane() and Wave operations on active lanes.
  8075. //
  8076. // Runs with shader models 6.0, 6.5 and 6.6 to test both the HLSL built-in IsHelperLane fallback
  8077. // function (sm <= 6.5) and the IsHelperLane intrisics (sm >= 6.6) and the shader model 6.5 wave intrinsics (sm >= 6.5).
  8078. //
  8079. // For compute and vertex shaders IsHelperLane() always returns false and might be optimized away in the front end.
  8080. // However it can be exposed to the driver in CS/VS through an exported function in a library so drivers need
  8081. // to be prepared to handle it. For this reason the test is compiled with disabled optimizations (/Od).
  8082. // The tests are also validating that wave intrinsics operate correctly with 3 threads in a CS or 3 vertices
  8083. // in a VS where the rest of the lanes in the wave are not active (dead lanes).
  8084. //
  8085. TEST_F(ExecutionTest, HelperLaneTestWave) {
  8086. WEX::TestExecution::SetVerifyOutput verifySettings(WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  8087. CComPtr<IStream> pStream;
  8088. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  8089. std::shared_ptr<st::ShaderOpSet> ShaderOpSet = std::make_shared<st::ShaderOpSet>();
  8090. st::ParseShaderOpSetFromStream(pStream, ShaderOpSet.get());
  8091. st::ShaderOp* pShaderOp = ShaderOpSet->GetShaderOp("HelperLaneTestWave");
  8092. #ifdef ISHELPERLANE_PLACEHOLDER
  8093. LPCSTR args = "/Od -DISHELPERLANE_PLACEHOLDER";
  8094. #else
  8095. LPCSTR args = "/Od";
  8096. #endif
  8097. if (args[0]) {
  8098. for (st::ShaderOpShader& S : pShaderOp->Shaders)
  8099. S.Arguments = args;
  8100. }
  8101. bool testPassed = true;
  8102. D3D_SHADER_MODEL TestShaderModels[] = { D3D_SHADER_MODEL_6_0, D3D_SHADER_MODEL_6_5, D3D_SHADER_MODEL_6_6 };
  8103. for (unsigned i = 0; i < _countof(TestShaderModels); i++) {
  8104. D3D_SHADER_MODEL sm = TestShaderModels[i];
  8105. LogCommentFmt(L"\r\nVerifying IsHelperLane using Wave intrinsics in shader model 6.%1u", ((UINT)sm & 0x0f));
  8106. bool smPassed = true;
  8107. CComPtr<ID3D12Device> pDevice;
  8108. if (!CreateDevice(&pDevice, sm, false /* skipUnsupported */)) {
  8109. continue;
  8110. }
  8111. if (!DoesDeviceSupportWaveOps(pDevice)) {
  8112. LogCommentFmt(L"Device does not support wave operations in shader model 6.%1u", ((UINT)sm & 0x0f));
  8113. continue;
  8114. }
  8115. if (sm >= D3D_SHADER_MODEL_6_5) {
  8116. // Reassign shader stages to 6.5 versions
  8117. LPCSTR CS65 = nullptr, VS65 = nullptr, PS65 = nullptr;
  8118. for (st::ShaderOpShader& S : pShaderOp->Shaders) {
  8119. if (!strcmp(S.Name, "CS65")) CS65 = S.Name;
  8120. if (!strcmp(S.Name, "VS65")) VS65 = S.Name;
  8121. if (!strcmp(S.Name, "PS65")) PS65 = S.Name;
  8122. }
  8123. pShaderOp->CS = CS65;
  8124. pShaderOp->VS = VS65;
  8125. pShaderOp->PS = PS65;
  8126. }
  8127. const unsigned CS_INDEX = 0, VS_INDEX = 0, PS_INDEX = 1, PS_INDEX_AFTER_DISCARD = 2;
  8128. // Test Compute shader
  8129. {
  8130. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTestAfterParse(pDevice, m_support, "HelperLaneTestWave",
  8131. CleanUAVBuffer0Buffer, ShaderOpSet);
  8132. MappedData uavData;
  8133. test->Test->GetReadBackData("UAVBuffer0", &uavData);
  8134. HelperLaneWaveTestResult* pTestResults = (HelperLaneWaveTestResult*)uavData.data();
  8135. LogCommentFmt(L"\r\nCompute shader");
  8136. smPassed &= VerifyHelperLaneWaveResults(sm, pTestResults[CS_INDEX], HelperLane_CS_ExpectedResults, true);
  8137. }
  8138. // Test Vertex + Pixel shader
  8139. {
  8140. pShaderOp->CS = nullptr;
  8141. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTestAfterParse(pDevice, m_support, "HelperLaneTestWave", CleanUAVBuffer0Buffer, ShaderOpSet);
  8142. MappedData uavData;
  8143. test->Test->GetReadBackData("UAVBuffer0", &uavData);
  8144. HelperLaneWaveTestResult* pTestResults = (HelperLaneWaveTestResult*)uavData.data();
  8145. LogCommentFmt(L"\r\nVertex shader");
  8146. smPassed &= VerifyHelperLaneWaveResults(sm, pTestResults[VS_INDEX], HelperLane_VS_ExpectedResults, false);
  8147. LogCommentFmt(L"\r\nPixel shader");
  8148. smPassed &= VerifyHelperLaneWaveResults(sm, pTestResults[PS_INDEX], HelperLane_PS_ExpectedResults, true);
  8149. LogCommentFmt(L"\r\nPixel shader with discarded pixel");
  8150. smPassed &= VerifyHelperLaneWaveResults(sm, pTestResults[PS_INDEX_AFTER_DISCARD], HelperLane_PSAfterDiscard_ExpectedResults, true);
  8151. MappedData renderData;
  8152. test->Test->GetReadBackData("RTarget", &renderData);
  8153. const uint32_t* pPixels = (uint32_t*)renderData.data();
  8154. UNREFERENCED_PARAMETER(pPixels);
  8155. }
  8156. testPassed &= smPassed;
  8157. }
  8158. VERIFY_ARE_EQUAL(testPassed, true);
  8159. }
  8160. #ifndef _HLK_CONF
  8161. static void WriteReadBackDump(st::ShaderOp *pShaderOp, st::ShaderOpTest *pTest,
  8162. char **pReadBackDump) {
  8163. std::stringstream str;
  8164. unsigned count = 0;
  8165. for (auto &R : pShaderOp->Resources) {
  8166. if (!R.ReadBack)
  8167. continue;
  8168. ++count;
  8169. str << "Resource: " << R.Name << "\r\n";
  8170. // Find a descriptor that can tell us how to dump this resource.
  8171. bool found = false;
  8172. for (auto &Heaps : pShaderOp->DescriptorHeaps) {
  8173. for (auto &D : Heaps.Descriptors) {
  8174. if (_stricmp(D.ResName, R.Name) != 0) {
  8175. continue;
  8176. }
  8177. found = true;
  8178. if (_stricmp(D.Kind, "UAV") != 0) {
  8179. str << "Resource dump for kind " << D.Kind << " not implemented yet.\r\n";
  8180. break;
  8181. }
  8182. if (D.UavDesc.ViewDimension != D3D12_UAV_DIMENSION_BUFFER) {
  8183. str << "Resource dump for this kind of view dimension not implemented yet.\r\n";
  8184. break;
  8185. }
  8186. // We can map back to the structure if a structured buffer via the shader, but
  8187. // we'll keep this simple and simply dump out 32-bit uint/float representations.
  8188. MappedData data;
  8189. pTest->GetReadBackData(R.Name, &data);
  8190. uint32_t *pData = (uint32_t *)data.data();
  8191. size_t u32_count = ((size_t)R.Desc.Width) / sizeof(uint32_t);
  8192. for (size_t i = 0; i < u32_count; ++i) {
  8193. float f = *(float *)pData;
  8194. str << i << ": 0n" << *pData << " 0x" << std::hex << *pData
  8195. << std::dec << " " << f << "\r\n";
  8196. ++pData;
  8197. }
  8198. break;
  8199. }
  8200. if (found) break;
  8201. }
  8202. if (!found) {
  8203. str << "Unable to find a view for the resource.\r\n";
  8204. }
  8205. }
  8206. str << "Resources read back: " << count << "\r\n";
  8207. std::string s(str.str());
  8208. CComHeapPtr<char> pDump;
  8209. if (!pDump.Allocate(s.size() + 1))
  8210. throw std::bad_alloc();
  8211. memcpy(pDump.m_pData, s.data(), s.size());
  8212. pDump.m_pData[s.size()] = '\0';
  8213. *pReadBackDump = pDump.Detach();
  8214. }
  8215. // This is the exported interface by use from HLSLHost.exe.
  8216. // It's exclusive with the use of the DLL as a TAEF target.
  8217. extern "C" {
  8218. __declspec(dllexport) HRESULT WINAPI InitializeOpTests(void *pStrCtx, st::OutputStringFn pOutputStrFn) {
  8219. HRESULT hr = EnableExperimentalShaderModels();
  8220. if (FAILED(hr)) {
  8221. pOutputStrFn(pStrCtx, L"Unable to enable experimental shader models.\r\n.");
  8222. }
  8223. return S_OK;
  8224. }
  8225. __declspec(dllexport) HRESULT WINAPI
  8226. RunOpTest(void *pStrCtx, st::OutputStringFn pOutputStrFn, LPCSTR pText,
  8227. ID3D12Device *pDevice, ID3D12CommandQueue *pCommandQueue,
  8228. ID3D12Resource *pRenderTarget, char **pReadBackDump) {
  8229. HRESULT hr;
  8230. if (pReadBackDump) *pReadBackDump = nullptr;
  8231. st::SetOutputFn(pStrCtx, pOutputStrFn);
  8232. CComPtr<ID3D12InfoQueue> pInfoQueue;
  8233. CComHeapPtr<char> pDump;
  8234. bool FilterCreation = false;
  8235. if (SUCCEEDED(pDevice->QueryInterface(&pInfoQueue))) {
  8236. // Creation is largely driven by inputs, so don't log create/destroy messages.
  8237. pInfoQueue->PushEmptyStorageFilter();
  8238. pInfoQueue->PushEmptyRetrievalFilter();
  8239. if (FilterCreation) {
  8240. D3D12_INFO_QUEUE_FILTER filter;
  8241. D3D12_MESSAGE_CATEGORY denyCategories[] = { D3D12_MESSAGE_CATEGORY_STATE_CREATION };
  8242. ZeroMemory(&filter, sizeof(filter));
  8243. filter.DenyList.NumCategories = _countof(denyCategories);
  8244. filter.DenyList.pCategoryList = denyCategories;
  8245. pInfoQueue->PushStorageFilter(&filter);
  8246. }
  8247. }
  8248. else {
  8249. pOutputStrFn(pStrCtx, L"Unable to enable info queue for D3D.\r\n.");
  8250. }
  8251. try {
  8252. dxc::DxcDllSupport m_support;
  8253. m_support.Initialize();
  8254. const char *pName = nullptr;
  8255. CComPtr<IStream> pStream = SHCreateMemStream((BYTE *)pText, (UINT)strlen(pText));
  8256. std::shared_ptr<st::ShaderOpSet> ShaderOpSet =
  8257. std::make_shared<st::ShaderOpSet>();
  8258. st::ParseShaderOpSetFromStream(pStream, ShaderOpSet.get());
  8259. st::ShaderOp *pShaderOp;
  8260. if (pName == nullptr) {
  8261. if (ShaderOpSet->ShaderOps.size() != 1) {
  8262. pOutputStrFn(pStrCtx, L"Expected a single shader operation.\r\n");
  8263. return E_FAIL;
  8264. }
  8265. pShaderOp = ShaderOpSet->ShaderOps[0].get();
  8266. }
  8267. else {
  8268. pShaderOp = ShaderOpSet->GetShaderOp(pName);
  8269. }
  8270. if (pShaderOp == nullptr) {
  8271. std::string msg = "Unable to find shader op ";
  8272. msg += pName;
  8273. msg += "; available ops";
  8274. const char sep = ':';
  8275. for (auto &pAvailOp : ShaderOpSet->ShaderOps) {
  8276. msg += sep;
  8277. msg += pAvailOp->Name ? pAvailOp->Name : "[n/a]";
  8278. }
  8279. CA2W msgWide(msg.c_str());
  8280. pOutputStrFn(pStrCtx, msgWide);
  8281. return E_FAIL;
  8282. }
  8283. std::shared_ptr<st::ShaderOpTest> test = std::make_shared<st::ShaderOpTest>();
  8284. test->SetupRenderTarget(pShaderOp, pDevice, pCommandQueue, pRenderTarget);
  8285. test->SetDxcSupport(&m_support);
  8286. test->RunShaderOp(pShaderOp);
  8287. test->PresentRenderTarget(pShaderOp, pCommandQueue, pRenderTarget);
  8288. pOutputStrFn(pStrCtx, L"Rendering complete.\r\n");
  8289. if (!pShaderOp->IsCompute()) {
  8290. D3D12_QUERY_DATA_PIPELINE_STATISTICS stats;
  8291. test->GetPipelineStats(&stats);
  8292. wchar_t statsText[400];
  8293. StringCchPrintfW(statsText, _countof(statsText),
  8294. L"Vertices/primitives read by input assembler: %I64u/%I64u\r\n"
  8295. L"Vertex shader invocations: %I64u\r\n"
  8296. L"Geometry shader invocations/output primitive: %I64u/%I64u\r\n"
  8297. L"Primitives sent to rasterizer/rendered: %I64u/%I64u\r\n"
  8298. L"PS/HS/DS/CS invocations: %I64u/%I64u/%I64u/%I64u\r\n",
  8299. stats.IAVertices, stats.IAPrimitives, stats.VSInvocations,
  8300. stats.GSInvocations, stats.GSPrimitives, stats.CInvocations,
  8301. stats.CPrimitives, stats.PSInvocations, stats.HSInvocations,
  8302. stats.DSInvocations, stats.CSInvocations);
  8303. pOutputStrFn(pStrCtx, statsText);
  8304. }
  8305. if (pReadBackDump) {
  8306. WriteReadBackDump(pShaderOp, test.get(), &pDump);
  8307. }
  8308. hr = S_OK;
  8309. }
  8310. catch (const CAtlException &E)
  8311. {
  8312. hr = E.m_hr;
  8313. }
  8314. catch (const std::bad_alloc &)
  8315. {
  8316. hr = E_OUTOFMEMORY;
  8317. }
  8318. catch (const std::exception &)
  8319. {
  8320. hr = E_FAIL;
  8321. }
  8322. // Drain the device message queue if available.
  8323. if (pInfoQueue != nullptr) {
  8324. wchar_t buf[200];
  8325. StringCchPrintfW(buf, _countof(buf),
  8326. L"NumStoredMessages=%u limit/discarded by limit=%u/%u "
  8327. L"allowed/denied by storage filter=%u/%u "
  8328. L"NumStoredMessagesAllowedByRetrievalFilter=%u\r\n",
  8329. (unsigned)pInfoQueue->GetNumStoredMessages(),
  8330. (unsigned)pInfoQueue->GetMessageCountLimit(),
  8331. (unsigned)pInfoQueue->GetNumMessagesDiscardedByMessageCountLimit(),
  8332. (unsigned)pInfoQueue->GetNumMessagesAllowedByStorageFilter(),
  8333. (unsigned)pInfoQueue->GetNumMessagesDeniedByStorageFilter(),
  8334. (unsigned)pInfoQueue->GetNumStoredMessagesAllowedByRetrievalFilter());
  8335. pOutputStrFn(pStrCtx, buf);
  8336. WriteInfoQueueMessages(pStrCtx, pOutputStrFn, pInfoQueue);
  8337. pInfoQueue->ClearStoredMessages();
  8338. pInfoQueue->PopRetrievalFilter();
  8339. pInfoQueue->PopStorageFilter();
  8340. if (FilterCreation) {
  8341. pInfoQueue->PopStorageFilter();
  8342. }
  8343. }
  8344. if (pReadBackDump) *pReadBackDump = pDump.Detach();
  8345. return hr;
  8346. }
  8347. }
  8348. #endif
  8349. // MARKER: ExecutionTest/DxilConf Shared Implementation End
  8350. // Do not remove the line above - it is used by TranslateExecutionTest.py