ExecutionTest.cpp 178 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527
  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. #include <algorithm>
  13. #include <memory>
  14. #include <vector>
  15. #include <string>
  16. #include <map>
  17. #include <unordered_set>
  18. #include <strstream>
  19. #include <iomanip>
  20. #include "CompilationResult.h"
  21. #include "HLSLTestData.h"
  22. #include <Shlwapi.h>
  23. #include <atlcoll.h>
  24. #include <locale>
  25. #include <algorithm>
  26. #undef _read
  27. #include "WexTestClass.h"
  28. #include "HlslTestUtils.h"
  29. #include "DxcTestUtils.h"
  30. #include "dxc/Support/Global.h"
  31. #include "dxc/Support/WinIncludes.h"
  32. #include "dxc/Support/FileIOHelper.h"
  33. #include "dxc/Support/Unicode.h"
  34. //
  35. // d3d12.h and dxgi1_4.h are included in the Windows 10 SDK
  36. // https://msdn.microsoft.com/en-us/library/windows/desktop/dn899120(v=vs.85).aspx
  37. // https://developer.microsoft.com/en-US/windows/downloads/windows-10-sdk
  38. //
  39. #include <d3d12.h>
  40. #include <dxgi1_4.h>
  41. #include <DXGIDebug.h>
  42. #include <D3dx12.h>
  43. #include <DirectXMath.h>
  44. #include <strsafe.h>
  45. #include <d3dcompiler.h>
  46. #include <wincodec.h>
  47. #include "ShaderOpTest.h"
  48. #pragma comment(lib, "d3dcompiler.lib")
  49. #pragma comment(lib, "windowscodecs.lib")
  50. #pragma comment(lib, "dxguid.lib")
  51. #pragma comment(lib, "version.lib")
  52. // A more recent Windows SDK than currently required is needed for these.
  53. typedef HRESULT(WINAPI *D3D12EnableExperimentalFeaturesFn)(
  54. UINT NumFeatures,
  55. __in_ecount(NumFeatures) const IID* pIIDs,
  56. __in_ecount_opt(NumFeatures) void* pConfigurationStructs,
  57. __in_ecount_opt(NumFeatures) UINT* pConfigurationStructSizes);
  58. static const GUID D3D12ExperimentalShaderModelsID = { /* 76f5573e-f13a-40f5-b297-81ce9e18933f */
  59. 0x76f5573e,
  60. 0xf13a,
  61. 0x40f5,
  62. { 0xb2, 0x97, 0x81, 0xce, 0x9e, 0x18, 0x93, 0x3f }
  63. };
  64. using namespace DirectX;
  65. using namespace hlsl_test;
  66. template <typename TSequence, typename T>
  67. static bool contains(TSequence s, const T &val) {
  68. return std::cend(s) != std::find(std::cbegin(s), std::cend(s), val);
  69. }
  70. template <typename InputIterator, typename T>
  71. static bool contains(InputIterator b, InputIterator e, const T &val) {
  72. return e != std::find(b, e, val);
  73. }
  74. static HRESULT EnableExperimentalShaderModels() {
  75. HMODULE hRuntime = LoadLibraryW(L"d3d12.dll");
  76. if (hRuntime == NULL) {
  77. return HRESULT_FROM_WIN32(GetLastError());
  78. }
  79. D3D12EnableExperimentalFeaturesFn pD3D12EnableExperimentalFeatures =
  80. (D3D12EnableExperimentalFeaturesFn)GetProcAddress(hRuntime, "D3D12EnableExperimentalFeatures");
  81. if (pD3D12EnableExperimentalFeatures == nullptr) {
  82. FreeLibrary(hRuntime);
  83. return HRESULT_FROM_WIN32(GetLastError());
  84. }
  85. HRESULT hr = pD3D12EnableExperimentalFeatures(1, &D3D12ExperimentalShaderModelsID, nullptr, nullptr);
  86. FreeLibrary(hRuntime);
  87. return hr;
  88. }
  89. static HRESULT ReportLiveObjects() {
  90. CComPtr<IDXGIDebug1> pDebug;
  91. IFR(DXGIGetDebugInterface1(0, IID_PPV_ARGS(&pDebug)));
  92. IFR(pDebug->ReportLiveObjects(DXGI_DEBUG_ALL, DXGI_DEBUG_RLO_ALL));
  93. return S_OK;
  94. }
  95. static void WriteInfoQueueMessages(void *pStrCtx, st::OutputStringFn pOutputStrFn, ID3D12InfoQueue *pInfoQueue) {
  96. bool allMessagesOK = true;
  97. UINT64 count = pInfoQueue->GetNumStoredMessages();
  98. CAtlArray<BYTE> message;
  99. for (UINT64 i = 0; i < count; ++i) {
  100. // 'GetMessageA' rather than 'GetMessage' is an artifact of user32 headers.
  101. SIZE_T msgLen = 0;
  102. if (FAILED(pInfoQueue->GetMessageA(i, nullptr, &msgLen))) {
  103. allMessagesOK = false;
  104. continue;
  105. }
  106. if (message.GetCount() < msgLen) {
  107. if (!message.SetCount(msgLen)) {
  108. allMessagesOK = false;
  109. continue;
  110. }
  111. }
  112. D3D12_MESSAGE *pMessage = (D3D12_MESSAGE *)message.GetData();
  113. if (FAILED(pInfoQueue->GetMessageA(i, pMessage, &msgLen))) {
  114. allMessagesOK = false;
  115. continue;
  116. }
  117. CA2W msgW(pMessage->pDescription, CP_ACP);
  118. pOutputStrFn(pStrCtx, msgW.m_psz);
  119. pOutputStrFn(pStrCtx, L"\r\n");
  120. }
  121. if (!allMessagesOK) {
  122. pOutputStrFn(pStrCtx, L"Failed to retrieve some messages.\r\n");
  123. }
  124. }
  125. class CComContext {
  126. private:
  127. bool m_init;
  128. public:
  129. CComContext() : m_init(false) {}
  130. ~CComContext() { Dispose(); }
  131. void Dispose() { if (!m_init) return; m_init = false; CoUninitialize(); }
  132. HRESULT Init() { HRESULT hr = CoInitializeEx(0, COINIT_MULTITHREADED); if (SUCCEEDED(hr)) { m_init = true; } return hr; }
  133. };
  134. static void SavePixelsToFile(LPCVOID pPixels, DXGI_FORMAT format, UINT32 m_width, UINT32 m_height, LPCWSTR pFileName) {
  135. CComContext ctx;
  136. CComPtr<IWICImagingFactory> pFactory;
  137. CComPtr<IWICBitmap> pBitmap;
  138. CComPtr<IWICBitmapEncoder> pEncoder;
  139. CComPtr<IWICBitmapFrameEncode> pFrameEncode;
  140. CComPtr<hlsl::AbstractMemoryStream> pStream;
  141. CComPtr<IMalloc> pMalloc;
  142. struct PF {
  143. DXGI_FORMAT Format;
  144. GUID PixelFormat;
  145. UINT32 PixelSize;
  146. bool operator==(DXGI_FORMAT F) const {
  147. return F == Format;
  148. }
  149. } Vals[] = {
  150. // Add more pixel format mappings as needed.
  151. { DXGI_FORMAT_R8G8B8A8_UNORM, GUID_WICPixelFormat32bppRGBA, 4 }
  152. };
  153. PF *pFormat = std::find(Vals, Vals + _countof(Vals), format);
  154. VERIFY_SUCCEEDED(ctx.Init());
  155. VERIFY_SUCCEEDED(CoCreateInstance(CLSID_WICImagingFactory, NULL, CLSCTX_INPROC_SERVER, IID_IWICImagingFactory, (LPVOID*)&pFactory));
  156. VERIFY_SUCCEEDED(CoGetMalloc(1, &pMalloc));
  157. VERIFY_SUCCEEDED(hlsl::CreateMemoryStream(pMalloc, &pStream));
  158. VERIFY_ARE_NOT_EQUAL(pFormat, Vals + _countof(Vals));
  159. VERIFY_SUCCEEDED(pFactory->CreateBitmapFromMemory(m_width, m_height, pFormat->PixelFormat, m_width * pFormat->PixelSize, m_width * m_height * pFormat->PixelSize, (BYTE *)pPixels, &pBitmap));
  160. VERIFY_SUCCEEDED(pFactory->CreateEncoder(GUID_ContainerFormatBmp, nullptr, &pEncoder));
  161. VERIFY_SUCCEEDED(pEncoder->Initialize(pStream, WICBitmapEncoderNoCache));
  162. VERIFY_SUCCEEDED(pEncoder->CreateNewFrame(&pFrameEncode, nullptr));
  163. VERIFY_SUCCEEDED(pFrameEncode->Initialize(nullptr));
  164. VERIFY_SUCCEEDED(pFrameEncode->WriteSource(pBitmap, nullptr));
  165. VERIFY_SUCCEEDED(pFrameEncode->Commit());
  166. VERIFY_SUCCEEDED(pEncoder->Commit());
  167. hlsl::WriteBinaryFile(pFileName, pStream->GetPtr(), pStream->GetPtrSize());
  168. }
  169. // Setup for wave intrinsics tests
  170. enum class ShaderOpKind {
  171. WaveSum,
  172. WaveProduct,
  173. WaveActiveMax,
  174. WaveActiveMin,
  175. WaveCountBits,
  176. WaveActiveAllEqual,
  177. WaveActiveAnyTrue,
  178. WaveActiveAllTrue,
  179. WaveActiveBitOr,
  180. WaveActiveBitAnd,
  181. WaveActiveBitXor,
  182. ShaderOpInvalid
  183. };
  184. struct ShaderOpKindPair {
  185. LPCWSTR name;
  186. ShaderOpKind kind;
  187. };
  188. static ShaderOpKindPair ShaderOpKindTable[] = {
  189. { L"WaveActiveSum", ShaderOpKind::WaveSum },
  190. { L"WaveActiveUSum", ShaderOpKind::WaveSum },
  191. { L"WaveActiveProduct", ShaderOpKind::WaveProduct },
  192. { L"WaveActiveUProduct", ShaderOpKind::WaveProduct },
  193. { L"WaveActiveMax", ShaderOpKind::WaveActiveMax },
  194. { L"WaveActiveUMax", ShaderOpKind::WaveActiveMax },
  195. { L"WaveActiveMin", ShaderOpKind::WaveActiveMin },
  196. { L"WaveActiveUMin", ShaderOpKind::WaveActiveMin },
  197. { L"WaveActiveCountBits", ShaderOpKind::WaveCountBits },
  198. { L"WaveActiveAllEqual", ShaderOpKind::WaveActiveAllEqual },
  199. { L"WaveActiveAnyTrue", ShaderOpKind::WaveActiveAnyTrue },
  200. { L"WaveActiveAllTrue", ShaderOpKind::WaveActiveAllTrue },
  201. { L"WaveActiveBitOr", ShaderOpKind::WaveActiveBitOr },
  202. { L"WaveActiveBitAnd", ShaderOpKind::WaveActiveBitAnd },
  203. { L"WaveActiveBitXor", ShaderOpKind::WaveActiveBitXor },
  204. { L"WavePrefixSum", ShaderOpKind::WaveSum },
  205. { L"WavePrefixUSum", ShaderOpKind::WaveSum },
  206. { L"WavePrefixProduct", ShaderOpKind::WaveProduct },
  207. { L"WavePrefixUProduct", ShaderOpKind::WaveProduct },
  208. { L"WavePrefixMax", ShaderOpKind::WaveActiveMax },
  209. { L"WavePrefixUMax", ShaderOpKind::WaveActiveMax },
  210. { L"WavePrefixMin", ShaderOpKind::WaveActiveMin },
  211. { L"WavePrefixUMin", ShaderOpKind::WaveActiveMin },
  212. { L"WavePrefixCountBits", ShaderOpKind::WaveCountBits }
  213. };
  214. ShaderOpKind GetShaderOpKind(LPCWSTR str) {
  215. for (size_t i = 0; i < sizeof(ShaderOpKindTable)/sizeof(ShaderOpKindPair); ++i) {
  216. if (_wcsicmp(ShaderOpKindTable[i].name, str) == 0) {
  217. return ShaderOpKindTable[i].kind;
  218. }
  219. }
  220. DXASSERT(false, "Invalid ShaderOp name: %s", str);
  221. return ShaderOpKind::ShaderOpInvalid;
  222. }
  223. // Virtual class to compute the expected result given a set of inputs
  224. struct TableParameter;
  225. template <typename InType, typename OutType, ShaderOpKind kind>
  226. struct computeExpected {
  227. OutType operator()(const std::vector<InType> &inputs,
  228. const std::vector<int> &masks, int maskValue,
  229. unsigned int index) {
  230. return 0;
  231. }
  232. };
  233. template <typename InType, typename OutType>
  234. struct computeExpected<InType, OutType, ShaderOpKind::WaveSum> {
  235. OutType operator()(const std::vector<InType> &inputs,
  236. const std::vector<int> &masks, int maskValue,
  237. unsigned int index) {
  238. OutType sum = 0;
  239. for (size_t i = 0; i < index; ++i) {
  240. if (masks.at(i) == maskValue) {
  241. sum += inputs.at(i);
  242. }
  243. }
  244. return sum;
  245. }
  246. };
  247. template <typename InType, typename OutType>
  248. struct computeExpected<InType, OutType, ShaderOpKind::WaveProduct> {
  249. OutType operator()(const std::vector<InType> &inputs,
  250. const std::vector<int> &masks, int maskValue,
  251. unsigned int index) {
  252. OutType prod = 1;
  253. for (size_t i = 0; i < index; ++i) {
  254. if (masks.at(i) == maskValue) {
  255. prod *= inputs.at(i);
  256. }
  257. }
  258. return prod;
  259. }
  260. };
  261. template <typename InType, typename OutType>
  262. struct computeExpected<InType, OutType, ShaderOpKind::WaveActiveMax> {
  263. OutType operator()(const std::vector<InType> &inputs,
  264. const std::vector<int> &masks, int maskValue,
  265. unsigned int index) {
  266. OutType maximum = std::numeric_limits<OutType>::min();
  267. for (size_t i = 0; i < index; ++i) {
  268. if (masks.at(i) == maskValue && inputs.at(i) > maximum)
  269. maximum = inputs.at(i);
  270. }
  271. return maximum;
  272. }
  273. };
  274. template <typename InType, typename OutType>
  275. struct computeExpected<InType, OutType, ShaderOpKind::WaveActiveMin> {
  276. OutType operator()(const std::vector<InType> &inputs,
  277. const std::vector<int> &masks, int maskValue,
  278. unsigned int index) {
  279. OutType minimum = std::numeric_limits<OutType>::max();
  280. for (size_t i = 0; i < index; ++i) {
  281. if (masks.at(i) == maskValue && inputs.at(i) < minimum)
  282. minimum = inputs.at(i);
  283. }
  284. return minimum;
  285. }
  286. };
  287. template <typename InType, typename OutType>
  288. struct computeExpected<InType, OutType, ShaderOpKind::WaveCountBits> {
  289. OutType operator()(const std::vector<InType> &inputs,
  290. const std::vector<int> &masks, int maskValue,
  291. unsigned int index) {
  292. OutType count = 0;
  293. for (size_t i = 0; i < index; ++i) {
  294. if (masks.at(i) == maskValue && inputs.at(i) > 3) {
  295. count++;
  296. }
  297. }
  298. return count;
  299. }
  300. };
  301. // In HLSL, boolean is represented in a 4 byte (uint32) format,
  302. // So we cannot use c++ bool type to represent bool in HLSL
  303. // HLSL returns 0 for false and 1 for true
  304. template <typename InType, typename OutType>
  305. struct computeExpected<InType, OutType, ShaderOpKind::WaveActiveAnyTrue> {
  306. OutType operator()(const std::vector<InType> &inputs,
  307. const std::vector<int> &masks, int maskValue,
  308. unsigned int index) {
  309. for (size_t i = 0; i < index; ++i) {
  310. if (masks.at(i) == maskValue && inputs.at(i) != 0) {
  311. return 1;
  312. }
  313. }
  314. return 0;
  315. }
  316. };
  317. template <typename InType, typename OutType>
  318. struct computeExpected<InType, OutType, ShaderOpKind::WaveActiveAllTrue> {
  319. OutType operator()(const std::vector<InType> &inputs,
  320. const std::vector<int> &masks, int maskValue,
  321. unsigned int index) {
  322. for (size_t i = 0; i < index; ++i) {
  323. if (masks.at(i) == maskValue && inputs.at(i) == 0) {
  324. return 0;
  325. }
  326. }
  327. return 1;
  328. }
  329. };
  330. template <typename InType, typename OutType>
  331. struct computeExpected<InType, OutType, ShaderOpKind::WaveActiveAllEqual> {
  332. OutType operator()(const std::vector<InType> &inputs,
  333. const std::vector<int> &masks, int maskValue,
  334. unsigned int index) {
  335. const InType *val = nullptr;
  336. for (size_t i = 0; i < index; ++i) {
  337. if (masks.at(i) == maskValue) {
  338. if (val && *val != inputs.at(i)) {
  339. return 0;
  340. }
  341. val = &inputs.at(i);
  342. }
  343. }
  344. return 1;
  345. }
  346. };
  347. template <typename InType, typename OutType>
  348. struct computeExpected<InType, OutType, ShaderOpKind::WaveActiveBitOr> {
  349. OutType operator()(const std::vector<InType> &inputs,
  350. const std::vector<int> &masks, int maskValue,
  351. unsigned int index) {
  352. OutType bits = 0x00000000;
  353. for (size_t i = 0; i < index; ++i) {
  354. if (masks.at(i) == maskValue) {
  355. bits |= inputs.at(i);
  356. }
  357. }
  358. return bits;
  359. }
  360. };
  361. template <typename InType, typename OutType>
  362. struct computeExpected<InType, OutType, ShaderOpKind::WaveActiveBitAnd> {
  363. OutType operator()(const std::vector<InType> &inputs,
  364. const std::vector<int> &masks, int maskValue,
  365. unsigned int index) {
  366. OutType bits = 0xffffffff;
  367. for (size_t i = 0; i < index; ++i) {
  368. if (masks.at(i) == maskValue) {
  369. bits &= inputs.at(i);
  370. }
  371. }
  372. return bits;
  373. }
  374. };
  375. template <typename InType, typename OutType>
  376. struct computeExpected<InType, OutType, ShaderOpKind::WaveActiveBitXor> {
  377. OutType operator()(const std::vector<InType> &inputs,
  378. const std::vector<int> &masks, int maskValue,
  379. unsigned int index) {
  380. OutType bits = 0x00000000;
  381. for (size_t i = 0; i < index; ++i) {
  382. if (masks.at(i) == maskValue) {
  383. bits ^= inputs.at(i);
  384. }
  385. }
  386. return bits;
  387. }
  388. };
  389. // Mask functions used to control active lanes
  390. static int MaskAll(int i) {
  391. return 1;
  392. }
  393. static int MaskEveryOther(int i) {
  394. return i % 2 == 0 ? 1 : 0;
  395. }
  396. static int MaskEveryThird(int i) {
  397. return i % 3 == 0 ? 1 : 0;
  398. }
  399. typedef int(*MaskFunction)(int);
  400. static MaskFunction MaskFunctionTable[] = {
  401. MaskAll, MaskEveryOther, MaskEveryThird
  402. };
  403. template <typename InType, typename OutType>
  404. static OutType computeExpectedWithShaderOp(const std::vector<InType> &inputs,
  405. const std::vector<int> &masks,
  406. int maskValue, unsigned int index,
  407. LPCWSTR str) {
  408. ShaderOpKind kind = GetShaderOpKind(str);
  409. switch (kind) {
  410. case ShaderOpKind::WaveSum:
  411. return computeExpected<InType, OutType, ShaderOpKind::WaveSum>()(inputs, masks, maskValue, index);
  412. case ShaderOpKind::WaveProduct:
  413. return computeExpected<InType, OutType, ShaderOpKind::WaveProduct>()(inputs, masks, maskValue, index);
  414. case ShaderOpKind::WaveActiveMax:
  415. return computeExpected<InType, OutType, ShaderOpKind::WaveActiveMax>()(inputs, masks, maskValue, index);
  416. case ShaderOpKind::WaveActiveMin:
  417. return computeExpected<InType, OutType, ShaderOpKind::WaveActiveMin>()(inputs, masks, maskValue, index);
  418. case ShaderOpKind::WaveCountBits:
  419. return computeExpected<InType, OutType, ShaderOpKind::WaveCountBits>()(inputs, masks, maskValue, index);
  420. case ShaderOpKind::WaveActiveBitOr:
  421. return computeExpected<InType, OutType, ShaderOpKind::WaveActiveBitOr>()(inputs, masks, maskValue, index);
  422. case ShaderOpKind::WaveActiveBitAnd:
  423. return computeExpected<InType, OutType, ShaderOpKind::WaveActiveBitAnd>()(inputs, masks, maskValue, index);
  424. case ShaderOpKind::WaveActiveBitXor:
  425. return computeExpected<InType, OutType, ShaderOpKind::WaveActiveBitXor>()(inputs, masks, maskValue, index);
  426. case ShaderOpKind::WaveActiveAnyTrue:
  427. return computeExpected<InType, OutType, ShaderOpKind::WaveActiveAnyTrue>()(inputs, masks, maskValue, index);
  428. case ShaderOpKind::WaveActiveAllTrue:
  429. return computeExpected<InType, OutType, ShaderOpKind::WaveActiveAllTrue>()(inputs, masks, maskValue, index);
  430. case ShaderOpKind::WaveActiveAllEqual:
  431. return computeExpected<InType, OutType, ShaderOpKind::WaveActiveAllEqual>()(inputs, masks, maskValue, index);
  432. default:
  433. DXASSERT(false, "Invalid ShaderOp Name: %s", str);
  434. return (OutType) 0;
  435. }
  436. };
  437. // Checks if the given warp version supports the given operation.
  438. bool IsValidWarpDllVersion(unsigned int minBuildNumber) {
  439. HMODULE pLibrary = LoadLibrary("D3D10Warp.dll");
  440. if (pLibrary) {
  441. char path[MAX_PATH];
  442. DWORD length = GetModuleFileName(pLibrary, path, MAX_PATH);
  443. if (length) {
  444. DWORD dwVerHnd = 0;
  445. DWORD dwVersionInfoSize = GetFileVersionInfoSize(path, &dwVerHnd);
  446. std::unique_ptr<int[]> VffInfo(new int[dwVersionInfoSize]);
  447. if (GetFileVersionInfo(path, NULL, dwVersionInfoSize, VffInfo.get())) {
  448. LPVOID versionInfo;
  449. UINT size;
  450. if (VerQueryValue(VffInfo.get(), "\\", &versionInfo, &size)) {
  451. if (size) {
  452. VS_FIXEDFILEINFO *verInfo = (VS_FIXEDFILEINFO *)versionInfo;
  453. unsigned int warpBuildNumber = verInfo->dwFileVersionLS >> 16 & 0xffff;
  454. if (verInfo->dwSignature == 0xFEEF04BD && warpBuildNumber >= minBuildNumber) {
  455. return true;
  456. }
  457. }
  458. }
  459. }
  460. }
  461. FreeLibrary(pLibrary);
  462. }
  463. return false;
  464. }
  465. class ExecutionTest {
  466. public:
  467. // By default, ignore these tests, which require a recent build to run properly.
  468. BEGIN_TEST_CLASS(ExecutionTest)
  469. TEST_CLASS_PROPERTY(L"Parallel", L"true")
  470. TEST_CLASS_PROPERTY(L"Ignore", L"true")
  471. TEST_METHOD_PROPERTY(L"Priority", L"0")
  472. END_TEST_CLASS()
  473. TEST_CLASS_SETUP(ExecutionTestClassSetup)
  474. TEST_METHOD(BasicComputeTest);
  475. TEST_METHOD(BasicTriangleTest);
  476. TEST_METHOD(BasicTriangleOpTest);
  477. BEGIN_TEST_METHOD(BasicTriangleOpTestHalf)
  478. TEST_METHOD_PROPERTY(L"Priority", L"2") // Remove this line once warp supports this feature in Shader Model 6.2
  479. END_TEST_METHOD()
  480. TEST_METHOD(OutOfBoundsTest);
  481. TEST_METHOD(SaturateTest);
  482. TEST_METHOD(SignTest);
  483. TEST_METHOD(Int64Test);
  484. TEST_METHOD(WaveIntrinsicsTest);
  485. TEST_METHOD(WaveIntrinsicsDDITest);
  486. TEST_METHOD(WaveIntrinsicsInPSTest);
  487. TEST_METHOD(PartialDerivTest);
  488. BEGIN_TEST_METHOD(CBufferTestHalf)
  489. TEST_METHOD_PROPERTY(L"Priority", L"2") // Remove this line once warp supports this feature in Shader Model 6.2
  490. END_TEST_METHOD()
  491. BEGIN_TEST_METHOD(WaveIntrinsicsActiveIntTest)
  492. TEST_METHOD_PROPERTY(L"DataSource", L"Table:ShaderOpArithTable.xml#WaveIntrinsicsActiveIntTable")
  493. END_TEST_METHOD()
  494. BEGIN_TEST_METHOD(WaveIntrinsicsActiveUintTest)
  495. TEST_METHOD_PROPERTY(L"DataSource", L"Table:ShaderOpArithTable.xml#WaveIntrinsicsActiveUintTable")
  496. END_TEST_METHOD()
  497. BEGIN_TEST_METHOD(WaveIntrinsicsPrefixIntTest)
  498. TEST_METHOD_PROPERTY(L"DataSource", L"Table:ShaderOpArithTable.xml#WaveIntrinsicsPrefixIntTable")
  499. END_TEST_METHOD()
  500. BEGIN_TEST_METHOD(WaveIntrinsicsPrefixUintTest)
  501. TEST_METHOD_PROPERTY(L"DataSource", L"Table:ShaderOpArithTable.xml#WaveIntrinsicsPrefixUintTable")
  502. END_TEST_METHOD()
  503. // TAEF data-driven tests.
  504. BEGIN_TEST_METHOD(UnaryFloatOpTest)
  505. TEST_METHOD_PROPERTY(L"DataSource", L"Table:ShaderOpArithTable.xml#UnaryFloatOpTable")
  506. END_TEST_METHOD()
  507. BEGIN_TEST_METHOD(BinaryFloatOpTest)
  508. TEST_METHOD_PROPERTY(L"DataSource", L"Table:ShaderOpArithTable.xml#BinaryFloatOpTable")
  509. END_TEST_METHOD()
  510. BEGIN_TEST_METHOD(TertiaryFloatOpTest)
  511. TEST_METHOD_PROPERTY(L"DataSource", L"Table:ShaderOpArithTable.xml#TertiaryFloatOpTable")
  512. END_TEST_METHOD()
  513. BEGIN_TEST_METHOD(UnaryIntOpTest)
  514. TEST_METHOD_PROPERTY(L"DataSource", L"Table:ShaderOpArithTable.xml#UnaryIntOpTable")
  515. END_TEST_METHOD()
  516. BEGIN_TEST_METHOD(BinaryIntOpTest)
  517. TEST_METHOD_PROPERTY(L"DataSource", L"Table:ShaderOpArithTable.xml#BinaryIntOpTable")
  518. END_TEST_METHOD()
  519. BEGIN_TEST_METHOD(TertiaryIntOpTest)
  520. TEST_METHOD_PROPERTY(L"DataSource", L"Table:ShaderOpArithTable.xml#TertiaryIntOpTable")
  521. END_TEST_METHOD()
  522. BEGIN_TEST_METHOD(UnaryUintOpTest)
  523. TEST_METHOD_PROPERTY(L"DataSource", L"Table:ShaderOpArithTable.xml#UnaryUintOpTable")
  524. END_TEST_METHOD()
  525. BEGIN_TEST_METHOD(BinaryUintOpTest)
  526. TEST_METHOD_PROPERTY(L"DataSource", L"Table:ShaderOpArithTable.xml#BinaryUintOpTable")
  527. END_TEST_METHOD()
  528. BEGIN_TEST_METHOD(TertiaryUintOpTest)
  529. TEST_METHOD_PROPERTY(L"DataSource", L"Table:ShaderOpArithTable.xml#TertiaryUintOpTable")
  530. END_TEST_METHOD()
  531. BEGIN_TEST_METHOD(DotTest)
  532. TEST_METHOD_PROPERTY(L"DataSource", L"Table:ShaderOpArithTable.xml#DotOpTable")
  533. END_TEST_METHOD()
  534. BEGIN_TEST_METHOD(Msad4Test)
  535. TEST_METHOD_PROPERTY(L"DataSource", L"Table:ShaderOpArithTable.xml#Msad4Table")
  536. END_TEST_METHOD()
  537. dxc::DxcDllSupport m_support;
  538. VersionSupportInfo m_ver;
  539. bool m_ExperimentalModeEnabled = false;
  540. static const float ClearColor[4];
  541. template <class T1, class T2>
  542. void WaveIntrinsicsActivePrefixTest(
  543. TableParameter *pParameterList, size_t numParameter, bool isPrefix);
  544. void BasicTriangleTestSetup(LPCSTR OpName, LPCWSTR FileName);
  545. bool UseDxbc() {
  546. return GetTestParamBool(L"DXBC");
  547. }
  548. bool UseDebugIfaces() {
  549. return true;
  550. }
  551. bool SaveImages() {
  552. return GetTestParamBool(L"SaveImages");
  553. }
  554. void CompileFromText(LPCSTR pText, LPCWSTR pEntryPoint, LPCWSTR pTargetProfile, ID3DBlob **ppBlob) {
  555. VERIFY_SUCCEEDED(m_support.Initialize());
  556. CComPtr<IDxcCompiler> pCompiler;
  557. CComPtr<IDxcLibrary> pLibrary;
  558. CComPtr<IDxcBlobEncoding> pTextBlob;
  559. CComPtr<IDxcOperationResult> pResult;
  560. HRESULT resultCode;
  561. VERIFY_SUCCEEDED(m_support.CreateInstance(CLSID_DxcCompiler, &pCompiler));
  562. VERIFY_SUCCEEDED(m_support.CreateInstance(CLSID_DxcLibrary, &pLibrary));
  563. VERIFY_SUCCEEDED(pLibrary->CreateBlobWithEncodingFromPinned((LPBYTE)pText, strlen(pText), CP_UTF8, &pTextBlob));
  564. VERIFY_SUCCEEDED(pCompiler->Compile(pTextBlob, L"hlsl.hlsl", pEntryPoint, pTargetProfile, nullptr, 0, nullptr, 0, nullptr, &pResult));
  565. VERIFY_SUCCEEDED(pResult->GetStatus(&resultCode));
  566. if (FAILED(resultCode)) {
  567. CComPtr<IDxcBlobEncoding> errors;
  568. VERIFY_SUCCEEDED(pResult->GetErrorBuffer(&errors));
  569. LogCommentFmt(L"Failed to compile shader: %s", BlobToUtf16(errors).data());
  570. }
  571. VERIFY_SUCCEEDED(resultCode);
  572. VERIFY_SUCCEEDED(pResult->GetResult((IDxcBlob **)ppBlob));
  573. }
  574. void CreateComputeCommandQueue(ID3D12Device *pDevice, LPCWSTR pName, ID3D12CommandQueue **ppCommandQueue) {
  575. D3D12_COMMAND_QUEUE_DESC queueDesc = {};
  576. queueDesc.Flags = D3D12_COMMAND_QUEUE_FLAG_NONE;
  577. queueDesc.Type = D3D12_COMMAND_LIST_TYPE_COMPUTE;
  578. VERIFY_SUCCEEDED(pDevice->CreateCommandQueue(&queueDesc, IID_PPV_ARGS(ppCommandQueue)));
  579. VERIFY_SUCCEEDED((*ppCommandQueue)->SetName(pName));
  580. }
  581. void CreateComputePSO(ID3D12Device *pDevice, ID3D12RootSignature *pRootSignature, LPCSTR pShader, ID3D12PipelineState **ppComputeState) {
  582. CComPtr<ID3DBlob> pComputeShader;
  583. // Load and compile shaders.
  584. if (UseDxbc()) {
  585. DXBCFromText(pShader, L"main", L"cs_6_0", &pComputeShader);
  586. }
  587. else {
  588. CompileFromText(pShader, L"main", L"cs_6_0", &pComputeShader);
  589. }
  590. // Describe and create the compute pipeline state object (PSO).
  591. D3D12_COMPUTE_PIPELINE_STATE_DESC computePsoDesc = {};
  592. computePsoDesc.pRootSignature = pRootSignature;
  593. computePsoDesc.CS = CD3DX12_SHADER_BYTECODE(pComputeShader);
  594. VERIFY_SUCCEEDED(pDevice->CreateComputePipelineState(&computePsoDesc, IID_PPV_ARGS(ppComputeState)));
  595. }
  596. bool CreateDevice(_COM_Outptr_ ID3D12Device **ppDevice) {
  597. const D3D_FEATURE_LEVEL FeatureLevelRequired = D3D_FEATURE_LEVEL_11_0;
  598. CComPtr<IDXGIFactory4> factory;
  599. CComPtr<ID3D12Device> pDevice;
  600. *ppDevice = nullptr;
  601. VERIFY_SUCCEEDED(CreateDXGIFactory1(IID_PPV_ARGS(&factory)));
  602. if (GetTestParamUseWARP(true)) {
  603. CComPtr<IDXGIAdapter> warpAdapter;
  604. VERIFY_SUCCEEDED(factory->EnumWarpAdapter(IID_PPV_ARGS(&warpAdapter)));
  605. HRESULT createHR = D3D12CreateDevice(warpAdapter, FeatureLevelRequired,
  606. IID_PPV_ARGS(&pDevice));
  607. if (FAILED(createHR)) {
  608. LogCommentFmt(L"The available version of WARP does not support d3d12.");
  609. WEX::Logging::Log::Result(WEX::Logging::TestResults::Blocked);
  610. return false;
  611. }
  612. } else {
  613. CComPtr<IDXGIAdapter1> hardwareAdapter;
  614. WEX::Common::String AdapterValue;
  615. IFT(WEX::TestExecution::RuntimeParameters::TryGetValue(L"Adapter",
  616. AdapterValue));
  617. GetHardwareAdapter(factory, AdapterValue, &hardwareAdapter);
  618. if (hardwareAdapter == nullptr) {
  619. WEX::Logging::Log::Error(
  620. L"Unable to find hardware adapter with D3D12 support.");
  621. return false;
  622. }
  623. VERIFY_SUCCEEDED(D3D12CreateDevice(hardwareAdapter, FeatureLevelRequired,
  624. IID_PPV_ARGS(&pDevice)));
  625. DXGI_ADAPTER_DESC1 AdapterDesc;
  626. VERIFY_SUCCEEDED(hardwareAdapter->GetDesc1(&AdapterDesc));
  627. LogCommentFmt(L"Using Adapter: %s", AdapterDesc.Description);
  628. }
  629. if (pDevice == nullptr)
  630. return false;
  631. if (!UseDxbc()) {
  632. // Check for DXIL support.
  633. // This is defined in d3d.h for Windows 10 Anniversary Edition SDK, but we only
  634. // require the Windows 10 SDK.
  635. typedef enum D3D_SHADER_MODEL {
  636. D3D_SHADER_MODEL_5_1 = 0x51,
  637. D3D_SHADER_MODEL_6_0 = 0x60
  638. } D3D_SHADER_MODEL;
  639. typedef struct D3D12_FEATURE_DATA_SHADER_MODEL {
  640. _Inout_ D3D_SHADER_MODEL HighestShaderModel;
  641. } D3D12_FEATURE_DATA_SHADER_MODEL;
  642. const UINT D3D12_FEATURE_SHADER_MODEL = 7;
  643. D3D12_FEATURE_DATA_SHADER_MODEL SMData;
  644. SMData.HighestShaderModel = D3D_SHADER_MODEL_6_0;
  645. VERIFY_SUCCEEDED(pDevice->CheckFeatureSupport(
  646. (D3D12_FEATURE)D3D12_FEATURE_SHADER_MODEL, &SMData, sizeof(SMData)));
  647. if (SMData.HighestShaderModel != D3D_SHADER_MODEL_6_0) {
  648. LogCommentFmt(L"The selected device does not support "
  649. L"shader model 6 (required for DXIL).");
  650. WEX::Logging::Log::Result(WEX::Logging::TestResults::Blocked);
  651. return false;
  652. }
  653. }
  654. if (UseDebugIfaces()) {
  655. CComPtr<ID3D12InfoQueue> pInfoQueue;
  656. if (SUCCEEDED(pDevice->QueryInterface(&pInfoQueue))) {
  657. pInfoQueue->SetMuteDebugOutput(FALSE);
  658. }
  659. }
  660. *ppDevice = pDevice.Detach();
  661. return true;
  662. }
  663. void CreateGraphicsCommandQueue(ID3D12Device *pDevice, ID3D12CommandQueue **ppCommandQueue) {
  664. D3D12_COMMAND_QUEUE_DESC queueDesc = {};
  665. queueDesc.Flags = D3D12_COMMAND_QUEUE_FLAG_NONE;
  666. queueDesc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT;;
  667. VERIFY_SUCCEEDED(pDevice->CreateCommandQueue(&queueDesc, IID_PPV_ARGS(ppCommandQueue)));
  668. }
  669. void CreateGraphicsCommandQueueAndList(
  670. ID3D12Device *pDevice, ID3D12CommandQueue **ppCommandQueue,
  671. ID3D12CommandAllocator **ppAllocator,
  672. ID3D12GraphicsCommandList **ppCommandList, ID3D12PipelineState *pPSO) {
  673. CreateGraphicsCommandQueue(pDevice, ppCommandQueue);
  674. VERIFY_SUCCEEDED(pDevice->CreateCommandAllocator(
  675. D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(ppAllocator)));
  676. VERIFY_SUCCEEDED(pDevice->CreateCommandList(
  677. 0, D3D12_COMMAND_LIST_TYPE_DIRECT, *ppAllocator, pPSO,
  678. IID_PPV_ARGS(ppCommandList)));
  679. }
  680. void CreateGraphicsPSO(ID3D12Device *pDevice,
  681. D3D12_INPUT_LAYOUT_DESC *pInputLayout,
  682. ID3D12RootSignature *pRootSignature, LPCSTR pShaders,
  683. ID3D12PipelineState **ppPSO) {
  684. CComPtr<ID3DBlob> vertexShader;
  685. CComPtr<ID3DBlob> pixelShader;
  686. if (UseDxbc()) {
  687. DXBCFromText(pShaders, L"VSMain", L"vs_6_0", &vertexShader);
  688. DXBCFromText(pShaders, L"PSMain", L"ps_6_0", &pixelShader);
  689. } else {
  690. CompileFromText(pShaders, L"VSMain", L"vs_6_0", &vertexShader);
  691. CompileFromText(pShaders, L"PSMain", L"ps_6_0", &pixelShader);
  692. }
  693. // Describe and create the graphics pipeline state object (PSO).
  694. D3D12_GRAPHICS_PIPELINE_STATE_DESC psoDesc = {};
  695. psoDesc.InputLayout = *pInputLayout;
  696. psoDesc.pRootSignature = pRootSignature;
  697. psoDesc.VS = CD3DX12_SHADER_BYTECODE(vertexShader);
  698. psoDesc.PS = CD3DX12_SHADER_BYTECODE(pixelShader);
  699. psoDesc.RasterizerState = CD3DX12_RASTERIZER_DESC(D3D12_DEFAULT);
  700. psoDesc.BlendState = CD3DX12_BLEND_DESC(D3D12_DEFAULT);
  701. psoDesc.DepthStencilState.DepthEnable = FALSE;
  702. psoDesc.DepthStencilState.StencilEnable = FALSE;
  703. psoDesc.SampleMask = UINT_MAX;
  704. psoDesc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE;
  705. psoDesc.NumRenderTargets = 1;
  706. psoDesc.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM;
  707. psoDesc.SampleDesc.Count = 1;
  708. VERIFY_SUCCEEDED(
  709. pDevice->CreateGraphicsPipelineState(&psoDesc, IID_PPV_ARGS(ppPSO)));
  710. }
  711. void CreateRenderTargetAndReadback(ID3D12Device *pDevice,
  712. ID3D12DescriptorHeap *pHeap, UINT width,
  713. UINT height,
  714. ID3D12Resource **ppRenderTarget,
  715. ID3D12Resource **ppBuffer) {
  716. const DXGI_FORMAT format = DXGI_FORMAT_R8G8B8A8_UNORM;
  717. const size_t formatElementSize = 4;
  718. CComPtr<ID3D12Resource> pRenderTarget;
  719. CComPtr<ID3D12Resource> pBuffer;
  720. CD3DX12_CPU_DESCRIPTOR_HANDLE rtvHandle(
  721. pHeap->GetCPUDescriptorHandleForHeapStart());
  722. CD3DX12_HEAP_PROPERTIES rtHeap(D3D12_HEAP_TYPE_DEFAULT);
  723. CD3DX12_RESOURCE_DESC rtDesc(
  724. CD3DX12_RESOURCE_DESC::Tex2D(format, width, height));
  725. CD3DX12_CLEAR_VALUE rtClearVal(format, ClearColor);
  726. rtDesc.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET;
  727. VERIFY_SUCCEEDED(pDevice->CreateCommittedResource(
  728. &rtHeap, D3D12_HEAP_FLAG_NONE, &rtDesc, D3D12_RESOURCE_STATE_COPY_DEST,
  729. &rtClearVal, IID_PPV_ARGS(&pRenderTarget)));
  730. pDevice->CreateRenderTargetView(pRenderTarget, nullptr, rtvHandle);
  731. // rtvHandle.Offset(1, rtvDescriptorSize); // Not needed for a single
  732. // resource.
  733. CD3DX12_HEAP_PROPERTIES readHeap(D3D12_HEAP_TYPE_READBACK);
  734. CD3DX12_RESOURCE_DESC readDesc(
  735. CD3DX12_RESOURCE_DESC::Buffer(width * height * formatElementSize));
  736. VERIFY_SUCCEEDED(pDevice->CreateCommittedResource(
  737. &readHeap, D3D12_HEAP_FLAG_NONE, &readDesc,
  738. D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS(&pBuffer)));
  739. *ppRenderTarget = pRenderTarget.Detach();
  740. *ppBuffer = pBuffer.Detach();
  741. }
  742. void CreateRootSignatureFromDesc(ID3D12Device *pDevice,
  743. const D3D12_ROOT_SIGNATURE_DESC *pDesc,
  744. ID3D12RootSignature **pRootSig) {
  745. CComPtr<ID3DBlob> signature;
  746. CComPtr<ID3DBlob> error;
  747. VERIFY_SUCCEEDED(D3D12SerializeRootSignature(pDesc, D3D_ROOT_SIGNATURE_VERSION_1, &signature, &error));
  748. VERIFY_SUCCEEDED(pDevice->CreateRootSignature(
  749. 0, signature->GetBufferPointer(), signature->GetBufferSize(),
  750. IID_PPV_ARGS(pRootSig)));
  751. }
  752. void CreateRtvDescriptorHeap(ID3D12Device *pDevice, UINT numDescriptors,
  753. ID3D12DescriptorHeap **pRtvHeap, UINT *rtvDescriptorSize) {
  754. D3D12_DESCRIPTOR_HEAP_DESC rtvHeapDesc = {};
  755. rtvHeapDesc.NumDescriptors = numDescriptors;
  756. rtvHeapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_RTV;
  757. rtvHeapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_NONE;
  758. VERIFY_SUCCEEDED(
  759. pDevice->CreateDescriptorHeap(&rtvHeapDesc, IID_PPV_ARGS(pRtvHeap)));
  760. if (rtvDescriptorSize != nullptr) {
  761. *rtvDescriptorSize = pDevice->GetDescriptorHandleIncrementSize(
  762. D3D12_DESCRIPTOR_HEAP_TYPE_RTV);
  763. }
  764. }
  765. void CreateTestUavs(ID3D12Device *pDevice,
  766. ID3D12GraphicsCommandList *pCommandList, LPCVOID values,
  767. UINT32 valueSizeInBytes, ID3D12Resource **ppUavResource,
  768. ID3D12Resource **ppReadBuffer,
  769. ID3D12Resource **ppUploadResource) {
  770. CComPtr<ID3D12Resource> pUavResource;
  771. CComPtr<ID3D12Resource> pReadBuffer;
  772. CComPtr<ID3D12Resource> pUploadResource;
  773. D3D12_SUBRESOURCE_DATA transferData;
  774. D3D12_HEAP_PROPERTIES defaultHeapProperties = CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_DEFAULT);
  775. D3D12_HEAP_PROPERTIES uploadHeapProperties = CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_UPLOAD);
  776. D3D12_RESOURCE_DESC bufferDesc = CD3DX12_RESOURCE_DESC::Buffer(valueSizeInBytes, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS);
  777. D3D12_RESOURCE_DESC uploadBufferDesc = CD3DX12_RESOURCE_DESC::Buffer(valueSizeInBytes);
  778. CD3DX12_HEAP_PROPERTIES readHeap(D3D12_HEAP_TYPE_READBACK);
  779. CD3DX12_RESOURCE_DESC readDesc(CD3DX12_RESOURCE_DESC::Buffer(valueSizeInBytes));
  780. VERIFY_SUCCEEDED(pDevice->CreateCommittedResource(
  781. &defaultHeapProperties,
  782. D3D12_HEAP_FLAG_NONE,
  783. &bufferDesc,
  784. D3D12_RESOURCE_STATE_COPY_DEST,
  785. nullptr,
  786. IID_PPV_ARGS(&pUavResource)));
  787. VERIFY_SUCCEEDED(pDevice->CreateCommittedResource(
  788. &uploadHeapProperties,
  789. D3D12_HEAP_FLAG_NONE,
  790. &uploadBufferDesc,
  791. D3D12_RESOURCE_STATE_GENERIC_READ,
  792. nullptr,
  793. IID_PPV_ARGS(&pUploadResource)));
  794. VERIFY_SUCCEEDED(pDevice->CreateCommittedResource(
  795. &readHeap, D3D12_HEAP_FLAG_NONE, &readDesc,
  796. D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS(&pReadBuffer)));
  797. transferData.pData = values;
  798. transferData.RowPitch = valueSizeInBytes;
  799. transferData.SlicePitch = transferData.RowPitch;
  800. UpdateSubresources<1>(pCommandList, pUavResource.p, pUploadResource.p, 0, 0, 1, &transferData);
  801. RecordTransitionBarrier(pCommandList, pUavResource, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
  802. *ppUavResource = pUavResource.Detach();
  803. *ppReadBuffer = pReadBuffer.Detach();
  804. *ppUploadResource = pUploadResource.Detach();
  805. }
  806. template <typename TVertex, int len>
  807. void CreateVertexBuffer(ID3D12Device *pDevice, TVertex(&vertices)[len],
  808. ID3D12Resource **ppVertexBuffer,
  809. D3D12_VERTEX_BUFFER_VIEW *pVertexBufferView) {
  810. size_t vertexBufferSize = sizeof(vertices);
  811. CComPtr<ID3D12Resource> pVertexBuffer;
  812. CD3DX12_HEAP_PROPERTIES heapProps(D3D12_HEAP_TYPE_UPLOAD);
  813. CD3DX12_RESOURCE_DESC bufferDesc(
  814. CD3DX12_RESOURCE_DESC::Buffer(vertexBufferSize));
  815. VERIFY_SUCCEEDED(pDevice->CreateCommittedResource(
  816. &heapProps, D3D12_HEAP_FLAG_NONE, &bufferDesc,
  817. D3D12_RESOURCE_STATE_GENERIC_READ, nullptr,
  818. IID_PPV_ARGS(&pVertexBuffer)));
  819. UINT8 *pVertexDataBegin;
  820. CD3DX12_RANGE readRange(0, 0);
  821. VERIFY_SUCCEEDED(pVertexBuffer->Map(
  822. 0, &readRange, reinterpret_cast<void **>(&pVertexDataBegin)));
  823. memcpy(pVertexDataBegin, vertices, vertexBufferSize);
  824. pVertexBuffer->Unmap(0, nullptr);
  825. // Initialize the vertex buffer view.
  826. pVertexBufferView->BufferLocation = pVertexBuffer->GetGPUVirtualAddress();
  827. pVertexBufferView->StrideInBytes = sizeof(TVertex);
  828. pVertexBufferView->SizeInBytes = vertexBufferSize;
  829. *ppVertexBuffer = pVertexBuffer.Detach();
  830. }
  831. // Requires Anniversary Edition headers, so simplifying things for current setup.
  832. const UINT D3D12_FEATURE_D3D12_OPTIONS1 = 8;
  833. struct D3D12_FEATURE_DATA_D3D12_OPTIONS1 {
  834. BOOL WaveOps;
  835. UINT WaveLaneCountMin;
  836. UINT WaveLaneCountMax;
  837. UINT TotalLaneCount;
  838. BOOL ExpandedComputeResourceStates;
  839. BOOL Int64ShaderOps;
  840. };
  841. bool DoesDeviceSupportInt64(ID3D12Device *pDevice) {
  842. D3D12_FEATURE_DATA_D3D12_OPTIONS1 O;
  843. if (FAILED(pDevice->CheckFeatureSupport((D3D12_FEATURE)D3D12_FEATURE_D3D12_OPTIONS1, &O, sizeof(O))))
  844. return false;
  845. return O.Int64ShaderOps != FALSE;
  846. }
  847. bool DoesDeviceSupportWaveOps(ID3D12Device *pDevice) {
  848. D3D12_FEATURE_DATA_D3D12_OPTIONS1 O;
  849. if (FAILED(pDevice->CheckFeatureSupport((D3D12_FEATURE)D3D12_FEATURE_D3D12_OPTIONS1, &O, sizeof(O))))
  850. return false;
  851. return O.WaveOps != FALSE;
  852. }
  853. void DXBCFromText(LPCSTR pText, LPCWSTR pEntryPoint, LPCWSTR pTargetProfile, ID3DBlob **ppBlob) {
  854. CW2A pEntryPointA(pEntryPoint, CP_UTF8);
  855. CW2A pTargetProfileA(pTargetProfile, CP_UTF8);
  856. CComPtr<ID3DBlob> pErrors;
  857. D3D_SHADER_MACRO d3dMacro[2];
  858. ZeroMemory(d3dMacro, sizeof(d3dMacro));
  859. d3dMacro[0].Definition = "1";
  860. d3dMacro[0].Name = "USING_DXBC";
  861. HRESULT hr = D3DCompile(pText, strlen(pText), "hlsl.hlsl", d3dMacro, nullptr, pEntryPointA, pTargetProfileA, 0, 0, ppBlob, &pErrors);
  862. if (pErrors != nullptr) {
  863. CA2W errors((char *)pErrors->GetBufferPointer(), CP_ACP);
  864. LogCommentFmt(L"Compilation failure: %s", errors.m_szBuffer);
  865. }
  866. VERIFY_SUCCEEDED(hr);
  867. }
  868. HRESULT EnableDebugLayer() {
  869. // The debug layer does net yet validate DXIL programs that require rewriting,
  870. // but basic logging should work properly.
  871. HRESULT hr = S_FALSE;
  872. if (UseDebugIfaces()) {
  873. CComPtr<ID3D12Debug> debugController;
  874. hr = D3D12GetDebugInterface(IID_PPV_ARGS(&debugController));
  875. if (SUCCEEDED(hr)) {
  876. debugController->EnableDebugLayer();
  877. hr = S_OK;
  878. }
  879. }
  880. return hr;
  881. }
  882. HRESULT EnableExperimentalMode() {
  883. if (m_ExperimentalModeEnabled) {
  884. return S_OK;
  885. }
  886. if (!GetTestParamBool(L"ExperimentalShaders")) {
  887. return S_FALSE;
  888. }
  889. HRESULT hr = EnableExperimentalShaderModels();
  890. if (SUCCEEDED(hr)) {
  891. m_ExperimentalModeEnabled = true;
  892. }
  893. return hr;
  894. }
  895. struct FenceObj {
  896. HANDLE m_fenceEvent = NULL;
  897. CComPtr<ID3D12Fence> m_fence;
  898. UINT64 m_fenceValue;
  899. ~FenceObj() {
  900. if (m_fenceEvent) CloseHandle(m_fenceEvent);
  901. }
  902. };
  903. void InitFenceObj(ID3D12Device *pDevice, FenceObj *pObj) {
  904. pObj->m_fenceValue = 1;
  905. VERIFY_SUCCEEDED(pDevice->CreateFence(0, D3D12_FENCE_FLAG_NONE,
  906. IID_PPV_ARGS(&pObj->m_fence)));
  907. // Create an event handle to use for frame synchronization.
  908. pObj->m_fenceEvent = CreateEvent(nullptr, FALSE, FALSE, nullptr);
  909. if (pObj->m_fenceEvent == nullptr) {
  910. VERIFY_SUCCEEDED(HRESULT_FROM_WIN32(GetLastError()));
  911. }
  912. }
  913. void ReadHlslDataIntoNewStream(LPCWSTR relativePath, IStream **ppStream) {
  914. VERIFY_SUCCEEDED(m_support.Initialize());
  915. CComPtr<IDxcLibrary> pLibrary;
  916. CComPtr<IDxcBlobEncoding> pBlob;
  917. CComPtr<IStream> pStream;
  918. std::wstring path = GetPathToHlslDataFile(relativePath);
  919. VERIFY_SUCCEEDED(m_support.CreateInstance(CLSID_DxcLibrary, &pLibrary));
  920. VERIFY_SUCCEEDED(pLibrary->CreateBlobFromFile(path.c_str(), nullptr, &pBlob));
  921. VERIFY_SUCCEEDED(pLibrary->CreateStreamFromBlobReadOnly(pBlob, &pStream));
  922. *ppStream = pStream.Detach();
  923. }
  924. void RecordRenderAndReadback(ID3D12GraphicsCommandList *pList,
  925. ID3D12DescriptorHeap *pRtvHeap,
  926. UINT rtvDescriptorSize,
  927. UINT instanceCount,
  928. D3D12_VERTEX_BUFFER_VIEW *pVertexBufferView,
  929. ID3D12RootSignature *pRootSig,
  930. ID3D12Resource *pRenderTarget,
  931. ID3D12Resource *pReadBuffer) {
  932. D3D12_RESOURCE_DESC rtDesc = pRenderTarget->GetDesc();
  933. D3D12_VIEWPORT viewport;
  934. D3D12_RECT scissorRect;
  935. memset(&viewport, 0, sizeof(viewport));
  936. viewport.Height = rtDesc.Height;
  937. viewport.Width = rtDesc.Width;
  938. viewport.MaxDepth = 1.0f;
  939. memset(&scissorRect, 0, sizeof(scissorRect));
  940. scissorRect.right = rtDesc.Width;
  941. scissorRect.bottom = rtDesc.Height;
  942. if (pRootSig != nullptr) {
  943. pList->SetGraphicsRootSignature(pRootSig);
  944. }
  945. pList->RSSetViewports(1, &viewport);
  946. pList->RSSetScissorRects(1, &scissorRect);
  947. // Indicate that the buffer will be used as a render target.
  948. RecordTransitionBarrier(pList, pRenderTarget, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_RENDER_TARGET);
  949. CD3DX12_CPU_DESCRIPTOR_HANDLE rtvHandle(pRtvHeap->GetCPUDescriptorHandleForHeapStart(), 0, rtvDescriptorSize);
  950. pList->OMSetRenderTargets(1, &rtvHandle, FALSE, nullptr);
  951. pList->ClearRenderTargetView(rtvHandle, ClearColor, 0, nullptr);
  952. pList->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
  953. pList->IASetVertexBuffers(0, 1, pVertexBufferView);
  954. pList->DrawInstanced(3, instanceCount, 0, 0);
  955. // Transition to copy source and copy into read-back buffer.
  956. RecordTransitionBarrier(pList, pRenderTarget, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_COPY_SOURCE);
  957. // Copy into read-back buffer.
  958. UINT rowPitch = rtDesc.Width * 4;
  959. if (rowPitch % D3D12_TEXTURE_DATA_PITCH_ALIGNMENT)
  960. rowPitch += D3D12_TEXTURE_DATA_PITCH_ALIGNMENT - (rowPitch % D3D12_TEXTURE_DATA_PITCH_ALIGNMENT);
  961. D3D12_PLACED_SUBRESOURCE_FOOTPRINT Footprint;
  962. Footprint.Offset = 0;
  963. Footprint.Footprint = CD3DX12_SUBRESOURCE_FOOTPRINT(DXGI_FORMAT_R8G8B8A8_UNORM, rtDesc.Width, rtDesc.Height, 1, rowPitch);
  964. CD3DX12_TEXTURE_COPY_LOCATION DstLoc(pReadBuffer, Footprint);
  965. CD3DX12_TEXTURE_COPY_LOCATION SrcLoc(pRenderTarget, 0);
  966. pList->CopyTextureRegion(&DstLoc, 0, 0, 0, &SrcLoc, nullptr);
  967. }
  968. void RunRWByteBufferComputeTest(ID3D12Device *pDevice, LPCSTR shader, std::vector<uint32_t> &values);
  969. void SetDescriptorHeap(ID3D12GraphicsCommandList *pCommandList, ID3D12DescriptorHeap *pHeap) {
  970. ID3D12DescriptorHeap *const pHeaps[1] = { pHeap };
  971. pCommandList->SetDescriptorHeaps(1, pHeaps);
  972. }
  973. void WaitForSignal(ID3D12CommandQueue *pCQ, FenceObj &FO) {
  974. ::WaitForSignal(pCQ, FO.m_fence, FO.m_fenceEvent, FO.m_fenceValue++);
  975. }
  976. };
  977. const float ExecutionTest::ClearColor[4] = { 0.0f, 0.2f, 0.4f, 1.0f };
  978. #define WAVE_INTRINSIC_DXBC_GUARD \
  979. "#ifdef USING_DXBC\r\n" \
  980. "uint WaveGetLaneIndex() { return 1; }\r\n" \
  981. "uint WaveReadLaneFirst(uint u) { return u; }\r\n" \
  982. "bool WaveIsFirstLane() { return true; }\r\n" \
  983. "uint WaveGetLaneCount() { return 1; }\r\n" \
  984. "uint WaveReadLaneAt(uint n, uint u) { return u; }\r\n" \
  985. "bool WaveActiveAnyTrue(bool b) { return b; }\r\n" \
  986. "bool WaveActiveAllTrue(bool b) { return false; }\r\n" \
  987. "uint WaveActiveAllEqual(uint u) { return u; }\r\n" \
  988. "uint4 WaveActiveBallot(bool b) { return 1; }\r\n" \
  989. "uint WaveActiveCountBits(uint u) { return 1; }\r\n" \
  990. "uint WaveActiveSum(uint u) { return 1; }\r\n" \
  991. "uint WaveActiveProduct(uint u) { return 1; }\r\n" \
  992. "uint WaveActiveBitAnd(uint u) { return 1; }\r\n" \
  993. "uint WaveActiveBitOr(uint u) { return 1; }\r\n" \
  994. "uint WaveActiveBitXor(uint u) { return 1; }\r\n" \
  995. "uint WaveActiveMin(uint u) { return 1; }\r\n" \
  996. "uint WaveActiveMax(uint u) { return 1; }\r\n" \
  997. "uint WavePrefixCountBits(uint u) { return 1; }\r\n" \
  998. "uint WavePrefixSum(uint u) { return 1; }\r\n" \
  999. "uint WavePrefixProduct(uint u) { return 1; }\r\n" \
  1000. "uint QuadReadLaneAt(uint a, uint u) { return 1; }\r\n" \
  1001. "uint QuadReadAcrossX(uint u) { return 1; }\r\n" \
  1002. "uint QuadReadAcrossY(uint u) { return 1; }\r\n" \
  1003. "uint QuadReadAcrossDiagonal(uint u) { return 1; }\r\n" \
  1004. "#endif\r\n"
  1005. static void SetupComputeValuePattern(std::vector<uint32_t> &values, size_t count) {
  1006. values.resize(count); // one element per dispatch group, in bytes
  1007. for (size_t i = 0; i < count; ++i) {
  1008. values[i] = i;
  1009. }
  1010. }
  1011. bool ExecutionTest::ExecutionTestClassSetup() {
  1012. if (!m_support.IsEnabled()) {
  1013. VERIFY_SUCCEEDED(m_support.Initialize());
  1014. m_ver.Initialize(m_support);
  1015. }
  1016. HRESULT hr = EnableExperimentalMode();
  1017. if (FAILED(hr)) {
  1018. LogCommentFmt(L"Unable to enable shader experimental mode - 0x%08x.", hr);
  1019. }
  1020. else if (hr == S_FALSE) {
  1021. LogCommentFmt(L"Experimental mode not enabled.");
  1022. }
  1023. else {
  1024. LogCommentFmt(L"Experimental mode enabled.");
  1025. }
  1026. hr = EnableDebugLayer();
  1027. if (FAILED(hr)) {
  1028. LogCommentFmt(L"Unable to enable debug layer - 0x%08x.", hr);
  1029. }
  1030. else {
  1031. LogCommentFmt(L"Debug layer enabled.");
  1032. }
  1033. return true;
  1034. }
  1035. void ExecutionTest::RunRWByteBufferComputeTest(ID3D12Device *pDevice, LPCSTR pShader, std::vector<uint32_t> &values) {
  1036. static const int DispatchGroupX = 1;
  1037. static const int DispatchGroupY = 1;
  1038. static const int DispatchGroupZ = 1;
  1039. CComPtr<ID3D12GraphicsCommandList> pCommandList;
  1040. CComPtr<ID3D12CommandQueue> pCommandQueue;
  1041. CComPtr<ID3D12DescriptorHeap> pUavHeap;
  1042. CComPtr<ID3D12CommandAllocator> pCommandAllocator;
  1043. UINT uavDescriptorSize;
  1044. FenceObj FO;
  1045. const size_t valueSizeInBytes = values.size() * sizeof(uint32_t);
  1046. CreateComputeCommandQueue(pDevice, L"RunRWByteBufferComputeTest Command Queue", &pCommandQueue);
  1047. InitFenceObj(pDevice, &FO);
  1048. // Describe and create a UAV descriptor heap.
  1049. D3D12_DESCRIPTOR_HEAP_DESC heapDesc = {};
  1050. heapDesc.NumDescriptors = 1;
  1051. heapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV;
  1052. heapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE;
  1053. VERIFY_SUCCEEDED(pDevice->CreateDescriptorHeap(&heapDesc, IID_PPV_ARGS(&pUavHeap)));
  1054. uavDescriptorSize = pDevice->GetDescriptorHandleIncrementSize(heapDesc.Type);
  1055. // Create root signature.
  1056. CComPtr<ID3D12RootSignature> pRootSignature;
  1057. {
  1058. CD3DX12_DESCRIPTOR_RANGE ranges[1];
  1059. ranges[0].Init(D3D12_DESCRIPTOR_RANGE_TYPE_UAV, 1, 0, 0, 0);
  1060. CD3DX12_ROOT_PARAMETER rootParameters[1];
  1061. rootParameters[0].InitAsDescriptorTable(1, &ranges[0], D3D12_SHADER_VISIBILITY_ALL);
  1062. CD3DX12_ROOT_SIGNATURE_DESC rootSignatureDesc;
  1063. rootSignatureDesc.Init(_countof(rootParameters), rootParameters, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE);
  1064. CreateRootSignatureFromDesc(pDevice, &rootSignatureDesc, &pRootSignature);
  1065. }
  1066. // Create pipeline state object.
  1067. CComPtr<ID3D12PipelineState> pComputeState;
  1068. CreateComputePSO(pDevice, pRootSignature, pShader, &pComputeState);
  1069. // Create a command allocator and list for compute.
  1070. VERIFY_SUCCEEDED(pDevice->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_COMPUTE, IID_PPV_ARGS(&pCommandAllocator)));
  1071. VERIFY_SUCCEEDED(pDevice->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_COMPUTE, pCommandAllocator, pComputeState, IID_PPV_ARGS(&pCommandList)));
  1072. pCommandList->SetName(L"ExecutionTest::RunRWByteButterComputeTest Command List");
  1073. // Set up UAV resource.
  1074. CComPtr<ID3D12Resource> pUavResource;
  1075. CComPtr<ID3D12Resource> pReadBuffer;
  1076. CComPtr<ID3D12Resource> pUploadResource;
  1077. CreateTestUavs(pDevice, pCommandList, values.data(), valueSizeInBytes, &pUavResource, &pReadBuffer, &pUploadResource);
  1078. VERIFY_SUCCEEDED(pUavResource->SetName(L"RunRWByteBufferComputeText UAV"));
  1079. VERIFY_SUCCEEDED(pReadBuffer->SetName(L"RunRWByteBufferComputeText UAV Read Buffer"));
  1080. VERIFY_SUCCEEDED(pUploadResource->SetName(L"RunRWByteBufferComputeText UAV Upload Buffer"));
  1081. // Close the command list and execute it to perform the GPU setup.
  1082. pCommandList->Close();
  1083. ExecuteCommandList(pCommandQueue, pCommandList);
  1084. WaitForSignal(pCommandQueue, FO);
  1085. VERIFY_SUCCEEDED(pCommandAllocator->Reset());
  1086. VERIFY_SUCCEEDED(pCommandList->Reset(pCommandAllocator, pComputeState));
  1087. // Run the compute shader and copy the results back to readable memory.
  1088. {
  1089. D3D12_UNORDERED_ACCESS_VIEW_DESC uavDesc = {};
  1090. uavDesc.Format = DXGI_FORMAT_R32_TYPELESS;
  1091. uavDesc.ViewDimension = D3D12_UAV_DIMENSION_BUFFER;
  1092. uavDesc.Buffer.FirstElement = 0;
  1093. uavDesc.Buffer.NumElements = values.size();
  1094. uavDesc.Buffer.StructureByteStride = 0;
  1095. uavDesc.Buffer.CounterOffsetInBytes = 0;
  1096. uavDesc.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_RAW;
  1097. CD3DX12_CPU_DESCRIPTOR_HANDLE uavHandle(pUavHeap->GetCPUDescriptorHandleForHeapStart());
  1098. CD3DX12_GPU_DESCRIPTOR_HANDLE uavHandleGpu(pUavHeap->GetGPUDescriptorHandleForHeapStart());
  1099. pDevice->CreateUnorderedAccessView(pUavResource, nullptr, &uavDesc, uavHandle);
  1100. SetDescriptorHeap(pCommandList, pUavHeap);
  1101. pCommandList->SetComputeRootSignature(pRootSignature);
  1102. pCommandList->SetComputeRootDescriptorTable(0, uavHandleGpu);
  1103. }
  1104. pCommandList->Dispatch(DispatchGroupX, DispatchGroupY, DispatchGroupZ);
  1105. RecordTransitionBarrier(pCommandList, pUavResource, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE);
  1106. pCommandList->CopyResource(pReadBuffer, pUavResource);
  1107. pCommandList->Close();
  1108. ExecuteCommandList(pCommandQueue, pCommandList);
  1109. WaitForSignal(pCommandQueue, FO);
  1110. {
  1111. MappedData mappedData(pReadBuffer, valueSizeInBytes);
  1112. uint32_t *pData = (uint32_t *)mappedData.data();
  1113. memcpy(values.data(), pData, valueSizeInBytes);
  1114. }
  1115. WaitForSignal(pCommandQueue, FO);
  1116. }
  1117. TEST_F(ExecutionTest, BasicComputeTest) {
  1118. //
  1119. // BasicComputeTest is a simple compute shader that can be used as the basis
  1120. // for more interesting compute execution tests.
  1121. // The HLSL is compatible with shader models <=5.1 to allow using the DXBC
  1122. // rendering code paths for comparison.
  1123. //
  1124. static const char pShader[] =
  1125. "RWByteAddressBuffer g_bab : register(u0);\r\n"
  1126. "[numthreads(8,8,1)]\r\n"
  1127. "void main(uint GI : SV_GroupIndex) {"
  1128. " uint addr = GI * 4;\r\n"
  1129. " uint val = g_bab.Load(addr);\r\n"
  1130. " DeviceMemoryBarrierWithGroupSync();\r\n"
  1131. " g_bab.Store(addr, val + 1);\r\n"
  1132. "}";
  1133. static const int NumThreadsX = 8;
  1134. static const int NumThreadsY = 8;
  1135. static const int NumThreadsZ = 1;
  1136. static const int ThreadsPerGroup = NumThreadsX * NumThreadsY * NumThreadsZ;
  1137. static const int DispatchGroupCount = 1;
  1138. CComPtr<ID3D12Device> pDevice;
  1139. if (!CreateDevice(&pDevice))
  1140. return;
  1141. std::vector<uint32_t> values;
  1142. SetupComputeValuePattern(values, ThreadsPerGroup * DispatchGroupCount);
  1143. VERIFY_ARE_EQUAL(values[0], 0);
  1144. RunRWByteBufferComputeTest(pDevice, pShader, values);
  1145. VERIFY_ARE_EQUAL(values[0], 1);
  1146. }
  1147. TEST_F(ExecutionTest, BasicTriangleTest) {
  1148. static const UINT FrameCount = 2;
  1149. static const UINT m_width = 320;
  1150. static const UINT m_height = 200;
  1151. static const float m_aspectRatio = static_cast<float>(m_width) / static_cast<float>(m_height);
  1152. struct Vertex {
  1153. XMFLOAT3 position;
  1154. XMFLOAT4 color;
  1155. };
  1156. // Pipeline objects.
  1157. CComPtr<ID3D12Device> pDevice;
  1158. CComPtr<ID3D12Resource> pRenderTarget;
  1159. CComPtr<ID3D12CommandAllocator> pCommandAllocator;
  1160. CComPtr<ID3D12CommandQueue> pCommandQueue;
  1161. CComPtr<ID3D12RootSignature> pRootSig;
  1162. CComPtr<ID3D12DescriptorHeap> pRtvHeap;
  1163. CComPtr<ID3D12PipelineState> pPipelineState;
  1164. CComPtr<ID3D12GraphicsCommandList> pCommandList;
  1165. CComPtr<ID3D12Resource> pReadBuffer;
  1166. UINT rtvDescriptorSize;
  1167. CComPtr<ID3D12Resource> pVertexBuffer;
  1168. D3D12_VERTEX_BUFFER_VIEW vertexBufferView;
  1169. // Synchronization objects.
  1170. FenceObj FO;
  1171. // Shaders.
  1172. static const char pShaders[] =
  1173. "struct PSInput {\r\n"
  1174. " float4 position : SV_POSITION;\r\n"
  1175. " float4 color : COLOR;\r\n"
  1176. "};\r\n\r\n"
  1177. "PSInput VSMain(float4 position : POSITION, float4 color : COLOR) {\r\n"
  1178. " PSInput result;\r\n"
  1179. "\r\n"
  1180. " result.position = position;\r\n"
  1181. " result.color = color;\r\n"
  1182. " return result;\r\n"
  1183. "}\r\n\r\n"
  1184. "float4 PSMain(PSInput input) : SV_TARGET {\r\n"
  1185. " return 1; //input.color;\r\n"
  1186. "};\r\n";
  1187. if (!CreateDevice(&pDevice))
  1188. return;
  1189. struct BasicTestChecker {
  1190. CComPtr<ID3D12Device> m_pDevice;
  1191. CComPtr<ID3D12InfoQueue> m_pInfoQueue;
  1192. bool m_OK = false;
  1193. void SetOK(bool value) { m_OK = value; }
  1194. BasicTestChecker(ID3D12Device *pDevice) : m_pDevice(pDevice) {
  1195. if (FAILED(m_pDevice.QueryInterface(&m_pInfoQueue)))
  1196. return;
  1197. m_pInfoQueue->PushEmptyStorageFilter();
  1198. m_pInfoQueue->PushEmptyRetrievalFilter();
  1199. }
  1200. ~BasicTestChecker() {
  1201. if (!m_OK && m_pInfoQueue != nullptr) {
  1202. UINT64 count = m_pInfoQueue->GetNumStoredMessages();
  1203. bool invalidBytecodeFound = false;
  1204. CAtlArray<BYTE> m_pBytes;
  1205. for (UINT64 i = 0; i < count; ++i) {
  1206. SIZE_T len = 0;
  1207. if (FAILED(m_pInfoQueue->GetMessageA(i, nullptr, &len)))
  1208. continue;
  1209. if (m_pBytes.GetCount() < len && !m_pBytes.SetCount(len))
  1210. continue;
  1211. D3D12_MESSAGE *pMsg = (D3D12_MESSAGE *)m_pBytes.GetData();
  1212. if (FAILED(m_pInfoQueue->GetMessageA(i, pMsg, &len)))
  1213. continue;
  1214. if (pMsg->ID == D3D12_MESSAGE_ID_CREATEVERTEXSHADER_INVALIDSHADERBYTECODE ||
  1215. pMsg->ID == D3D12_MESSAGE_ID_CREATEPIXELSHADER_INVALIDSHADERBYTECODE) {
  1216. invalidBytecodeFound = true;
  1217. break;
  1218. }
  1219. }
  1220. if (invalidBytecodeFound) {
  1221. LogCommentFmt(L"%s", L"Found an invalid bytecode message. This "
  1222. L"typically indicates that experimental mode "
  1223. L"is not set up properly.");
  1224. if (!GetTestParamBool(L"ExperimentalShaders")) {
  1225. LogCommentFmt(L"Note that the ExperimentalShaders test parameter isn't set.");
  1226. }
  1227. }
  1228. else {
  1229. LogCommentFmt(L"Did not find corrupt pixel or vertex shaders in "
  1230. L"queue - dumping complete queue.");
  1231. WriteInfoQueueMessages(nullptr, OutputFn, m_pInfoQueue);
  1232. }
  1233. }
  1234. }
  1235. static void __stdcall OutputFn(void *pCtx, const wchar_t *pMsg) {
  1236. LogCommentFmt(L"%s", pMsg);
  1237. }
  1238. };
  1239. BasicTestChecker BTC(pDevice);
  1240. {
  1241. InitFenceObj(pDevice, &FO);
  1242. CreateRtvDescriptorHeap(pDevice, FrameCount, &pRtvHeap, &rtvDescriptorSize);
  1243. CreateRenderTargetAndReadback(pDevice, pRtvHeap, m_width, m_height, &pRenderTarget, &pReadBuffer);
  1244. // Create an empty root signature.
  1245. CD3DX12_ROOT_SIGNATURE_DESC rootSignatureDesc;
  1246. rootSignatureDesc.Init(
  1247. 0, nullptr, 0, nullptr,
  1248. D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT);
  1249. CreateRootSignatureFromDesc(pDevice, &rootSignatureDesc, &pRootSig);
  1250. // Create the pipeline state, which includes compiling and loading shaders.
  1251. // Define the vertex input layout.
  1252. D3D12_INPUT_ELEMENT_DESC inputElementDescs[] = {
  1253. {"POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0,
  1254. D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0},
  1255. {"COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 12,
  1256. D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0}};
  1257. D3D12_INPUT_LAYOUT_DESC InputLayout = { inputElementDescs, _countof(inputElementDescs) };
  1258. CreateGraphicsPSO(pDevice, &InputLayout, pRootSig, pShaders, &pPipelineState);
  1259. CreateGraphicsCommandQueueAndList(pDevice, &pCommandQueue,
  1260. &pCommandAllocator, &pCommandList,
  1261. pPipelineState);
  1262. // Define the geometry for a triangle.
  1263. Vertex triangleVertices[] = {
  1264. { { 0.0f, 0.25f * m_aspectRatio, 0.0f },{ 1.0f, 0.0f, 0.0f, 1.0f } },
  1265. { { 0.25f, -0.25f * m_aspectRatio, 0.0f },{ 0.0f, 1.0f, 0.0f, 1.0f } },
  1266. { { -0.25f, -0.25f * m_aspectRatio, 0.0f },{ 0.0f, 0.0f, 1.0f, 1.0f } } };
  1267. CreateVertexBuffer(pDevice, triangleVertices, &pVertexBuffer, &vertexBufferView);
  1268. WaitForSignal(pCommandQueue, FO);
  1269. }
  1270. // Render and execute the command list.
  1271. RecordRenderAndReadback(pCommandList, pRtvHeap, rtvDescriptorSize, 1,
  1272. &vertexBufferView, pRootSig, pRenderTarget,
  1273. pReadBuffer);
  1274. VERIFY_SUCCEEDED(pCommandList->Close());
  1275. ExecuteCommandList(pCommandQueue, pCommandList);
  1276. // Wait for previous frame.
  1277. WaitForSignal(pCommandQueue, FO);
  1278. // At this point, we've verified that execution succeeded with DXIL.
  1279. BTC.SetOK(true);
  1280. // Read back to CPU and examine contents.
  1281. {
  1282. MappedData data(pReadBuffer, m_width * m_height * 4);
  1283. const uint32_t *pPixels = (uint32_t *)data.data();
  1284. if (SaveImages()) {
  1285. SavePixelsToFile(pPixels, DXGI_FORMAT_R8G8B8A8_UNORM, m_width, m_height, L"basic.bmp");
  1286. }
  1287. uint32_t top = pPixels[m_width / 2]; // Top center.
  1288. uint32_t mid = pPixels[m_width / 2 + m_width * (m_height / 2)]; // Middle center.
  1289. VERIFY_ARE_EQUAL(0xff663300, top); // clear color
  1290. VERIFY_ARE_EQUAL(0xffffffff, mid); // white
  1291. }
  1292. }
  1293. TEST_F(ExecutionTest, Int64Test) {
  1294. static const char pShader[] =
  1295. "RWByteAddressBuffer g_bab : register(u0);\r\n"
  1296. "[numthreads(8,8,1)]\r\n"
  1297. "void main(uint GI : SV_GroupIndex) {"
  1298. " uint addr = GI * 4;\r\n"
  1299. " uint val = g_bab.Load(addr);\r\n"
  1300. " uint64_t u64 = val;\r\n"
  1301. " u64 *= val;\r\n"
  1302. " g_bab.Store(addr, (uint)(u64 >> 32));\r\n"
  1303. "}";
  1304. static const int NumThreadsX = 8;
  1305. static const int NumThreadsY = 8;
  1306. static const int NumThreadsZ = 1;
  1307. static const int ThreadsPerGroup = NumThreadsX * NumThreadsY * NumThreadsZ;
  1308. static const int DispatchGroupCount = 1;
  1309. CComPtr<ID3D12Device> pDevice;
  1310. if (!CreateDevice(&pDevice))
  1311. return;
  1312. if (!DoesDeviceSupportInt64(pDevice)) {
  1313. // Optional feature, so it's correct to not support it if declared as such.
  1314. WEX::Logging::Log::Comment(L"Device does not support int64 operations.");
  1315. return;
  1316. }
  1317. std::vector<uint32_t> values;
  1318. SetupComputeValuePattern(values, ThreadsPerGroup * DispatchGroupCount);
  1319. VERIFY_ARE_EQUAL(values[0], 0);
  1320. RunRWByteBufferComputeTest(pDevice, pShader, values);
  1321. VERIFY_ARE_EQUAL(values[0], 0);
  1322. }
  1323. TEST_F(ExecutionTest, SignTest) {
  1324. static const char pShader[] =
  1325. "RWByteAddressBuffer g_bab : register(u0);\r\n"
  1326. "[numthreads(8,1,1)]\r\n"
  1327. "void main(uint GI : SV_GroupIndex) {"
  1328. " uint addr = GI * 4;\r\n"
  1329. " int val = g_bab.Load(addr);\r\n"
  1330. " g_bab.Store(addr, (uint)(sign(val)));\r\n"
  1331. "}";
  1332. static const int NumThreadsX = 8;
  1333. static const int NumThreadsY = 1;
  1334. static const int NumThreadsZ = 1;
  1335. static const int ThreadsPerGroup = NumThreadsX * NumThreadsY * NumThreadsZ;
  1336. static const int DispatchGroupCount = 1;
  1337. CComPtr<ID3D12Device> pDevice;
  1338. if (!CreateDevice(&pDevice))
  1339. return;
  1340. std::vector<uint32_t> values = { (uint32_t)-3, (uint32_t)-2, (uint32_t)-1, 0, 1, 2, 3, 4};
  1341. RunRWByteBufferComputeTest(pDevice, pShader, values);
  1342. VERIFY_ARE_EQUAL(values[0], -1);
  1343. VERIFY_ARE_EQUAL(values[1], -1);
  1344. VERIFY_ARE_EQUAL(values[2], -1);
  1345. VERIFY_ARE_EQUAL(values[3], 0);
  1346. VERIFY_ARE_EQUAL(values[4], 1);
  1347. VERIFY_ARE_EQUAL(values[5], 1);
  1348. VERIFY_ARE_EQUAL(values[6], 1);
  1349. VERIFY_ARE_EQUAL(values[7], 1);
  1350. }
  1351. TEST_F(ExecutionTest, WaveIntrinsicsDDITest) {
  1352. CComPtr<ID3D12Device> pDevice;
  1353. if (!CreateDevice(&pDevice))
  1354. return;
  1355. D3D12_FEATURE_DATA_D3D12_OPTIONS1 O;
  1356. if (FAILED(pDevice->CheckFeatureSupport((D3D12_FEATURE)D3D12_FEATURE_D3D12_OPTIONS1, &O, sizeof(O))))
  1357. return;
  1358. bool waveSupported = O.WaveOps;
  1359. UINT laneCountMin = O.WaveLaneCountMin;
  1360. UINT laneCountMax = O.WaveLaneCountMax;
  1361. LogCommentFmt(L"WaveOps %i, WaveLaneCountMin %u, WaveLaneCountMax %u", waveSupported, laneCountMin, laneCountMax);
  1362. VERIFY_IS_TRUE(laneCountMin <= laneCountMax);
  1363. if (waveSupported) {
  1364. VERIFY_IS_TRUE(laneCountMin > 0 && laneCountMax > 0);
  1365. }
  1366. else {
  1367. VERIFY_IS_TRUE(laneCountMin == 0 && laneCountMax == 0);
  1368. }
  1369. }
  1370. TEST_F(ExecutionTest, WaveIntrinsicsTest) {
  1371. WEX::TestExecution::SetVerifyOutput verifySettings(WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  1372. struct PerThreadData {
  1373. uint32_t id, flags, laneIndex, laneCount, firstLaneId, preds, firstlaneX, lane1X;
  1374. uint32_t allBC, allSum, allProd, allAND, allOR, allXOR, allMin, allMax;
  1375. uint32_t pfBC, pfSum, pfProd;
  1376. uint32_t ballot[4];
  1377. uint32_t diver; // divergent value, used in calculation
  1378. int32_t i_diver; // divergent value, used in calculation
  1379. int32_t i_allMax, i_allMin, i_allSum, i_allProd;
  1380. int32_t i_pfSum, i_pfProd;
  1381. };
  1382. static const char pShader[] =
  1383. WAVE_INTRINSIC_DXBC_GUARD
  1384. "struct PerThreadData {\r\n"
  1385. " uint id, flags, laneIndex, laneCount, firstLaneId, preds, firstlaneX, lane1X;\r\n"
  1386. " uint allBC, allSum, allProd, allAND, allOR, allXOR, allMin, allMax;\r\n"
  1387. " uint pfBC, pfSum, pfProd;\r\n"
  1388. " uint4 ballot;\r\n"
  1389. " uint diver;\r\n"
  1390. " int i_diver;\r\n"
  1391. " int i_allMax, i_allMin, i_allSum, i_allProd;\r\n"
  1392. " int i_pfSum, i_pfProd;\r\n"
  1393. "};\r\n"
  1394. "RWStructuredBuffer<PerThreadData> g_sb : register(u0);\r\n"
  1395. "[numthreads(8,8,1)]\r\n"
  1396. "void main(uint GI : SV_GroupIndex, uint3 GTID : SV_GroupThreadID) {"
  1397. " PerThreadData pts = g_sb[GI];\r\n"
  1398. " uint diver = GTID.x + 2;\r\n"
  1399. " pts.diver = diver;\r\n"
  1400. " pts.flags = 0;\r\n"
  1401. " pts.preds = 0;\r\n"
  1402. " if (WaveIsFirstLane()) pts.flags |= 1;\r\n"
  1403. " pts.laneIndex = WaveGetLaneIndex();\r\n"
  1404. " pts.laneCount = WaveGetLaneCount();\r\n"
  1405. " pts.firstLaneId = WaveReadLaneFirst(pts.id);\r\n"
  1406. " pts.preds |= ((WaveActiveAnyTrue(diver == 1) ? 1 : 0) << 0);\r\n"
  1407. " pts.preds |= ((WaveActiveAllTrue(diver == 1) ? 1 : 0) << 1);\r\n"
  1408. " pts.preds |= ((WaveActiveAllEqual(diver) ? 1 : 0) << 2);\r\n"
  1409. " pts.preds |= ((WaveActiveAllEqual(GTID.z) ? 1 : 0) << 3);\r\n"
  1410. " pts.preds |= ((WaveActiveAllEqual(WaveReadLaneFirst(diver)) ? 1 : 0) << 4);\r\n"
  1411. " pts.ballot = WaveActiveBallot(diver > 3);\r\n"
  1412. " pts.firstlaneX = WaveReadLaneFirst(GTID.x);\r\n"
  1413. " pts.lane1X = WaveReadLaneAt(GTID.x, 1);\r\n"
  1414. "\r\n"
  1415. " pts.allBC = WaveActiveCountBits(diver > 3);\r\n"
  1416. " pts.allSum = WaveActiveSum(diver);\r\n"
  1417. " pts.allProd = WaveActiveProduct(diver);\r\n"
  1418. " pts.allAND = WaveActiveBitAnd(diver);\r\n"
  1419. " pts.allOR = WaveActiveBitOr(diver);\r\n"
  1420. " pts.allXOR = WaveActiveBitXor(diver);\r\n"
  1421. " pts.allMin = WaveActiveMin(diver);\r\n"
  1422. " pts.allMax = WaveActiveMax(diver);\r\n"
  1423. "\r\n"
  1424. " pts.pfBC = WavePrefixCountBits(diver > 3);\r\n"
  1425. " pts.pfSum = WavePrefixSum(diver);\r\n"
  1426. " pts.pfProd = WavePrefixProduct(diver);\r\n"
  1427. "\r\n"
  1428. " int i_diver = pts.i_diver;\r\n"
  1429. " pts.i_allMax = WaveActiveMax(i_diver);\r\n"
  1430. " pts.i_allMin = WaveActiveMin(i_diver);\r\n"
  1431. " pts.i_allSum = WaveActiveSum(i_diver);\r\n"
  1432. " pts.i_allProd = WaveActiveProduct(i_diver);\r\n"
  1433. " pts.i_pfSum = WavePrefixSum(i_diver);\r\n"
  1434. " pts.i_pfProd = WavePrefixProduct(i_diver);\r\n"
  1435. "\r\n"
  1436. " g_sb[GI] = pts;\r\n"
  1437. "}";
  1438. static const int NumtheadsX = 8;
  1439. static const int NumtheadsY = 8;
  1440. static const int NumtheadsZ = 1;
  1441. static const int ThreadsPerGroup = NumtheadsX * NumtheadsY * NumtheadsZ;
  1442. static const int DispatchGroupCount = 1;
  1443. CComPtr<ID3D12Device> pDevice;
  1444. if (!CreateDevice(&pDevice))
  1445. return;
  1446. if (!DoesDeviceSupportWaveOps(pDevice)) {
  1447. // Optional feature, so it's correct to not support it if declared as such.
  1448. WEX::Logging::Log::Comment(L"Device does not support wave operations.");
  1449. return;
  1450. }
  1451. std::vector<PerThreadData> values;
  1452. values.resize(ThreadsPerGroup * DispatchGroupCount);
  1453. for (size_t i = 0; i < values.size(); ++i) {
  1454. memset(&values[i], 0, sizeof(PerThreadData));
  1455. values[i].id = i;
  1456. values[i].i_diver = (int)i;
  1457. values[i].i_diver *= (i % 2) ? 1 : -1;
  1458. }
  1459. static const int DispatchGroupX = 1;
  1460. static const int DispatchGroupY = 1;
  1461. static const int DispatchGroupZ = 1;
  1462. CComPtr<ID3D12GraphicsCommandList> pCommandList;
  1463. CComPtr<ID3D12CommandQueue> pCommandQueue;
  1464. CComPtr<ID3D12DescriptorHeap> pUavHeap;
  1465. CComPtr<ID3D12CommandAllocator> pCommandAllocator;
  1466. UINT uavDescriptorSize;
  1467. FenceObj FO;
  1468. bool dxbc = UseDxbc();
  1469. const size_t valueSizeInBytes = values.size() * sizeof(PerThreadData);
  1470. CreateComputeCommandQueue(pDevice, L"WaveIntrinsicsTest Command Queue", &pCommandQueue);
  1471. InitFenceObj(pDevice, &FO);
  1472. // Describe and create a UAV descriptor heap.
  1473. D3D12_DESCRIPTOR_HEAP_DESC heapDesc = {};
  1474. heapDesc.NumDescriptors = 1;
  1475. heapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV;
  1476. heapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE;
  1477. VERIFY_SUCCEEDED(pDevice->CreateDescriptorHeap(&heapDesc, IID_PPV_ARGS(&pUavHeap)));
  1478. uavDescriptorSize = pDevice->GetDescriptorHandleIncrementSize(heapDesc.Type);
  1479. // Create root signature.
  1480. CComPtr<ID3D12RootSignature> pRootSignature;
  1481. {
  1482. CD3DX12_DESCRIPTOR_RANGE ranges[1];
  1483. ranges[0].Init(D3D12_DESCRIPTOR_RANGE_TYPE_UAV, 1, 0, 0, 0);
  1484. CD3DX12_ROOT_PARAMETER rootParameters[1];
  1485. rootParameters[0].InitAsDescriptorTable(1, &ranges[0], D3D12_SHADER_VISIBILITY_ALL);
  1486. CD3DX12_ROOT_SIGNATURE_DESC rootSignatureDesc;
  1487. rootSignatureDesc.Init(_countof(rootParameters), rootParameters, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE);
  1488. CComPtr<ID3DBlob> signature;
  1489. CComPtr<ID3DBlob> error;
  1490. VERIFY_SUCCEEDED(D3D12SerializeRootSignature(&rootSignatureDesc, D3D_ROOT_SIGNATURE_VERSION_1, &signature, &error));
  1491. VERIFY_SUCCEEDED(pDevice->CreateRootSignature(0, signature->GetBufferPointer(), signature->GetBufferSize(), IID_PPV_ARGS(&pRootSignature)));
  1492. }
  1493. // Create pipeline state object.
  1494. CComPtr<ID3D12PipelineState> pComputeState;
  1495. CreateComputePSO(pDevice, pRootSignature, pShader, &pComputeState);
  1496. // Create a command allocator and list for compute.
  1497. VERIFY_SUCCEEDED(pDevice->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_COMPUTE, IID_PPV_ARGS(&pCommandAllocator)));
  1498. VERIFY_SUCCEEDED(pDevice->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_COMPUTE, pCommandAllocator, pComputeState, IID_PPV_ARGS(&pCommandList)));
  1499. // Set up UAV resource.
  1500. CComPtr<ID3D12Resource> pUavResource;
  1501. CComPtr<ID3D12Resource> pReadBuffer;
  1502. CComPtr<ID3D12Resource> pUploadResource;
  1503. CreateTestUavs(pDevice, pCommandList, values.data(), valueSizeInBytes, &pUavResource, &pReadBuffer, &pUploadResource);
  1504. // Close the command list and execute it to perform the GPU setup.
  1505. pCommandList->Close();
  1506. ExecuteCommandList(pCommandQueue, pCommandList);
  1507. WaitForSignal(pCommandQueue, FO);
  1508. VERIFY_SUCCEEDED(pCommandAllocator->Reset());
  1509. VERIFY_SUCCEEDED(pCommandList->Reset(pCommandAllocator, pComputeState));
  1510. // Run the compute shader and copy the results back to readable memory.
  1511. {
  1512. D3D12_UNORDERED_ACCESS_VIEW_DESC uavDesc = {};
  1513. uavDesc.Format = DXGI_FORMAT_UNKNOWN;
  1514. uavDesc.ViewDimension = D3D12_UAV_DIMENSION_BUFFER;
  1515. uavDesc.Buffer.FirstElement = 0;
  1516. uavDesc.Buffer.NumElements = values.size();
  1517. uavDesc.Buffer.StructureByteStride = sizeof(PerThreadData);
  1518. uavDesc.Buffer.CounterOffsetInBytes = 0;
  1519. uavDesc.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_NONE;
  1520. CD3DX12_CPU_DESCRIPTOR_HANDLE uavHandle(pUavHeap->GetCPUDescriptorHandleForHeapStart());
  1521. CD3DX12_GPU_DESCRIPTOR_HANDLE uavHandleGpu(pUavHeap->GetGPUDescriptorHandleForHeapStart());
  1522. pDevice->CreateUnorderedAccessView(pUavResource, nullptr, &uavDesc, uavHandle);
  1523. SetDescriptorHeap(pCommandList, pUavHeap);
  1524. pCommandList->SetComputeRootSignature(pRootSignature);
  1525. pCommandList->SetComputeRootDescriptorTable(0, uavHandleGpu);
  1526. }
  1527. pCommandList->Dispatch(DispatchGroupX, DispatchGroupY, DispatchGroupZ);
  1528. RecordTransitionBarrier(pCommandList, pUavResource, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE);
  1529. pCommandList->CopyResource(pReadBuffer, pUavResource);
  1530. pCommandList->Close();
  1531. ExecuteCommandList(pCommandQueue, pCommandList);
  1532. WaitForSignal(pCommandQueue, FO);
  1533. {
  1534. MappedData mappedData(pReadBuffer, valueSizeInBytes);
  1535. PerThreadData *pData = (PerThreadData *)mappedData.data();
  1536. memcpy(values.data(), pData, valueSizeInBytes);
  1537. // Gather some general data.
  1538. // The 'firstLaneId' captures a unique number per first-lane per wave.
  1539. // Counting the number distinct firstLaneIds gives us the number of waves.
  1540. std::vector<uint32_t> firstLaneIds;
  1541. for (size_t i = 0; i < values.size(); ++i) {
  1542. PerThreadData &pts = values[i];
  1543. uint32_t firstLaneId = pts.firstLaneId;
  1544. if (!contains(firstLaneIds, firstLaneId)) {
  1545. firstLaneIds.push_back(firstLaneId);
  1546. }
  1547. }
  1548. // Waves should cover 4 threads or more.
  1549. LogCommentFmt(L"Found %u distinct lane ids: %u", firstLaneIds.size());
  1550. if (!dxbc) {
  1551. VERIFY_IS_GREATER_THAN_OR_EQUAL(values.size() / 4, firstLaneIds.size());
  1552. }
  1553. // Now, group threads into waves.
  1554. std::map<uint32_t, std::unique_ptr<std::vector<PerThreadData *> > > waves;
  1555. for (size_t i = 0; i < firstLaneIds.size(); ++i) {
  1556. waves[firstLaneIds[i]] = std::make_unique<std::vector<PerThreadData *> >();
  1557. }
  1558. for (size_t i = 0; i < values.size(); ++i) {
  1559. PerThreadData &pts = values[i];
  1560. std::unique_ptr<std::vector<PerThreadData *> > &wave = waves[pts.firstLaneId];
  1561. wave->push_back(&pts);
  1562. }
  1563. // Verify that all the wave values are coherent across the wave.
  1564. for (size_t i = 0; i < values.size(); ++i) {
  1565. PerThreadData &pts = values[i];
  1566. std::unique_ptr<std::vector<PerThreadData *> > &wave = waves[pts.firstLaneId];
  1567. // Sort the lanes by increasing lane ID.
  1568. struct LaneIdOrderPred {
  1569. bool operator()(PerThreadData *a, PerThreadData *b) {
  1570. return a->laneIndex < b->laneIndex;
  1571. }
  1572. };
  1573. std::sort(wave.get()->begin(), wave.get()->end(), LaneIdOrderPred());
  1574. // Verify some interesting properties of the first lane.
  1575. uint32_t pfBC, pfSum, pfProd;
  1576. int32_t i_pfSum, i_pfProd;
  1577. int32_t i_allMax, i_allMin;
  1578. {
  1579. PerThreadData *ptdFirst = wave->front();
  1580. VERIFY_IS_TRUE(0 != (ptdFirst->flags & 1)); // FirstLane sets this bit.
  1581. VERIFY_IS_TRUE(0 == ptdFirst->pfBC);
  1582. VERIFY_IS_TRUE(0 == ptdFirst->pfSum);
  1583. VERIFY_IS_TRUE(1 == ptdFirst->pfProd);
  1584. VERIFY_IS_TRUE(0 == ptdFirst->i_pfSum);
  1585. VERIFY_IS_TRUE(1 == ptdFirst->i_pfProd);
  1586. pfBC = (ptdFirst->diver > 3) ? 1 : 0;
  1587. pfSum = ptdFirst->diver;
  1588. pfProd = ptdFirst->diver;
  1589. i_pfSum = ptdFirst->i_diver;
  1590. i_pfProd = ptdFirst->i_diver;
  1591. i_allMax = i_allMin = ptdFirst->i_diver;
  1592. }
  1593. // Calculate values which take into consideration all lanes.
  1594. uint32_t preds = 0;
  1595. preds |= 1 << 1; // AllTrue starts true, switches to false if needed.
  1596. preds |= 1 << 2; // AllEqual starts true, switches to false if needed.
  1597. preds |= 1 << 3; // WaveActiveAllEqual(GTID.z) is always true
  1598. preds |= 1 << 4; // (WaveActiveAllEqual(WaveReadLaneFirst(diver)) is always true
  1599. uint32_t ballot[4] = { 0, 0, 0, 0 };
  1600. int32_t i_allSum = 0, i_allProd = 1;
  1601. for (size_t n = 0; n < wave->size(); ++n) {
  1602. std::vector<PerThreadData *> &lanes = *wave.get();
  1603. // pts.preds |= ((WaveActiveAnyTrue(diver == 1) ? 1 : 0) << 0);
  1604. if (lanes[n]->diver == 1) preds |= (1 << 0);
  1605. // pts.preds |= ((WaveActiveAllTrue(diver == 1) ? 1 : 0) << 1);
  1606. if (lanes[n]->diver != 1) preds &= ~(1 << 1);
  1607. // pts.preds |= ((WaveActiveAllEqual(diver) ? 1 : 0) << 2);
  1608. if (lanes[0]->diver != lanes[n]->diver) preds &= ~(1 << 2);
  1609. // pts.ballot = WaveActiveBallot(diver > 3);\r\n"
  1610. if (lanes[n]->diver > 3) {
  1611. // This is the uint4 result layout:
  1612. // .x -> bits 0 .. 31
  1613. // .y -> bits 32 .. 63
  1614. // .z -> bits 64 .. 95
  1615. // .w -> bits 96 ..127
  1616. uint32_t component = lanes[n]->laneIndex / 32;
  1617. uint32_t bit = lanes[n]->laneIndex % 32;
  1618. ballot[component] |= 1 << bit;
  1619. }
  1620. i_allMax = std::max(lanes[n]->i_diver, i_allMax);
  1621. i_allMin = std::min(lanes[n]->i_diver, i_allMin);
  1622. i_allProd *= lanes[n]->i_diver;
  1623. i_allSum += lanes[n]->i_diver;
  1624. }
  1625. for (size_t n = 1; n < wave->size(); ++n) {
  1626. // 'All' operations are uniform across the wave.
  1627. std::vector<PerThreadData *> &lanes = *wave.get();
  1628. VERIFY_IS_TRUE(0 == (lanes[n]->flags & 1)); // non-firstlanes do not set this bit
  1629. VERIFY_ARE_EQUAL(lanes[0]->allBC, lanes[n]->allBC);
  1630. VERIFY_ARE_EQUAL(lanes[0]->allSum, lanes[n]->allSum);
  1631. VERIFY_ARE_EQUAL(lanes[0]->allProd, lanes[n]->allProd);
  1632. VERIFY_ARE_EQUAL(lanes[0]->allAND, lanes[n]->allAND);
  1633. VERIFY_ARE_EQUAL(lanes[0]->allOR, lanes[n]->allOR);
  1634. VERIFY_ARE_EQUAL(lanes[0]->allXOR, lanes[n]->allXOR);
  1635. VERIFY_ARE_EQUAL(lanes[0]->allMin, lanes[n]->allMin);
  1636. VERIFY_ARE_EQUAL(lanes[0]->allMax, lanes[n]->allMax);
  1637. VERIFY_ARE_EQUAL(i_allMax, lanes[n]->i_allMax);
  1638. VERIFY_ARE_EQUAL(i_allMin, lanes[n]->i_allMin);
  1639. VERIFY_ARE_EQUAL(i_allProd, lanes[n]->i_allProd);
  1640. VERIFY_ARE_EQUAL(i_allSum, lanes[n]->i_allSum);
  1641. // first-lane reads and uniform reads are uniform across the wave.
  1642. VERIFY_ARE_EQUAL(lanes[0]->firstlaneX, lanes[n]->firstlaneX);
  1643. VERIFY_ARE_EQUAL(lanes[0]->lane1X, lanes[n]->lane1X);
  1644. // the lane count is uniform across the wave.
  1645. VERIFY_ARE_EQUAL(lanes[0]->laneCount, lanes[n]->laneCount);
  1646. // The predicates are uniform across the wave.
  1647. VERIFY_ARE_EQUAL(lanes[n]->preds, preds);
  1648. // the lane index is distinct per thread.
  1649. for (size_t prior = 0; prior < n; ++prior) {
  1650. VERIFY_ARE_NOT_EQUAL(lanes[prior]->laneIndex, lanes[n]->laneIndex);
  1651. }
  1652. // Ballot results are uniform across the wave.
  1653. VERIFY_ARE_EQUAL(0, memcmp(ballot, lanes[n]->ballot, sizeof(ballot)));
  1654. // Keep running total of prefix calculation. Prefix values are exclusive to
  1655. // the executing lane.
  1656. VERIFY_ARE_EQUAL(pfBC, lanes[n]->pfBC);
  1657. VERIFY_ARE_EQUAL(pfSum, lanes[n]->pfSum);
  1658. VERIFY_ARE_EQUAL(pfProd, lanes[n]->pfProd);
  1659. VERIFY_ARE_EQUAL(i_pfSum, lanes[n]->i_pfSum);
  1660. VERIFY_ARE_EQUAL(i_pfProd, lanes[n]->i_pfProd);
  1661. pfBC += (lanes[n]->diver > 3) ? 1 : 0;
  1662. pfSum += lanes[n]->diver;
  1663. pfProd *= lanes[n]->diver;
  1664. i_pfSum += lanes[n]->i_diver;
  1665. i_pfProd *= lanes[n]->i_diver;
  1666. }
  1667. // TODO: add divergent branching and verify that the otherwise uniform values properly diverge
  1668. }
  1669. // Compare each value of each per-thread element.
  1670. for (size_t i = 0; i < values.size(); ++i) {
  1671. PerThreadData &pts = values[i];
  1672. VERIFY_ARE_EQUAL(i, pts.id); // ID is unchanged.
  1673. }
  1674. }
  1675. }
  1676. // This test is assuming that the adapter implements WaveReadLaneFirst correctly
  1677. TEST_F(ExecutionTest, WaveIntrinsicsInPSTest) {
  1678. WEX::TestExecution::SetVerifyOutput verifySettings(WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  1679. struct Vertex {
  1680. XMFLOAT3 position;
  1681. };
  1682. struct PerPixelData {
  1683. XMFLOAT4 position;
  1684. uint32_t id, flags, laneIndex, laneCount, firstLaneId, sum1;
  1685. uint32_t id0, id1, id2, id3;
  1686. uint32_t acrossX, acrossY, acrossDiag, quadActiveCount;
  1687. };
  1688. const UINT RTWidth = 128;
  1689. const UINT RTHeight = 128;
  1690. // Shaders.
  1691. static const char pShaders[] =
  1692. WAVE_INTRINSIC_DXBC_GUARD
  1693. "struct PSInput {\r\n"
  1694. " float4 position : SV_POSITION;\r\n"
  1695. "};\r\n\r\n"
  1696. "PSInput VSMain(float4 position : POSITION) {\r\n"
  1697. " PSInput result;\r\n"
  1698. "\r\n"
  1699. " result.position = position;\r\n"
  1700. " return result;\r\n"
  1701. "}\r\n\r\n"
  1702. "uint pos_to_id(float4 pos) { return pos.x * 128 + pos.y; }\r\n"
  1703. "struct PerPixelData {\r\n"
  1704. " float4 position;\r\n"
  1705. " uint id, flags, laneIndex, laneCount, firstLaneId, sum1;\r\n"
  1706. " uint id0, id1, id2, id3;\r\n"
  1707. " uint acrossX, acrossY, acrossDiag, quadActiveCount;\r\n"
  1708. "};\r\n"
  1709. "AppendStructuredBuffer<PerPixelData> g_sb : register(u1);\r\n"
  1710. "float4 PSMain(PSInput input) : SV_TARGET {\r\n"
  1711. " uint one = 1;\r\n"
  1712. " PerPixelData d;\r\n"
  1713. " d.position = input.position;\r\n"
  1714. " d.id = pos_to_id(input.position);\r\n"
  1715. " d.flags = 0;\r\n"
  1716. " if (WaveIsFirstLane()) d.flags |= 1;\r\n"
  1717. " d.laneIndex = WaveGetLaneIndex();\r\n"
  1718. " d.laneCount = WaveGetLaneCount();\r\n"
  1719. " d.firstLaneId = WaveReadLaneFirst(d.id);\r\n"
  1720. " d.sum1 = WaveActiveSum(one);\r\n"
  1721. " d.id0 = QuadReadLaneAt(d.id, 0);\r\n"
  1722. " d.id1 = QuadReadLaneAt(d.id, 1);\r\n"
  1723. " d.id2 = QuadReadLaneAt(d.id, 2);\r\n"
  1724. " d.id3 = QuadReadLaneAt(d.id, 3);\r\n"
  1725. " d.acrossX = QuadReadAcrossX(d.id);\r\n"
  1726. " d.acrossY = QuadReadAcrossY(d.id);\r\n"
  1727. " d.acrossDiag = QuadReadAcrossDiagonal(d.id);\r\n"
  1728. " d.quadActiveCount = one + QuadReadAcrossX(one) + QuadReadAcrossY(one) + QuadReadAcrossDiagonal(one);\r\n"
  1729. " g_sb.Append(d);\r\n"
  1730. " return 1;\r\n"
  1731. "};\r\n";
  1732. CComPtr<ID3D12Device> pDevice;
  1733. CComPtr<ID3D12CommandQueue> pCommandQueue;
  1734. CComPtr<ID3D12DescriptorHeap> pUavHeap, pRtvHeap;
  1735. CComPtr<ID3D12CommandAllocator> pCommandAllocator;
  1736. CComPtr<ID3D12GraphicsCommandList> pCommandList;
  1737. CComPtr<ID3D12PipelineState> pPSO;
  1738. CComPtr<ID3D12Resource> pRenderTarget, pReadBuffer;
  1739. UINT uavDescriptorSize, rtvDescriptorSize;
  1740. CComPtr<ID3D12Resource> pVertexBuffer;
  1741. D3D12_VERTEX_BUFFER_VIEW vertexBufferView;
  1742. if (!CreateDevice(&pDevice))
  1743. return;
  1744. if (!DoesDeviceSupportWaveOps(pDevice)) {
  1745. // Optional feature, so it's correct to not support it if declared as such.
  1746. WEX::Logging::Log::Comment(L"Device does not support wave operations.");
  1747. return;
  1748. }
  1749. FenceObj FO;
  1750. InitFenceObj(pDevice, &FO);
  1751. // Describe and create a UAV descriptor heap.
  1752. D3D12_DESCRIPTOR_HEAP_DESC heapDesc = {};
  1753. heapDesc.NumDescriptors = 1;
  1754. heapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV;
  1755. heapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE;
  1756. VERIFY_SUCCEEDED(pDevice->CreateDescriptorHeap(&heapDesc, IID_PPV_ARGS(&pUavHeap)));
  1757. uavDescriptorSize = pDevice->GetDescriptorHandleIncrementSize(heapDesc.Type);
  1758. CreateRtvDescriptorHeap(pDevice, 1, &pRtvHeap, &rtvDescriptorSize);
  1759. CreateRenderTargetAndReadback(pDevice, pRtvHeap, RTHeight, RTWidth, &pRenderTarget, &pReadBuffer);
  1760. // Create root signature: one UAV.
  1761. CComPtr<ID3D12RootSignature> pRootSignature;
  1762. {
  1763. CD3DX12_DESCRIPTOR_RANGE ranges[1];
  1764. ranges[0].Init(D3D12_DESCRIPTOR_RANGE_TYPE_UAV, 1, 1, 0, 0);
  1765. CD3DX12_ROOT_PARAMETER rootParameters[1];
  1766. rootParameters[0].InitAsDescriptorTable(1, &ranges[0], D3D12_SHADER_VISIBILITY_ALL);
  1767. CD3DX12_ROOT_SIGNATURE_DESC rootSignatureDesc;
  1768. rootSignatureDesc.Init(_countof(rootParameters), rootParameters, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT);
  1769. CreateRootSignatureFromDesc(pDevice, &rootSignatureDesc, &pRootSignature);
  1770. }
  1771. D3D12_INPUT_ELEMENT_DESC elementDesc[] = {
  1772. {"POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0,
  1773. D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0}};
  1774. D3D12_INPUT_LAYOUT_DESC InputLayout = {elementDesc, _countof(elementDesc)};
  1775. CreateGraphicsPSO(pDevice, &InputLayout, pRootSignature, pShaders, &pPSO);
  1776. CreateGraphicsCommandQueueAndList(pDevice, &pCommandQueue, &pCommandAllocator,
  1777. &pCommandList, pPSO);
  1778. // Single triangle covering half the target.
  1779. Vertex vertices[] = {
  1780. { { -1.0f, 1.0f, 0.0f } },
  1781. { { 1.0f, 1.0f, 0.0f } },
  1782. { { -1.0f, -1.0f, 0.0f } } };
  1783. const UINT TriangleCount = _countof(vertices) / 3;
  1784. CreateVertexBuffer(pDevice, vertices, &pVertexBuffer, &vertexBufferView);
  1785. bool dxbc = UseDxbc();
  1786. // Set up UAV resource.
  1787. std::vector<PerPixelData> values;
  1788. values.resize(RTWidth * RTHeight * 2);
  1789. UINT valueSizeInBytes = values.size() * sizeof(PerPixelData);
  1790. memset(values.data(), 0, valueSizeInBytes);
  1791. CComPtr<ID3D12Resource> pUavResource;
  1792. CComPtr<ID3D12Resource> pUavReadBuffer;
  1793. CComPtr<ID3D12Resource> pUploadResource;
  1794. CreateTestUavs(pDevice, pCommandList, values.data(), valueSizeInBytes, &pUavResource, &pUavReadBuffer, &pUploadResource);
  1795. // Set up the append counter resource.
  1796. CComPtr<ID3D12Resource> pUavCounterResource;
  1797. CComPtr<ID3D12Resource> pReadCounterBuffer;
  1798. CComPtr<ID3D12Resource> pUploadCounterResource;
  1799. BYTE zero[sizeof(UINT)] = { 0 };
  1800. CreateTestUavs(pDevice, pCommandList, zero, sizeof(zero), &pUavCounterResource, &pReadCounterBuffer, &pUploadCounterResource);
  1801. // Close the command list and execute it to perform the GPU setup.
  1802. pCommandList->Close();
  1803. ExecuteCommandList(pCommandQueue, pCommandList);
  1804. WaitForSignal(pCommandQueue, FO);
  1805. VERIFY_SUCCEEDED(pCommandAllocator->Reset());
  1806. VERIFY_SUCCEEDED(pCommandList->Reset(pCommandAllocator, pPSO));
  1807. pCommandList->SetGraphicsRootSignature(pRootSignature);
  1808. SetDescriptorHeap(pCommandList, pUavHeap);
  1809. {
  1810. D3D12_UNORDERED_ACCESS_VIEW_DESC uavDesc = {};
  1811. uavDesc.Format = DXGI_FORMAT_UNKNOWN;
  1812. uavDesc.ViewDimension = D3D12_UAV_DIMENSION_BUFFER;
  1813. uavDesc.Buffer.FirstElement = 0;
  1814. uavDesc.Buffer.NumElements = values.size();
  1815. uavDesc.Buffer.StructureByteStride = sizeof(PerPixelData);
  1816. uavDesc.Buffer.CounterOffsetInBytes = 0;
  1817. uavDesc.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_NONE;
  1818. CD3DX12_CPU_DESCRIPTOR_HANDLE uavHandle(pUavHeap->GetCPUDescriptorHandleForHeapStart());
  1819. CD3DX12_GPU_DESCRIPTOR_HANDLE uavHandleGpu(pUavHeap->GetGPUDescriptorHandleForHeapStart());
  1820. pDevice->CreateUnorderedAccessView(pUavResource, pUavCounterResource, &uavDesc, uavHandle);
  1821. pCommandList->SetGraphicsRootDescriptorTable(0, uavHandleGpu);
  1822. }
  1823. RecordRenderAndReadback(pCommandList, pRtvHeap, rtvDescriptorSize, TriangleCount, &vertexBufferView, nullptr, pRenderTarget, pReadBuffer);
  1824. RecordTransitionBarrier(pCommandList, pUavResource, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE);
  1825. RecordTransitionBarrier(pCommandList, pUavCounterResource, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE);
  1826. pCommandList->CopyResource(pUavReadBuffer, pUavResource);
  1827. pCommandList->CopyResource(pReadCounterBuffer, pUavCounterResource);
  1828. VERIFY_SUCCEEDED(pCommandList->Close());
  1829. LogCommentFmt(L"Rendering to %u by %u", RTWidth, RTHeight);
  1830. ExecuteCommandList(pCommandQueue, pCommandList);
  1831. WaitForSignal(pCommandQueue, FO);
  1832. {
  1833. MappedData data(pReadBuffer, RTWidth * RTHeight * 4);
  1834. const uint32_t *pPixels = (uint32_t *)data.data();
  1835. if (SaveImages()) {
  1836. SavePixelsToFile(pPixels, DXGI_FORMAT_R8G8B8A8_UNORM, RTWidth, RTHeight, L"psintrin.bmp");
  1837. }
  1838. }
  1839. uint32_t appendCount;
  1840. {
  1841. MappedData mappedData(pReadCounterBuffer, sizeof(uint32_t));
  1842. appendCount = *((uint32_t *)mappedData.data());
  1843. LogCommentFmt(L"%u elements in append buffer", appendCount);
  1844. }
  1845. {
  1846. MappedData mappedData(pUavReadBuffer, values.size());
  1847. PerPixelData *pData = (PerPixelData *)mappedData.data();
  1848. memcpy(values.data(), pData, valueSizeInBytes);
  1849. // DXBC is handy to test pipeline setup, but interesting functions are
  1850. // stubbed out, so there is no point in further validation.
  1851. if (dxbc)
  1852. return;
  1853. uint32_t maxActiveLaneCount = 0;
  1854. uint32_t maxLaneCount = 0;
  1855. for (uint32_t i = 0; i < appendCount; ++i) {
  1856. maxActiveLaneCount = std::max(maxActiveLaneCount, values[i].sum1);
  1857. maxLaneCount = std::max(maxLaneCount, values[i].laneCount);
  1858. }
  1859. uint32_t peerOfHelperLanes = 0;
  1860. for (uint32_t i = 0; i < appendCount; ++i) {
  1861. if (values[i].sum1 != maxActiveLaneCount) {
  1862. ++peerOfHelperLanes;
  1863. }
  1864. }
  1865. LogCommentFmt(
  1866. L"Found: %u threads. Waves reported up to %u total lanes, up "
  1867. L"to %u active lanes, and %u threads had helper/inactive lanes.",
  1868. appendCount, maxLaneCount, maxActiveLaneCount, peerOfHelperLanes);
  1869. // Group threads into quad invocations.
  1870. uint32_t singlePixelCount = 0;
  1871. uint32_t multiPixelCount = 0;
  1872. std::unordered_set<uint32_t> ids;
  1873. std::multimap<uint32_t, PerPixelData *> idGroups;
  1874. std::multimap<uint32_t, PerPixelData *> firstIdGroups;
  1875. for (uint32_t i = 0; i < appendCount; ++i) {
  1876. ids.insert(values[i].id);
  1877. idGroups.insert(std::make_pair(values[i].id, &values[i]));
  1878. firstIdGroups.insert(std::make_pair(values[i].firstLaneId, &values[i]));
  1879. }
  1880. for (uint32_t id : ids) {
  1881. if (idGroups.count(id) == 1)
  1882. ++singlePixelCount;
  1883. else
  1884. ++multiPixelCount;
  1885. }
  1886. LogCommentFmt(L"%u pixels were processed by a single thread. %u invocations were for shared pixels.",
  1887. singlePixelCount, multiPixelCount);
  1888. // Multiple threads may have tried to shade the same pixel. (Is this true even if we have only one triangle?)
  1889. // Where every pixel is distinct, it's very straightforward to validate.
  1890. {
  1891. auto cur = firstIdGroups.begin(), end = firstIdGroups.end();
  1892. while (cur != end) {
  1893. bool simpleWave = true;
  1894. uint32_t firstId = (*cur).first;
  1895. auto groupEnd = cur;
  1896. while (groupEnd != end && (*groupEnd).first == firstId) {
  1897. if (idGroups.count((*groupEnd).second->id) > 1)
  1898. simpleWave = false;
  1899. ++groupEnd;
  1900. }
  1901. if (simpleWave) {
  1902. // Break the wave into quads.
  1903. struct QuadData {
  1904. unsigned count;
  1905. PerPixelData *data[4];
  1906. };
  1907. std::map<uint32_t, QuadData> quads;
  1908. for (auto i = cur; i != groupEnd; ++i) {
  1909. // assuming that it is a simple wave, idGroups has a unique id for each entry.
  1910. uint32_t laneId = (*i).second->id;
  1911. uint32_t laneIds[4] = {(*i).second->id0, (*i).second->id1,
  1912. (*i).second->id2, (*i).second->id3};
  1913. // Since this is a simple wave, each lane has an unique id and
  1914. // therefore should not have any ids in there.
  1915. VERIFY_IS_TRUE(quads.find(laneId) == quads.end());
  1916. // check if QuadReadLaneAt is returning same values in a single quad.
  1917. bool newQuad = true;
  1918. for (unsigned quadIndex = 0; quadIndex < 4; ++quadIndex) {
  1919. auto match = quads.find(laneIds[quadIndex]);
  1920. if (match != quads.end()) {
  1921. (*match).second.data[(*match).second.count++] = (*i).second;
  1922. newQuad = false;
  1923. break;
  1924. }
  1925. auto quadMemberData = idGroups.find(laneIds[quadIndex]);
  1926. if (quadMemberData != idGroups.end()) {
  1927. VERIFY_IS_TRUE((*quadMemberData).second->id0 == laneIds[0]);
  1928. VERIFY_IS_TRUE((*quadMemberData).second->id1 == laneIds[1]);
  1929. VERIFY_IS_TRUE((*quadMemberData).second->id2 == laneIds[2]);
  1930. VERIFY_IS_TRUE((*quadMemberData).second->id3 == laneIds[3]);
  1931. }
  1932. }
  1933. if (newQuad) {
  1934. QuadData qdata;
  1935. qdata.count = 1;
  1936. qdata.data[0] = (*i).second;
  1937. quads.insert(std::make_pair(laneId, qdata));
  1938. }
  1939. }
  1940. for (auto quadPair : quads) {
  1941. unsigned count = quadPair.second.count;
  1942. // There could be only one pixel data on the edge of the triangle
  1943. if (count < 2) continue;
  1944. PerPixelData **data = quadPair.second.data;
  1945. bool isTop[4];
  1946. bool isLeft[4];
  1947. PerPixelData helperData;
  1948. memset(&helperData, sizeof(helperData), 0);
  1949. PerPixelData *layout[4]; // tl,tr,bl,br
  1950. memset(layout, sizeof(layout), 0);
  1951. auto fnToLayout = [&](bool top, bool left) -> PerPixelData ** {
  1952. int idx = top ? 0 : 2;
  1953. idx += left ? 0 : 1;
  1954. return &layout[idx];
  1955. };
  1956. auto fnToLayoutData = [&](bool top, bool left) -> PerPixelData * {
  1957. PerPixelData **pResult = fnToLayout(top, left);
  1958. if (*pResult == nullptr) return &helperData;
  1959. return *pResult;
  1960. };
  1961. VERIFY_IS_TRUE(count <= 4);
  1962. if (count == 2) {
  1963. isTop[0] = data[0]->position.y < data[1]->position.y;
  1964. isTop[1] = (data[0]->position.y == data[1]->position.y) ? isTop[0] : !isTop[0];
  1965. isLeft[0] = data[0]->position.x < data[1]->position.x;
  1966. isLeft[1] = (data[0]->position.x == data[1]->position.x) ? isLeft[0] : !isLeft[0];
  1967. }
  1968. else {
  1969. // with at least three samples, we have distinct x and y coordinates.
  1970. float left = std::min(data[0]->position.x, data[1]->position.x);
  1971. left = std::min(data[2]->position.x, left);
  1972. float top = std::min(data[0]->position.y, data[1]->position.y);
  1973. top = std::min(data[2]->position.y, top);
  1974. for (unsigned i = 0; i < count; ++i) {
  1975. isTop[i] = data[i]->position.y == top;
  1976. isLeft[i] = data[i]->position.x == left;
  1977. }
  1978. }
  1979. for (unsigned i = 0; i < count; ++i) {
  1980. *(fnToLayout(isTop[i], isLeft[i])) = data[i];
  1981. }
  1982. // Finally, we have a proper quad reconstructed. Validate.
  1983. for (unsigned i = 0; i < count; ++i) {
  1984. PerPixelData *d = data[i];
  1985. VERIFY_ARE_EQUAL(d->id0, fnToLayoutData(true, true)->id);
  1986. VERIFY_ARE_EQUAL(d->id1, fnToLayoutData(true, false)->id);
  1987. VERIFY_ARE_EQUAL(d->id2, fnToLayoutData(false, true)->id);
  1988. VERIFY_ARE_EQUAL(d->id3, fnToLayoutData(false, false)->id);
  1989. VERIFY_ARE_EQUAL(d->acrossX, fnToLayoutData(isTop[i], !isLeft[i])->id);
  1990. VERIFY_ARE_EQUAL(d->acrossY, fnToLayoutData(!isTop[i], isLeft[i])->id);
  1991. VERIFY_ARE_EQUAL(d->acrossDiag, fnToLayoutData(!isTop[i], !isLeft[i])->id);
  1992. VERIFY_ARE_EQUAL(d->quadActiveCount, count);
  1993. }
  1994. }
  1995. }
  1996. cur = groupEnd;
  1997. }
  1998. }
  1999. // TODO: provide validation for quads where the same pixel was shaded multiple times
  2000. //
  2001. // Consider: for pixels that were shaded multiple times, check whether
  2002. // some grouping of threads into quads satisfies all value requirements.
  2003. }
  2004. }
  2005. struct ShaderOpTestResult {
  2006. st::ShaderOp *ShaderOp;
  2007. std::shared_ptr<st::ShaderOpSet> ShaderOpSet;
  2008. std::shared_ptr<st::ShaderOpTest> Test;
  2009. };
  2010. struct SPrimitives {
  2011. float f_float;
  2012. float f_float2;
  2013. float f_float_o;
  2014. float f_float2_o;
  2015. };
  2016. std::shared_ptr<ShaderOpTestResult>
  2017. RunShaderOpTestAfterParse(ID3D12Device *pDevice, dxc::DxcDllSupport &support,
  2018. IStream *pStream, LPCSTR pName,
  2019. st::ShaderOpTest::TInitCallbackFn pInitCallback, std::shared_ptr<st::ShaderOpSet> ShaderOpSet) {
  2020. DXASSERT_NOMSG(pStream != nullptr);
  2021. st::ShaderOp *pShaderOp;
  2022. if (pName == nullptr) {
  2023. if (ShaderOpSet->ShaderOps.size() != 1) {
  2024. VERIFY_FAIL(L"Expected a single shader operation.");
  2025. }
  2026. pShaderOp = ShaderOpSet->ShaderOps[0].get();
  2027. }
  2028. else {
  2029. pShaderOp = ShaderOpSet->GetShaderOp(pName);
  2030. }
  2031. if (pShaderOp == nullptr) {
  2032. std::string msg = "Unable to find shader op ";
  2033. msg += pName;
  2034. msg += "; available ops";
  2035. const char sep = ':';
  2036. for (auto &pAvailOp : ShaderOpSet->ShaderOps) {
  2037. msg += sep;
  2038. msg += pAvailOp->Name ? pAvailOp->Name : "[n/a]";
  2039. }
  2040. CA2W msgWide(msg.c_str());
  2041. VERIFY_FAIL(msgWide.m_psz);
  2042. }
  2043. // This won't actually be used since we're supplying the device,
  2044. // but let's make it consistent.
  2045. pShaderOp->UseWarpDevice = GetTestParamUseWARP(true);
  2046. std::shared_ptr<st::ShaderOpTest> test = std::make_shared<st::ShaderOpTest>();
  2047. test->SetDxcSupport(&support);
  2048. test->SetInitCallback(pInitCallback);
  2049. test->SetDevice(pDevice);
  2050. test->RunShaderOp(pShaderOp);
  2051. std::shared_ptr<ShaderOpTestResult> result =
  2052. std::make_shared<ShaderOpTestResult>();
  2053. result->ShaderOpSet = ShaderOpSet;
  2054. result->Test = test;
  2055. result->ShaderOp = pShaderOp;
  2056. return result;
  2057. }
  2058. std::shared_ptr<ShaderOpTestResult>
  2059. RunShaderOpTest(ID3D12Device *pDevice, dxc::DxcDllSupport &support,
  2060. IStream *pStream, LPCSTR pName,
  2061. st::ShaderOpTest::TInitCallbackFn pInitCallback) {
  2062. DXASSERT_NOMSG(pStream != nullptr);
  2063. std::shared_ptr<st::ShaderOpSet> ShaderOpSet =
  2064. std::make_shared<st::ShaderOpSet>();
  2065. st::ParseShaderOpSetFromStream(pStream, ShaderOpSet.get());
  2066. return RunShaderOpTestAfterParse(pDevice, support, pStream, pName, pInitCallback, ShaderOpSet);
  2067. }
  2068. TEST_F(ExecutionTest, OutOfBoundsTest) {
  2069. WEX::TestExecution::SetVerifyOutput verifySettings(WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  2070. CComPtr<IStream> pStream;
  2071. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  2072. // Single operation test at the moment.
  2073. CComPtr<ID3D12Device> pDevice;
  2074. if (!CreateDevice(&pDevice))
  2075. return;
  2076. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTest(pDevice, m_support, pStream, "OOB", nullptr);
  2077. MappedData data;
  2078. // Read back to CPU and examine contents - should get pure red.
  2079. {
  2080. MappedData data;
  2081. test->Test->GetReadBackData("RTarget", &data);
  2082. const uint32_t *pPixels = (uint32_t *)data.data();
  2083. uint32_t first = *pPixels;
  2084. VERIFY_ARE_EQUAL(0xff0000ff, first); // pure red - only first component is read
  2085. }
  2086. }
  2087. TEST_F(ExecutionTest, SaturateTest) {
  2088. WEX::TestExecution::SetVerifyOutput verifySettings(WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  2089. CComPtr<IStream> pStream;
  2090. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  2091. // Single operation test at the moment.
  2092. CComPtr<ID3D12Device> pDevice;
  2093. if (!CreateDevice(&pDevice))
  2094. return;
  2095. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTest(pDevice, m_support, pStream, "Saturate", nullptr);
  2096. MappedData data;
  2097. test->Test->GetReadBackData("U0", &data);
  2098. const float *pValues = (float *)data.data();
  2099. // Everything is zero except for 1.5f and +Inf, which saturate to 1.0f
  2100. const float ExpectedCases[9] = {
  2101. 0.0f, 0.0f, 0.0f, 0.0f, // -inf, -1.5, -denorm, -0
  2102. 0.0f, 0.0f, 1.0f, 1.0f, // 0, denorm, 1.5f, inf
  2103. 0.0f // nan
  2104. };
  2105. for (size_t i = 0; i < _countof(ExpectedCases); ++i) {
  2106. VERIFY_IS_TRUE(ifdenorm_flushf_eq(*pValues, ExpectedCases[i]));
  2107. ++pValues;
  2108. }
  2109. }
  2110. void ExecutionTest::BasicTriangleTestSetup(LPCSTR ShaderOpName, LPCWSTR FileName) {
  2111. WEX::TestExecution::SetVerifyOutput verifySettings(WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  2112. CComPtr<IStream> pStream;
  2113. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  2114. // Single operation test at the moment.
  2115. CComPtr<ID3D12Device> pDevice;
  2116. if (!CreateDevice(&pDevice))
  2117. return;
  2118. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTest(pDevice, m_support, pStream, ShaderOpName, nullptr);
  2119. MappedData data;
  2120. D3D12_RESOURCE_DESC &D = test->ShaderOp->GetResourceByName("RTarget")->Desc;
  2121. UINT width = (UINT64)D.Width;
  2122. UINT height = (UINT64)D.Height;
  2123. test->Test->GetReadBackData("RTarget", &data);
  2124. const uint32_t *pPixels = (uint32_t *)data.data();
  2125. if (SaveImages()) {
  2126. SavePixelsToFile(pPixels, DXGI_FORMAT_R8G8B8A8_UNORM, 320, 200, FileName);
  2127. }
  2128. uint32_t top = pPixels[width / 2]; // Top center.
  2129. uint32_t mid = pPixels[width / 2 + width * (height / 2)]; // Middle center.
  2130. VERIFY_ARE_EQUAL(0xff663300, top); // clear color
  2131. VERIFY_ARE_EQUAL(0xffffffff, mid); // white
  2132. // This is the basic validation test for shader operations, so it's good to
  2133. // check this here at least for this one test case.
  2134. data.reset();
  2135. test.reset();
  2136. ReportLiveObjects();
  2137. }
  2138. TEST_F(ExecutionTest, BasicTriangleOpTest) {
  2139. BasicTriangleTestSetup("Triangle", L"basic-triangle.bmp");
  2140. }
  2141. TEST_F(ExecutionTest, BasicTriangleOpTestHalf) {
  2142. BasicTriangleTestSetup("TriangleHalf", L"basic-triangle-half.bmp");
  2143. }
  2144. // Rendering two right triangles forming a square and assigning a texture value
  2145. // for each pixel to calculate derivates.
  2146. TEST_F(ExecutionTest, PartialDerivTest) {
  2147. WEX::TestExecution::SetVerifyOutput verifySettings(WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  2148. CComPtr<IStream> pStream;
  2149. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  2150. CComPtr<ID3D12Device> pDevice;
  2151. if (!CreateDevice(&pDevice))
  2152. return;
  2153. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTest(pDevice, m_support, pStream, "DerivFine", nullptr);
  2154. MappedData data;
  2155. D3D12_RESOURCE_DESC &D = test->ShaderOp->GetResourceByName("RTarget")->Desc;
  2156. UINT width = (UINT64)D.Width;
  2157. UINT height = (UINT64)D.Height;
  2158. UINT pixelSize = GetByteSizeForFormat(D.Format) / 4;
  2159. test->Test->GetReadBackData("RTarget", &data);
  2160. const float *pPixels = (float *)data.data();
  2161. UINT centerIndex = (UINT64)width * height / 2 - width / 2;
  2162. // pixel at the center
  2163. UINT offsetCenter = centerIndex * pixelSize;
  2164. float CenterDDXFine = pPixels[offsetCenter];
  2165. float CenterDDYFine = pPixels[offsetCenter + 1];
  2166. float CenterDDXCoarse = pPixels[offsetCenter + 2];
  2167. float CenterDDYCoarse = pPixels[offsetCenter + 3];
  2168. LogCommentFmt(
  2169. L"center ddx_fine: %8f, ddy_fine: %8f, ddx_coarse: %8f, ddy_coarse: %8f",
  2170. CenterDDXFine, CenterDDYFine, CenterDDXCoarse, CenterDDYCoarse);
  2171. // The texture for the 9 pixels in the center should look like the following
  2172. // 256 32 64
  2173. // 2048 256 512
  2174. // 1 .125 .25
  2175. // In D3D12 there is no guarantee of how the adapter is grouping 2x2 pixels
  2176. // So for fine derivatives there can be up to two possible results for the center pixel,
  2177. // while for coarse derivatives there can be up to six possible results.
  2178. int ulpTolerance = 1;
  2179. // 512 - 256 or 2048 - 256
  2180. bool left = CompareFloatULP(CenterDDXFine, -1792.0f, ulpTolerance);
  2181. VERIFY_IS_TRUE(left || CompareFloatULP(CenterDDXFine, 256.0f, ulpTolerance));
  2182. // 256 - 32 or 256 - .125
  2183. bool top = CompareFloatULP(CenterDDYFine, 224.0f, ulpTolerance);
  2184. VERIFY_IS_TRUE(top || CompareFloatULP(CenterDDYFine, -255.875, ulpTolerance));
  2185. if (top && left) {
  2186. VERIFY_IS_TRUE((CompareFloatULP(CenterDDXCoarse, -224.0f, ulpTolerance) ||
  2187. CompareFloatULP(CenterDDXCoarse, -1792.0f, ulpTolerance)) &&
  2188. (CompareFloatULP(CenterDDYCoarse, 224.0f, ulpTolerance) ||
  2189. CompareFloatULP(CenterDDYCoarse, 1792.0f, ulpTolerance)));
  2190. }
  2191. else if (top) { // top right quad
  2192. VERIFY_IS_TRUE((CompareFloatULP(CenterDDXCoarse, 256.0f, ulpTolerance) ||
  2193. CompareFloatULP(CenterDDXCoarse, 32.0f, ulpTolerance)) &&
  2194. (CompareFloatULP(CenterDDYCoarse, 224.0f, ulpTolerance) ||
  2195. CompareFloatULP(CenterDDYCoarse, 448.0f, ulpTolerance)));
  2196. }
  2197. else if (left) { // bottom left quad
  2198. VERIFY_IS_TRUE((CompareFloatULP(CenterDDXCoarse, -1792.0f, ulpTolerance) ||
  2199. CompareFloatULP(CenterDDXCoarse, -.875f, ulpTolerance)) &&
  2200. (CompareFloatULP(CenterDDYCoarse, -2047.0f, ulpTolerance) ||
  2201. CompareFloatULP(CenterDDYCoarse, -255.875f, ulpTolerance)));
  2202. }
  2203. else { // bottom right
  2204. VERIFY_IS_TRUE((CompareFloatULP(CenterDDXCoarse, 256.0f, ulpTolerance) ||
  2205. CompareFloatULP(CenterDDXCoarse, .125f, ulpTolerance)) &&
  2206. (CompareFloatULP(CenterDDYCoarse, -255.875f, ulpTolerance) ||
  2207. CompareFloatULP(CenterDDYCoarse, -511.75f, ulpTolerance)));
  2208. }
  2209. }
  2210. // Resource structure for data-driven tests.
  2211. struct SUnaryFPOp {
  2212. float input;
  2213. float output;
  2214. };
  2215. struct SBinaryFPOp {
  2216. float input1;
  2217. float input2;
  2218. float output1;
  2219. float output2;
  2220. };
  2221. struct STertiaryFPOp {
  2222. float input1;
  2223. float input2;
  2224. float input3;
  2225. float output;
  2226. };
  2227. struct SUnaryIntOp {
  2228. int input;
  2229. int output;
  2230. };
  2231. struct SUnaryUintOp {
  2232. unsigned int input;
  2233. unsigned int output;
  2234. };
  2235. struct SBinaryIntOp {
  2236. int input1;
  2237. int input2;
  2238. int output1;
  2239. int output2;
  2240. };
  2241. struct STertiaryIntOp {
  2242. int input1;
  2243. int input2;
  2244. int input3;
  2245. int output;
  2246. };
  2247. struct SBinaryUintOp {
  2248. unsigned int input1;
  2249. unsigned int input2;
  2250. unsigned int output1;
  2251. unsigned int output2;
  2252. };
  2253. struct STertiaryUintOp {
  2254. unsigned int input1;
  2255. unsigned int input2;
  2256. unsigned int input3;
  2257. unsigned int output;
  2258. };
  2259. // representation for HLSL float vectors
  2260. struct SDotOp {
  2261. XMFLOAT4 input1;
  2262. XMFLOAT4 input2;
  2263. float o_dot2;
  2264. float o_dot3;
  2265. float o_dot4;
  2266. };
  2267. struct SMsad4 {
  2268. unsigned int ref;
  2269. XMUINT2 src;
  2270. XMUINT4 accum;
  2271. XMUINT4 result;
  2272. };
  2273. // Parameter representation for taef data-driven tests
  2274. struct TableParameter {
  2275. LPCWSTR m_name;
  2276. enum TableParameterType {
  2277. INT8,
  2278. INT16,
  2279. INT32,
  2280. UINT,
  2281. FLOAT,
  2282. HALF,
  2283. DOUBLE,
  2284. STRING,
  2285. BOOL,
  2286. INT8_TABLE,
  2287. INT16_TABLE,
  2288. INT32_TABLE,
  2289. FLOAT_TABLE,
  2290. HALF_TABLE,
  2291. DOUBLE_TABLE,
  2292. STRING_TABLE,
  2293. UINT_TABLE,
  2294. BOOL_TABLE
  2295. };
  2296. TableParameterType m_type;
  2297. bool m_required; // required parameter
  2298. int8_t m_int8;
  2299. int16_t m_int16;
  2300. int m_int32;
  2301. unsigned int m_uint;
  2302. float m_float;
  2303. uint16_t m_half; // no such thing as half type in c++. Use int16 instead
  2304. double m_double;
  2305. bool m_bool;
  2306. WEX::Common::String m_str;
  2307. std::vector<int8_t> m_int8Table;
  2308. std::vector<int16_t> m_int16Table;
  2309. std::vector<int> m_int32Table;
  2310. std::vector<unsigned int> m_uintTable;
  2311. std::vector<float> m_floatTable;
  2312. std::vector<uint16_t> m_halfTable; // no such thing as half type in c++
  2313. std::vector<double> m_doubleTable;
  2314. std::vector<bool> m_boolTable;
  2315. std::vector<WEX::Common::String> m_StringTable;
  2316. };
  2317. class TableParameterHandler {
  2318. public:
  2319. TableParameter* m_table;
  2320. size_t m_tableSize;
  2321. TableParameterHandler(TableParameter *pTable, size_t size) : m_table(pTable), m_tableSize(size) {}
  2322. TableParameter* GetTableParamByName(LPCWSTR name) {
  2323. for (size_t i = 0; i < m_tableSize; ++i) {
  2324. if (_wcsicmp(name, m_table[i].m_name) == 0) {
  2325. return &m_table[i];
  2326. }
  2327. }
  2328. DXASSERT(false, "Invalid Table Parameter Name %s", name);
  2329. return nullptr;
  2330. }
  2331. void clearTableParameter() {
  2332. for (size_t i = 0; i < m_tableSize; ++i) {
  2333. m_table[i].m_int32 = 0;
  2334. m_table[i].m_uint = 0;
  2335. m_table[i].m_double = 0;
  2336. m_table[i].m_bool = false;
  2337. m_table[i].m_str = WEX::Common::String();
  2338. }
  2339. }
  2340. template <class T1>
  2341. std::vector<T1> *GetDataArray(LPCWSTR name) {
  2342. return nullptr;
  2343. }
  2344. template <>
  2345. std::vector<int> *GetDataArray(LPCWSTR name) {
  2346. for (size_t i = 0; i < m_tableSize; ++i) {
  2347. if (_wcsicmp(name, m_table[i].m_name) == 0) {
  2348. return &(m_table[i].m_int32Table);
  2349. }
  2350. }
  2351. DXASSERT(false, "Invalid Table Parameter Name %s", name);
  2352. return nullptr;
  2353. }
  2354. template <>
  2355. std::vector<int8_t> *GetDataArray(LPCWSTR name) {
  2356. for (size_t i = 0; i < m_tableSize; ++i) {
  2357. if (_wcsicmp(name, m_table[i].m_name) == 0) {
  2358. return &(m_table[i].m_int8Table);
  2359. }
  2360. }
  2361. DXASSERT(false, "Invalid Table Parameter Name %s", name);
  2362. return nullptr;
  2363. }
  2364. template <>
  2365. std::vector<int16_t> *GetDataArray(LPCWSTR name) {
  2366. for (size_t i = 0; i < m_tableSize; ++i) {
  2367. if (_wcsicmp(name, m_table[i].m_name) == 0) {
  2368. return &(m_table[i].m_int16Table);
  2369. }
  2370. }
  2371. DXASSERT(false, "Invalid Table Parameter Name %s", name);
  2372. return nullptr;
  2373. }
  2374. template <>
  2375. std::vector<unsigned int> *GetDataArray(LPCWSTR name) {
  2376. for (size_t i = 0; i < m_tableSize; ++i) {
  2377. if (_wcsicmp(name, m_table[i].m_name) == 0) {
  2378. return &(m_table[i].m_uintTable);
  2379. }
  2380. }
  2381. DXASSERT(false, "Invalid Table Parameter Name %s", name);
  2382. return nullptr;
  2383. }
  2384. template <>
  2385. std::vector<float> *GetDataArray(LPCWSTR name) {
  2386. for (size_t i = 0; i < m_tableSize; ++i) {
  2387. if (_wcsicmp(name, m_table[i].m_name) == 0) {
  2388. return &(m_table[i].m_floatTable);
  2389. }
  2390. }
  2391. DXASSERT(false, "Invalid Table Parameter Name %s", name);
  2392. return nullptr;
  2393. }
  2394. // TODO: uin16_t may be used to represent two different types when we introduce uint16
  2395. template <>
  2396. std::vector<uint16_t> *GetDataArray(LPCWSTR name) {
  2397. for (size_t i = 0; i < m_tableSize; ++i) {
  2398. if (_wcsicmp(name, m_table[i].m_name) == 0) {
  2399. return &(m_table[i].m_halfTable);
  2400. }
  2401. }
  2402. DXASSERT(false, "Invalid Table Parameter Name %s", name);
  2403. return nullptr;
  2404. }
  2405. template <>
  2406. std::vector<double> *GetDataArray(LPCWSTR name) {
  2407. for (size_t i = 0; i < m_tableSize; ++i) {
  2408. if (_wcsicmp(name, m_table[i].m_name) == 0) {
  2409. return &(m_table[i].m_doubleTable);
  2410. }
  2411. }
  2412. DXASSERT(false, "Invalid Table Parameter Name %s", name);
  2413. return nullptr;
  2414. }
  2415. template <>
  2416. std::vector<bool> *GetDataArray(LPCWSTR name) {
  2417. for (size_t i = 0; i < m_tableSize; ++i) {
  2418. if (_wcsicmp(name, m_table[i].m_name) == 0) {
  2419. return &(m_table[i].m_boolTable);
  2420. }
  2421. }
  2422. DXASSERT(false, "Invalid Table Parameter Name %s", name);
  2423. return nullptr;
  2424. }
  2425. };
  2426. static TableParameter UnaryFPOpParameters[] = {
  2427. { L"ShaderOp.Target", TableParameter::STRING, true },
  2428. { L"ShaderOp.Text", TableParameter::STRING, true },
  2429. { L"Validation.Input1", TableParameter::STRING_TABLE, true },
  2430. { L"Validation.Expected1", TableParameter::STRING_TABLE, true },
  2431. { L"Validation.Type", TableParameter::STRING, true },
  2432. { L"Validation.Tolerance", TableParameter::DOUBLE, true },
  2433. { L"Warp.Version", TableParameter::UINT, false }
  2434. };
  2435. static TableParameter BinaryFPOpParameters[] = {
  2436. { L"ShaderOp.Target", TableParameter::STRING, true },
  2437. { L"ShaderOp.Text", TableParameter::STRING, true },
  2438. { L"Validation.Input1", TableParameter::STRING_TABLE, true },
  2439. { L"Validation.Input2", TableParameter::STRING_TABLE, true },
  2440. { L"Validation.Expected1", TableParameter::STRING_TABLE, true },
  2441. { L"Validation.Expected2", TableParameter::STRING_TABLE, false },
  2442. { L"Validation.Type", TableParameter::STRING, true },
  2443. { L"Validation.Tolerance", TableParameter::DOUBLE, true },
  2444. };
  2445. static TableParameter TertiaryFPOpParameters[] = {
  2446. { L"ShaderOp.Target", TableParameter::STRING, true },
  2447. { L"ShaderOp.Text", TableParameter::STRING, true },
  2448. { L"Validation.Input1", TableParameter::STRING_TABLE, true },
  2449. { L"Validation.Input2", TableParameter::STRING_TABLE, true },
  2450. { L"Validation.Input3", TableParameter::STRING_TABLE, true },
  2451. { L"Validation.Expected1", TableParameter::STRING_TABLE, true },
  2452. { L"Validation.Type", TableParameter::STRING, true },
  2453. { L"Validation.Tolerance", TableParameter::DOUBLE, true },
  2454. };
  2455. static TableParameter UnaryIntOpParameters[] = {
  2456. { L"ShaderOp.Target", TableParameter::STRING, true },
  2457. { L"ShaderOp.Text", TableParameter::STRING, true },
  2458. { L"Validation.Input1", TableParameter::INT32_TABLE, true },
  2459. { L"Validation.Expected1", TableParameter::INT32_TABLE, true },
  2460. { L"Validation.Tolerance", TableParameter::INT32, true },
  2461. };
  2462. static TableParameter UnaryUintOpParameters[] = {
  2463. { L"ShaderOp.Target", TableParameter::STRING, true },
  2464. { L"ShaderOp.Text", TableParameter::STRING, true },
  2465. { L"Validation.Input1", TableParameter::UINT_TABLE, true },
  2466. { L"Validation.Expected1", TableParameter::UINT_TABLE, true },
  2467. { L"Validation.Tolerance", TableParameter::INT32, true },
  2468. };
  2469. static TableParameter BinaryIntOpParameters[] = {
  2470. { L"ShaderOp.Target", TableParameter::STRING, true },
  2471. { L"ShaderOp.Text", TableParameter::STRING, true },
  2472. { L"Validation.Input1", TableParameter::INT32_TABLE, true },
  2473. { L"Validation.Input2", TableParameter::INT32_TABLE, true },
  2474. { L"Validation.Expected1", TableParameter::INT32_TABLE, true },
  2475. { L"Validation.Expected2", TableParameter::INT32_TABLE, false },
  2476. { L"Validation.Tolerance", TableParameter::INT32, true },
  2477. };
  2478. static TableParameter TertiaryIntOpParameters[] = {
  2479. { L"ShaderOp.Target", TableParameter::STRING, true },
  2480. { L"ShaderOp.Text", TableParameter::STRING, true },
  2481. { L"Validation.Input1", TableParameter::INT32_TABLE, true },
  2482. { L"Validation.Input2", TableParameter::INT32_TABLE, true },
  2483. { L"Validation.Input3", TableParameter::INT32_TABLE, true },
  2484. { L"Validation.Expected1", TableParameter::INT32_TABLE, true },
  2485. { L"Validation.Tolerance", TableParameter::INT32, true },
  2486. };
  2487. static TableParameter BinaryUintOpParameters[] = {
  2488. { L"ShaderOp.Target", TableParameter::STRING, true },
  2489. { L"ShaderOp.Text", TableParameter::STRING, true },
  2490. { L"Validation.Input1", TableParameter::UINT_TABLE, true },
  2491. { L"Validation.Input2", TableParameter::UINT_TABLE, true },
  2492. { L"Validation.Expected1", TableParameter::UINT_TABLE, true },
  2493. { L"Validation.Expected2", TableParameter::UINT_TABLE, false },
  2494. { L"Validation.Tolerance", TableParameter::INT32, true },
  2495. };
  2496. static TableParameter TertiaryUintOpParameters[] = {
  2497. { L"ShaderOp.Target", TableParameter::STRING, true },
  2498. { L"ShaderOp.Text", TableParameter::STRING, true },
  2499. { L"Validation.Input1", TableParameter::UINT_TABLE, true },
  2500. { L"Validation.Input2", TableParameter::UINT_TABLE, true },
  2501. { L"Validation.Input3", TableParameter::UINT_TABLE, true },
  2502. { L"Validation.Expected1", TableParameter::UINT_TABLE, true },
  2503. { L"Validation.Tolerance", TableParameter::INT32, true },
  2504. };
  2505. static TableParameter DotOpParameters[] = {
  2506. { L"ShaderOp.Target", TableParameter::STRING, true },
  2507. { L"ShaderOp.Text", TableParameter::STRING, true },
  2508. { L"Validation.Input1", TableParameter::STRING_TABLE, true },
  2509. { L"Validation.Input2", TableParameter::STRING_TABLE, true },
  2510. { L"Validation.Expected1", TableParameter::STRING_TABLE, true },
  2511. { L"Validation.Expected2", TableParameter::STRING_TABLE, true },
  2512. { L"Validation.Expected3", TableParameter::STRING_TABLE, true },
  2513. { L"Validation.Type", TableParameter::STRING, true },
  2514. { L"Validation.Tolerance", TableParameter::DOUBLE, true },
  2515. };
  2516. static TableParameter Msad4OpParameters[] = {
  2517. { L"ShaderOp.Text", TableParameter::STRING, true },
  2518. { L"Validation.Tolerance", TableParameter::DOUBLE, true },
  2519. { L"Validation.Input1", TableParameter::UINT_TABLE, true},
  2520. { L"Validation.Input2", TableParameter::STRING_TABLE, true },
  2521. { L"Validation.Input3", TableParameter::STRING_TABLE, true },
  2522. { L"Validation.Expected1", TableParameter::STRING_TABLE, true }
  2523. };
  2524. static TableParameter WaveIntrinsicsActiveIntParameters[] = {
  2525. { L"ShaderOp.Name", TableParameter::STRING, true },
  2526. { L"ShaderOp.Text", TableParameter::STRING, true },
  2527. { L"Validation.NumInputSet", TableParameter::UINT, true },
  2528. { L"Validation.InputSet1", TableParameter::INT32_TABLE, true },
  2529. { L"Validation.InputSet2", TableParameter::INT32_TABLE, false },
  2530. { L"Validation.InputSet3", TableParameter::INT32_TABLE, false },
  2531. { L"Validation.InputSet4", TableParameter::INT32_TABLE, false }
  2532. };
  2533. static TableParameter WaveIntrinsicsPrefixIntParameters[] = {
  2534. { L"ShaderOp.Name", TableParameter::STRING, true },
  2535. { L"ShaderOp.Text", TableParameter::STRING, true },
  2536. { L"Validation.NumInputSet", TableParameter::UINT, true },
  2537. { L"Validation.InputSet1", TableParameter::INT32_TABLE, true },
  2538. { L"Validation.InputSet2", TableParameter::INT32_TABLE, false },
  2539. { L"Validation.InputSet3", TableParameter::INT32_TABLE, false },
  2540. { L"Validation.InputSet4", TableParameter::INT32_TABLE, false }
  2541. };
  2542. static TableParameter WaveIntrinsicsActiveUintParameters[] = {
  2543. { L"ShaderOp.Name", TableParameter::STRING, true },
  2544. { L"ShaderOp.Text", TableParameter::STRING, true },
  2545. { L"Validation.NumInputSet", TableParameter::UINT, true },
  2546. { L"Validation.InputSet1", TableParameter::UINT_TABLE, true },
  2547. { L"Validation.InputSet2", TableParameter::UINT_TABLE, false },
  2548. { L"Validation.InputSet3", TableParameter::UINT_TABLE, false },
  2549. { L"Validation.InputSet4", TableParameter::UINT_TABLE, false }
  2550. };
  2551. static TableParameter WaveIntrinsicsPrefixUintParameters[] = {
  2552. { L"ShaderOp.Name", TableParameter::STRING, true },
  2553. { L"ShaderOp.Text", TableParameter::STRING, true },
  2554. { L"Validation.NumInputSet", TableParameter::UINT, true },
  2555. { L"Validation.InputSet1", TableParameter::UINT_TABLE, true },
  2556. { L"Validation.InputSet2", TableParameter::UINT_TABLE, false },
  2557. { L"Validation.InputSet3", TableParameter::UINT_TABLE, false },
  2558. { L"Validation.InputSet4", TableParameter::UINT_TABLE, false }
  2559. };
  2560. static TableParameter WaveIntrinsicsActiveBoolParameters[] = {
  2561. { L"ShaderOp.Name", TableParameter::STRING, true },
  2562. { L"ShaderOp.Text", TableParameter::STRING, true },
  2563. { L"Validation.NumInputSet", TableParameter::UINT, true },
  2564. { L"Validation.InputSet1", TableParameter::BOOL_TABLE, true },
  2565. { L"Validation.InputSet2", TableParameter::BOOL_TABLE, false },
  2566. { L"Validation.InputSet3", TableParameter::BOOL_TABLE, false },
  2567. };
  2568. static TableParameter CBufferTestHalfParameters[] = {
  2569. { L"Validation.InputSet", TableParameter::HALF_TABLE, true },
  2570. };
  2571. static HRESULT ParseDataToFloat(PCWSTR str, float &value) {
  2572. std::wstring wString(str);
  2573. wString.erase(std::remove(wString.begin(), wString.end(), L' '), wString.end());
  2574. PCWSTR wstr = wString.data();
  2575. if (_wcsicmp(wstr, L"NaN") == 0) {
  2576. value = NAN;
  2577. } else if (_wcsicmp(wstr, L"-inf") == 0) {
  2578. value = -(INFINITY);
  2579. } else if (_wcsicmp(wstr, L"inf") == 0) {
  2580. value = INFINITY;
  2581. } else if (_wcsicmp(wstr, L"-denorm") == 0) {
  2582. value = -(FLT_MIN / 2);
  2583. } else if (_wcsicmp(wstr, L"denorm") == 0) {
  2584. value = FLT_MIN / 2;
  2585. } else if (_wcsicmp(wstr, L"-0.0f") == 0 || _wcsicmp(wstr, L"-0.0") == 0 ||
  2586. _wcsicmp(wstr, L"-0") == 0) {
  2587. value = -0.0f;
  2588. } else if (_wcsicmp(wstr, L"0.0f") == 0 || _wcsicmp(wstr, L"0.0") == 0 ||
  2589. _wcsicmp(wstr, L"0") == 0) {
  2590. value = 0.0f;
  2591. } else {
  2592. // evaluate the expression of wstring
  2593. double val = _wtof(wstr);
  2594. if (val == 0) {
  2595. LogErrorFmt(L"Failed to parse parameter %s to float", wstr);
  2596. return E_FAIL;
  2597. }
  2598. value = val;
  2599. }
  2600. return S_OK;
  2601. }
  2602. static HRESULT ParseDataToInt(PCWSTR str, int &value) {
  2603. std::wstring wString(str);
  2604. wString.erase(std::remove(wString.begin(), wString.end(), L' '), wString.end());
  2605. PCWSTR wstr = wString.data();
  2606. // evaluate the expression of string
  2607. if (_wcsicmp(wstr, L"0.0") == 0 || _wcsicmp(wstr, L"0") == 0) {
  2608. value = 0;
  2609. return S_OK;
  2610. }
  2611. int val = _wtoi(wstr);
  2612. if (val == 0) {
  2613. LogErrorFmt(L"Failed to parse parameter %s to int", wstr);
  2614. return E_FAIL;
  2615. }
  2616. value = val;
  2617. return S_OK;
  2618. }
  2619. static HRESULT ParseDataToUint(PCWSTR str, unsigned int &value) {
  2620. std::wstring wString(str);
  2621. wString.erase(std::remove(wString.begin(), wString.end(), L' '), wString.end());
  2622. PCWSTR wstr = wString.data();
  2623. // evaluate the expression of string
  2624. if (_wcsicmp(wstr, L"0") == 0 || _wcsicmp(wstr, L"0x00000000") == 0) {
  2625. value = 0;
  2626. return S_OK;
  2627. }
  2628. wchar_t *end;
  2629. unsigned int val = std::wcstoul(wstr, &end, 0);
  2630. if (val == 0) {
  2631. LogErrorFmt(L"Failed to parse parameter %s to int", wstr);
  2632. return E_FAIL;
  2633. }
  2634. value = val;
  2635. return S_OK;
  2636. }
  2637. static HRESULT ParseDataToVectorFloat(PCWSTR str, float *ptr, size_t count) {
  2638. std::wstring wstr(str);
  2639. size_t curPosition = 0;
  2640. // parse a string of dot product separated by commas
  2641. for (size_t i = 0; i < count; ++i) {
  2642. size_t nextPosition = wstr.find(L",", curPosition);
  2643. if (FAILED(ParseDataToFloat(
  2644. wstr.substr(curPosition, nextPosition - curPosition).data(),
  2645. *(ptr + i)))) {
  2646. return E_FAIL;
  2647. }
  2648. curPosition = nextPosition + 1;
  2649. }
  2650. return S_OK;
  2651. }
  2652. static HRESULT ParseDataToVectorUint(PCWSTR str, unsigned int *ptr, size_t count) {
  2653. std::wstring wstr(str);
  2654. size_t curPosition = 0;
  2655. // parse a string of dot product separated by commas
  2656. for (size_t i = 0; i < count; ++i) {
  2657. size_t nextPosition = wstr.find(L",", curPosition);
  2658. if (FAILED(ParseDataToUint(
  2659. wstr.substr(curPosition, nextPosition - curPosition).data(),
  2660. *(ptr + i)))) {
  2661. return E_FAIL;
  2662. }
  2663. curPosition = nextPosition + 1;
  2664. }
  2665. return S_OK;
  2666. }
  2667. static HRESULT ParseTableRow(TableParameter *table, unsigned int size) {
  2668. for (unsigned int i = 0; i < size; ++i) {
  2669. switch (table[i].m_type) {
  2670. case TableParameter::INT8:
  2671. if (FAILED(WEX::TestExecution::TestData::TryGetValue(table[i].m_name,
  2672. table[i].m_int32)) && table[i].m_required) {
  2673. // TryGetValue does not suppport reading from int16
  2674. LogErrorFmt(L"Failed to get %s", table[i].m_name);
  2675. return E_FAIL;
  2676. }
  2677. table[i].m_int8 = (short)(table[i].m_int32);
  2678. break;
  2679. case TableParameter::INT16:
  2680. if (FAILED(WEX::TestExecution::TestData::TryGetValue(table[i].m_name,
  2681. table[i].m_int32)) && table[i].m_required) {
  2682. // TryGetValue does not suppport reading from int16
  2683. LogErrorFmt(L"Failed to get %s", table[i].m_name);
  2684. return E_FAIL;
  2685. }
  2686. table[i].m_int16 = (short)(table[i].m_int32);
  2687. break;
  2688. case TableParameter::INT32:
  2689. if (FAILED(WEX::TestExecution::TestData::TryGetValue(table[i].m_name,
  2690. table[i].m_int32)) && table[i].m_required) {
  2691. LogErrorFmt(L"Failed to get %s", table[i].m_name);
  2692. return E_FAIL;
  2693. }
  2694. break;
  2695. case TableParameter::UINT:
  2696. if (FAILED(WEX::TestExecution::TestData::TryGetValue(table[i].m_name,
  2697. table[i].m_uint)) && table[i].m_required) {
  2698. LogErrorFmt(L"Failed to get %s", table[i].m_name);
  2699. return E_FAIL;
  2700. }
  2701. break;
  2702. case TableParameter::DOUBLE:
  2703. if (FAILED(WEX::TestExecution::TestData::TryGetValue(
  2704. table[i].m_name, table[i].m_double)) && table[i].m_required) {
  2705. LogErrorFmt(L"Failed to get %s", table[i].m_name);
  2706. return E_FAIL;
  2707. }
  2708. break;
  2709. case TableParameter::STRING:
  2710. if (FAILED(WEX::TestExecution::TestData::TryGetValue(table[i].m_name,
  2711. table[i].m_str)) && table[i].m_required) {
  2712. LogErrorFmt(L"Failed to get %s", table[i].m_name);
  2713. return E_FAIL;
  2714. }
  2715. break;
  2716. case TableParameter::BOOL:
  2717. if (FAILED(WEX::TestExecution::TestData::TryGetValue(table[i].m_name,
  2718. table[i].m_str)) && table[i].m_bool) {
  2719. LogErrorFmt(L"Failed to get %s", table[i].m_name);
  2720. return E_FAIL;
  2721. }
  2722. break;
  2723. case TableParameter::INT8_TABLE: {
  2724. WEX::TestExecution::TestDataArray<int> tempTable;
  2725. if (FAILED(WEX::TestExecution::TestData::TryGetValue(
  2726. table[i].m_name, tempTable)) && table[i].m_required) {
  2727. LogErrorFmt(L"Failed to get %s", table[i].m_name);
  2728. return E_FAIL;
  2729. }
  2730. // TryGetValue does not suppport reading from int8
  2731. table[i].m_int8Table.resize(tempTable.GetSize());
  2732. for (size_t j = 0, end = tempTable.GetSize(); j != end; ++j) {
  2733. table[i].m_int8Table[j] = (char)tempTable[j];
  2734. }
  2735. break;
  2736. }
  2737. case TableParameter::INT16_TABLE: {
  2738. WEX::TestExecution::TestDataArray<int> tempTable;
  2739. if (FAILED(WEX::TestExecution::TestData::TryGetValue(
  2740. table[i].m_name, tempTable)) && table[i].m_required) {
  2741. LogErrorFmt(L"Failed to get %s", table[i].m_name);
  2742. return E_FAIL;
  2743. }
  2744. // TryGetValue does not suppport reading from int8
  2745. table[i].m_int16Table.resize(tempTable.GetSize());
  2746. for (size_t j = 0, end = tempTable.GetSize(); j != end; ++j) {
  2747. table[i].m_int16Table[j] = (int16_t)tempTable[j];
  2748. }
  2749. break;
  2750. }
  2751. case TableParameter::INT32_TABLE: {
  2752. WEX::TestExecution::TestDataArray<int> tempTable;
  2753. if (FAILED(WEX::TestExecution::TestData::TryGetValue(
  2754. table[i].m_name, tempTable)) && table[i].m_required) {
  2755. // TryGetValue does not suppport reading from int8
  2756. LogErrorFmt(L"Failed to get %s", table[i].m_name);
  2757. return E_FAIL;
  2758. }
  2759. table[i].m_int32Table.resize(tempTable.GetSize());
  2760. for (size_t j = 0, end = tempTable.GetSize(); j != end; ++j) {
  2761. table[i].m_int32Table[j] = tempTable[j];
  2762. }
  2763. break;
  2764. }
  2765. case TableParameter::UINT_TABLE: {
  2766. WEX::TestExecution::TestDataArray<unsigned int> tempTable;
  2767. if (FAILED(WEX::TestExecution::TestData::TryGetValue(
  2768. table[i].m_name, tempTable)) && table[i].m_required) {
  2769. // TryGetValue does not suppport reading from int8
  2770. LogErrorFmt(L"Failed to get %s", table[i].m_name);
  2771. return E_FAIL;
  2772. }
  2773. table[i].m_uintTable.resize(tempTable.GetSize());
  2774. for (size_t j = 0, end = tempTable.GetSize(); j != end; ++j) {
  2775. table[i].m_uintTable[j] = tempTable[j];
  2776. }
  2777. break;
  2778. }
  2779. case TableParameter::FLOAT_TABLE: {
  2780. WEX::TestExecution::TestDataArray<WEX::Common::String> tempTable;
  2781. if (FAILED(WEX::TestExecution::TestData::TryGetValue(
  2782. table[i].m_name, tempTable)) && table[i].m_required) {
  2783. // TryGetValue does not suppport reading from int8
  2784. LogErrorFmt(L"Failed to get %s", table[i].m_name);
  2785. return E_FAIL;
  2786. }
  2787. table[i].m_floatTable.resize(tempTable.GetSize());
  2788. for (size_t j = 0, end = tempTable.GetSize(); j != end; ++j) {
  2789. ParseDataToFloat(tempTable[j], table[i].m_floatTable[j]);
  2790. }
  2791. break;
  2792. }
  2793. case TableParameter::HALF_TABLE: {
  2794. WEX::TestExecution::TestDataArray<WEX::Common::String> tempTable;
  2795. if (FAILED(WEX::TestExecution::TestData::TryGetValue(
  2796. table[i].m_name, tempTable)) && table[i].m_required) {
  2797. // TryGetValue does not suppport reading from int8
  2798. LogErrorFmt(L"Failed to get %s", table[i].m_name);
  2799. return E_FAIL;
  2800. }
  2801. table[i].m_halfTable.resize(tempTable.GetSize());
  2802. for (size_t j = 0, end = tempTable.GetSize(); j != end; ++j) {
  2803. float val;
  2804. ParseDataToFloat(tempTable[j], val);
  2805. table[i].m_halfTable[j] = st::ConvertFloat32ToFloat16(val);
  2806. }
  2807. break;
  2808. }
  2809. case TableParameter::DOUBLE_TABLE: {
  2810. WEX::TestExecution::TestDataArray<double> tempTable;
  2811. if (FAILED(WEX::TestExecution::TestData::TryGetValue(
  2812. table[i].m_name, tempTable)) && table[i].m_required) {
  2813. // TryGetValue does not suppport reading from int8
  2814. LogErrorFmt(L"Failed to get %s", table[i].m_name);
  2815. return E_FAIL;
  2816. }
  2817. table[i].m_doubleTable.resize(tempTable.GetSize());
  2818. for (size_t j = 0, end = tempTable.GetSize(); j != end; ++j) {
  2819. table[i].m_doubleTable[j] = tempTable[j];
  2820. }
  2821. break;
  2822. }
  2823. case TableParameter::BOOL_TABLE: {
  2824. WEX::TestExecution::TestDataArray<bool> tempTable;
  2825. if (FAILED(WEX::TestExecution::TestData::TryGetValue(
  2826. table[i].m_name, tempTable)) && table[i].m_required) {
  2827. // TryGetValue does not suppport reading from int8
  2828. LogErrorFmt(L"Failed to get %s", table[i].m_name);
  2829. return E_FAIL;
  2830. }
  2831. table[i].m_boolTable.resize(tempTable.GetSize());
  2832. for (size_t j = 0, end = tempTable.GetSize(); j != end; ++j) {
  2833. table[i].m_boolTable[j] = tempTable[j];
  2834. }
  2835. break;
  2836. }
  2837. case TableParameter::STRING_TABLE: {
  2838. WEX::TestExecution::TestDataArray<WEX::Common::String> tempTable;
  2839. if (FAILED(WEX::TestExecution::TestData::TryGetValue(
  2840. table[i].m_name, tempTable)) && table[i].m_required) {
  2841. // TryGetValue does not suppport reading from int8
  2842. LogErrorFmt(L"Failed to get %s", table[i].m_name);
  2843. return E_FAIL;
  2844. }
  2845. table[i].m_StringTable.resize(tempTable.GetSize());
  2846. for (size_t j = 0, end = tempTable.GetSize(); j != end; ++j) {
  2847. table[i].m_StringTable[j] = tempTable[j];
  2848. }
  2849. break;
  2850. }
  2851. default:
  2852. DXASSERT_NOMSG("Invalid Parameter Type");
  2853. }
  2854. if (errno == ERANGE) {
  2855. LogErrorFmt(L"got out of range value for table %s", table[i].m_name);
  2856. return E_FAIL;
  2857. }
  2858. }
  2859. return S_OK;
  2860. }
  2861. static void VerifyOutputWithExpectedValueInt(int output, int ref, int tolerance) {
  2862. VERIFY_IS_TRUE(output - ref <= tolerance && ref - output <= tolerance);
  2863. }
  2864. static void VerifyOutputWithExpectedValueFloat(float output, float ref, LPCWSTR type, double tolerance) {
  2865. if (_wcsicmp(type, L"Relative") == 0) {
  2866. VERIFY_IS_TRUE(CompareFloatRelativeEpsilon(output, ref, tolerance));
  2867. }
  2868. else if (_wcsicmp(type, L"Epsilon") == 0) {
  2869. VERIFY_IS_TRUE(CompareFloatEpsilon(output, ref, tolerance));
  2870. }
  2871. else if (_wcsicmp(type, L"ULP") == 0) {
  2872. VERIFY_IS_TRUE(CompareFloatULP(output, ref, (int)tolerance));
  2873. }
  2874. else {
  2875. LogErrorFmt(L"Failed to read comparison type %S", type);
  2876. }
  2877. }
  2878. TEST_F(ExecutionTest, UnaryFloatOpTest) {
  2879. WEX::TestExecution::SetVerifyOutput verifySettings(
  2880. WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  2881. CComPtr<IStream> pStream;
  2882. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  2883. CComPtr<ID3D12Device> pDevice;
  2884. if (!CreateDevice(&pDevice)) {
  2885. return;
  2886. }
  2887. // Read data from the table
  2888. int tableSize = sizeof(UnaryFPOpParameters) / sizeof(TableParameter);
  2889. TableParameterHandler handler(UnaryFPOpParameters, tableSize);
  2890. handler.clearTableParameter();
  2891. VERIFY_SUCCEEDED(ParseTableRow(UnaryFPOpParameters, tableSize));
  2892. CW2A Target(handler.GetTableParamByName(L"ShaderOp.Target")->m_str);
  2893. CW2A Text(handler.GetTableParamByName(L"ShaderOp.Text")->m_str);
  2894. unsigned int WarpVersion = handler.GetTableParamByName(L"Warp.Version")->m_uint;
  2895. if (GetTestParamUseWARP(true) && !IsValidWarpDllVersion(WarpVersion)) {
  2896. return;
  2897. }
  2898. std::vector<WEX::Common::String> *Validation_Input =
  2899. &(handler.GetTableParamByName(L"Validation.Input1")->m_StringTable);
  2900. std::vector<WEX::Common::String> *Validation_Expected =
  2901. &(handler.GetTableParamByName(L"Validation.Expected1")->m_StringTable);
  2902. LPCWSTR Validation_Type = handler.GetTableParamByName(L"Validation.Type")->m_str;
  2903. double Validation_Tolerance = handler.GetTableParamByName(L"Validation.Tolerance")->m_double;
  2904. size_t count = Validation_Input->size();
  2905. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTest(
  2906. pDevice, m_support, pStream, "UnaryFPOp",
  2907. // this callbacked is called when the test
  2908. // is creating the resource to run the test
  2909. [&](LPCSTR Name, std::vector<BYTE> &Data, st::ShaderOp *pShaderOp) {
  2910. VERIFY_IS_TRUE(0 == _stricmp(Name, "SUnaryFPOp"));
  2911. size_t size = sizeof(SUnaryFPOp) * count;
  2912. Data.resize(size);
  2913. SUnaryFPOp *pPrimitives = (SUnaryFPOp *)Data.data();
  2914. for (size_t i = 0; i < count; ++i) {
  2915. SUnaryFPOp *p = &pPrimitives[i];
  2916. PCWSTR str = (*Validation_Input)[i % Validation_Input->size()];
  2917. float val;
  2918. VERIFY_SUCCEEDED(ParseDataToFloat(str, val));
  2919. p->input = val;
  2920. }
  2921. // use shader from data table
  2922. pShaderOp->Shaders.at(0).Target = Target.m_psz;
  2923. pShaderOp->Shaders.at(0).Text = Text.m_psz;
  2924. });
  2925. MappedData data;
  2926. test->Test->GetReadBackData("SUnaryFPOp", &data);
  2927. SUnaryFPOp *pPrimitives = (SUnaryFPOp*)data.data();
  2928. WEX::TestExecution::DisableVerifyExceptions dve;
  2929. for (unsigned i = 0; i < count; ++i) {
  2930. SUnaryFPOp *p = &pPrimitives[i];
  2931. LPCWSTR str = (*Validation_Expected)[i % Validation_Expected->size()];
  2932. float val;
  2933. VERIFY_SUCCEEDED(ParseDataToFloat(str, val));
  2934. LogCommentFmt(
  2935. L"element #%u, input = %6.8f, output = %6.8f, expected = %6.8f", i,
  2936. p->input, p->output, val);
  2937. VerifyOutputWithExpectedValueFloat(p->output, val, Validation_Type, Validation_Tolerance);
  2938. }
  2939. }
  2940. TEST_F(ExecutionTest, BinaryFloatOpTest) {
  2941. WEX::TestExecution::SetVerifyOutput verifySettings(
  2942. WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  2943. CComPtr<IStream> pStream;
  2944. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  2945. CComPtr<ID3D12Device> pDevice;
  2946. if (!CreateDevice(&pDevice)) {
  2947. return;
  2948. }
  2949. // Read data from the table
  2950. int tableSize = sizeof(BinaryFPOpParameters) / sizeof(TableParameter);
  2951. TableParameterHandler handler(BinaryFPOpParameters, tableSize);
  2952. handler.clearTableParameter();
  2953. VERIFY_SUCCEEDED(ParseTableRow(BinaryFPOpParameters, tableSize));
  2954. CW2A Target(handler.GetTableParamByName(L"ShaderOp.Target")->m_str);
  2955. CW2A Text(handler.GetTableParamByName(L"ShaderOp.Text")->m_str);
  2956. std::vector<WEX::Common::String> *Validation_Input1 =
  2957. &(handler.GetTableParamByName(L"Validation.Input1")->m_StringTable);
  2958. std::vector<WEX::Common::String> *Validation_Input2 =
  2959. &(handler.GetTableParamByName(L"Validation.Input2")->m_StringTable);
  2960. std::vector<WEX::Common::String> *Validation_Expected1 =
  2961. &(handler.GetTableParamByName(L"Validation.Expected1")->m_StringTable);
  2962. std::vector<WEX::Common::String> *Validation_Expected2 =
  2963. &(handler.GetTableParamByName(L"Validation.Expected2")->m_StringTable);
  2964. LPCWSTR Validation_Type = handler.GetTableParamByName(L"Validation.Type")->m_str;
  2965. double Validation_Tolerance = handler.GetTableParamByName(L"Validation.Tolerance")->m_double;
  2966. size_t count = Validation_Input1->size();
  2967. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTest(
  2968. pDevice, m_support, pStream, "BinaryFPOp",
  2969. // this callbacked is called when the test
  2970. // is creating the resource to run the test
  2971. [&](LPCSTR Name, std::vector<BYTE> &Data, st::ShaderOp *pShaderOp) {
  2972. VERIFY_IS_TRUE(0 == _stricmp(Name, "SBinaryFPOp"));
  2973. size_t size = sizeof(SBinaryFPOp) * count;
  2974. Data.resize(size);
  2975. SBinaryFPOp *pPrimitives = (SBinaryFPOp *)Data.data();
  2976. for (size_t i = 0; i < count; ++i) {
  2977. SBinaryFPOp *p = &pPrimitives[i];
  2978. PCWSTR str1 = (*Validation_Input1)[i % Validation_Input1->size()];
  2979. PCWSTR str2 = (*Validation_Input2)[i % Validation_Input2->size()];
  2980. float val1, val2;
  2981. VERIFY_SUCCEEDED(ParseDataToFloat(str1, val1));
  2982. VERIFY_SUCCEEDED(ParseDataToFloat(str2, val2));
  2983. p->input1 = val1;
  2984. p->input2 = val2;
  2985. }
  2986. // use shader from data table
  2987. pShaderOp->Shaders.at(0).Target = Target.m_psz;
  2988. pShaderOp->Shaders.at(0).Text = Text.m_psz;
  2989. });
  2990. MappedData data;
  2991. test->Test->GetReadBackData("SBinaryFPOp", &data);
  2992. SBinaryFPOp *pPrimitives = (SBinaryFPOp *)data.data();
  2993. WEX::TestExecution::DisableVerifyExceptions dve;
  2994. unsigned numExpected = Validation_Expected2->size() == 0 ? 1 : 2;
  2995. if (numExpected == 2) {
  2996. for (unsigned i = 0; i < count; ++i) {
  2997. SBinaryFPOp *p = &pPrimitives[i];
  2998. LPCWSTR str1 = (*Validation_Expected1)[i % Validation_Expected1->size()];
  2999. LPCWSTR str2 = (*Validation_Expected2)[i % Validation_Expected2->size()];
  3000. float val1, val2;
  3001. VERIFY_SUCCEEDED(ParseDataToFloat(str1, val1));
  3002. VERIFY_SUCCEEDED(ParseDataToFloat(str2, val2));
  3003. LogCommentFmt(L"element #%u, input1 = %6.8f, input2 = %6.8f, output1 = "
  3004. L"%6.8f, expected1 = %6.8f, output2 = %6.8f, expected2 = %6.8f",
  3005. i, p->input1, p->input2, p->output1, val1, p->output2,
  3006. val2);
  3007. VerifyOutputWithExpectedValueFloat(p->output1, val1, Validation_Type,
  3008. Validation_Tolerance);
  3009. VerifyOutputWithExpectedValueFloat(p->output2, val2, Validation_Type,
  3010. Validation_Tolerance);
  3011. }
  3012. }
  3013. else if (numExpected == 1) {
  3014. for (unsigned i = 0; i < count; ++i) {
  3015. SBinaryFPOp *p = &pPrimitives[i];
  3016. LPCWSTR str1 = (*Validation_Expected1)[i % Validation_Expected1->size()];
  3017. float val1;
  3018. VERIFY_SUCCEEDED(ParseDataToFloat(str1, val1));
  3019. LogCommentFmt(L"element #%u, input1 = %6.8f, input2 = %6.8f, output1 = "
  3020. L"%6.8f, expected1 = %6.8f",
  3021. i, p->input1, p->input2, p->output1, val1);
  3022. VerifyOutputWithExpectedValueFloat(p->output1, val1, Validation_Type,
  3023. Validation_Tolerance);
  3024. }
  3025. }
  3026. else {
  3027. LogErrorFmt(L"Unexpected number of expected values for operation %i", numExpected);
  3028. }
  3029. }
  3030. TEST_F(ExecutionTest, TertiaryFloatOpTest) {
  3031. WEX::TestExecution::SetVerifyOutput verifySettings(
  3032. WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  3033. CComPtr<IStream> pStream;
  3034. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  3035. CComPtr<ID3D12Device> pDevice;
  3036. if (!CreateDevice(&pDevice)) {
  3037. return;
  3038. }
  3039. // Read data from the table
  3040. int tableSize = sizeof(TertiaryFPOpParameters) / sizeof(TableParameter);
  3041. TableParameterHandler handler(TertiaryFPOpParameters, tableSize);
  3042. handler.clearTableParameter();
  3043. VERIFY_SUCCEEDED(ParseTableRow(TertiaryFPOpParameters, tableSize));
  3044. CW2A Target(handler.GetTableParamByName(L"ShaderOp.Target")->m_str);
  3045. CW2A Text(handler.GetTableParamByName(L"ShaderOp.Text")->m_str);
  3046. std::vector<WEX::Common::String> *Validation_Input1 =
  3047. &(handler.GetTableParamByName(L"Validation.Input1")->m_StringTable);
  3048. std::vector<WEX::Common::String> *Validation_Input2 =
  3049. &(handler.GetTableParamByName(L"Validation.Input2")->m_StringTable);
  3050. std::vector<WEX::Common::String> *Validation_Input3 =
  3051. &(handler.GetTableParamByName(L"Validation.Input3")->m_StringTable);
  3052. std::vector<WEX::Common::String> *Validation_Expected =
  3053. &(handler.GetTableParamByName(L"Validation.Expected1")->m_StringTable);
  3054. LPCWSTR Validation_Type = handler.GetTableParamByName(L"Validation.Type")->m_str;
  3055. double Validation_Tolerance = handler.GetTableParamByName(L"Validation.Tolerance")->m_double;
  3056. size_t count = Validation_Input1->size();
  3057. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTest(
  3058. pDevice, m_support, pStream, "TertiaryFPOp",
  3059. // this callbacked is called when the test
  3060. // is creating the resource to run the test
  3061. [&](LPCSTR Name, std::vector<BYTE> &Data, st::ShaderOp *pShaderOp) {
  3062. VERIFY_IS_TRUE(0 == _stricmp(Name, "STertiaryFPOp"));
  3063. size_t size = sizeof(STertiaryFPOp) * count;
  3064. Data.resize(size);
  3065. STertiaryFPOp *pPrimitives = (STertiaryFPOp *)Data.data();
  3066. for (size_t i = 0; i < count; ++i) {
  3067. STertiaryFPOp *p = &pPrimitives[i];
  3068. PCWSTR str1 = (*Validation_Input1)[i % Validation_Input1->size()];
  3069. PCWSTR str2 = (*Validation_Input2)[i % Validation_Input2->size()];
  3070. PCWSTR str3 = (*Validation_Input3)[i % Validation_Input3->size()];
  3071. float val1, val2, val3;
  3072. VERIFY_SUCCEEDED(ParseDataToFloat(str1, val1));
  3073. VERIFY_SUCCEEDED(ParseDataToFloat(str2, val2));
  3074. VERIFY_SUCCEEDED(ParseDataToFloat(str3, val3));
  3075. p->input1 = val1;
  3076. p->input2 = val2;
  3077. p->input3 = val3;
  3078. }
  3079. // use shader from data table
  3080. pShaderOp->Shaders.at(0).Target = Target.m_psz;
  3081. pShaderOp->Shaders.at(0).Text = Text.m_psz;
  3082. });
  3083. MappedData data;
  3084. test->Test->GetReadBackData("STertiaryFPOp", &data);
  3085. STertiaryFPOp *pPrimitives = (STertiaryFPOp *)data.data();
  3086. WEX::TestExecution::DisableVerifyExceptions dve;
  3087. for (unsigned i = 0; i < count; ++i) {
  3088. STertiaryFPOp *p = &pPrimitives[i];
  3089. LPCWSTR str = (*Validation_Expected)[i % Validation_Expected->size()];
  3090. float val;
  3091. VERIFY_SUCCEEDED(ParseDataToFloat(str, val));
  3092. LogCommentFmt(L"element #%u, input1 = %6.8f, input2 = %6.8f, input3 = %6.8f, output1 = "
  3093. L"%6.8f, expected = %6.8f",
  3094. i, p->input1, p->input2, p->input3, p->output, val);
  3095. VerifyOutputWithExpectedValueFloat(p->output, val, Validation_Type,
  3096. Validation_Tolerance);
  3097. }
  3098. }
  3099. TEST_F(ExecutionTest, UnaryIntOpTest) {
  3100. WEX::TestExecution::SetVerifyOutput verifySettings(
  3101. WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  3102. CComPtr<IStream> pStream;
  3103. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  3104. CComPtr<ID3D12Device> pDevice;
  3105. if (!CreateDevice(&pDevice)) {
  3106. return;
  3107. }
  3108. // Read data from the table
  3109. int tableSize = sizeof(UnaryIntOpParameters) / sizeof(TableParameter);
  3110. TableParameterHandler handler(UnaryIntOpParameters, tableSize);
  3111. handler.clearTableParameter();
  3112. VERIFY_SUCCEEDED(ParseTableRow(UnaryIntOpParameters, tableSize));
  3113. CW2A Target(handler.GetTableParamByName(L"ShaderOp.Target")->m_str);
  3114. CW2A Text(handler.GetTableParamByName(L"ShaderOp.Text")->m_str);
  3115. std::vector<int> *Validation_Input =
  3116. &handler.GetTableParamByName(L"Validation.Input1")->m_int32Table;
  3117. std::vector<int> *Validation_Expected =
  3118. &handler.GetTableParamByName(L"Validation.Expected1")->m_int32Table;
  3119. int Validation_Tolerance = handler.GetTableParamByName(L"Validation.Tolerance")->m_int32;
  3120. size_t count = Validation_Input->size();
  3121. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTest(
  3122. pDevice, m_support, pStream, "UnaryIntOp",
  3123. // this callbacked is called when the test
  3124. // is creating the resource to run the test
  3125. [&](LPCSTR Name, std::vector<BYTE> &Data, st::ShaderOp *pShaderOp) {
  3126. VERIFY_IS_TRUE(0 == _stricmp(Name, "SUnaryIntOp"));
  3127. size_t size = sizeof(SUnaryIntOp) * count;
  3128. Data.resize(size);
  3129. SUnaryIntOp *pPrimitives = (SUnaryIntOp *)Data.data();
  3130. for (size_t i = 0; i < count; ++i) {
  3131. SUnaryIntOp *p = &pPrimitives[i];
  3132. int val = (*Validation_Input)[i % Validation_Input->size()];
  3133. p->input = val;
  3134. }
  3135. // use shader data table
  3136. pShaderOp->Shaders.at(0).Target = Target.m_psz;
  3137. pShaderOp->Shaders.at(0).Text = Text.m_psz;
  3138. });
  3139. MappedData data;
  3140. test->Test->GetReadBackData("SUnaryIntOp", &data);
  3141. SUnaryIntOp *pPrimitives = (SUnaryIntOp *)data.data();
  3142. WEX::TestExecution::DisableVerifyExceptions dve;
  3143. for (unsigned i = 0; i < count; ++i) {
  3144. SUnaryIntOp *p = &pPrimitives[i];
  3145. int val = (*Validation_Expected)[i % Validation_Expected->size()];
  3146. LogCommentFmt(L"element #%u, input = %11i(0x%08x), output = %11i(0x%08x), "
  3147. L"expected = %11i(0x%08x)",
  3148. i, p->input, p->input, p->output, p->output, val, val);
  3149. VerifyOutputWithExpectedValueInt(p->output, val, Validation_Tolerance);
  3150. }
  3151. }
  3152. TEST_F(ExecutionTest, UnaryUintOpTest) {
  3153. WEX::TestExecution::SetVerifyOutput verifySettings(
  3154. WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  3155. CComPtr<IStream> pStream;
  3156. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  3157. CComPtr<ID3D12Device> pDevice;
  3158. if (!CreateDevice(&pDevice)) {
  3159. return;
  3160. }
  3161. // Read data from the table
  3162. int tableSize = sizeof(UnaryUintOpParameters) / sizeof(TableParameter);
  3163. TableParameterHandler handler(UnaryUintOpParameters, tableSize);
  3164. handler.clearTableParameter();
  3165. VERIFY_SUCCEEDED(ParseTableRow(UnaryUintOpParameters, tableSize));
  3166. CW2A Target(handler.GetTableParamByName(L"ShaderOp.Target")->m_str);
  3167. CW2A Text(handler.GetTableParamByName(L"ShaderOp.Text")->m_str);
  3168. std::vector<unsigned int> *Validation_Input =
  3169. &handler.GetTableParamByName(L"Validation.Input1")->m_uintTable;
  3170. std::vector<unsigned int> *Validation_Expected =
  3171. &handler.GetTableParamByName(L"Validation.Expected1")->m_uintTable;
  3172. int Validation_Tolerance = handler.GetTableParamByName(L"Validation.Tolerance")->m_int32;
  3173. size_t count = Validation_Input->size();
  3174. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTest(
  3175. pDevice, m_support, pStream, "UnaryUintOp",
  3176. // this callbacked is called when the test
  3177. // is creating the resource to run the test
  3178. [&](LPCSTR Name, std::vector<BYTE> &Data, st::ShaderOp *pShaderOp) {
  3179. VERIFY_IS_TRUE(0 == _stricmp(Name, "SUnaryUintOp"));
  3180. size_t size = sizeof(SUnaryUintOp) * count;
  3181. Data.resize(size);
  3182. SUnaryUintOp *pPrimitives = (SUnaryUintOp *)Data.data();
  3183. for (size_t i = 0; i < count; ++i) {
  3184. SUnaryUintOp *p = &pPrimitives[i];
  3185. unsigned int val = (*Validation_Input)[i % Validation_Input->size()];
  3186. p->input = val;
  3187. }
  3188. // use shader data table
  3189. pShaderOp->Shaders.at(0).Target = Target.m_psz;
  3190. pShaderOp->Shaders.at(0).Text = Text.m_psz;
  3191. });
  3192. MappedData data;
  3193. test->Test->GetReadBackData("SUnaryUintOp", &data);
  3194. SUnaryUintOp *pPrimitives = (SUnaryUintOp *)data.data();
  3195. WEX::TestExecution::DisableVerifyExceptions dve;
  3196. for (unsigned i = 0; i < count; ++i) {
  3197. SUnaryUintOp *p = &pPrimitives[i];
  3198. unsigned int val = (*Validation_Expected)[i % Validation_Expected->size()];
  3199. LogCommentFmt(L"element #%u, input = %11u(0x%08x), output = %11u(0x%08x), "
  3200. L"expected = %11u(0x%08x)",
  3201. i, p->input, p->input, p->output, p->output, val, val);
  3202. VerifyOutputWithExpectedValueInt(p->output, val, Validation_Tolerance);
  3203. }
  3204. }
  3205. TEST_F(ExecutionTest, BinaryIntOpTest) {
  3206. WEX::TestExecution::SetVerifyOutput verifySettings(
  3207. WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  3208. CComPtr<IStream> pStream;
  3209. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  3210. CComPtr<ID3D12Device> pDevice;
  3211. if (!CreateDevice(&pDevice)) {
  3212. return;
  3213. }
  3214. // Read data from the table
  3215. size_t tableSize = sizeof(BinaryIntOpParameters) / sizeof(TableParameter);
  3216. TableParameterHandler handler(BinaryIntOpParameters, tableSize);
  3217. handler.clearTableParameter();
  3218. VERIFY_SUCCEEDED(ParseTableRow(BinaryIntOpParameters,tableSize));
  3219. CW2A Target(handler.GetTableParamByName(L"ShaderOp.Target")->m_str);
  3220. CW2A Text(handler.GetTableParamByName(L"ShaderOp.Text")->m_str);
  3221. std::vector<int> *Validation_Input1 =
  3222. &handler.GetTableParamByName(L"Validation.Input1")->m_int32Table;
  3223. std::vector<int> *Validation_Input2 =
  3224. &handler.GetTableParamByName(L"Validation.Input2")->m_int32Table;
  3225. std::vector<int> *Validation_Expected1 =
  3226. &handler.GetTableParamByName(L"Validation.Expected1")->m_int32Table;
  3227. std::vector<int> *Validation_Expected2 =
  3228. &handler.GetTableParamByName(L"Validation.Expected2")->m_int32Table;
  3229. int Validation_Tolerance = handler.GetTableParamByName(L"Validation.Tolerance")->m_int32;
  3230. size_t count = Validation_Input1->size();
  3231. size_t numExpected = Validation_Expected2->size() == 0 ? 1 : 2;
  3232. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTest(
  3233. pDevice, m_support, pStream, "BinaryIntOp",
  3234. // this callbacked is called when the test
  3235. // is creating the resource to run the test
  3236. [&](LPCSTR Name, std::vector<BYTE> &Data, st::ShaderOp *pShaderOp) {
  3237. VERIFY_IS_TRUE(0 == _stricmp(Name, "SBinaryIntOp"));
  3238. size_t size = sizeof(SBinaryIntOp) * count;
  3239. Data.resize(size);
  3240. SBinaryIntOp *pPrimitives = (SBinaryIntOp *)Data.data();
  3241. for (size_t i = 0; i < count; ++i) {
  3242. SBinaryIntOp *p = &pPrimitives[i];
  3243. int val1 = (*Validation_Input1)[i % Validation_Input1->size()];
  3244. int val2 = (*Validation_Input2)[i % Validation_Input2->size()];
  3245. p->input1 = val1;
  3246. p->input2 = val2;
  3247. }
  3248. // use shader from data table
  3249. pShaderOp->Shaders.at(0).Target = Target.m_psz;
  3250. pShaderOp->Shaders.at(0).Text = Text.m_psz;
  3251. });
  3252. MappedData data;
  3253. test->Test->GetReadBackData("SBinaryIntOp", &data);
  3254. SBinaryIntOp *pPrimitives = (SBinaryIntOp *)data.data();
  3255. WEX::TestExecution::DisableVerifyExceptions dve;
  3256. if (numExpected == 2) {
  3257. for (unsigned i = 0; i < count; ++i) {
  3258. SBinaryIntOp *p = &pPrimitives[i];
  3259. int val1 = (*Validation_Expected1)[i % Validation_Expected1->size()];
  3260. int val2 = (*Validation_Expected2)[i % Validation_Expected2->size()];
  3261. LogCommentFmt(L"element #%u, input1 = %11i(0x%08x), input2 = "
  3262. L"%11i(0x%08x), output1 = "
  3263. L"%11i(0x%08x), expected1 = %11i(0x%08x), output2 = "
  3264. L"%11i(0x%08x), expected2 = %11i(0x%08x)",
  3265. i, p->input1, p->input1, p->input2, p->input2, p->output1,
  3266. p->output1, val1, val1, p->output2, p->output2, val2,
  3267. val2);
  3268. VerifyOutputWithExpectedValueInt(p->output1, val1, Validation_Tolerance);
  3269. VerifyOutputWithExpectedValueInt(p->output2, val2, Validation_Tolerance);
  3270. }
  3271. }
  3272. else if (numExpected == 1) {
  3273. for (unsigned i = 0; i < count; ++i) {
  3274. SBinaryIntOp *p = &pPrimitives[i];
  3275. int val1 = (*Validation_Expected1)[i % Validation_Expected1->size()];
  3276. LogCommentFmt(L"element #%u, input1 = %11i(0x%08x), input2 = "
  3277. L"%11i(0x%08x), output = "
  3278. L"%11i(0x%08x), expected = %11i(0x%08x)", i,
  3279. p->input1, p->input1, p->input2, p->input2,
  3280. p->output1, p->output1, val1, val1);
  3281. VerifyOutputWithExpectedValueInt(p->output1, val1, Validation_Tolerance);
  3282. }
  3283. }
  3284. else {
  3285. LogErrorFmt(L"Unexpected number of expected values for operation %i", numExpected);
  3286. }
  3287. }
  3288. TEST_F(ExecutionTest, TertiaryIntOpTest) {
  3289. WEX::TestExecution::SetVerifyOutput verifySettings(
  3290. WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  3291. CComPtr<IStream> pStream;
  3292. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  3293. CComPtr<ID3D12Device> pDevice;
  3294. if (!CreateDevice(&pDevice)) {
  3295. return;
  3296. }
  3297. // Read data from the table
  3298. size_t tableSize = sizeof(TertiaryIntOpParameters) / sizeof(TableParameter);
  3299. TableParameterHandler handler(TertiaryIntOpParameters, tableSize);
  3300. handler.clearTableParameter();
  3301. VERIFY_SUCCEEDED(ParseTableRow(TertiaryIntOpParameters, tableSize));
  3302. CW2A Target(handler.GetTableParamByName(L"ShaderOp.Target")->m_str);
  3303. CW2A Text(handler.GetTableParamByName(L"ShaderOp.Text")->m_str);
  3304. std::vector<int> *Validation_Input1 =
  3305. &handler.GetTableParamByName(L"Validation.Input1")->m_int32Table;
  3306. std::vector<int> *Validation_Input2 =
  3307. &handler.GetTableParamByName(L"Validation.Input2")->m_int32Table;
  3308. std::vector<int> *Validation_Input3 =
  3309. &handler.GetTableParamByName(L"Validation.Input3")->m_int32Table;
  3310. std::vector<int> *Validation_Expected =
  3311. &handler.GetTableParamByName(L"Validation.Expected1")->m_int32Table;
  3312. int Validation_Tolerance = handler.GetTableParamByName(L"Validation.Tolerance")->m_int32;
  3313. size_t count = Validation_Input1->size();
  3314. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTest(
  3315. pDevice, m_support, pStream, "TertiaryIntOp",
  3316. // this callbacked is called when the test
  3317. // is creating the resource to run the test
  3318. [&](LPCSTR Name, std::vector<BYTE> &Data, st::ShaderOp *pShaderOp) {
  3319. VERIFY_IS_TRUE(0 == _stricmp(Name, "STertiaryIntOp"));
  3320. size_t size = sizeof(STertiaryIntOp) * count;
  3321. Data.resize(size);
  3322. STertiaryIntOp *pPrimitives = (STertiaryIntOp *)Data.data();
  3323. for (size_t i = 0; i < count; ++i) {
  3324. STertiaryIntOp *p = &pPrimitives[i];
  3325. int val1 = (*Validation_Input1)[i % Validation_Input1->size()];
  3326. int val2 = (*Validation_Input2)[i % Validation_Input2->size()];
  3327. int val3 = (*Validation_Input3)[i % Validation_Input3->size()];
  3328. p->input1 = val1;
  3329. p->input2 = val2;
  3330. p->input3 = val3;
  3331. }
  3332. // use shader from data table
  3333. pShaderOp->Shaders.at(0).Target = Target.m_psz;
  3334. pShaderOp->Shaders.at(0).Text = Text.m_psz;
  3335. });
  3336. MappedData data;
  3337. test->Test->GetReadBackData("STertiaryIntOp", &data);
  3338. STertiaryIntOp *pPrimitives = (STertiaryIntOp *)data.data();
  3339. WEX::TestExecution::DisableVerifyExceptions dve;
  3340. for (unsigned i = 0; i < count; ++i) {
  3341. STertiaryIntOp *p = &pPrimitives[i];
  3342. int val1 = (*Validation_Expected)[i % Validation_Expected->size()];
  3343. LogCommentFmt(L"element #%u, input1 = %11i(0x%08x), input2 = "
  3344. L"%11i(0x%08x), input3= %11i(0x%08x), output = "
  3345. L"%11i(0x%08x), expected = %11i(0x%08x)",
  3346. i, p->input1, p->input1, p->input2, p->input2,
  3347. p->input3, p->input3, p->output, p->output, val1,
  3348. val1);
  3349. VerifyOutputWithExpectedValueInt(p->output, val1, Validation_Tolerance);
  3350. }
  3351. }
  3352. TEST_F(ExecutionTest, BinaryUintOpTest) {
  3353. WEX::TestExecution::SetVerifyOutput verifySettings(
  3354. WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  3355. CComPtr<IStream> pStream;
  3356. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  3357. CComPtr<ID3D12Device> pDevice;
  3358. if (!CreateDevice(&pDevice)) {
  3359. return;
  3360. }
  3361. // Read data from the table
  3362. size_t tableSize = sizeof(BinaryUintOpParameters) / sizeof(TableParameter);
  3363. TableParameterHandler handler(BinaryUintOpParameters, tableSize);
  3364. handler.clearTableParameter();
  3365. VERIFY_SUCCEEDED(ParseTableRow(BinaryUintOpParameters, tableSize));
  3366. CW2A Target(handler.GetTableParamByName(L"ShaderOp.Target")->m_str);
  3367. CW2A Text(handler.GetTableParamByName(L"ShaderOp.Text")->m_str);
  3368. std::vector<unsigned int> *Validation_Input1 =
  3369. &handler.GetTableParamByName(L"Validation.Input1")->m_uintTable;
  3370. std::vector<unsigned int> *Validation_Input2 =
  3371. &handler.GetTableParamByName(L"Validation.Input2")->m_uintTable;
  3372. std::vector<unsigned int> *Validation_Expected1 =
  3373. &handler.GetTableParamByName(L"Validation.Expected1")->m_uintTable;
  3374. std::vector<unsigned int> *Validation_Expected2 =
  3375. &handler.GetTableParamByName(L"Validation.Expected2")->m_uintTable;
  3376. int Validation_Tolerance = handler.GetTableParamByName(L"Validation.Tolerance")->m_int32;
  3377. size_t count = Validation_Input1->size();
  3378. int numExpected = Validation_Expected2->size() == 0 ? 1 : 2;
  3379. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTest(
  3380. pDevice, m_support, pStream, "BinaryUintOp",
  3381. // this callbacked is called when the test
  3382. // is creating the resource to run the test
  3383. [&](LPCSTR Name, std::vector<BYTE> &Data, st::ShaderOp *pShaderOp) {
  3384. VERIFY_IS_TRUE(0 == _stricmp(Name, "SBinaryUintOp"));
  3385. size_t size = sizeof(SBinaryUintOp) * count;
  3386. Data.resize(size);
  3387. SBinaryUintOp *pPrimitives = (SBinaryUintOp *)Data.data();
  3388. for (size_t i = 0; i < count; ++i) {
  3389. SBinaryUintOp *p = &pPrimitives[i];
  3390. unsigned int val1 = (*Validation_Input1)[i % Validation_Input1->size()];
  3391. unsigned int val2 = (*Validation_Input2)[i % Validation_Input2->size()];
  3392. p->input1 = val1;
  3393. p->input2 = val2;
  3394. }
  3395. // use shader from data table
  3396. pShaderOp->Shaders.at(0).Target = Target.m_psz;
  3397. pShaderOp->Shaders.at(0).Text = Text.m_psz;
  3398. });
  3399. MappedData data;
  3400. test->Test->GetReadBackData("SBinaryUintOp", &data);
  3401. SBinaryUintOp *pPrimitives = (SBinaryUintOp *)data.data();
  3402. WEX::TestExecution::DisableVerifyExceptions dve;
  3403. if (numExpected == 2) {
  3404. for (unsigned i = 0; i < count; ++i) {
  3405. SBinaryUintOp *p = &pPrimitives[i];
  3406. unsigned int val1 = (*Validation_Expected1)[i % Validation_Expected1->size()];
  3407. unsigned int val2 = (*Validation_Expected2)[i % Validation_Expected2->size()];
  3408. LogCommentFmt(L"element #%u, input1 = %11u(0x%08x), input2 = "
  3409. L"%11u(0x%08x), output1 = "
  3410. L"%11u(0x%08x), expected1 = %11u(0x%08x), output2 = "
  3411. L"%11u(0x%08x), expected2 = %11u(0x%08x)",
  3412. i, p->input1, p->input1, p->input2, p->input2, p->output1,
  3413. p->output1, val1, val1, p->output2, p->output2, val2,
  3414. val2);
  3415. VerifyOutputWithExpectedValueInt(p->output1, val1, Validation_Tolerance);
  3416. VerifyOutputWithExpectedValueInt(p->output2, val2, Validation_Tolerance);
  3417. }
  3418. }
  3419. else if (numExpected == 1) {
  3420. for (unsigned i = 0; i < count; ++i) {
  3421. SBinaryUintOp *p = &pPrimitives[i];
  3422. unsigned int val1 = (*Validation_Expected1)[i % Validation_Expected1->size()];
  3423. LogCommentFmt(L"element #%u, input1 = %11u(0x%08x), input2 = "
  3424. L"%11u(0x%08x), output = "
  3425. L"%11u(0x%08x), expected = %11u(0x%08x)", i,
  3426. p->input1, p->input1, p->input2, p->input2,
  3427. p->output1, p->output1, val1, val1);
  3428. VerifyOutputWithExpectedValueInt(p->output1, val1, Validation_Tolerance);
  3429. }
  3430. }
  3431. else {
  3432. LogErrorFmt(L"Unexpected number of expected values for operation %i", numExpected);
  3433. }
  3434. }
  3435. TEST_F(ExecutionTest, TertiaryUintOpTest) {
  3436. WEX::TestExecution::SetVerifyOutput verifySettings(
  3437. WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  3438. CComPtr<IStream> pStream;
  3439. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  3440. CComPtr<ID3D12Device> pDevice;
  3441. if (!CreateDevice(&pDevice)) {
  3442. return;
  3443. }
  3444. // Read data from the table
  3445. size_t tableSize = sizeof(TertiaryUintOpParameters) / sizeof(TableParameter);
  3446. TableParameterHandler handler(TertiaryUintOpParameters, tableSize);
  3447. handler.clearTableParameter();
  3448. VERIFY_SUCCEEDED(ParseTableRow(TertiaryUintOpParameters, tableSize));
  3449. CW2A Target(handler.GetTableParamByName(L"ShaderOp.Target")->m_str);
  3450. CW2A Text(handler.GetTableParamByName(L"ShaderOp.Text")->m_str);
  3451. std::vector<unsigned int> *Validation_Input1 =
  3452. &handler.GetTableParamByName(L"Validation.Input1")->m_uintTable;
  3453. std::vector<unsigned int> *Validation_Input2 =
  3454. &handler.GetTableParamByName(L"Validation.Input2")->m_uintTable;
  3455. std::vector<unsigned int> *Validation_Input3 =
  3456. &handler.GetTableParamByName(L"Validation.Input3")->m_uintTable;
  3457. std::vector<unsigned int> *Validation_Expected =
  3458. &handler.GetTableParamByName(L"Validation.Expected1")->m_uintTable;
  3459. int Validation_Tolerance = handler.GetTableParamByName(L"Validation.Tolerance")->m_int32;
  3460. size_t count = Validation_Input1->size();
  3461. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTest(
  3462. pDevice, m_support, pStream, "TertiaryUintOp",
  3463. // this callbacked is called when the test
  3464. // is creating the resource to run the test
  3465. [&](LPCSTR Name, std::vector<BYTE> &Data, st::ShaderOp *pShaderOp) {
  3466. VERIFY_IS_TRUE(0 == _stricmp(Name, "STertiaryUintOp"));
  3467. size_t size = sizeof(STertiaryUintOp) * count;
  3468. Data.resize(size);
  3469. STertiaryUintOp *pPrimitives = (STertiaryUintOp *)Data.data();
  3470. for (size_t i = 0; i < count; ++i) {
  3471. STertiaryUintOp *p = &pPrimitives[i];
  3472. unsigned int val1 = (*Validation_Input1)[i % Validation_Input1->size()];
  3473. unsigned int val2 = (*Validation_Input2)[i % Validation_Input2->size()];
  3474. unsigned int val3 = (*Validation_Input3)[i % Validation_Input3->size()];
  3475. p->input1 = val1;
  3476. p->input2 = val2;
  3477. p->input3 = val3;
  3478. }
  3479. // use shader from data table
  3480. pShaderOp->Shaders.at(0).Target = Target.m_psz;
  3481. pShaderOp->Shaders.at(0).Text = Text.m_psz;
  3482. });
  3483. MappedData data;
  3484. test->Test->GetReadBackData("STertiaryUintOp", &data);
  3485. STertiaryUintOp *pPrimitives = (STertiaryUintOp *)data.data();
  3486. WEX::TestExecution::DisableVerifyExceptions dve;
  3487. for (unsigned i = 0; i < count; ++i) {
  3488. STertiaryUintOp *p = &pPrimitives[i];
  3489. unsigned int val1 = (*Validation_Expected)[i % Validation_Expected->size()];
  3490. LogCommentFmt(L"element #%u, input1 = %11u(0x%08x), input2 = "
  3491. L"%11u(0x%08x), input3 = %11u(0x%08x), output = "
  3492. L"%11u(0x%08x), expected = %11u(0x%08x)", i,
  3493. p->input1, p->input1, p->input2, p->input2, p->input3, p->input3,
  3494. p->output, p->output, val1, val1);
  3495. VerifyOutputWithExpectedValueInt(p->output, val1, Validation_Tolerance);
  3496. }
  3497. }
  3498. TEST_F(ExecutionTest, DotTest) {
  3499. WEX::TestExecution::SetVerifyOutput verifySettings(
  3500. WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  3501. CComPtr<IStream> pStream;
  3502. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  3503. CComPtr<ID3D12Device> pDevice;
  3504. if (!CreateDevice(&pDevice)) {
  3505. return;
  3506. }
  3507. int tableSize = sizeof(DotOpParameters) / sizeof(TableParameter);
  3508. TableParameterHandler handler(DotOpParameters, tableSize);
  3509. handler.clearTableParameter();
  3510. VERIFY_SUCCEEDED(ParseTableRow(DotOpParameters, tableSize));
  3511. CW2A Target(handler.GetTableParamByName(L"ShaderOp.Target")->m_str);
  3512. CW2A Text(handler.GetTableParamByName(L"ShaderOp.Text")->m_str);
  3513. std::vector<WEX::Common::String> *Validation_Input1 =
  3514. &handler.GetTableParamByName(L"Validation.Input1")->m_StringTable;
  3515. std::vector<WEX::Common::String> *Validation_Input2 =
  3516. &handler.GetTableParamByName(L"Validation.Input2")->m_StringTable;
  3517. std::vector<WEX::Common::String> *Validation_dot2 =
  3518. &handler.GetTableParamByName(L"Validation.Expected1")->m_StringTable;
  3519. std::vector<WEX::Common::String> *Validation_dot3 =
  3520. &handler.GetTableParamByName(L"Validation.Expected2")->m_StringTable;
  3521. std::vector<WEX::Common::String> *Validation_dot4 =
  3522. &handler.GetTableParamByName(L"Validation.Expected3")->m_StringTable;
  3523. PCWSTR Validation_type = handler.GetTableParamByName(L"Validation.Type")->m_str;
  3524. double tolerance = handler.GetTableParamByName(L"Validation.Tolerance")->m_double;
  3525. unsigned int count = Validation_Input1->size();
  3526. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTest(
  3527. pDevice, m_support, pStream, "DotOp",
  3528. // this callbacked is called when the test
  3529. // is creating the resource to run the test
  3530. [&](LPCSTR Name, std::vector<BYTE> &Data, st::ShaderOp *pShaderOp) {
  3531. VERIFY_IS_TRUE(0 == _stricmp(Name, "SDotOp"));
  3532. size_t size = sizeof(SDotOp) * count;
  3533. Data.resize(size);
  3534. SDotOp *pPrimitives = (SDotOp*)Data.data();
  3535. for (size_t i = 0; i < count; ++i) {
  3536. SDotOp *p = &pPrimitives[i];
  3537. XMFLOAT4 val1,val2;
  3538. VERIFY_SUCCEEDED(ParseDataToVectorFloat((*Validation_Input1)[i],
  3539. (float *)&val1, 4));
  3540. VERIFY_SUCCEEDED(ParseDataToVectorFloat((*Validation_Input2)[i],
  3541. (float *)&val2, 4));
  3542. p->input1 = val1;
  3543. p->input2 = val2;
  3544. }
  3545. // use shader from data table
  3546. pShaderOp->Shaders.at(0).Target = Target.m_psz;
  3547. pShaderOp->Shaders.at(0).Text = Text.m_psz;
  3548. });
  3549. MappedData data;
  3550. test->Test->GetReadBackData("SDotOp", &data);
  3551. SDotOp *pPrimitives = (SDotOp*)data.data();
  3552. WEX::TestExecution::DisableVerifyExceptions dve;
  3553. for (size_t i = 0; i < count; ++i) {
  3554. SDotOp *p = &pPrimitives[i];
  3555. float dot2, dot3, dot4;
  3556. VERIFY_SUCCEEDED(ParseDataToFloat((*Validation_dot2)[i], dot2));
  3557. VERIFY_SUCCEEDED(ParseDataToFloat((*Validation_dot3)[i], dot3));
  3558. VERIFY_SUCCEEDED(ParseDataToFloat((*Validation_dot4)[i], dot4));
  3559. LogCommentFmt(
  3560. L"element #%u, input1 = (%f, %f, %f, %f), input2 = (%f, %f, "
  3561. L"%f, %f), \n dot2 = %f, dot2_expected = %f, dot3 = %f, "
  3562. L"dot3_expected = %f, dot4 = %f, dot4_expected = %f",
  3563. i, p->input1.x, p->input1.y, p->input1.z, p->input1.w, p->input2.x,
  3564. p->input2.y, p->input2.z, p->input2.w, p->o_dot2, dot2, p->o_dot3, dot3,
  3565. p->o_dot4, dot4);
  3566. VerifyOutputWithExpectedValueFloat(p->o_dot2, dot2, Validation_type,
  3567. tolerance);
  3568. VerifyOutputWithExpectedValueFloat(p->o_dot3, dot3, Validation_type,
  3569. tolerance);
  3570. VerifyOutputWithExpectedValueFloat(p->o_dot4, dot4, Validation_type,
  3571. tolerance);
  3572. }
  3573. }
  3574. TEST_F(ExecutionTest, Msad4Test) {
  3575. WEX::TestExecution::SetVerifyOutput verifySettings(
  3576. WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  3577. CComPtr<IStream> pStream;
  3578. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  3579. CComPtr<ID3D12Device> pDevice;
  3580. if (!CreateDevice(&pDevice)) {
  3581. return;
  3582. }
  3583. size_t tableSize = sizeof(Msad4OpParameters) / sizeof(TableParameter);
  3584. TableParameterHandler handler(Msad4OpParameters, tableSize);
  3585. handler.clearTableParameter();
  3586. VERIFY_SUCCEEDED(ParseTableRow(Msad4OpParameters, tableSize));
  3587. CW2A Text(handler.GetTableParamByName(L"ShaderOp.Text")->m_str);
  3588. double tolerance = handler.GetTableParamByName(L"Validation.Tolerance")->m_double;
  3589. std::vector<unsigned int> *Validation_Reference =
  3590. &handler.GetTableParamByName(L"Validation.Input1")->m_uintTable;
  3591. std::vector<WEX::Common::String> *Validation_Source =
  3592. &handler.GetTableParamByName(L"Validation.Input2")->m_StringTable;
  3593. std::vector<WEX::Common::String> *Validation_Accum =
  3594. &handler.GetTableParamByName(L"Validation.Input3")->m_StringTable;
  3595. std::vector<WEX::Common::String> *Validation_Expected =
  3596. &handler.GetTableParamByName(L"Validation.Expected1")->m_StringTable;
  3597. size_t count = Validation_Expected->size();
  3598. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTest(
  3599. pDevice, m_support, pStream, "Msad4",
  3600. // this callbacked is called when the test
  3601. // is creating the resource to run the test
  3602. [&](LPCSTR Name, std::vector<BYTE> &Data, st::ShaderOp *pShaderOp) {
  3603. VERIFY_IS_TRUE(0 == _stricmp(Name, "SMsad4"));
  3604. size_t size = sizeof(SMsad4) * count;
  3605. Data.resize(size);
  3606. SMsad4 *pPrimitives = (SMsad4*)Data.data();
  3607. for (size_t i = 0; i < count; ++i) {
  3608. SMsad4 *p = &pPrimitives[i];
  3609. XMUINT2 src;
  3610. XMUINT4 accum;
  3611. VERIFY_SUCCEEDED(ParseDataToVectorUint((*Validation_Source)[i], (unsigned int*)&src, 2));
  3612. VERIFY_SUCCEEDED(ParseDataToVectorUint((*Validation_Accum)[i], (unsigned int*)&accum, 4));
  3613. p->ref = (*Validation_Reference)[i];
  3614. p->src = src;
  3615. p->accum = accum;
  3616. }
  3617. // use shader from data table
  3618. pShaderOp->Shaders.at(0).Text = Text.m_psz;
  3619. });
  3620. MappedData data;
  3621. test->Test->GetReadBackData("SMsad4", &data);
  3622. SMsad4 *pPrimitives = (SMsad4*)data.data();
  3623. WEX::TestExecution::DisableVerifyExceptions dve;
  3624. for (size_t i = 0; i < count; ++i) {
  3625. SMsad4 *p = &pPrimitives[i];
  3626. XMUINT4 result;
  3627. VERIFY_SUCCEEDED(ParseDataToVectorUint((*Validation_Expected)[i],
  3628. (unsigned int *)&result, 4));
  3629. LogCommentFmt(
  3630. L"element #%u, ref = %u(0x%08x), src = %u(0x%08x), %u(0x%08x), "
  3631. L"accum = %u(0x%08x), %u(0x%08x), %u(0x%08x), %u(0x%08x),\n"
  3632. L"result = %u(0x%08x), %u(0x%08x), %u(0x%08x), %u(0x%08x),\n"
  3633. L"expected = %u(0x%08x), %u(0x%08x), %u(0x%08x), %u(0x%08x)", i,
  3634. p->ref, p->ref, p->src.x, p->src.x, p->src.y, p->src.y, p->accum.x,
  3635. p->accum.x, p->accum.y, p->accum.y, p->accum.z, p->accum.z,
  3636. p->accum.w, p->accum.w, p->result.x, p->result.x, p->result.y,
  3637. p->result.y, p->result.z, p->result.z, p->result.w, p->result.w,
  3638. result.x, result.x, result.y, result.y, result.z, result.z,
  3639. result.w, result.w);
  3640. VerifyOutputWithExpectedValueInt(p->result.x, result.x, tolerance);
  3641. VerifyOutputWithExpectedValueInt(p->result.y, result.y, tolerance);
  3642. VerifyOutputWithExpectedValueInt(p->result.z, result.z, tolerance);
  3643. VerifyOutputWithExpectedValueInt(p->result.w, result.w, tolerance);
  3644. }
  3645. }
  3646. // A framework for testing individual wave intrinsics tests.
  3647. // This test case is assuming that functions 1) WaveIsFirstLane and 2) WaveGetLaneIndex are correct for all lanes.
  3648. template <class T1, class T2>
  3649. void ExecutionTest::WaveIntrinsicsActivePrefixTest(
  3650. TableParameter *pParameterList, size_t numParameter, bool isPrefix) {
  3651. WEX::TestExecution::SetVerifyOutput verifySettings(WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  3652. // Resource representation for compute shader
  3653. // firstLaneId is used to group different waves
  3654. // laneIndex is used to identify lane within the wave.
  3655. // Lane ids are not necessarily in same order as thread ids.
  3656. struct PerThreadData {
  3657. unsigned firstLaneId;
  3658. unsigned laneIndex;
  3659. int mask;
  3660. T1 input;
  3661. T2 output;
  3662. };
  3663. unsigned int NumThreadsX = 8;
  3664. unsigned int NumThreadsY = 12;
  3665. unsigned int NumThreadsZ = 1;
  3666. static const unsigned int ThreadsPerGroup = NumThreadsX * NumThreadsY * NumThreadsZ;
  3667. static const unsigned int DispatchGroupCount = 1;
  3668. static const unsigned int ThreadCount = ThreadsPerGroup * DispatchGroupCount;
  3669. CComPtr<IStream> pStream;
  3670. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  3671. CComPtr<ID3D12Device> pDevice;
  3672. if (!CreateDevice(&pDevice)) {
  3673. return;
  3674. }
  3675. if (!DoesDeviceSupportWaveOps(pDevice)) {
  3676. // Optional feature, so it's correct to not support it if declared as such.
  3677. WEX::Logging::Log::Comment(L"Device does not support wave operations.");
  3678. return;
  3679. }
  3680. TableParameterHandler handler(pParameterList, numParameter);
  3681. handler.clearTableParameter();
  3682. VERIFY_SUCCEEDED(ParseTableRow(pParameterList, numParameter));
  3683. unsigned int numInputSet = handler.GetTableParamByName(L"Validation.NumInputSet")->m_uint;
  3684. // Obtain the list of input lists
  3685. std::vector<std::vector<T1>*> InputDataList;
  3686. for (unsigned int i = 0;
  3687. i < numInputSet; ++i) {
  3688. std::wstring inputName = L"Validation.InputSet";
  3689. inputName.append(std::to_wstring(i + 1));
  3690. InputDataList.push_back(handler.GetDataArray<T1>(inputName.data()));
  3691. }
  3692. CW2A Text(handler.GetTableParamByName(L"ShaderOp.text")->m_str);
  3693. std::shared_ptr<st::ShaderOpSet> ShaderOpSet = std::make_shared<st::ShaderOpSet>();
  3694. st::ParseShaderOpSetFromStream(pStream, ShaderOpSet.get());
  3695. // Running compute shader for each input set with different masks
  3696. for (size_t setIndex = 0; setIndex < numInputSet; ++setIndex) {
  3697. for (size_t maskIndex = 0; maskIndex < sizeof(MaskFunctionTable) / sizeof(MaskFunction); ++maskIndex) {
  3698. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTestAfterParse(
  3699. pDevice, m_support, pStream, "WaveIntrinsicsOp",
  3700. // this callbacked is called when the test
  3701. // is creating the resource to run the test
  3702. [&](LPCSTR Name, std::vector<BYTE> &Data, st::ShaderOp *pShaderOp) {
  3703. VERIFY_IS_TRUE(0 == _stricmp(Name, "SWaveIntrinsicsOp"));
  3704. size_t size = sizeof(PerThreadData) * ThreadCount;
  3705. Data.resize(size);
  3706. PerThreadData *pPrimitives = (PerThreadData*)Data.data();
  3707. // 4 different inputs for each operation test
  3708. size_t index = 0;
  3709. std::vector<T1> *IntList = InputDataList[setIndex];
  3710. while (index < ThreadCount) {
  3711. PerThreadData *p = &pPrimitives[index];
  3712. p->firstLaneId = 0xFFFFBFFF;
  3713. p->laneIndex = 0xFFFFBFFF;
  3714. p->mask = MaskFunctionTable[maskIndex](index);
  3715. p->input = (*IntList)[index % IntList->size()];
  3716. p->output = 0xFFFFBFFF;
  3717. index++;
  3718. }
  3719. // use shader from data table
  3720. pShaderOp->Shaders.at(0).Text = Text.m_psz;
  3721. }, ShaderOpSet);
  3722. // Check the value
  3723. MappedData data;
  3724. test->Test->GetReadBackData("SWaveIntrinsicsOp", &data);
  3725. PerThreadData *pPrimitives = (PerThreadData*)data.data();
  3726. WEX::TestExecution::DisableVerifyExceptions dve;
  3727. // Grouping data by waves
  3728. std::vector<int> firstLaneIds;
  3729. for (size_t i = 0; i < ThreadCount; ++i) {
  3730. PerThreadData *p = &pPrimitives[i];
  3731. int firstLaneId = p->firstLaneId;
  3732. if (!contains(firstLaneIds, firstLaneId)) {
  3733. firstLaneIds.push_back(firstLaneId);
  3734. }
  3735. }
  3736. std::map<int, std::unique_ptr<std::vector<PerThreadData *>>> waves;
  3737. for (size_t i = 0; i < firstLaneIds.size(); ++i) {
  3738. waves[firstLaneIds.at(i)] = std::make_unique<std::vector<PerThreadData*>>(std::vector<PerThreadData*>());
  3739. }
  3740. for (size_t i = 0; i < ThreadCount; ++i) {
  3741. PerThreadData *p = &pPrimitives[i];
  3742. waves[p->firstLaneId].get()->push_back(p);
  3743. }
  3744. // validate for each wave
  3745. for (size_t i = 0; i < firstLaneIds.size(); ++i) {
  3746. // collect inputs and masks for a given wave
  3747. std::vector<PerThreadData *> *waveData = waves[firstLaneIds.at(i)].get();
  3748. std::vector<T1> inputList(waveData->size());
  3749. std::vector<int> maskList(waveData->size(), -1);
  3750. std::vector<T2> outputList(waveData->size());
  3751. // sort inputList and masklist by lane id. input for each lane can be computed for its group index
  3752. for (size_t j = 0, end = waveData->size(); j < end; ++j) {
  3753. unsigned laneID = waveData->at(j)->laneIndex;
  3754. // ensure that each lane ID is unique and within the range
  3755. VERIFY_IS_TRUE(0 <= laneID && laneID < waveData->size());
  3756. VERIFY_IS_TRUE(maskList.at(laneID) == -1);
  3757. maskList.at(laneID) = waveData->at(j)->mask;
  3758. inputList.at(laneID) = waveData->at(j)->input;
  3759. outputList.at(laneID) = waveData->at(j)->output;
  3760. }
  3761. std::wstring inputStr = L"Wave Inputs: ";
  3762. std::wstring maskStr = L"Wave Masks: ";
  3763. std::wstring outputStr = L"Wave Outputs: ";
  3764. // append input string and mask string in lane id order
  3765. for (size_t j = 0, end = waveData->size(); j < end; ++j) {
  3766. maskStr.append(std::to_wstring(maskList.at(j)));
  3767. maskStr.append(L" ");
  3768. inputStr.append(std::to_wstring(inputList.at(j)));
  3769. inputStr.append(L" ");
  3770. outputStr.append(std::to_wstring(outputList.at(j)));
  3771. outputStr.append(L" ");
  3772. }
  3773. LogCommentFmt(inputStr.data());
  3774. LogCommentFmt(maskStr.data());
  3775. LogCommentFmt(outputStr.data());
  3776. LogCommentFmt(L"\n");
  3777. // Compute expected output for a given inputs, masks, and index
  3778. for (size_t laneIndex = 0, laneEnd = inputList.size(); laneIndex < laneEnd; ++laneIndex) {
  3779. T2 expected;
  3780. // WaveActive is equivalent to WavePrefix lane # lane count
  3781. unsigned index = isPrefix ? laneIndex : inputList.size();
  3782. if (maskList.at(laneIndex) == 1) {
  3783. expected = computeExpectedWithShaderOp<T1, T2>(
  3784. inputList, maskList, 1, index,
  3785. handler.GetTableParamByName(L"ShaderOp.Name")->m_str);
  3786. }
  3787. else {
  3788. expected = computeExpectedWithShaderOp<T1, T2>(
  3789. inputList, maskList, 0, index,
  3790. handler.GetTableParamByName(L"ShaderOp.Name")->m_str);
  3791. }
  3792. // TODO: use different comparison for floating point inputs
  3793. bool equal = outputList.at(laneIndex) == expected;
  3794. if (!equal) {
  3795. LogCommentFmt(L"lane%d: %4d, Expected : %4d", laneIndex, outputList.at(laneIndex), expected);
  3796. }
  3797. VERIFY_IS_TRUE(equal);
  3798. }
  3799. }
  3800. }
  3801. }
  3802. }
  3803. static const unsigned int MinWarpVersionForWaveIntrinsics = 16202;
  3804. TEST_F(ExecutionTest, WaveIntrinsicsActiveIntTest) {
  3805. if (GetTestParamUseWARP(true) &&
  3806. !IsValidWarpDllVersion(MinWarpVersionForWaveIntrinsics)) {
  3807. return;
  3808. }
  3809. WaveIntrinsicsActivePrefixTest<int, int>(
  3810. WaveIntrinsicsActiveIntParameters,
  3811. sizeof(WaveIntrinsicsActiveIntParameters) / sizeof(TableParameter),
  3812. /*isPrefix*/ false);
  3813. }
  3814. TEST_F(ExecutionTest, WaveIntrinsicsActiveUintTest) {
  3815. if (GetTestParamUseWARP(true) &&
  3816. !IsValidWarpDllVersion(MinWarpVersionForWaveIntrinsics)) {
  3817. return;
  3818. }
  3819. WaveIntrinsicsActivePrefixTest<unsigned int, unsigned int>(
  3820. WaveIntrinsicsActiveUintParameters,
  3821. sizeof(WaveIntrinsicsActiveUintParameters) / sizeof(TableParameter),
  3822. /*isPrefix*/ false);
  3823. }
  3824. TEST_F(ExecutionTest, WaveIntrinsicsPrefixIntTest) {
  3825. if (GetTestParamUseWARP(true) &&
  3826. !IsValidWarpDllVersion(MinWarpVersionForWaveIntrinsics)) {
  3827. return;
  3828. }
  3829. WaveIntrinsicsActivePrefixTest<int, int>(
  3830. WaveIntrinsicsPrefixIntParameters,
  3831. sizeof(WaveIntrinsicsPrefixIntParameters) / sizeof(TableParameter),
  3832. /*isPrefix*/ true);
  3833. }
  3834. TEST_F(ExecutionTest, WaveIntrinsicsPrefixUintTest) {
  3835. if (GetTestParamUseWARP(true) &&
  3836. !IsValidWarpDllVersion(MinWarpVersionForWaveIntrinsics)) {
  3837. return;
  3838. }
  3839. WaveIntrinsicsActivePrefixTest<unsigned int, unsigned int>(
  3840. WaveIntrinsicsPrefixUintParameters,
  3841. sizeof(WaveIntrinsicsPrefixUintParameters) / sizeof(TableParameter),
  3842. /*isPrefix*/ true);
  3843. }
  3844. TEST_F(ExecutionTest, CBufferTestHalf) {
  3845. if (m_ver.SkipDxilVersion(1, 2)) return;
  3846. WEX::TestExecution::SetVerifyOutput verifySettings(WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  3847. CComPtr<IStream> pStream;
  3848. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  3849. // Single operation test at the moment.
  3850. CComPtr<ID3D12Device> pDevice;
  3851. if (!CreateDevice(&pDevice))
  3852. return;
  3853. std::vector<uint16_t> InputData = { 0x3F80, 0x3F00, 0x3D80, 0x7BFF };
  3854. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTest(pDevice, m_support, pStream, "CBufferTestHalf",
  3855. [&](LPCSTR Name, std::vector<BYTE> &Data, st::ShaderOp *pShaderOp) {
  3856. VERIFY_IS_TRUE(0 == _stricmp(Name, "CB0"));
  3857. // use shader from data table.
  3858. Data.resize(4 * sizeof(uint16_t));
  3859. for (size_t i = 0; i < 4; ++i) {
  3860. // pack two halves in 32 bits
  3861. uint16_t val = InputData[i];
  3862. Data.at(2*i) = val & 0xff;
  3863. Data.at(2*i + 1) = val >> 8;
  3864. }
  3865. });
  3866. {
  3867. MappedData data;
  3868. test->Test->GetReadBackData("RTarget", &data);
  3869. const uint16_t *pPixels = (uint16_t *)data.data();
  3870. uint16_t first = *pPixels;
  3871. uint16_t second = *(pPixels + 1);
  3872. uint16_t third = *(pPixels + 2);
  3873. uint16_t fourth = *(pPixels + 3);
  3874. LogCommentFmt(L"first %f", first);
  3875. LogCommentFmt(L"second %f", second);
  3876. LogCommentFmt(L"third %f", third);
  3877. LogCommentFmt(L"fourth %f", fourth);
  3878. VERIFY_ARE_EQUAL(first, InputData[0]);
  3879. VERIFY_ARE_EQUAL(second, InputData[1]);
  3880. VERIFY_ARE_EQUAL(third, InputData[2]);
  3881. VERIFY_ARE_EQUAL(fourth, InputData[3]);
  3882. }
  3883. }
  3884. static void WriteReadBackDump(st::ShaderOp *pShaderOp, st::ShaderOpTest *pTest,
  3885. char **pReadBackDump) {
  3886. std::stringstream str;
  3887. unsigned count = 0;
  3888. for (auto &R : pShaderOp->Resources) {
  3889. if (!R.ReadBack)
  3890. continue;
  3891. ++count;
  3892. str << "Resource: " << R.Name << "\r\n";
  3893. // Find a descriptor that can tell us how to dump this resource.
  3894. bool found = false;
  3895. for (auto &Heaps : pShaderOp->DescriptorHeaps) {
  3896. for (auto &D : Heaps.Descriptors) {
  3897. if (_stricmp(D.ResName, R.Name) != 0) {
  3898. continue;
  3899. }
  3900. found = true;
  3901. if (_stricmp(D.Kind, "UAV") != 0) {
  3902. str << "Resource dump for kind " << D.Kind << " not implemented yet.\r\n";
  3903. break;
  3904. }
  3905. if (D.UavDesc.ViewDimension != D3D12_UAV_DIMENSION_BUFFER) {
  3906. str << "Resource dump for this kind of view dimension not implemented yet.\r\n";
  3907. break;
  3908. }
  3909. // We can map back to the structure if a structured buffer via the shader, but
  3910. // we'll keep this simple and simply dump out 32-bit uint/float representations.
  3911. MappedData data;
  3912. pTest->GetReadBackData(R.Name, &data);
  3913. uint32_t *pData = (uint32_t *)data.data();
  3914. size_t u32_count = R.Desc.Width / sizeof(uint32_t);
  3915. for (size_t i = 0; i < u32_count; ++i) {
  3916. float f = *(float *)pData;
  3917. str << i << ": 0n" << *pData << " 0x" << std::hex << *pData
  3918. << std::dec << " " << f << "\r\n";
  3919. ++pData;
  3920. }
  3921. break;
  3922. }
  3923. if (found) break;
  3924. }
  3925. if (!found) {
  3926. str << "Unable to find a view for the resource.\r\n";
  3927. }
  3928. }
  3929. str << "Resources read back: " << count << "\r\n";
  3930. std::string s(str.str());
  3931. CComHeapPtr<char> pDump;
  3932. if (!pDump.Allocate(s.size() + 1))
  3933. throw std::bad_alloc();
  3934. memcpy(pDump.m_pData, s.data(), s.size());
  3935. pDump.m_pData[s.size()] = '\0';
  3936. *pReadBackDump = pDump.Detach();
  3937. }
  3938. // This is the exported interface by use from HLSLHost.exe.
  3939. // It's exclusive with the use of the DLL as a TAEF target.
  3940. extern "C" {
  3941. __declspec(dllexport) HRESULT WINAPI InitializeOpTests(void *pStrCtx, st::OutputStringFn pOutputStrFn) {
  3942. HRESULT hr = EnableExperimentalShaderModels();
  3943. if (FAILED(hr)) {
  3944. pOutputStrFn(pStrCtx, L"Unable to enable experimental shader models.\r\n.");
  3945. }
  3946. return S_OK;
  3947. }
  3948. __declspec(dllexport) HRESULT WINAPI
  3949. RunOpTest(void *pStrCtx, st::OutputStringFn pOutputStrFn, LPCSTR pText,
  3950. ID3D12Device *pDevice, ID3D12CommandQueue *pCommandQueue,
  3951. ID3D12Resource *pRenderTarget, char **pReadBackDump) {
  3952. HRESULT hr;
  3953. if (pReadBackDump) *pReadBackDump = nullptr;
  3954. st::SetOutputFn(pStrCtx, pOutputStrFn);
  3955. CComPtr<ID3D12InfoQueue> pInfoQueue;
  3956. CComHeapPtr<char> pDump;
  3957. bool FilterCreation = false;
  3958. if (SUCCEEDED(pDevice->QueryInterface(&pInfoQueue))) {
  3959. // Creation is largely driven by inputs, so don't log create/destroy messages.
  3960. pInfoQueue->PushEmptyStorageFilter();
  3961. pInfoQueue->PushEmptyRetrievalFilter();
  3962. if (FilterCreation) {
  3963. D3D12_INFO_QUEUE_FILTER filter;
  3964. D3D12_MESSAGE_CATEGORY denyCategories[] = { D3D12_MESSAGE_CATEGORY_STATE_CREATION };
  3965. ZeroMemory(&filter, sizeof(filter));
  3966. filter.DenyList.NumCategories = _countof(denyCategories);
  3967. filter.DenyList.pCategoryList = denyCategories;
  3968. pInfoQueue->PushStorageFilter(&filter);
  3969. }
  3970. }
  3971. else {
  3972. pOutputStrFn(pStrCtx, L"Unable to enable info queue for D3D.\r\n.");
  3973. }
  3974. try {
  3975. dxc::DxcDllSupport m_support;
  3976. m_support.Initialize();
  3977. const char *pName = nullptr;
  3978. CComPtr<IStream> pStream = SHCreateMemStream((BYTE *)pText, strlen(pText));
  3979. std::shared_ptr<st::ShaderOpSet> ShaderOpSet =
  3980. std::make_shared<st::ShaderOpSet>();
  3981. st::ParseShaderOpSetFromStream(pStream, ShaderOpSet.get());
  3982. st::ShaderOp *pShaderOp;
  3983. if (pName == nullptr) {
  3984. if (ShaderOpSet->ShaderOps.size() != 1) {
  3985. pOutputStrFn(pStrCtx, L"Expected a single shader operation.\r\n");
  3986. return E_FAIL;
  3987. }
  3988. pShaderOp = ShaderOpSet->ShaderOps[0].get();
  3989. }
  3990. else {
  3991. pShaderOp = ShaderOpSet->GetShaderOp(pName);
  3992. }
  3993. if (pShaderOp == nullptr) {
  3994. std::string msg = "Unable to find shader op ";
  3995. msg += pName;
  3996. msg += "; available ops";
  3997. const char sep = ':';
  3998. for (auto &pAvailOp : ShaderOpSet->ShaderOps) {
  3999. msg += sep;
  4000. msg += pAvailOp->Name ? pAvailOp->Name : "[n/a]";
  4001. }
  4002. CA2W msgWide(msg.c_str());
  4003. pOutputStrFn(pStrCtx, msgWide);
  4004. return E_FAIL;
  4005. }
  4006. std::shared_ptr<st::ShaderOpTest> test = std::make_shared<st::ShaderOpTest>();
  4007. test->SetupRenderTarget(pShaderOp, pDevice, pCommandQueue, pRenderTarget);
  4008. test->SetDxcSupport(&m_support);
  4009. test->RunShaderOp(pShaderOp);
  4010. test->PresentRenderTarget(pShaderOp, pCommandQueue, pRenderTarget);
  4011. pOutputStrFn(pStrCtx, L"Rendering complete.\r\n");
  4012. if (!pShaderOp->IsCompute()) {
  4013. D3D12_QUERY_DATA_PIPELINE_STATISTICS stats;
  4014. test->GetPipelineStats(&stats);
  4015. wchar_t statsText[400];
  4016. StringCchPrintfW(statsText, _countof(statsText),
  4017. L"Vertices/primitives read by input assembler: %I64u/%I64u\r\n"
  4018. L"Vertex shader invocations: %I64u\r\n"
  4019. L"Geometry shader invocations/output primitive: %I64u/%I64u\r\n"
  4020. L"Primitives sent to rasterizer/rendered: %I64u/%I64u\r\n"
  4021. L"PS/HS/DS/CS invocations: %I64u/%I64u/%I64u/%I64u\r\n",
  4022. stats.IAVertices, stats.IAPrimitives, stats.VSInvocations,
  4023. stats.GSInvocations, stats.GSPrimitives, stats.CInvocations,
  4024. stats.CPrimitives, stats.PSInvocations, stats.HSInvocations,
  4025. stats.DSInvocations, stats.CSInvocations);
  4026. pOutputStrFn(pStrCtx, statsText);
  4027. }
  4028. if (pReadBackDump) {
  4029. WriteReadBackDump(pShaderOp, test.get(), &pDump);
  4030. }
  4031. hr = S_OK;
  4032. }
  4033. catch (const CAtlException &E)
  4034. {
  4035. hr = E.m_hr;
  4036. }
  4037. catch (const std::bad_alloc &)
  4038. {
  4039. hr = E_OUTOFMEMORY;
  4040. }
  4041. catch (const std::exception &)
  4042. {
  4043. hr = E_FAIL;
  4044. }
  4045. // Drain the device message queue if available.
  4046. if (pInfoQueue != nullptr) {
  4047. wchar_t buf[200];
  4048. StringCchPrintfW(buf, _countof(buf),
  4049. L"NumStoredMessages=%u limit/discarded by limit=%u/%u "
  4050. L"allowed/denied by storage filter=%u/%u "
  4051. L"NumStoredMessagesAllowedByRetrievalFilter=%u\r\n",
  4052. (unsigned)pInfoQueue->GetNumStoredMessages(),
  4053. (unsigned)pInfoQueue->GetMessageCountLimit(),
  4054. (unsigned)pInfoQueue->GetNumMessagesDiscardedByMessageCountLimit(),
  4055. (unsigned)pInfoQueue->GetNumMessagesAllowedByStorageFilter(),
  4056. (unsigned)pInfoQueue->GetNumMessagesDeniedByStorageFilter(),
  4057. (unsigned)pInfoQueue->GetNumStoredMessagesAllowedByRetrievalFilter());
  4058. pOutputStrFn(pStrCtx, buf);
  4059. WriteInfoQueueMessages(pStrCtx, pOutputStrFn, pInfoQueue);
  4060. pInfoQueue->ClearStoredMessages();
  4061. pInfoQueue->PopRetrievalFilter();
  4062. pInfoQueue->PopStorageFilter();
  4063. if (FilterCreation) {
  4064. pInfoQueue->PopStorageFilter();
  4065. }
  4066. }
  4067. if (pReadBackDump) *pReadBackDump = pDump.Detach();
  4068. return hr;
  4069. }
  4070. }