DxilValidation.cpp 220 KB

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