DxilValidation.cpp 181 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697
  1. ///////////////////////////////////////////////////////////////////////////////
  2. // //
  3. // DxilValidation.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. // This file provides support for validating DXIL shaders. //
  9. // //
  10. ///////////////////////////////////////////////////////////////////////////////
  11. #include "dxc/HLSL/DxilValidation.h"
  12. #include "dxc/HLSL/DxilGenerationPass.h"
  13. #include "dxc/HLSL/DXILOperations.h"
  14. #include "dxc/HLSL/DxilModule.h"
  15. #include "dxc/HLSL/DxilShaderModel.h"
  16. #include "dxc/HLSL/DxilContainer.h"
  17. #include "dxc/Support/Global.h"
  18. #include "dxc/HLSL/DxilUtil.h"
  19. #include "dxc/HLSL/DxilInstructions.h"
  20. #include "dxc/HLSL/ReducibilityAnalysis.h"
  21. #include "dxc/Support/WinIncludes.h"
  22. #include "dxc/Support/FileIOHelper.h"
  23. #include "llvm/ADT/ArrayRef.h"
  24. #include "llvm/Analysis/CallGraph.h"
  25. #include "llvm/IR/LLVMContext.h"
  26. #include "llvm/IR/Module.h"
  27. #include "llvm/IR/Type.h"
  28. #include "llvm/IR/Operator.h"
  29. #include "llvm/IR/Instructions.h"
  30. #include "llvm/IR/InstIterator.h"
  31. #include "llvm/IR/Constants.h"
  32. #include "llvm/IR/DiagnosticInfo.h"
  33. #include "llvm/IR/DiagnosticPrinter.h"
  34. #include "llvm/ADT/BitVector.h"
  35. #include "llvm/Support/raw_ostream.h"
  36. #include "llvm/Support/MemoryBuffer.h"
  37. #include "llvm/Bitcode/ReaderWriter.h"
  38. #include <unordered_set>
  39. #include "llvm/Analysis/LoopInfo.h"
  40. #include "llvm/IR/Dominators.h"
  41. #include "llvm/Analysis/PostDominators.h"
  42. #include "dxc/HLSL/DxilSpanAllocator.h"
  43. #include "dxc/HLSL/DxilSignatureAllocator.h"
  44. #include "dxc/HLSL/DxilRootSignature.h"
  45. #include <algorithm>
  46. using namespace llvm;
  47. using namespace std;
  48. ///////////////////////////////////////////////////////////////////////////////
  49. // Error messages.
  50. const char *hlsl::GetValidationRuleText(ValidationRule value) {
  51. /* <py::lines('VALRULE-TEXT')>hctdb_instrhelp.get_valrule_text()</py>*/
  52. // VALRULE-TEXT:BEGIN
  53. switch(value) {
  54. case hlsl::ValidationRule::BitcodeValid: return "Module bitcode is invalid";
  55. case hlsl::ValidationRule::ContainerPartMatches: return "Container part '%0' does not match expected for module.";
  56. case hlsl::ValidationRule::ContainerPartRepeated: return "More than one container part '%0'.";
  57. case hlsl::ValidationRule::ContainerPartMissing: return "Missing part '%0' required by module.";
  58. case hlsl::ValidationRule::ContainerPartInvalid: return "Unknown part '%0' found in DXIL container.";
  59. case hlsl::ValidationRule::ContainerRootSignatureIncompatible: return "Root Signature in DXIL container is not compatible with shader.";
  60. case hlsl::ValidationRule::MetaRequired: return "TODO - Required metadata missing";
  61. case hlsl::ValidationRule::MetaKnown: return "Named metadata '%0' is unknown";
  62. case hlsl::ValidationRule::MetaUsed: return "All metadata must be used by dxil";
  63. case hlsl::ValidationRule::MetaTarget: return "Unknown target triple '%0'";
  64. case hlsl::ValidationRule::MetaWellFormed: return "TODO - Metadata must be well-formed in operand count and types";
  65. case hlsl::ValidationRule::MetaSemanticLen: return "Semantic length must be at least 1 and at most 64";
  66. case hlsl::ValidationRule::MetaInterpModeValid: return "Invalid interpolation mode for '%0'";
  67. case hlsl::ValidationRule::MetaSemaKindValid: return "Semantic kind for '%0' is invalid";
  68. case hlsl::ValidationRule::MetaNoSemanticOverlap: return "Semantic '%0' overlap at %1";
  69. case hlsl::ValidationRule::MetaSemaKindMatchesName: return "Semantic name %0 does not match System Value kind %1";
  70. case hlsl::ValidationRule::MetaDuplicateSysValue: return "System value %0 appears more than once in the same signature.";
  71. case hlsl::ValidationRule::MetaSemanticIndexMax: return "%0 semantic index exceeds maximum (%1)";
  72. case hlsl::ValidationRule::MetaSystemValueRows: return "rows for system value semantic %0 must be 1";
  73. case hlsl::ValidationRule::MetaSemanticShouldBeAllocated: return "%0 Semantic '%1' should have a valid packing location";
  74. case hlsl::ValidationRule::MetaSemanticShouldNotBeAllocated: return "%0 Semantic '%1' should have a packing location of -1";
  75. case hlsl::ValidationRule::MetaValueRange: return "Metadata value must be within range";
  76. case hlsl::ValidationRule::MetaFlagsUsage: return "Flags must match usage";
  77. case hlsl::ValidationRule::MetaDenseResIDs: return "Resource identifiers must be zero-based and dense";
  78. case hlsl::ValidationRule::MetaSignatureOverlap: return "signature element %0 at location (%1,%2) size (%3,%4) overlaps another signature element.";
  79. case hlsl::ValidationRule::MetaSignatureOutOfRange: return "signature element %0 at location (%1,%2) size (%3,%4) is out of range.";
  80. case hlsl::ValidationRule::MetaSignatureIndexConflict: return "signature element %0 at location (%1,%2) size (%3,%4) has an indexing conflict with another signature element packed into the same row.";
  81. case hlsl::ValidationRule::MetaSignatureIllegalComponentOrder: return "signature element %0 at location (%1,%2) size (%3,%4) violates component ordering rule (arb < sv < sgv).";
  82. case hlsl::ValidationRule::MetaIntegerInterpMode: return "signature element %0 specifies invalid interpolation mode for integer component type.";
  83. case hlsl::ValidationRule::MetaInterpModeInOneRow: return "signature element %0 at location (%1,%2) size (%3,%4) has interpolation mode that differs from another element packed into the same row.";
  84. case hlsl::ValidationRule::MetaSemanticCompType: return "%0 must be %1";
  85. case hlsl::ValidationRule::MetaClipCullMaxRows: return "ClipDistance and CullDistance occupy more than the maximum of 2 rows combined.";
  86. case hlsl::ValidationRule::MetaClipCullMaxComponents: return "ClipDistance and CullDistance use more than the maximum of 8 components combined.";
  87. case hlsl::ValidationRule::MetaSignatureCompType: return "signature %0 specifies unrecognized or invalid component type";
  88. case hlsl::ValidationRule::MetaTessellatorPartition: return "Invalid Tessellator Partitioning specified. Must be integer, pow2, fractional_odd or fractional_even.";
  89. case hlsl::ValidationRule::MetaTessellatorOutputPrimitive: return "Invalid Tessellator Output Primitive specified. Must be point, line, triangleCW or triangleCCW.";
  90. case hlsl::ValidationRule::MetaMaxTessFactor: return "Hull Shader MaxTessFactor must be [%0..%1]. %2 specified";
  91. case hlsl::ValidationRule::MetaValidSamplerMode: return "Invalid sampler mode on sampler ";
  92. case hlsl::ValidationRule::MetaFunctionAnnotation: return "Cannot find function annotation for %0";
  93. case hlsl::ValidationRule::MetaGlcNotOnAppendConsume: return "globallycoherent cannot be used with append/consume buffers";
  94. case hlsl::ValidationRule::MetaStructBufAlignment: return "structured buffer element size must be a multiple of %0 bytes (actual size %1 bytes)";
  95. case hlsl::ValidationRule::MetaStructBufAlignmentOutOfBound: return "structured buffer elements cannot be larger than %0 bytes (actual size %1 bytes)";
  96. case hlsl::ValidationRule::MetaEntryFunction: return "entrypoint not found";
  97. case hlsl::ValidationRule::MetaInvalidControlFlowHint: return "Invalid control flow hint";
  98. case hlsl::ValidationRule::MetaBranchFlatten: return "Can't use branch and flatten attributes together";
  99. case hlsl::ValidationRule::MetaForceCaseOnSwitch: return "Attribute forcecase only works for switch";
  100. case hlsl::ValidationRule::MetaControlFlowHintNotOnControlFlow: return "Control flow hint only works on control flow inst";
  101. case hlsl::ValidationRule::MetaTextureType: return "elements of typed buffers and textures must fit in four 32-bit quantities";
  102. case hlsl::ValidationRule::MetaBarycentricsInterpolation: return "SV_Barycentrics cannot be used with 'nointerpolation' type";
  103. case hlsl::ValidationRule::MetaBarycentricsFloat3: return "only 'float3' type is allowed for SV_Barycentrics.";
  104. case hlsl::ValidationRule::MetaBarycentricsTwoPerspectives: return "There can only be up to two input attributes of SV_Barycentrics with different perspective interpolation mode.";
  105. case hlsl::ValidationRule::MetaFPFlag: return "Invalid funciton floating point flag.";
  106. case hlsl::ValidationRule::InstrOload: return "DXIL intrinsic overload must be valid";
  107. case hlsl::ValidationRule::InstrCallOload: return "Call to DXIL intrinsic '%0' does not match an allowed overload signature";
  108. case hlsl::ValidationRule::InstrPtrBitCast: return "Pointer type bitcast must be have same size";
  109. case hlsl::ValidationRule::InstrMinPrecisonBitCast: return "Bitcast on minprecison types is not allowed";
  110. case hlsl::ValidationRule::InstrStructBitCast: return "Bitcast on struct types is not allowed";
  111. case hlsl::ValidationRule::InstrOpConst: return "%0 of %1 must be an immediate constant";
  112. case hlsl::ValidationRule::InstrAllowed: return "Instructions must be of an allowed type";
  113. case hlsl::ValidationRule::InstrOpCodeReserved: return "Instructions must not reference reserved opcodes";
  114. case hlsl::ValidationRule::InstrOperandRange: return "expect %0 between %1, got %2";
  115. case hlsl::ValidationRule::InstrNoReadingUninitialized: return "Instructions should not read uninitialized value";
  116. case hlsl::ValidationRule::InstrNoGenericPtrAddrSpaceCast: return "Address space cast between pointer types must have one part to be generic address space";
  117. case hlsl::ValidationRule::InstrInBoundsAccess: return "Access to out-of-bounds memory is disallowed";
  118. case hlsl::ValidationRule::InstrOpConstRange: return "Constant values must be in-range for operation";
  119. case hlsl::ValidationRule::InstrImmBiasForSampleB: return "bias amount for sample_b must be in the range [%0,%1], but %2 was specified as an immediate";
  120. case hlsl::ValidationRule::InstrNoIndefiniteLog: return "No indefinite logarithm";
  121. case hlsl::ValidationRule::InstrNoIndefiniteAsin: return "No indefinite arcsine";
  122. case hlsl::ValidationRule::InstrNoIndefiniteAcos: return "No indefinite arccosine";
  123. case hlsl::ValidationRule::InstrNoIDivByZero: return "No signed integer division by zero";
  124. case hlsl::ValidationRule::InstrNoUDivByZero: return "No unsigned integer division by zero";
  125. case hlsl::ValidationRule::InstrNoIndefiniteDsxy: return "No indefinite derivative calculation";
  126. case hlsl::ValidationRule::InstrMinPrecisionNotPrecise: return "Instructions marked precise may not refer to minprecision values";
  127. case hlsl::ValidationRule::InstrOnlyOneAllocConsume: return "RWStructuredBuffers may increment or decrement their counters, but not both.";
  128. case hlsl::ValidationRule::InstrTextureOffset: return "offset texture instructions must take offset which can resolve to integer literal in the range -8 to 7";
  129. case hlsl::ValidationRule::InstrCannotPullPosition: return "%0 does not support pull-model evaluation of position";
  130. case hlsl::ValidationRule::InstrEvalInterpolationMode: return "Interpolation mode on %0 used with eval_* instruction must be linear, linear_centroid, linear_noperspective, linear_noperspective_centroid, linear_sample or linear_noperspective_sample";
  131. case hlsl::ValidationRule::InstrResourceCoordinateMiss: return "coord uninitialized";
  132. case hlsl::ValidationRule::InstrResourceCoordinateTooMany: return "out of bound coord must be undef";
  133. case hlsl::ValidationRule::InstrResourceOffsetMiss: return "offset uninitialized";
  134. case hlsl::ValidationRule::InstrResourceOffsetTooMany: return "out of bound offset must be undef";
  135. case hlsl::ValidationRule::InstrUndefResultForGetDimension: return "GetDimensions used undef dimension %0 on %1";
  136. case hlsl::ValidationRule::InstrSamplerModeForLOD: return "lod instruction requires sampler declared in default mode";
  137. case hlsl::ValidationRule::InstrSamplerModeForSample: return "sample/_l/_d/_cl_s/gather instruction requires sampler declared in default mode";
  138. case hlsl::ValidationRule::InstrSamplerModeForSampleC: return "sample_c_*/gather_c instructions require sampler declared in comparison mode";
  139. case hlsl::ValidationRule::InstrSampleCompType: return "sample_* instructions require resource to be declared to return UNORM, SNORM or FLOAT.";
  140. case hlsl::ValidationRule::InstrBarrierModeUselessUGroup: return "sync can't specify both _ugroup and _uglobal. If both are needed, just specify _uglobal.";
  141. case hlsl::ValidationRule::InstrBarrierModeNoMemory: return "sync must include some form of memory barrier - _u (UAV) and/or _g (Thread Group Shared Memory). Only _t (thread group sync) is optional. ";
  142. case hlsl::ValidationRule::InstrBarrierModeForNonCS: return "sync in a non-Compute Shader must only sync UAV (sync_uglobal)";
  143. case hlsl::ValidationRule::InstrWriteMaskForTypedUAVStore: return "store on typed uav must write to all four components of the UAV";
  144. case hlsl::ValidationRule::InstrResourceKindForCalcLOD: return "lod requires resource declared as texture1D/2D/3D/Cube/CubeArray/1DArray/2DArray";
  145. case hlsl::ValidationRule::InstrResourceKindForSample: return "sample/_l/_d requires resource declared as texture1D/2D/3D/Cube/1DArray/2DArray/CubeArray";
  146. case hlsl::ValidationRule::InstrResourceKindForSampleC: return "samplec requires resource declared as texture1D/2D/Cube/1DArray/2DArray/CubeArray";
  147. case hlsl::ValidationRule::InstrResourceKindForGather: return "gather requires resource declared as texture/2D/Cube/2DArray/CubeArray";
  148. case hlsl::ValidationRule::InstrWriteMaskMatchValueForUAVStore: return "uav store write mask must match store value mask, write mask is %0 and store value mask is %1";
  149. case hlsl::ValidationRule::InstrResourceKindForBufferLoadStore: return "buffer load/store only works on Raw/Typed/StructuredBuffer";
  150. case hlsl::ValidationRule::InstrResourceKindForTextureStore: return "texture store only works on Texture1D/1DArray/2D/2DArray/3D";
  151. case hlsl::ValidationRule::InstrResourceKindForGetDim: return "Invalid resource kind on GetDimensions";
  152. case hlsl::ValidationRule::InstrResourceKindForTextureLoad: return "texture load only works on Texture1D/1DArray/2D/2DArray/3D/MS2D/MS2DArray";
  153. case hlsl::ValidationRule::InstrResourceClassForSamplerGather: return "sample, lod and gather should on srv resource.";
  154. case hlsl::ValidationRule::InstrResourceClassForUAVStore: return "store should on uav resource.";
  155. case hlsl::ValidationRule::InstrResourceClassForLoad: return "load can only run on UAV/SRV resource";
  156. case hlsl::ValidationRule::InstrOffsetOnUAVLoad: return "uav load don't support offset";
  157. case hlsl::ValidationRule::InstrMipOnUAVLoad: return "uav load don't support mipLevel/sampleIndex";
  158. case hlsl::ValidationRule::InstrSampleIndexForLoad2DMS: return "load on Texture2DMS/2DMSArray require sampleIndex";
  159. case hlsl::ValidationRule::InstrCoordinateCountForRawTypedBuf: return "raw/typed buffer don't need 2 coordinates";
  160. case hlsl::ValidationRule::InstrCoordinateCountForStructBuf: return "structured buffer require 2 coordinates";
  161. case hlsl::ValidationRule::InstrMipLevelForGetDimension: return "Use mip level on buffer when GetDimensions";
  162. case hlsl::ValidationRule::InstrDxilStructUser: return "Dxil struct types should only used by ExtractValue";
  163. case hlsl::ValidationRule::InstrDxilStructUserOutOfBound: return "Index out of bound when extract value from dxil struct types";
  164. case hlsl::ValidationRule::InstrHandleNotFromCreateHandle: return "Resource handle should returned by createHandle";
  165. case hlsl::ValidationRule::InstrBufferUpdateCounterOnUAV: return "BufferUpdateCounter valid only on UAV";
  166. case hlsl::ValidationRule::InstrCBufferOutOfBound: return "Cbuffer access out of bound";
  167. case hlsl::ValidationRule::InstrCBufferClassForCBufferHandle: return "Expect Cbuffer for CBufferLoad handle";
  168. case hlsl::ValidationRule::InstrFailToResloveTGSMPointer: return "TGSM pointers must originate from an unambiguous TGSM global variable.";
  169. case hlsl::ValidationRule::InstrExtractValue: return "ExtractValue should only be used on dxil struct types and cmpxchg";
  170. case hlsl::ValidationRule::InstrTGSMRaceCond: return "Race condition writing to shared memory detected, consider making this write conditional";
  171. case hlsl::ValidationRule::InstrAttributeAtVertexNoInterpolation: return "Attribute %0 must have nointerpolation mode in order to use GetAttributeAtVertex function.";
  172. case hlsl::ValidationRule::TypesNoVector: return "Vector type '%0' is not allowed";
  173. case hlsl::ValidationRule::TypesDefined: return "Type '%0' is not defined on DXIL primitives";
  174. case hlsl::ValidationRule::TypesIntWidth: return "Int type '%0' has an invalid width";
  175. case hlsl::ValidationRule::TypesNoMultiDim: return "Only one dimension allowed for array type";
  176. case hlsl::ValidationRule::TypesI8: return "I8 can only used as immediate value for intrinsic";
  177. case hlsl::ValidationRule::SmName: return "Unknown shader model '%0'";
  178. case hlsl::ValidationRule::SmDxilVersion: return "Shader model requires Dxil Version %0,%1";
  179. case hlsl::ValidationRule::SmOpcode: return "Opcode %0 not valid in shader model %1";
  180. case hlsl::ValidationRule::SmOperand: return "Operand must be defined in target shader model";
  181. case hlsl::ValidationRule::SmSemantic: return "Semantic '%0' is invalid as %1 %2";
  182. case hlsl::ValidationRule::SmNoInterpMode: return "Interpolation mode for '%0' is set but should be undefined";
  183. case hlsl::ValidationRule::SmNoPSOutputIdx: return "Pixel shader output registers are not indexable.";
  184. case hlsl::ValidationRule::SmPSConsistentInterp: return "Interpolation mode for PS input position must be linear_noperspective_centroid or linear_noperspective_sample when outputting oDepthGE or oDepthLE and not running at sample frequency (which is forced by inputting SV_SampleIndex or declaring an input linear_sample or linear_noperspective_sample)";
  185. case hlsl::ValidationRule::SmThreadGroupChannelRange: return "Declared Thread Group %0 size %1 outside valid range [%2..%3]";
  186. case hlsl::ValidationRule::SmMaxTheadGroup: return "Declared Thread Group Count %0 (X*Y*Z) is beyond the valid maximum of %1";
  187. case hlsl::ValidationRule::SmMaxTGSMSize: return "Total Thread Group Shared Memory storage is %0, exceeded %1";
  188. case hlsl::ValidationRule::SmROVOnlyInPS: return "RasterizerOrdered objects are only allowed in 5.0+ pixel shaders";
  189. case hlsl::ValidationRule::SmTessFactorForDomain: return "Required TessFactor for domain not found declared anywhere in Patch Constant data";
  190. case hlsl::ValidationRule::SmTessFactorSizeMatchDomain: return "TessFactor rows, columns (%0, %1) invalid for domain %2. Expected %3 rows and 1 column.";
  191. case hlsl::ValidationRule::SmInsideTessFactorSizeMatchDomain: return "InsideTessFactor rows, columns (%0, %1) invalid for domain %2. Expected %3 rows and 1 column.";
  192. case hlsl::ValidationRule::SmDomainLocationIdxOOB: return "DomainLocation component index out of bounds for the domain.";
  193. case hlsl::ValidationRule::SmHullPassThruControlPointCountMatch: return "For pass thru hull shader, input control point count must match output control point count";
  194. case hlsl::ValidationRule::SmOutputControlPointsTotalScalars: return "Total number of scalars across all HS output control points must not exceed ";
  195. case hlsl::ValidationRule::SmIsoLineOutputPrimitiveMismatch: return "Hull Shader declared with IsoLine Domain must specify output primitive point or line. Triangle_cw or triangle_ccw output are not compatible with the IsoLine Domain.";
  196. case hlsl::ValidationRule::SmTriOutputPrimitiveMismatch: return "Hull Shader declared with Tri Domain must specify output primitive point, triangle_cw or triangle_ccw. Line output is not compatible with the Tri domain";
  197. case hlsl::ValidationRule::SmValidDomain: return "Invalid Tessellator Domain specified. Must be isoline, tri or quad";
  198. case hlsl::ValidationRule::SmPatchConstantOnlyForHSDS: return "patch constant signature only valid in HS and DS";
  199. case hlsl::ValidationRule::SmStreamIndexRange: return "Stream index (%0) must between 0 and %1";
  200. case hlsl::ValidationRule::SmPSOutputSemantic: return "Pixel Shader allows output semantics to be SV_Target, SV_Depth, SV_DepthGreaterEqual, SV_DepthLessEqual, SV_Coverage or SV_StencilRef, %0 found";
  201. case hlsl::ValidationRule::SmPSMultipleDepthSemantic: return "Pixel Shader only allows one type of depth semantic to be declared";
  202. case hlsl::ValidationRule::SmPSTargetIndexMatchesRow: return "SV_Target semantic index must match packed row location";
  203. case hlsl::ValidationRule::SmPSTargetCol0: return "SV_Target packed location must start at column 0";
  204. case hlsl::ValidationRule::SmPSCoverageAndInnerCoverage: return "InnerCoverage and Coverage are mutually exclusive.";
  205. case hlsl::ValidationRule::SmGSOutputVertexCountRange: return "GS output vertex count must be [0..%0]. %1 specified";
  206. case hlsl::ValidationRule::SmGSInstanceCountRange: return "GS instance count must be [1..%0]. %1 specified";
  207. case hlsl::ValidationRule::SmDSInputControlPointCountRange: return "DS input control point count must be [0..%0]. %1 specified";
  208. case hlsl::ValidationRule::SmHSInputControlPointCountRange: return "HS input control point count must be [0..%0]. %1 specified";
  209. case hlsl::ValidationRule::SmZeroHSInputControlPointWithInput: return "When HS input control point count is 0, no input signature should exist";
  210. case hlsl::ValidationRule::SmOutputControlPointCountRange: return "output control point count must be [0..%0]. %1 specified";
  211. case hlsl::ValidationRule::SmGSValidInputPrimitive: return "GS input primitive unrecognized";
  212. case hlsl::ValidationRule::SmGSValidOutputPrimitiveTopology: return "GS output primitive topology unrecognized";
  213. case hlsl::ValidationRule::SmAppendAndConsumeOnSameUAV: return "BufferUpdateCounter inc and dec on a given UAV (%d) cannot both be in the same shader for shader model less than 5.1.";
  214. case hlsl::ValidationRule::SmInvalidTextureKindOnUAV: return "Texture2DMS[Array] or TextureCube[Array] resources are not supported with UAVs";
  215. case hlsl::ValidationRule::SmInvalidResourceKind: return "Invalid resources kind";
  216. case hlsl::ValidationRule::SmInvalidResourceCompType: return "Invalid resource return type";
  217. case hlsl::ValidationRule::SmSampleCountOnlyOn2DMS: return "Only Texture2DMS/2DMSArray could has sample count";
  218. case hlsl::ValidationRule::SmCounterOnlyOnStructBuf: return "BufferUpdateCounter valid only on structured buffers";
  219. case hlsl::ValidationRule::SmGSTotalOutputVertexDataRange: return "Declared output vertex count (%0) multiplied by the total number of declared scalar components of output data (%1) equals %2. This value cannot be greater than %3";
  220. case hlsl::ValidationRule::SmMultiStreamMustBePoint: return "Multiple GS output streams are used but '%0' is not pointlist";
  221. case hlsl::ValidationRule::SmCompletePosition: return "Not all elements of SV_Position were written";
  222. case hlsl::ValidationRule::SmUndefinedOutput: return "Not all elements of output %0 were written";
  223. case hlsl::ValidationRule::SmCSNoReturn: return "Compute shaders can't return values, outputs must be written in writable resources (UAVs).";
  224. case hlsl::ValidationRule::SmCBufferTemplateTypeMustBeStruct: return "D3D12 constant/texture buffer template element can only be a struct";
  225. case hlsl::ValidationRule::SmResourceRangeOverlap: return "Resource %0 with base %1 size %2 overlap with other resource with base %3 size %4 in space %5";
  226. case hlsl::ValidationRule::SmCBufferOffsetOverlap: return "CBuffer %0 has offset overlaps at %1";
  227. case hlsl::ValidationRule::SmCBufferElementOverflow: return "CBuffer %0 size insufficient for element at offset %1";
  228. case hlsl::ValidationRule::SmOpcodeInInvalidFunction: return "opcode '%0' should only used in '%1'";
  229. case hlsl::ValidationRule::SmViewIDNeedsSlot: return "Pixel shader input signature lacks available space for ViewID";
  230. case hlsl::ValidationRule::UniNoWaveSensitiveGradient: return "Gradient operations are not affected by wave-sensitive data or control flow.";
  231. case hlsl::ValidationRule::FlowReducible: return "Execution flow must be reducible";
  232. case hlsl::ValidationRule::FlowNoRecusion: return "Recursion is not permitted";
  233. case hlsl::ValidationRule::FlowDeadLoop: return "Loop must have break";
  234. case hlsl::ValidationRule::FlowFunctionCall: return "Function %0 with parameter is not permitted, it should be inlined";
  235. case hlsl::ValidationRule::DeclDxilNsReserved: return "Declaration '%0' uses a reserved prefix";
  236. case hlsl::ValidationRule::DeclDxilFnExtern: return "External function '%0' is not a DXIL function";
  237. case hlsl::ValidationRule::DeclUsedInternal: return "Internal declaration '%0' is unused";
  238. case hlsl::ValidationRule::DeclNotUsedExternal: return "External declaration '%0' is unused";
  239. case hlsl::ValidationRule::DeclUsedExternalFunction: return "External function '%0' is unused";
  240. case hlsl::ValidationRule::DeclFnIsCalled: return "Function '%0' is used for something other than calling";
  241. case hlsl::ValidationRule::DeclFnFlattenParam: return "Type '%0' is a struct type but is used as a parameter in function '%1'";
  242. }
  243. // VALRULE-TEXT:END
  244. llvm_unreachable("invalid value");
  245. return "<unknown>";
  246. }
  247. namespace {
  248. // Utility class for setting and restoring the diagnostic context so we may capture errors/warnings
  249. struct DiagRestore {
  250. LLVMContext &Ctx;
  251. void *OrigDiagContext;
  252. LLVMContext::DiagnosticHandlerTy OrigHandler;
  253. DiagRestore(llvm::LLVMContext &Ctx, void *DiagContext) : Ctx(Ctx) {
  254. OrigHandler = Ctx.getDiagnosticHandler();
  255. OrigDiagContext = Ctx.getDiagnosticContext();
  256. Ctx.setDiagnosticHandler(
  257. hlsl::PrintDiagnosticContext::PrintDiagnosticHandler, DiagContext);
  258. }
  259. ~DiagRestore() {
  260. Ctx.setDiagnosticHandler(OrigHandler, OrigDiagContext);
  261. }
  262. };
  263. class DxilErrorDiagnosticInfo : public DiagnosticInfo {
  264. private:
  265. const char *m_message;
  266. public:
  267. DxilErrorDiagnosticInfo(const char *str)
  268. : DiagnosticInfo(DK_FirstPluginKind, DiagnosticSeverity::DS_Error),
  269. m_message(str) { }
  270. __override void print(DiagnosticPrinter &DP) const {
  271. DP << m_message;
  272. }
  273. };
  274. static void emitDxilDiag(const LLVMContext &Ctx, const char *str) {
  275. // diagnose doesn't actually mutate anything.
  276. LLVMContext &diagCtx = const_cast<LLVMContext &>(Ctx);
  277. diagCtx.diagnose(DxilErrorDiagnosticInfo(str));
  278. }
  279. // Printing of types.
  280. static inline DiagnosticPrinter &operator<<(DiagnosticPrinter &OS, Type &T) {
  281. std::string O;
  282. raw_string_ostream OSS(O);
  283. T.print(OSS);
  284. OS << OSS.str();
  285. return OS;
  286. }
  287. } // anon namespace
  288. namespace hlsl {
  289. // PrintDiagnosticContext methods.
  290. PrintDiagnosticContext::PrintDiagnosticContext(DiagnosticPrinter &printer)
  291. : m_Printer(printer), m_errorsFound(false), m_warningsFound(false) {}
  292. bool PrintDiagnosticContext::HasErrors() const { return m_errorsFound; }
  293. bool PrintDiagnosticContext::HasWarnings() const { return m_warningsFound; }
  294. void PrintDiagnosticContext::Handle(const DiagnosticInfo &DI) {
  295. DI.print(m_Printer);
  296. switch (DI.getSeverity()) {
  297. case llvm::DiagnosticSeverity::DS_Error:
  298. m_errorsFound = true;
  299. break;
  300. case llvm::DiagnosticSeverity::DS_Warning:
  301. m_warningsFound = true;
  302. break;
  303. default:
  304. break;
  305. }
  306. m_Printer << "\n";
  307. }
  308. void PrintDiagnosticContext::PrintDiagnosticHandler(const DiagnosticInfo &DI, void *Context) {
  309. reinterpret_cast<hlsl::PrintDiagnosticContext *>(Context)->Handle(DI);
  310. }
  311. struct PSExecutionInfo {
  312. bool SuperSampling = false;
  313. DXIL::SemanticKind OutputDepthKind = DXIL::SemanticKind::Invalid;
  314. const InterpolationMode *PositionInterpolationMode = nullptr;
  315. };
  316. struct ValidationContext {
  317. bool Failed = false;
  318. Module &M;
  319. Module *pDebugModule;
  320. DxilModule &DxilMod;
  321. const DataLayout &DL;
  322. DiagnosticPrinterRawOStream &DiagPrinter;
  323. PSExecutionInfo PSExec;
  324. DebugLoc LastDebugLocEmit;
  325. ValidationRule LastRuleEmit;
  326. std::unordered_set<Function *> entryFuncCallSet;
  327. std::unordered_set<Function *> patchConstFuncCallSet;
  328. std::unordered_map<unsigned, bool> UavCounterIncMap;
  329. bool hasOutputPosition[DXIL::kNumOutputStreams];
  330. bool hasViewID;
  331. unsigned OutputPositionMask[DXIL::kNumOutputStreams];
  332. std::vector<unsigned> outputCols;
  333. std::vector<unsigned> patchConstCols;
  334. unsigned domainLocSize;
  335. const unsigned kDxilControlFlowHintMDKind;
  336. const unsigned kDxilPreciseMDKind;
  337. const unsigned kLLVMLoopMDKind;
  338. bool m_bCoverageIn, m_bInnerCoverageIn;
  339. unsigned m_DxilMajor, m_DxilMinor;
  340. ValidationContext(Module &llvmModule, Module *DebugModule,
  341. DxilModule &dxilModule,
  342. DiagnosticPrinterRawOStream &DiagPrn)
  343. : M(llvmModule), pDebugModule(DebugModule), DxilMod(dxilModule),
  344. DL(llvmModule.getDataLayout()),
  345. kDxilControlFlowHintMDKind(llvmModule.getContext().getMDKindID(
  346. DxilMDHelper::kDxilControlFlowHintMDName)),
  347. kDxilPreciseMDKind(llvmModule.getContext().getMDKindID(
  348. DxilMDHelper::kDxilPreciseAttributeMDName)),
  349. kLLVMLoopMDKind(llvmModule.getContext().getMDKindID("llvm.loop")),
  350. DiagPrinter(DiagPrn), LastRuleEmit((ValidationRule)-1),
  351. m_bCoverageIn(false), m_bInnerCoverageIn(false),
  352. hasViewID(false) {
  353. DxilMod.GetDxilVersion(m_DxilMajor, m_DxilMinor);
  354. for (unsigned i = 0; i < DXIL::kNumOutputStreams; i++) {
  355. hasOutputPosition[i] = false;
  356. OutputPositionMask[i] = 0;
  357. }
  358. outputCols.resize(DxilMod.GetOutputSignature().GetElements().size(), 0);
  359. patchConstCols.resize(DxilMod.GetPatchConstantSignature().GetElements().size(), 0);
  360. }
  361. // Provide direct access to the raw_ostream in DiagPrinter.
  362. raw_ostream &DiagStream() {
  363. struct DiagnosticPrinterRawOStream_Pub : public DiagnosticPrinterRawOStream {
  364. public:
  365. raw_ostream &DiagStream() { return Stream; }
  366. };
  367. DiagnosticPrinterRawOStream_Pub* p = (DiagnosticPrinterRawOStream_Pub*)&DiagPrinter;
  368. return p->DiagStream();
  369. }
  370. void EmitGlobalValueError(GlobalValue *GV, ValidationRule rule) {
  371. EmitFormatError(rule, { GV->getName().str() });
  372. }
  373. // This is the least desirable mechanism, as it has no context.
  374. void EmitError(ValidationRule rule) {
  375. DiagPrinter << GetValidationRuleText(rule) << '\n';
  376. Failed = true;
  377. }
  378. void FormatRuleText(std::string &ruleText, ArrayRef<StringRef> args) {
  379. // Consider changing const char * to StringRef
  380. for (unsigned i = 0; i < args.size(); i++) {
  381. std::string argIdx = "%" + std::to_string(i);
  382. StringRef pArg = args[i];
  383. if (pArg == "")
  384. pArg = "<null>";
  385. std::string::size_type offset = ruleText.find(argIdx);
  386. if (offset == std::string::npos)
  387. continue;
  388. unsigned size = argIdx.size();
  389. ruleText.replace(offset, size, args[i]);
  390. }
  391. }
  392. void EmitFormatError(ValidationRule rule, ArrayRef<StringRef> args) {
  393. std::string ruleText = GetValidationRuleText(rule);
  394. FormatRuleText(ruleText, args);
  395. DiagPrinter << ruleText << '\n';
  396. Failed = true;
  397. }
  398. void EmitMetaError(Metadata *Meta, ValidationRule rule) {
  399. DiagPrinter << GetValidationRuleText(rule);
  400. Meta->print(DiagStream(), &M);
  401. DiagPrinter << '\n';
  402. Failed = true;
  403. }
  404. void EmitResourceError(const hlsl::DxilResourceBase *Res, ValidationRule rule) {
  405. DiagPrinter << GetValidationRuleText(rule);
  406. DiagPrinter << '\'' << Res->GetGlobalName() << '\'';
  407. DiagPrinter << '\n';
  408. Failed = true;
  409. }
  410. void EmitResourceFormatError(const hlsl::DxilResourceBase *Res,
  411. ValidationRule rule,
  412. ArrayRef<StringRef> args) {
  413. std::string ruleText = GetValidationRuleText(rule);
  414. FormatRuleText(ruleText, args);
  415. DiagPrinter << ruleText;
  416. DiagPrinter << '\'' << Res->GetGlobalName() << '\'';
  417. DiagPrinter << '\n';
  418. Failed = true;
  419. }
  420. bool IsDebugFunctionCall(Instruction *I) {
  421. CallInst *CI = dyn_cast<CallInst>(I);
  422. return CI && CI->getCalledFunction()->getName().startswith("llvm.dbg.");
  423. }
  424. DebugLoc GetDebugLoc(Instruction *I) {
  425. DXASSERT_NOMSG(I);
  426. if (pDebugModule) {
  427. // Look up the matching instruction in the debug module.
  428. llvm::Function *Fn = I->getParent()->getParent();
  429. llvm::Function *DbgFn = pDebugModule->getFunction(Fn->getName());
  430. if (DbgFn) {
  431. // Linear lookup, but then again, failing validation is rare.
  432. inst_iterator it = inst_begin(Fn);
  433. inst_iterator dbg_it = inst_begin(DbgFn);
  434. while (IsDebugFunctionCall(&*dbg_it)) ++dbg_it;
  435. while (&*it != I) {
  436. ++it;
  437. ++dbg_it;
  438. while (IsDebugFunctionCall(&*dbg_it)) ++dbg_it;
  439. }
  440. return dbg_it->getDebugLoc();
  441. }
  442. }
  443. return I->getDebugLoc();
  444. }
  445. bool EmitInstrLoc(Instruction *I, ValidationRule Rule) {
  446. const DebugLoc &L = GetDebugLoc(I);
  447. if (L) {
  448. // Instructions that get scalarized will likely hit
  449. // this case. Avoid redundant diagnostic messages.
  450. if (Rule == LastRuleEmit && L == LastDebugLocEmit) {
  451. return false;
  452. }
  453. LastRuleEmit = Rule;
  454. LastDebugLocEmit = L;
  455. L.print(DiagStream());
  456. DiagPrinter << ' ';
  457. return true;
  458. }
  459. BasicBlock *BB = I->getParent();
  460. Function *F = BB->getParent();
  461. DiagPrinter << "at " << I;
  462. DiagPrinter << " inside block ";
  463. if (!BB->getName().empty()) {
  464. DiagPrinter << BB->getName();
  465. }
  466. else {
  467. unsigned idx = 0;
  468. for (auto i = F->getBasicBlockList().begin(),
  469. e = F->getBasicBlockList().end(); i != e; ++i) {
  470. if (BB == &(*i)) {
  471. break;
  472. }
  473. }
  474. DiagPrinter << "#" << idx;
  475. }
  476. DiagPrinter << " of function " << *F << ' ';
  477. return true;
  478. }
  479. void EmitInstrError(Instruction *I, ValidationRule rule) {
  480. if (!EmitInstrLoc(I, rule)) return;
  481. DiagPrinter << GetValidationRuleText(rule);
  482. DiagPrinter << '\n';
  483. Failed = true;
  484. }
  485. void EmitInstrFormatError(Instruction *I, ValidationRule rule, ArrayRef<StringRef> args) {
  486. if (!EmitInstrLoc(I, rule)) return;
  487. std::string ruleText = GetValidationRuleText(rule);
  488. FormatRuleText(ruleText, args);
  489. DiagPrinter << ruleText;
  490. DiagPrinter << '\n';
  491. Failed = true;
  492. }
  493. void EmitOperandOutOfRange(Instruction *I, StringRef name, StringRef range, StringRef v) {
  494. if (!EmitInstrLoc(I, ValidationRule::InstrOperandRange)) return;
  495. std::string ruleText = GetValidationRuleText(ValidationRule::InstrOperandRange);
  496. FormatRuleText(ruleText, {name, range, v});
  497. DiagPrinter << ruleText;
  498. DiagPrinter << '\n';
  499. Failed = true;
  500. }
  501. void EmitSignatureError(DxilSignatureElement *SE, ValidationRule rule) {
  502. EmitFormatError(rule, { SE->GetName() });
  503. }
  504. void EmitTypeError(Type *Ty, ValidationRule rule) {
  505. std::string O;
  506. raw_string_ostream OSS(O);
  507. Ty->print(OSS);
  508. EmitFormatError(rule, { OSS.str() });
  509. }
  510. };
  511. static bool ValidateOpcodeInProfile(DXIL::OpCode opcode,
  512. const ShaderModel *pSM) {
  513. unsigned op = (unsigned)opcode;
  514. /* <py::lines('VALOPCODESM-TEXT')>hctdb_instrhelp.get_valopcode_sm_text()</py>*/
  515. // VALOPCODESM-TEXT:BEGIN
  516. // Instructions: ThreadId=93, GroupId=94, ThreadIdInGroup=95,
  517. // FlattenedThreadIdInGroup=96
  518. if (93 <= op && op <= 96)
  519. return (pSM->IsCS());
  520. // Instructions: DomainLocation=105
  521. if (op == 105)
  522. return (pSM->IsDS());
  523. // Instructions: LoadOutputControlPoint=103, LoadPatchConstant=104
  524. if (103 <= op && op <= 104)
  525. return (pSM->IsDS() || pSM->IsHS());
  526. // Instructions: EmitStream=97, CutStream=98, EmitThenCutStream=99,
  527. // GSInstanceID=100
  528. if (97 <= op && op <= 100)
  529. return (pSM->IsGS());
  530. // Instructions: PrimitiveID=108
  531. if (op == 108)
  532. return (pSM->IsGS() || pSM->IsDS() || pSM->IsHS() || pSM->IsPS());
  533. // Instructions: StorePatchConstant=106, OutputControlPointID=107
  534. if (106 <= op && op <= 107)
  535. return (pSM->IsHS());
  536. // Instructions: Sample=60, SampleBias=61, SampleCmp=64,
  537. // RenderTargetGetSamplePosition=76, RenderTargetGetSampleCount=77,
  538. // CalculateLOD=81, Discard=82, DerivCoarseX=83, DerivCoarseY=84,
  539. // DerivFineX=85, DerivFineY=86, EvalSnapped=87, EvalSampleIndex=88,
  540. // EvalCentroid=89, SampleIndex=90, Coverage=91, InnerCoverage=92
  541. if (60 <= op && op <= 61 || op == 64 || 76 <= op && op <= 77 || 81 <= op && op <= 92)
  542. return (pSM->IsPS());
  543. // Instructions: AttributeAtVertex=137
  544. if (op == 137)
  545. return (pSM->GetMajor() > 6 || (pSM->GetMajor() == 6 && pSM->GetMinor() >= 1))
  546. && (pSM->IsPS());
  547. // Instructions: ViewID=138
  548. if (op == 138)
  549. return (pSM->GetMajor() > 6 || (pSM->GetMajor() == 6 && pSM->GetMinor() >= 1))
  550. && (pSM->IsVS() || pSM->IsHS() || pSM->IsDS() || pSM->IsGS() || pSM->IsPS());
  551. return true;
  552. // VALOPCODESM-TEXT:END
  553. }
  554. static unsigned ValidateSignatureRowCol(Instruction *I, DxilSignatureElement &SE,
  555. Value *rowVal, Value *colVal,
  556. ValidationContext &ValCtx) {
  557. if (ConstantInt *constRow = dyn_cast<ConstantInt>(rowVal)) {
  558. unsigned row = constRow->getLimitedValue();
  559. if (row >= SE.GetRows()) {
  560. ValCtx.EmitInstrError(I, ValidationRule::InstrOperandRange);
  561. }
  562. }
  563. if (!isa<ConstantInt>(colVal)) {
  564. // col must be const
  565. ValCtx.EmitInstrFormatError(I, ValidationRule::InstrOpConst,
  566. {"Col", "LoadInput/StoreOutput"});
  567. return 0;
  568. }
  569. unsigned col = cast<ConstantInt>(colVal)->getLimitedValue();
  570. if (col > SE.GetCols()) {
  571. ValCtx.EmitInstrError(I, ValidationRule::InstrOperandRange);
  572. } else {
  573. if (SE.IsOutput())
  574. ValCtx.outputCols[SE.GetID()] |= 1 << col;
  575. if (SE.IsPatchConstant())
  576. ValCtx.patchConstCols[SE.GetID()] |= 1 << col;
  577. }
  578. return col;
  579. }
  580. static DxilSignatureElement *ValidateSignatureAccess(Instruction *I, DxilSignature &sig,
  581. Value *sigID, Value *rowVal, Value *colVal,
  582. ValidationContext &ValCtx) {
  583. if (!isa<ConstantInt>(sigID)) {
  584. // inputID must be const
  585. ValCtx.EmitInstrFormatError(I, ValidationRule::InstrOpConst,
  586. {"SignatureID", "LoadInput/StoreOutput"});
  587. return nullptr;
  588. }
  589. unsigned SEIdx = cast<ConstantInt>(sigID)->getLimitedValue();
  590. if (sig.GetElements().size() <= SEIdx) {
  591. ValCtx.EmitInstrError(I, ValidationRule::InstrOpConstRange);
  592. return nullptr;
  593. }
  594. DxilSignatureElement &SE = sig.GetElement(SEIdx);
  595. bool isOutput = sig.IsOutput();
  596. unsigned col = ValidateSignatureRowCol(I, SE, rowVal, colVal, ValCtx);
  597. if (isOutput && SE.GetSemantic()->GetKind() == DXIL::SemanticKind::Position) {
  598. unsigned mask = ValCtx.OutputPositionMask[SE.GetOutputStream()];
  599. mask |= 1<<col;
  600. if (SE.GetOutputStream() < DXIL::kNumOutputStreams)
  601. ValCtx.OutputPositionMask[SE.GetOutputStream()] = mask;
  602. }
  603. return &SE;
  604. }
  605. static DXIL::SamplerKind GetSamplerKind(Value *samplerHandle, ValidationContext &ValCtx) {
  606. if (!isa<CallInst>(samplerHandle)) {
  607. ValCtx.EmitError(ValidationRule::InstrHandleNotFromCreateHandle);
  608. return DXIL::SamplerKind::Invalid;
  609. }
  610. DxilInst_CreateHandle createHandle(cast<CallInst>(samplerHandle));
  611. if (!createHandle) {
  612. ValCtx.EmitInstrError(cast<CallInst>(samplerHandle), ValidationRule::InstrHandleNotFromCreateHandle);
  613. return DXIL::SamplerKind::Invalid;
  614. }
  615. Value *resClass = createHandle.get_resourceClass();
  616. if (!isa<ConstantInt>(resClass)) {
  617. return DXIL::SamplerKind::Invalid;
  618. }
  619. if (createHandle.get_resourceClass_val() != static_cast<unsigned>(DXIL::ResourceClass::Sampler)) {
  620. // must be sampler.
  621. return DXIL::SamplerKind::Invalid;
  622. }
  623. Value *rangeIndex = createHandle.get_rangeId();
  624. if (!isa<ConstantInt>(rangeIndex)) {
  625. // must be constant
  626. return DXIL::SamplerKind::Invalid;
  627. }
  628. unsigned samplerIndex = cast<ConstantInt>(rangeIndex)->getLimitedValue();
  629. auto &samplers = ValCtx.DxilMod.GetSamplers();
  630. if (samplerIndex >= samplers.size()) {
  631. return DXIL::SamplerKind::Invalid;
  632. }
  633. DxilSampler *sampler = samplers[samplerIndex].get();
  634. Value *index = createHandle.get_index();
  635. ConstantInt *cIndex = dyn_cast<ConstantInt>(index);
  636. if (!sampler->GetGlobalSymbol()->getType()->getPointerElementType()->isArrayTy()) {
  637. if (!cIndex) {
  638. // index must be 0 for none array resource.
  639. return DXIL::SamplerKind::Invalid;
  640. }
  641. }
  642. if (cIndex) {
  643. unsigned index = cIndex->getLimitedValue();
  644. if (index < sampler->GetLowerBound() || index > sampler->GetUpperBound()) {
  645. // index out of range.
  646. return DXIL::SamplerKind::Invalid;
  647. }
  648. }
  649. return sampler->GetSamplerKind();
  650. }
  651. static DXIL::ResourceKind GetResourceKindAndCompTy(Value *handle, DXIL::ComponentType &CompTy, DXIL::ResourceClass &ResClass,
  652. unsigned &resIndex,
  653. ValidationContext &ValCtx) {
  654. CompTy = DXIL::ComponentType::Invalid;
  655. ResClass = DXIL::ResourceClass::Invalid;
  656. if (!isa<CallInst>(handle)) {
  657. ValCtx.EmitError(ValidationRule::InstrHandleNotFromCreateHandle);
  658. return DXIL::ResourceKind::Invalid;
  659. }
  660. DxilInst_CreateHandle createHandle(cast<CallInst>(handle));
  661. if (!createHandle) {
  662. ValCtx.EmitInstrError(cast<CallInst>(handle), ValidationRule::InstrHandleNotFromCreateHandle);
  663. return DXIL::ResourceKind::Invalid;
  664. }
  665. Value *resourceClass = createHandle.get_resourceClass();
  666. if (!isa<ConstantInt>(resourceClass)) {
  667. return DXIL::ResourceKind::Invalid;
  668. }
  669. ResClass = static_cast<DXIL::ResourceClass>(createHandle.get_resourceClass_val());
  670. switch (ResClass) {
  671. case DXIL::ResourceClass::SRV:
  672. case DXIL::ResourceClass::UAV:
  673. break;
  674. case DXIL::ResourceClass::CBuffer:
  675. return DXIL::ResourceKind::CBuffer;
  676. case DXIL::ResourceClass::Sampler:
  677. return DXIL::ResourceKind::Sampler;
  678. default:
  679. // Emit invalid res class
  680. return DXIL::ResourceKind::Invalid;
  681. }
  682. Value *rangeIndex = createHandle.get_rangeId();
  683. if (!isa<ConstantInt>(rangeIndex)) {
  684. // must be constant
  685. return DXIL::ResourceKind::Invalid;
  686. }
  687. resIndex = cast<ConstantInt>(rangeIndex)->getLimitedValue();
  688. DxilResource *res = nullptr;
  689. if (ResClass == DXIL::ResourceClass::UAV) {
  690. auto &resources = ValCtx.DxilMod.GetUAVs();
  691. if (resIndex >= resources.size()) {
  692. return DXIL::ResourceKind::Invalid;
  693. }
  694. res = resources[resIndex].get();
  695. } else {
  696. if (ResClass != DXIL::ResourceClass::SRV) {
  697. return DXIL::ResourceKind::Invalid;
  698. }
  699. auto &resources = ValCtx.DxilMod.GetSRVs();
  700. if (resIndex >= resources.size()) {
  701. return DXIL::ResourceKind::Invalid;
  702. }
  703. res = resources[resIndex].get();
  704. }
  705. CompTy = res->GetCompType().GetKind();
  706. Value *index = createHandle.get_index();
  707. ConstantInt *cIndex = dyn_cast<ConstantInt>(index);
  708. if (!res->GetGlobalSymbol()->getType()->getPointerElementType()->isArrayTy()) {
  709. if (!cIndex) {
  710. // index must be 0 for none array resource.
  711. return DXIL::ResourceKind::Invalid;
  712. }
  713. }
  714. if (cIndex) {
  715. unsigned index = cIndex->getLimitedValue();
  716. if (index < res->GetLowerBound() || index > res->GetUpperBound()) {
  717. // index out of range.
  718. return DXIL::ResourceKind::Invalid;
  719. }
  720. }
  721. return res->GetKind();
  722. }
  723. struct ResRetUsage {
  724. bool x;
  725. bool y;
  726. bool z;
  727. bool w;
  728. bool status;
  729. ResRetUsage() : x(false), y(false), z(false), w(false), status(false) {}
  730. };
  731. static void CollectGetDimResRetUsage(ResRetUsage &usage, Instruction *ResRet,
  732. ValidationContext &ValCtx) {
  733. const unsigned kMaxResRetElementIndex = 5;
  734. for (User *U : ResRet->users()) {
  735. if (ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(U)) {
  736. for (unsigned idx : EVI->getIndices()) {
  737. switch (idx) {
  738. case 0:
  739. usage.x = true;
  740. break;
  741. case 1:
  742. usage.y = true;
  743. break;
  744. case 2:
  745. usage.z = true;
  746. break;
  747. case 3:
  748. usage.w = true;
  749. break;
  750. case 4:
  751. usage.status = true;
  752. break;
  753. default:
  754. // Emit index out of bound.
  755. ValCtx.EmitInstrError(EVI,
  756. ValidationRule::InstrDxilStructUserOutOfBound);
  757. break;
  758. }
  759. }
  760. } else if (PHINode *PHI = dyn_cast<PHINode>(U)) {
  761. CollectGetDimResRetUsage(usage, PHI, ValCtx);
  762. } else {
  763. Instruction *User = cast<Instruction>(U);
  764. ValCtx.EmitInstrError(User, ValidationRule::InstrDxilStructUser);
  765. }
  766. }
  767. }
  768. static void ValidateResourceCoord(CallInst *CI, DXIL::ResourceKind resKind,
  769. ArrayRef<Value *> coords,
  770. ValidationContext &ValCtx) {
  771. const unsigned kMaxNumCoords = 4;
  772. unsigned numCoords = DxilResource::GetNumCoords(resKind);
  773. for (unsigned i = 0; i < kMaxNumCoords; i++) {
  774. if (i < numCoords) {
  775. if (isa<UndefValue>(coords[i])) {
  776. ValCtx.EmitInstrError(CI, ValidationRule::InstrResourceCoordinateMiss);
  777. }
  778. } else {
  779. if (!isa<UndefValue>(coords[i])) {
  780. ValCtx.EmitInstrError(CI, ValidationRule::InstrResourceCoordinateTooMany);
  781. }
  782. }
  783. }
  784. }
  785. static void ValidateCalcLODResourceDimensionCoord(CallInst *CI, DXIL::ResourceKind resKind,
  786. ArrayRef<Value *> coords,
  787. ValidationContext &ValCtx) {
  788. const unsigned kMaxNumDimCoords = 3;
  789. unsigned numCoords = DxilResource::GetNumDimensionsForCalcLOD(resKind);
  790. for (unsigned i = 0; i < kMaxNumDimCoords; i++) {
  791. if (i < numCoords) {
  792. if (isa<UndefValue>(coords[i])) {
  793. ValCtx.EmitInstrError(CI, ValidationRule::InstrResourceCoordinateMiss);
  794. }
  795. } else {
  796. if (!isa<UndefValue>(coords[i])) {
  797. ValCtx.EmitInstrError(CI, ValidationRule::InstrResourceCoordinateTooMany);
  798. }
  799. }
  800. }
  801. }
  802. static void ValidateResourceOffset(CallInst *CI, DXIL::ResourceKind resKind,
  803. ArrayRef<Value *> offsets,
  804. ValidationContext &ValCtx) {
  805. const unsigned kMaxNumOffsets = 3;
  806. unsigned numOffsets = DxilResource::GetNumOffsets(resKind);
  807. bool hasOffset = !isa<UndefValue>(offsets[0]);
  808. auto validateOffset = [&](Value *offset) {
  809. if (ConstantInt *cOffset = dyn_cast<ConstantInt>(offset)) {
  810. int offset = cOffset->getValue().getSExtValue();
  811. if (offset > 7 || offset < -8) {
  812. ValCtx.EmitInstrError(CI, ValidationRule::InstrTextureOffset);
  813. }
  814. } else {
  815. ValCtx.EmitInstrError(CI, ValidationRule::InstrTextureOffset);
  816. }
  817. };
  818. if (hasOffset) {
  819. validateOffset(offsets[0]);
  820. }
  821. for (unsigned i = 1; i < kMaxNumOffsets; i++) {
  822. if (i < numOffsets) {
  823. if (hasOffset) {
  824. if (isa<UndefValue>(offsets[i]))
  825. ValCtx.EmitInstrError(CI, ValidationRule::InstrResourceOffsetMiss);
  826. else
  827. validateOffset(offsets[i]);
  828. }
  829. } else {
  830. if (!isa<UndefValue>(offsets[i])) {
  831. ValCtx.EmitInstrError(CI, ValidationRule::InstrResourceOffsetTooMany);
  832. }
  833. }
  834. }
  835. }
  836. static void ValidateSampleInst(CallInst *CI, Value *srvHandle, Value *samplerHandle,
  837. ArrayRef<Value *> coords,
  838. ArrayRef<Value *> offsets,
  839. bool IsSampleC,
  840. ValidationContext &ValCtx) {
  841. if (!IsSampleC) {
  842. if (GetSamplerKind(samplerHandle, ValCtx) != DXIL::SamplerKind::Default) {
  843. ValCtx.EmitInstrError(CI, ValidationRule::InstrSamplerModeForSample);
  844. }
  845. } else {
  846. if (GetSamplerKind(samplerHandle, ValCtx) !=
  847. DXIL::SamplerKind::Comparison) {
  848. ValCtx.EmitInstrError(CI, ValidationRule::InstrSamplerModeForSampleC);
  849. }
  850. }
  851. DXIL::ComponentType compTy;
  852. DXIL::ResourceClass resClass;
  853. unsigned resIndex;
  854. DXIL::ResourceKind resKind =
  855. GetResourceKindAndCompTy(srvHandle, compTy, resClass, resIndex, ValCtx);
  856. bool isSampleCompTy = compTy == DXIL::ComponentType::F32;
  857. isSampleCompTy |= compTy == DXIL::ComponentType::SNormF32;
  858. isSampleCompTy |= compTy == DXIL::ComponentType::UNormF32;
  859. if (!isSampleCompTy) {
  860. ValCtx.EmitInstrError(CI, ValidationRule::InstrSampleCompType);
  861. }
  862. if (resClass != DXIL::ResourceClass::SRV) {
  863. ValCtx.EmitInstrError(CI, ValidationRule::InstrResourceClassForSamplerGather);
  864. }
  865. ValidationRule rule = ValidationRule::InstrResourceKindForSample;
  866. if (IsSampleC) {
  867. rule = ValidationRule::InstrResourceKindForSampleC;
  868. }
  869. switch (resKind) {
  870. case DXIL::ResourceKind::Texture1D:
  871. case DXIL::ResourceKind::Texture1DArray:
  872. case DXIL::ResourceKind::Texture2D:
  873. case DXIL::ResourceKind::Texture2DArray:
  874. case DXIL::ResourceKind::TextureCube:
  875. case DXIL::ResourceKind::TextureCubeArray:
  876. break;
  877. case DXIL::ResourceKind::Texture3D:
  878. if (IsSampleC) {
  879. ValCtx.EmitInstrError(CI, rule);
  880. }
  881. break;
  882. default:
  883. ValCtx.EmitInstrError(CI, rule);
  884. return;
  885. }
  886. // Coord match resource kind.
  887. ValidateResourceCoord(CI, resKind, coords, ValCtx);
  888. // Offset match resource kind.
  889. ValidateResourceOffset(CI, resKind, offsets, ValCtx);
  890. }
  891. static void ValidateGather(CallInst *CI, Value *srvHandle, Value *samplerHandle,
  892. ArrayRef<Value *> coords,
  893. ArrayRef<Value *> offsets,
  894. bool IsSampleC,
  895. ValidationContext &ValCtx) {
  896. if (!IsSampleC) {
  897. if (GetSamplerKind(samplerHandle, ValCtx) != DXIL::SamplerKind::Default) {
  898. ValCtx.EmitInstrError(CI, ValidationRule::InstrSamplerModeForSample);
  899. }
  900. } else {
  901. if (GetSamplerKind(samplerHandle, ValCtx) !=
  902. DXIL::SamplerKind::Comparison) {
  903. ValCtx.EmitInstrError(CI, ValidationRule::InstrSamplerModeForSampleC);
  904. }
  905. }
  906. DXIL::ComponentType compTy;
  907. DXIL::ResourceClass resClass;
  908. unsigned resIndex;
  909. DXIL::ResourceKind resKind =
  910. GetResourceKindAndCompTy(srvHandle, compTy, resClass, resIndex, ValCtx);
  911. if (resClass != DXIL::ResourceClass::SRV) {
  912. ValCtx.EmitInstrError(CI, ValidationRule::InstrResourceClassForSamplerGather);
  913. return;
  914. }
  915. // Coord match resource kind.
  916. ValidateResourceCoord(CI, resKind, coords, ValCtx);
  917. // Offset match resource kind.
  918. switch (resKind) {
  919. case DXIL::ResourceKind::Texture2D:
  920. case DXIL::ResourceKind::Texture2DArray: {
  921. bool hasOffset = !isa<UndefValue>(offsets[0]);
  922. if (hasOffset) {
  923. if (isa<UndefValue>(offsets[1])) {
  924. ValCtx.EmitInstrError(CI, ValidationRule::InstrResourceOffsetMiss);
  925. }
  926. }
  927. } break;
  928. case DXIL::ResourceKind::TextureCube:
  929. case DXIL::ResourceKind::TextureCubeArray: {
  930. if (!isa<UndefValue>(offsets[0])) {
  931. ValCtx.EmitInstrError(CI, ValidationRule::InstrResourceOffsetTooMany);
  932. }
  933. if (!isa<UndefValue>(offsets[1])) {
  934. ValCtx.EmitInstrError(CI, ValidationRule::InstrResourceOffsetTooMany);
  935. }
  936. } break;
  937. default:
  938. // Invalid resource type for gather.
  939. ValCtx.EmitInstrError(CI, ValidationRule::InstrResourceKindForGather);
  940. break;
  941. }
  942. }
  943. static unsigned StoreValueToMask(ArrayRef<Value *> vals) {
  944. unsigned mask = 0;
  945. for (unsigned i = 0; i < 4; i++) {
  946. if (!isa<UndefValue>(vals[i])) {
  947. mask |= 1<<i;
  948. }
  949. }
  950. return mask;
  951. }
  952. static int GetCBufSize(Value *cbHandle, ValidationContext &ValCtx) {
  953. DxilInst_CreateHandle createHandle(cast<CallInst>(cbHandle));
  954. if (!createHandle) {
  955. ValCtx.EmitInstrError(cast<CallInst>(cbHandle),
  956. ValidationRule::InstrHandleNotFromCreateHandle);
  957. return -1;
  958. }
  959. Value *resourceClass = createHandle.get_resourceClass();
  960. if (!isa<ConstantInt>(resourceClass)) {
  961. ValCtx.EmitInstrError(cast<CallInst>(cbHandle),
  962. ValidationRule::InstrOpConstRange);
  963. return -1;
  964. }
  965. if (static_cast<DXIL::ResourceClass>(createHandle.get_resourceClass_val()) !=
  966. DXIL::ResourceClass::CBuffer) {
  967. ValCtx.EmitInstrError(cast<CallInst>(cbHandle), ValidationRule::InstrCBufferClassForCBufferHandle);
  968. return -1;
  969. }
  970. Value *rangeIndex = createHandle.get_rangeId();
  971. if (!isa<ConstantInt>(rangeIndex)) {
  972. ValCtx.EmitInstrError(cast<CallInst>(cbHandle),
  973. ValidationRule::InstrOpConstRange);
  974. return -1;
  975. }
  976. DxilCBuffer &CB = ValCtx.DxilMod.GetCBuffer(
  977. cast<ConstantInt>(rangeIndex)->getLimitedValue());
  978. return CB.GetSize();
  979. }
  980. static unsigned GetNumVertices(DXIL::InputPrimitive inputPrimitive) {
  981. const unsigned InputPrimitiveVertexTab[] = {
  982. 0, // Undefined = 0,
  983. 1, // Point = 1,
  984. 2, // Line = 2,
  985. 3, // Triangle = 3,
  986. 0, // Reserved4 = 4,
  987. 0, // Reserved5 = 5,
  988. 4, // LineWithAdjacency = 6,
  989. 6, // TriangleWithAdjacency = 7,
  990. 1, // ControlPointPatch1 = 8,
  991. 2, // ControlPointPatch2 = 9,
  992. 3, // ControlPointPatch3 = 10,
  993. 4, // ControlPointPatch4 = 11,
  994. 5, // ControlPointPatch5 = 12,
  995. 6, // ControlPointPatch6 = 13,
  996. 7, // ControlPointPatch7 = 14,
  997. 8, // ControlPointPatch8 = 15,
  998. 9, // ControlPointPatch9 = 16,
  999. 10, // ControlPointPatch10 = 17,
  1000. 11, // ControlPointPatch11 = 18,
  1001. 12, // ControlPointPatch12 = 19,
  1002. 13, // ControlPointPatch13 = 20,
  1003. 14, // ControlPointPatch14 = 21,
  1004. 15, // ControlPointPatch15 = 22,
  1005. 16, // ControlPointPatch16 = 23,
  1006. 17, // ControlPointPatch17 = 24,
  1007. 18, // ControlPointPatch18 = 25,
  1008. 19, // ControlPointPatch19 = 26,
  1009. 20, // ControlPointPatch20 = 27,
  1010. 21, // ControlPointPatch21 = 28,
  1011. 22, // ControlPointPatch22 = 29,
  1012. 23, // ControlPointPatch23 = 30,
  1013. 24, // ControlPointPatch24 = 31,
  1014. 25, // ControlPointPatch25 = 32,
  1015. 26, // ControlPointPatch26 = 33,
  1016. 27, // ControlPointPatch27 = 34,
  1017. 28, // ControlPointPatch28 = 35,
  1018. 29, // ControlPointPatch29 = 36,
  1019. 30, // ControlPointPatch30 = 37,
  1020. 31, // ControlPointPatch31 = 38,
  1021. 32, // ControlPointPatch32 = 39,
  1022. 0, // LastEntry,
  1023. };
  1024. unsigned primitiveIdx = static_cast<unsigned>(inputPrimitive);
  1025. return InputPrimitiveVertexTab[primitiveIdx];
  1026. }
  1027. static void ValidateDxilOperationCallInProfile(CallInst *CI,
  1028. DXIL::OpCode opcode,
  1029. const ShaderModel *pSM,
  1030. ValidationContext &ValCtx) {
  1031. switch (opcode) {
  1032. case DXIL::OpCode::LoadInput: {
  1033. Value *inputID = CI->getArgOperand(DXIL::OperandIndex::kLoadInputIDOpIdx);
  1034. DxilSignature &inputSig = ValCtx.DxilMod.GetInputSignature();
  1035. Value *row = CI->getArgOperand(DXIL::OperandIndex::kLoadInputRowOpIdx);
  1036. Value *col = CI->getArgOperand(DXIL::OperandIndex::kLoadInputColOpIdx);
  1037. ValidateSignatureAccess(CI, inputSig, inputID, row, col, ValCtx);
  1038. // Check vertexID in ps/vs. and none array input.
  1039. Value *vertexID =
  1040. CI->getArgOperand(DXIL::OperandIndex::kLoadInputVertexIDOpIdx);
  1041. bool usedVertexID = vertexID && !isa<UndefValue>(vertexID);
  1042. if (pSM->IsVS() || pSM->IsPS()) {
  1043. if (usedVertexID) {
  1044. // use vertexID in VS/PS input.
  1045. ValCtx.EmitInstrError(CI, ValidationRule::SmOperand);
  1046. return;
  1047. }
  1048. } else {
  1049. if (ConstantInt *cVertexID = dyn_cast<ConstantInt>(vertexID)) {
  1050. int immVertexID = cVertexID->getValue().getLimitedValue();
  1051. if (cVertexID->getValue().isNegative()) {
  1052. immVertexID = cVertexID->getValue().getSExtValue();
  1053. }
  1054. const int low = 0;
  1055. int high = 0;
  1056. if (pSM->IsGS()) {
  1057. DXIL::InputPrimitive inputPrimitive =
  1058. ValCtx.DxilMod.GetInputPrimitive();
  1059. high = GetNumVertices(inputPrimitive);
  1060. } else if (pSM->IsDS()) {
  1061. high = ValCtx.DxilMod.GetInputControlPointCount();
  1062. } else if (pSM->IsHS()) {
  1063. high = ValCtx.DxilMod.GetInputControlPointCount();
  1064. } else {
  1065. ValCtx.EmitFormatError(ValidationRule::SmOpcodeInInvalidFunction,
  1066. {"LoadInput", "VS/HS/DS/GS/PS"});
  1067. }
  1068. if (immVertexID < low || immVertexID >= high) {
  1069. std::string range = std::to_string(low)+"~"+
  1070. std::to_string(high);
  1071. ValCtx.EmitOperandOutOfRange(CI, "VertexID", range,
  1072. std::to_string(immVertexID));
  1073. }
  1074. }
  1075. }
  1076. } break;
  1077. case DXIL::OpCode::DomainLocation: {
  1078. Value *colValue = CI->getArgOperand(DXIL::OperandIndex::kDomainLocationColOpIdx);
  1079. if (!isa<ConstantInt>(colValue)) {
  1080. // col must be const
  1081. ValCtx.EmitInstrFormatError(CI, ValidationRule::InstrOpConst,
  1082. {"Col", "DomainLocation"});
  1083. } else {
  1084. unsigned col = cast<ConstantInt>(colValue)->getLimitedValue();
  1085. if (col >= ValCtx.domainLocSize) {
  1086. ValCtx.EmitError(ValidationRule::SmDomainLocationIdxOOB);
  1087. }
  1088. }
  1089. } break;
  1090. case DXIL::OpCode::CBufferLoad: {
  1091. DxilInst_CBufferLoad CBLoad(CI);
  1092. Value *regIndex = CBLoad.get_byteOffset();
  1093. if (ConstantInt *cIndex = dyn_cast<ConstantInt>(regIndex)) {
  1094. int offset = cIndex->getLimitedValue();
  1095. int size = GetCBufSize(CBLoad.get_handle(), ValCtx);
  1096. if (size > 0 && offset >= size) {
  1097. ValCtx.EmitInstrError(CI, ValidationRule::InstrCBufferOutOfBound);
  1098. }
  1099. }
  1100. } break;
  1101. case DXIL::OpCode::CBufferLoadLegacy: {
  1102. DxilInst_CBufferLoadLegacy CBLoad(CI);
  1103. Value *regIndex = CBLoad.get_regIndex();
  1104. if (ConstantInt *cIndex = dyn_cast<ConstantInt>(regIndex)) {
  1105. int offset = cIndex->getLimitedValue() * 16; // 16 bytes align
  1106. int size = GetCBufSize(CBLoad.get_handle(), ValCtx);
  1107. if (size > 0 && offset >= size) {
  1108. ValCtx.EmitInstrError(CI, ValidationRule::InstrCBufferOutOfBound);
  1109. }
  1110. }
  1111. } break;
  1112. case DXIL::OpCode::StoreOutput: {
  1113. Value *outputID =
  1114. CI->getArgOperand(DXIL::OperandIndex::kStoreOutputIDOpIdx);
  1115. DxilSignature &outputSig = ValCtx.DxilMod.GetOutputSignature();
  1116. Value *row = CI->getArgOperand(DXIL::OperandIndex::kStoreOutputRowOpIdx);
  1117. Value *col = CI->getArgOperand(DXIL::OperandIndex::kStoreOutputColOpIdx);
  1118. ValidateSignatureAccess(CI, outputSig, outputID, row, col, ValCtx);
  1119. } break;
  1120. case DXIL::OpCode::OutputControlPointID: {
  1121. // Only used in hull shader.
  1122. Function *func = CI->getParent()->getParent();
  1123. if (ValCtx.patchConstFuncCallSet.count(func) > 0 || !ValCtx.DxilMod.GetShaderModel()->IsHS()) {
  1124. ValCtx.EmitFormatError(ValidationRule::SmOpcodeInInvalidFunction,
  1125. {"OutputControlPointID", "hull function"});
  1126. }
  1127. } break;
  1128. case DXIL::OpCode::LoadOutputControlPoint: {
  1129. // Only used in patch constant function.
  1130. Function *func = CI->getParent()->getParent();
  1131. if (ValCtx.entryFuncCallSet.count(func) > 0) {
  1132. ValCtx.EmitFormatError(
  1133. ValidationRule::SmOpcodeInInvalidFunction,
  1134. {"LoadOutputControlPoint", "PatchConstant function"});
  1135. }
  1136. Value *outputID =
  1137. CI->getArgOperand(DXIL::OperandIndex::kStoreOutputIDOpIdx);
  1138. DxilSignature &outputSig = ValCtx.DxilMod.GetOutputSignature();
  1139. Value *row = CI->getArgOperand(DXIL::OperandIndex::kStoreOutputRowOpIdx);
  1140. Value *col = CI->getArgOperand(DXIL::OperandIndex::kStoreOutputColOpIdx);
  1141. ValidateSignatureAccess(CI, outputSig, outputID, row, col, ValCtx);
  1142. } break;
  1143. case DXIL::OpCode::StorePatchConstant: {
  1144. // Only used in patch constant function.
  1145. Function *func = CI->getParent()->getParent();
  1146. if (ValCtx.entryFuncCallSet.count(func) > 0) {
  1147. ValCtx.EmitFormatError(ValidationRule::SmOpcodeInInvalidFunction,
  1148. {"StorePatchConstant", "PatchConstant function"});
  1149. }
  1150. Value *outputID =
  1151. CI->getArgOperand(DXIL::OperandIndex::kStoreOutputIDOpIdx);
  1152. DxilSignature &outputSig = ValCtx.DxilMod.GetPatchConstantSignature();
  1153. Value *row = CI->getArgOperand(DXIL::OperandIndex::kStoreOutputRowOpIdx);
  1154. Value *col = CI->getArgOperand(DXIL::OperandIndex::kStoreOutputColOpIdx);
  1155. ValidateSignatureAccess(CI, outputSig, outputID, row, col, ValCtx);
  1156. } break;
  1157. case DXIL::OpCode::EvalCentroid:
  1158. case DXIL::OpCode::EvalSampleIndex:
  1159. case DXIL::OpCode::EvalSnapped: {
  1160. // Eval* share same operand index with load input.
  1161. Value *inputID = CI->getArgOperand(DXIL::OperandIndex::kLoadInputIDOpIdx);
  1162. DxilSignature &inputSig = ValCtx.DxilMod.GetInputSignature();
  1163. Value *row = CI->getArgOperand(DXIL::OperandIndex::kLoadInputRowOpIdx);
  1164. Value *col = CI->getArgOperand(DXIL::OperandIndex::kLoadInputColOpIdx);
  1165. DxilSignatureElement *pSE =
  1166. ValidateSignatureAccess(CI, inputSig, inputID, row, col, ValCtx);
  1167. if (pSE) {
  1168. switch (pSE->GetInterpolationMode()->GetKind()) {
  1169. case DXIL::InterpolationMode::Linear:
  1170. case DXIL::InterpolationMode::LinearNoperspective:
  1171. case DXIL::InterpolationMode::LinearCentroid:
  1172. case DXIL::InterpolationMode::LinearNoperspectiveCentroid:
  1173. case DXIL::InterpolationMode::LinearSample:
  1174. case DXIL::InterpolationMode::LinearNoperspectiveSample:
  1175. break;
  1176. default:
  1177. ValCtx.EmitInstrFormatError(
  1178. CI, ValidationRule::InstrEvalInterpolationMode, {pSE->GetName()});
  1179. break;
  1180. }
  1181. if (pSE->GetSemantic()->GetKind() == DXIL::SemanticKind::Position) {
  1182. ValCtx.EmitInstrFormatError(
  1183. CI, ValidationRule::InstrCannotPullPosition,
  1184. {ValCtx.DxilMod.GetShaderModel()->GetName()});
  1185. }
  1186. }
  1187. } break;
  1188. case DXIL::OpCode::AttributeAtVertex: {
  1189. Value *Attribute = CI->getArgOperand(DXIL::OperandIndex::kBinarySrc0OpIdx);
  1190. DxilSignature &inputSig = ValCtx.DxilMod.GetInputSignature();
  1191. Value *row = CI->getArgOperand(DXIL::OperandIndex::kLoadInputRowOpIdx);
  1192. Value *col = CI->getArgOperand(DXIL::OperandIndex::kLoadInputColOpIdx);
  1193. DxilSignatureElement *pSE =
  1194. ValidateSignatureAccess(CI, inputSig, Attribute, row, col, ValCtx);
  1195. if (pSE && pSE->GetInterpolationMode()->GetKind() !=
  1196. hlsl::InterpolationMode::Kind::Constant) {
  1197. ValCtx.EmitInstrFormatError(
  1198. CI, ValidationRule::InstrAttributeAtVertexNoInterpolation,
  1199. {pSE->GetName()});
  1200. }
  1201. } break;
  1202. case DXIL::OpCode::GetDimensions: {
  1203. DxilInst_GetDimensions getDim(CI);
  1204. Value *handle = getDim.get_handle();
  1205. DXIL::ComponentType compTy;
  1206. DXIL::ResourceClass resClass;
  1207. unsigned resIndex;
  1208. DXIL::ResourceKind resKind =
  1209. GetResourceKindAndCompTy(handle, compTy, resClass, resIndex, ValCtx);
  1210. // Check the result component use.
  1211. ResRetUsage usage;
  1212. CollectGetDimResRetUsage(usage, CI, ValCtx);
  1213. // Mip level only for texture.
  1214. switch (resKind) {
  1215. case DXIL::ResourceKind::Texture1D:
  1216. if (usage.y) {
  1217. ValCtx.EmitInstrFormatError(
  1218. CI, ValidationRule::InstrUndefResultForGetDimension,
  1219. {"y", "Texture1D"});
  1220. }
  1221. if (usage.z) {
  1222. ValCtx.EmitInstrFormatError(
  1223. CI, ValidationRule::InstrUndefResultForGetDimension,
  1224. {"z", "Texture1D"});
  1225. }
  1226. break;
  1227. case DXIL::ResourceKind::Texture1DArray:
  1228. if (usage.z) {
  1229. ValCtx.EmitInstrFormatError(
  1230. CI, ValidationRule::InstrUndefResultForGetDimension,
  1231. {"z", "Texture1DArray"});
  1232. }
  1233. break;
  1234. case DXIL::ResourceKind::Texture2D:
  1235. if (usage.z) {
  1236. ValCtx.EmitInstrFormatError(
  1237. CI, ValidationRule::InstrUndefResultForGetDimension,
  1238. {"z", "Texture2D"});
  1239. }
  1240. break;
  1241. case DXIL::ResourceKind::Texture2DArray:
  1242. break;
  1243. case DXIL::ResourceKind::Texture2DMS:
  1244. if (usage.z) {
  1245. ValCtx.EmitInstrFormatError(
  1246. CI, ValidationRule::InstrUndefResultForGetDimension,
  1247. {"z", "Texture2DMS"});
  1248. }
  1249. break;
  1250. case DXIL::ResourceKind::Texture2DMSArray:
  1251. break;
  1252. case DXIL::ResourceKind::Texture3D:
  1253. break;
  1254. case DXIL::ResourceKind::TextureCube:
  1255. if (usage.z) {
  1256. ValCtx.EmitInstrFormatError(
  1257. CI, ValidationRule::InstrUndefResultForGetDimension,
  1258. {"z", "TextureCube"});
  1259. }
  1260. break;
  1261. case DXIL::ResourceKind::TextureCubeArray:
  1262. break;
  1263. case DXIL::ResourceKind::StructuredBuffer:
  1264. case DXIL::ResourceKind::RawBuffer:
  1265. case DXIL::ResourceKind::TypedBuffer:
  1266. case DXIL::ResourceKind::TBuffer: {
  1267. Value *mip = getDim.get_mipLevel();
  1268. if (!isa<UndefValue>(mip)) {
  1269. ValCtx.EmitInstrError(
  1270. CI, ValidationRule::InstrMipLevelForGetDimension);
  1271. }
  1272. if (resKind != DXIL::ResourceKind::Invalid) {
  1273. if (usage.y || usage.z || usage.w) {
  1274. ValCtx.EmitInstrFormatError(
  1275. CI, ValidationRule::InstrUndefResultForGetDimension,
  1276. {"invalid", "resource"});
  1277. }
  1278. }
  1279. } break;
  1280. default: {
  1281. ValCtx.EmitInstrError(
  1282. CI, ValidationRule::InstrResourceKindForGetDim);
  1283. } break;
  1284. }
  1285. if (usage.status) {
  1286. ValCtx.EmitInstrFormatError(
  1287. CI, ValidationRule::InstrUndefResultForGetDimension,
  1288. {"invalid", "resource"});
  1289. }
  1290. } break;
  1291. case DXIL::OpCode::CalculateLOD: {
  1292. DxilInst_CalculateLOD lod(CI);
  1293. Value *samplerHandle = lod.get_sampler();
  1294. if (GetSamplerKind(samplerHandle, ValCtx) != DXIL::SamplerKind::Default) {
  1295. ValCtx.EmitInstrError(CI,
  1296. ValidationRule::InstrSamplerModeForLOD);
  1297. }
  1298. Value *handle = lod.get_handle();
  1299. DXIL::ComponentType compTy;
  1300. DXIL::ResourceClass resClass;
  1301. unsigned resIndex;
  1302. DXIL::ResourceKind resKind =
  1303. GetResourceKindAndCompTy(handle, compTy, resClass, resIndex, ValCtx);
  1304. if (resClass != DXIL::ResourceClass::SRV) {
  1305. ValCtx.EmitInstrError(CI,
  1306. ValidationRule::InstrResourceClassForSamplerGather);
  1307. return;
  1308. }
  1309. // Coord match resource.
  1310. ValidateCalcLODResourceDimensionCoord(
  1311. CI, resKind, {lod.get_coord0(), lod.get_coord1(), lod.get_coord2()},
  1312. ValCtx);
  1313. switch (resKind) {
  1314. case DXIL::ResourceKind::Texture1D:
  1315. case DXIL::ResourceKind::Texture1DArray:
  1316. case DXIL::ResourceKind::Texture2D:
  1317. case DXIL::ResourceKind::Texture2DArray:
  1318. case DXIL::ResourceKind::Texture3D:
  1319. case DXIL::ResourceKind::TextureCube:
  1320. case DXIL::ResourceKind::TextureCubeArray:
  1321. break;
  1322. default:
  1323. ValCtx.EmitInstrError(
  1324. CI, ValidationRule::InstrResourceKindForCalcLOD);
  1325. break;
  1326. }
  1327. } break;
  1328. case DXIL::OpCode::TextureGather: {
  1329. DxilInst_TextureGather gather(CI);
  1330. ValidateGather(CI, gather.get_srv(), gather.get_sampler(),
  1331. {gather.get_coord0(), gather.get_coord1(),
  1332. gather.get_coord2(), gather.get_coord3()},
  1333. {gather.get_offset0(), gather.get_offset1()},
  1334. /*IsSampleC*/ false, ValCtx);
  1335. } break;
  1336. case DXIL::OpCode::TextureGatherCmp: {
  1337. DxilInst_TextureGatherCmp gather(CI);
  1338. ValidateGather(CI, gather.get_srv(), gather.get_sampler(),
  1339. {gather.get_coord0(), gather.get_coord1(),
  1340. gather.get_coord2(), gather.get_coord3()},
  1341. {gather.get_offset0(), gather.get_offset1()},
  1342. /*IsSampleC*/ true, ValCtx);
  1343. } break;
  1344. case DXIL::OpCode::Sample: {
  1345. DxilInst_Sample sample(CI);
  1346. ValidateSampleInst(
  1347. CI, sample.get_srv(), sample.get_sampler(),
  1348. {sample.get_coord0(), sample.get_coord1(), sample.get_coord2(),
  1349. sample.get_coord3()},
  1350. {sample.get_offset0(), sample.get_offset1(), sample.get_offset2()},
  1351. /*IsSampleC*/ false, ValCtx);
  1352. } break;
  1353. case DXIL::OpCode::SampleCmp: {
  1354. DxilInst_SampleCmp sample(CI);
  1355. ValidateSampleInst(
  1356. CI, sample.get_srv(), sample.get_sampler(),
  1357. {sample.get_coord0(), sample.get_coord1(), sample.get_coord2(),
  1358. sample.get_coord3()},
  1359. {sample.get_offset0(), sample.get_offset1(), sample.get_offset2()},
  1360. /*IsSampleC*/ true, ValCtx);
  1361. } break;
  1362. case DXIL::OpCode::SampleCmpLevelZero: {
  1363. // sampler must be comparison mode.
  1364. DxilInst_SampleCmpLevelZero sample(CI);
  1365. ValidateSampleInst(
  1366. CI, sample.get_srv(), sample.get_sampler(),
  1367. {sample.get_coord0(), sample.get_coord1(), sample.get_coord2(),
  1368. sample.get_coord3()},
  1369. {sample.get_offset0(), sample.get_offset1(), sample.get_offset2()},
  1370. /*IsSampleC*/ true, ValCtx);
  1371. } break;
  1372. case DXIL::OpCode::SampleBias: {
  1373. DxilInst_SampleBias sample(CI);
  1374. Value *bias = sample.get_bias();
  1375. if (ConstantFP *cBias = dyn_cast<ConstantFP>(bias)) {
  1376. float fBias = cBias->getValueAPF().convertToFloat();
  1377. if (fBias < DXIL::kMinMipLodBias || fBias > DXIL::kMaxMipLodBias) {
  1378. ValCtx.EmitInstrFormatError(
  1379. CI, ValidationRule::InstrImmBiasForSampleB,
  1380. {std::to_string(DXIL::kMinMipLodBias),
  1381. std::to_string(DXIL::kMaxMipLodBias),
  1382. std::to_string(cBias->getValueAPF().convertToFloat())});
  1383. }
  1384. }
  1385. ValidateSampleInst(
  1386. CI, sample.get_srv(), sample.get_sampler(),
  1387. {sample.get_coord0(), sample.get_coord1(), sample.get_coord2(),
  1388. sample.get_coord3()},
  1389. {sample.get_offset0(), sample.get_offset1(), sample.get_offset2()},
  1390. /*IsSampleC*/ false, ValCtx);
  1391. } break;
  1392. case DXIL::OpCode::SampleGrad: {
  1393. DxilInst_SampleGrad sample(CI);
  1394. ValidateSampleInst(
  1395. CI, sample.get_srv(), sample.get_sampler(),
  1396. {sample.get_coord0(), sample.get_coord1(), sample.get_coord2(),
  1397. sample.get_coord3()},
  1398. {sample.get_offset0(), sample.get_offset1(), sample.get_offset2()},
  1399. /*IsSampleC*/ false, ValCtx);
  1400. } break;
  1401. case DXIL::OpCode::SampleLevel: {
  1402. DxilInst_SampleLevel sample(CI);
  1403. ValidateSampleInst(
  1404. CI, sample.get_srv(), sample.get_sampler(),
  1405. {sample.get_coord0(), sample.get_coord1(), sample.get_coord2(),
  1406. sample.get_coord3()},
  1407. {sample.get_offset0(), sample.get_offset1(), sample.get_offset2()},
  1408. /*IsSampleC*/ false, ValCtx);
  1409. } break;
  1410. case DXIL::OpCode::Barrier: {
  1411. DxilInst_Barrier barrier(CI);
  1412. Value *mode = barrier.get_barrierMode();
  1413. ConstantInt *cMode = dyn_cast<ConstantInt>(mode);
  1414. if (!cMode) {
  1415. ValCtx.EmitInstrFormatError(CI, ValidationRule::InstrOpConst,
  1416. {"Mode", "Barrier"});
  1417. return;
  1418. }
  1419. const unsigned uglobal =
  1420. static_cast<unsigned>(DXIL::BarrierMode::UAVFenceGlobal);
  1421. const unsigned g = static_cast<unsigned>(DXIL::BarrierMode::TGSMFence);
  1422. const unsigned t =
  1423. static_cast<unsigned>(DXIL::BarrierMode::SyncThreadGroup);
  1424. const unsigned ut =
  1425. static_cast<unsigned>(DXIL::BarrierMode::UAVFenceThreadGroup);
  1426. unsigned barrierMode = cMode->getLimitedValue();
  1427. if (ValCtx.DxilMod.GetShaderModel()->IsCS()) {
  1428. bool bHasUGlobal = barrierMode & uglobal;
  1429. bool bHasGroup = barrierMode & g;
  1430. bool bHasUGroup = barrierMode & ut;
  1431. if (bHasUGlobal && bHasUGroup) {
  1432. ValCtx.EmitInstrError(CI,
  1433. ValidationRule::InstrBarrierModeUselessUGroup);
  1434. }
  1435. if (!bHasUGlobal && !bHasGroup && !bHasUGroup) {
  1436. ValCtx.EmitInstrError(CI, ValidationRule::InstrBarrierModeNoMemory);
  1437. }
  1438. } else {
  1439. if (uglobal != barrierMode) {
  1440. ValCtx.EmitInstrError(CI, ValidationRule::InstrBarrierModeForNonCS);
  1441. }
  1442. }
  1443. } break;
  1444. case DXIL::OpCode::BufferStore: {
  1445. DxilInst_BufferStore bufSt(CI);
  1446. DXIL::ComponentType compTy;
  1447. DXIL::ResourceClass resClass;
  1448. unsigned resIndex;
  1449. DXIL::ResourceKind resKind =
  1450. GetResourceKindAndCompTy(bufSt.get_uav(), compTy, resClass, resIndex, ValCtx);
  1451. if (resClass != DXIL::ResourceClass::UAV) {
  1452. ValCtx.EmitInstrError(CI, ValidationRule::InstrResourceClassForUAVStore);
  1453. }
  1454. ConstantInt *mask = dyn_cast<ConstantInt>(bufSt.get_mask());
  1455. if (!mask) {
  1456. // Mask for buffer store should be immediate.
  1457. ValCtx.EmitInstrFormatError(CI, ValidationRule::InstrOpConst, {"Mask", "BufferStore"});
  1458. return;
  1459. }
  1460. unsigned uMask = mask->getLimitedValue();
  1461. unsigned stValMask =
  1462. StoreValueToMask({bufSt.get_value0(), bufSt.get_value1(),
  1463. bufSt.get_value2(), bufSt.get_value3()});
  1464. if (stValMask != uMask) {
  1465. ValCtx.EmitInstrFormatError(
  1466. CI, ValidationRule::InstrWriteMaskMatchValueForUAVStore,
  1467. {std::to_string(uMask), std::to_string(stValMask)});
  1468. }
  1469. Value *offset = bufSt.get_coord1();
  1470. switch (resKind) {
  1471. case DXIL::ResourceKind::RawBuffer:
  1472. if (!isa<UndefValue>(offset)) {
  1473. ValCtx.EmitInstrError(
  1474. CI, ValidationRule::InstrCoordinateCountForRawTypedBuf);
  1475. }
  1476. break;
  1477. case DXIL::ResourceKind::TypedBuffer:
  1478. case DXIL::ResourceKind::TBuffer:
  1479. if (!isa<UndefValue>(offset)) {
  1480. ValCtx.EmitInstrError(
  1481. CI, ValidationRule::InstrCoordinateCountForRawTypedBuf);
  1482. }
  1483. if (uMask != 0xf) {
  1484. ValCtx.EmitInstrError(
  1485. CI, ValidationRule::InstrWriteMaskForTypedUAVStore);
  1486. }
  1487. break;
  1488. case DXIL::ResourceKind::StructuredBuffer:
  1489. if (isa<UndefValue>(offset)) {
  1490. ValCtx.EmitInstrError(
  1491. CI, ValidationRule::InstrCoordinateCountForStructBuf);
  1492. }
  1493. break;
  1494. default:
  1495. ValCtx.EmitInstrError(
  1496. CI, ValidationRule::InstrResourceKindForBufferLoadStore);
  1497. break;
  1498. }
  1499. } break;
  1500. case DXIL::OpCode::TextureStore: {
  1501. DxilInst_TextureStore texSt(CI);
  1502. DXIL::ComponentType compTy;
  1503. DXIL::ResourceClass resClass;
  1504. unsigned resIndex;
  1505. DXIL::ResourceKind resKind =
  1506. GetResourceKindAndCompTy(texSt.get_srv(), compTy, resClass, resIndex, ValCtx);
  1507. if (resClass != DXIL::ResourceClass::UAV) {
  1508. ValCtx.EmitInstrError(CI, ValidationRule::InstrResourceClassForUAVStore);
  1509. }
  1510. ConstantInt *mask = dyn_cast<ConstantInt>(texSt.get_mask());
  1511. if (!mask) {
  1512. // Mask for buffer store should be immediate.
  1513. ValCtx.EmitInstrFormatError(CI, ValidationRule::InstrOpConst, {"Mask", "TextureStore"});
  1514. return;
  1515. }
  1516. unsigned uMask = mask->getLimitedValue();
  1517. if (uMask != 0xf) {
  1518. ValCtx.EmitInstrError(
  1519. CI, ValidationRule::InstrWriteMaskForTypedUAVStore);
  1520. }
  1521. unsigned stValMask =
  1522. StoreValueToMask({texSt.get_value0(), texSt.get_value1(),
  1523. texSt.get_value2(), texSt.get_value3()});
  1524. if (stValMask != uMask) {
  1525. ValCtx.EmitInstrFormatError(
  1526. CI, ValidationRule::InstrWriteMaskMatchValueForUAVStore,
  1527. {std::to_string(uMask), std::to_string(stValMask)});
  1528. }
  1529. switch (resKind) {
  1530. case DXIL::ResourceKind::Texture1D:
  1531. case DXIL::ResourceKind::Texture1DArray:
  1532. case DXIL::ResourceKind::Texture2D:
  1533. case DXIL::ResourceKind::Texture2DArray:
  1534. case DXIL::ResourceKind::Texture3D:
  1535. break;
  1536. default:
  1537. ValCtx.EmitInstrError(
  1538. CI, ValidationRule::InstrResourceKindForTextureStore);
  1539. break;
  1540. }
  1541. } break;
  1542. case DXIL::OpCode::BufferLoad: {
  1543. DxilInst_BufferLoad bufLd(CI);
  1544. DXIL::ComponentType compTy;
  1545. DXIL::ResourceClass resClass;
  1546. unsigned resIndex;
  1547. DXIL::ResourceKind resKind =
  1548. GetResourceKindAndCompTy(bufLd.get_srv(), compTy, resClass, resIndex, ValCtx);
  1549. if (resClass != DXIL::ResourceClass::SRV &&
  1550. resClass != DXIL::ResourceClass::UAV) {
  1551. ValCtx.EmitInstrError(CI, ValidationRule::InstrResourceClassForLoad);
  1552. }
  1553. Value *offset = bufLd.get_wot();
  1554. switch (resKind) {
  1555. case DXIL::ResourceKind::RawBuffer:
  1556. case DXIL::ResourceKind::TypedBuffer:
  1557. case DXIL::ResourceKind::TBuffer:
  1558. if (!isa<UndefValue>(offset)) {
  1559. ValCtx.EmitInstrError(
  1560. CI, ValidationRule::InstrCoordinateCountForRawTypedBuf);
  1561. }
  1562. break;
  1563. case DXIL::ResourceKind::StructuredBuffer:
  1564. if (isa<UndefValue>(offset)) {
  1565. ValCtx.EmitInstrError(
  1566. CI, ValidationRule::InstrCoordinateCountForStructBuf);
  1567. }
  1568. break;
  1569. default:
  1570. ValCtx.EmitInstrError(
  1571. CI, ValidationRule::InstrResourceKindForBufferLoadStore);
  1572. break;
  1573. }
  1574. } break;
  1575. case DXIL::OpCode::TextureLoad: {
  1576. DxilInst_TextureLoad texLd(CI);
  1577. DXIL::ComponentType compTy;
  1578. DXIL::ResourceClass resClass;
  1579. unsigned resIndex;
  1580. DXIL::ResourceKind resKind =
  1581. GetResourceKindAndCompTy(texLd.get_srv(), compTy, resClass, resIndex, ValCtx);
  1582. Value *mipLevel = texLd.get_mipLevelOrSampleCount();
  1583. if (resClass == DXIL::ResourceClass::UAV) {
  1584. bool noOffset = isa<UndefValue>(texLd.get_offset0());
  1585. noOffset &= isa<UndefValue>(texLd.get_offset1());
  1586. noOffset &= isa<UndefValue>(texLd.get_offset2());
  1587. if (!noOffset) {
  1588. ValCtx.EmitInstrError(CI,
  1589. ValidationRule::InstrOffsetOnUAVLoad);
  1590. }
  1591. if (!isa<UndefValue>(mipLevel)) {
  1592. ValCtx.EmitInstrError(CI, ValidationRule::InstrMipOnUAVLoad);
  1593. }
  1594. } else {
  1595. if (resClass != DXIL::ResourceClass::SRV) {
  1596. ValCtx.EmitInstrError(CI, ValidationRule::InstrResourceClassForLoad);
  1597. }
  1598. }
  1599. switch (resKind) {
  1600. case DXIL::ResourceKind::Texture1D:
  1601. case DXIL::ResourceKind::Texture1DArray:
  1602. case DXIL::ResourceKind::Texture2D:
  1603. case DXIL::ResourceKind::Texture2DArray:
  1604. case DXIL::ResourceKind::Texture3D:
  1605. break;
  1606. case DXIL::ResourceKind::Texture2DMS:
  1607. case DXIL::ResourceKind::Texture2DMSArray: {
  1608. if (isa<UndefValue>(mipLevel)) {
  1609. ValCtx.EmitInstrError(
  1610. CI, ValidationRule::InstrSampleIndexForLoad2DMS);
  1611. }
  1612. } break;
  1613. default:
  1614. ValCtx.EmitInstrError(
  1615. CI, ValidationRule::InstrResourceKindForTextureLoad);
  1616. break;
  1617. }
  1618. } break;
  1619. case DXIL::OpCode::CutStream:
  1620. case DXIL::OpCode::EmitThenCutStream:
  1621. case DXIL::OpCode::EmitStream: {
  1622. if (pSM->IsGS()) {
  1623. unsigned streamMask = ValCtx.DxilMod.GetActiveStreamMask();
  1624. Value *streamID =
  1625. CI->getArgOperand(DXIL::OperandIndex::kStreamEmitCutIDOpIdx);
  1626. if (ConstantInt *cStreamID = dyn_cast<ConstantInt>(streamID)) {
  1627. int immStreamID = cStreamID->getValue().getLimitedValue();
  1628. if (cStreamID->getValue().isNegative() || immStreamID >= 4) {
  1629. ValCtx.EmitOperandOutOfRange(CI, "StreamID","0~4",
  1630. std::to_string(immStreamID));
  1631. } else {
  1632. unsigned immMask = 1 << immStreamID;
  1633. if ((streamMask & immMask) == 0) {
  1634. std::string range;
  1635. for (unsigned i = 0; i < 4; i++) {
  1636. if (streamMask & (1 << i)) {
  1637. range += std::to_string(i) + " ";
  1638. }
  1639. }
  1640. ValCtx.EmitOperandOutOfRange(CI, "StreamID", range,
  1641. std::to_string(immStreamID));
  1642. }
  1643. }
  1644. } else {
  1645. ValCtx.EmitInstrFormatError(CI, ValidationRule::InstrOpConst,
  1646. {"StreamID", "Emit/CutStream"});
  1647. }
  1648. } else {
  1649. ValCtx.EmitInstrFormatError(CI, ValidationRule::SmOpcodeInInvalidFunction,
  1650. {"Emit/CutStream", "Geometry shader"});
  1651. }
  1652. } break;
  1653. case DXIL::OpCode::BufferUpdateCounter: {
  1654. DxilInst_BufferUpdateCounter updateCounter(CI);
  1655. DXIL::ComponentType compTy;
  1656. DXIL::ResourceClass resClass;
  1657. unsigned resIndex;
  1658. DXIL::ResourceKind resKind =
  1659. GetResourceKindAndCompTy(updateCounter.get_uav(), compTy, resClass, resIndex, ValCtx);
  1660. if (resClass != DXIL::ResourceClass::UAV) {
  1661. ValCtx.EmitInstrError(CI,
  1662. ValidationRule::InstrBufferUpdateCounterOnUAV);
  1663. }
  1664. if (resKind != DXIL::ResourceKind::StructuredBuffer) {
  1665. ValCtx.EmitInstrError(CI,
  1666. ValidationRule::SmCounterOnlyOnStructBuf);
  1667. }
  1668. Value *inc = updateCounter.get_inc();
  1669. if (ConstantInt *cInc = dyn_cast<ConstantInt>(inc)) {
  1670. bool isInc = cInc->getLimitedValue() == 1;
  1671. if (ValCtx.UavCounterIncMap.count(resIndex)) {
  1672. if (isInc != ValCtx.UavCounterIncMap[resIndex]) {
  1673. ValCtx.EmitInstrError(CI, ValidationRule::InstrOnlyOneAllocConsume);
  1674. }
  1675. }
  1676. else {
  1677. ValCtx.UavCounterIncMap[resIndex] = isInc;
  1678. }
  1679. } else {
  1680. ValCtx.EmitInstrFormatError(CI, ValidationRule::InstrOpConst, {"inc", "BufferUpdateCounter"});
  1681. }
  1682. } break;
  1683. case DXIL::OpCode::Asin: {
  1684. DxilInst_Asin I(CI);
  1685. if (ConstantFP *imm = dyn_cast<ConstantFP>(I.get_value())) {
  1686. if (imm->getValueAPF().isInfinity()) {
  1687. ValCtx.EmitInstrError(CI, ValidationRule::InstrNoIndefiniteAsin);
  1688. }
  1689. }
  1690. } break;
  1691. case DXIL::OpCode::Acos: {
  1692. DxilInst_Acos I(CI);
  1693. if (ConstantFP *imm = dyn_cast<ConstantFP>(I.get_value())) {
  1694. if (imm->getValueAPF().isInfinity()) {
  1695. ValCtx.EmitInstrError(CI, ValidationRule::InstrNoIndefiniteAcos);
  1696. }
  1697. }
  1698. } break;
  1699. case DXIL::OpCode::Log: {
  1700. DxilInst_Log I(CI);
  1701. if (ConstantFP *imm = dyn_cast<ConstantFP>(I.get_value())) {
  1702. if (imm->getValueAPF().isInfinity()) {
  1703. ValCtx.EmitInstrError(CI, ValidationRule::InstrNoIndefiniteLog);
  1704. }
  1705. }
  1706. } break;
  1707. case DXIL::OpCode::DerivFineX:
  1708. case DXIL::OpCode::DerivFineY:
  1709. case DXIL::OpCode::DerivCoarseX:
  1710. case DXIL::OpCode::DerivCoarseY: {
  1711. Value *V = CI->getArgOperand(DXIL::OperandIndex::kUnarySrc0OpIdx);
  1712. if (ConstantFP *imm = dyn_cast<ConstantFP>(V)) {
  1713. if (imm->getValueAPF().isInfinity()) {
  1714. ValCtx.EmitInstrError(CI, ValidationRule::InstrNoIndefiniteDsxy);
  1715. }
  1716. }
  1717. } break;
  1718. case DXIL::OpCode::Coverage:
  1719. ValCtx.m_bCoverageIn = true;
  1720. break;
  1721. case DXIL::OpCode::InnerCoverage:
  1722. ValCtx.m_bInnerCoverageIn = true;
  1723. break;
  1724. case DXIL::OpCode::ViewID:
  1725. ValCtx.hasViewID = true;
  1726. break;
  1727. default:
  1728. // Skip opcodes don't need special check.
  1729. break;
  1730. }
  1731. if (ValCtx.m_bCoverageIn && ValCtx.m_bInnerCoverageIn) {
  1732. ValCtx.EmitError(ValidationRule::SmPSCoverageAndInnerCoverage);
  1733. }
  1734. }
  1735. static bool IsDxilFunction(llvm::Function *F) {
  1736. unsigned argSize = F->arg_size();
  1737. if (argSize < 1) {
  1738. // Cannot be a DXIL operation.
  1739. return false;
  1740. }
  1741. return OP::IsDxilOpFunc(F);
  1742. }
  1743. static void ValidateExternalFunction(Function *F, ValidationContext &ValCtx) {
  1744. if (!IsDxilFunction(F)) {
  1745. ValCtx.EmitGlobalValueError(F, ValidationRule::DeclDxilFnExtern);
  1746. return;
  1747. }
  1748. if (F->use_empty()) {
  1749. ValCtx.EmitGlobalValueError(F, ValidationRule::DeclUsedExternalFunction);
  1750. return;
  1751. }
  1752. const ShaderModel *pSM = ValCtx.DxilMod.GetShaderModel();
  1753. OP *hlslOP = ValCtx.DxilMod.GetOP();
  1754. Type *voidTy = Type::getVoidTy(F->getContext());
  1755. for (User *user : F->users()) {
  1756. CallInst *CI = dyn_cast<CallInst>(user);
  1757. if (!CI) {
  1758. ValCtx.EmitGlobalValueError(F, ValidationRule::DeclFnIsCalled);
  1759. continue;
  1760. }
  1761. Value *argOpcode = CI->getArgOperand(0);
  1762. ConstantInt *constOpcode = dyn_cast<ConstantInt>(argOpcode);
  1763. if (!constOpcode) {
  1764. // opcode not immediate; function body will validate this error.
  1765. continue;
  1766. }
  1767. unsigned opcode = constOpcode->getLimitedValue();
  1768. if (opcode >= (unsigned)DXIL::OpCode::NumOpCodes) {
  1769. // invalid opcode; function body will validate this error.
  1770. continue;
  1771. }
  1772. DXIL::OpCode dxilOpcode = (DXIL::OpCode)opcode;
  1773. // In some cases, no overloads are provided (void is exclusive to others)
  1774. Function *dxilFunc;
  1775. if (hlslOP->IsOverloadLegal(dxilOpcode, voidTy)) {
  1776. dxilFunc = hlslOP->GetOpFunc(dxilOpcode, voidTy);
  1777. }
  1778. else {
  1779. Type *Ty = hlslOP->GetOverloadType(dxilOpcode, CI->getCalledFunction());
  1780. try {
  1781. if (!hlslOP->IsOverloadLegal(dxilOpcode, Ty)) {
  1782. ValCtx.EmitInstrError(CI, ValidationRule::InstrOload);
  1783. continue;
  1784. }
  1785. }
  1786. catch (...) {
  1787. ValCtx.EmitInstrError(CI, ValidationRule::InstrOload);
  1788. continue;
  1789. }
  1790. dxilFunc = hlslOP->GetOpFunc(dxilOpcode, Ty->getScalarType());
  1791. }
  1792. if (!dxilFunc) {
  1793. // Cannot find dxilFunction based on opcode and type.
  1794. ValCtx.EmitInstrError(CI, ValidationRule::InstrOload);
  1795. continue;
  1796. }
  1797. if (dxilFunc->getFunctionType() != F->getFunctionType()) {
  1798. ValCtx.EmitGlobalValueError(dxilFunc, ValidationRule::InstrCallOload);
  1799. continue;
  1800. }
  1801. if (!ValidateOpcodeInProfile(dxilOpcode, pSM)) {
  1802. // Opcode not available in profile.
  1803. ValCtx.EmitInstrFormatError(CI, ValidationRule::SmOpcode,
  1804. {hlslOP->GetOpCodeName(dxilOpcode),
  1805. pSM->GetName()});
  1806. continue;
  1807. }
  1808. // Check more detail.
  1809. ValidateDxilOperationCallInProfile(CI, dxilOpcode, pSM, ValCtx);
  1810. }
  1811. }
  1812. ///////////////////////////////////////////////////////////////////////////////
  1813. // Instruction validation functions. //
  1814. static bool IsLLVMInstructionAllowed(llvm::Instruction &I) {
  1815. unsigned op = I.getOpcode();
  1816. /* <py::lines('OPCODE-ALLOWED')>hctdb_instrhelp.get_instrs_pred("op", lambda i: not i.is_dxil_op and i.is_allowed, "llvm_id")</py>*/
  1817. // OPCODE-ALLOWED:BEGIN
  1818. // Instructions: Ret=1, Br=2, Switch=3, Add=8, FAdd=9, Sub=10, FSub=11, Mul=12,
  1819. // FMul=13, UDiv=14, SDiv=15, FDiv=16, URem=17, SRem=18, FRem=19, Shl=20,
  1820. // LShr=21, AShr=22, And=23, Or=24, Xor=25, Alloca=26, Load=27, Store=28,
  1821. // GetElementPtr=29, AtomicCmpXchg=31, AtomicRMW=32, Trunc=33, ZExt=34,
  1822. // SExt=35, FPToUI=36, FPToSI=37, UIToFP=38, SIToFP=39, FPTrunc=40, FPExt=41,
  1823. // BitCast=44, AddrSpaceCast=45, ICmp=46, FCmp=47, PHI=48, Call=49, Select=50,
  1824. // ExtractValue=57
  1825. return 1 <= op && op <= 3 || 8 <= op && op <= 29 || 31 <= op && op <= 41 || 44 <= op && op <= 50 || op == 57;
  1826. // OPCODE-ALLOWED:END
  1827. }
  1828. static bool IsDxilBuiltinStructType(StructType *ST, hlsl::OP *hlslOP) {
  1829. if (ST == hlslOP->GetBinaryWithCarryType())
  1830. return true;
  1831. if (ST == hlslOP->GetBinaryWithTwoOutputsType())
  1832. return true;
  1833. if (ST == hlslOP->GetInt4Type())
  1834. return true;
  1835. if (ST == hlslOP->GetDimensionsType())
  1836. return true;
  1837. if (ST == hlslOP->GetHandleType())
  1838. return true;
  1839. if (ST == hlslOP->GetSamplePosType())
  1840. return true;
  1841. if (ST == hlslOP->GetSplitDoubleType())
  1842. return true;
  1843. unsigned EltNum = ST->getNumElements();
  1844. switch (EltNum) {
  1845. case 2:
  1846. case 4:
  1847. case 8: { // 2 for doubles, 8 for halfs.
  1848. Type *EltTy = ST->getElementType(0);
  1849. return ST == hlslOP->GetCBufferRetType(EltTy);
  1850. } break;
  1851. case 5: {
  1852. Type *EltTy = ST->getElementType(0);
  1853. return ST == hlslOP->GetResRetType(EltTy);
  1854. } break;
  1855. default:
  1856. return false;
  1857. }
  1858. }
  1859. static bool ValidateType(Type *Ty, ValidationContext &ValCtx) {
  1860. DXASSERT_NOMSG(Ty != nullptr);
  1861. if (Ty->isPointerTy()) {
  1862. return ValidateType(Ty->getPointerElementType(), ValCtx);
  1863. }
  1864. if (Ty->isArrayTy()) {
  1865. Type *EltTy = Ty->getArrayElementType();
  1866. if (isa<ArrayType>(EltTy)) {
  1867. ValCtx.EmitTypeError(Ty, ValidationRule::TypesNoMultiDim);
  1868. return false;
  1869. }
  1870. return ValidateType(EltTy, ValCtx);
  1871. }
  1872. if (Ty->isStructTy()) {
  1873. bool result = true;
  1874. StructType *ST = cast<StructType>(Ty);
  1875. StringRef Name = ST->getName();
  1876. if (Name.startswith("dx.")) {
  1877. hlsl::OP *hlslOP = ValCtx.DxilMod.GetOP();
  1878. if (IsDxilBuiltinStructType(ST, hlslOP)) {
  1879. ValCtx.EmitTypeError(Ty, ValidationRule::InstrDxilStructUser);
  1880. result = false;
  1881. }
  1882. ValCtx.EmitTypeError(Ty, ValidationRule::DeclDxilNsReserved);
  1883. result = false;
  1884. }
  1885. for (auto e : ST->elements()) {
  1886. if (!ValidateType(e, ValCtx)) {
  1887. result = false;
  1888. }
  1889. }
  1890. return result;
  1891. }
  1892. if (Ty->isFloatTy() || Ty->isHalfTy() || Ty->isDoubleTy()) {
  1893. return true;
  1894. }
  1895. if (Ty->isIntegerTy()) {
  1896. unsigned width = Ty->getIntegerBitWidth();
  1897. if (width != 1 && width != 8 && width != 16 && width != 32 && width != 64) {
  1898. ValCtx.EmitTypeError(Ty, ValidationRule::TypesIntWidth);
  1899. return false;
  1900. }
  1901. return true;
  1902. }
  1903. if (Ty->isVectorTy()) {
  1904. ValCtx.EmitTypeError(Ty, ValidationRule::TypesNoVector);
  1905. return false;
  1906. }
  1907. ValCtx.EmitTypeError(Ty, ValidationRule::TypesDefined);
  1908. return false;
  1909. }
  1910. static bool GetNodeOperandAsInt(ValidationContext &ValCtx, MDNode *pMD, unsigned index, uint64_t *pValue) {
  1911. *pValue = 0;
  1912. if (pMD->getNumOperands() < index) {
  1913. ValCtx.EmitMetaError(pMD, ValidationRule::MetaWellFormed);
  1914. return false;
  1915. }
  1916. ConstantAsMetadata *C = dyn_cast<ConstantAsMetadata>(pMD->getOperand(index));
  1917. if (C == nullptr) {
  1918. ValCtx.EmitMetaError(pMD, ValidationRule::MetaWellFormed);
  1919. return false;
  1920. }
  1921. ConstantInt *CI = dyn_cast<ConstantInt>(C->getValue());
  1922. if (CI == nullptr) {
  1923. ValCtx.EmitMetaError(pMD, ValidationRule::MetaWellFormed);
  1924. return false;
  1925. }
  1926. *pValue = CI->getValue().getZExtValue();
  1927. return true;
  1928. }
  1929. static bool IsPrecise(Instruction &I, ValidationContext &ValCtx) {
  1930. MDNode *pMD = I.getMetadata(DxilMDHelper::kDxilPreciseAttributeMDName);
  1931. if (pMD == nullptr) {
  1932. return false;
  1933. }
  1934. if (pMD->getNumOperands() != 1) {
  1935. ValCtx.EmitMetaError(pMD, ValidationRule::MetaWellFormed);
  1936. return false;
  1937. }
  1938. uint64_t val;
  1939. if (!GetNodeOperandAsInt(ValCtx, pMD, 0, &val)) {
  1940. return false;
  1941. }
  1942. if (val == 1) {
  1943. return true;
  1944. }
  1945. if (val != 0) {
  1946. ValCtx.EmitMetaError(pMD, ValidationRule::MetaValueRange);
  1947. }
  1948. return false;
  1949. }
  1950. static bool IsValueMinPrec(DxilModule &DxilMod, Value *V) {
  1951. DXASSERT(DxilMod.GetGlobalFlags() & DXIL::kEnableMinPrecision,
  1952. "else caller didn't check - currently this path should never be hit "
  1953. "otherwise");
  1954. (DxilMod);
  1955. Type *Ty = V->getType();
  1956. if (Ty->isIntegerTy()) {
  1957. return 16 == Ty->getIntegerBitWidth();
  1958. }
  1959. return Ty->isHalfTy();
  1960. }
  1961. static void ValidateGradientOps(Function *F, ArrayRef<CallInst *> ops, ArrayRef<CallInst *> barriers, ValidationContext &ValCtx) {
  1962. // In the absence of wave operations, the wave validation effect need not happen.
  1963. // We haven't verified this is true at this point, but validation will fail
  1964. // later if the flags don't match in any case. Given that most shaders will
  1965. // not be using these wave operations, it's a reasonable cost saving.
  1966. if (!ValCtx.DxilMod.m_ShaderFlags.GetWaveOps()) {
  1967. return;
  1968. }
  1969. std::unique_ptr<WaveSensitivityAnalysis> WaveVal(WaveSensitivityAnalysis::create());
  1970. WaveVal->Analyze(F);
  1971. for (CallInst *op : ops) {
  1972. if (WaveVal->IsWaveSensitive(op)) {
  1973. ValCtx.EmitInstrError(op, ValidationRule::UniNoWaveSensitiveGradient);
  1974. }
  1975. }
  1976. }
  1977. static void ValidateControlFlowHint(BasicBlock &bb, ValidationContext &ValCtx) {
  1978. // Validate controlflow hint.
  1979. TerminatorInst *TI = bb.getTerminator();
  1980. if (!TI)
  1981. return;
  1982. MDNode *pNode = TI->getMetadata(DxilMDHelper::kDxilControlFlowHintMDName);
  1983. if (!pNode)
  1984. return;
  1985. if (pNode->getNumOperands() < 3)
  1986. return;
  1987. bool bHasBranch = false;
  1988. bool bHasFlatten = false;
  1989. bool bForceCase = false;
  1990. for (unsigned i = 2; i < pNode->getNumOperands(); i++) {
  1991. uint64_t value = 0;
  1992. if (GetNodeOperandAsInt(ValCtx, pNode, i, &value)) {
  1993. DXIL::ControlFlowHint hint = static_cast<DXIL::ControlFlowHint>(value);
  1994. switch (hint) {
  1995. case DXIL::ControlFlowHint::Flatten:
  1996. bHasFlatten = true;
  1997. break;
  1998. case DXIL::ControlFlowHint::Branch:
  1999. bHasBranch = true;
  2000. break;
  2001. case DXIL::ControlFlowHint::ForceCase:
  2002. bForceCase = true;
  2003. break;
  2004. default:
  2005. ValCtx.EmitMetaError(pNode,
  2006. ValidationRule::MetaInvalidControlFlowHint);
  2007. }
  2008. }
  2009. }
  2010. if (bHasBranch && bHasFlatten) {
  2011. ValCtx.EmitMetaError(pNode, ValidationRule::MetaBranchFlatten);
  2012. }
  2013. if (bForceCase && !isa<SwitchInst>(TI)) {
  2014. ValCtx.EmitMetaError(pNode, ValidationRule::MetaForceCaseOnSwitch);
  2015. }
  2016. }
  2017. static void ValidateTBAAMetadata(MDNode *Node, ValidationContext &ValCtx) {
  2018. switch (Node->getNumOperands()) {
  2019. case 1: {
  2020. if (Node->getOperand(0)->getMetadataID() != Metadata::MDStringKind) {
  2021. ValCtx.EmitMetaError(Node, ValidationRule::MetaWellFormed);
  2022. }
  2023. } break;
  2024. case 2: {
  2025. MDNode *rootNode = dyn_cast<MDNode>(Node->getOperand(1));
  2026. if (!rootNode) {
  2027. ValCtx.EmitMetaError(Node, ValidationRule::MetaWellFormed);
  2028. } else {
  2029. ValidateTBAAMetadata(rootNode, ValCtx);
  2030. }
  2031. } break;
  2032. case 3: {
  2033. MDNode *rootNode = dyn_cast<MDNode>(Node->getOperand(1));
  2034. if (!rootNode) {
  2035. ValCtx.EmitMetaError(Node, ValidationRule::MetaWellFormed);
  2036. } else {
  2037. ValidateTBAAMetadata(rootNode, ValCtx);
  2038. }
  2039. ConstantAsMetadata *pointsToConstMem = dyn_cast<ConstantAsMetadata>(Node->getOperand(2));
  2040. if (!pointsToConstMem) {
  2041. ValCtx.EmitMetaError(Node, ValidationRule::MetaWellFormed);
  2042. } else {
  2043. ConstantInt *isConst = dyn_cast<ConstantInt>(pointsToConstMem->getValue());
  2044. if (!isConst) {
  2045. ValCtx.EmitMetaError(Node, ValidationRule::MetaWellFormed);
  2046. } else if (isConst->getValue().getLimitedValue() > 1) {
  2047. ValCtx.EmitMetaError(Node, ValidationRule::MetaWellFormed);
  2048. }
  2049. }
  2050. } break;
  2051. default:
  2052. ValCtx.EmitMetaError(Node, ValidationRule::MetaWellFormed);
  2053. }
  2054. }
  2055. static void ValidateLoopMetadata(MDNode *Node, ValidationContext &ValCtx) {
  2056. if (Node->getNumOperands() == 0 || Node->getNumOperands() > 2) {
  2057. ValCtx.EmitMetaError(Node, ValidationRule::MetaWellFormed);
  2058. return;
  2059. }
  2060. if (Node != Node->getOperand(0).get()) {
  2061. ValCtx.EmitMetaError(Node, ValidationRule::MetaWellFormed);
  2062. return;
  2063. }
  2064. if (Node->getNumOperands() == 1) {
  2065. return;
  2066. }
  2067. MDNode *LoopNode = dyn_cast<MDNode>(Node->getOperand(1).get());
  2068. if (!LoopNode) {
  2069. ValCtx.EmitMetaError(Node, ValidationRule::MetaWellFormed);
  2070. return;
  2071. }
  2072. if (LoopNode->getNumOperands() < 1 || LoopNode->getNumOperands() > 2) {
  2073. ValCtx.EmitMetaError(LoopNode, ValidationRule::MetaWellFormed);
  2074. return;
  2075. }
  2076. if (LoopNode->getOperand(0) == LoopNode) {
  2077. ValidateLoopMetadata(LoopNode, ValCtx);
  2078. return;
  2079. }
  2080. MDString *LoopStr = dyn_cast<MDString>(LoopNode->getOperand(0));
  2081. if (!LoopStr) {
  2082. ValCtx.EmitMetaError(LoopNode, ValidationRule::MetaWellFormed);
  2083. return;
  2084. }
  2085. StringRef Name = LoopStr->getString();
  2086. if (Name != "llvm.loop.unroll.full" && Name != "llvm.loop.unroll.disable" &&
  2087. Name != "llvm.loop.unroll.count") {
  2088. ValCtx.EmitMetaError(LoopNode, ValidationRule::MetaWellFormed);
  2089. return;
  2090. }
  2091. if (Name == "llvm.loop.unroll.count") {
  2092. if (LoopNode->getNumOperands() != 2) {
  2093. ValCtx.EmitMetaError(LoopNode, ValidationRule::MetaWellFormed);
  2094. return;
  2095. }
  2096. ConstantAsMetadata *CountNode =
  2097. dyn_cast<ConstantAsMetadata>(LoopNode->getOperand(1));
  2098. if (!CountNode) {
  2099. ValCtx.EmitMetaError(LoopNode, ValidationRule::MetaWellFormed);
  2100. } else {
  2101. ConstantInt *Count = dyn_cast<ConstantInt>(CountNode->getValue());
  2102. if (!Count) {
  2103. ValCtx.EmitMetaError(CountNode, ValidationRule::MetaWellFormed);
  2104. }
  2105. }
  2106. }
  2107. }
  2108. static void ValidateInstructionMetadata(Instruction *I,
  2109. ValidationContext &ValCtx) {
  2110. SmallVector<std::pair<unsigned, MDNode *>, 2> MDNodes;
  2111. I->getAllMetadataOtherThanDebugLoc(MDNodes);
  2112. for (auto &MD : MDNodes) {
  2113. if (MD.first == ValCtx.kDxilControlFlowHintMDKind) {
  2114. if (!isa<TerminatorInst>(I)) {
  2115. ValCtx.EmitInstrError(
  2116. I, ValidationRule::MetaControlFlowHintNotOnControlFlow);
  2117. }
  2118. } else if (MD.first == ValCtx.kDxilPreciseMDKind) {
  2119. // Validated in IsPrecise.
  2120. } else if (MD.first == ValCtx.kLLVMLoopMDKind) {
  2121. ValidateLoopMetadata(MD.second, ValCtx);
  2122. } else if (MD.first == LLVMContext::MD_tbaa) {
  2123. ValidateTBAAMetadata(MD.second, ValCtx);
  2124. } else if (MD.first == LLVMContext::MD_range) {
  2125. // Validated in Verifier.cpp.
  2126. } else if (MD.first == LLVMContext::MD_noalias ||
  2127. MD.first == LLVMContext::MD_alias_scope) {
  2128. // noalias for DXIL validator >= 1.2
  2129. } else {
  2130. ValCtx.EmitMetaError(MD.second, ValidationRule::MetaUsed);
  2131. }
  2132. }
  2133. }
  2134. static void ValidateFunctionMetadata(Function *F, ValidationContext &ValCtx) {
  2135. SmallVector<std::pair<unsigned, MDNode *>, 2> MDNodes;
  2136. F->getAllMetadata(MDNodes);
  2137. for (auto &MD : MDNodes) {
  2138. ValCtx.EmitMetaError(MD.second, ValidationRule::MetaUsed);
  2139. }
  2140. }
  2141. static void ValidateFunctionBody(Function *F, ValidationContext &ValCtx) {
  2142. bool SupportsMinPrecision =
  2143. ValCtx.DxilMod.GetGlobalFlags() & DXIL::kEnableMinPrecision;
  2144. SmallVector<CallInst *, 16> gradientOps;
  2145. SmallVector<CallInst *, 16> barriers;
  2146. for (auto b = F->begin(), bend = F->end(); b != bend; ++b) {
  2147. for (auto i = b->begin(), iend = b->end(); i != iend; ++i) {
  2148. llvm::Instruction &I = *i;
  2149. if (I.hasMetadata()) {
  2150. ValidateInstructionMetadata(&I, ValCtx);
  2151. }
  2152. // Instructions must be allowed.
  2153. if (!IsLLVMInstructionAllowed(I)) {
  2154. ValCtx.EmitInstrError(&I, ValidationRule::InstrAllowed);
  2155. continue;
  2156. }
  2157. // Instructions marked precise may not have minprecision arguments.
  2158. if (SupportsMinPrecision) {
  2159. if (IsPrecise(I, ValCtx)) {
  2160. for (auto &O : I.operands()) {
  2161. if (IsValueMinPrec(ValCtx.DxilMod, O)) {
  2162. ValCtx.EmitInstrError(
  2163. &I, ValidationRule::InstrMinPrecisionNotPrecise);
  2164. break;
  2165. }
  2166. }
  2167. }
  2168. }
  2169. // Calls to external functions.
  2170. CallInst *CI = dyn_cast<CallInst>(&I);
  2171. if (CI) {
  2172. Function *FCalled = CI->getCalledFunction();
  2173. if (FCalled->isDeclaration()) {
  2174. // External function validation will diagnose.
  2175. if (!IsDxilFunction(FCalled)) {
  2176. continue;
  2177. }
  2178. Value *opcodeVal = CI->getOperand(0);
  2179. ConstantInt *OpcodeConst = dyn_cast<ConstantInt>(opcodeVal);
  2180. if (OpcodeConst == nullptr) {
  2181. ValCtx.EmitInstrFormatError(&I, ValidationRule::InstrOpConst,
  2182. {"Opcode", "DXIL operation"});
  2183. continue;
  2184. }
  2185. unsigned opcode = OpcodeConst->getLimitedValue();
  2186. DXIL::OpCode dxilOpcode = (DXIL::OpCode)opcode;
  2187. if (OP::IsDxilOpGradient(dxilOpcode)) {
  2188. gradientOps.push_back(CI);
  2189. }
  2190. if (dxilOpcode == DXIL::OpCode::Barrier) {
  2191. barriers.push_back(CI);
  2192. }
  2193. // External function validation will check the parameter
  2194. // list. This function will check that the call does not
  2195. // violate any rules.
  2196. }
  2197. continue;
  2198. }
  2199. for (Value *op : I.operands()) {
  2200. if (!isa<PHINode>(&I) && isa<UndefValue>(op)) {
  2201. ValCtx.EmitInstrError(&I,
  2202. ValidationRule::InstrNoReadingUninitialized);
  2203. } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(op)) {
  2204. for (Value *opCE : CE->operands()) {
  2205. if (isa<UndefValue>(opCE)) {
  2206. ValCtx.EmitInstrError(
  2207. &I, ValidationRule::InstrNoReadingUninitialized);
  2208. }
  2209. }
  2210. }
  2211. if (IntegerType *IT = dyn_cast<IntegerType>(op->getType())) {
  2212. if (IT->getBitWidth() == 8) {
  2213. ValCtx.EmitInstrError(&I, ValidationRule::TypesI8);
  2214. }
  2215. }
  2216. }
  2217. Type *Ty = I.getType();
  2218. if (isa<PointerType>(Ty))
  2219. Ty = Ty->getPointerElementType();
  2220. while (isa<ArrayType>(Ty))
  2221. Ty = Ty->getArrayElementType();
  2222. if (IntegerType *IT = dyn_cast<IntegerType>(Ty)) {
  2223. if (IT->getBitWidth() == 8) {
  2224. ValCtx.EmitInstrError(&I, ValidationRule::TypesI8);
  2225. }
  2226. }
  2227. unsigned opcode = I.getOpcode();
  2228. switch (opcode) {
  2229. case Instruction::Alloca: {
  2230. AllocaInst *AI = cast<AllocaInst>(&I);
  2231. // TODO: validate address space and alignment
  2232. Type *Ty = AI->getAllocatedType();
  2233. if (!ValidateType(Ty, ValCtx)) {
  2234. continue;
  2235. }
  2236. } break;
  2237. case Instruction::ExtractValue: {
  2238. ExtractValueInst *EV = cast<ExtractValueInst>(&I);
  2239. Type *Ty = EV->getAggregateOperand()->getType();
  2240. if (StructType *ST = dyn_cast<StructType>(Ty)) {
  2241. Value *Agg = EV->getAggregateOperand();
  2242. if (!isa<AtomicCmpXchgInst>(Agg) &&
  2243. !IsDxilBuiltinStructType(ST, ValCtx.DxilMod.GetOP())) {
  2244. ValCtx.EmitInstrError(EV, ValidationRule::InstrExtractValue);
  2245. }
  2246. } else {
  2247. ValCtx.EmitInstrError(EV, ValidationRule::InstrExtractValue);
  2248. }
  2249. } break;
  2250. case Instruction::Load: {
  2251. Type *Ty = I.getType();
  2252. if (!ValidateType(Ty, ValCtx)) {
  2253. continue;
  2254. }
  2255. } break;
  2256. case Instruction::Store: {
  2257. StoreInst *SI = cast<StoreInst>(&I);
  2258. Type *Ty = SI->getValueOperand()->getType();
  2259. if (!ValidateType(Ty, ValCtx)) {
  2260. continue;
  2261. }
  2262. } break;
  2263. case Instruction::GetElementPtr: {
  2264. Type *Ty = I.getType()->getPointerElementType();
  2265. if (!ValidateType(Ty, ValCtx)) {
  2266. continue;
  2267. }
  2268. GetElementPtrInst *GEP = cast<GetElementPtrInst>(&I);
  2269. bool allImmIndex = true;
  2270. for (auto Idx = GEP->idx_begin(), E = GEP->idx_end(); Idx != E; Idx++) {
  2271. if (!isa<ConstantInt>(Idx)) {
  2272. allImmIndex = false;
  2273. break;
  2274. }
  2275. }
  2276. if (allImmIndex) {
  2277. const DataLayout &DL = ValCtx.DL;
  2278. Value *Ptr = GEP->getPointerOperand();
  2279. unsigned size =
  2280. DL.getTypeAllocSize(Ptr->getType()->getPointerElementType());
  2281. unsigned valSize = DL.getTypeAllocSize(GEP->getType()->getPointerElementType());
  2282. SmallVector<Value *, 8> Indices(GEP->idx_begin(), GEP->idx_end());
  2283. unsigned offset =
  2284. DL.getIndexedOffset(GEP->getPointerOperandType(), Indices);
  2285. if ((offset + valSize) > size) {
  2286. ValCtx.EmitInstrError(GEP, ValidationRule::InstrInBoundsAccess);
  2287. }
  2288. }
  2289. } break;
  2290. case Instruction::SDiv: {
  2291. BinaryOperator *BO = cast<BinaryOperator>(&I);
  2292. Value *V = BO->getOperand(1);
  2293. if (ConstantInt *imm = dyn_cast<ConstantInt>(V)) {
  2294. if (imm->getValue().getLimitedValue() == 0) {
  2295. ValCtx.EmitInstrError(BO, ValidationRule::InstrNoIDivByZero);
  2296. }
  2297. }
  2298. } break;
  2299. case Instruction::UDiv: {
  2300. BinaryOperator *BO = cast<BinaryOperator>(&I);
  2301. Value *V = BO->getOperand(1);
  2302. if (ConstantInt *imm = dyn_cast<ConstantInt>(V)) {
  2303. if (imm->getValue().getLimitedValue() == 0) {
  2304. ValCtx.EmitInstrError(BO, ValidationRule::InstrNoUDivByZero);
  2305. }
  2306. }
  2307. } break;
  2308. case Instruction::AddrSpaceCast: {
  2309. AddrSpaceCastInst *Cast = cast<AddrSpaceCastInst>(&I);
  2310. unsigned ToAddrSpace = Cast->getType()->getPointerAddressSpace();
  2311. unsigned FromAddrSpace = Cast->getOperand(0)->getType()->getPointerAddressSpace();
  2312. if (ToAddrSpace != DXIL::kGenericPointerAddrSpace &&
  2313. FromAddrSpace != DXIL::kGenericPointerAddrSpace) {
  2314. ValCtx.EmitInstrError(Cast, ValidationRule::InstrNoGenericPtrAddrSpaceCast);
  2315. }
  2316. } break;
  2317. case Instruction::BitCast: {
  2318. BitCastInst *Cast = cast<BitCastInst>(&I);
  2319. Type *FromTy = Cast->getOperand(0)->getType();
  2320. Type *ToTy = Cast->getType();
  2321. if (isa<PointerType>(FromTy)) {
  2322. FromTy = FromTy->getPointerElementType();
  2323. ToTy = ToTy->getPointerElementType();
  2324. unsigned FromSize = ValCtx.DL.getTypeAllocSize(FromTy);
  2325. unsigned ToSize = ValCtx.DL.getTypeAllocSize(ToTy);
  2326. if (FromSize != ToSize) {
  2327. ValCtx.EmitInstrError(Cast, ValidationRule::InstrPtrBitCast);
  2328. continue;
  2329. }
  2330. while (isa<ArrayType>(FromTy)) {
  2331. FromTy = FromTy->getArrayElementType();
  2332. }
  2333. while (isa<ArrayType>(ToTy)) {
  2334. ToTy = ToTy->getArrayElementType();
  2335. }
  2336. }
  2337. if (isa<StructType>(FromTy) || isa<StructType>(ToTy)) {
  2338. ValCtx.EmitInstrError(Cast, ValidationRule::InstrStructBitCast);
  2339. continue;
  2340. }
  2341. bool IsMinPrecisionTy = ValCtx.DL.getTypeAllocSize(FromTy) < 4 ||
  2342. ValCtx.DL.getTypeAllocSize(ToTy) < 4;
  2343. if (IsMinPrecisionTy) {
  2344. ValCtx.EmitInstrError(Cast, ValidationRule::InstrMinPrecisonBitCast);
  2345. }
  2346. } break;
  2347. }
  2348. if (PointerType *PT = dyn_cast<PointerType>(I.getType())) {
  2349. if (PT->getAddressSpace() == DXIL::kTGSMAddrSpace) {
  2350. if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&I)) {
  2351. Value *Ptr = GEP->getPointerOperand();
  2352. if (!isa<GlobalVariable>(Ptr)) {
  2353. ValCtx.EmitInstrError(
  2354. &I, ValidationRule::InstrFailToResloveTGSMPointer);
  2355. }
  2356. } else if (BitCastInst *BCI = dyn_cast<BitCastInst>(&I)) {
  2357. Value *Ptr = BCI->getOperand(0);
  2358. if (!isa<GetElementPtrInst>(Ptr) && !isa<GlobalVariable>(Ptr)) {
  2359. ValCtx.EmitInstrError(
  2360. &I, ValidationRule::InstrFailToResloveTGSMPointer);
  2361. }
  2362. } else {
  2363. ValCtx.EmitInstrError(
  2364. &I, ValidationRule::InstrFailToResloveTGSMPointer);
  2365. }
  2366. }
  2367. }
  2368. }
  2369. ValidateControlFlowHint(*b, ValCtx);
  2370. }
  2371. if (!gradientOps.empty()) {
  2372. ValidateGradientOps(F, gradientOps, barriers, ValCtx);
  2373. }
  2374. }
  2375. static void ValidateFunction(Function &F, ValidationContext &ValCtx) {
  2376. if (F.isDeclaration()) {
  2377. ValidateExternalFunction(&F, ValCtx);
  2378. } else {
  2379. if (!F.arg_empty())
  2380. ValCtx.EmitFormatError(ValidationRule::FlowFunctionCall,
  2381. {F.getName().str()});
  2382. DxilFunctionAnnotation *funcAnnotation =
  2383. ValCtx.DxilMod.GetTypeSystem().GetFunctionAnnotation(&F);
  2384. if (!funcAnnotation) {
  2385. ValCtx.EmitFormatError(ValidationRule::MetaFunctionAnnotation,
  2386. {F.getName().str()});
  2387. return;
  2388. }
  2389. // Validate parameter type.
  2390. for (auto &arg : F.args()) {
  2391. Type *argTy = arg.getType();
  2392. if (argTy->isPointerTy())
  2393. argTy = argTy->getPointerElementType();
  2394. while (argTy->isArrayTy()) {
  2395. argTy = argTy->getArrayElementType();
  2396. }
  2397. if (argTy->isStructTy()) {
  2398. if (arg.hasName())
  2399. ValCtx.EmitFormatError(
  2400. ValidationRule::DeclFnFlattenParam,
  2401. {arg.getName().str(), F.getName().str()});
  2402. else
  2403. ValCtx.EmitFormatError(ValidationRule::DeclFnFlattenParam,
  2404. {std::to_string(arg.getArgNo()),
  2405. F.getName().str()});
  2406. break;
  2407. }
  2408. }
  2409. ValidateFunctionBody(&F, ValCtx);
  2410. }
  2411. if (F.hasMetadata()) {
  2412. ValidateFunctionMetadata(&F, ValCtx);
  2413. }
  2414. }
  2415. static void ValidateGlobalVariable(GlobalVariable &GV,
  2416. ValidationContext &ValCtx) {
  2417. bool isInternalGV =
  2418. dxilutil::IsStaticGlobal(&GV) || dxilutil::IsSharedMemoryGlobal(&GV);
  2419. if (!isInternalGV) {
  2420. if (!GV.user_empty()) {
  2421. bool hasInstructionUser = false;
  2422. for (User *U : GV.users()) {
  2423. if (isa<Instruction>(U)) {
  2424. hasInstructionUser = true;
  2425. break;
  2426. }
  2427. }
  2428. // External GV should not have instruction user.
  2429. if (hasInstructionUser) {
  2430. ValCtx.EmitGlobalValueError(&GV, ValidationRule::DeclNotUsedExternal);
  2431. }
  2432. }
  2433. // Must have metadata description for each variable.
  2434. } else {
  2435. // Internal GV must have user.
  2436. if (GV.user_empty()) {
  2437. ValCtx.EmitGlobalValueError(&GV, ValidationRule::DeclUsedInternal);
  2438. }
  2439. // Validate type for internal globals.
  2440. if (dxilutil::IsStaticGlobal(&GV) || dxilutil::IsSharedMemoryGlobal(&GV)) {
  2441. Type *Ty = GV.getType()->getPointerElementType();
  2442. ValidateType(Ty, ValCtx);
  2443. }
  2444. }
  2445. }
  2446. static void CollectFixAddressAccess(Value *V,
  2447. std::vector<StoreInst *> &fixAddrTGSMList) {
  2448. for (User *U : V->users()) {
  2449. if (GEPOperator *GEP = dyn_cast<GEPOperator>(U)) {
  2450. if (isa<ConstantExpr>(GEP) || GEP->hasAllConstantIndices()) {
  2451. CollectFixAddressAccess(GEP, fixAddrTGSMList);
  2452. }
  2453. } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
  2454. fixAddrTGSMList.emplace_back(SI);
  2455. }
  2456. }
  2457. }
  2458. static bool IsDivergent(Value *V) {
  2459. // TODO: return correct result.
  2460. return false;
  2461. }
  2462. static void ValidateTGSMRaceCondition(std::vector<StoreInst *> &fixAddrTGSMList,
  2463. ValidationContext &ValCtx) {
  2464. std::unordered_set<Function *> fixAddrTGSMFuncSet;
  2465. for (StoreInst *I : fixAddrTGSMList) {
  2466. BasicBlock *BB = I->getParent();
  2467. fixAddrTGSMFuncSet.insert(BB->getParent());
  2468. }
  2469. for (auto &F : ValCtx.DxilMod.GetModule()->functions()) {
  2470. if (F.isDeclaration() || !fixAddrTGSMFuncSet.count(&F))
  2471. continue;
  2472. PostDominatorTree PDT;
  2473. PDT.runOnFunction(F);
  2474. BasicBlock *Entry = &F.getEntryBlock();
  2475. for (StoreInst *SI : fixAddrTGSMList) {
  2476. BasicBlock *BB = SI->getParent();
  2477. if (BB->getParent() == &F) {
  2478. if (PDT.dominates(BB, Entry)) {
  2479. if (IsDivergent(SI->getValueOperand()))
  2480. ValCtx.EmitInstrError(SI, ValidationRule::InstrTGSMRaceCond);
  2481. }
  2482. }
  2483. }
  2484. }
  2485. }
  2486. static void ValidateGlobalVariables(ValidationContext &ValCtx) {
  2487. DxilModule &M = ValCtx.DxilMod;
  2488. unsigned TGSMSize = 0;
  2489. std::vector<StoreInst*> fixAddrTGSMList;
  2490. const DataLayout &DL = M.GetModule()->getDataLayout();
  2491. for (GlobalVariable &GV : M.GetModule()->globals()) {
  2492. ValidateGlobalVariable(GV, ValCtx);
  2493. if (GV.getType()->getAddressSpace() == DXIL::kTGSMAddrSpace) {
  2494. TGSMSize += DL.getTypeAllocSize(GV.getType()->getElementType());
  2495. CollectFixAddressAccess(&GV, fixAddrTGSMList);
  2496. }
  2497. }
  2498. if (TGSMSize > DXIL::kMaxTGSMSize) {
  2499. ValCtx.EmitFormatError(ValidationRule::SmMaxTGSMSize,
  2500. {std::to_string(TGSMSize),
  2501. std::to_string(DXIL::kMaxTGSMSize)});
  2502. }
  2503. if (!fixAddrTGSMList.empty()) {
  2504. ValidateTGSMRaceCondition(fixAddrTGSMList, ValCtx);
  2505. }
  2506. }
  2507. static void ValidateValidatorVersion(ValidationContext &ValCtx) {
  2508. Module *pModule = &ValCtx.M;
  2509. NamedMDNode *pNode = pModule->getNamedMetadata("dx.valver");
  2510. if (pNode == nullptr) {
  2511. return;
  2512. }
  2513. if (pNode->getNumOperands() == 1) {
  2514. MDTuple *pVerValues = dyn_cast<MDTuple>(pNode->getOperand(0));
  2515. if (pVerValues != nullptr && pVerValues->getNumOperands() == 2) {
  2516. uint64_t majorVer, minorVer;
  2517. if (GetNodeOperandAsInt(ValCtx, pVerValues, 0, &majorVer) &&
  2518. GetNodeOperandAsInt(ValCtx, pVerValues, 1, &minorVer)) {
  2519. unsigned curMajor, curMinor;
  2520. GetValidationVersion(&curMajor, &curMinor);
  2521. // This will need to be updated as major/minor versions evolve,
  2522. // depending on the degree of compat across versions.
  2523. if (majorVer == curMajor && minorVer <= curMinor) {
  2524. return;
  2525. }
  2526. }
  2527. }
  2528. }
  2529. ValCtx.EmitError(ValidationRule::MetaWellFormed);
  2530. }
  2531. static void ValidateDxilVersion(ValidationContext &ValCtx) {
  2532. Module *pModule = &ValCtx.M;
  2533. NamedMDNode *pNode = pModule->getNamedMetadata("dx.version");
  2534. if (pNode && pNode->getNumOperands() == 1) {
  2535. MDTuple *pVerValues = dyn_cast<MDTuple>(pNode->getOperand(0));
  2536. if (pVerValues != nullptr && pVerValues->getNumOperands() == 2) {
  2537. uint64_t majorVer, minorVer;
  2538. if (GetNodeOperandAsInt(ValCtx, pVerValues, 0, &majorVer) &&
  2539. GetNodeOperandAsInt(ValCtx, pVerValues, 1, &minorVer)) {
  2540. // This will need to be updated as dxil major/minor versions evolve,
  2541. // depending on the degree of compat across versions.
  2542. if ((majorVer == 1 && minorVer < 3) &&
  2543. (majorVer == ValCtx.m_DxilMajor && minorVer == ValCtx.m_DxilMinor)) {
  2544. return;
  2545. }
  2546. }
  2547. }
  2548. }
  2549. ValCtx.EmitError(ValidationRule::MetaWellFormed);
  2550. }
  2551. static void ValidateTypeAnnotation(ValidationContext &ValCtx) {
  2552. if (ValCtx.m_DxilMajor == 1 && ValCtx.m_DxilMinor >= 2) {
  2553. Module *pModule = &ValCtx.M;
  2554. NamedMDNode *TA = pModule->getNamedMetadata("dx.typeAnnotations");
  2555. if (TA == nullptr)
  2556. return;
  2557. for (unsigned i = 0, end = TA->getNumOperands(); i < end; ++i) {
  2558. MDTuple *TANode = dyn_cast<MDTuple>(TA->getOperand(i));
  2559. if (TANode->getNumOperands() < 3) {
  2560. ValCtx.EmitMetaError(TANode, ValidationRule::MetaWellFormed);
  2561. return;
  2562. }
  2563. ConstantInt *tag = mdconst::extract<ConstantInt>(TANode->getOperand(0));
  2564. uint64_t tagValue = tag->getZExtValue();
  2565. if (tagValue != DxilMDHelper::kDxilTypeSystemStructTag &&
  2566. tagValue != DxilMDHelper::kDxilTypeSystemFunctionTag &&
  2567. tagValue != DxilMDHelper::kDxilTypeSystemFunction2Tag) {
  2568. ValCtx.EmitMetaError(TANode, ValidationRule::MetaWellFormed);
  2569. return;
  2570. }
  2571. if (tagValue == DxilMDHelper::kDxilTypeSystemFunction2Tag) {
  2572. for (unsigned j = 2, jEnd = TANode->getNumOperands();
  2573. j != jEnd; ++j) {
  2574. MDTuple *FA = dyn_cast<MDTuple>(TANode->getOperand(j));
  2575. if (FA == nullptr) {
  2576. ValCtx.EmitMetaError(FA, ValidationRule::MetaWellFormed);
  2577. return;
  2578. }
  2579. MDNode *FlagNode = dyn_cast<MDNode>(FA->getOperand(0));
  2580. uint64_t flagValue = mdconst::extract<ConstantInt>(FlagNode->getOperand(0))->getZExtValue();
  2581. if (flagValue != (uint64_t)DXIL::FPDenormMode::Any &&
  2582. flagValue != (uint64_t)DXIL::FPDenormMode::FTZ &&
  2583. flagValue != (uint64_t)DXIL::FPDenormMode::Preserve) {
  2584. ValCtx.EmitMetaError(FA->getOperand(0), ValidationRule::MetaFPFlag);
  2585. }
  2586. }
  2587. }
  2588. }
  2589. }
  2590. }
  2591. static void ValidateMetadata(ValidationContext &ValCtx) {
  2592. Module *pModule = &ValCtx.M;
  2593. const std::string &target = pModule->getTargetTriple();
  2594. if (target != "dxil-ms-dx") {
  2595. ValCtx.EmitFormatError(ValidationRule::MetaTarget, {target});
  2596. }
  2597. // The llvm.dbg.(cu/contents/defines/mainFileName/arg) named metadata nodes
  2598. // are only available in debug modules, not in the validated ones.
  2599. // llvm.bitsets is also disallowed.
  2600. //
  2601. // These are verified in lib/IR/Verifier.cpp.
  2602. StringMap<bool> llvmNamedMeta;
  2603. llvmNamedMeta["llvm.ident"];
  2604. llvmNamedMeta["llvm.module.flags"];
  2605. for (auto &NamedMetaNode : pModule->named_metadata()) {
  2606. if (!DxilModule::IsKnownNamedMetaData(NamedMetaNode)) {
  2607. StringRef name = NamedMetaNode.getName();
  2608. if (!name.startswith_lower("llvm."))
  2609. ValCtx.EmitFormatError(ValidationRule::MetaKnown, {name.str()});
  2610. else {
  2611. if (llvmNamedMeta.count(name) == 0) {
  2612. ValCtx.EmitFormatError(ValidationRule::MetaKnown,
  2613. {name.str()});
  2614. }
  2615. }
  2616. }
  2617. }
  2618. const hlsl::ShaderModel *SM = ValCtx.DxilMod.GetShaderModel();
  2619. if (!SM->IsValidForDxil()) {
  2620. ValCtx.EmitFormatError(ValidationRule::SmName,
  2621. {ValCtx.DxilMod.GetShaderModel()->GetName()});
  2622. }
  2623. if (SM->GetMajor() == 6) {
  2624. // Make sure DxilVersion matches the shader model.
  2625. unsigned SMDxilMajor, SMDxilMinor;
  2626. SM->GetDxilVersion(SMDxilMajor, SMDxilMinor);
  2627. if (ValCtx.m_DxilMajor != SMDxilMajor || ValCtx.m_DxilMinor != SMDxilMinor) {
  2628. ValCtx.EmitFormatError(ValidationRule::SmDxilVersion,
  2629. {std::to_string(SMDxilMajor),
  2630. std::to_string(SMDxilMinor)});
  2631. }
  2632. }
  2633. ValidateDxilVersion(ValCtx);
  2634. ValidateValidatorVersion(ValCtx);
  2635. ValidateTypeAnnotation(ValCtx);
  2636. }
  2637. static void ValidateResourceOverlap(
  2638. hlsl::DxilResourceBase &res,
  2639. SpacesAllocator<unsigned, DxilResourceBase> &spaceAllocator,
  2640. ValidationContext &ValCtx) {
  2641. unsigned base = res.GetLowerBound();
  2642. unsigned size = res.GetRangeSize();
  2643. unsigned space = res.GetSpaceID();
  2644. auto &allocator = spaceAllocator.Get(space);
  2645. unsigned end = base + size - 1;
  2646. // unbounded
  2647. if (end < base)
  2648. end = size;
  2649. const DxilResourceBase *conflictRes = allocator.Insert(&res, base, end);
  2650. if (conflictRes) {
  2651. ValCtx.EmitFormatError(
  2652. ValidationRule::SmResourceRangeOverlap,
  2653. {res.GetGlobalName(), std::to_string(base),
  2654. std::to_string(size),
  2655. std::to_string(conflictRes->GetLowerBound()),
  2656. std::to_string(conflictRes->GetRangeSize()),
  2657. std::to_string(space)});
  2658. }
  2659. }
  2660. static void ValidateResource(hlsl::DxilResource &res,
  2661. ValidationContext &ValCtx) {
  2662. switch (res.GetKind()) {
  2663. case DXIL::ResourceKind::RawBuffer:
  2664. case DXIL::ResourceKind::TypedBuffer:
  2665. case DXIL::ResourceKind::TBuffer:
  2666. case DXIL::ResourceKind::StructuredBuffer:
  2667. case DXIL::ResourceKind::Texture1D:
  2668. case DXIL::ResourceKind::Texture1DArray:
  2669. case DXIL::ResourceKind::Texture2D:
  2670. case DXIL::ResourceKind::Texture2DArray:
  2671. case DXIL::ResourceKind::Texture3D:
  2672. case DXIL::ResourceKind::TextureCube:
  2673. case DXIL::ResourceKind::TextureCubeArray:
  2674. if (res.GetSampleCount() > 0) {
  2675. ValCtx.EmitResourceError(&res, ValidationRule::SmSampleCountOnlyOn2DMS);
  2676. }
  2677. break;
  2678. case DXIL::ResourceKind::Texture2DMS:
  2679. case DXIL::ResourceKind::Texture2DMSArray:
  2680. break;
  2681. default:
  2682. ValCtx.EmitResourceError(&res, ValidationRule::SmInvalidResourceKind);
  2683. break;
  2684. }
  2685. switch (res.GetCompType().GetKind()) {
  2686. case DXIL::ComponentType::F32:
  2687. case DXIL::ComponentType::SNormF32:
  2688. case DXIL::ComponentType::UNormF32:
  2689. case DXIL::ComponentType::F64:
  2690. case DXIL::ComponentType::I32:
  2691. case DXIL::ComponentType::I64:
  2692. case DXIL::ComponentType::U32:
  2693. case DXIL::ComponentType::U64:
  2694. case DXIL::ComponentType::F16:
  2695. case DXIL::ComponentType::I16:
  2696. case DXIL::ComponentType::U16:
  2697. break;
  2698. default:
  2699. if (!res.IsStructuredBuffer() && !res.IsRawBuffer())
  2700. ValCtx.EmitResourceError(&res, ValidationRule::SmInvalidResourceCompType);
  2701. break;
  2702. }
  2703. if (res.IsStructuredBuffer()) {
  2704. unsigned stride = res.GetElementStride();
  2705. bool alignedTo4Bytes = (stride & 3) == 0;
  2706. if (!alignedTo4Bytes) {
  2707. ValCtx.EmitResourceFormatError(
  2708. &res, ValidationRule::MetaStructBufAlignment,
  2709. {std::to_string(4), std::to_string(stride)});
  2710. }
  2711. if (stride > DXIL::kMaxStructBufferStride) {
  2712. ValCtx.EmitResourceFormatError(
  2713. &res, ValidationRule::MetaStructBufAlignmentOutOfBound,
  2714. {std::to_string(DXIL::kMaxStructBufferStride),
  2715. std::to_string(stride)});
  2716. }
  2717. }
  2718. if (res.IsAnyTexture() || res.IsTypedBuffer()) {
  2719. Type *RetTy = res.GetRetType();
  2720. unsigned size = ValCtx.DxilMod.GetModule()->getDataLayout().getTypeAllocSize(RetTy);
  2721. if (size > 4*4) {
  2722. ValCtx.EmitResourceError(&res, ValidationRule::MetaTextureType);
  2723. }
  2724. }
  2725. }
  2726. static void
  2727. CollectCBufferRanges(DxilStructAnnotation *annotation,
  2728. SpanAllocator<unsigned, DxilFieldAnnotation> &constAllocator,
  2729. unsigned base, DxilTypeSystem &typeSys, StringRef cbName,
  2730. ValidationContext &ValCtx) {
  2731. unsigned cbSize = annotation->GetCBufferSize();
  2732. const StructType *ST = annotation->GetStructType();
  2733. for (int i = annotation->GetNumFields() - 1; i >= 0; i--) {
  2734. DxilFieldAnnotation &fieldAnnotation = annotation->GetFieldAnnotation(i);
  2735. Type *EltTy = ST->getElementType(i);
  2736. unsigned offset = fieldAnnotation.GetCBufferOffset();
  2737. unsigned EltSize = dxilutil::GetLegacyCBufferFieldElementSize(
  2738. fieldAnnotation, EltTy, typeSys);
  2739. bool bOutOfBound = false;
  2740. if (!EltTy->isAggregateType()) {
  2741. bOutOfBound = (offset + EltSize) > cbSize;
  2742. if (!bOutOfBound) {
  2743. if (constAllocator.Insert(&fieldAnnotation, base + offset,
  2744. base + offset + EltSize - 1)) {
  2745. ValCtx.EmitFormatError(
  2746. ValidationRule::SmCBufferOffsetOverlap,
  2747. {cbName, std::to_string(base + offset)});
  2748. }
  2749. }
  2750. } else if (isa<ArrayType>(EltTy)) {
  2751. unsigned arrayCount = 1;
  2752. while (isa<ArrayType>(EltTy)) {
  2753. arrayCount *= EltTy->getArrayNumElements();
  2754. EltTy = EltTy->getArrayElementType();
  2755. }
  2756. unsigned arrayBase = base + offset;
  2757. DxilStructAnnotation *EltAnnotation = nullptr;
  2758. if (StructType *EltST = dyn_cast<StructType>(EltTy))
  2759. EltAnnotation = typeSys.GetStructAnnotation(EltST);
  2760. for (unsigned idx = 0; idx < arrayCount; idx++) {
  2761. // 16 bytes align except last component.
  2762. if (idx < (arrayCount - 1)) {
  2763. arrayBase = (arrayBase + 15) & ~(0xf);
  2764. }
  2765. if (arrayBase > (base + cbSize)) {
  2766. bOutOfBound = true;
  2767. break;
  2768. }
  2769. if (!EltAnnotation) {
  2770. if (constAllocator.Insert(&fieldAnnotation, arrayBase,
  2771. arrayBase + EltSize - 1)) {
  2772. ValCtx.EmitFormatError(
  2773. ValidationRule::SmCBufferOffsetOverlap,
  2774. {cbName, std::to_string(base + offset)});
  2775. }
  2776. } else {
  2777. CollectCBufferRanges(EltAnnotation,
  2778. constAllocator, arrayBase, typeSys,
  2779. cbName, ValCtx);
  2780. }
  2781. arrayBase += EltSize;
  2782. }
  2783. } else {
  2784. cast<StructType>(EltTy);
  2785. bOutOfBound = (offset + EltSize) > cbSize;
  2786. }
  2787. if (bOutOfBound) {
  2788. ValCtx.EmitFormatError(ValidationRule::SmCBufferElementOverflow,
  2789. {cbName, std::to_string(base + offset)});
  2790. }
  2791. }
  2792. }
  2793. static void ValidateCBuffer(DxilCBuffer &cb, ValidationContext &ValCtx) {
  2794. Type *Ty = cb.GetGlobalSymbol()->getType()->getPointerElementType();
  2795. if (cb.GetRangeSize() != 1) {
  2796. Ty = Ty->getArrayElementType();
  2797. }
  2798. if (!isa<StructType>(Ty)) {
  2799. ValCtx.EmitResourceError(&cb,
  2800. ValidationRule::SmCBufferTemplateTypeMustBeStruct);
  2801. return;
  2802. }
  2803. StructType *ST = cast<StructType>(Ty);
  2804. DxilTypeSystem &typeSys = ValCtx.DxilMod.GetTypeSystem();
  2805. DxilStructAnnotation *annotation = typeSys.GetStructAnnotation(ST);
  2806. if (!annotation)
  2807. return;
  2808. // Collect constant ranges.
  2809. std::vector<std::pair<unsigned, unsigned>> constRanges;
  2810. SpanAllocator<unsigned, DxilFieldAnnotation> constAllocator(0,
  2811. // 4096 * 16 bytes.
  2812. DXIL::kMaxCBufferSize << 4);
  2813. CollectCBufferRanges(annotation, constAllocator,
  2814. 0, typeSys,
  2815. cb.GetGlobalName(), ValCtx);
  2816. }
  2817. static void ValidateResources(ValidationContext &ValCtx) {
  2818. const vector<unique_ptr<DxilResource>> &uavs = ValCtx.DxilMod.GetUAVs();
  2819. bool hasROV = false;
  2820. SpacesAllocator<unsigned, DxilResourceBase> uavAllocator;
  2821. for (auto &uav : uavs) {
  2822. if (uav->IsROV()) {
  2823. hasROV = true;
  2824. if (!ValCtx.DxilMod.GetShaderModel()->IsPS()) {
  2825. ValCtx.EmitResourceError(uav.get(), ValidationRule::SmROVOnlyInPS);
  2826. }
  2827. }
  2828. switch (uav->GetKind()) {
  2829. case DXIL::ResourceKind::Texture2DMS:
  2830. case DXIL::ResourceKind::Texture2DMSArray:
  2831. case DXIL::ResourceKind::TextureCube:
  2832. case DXIL::ResourceKind::TextureCubeArray:
  2833. ValCtx.EmitResourceError(uav.get(),
  2834. ValidationRule::SmInvalidTextureKindOnUAV);
  2835. break;
  2836. default:
  2837. break;
  2838. }
  2839. if (uav->HasCounter() && !uav->IsStructuredBuffer()) {
  2840. ValCtx.EmitResourceError(uav.get(),
  2841. ValidationRule::SmCounterOnlyOnStructBuf);
  2842. }
  2843. if (uav->HasCounter() && uav->IsGloballyCoherent())
  2844. ValCtx.EmitResourceError(uav.get(),
  2845. ValidationRule::MetaGlcNotOnAppendConsume);
  2846. ValidateResource(*uav, ValCtx);
  2847. ValidateResourceOverlap(*uav, uavAllocator, ValCtx);
  2848. }
  2849. SpacesAllocator<unsigned, DxilResourceBase> srvAllocator;
  2850. const vector<unique_ptr<DxilResource>> &srvs = ValCtx.DxilMod.GetSRVs();
  2851. for (auto &srv : srvs) {
  2852. ValidateResource(*srv, ValCtx);
  2853. ValidateResourceOverlap(*srv, srvAllocator, ValCtx);
  2854. }
  2855. hlsl::DxilResourceBase *pNonDense;
  2856. if (!AreDxilResourcesDense(&ValCtx.M, &pNonDense)) {
  2857. ValCtx.EmitResourceError(pNonDense, ValidationRule::MetaDenseResIDs);
  2858. }
  2859. SpacesAllocator<unsigned, DxilResourceBase> samplerAllocator;
  2860. for (auto &sampler : ValCtx.DxilMod.GetSamplers()) {
  2861. if (sampler->GetSamplerKind() == DXIL::SamplerKind::Invalid) {
  2862. ValCtx.EmitResourceError(sampler.get(),
  2863. ValidationRule::MetaValidSamplerMode);
  2864. }
  2865. ValidateResourceOverlap(*sampler, samplerAllocator, ValCtx);
  2866. }
  2867. SpacesAllocator<unsigned, DxilResourceBase> cbufferAllocator;
  2868. for (auto &cbuffer : ValCtx.DxilMod.GetCBuffers()) {
  2869. ValidateCBuffer(*cbuffer, ValCtx);
  2870. ValidateResourceOverlap(*cbuffer, cbufferAllocator, ValCtx);
  2871. }
  2872. }
  2873. static void ValidateShaderFlags(ValidationContext &ValCtx) {
  2874. DxilModule::ShaderFlags calcFlags;
  2875. ValCtx.DxilMod.CollectShaderFlags(calcFlags);
  2876. const uint64_t mask = DxilModule::ShaderFlags::GetShaderFlagsRawForCollection();
  2877. uint64_t declaredFlagsRaw = ValCtx.DxilMod.m_ShaderFlags.GetShaderFlagsRaw();
  2878. uint64_t calcFlagsRaw = calcFlags.GetShaderFlagsRaw();
  2879. declaredFlagsRaw &= mask;
  2880. calcFlagsRaw &= mask;
  2881. if (declaredFlagsRaw == calcFlagsRaw) {
  2882. return;
  2883. }
  2884. ValCtx.EmitError(ValidationRule::MetaFlagsUsage);
  2885. ValCtx.DiagStream() << "Flags declared=" << declaredFlagsRaw
  2886. << ", actual=" << calcFlagsRaw << "\n";
  2887. }
  2888. static void ValidateSignatureElement(DxilSignatureElement &SE,
  2889. ValidationContext &ValCtx) {
  2890. DXIL::SemanticKind semanticKind = SE.GetSemantic()->GetKind();
  2891. CompType::Kind compKind = SE.GetCompType().GetKind();
  2892. DXIL::InterpolationMode Mode = SE.GetInterpolationMode()->GetKind();
  2893. StringRef Name = SE.GetName();
  2894. if (Name.size() < 1 || Name.size() > 64) {
  2895. ValCtx.EmitSignatureError(&SE, ValidationRule::MetaSemanticLen);
  2896. }
  2897. if (semanticKind > DXIL::SemanticKind::Arbitrary && semanticKind < DXIL::SemanticKind::Invalid) {
  2898. if (semanticKind != Semantic::GetByName(SE.GetName())->GetKind()) {
  2899. ValCtx.EmitFormatError(ValidationRule::MetaSemaKindMatchesName,
  2900. {SE.GetName(), SE.GetSemantic()->GetName()});
  2901. }
  2902. }
  2903. unsigned compWidth = 0;
  2904. bool compFloat = false;
  2905. bool compInt = false;
  2906. bool compUnsigned = false;
  2907. bool compBool = false;
  2908. bool compSNorm = false;
  2909. bool compUNorm = false;
  2910. switch (compKind) {
  2911. case CompType::Kind::U64: compWidth = 64; compInt = true; compUnsigned = true; break;
  2912. case CompType::Kind::I64: compWidth = 64; compInt = true; break;
  2913. case CompType::Kind::U32: compWidth = 32; compInt = true; compUnsigned = true; break;
  2914. case CompType::Kind::I32: compWidth = 32; compInt = true; break;
  2915. case CompType::Kind::U16: compWidth = 16; compInt = true; compUnsigned = true; break;
  2916. case CompType::Kind::I16: compWidth = 16; compInt = true; break;
  2917. case CompType::Kind::I1: compWidth = 1; compBool = true; break;
  2918. case CompType::Kind::F64: compWidth = 64; compFloat = true; break;
  2919. case CompType::Kind::F32: compWidth = 32; compFloat = true; break;
  2920. case CompType::Kind::F16: compWidth = 16; compFloat = true; break;
  2921. case CompType::Kind::SNormF64: compWidth = 64; compFloat = true; compSNorm = true; break;
  2922. case CompType::Kind::SNormF32: compWidth = 32; compFloat = true; compSNorm = true; break;
  2923. case CompType::Kind::SNormF16: compWidth = 16; compFloat = true; compSNorm = true; break;
  2924. case CompType::Kind::UNormF64: compWidth = 64; compFloat = true; compUNorm = true; break;
  2925. case CompType::Kind::UNormF32: compWidth = 32; compFloat = true; compUNorm = true; break;
  2926. case CompType::Kind::UNormF16: compWidth = 16; compFloat = true; compUNorm = true; break;
  2927. case CompType::Kind::Invalid:
  2928. default:
  2929. ValCtx.EmitFormatError(ValidationRule::MetaSignatureCompType, { SE.GetName() });
  2930. break;
  2931. }
  2932. if (compInt || compBool) {
  2933. switch (Mode) {
  2934. case DXIL::InterpolationMode::Linear:
  2935. case DXIL::InterpolationMode::LinearCentroid:
  2936. case DXIL::InterpolationMode::LinearNoperspective:
  2937. case DXIL::InterpolationMode::LinearNoperspectiveCentroid:
  2938. case DXIL::InterpolationMode::LinearSample:
  2939. case DXIL::InterpolationMode::LinearNoperspectiveSample: {
  2940. ValCtx.EmitFormatError(ValidationRule::MetaIntegerInterpMode, {SE.GetName()});
  2941. } break;
  2942. default:
  2943. break;
  2944. }
  2945. }
  2946. // Elements that should not appear in the Dxil signature:
  2947. bool bAllowedInSig = true;
  2948. bool bShouldBeAllocated = true;
  2949. switch (SE.GetInterpretation()) {
  2950. case DXIL::SemanticInterpretationKind::NA:
  2951. case DXIL::SemanticInterpretationKind::NotInSig:
  2952. case DXIL::SemanticInterpretationKind::Invalid:
  2953. bAllowedInSig = false;
  2954. __fallthrough;
  2955. case DXIL::SemanticInterpretationKind::NotPacked:
  2956. case DXIL::SemanticInterpretationKind::Shadow:
  2957. bShouldBeAllocated = false;
  2958. break;
  2959. default:
  2960. break;
  2961. }
  2962. const char *inputOutput = nullptr;
  2963. if (SE.IsInput())
  2964. inputOutput = "Input";
  2965. else if (SE.IsOutput())
  2966. inputOutput = "Output";
  2967. else
  2968. inputOutput = "PatchConstant";
  2969. if (!bAllowedInSig) {
  2970. ValCtx.EmitFormatError(
  2971. ValidationRule::SmSemantic,
  2972. {SE.GetName(), ValCtx.DxilMod.GetShaderModel()->GetKindName(), inputOutput});
  2973. } else if (bShouldBeAllocated && !SE.IsAllocated()) {
  2974. ValCtx.EmitFormatError(ValidationRule::MetaSemanticShouldBeAllocated,
  2975. {inputOutput, SE.GetName()});
  2976. } else if (!bShouldBeAllocated && SE.IsAllocated()) {
  2977. ValCtx.EmitFormatError(ValidationRule::MetaSemanticShouldNotBeAllocated,
  2978. {inputOutput, SE.GetName()});
  2979. }
  2980. bool bIsClipCull = false;
  2981. bool bIsTessfactor = false;
  2982. bool bIsBarycentric = false;
  2983. switch (semanticKind) {
  2984. case DXIL::SemanticKind::Depth:
  2985. case DXIL::SemanticKind::DepthGreaterEqual:
  2986. case DXIL::SemanticKind::DepthLessEqual:
  2987. if (!compFloat || compWidth > 32 || SE.GetCols() != 1) {
  2988. ValCtx.EmitFormatError(ValidationRule::MetaSemanticCompType,
  2989. {SE.GetSemantic()->GetName(), "float"});
  2990. }
  2991. break;
  2992. case DXIL::SemanticKind::Coverage:
  2993. DXASSERT(!SE.IsInput() || !bAllowedInSig, "else internal inconsistency between semantic interpretation table and validation code");
  2994. __fallthrough;
  2995. case DXIL::SemanticKind::InnerCoverage:
  2996. case DXIL::SemanticKind::OutputControlPointID:
  2997. if (compKind != CompType::Kind::U32 || SE.GetCols() != 1) {
  2998. ValCtx.EmitFormatError(ValidationRule::MetaSemanticCompType,
  2999. {SE.GetSemantic()->GetName(), "uint"});
  3000. }
  3001. break;
  3002. case DXIL::SemanticKind::Position:
  3003. if (!compFloat || compWidth > 32 || SE.GetCols() != 4) {
  3004. ValCtx.EmitFormatError(ValidationRule::MetaSemanticCompType,
  3005. {SE.GetSemantic()->GetName(), "float4"});
  3006. }
  3007. break;
  3008. case DXIL::SemanticKind::Target:
  3009. if (compWidth > 32) {
  3010. ValCtx.EmitFormatError(ValidationRule::MetaSemanticCompType,
  3011. {SE.GetSemantic()->GetName(), "float/int/uint"});
  3012. }
  3013. break;
  3014. case DXIL::SemanticKind::ClipDistance:
  3015. case DXIL::SemanticKind::CullDistance:
  3016. bIsClipCull = true;
  3017. if (!compFloat || compWidth > 32) {
  3018. ValCtx.EmitFormatError(ValidationRule::MetaSemanticCompType,
  3019. {SE.GetSemantic()->GetName(), "float"});
  3020. }
  3021. // NOTE: clip cull distance size is checked at ValidateSignature.
  3022. break;
  3023. case DXIL::SemanticKind::IsFrontFace:
  3024. if (!compBool || SE.GetCols() != 1) {
  3025. ValCtx.EmitFormatError(ValidationRule::MetaSemanticCompType,
  3026. {SE.GetSemantic()->GetName(), "bool"});
  3027. }
  3028. break;
  3029. case DXIL::SemanticKind::RenderTargetArrayIndex:
  3030. case DXIL::SemanticKind::ViewPortArrayIndex:
  3031. case DXIL::SemanticKind::VertexID:
  3032. case DXIL::SemanticKind::PrimitiveID:
  3033. case DXIL::SemanticKind::InstanceID:
  3034. case DXIL::SemanticKind::GSInstanceID:
  3035. case DXIL::SemanticKind::SampleIndex:
  3036. case DXIL::SemanticKind::StencilRef:
  3037. if ((compKind != CompType::Kind::U32 && compKind != CompType::Kind::U16) || SE.GetCols() != 1) {
  3038. ValCtx.EmitFormatError(ValidationRule::MetaSemanticCompType,
  3039. {SE.GetSemantic()->GetName(), "uint"});
  3040. }
  3041. break;
  3042. case DXIL::SemanticKind::TessFactor:
  3043. case DXIL::SemanticKind::InsideTessFactor:
  3044. // NOTE: the size check is at CheckPatchConstantSemantic.
  3045. bIsTessfactor = true;
  3046. if (!compFloat || compWidth > 32) {
  3047. ValCtx.EmitFormatError(ValidationRule::MetaSemanticCompType,
  3048. {SE.GetSemantic()->GetName(), "float"});
  3049. }
  3050. break;
  3051. case DXIL::SemanticKind::Arbitrary:
  3052. break;
  3053. case DXIL::SemanticKind::DomainLocation:
  3054. case DXIL::SemanticKind::Invalid:
  3055. DXASSERT(!bAllowedInSig, "else internal inconsistency between semantic interpretation table and validation code");
  3056. break;
  3057. case DXIL::SemanticKind::Barycentrics:
  3058. bIsBarycentric = true;
  3059. if (!compFloat || compWidth > 32) {
  3060. ValCtx.EmitFormatError(ValidationRule::MetaSemanticCompType, {SE.GetSemantic()->GetName(), "float"});
  3061. }
  3062. if (Mode != InterpolationMode::Kind::Linear &&
  3063. Mode != InterpolationMode::Kind::LinearCentroid &&
  3064. Mode != InterpolationMode::Kind::LinearNoperspective &&
  3065. Mode != InterpolationMode::Kind::LinearNoperspectiveCentroid &&
  3066. Mode != InterpolationMode::Kind::LinearNoperspectiveSample &&
  3067. Mode != InterpolationMode::Kind::LinearSample) {
  3068. ValCtx.EmitSignatureError(&SE, ValidationRule::MetaBarycentricsInterpolation);
  3069. }
  3070. if (SE.GetCols() != 3) {
  3071. ValCtx.EmitSignatureError(&SE, ValidationRule::MetaBarycentricsFloat3);
  3072. }
  3073. break;
  3074. default:
  3075. ValCtx.EmitSignatureError(&SE, ValidationRule::MetaSemaKindValid);
  3076. break;
  3077. }
  3078. if (ValCtx.DxilMod.GetShaderModel()->IsGS() && SE.IsOutput()) {
  3079. if (SE.GetOutputStream() >= DXIL::kNumOutputStreams) {
  3080. ValCtx.EmitFormatError(ValidationRule::SmStreamIndexRange,
  3081. {std::to_string(SE.GetOutputStream()),
  3082. std::to_string(DXIL::kNumOutputStreams - 1)});
  3083. }
  3084. } else {
  3085. if (SE.GetOutputStream() > 0) {
  3086. ValCtx.EmitFormatError(ValidationRule::SmStreamIndexRange,
  3087. {std::to_string(SE.GetOutputStream()),
  3088. "0"});
  3089. }
  3090. }
  3091. if (ValCtx.DxilMod.GetShaderModel()->IsGS()) {
  3092. if (SE.GetOutputStream() != 0) {
  3093. if (ValCtx.DxilMod.GetStreamPrimitiveTopology() !=
  3094. DXIL::PrimitiveTopology::PointList) {
  3095. ValCtx.EmitSignatureError(&SE,
  3096. ValidationRule::SmMultiStreamMustBePoint);
  3097. }
  3098. }
  3099. }
  3100. if (semanticKind == DXIL::SemanticKind::Target) {
  3101. // Verify packed row == semantic index
  3102. unsigned row = SE.GetStartRow();
  3103. for (unsigned i : SE.GetSemanticIndexVec()) {
  3104. if (row != i) {
  3105. ValCtx.EmitSignatureError(&SE, ValidationRule::SmPSTargetIndexMatchesRow);
  3106. }
  3107. ++row;
  3108. }
  3109. // Verify packed col is 0
  3110. if (SE.GetStartCol() != 0) {
  3111. ValCtx.EmitSignatureError(&SE, ValidationRule::SmPSTargetCol0);
  3112. }
  3113. // Verify max row used < 8
  3114. if (SE.GetStartRow() + SE.GetRows() > 8) {
  3115. ValCtx.EmitFormatError(ValidationRule::MetaSemanticIndexMax, {"SV_Target", "7"});
  3116. }
  3117. } else if (bAllowedInSig && semanticKind != DXIL::SemanticKind::Arbitrary) {
  3118. if (bIsBarycentric) {
  3119. if (SE.GetSemanticStartIndex() > 1) {
  3120. ValCtx.EmitFormatError(ValidationRule::MetaSemanticIndexMax, { SE.GetSemantic()->GetName(), "1" });
  3121. }
  3122. }
  3123. else if (!bIsClipCull && SE.GetSemanticStartIndex() > 0) {
  3124. ValCtx.EmitFormatError(ValidationRule::MetaSemanticIndexMax, {SE.GetSemantic()->GetName(), "0"});
  3125. }
  3126. // Maximum rows is 1 for system values other than Target
  3127. // with the exception of tessfactors, which are validated in CheckPatchConstantSemantic
  3128. if (!bIsTessfactor && SE.GetRows() > 1) {
  3129. ValCtx.EmitSignatureError(&SE, ValidationRule::MetaSystemValueRows);
  3130. }
  3131. }
  3132. if (SE.GetCols() + (SE.IsAllocated() ? SE.GetStartCol() : 0) > 4) {
  3133. unsigned size = (SE.GetRows() - 1) * 4 + SE.GetCols();
  3134. ValCtx.EmitFormatError(ValidationRule::MetaSignatureOutOfRange,
  3135. {SE.GetName(),
  3136. std::to_string(SE.GetStartRow()),
  3137. std::to_string(SE.GetStartCol()),
  3138. std::to_string(size)});
  3139. }
  3140. if (!SE.GetInterpolationMode()->IsValid()) {
  3141. ValCtx.EmitSignatureError(&SE, ValidationRule::MetaInterpModeValid);
  3142. }
  3143. }
  3144. static void ValidateSignatureOverlap(
  3145. DxilSignatureElement &E, unsigned maxScalars,
  3146. DxilSignatureAllocator &allocator,
  3147. ValidationContext &ValCtx) {
  3148. // Skip entries that are not or should not be allocated. Validation occurs in ValidateSignatureElement.
  3149. if (!E.IsAllocated())
  3150. return;
  3151. switch (E.GetInterpretation()) {
  3152. case DXIL::SemanticInterpretationKind::NA:
  3153. case DXIL::SemanticInterpretationKind::NotInSig:
  3154. case DXIL::SemanticInterpretationKind::Invalid:
  3155. case DXIL::SemanticInterpretationKind::NotPacked:
  3156. case DXIL::SemanticInterpretationKind::Shadow:
  3157. return;
  3158. default:
  3159. break;
  3160. }
  3161. DxilPackElement PE(&E);
  3162. DxilSignatureAllocator::ConflictType conflict = allocator.DetectRowConflict(&PE, E.GetStartRow());
  3163. if (conflict == DxilSignatureAllocator::kNoConflict || conflict == DxilSignatureAllocator::kInsufficientFreeComponents)
  3164. conflict = allocator.DetectColConflict(&PE, E.GetStartRow(), E.GetStartCol());
  3165. switch (conflict) {
  3166. case DxilSignatureAllocator::kNoConflict:
  3167. allocator.PlaceElement(&PE, E.GetStartRow(), E.GetStartCol());
  3168. break;
  3169. case DxilSignatureAllocator::kConflictsWithIndexed:
  3170. ValCtx.EmitFormatError(ValidationRule::MetaSignatureIndexConflict,
  3171. {E.GetName(),
  3172. std::to_string(E.GetStartRow()),
  3173. std::to_string(E.GetStartCol()),
  3174. std::to_string(E.GetRows()),
  3175. std::to_string(E.GetCols())});
  3176. break;
  3177. case DxilSignatureAllocator::kConflictsWithIndexedTessFactor:
  3178. ValCtx.EmitFormatError(ValidationRule::MetaSignatureIndexConflict,
  3179. {E.GetName(),
  3180. std::to_string(E.GetStartRow()),
  3181. std::to_string(E.GetStartCol()),
  3182. std::to_string(E.GetRows()),
  3183. std::to_string(E.GetCols())});
  3184. break;
  3185. case DxilSignatureAllocator::kConflictsWithInterpolationMode:
  3186. ValCtx.EmitFormatError(ValidationRule::MetaInterpModeInOneRow,
  3187. {E.GetName(),
  3188. std::to_string(E.GetStartRow()),
  3189. std::to_string(E.GetStartCol()),
  3190. std::to_string(E.GetRows()),
  3191. std::to_string(E.GetCols())});
  3192. break;
  3193. case DxilSignatureAllocator::kInsufficientFreeComponents:
  3194. DXASSERT(false, "otherwise, conflict not translated");
  3195. break;
  3196. case DxilSignatureAllocator::kOverlapElement:
  3197. ValCtx.EmitFormatError(ValidationRule::MetaSignatureOverlap,
  3198. {E.GetName(),
  3199. std::to_string(E.GetStartRow()),
  3200. std::to_string(E.GetStartCol()),
  3201. std::to_string(E.GetRows()),
  3202. std::to_string(E.GetCols())});
  3203. break;
  3204. case DxilSignatureAllocator::kIllegalComponentOrder:
  3205. ValCtx.EmitFormatError(ValidationRule::MetaSignatureIllegalComponentOrder,
  3206. {E.GetName(),
  3207. std::to_string(E.GetStartRow()),
  3208. std::to_string(E.GetStartCol()),
  3209. std::to_string(E.GetRows()),
  3210. std::to_string(E.GetCols())});
  3211. break;
  3212. case DxilSignatureAllocator::kConflictFit:
  3213. ValCtx.EmitFormatError(ValidationRule::MetaSignatureOutOfRange,
  3214. {E.GetName(),
  3215. std::to_string(E.GetStartRow()),
  3216. std::to_string(E.GetStartCol()),
  3217. std::to_string(E.GetRows()),
  3218. std::to_string(E.GetCols())});
  3219. break;
  3220. default:
  3221. DXASSERT(false, "otherwise, unrecognized conflict type from DxilSignatureAllocator");
  3222. }
  3223. }
  3224. static void ValidateSignature(ValidationContext &ValCtx, const DxilSignature &S,
  3225. unsigned maxScalars) {
  3226. DxilSignatureAllocator allocator[DXIL::kNumOutputStreams] = {32, 32, 32, 32};
  3227. unordered_set<Semantic::Kind> semanticUsageSet[DXIL::kNumOutputStreams];
  3228. StringMap<unordered_set<unsigned>> semanticIndexMap[DXIL::kNumOutputStreams];
  3229. unordered_set<unsigned> clipcullRowSet[DXIL::kNumOutputStreams];
  3230. unsigned clipcullComponents[DXIL::kNumOutputStreams] = {0, 0, 0, 0};
  3231. bool isOutput = S.IsOutput();
  3232. unsigned TargetMask = 0;
  3233. DXIL::SemanticKind DepthKind = DXIL::SemanticKind::Invalid;
  3234. const InterpolationMode *prevBaryInterpMode = nullptr;
  3235. unsigned numBarycentrics = 0;
  3236. for (auto &E : S.GetElements()) {
  3237. DXIL::SemanticKind semanticKind = E->GetSemantic()->GetKind();
  3238. ValidateSignatureElement(*E, ValCtx);
  3239. // Avoid OOB indexing on streamId.
  3240. unsigned streamId = E->GetOutputStream();
  3241. if (streamId >= DXIL::kNumOutputStreams ||
  3242. !isOutput ||
  3243. !ValCtx.DxilMod.GetShaderModel()->IsGS()) {
  3244. streamId = 0;
  3245. }
  3246. // Semantic index overlap check, keyed by name.
  3247. std::string nameUpper(E->GetName());
  3248. std::transform(nameUpper.begin(), nameUpper.end(), nameUpper.begin(), toupper);
  3249. unordered_set<unsigned> &semIdxSet = semanticIndexMap[streamId][nameUpper];
  3250. for (unsigned semIdx : E->GetSemanticIndexVec()) {
  3251. if (semIdxSet.count(semIdx) > 0) {
  3252. ValCtx.EmitFormatError(ValidationRule::MetaNoSemanticOverlap,
  3253. {E->GetName(), std::to_string(semIdx)});
  3254. return;
  3255. } else
  3256. semIdxSet.insert(semIdx);
  3257. }
  3258. // SV_Target has special rules
  3259. if (semanticKind == DXIL::SemanticKind::Target) {
  3260. // Validate target overlap
  3261. if (E->GetStartRow() + E->GetRows() <= 8) {
  3262. unsigned mask = ((1 << E->GetRows()) - 1) << E->GetStartRow();
  3263. if (TargetMask & mask) {
  3264. ValCtx.EmitFormatError(ValidationRule::MetaNoSemanticOverlap,
  3265. {"SV_Target", std::to_string(E->GetStartRow())});
  3266. }
  3267. TargetMask = TargetMask | mask;
  3268. }
  3269. if (E->GetRows() > 1) {
  3270. ValCtx.EmitError(ValidationRule::SmNoPSOutputIdx);
  3271. }
  3272. continue;
  3273. }
  3274. if (E->GetSemantic()->IsInvalid())
  3275. continue;
  3276. // validate system value semantic rules
  3277. switch (semanticKind) {
  3278. case DXIL::SemanticKind::Arbitrary:
  3279. break;
  3280. case DXIL::SemanticKind::ClipDistance:
  3281. case DXIL::SemanticKind::CullDistance:
  3282. // Validate max 8 components across 2 rows (registers)
  3283. clipcullRowSet[streamId].insert(E->GetStartRow());
  3284. if (clipcullRowSet[streamId].size() > 2) {
  3285. ValCtx.EmitError(ValidationRule::MetaClipCullMaxRows);
  3286. }
  3287. clipcullComponents[streamId] += E->GetCols();
  3288. if (clipcullComponents[streamId] > 8) {
  3289. ValCtx.EmitError(ValidationRule::MetaClipCullMaxComponents);
  3290. }
  3291. break;
  3292. case DXIL::SemanticKind::Depth:
  3293. case DXIL::SemanticKind::DepthGreaterEqual:
  3294. case DXIL::SemanticKind::DepthLessEqual:
  3295. if (DepthKind != DXIL::SemanticKind::Invalid) {
  3296. ValCtx.EmitError(ValidationRule::SmPSMultipleDepthSemantic);
  3297. }
  3298. DepthKind = semanticKind;
  3299. break;
  3300. case DXIL::SemanticKind::Barycentrics: {
  3301. // There can only be up to two SV_Barycentrics
  3302. // with differeent perspective interpolation modes.
  3303. if (numBarycentrics++ > 1) {
  3304. ValCtx.EmitError(ValidationRule::MetaBarycentricsTwoPerspectives);
  3305. break;
  3306. }
  3307. const InterpolationMode *mode = E->GetInterpolationMode();
  3308. if (prevBaryInterpMode) {
  3309. if ((mode->IsAnyNoPerspective() && prevBaryInterpMode->IsAnyNoPerspective())
  3310. || (!mode->IsAnyNoPerspective() && !prevBaryInterpMode->IsAnyNoPerspective())) {
  3311. ValCtx.EmitError(ValidationRule::MetaBarycentricsTwoPerspectives);
  3312. }
  3313. }
  3314. prevBaryInterpMode = mode;
  3315. break;
  3316. }
  3317. default:
  3318. if (semanticUsageSet[streamId].count(semanticKind) > 0) {
  3319. ValCtx.EmitFormatError(ValidationRule::MetaDuplicateSysValue,
  3320. {E->GetSemantic()->GetName()});
  3321. }
  3322. semanticUsageSet[streamId].insert(semanticKind);
  3323. break;
  3324. }
  3325. // Packed element overlap check.
  3326. ValidateSignatureOverlap(*E.get(), maxScalars, allocator[streamId], ValCtx);
  3327. if (isOutput && semanticKind == DXIL::SemanticKind::Position) {
  3328. ValCtx.hasOutputPosition[E->GetOutputStream()] = true;
  3329. }
  3330. }
  3331. if (ValCtx.hasViewID && S.IsInput() && ValCtx.DxilMod.GetShaderModel()->GetKind() == DXIL::ShaderKind::Pixel) {
  3332. // Ensure sufficient space for ViewID:
  3333. DxilSignatureAllocator::DummyElement viewID;
  3334. viewID.rows = 1;
  3335. viewID.cols = 1;
  3336. viewID.kind = DXIL::SemanticKind::Arbitrary;
  3337. viewID.interpolation = DXIL::InterpolationMode::Constant;
  3338. viewID.interpretation = DXIL::SemanticInterpretationKind::SGV;
  3339. allocator[0].PackNext(&viewID, 0, 32);
  3340. if (!viewID.IsAllocated()) {
  3341. ValCtx.EmitError(ValidationRule::SmViewIDNeedsSlot);
  3342. }
  3343. }
  3344. }
  3345. static void ValidateNoInterpModeSignature(ValidationContext &ValCtx, const DxilSignature &S) {
  3346. for (auto &E : S.GetElements()) {
  3347. if (!E->GetInterpolationMode()->IsUndefined()) {
  3348. ValCtx.EmitSignatureError(E.get(), ValidationRule::SmNoInterpMode);
  3349. }
  3350. }
  3351. }
  3352. static void ValidateSignatures(ValidationContext &ValCtx) {
  3353. DxilModule &M = ValCtx.DxilMod;
  3354. bool isPS = M.GetShaderModel()->IsPS();
  3355. bool isVS = M.GetShaderModel()->IsVS();
  3356. bool isGS = M.GetShaderModel()->IsGS();
  3357. bool isCS = M.GetShaderModel()->IsCS();
  3358. if (isPS) {
  3359. // PS output no interp mode.
  3360. ValidateNoInterpModeSignature(ValCtx, ValCtx.DxilMod.GetOutputSignature());
  3361. } else if (isVS) {
  3362. // VS input no interp mode.
  3363. ValidateNoInterpModeSignature(ValCtx, ValCtx.DxilMod.GetInputSignature());
  3364. }
  3365. // patch constant no interp mode.
  3366. ValidateNoInterpModeSignature(ValCtx, ValCtx.DxilMod.GetPatchConstantSignature());
  3367. unsigned maxInputScalars = DXIL::kMaxInputTotalScalars;
  3368. unsigned maxOutputScalars = 0;
  3369. unsigned maxPatchConstantScalars = 0;
  3370. switch (M.GetShaderModel()->GetKind()) {
  3371. case DXIL::ShaderKind::Compute:
  3372. break;
  3373. case DXIL::ShaderKind::Vertex:
  3374. case DXIL::ShaderKind::Geometry:
  3375. case DXIL::ShaderKind::Pixel:
  3376. maxOutputScalars = DXIL::kMaxOutputTotalScalars;
  3377. break;
  3378. case DXIL::ShaderKind::Hull:
  3379. case DXIL::ShaderKind::Domain:
  3380. maxOutputScalars = DXIL::kMaxOutputTotalScalars;
  3381. maxPatchConstantScalars = DXIL::kMaxHSOutputPatchConstantTotalScalars;
  3382. break;
  3383. default:
  3384. break;
  3385. }
  3386. ValidateSignature(ValCtx, ValCtx.DxilMod.GetInputSignature(), maxInputScalars);
  3387. ValidateSignature(ValCtx, ValCtx.DxilMod.GetOutputSignature(), maxOutputScalars);
  3388. ValidateSignature(ValCtx, ValCtx.DxilMod.GetPatchConstantSignature(), maxPatchConstantScalars);
  3389. if (isPS) {
  3390. // Gather execution information.
  3391. hlsl::PSExecutionInfo &PSExec = ValCtx.PSExec;
  3392. for (auto &E : ValCtx.DxilMod.GetInputSignature().GetElements()) {
  3393. if (E->GetKind() == DXIL::SemanticKind::SampleIndex) {
  3394. PSExec.SuperSampling = true;
  3395. continue;
  3396. }
  3397. const InterpolationMode *IM = E->GetInterpolationMode();
  3398. if (IM->IsLinearSample() || IM->IsLinearNoperspectiveSample()) {
  3399. PSExec.SuperSampling = true;
  3400. }
  3401. if (E->GetKind() == DXIL::SemanticKind::Position) {
  3402. PSExec.PositionInterpolationMode = IM;
  3403. }
  3404. }
  3405. for (auto &E : ValCtx.DxilMod.GetOutputSignature().GetElements()) {
  3406. if (E->IsAnyDepth()) {
  3407. PSExec.OutputDepthKind = E->GetKind();
  3408. break;
  3409. }
  3410. }
  3411. if (!PSExec.SuperSampling &&
  3412. PSExec.OutputDepthKind != DXIL::SemanticKind::Invalid &&
  3413. PSExec.OutputDepthKind != DXIL::SemanticKind::Depth) {
  3414. if (PSExec.PositionInterpolationMode != nullptr) {
  3415. if (!PSExec.PositionInterpolationMode->IsUndefined() &&
  3416. !PSExec.PositionInterpolationMode->IsLinearNoperspectiveCentroid() &&
  3417. !PSExec.PositionInterpolationMode->IsLinearNoperspectiveSample()) {
  3418. ValCtx.EmitError(ValidationRule::SmPSConsistentInterp);
  3419. }
  3420. }
  3421. }
  3422. // Validate PS output semantic.
  3423. DxilSignature &outputSig = M.GetOutputSignature();
  3424. for (auto &SE : outputSig.GetElements()) {
  3425. Semantic::Kind semanticKind = SE->GetSemantic()->GetKind();
  3426. switch (semanticKind) {
  3427. case Semantic::Kind::Target:
  3428. case Semantic::Kind::Coverage:
  3429. case Semantic::Kind::Depth:
  3430. case Semantic::Kind::DepthGreaterEqual:
  3431. case Semantic::Kind::DepthLessEqual:
  3432. case Semantic::Kind::StencilRef:
  3433. break;
  3434. default: {
  3435. ValCtx.EmitFormatError(ValidationRule::SmPSOutputSemantic, {SE->GetName()});
  3436. } break;
  3437. }
  3438. }
  3439. }
  3440. if (isGS) {
  3441. unsigned maxVertexCount = M.GetMaxVertexCount();
  3442. unsigned outputScalarCount = 0;
  3443. DxilSignature &outSig = ValCtx.DxilMod.GetOutputSignature();
  3444. for (auto &SE : outSig.GetElements()) {
  3445. outputScalarCount += SE->GetRows() * SE->GetCols();
  3446. }
  3447. unsigned totalOutputScalars = maxVertexCount * outputScalarCount;
  3448. if (totalOutputScalars > DXIL::kMaxGSOutputTotalScalars) {
  3449. ValCtx.EmitFormatError(
  3450. ValidationRule::SmGSTotalOutputVertexDataRange,
  3451. {std::to_string(maxVertexCount),
  3452. std::to_string(outputScalarCount),
  3453. std::to_string(totalOutputScalars),
  3454. std::to_string(DXIL::kMaxGSOutputTotalScalars)});
  3455. }
  3456. }
  3457. if (isCS) {
  3458. if (!ValCtx.DxilMod.GetOutputSignature().GetElements().empty() ||
  3459. !ValCtx.DxilMod.GetPatchConstantSignature().GetElements().empty()) {
  3460. ValCtx.EmitError(ValidationRule::SmCSNoReturn);
  3461. }
  3462. }
  3463. }
  3464. static void CheckPatchConstantSemantic(ValidationContext &ValCtx)
  3465. {
  3466. bool isHS = ValCtx.DxilMod.GetShaderModel()->IsHS();
  3467. DXIL::TessellatorDomain domain = ValCtx.DxilMod.GetTessellatorDomain();
  3468. DxilSignature &patchConstantSig = ValCtx.DxilMod.GetPatchConstantSignature();
  3469. const unsigned kQuadEdgeSize = 4;
  3470. const unsigned kQuadInsideSize = 2;
  3471. const unsigned kQuadDomainLocSize = 2;
  3472. const unsigned kTriEdgeSize = 3;
  3473. const unsigned kTriInsideSize = 1;
  3474. const unsigned kTriDomainLocSize = 3;
  3475. const unsigned kIsolineEdgeSize = 2;
  3476. const unsigned kIsolineInsideSize = 0;
  3477. const unsigned kIsolineDomainLocSize = 3;
  3478. const char *domainName = "";
  3479. DXIL::SemanticKind kEdgeSemantic = DXIL::SemanticKind::TessFactor;
  3480. unsigned edgeSize = 0;
  3481. DXIL::SemanticKind kInsideSemantic = DXIL::SemanticKind::InsideTessFactor;
  3482. unsigned insideSize = 0;
  3483. ValCtx.domainLocSize = 0;
  3484. switch (domain) {
  3485. case DXIL::TessellatorDomain::IsoLine:
  3486. domainName = "IsoLine";
  3487. edgeSize = kIsolineEdgeSize;
  3488. insideSize = kIsolineInsideSize;
  3489. ValCtx.domainLocSize = kIsolineDomainLocSize;
  3490. break;
  3491. case DXIL::TessellatorDomain::Tri:
  3492. domainName = "Tri";
  3493. edgeSize = kTriEdgeSize;
  3494. insideSize = kTriInsideSize;
  3495. ValCtx.domainLocSize = kTriDomainLocSize;
  3496. break;
  3497. case DXIL::TessellatorDomain::Quad:
  3498. domainName = "Quad";
  3499. edgeSize = kQuadEdgeSize;
  3500. insideSize = kQuadInsideSize;
  3501. ValCtx.domainLocSize = kQuadDomainLocSize;
  3502. break;
  3503. default:
  3504. // Don't bother with other tests if domain is invalid
  3505. return;
  3506. }
  3507. bool bFoundEdgeSemantic = false;
  3508. bool bFoundInsideSemantic = false;
  3509. for (auto &SE : patchConstantSig.GetElements()) {
  3510. Semantic::Kind kind = SE->GetSemantic()->GetKind();
  3511. if (kind == kEdgeSemantic) {
  3512. bFoundEdgeSemantic = true;
  3513. if (SE->GetRows() != edgeSize || SE->GetCols() > 1) {
  3514. ValCtx.EmitFormatError(ValidationRule::SmTessFactorSizeMatchDomain,
  3515. {std::to_string(SE->GetRows()),
  3516. std::to_string(SE->GetCols()),
  3517. domainName,
  3518. std::to_string(edgeSize)});
  3519. }
  3520. } else if (kind == kInsideSemantic) {
  3521. bFoundInsideSemantic = true;
  3522. if (SE->GetRows() != insideSize || SE->GetCols() > 1) {
  3523. ValCtx.EmitFormatError(ValidationRule::SmInsideTessFactorSizeMatchDomain,
  3524. {std::to_string(SE->GetRows()),
  3525. std::to_string(SE->GetCols()),
  3526. domainName,
  3527. std::to_string(insideSize)});
  3528. }
  3529. }
  3530. }
  3531. if (isHS) {
  3532. if (!bFoundEdgeSemantic) {
  3533. ValCtx.EmitError(ValidationRule::SmTessFactorForDomain);
  3534. }
  3535. if (!bFoundInsideSemantic && domain != DXIL::TessellatorDomain::IsoLine) {
  3536. ValCtx.EmitError(ValidationRule::SmTessFactorForDomain);
  3537. }
  3538. }
  3539. }
  3540. static void ValidateShaderState(ValidationContext &ValCtx) {
  3541. DxilModule &M = ValCtx.DxilMod;
  3542. DXIL::ShaderKind ShaderType = M.GetShaderModel()->GetKind();
  3543. if (ShaderType == DXIL::ShaderKind::Compute) {
  3544. unsigned x = M.m_NumThreads[0];
  3545. unsigned y = M.m_NumThreads[1];
  3546. unsigned z = M.m_NumThreads[2];
  3547. unsigned threadsInGroup = x * y * z;
  3548. if ((x < DXIL::kMinCSThreadGroupX) || (x > DXIL::kMaxCSThreadGroupX)) {
  3549. ValCtx.EmitFormatError(
  3550. ValidationRule::SmThreadGroupChannelRange,
  3551. {"X", std::to_string(x),
  3552. std::to_string(DXIL::kMinCSThreadGroupX),
  3553. std::to_string(DXIL::kMaxCSThreadGroupX)});
  3554. }
  3555. if ((y < DXIL::kMinCSThreadGroupY) || (y > DXIL::kMaxCSThreadGroupY)) {
  3556. ValCtx.EmitFormatError(
  3557. ValidationRule::SmThreadGroupChannelRange,
  3558. {"Y", std::to_string(y),
  3559. std::to_string(DXIL::kMinCSThreadGroupY),
  3560. std::to_string(DXIL::kMaxCSThreadGroupY)});
  3561. }
  3562. if ((z < DXIL::kMinCSThreadGroupZ) || (z > DXIL::kMaxCSThreadGroupZ)) {
  3563. ValCtx.EmitFormatError(
  3564. ValidationRule::SmThreadGroupChannelRange,
  3565. {"Z", std::to_string(z),
  3566. std::to_string(DXIL::kMinCSThreadGroupZ),
  3567. std::to_string(DXIL::kMaxCSThreadGroupZ)});
  3568. }
  3569. if (threadsInGroup > DXIL::kMaxCSThreadsPerGroup) {
  3570. ValCtx.EmitFormatError(
  3571. ValidationRule::SmMaxTheadGroup,
  3572. {std::to_string(threadsInGroup),
  3573. std::to_string(DXIL::kMaxCSThreadsPerGroup)});
  3574. }
  3575. // type of threadID, thread group ID take care by DXIL operation overload
  3576. // check.
  3577. } else if (ShaderType == DXIL::ShaderKind::Domain) {
  3578. DXIL::TessellatorDomain domain = M.GetTessellatorDomain();
  3579. if (domain >= DXIL::TessellatorDomain::LastEntry)
  3580. domain = DXIL::TessellatorDomain::Undefined;
  3581. unsigned inputControlPointCount = M.GetInputControlPointCount();
  3582. if (inputControlPointCount > DXIL::kMaxIAPatchControlPointCount) {
  3583. ValCtx.EmitFormatError(
  3584. ValidationRule::SmDSInputControlPointCountRange,
  3585. {std::to_string(DXIL::kMaxIAPatchControlPointCount),
  3586. std::to_string(inputControlPointCount)});
  3587. }
  3588. if (domain == DXIL::TessellatorDomain::Undefined) {
  3589. ValCtx.EmitError(ValidationRule::SmValidDomain);
  3590. }
  3591. CheckPatchConstantSemantic(ValCtx);
  3592. } else if (ShaderType == DXIL::ShaderKind::Hull) {
  3593. DXIL::TessellatorDomain domain = M.GetTessellatorDomain();
  3594. if (domain >= DXIL::TessellatorDomain::LastEntry)
  3595. domain = DXIL::TessellatorDomain::Undefined;
  3596. unsigned inputControlPointCount = M.GetInputControlPointCount();
  3597. if (inputControlPointCount == 0) {
  3598. if (!M.GetInputSignature().GetElements().empty()) {
  3599. ValCtx.EmitError(
  3600. ValidationRule::SmZeroHSInputControlPointWithInput);
  3601. }
  3602. } else if (inputControlPointCount > DXIL::kMaxIAPatchControlPointCount) {
  3603. ValCtx.EmitFormatError(
  3604. ValidationRule::SmHSInputControlPointCountRange,
  3605. {std::to_string(DXIL::kMaxIAPatchControlPointCount),
  3606. std::to_string(inputControlPointCount)});
  3607. }
  3608. if (domain == DXIL::TessellatorDomain::Undefined) {
  3609. ValCtx.EmitError(ValidationRule::SmValidDomain);
  3610. }
  3611. DXIL::TessellatorPartitioning partition = M.GetTessellatorPartitioning();
  3612. if (partition == DXIL::TessellatorPartitioning::Undefined) {
  3613. ValCtx.EmitError(ValidationRule::MetaTessellatorPartition);
  3614. }
  3615. DXIL::TessellatorOutputPrimitive tessOutputPrimitive =
  3616. M.GetTessellatorOutputPrimitive();
  3617. if (tessOutputPrimitive == DXIL::TessellatorOutputPrimitive::Undefined ||
  3618. tessOutputPrimitive == DXIL::TessellatorOutputPrimitive::LastEntry) {
  3619. ValCtx.EmitError(ValidationRule::MetaTessellatorOutputPrimitive);
  3620. }
  3621. float maxTessFactor = M.GetMaxTessellationFactor();
  3622. if (maxTessFactor < DXIL::kHSMaxTessFactorLowerBound ||
  3623. maxTessFactor > DXIL::kHSMaxTessFactorUpperBound) {
  3624. ValCtx.EmitFormatError(
  3625. ValidationRule::MetaMaxTessFactor,
  3626. {std::to_string(DXIL::kHSMaxTessFactorLowerBound),
  3627. std::to_string(DXIL::kHSMaxTessFactorUpperBound),
  3628. std::to_string(maxTessFactor)});
  3629. }
  3630. // Domain and OutPrimivtive match.
  3631. switch (domain) {
  3632. case DXIL::TessellatorDomain::IsoLine:
  3633. switch (tessOutputPrimitive) {
  3634. case DXIL::TessellatorOutputPrimitive::TriangleCW:
  3635. case DXIL::TessellatorOutputPrimitive::TriangleCCW:
  3636. ValCtx.EmitError(ValidationRule::SmIsoLineOutputPrimitiveMismatch);
  3637. break;
  3638. default:
  3639. break;
  3640. }
  3641. break;
  3642. case DXIL::TessellatorDomain::Tri:
  3643. switch (tessOutputPrimitive) {
  3644. case DXIL::TessellatorOutputPrimitive::Line:
  3645. ValCtx.EmitError(ValidationRule::SmTriOutputPrimitiveMismatch);
  3646. break;
  3647. default:
  3648. break;
  3649. }
  3650. break;
  3651. case DXIL::TessellatorDomain::Quad:
  3652. switch (tessOutputPrimitive) {
  3653. case DXIL::TessellatorOutputPrimitive::Line:
  3654. ValCtx.EmitError(ValidationRule::SmTriOutputPrimitiveMismatch);
  3655. break;
  3656. default:
  3657. break;
  3658. }
  3659. break;
  3660. default:
  3661. ValCtx.EmitError(ValidationRule::SmValidDomain);
  3662. break;
  3663. }
  3664. // Check pass thru HS.
  3665. if (M.GetEntryFunction() == nullptr) {
  3666. if (M.GetShaderModel()->IsHS()) {
  3667. if (M.GetInputControlPointCount() < M.GetOutputControlPointCount()) {
  3668. ValCtx.EmitError(
  3669. ValidationRule::SmHullPassThruControlPointCountMatch);
  3670. }
  3671. // Check declared control point outputs storage amounts are ok to pass
  3672. // through (less output storage than input for control points).
  3673. DxilSignature &outSig = M.GetOutputSignature();
  3674. unsigned totalOutputCPScalars = 0;
  3675. for (auto &SE : outSig.GetElements()) {
  3676. totalOutputCPScalars += SE->GetRows() * SE->GetCols();
  3677. }
  3678. if (totalOutputCPScalars * M.GetOutputControlPointCount() >
  3679. DXIL::kMaxHSOutputControlPointsTotalScalars) {
  3680. ValCtx.EmitError(ValidationRule::SmOutputControlPointsTotalScalars);
  3681. }
  3682. } else {
  3683. ValCtx.EmitError(ValidationRule::MetaEntryFunction);
  3684. }
  3685. }
  3686. CheckPatchConstantSemantic(ValCtx);
  3687. } else if (ShaderType == DXIL::ShaderKind::Geometry) {
  3688. unsigned maxVertexCount = M.GetMaxVertexCount();
  3689. if (maxVertexCount > DXIL::kMaxGSOutputVertexCount) {
  3690. ValCtx.EmitFormatError(
  3691. ValidationRule::SmGSOutputVertexCountRange,
  3692. {std::to_string(DXIL::kMaxGSOutputVertexCount),
  3693. std::to_string(maxVertexCount)});
  3694. }
  3695. unsigned instanceCount = M.GetGSInstanceCount();
  3696. if (instanceCount > DXIL::kMaxGSInstanceCount || instanceCount < 1) {
  3697. ValCtx.EmitFormatError(ValidationRule::SmGSInstanceCountRange,
  3698. {std::to_string(DXIL::kMaxGSInstanceCount),
  3699. std::to_string(instanceCount)});
  3700. }
  3701. DXIL::PrimitiveTopology topo = M.GetStreamPrimitiveTopology();
  3702. switch (topo) {
  3703. case DXIL::PrimitiveTopology::PointList:
  3704. case DXIL::PrimitiveTopology::LineStrip:
  3705. case DXIL::PrimitiveTopology::TriangleStrip:
  3706. break;
  3707. default: {
  3708. ValCtx.EmitError(ValidationRule::SmGSValidOutputPrimitiveTopology);
  3709. } break;
  3710. }
  3711. DXIL::InputPrimitive inputPrimitive = M.GetInputPrimitive();
  3712. unsigned VertexCount = GetNumVertices(inputPrimitive);
  3713. if (VertexCount == 0 && inputPrimitive != DXIL::InputPrimitive::Undefined) {
  3714. ValCtx.EmitError(ValidationRule::SmGSValidInputPrimitive);
  3715. }
  3716. }
  3717. unsigned outputControlPointCount = M.GetOutputControlPointCount();
  3718. if (outputControlPointCount > DXIL::kMaxIAPatchControlPointCount) {
  3719. ValCtx.EmitFormatError(
  3720. ValidationRule::SmOutputControlPointCountRange,
  3721. {std::to_string(DXIL::kMaxIAPatchControlPointCount),
  3722. std::to_string(outputControlPointCount)});
  3723. }
  3724. }
  3725. static bool
  3726. CalculateCallDepth(CallGraphNode *node,
  3727. std::unordered_map<CallGraphNode *, unsigned> &depthMap,
  3728. std::unordered_set<CallGraphNode *> &callStack,
  3729. std::unordered_set<Function *> &funcSet) {
  3730. unsigned depth = callStack.size();
  3731. funcSet.insert(node->getFunction());
  3732. for (auto it = node->begin(), ei = node->end(); it != ei; it++) {
  3733. CallGraphNode *toNode = it->second;
  3734. if (callStack.insert(toNode).second == false) {
  3735. // Recursive.
  3736. return true;
  3737. }
  3738. if (depthMap[toNode] < depth)
  3739. depthMap[toNode] = depth;
  3740. if (CalculateCallDepth(toNode, depthMap, callStack, funcSet)) {
  3741. // Recursive
  3742. return true;
  3743. }
  3744. callStack.erase(toNode);
  3745. }
  3746. return false;
  3747. }
  3748. static void ValidateCallGraph(ValidationContext &ValCtx) {
  3749. // Build CallGraph.
  3750. CallGraph CG(*ValCtx.DxilMod.GetModule());
  3751. std::unordered_map<CallGraphNode*, unsigned> depthMap;
  3752. std::unordered_set<CallGraphNode*> callStack;
  3753. CallGraphNode *entryNode = CG[ValCtx.DxilMod.GetEntryFunction()];
  3754. depthMap[entryNode] = 0;
  3755. bool bRecursive = CalculateCallDepth(entryNode, depthMap, callStack, ValCtx.entryFuncCallSet);
  3756. if (ValCtx.DxilMod.GetShaderModel()->IsHS()) {
  3757. CallGraphNode *patchConstantNode = CG[ValCtx.DxilMod.GetPatchConstantFunction()];
  3758. depthMap[patchConstantNode] = 0;
  3759. callStack.clear();
  3760. bRecursive |= CalculateCallDepth(patchConstantNode, depthMap, callStack, ValCtx.patchConstFuncCallSet);
  3761. }
  3762. if (bRecursive) {
  3763. ValCtx.EmitError(ValidationRule::FlowNoRecusion);
  3764. }
  3765. }
  3766. static void ValidateFlowControl(ValidationContext &ValCtx) {
  3767. bool reducible =
  3768. IsReducible(*ValCtx.DxilMod.GetModule(), IrreducibilityAction::Ignore);
  3769. if (!reducible) {
  3770. ValCtx.EmitError(ValidationRule::FlowReducible);
  3771. return;
  3772. }
  3773. ValidateCallGraph(ValCtx);
  3774. for (auto &F : ValCtx.DxilMod.GetModule()->functions()) {
  3775. if (F.isDeclaration())
  3776. continue;
  3777. DominatorTreeAnalysis DTA;
  3778. DominatorTree DT = DTA.run(F);
  3779. LoopInfo LI;
  3780. LI.Analyze(DT);
  3781. for (auto loopIt = LI.begin(); loopIt != LI.end(); loopIt++) {
  3782. Loop *loop = *loopIt;
  3783. SmallVector<BasicBlock *, 4> exitBlocks;
  3784. loop->getExitBlocks(exitBlocks);
  3785. if (exitBlocks.empty())
  3786. ValCtx.EmitError(ValidationRule::FlowDeadLoop);
  3787. }
  3788. }
  3789. // fxc has ERR_CONTINUE_INSIDE_SWITCH to disallow continue in switch.
  3790. // Not do it for now.
  3791. }
  3792. static void ValidateUninitializedOutput(ValidationContext &ValCtx) {
  3793. // For HS only need to check Tessfactor which is in patch constant sig.
  3794. if (ValCtx.DxilMod.GetShaderModel()->IsHS()) {
  3795. std::vector<unsigned> &patchConstCols = ValCtx.patchConstCols;
  3796. for (auto &E : ValCtx.DxilMod.GetPatchConstantSignature().GetElements()) {
  3797. unsigned mask = patchConstCols[E->GetID()];
  3798. unsigned requireMask = (1 << E->GetCols()) - 1;
  3799. // TODO: check other case uninitialized output is allowed.
  3800. if (mask != requireMask && !E->GetSemantic()->IsArbitrary()) {
  3801. ValCtx.EmitFormatError(ValidationRule::SmUndefinedOutput,
  3802. {E->GetName()});
  3803. }
  3804. }
  3805. return;
  3806. }
  3807. std::vector<unsigned> &outputCols = ValCtx.outputCols;
  3808. for (auto &E : ValCtx.DxilMod.GetOutputSignature().GetElements()) {
  3809. unsigned mask = outputCols[E->GetID()];
  3810. unsigned requireMask = (1 << E->GetCols()) - 1;
  3811. // TODO: check other case uninitialized output is allowed.
  3812. if (mask != requireMask && !E->GetSemantic()->IsArbitrary() &&
  3813. E->GetSemantic()->GetKind() != Semantic::Kind::Target) {
  3814. ValCtx.EmitFormatError(ValidationRule::SmUndefinedOutput, {E->GetName()});
  3815. }
  3816. }
  3817. }
  3818. void GetValidationVersion(_Out_ unsigned *pMajor, _Out_ unsigned *pMinor) {
  3819. // 1.0 is the first validator.
  3820. // 1.1 adds:
  3821. // - ILDN container part support
  3822. // 1.2 adds:
  3823. // - Metadata for floating point denorm mode
  3824. *pMajor = 1;
  3825. *pMinor = 2;
  3826. }
  3827. _Use_decl_annotations_ HRESULT
  3828. ValidateDxilModule(llvm::Module *pModule, llvm::Module *pDebugModule) {
  3829. std::string diagStr;
  3830. raw_string_ostream diagStream(diagStr);
  3831. DiagnosticPrinterRawOStream DiagPrinter(diagStream);
  3832. DxilModule *pDxilModule = DxilModule::TryGetDxilModule(pModule);
  3833. if (!pDxilModule) {
  3834. return DXC_E_IR_VERIFICATION_FAILED;
  3835. }
  3836. ValidationContext ValCtx(*pModule, pDebugModule, *pDxilModule, DiagPrinter);
  3837. ValidateMetadata(ValCtx);
  3838. ValidateShaderState(ValCtx);
  3839. ValidateGlobalVariables(ValCtx);
  3840. ValidateResources(ValCtx);
  3841. // Validate control flow and collect function call info.
  3842. // If has recursive call, call info collection will not finish.
  3843. ValidateFlowControl(ValCtx);
  3844. // Validate functions.
  3845. for (Function &F : pModule->functions()) {
  3846. ValidateFunction(F, ValCtx);
  3847. }
  3848. ValidateUninitializedOutput(ValCtx);
  3849. ValidateShaderFlags(ValCtx);
  3850. ValidateSignatures(ValCtx);
  3851. if (!pDxilModule->GetShaderModel()->IsGS()) {
  3852. unsigned posMask = ValCtx.OutputPositionMask[0];
  3853. if (posMask != 0xf && ValCtx.hasOutputPosition[0]) {
  3854. ValCtx.EmitError(ValidationRule::SmCompletePosition);
  3855. }
  3856. } else {
  3857. unsigned streamMask = ValCtx.DxilMod.GetActiveStreamMask();
  3858. for (unsigned i = 0; i < DXIL::kNumOutputStreams; i++) {
  3859. if (streamMask & (1 << i)) {
  3860. unsigned posMask = ValCtx.OutputPositionMask[i];
  3861. if (posMask != 0xf && ValCtx.hasOutputPosition[i]) {
  3862. ValCtx.EmitError(ValidationRule::SmCompletePosition);
  3863. }
  3864. }
  3865. }
  3866. }
  3867. // Ensure error messages are flushed out on error.
  3868. if (ValCtx.Failed) {
  3869. emitDxilDiag(pModule->getContext(), diagStream.str().c_str());
  3870. return DXC_E_IR_VERIFICATION_FAILED;
  3871. }
  3872. return S_OK;
  3873. }
  3874. // DXIL Container Verification Functions
  3875. static void VerifyBlobPartMatches(_In_ ValidationContext &ValCtx,
  3876. _In_ LPCSTR pName,
  3877. DxilPartWriter *pWriter,
  3878. _In_reads_bytes_opt_(Size) const void *pData,
  3879. _In_ uint32_t Size) {
  3880. if (!pData && pWriter->size()) {
  3881. // No blob part, but writer says non-zero size is expected.
  3882. ValCtx.EmitFormatError(ValidationRule::ContainerPartMissing, {pName});
  3883. return;
  3884. }
  3885. // Compare sizes
  3886. if (pWriter->size() != Size) {
  3887. ValCtx.EmitFormatError(ValidationRule::ContainerPartMatches, {pName});
  3888. return;
  3889. }
  3890. if (Size == 0) {
  3891. return;
  3892. }
  3893. CComPtr<AbstractMemoryStream> pOutputStream;
  3894. IFT(CreateMemoryStream(DxcGetThreadMallocNoRef(), &pOutputStream));
  3895. pOutputStream->Reserve(Size);
  3896. pWriter->write(pOutputStream);
  3897. DXASSERT(pOutputStream->GetPtrSize() == Size, "otherwise, DxilPartWriter misreported size");
  3898. if (memcmp(pData, pOutputStream->GetPtr(), Size)) {
  3899. ValCtx.EmitFormatError(ValidationRule::ContainerPartMatches, {pName});
  3900. return;
  3901. }
  3902. return;
  3903. }
  3904. static void VerifySignatureMatches(_In_ ValidationContext &ValCtx,
  3905. DXIL::SignatureKind SigKind,
  3906. _In_reads_bytes_opt_(SigSize) const void *pSigData,
  3907. _In_ uint32_t SigSize) {
  3908. // Generate corresponding signature from module and memcmp
  3909. const char *pName = nullptr;
  3910. switch (SigKind)
  3911. {
  3912. case hlsl::DXIL::SignatureKind::Input:
  3913. pName = "Program Input Signature";
  3914. break;
  3915. case hlsl::DXIL::SignatureKind::Output:
  3916. pName = "Program Output Signature";
  3917. break;
  3918. case hlsl::DXIL::SignatureKind::PatchConstant:
  3919. pName = "Program Patch Constant Signature";
  3920. break;
  3921. default:
  3922. break;
  3923. }
  3924. unique_ptr<DxilPartWriter> pWriter(NewProgramSignatureWriter(ValCtx.DxilMod, SigKind));
  3925. VerifyBlobPartMatches(ValCtx, pName, pWriter.get(), pSigData, SigSize);
  3926. }
  3927. _Use_decl_annotations_
  3928. bool VerifySignatureMatches(llvm::Module *pModule,
  3929. DXIL::SignatureKind SigKind,
  3930. const void *pSigData,
  3931. uint32_t SigSize) {
  3932. std::string diagStr;
  3933. raw_string_ostream diagStream(diagStr);
  3934. DiagnosticPrinterRawOStream DiagPrinter(diagStream);
  3935. ValidationContext ValCtx(*pModule, nullptr, pModule->GetOrCreateDxilModule(), DiagPrinter);
  3936. VerifySignatureMatches(ValCtx, SigKind, pSigData, SigSize);
  3937. if (ValCtx.Failed) {
  3938. emitDxilDiag(pModule->getContext(), diagStream.str().c_str());
  3939. }
  3940. return !ValCtx.Failed;
  3941. }
  3942. static void VerifyPSVMatches(_In_ ValidationContext &ValCtx,
  3943. _In_reads_bytes_(PSVSize) const void *pPSVData,
  3944. _In_ uint32_t PSVSize) {
  3945. uint32_t PSVVersion = 1; // This should be set to the newest version
  3946. unique_ptr<DxilPartWriter> pWriter(NewPSVWriter(ValCtx.DxilMod, PSVVersion));
  3947. // Try each version in case an earlier version matches module
  3948. while (PSVVersion && pWriter->size() != PSVSize) {
  3949. PSVVersion --;
  3950. pWriter.reset(NewPSVWriter(ValCtx.DxilMod, PSVVersion));
  3951. }
  3952. // generate PSV data from module and memcmp
  3953. VerifyBlobPartMatches(ValCtx, "Pipeline State Validation", pWriter.get(), pPSVData, PSVSize);
  3954. }
  3955. _Use_decl_annotations_
  3956. bool VerifyPSVMatches(llvm::Module *pModule,
  3957. const void *pPSVData,
  3958. uint32_t PSVSize) {
  3959. std::string diagStr;
  3960. raw_string_ostream diagStream(diagStr);
  3961. DiagnosticPrinterRawOStream DiagPrinter(diagStream);
  3962. ValidationContext ValCtx(*pModule, nullptr, pModule->GetOrCreateDxilModule(), DiagPrinter);
  3963. VerifyPSVMatches(ValCtx, pPSVData, PSVSize);
  3964. if (ValCtx.Failed) {
  3965. emitDxilDiag(pModule->getContext(), diagStream.str().c_str());
  3966. }
  3967. return !ValCtx.Failed;
  3968. }
  3969. static void VerifyFeatureInfoMatches(_In_ ValidationContext &ValCtx,
  3970. _In_reads_bytes_(FeatureInfoSize) const void *pFeatureInfoData,
  3971. _In_ uint32_t FeatureInfoSize) {
  3972. // generate Feature Info data from module and memcmp
  3973. unique_ptr<DxilPartWriter> pWriter(NewFeatureInfoWriter(ValCtx.DxilMod));
  3974. VerifyBlobPartMatches(ValCtx, "Feature Info", pWriter.get(), pFeatureInfoData, FeatureInfoSize);
  3975. }
  3976. _Use_decl_annotations_
  3977. bool VerifyFeatureInfoMatches(llvm::Module *pModule,
  3978. const void *pFeatureInfoData,
  3979. uint32_t FeatureInfoSize) {
  3980. std::string diagStr;
  3981. raw_string_ostream diagStream(diagStr);
  3982. DiagnosticPrinterRawOStream DiagPrinter(diagStream);
  3983. ValidationContext ValCtx(*pModule, nullptr, pModule->GetOrCreateDxilModule(), DiagPrinter);
  3984. VerifyFeatureInfoMatches(ValCtx, pFeatureInfoData, FeatureInfoSize);
  3985. if (ValCtx.Failed) {
  3986. emitDxilDiag(pModule->getContext(), diagStream.str().c_str());
  3987. }
  3988. return !ValCtx.Failed;
  3989. }
  3990. _Use_decl_annotations_
  3991. HRESULT ValidateDxilContainerParts(llvm::Module *pModule,
  3992. llvm::Module *pDebugModule,
  3993. const DxilContainerHeader *pContainer,
  3994. uint32_t ContainerSize) {
  3995. DXASSERT_NOMSG(pModule);
  3996. if (!pContainer || !IsValidDxilContainer(pContainer, ContainerSize)) {
  3997. return DXC_E_CONTAINER_INVALID;
  3998. }
  3999. DxilModule *pDxilModule = DxilModule::TryGetDxilModule(pModule);
  4000. if (!pDxilModule) {
  4001. return DXC_E_IR_VERIFICATION_FAILED;
  4002. }
  4003. std::string diagStr;
  4004. raw_string_ostream DiagStream(diagStr);
  4005. DiagnosticPrinterRawOStream DiagPrinter(DiagStream);
  4006. ValidationContext ValCtx(*pModule, pDebugModule, *pDxilModule, DiagPrinter);
  4007. DXIL::ShaderKind ShaderKind = pDxilModule->GetShaderModel()->GetKind();
  4008. bool bTess = ShaderKind == DXIL::ShaderKind::Hull || ShaderKind == DXIL::ShaderKind::Domain;
  4009. std::unordered_set<uint32_t> FourCCFound;
  4010. const DxilPartHeader *pRootSignaturePart = nullptr;
  4011. const DxilPartHeader *pPSVPart = nullptr;
  4012. for (auto it = begin(pContainer), itEnd = end(pContainer); it != itEnd; ++it) {
  4013. const DxilPartHeader *pPart = *it;
  4014. char szFourCC[5];
  4015. PartKindToCharArray(pPart->PartFourCC, szFourCC);
  4016. if (FourCCFound.find(pPart->PartFourCC) != FourCCFound.end()) {
  4017. // Two parts with same FourCC found
  4018. ValCtx.EmitFormatError(ValidationRule::ContainerPartRepeated, {szFourCC});
  4019. continue;
  4020. }
  4021. FourCCFound.insert(pPart->PartFourCC);
  4022. switch (pPart->PartFourCC)
  4023. {
  4024. case DFCC_InputSignature:
  4025. VerifySignatureMatches(ValCtx, DXIL::SignatureKind::Input, GetDxilPartData(pPart), pPart->PartSize);
  4026. break;
  4027. case DFCC_OutputSignature:
  4028. VerifySignatureMatches(ValCtx, DXIL::SignatureKind::Output, GetDxilPartData(pPart), pPart->PartSize);
  4029. break;
  4030. case DFCC_PatchConstantSignature:
  4031. if (bTess) {
  4032. VerifySignatureMatches(ValCtx, DXIL::SignatureKind::PatchConstant, GetDxilPartData(pPart), pPart->PartSize);
  4033. } else {
  4034. ValCtx.EmitFormatError(ValidationRule::ContainerPartMatches, {"Program Patch Constant Signature"});
  4035. }
  4036. break;
  4037. case DFCC_FeatureInfo:
  4038. VerifyFeatureInfoMatches(ValCtx, GetDxilPartData(pPart), pPart->PartSize);
  4039. break;
  4040. case DFCC_RootSignature:
  4041. pRootSignaturePart = pPart;
  4042. break;
  4043. case DFCC_PipelineStateValidation:
  4044. pPSVPart = pPart;
  4045. VerifyPSVMatches(ValCtx, GetDxilPartData(pPart), pPart->PartSize);
  4046. break;
  4047. // Skip these
  4048. case DFCC_ResourceDef:
  4049. case DFCC_ShaderStatistics:
  4050. case DFCC_PrivateData:
  4051. case DFCC_DXIL:
  4052. case DFCC_ShaderDebugInfoDXIL:
  4053. case DFCC_ShaderDebugName:
  4054. continue;
  4055. case DFCC_Container:
  4056. default:
  4057. ValCtx.EmitFormatError(ValidationRule::ContainerPartInvalid, {szFourCC});
  4058. break;
  4059. }
  4060. }
  4061. // Verify required parts found
  4062. if (FourCCFound.find(DFCC_InputSignature) == FourCCFound.end()) {
  4063. VerifySignatureMatches(ValCtx, DXIL::SignatureKind::Input, nullptr, 0);
  4064. }
  4065. if (FourCCFound.find(DFCC_OutputSignature) == FourCCFound.end()) {
  4066. VerifySignatureMatches(ValCtx, DXIL::SignatureKind::Output, nullptr, 0);
  4067. }
  4068. if (bTess && FourCCFound.find(DFCC_PatchConstantSignature) == FourCCFound.end() &&
  4069. pDxilModule->GetPatchConstantSignature().GetElements().size())
  4070. {
  4071. ValCtx.EmitFormatError(ValidationRule::ContainerPartMissing, {"Program Patch Constant Signature"});
  4072. }
  4073. if (FourCCFound.find(DFCC_FeatureInfo) == FourCCFound.end()) {
  4074. // Could be optional, but RS1 runtime doesn't handle this case properly.
  4075. ValCtx.EmitFormatError(ValidationRule::ContainerPartMissing, {"Feature Info"});
  4076. }
  4077. // Validate Root Signature
  4078. if (pPSVPart) {
  4079. if (pRootSignaturePart) {
  4080. try {
  4081. RootSignatureHandle RS;
  4082. RS.LoadSerialized((const uint8_t*)GetDxilPartData(pRootSignaturePart), pRootSignaturePart->PartSize);
  4083. RS.Deserialize();
  4084. IFTBOOL(VerifyRootSignatureWithShaderPSV(RS.GetDesc(),
  4085. pDxilModule->GetShaderModel()->GetKind(),
  4086. GetDxilPartData(pPSVPart), pPSVPart->PartSize,
  4087. DiagStream), DXC_E_INCORRECT_ROOT_SIGNATURE);
  4088. } catch (...) {
  4089. ValCtx.EmitError(ValidationRule::ContainerRootSignatureIncompatible);
  4090. }
  4091. }
  4092. } else {
  4093. ValCtx.EmitFormatError(ValidationRule::ContainerPartMissing, {"Pipeline State Validation"});
  4094. }
  4095. if (ValCtx.Failed) {
  4096. emitDxilDiag(pModule->getContext(), DiagStream.str().c_str());
  4097. return DXC_E_MALFORMED_CONTAINER;
  4098. }
  4099. return S_OK;
  4100. }
  4101. static HRESULT FindDxilPart(_In_reads_bytes_(ContainerSize) const void *pContainerBytes,
  4102. _In_ uint32_t ContainerSize,
  4103. _In_ DxilFourCC FourCC,
  4104. _In_ const DxilPartHeader **ppPart) {
  4105. const DxilContainerHeader *pContainer =
  4106. IsDxilContainerLike(pContainerBytes, ContainerSize);
  4107. if (!pContainer) {
  4108. IFR(DXC_E_CONTAINER_INVALID);
  4109. }
  4110. if (!IsValidDxilContainer(pContainer, ContainerSize)) {
  4111. IFR(DXC_E_CONTAINER_INVALID);
  4112. }
  4113. DxilPartIterator it = std::find_if(begin(pContainer), end(pContainer),
  4114. DxilPartIsType(FourCC));
  4115. if (it == end(pContainer)) {
  4116. IFR(DXC_E_CONTAINER_MISSING_DXIL);
  4117. }
  4118. const DxilProgramHeader *pProgramHeader =
  4119. reinterpret_cast<const DxilProgramHeader *>(GetDxilPartData(*it));
  4120. if (!IsValidDxilProgramHeader(pProgramHeader, (*it)->PartSize)) {
  4121. IFR(DXC_E_CONTAINER_INVALID);
  4122. }
  4123. *ppPart = *it;
  4124. return S_OK;
  4125. }
  4126. _Use_decl_annotations_
  4127. HRESULT ValidateLoadModule(const char *pIL,
  4128. uint32_t ILLength,
  4129. unique_ptr<llvm::Module> &pModule,
  4130. LLVMContext &Ctx,
  4131. llvm::raw_ostream &DiagStream,
  4132. unsigned bLazyLoad) {
  4133. llvm::DiagnosticPrinterRawOStream DiagPrinter(DiagStream);
  4134. PrintDiagnosticContext DiagContext(DiagPrinter);
  4135. DiagRestore DR(Ctx, &DiagContext);
  4136. std::unique_ptr<llvm::MemoryBuffer> pBitcodeBuf;
  4137. pBitcodeBuf.reset(llvm::MemoryBuffer::getMemBuffer(
  4138. llvm::StringRef(pIL, ILLength), "", false).release());
  4139. ErrorOr<std::unique_ptr<Module>> loadedModuleResult =
  4140. bLazyLoad == 0?
  4141. llvm::parseBitcodeFile(pBitcodeBuf->getMemBufferRef(), Ctx) :
  4142. llvm::getLazyBitcodeModule(std::move(pBitcodeBuf), Ctx);
  4143. // DXIL disallows some LLVM bitcode constructs, like unaccounted-for sub-blocks.
  4144. // These appear as warnings, which the validator should reject.
  4145. if (DiagContext.HasErrors() || DiagContext.HasWarnings() || loadedModuleResult.getError())
  4146. return DXC_E_IR_VERIFICATION_FAILED;
  4147. pModule = std::move(loadedModuleResult.get());
  4148. return S_OK;
  4149. }
  4150. HRESULT ValidateDxilBitcode(
  4151. _In_reads_bytes_(ILLength) const char *pIL,
  4152. _In_ uint32_t ILLength,
  4153. _In_ llvm::raw_ostream &DiagStream) {
  4154. LLVMContext Ctx;
  4155. std::unique_ptr<llvm::Module> pModule;
  4156. llvm::DiagnosticPrinterRawOStream DiagPrinter(DiagStream);
  4157. PrintDiagnosticContext DiagContext(DiagPrinter);
  4158. Ctx.setDiagnosticHandler(PrintDiagnosticContext::PrintDiagnosticHandler,
  4159. &DiagContext, true);
  4160. HRESULT hr;
  4161. if (FAILED(hr = ValidateLoadModule(pIL, ILLength, pModule, Ctx, DiagStream,
  4162. /*bLazyLoad*/ false)))
  4163. return hr;
  4164. if (FAILED(hr = ValidateDxilModule(pModule.get(), nullptr)))
  4165. return hr;
  4166. DxilModule &dxilModule = pModule->GetDxilModule();
  4167. if (!dxilModule.GetRootSignature().IsEmpty()) {
  4168. unique_ptr<DxilPartWriter> pWriter(NewPSVWriter(dxilModule, 0));
  4169. DXASSERT_NOMSG(pWriter->size());
  4170. CComPtr<AbstractMemoryStream> pOutputStream;
  4171. IFT(CreateMemoryStream(DxcGetThreadMallocNoRef(), &pOutputStream));
  4172. pOutputStream->Reserve(pWriter->size());
  4173. pWriter->write(pOutputStream);
  4174. const DxilVersionedRootSignatureDesc* pDesc = dxilModule.GetRootSignature().GetDesc();
  4175. RootSignatureHandle RS;
  4176. try {
  4177. if (!pDesc) {
  4178. RS.Assign(nullptr, dxilModule.GetRootSignature().GetSerialized());
  4179. RS.Deserialize();
  4180. pDesc = RS.GetDesc();
  4181. if (!pDesc)
  4182. return DXC_E_INCORRECT_ROOT_SIGNATURE;
  4183. }
  4184. IFTBOOL(VerifyRootSignatureWithShaderPSV(pDesc,
  4185. dxilModule.GetShaderModel()->GetKind(),
  4186. pOutputStream->GetPtr(), pWriter->size(),
  4187. DiagStream), DXC_E_INCORRECT_ROOT_SIGNATURE);
  4188. } catch (...) {
  4189. return DXC_E_INCORRECT_ROOT_SIGNATURE;
  4190. }
  4191. }
  4192. if (DiagContext.HasErrors() || DiagContext.HasWarnings()) {
  4193. return DXC_E_IR_VERIFICATION_FAILED;
  4194. }
  4195. return S_OK;
  4196. }
  4197. static HRESULT ValidateLoadModuleFromContainer(
  4198. _In_reads_bytes_(ILLength) const void *pContainer,
  4199. _In_ uint32_t ContainerSize, _In_ std::unique_ptr<llvm::Module> &pModule,
  4200. _In_ std::unique_ptr<llvm::Module> &pDebugModule,
  4201. _In_ llvm::LLVMContext &Ctx, LLVMContext &DbgCtx,
  4202. _In_ llvm::raw_ostream &DiagStream, _In_ unsigned bLazyLoad) {
  4203. llvm::DiagnosticPrinterRawOStream DiagPrinter(DiagStream);
  4204. PrintDiagnosticContext DiagContext(DiagPrinter);
  4205. DiagRestore DR(Ctx, &DiagContext);
  4206. DiagRestore DR2(DbgCtx, &DiagContext);
  4207. const DxilPartHeader *pPart = nullptr;
  4208. IFR(FindDxilPart(pContainer, ContainerSize, DFCC_DXIL, &pPart));
  4209. const char *pIL = nullptr;
  4210. uint32_t ILLength = 0;
  4211. GetDxilProgramBitcode(
  4212. reinterpret_cast<const DxilProgramHeader *>(GetDxilPartData(pPart)), &pIL,
  4213. &ILLength);
  4214. IFR(ValidateLoadModule(pIL, ILLength, pModule, Ctx, DiagStream, bLazyLoad));
  4215. HRESULT hr;
  4216. const DxilPartHeader *pDbgPart = nullptr;
  4217. if (FAILED(hr = FindDxilPart(pContainer, ContainerSize,
  4218. DFCC_ShaderDebugInfoDXIL, &pDbgPart)) &&
  4219. hr != DXC_E_CONTAINER_MISSING_DXIL) {
  4220. return hr;
  4221. }
  4222. if (pDbgPart) {
  4223. GetDxilProgramBitcode(
  4224. reinterpret_cast<const DxilProgramHeader *>(GetDxilPartData(pDbgPart)),
  4225. &pIL, &ILLength);
  4226. if (FAILED(hr = ValidateLoadModule(pIL, ILLength, pDebugModule, DbgCtx,
  4227. DiagStream, bLazyLoad))) {
  4228. return hr;
  4229. }
  4230. }
  4231. return S_OK;
  4232. }
  4233. _Use_decl_annotations_ HRESULT ValidateLoadModuleFromContainer(
  4234. _In_reads_bytes_(ContainerSize) const void *pContainer,
  4235. _In_ uint32_t ContainerSize, _In_ std::unique_ptr<llvm::Module> &pModule,
  4236. _In_ std::unique_ptr<llvm::Module> &pDebugModule,
  4237. _In_ llvm::LLVMContext &Ctx, llvm::LLVMContext &DbgCtx,
  4238. _In_ llvm::raw_ostream &DiagStream) {
  4239. return ValidateLoadModuleFromContainer(pContainer, ContainerSize, pModule,
  4240. pDebugModule, Ctx, DbgCtx, DiagStream,
  4241. /*bLazyLoad*/ false);
  4242. }
  4243. // Lazy loads module from container, validating load, but not module.
  4244. _Use_decl_annotations_ HRESULT ValidateLoadModuleFromContainerLazy(
  4245. _In_reads_bytes_(ContainerSize) const void *pContainer,
  4246. _In_ uint32_t ContainerSize, _In_ std::unique_ptr<llvm::Module> &pModule,
  4247. _In_ std::unique_ptr<llvm::Module> &pDebugModule,
  4248. _In_ llvm::LLVMContext &Ctx, llvm::LLVMContext &DbgCtx,
  4249. _In_ llvm::raw_ostream &DiagStream) {
  4250. return ValidateLoadModuleFromContainer(pContainer, ContainerSize, pModule,
  4251. pDebugModule, Ctx, DbgCtx, DiagStream,
  4252. /*bLazyLoad*/ true);
  4253. }
  4254. _Use_decl_annotations_
  4255. HRESULT ValidateDxilContainer(const void *pContainer,
  4256. uint32_t ContainerSize,
  4257. llvm::raw_ostream &DiagStream) {
  4258. LLVMContext Ctx, DbgCtx;
  4259. std::unique_ptr<llvm::Module> pModule, pDebugModule;
  4260. llvm::DiagnosticPrinterRawOStream DiagPrinter(DiagStream);
  4261. PrintDiagnosticContext DiagContext(DiagPrinter);
  4262. Ctx.setDiagnosticHandler(PrintDiagnosticContext::PrintDiagnosticHandler,
  4263. &DiagContext, true);
  4264. DbgCtx.setDiagnosticHandler(PrintDiagnosticContext::PrintDiagnosticHandler,
  4265. &DiagContext, true);
  4266. IFR(ValidateLoadModuleFromContainer(pContainer, ContainerSize, pModule, pDebugModule,
  4267. Ctx, DbgCtx, DiagStream));
  4268. // Validate DXIL Module
  4269. IFR(ValidateDxilModule(pModule.get(), pDebugModule.get()));
  4270. if (DiagContext.HasErrors() || DiagContext.HasWarnings()) {
  4271. return DXC_E_IR_VERIFICATION_FAILED;
  4272. }
  4273. return ValidateDxilContainerParts(pModule.get(), pDebugModule.get(),
  4274. IsDxilContainerLike(pContainer, ContainerSize), ContainerSize);
  4275. }
  4276. } // namespace hlsl