DxilValidation.cpp 146 KB

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