DxilValidation.cpp 244 KB

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