DxilValidation.cpp 152 KB

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