ExecutionTest.cpp 175 KB

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