ExecutionTest.cpp 184 KB

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