DxilValidation.cpp 154 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988
  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/Support/Global.h"
  18. #include "dxc/HLSL/HLModule.h"
  19. #include "dxc/HLSL/DxilInstructions.h"
  20. #include "dxc/HLSL/ReducibilityAnalysis.h"
  21. #include "llvm/ADT/ArrayRef.h"
  22. #include "llvm/Analysis/CallGraph.h"
  23. #include "llvm/IR/LLVMContext.h"
  24. #include "llvm/IR/Module.h"
  25. #include "llvm/IR/Type.h"
  26. #include "llvm/IR/Operator.h"
  27. #include "llvm/IR/Instructions.h"
  28. #include "llvm/IR/InstIterator.h"
  29. #include "llvm/IR/Constants.h"
  30. #include "llvm/IR/DiagnosticInfo.h"
  31. #include "llvm/IR/DiagnosticPrinter.h"
  32. #include "llvm/ADT/BitVector.h"
  33. #include <winerror.h>
  34. #include "llvm/Support/raw_ostream.h"
  35. #include <unordered_set>
  36. #include "llvm/Analysis/LoopInfo.h"
  37. #include "llvm/IR/Dominators.h"
  38. #include "llvm/Analysis/PostDominators.h"
  39. #include "dxc/HLSL/DxilSpanAllocator.h"
  40. #include "dxc/HLSL/DxilSignatureAllocator.h"
  41. #include <algorithm>
  42. using namespace llvm;
  43. using namespace std;
  44. ///////////////////////////////////////////////////////////////////////////////
  45. // Error messages.
  46. const char *hlsl::GetValidationRuleText(ValidationRule value) {
  47. /* <py::lines('VALRULE-TEXT')>hctdb_instrhelp.get_valrule_text()</py>*/
  48. // VALRULE-TEXT:BEGIN
  49. switch(value) {
  50. case hlsl::ValidationRule::BitcodeValid: return "Module bitcode is invalid";
  51. case hlsl::ValidationRule::MetaRequired: return "TODO - Required metadata missing";
  52. case hlsl::ValidationRule::MetaKnown: return "Named metadata '%0' is unknown";
  53. case hlsl::ValidationRule::MetaUsed: return "All metadata must be used by dxil";
  54. case hlsl::ValidationRule::MetaTarget: return "Unknown target triple '%0'";
  55. case hlsl::ValidationRule::MetaWellFormed: return "TODO - Metadata must be well-formed in operand count and types";
  56. case hlsl::ValidationRule::MetaSemanticLen: return "Semantic length must be at least 1 and at most 64";
  57. case hlsl::ValidationRule::MetaInterpModeValid: return "Invalid interpolation mode for '%0'";
  58. case hlsl::ValidationRule::MetaSemaKindValid: return "Semantic kind for '%0' is invalid";
  59. case hlsl::ValidationRule::MetaNoSemanticOverlap: return "Semantic '%0' overlap at %1";
  60. case hlsl::ValidationRule::MetaSemaKindMatchesName: return "Semantic name %0 does not match System Value kind %1";
  61. case hlsl::ValidationRule::MetaDuplicateSysValue: return "System value %0 appears more than once in the same signature.";
  62. case hlsl::ValidationRule::MetaSemanticIndexMax: return "%0 semantic index exceeds maximum (%1)";
  63. case hlsl::ValidationRule::MetaSystemValueRows: return "rows for system value semantic %0 must be 1";
  64. case hlsl::ValidationRule::MetaSemanticShouldBeAllocated: return "%0 Semantic '%1' should have a valid packing location";
  65. case hlsl::ValidationRule::MetaSemanticShouldNotBeAllocated: return "%0 Semantic '%1' should have a packing location of -1";
  66. case hlsl::ValidationRule::MetaValueRange: return "Metadata value must be within range";
  67. case hlsl::ValidationRule::MetaFlagsUsage: return "Flags must match usage";
  68. case hlsl::ValidationRule::MetaDenseResIDs: return "Resource identifiers must be zero-based and dense";
  69. case hlsl::ValidationRule::MetaSignatureOverlap: return "signature element %0 at location (%1,%2) size (%3,%4) overlaps another signature element.";
  70. case hlsl::ValidationRule::MetaSignatureOutOfRange: return "signature element %0 at location (%1,%2) size (%3,%4) is out of range.";
  71. 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.";
  72. case hlsl::ValidationRule::MetaSignatureIllegalComponentOrder: return "signature element %0 at location (%1,%2) size (%3,%4) violates component ordering rule (arb < sv < sgv).";
  73. case hlsl::ValidationRule::MetaIntegerInterpMode: return "signature element %0 specifies invalid interpolation mode for integer component type.";
  74. 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.";
  75. case hlsl::ValidationRule::MetaSemanticCompType: return "%0 must be %1";
  76. case hlsl::ValidationRule::MetaClipCullMaxRows: return "ClipDistance and CullDistance occupy more than the maximum of 2 rows combined.";
  77. case hlsl::ValidationRule::MetaClipCullMaxComponents: return "ClipDistance and CullDistance use more than the maximum of 8 components combined.";
  78. case hlsl::ValidationRule::MetaSignatureCompType: return "signature %0 specifies unrecognized or invalid component type";
  79. case hlsl::ValidationRule::MetaTessellatorPartition: return "Invalid Tessellator Partitioning specified. Must be integer, pow2, fractional_odd or fractional_even.";
  80. case hlsl::ValidationRule::MetaTessellatorOutputPrimitive: return "Invalid Tessellator Output Primitive specified. Must be point, line, triangleCW or triangleCCW.";
  81. case hlsl::ValidationRule::MetaMaxTessFactor: return "Hull Shader MaxTessFactor must be [%0..%1]. %2 specified";
  82. case hlsl::ValidationRule::MetaValidSamplerMode: return "Invalid sampler mode on sampler ";
  83. case hlsl::ValidationRule::MetaFunctionAnnotation: return "Cannot find function annotation for %0";
  84. case hlsl::ValidationRule::MetaGlcNotOnAppendConsume: return "globallycoherent cannot be used with append/consume buffers";
  85. case hlsl::ValidationRule::MetaStructBufAlignment: return "structured buffer element size must be a multiple of %0 bytes (actual size %1 bytes)";
  86. case hlsl::ValidationRule::MetaStructBufAlignmentOutOfBound: return "structured buffer elements cannot be larger than %0 bytes (actual size %1 bytes)";
  87. case hlsl::ValidationRule::MetaEntryFunction: return "entrypoint not found";
  88. case hlsl::ValidationRule::MetaInvalidControlFlowHint: return "Invalid control flow hint";
  89. case hlsl::ValidationRule::MetaBranchFlatten: return "Can't use branch and flatten attributes together";
  90. case hlsl::ValidationRule::MetaForceCaseOnSwitch: return "Attribute forcecase only works for switch";
  91. case hlsl::ValidationRule::MetaControlFlowHintNotOnControlFlow: return "Control flow hint only works on control flow inst";
  92. case hlsl::ValidationRule::MetaTextureType: return "elements of typed buffers and textures must fit in four 32-bit quantities";
  93. case hlsl::ValidationRule::InstrOload: return "DXIL intrinsic overload must be valid";
  94. case hlsl::ValidationRule::InstrCallOload: return "Call to DXIL intrinsic '%0' does not match an allowed overload signature";
  95. case hlsl::ValidationRule::InstrPtrBitCast: return "Pointer type bitcast must be have same size";
  96. case hlsl::ValidationRule::InstrMinPrecisonBitCast: return "Bitcast on minprecison types is not allowed";
  97. case hlsl::ValidationRule::InstrStructBitCast: return "Bitcast on struct types is not allowed";
  98. case hlsl::ValidationRule::InstrOpConst: return "%0 of %1 must be an immediate constant";
  99. case hlsl::ValidationRule::InstrAllowed: return "Instructions must be of an allowed type";
  100. case hlsl::ValidationRule::InstrOpCodeReserved: return "Instructions must not reference reserved opcodes";
  101. case hlsl::ValidationRule::InstrOperandRange: return "expect %0 between %1, got %2";
  102. case hlsl::ValidationRule::InstrNoReadingUninitialized: return "Instructions should not read uninitialized value";
  103. case hlsl::ValidationRule::InstrNoGenericPtrAddrSpaceCast: return "Address space cast between pointer types must have one part to be generic address space";
  104. case hlsl::ValidationRule::InstrInBoundsAccess: return "Access to out-of-bounds memory is disallowed";
  105. case hlsl::ValidationRule::InstrOpConstRange: return "Constant values must be in-range for operation";
  106. case hlsl::ValidationRule::InstrImmBiasForSampleB: return "bias amount for sample_b must be in the range [%0,%1], but %2 was specified as an immediate";
  107. case hlsl::ValidationRule::InstrNoIndefiniteLog: return "No indefinite logarithm";
  108. case hlsl::ValidationRule::InstrNoIndefiniteAsin: return "No indefinite arcsine";
  109. case hlsl::ValidationRule::InstrNoIndefiniteAcos: return "No indefinite arccosine";
  110. case hlsl::ValidationRule::InstrNoIDivByZero: return "No signed integer division by zero";
  111. case hlsl::ValidationRule::InstrNoUDivByZero: return "No unsigned integer division by zero";
  112. case hlsl::ValidationRule::InstrNoIndefiniteDsxy: return "No indefinite derivative calculation";
  113. case hlsl::ValidationRule::InstrMinPrecisionNotPrecise: return "Instructions marked precise may not refer to minprecision values";
  114. case hlsl::ValidationRule::InstrOnlyOneAllocConsume: return "RWStructuredBuffers may increment or decrement their counters, but not both.";
  115. case hlsl::ValidationRule::InstrTextureOffset: return "offset texture instructions must take offset which can resolve to integer literal in the range -8 to 7";
  116. case hlsl::ValidationRule::InstrCannotPullPosition: return "%0 does not support pull-model evaluation of position";
  117. 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";
  118. case hlsl::ValidationRule::InstrResourceCoordinateMiss: return "coord uninitialized";
  119. case hlsl::ValidationRule::InstrResourceCoordinateTooMany: return "out of bound coord must be undef";
  120. case hlsl::ValidationRule::InstrResourceOffsetMiss: return "offset uninitialized";
  121. case hlsl::ValidationRule::InstrResourceOffsetTooMany: return "out of bound offset must be undef";
  122. case hlsl::ValidationRule::InstrUndefResultForGetDimension: return "GetDimensions used undef dimension %0 on %1";
  123. case hlsl::ValidationRule::InstrSamplerModeForLOD: return "lod instruction requires sampler declared in default mode";
  124. case hlsl::ValidationRule::InstrSamplerModeForSample: return "sample/_l/_d/_cl_s/gather instruction requires sampler declared in default mode";
  125. case hlsl::ValidationRule::InstrSamplerModeForSampleC: return "sample_c_*/gather_c instructions require sampler declared in comparison mode";
  126. case hlsl::ValidationRule::InstrSampleCompType: return "sample_* instructions require resource to be declared to return UNORM, SNORM or FLOAT.";
  127. case hlsl::ValidationRule::InstrBarrierModeUselessUGroup: return "sync can't specify both _ugroup and _uglobal. If both are needed, just specify _uglobal.";
  128. 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. ";
  129. case hlsl::ValidationRule::InstrBarrierModeForNonCS: return "sync in a non-Compute Shader must only sync UAV (sync_uglobal)";
  130. case hlsl::ValidationRule::InstrWriteMaskForTypedUAVStore: return "store on typed uav must write to all four components of the UAV";
  131. case hlsl::ValidationRule::InstrResourceKindForCalcLOD: return "lod requires resource declared as texture1D/2D/3D/Cube/CubeArray/1DArray/2DArray";
  132. case hlsl::ValidationRule::InstrResourceKindForSample: return "sample/_l/_d requires resource declared as texture1D/2D/3D/Cube/1DArray/2DArray/CubeArray";
  133. case hlsl::ValidationRule::InstrResourceKindForSampleC: return "samplec requires resource declared as texture1D/2D/Cube/1DArray/2DArray/CubeArray";
  134. case hlsl::ValidationRule::InstrResourceKindForGather: return "gather requires resource declared as texture/2D/Cube/2DArray/CubeArray";
  135. case hlsl::ValidationRule::InstrWriteMaskMatchValueForUAVStore: return "uav store write mask must match store value mask, write mask is %0 and store value mask is %1";
  136. case hlsl::ValidationRule::InstrResourceKindForBufferLoadStore: return "buffer load/store only works on Raw/Typed/StructuredBuffer";
  137. case hlsl::ValidationRule::InstrResourceKindForTextureStore: return "texture store only works on Texture1D/1DArray/2D/2DArray/3D";
  138. case hlsl::ValidationRule::InstrResourceKindForGetDim: return "Invalid resource kind on GetDimensions";
  139. case hlsl::ValidationRule::InstrResourceKindForTextureLoad: return "texture load only works on Texture1D/1DArray/2D/2DArray/3D/MS2D/MS2DArray";
  140. case hlsl::ValidationRule::InstrResourceClassForSamplerGather: return "sample, lod and gather should on srv resource.";
  141. case hlsl::ValidationRule::InstrResourceClassForUAVStore: return "store should on uav resource.";
  142. case hlsl::ValidationRule::InstrResourceClassForLoad: return "load can only run on UAV/SRV resource";
  143. case hlsl::ValidationRule::InstrOffsetOnUAVLoad: return "uav load don't support offset";
  144. case hlsl::ValidationRule::InstrMipOnUAVLoad: return "uav load don't support mipLevel/sampleIndex";
  145. case hlsl::ValidationRule::InstrSampleIndexForLoad2DMS: return "load on Texture2DMS/2DMSArray require sampleIndex";
  146. case hlsl::ValidationRule::InstrCoordinateCountForRawTypedBuf: return "raw/typed buffer don't need 2 coordinates";
  147. case hlsl::ValidationRule::InstrCoordinateCountForStructBuf: return "structured buffer require 2 coordinates";
  148. case hlsl::ValidationRule::InstrMipLevelForGetDimension: return "Use mip level on buffer when GetDimensions";
  149. case hlsl::ValidationRule::InstrDxilStructUser: return "Dxil struct types should only used by ExtractValue";
  150. case hlsl::ValidationRule::InstrDxilStructUserOutOfBound: return "Index out of bound when extract value from dxil struct types";
  151. case hlsl::ValidationRule::InstrHandleNotFromCreateHandle: return "Resource handle should returned by createHandle";
  152. case hlsl::ValidationRule::InstrBufferUpdateCounterOnUAV: return "BufferUpdateCounter valid only on UAV";
  153. case hlsl::ValidationRule::InstrCBufferOutOfBound: return "Cbuffer access out of bound";
  154. case hlsl::ValidationRule::InstrCBufferClassForCBufferHandle: return "Expect Cbuffer for CBufferLoad handle";
  155. case hlsl::ValidationRule::InstrFailToResloveTGSMPointer: return "TGSM pointers must originate from an unambiguous TGSM global variable.";
  156. case hlsl::ValidationRule::InstrExtractValue: return "ExtractValue should only be used on dxil struct types and cmpxchg";
  157. case hlsl::ValidationRule::InstrTGSMRaceCond: return "Race condition writing to shared memory detected, consider making this write conditional";
  158. case hlsl::ValidationRule::TypesNoVector: return "Vector type '%0' is not allowed";
  159. case hlsl::ValidationRule::TypesDefined: return "Type '%0' is not defined on DXIL primitives";
  160. case hlsl::ValidationRule::TypesIntWidth: return "Int type '%0' has an invalid width";
  161. case hlsl::ValidationRule::TypesNoMultiDim: return "Only one dimension allowed for array type";
  162. case hlsl::ValidationRule::TypesI8: return "I8 can only used as immediate value for intrinsic";
  163. case hlsl::ValidationRule::SmName: return "Unknown shader model '%0'";
  164. case hlsl::ValidationRule::SmOpcode: return "Opcode must be defined in target shader model";
  165. case hlsl::ValidationRule::SmOperand: return "Operand must be defined in target shader model";
  166. case hlsl::ValidationRule::SmSemantic: return "Semantic '%0' is invalid as %1 %2";
  167. case hlsl::ValidationRule::SmNoInterpMode: return "Interpolation mode for '%0' is set but should be undefined";
  168. case hlsl::ValidationRule::SmNoPSOutputIdx: return "Pixel shader output registers are not indexable.";
  169. 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)";
  170. case hlsl::ValidationRule::SmThreadGroupChannelRange: return "Declared Thread Group %0 size %1 outside valid range [%2..%3]";
  171. case hlsl::ValidationRule::SmMaxTheadGroup: return "Declared Thread Group Count %0 (X*Y*Z) is beyond the valid maximum of %1";
  172. case hlsl::ValidationRule::SmMaxTGSMSize: return "Total Thread Group Shared Memory storage is %0, exceeded %1";
  173. case hlsl::ValidationRule::SmROVOnlyInPS: return "RasterizerOrdered objects are only allowed in 5.0+ pixel shaders";
  174. case hlsl::ValidationRule::SmTessFactorForDomain: return "Required TessFactor for domain not found declared anywhere in Patch Constant data";
  175. case hlsl::ValidationRule::SmTessFactorSizeMatchDomain: return "TessFactor rows, columns (%0, %1) invalid for domain %2. Expected %3 rows and 1 column.";
  176. case hlsl::ValidationRule::SmInsideTessFactorSizeMatchDomain: return "InsideTessFactor rows, columns (%0, %1) invalid for domain %2. Expected %3 rows and 1 column.";
  177. case hlsl::ValidationRule::SmDomainLocationIdxOOB: return "DomainLocation component index out of bounds for the domain.";
  178. case hlsl::ValidationRule::SmHullPassThruControlPointCountMatch: return "For pass thru hull shader, input control point count must match output control point count";
  179. case hlsl::ValidationRule::SmOutputControlPointsTotalScalars: return "Total number of scalars across all HS output control points must not exceed ";
  180. 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.";
  181. 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";
  182. case hlsl::ValidationRule::SmValidDomain: return "Invalid Tessellator Domain specified. Must be isoline, tri or quad";
  183. case hlsl::ValidationRule::SmPatchConstantOnlyForHSDS: return "patch constant signature only valid in HS and DS";
  184. case hlsl::ValidationRule::SmStreamIndexRange: return "Stream index (%0) must between 0 and %1";
  185. 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";
  186. case hlsl::ValidationRule::SmPSMultipleDepthSemantic: return "Pixel Shader only allows one type of depth semantic to be declared";
  187. case hlsl::ValidationRule::SmPSTargetIndexMatchesRow: return "SV_Target semantic index must match packed row location";
  188. case hlsl::ValidationRule::SmPSTargetCol0: return "SV_Target packed location must start at column 0";
  189. case hlsl::ValidationRule::SmPSCoverageAndInnerCoverage: return "InnerCoverage and Coverage are mutually exclusive.";
  190. case hlsl::ValidationRule::SmGSOutputVertexCountRange: return "GS output vertex count must be [0..%0]. %1 specified";
  191. case hlsl::ValidationRule::SmGSInstanceCountRange: return "GS instance count must be [1..%0]. %1 specified";
  192. case hlsl::ValidationRule::SmDSInputControlPointCountRange: return "DS input control point count must be [0..%0]. %1 specified";
  193. case hlsl::ValidationRule::SmHSInputControlPointCountRange: return "HS input control point count must be [1..%0]. %1 specified";
  194. case hlsl::ValidationRule::SmOutputControlPointCountRange: return "output control point count must be [0..%0]. %1 specified";
  195. case hlsl::ValidationRule::SmGSValidInputPrimitive: return "GS input primitive unrecognized";
  196. case hlsl::ValidationRule::SmGSValidOutputPrimitiveTopology: return "GS output primitive topology unrecognized";
  197. 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.";
  198. case hlsl::ValidationRule::SmInvalidTextureKindOnUAV: return "Texture2DMS[Array] or TextureCube[Array] resources are not supported with UAVs";
  199. case hlsl::ValidationRule::SmInvalidResourceKind: return "Invalid resources kind";
  200. case hlsl::ValidationRule::SmInvalidResourceCompType: return "Invalid resource return type";
  201. case hlsl::ValidationRule::SmSampleCountOnlyOn2DMS: return "Only Texture2DMS/2DMSArray could has sample count";
  202. case hlsl::ValidationRule::SmCounterOnlyOnStructBuf: return "BufferUpdateCounter valid only on structured buffers";
  203. 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";
  204. case hlsl::ValidationRule::SmMultiStreamMustBePoint: return "Multiple GS output streams are used but '%0' is not pointlist";
  205. case hlsl::ValidationRule::SmCompletePosition: return "Not all elements of SV_Position were written";
  206. case hlsl::ValidationRule::SmUndefinedOutput: return "Not all elements of output %0 were written";
  207. case hlsl::ValidationRule::SmCSNoReturn: return "Compute shaders can't return values, outputs must be written in writable resources (UAVs).";
  208. case hlsl::ValidationRule::SmCBufferTemplateTypeMustBeStruct: return "D3D12 constant/texture buffer template element can only be a struct";
  209. case hlsl::ValidationRule::SmResourceRangeOverlap: return "Resource %0 with base %1 size %2 overlap with other resource with base %3 size %4 in space %5";
  210. case hlsl::ValidationRule::SmCBufferOffsetOverlap: return "CBuffer %0 has offset overlaps at %1";
  211. case hlsl::ValidationRule::SmCBufferElementOverflow: return "CBuffer %0 size insufficient for element at offset %1";
  212. case hlsl::ValidationRule::SmOpcodeInInvalidFunction: return "opcode '%0' should only used in '%1'";
  213. case hlsl::ValidationRule::UniNoWaveSensitiveGradient: return "Gradient operations are not affected by wave-sensitive data or control flow.";
  214. case hlsl::ValidationRule::FlowReducible: return "Execution flow must be reducible";
  215. case hlsl::ValidationRule::FlowNoRecusion: return "Recursion is not permitted";
  216. case hlsl::ValidationRule::FlowDeadLoop: return "Loop must have break";
  217. case hlsl::ValidationRule::FlowFunctionCall: return "Function %0 with parameter is not permitted, it should be inlined";
  218. case hlsl::ValidationRule::DeclDxilNsReserved: return "Declaration '%0' uses a reserved prefix";
  219. case hlsl::ValidationRule::DeclDxilFnExtern: return "External function '%0' is not a DXIL function";
  220. case hlsl::ValidationRule::DeclUsedInternal: return "Internal declaration '%0' is unused";
  221. case hlsl::ValidationRule::DeclNotUsedExternal: return "External declaration '%0' is unused";
  222. case hlsl::ValidationRule::DeclUsedExternalFunction: return "External function '%0' is unused";
  223. case hlsl::ValidationRule::DeclFnIsCalled: return "Function '%0' is used for something other than calling";
  224. case hlsl::ValidationRule::DeclFnFlattenParam: return "Type '%0' is a struct type but is used as a parameter in function '%1'";
  225. }
  226. // VALRULE-TEXT:END
  227. llvm_unreachable("invalid value");
  228. return "<unknown>";
  229. }
  230. class DxilErrorDiagnosticInfo : public DiagnosticInfo {
  231. private:
  232. const char *m_message;
  233. public:
  234. DxilErrorDiagnosticInfo(const char *str)
  235. : DiagnosticInfo(DK_FirstPluginKind, DiagnosticSeverity::DS_Error),
  236. m_message(str) { }
  237. __override void print(DiagnosticPrinter &DP) const {
  238. DP << m_message;
  239. }
  240. };
  241. static void emitDxilDiag(const LLVMContext &Ctx, const char *str) {
  242. // diagnose doesn't actually mutate anything.
  243. LLVMContext &diagCtx = const_cast<LLVMContext &>(Ctx);
  244. diagCtx.diagnose(DxilErrorDiagnosticInfo(str));
  245. }
  246. // Printing of types.
  247. static inline DiagnosticPrinter &operator<<(DiagnosticPrinter &OS, Type &T) {
  248. std::string O;
  249. raw_string_ostream OSS(O);
  250. T.print(OSS);
  251. OS << OSS.str();
  252. return OS;
  253. }
  254. namespace hlsl {
  255. struct PSExecutionInfo {
  256. bool SuperSampling = false;
  257. DXIL::SemanticKind OutputDepthKind = DXIL::SemanticKind::Invalid;
  258. const InterpolationMode *PositionInterpolationMode = nullptr;
  259. };
  260. struct ValidationContext {
  261. bool Failed = false;
  262. Module &M;
  263. Module *pDebugModule;
  264. DxilModule &DxilMod;
  265. const DataLayout &DL;
  266. DiagnosticPrinterRawOStream &DiagPrinter;
  267. PSExecutionInfo PSExec;
  268. DebugLoc LastDebugLocEmit;
  269. ValidationRule LastRuleEmit;
  270. std::unordered_set<Function *> entryFuncCallSet;
  271. std::unordered_set<Function *> patchConstFuncCallSet;
  272. std::unordered_map<unsigned, bool> UavCounterIncMap;
  273. bool hasOutputPosition[DXIL::kNumOutputStreams];
  274. unsigned OutputPositionMask[DXIL::kNumOutputStreams];
  275. std::vector<unsigned> outputCols;
  276. std::vector<unsigned> patchConstCols;
  277. unsigned domainLocSize;
  278. const unsigned kDxilControlFlowHintMDKind;
  279. const unsigned kDxilPreciseMDKind;
  280. const unsigned kLLVMLoopMDKind;
  281. bool m_bCoverageIn, m_bInnerCoverageIn;
  282. ValidationContext(Module &llvmModule, Module *DebugModule,
  283. DxilModule &dxilModule,
  284. DiagnosticPrinterRawOStream &DiagPrn)
  285. : M(llvmModule), pDebugModule(DebugModule), DxilMod(dxilModule),
  286. DL(llvmModule.getDataLayout()),
  287. kDxilControlFlowHintMDKind(llvmModule.getContext().getMDKindID(
  288. DxilMDHelper::kDxilControlFlowHintMDName)),
  289. kDxilPreciseMDKind(llvmModule.getContext().getMDKindID(
  290. DxilMDHelper::kDxilPreciseAttributeMDName)),
  291. kLLVMLoopMDKind(llvmModule.getContext().getMDKindID("llvm.loop")),
  292. DiagPrinter(DiagPrn), LastRuleEmit((ValidationRule)-1),
  293. m_bCoverageIn(false), m_bInnerCoverageIn(false) {
  294. for (unsigned i = 0; i < DXIL::kNumOutputStreams; i++) {
  295. hasOutputPosition[i] = false;
  296. OutputPositionMask[i] = 0;
  297. }
  298. outputCols.resize(DxilMod.GetOutputSignature().GetElements().size(), 0);
  299. patchConstCols.resize(DxilMod.GetPatchConstantSignature().GetElements().size(), 0);
  300. }
  301. // Provide direct access to the raw_ostream in DiagPrinter.
  302. raw_ostream &DiagStream() {
  303. struct DiagnosticPrinterRawOStream_Pub : public DiagnosticPrinterRawOStream {
  304. public:
  305. raw_ostream &DiagStream() { return Stream; }
  306. };
  307. DiagnosticPrinterRawOStream_Pub* p = (DiagnosticPrinterRawOStream_Pub*)&DiagPrinter;
  308. return p->DiagStream();
  309. }
  310. void EmitGlobalValueError(GlobalValue *GV, ValidationRule rule) {
  311. EmitFormatError(rule, { GV->getName().str().c_str() });
  312. }
  313. // This is the least desirable mechanism, as it has no context.
  314. void EmitError(ValidationRule rule) {
  315. DiagPrinter << GetValidationRuleText(rule) << '\n';
  316. Failed = true;
  317. }
  318. void FormatRuleText(std::string &ruleText, ArrayRef<const char *> args) {
  319. // Consider changing const char * to StringRef
  320. for (unsigned i = 0; i < args.size(); i++) {
  321. std::string argIdx = "%" + std::to_string(i);
  322. const char *pArg = args[i];
  323. if (pArg == nullptr)
  324. pArg = "<null>";
  325. std::string::size_type offset = ruleText.find(argIdx);
  326. if (offset == std::string::npos)
  327. continue;
  328. unsigned size = argIdx.size();
  329. ruleText.replace(offset, size, args[i]);
  330. }
  331. }
  332. void EmitFormatError(ValidationRule rule, ArrayRef<const char *> args) {
  333. std::string ruleText = GetValidationRuleText(rule);
  334. FormatRuleText(ruleText, args);
  335. DiagPrinter << ruleText << '\n';
  336. Failed = true;
  337. }
  338. void EmitMetaError(Metadata *Meta, ValidationRule rule) {
  339. DiagPrinter << GetValidationRuleText(rule);
  340. Meta->print(DiagStream(), &M);
  341. DiagPrinter << '\n';
  342. Failed = true;
  343. }
  344. void EmitResourceError(const hlsl::DxilResourceBase *Res, ValidationRule rule) {
  345. DiagPrinter << GetValidationRuleText(rule);
  346. DiagPrinter << '\'' << Res->GetGlobalName() << '\'';
  347. DiagPrinter << '\n';
  348. Failed = true;
  349. }
  350. void EmitResourceFormatError(const hlsl::DxilResourceBase *Res,
  351. ValidationRule rule,
  352. ArrayRef<const char *> args) {
  353. std::string ruleText = GetValidationRuleText(rule);
  354. FormatRuleText(ruleText, args);
  355. DiagPrinter << ruleText;
  356. DiagPrinter << '\'' << Res->GetGlobalName() << '\'';
  357. DiagPrinter << '\n';
  358. Failed = true;
  359. }
  360. bool IsDebugFunctionCall(Instruction *I) {
  361. CallInst *CI = dyn_cast<CallInst>(I);
  362. return CI && CI->getCalledFunction()->getName().startswith("llvm.dbg.");
  363. }
  364. DebugLoc GetDebugLoc(Instruction *I) {
  365. DXASSERT_NOMSG(I);
  366. if (pDebugModule) {
  367. // Look up the matching instruction in the debug module.
  368. llvm::Function *Fn = I->getParent()->getParent();
  369. llvm::Function *DbgFn = pDebugModule->getFunction(Fn->getName());
  370. if (DbgFn) {
  371. // Linear lookup, but then again, failing validation is rare.
  372. inst_iterator it = inst_begin(Fn);
  373. inst_iterator dbg_it = inst_begin(DbgFn);
  374. while (IsDebugFunctionCall(&*dbg_it)) ++dbg_it;
  375. while (&*it != I) {
  376. ++it;
  377. ++dbg_it;
  378. while (IsDebugFunctionCall(&*dbg_it)) ++dbg_it;
  379. }
  380. return dbg_it->getDebugLoc();
  381. }
  382. }
  383. return I->getDebugLoc();
  384. }
  385. bool EmitInstrLoc(Instruction *I, ValidationRule Rule) {
  386. const DebugLoc &L = GetDebugLoc(I);
  387. if (L) {
  388. // Instructions that get scalarized will likely hit
  389. // this case. Avoid redundant diagnostic messages.
  390. if (Rule == LastRuleEmit && L == LastDebugLocEmit) {
  391. return false;
  392. }
  393. LastRuleEmit = Rule;
  394. LastDebugLocEmit = L;
  395. L.print(DiagStream());
  396. DiagPrinter << ' ';
  397. return true;
  398. }
  399. BasicBlock *BB = I->getParent();
  400. Function *F = BB->getParent();
  401. DiagPrinter << "at " << I;
  402. DiagPrinter << " inside block ";
  403. if (!BB->getName().empty()) {
  404. DiagPrinter << BB->getName();
  405. }
  406. else {
  407. unsigned idx = 0;
  408. for (auto i = F->getBasicBlockList().begin(),
  409. e = F->getBasicBlockList().end(); i != e; ++i) {
  410. if (BB == i) {
  411. break;
  412. }
  413. }
  414. DiagPrinter << "#" << idx;
  415. }
  416. DiagPrinter << " of function " << *F << ' ';
  417. return true;
  418. }
  419. void EmitInstrError(Instruction *I, ValidationRule rule) {
  420. if (!EmitInstrLoc(I, rule)) return;
  421. DiagPrinter << GetValidationRuleText(rule);
  422. DiagPrinter << '\n';
  423. Failed = true;
  424. }
  425. void EmitInstrFormatError(Instruction *I, ValidationRule rule, ArrayRef<const char *> args) {
  426. if (!EmitInstrLoc(I, rule)) return;
  427. std::string ruleText = GetValidationRuleText(rule);
  428. FormatRuleText(ruleText, args);
  429. DiagPrinter << ruleText;
  430. DiagPrinter << '\n';
  431. Failed = true;
  432. }
  433. void EmitOperandOutOfRange(Instruction *I, const char *name, const char * range, const char * v) {
  434. if (!EmitInstrLoc(I, ValidationRule::InstrOperandRange)) return;
  435. std::string ruleText = GetValidationRuleText(ValidationRule::InstrOperandRange);
  436. FormatRuleText(ruleText, {name, range, v});
  437. DiagPrinter << ruleText;
  438. DiagPrinter << '\n';
  439. Failed = true;
  440. }
  441. void EmitSignatureError(DxilSignatureElement *SE, ValidationRule rule) {
  442. EmitFormatError(rule, { SE->GetName() });
  443. }
  444. void EmitTypeError(Type *Ty, ValidationRule rule) {
  445. std::string O;
  446. raw_string_ostream OSS(O);
  447. Ty->print(OSS);
  448. EmitFormatError(rule, { OSS.str().c_str() });
  449. }
  450. };
  451. static bool ValidateOpcodeInProfile(DXIL::OpCode opcode,
  452. const ShaderModel *pSM) {
  453. unsigned op = (unsigned)opcode;
  454. /* <py::lines('VALOPCODESM-TEXT')>hctdb_instrhelp.get_valopcode_sm_text()</py>*/
  455. // VALOPCODESM-TEXT:BEGIN
  456. // Instructions: ThreadId=95, GroupId=96, ThreadIdInGroup=97,
  457. // FlattenedThreadIdInGroup=98
  458. if (95 <= op && op <= 98)
  459. return pSM->IsCS();
  460. // Instructions: DomainLocation=107
  461. if (op == 107)
  462. return pSM->IsDS();
  463. // Instructions: LoadOutputControlPoint=105, LoadPatchConstant=106
  464. if (105 <= op && op <= 106)
  465. return pSM->IsDS() || pSM->IsHS();
  466. // Instructions: EmitStream=99, CutStream=100, EmitThenCutStream=101,
  467. // GSInstanceID=102
  468. if (99 <= op && op <= 102)
  469. return pSM->IsGS();
  470. // Instructions: PrimitiveID=110
  471. if (op == 110)
  472. return pSM->IsGS() || pSM->IsDS() || pSM->IsHS() || pSM->IsPS();
  473. // Instructions: StorePatchConstant=108, OutputControlPointID=109
  474. if (108 <= op && op <= 109)
  475. return pSM->IsHS();
  476. // Instructions: Sample=62, SampleBias=63, SampleCmp=66, SampleCmpLevelZero=67,
  477. // RenderTargetGetSamplePosition=78, RenderTargetGetSampleCount=79,
  478. // CalculateLOD=83, Discard=84, DerivCoarseX=85, DerivCoarseY=86,
  479. // DerivFineX=87, DerivFineY=88, EvalSnapped=89, EvalSampleIndex=90,
  480. // EvalCentroid=91, SampleIndex=92, Coverage=93, InnerCoverage=94
  481. if (62 <= op && op <= 63 || 66 <= op && op <= 67 || 78 <= op && op <= 79 || 83 <= op && op <= 94)
  482. return pSM->IsPS();
  483. return true;
  484. // VALOPCODESM-TEXT:END
  485. }
  486. static unsigned ValidateSignatureRowCol(Instruction *I, DxilSignatureElement &SE,
  487. Value *rowVal, Value *colVal,
  488. ValidationContext &ValCtx) {
  489. if (ConstantInt *constRow = dyn_cast<ConstantInt>(rowVal)) {
  490. unsigned row = constRow->getLimitedValue();
  491. if (row >= SE.GetRows()) {
  492. ValCtx.EmitInstrError(I, ValidationRule::InstrOperandRange);
  493. }
  494. }
  495. if (!isa<ConstantInt>(colVal)) {
  496. // col must be const
  497. ValCtx.EmitInstrFormatError(I, ValidationRule::InstrOpConst,
  498. {"Col", "LoadInput/StoreOutput"});
  499. return 0;
  500. }
  501. unsigned col = cast<ConstantInt>(colVal)->getLimitedValue();
  502. if (col > SE.GetCols()) {
  503. ValCtx.EmitInstrError(I, ValidationRule::InstrOperandRange);
  504. } else {
  505. if (SE.IsOutput())
  506. ValCtx.outputCols[SE.GetID()] |= 1 << col;
  507. if (SE.IsPatchConstant())
  508. ValCtx.patchConstCols[SE.GetID()] |= 1 << col;
  509. }
  510. return col;
  511. }
  512. static DxilSignatureElement *ValidateSignatureAccess(Instruction *I, DxilSignature &sig,
  513. Value *sigID, Value *rowVal, Value *colVal,
  514. ValidationContext &ValCtx) {
  515. if (!isa<ConstantInt>(sigID)) {
  516. // inputID must be const
  517. ValCtx.EmitInstrFormatError(I, ValidationRule::InstrOpConst,
  518. {"SignatureID", "LoadInput/StoreOutput"});
  519. return nullptr;
  520. }
  521. unsigned SEIdx = cast<ConstantInt>(sigID)->getLimitedValue();
  522. if (sig.GetElements().size() <= SEIdx) {
  523. ValCtx.EmitInstrError(I, ValidationRule::InstrOpConstRange);
  524. return nullptr;
  525. }
  526. DxilSignatureElement &SE = sig.GetElement(SEIdx);
  527. bool isOutput = sig.IsOutput();
  528. unsigned col = ValidateSignatureRowCol(I, SE, rowVal, colVal, ValCtx);
  529. if (isOutput && SE.GetSemantic()->GetKind() == DXIL::SemanticKind::Position) {
  530. unsigned mask = ValCtx.OutputPositionMask[SE.GetOutputStream()];
  531. mask |= 1<<col;
  532. if (SE.GetOutputStream() < DXIL::kNumOutputStreams)
  533. ValCtx.OutputPositionMask[SE.GetOutputStream()] = mask;
  534. }
  535. return &SE;
  536. }
  537. static DXIL::SamplerKind GetSamplerKind(Value *samplerHandle, ValidationContext &ValCtx) {
  538. if (!isa<CallInst>(samplerHandle)) {
  539. ValCtx.EmitError(ValidationRule::InstrHandleNotFromCreateHandle);
  540. return DXIL::SamplerKind::Invalid;
  541. }
  542. DxilInst_CreateHandle createHandle(cast<CallInst>(samplerHandle));
  543. if (!createHandle) {
  544. ValCtx.EmitInstrError(cast<CallInst>(samplerHandle), ValidationRule::InstrHandleNotFromCreateHandle);
  545. return DXIL::SamplerKind::Invalid;
  546. }
  547. Value *resClass = createHandle.get_resourceClass();
  548. if (!isa<ConstantInt>(resClass)) {
  549. return DXIL::SamplerKind::Invalid;
  550. }
  551. if (createHandle.get_resourceClass_val() != static_cast<unsigned>(DXIL::ResourceClass::Sampler)) {
  552. // must be sampler.
  553. return DXIL::SamplerKind::Invalid;
  554. }
  555. Value *rangeIndex = createHandle.get_rangeId();
  556. if (!isa<ConstantInt>(rangeIndex)) {
  557. // must be constant
  558. return DXIL::SamplerKind::Invalid;
  559. }
  560. unsigned samplerIndex = cast<ConstantInt>(rangeIndex)->getLimitedValue();
  561. auto &samplers = ValCtx.DxilMod.GetSamplers();
  562. if (samplerIndex >= samplers.size()) {
  563. return DXIL::SamplerKind::Invalid;
  564. }
  565. DxilSampler *sampler = samplers[samplerIndex].get();
  566. Value *index = createHandle.get_index();
  567. ConstantInt *cIndex = dyn_cast<ConstantInt>(index);
  568. if (!sampler->GetGlobalSymbol()->getType()->getPointerElementType()->isArrayTy()) {
  569. if (!cIndex) {
  570. // index must be 0 for none array resource.
  571. return DXIL::SamplerKind::Invalid;
  572. }
  573. }
  574. if (cIndex) {
  575. unsigned index = cIndex->getLimitedValue();
  576. if (index < sampler->GetLowerBound() || index > sampler->GetUpperBound()) {
  577. // index out of range.
  578. return DXIL::SamplerKind::Invalid;
  579. }
  580. }
  581. return sampler->GetSamplerKind();
  582. }
  583. static DXIL::ResourceKind GetResourceKindAndCompTy(Value *handle, DXIL::ComponentType &CompTy, DXIL::ResourceClass &ResClass,
  584. unsigned &resIndex,
  585. ValidationContext &ValCtx) {
  586. CompTy = DXIL::ComponentType::Invalid;
  587. ResClass = DXIL::ResourceClass::Invalid;
  588. if (!isa<CallInst>(handle)) {
  589. ValCtx.EmitError(ValidationRule::InstrHandleNotFromCreateHandle);
  590. return DXIL::ResourceKind::Invalid;
  591. }
  592. DxilInst_CreateHandle createHandle(cast<CallInst>(handle));
  593. if (!createHandle) {
  594. ValCtx.EmitInstrError(cast<CallInst>(handle), ValidationRule::InstrHandleNotFromCreateHandle);
  595. return DXIL::ResourceKind::Invalid;
  596. }
  597. Value *resourceClass = createHandle.get_resourceClass();
  598. if (!isa<ConstantInt>(resourceClass)) {
  599. return DXIL::ResourceKind::Invalid;
  600. }
  601. ResClass = static_cast<DXIL::ResourceClass>(createHandle.get_resourceClass_val());
  602. switch (ResClass) {
  603. case DXIL::ResourceClass::SRV:
  604. case DXIL::ResourceClass::UAV:
  605. break;
  606. case DXIL::ResourceClass::CBuffer:
  607. return DXIL::ResourceKind::CBuffer;
  608. case DXIL::ResourceClass::Sampler:
  609. return DXIL::ResourceKind::Sampler;
  610. default:
  611. // Emit invalid res class
  612. return DXIL::ResourceKind::Invalid;
  613. }
  614. Value *rangeIndex = createHandle.get_rangeId();
  615. if (!isa<ConstantInt>(rangeIndex)) {
  616. // must be constant
  617. return DXIL::ResourceKind::Invalid;
  618. }
  619. resIndex = cast<ConstantInt>(rangeIndex)->getLimitedValue();
  620. DxilResource *res = nullptr;
  621. if (ResClass == DXIL::ResourceClass::UAV) {
  622. auto &resources = ValCtx.DxilMod.GetUAVs();
  623. if (resIndex >= resources.size()) {
  624. return DXIL::ResourceKind::Invalid;
  625. }
  626. res = resources[resIndex].get();
  627. } else {
  628. if (ResClass != DXIL::ResourceClass::SRV) {
  629. return DXIL::ResourceKind::Invalid;
  630. }
  631. auto &resources = ValCtx.DxilMod.GetSRVs();
  632. if (resIndex >= resources.size()) {
  633. return DXIL::ResourceKind::Invalid;
  634. }
  635. res = resources[resIndex].get();
  636. }
  637. CompTy = res->GetCompType().GetKind();
  638. Value *index = createHandle.get_index();
  639. ConstantInt *cIndex = dyn_cast<ConstantInt>(index);
  640. if (!res->GetGlobalSymbol()->getType()->getPointerElementType()->isArrayTy()) {
  641. if (!cIndex) {
  642. // index must be 0 for none array resource.
  643. return DXIL::ResourceKind::Invalid;
  644. }
  645. }
  646. if (cIndex) {
  647. unsigned index = cIndex->getLimitedValue();
  648. if (index < res->GetLowerBound() || index > res->GetUpperBound()) {
  649. // index out of range.
  650. return DXIL::ResourceKind::Invalid;
  651. }
  652. }
  653. return res->GetKind();
  654. }
  655. struct ResRetUsage {
  656. bool x;
  657. bool y;
  658. bool z;
  659. bool w;
  660. bool status;
  661. ResRetUsage() : x(false), y(false), z(false), w(false), status(false) {}
  662. };
  663. static void CollectGetDimResRetUsage(ResRetUsage &usage, Instruction *ResRet,
  664. ValidationContext &ValCtx) {
  665. const unsigned kMaxResRetElementIndex = 5;
  666. for (User *U : ResRet->users()) {
  667. if (ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(U)) {
  668. for (unsigned idx : EVI->getIndices()) {
  669. switch (idx) {
  670. case 0:
  671. usage.x = true;
  672. break;
  673. case 1:
  674. usage.y = true;
  675. break;
  676. case 2:
  677. usage.z = true;
  678. break;
  679. case 3:
  680. usage.w = true;
  681. break;
  682. case 4:
  683. usage.status = true;
  684. break;
  685. default:
  686. // Emit index out of bound.
  687. ValCtx.EmitInstrError(EVI,
  688. ValidationRule::InstrDxilStructUserOutOfBound);
  689. break;
  690. }
  691. }
  692. } else if (PHINode *PHI = dyn_cast<PHINode>(U)) {
  693. CollectGetDimResRetUsage(usage, PHI, ValCtx);
  694. } else {
  695. Instruction *User = cast<Instruction>(U);
  696. ValCtx.EmitInstrError(User, ValidationRule::InstrDxilStructUser);
  697. }
  698. }
  699. }
  700. static void ValidateResourceCoord(CallInst *CI, DXIL::ResourceKind resKind,
  701. ArrayRef<Value *> coords,
  702. ValidationContext &ValCtx) {
  703. const unsigned kMaxNumCoords = 4;
  704. unsigned numCoords = DxilResource::GetNumCoords(resKind);
  705. for (unsigned i = 0; i < kMaxNumCoords; i++) {
  706. if (i < numCoords) {
  707. if (isa<UndefValue>(coords[i])) {
  708. ValCtx.EmitInstrError(CI, ValidationRule::InstrResourceCoordinateMiss);
  709. }
  710. } else {
  711. if (!isa<UndefValue>(coords[i])) {
  712. ValCtx.EmitInstrError(CI, ValidationRule::InstrResourceCoordinateTooMany);
  713. }
  714. }
  715. }
  716. }
  717. static void ValidateCalcLODResourceDimensionCoord(CallInst *CI, DXIL::ResourceKind resKind,
  718. ArrayRef<Value *> coords,
  719. ValidationContext &ValCtx) {
  720. const unsigned kMaxNumDimCoords = 3;
  721. unsigned numCoords = DxilResource::GetNumDimensionsForCalcLOD(resKind);
  722. for (unsigned i = 0; i < kMaxNumDimCoords; i++) {
  723. if (i < numCoords) {
  724. if (isa<UndefValue>(coords[i])) {
  725. ValCtx.EmitInstrError(CI, ValidationRule::InstrResourceCoordinateMiss);
  726. }
  727. } else {
  728. if (!isa<UndefValue>(coords[i])) {
  729. ValCtx.EmitInstrError(CI, ValidationRule::InstrResourceCoordinateTooMany);
  730. }
  731. }
  732. }
  733. }
  734. static void ValidateResourceOffset(CallInst *CI, DXIL::ResourceKind resKind,
  735. ArrayRef<Value *> offsets,
  736. ValidationContext &ValCtx) {
  737. const unsigned kMaxNumOffsets = 3;
  738. unsigned numOffsets = DxilResource::GetNumOffsets(resKind);
  739. bool hasOffset = !isa<UndefValue>(offsets[0]);
  740. auto validateOffset = [&](Value *offset) {
  741. if (ConstantInt *cOffset = dyn_cast<ConstantInt>(offset)) {
  742. int offset = cOffset->getValue().getSExtValue();
  743. if (offset > 7 || offset < -8) {
  744. ValCtx.EmitInstrError(CI, ValidationRule::InstrTextureOffset);
  745. }
  746. } else {
  747. ValCtx.EmitInstrError(CI, ValidationRule::InstrTextureOffset);
  748. }
  749. };
  750. if (hasOffset) {
  751. validateOffset(offsets[0]);
  752. }
  753. for (unsigned i = 1; i < kMaxNumOffsets; i++) {
  754. if (i < numOffsets) {
  755. if (hasOffset) {
  756. if (isa<UndefValue>(offsets[i]))
  757. ValCtx.EmitInstrError(CI, ValidationRule::InstrResourceOffsetMiss);
  758. else
  759. validateOffset(offsets[i]);
  760. }
  761. } else {
  762. if (!isa<UndefValue>(offsets[i])) {
  763. ValCtx.EmitInstrError(CI, ValidationRule::InstrResourceOffsetTooMany);
  764. }
  765. }
  766. }
  767. }
  768. static void ValidateSampleInst(CallInst *CI, Value *srvHandle, Value *samplerHandle,
  769. ArrayRef<Value *> coords,
  770. ArrayRef<Value *> offsets,
  771. bool IsSampleC,
  772. ValidationContext &ValCtx) {
  773. if (!IsSampleC) {
  774. if (GetSamplerKind(samplerHandle, ValCtx) != DXIL::SamplerKind::Default) {
  775. ValCtx.EmitInstrError(CI, ValidationRule::InstrSamplerModeForSample);
  776. }
  777. } else {
  778. if (GetSamplerKind(samplerHandle, ValCtx) !=
  779. DXIL::SamplerKind::Comparison) {
  780. ValCtx.EmitInstrError(CI, ValidationRule::InstrSamplerModeForSampleC);
  781. }
  782. }
  783. DXIL::ComponentType compTy;
  784. DXIL::ResourceClass resClass;
  785. unsigned resIndex;
  786. DXIL::ResourceKind resKind =
  787. GetResourceKindAndCompTy(srvHandle, compTy, resClass, resIndex, ValCtx);
  788. bool isSampleCompTy = compTy == DXIL::ComponentType::F32;
  789. isSampleCompTy |= compTy == DXIL::ComponentType::SNormF32;
  790. isSampleCompTy |= compTy == DXIL::ComponentType::UNormF32;
  791. if (!isSampleCompTy) {
  792. ValCtx.EmitInstrError(CI, ValidationRule::InstrSampleCompType);
  793. }
  794. if (resClass != DXIL::ResourceClass::SRV) {
  795. ValCtx.EmitInstrError(CI, ValidationRule::InstrResourceClassForSamplerGather);
  796. }
  797. ValidationRule rule = ValidationRule::InstrResourceKindForSample;
  798. if (IsSampleC) {
  799. rule = ValidationRule::InstrResourceKindForSampleC;
  800. }
  801. switch (resKind) {
  802. case DXIL::ResourceKind::Texture1D:
  803. case DXIL::ResourceKind::Texture1DArray:
  804. case DXIL::ResourceKind::Texture2D:
  805. case DXIL::ResourceKind::Texture2DArray:
  806. case DXIL::ResourceKind::TextureCube:
  807. case DXIL::ResourceKind::TextureCubeArray:
  808. break;
  809. case DXIL::ResourceKind::Texture3D:
  810. if (IsSampleC) {
  811. ValCtx.EmitInstrError(CI, rule);
  812. }
  813. break;
  814. default:
  815. ValCtx.EmitInstrError(CI, rule);
  816. return;
  817. }
  818. // Coord match resource kind.
  819. ValidateResourceCoord(CI, resKind, coords, ValCtx);
  820. // Offset match resource kind.
  821. ValidateResourceOffset(CI, resKind, offsets, ValCtx);
  822. }
  823. static void ValidateGather(CallInst *CI, Value *srvHandle, Value *samplerHandle,
  824. ArrayRef<Value *> coords,
  825. ArrayRef<Value *> offsets,
  826. bool IsSampleC,
  827. ValidationContext &ValCtx) {
  828. if (!IsSampleC) {
  829. if (GetSamplerKind(samplerHandle, ValCtx) != DXIL::SamplerKind::Default) {
  830. ValCtx.EmitInstrError(CI, ValidationRule::InstrSamplerModeForSample);
  831. }
  832. } else {
  833. if (GetSamplerKind(samplerHandle, ValCtx) !=
  834. DXIL::SamplerKind::Comparison) {
  835. ValCtx.EmitInstrError(CI, ValidationRule::InstrSamplerModeForSampleC);
  836. }
  837. }
  838. DXIL::ComponentType compTy;
  839. DXIL::ResourceClass resClass;
  840. unsigned resIndex;
  841. DXIL::ResourceKind resKind =
  842. GetResourceKindAndCompTy(srvHandle, compTy, resClass, resIndex, ValCtx);
  843. if (resClass != DXIL::ResourceClass::SRV) {
  844. ValCtx.EmitInstrError(CI, ValidationRule::InstrResourceClassForSamplerGather);
  845. return;
  846. }
  847. // Coord match resource kind.
  848. ValidateResourceCoord(CI, resKind, coords, ValCtx);
  849. // Offset match resource kind.
  850. switch (resKind) {
  851. case DXIL::ResourceKind::Texture2D:
  852. case DXIL::ResourceKind::Texture2DArray: {
  853. bool hasOffset = !isa<UndefValue>(offsets[0]);
  854. if (hasOffset) {
  855. if (isa<UndefValue>(offsets[1])) {
  856. ValCtx.EmitInstrError(CI, ValidationRule::InstrResourceOffsetMiss);
  857. }
  858. }
  859. } break;
  860. case DXIL::ResourceKind::TextureCube:
  861. case DXIL::ResourceKind::TextureCubeArray: {
  862. if (!isa<UndefValue>(offsets[0])) {
  863. ValCtx.EmitInstrError(CI, ValidationRule::InstrResourceOffsetTooMany);
  864. }
  865. if (!isa<UndefValue>(offsets[1])) {
  866. ValCtx.EmitInstrError(CI, ValidationRule::InstrResourceOffsetTooMany);
  867. }
  868. } break;
  869. default:
  870. // Invalid resource type for gather.
  871. ValCtx.EmitInstrError(CI, ValidationRule::InstrResourceKindForGather);
  872. break;
  873. }
  874. }
  875. static unsigned StoreValueToMask(ArrayRef<Value *> vals) {
  876. unsigned mask = 0;
  877. for (unsigned i = 0; i < 4; i++) {
  878. if (!isa<UndefValue>(vals[i])) {
  879. mask |= 1<<i;
  880. }
  881. }
  882. return mask;
  883. }
  884. static int GetCBufSize(Value *cbHandle, ValidationContext &ValCtx) {
  885. DxilInst_CreateHandle createHandle(cast<CallInst>(cbHandle));
  886. if (!createHandle) {
  887. ValCtx.EmitInstrError(cast<CallInst>(cbHandle),
  888. ValidationRule::InstrHandleNotFromCreateHandle);
  889. return -1;
  890. }
  891. Value *resourceClass = createHandle.get_resourceClass();
  892. if (!isa<ConstantInt>(resourceClass)) {
  893. ValCtx.EmitInstrError(cast<CallInst>(cbHandle),
  894. ValidationRule::InstrOpConstRange);
  895. return -1;
  896. }
  897. if (static_cast<DXIL::ResourceClass>(createHandle.get_resourceClass_val()) !=
  898. DXIL::ResourceClass::CBuffer) {
  899. ValCtx.EmitInstrError(cast<CallInst>(cbHandle), ValidationRule::InstrCBufferClassForCBufferHandle);
  900. return -1;
  901. }
  902. Value *rangeIndex = createHandle.get_rangeId();
  903. if (!isa<ConstantInt>(rangeIndex)) {
  904. ValCtx.EmitInstrError(cast<CallInst>(cbHandle),
  905. ValidationRule::InstrOpConstRange);
  906. return -1;
  907. }
  908. DxilCBuffer &CB = ValCtx.DxilMod.GetCBuffer(
  909. cast<ConstantInt>(rangeIndex)->getLimitedValue());
  910. return CB.GetSize();
  911. }
  912. static unsigned GetNumVertices(DXIL::InputPrimitive inputPrimitive) {
  913. const unsigned InputPrimitiveVertexTab[] = {
  914. 0, // Undefined = 0,
  915. 1, // Point = 1,
  916. 2, // Line = 2,
  917. 3, // Triangle = 3,
  918. 0, // Reserved4 = 4,
  919. 0, // Reserved5 = 5,
  920. 4, // LineWithAdjacency = 6,
  921. 6, // TriangleWithAdjacency = 7,
  922. 1, // ControlPointPatch1 = 8,
  923. 2, // ControlPointPatch2 = 9,
  924. 3, // ControlPointPatch3 = 10,
  925. 4, // ControlPointPatch4 = 11,
  926. 5, // ControlPointPatch5 = 12,
  927. 6, // ControlPointPatch6 = 13,
  928. 7, // ControlPointPatch7 = 14,
  929. 8, // ControlPointPatch8 = 15,
  930. 9, // ControlPointPatch9 = 16,
  931. 10, // ControlPointPatch10 = 17,
  932. 11, // ControlPointPatch11 = 18,
  933. 12, // ControlPointPatch12 = 19,
  934. 13, // ControlPointPatch13 = 20,
  935. 14, // ControlPointPatch14 = 21,
  936. 15, // ControlPointPatch15 = 22,
  937. 16, // ControlPointPatch16 = 23,
  938. 17, // ControlPointPatch17 = 24,
  939. 18, // ControlPointPatch18 = 25,
  940. 19, // ControlPointPatch19 = 26,
  941. 20, // ControlPointPatch20 = 27,
  942. 21, // ControlPointPatch21 = 28,
  943. 22, // ControlPointPatch22 = 29,
  944. 23, // ControlPointPatch23 = 30,
  945. 24, // ControlPointPatch24 = 31,
  946. 25, // ControlPointPatch25 = 32,
  947. 26, // ControlPointPatch26 = 33,
  948. 27, // ControlPointPatch27 = 34,
  949. 28, // ControlPointPatch28 = 35,
  950. 29, // ControlPointPatch29 = 36,
  951. 30, // ControlPointPatch30 = 37,
  952. 31, // ControlPointPatch31 = 38,
  953. 32, // ControlPointPatch32 = 39,
  954. 0, // LastEntry,
  955. };
  956. unsigned primitiveIdx = static_cast<unsigned>(inputPrimitive);
  957. return InputPrimitiveVertexTab[primitiveIdx];
  958. }
  959. static void ValidateDxilOperationCallInProfile(CallInst *CI,
  960. DXIL::OpCode opcode,
  961. const ShaderModel *pSM,
  962. ValidationContext &ValCtx) {
  963. switch (opcode) {
  964. case DXIL::OpCode::LoadInput: {
  965. Value *inputID = CI->getArgOperand(DXIL::OperandIndex::kLoadInputIDOpIdx);
  966. DxilSignature &inputSig = ValCtx.DxilMod.GetInputSignature();
  967. Value *row = CI->getArgOperand(DXIL::OperandIndex::kLoadInputRowOpIdx);
  968. Value *col = CI->getArgOperand(DXIL::OperandIndex::kLoadInputColOpIdx);
  969. ValidateSignatureAccess(CI, inputSig, inputID, row, col, ValCtx);
  970. // Check vertexID in ps/vs. and none array input.
  971. Value *vertexID =
  972. CI->getArgOperand(DXIL::OperandIndex::kLoadInputVertexIDOpIdx);
  973. bool usedVertexID = vertexID && !isa<UndefValue>(vertexID);
  974. if (pSM->IsVS() || pSM->IsPS()) {
  975. if (usedVertexID) {
  976. // use vertexID in VS/PS input.
  977. ValCtx.EmitInstrError(CI, ValidationRule::SmOperand);
  978. return;
  979. }
  980. } else {
  981. if (ConstantInt *cVertexID = dyn_cast<ConstantInt>(vertexID)) {
  982. int immVertexID = cVertexID->getValue().getLimitedValue();
  983. if (cVertexID->getValue().isNegative()) {
  984. immVertexID = cVertexID->getValue().getSExtValue();
  985. }
  986. const int low = 0;
  987. int high = 0;
  988. if (pSM->IsGS()) {
  989. DXIL::InputPrimitive inputPrimitive =
  990. ValCtx.DxilMod.GetInputPrimitive();
  991. high = GetNumVertices(inputPrimitive);
  992. } else if (pSM->IsDS()) {
  993. high = ValCtx.DxilMod.GetInputControlPointCount();
  994. } else if (pSM->IsHS()) {
  995. high = ValCtx.DxilMod.GetInputControlPointCount();
  996. } else {
  997. ValCtx.EmitFormatError(ValidationRule::SmOpcodeInInvalidFunction,
  998. {"LoadInput", "VS/HS/DS/GS/PS"});
  999. }
  1000. if (immVertexID < low || immVertexID >= high) {
  1001. std::string range = std::to_string(low)+"~"+
  1002. std::to_string(high);
  1003. ValCtx.EmitOperandOutOfRange(CI, "VertexID", range.c_str(),
  1004. std::to_string(immVertexID).c_str());
  1005. }
  1006. }
  1007. }
  1008. } break;
  1009. case DXIL::OpCode::DomainLocation: {
  1010. Value *colValue = CI->getArgOperand(DXIL::OperandIndex::kDomainLocationColOpIdx);
  1011. if (!isa<ConstantInt>(colValue)) {
  1012. // col must be const
  1013. ValCtx.EmitInstrFormatError(CI, ValidationRule::InstrOpConst,
  1014. {"Col", "DomainLocation"});
  1015. } else {
  1016. unsigned col = cast<ConstantInt>(colValue)->getLimitedValue();
  1017. if (col >= ValCtx.domainLocSize) {
  1018. ValCtx.EmitError(ValidationRule::SmDomainLocationIdxOOB);
  1019. }
  1020. }
  1021. } break;
  1022. case DXIL::OpCode::CBufferLoad: {
  1023. DxilInst_CBufferLoad CBLoad(CI);
  1024. Value *regIndex = CBLoad.get_byteOffset();
  1025. if (ConstantInt *cIndex = dyn_cast<ConstantInt>(regIndex)) {
  1026. int offset = cIndex->getLimitedValue();
  1027. int size = GetCBufSize(CBLoad.get_handle(), ValCtx);
  1028. if (size > 0 && offset >= size) {
  1029. ValCtx.EmitInstrError(CI, ValidationRule::InstrCBufferOutOfBound);
  1030. }
  1031. }
  1032. } break;
  1033. case DXIL::OpCode::CBufferLoadLegacy: {
  1034. DxilInst_CBufferLoadLegacy CBLoad(CI);
  1035. Value *regIndex = CBLoad.get_regIndex();
  1036. if (ConstantInt *cIndex = dyn_cast<ConstantInt>(regIndex)) {
  1037. int offset = cIndex->getLimitedValue() * 16; // 16 bytes align
  1038. int size = GetCBufSize(CBLoad.get_handle(), ValCtx);
  1039. if (size > 0 && offset >= size) {
  1040. ValCtx.EmitInstrError(CI, ValidationRule::InstrCBufferOutOfBound);
  1041. }
  1042. }
  1043. } break;
  1044. case DXIL::OpCode::StoreOutput: {
  1045. Value *outputID =
  1046. CI->getArgOperand(DXIL::OperandIndex::kStoreOutputIDOpIdx);
  1047. DxilSignature &outputSig = ValCtx.DxilMod.GetOutputSignature();
  1048. Value *row = CI->getArgOperand(DXIL::OperandIndex::kStoreOutputRowOpIdx);
  1049. Value *col = CI->getArgOperand(DXIL::OperandIndex::kStoreOutputColOpIdx);
  1050. ValidateSignatureAccess(CI, outputSig, outputID, row, col, ValCtx);
  1051. } break;
  1052. case DXIL::OpCode::OutputControlPointID: {
  1053. // Only used in hull shader.
  1054. Function *func = CI->getParent()->getParent();
  1055. if (ValCtx.patchConstFuncCallSet.count(func) > 0 || !ValCtx.DxilMod.GetShaderModel()->IsHS()) {
  1056. ValCtx.EmitFormatError(ValidationRule::SmOpcodeInInvalidFunction,
  1057. {"OutputControlPointID", "hull function"});
  1058. }
  1059. } break;
  1060. case DXIL::OpCode::LoadOutputControlPoint: {
  1061. // Only used in patch constant function.
  1062. Function *func = CI->getParent()->getParent();
  1063. if (ValCtx.entryFuncCallSet.count(func) > 0) {
  1064. ValCtx.EmitFormatError(
  1065. ValidationRule::SmOpcodeInInvalidFunction,
  1066. {"LoadOutputControlPoint", "PatchConstant function"});
  1067. }
  1068. Value *outputID =
  1069. CI->getArgOperand(DXIL::OperandIndex::kStoreOutputIDOpIdx);
  1070. DxilSignature &outputSig = ValCtx.DxilMod.GetOutputSignature();
  1071. Value *row = CI->getArgOperand(DXIL::OperandIndex::kStoreOutputRowOpIdx);
  1072. Value *col = CI->getArgOperand(DXIL::OperandIndex::kStoreOutputColOpIdx);
  1073. ValidateSignatureAccess(CI, outputSig, outputID, row, col, ValCtx);
  1074. } break;
  1075. case DXIL::OpCode::StorePatchConstant: {
  1076. // Only used in patch constant function.
  1077. Function *func = CI->getParent()->getParent();
  1078. if (ValCtx.entryFuncCallSet.count(func) > 0) {
  1079. ValCtx.EmitFormatError(ValidationRule::SmOpcodeInInvalidFunction,
  1080. {"StorePatchConstant", "PatchConstant function"});
  1081. }
  1082. Value *outputID =
  1083. CI->getArgOperand(DXIL::OperandIndex::kStoreOutputIDOpIdx);
  1084. DxilSignature &outputSig = ValCtx.DxilMod.GetPatchConstantSignature();
  1085. Value *row = CI->getArgOperand(DXIL::OperandIndex::kStoreOutputRowOpIdx);
  1086. Value *col = CI->getArgOperand(DXIL::OperandIndex::kStoreOutputColOpIdx);
  1087. ValidateSignatureAccess(CI, outputSig, outputID, row, col, ValCtx);
  1088. } break;
  1089. case DXIL::OpCode::EvalCentroid:
  1090. case DXIL::OpCode::EvalSampleIndex:
  1091. case DXIL::OpCode::EvalSnapped: {
  1092. // Eval* share same operand index with load input.
  1093. Value *inputID = CI->getArgOperand(DXIL::OperandIndex::kLoadInputIDOpIdx);
  1094. DxilSignature &inputSig = ValCtx.DxilMod.GetInputSignature();
  1095. Value *row = CI->getArgOperand(DXIL::OperandIndex::kLoadInputRowOpIdx);
  1096. Value *col = CI->getArgOperand(DXIL::OperandIndex::kLoadInputColOpIdx);
  1097. DxilSignatureElement *pSE =
  1098. ValidateSignatureAccess(CI, inputSig, inputID, row, col, ValCtx);
  1099. if (pSE) {
  1100. switch (pSE->GetInterpolationMode()->GetKind()) {
  1101. case DXIL::InterpolationMode::Linear:
  1102. case DXIL::InterpolationMode::LinearNoperspective:
  1103. case DXIL::InterpolationMode::LinearCentroid:
  1104. case DXIL::InterpolationMode::LinearNoperspectiveCentroid:
  1105. case DXIL::InterpolationMode::LinearSample:
  1106. case DXIL::InterpolationMode::LinearNoperspectiveSample:
  1107. break;
  1108. default:
  1109. ValCtx.EmitInstrFormatError(
  1110. CI, ValidationRule::InstrEvalInterpolationMode, {pSE->GetName()});
  1111. break;
  1112. }
  1113. if (pSE->GetSemantic()->GetKind() == DXIL::SemanticKind::Position) {
  1114. ValCtx.EmitInstrFormatError(
  1115. CI, ValidationRule::InstrCannotPullPosition,
  1116. {ValCtx.DxilMod.GetShaderModel()->GetName()});
  1117. }
  1118. }
  1119. } break;
  1120. case DXIL::OpCode::GetDimensions: {
  1121. DxilInst_GetDimensions getDim(CI);
  1122. Value *handle = getDim.get_handle();
  1123. DXIL::ComponentType compTy;
  1124. DXIL::ResourceClass resClass;
  1125. unsigned resIndex;
  1126. DXIL::ResourceKind resKind =
  1127. GetResourceKindAndCompTy(handle, compTy, resClass, resIndex, ValCtx);
  1128. // Check the result component use.
  1129. ResRetUsage usage;
  1130. CollectGetDimResRetUsage(usage, CI, ValCtx);
  1131. // Mip level only for texture.
  1132. switch (resKind) {
  1133. case DXIL::ResourceKind::Texture1D:
  1134. if (usage.y) {
  1135. ValCtx.EmitInstrFormatError(
  1136. CI, ValidationRule::InstrUndefResultForGetDimension,
  1137. {"y", "Texture1D"});
  1138. }
  1139. if (usage.z) {
  1140. ValCtx.EmitInstrFormatError(
  1141. CI, ValidationRule::InstrUndefResultForGetDimension,
  1142. {"z", "Texture1D"});
  1143. }
  1144. break;
  1145. case DXIL::ResourceKind::Texture1DArray:
  1146. if (usage.z) {
  1147. ValCtx.EmitInstrFormatError(
  1148. CI, ValidationRule::InstrUndefResultForGetDimension,
  1149. {"z", "Texture1DArray"});
  1150. }
  1151. break;
  1152. case DXIL::ResourceKind::Texture2D:
  1153. if (usage.z) {
  1154. ValCtx.EmitInstrFormatError(
  1155. CI, ValidationRule::InstrUndefResultForGetDimension,
  1156. {"z", "Texture2D"});
  1157. }
  1158. break;
  1159. case DXIL::ResourceKind::Texture2DArray:
  1160. break;
  1161. case DXIL::ResourceKind::Texture2DMS:
  1162. if (usage.z) {
  1163. ValCtx.EmitInstrFormatError(
  1164. CI, ValidationRule::InstrUndefResultForGetDimension,
  1165. {"z", "Texture2DMS"});
  1166. }
  1167. break;
  1168. case DXIL::ResourceKind::Texture2DMSArray:
  1169. break;
  1170. case DXIL::ResourceKind::Texture3D:
  1171. break;
  1172. case DXIL::ResourceKind::TextureCube:
  1173. if (usage.z) {
  1174. ValCtx.EmitInstrFormatError(
  1175. CI, ValidationRule::InstrUndefResultForGetDimension,
  1176. {"z", "TextureCube"});
  1177. }
  1178. break;
  1179. case DXIL::ResourceKind::TextureCubeArray:
  1180. break;
  1181. case DXIL::ResourceKind::StructuredBuffer:
  1182. case DXIL::ResourceKind::RawBuffer:
  1183. case DXIL::ResourceKind::TypedBuffer:
  1184. case DXIL::ResourceKind::TBuffer: {
  1185. Value *mip = getDim.get_mipLevel();
  1186. if (!isa<UndefValue>(mip)) {
  1187. ValCtx.EmitInstrError(
  1188. CI, ValidationRule::InstrMipLevelForGetDimension);
  1189. }
  1190. if (resKind != DXIL::ResourceKind::Invalid) {
  1191. if (usage.y || usage.z || usage.w) {
  1192. ValCtx.EmitInstrFormatError(
  1193. CI, ValidationRule::InstrUndefResultForGetDimension,
  1194. {"invalid", "resource"});
  1195. }
  1196. }
  1197. } break;
  1198. default: {
  1199. ValCtx.EmitInstrError(
  1200. CI, ValidationRule::InstrResourceKindForGetDim);
  1201. } break;
  1202. }
  1203. if (usage.status) {
  1204. ValCtx.EmitInstrFormatError(
  1205. CI, ValidationRule::InstrUndefResultForGetDimension,
  1206. {"invalid", "resource"});
  1207. }
  1208. } break;
  1209. case DXIL::OpCode::CalculateLOD: {
  1210. DxilInst_CalculateLOD lod(CI);
  1211. Value *samplerHandle = lod.get_sampler();
  1212. if (GetSamplerKind(samplerHandle, ValCtx) != DXIL::SamplerKind::Default) {
  1213. ValCtx.EmitInstrError(CI,
  1214. ValidationRule::InstrSamplerModeForLOD);
  1215. }
  1216. Value *handle = lod.get_handle();
  1217. DXIL::ComponentType compTy;
  1218. DXIL::ResourceClass resClass;
  1219. unsigned resIndex;
  1220. DXIL::ResourceKind resKind =
  1221. GetResourceKindAndCompTy(handle, compTy, resClass, resIndex, ValCtx);
  1222. if (resClass != DXIL::ResourceClass::SRV) {
  1223. ValCtx.EmitInstrError(CI,
  1224. ValidationRule::InstrResourceClassForSamplerGather);
  1225. return;
  1226. }
  1227. // Coord match resource.
  1228. ValidateCalcLODResourceDimensionCoord(
  1229. CI, resKind, {lod.get_coord0(), lod.get_coord1(), lod.get_coord2()},
  1230. ValCtx);
  1231. switch (resKind) {
  1232. case DXIL::ResourceKind::Texture1D:
  1233. case DXIL::ResourceKind::Texture1DArray:
  1234. case DXIL::ResourceKind::Texture2D:
  1235. case DXIL::ResourceKind::Texture2DArray:
  1236. case DXIL::ResourceKind::Texture3D:
  1237. case DXIL::ResourceKind::TextureCube:
  1238. case DXIL::ResourceKind::TextureCubeArray:
  1239. break;
  1240. default:
  1241. ValCtx.EmitInstrError(
  1242. CI, ValidationRule::InstrResourceKindForCalcLOD);
  1243. break;
  1244. }
  1245. } break;
  1246. case DXIL::OpCode::TextureGather: {
  1247. DxilInst_TextureGather gather(CI);
  1248. ValidateGather(CI, gather.get_srv(), gather.get_sampler(),
  1249. {gather.get_coord0(), gather.get_coord1(),
  1250. gather.get_coord2(), gather.get_coord3()},
  1251. {gather.get_offset0(), gather.get_offset1()},
  1252. /*IsSampleC*/ false, ValCtx);
  1253. } break;
  1254. case DXIL::OpCode::TextureGatherCmp: {
  1255. DxilInst_TextureGatherCmp gather(CI);
  1256. ValidateGather(CI, gather.get_srv(), gather.get_sampler(),
  1257. {gather.get_coord0(), gather.get_coord1(),
  1258. gather.get_coord2(), gather.get_coord3()},
  1259. {gather.get_offset0(), gather.get_offset1()},
  1260. /*IsSampleC*/ true, ValCtx);
  1261. } break;
  1262. case DXIL::OpCode::Sample: {
  1263. DxilInst_Sample sample(CI);
  1264. ValidateSampleInst(
  1265. CI, sample.get_srv(), sample.get_sampler(),
  1266. {sample.get_coord0(), sample.get_coord1(), sample.get_coord2(),
  1267. sample.get_coord3()},
  1268. {sample.get_offset0(), sample.get_offset1(), sample.get_offset2()},
  1269. /*IsSampleC*/ false, ValCtx);
  1270. } break;
  1271. case DXIL::OpCode::SampleCmp: {
  1272. DxilInst_SampleCmp sample(CI);
  1273. ValidateSampleInst(
  1274. CI, sample.get_srv(), sample.get_sampler(),
  1275. {sample.get_coord0(), sample.get_coord1(), sample.get_coord2(),
  1276. sample.get_coord3()},
  1277. {sample.get_offset0(), sample.get_offset1(), sample.get_offset2()},
  1278. /*IsSampleC*/ true, ValCtx);
  1279. } break;
  1280. case DXIL::OpCode::SampleCmpLevelZero: {
  1281. // sampler must be comparison mode.
  1282. DxilInst_SampleCmpLevelZero sample(CI);
  1283. ValidateSampleInst(
  1284. CI, sample.get_srv(), sample.get_sampler(),
  1285. {sample.get_coord0(), sample.get_coord1(), sample.get_coord2(),
  1286. sample.get_coord3()},
  1287. {sample.get_offset0(), sample.get_offset1(), sample.get_offset2()},
  1288. /*IsSampleC*/ true, ValCtx);
  1289. } break;
  1290. case DXIL::OpCode::SampleBias: {
  1291. DxilInst_SampleBias sample(CI);
  1292. Value *bias = sample.get_bias();
  1293. if (ConstantFP *cBias = dyn_cast<ConstantFP>(bias)) {
  1294. float fBias = cBias->getValueAPF().convertToFloat();
  1295. if (fBias < DXIL::kMinMipLodBias || fBias > DXIL::kMaxMipLodBias) {
  1296. ValCtx.EmitInstrFormatError(
  1297. CI, ValidationRule::InstrImmBiasForSampleB,
  1298. {std::to_string(DXIL::kMinMipLodBias).c_str(),
  1299. std::to_string(DXIL::kMaxMipLodBias).c_str(),
  1300. std::to_string(cBias->getValueAPF().convertToFloat()).c_str()});
  1301. }
  1302. }
  1303. ValidateSampleInst(
  1304. CI, sample.get_srv(), sample.get_sampler(),
  1305. {sample.get_coord0(), sample.get_coord1(), sample.get_coord2(),
  1306. sample.get_coord3()},
  1307. {sample.get_offset0(), sample.get_offset1(), sample.get_offset2()},
  1308. /*IsSampleC*/ false, ValCtx);
  1309. } break;
  1310. case DXIL::OpCode::SampleGrad: {
  1311. DxilInst_SampleGrad sample(CI);
  1312. ValidateSampleInst(
  1313. CI, sample.get_srv(), sample.get_sampler(),
  1314. {sample.get_coord0(), sample.get_coord1(), sample.get_coord2(),
  1315. sample.get_coord3()},
  1316. {sample.get_offset0(), sample.get_offset1(), sample.get_offset2()},
  1317. /*IsSampleC*/ false, ValCtx);
  1318. } break;
  1319. case DXIL::OpCode::SampleLevel: {
  1320. DxilInst_SampleLevel sample(CI);
  1321. ValidateSampleInst(
  1322. CI, sample.get_srv(), sample.get_sampler(),
  1323. {sample.get_coord0(), sample.get_coord1(), sample.get_coord2(),
  1324. sample.get_coord3()},
  1325. {sample.get_offset0(), sample.get_offset1(), sample.get_offset2()},
  1326. /*IsSampleC*/ false, ValCtx);
  1327. } break;
  1328. case DXIL::OpCode::Barrier: {
  1329. DxilInst_Barrier barrier(CI);
  1330. Value *mode = barrier.get_barrierMode();
  1331. ConstantInt *cMode = dyn_cast<ConstantInt>(mode);
  1332. if (!cMode) {
  1333. ValCtx.EmitInstrFormatError(CI, ValidationRule::InstrOpConst,
  1334. {"Mode", "Barrier"});
  1335. return;
  1336. }
  1337. const unsigned uglobal =
  1338. static_cast<unsigned>(DXIL::BarrierMode::UAVFenceGlobal);
  1339. const unsigned g = static_cast<unsigned>(DXIL::BarrierMode::TGSMFence);
  1340. const unsigned t =
  1341. static_cast<unsigned>(DXIL::BarrierMode::SyncThreadGroup);
  1342. const unsigned ut =
  1343. static_cast<unsigned>(DXIL::BarrierMode::UAVFenceThreadGroup);
  1344. unsigned barrierMode = cMode->getLimitedValue();
  1345. if (ValCtx.DxilMod.GetShaderModel()->IsCS()) {
  1346. bool bHasUGlobal = barrierMode & uglobal;
  1347. bool bHasGroup = barrierMode & g;
  1348. bool bHasUGroup = barrierMode & ut;
  1349. if (bHasUGlobal && bHasUGroup) {
  1350. ValCtx.EmitInstrError(CI,
  1351. ValidationRule::InstrBarrierModeUselessUGroup);
  1352. }
  1353. if (!bHasUGlobal && !bHasGroup && !bHasUGroup) {
  1354. ValCtx.EmitInstrError(CI, ValidationRule::InstrBarrierModeNoMemory);
  1355. }
  1356. } else {
  1357. if (uglobal != barrierMode) {
  1358. ValCtx.EmitInstrError(CI, ValidationRule::InstrBarrierModeForNonCS);
  1359. }
  1360. }
  1361. } break;
  1362. case DXIL::OpCode::BufferStore: {
  1363. DxilInst_BufferStore bufSt(CI);
  1364. DXIL::ComponentType compTy;
  1365. DXIL::ResourceClass resClass;
  1366. unsigned resIndex;
  1367. DXIL::ResourceKind resKind =
  1368. GetResourceKindAndCompTy(bufSt.get_uav(), compTy, resClass, resIndex, ValCtx);
  1369. if (resClass != DXIL::ResourceClass::UAV) {
  1370. ValCtx.EmitInstrError(CI, ValidationRule::InstrResourceClassForUAVStore);
  1371. }
  1372. ConstantInt *mask = dyn_cast<ConstantInt>(bufSt.get_mask());
  1373. if (!mask) {
  1374. // Mask for buffer store should be immediate.
  1375. ValCtx.EmitInstrFormatError(CI, ValidationRule::InstrOpConst, {"Mask", "BufferStore"});
  1376. return;
  1377. }
  1378. unsigned uMask = mask->getLimitedValue();
  1379. unsigned stValMask =
  1380. StoreValueToMask({bufSt.get_value0(), bufSt.get_value1(),
  1381. bufSt.get_value2(), bufSt.get_value3()});
  1382. if (stValMask != uMask) {
  1383. ValCtx.EmitInstrFormatError(
  1384. CI, ValidationRule::InstrWriteMaskMatchValueForUAVStore,
  1385. {std::to_string(uMask).c_str(), std::to_string(stValMask).c_str()});
  1386. }
  1387. Value *offset = bufSt.get_coord1();
  1388. switch (resKind) {
  1389. case DXIL::ResourceKind::RawBuffer:
  1390. if (!isa<UndefValue>(offset)) {
  1391. ValCtx.EmitInstrError(
  1392. CI, ValidationRule::InstrCoordinateCountForRawTypedBuf);
  1393. }
  1394. break;
  1395. case DXIL::ResourceKind::TypedBuffer:
  1396. case DXIL::ResourceKind::TBuffer:
  1397. if (!isa<UndefValue>(offset)) {
  1398. ValCtx.EmitInstrError(
  1399. CI, ValidationRule::InstrCoordinateCountForRawTypedBuf);
  1400. }
  1401. if (uMask != 0xf) {
  1402. ValCtx.EmitInstrError(
  1403. CI, ValidationRule::InstrWriteMaskForTypedUAVStore);
  1404. }
  1405. break;
  1406. case DXIL::ResourceKind::StructuredBuffer:
  1407. if (isa<UndefValue>(offset)) {
  1408. ValCtx.EmitInstrError(
  1409. CI, ValidationRule::InstrCoordinateCountForStructBuf);
  1410. }
  1411. break;
  1412. default:
  1413. ValCtx.EmitInstrError(
  1414. CI, ValidationRule::InstrResourceKindForBufferLoadStore);
  1415. break;
  1416. }
  1417. } break;
  1418. case DXIL::OpCode::TextureStore: {
  1419. DxilInst_TextureStore texSt(CI);
  1420. DXIL::ComponentType compTy;
  1421. DXIL::ResourceClass resClass;
  1422. unsigned resIndex;
  1423. DXIL::ResourceKind resKind =
  1424. GetResourceKindAndCompTy(texSt.get_srv(), compTy, resClass, resIndex, ValCtx);
  1425. if (resClass != DXIL::ResourceClass::UAV) {
  1426. ValCtx.EmitInstrError(CI, ValidationRule::InstrResourceClassForUAVStore);
  1427. }
  1428. ConstantInt *mask = dyn_cast<ConstantInt>(texSt.get_mask());
  1429. if (!mask) {
  1430. // Mask for buffer store should be immediate.
  1431. ValCtx.EmitInstrFormatError(CI, ValidationRule::InstrOpConst, {"Mask", "TextureStore"});
  1432. return;
  1433. }
  1434. unsigned uMask = mask->getLimitedValue();
  1435. if (uMask != 0xf) {
  1436. ValCtx.EmitInstrError(
  1437. CI, ValidationRule::InstrWriteMaskForTypedUAVStore);
  1438. }
  1439. unsigned stValMask =
  1440. StoreValueToMask({texSt.get_value0(), texSt.get_value1(),
  1441. texSt.get_value2(), texSt.get_value3()});
  1442. if (stValMask != uMask) {
  1443. ValCtx.EmitInstrError(
  1444. CI, ValidationRule::InstrWriteMaskMatchValueForUAVStore);
  1445. }
  1446. switch (resKind) {
  1447. case DXIL::ResourceKind::Texture1D:
  1448. case DXIL::ResourceKind::Texture1DArray:
  1449. case DXIL::ResourceKind::Texture2D:
  1450. case DXIL::ResourceKind::Texture2DArray:
  1451. case DXIL::ResourceKind::Texture3D:
  1452. break;
  1453. default:
  1454. ValCtx.EmitInstrError(
  1455. CI, ValidationRule::InstrResourceKindForTextureStore);
  1456. break;
  1457. }
  1458. } break;
  1459. case DXIL::OpCode::BufferLoad: {
  1460. DxilInst_BufferLoad bufLd(CI);
  1461. DXIL::ComponentType compTy;
  1462. DXIL::ResourceClass resClass;
  1463. unsigned resIndex;
  1464. DXIL::ResourceKind resKind =
  1465. GetResourceKindAndCompTy(bufLd.get_srv(), compTy, resClass, resIndex, ValCtx);
  1466. if (resClass != DXIL::ResourceClass::SRV &&
  1467. resClass != DXIL::ResourceClass::UAV) {
  1468. ValCtx.EmitInstrError(CI, ValidationRule::InstrResourceClassForLoad);
  1469. }
  1470. Value *offset = bufLd.get_wot();
  1471. switch (resKind) {
  1472. case DXIL::ResourceKind::RawBuffer:
  1473. case DXIL::ResourceKind::TypedBuffer:
  1474. case DXIL::ResourceKind::TBuffer:
  1475. if (!isa<UndefValue>(offset)) {
  1476. ValCtx.EmitInstrError(
  1477. CI, ValidationRule::InstrCoordinateCountForRawTypedBuf);
  1478. }
  1479. break;
  1480. case DXIL::ResourceKind::StructuredBuffer:
  1481. if (isa<UndefValue>(offset)) {
  1482. ValCtx.EmitInstrError(
  1483. CI, ValidationRule::InstrCoordinateCountForStructBuf);
  1484. }
  1485. break;
  1486. default:
  1487. ValCtx.EmitInstrError(
  1488. CI, ValidationRule::InstrResourceKindForBufferLoadStore);
  1489. break;
  1490. }
  1491. } break;
  1492. case DXIL::OpCode::TextureLoad: {
  1493. DxilInst_TextureLoad texLd(CI);
  1494. DXIL::ComponentType compTy;
  1495. DXIL::ResourceClass resClass;
  1496. unsigned resIndex;
  1497. DXIL::ResourceKind resKind =
  1498. GetResourceKindAndCompTy(texLd.get_srv(), compTy, resClass, resIndex, ValCtx);
  1499. Value *mipLevel = texLd.get_mipLevelOrSampleCount();
  1500. if (resClass == DXIL::ResourceClass::UAV) {
  1501. bool noOffset = isa<UndefValue>(texLd.get_offset0());
  1502. noOffset &= isa<UndefValue>(texLd.get_offset1());
  1503. noOffset &= isa<UndefValue>(texLd.get_offset2());
  1504. if (!noOffset) {
  1505. ValCtx.EmitInstrError(CI,
  1506. ValidationRule::InstrOffsetOnUAVLoad);
  1507. }
  1508. if (!isa<UndefValue>(mipLevel)) {
  1509. ValCtx.EmitInstrError(CI, ValidationRule::InstrMipOnUAVLoad);
  1510. }
  1511. } else {
  1512. if (resClass != DXIL::ResourceClass::SRV) {
  1513. ValCtx.EmitInstrError(CI, ValidationRule::InstrResourceClassForLoad);
  1514. }
  1515. }
  1516. switch (resKind) {
  1517. case DXIL::ResourceKind::Texture1D:
  1518. case DXIL::ResourceKind::Texture1DArray:
  1519. case DXIL::ResourceKind::Texture2D:
  1520. case DXIL::ResourceKind::Texture2DArray:
  1521. case DXIL::ResourceKind::Texture3D:
  1522. break;
  1523. case DXIL::ResourceKind::Texture2DMS:
  1524. case DXIL::ResourceKind::Texture2DMSArray: {
  1525. if (isa<UndefValue>(mipLevel)) {
  1526. ValCtx.EmitInstrError(
  1527. CI, ValidationRule::InstrSampleIndexForLoad2DMS);
  1528. }
  1529. } break;
  1530. default:
  1531. ValCtx.EmitInstrError(
  1532. CI, ValidationRule::InstrResourceKindForTextureLoad);
  1533. break;
  1534. }
  1535. } break;
  1536. case DXIL::OpCode::CutStream:
  1537. case DXIL::OpCode::EmitThenCutStream:
  1538. case DXIL::OpCode::EmitStream: {
  1539. if (pSM->IsGS()) {
  1540. unsigned streamMask = ValCtx.DxilMod.GetActiveStreamMask();
  1541. Value *streamID =
  1542. CI->getArgOperand(DXIL::OperandIndex::kStreamEmitCutIDOpIdx);
  1543. if (ConstantInt *cStreamID = dyn_cast<ConstantInt>(streamID)) {
  1544. int immStreamID = cStreamID->getValue().getLimitedValue();
  1545. if (cStreamID->getValue().isNegative() || immStreamID >= 4) {
  1546. ValCtx.EmitOperandOutOfRange(CI, "StreamID","0~4",
  1547. std::to_string(immStreamID).c_str());
  1548. } else {
  1549. unsigned immMask = 1 << immStreamID;
  1550. if ((streamMask & immMask) == 0) {
  1551. std::string range;
  1552. for (unsigned i = 0; i < 4; i++) {
  1553. if (streamMask & (1 << i)) {
  1554. range += std::to_string(i) + " ";
  1555. }
  1556. }
  1557. ValCtx.EmitOperandOutOfRange(CI, "StreamID", range.c_str(),
  1558. std::to_string(immStreamID).c_str());
  1559. }
  1560. }
  1561. } else {
  1562. ValCtx.EmitInstrFormatError(CI, ValidationRule::InstrOpConst,
  1563. {"StreamID", "Emit/CutStream"});
  1564. }
  1565. } else {
  1566. ValCtx.EmitInstrFormatError(CI, ValidationRule::SmOpcodeInInvalidFunction,
  1567. {"Emit/CutStream", "Geometry shader"});
  1568. }
  1569. } break;
  1570. case DXIL::OpCode::BufferUpdateCounter: {
  1571. DxilInst_BufferUpdateCounter updateCounter(CI);
  1572. DXIL::ComponentType compTy;
  1573. DXIL::ResourceClass resClass;
  1574. unsigned resIndex;
  1575. DXIL::ResourceKind resKind =
  1576. GetResourceKindAndCompTy(updateCounter.get_uav(), compTy, resClass, resIndex, ValCtx);
  1577. if (resClass != DXIL::ResourceClass::UAV) {
  1578. ValCtx.EmitInstrError(CI,
  1579. ValidationRule::InstrBufferUpdateCounterOnUAV);
  1580. }
  1581. if (resKind != DXIL::ResourceKind::StructuredBuffer) {
  1582. ValCtx.EmitInstrError(CI,
  1583. ValidationRule::SmCounterOnlyOnStructBuf);
  1584. }
  1585. Value *inc = updateCounter.get_inc();
  1586. if (ConstantInt *cInc = dyn_cast<ConstantInt>(inc)) {
  1587. bool isInc = cInc->getLimitedValue() == 1;
  1588. if (ValCtx.UavCounterIncMap.count(resIndex)) {
  1589. if (isInc != ValCtx.UavCounterIncMap[resIndex]) {
  1590. ValCtx.EmitInstrError(CI, ValidationRule::InstrOnlyOneAllocConsume);
  1591. }
  1592. }
  1593. else {
  1594. ValCtx.UavCounterIncMap[resIndex] = isInc;
  1595. }
  1596. } else {
  1597. ValCtx.EmitInstrFormatError(CI, ValidationRule::InstrOpConst, {"inc", "BufferUpdateCounter"});
  1598. }
  1599. } break;
  1600. case DXIL::OpCode::Asin: {
  1601. DxilInst_Asin I(CI);
  1602. if (ConstantFP *imm = dyn_cast<ConstantFP>(I.get_value())) {
  1603. if (imm->getValueAPF().isInfinity()) {
  1604. ValCtx.EmitInstrError(CI, ValidationRule::InstrNoIndefiniteAsin);
  1605. }
  1606. }
  1607. } break;
  1608. case DXIL::OpCode::Acos: {
  1609. DxilInst_Acos I(CI);
  1610. if (ConstantFP *imm = dyn_cast<ConstantFP>(I.get_value())) {
  1611. if (imm->getValueAPF().isInfinity()) {
  1612. ValCtx.EmitInstrError(CI, ValidationRule::InstrNoIndefiniteAcos);
  1613. }
  1614. }
  1615. } break;
  1616. case DXIL::OpCode::Log: {
  1617. DxilInst_Log I(CI);
  1618. if (ConstantFP *imm = dyn_cast<ConstantFP>(I.get_value())) {
  1619. if (imm->getValueAPF().isInfinity()) {
  1620. ValCtx.EmitInstrError(CI, ValidationRule::InstrNoIndefiniteLog);
  1621. }
  1622. }
  1623. } break;
  1624. case DXIL::OpCode::DerivFineX:
  1625. case DXIL::OpCode::DerivFineY:
  1626. case DXIL::OpCode::DerivCoarseX:
  1627. case DXIL::OpCode::DerivCoarseY: {
  1628. Value *V = CI->getArgOperand(DXIL::OperandIndex::kUnarySrc0OpIdx);
  1629. if (ConstantFP *imm = dyn_cast<ConstantFP>(V)) {
  1630. if (imm->getValueAPF().isInfinity()) {
  1631. ValCtx.EmitInstrError(CI, ValidationRule::InstrNoIndefiniteDsxy);
  1632. }
  1633. }
  1634. } break;
  1635. case DXIL::OpCode::Coverage:
  1636. ValCtx.m_bCoverageIn = true;
  1637. break;
  1638. case DXIL::OpCode::InnerCoverage:
  1639. ValCtx.m_bInnerCoverageIn = true;
  1640. break;
  1641. }
  1642. if (ValCtx.m_bCoverageIn && ValCtx.m_bInnerCoverageIn) {
  1643. ValCtx.EmitError(ValidationRule::SmPSCoverageAndInnerCoverage);
  1644. }
  1645. }
  1646. static bool IsDxilFunction(llvm::Function *F) {
  1647. unsigned argSize = F->getArgumentList().size();
  1648. if (argSize < 1) {
  1649. // Cannot be a DXIL operation.
  1650. return false;
  1651. }
  1652. return OP::IsDxilOpFunc(F);
  1653. }
  1654. static void ValidateExternalFunction(Function *F, ValidationContext &ValCtx) {
  1655. if (!IsDxilFunction(F)) {
  1656. ValCtx.EmitGlobalValueError(F, ValidationRule::DeclDxilFnExtern);
  1657. return;
  1658. }
  1659. if (F->use_empty()) {
  1660. ValCtx.EmitGlobalValueError(F, ValidationRule::DeclUsedExternalFunction);
  1661. return;
  1662. }
  1663. const ShaderModel *pSM = ValCtx.DxilMod.GetShaderModel();
  1664. OP *hlslOP = ValCtx.DxilMod.GetOP();
  1665. Type *voidTy = Type::getVoidTy(F->getContext());
  1666. for (User *user : F->users()) {
  1667. CallInst *CI = dyn_cast<CallInst>(user);
  1668. if (!CI) {
  1669. ValCtx.EmitGlobalValueError(F, ValidationRule::DeclFnIsCalled);
  1670. continue;
  1671. }
  1672. Value *argOpcode = CI->getArgOperand(0);
  1673. ConstantInt *constOpcode = dyn_cast<ConstantInt>(argOpcode);
  1674. if (!constOpcode) {
  1675. // opcode not immediate; function body will validate this error.
  1676. continue;
  1677. }
  1678. unsigned opcode = constOpcode->getLimitedValue();
  1679. if (opcode >= (unsigned)DXIL::OpCode::NumOpCodes) {
  1680. // invalid opcode; function body will validate this error.
  1681. continue;
  1682. }
  1683. DXIL::OpCode dxilOpcode = (DXIL::OpCode)opcode;
  1684. // In some cases, no overloads are provided (void is exclusive to others)
  1685. Function *dxilFunc;
  1686. if (hlslOP->IsOverloadLegal(dxilOpcode, voidTy)) {
  1687. dxilFunc = hlslOP->GetOpFunc(dxilOpcode, voidTy);
  1688. }
  1689. else {
  1690. Type *Ty = hlslOP->GetOverloadType(dxilOpcode, CI->getCalledFunction());
  1691. try {
  1692. if (!hlslOP->IsOverloadLegal(dxilOpcode, Ty)) {
  1693. ValCtx.EmitInstrError(CI, ValidationRule::InstrOload);
  1694. continue;
  1695. }
  1696. }
  1697. catch (...) {
  1698. ValCtx.EmitInstrError(CI, ValidationRule::InstrOload);
  1699. continue;
  1700. }
  1701. dxilFunc = hlslOP->GetOpFunc(dxilOpcode, Ty->getScalarType());
  1702. }
  1703. if (!dxilFunc) {
  1704. // Cannot find dxilFunction based on opcode and type.
  1705. ValCtx.EmitInstrError(CI, ValidationRule::InstrOload);
  1706. continue;
  1707. }
  1708. if (dxilFunc->getFunctionType() != F->getFunctionType()) {
  1709. ValCtx.EmitGlobalValueError(dxilFunc, ValidationRule::InstrCallOload);
  1710. continue;
  1711. }
  1712. if (!ValidateOpcodeInProfile(dxilOpcode, pSM)) {
  1713. // Opcode not available in profile.
  1714. ValCtx.EmitInstrError(CI, ValidationRule::SmOpcode);
  1715. continue;
  1716. }
  1717. // Check more detail.
  1718. ValidateDxilOperationCallInProfile(CI, dxilOpcode, pSM, ValCtx);
  1719. }
  1720. }
  1721. ///////////////////////////////////////////////////////////////////////////////
  1722. // Instruction validation functions. //
  1723. static bool IsLLVMInstructionAllowed(llvm::Instruction &I) {
  1724. unsigned op = I.getOpcode();
  1725. /* <py::lines('OPCODE-ALLOWED')>hctdb_instrhelp.get_instrs_pred("op", lambda i: not i.is_dxil_op and i.is_allowed, "llvm_id")</py>*/
  1726. // OPCODE-ALLOWED:BEGIN
  1727. // Instructions: Ret=1, Br=2, Switch=3, Add=8, FAdd=9, Sub=10, FSub=11, Mul=12,
  1728. // FMul=13, UDiv=14, SDiv=15, FDiv=16, URem=17, SRem=18, FRem=19, Shl=20,
  1729. // LShr=21, AShr=22, And=23, Or=24, Xor=25, Alloca=26, Load=27, Store=28,
  1730. // GetElementPtr=29, AtomicCmpXchg=31, AtomicRMW=32, Trunc=33, ZExt=34,
  1731. // SExt=35, FPToUI=36, FPToSI=37, UIToFP=38, SIToFP=39, FPTrunc=40, FPExt=41,
  1732. // BitCast=44, AddrSpaceCast=45, ICmp=46, FCmp=47, PHI=48, Call=49, Select=50,
  1733. // ExtractValue=57
  1734. return 1 <= op && op <= 3 || 8 <= op && op <= 29 || 31 <= op && op <= 41 || 44 <= op && op <= 50 || op == 57;
  1735. // OPCODE-ALLOWED:END
  1736. }
  1737. static bool IsDxilBuiltinStructType(StructType *ST, hlsl::OP *hlslOP) {
  1738. if (ST == hlslOP->GetBinaryWithCarryType())
  1739. return true;
  1740. if (ST == hlslOP->GetBinaryWithTwoOutputsType())
  1741. return true;
  1742. if (ST == hlslOP->GetInt4Type())
  1743. return true;
  1744. if (ST == hlslOP->GetDimensionsType())
  1745. return true;
  1746. if (ST == hlslOP->GetHandleType())
  1747. return true;
  1748. if (ST == hlslOP->GetSamplePosType())
  1749. return true;
  1750. if (ST == hlslOP->GetSplitDoubleType())
  1751. return true;
  1752. unsigned EltNum = ST->getNumElements();
  1753. switch (EltNum) {
  1754. case 2:
  1755. case 4: {
  1756. Type *EltTy = ST->getElementType(0);
  1757. return ST == hlslOP->GetCBufferRetType(EltTy);
  1758. } break;
  1759. case 5: {
  1760. Type *EltTy = ST->getElementType(0);
  1761. return ST == hlslOP->GetResRetType(EltTy);
  1762. } break;
  1763. default:
  1764. return false;
  1765. }
  1766. }
  1767. static bool ValidateType(Type *Ty, ValidationContext &ValCtx) {
  1768. DXASSERT_NOMSG(Ty != nullptr);
  1769. if (Ty->isPointerTy()) {
  1770. return ValidateType(Ty->getPointerElementType(), ValCtx);
  1771. }
  1772. if (Ty->isArrayTy()) {
  1773. Type *EltTy = Ty->getArrayElementType();
  1774. if (isa<ArrayType>(EltTy)) {
  1775. ValCtx.EmitTypeError(Ty, ValidationRule::TypesNoMultiDim);
  1776. return false;
  1777. }
  1778. return ValidateType(EltTy, ValCtx);
  1779. }
  1780. if (Ty->isStructTy()) {
  1781. bool result = true;
  1782. StructType *ST = cast<StructType>(Ty);
  1783. StringRef Name = ST->getName();
  1784. if (Name.startswith("dx.")) {
  1785. hlsl::OP *hlslOP = ValCtx.DxilMod.GetOP();
  1786. if (IsDxilBuiltinStructType(ST, hlslOP)) {
  1787. ValCtx.EmitTypeError(Ty, ValidationRule::InstrDxilStructUser);
  1788. result = false;
  1789. }
  1790. ValCtx.EmitTypeError(Ty, ValidationRule::DeclDxilNsReserved);
  1791. result = false;
  1792. }
  1793. for (auto e : ST->elements()) {
  1794. if (!ValidateType(e, ValCtx)) {
  1795. result = false;
  1796. }
  1797. }
  1798. return result;
  1799. }
  1800. if (Ty->isFloatTy() || Ty->isHalfTy() || Ty->isDoubleTy()) {
  1801. return true;
  1802. }
  1803. if (Ty->isIntegerTy()) {
  1804. unsigned width = Ty->getIntegerBitWidth();
  1805. if (width != 1 && width != 8 && width != 16 && width != 32 && width != 64) {
  1806. ValCtx.EmitTypeError(Ty, ValidationRule::TypesIntWidth);
  1807. return false;
  1808. }
  1809. return true;
  1810. }
  1811. if (Ty->isVectorTy()) {
  1812. ValCtx.EmitTypeError(Ty, ValidationRule::TypesNoVector);
  1813. return false;
  1814. }
  1815. ValCtx.EmitTypeError(Ty, ValidationRule::TypesDefined);
  1816. return false;
  1817. }
  1818. static bool GetNodeOperandAsInt(ValidationContext &ValCtx, MDNode *pMD, unsigned index, uint64_t *pValue) {
  1819. *pValue = 0;
  1820. if (pMD->getNumOperands() < index) {
  1821. ValCtx.EmitMetaError(pMD, ValidationRule::MetaWellFormed);
  1822. return false;
  1823. }
  1824. ConstantAsMetadata *C = dyn_cast<ConstantAsMetadata>(pMD->getOperand(index));
  1825. if (C == nullptr) {
  1826. ValCtx.EmitMetaError(pMD, ValidationRule::MetaWellFormed);
  1827. return false;
  1828. }
  1829. ConstantInt *CI = dyn_cast<ConstantInt>(C->getValue());
  1830. if (CI == nullptr) {
  1831. ValCtx.EmitMetaError(pMD, ValidationRule::MetaWellFormed);
  1832. return false;
  1833. }
  1834. *pValue = CI->getValue().getZExtValue();
  1835. return true;
  1836. }
  1837. static bool IsPrecise(Instruction &I, ValidationContext &ValCtx) {
  1838. MDNode *pMD = I.getMetadata(DxilMDHelper::kDxilPreciseAttributeMDName);
  1839. if (pMD == nullptr) {
  1840. return false;
  1841. }
  1842. if (pMD->getNumOperands() != 1) {
  1843. ValCtx.EmitMetaError(pMD, ValidationRule::MetaWellFormed);
  1844. return false;
  1845. }
  1846. uint64_t val;
  1847. if (!GetNodeOperandAsInt(ValCtx, pMD, 0, &val)) {
  1848. return false;
  1849. }
  1850. if (val == 1) {
  1851. return true;
  1852. }
  1853. if (val != 0) {
  1854. ValCtx.EmitMetaError(pMD, ValidationRule::MetaValueRange);
  1855. }
  1856. return false;
  1857. }
  1858. static bool IsValueMinPrec(DxilModule &DxilMod, Value *V) {
  1859. DXASSERT(DxilMod.GetGlobalFlags() & DXIL::kEnableMinPrecision,
  1860. "else caller didn't check - currently this path should never be hit "
  1861. "otherwise");
  1862. (DxilMod);
  1863. Type *Ty = V->getType();
  1864. if (Ty->isIntegerTy()) {
  1865. return 16 == Ty->getIntegerBitWidth();
  1866. }
  1867. return Ty->isHalfTy();
  1868. }
  1869. static void ValidateGradientOps(Function *F, ArrayRef<CallInst *> ops, ArrayRef<CallInst *> barriers, ValidationContext &ValCtx) {
  1870. // In the absence of wave operations, the wave validation effect need not happen.
  1871. // We haven't verified this is true at this point, but validation will fail
  1872. // later if the flags don't match in any case. Given that most shaders will
  1873. // not be using these wave operations, it's a reasonable cost saving.
  1874. if (!ValCtx.DxilMod.m_ShaderFlags.GetWaveOps()) {
  1875. return;
  1876. }
  1877. std::unique_ptr<WaveSensitivityAnalysis> WaveVal(WaveSensitivityAnalysis::create());
  1878. WaveVal->Analyze(F);
  1879. for (CallInst *op : ops) {
  1880. if (WaveVal->IsWaveSensitive(op)) {
  1881. ValCtx.EmitInstrError(op, ValidationRule::UniNoWaveSensitiveGradient);
  1882. }
  1883. }
  1884. }
  1885. static void ValidateControlFlowHint(BasicBlock &bb, ValidationContext &ValCtx) {
  1886. // Validate controlflow hint.
  1887. TerminatorInst *TI = bb.getTerminator();
  1888. if (!TI)
  1889. return;
  1890. MDNode *pNode = TI->getMetadata(DxilMDHelper::kDxilControlFlowHintMDName);
  1891. if (!pNode)
  1892. return;
  1893. if (pNode->getNumOperands() < 3)
  1894. return;
  1895. bool bHasBranch = false;
  1896. bool bHasFlatten = false;
  1897. bool bForceCase = false;
  1898. for (unsigned i = 2; i < pNode->getNumOperands(); i++) {
  1899. uint64_t value = 0;
  1900. if (GetNodeOperandAsInt(ValCtx, pNode, i, &value)) {
  1901. DXIL::ControlFlowHint hint = static_cast<DXIL::ControlFlowHint>(value);
  1902. switch (hint) {
  1903. case DXIL::ControlFlowHint::Flatten:
  1904. bHasFlatten = true;
  1905. break;
  1906. case DXIL::ControlFlowHint::Branch:
  1907. bHasBranch = true;
  1908. break;
  1909. case DXIL::ControlFlowHint::ForceCase:
  1910. bForceCase = true;
  1911. break;
  1912. default:
  1913. ValCtx.EmitMetaError(pNode,
  1914. ValidationRule::MetaInvalidControlFlowHint);
  1915. }
  1916. }
  1917. }
  1918. if (bHasBranch && bHasFlatten) {
  1919. ValCtx.EmitMetaError(pNode, ValidationRule::MetaBranchFlatten);
  1920. }
  1921. if (bForceCase && !isa<SwitchInst>(TI)) {
  1922. ValCtx.EmitMetaError(pNode, ValidationRule::MetaForceCaseOnSwitch);
  1923. }
  1924. }
  1925. static void ValidateTBAAMetadata(MDNode *Node, ValidationContext &ValCtx) {
  1926. switch (Node->getNumOperands()) {
  1927. case 1: {
  1928. if (Node->getOperand(0)->getMetadataID() != Metadata::MDStringKind) {
  1929. ValCtx.EmitMetaError(Node, ValidationRule::MetaWellFormed);
  1930. }
  1931. } break;
  1932. case 2: {
  1933. MDNode *rootNode = dyn_cast<MDNode>(Node->getOperand(1));
  1934. if (!rootNode) {
  1935. ValCtx.EmitMetaError(Node, ValidationRule::MetaWellFormed);
  1936. } else {
  1937. ValidateTBAAMetadata(rootNode, ValCtx);
  1938. }
  1939. } break;
  1940. case 3: {
  1941. MDNode *rootNode = dyn_cast<MDNode>(Node->getOperand(1));
  1942. if (!rootNode) {
  1943. ValCtx.EmitMetaError(Node, ValidationRule::MetaWellFormed);
  1944. } else {
  1945. ValidateTBAAMetadata(rootNode, ValCtx);
  1946. }
  1947. ConstantAsMetadata *pointsToConstMem = dyn_cast<ConstantAsMetadata>(Node->getOperand(2));
  1948. if (!pointsToConstMem) {
  1949. ValCtx.EmitMetaError(Node, ValidationRule::MetaWellFormed);
  1950. } else {
  1951. ConstantInt *isConst = dyn_cast<ConstantInt>(pointsToConstMem->getValue());
  1952. if (!isConst) {
  1953. ValCtx.EmitMetaError(Node, ValidationRule::MetaWellFormed);
  1954. } else if (isConst->getValue().getLimitedValue() > 1) {
  1955. ValCtx.EmitMetaError(Node, ValidationRule::MetaWellFormed);
  1956. }
  1957. }
  1958. } break;
  1959. default:
  1960. ValCtx.EmitMetaError(Node, ValidationRule::MetaWellFormed);
  1961. }
  1962. }
  1963. static void ValidateLoopMetadata(MDNode *Node, ValidationContext &ValCtx) {
  1964. if (Node->getNumOperands() == 0 || Node->getNumOperands() > 2) {
  1965. ValCtx.EmitMetaError(Node, ValidationRule::MetaWellFormed);
  1966. return;
  1967. }
  1968. if (Node != Node->getOperand(0).get()) {
  1969. ValCtx.EmitMetaError(Node, ValidationRule::MetaWellFormed);
  1970. return;
  1971. }
  1972. if (Node->getNumOperands() == 1) {
  1973. return;
  1974. }
  1975. MDNode *LoopNode = dyn_cast<MDNode>(Node->getOperand(1).get());
  1976. if (!LoopNode) {
  1977. ValCtx.EmitMetaError(Node, ValidationRule::MetaWellFormed);
  1978. return;
  1979. }
  1980. if (LoopNode->getNumOperands() < 1 || LoopNode->getNumOperands() > 2) {
  1981. ValCtx.EmitMetaError(LoopNode, ValidationRule::MetaWellFormed);
  1982. return;
  1983. }
  1984. if (LoopNode->getOperand(0) == LoopNode) {
  1985. ValidateLoopMetadata(LoopNode, ValCtx);
  1986. return;
  1987. }
  1988. MDString *LoopStr = dyn_cast<MDString>(LoopNode->getOperand(0));
  1989. if (!LoopStr) {
  1990. ValCtx.EmitMetaError(LoopNode, ValidationRule::MetaWellFormed);
  1991. return;
  1992. }
  1993. StringRef Name = LoopStr->getString();
  1994. if (Name != "llvm.loop.unroll.full" && Name != "llvm.loop.unroll.disable" &&
  1995. Name != "llvm.loop.unroll.count") {
  1996. ValCtx.EmitMetaError(LoopNode, ValidationRule::MetaWellFormed);
  1997. return;
  1998. }
  1999. if (Name == "llvm.loop.unroll.count") {
  2000. if (LoopNode->getNumOperands() != 2) {
  2001. ValCtx.EmitMetaError(LoopNode, ValidationRule::MetaWellFormed);
  2002. return;
  2003. }
  2004. ConstantAsMetadata *CountNode =
  2005. dyn_cast<ConstantAsMetadata>(LoopNode->getOperand(1));
  2006. if (!CountNode) {
  2007. ValCtx.EmitMetaError(LoopNode, ValidationRule::MetaWellFormed);
  2008. } else {
  2009. ConstantInt *Count = dyn_cast<ConstantInt>(CountNode->getValue());
  2010. if (!Count) {
  2011. ValCtx.EmitMetaError(CountNode, ValidationRule::MetaWellFormed);
  2012. }
  2013. }
  2014. }
  2015. }
  2016. static void ValidateInstructionMetadata(Instruction *I,
  2017. ValidationContext &ValCtx) {
  2018. SmallVector<std::pair<unsigned, MDNode *>, 2> MDNodes;
  2019. I->getAllMetadataOtherThanDebugLoc(MDNodes);
  2020. for (auto &MD : MDNodes) {
  2021. if (MD.first == ValCtx.kDxilControlFlowHintMDKind) {
  2022. if (!isa<TerminatorInst>(I)) {
  2023. ValCtx.EmitInstrError(
  2024. I, ValidationRule::MetaControlFlowHintNotOnControlFlow);
  2025. }
  2026. } else if (MD.first == ValCtx.kDxilPreciseMDKind) {
  2027. // Validated in IsPrecise.
  2028. } else if (MD.first == ValCtx.kLLVMLoopMDKind) {
  2029. ValidateLoopMetadata(MD.second, ValCtx);
  2030. } else if (MD.first == LLVMContext::MD_tbaa) {
  2031. ValidateTBAAMetadata(MD.second, ValCtx);
  2032. } else if (MD.first == LLVMContext::MD_range) {
  2033. // Validated in Verifier.cpp.
  2034. } else {
  2035. ValCtx.EmitMetaError(MD.second, ValidationRule::MetaUsed);
  2036. }
  2037. }
  2038. }
  2039. static void ValidateFunctionMetadata(Function *F, ValidationContext &ValCtx) {
  2040. SmallVector<std::pair<unsigned, MDNode *>, 2> MDNodes;
  2041. F->getAllMetadata(MDNodes);
  2042. for (auto &MD : MDNodes) {
  2043. ValCtx.EmitMetaError(MD.second, ValidationRule::MetaUsed);
  2044. }
  2045. }
  2046. static void ValidateFunctionBody(Function *F, ValidationContext &ValCtx) {
  2047. bool SupportsMinPrecision =
  2048. ValCtx.DxilMod.GetGlobalFlags() & DXIL::kEnableMinPrecision;
  2049. SmallVector<CallInst *, 16> gradientOps;
  2050. SmallVector<CallInst *, 16> barriers;
  2051. for (auto b = F->begin(), bend = F->end(); b != bend; ++b) {
  2052. for (auto i = b->begin(), iend = b->end(); i != iend; ++i) {
  2053. llvm::Instruction &I = *i;
  2054. if (I.hasMetadata()) {
  2055. ValidateInstructionMetadata(&I, ValCtx);
  2056. }
  2057. // Instructions must be allowed.
  2058. if (!IsLLVMInstructionAllowed(I)) {
  2059. ValCtx.EmitInstrError(&I, ValidationRule::InstrAllowed);
  2060. continue;
  2061. }
  2062. // Instructions marked precise may not have minprecision arguments.
  2063. if (SupportsMinPrecision) {
  2064. if (IsPrecise(I, ValCtx)) {
  2065. for (auto &O : I.operands()) {
  2066. if (IsValueMinPrec(ValCtx.DxilMod, O)) {
  2067. ValCtx.EmitInstrError(
  2068. &I, ValidationRule::InstrMinPrecisionNotPrecise);
  2069. break;
  2070. }
  2071. }
  2072. }
  2073. }
  2074. // Calls to external functions.
  2075. CallInst *CI = dyn_cast<CallInst>(&I);
  2076. if (CI) {
  2077. Function *FCalled = CI->getCalledFunction();
  2078. if (FCalled->isDeclaration()) {
  2079. // External function validation will diagnose.
  2080. if (!IsDxilFunction(FCalled)) {
  2081. continue;
  2082. }
  2083. Value *opcodeVal = CI->getOperand(0);
  2084. ConstantInt *OpcodeConst = dyn_cast<ConstantInt>(opcodeVal);
  2085. if (OpcodeConst == nullptr) {
  2086. ValCtx.EmitInstrFormatError(&I, ValidationRule::InstrOpConst,
  2087. {"Opcode", "DXIL operation"});
  2088. continue;
  2089. }
  2090. unsigned opcode = OpcodeConst->getLimitedValue();
  2091. DXIL::OpCode dxilOpcode = (DXIL::OpCode)opcode;
  2092. if (OP::IsDxilOpGradient(dxilOpcode)) {
  2093. gradientOps.push_back(CI);
  2094. }
  2095. if (dxilOpcode == DXIL::OpCode::Barrier) {
  2096. barriers.push_back(CI);
  2097. }
  2098. // External function validation will check the parameter
  2099. // list. This function will check that the call does not
  2100. // violate any rules.
  2101. }
  2102. continue;
  2103. }
  2104. for (Value *op : I.operands()) {
  2105. if (!isa<PHINode>(&I) && isa<UndefValue>(op)) {
  2106. ValCtx.EmitInstrError(&I,
  2107. ValidationRule::InstrNoReadingUninitialized);
  2108. } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(op)) {
  2109. for (Value *opCE : CE->operands()) {
  2110. if (isa<UndefValue>(opCE)) {
  2111. ValCtx.EmitInstrError(
  2112. &I, ValidationRule::InstrNoReadingUninitialized);
  2113. }
  2114. }
  2115. }
  2116. if (IntegerType *IT = dyn_cast<IntegerType>(op->getType())) {
  2117. if (IT->getBitWidth() == 8) {
  2118. ValCtx.EmitInstrError(&I, ValidationRule::TypesI8);
  2119. }
  2120. }
  2121. }
  2122. Type *Ty = I.getType();
  2123. if (isa<PointerType>(Ty))
  2124. Ty = Ty->getPointerElementType();
  2125. while (isa<ArrayType>(Ty))
  2126. Ty = Ty->getArrayElementType();
  2127. if (IntegerType *IT = dyn_cast<IntegerType>(Ty)) {
  2128. if (IT->getBitWidth() == 8) {
  2129. ValCtx.EmitInstrError(&I, ValidationRule::TypesI8);
  2130. }
  2131. }
  2132. unsigned opcode = I.getOpcode();
  2133. switch (opcode) {
  2134. case Instruction::Alloca: {
  2135. AllocaInst *AI = cast<AllocaInst>(&I);
  2136. // TODO: validate address space and alignment
  2137. Type *Ty = AI->getAllocatedType();
  2138. if (!ValidateType(Ty, ValCtx)) {
  2139. continue;
  2140. }
  2141. } break;
  2142. case Instruction::ExtractValue: {
  2143. ExtractValueInst *EV = cast<ExtractValueInst>(&I);
  2144. Type *Ty = EV->getAggregateOperand()->getType();
  2145. if (StructType *ST = dyn_cast<StructType>(Ty)) {
  2146. Value *Agg = EV->getAggregateOperand();
  2147. if (!isa<AtomicCmpXchgInst>(Agg) &&
  2148. !IsDxilBuiltinStructType(ST, ValCtx.DxilMod.GetOP())) {
  2149. ValCtx.EmitInstrError(EV, ValidationRule::InstrExtractValue);
  2150. }
  2151. } else {
  2152. ValCtx.EmitInstrError(EV, ValidationRule::InstrExtractValue);
  2153. }
  2154. } break;
  2155. case Instruction::Load: {
  2156. Type *Ty = I.getType();
  2157. if (!ValidateType(Ty, ValCtx)) {
  2158. continue;
  2159. }
  2160. } break;
  2161. case Instruction::Store: {
  2162. StoreInst *SI = cast<StoreInst>(&I);
  2163. Type *Ty = SI->getValueOperand()->getType();
  2164. if (!ValidateType(Ty, ValCtx)) {
  2165. continue;
  2166. }
  2167. } break;
  2168. case Instruction::GetElementPtr: {
  2169. Type *Ty = I.getType()->getPointerElementType();
  2170. if (!ValidateType(Ty, ValCtx)) {
  2171. continue;
  2172. }
  2173. GetElementPtrInst *GEP = cast<GetElementPtrInst>(&I);
  2174. bool allImmIndex = true;
  2175. for (auto Idx = GEP->idx_begin(), E = GEP->idx_end(); Idx != E; Idx++) {
  2176. if (!isa<ConstantInt>(Idx)) {
  2177. allImmIndex = false;
  2178. break;
  2179. }
  2180. }
  2181. if (allImmIndex) {
  2182. const DataLayout &DL = ValCtx.DL;
  2183. Value *Ptr = GEP->getPointerOperand();
  2184. unsigned size =
  2185. DL.getTypeAllocSize(Ptr->getType()->getPointerElementType());
  2186. unsigned valSize = DL.getTypeAllocSize(GEP->getType()->getPointerElementType());
  2187. SmallVector<Value *, 8> Indices(GEP->idx_begin(), GEP->idx_end());
  2188. unsigned offset =
  2189. DL.getIndexedOffset(GEP->getPointerOperandType(), Indices);
  2190. if ((offset + valSize) > size) {
  2191. ValCtx.EmitInstrError(GEP, ValidationRule::InstrInBoundsAccess);
  2192. }
  2193. }
  2194. } break;
  2195. case Instruction::SDiv: {
  2196. BinaryOperator *BO = cast<BinaryOperator>(&I);
  2197. Value *V = BO->getOperand(1);
  2198. if (ConstantInt *imm = dyn_cast<ConstantInt>(V)) {
  2199. if (imm->getValue().getLimitedValue() == 0) {
  2200. ValCtx.EmitInstrError(BO, ValidationRule::InstrNoIDivByZero);
  2201. }
  2202. }
  2203. } break;
  2204. case Instruction::UDiv: {
  2205. BinaryOperator *BO = cast<BinaryOperator>(&I);
  2206. Value *V = BO->getOperand(1);
  2207. if (ConstantInt *imm = dyn_cast<ConstantInt>(V)) {
  2208. if (imm->getValue().getLimitedValue() == 0) {
  2209. ValCtx.EmitInstrError(BO, ValidationRule::InstrNoUDivByZero);
  2210. }
  2211. }
  2212. } break;
  2213. case Instruction::AddrSpaceCast: {
  2214. AddrSpaceCastInst *Cast = cast<AddrSpaceCastInst>(&I);
  2215. unsigned ToAddrSpace = Cast->getType()->getPointerAddressSpace();
  2216. unsigned FromAddrSpace = Cast->getOperand(0)->getType()->getPointerAddressSpace();
  2217. if (ToAddrSpace != DXIL::kGenericPointerAddrSpace &&
  2218. FromAddrSpace != DXIL::kGenericPointerAddrSpace) {
  2219. ValCtx.EmitInstrError(Cast, ValidationRule::InstrNoGenericPtrAddrSpaceCast);
  2220. }
  2221. } break;
  2222. case Instruction::BitCast: {
  2223. BitCastInst *Cast = cast<BitCastInst>(&I);
  2224. Type *FromTy = Cast->getOperand(0)->getType();
  2225. Type *ToTy = Cast->getType();
  2226. if (isa<PointerType>(FromTy)) {
  2227. FromTy = FromTy->getPointerElementType();
  2228. ToTy = ToTy->getPointerElementType();
  2229. unsigned FromSize = ValCtx.DL.getTypeAllocSize(FromTy);
  2230. unsigned ToSize = ValCtx.DL.getTypeAllocSize(ToTy);
  2231. if (FromSize != ToSize) {
  2232. ValCtx.EmitInstrError(Cast, ValidationRule::InstrPtrBitCast);
  2233. continue;
  2234. }
  2235. while (isa<ArrayType>(FromTy)) {
  2236. FromTy = FromTy->getArrayElementType();
  2237. }
  2238. while (isa<ArrayType>(ToTy)) {
  2239. ToTy = ToTy->getArrayElementType();
  2240. }
  2241. }
  2242. if (isa<StructType>(FromTy) || isa<StructType>(ToTy)) {
  2243. ValCtx.EmitInstrError(Cast, ValidationRule::InstrStructBitCast);
  2244. continue;
  2245. }
  2246. bool IsMinPrecisionTy = ValCtx.DL.getTypeAllocSize(FromTy) < 4 ||
  2247. ValCtx.DL.getTypeAllocSize(ToTy) < 4;
  2248. if (IsMinPrecisionTy) {
  2249. ValCtx.EmitInstrError(Cast, ValidationRule::InstrMinPrecisonBitCast);
  2250. }
  2251. } break;
  2252. }
  2253. if (PointerType *PT = dyn_cast<PointerType>(I.getType())) {
  2254. if (PT->getAddressSpace() == DXIL::kTGSMAddrSpace) {
  2255. if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&I)) {
  2256. Value *Ptr = GEP->getPointerOperand();
  2257. if (!isa<GlobalVariable>(Ptr)) {
  2258. ValCtx.EmitInstrError(
  2259. &I, ValidationRule::InstrFailToResloveTGSMPointer);
  2260. }
  2261. } else if (BitCastInst *BCI = dyn_cast<BitCastInst>(&I)) {
  2262. Value *Ptr = BCI->getOperand(0);
  2263. if (!isa<GetElementPtrInst>(Ptr) && !isa<GlobalVariable>(Ptr)) {
  2264. ValCtx.EmitInstrError(
  2265. &I, ValidationRule::InstrFailToResloveTGSMPointer);
  2266. }
  2267. } else {
  2268. ValCtx.EmitInstrError(
  2269. &I, ValidationRule::InstrFailToResloveTGSMPointer);
  2270. }
  2271. }
  2272. }
  2273. }
  2274. ValidateControlFlowHint(*b, ValCtx);
  2275. }
  2276. if (!gradientOps.empty()) {
  2277. ValidateGradientOps(F, gradientOps, barriers, ValCtx);
  2278. }
  2279. }
  2280. static void ValidateFunction(Function &F, ValidationContext &ValCtx) {
  2281. if (F.isDeclaration()) {
  2282. ValidateExternalFunction(&F, ValCtx);
  2283. } else {
  2284. if (!F.arg_empty())
  2285. ValCtx.EmitFormatError(ValidationRule::FlowFunctionCall,
  2286. {F.getName().str().c_str()});
  2287. DxilFunctionAnnotation *funcAnnotation =
  2288. ValCtx.DxilMod.GetTypeSystem().GetFunctionAnnotation(&F);
  2289. if (!funcAnnotation) {
  2290. ValCtx.EmitFormatError(ValidationRule::MetaFunctionAnnotation,
  2291. {F.getName().str().c_str()});
  2292. return;
  2293. }
  2294. // Validate parameter type.
  2295. for (auto &arg : F.args()) {
  2296. Type *argTy = arg.getType();
  2297. if (argTy->isPointerTy())
  2298. argTy = argTy->getPointerElementType();
  2299. while (argTy->isArrayTy()) {
  2300. argTy = argTy->getArrayElementType();
  2301. }
  2302. DxilParameterAnnotation &paramAnnoation =
  2303. funcAnnotation->GetParameterAnnotation(arg.getArgNo());
  2304. if (argTy->isStructTy() && !HLModule::IsStreamOutputType(argTy) &&
  2305. !paramAnnoation.HasMatrixAnnotation()) {
  2306. if (arg.hasName())
  2307. ValCtx.EmitFormatError(
  2308. ValidationRule::DeclFnFlattenParam,
  2309. {arg.getName().str().c_str(), F.getName().str().c_str()});
  2310. else
  2311. ValCtx.EmitFormatError(ValidationRule::DeclFnFlattenParam,
  2312. {std::to_string(arg.getArgNo()).c_str(),
  2313. F.getName().str().c_str()});
  2314. break;
  2315. }
  2316. }
  2317. ValidateFunctionBody(&F, ValCtx);
  2318. }
  2319. if (F.hasMetadata()) {
  2320. ValidateFunctionMetadata(&F, ValCtx);
  2321. }
  2322. }
  2323. static void ValidateGlobalVariable(GlobalVariable &GV,
  2324. ValidationContext &ValCtx) {
  2325. bool isInternalGV =
  2326. HLModule::IsStaticGlobal(&GV) || HLModule::IsSharedMemoryGlobal(&GV);
  2327. if (!isInternalGV) {
  2328. if (!GV.user_empty()) {
  2329. bool hasInstructionUser = false;
  2330. for (User *U : GV.users()) {
  2331. if (isa<Instruction>(U)) {
  2332. hasInstructionUser = true;
  2333. break;
  2334. }
  2335. }
  2336. // External GV should not have instruction user.
  2337. if (hasInstructionUser) {
  2338. ValCtx.EmitGlobalValueError(&GV, ValidationRule::DeclNotUsedExternal);
  2339. }
  2340. }
  2341. // Must have metadata description for each variable.
  2342. } else {
  2343. // Internal GV must have user.
  2344. if (GV.user_empty()) {
  2345. ValCtx.EmitGlobalValueError(&GV, ValidationRule::DeclUsedInternal);
  2346. }
  2347. // Validate type for internal globals.
  2348. if (HLModule::IsStaticGlobal(&GV) || HLModule::IsSharedMemoryGlobal(&GV)) {
  2349. Type *Ty = GV.getType()->getPointerElementType();
  2350. ValidateType(Ty, ValCtx);
  2351. }
  2352. }
  2353. }
  2354. static void
  2355. CollectFixAddressAccess(Value *V, std::vector<Instruction *> &fixAddrTGSMList) {
  2356. for (User *U : V->users()) {
  2357. if (GEPOperator *GEP = dyn_cast<GEPOperator>(U)) {
  2358. if (isa<ConstantExpr>(GEP) || GEP->hasAllConstantIndices()) {
  2359. CollectFixAddressAccess(GEP, fixAddrTGSMList);
  2360. }
  2361. } else if (isa<StoreInst>(U)) {
  2362. }
  2363. }
  2364. }
  2365. static void
  2366. ValidateTGSMRaceCondition(std::vector<Instruction *> &fixAddrTGSMList,
  2367. ValidationContext &ValCtx) {
  2368. std::unordered_set<Function *> fixAddrTGSMFuncSet;
  2369. for (Instruction *I : fixAddrTGSMList) {
  2370. BasicBlock *BB = I->getParent();
  2371. fixAddrTGSMFuncSet.insert(BB->getParent());
  2372. }
  2373. for (auto &F : ValCtx.DxilMod.GetModule()->functions()) {
  2374. continue;
  2375. PostDominatorTree PDT;
  2376. PDT.runOnFunction(F);
  2377. BasicBlock *Entry = &F.getEntryBlock();
  2378. for (Instruction *I : fixAddrTGSMList) {
  2379. BasicBlock *BB = I->getParent();
  2380. if (BB->getParent() == &F) {
  2381. if (PDT.dominates(BB, Entry)) {
  2382. ValCtx.EmitInstrError(I, ValidationRule::InstrTGSMRaceCond);
  2383. }
  2384. }
  2385. }
  2386. }
  2387. }
  2388. static void ValidateGlobalVariables(ValidationContext &ValCtx) {
  2389. DxilModule &M = ValCtx.DxilMod;
  2390. unsigned TGSMSize = 0;
  2391. std::vector<Instruction*> fixAddrTGSMList;
  2392. const DataLayout &DL = M.GetModule()->getDataLayout();
  2393. for (GlobalVariable &GV : M.GetModule()->globals()) {
  2394. ValidateGlobalVariable(GV, ValCtx);
  2395. if (GV.getType()->getAddressSpace() == DXIL::kTGSMAddrSpace) {
  2396. TGSMSize += DL.getTypeAllocSize(GV.getType()->getElementType());
  2397. CollectFixAddressAccess(&GV, fixAddrTGSMList);
  2398. }
  2399. }
  2400. if (TGSMSize > DXIL::kMaxTGSMSize) {
  2401. ValCtx.EmitFormatError(ValidationRule::SmMaxTGSMSize,
  2402. {std::to_string(TGSMSize).c_str(),
  2403. std::to_string(DXIL::kMaxTGSMSize).c_str()});
  2404. }
  2405. if (!fixAddrTGSMList.empty()) {
  2406. ValidateTGSMRaceCondition(fixAddrTGSMList, ValCtx);
  2407. }
  2408. }
  2409. static void ValidateValidatorVersion(ValidationContext &ValCtx) {
  2410. Module *pModule = &ValCtx.M;
  2411. NamedMDNode *pNode = pModule->getNamedMetadata("dx.valver");
  2412. if (pNode == nullptr) {
  2413. return;
  2414. }
  2415. if (pNode->getNumOperands() == 1) {
  2416. MDTuple *pVerValues = dyn_cast<MDTuple>(pNode->getOperand(0));
  2417. if (pVerValues != nullptr && pVerValues->getNumOperands() == 2) {
  2418. uint64_t majorVer, minorVer;
  2419. if (GetNodeOperandAsInt(ValCtx, pVerValues, 0, &majorVer) &&
  2420. GetNodeOperandAsInt(ValCtx, pVerValues, 1, &minorVer)) {
  2421. unsigned curMajor, curMinor;
  2422. GetValidationVersion(&curMajor, &curMinor);
  2423. // This will need to be updated as major/minor versions evolve,
  2424. // depending on the degree of compat across versions.
  2425. if (majorVer == curMajor && minorVer <= curMinor) {
  2426. return;
  2427. }
  2428. }
  2429. }
  2430. }
  2431. ValCtx.EmitError(ValidationRule::MetaWellFormed);
  2432. }
  2433. static void ValidateMetadata(ValidationContext &ValCtx) {
  2434. Module *pModule = &ValCtx.M;
  2435. const std::string &target = pModule->getTargetTriple();
  2436. if (target != "dxil-ms-dx") {
  2437. ValCtx.EmitFormatError(ValidationRule::MetaTarget, {target.c_str()});
  2438. }
  2439. StringMap<bool> llvmNamedMeta;
  2440. // These llvm named metadata is verified in lib/IR/Verifier.cpp.
  2441. llvmNamedMeta["llvm.dbg.cu"];
  2442. llvmNamedMeta["llvm.dbg.contents"];
  2443. llvmNamedMeta["llvm.dbg.defines"];
  2444. llvmNamedMeta["llvm.dbg.mainFileName"];
  2445. llvmNamedMeta["llvm.dbg.args"];
  2446. llvmNamedMeta["llvm.ident"];
  2447. // Not for HLSL which does not have vtable.
  2448. // llvmNamedMeta["llvm.bitsets"];
  2449. llvmNamedMeta["llvm.module.flags"];
  2450. for (auto &NamedMetaNode : pModule->named_metadata()) {
  2451. if (!DxilModule::IsKnownNamedMetaData(NamedMetaNode)) {
  2452. StringRef name = NamedMetaNode.getName();
  2453. if (!name.startswith_lower("llvm."))
  2454. ValCtx.EmitFormatError(ValidationRule::MetaKnown, {name.str().c_str()});
  2455. else {
  2456. if (llvmNamedMeta.count(name) == 0) {
  2457. ValCtx.EmitFormatError(ValidationRule::MetaKnown,
  2458. {name.str().c_str()});
  2459. }
  2460. }
  2461. }
  2462. }
  2463. const hlsl::ShaderModel *SM = ValCtx.DxilMod.GetShaderModel();
  2464. if (!SM->IsValid() || SM->GetMajor() != 6 || SM->GetMinor() != 0) {
  2465. ValCtx.EmitFormatError(ValidationRule::SmName,
  2466. {ValCtx.DxilMod.GetShaderModel()->GetName()});
  2467. }
  2468. ValidateValidatorVersion(ValCtx);
  2469. }
  2470. static void ValidateResourceOverlap(
  2471. hlsl::DxilResourceBase &res,
  2472. SpacesAllocator<unsigned, DxilResourceBase> &spaceAllocator,
  2473. ValidationContext &ValCtx) {
  2474. unsigned base = res.GetLowerBound();
  2475. unsigned size = res.GetRangeSize();
  2476. unsigned space = res.GetSpaceID();
  2477. auto &allocator = spaceAllocator.Get(space);
  2478. unsigned end = base + size - 1;
  2479. // unbounded
  2480. if (end < base)
  2481. end = size;
  2482. const DxilResourceBase *conflictRes = allocator.Insert(&res, base, end);
  2483. if (conflictRes) {
  2484. ValCtx.EmitFormatError(
  2485. ValidationRule::SmResourceRangeOverlap,
  2486. {res.GetGlobalName().c_str(), std::to_string(base).c_str(),
  2487. std::to_string(size).c_str(),
  2488. std::to_string(conflictRes->GetLowerBound()).c_str(),
  2489. std::to_string(conflictRes->GetRangeSize()).c_str(),
  2490. std::to_string(space).c_str()});
  2491. }
  2492. }
  2493. static void ValidateResource(hlsl::DxilResource &res,
  2494. ValidationContext &ValCtx) {
  2495. switch (res.GetKind()) {
  2496. case DXIL::ResourceKind::RawBuffer:
  2497. case DXIL::ResourceKind::TypedBuffer:
  2498. case DXIL::ResourceKind::TBuffer:
  2499. case DXIL::ResourceKind::StructuredBuffer:
  2500. case DXIL::ResourceKind::Texture1D:
  2501. case DXIL::ResourceKind::Texture1DArray:
  2502. case DXIL::ResourceKind::Texture2D:
  2503. case DXIL::ResourceKind::Texture2DArray:
  2504. case DXIL::ResourceKind::Texture3D:
  2505. case DXIL::ResourceKind::TextureCube:
  2506. case DXIL::ResourceKind::TextureCubeArray:
  2507. if (res.GetSampleCount() > 0) {
  2508. ValCtx.EmitResourceError(&res, ValidationRule::SmSampleCountOnlyOn2DMS);
  2509. }
  2510. break;
  2511. case DXIL::ResourceKind::Texture2DMS:
  2512. case DXIL::ResourceKind::Texture2DMSArray:
  2513. break;
  2514. default:
  2515. ValCtx.EmitResourceError(&res, ValidationRule::SmInvalidResourceKind);
  2516. break;
  2517. }
  2518. switch (res.GetCompType().GetKind()) {
  2519. case DXIL::ComponentType::F32:
  2520. case DXIL::ComponentType::SNormF32:
  2521. case DXIL::ComponentType::UNormF32:
  2522. case DXIL::ComponentType::F64:
  2523. case DXIL::ComponentType::I32:
  2524. case DXIL::ComponentType::I64:
  2525. case DXIL::ComponentType::U32:
  2526. case DXIL::ComponentType::U64:
  2527. case DXIL::ComponentType::F16:
  2528. case DXIL::ComponentType::I16:
  2529. case DXIL::ComponentType::U16:
  2530. break;
  2531. default:
  2532. if (!res.IsStructuredBuffer() && !res.IsRawBuffer())
  2533. ValCtx.EmitResourceError(&res, ValidationRule::SmInvalidResourceCompType);
  2534. break;
  2535. }
  2536. if (res.IsStructuredBuffer()) {
  2537. unsigned stride = res.GetElementStride();
  2538. bool alignedTo4Bytes = (stride & 3) == 0;
  2539. if (!alignedTo4Bytes) {
  2540. ValCtx.EmitResourceFormatError(
  2541. &res, ValidationRule::MetaStructBufAlignment,
  2542. {std::to_string(4).c_str(), std::to_string(stride).c_str()});
  2543. }
  2544. if (stride > DXIL::kMaxStructBufferStride) {
  2545. ValCtx.EmitResourceFormatError(
  2546. &res, ValidationRule::MetaStructBufAlignmentOutOfBound,
  2547. {std::to_string(DXIL::kMaxStructBufferStride).c_str(),
  2548. std::to_string(stride).c_str()});
  2549. }
  2550. }
  2551. if (res.IsAnyTexture() || res.IsTypedBuffer()) {
  2552. Type *RetTy = res.GetRetType();
  2553. unsigned size = ValCtx.DxilMod.GetModule()->getDataLayout().getTypeAllocSize(RetTy);
  2554. if (size > 4*4) {
  2555. ValCtx.EmitResourceError(&res, ValidationRule::MetaTextureType);
  2556. }
  2557. }
  2558. }
  2559. static void
  2560. CollectCBufferRanges(DxilStructAnnotation *annotation,
  2561. SpanAllocator<unsigned, DxilFieldAnnotation> &constAllocator,
  2562. unsigned base, DxilTypeSystem &typeSys, const char *cbName,
  2563. ValidationContext &ValCtx) {
  2564. unsigned cbSize = annotation->GetCBufferSize();
  2565. const StructType *ST = annotation->GetStructType();
  2566. for (int i = annotation->GetNumFields() - 1; i >= 0; i--) {
  2567. DxilFieldAnnotation &fieldAnnotation = annotation->GetFieldAnnotation(i);
  2568. Type *EltTy = ST->getElementType(i);
  2569. unsigned offset = fieldAnnotation.GetCBufferOffset();
  2570. unsigned EltSize = HLModule::GetLegacyCBufferFieldElementSize(
  2571. fieldAnnotation, EltTy, typeSys);
  2572. bool bOutOfBound = false;
  2573. if (!EltTy->isAggregateType()) {
  2574. bOutOfBound = (offset + EltSize) > cbSize;
  2575. if (!bOutOfBound) {
  2576. if (constAllocator.Insert(&fieldAnnotation, base + offset,
  2577. base + offset + EltSize - 1)) {
  2578. ValCtx.EmitFormatError(
  2579. ValidationRule::SmCBufferOffsetOverlap,
  2580. {cbName, std::to_string(base + offset).c_str()});
  2581. }
  2582. }
  2583. } else if (isa<ArrayType>(EltTy)) {
  2584. unsigned arrayCount = 1;
  2585. while (isa<ArrayType>(EltTy)) {
  2586. arrayCount *= EltTy->getArrayNumElements();
  2587. EltTy = EltTy->getArrayElementType();
  2588. }
  2589. unsigned arrayBase = base + offset;
  2590. DxilStructAnnotation *EltAnnotation = nullptr;
  2591. if (StructType *EltST = dyn_cast<StructType>(EltTy))
  2592. EltAnnotation = typeSys.GetStructAnnotation(EltST);
  2593. for (unsigned idx = 0; idx < arrayCount; idx++) {
  2594. // 16 bytes align except last component.
  2595. if (idx < (arrayCount - 1)) {
  2596. arrayBase = (arrayBase + 15) & ~(0xf);
  2597. }
  2598. if (arrayBase > (base + cbSize)) {
  2599. bOutOfBound = true;
  2600. break;
  2601. }
  2602. if (!EltAnnotation) {
  2603. if (constAllocator.Insert(&fieldAnnotation, arrayBase,
  2604. arrayBase + EltSize - 1)) {
  2605. ValCtx.EmitFormatError(
  2606. ValidationRule::SmCBufferOffsetOverlap,
  2607. {cbName, std::to_string(base + offset).c_str()});
  2608. }
  2609. } else {
  2610. CollectCBufferRanges(EltAnnotation,
  2611. constAllocator, arrayBase, typeSys,
  2612. cbName, ValCtx);
  2613. }
  2614. arrayBase += EltSize;
  2615. }
  2616. } else {
  2617. cast<StructType>(EltTy);
  2618. bOutOfBound = (offset + EltSize) > cbSize;
  2619. }
  2620. if (bOutOfBound) {
  2621. ValCtx.EmitFormatError(ValidationRule::SmCBufferElementOverflow,
  2622. {cbName, std::to_string(base + offset).c_str()});
  2623. }
  2624. }
  2625. }
  2626. static void ValidateCBuffer(DxilCBuffer &cb, ValidationContext &ValCtx) {
  2627. Type *Ty = cb.GetGlobalSymbol()->getType()->getPointerElementType();
  2628. if (cb.GetRangeSize() != 1) {
  2629. Ty = Ty->getArrayElementType();
  2630. }
  2631. if (!isa<StructType>(Ty)) {
  2632. ValCtx.EmitResourceError(&cb,
  2633. ValidationRule::SmCBufferTemplateTypeMustBeStruct);
  2634. return;
  2635. }
  2636. StructType *ST = cast<StructType>(Ty);
  2637. DxilTypeSystem &typeSys = ValCtx.DxilMod.GetTypeSystem();
  2638. DxilStructAnnotation *annotation = typeSys.GetStructAnnotation(ST);
  2639. if (!annotation)
  2640. return;
  2641. // Collect constant ranges.
  2642. std::vector<std::pair<unsigned, unsigned>> constRanges;
  2643. SpanAllocator<unsigned, DxilFieldAnnotation> constAllocator(0,
  2644. // 4096 * 16 bytes.
  2645. DXIL::kMaxCBufferSize << 4);
  2646. CollectCBufferRanges(annotation, constAllocator,
  2647. 0, typeSys,
  2648. cb.GetGlobalName().c_str(), ValCtx);
  2649. }
  2650. static void ValidateResources(ValidationContext &ValCtx) {
  2651. const vector<unique_ptr<DxilResource>> &uavs = ValCtx.DxilMod.GetUAVs();
  2652. bool hasROV = false;
  2653. SpacesAllocator<unsigned, DxilResourceBase> uavAllocator;
  2654. for (auto &uav : uavs) {
  2655. if (uav->IsROV()) {
  2656. hasROV = true;
  2657. if (!ValCtx.DxilMod.GetShaderModel()->IsPS()) {
  2658. ValCtx.EmitResourceError(uav.get(), ValidationRule::SmROVOnlyInPS);
  2659. }
  2660. }
  2661. switch (uav->GetKind()) {
  2662. case DXIL::ResourceKind::Texture2DMS:
  2663. case DXIL::ResourceKind::Texture2DMSArray:
  2664. case DXIL::ResourceKind::TextureCube:
  2665. case DXIL::ResourceKind::TextureCubeArray:
  2666. ValCtx.EmitResourceError(uav.get(),
  2667. ValidationRule::SmInvalidTextureKindOnUAV);
  2668. break;
  2669. default:
  2670. break;
  2671. }
  2672. if (uav->HasCounter() && !uav->IsStructuredBuffer()) {
  2673. ValCtx.EmitResourceError(uav.get(),
  2674. ValidationRule::SmCounterOnlyOnStructBuf);
  2675. }
  2676. if (uav->HasCounter() && uav->IsGloballyCoherent())
  2677. ValCtx.EmitResourceError(uav.get(),
  2678. ValidationRule::MetaGlcNotOnAppendConsume);
  2679. ValidateResource(*uav, ValCtx);
  2680. ValidateResourceOverlap(*uav, uavAllocator, ValCtx);
  2681. }
  2682. SpacesAllocator<unsigned, DxilResourceBase> srvAllocator;
  2683. const vector<unique_ptr<DxilResource>> &srvs = ValCtx.DxilMod.GetSRVs();
  2684. for (auto &srv : srvs) {
  2685. ValidateResource(*srv, ValCtx);
  2686. ValidateResourceOverlap(*srv, srvAllocator, ValCtx);
  2687. }
  2688. hlsl::DxilResourceBase *pNonDense;
  2689. if (!AreDxilResourcesDense(&ValCtx.M, &pNonDense)) {
  2690. ValCtx.EmitResourceError(pNonDense, ValidationRule::MetaDenseResIDs);
  2691. }
  2692. SpacesAllocator<unsigned, DxilResourceBase> samplerAllocator;
  2693. for (auto &sampler : ValCtx.DxilMod.GetSamplers()) {
  2694. if (sampler->GetSamplerKind() == DXIL::SamplerKind::Invalid) {
  2695. ValCtx.EmitResourceError(sampler.get(),
  2696. ValidationRule::MetaValidSamplerMode);
  2697. }
  2698. ValidateResourceOverlap(*sampler, samplerAllocator, ValCtx);
  2699. }
  2700. SpacesAllocator<unsigned, DxilResourceBase> cbufferAllocator;
  2701. for (auto &cbuffer : ValCtx.DxilMod.GetCBuffers()) {
  2702. ValidateCBuffer(*cbuffer, ValCtx);
  2703. ValidateResourceOverlap(*cbuffer, cbufferAllocator, ValCtx);
  2704. }
  2705. }
  2706. static void ValidateShaderFlags(ValidationContext &ValCtx) {
  2707. DxilModule::ShaderFlags calcFlags;
  2708. ValCtx.DxilMod.CollectShaderFlags(calcFlags);
  2709. const uint64_t mask = DxilModule::ShaderFlags::GetShaderFlagsRawForCollection();
  2710. uint64_t declaredFlagsRaw = ValCtx.DxilMod.m_ShaderFlags.GetShaderFlagsRaw();
  2711. uint64_t calcFlagsRaw = calcFlags.GetShaderFlagsRaw();
  2712. declaredFlagsRaw &= mask;
  2713. calcFlagsRaw &= mask;
  2714. if (declaredFlagsRaw == calcFlagsRaw) {
  2715. return;
  2716. }
  2717. ValCtx.EmitError(ValidationRule::MetaFlagsUsage);
  2718. ValCtx.DiagStream() << "Flags declared=" << declaredFlagsRaw
  2719. << ", actual=" << calcFlagsRaw << "\n";
  2720. }
  2721. static void ValidateSignatureElement(DxilSignatureElement &SE,
  2722. ValidationContext &ValCtx) {
  2723. DXIL::SemanticKind semanticKind = SE.GetSemantic()->GetKind();
  2724. CompType::Kind compKind = SE.GetCompType().GetKind();
  2725. DXIL::InterpolationMode Mode = SE.GetInterpolationMode()->GetKind();
  2726. StringRef Name = SE.GetName();
  2727. if (Name.size() < 1 || Name.size() > 64) {
  2728. ValCtx.EmitSignatureError(&SE, ValidationRule::MetaSemanticLen);
  2729. }
  2730. if (semanticKind > DXIL::SemanticKind::Arbitrary && semanticKind < DXIL::SemanticKind::Invalid) {
  2731. if (semanticKind != Semantic::GetByName(SE.GetName())->GetKind()) {
  2732. ValCtx.EmitFormatError(ValidationRule::MetaSemaKindMatchesName,
  2733. {SE.GetName(), SE.GetSemantic()->GetName()});
  2734. }
  2735. }
  2736. switch (compKind) {
  2737. case CompType::Kind::U64:
  2738. case CompType::Kind::I64:
  2739. case CompType::Kind::U32:
  2740. case CompType::Kind::I32:
  2741. case CompType::Kind::U16:
  2742. case CompType::Kind::I16:
  2743. case CompType::Kind::I1:
  2744. switch (Mode) {
  2745. case DXIL::InterpolationMode::Linear:
  2746. case DXIL::InterpolationMode::LinearCentroid:
  2747. case DXIL::InterpolationMode::LinearNoperspective:
  2748. case DXIL::InterpolationMode::LinearNoperspectiveCentroid:
  2749. case DXIL::InterpolationMode::LinearSample:
  2750. case DXIL::InterpolationMode::LinearNoperspectiveSample: {
  2751. ValCtx.EmitFormatError(ValidationRule::MetaIntegerInterpMode, {SE.GetName()});
  2752. } break;
  2753. }
  2754. break;
  2755. case CompType::Kind::F64:
  2756. case CompType::Kind::F32:
  2757. case CompType::Kind::F16:
  2758. case CompType::Kind::SNormF64:
  2759. case CompType::Kind::SNormF32:
  2760. case CompType::Kind::SNormF16:
  2761. case CompType::Kind::UNormF64:
  2762. case CompType::Kind::UNormF32:
  2763. case CompType::Kind::UNormF16:
  2764. break;
  2765. case CompType::Kind::Invalid:
  2766. default:
  2767. ValCtx.EmitFormatError(ValidationRule::MetaSignatureCompType, {SE.GetName()});
  2768. break;
  2769. }
  2770. // Elements that should not appear in the Dxil signature:
  2771. bool bAllowedInSig = true;
  2772. bool bShouldBeAllocated = true;
  2773. switch (SE.GetInterpretation()) {
  2774. case DXIL::SemanticInterpretationKind::NA:
  2775. case DXIL::SemanticInterpretationKind::NotInSig:
  2776. case DXIL::SemanticInterpretationKind::Invalid:
  2777. bAllowedInSig = false;
  2778. __fallthrough;
  2779. case DXIL::SemanticInterpretationKind::NotPacked:
  2780. case DXIL::SemanticInterpretationKind::Shadow:
  2781. bShouldBeAllocated = false;
  2782. break;
  2783. }
  2784. const char *inputOutput = nullptr;
  2785. if (SE.IsInput())
  2786. inputOutput = "Input";
  2787. else if (SE.IsOutput())
  2788. inputOutput = "Output";
  2789. else
  2790. inputOutput = "PatchConstant";
  2791. if (!bAllowedInSig) {
  2792. ValCtx.EmitFormatError(
  2793. ValidationRule::SmSemantic,
  2794. {SE.GetName(), ValCtx.DxilMod.GetShaderModel()->GetKindName().c_str(), inputOutput});
  2795. } else if (bShouldBeAllocated && !SE.IsAllocated()) {
  2796. ValCtx.EmitFormatError(ValidationRule::MetaSemanticShouldBeAllocated,
  2797. {inputOutput, SE.GetName()});
  2798. } else if (!bShouldBeAllocated && SE.IsAllocated()) {
  2799. ValCtx.EmitFormatError(ValidationRule::MetaSemanticShouldNotBeAllocated,
  2800. {inputOutput, SE.GetName()});
  2801. }
  2802. bool bIsClipCull = false;
  2803. bool bIsTessfactor = false;
  2804. switch (semanticKind) {
  2805. case DXIL::SemanticKind::Depth:
  2806. case DXIL::SemanticKind::DepthGreaterEqual:
  2807. case DXIL::SemanticKind::DepthLessEqual:
  2808. if (compKind != CompType::Kind::F32 || SE.GetCols() != 1) {
  2809. ValCtx.EmitFormatError(ValidationRule::MetaSemanticCompType,
  2810. {SE.GetSemantic()->GetName(), "float"});
  2811. }
  2812. break;
  2813. case DXIL::SemanticKind::Coverage:
  2814. DXASSERT(!SE.IsInput() || !bAllowedInSig, "else internal inconsistency between semantic interpretation table and validation code");
  2815. __fallthrough;
  2816. case DXIL::SemanticKind::InnerCoverage:
  2817. case DXIL::SemanticKind::OutputControlPointID:
  2818. if (compKind != CompType::Kind::U32 || SE.GetCols() != 1) {
  2819. ValCtx.EmitFormatError(ValidationRule::MetaSemanticCompType,
  2820. {SE.GetSemantic()->GetName(), "uint"});
  2821. }
  2822. break;
  2823. case DXIL::SemanticKind::Position:
  2824. if (compKind != CompType::Kind::F32 || SE.GetCols() != 4) {
  2825. ValCtx.EmitFormatError(ValidationRule::MetaSemanticCompType,
  2826. {SE.GetSemantic()->GetName(), "float4"});
  2827. }
  2828. break;
  2829. case DXIL::SemanticKind::Target:
  2830. if (compKind == CompType::Kind::F64 ||
  2831. compKind == CompType::Kind::I64 ||
  2832. compKind == CompType::Kind::U64) {
  2833. ValCtx.EmitFormatError(ValidationRule::MetaSemanticCompType,
  2834. {SE.GetSemantic()->GetName(), "float/int/uint"});
  2835. }
  2836. break;
  2837. case DXIL::SemanticKind::ClipDistance:
  2838. case DXIL::SemanticKind::CullDistance:
  2839. bIsClipCull = true;
  2840. if ((compKind != CompType::Kind::F32 && compKind != CompType::Kind::F16)) {
  2841. ValCtx.EmitFormatError(ValidationRule::MetaSemanticCompType,
  2842. {SE.GetSemantic()->GetName(), "float"});
  2843. }
  2844. // NOTE: clip cull distance size is checked at ValidateSignature.
  2845. break;
  2846. case DXIL::SemanticKind::IsFrontFace:
  2847. if (compKind != CompType::Kind::I1 || SE.GetCols() != 1) {
  2848. ValCtx.EmitFormatError(ValidationRule::MetaSemanticCompType,
  2849. {SE.GetSemantic()->GetName(), "bool"});
  2850. }
  2851. break;
  2852. case DXIL::SemanticKind::RenderTargetArrayIndex:
  2853. case DXIL::SemanticKind::ViewPortArrayIndex:
  2854. case DXIL::SemanticKind::VertexID:
  2855. case DXIL::SemanticKind::PrimitiveID:
  2856. case DXIL::SemanticKind::InstanceID:
  2857. case DXIL::SemanticKind::GSInstanceID:
  2858. case DXIL::SemanticKind::SampleIndex:
  2859. case DXIL::SemanticKind::StencilRef:
  2860. if ((compKind != CompType::Kind::U32 && compKind != CompType::Kind::U16) || SE.GetCols() != 1) {
  2861. ValCtx.EmitFormatError(ValidationRule::MetaSemanticCompType,
  2862. {SE.GetSemantic()->GetName(), "uint"});
  2863. }
  2864. break;
  2865. case DXIL::SemanticKind::TessFactor:
  2866. case DXIL::SemanticKind::InsideTessFactor:
  2867. // NOTE: the size check is at CheckPatchConstantSemantic.
  2868. bIsTessfactor = true;
  2869. if (compKind != CompType::Kind::F32) {
  2870. ValCtx.EmitFormatError(ValidationRule::MetaSemanticCompType,
  2871. {SE.GetSemantic()->GetName(), "float"});
  2872. }
  2873. break;
  2874. case DXIL::SemanticKind::Arbitrary:
  2875. break;
  2876. case DXIL::SemanticKind::DomainLocation:
  2877. case DXIL::SemanticKind::Invalid:
  2878. DXASSERT(!bAllowedInSig, "else internal inconsistency between semantic interpretation table and validation code");
  2879. break;
  2880. default:
  2881. ValCtx.EmitSignatureError(&SE, ValidationRule::MetaSemaKindValid);
  2882. break;
  2883. }
  2884. if (ValCtx.DxilMod.GetShaderModel()->IsGS() && SE.IsOutput()) {
  2885. if (SE.GetOutputStream() >= DXIL::kNumOutputStreams) {
  2886. ValCtx.EmitFormatError(ValidationRule::SmStreamIndexRange,
  2887. {std::to_string(SE.GetOutputStream()).c_str(),
  2888. std::to_string(DXIL::kNumOutputStreams - 1).c_str()});
  2889. }
  2890. } else {
  2891. if (SE.GetOutputStream() > 0) {
  2892. ValCtx.EmitFormatError(ValidationRule::SmStreamIndexRange,
  2893. {std::to_string(SE.GetOutputStream()).c_str(),
  2894. "0"});
  2895. }
  2896. }
  2897. if (ValCtx.DxilMod.GetShaderModel()->IsGS()) {
  2898. if (SE.GetOutputStream() != 0) {
  2899. if (ValCtx.DxilMod.GetStreamPrimitiveTopology() !=
  2900. DXIL::PrimitiveTopology::PointList) {
  2901. ValCtx.EmitSignatureError(&SE,
  2902. ValidationRule::SmMultiStreamMustBePoint);
  2903. }
  2904. }
  2905. }
  2906. if (semanticKind == DXIL::SemanticKind::Target) {
  2907. // Verify packed row == semantic index
  2908. unsigned row = SE.GetStartRow();
  2909. for (unsigned i : SE.GetSemanticIndexVec()) {
  2910. if (row != i) {
  2911. ValCtx.EmitSignatureError(&SE, ValidationRule::SmPSTargetIndexMatchesRow);
  2912. }
  2913. ++row;
  2914. }
  2915. // Verify packed col is 0
  2916. if (SE.GetStartCol() != 0) {
  2917. ValCtx.EmitSignatureError(&SE, ValidationRule::SmPSTargetCol0);
  2918. }
  2919. // Verify max row used < 8
  2920. if (SE.GetStartRow() + SE.GetRows() > 8) {
  2921. ValCtx.EmitFormatError(ValidationRule::MetaSemanticIndexMax, {"SV_Target", "7"});
  2922. }
  2923. } else if (bAllowedInSig && semanticKind != DXIL::SemanticKind::Arbitrary) {
  2924. if (!bIsClipCull && SE.GetSemanticStartIndex() > 0) {
  2925. ValCtx.EmitFormatError(ValidationRule::MetaSemanticIndexMax, {SE.GetSemantic()->GetName(), "0"});
  2926. }
  2927. // Maximum rows is 1 for system values other than Target
  2928. // with the exception of tessfactors, which are validated in CheckPatchConstantSemantic
  2929. if (!bIsTessfactor && SE.GetRows() > 1) {
  2930. ValCtx.EmitSignatureError(&SE, ValidationRule::MetaSystemValueRows);
  2931. }
  2932. }
  2933. if (SE.GetCols() + (SE.IsAllocated() ? SE.GetStartCol() : 0) > 4) {
  2934. unsigned size = (SE.GetRows() - 1) * 4 + SE.GetCols();
  2935. ValCtx.EmitFormatError(ValidationRule::MetaSignatureOutOfRange,
  2936. {SE.GetName(),
  2937. std::to_string(SE.GetStartRow()).c_str(),
  2938. std::to_string(SE.GetStartCol()).c_str(),
  2939. std::to_string(size).c_str()});
  2940. }
  2941. if (!SE.GetInterpolationMode()->IsValid()) {
  2942. ValCtx.EmitSignatureError(&SE, ValidationRule::MetaInterpModeValid);
  2943. }
  2944. }
  2945. static void ValidateSignatureOverlap(
  2946. DxilSignatureElement &E, unsigned maxScalars,
  2947. DxilSignatureAllocator &allocator,
  2948. ValidationContext &ValCtx) {
  2949. // Skip entries that are not or should not be allocated. Validation occurs in ValidateSignatureElement.
  2950. if (!E.IsAllocated())
  2951. return;
  2952. switch (E.GetInterpretation()) {
  2953. case DXIL::SemanticInterpretationKind::NA:
  2954. case DXIL::SemanticInterpretationKind::NotInSig:
  2955. case DXIL::SemanticInterpretationKind::Invalid:
  2956. case DXIL::SemanticInterpretationKind::NotPacked:
  2957. case DXIL::SemanticInterpretationKind::Shadow:
  2958. return;
  2959. }
  2960. DxilSignatureAllocator::ConflictType conflict = allocator.DetectRowConflict(&E, E.GetStartRow());
  2961. if (conflict == DxilSignatureAllocator::kNoConflict || conflict == DxilSignatureAllocator::kInsufficientFreeComponents)
  2962. conflict = allocator.DetectColConflict(&E, E.GetStartRow(), E.GetStartCol());
  2963. switch (conflict) {
  2964. case DxilSignatureAllocator::kNoConflict:
  2965. allocator.PlaceElement(&E, E.GetStartRow(), E.GetStartCol());
  2966. break;
  2967. case DxilSignatureAllocator::kConflictsWithIndexed:
  2968. ValCtx.EmitFormatError(ValidationRule::MetaSignatureIndexConflict,
  2969. {E.GetName(),
  2970. std::to_string(E.GetStartRow()).c_str(),
  2971. std::to_string(E.GetStartCol()).c_str(),
  2972. std::to_string(E.GetRows()).c_str(),
  2973. std::to_string(E.GetCols()).c_str()});
  2974. break;
  2975. case DxilSignatureAllocator::kConflictsWithIndexedTessFactor:
  2976. ValCtx.EmitFormatError(ValidationRule::MetaSignatureIndexConflict,
  2977. {E.GetName(),
  2978. std::to_string(E.GetStartRow()).c_str(),
  2979. std::to_string(E.GetStartCol()).c_str(),
  2980. std::to_string(E.GetRows()).c_str(),
  2981. std::to_string(E.GetCols()).c_str()});
  2982. break;
  2983. case DxilSignatureAllocator::kConflictsWithInterpolationMode:
  2984. ValCtx.EmitFormatError(ValidationRule::MetaInterpModeInOneRow,
  2985. {E.GetName(),
  2986. std::to_string(E.GetStartRow()).c_str(),
  2987. std::to_string(E.GetStartCol()).c_str(),
  2988. std::to_string(E.GetRows()).c_str(),
  2989. std::to_string(E.GetCols()).c_str()});
  2990. break;
  2991. case DxilSignatureAllocator::kInsufficientFreeComponents:
  2992. DXASSERT(false, "otherwise, conflict not translated");
  2993. break;
  2994. case DxilSignatureAllocator::kOverlapElement:
  2995. ValCtx.EmitFormatError(ValidationRule::MetaSignatureOverlap,
  2996. {E.GetName(),
  2997. std::to_string(E.GetStartRow()).c_str(),
  2998. std::to_string(E.GetStartCol()).c_str(),
  2999. std::to_string(E.GetRows()).c_str(),
  3000. std::to_string(E.GetCols()).c_str()});
  3001. break;
  3002. case DxilSignatureAllocator::kIllegalComponentOrder:
  3003. ValCtx.EmitFormatError(ValidationRule::MetaSignatureIllegalComponentOrder,
  3004. {E.GetName(),
  3005. std::to_string(E.GetStartRow()).c_str(),
  3006. std::to_string(E.GetStartCol()).c_str(),
  3007. std::to_string(E.GetRows()).c_str(),
  3008. std::to_string(E.GetCols()).c_str()});
  3009. break;
  3010. case DxilSignatureAllocator::kConflictFit:
  3011. ValCtx.EmitFormatError(ValidationRule::MetaSignatureOutOfRange,
  3012. {E.GetName(),
  3013. std::to_string(E.GetStartRow()).c_str(),
  3014. std::to_string(E.GetStartCol()).c_str(),
  3015. std::to_string(E.GetRows()).c_str(),
  3016. std::to_string(E.GetCols()).c_str()});
  3017. break;
  3018. default:
  3019. DXASSERT(false, "otherwise, unrecognized conflict type from DxilSignatureAllocator");
  3020. }
  3021. }
  3022. static void ValidateSignature(ValidationContext &ValCtx, const DxilSignature &S,
  3023. unsigned maxScalars) {
  3024. DxilSignatureAllocator allocator[DXIL::kNumOutputStreams] = {32, 32, 32, 32};
  3025. unordered_set<Semantic::Kind> semanticUsageSet[DXIL::kNumOutputStreams];
  3026. StringMap<unordered_set<unsigned>> semanticIndexMap[DXIL::kNumOutputStreams];
  3027. unordered_set<unsigned> clipcullRowSet[DXIL::kNumOutputStreams];
  3028. unsigned clipcullComponents[DXIL::kNumOutputStreams] = {0, 0, 0, 0};
  3029. bool isOutput = S.IsOutput();
  3030. unsigned TargetMask = 0;
  3031. DXIL::SemanticKind DepthKind = DXIL::SemanticKind::Invalid;
  3032. for (auto &E : S.GetElements()) {
  3033. DXIL::SemanticKind semanticKind = E->GetSemantic()->GetKind();
  3034. ValidateSignatureElement(*E, ValCtx);
  3035. // Avoid OOB indexing on streamId.
  3036. unsigned streamId = E->GetOutputStream();
  3037. if (streamId >= DXIL::kNumOutputStreams ||
  3038. !isOutput ||
  3039. !ValCtx.DxilMod.GetShaderModel()->IsGS()) {
  3040. streamId = 0;
  3041. }
  3042. // Semantic index overlap check, keyed by name.
  3043. std::string nameUpper(E->GetName());
  3044. std::transform(nameUpper.begin(), nameUpper.end(), nameUpper.begin(), toupper);
  3045. unordered_set<unsigned> &semIdxSet = semanticIndexMap[streamId][nameUpper];
  3046. for (unsigned semIdx : E->GetSemanticIndexVec()) {
  3047. if (semIdxSet.count(semIdx) > 0) {
  3048. ValCtx.EmitFormatError(ValidationRule::MetaNoSemanticOverlap,
  3049. {E->GetName(), std::to_string(semIdx).c_str()});
  3050. return;
  3051. } else
  3052. semIdxSet.insert(semIdx);
  3053. }
  3054. // SV_Target has special rules
  3055. if (semanticKind == DXIL::SemanticKind::Target) {
  3056. // Validate target overlap
  3057. if (E->GetStartRow() + E->GetRows() <= 8) {
  3058. unsigned mask = ((1 << E->GetRows()) - 1) << E->GetStartRow();
  3059. if (TargetMask & mask) {
  3060. ValCtx.EmitFormatError(ValidationRule::MetaNoSemanticOverlap,
  3061. {"SV_Target", std::to_string(E->GetStartRow()).c_str()});
  3062. }
  3063. TargetMask = TargetMask | mask;
  3064. }
  3065. if (E->GetRows() > 1) {
  3066. ValCtx.EmitError(ValidationRule::SmNoPSOutputIdx);
  3067. }
  3068. continue;
  3069. }
  3070. if (E->GetSemantic()->IsInvalid())
  3071. continue;
  3072. // validate system value semantic rules
  3073. switch (semanticKind) {
  3074. case DXIL::SemanticKind::Arbitrary:
  3075. break;
  3076. case DXIL::SemanticKind::ClipDistance:
  3077. case DXIL::SemanticKind::CullDistance:
  3078. // Validate max 8 components across 2 rows (registers)
  3079. clipcullRowSet[streamId].insert(E->GetStartRow());
  3080. if (clipcullRowSet[streamId].size() > 2) {
  3081. ValCtx.EmitError(ValidationRule::MetaClipCullMaxRows);
  3082. }
  3083. clipcullComponents[streamId] += E->GetCols();
  3084. if (clipcullComponents[streamId] > 8) {
  3085. ValCtx.EmitError(ValidationRule::MetaClipCullMaxComponents);
  3086. }
  3087. break;
  3088. case DXIL::SemanticKind::Depth:
  3089. case DXIL::SemanticKind::DepthGreaterEqual:
  3090. case DXIL::SemanticKind::DepthLessEqual:
  3091. if (DepthKind != DXIL::SemanticKind::Invalid) {
  3092. ValCtx.EmitError(ValidationRule::SmPSMultipleDepthSemantic);
  3093. }
  3094. DepthKind = semanticKind;
  3095. break;
  3096. default:
  3097. if (semanticUsageSet[streamId].count(semanticKind) > 0) {
  3098. ValCtx.EmitFormatError(ValidationRule::MetaDuplicateSysValue,
  3099. {E->GetSemantic()->GetName()});
  3100. }
  3101. semanticUsageSet[streamId].insert(semanticKind);
  3102. break;
  3103. }
  3104. // Packed element overlap check.
  3105. ValidateSignatureOverlap(*E.get(), maxScalars, allocator[streamId], ValCtx);
  3106. if (isOutput && semanticKind == DXIL::SemanticKind::Position) {
  3107. ValCtx.hasOutputPosition[E->GetOutputStream()] = true;
  3108. }
  3109. }
  3110. }
  3111. static void ValidateNoInterpModeSignature(ValidationContext &ValCtx, const DxilSignature &S) {
  3112. for (auto &E : S.GetElements()) {
  3113. if (!E->GetInterpolationMode()->IsUndefined()) {
  3114. ValCtx.EmitSignatureError(E.get(), ValidationRule::SmNoInterpMode);
  3115. }
  3116. }
  3117. }
  3118. static void ValidateSignatures(ValidationContext &ValCtx) {
  3119. DxilModule &M = ValCtx.DxilMod;
  3120. bool isPS = M.GetShaderModel()->IsPS();
  3121. bool isVS = M.GetShaderModel()->IsVS();
  3122. bool isGS = M.GetShaderModel()->IsGS();
  3123. bool isCS = M.GetShaderModel()->IsCS();
  3124. if (isPS) {
  3125. // PS output no interp mode.
  3126. ValidateNoInterpModeSignature(ValCtx, ValCtx.DxilMod.GetOutputSignature());
  3127. } else if (isVS) {
  3128. // VS input no interp mode.
  3129. ValidateNoInterpModeSignature(ValCtx, ValCtx.DxilMod.GetInputSignature());
  3130. }
  3131. // patch constant no interp mode.
  3132. ValidateNoInterpModeSignature(ValCtx, ValCtx.DxilMod.GetPatchConstantSignature());
  3133. unsigned maxInputScalars = DXIL::kMaxInputTotalScalars;
  3134. unsigned maxOutputScalars = 0;
  3135. unsigned maxPatchConstantScalars = 0;
  3136. switch (M.GetShaderModel()->GetKind()) {
  3137. case DXIL::ShaderKind::Compute:
  3138. break;
  3139. case DXIL::ShaderKind::Vertex:
  3140. case DXIL::ShaderKind::Geometry:
  3141. case DXIL::ShaderKind::Pixel:
  3142. maxOutputScalars = DXIL::kMaxOutputTotalScalars;
  3143. break;
  3144. case DXIL::ShaderKind::Hull:
  3145. case DXIL::ShaderKind::Domain:
  3146. maxOutputScalars = DXIL::kMaxOutputTotalScalars;
  3147. maxPatchConstantScalars = DXIL::kMaxHSOutputPatchConstantTotalScalars;
  3148. break;
  3149. }
  3150. ValidateSignature(ValCtx, ValCtx.DxilMod.GetInputSignature(), maxInputScalars);
  3151. ValidateSignature(ValCtx, ValCtx.DxilMod.GetOutputSignature(), maxOutputScalars);
  3152. ValidateSignature(ValCtx, ValCtx.DxilMod.GetPatchConstantSignature(), maxPatchConstantScalars);
  3153. if (isPS) {
  3154. // Gather execution information.
  3155. hlsl::PSExecutionInfo &PSExec = ValCtx.PSExec;
  3156. for (auto &E : ValCtx.DxilMod.GetInputSignature().GetElements()) {
  3157. if (E->GetKind() == DXIL::SemanticKind::SampleIndex) {
  3158. PSExec.SuperSampling = true;
  3159. continue;
  3160. }
  3161. const InterpolationMode *IM = E->GetInterpolationMode();
  3162. if (IM->IsLinearSample() || IM->IsLinearNoperspectiveSample()) {
  3163. PSExec.SuperSampling = true;
  3164. }
  3165. if (E->GetKind() == DXIL::SemanticKind::Position) {
  3166. PSExec.PositionInterpolationMode = IM;
  3167. }
  3168. }
  3169. for (auto &E : ValCtx.DxilMod.GetOutputSignature().GetElements()) {
  3170. if (E->IsAnyDepth()) {
  3171. PSExec.OutputDepthKind = E->GetKind();
  3172. break;
  3173. }
  3174. }
  3175. if (!PSExec.SuperSampling &&
  3176. PSExec.OutputDepthKind != DXIL::SemanticKind::Invalid &&
  3177. PSExec.OutputDepthKind != DXIL::SemanticKind::Depth) {
  3178. if (PSExec.PositionInterpolationMode != nullptr) {
  3179. if (!PSExec.PositionInterpolationMode->IsUndefined() &&
  3180. !PSExec.PositionInterpolationMode->IsLinearNoperspectiveCentroid() &&
  3181. !PSExec.PositionInterpolationMode->IsLinearNoperspectiveSample()) {
  3182. ValCtx.EmitError(ValidationRule::SmPSConsistentInterp);
  3183. }
  3184. }
  3185. }
  3186. // Validate PS output semantic.
  3187. DxilSignature &outputSig = M.GetOutputSignature();
  3188. for (auto &SE : outputSig.GetElements()) {
  3189. Semantic::Kind semanticKind = SE->GetSemantic()->GetKind();
  3190. switch (semanticKind) {
  3191. case Semantic::Kind::Target:
  3192. case Semantic::Kind::Coverage:
  3193. case Semantic::Kind::Depth:
  3194. case Semantic::Kind::DepthGreaterEqual:
  3195. case Semantic::Kind::DepthLessEqual:
  3196. case Semantic::Kind::StencilRef:
  3197. break;
  3198. default: {
  3199. ValCtx.EmitFormatError(ValidationRule::SmPSOutputSemantic, {SE->GetName()});
  3200. } break;
  3201. }
  3202. }
  3203. }
  3204. if (isGS) {
  3205. unsigned maxVertexCount = M.GetMaxVertexCount();
  3206. unsigned outputScalarCount = 0;
  3207. DxilSignature &outSig = ValCtx.DxilMod.GetOutputSignature();
  3208. for (auto &SE : outSig.GetElements()) {
  3209. outputScalarCount += SE->GetRows() * SE->GetCols();
  3210. }
  3211. unsigned totalOutputScalars = maxVertexCount * outputScalarCount;
  3212. if (totalOutputScalars > DXIL::kMaxGSOutputTotalScalars) {
  3213. ValCtx.EmitFormatError(
  3214. ValidationRule::SmGSTotalOutputVertexDataRange,
  3215. {std::to_string(maxVertexCount).c_str(),
  3216. std::to_string(outputScalarCount).c_str(),
  3217. std::to_string(totalOutputScalars).c_str(),
  3218. std::to_string(DXIL::kMaxGSOutputTotalScalars).c_str()});
  3219. }
  3220. }
  3221. if (isCS) {
  3222. if (!ValCtx.DxilMod.GetOutputSignature().GetElements().empty() ||
  3223. !ValCtx.DxilMod.GetPatchConstantSignature().GetElements().empty()) {
  3224. ValCtx.EmitError(ValidationRule::SmCSNoReturn);
  3225. }
  3226. }
  3227. }
  3228. static void CheckPatchConstantSemantic(ValidationContext &ValCtx)
  3229. {
  3230. bool isHS = ValCtx.DxilMod.GetShaderModel()->IsHS();
  3231. DXIL::TessellatorDomain domain = ValCtx.DxilMod.GetTessellatorDomain();
  3232. DxilSignature &patchConstantSig = ValCtx.DxilMod.GetPatchConstantSignature();
  3233. const unsigned kQuadEdgeSize = 4;
  3234. const unsigned kQuadInsideSize = 2;
  3235. const unsigned kQuadDomainLocSize = 2;
  3236. const unsigned kTriEdgeSize = 3;
  3237. const unsigned kTriInsideSize = 1;
  3238. const unsigned kTriDomainLocSize = 3;
  3239. const unsigned kIsolineEdgeSize = 2;
  3240. const unsigned kIsolineInsideSize = 0;
  3241. const unsigned kIsolineDomainLocSize = 3;
  3242. const char *domainName = "";
  3243. DXIL::SemanticKind kEdgeSemantic = DXIL::SemanticKind::TessFactor;
  3244. unsigned edgeSize = 0;
  3245. DXIL::SemanticKind kInsideSemantic = DXIL::SemanticKind::InsideTessFactor;
  3246. unsigned insideSize = 0;
  3247. ValCtx.domainLocSize = 0;
  3248. switch (domain) {
  3249. case DXIL::TessellatorDomain::IsoLine:
  3250. domainName = "IsoLine";
  3251. edgeSize = kIsolineEdgeSize;
  3252. insideSize = kIsolineInsideSize;
  3253. ValCtx.domainLocSize = kIsolineDomainLocSize;
  3254. break;
  3255. case DXIL::TessellatorDomain::Tri:
  3256. domainName = "Tri";
  3257. edgeSize = kTriEdgeSize;
  3258. insideSize = kTriInsideSize;
  3259. ValCtx.domainLocSize = kTriDomainLocSize;
  3260. break;
  3261. case DXIL::TessellatorDomain::Quad:
  3262. domainName = "Quad";
  3263. edgeSize = kQuadEdgeSize;
  3264. insideSize = kQuadInsideSize;
  3265. ValCtx.domainLocSize = kQuadDomainLocSize;
  3266. break;
  3267. default:
  3268. // Don't bother with other tests if domain is invalid
  3269. return;
  3270. }
  3271. bool bFoundEdgeSemantic = false;
  3272. bool bFoundInsideSemantic = false;
  3273. for (auto &SE : patchConstantSig.GetElements()) {
  3274. Semantic::Kind kind = SE->GetSemantic()->GetKind();
  3275. if (kind == kEdgeSemantic) {
  3276. bFoundEdgeSemantic = true;
  3277. if (SE->GetRows() != edgeSize || SE->GetCols() > 1) {
  3278. ValCtx.EmitFormatError(ValidationRule::SmTessFactorSizeMatchDomain,
  3279. {std::to_string(SE->GetRows()).c_str(),
  3280. std::to_string(SE->GetCols()).c_str(),
  3281. domainName,
  3282. std::to_string(edgeSize).c_str()});
  3283. }
  3284. } else if (kind == kInsideSemantic) {
  3285. bFoundInsideSemantic = true;
  3286. if (SE->GetRows() != insideSize || SE->GetCols() > 1) {
  3287. ValCtx.EmitFormatError(ValidationRule::SmInsideTessFactorSizeMatchDomain,
  3288. {std::to_string(SE->GetRows()).c_str(),
  3289. std::to_string(SE->GetCols()).c_str(),
  3290. domainName,
  3291. std::to_string(insideSize).c_str()});
  3292. }
  3293. }
  3294. }
  3295. if (isHS) {
  3296. if (!bFoundEdgeSemantic) {
  3297. ValCtx.EmitError(ValidationRule::SmTessFactorForDomain);
  3298. }
  3299. if (!bFoundInsideSemantic && domain != DXIL::TessellatorDomain::IsoLine) {
  3300. ValCtx.EmitError(ValidationRule::SmTessFactorForDomain);
  3301. }
  3302. }
  3303. }
  3304. static void ValidateShaderState(ValidationContext &ValCtx) {
  3305. DxilModule &M = ValCtx.DxilMod;
  3306. DXIL::ShaderKind ShaderType = M.GetShaderModel()->GetKind();
  3307. if (ShaderType == DXIL::ShaderKind::Compute) {
  3308. unsigned x = M.m_NumThreads[0];
  3309. unsigned y = M.m_NumThreads[1];
  3310. unsigned z = M.m_NumThreads[2];
  3311. unsigned threadsInGroup = x * y * z;
  3312. if ((x < DXIL::kMinCSThreadGroupX) || (x > DXIL::kMaxCSThreadGroupX)) {
  3313. ValCtx.EmitFormatError(
  3314. ValidationRule::SmThreadGroupChannelRange,
  3315. {"X", std::to_string(x).c_str(),
  3316. std::to_string(DXIL::kMinCSThreadGroupX).c_str(),
  3317. std::to_string(DXIL::kMaxCSThreadGroupX).c_str()});
  3318. }
  3319. if ((y < DXIL::kMinCSThreadGroupY) || (y > DXIL::kMaxCSThreadGroupY)) {
  3320. ValCtx.EmitFormatError(
  3321. ValidationRule::SmThreadGroupChannelRange,
  3322. {"Y", std::to_string(y).c_str(),
  3323. std::to_string(DXIL::kMinCSThreadGroupY).c_str(),
  3324. std::to_string(DXIL::kMaxCSThreadGroupY).c_str()});
  3325. }
  3326. if ((z < DXIL::kMinCSThreadGroupZ) || (z > DXIL::kMaxCSThreadGroupZ)) {
  3327. ValCtx.EmitFormatError(
  3328. ValidationRule::SmThreadGroupChannelRange,
  3329. {"Z", std::to_string(z).c_str(),
  3330. std::to_string(DXIL::kMinCSThreadGroupZ).c_str(),
  3331. std::to_string(DXIL::kMaxCSThreadGroupZ).c_str()});
  3332. }
  3333. if (threadsInGroup > DXIL::kMaxCSThreadsPerGroup) {
  3334. ValCtx.EmitFormatError(
  3335. ValidationRule::SmMaxTheadGroup,
  3336. {std::to_string(threadsInGroup).c_str(),
  3337. std::to_string(DXIL::kMaxCSThreadsPerGroup).c_str()});
  3338. }
  3339. // type of threadID, thread group ID take care by DXIL operation overload
  3340. // check.
  3341. } else if (ShaderType == DXIL::ShaderKind::Domain) {
  3342. DXIL::TessellatorDomain domain = M.GetTessellatorDomain();
  3343. if (domain >= DXIL::TessellatorDomain::LastEntry)
  3344. domain = DXIL::TessellatorDomain::Undefined;
  3345. unsigned inputControlPointCount = M.GetInputControlPointCount();
  3346. if (inputControlPointCount > DXIL::kMaxIAPatchControlPointCount) {
  3347. ValCtx.EmitFormatError(
  3348. ValidationRule::SmDSInputControlPointCountRange,
  3349. {std::to_string(DXIL::kMaxIAPatchControlPointCount).c_str(),
  3350. std::to_string(inputControlPointCount).c_str()});
  3351. }
  3352. if (domain == DXIL::TessellatorDomain::Undefined) {
  3353. ValCtx.EmitError(ValidationRule::SmValidDomain);
  3354. }
  3355. CheckPatchConstantSemantic(ValCtx);
  3356. } else if (ShaderType == DXIL::ShaderKind::Hull) {
  3357. DXIL::TessellatorDomain domain = M.GetTessellatorDomain();
  3358. if (domain >= DXIL::TessellatorDomain::LastEntry)
  3359. domain = DXIL::TessellatorDomain::Undefined;
  3360. unsigned inputControlPointCount = M.GetInputControlPointCount();
  3361. if (inputControlPointCount < 1 ||
  3362. inputControlPointCount > DXIL::kMaxIAPatchControlPointCount) {
  3363. ValCtx.EmitFormatError(
  3364. ValidationRule::SmHSInputControlPointCountRange,
  3365. {std::to_string(DXIL::kMaxIAPatchControlPointCount).c_str(),
  3366. std::to_string(inputControlPointCount).c_str()});
  3367. }
  3368. if (domain == DXIL::TessellatorDomain::Undefined) {
  3369. ValCtx.EmitError(ValidationRule::SmValidDomain);
  3370. }
  3371. DXIL::TessellatorPartitioning partition = M.GetTessellatorPartitioning();
  3372. if (partition == DXIL::TessellatorPartitioning::Undefined) {
  3373. ValCtx.EmitError(ValidationRule::MetaTessellatorPartition);
  3374. }
  3375. DXIL::TessellatorOutputPrimitive tessOutputPrimitive =
  3376. M.GetTessellatorOutputPrimitive();
  3377. if (tessOutputPrimitive == DXIL::TessellatorOutputPrimitive::Undefined ||
  3378. tessOutputPrimitive == DXIL::TessellatorOutputPrimitive::LastEntry) {
  3379. ValCtx.EmitError(ValidationRule::MetaTessellatorOutputPrimitive);
  3380. }
  3381. float maxTessFactor = M.GetMaxTessellationFactor();
  3382. if (maxTessFactor < DXIL::kHSMaxTessFactorLowerBound ||
  3383. maxTessFactor > DXIL::kHSMaxTessFactorUpperBound) {
  3384. ValCtx.EmitFormatError(
  3385. ValidationRule::MetaMaxTessFactor,
  3386. {std::to_string(DXIL::kHSMaxTessFactorLowerBound).c_str(),
  3387. std::to_string(DXIL::kHSMaxTessFactorUpperBound).c_str(),
  3388. std::to_string(maxTessFactor).c_str()});
  3389. }
  3390. // Domain and OutPrimivtive match.
  3391. switch (domain) {
  3392. case DXIL::TessellatorDomain::IsoLine:
  3393. switch (tessOutputPrimitive) {
  3394. case DXIL::TessellatorOutputPrimitive::TriangleCW:
  3395. case DXIL::TessellatorOutputPrimitive::TriangleCCW:
  3396. ValCtx.EmitError(ValidationRule::SmIsoLineOutputPrimitiveMismatch);
  3397. break;
  3398. }
  3399. break;
  3400. case DXIL::TessellatorDomain::Tri:
  3401. switch (tessOutputPrimitive) {
  3402. case DXIL::TessellatorOutputPrimitive::Line:
  3403. ValCtx.EmitError(ValidationRule::SmTriOutputPrimitiveMismatch);
  3404. break;
  3405. }
  3406. break;
  3407. case DXIL::TessellatorDomain::Quad:
  3408. switch (tessOutputPrimitive) {
  3409. case DXIL::TessellatorOutputPrimitive::Line:
  3410. ValCtx.EmitError(ValidationRule::SmTriOutputPrimitiveMismatch);
  3411. break;
  3412. }
  3413. break;
  3414. default:
  3415. ValCtx.EmitError(ValidationRule::SmValidDomain);
  3416. break;
  3417. }
  3418. // Check pass thru HS.
  3419. if (M.GetEntryFunction() == nullptr) {
  3420. if (M.GetShaderModel()->IsHS()) {
  3421. if (M.GetInputControlPointCount() < M.GetOutputControlPointCount()) {
  3422. ValCtx.EmitError(
  3423. ValidationRule::SmHullPassThruControlPointCountMatch);
  3424. }
  3425. // Check declared control point outputs storage amounts are ok to pass
  3426. // through (less output storage than input for control points).
  3427. DxilSignature &outSig = M.GetOutputSignature();
  3428. unsigned totalOutputCPScalars = 0;
  3429. for (auto &SE : outSig.GetElements()) {
  3430. totalOutputCPScalars += SE->GetRows() * SE->GetCols();
  3431. }
  3432. if (totalOutputCPScalars * M.GetOutputControlPointCount() >
  3433. DXIL::kMaxHSOutputControlPointsTotalScalars) {
  3434. ValCtx.EmitError(ValidationRule::SmOutputControlPointsTotalScalars);
  3435. }
  3436. } else {
  3437. ValCtx.EmitError(ValidationRule::MetaEntryFunction);
  3438. }
  3439. }
  3440. CheckPatchConstantSemantic(ValCtx);
  3441. } else if (ShaderType == DXIL::ShaderKind::Geometry) {
  3442. unsigned maxVertexCount = M.GetMaxVertexCount();
  3443. if (maxVertexCount > DXIL::kMaxGSOutputVertexCount) {
  3444. ValCtx.EmitFormatError(
  3445. ValidationRule::SmGSOutputVertexCountRange,
  3446. {std::to_string(DXIL::kMaxGSOutputVertexCount).c_str(),
  3447. std::to_string(maxVertexCount).c_str()});
  3448. }
  3449. unsigned instanceCount = M.GetGSInstanceCount();
  3450. if (instanceCount > DXIL::kMaxGSInstanceCount || instanceCount < 1) {
  3451. ValCtx.EmitFormatError(ValidationRule::SmGSInstanceCountRange,
  3452. {std::to_string(DXIL::kMaxGSInstanceCount).c_str(),
  3453. std::to_string(instanceCount).c_str()});
  3454. }
  3455. DXIL::PrimitiveTopology topo = M.GetStreamPrimitiveTopology();
  3456. switch (topo) {
  3457. case DXIL::PrimitiveTopology::PointList:
  3458. case DXIL::PrimitiveTopology::LineStrip:
  3459. case DXIL::PrimitiveTopology::TriangleStrip:
  3460. break;
  3461. default: {
  3462. ValCtx.EmitError(ValidationRule::SmGSValidOutputPrimitiveTopology);
  3463. } break;
  3464. }
  3465. DXIL::InputPrimitive inputPrimitive = M.GetInputPrimitive();
  3466. unsigned VertexCount = GetNumVertices(inputPrimitive);
  3467. if (VertexCount == 0 && inputPrimitive != DXIL::InputPrimitive::Undefined) {
  3468. ValCtx.EmitError(ValidationRule::SmGSValidInputPrimitive);
  3469. }
  3470. }
  3471. unsigned outputControlPointCount = M.GetOutputControlPointCount();
  3472. if (outputControlPointCount > DXIL::kMaxIAPatchControlPointCount) {
  3473. ValCtx.EmitFormatError(
  3474. ValidationRule::SmOutputControlPointCountRange,
  3475. {std::to_string(DXIL::kMaxIAPatchControlPointCount).c_str(),
  3476. std::to_string(outputControlPointCount).c_str()});
  3477. }
  3478. }
  3479. static bool
  3480. CalculateCallDepth(CallGraphNode *node,
  3481. std::unordered_map<CallGraphNode *, unsigned> &depthMap,
  3482. std::unordered_set<CallGraphNode *> &callStack,
  3483. std::unordered_set<Function *> &funcSet) {
  3484. unsigned depth = callStack.size();
  3485. funcSet.insert(node->getFunction());
  3486. for (auto it = node->begin(), ei = node->end(); it != ei; it++) {
  3487. CallGraphNode *toNode = it->second;
  3488. if (callStack.count(toNode) > 0) {
  3489. // Recursive
  3490. return true;
  3491. }
  3492. if (depthMap[toNode] < depth)
  3493. depthMap[toNode] = depth;
  3494. callStack.insert(toNode);
  3495. if (CalculateCallDepth(toNode, depthMap, callStack, funcSet)) {
  3496. // Recursive
  3497. return true;
  3498. }
  3499. callStack.erase(toNode);
  3500. }
  3501. return false;
  3502. }
  3503. static void ValidateCallGraph(ValidationContext &ValCtx) {
  3504. // Build CallGraph.
  3505. CallGraph CG(*ValCtx.DxilMod.GetModule());
  3506. std::unordered_map<CallGraphNode*, unsigned> depthMap;
  3507. std::unordered_set<CallGraphNode*> callStack;
  3508. CallGraphNode *entryNode = CG[ValCtx.DxilMod.GetEntryFunction()];
  3509. depthMap[entryNode] = 0;
  3510. bool bRecursive = CalculateCallDepth(entryNode, depthMap, callStack, ValCtx.entryFuncCallSet);
  3511. if (ValCtx.DxilMod.GetShaderModel()->IsHS()) {
  3512. CallGraphNode *patchConstantNode = CG[ValCtx.DxilMod.GetPatchConstantFunction()];
  3513. depthMap[patchConstantNode] = 0;
  3514. callStack.clear();
  3515. bRecursive |= CalculateCallDepth(patchConstantNode, depthMap, callStack, ValCtx.patchConstFuncCallSet);
  3516. }
  3517. if (bRecursive) {
  3518. ValCtx.EmitError(ValidationRule::FlowNoRecusion);
  3519. }
  3520. }
  3521. static void ValidateFlowControl(ValidationContext &ValCtx) {
  3522. bool reducible =
  3523. IsReducible(*ValCtx.DxilMod.GetModule(), IrreducibilityAction::Ignore);
  3524. if (!reducible) {
  3525. ValCtx.EmitError(ValidationRule::FlowReducible);
  3526. return;
  3527. }
  3528. ValidateCallGraph(ValCtx);
  3529. for (auto &F : ValCtx.DxilMod.GetModule()->functions()) {
  3530. if (F.isDeclaration())
  3531. continue;
  3532. DominatorTreeAnalysis DTA;
  3533. DominatorTree DT = DTA.run(F);
  3534. LoopInfo LI;
  3535. LI.Analyze(DT);
  3536. for (auto loopIt = LI.begin(); loopIt != LI.end(); loopIt++) {
  3537. Loop *loop = *loopIt;
  3538. SmallVector<BasicBlock *, 4> exitBlocks;
  3539. loop->getExitBlocks(exitBlocks);
  3540. if (exitBlocks.empty())
  3541. ValCtx.EmitError(ValidationRule::FlowDeadLoop);
  3542. }
  3543. }
  3544. // fxc has ERR_CONTINUE_INSIDE_SWITCH to disallow continue in switch.
  3545. // Not do it for now.
  3546. }
  3547. static void ValidateUninitializedOutput(ValidationContext &ValCtx) {
  3548. // For HS only need to check Tessfactor which is in patch constant sig.
  3549. if (ValCtx.DxilMod.GetShaderModel()->IsHS()) {
  3550. std::vector<unsigned> &patchConstCols = ValCtx.patchConstCols;
  3551. for (auto &E : ValCtx.DxilMod.GetPatchConstantSignature().GetElements()) {
  3552. unsigned mask = patchConstCols[E->GetID()];
  3553. unsigned requireMask = (1 << E->GetCols()) - 1;
  3554. // TODO: check other case uninitialized output is allowed.
  3555. if (mask != requireMask && !E->GetSemantic()->IsArbitrary()) {
  3556. ValCtx.EmitFormatError(ValidationRule::SmUndefinedOutput,
  3557. {E->GetName()});
  3558. }
  3559. }
  3560. return;
  3561. }
  3562. std::vector<unsigned> &outputCols = ValCtx.outputCols;
  3563. for (auto &E : ValCtx.DxilMod.GetOutputSignature().GetElements()) {
  3564. unsigned mask = outputCols[E->GetID()];
  3565. unsigned requireMask = (1 << E->GetCols()) - 1;
  3566. // TODO: check other case uninitialized output is allowed.
  3567. if (mask != requireMask && !E->GetSemantic()->IsArbitrary() &&
  3568. E->GetSemantic()->GetKind() != Semantic::Kind::Target) {
  3569. ValCtx.EmitFormatError(ValidationRule::SmUndefinedOutput, {E->GetName()});
  3570. }
  3571. }
  3572. }
  3573. void GetValidationVersion(_Out_ unsigned *pMajor, _Out_ unsigned *pMinor) {
  3574. // Bump these versions after 1.0 to account for additional validation rules.
  3575. *pMajor = 1;
  3576. *pMinor = 0;
  3577. }
  3578. _Use_decl_annotations_ std::error_code
  3579. ValidateDxilModule(llvm::Module *pModule, llvm::Module *pDebugModule) {
  3580. const LLVMContext &Ctx = pModule->getContext();
  3581. std::string diagStr;
  3582. raw_string_ostream diagStream(diagStr);
  3583. DiagnosticPrinterRawOStream DiagPrinter(diagStream);
  3584. DxilModule *pDxilModule;
  3585. // TODO: add detail error in DxilMDHelper.
  3586. try {
  3587. pDxilModule = &pModule->GetOrCreateDxilModule();
  3588. } catch (const ::hlsl::Exception &hlslException) {
  3589. DiagPrinter << "load dxil metadata failed -";
  3590. try {
  3591. const char *msg = hlslException.what();
  3592. if (msg == nullptr || *msg == '\0')
  3593. DiagPrinter << " error code " << hlslException.hr << "\n";
  3594. else
  3595. DiagPrinter << msg;
  3596. } catch (...) {
  3597. DiagPrinter << " unable to retrieve error message.\n";
  3598. }
  3599. emitDxilDiag(Ctx, diagStr.c_str());
  3600. return std::error_code(ERROR_INVALID_DATA, std::system_category());
  3601. } catch (...) {
  3602. emitDxilDiag(Ctx, "load dxil metadata failed - unknown error.\n");
  3603. return std::error_code(ERROR_INVALID_DATA, std::system_category());
  3604. }
  3605. ValidationContext ValCtx(*pModule, pDebugModule, *pDxilModule, DiagPrinter);
  3606. ValidateMetadata(ValCtx);
  3607. ValidateShaderState(ValCtx);
  3608. ValidateGlobalVariables(ValCtx);
  3609. ValidateResources(ValCtx);
  3610. ValidateSignatures(ValCtx);
  3611. // Validate control flow and collect function call info.
  3612. // If has recursive call, call info collection will not finish.
  3613. ValidateFlowControl(ValCtx);
  3614. // Validate functions.
  3615. for (Function &F : pModule->functions()) {
  3616. ValidateFunction(F, ValCtx);
  3617. }
  3618. ValidateUninitializedOutput(ValCtx);
  3619. ValidateShaderFlags(ValCtx);
  3620. if (!pDxilModule->GetShaderModel()->IsGS()) {
  3621. unsigned posMask = ValCtx.OutputPositionMask[0];
  3622. if (posMask != 0xf && ValCtx.hasOutputPosition[0]) {
  3623. ValCtx.EmitError(ValidationRule::SmCompletePosition);
  3624. }
  3625. } else {
  3626. unsigned streamMask = ValCtx.DxilMod.GetActiveStreamMask();
  3627. for (unsigned i = 0; i < DXIL::kNumOutputStreams; i++) {
  3628. if (streamMask & (1 << i)) {
  3629. unsigned posMask = ValCtx.OutputPositionMask[i];
  3630. if (posMask != 0xf && ValCtx.hasOutputPosition[i]) {
  3631. ValCtx.EmitError(ValidationRule::SmCompletePosition);
  3632. }
  3633. }
  3634. }
  3635. }
  3636. // Ensure error messages are flushed out on error.
  3637. if (ValCtx.Failed) {
  3638. diagStream.flush();
  3639. emitDxilDiag(Ctx, diagStr.c_str());
  3640. }
  3641. if (ValCtx.Failed)
  3642. return std::error_code(ERROR_INVALID_DATA, std::system_category());
  3643. return std::error_code();
  3644. }
  3645. } // namespace hlsl