DxilValidation.cpp 221 KB

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