DxilValidation.cpp 255 KB

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