DxilValidation.cpp 214 KB

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