DxilValidation.cpp 216 KB

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