Instructions.cs 107 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480
  1. using Ryujinx.Graphics.Shader.IntermediateRepresentation;
  2. using Ryujinx.Graphics.Shader.StructuredIr;
  3. using Ryujinx.Graphics.Shader.Translation;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Diagnostics;
  7. using System.Linq;
  8. using System.Numerics;
  9. using static Spv.Specification;
  10. namespace Ryujinx.Graphics.Shader.CodeGen.Spirv
  11. {
  12. using SpvInstruction = Spv.Generator.Instruction;
  13. using SpvLiteralInteger = Spv.Generator.LiteralInteger;
  14. static class Instructions
  15. {
  16. private const MemorySemanticsMask DefaultMemorySemantics =
  17. MemorySemanticsMask.ImageMemory |
  18. MemorySemanticsMask.AtomicCounterMemory |
  19. MemorySemanticsMask.WorkgroupMemory |
  20. MemorySemanticsMask.UniformMemory |
  21. MemorySemanticsMask.AcquireRelease;
  22. private static readonly Func<CodeGenContext, AstOperation, OperationResult>[] InstTable;
  23. static Instructions()
  24. {
  25. InstTable = new Func<CodeGenContext, AstOperation, OperationResult>[(int)Instruction.Count];
  26. Add(Instruction.Absolute, GenerateAbsolute);
  27. Add(Instruction.Add, GenerateAdd);
  28. Add(Instruction.AtomicAdd, GenerateAtomicAdd);
  29. Add(Instruction.AtomicAnd, GenerateAtomicAnd);
  30. Add(Instruction.AtomicCompareAndSwap, GenerateAtomicCompareAndSwap);
  31. Add(Instruction.AtomicMinS32, GenerateAtomicMinS32);
  32. Add(Instruction.AtomicMinU32, GenerateAtomicMinU32);
  33. Add(Instruction.AtomicMaxS32, GenerateAtomicMaxS32);
  34. Add(Instruction.AtomicMaxU32, GenerateAtomicMaxU32);
  35. Add(Instruction.AtomicOr, GenerateAtomicOr);
  36. Add(Instruction.AtomicSwap, GenerateAtomicSwap);
  37. Add(Instruction.AtomicXor, GenerateAtomicXor);
  38. Add(Instruction.Ballot, GenerateBallot);
  39. Add(Instruction.Barrier, GenerateBarrier);
  40. Add(Instruction.BitCount, GenerateBitCount);
  41. Add(Instruction.BitfieldExtractS32, GenerateBitfieldExtractS32);
  42. Add(Instruction.BitfieldExtractU32, GenerateBitfieldExtractU32);
  43. Add(Instruction.BitfieldInsert, GenerateBitfieldInsert);
  44. Add(Instruction.BitfieldReverse, GenerateBitfieldReverse);
  45. Add(Instruction.BitwiseAnd, GenerateBitwiseAnd);
  46. Add(Instruction.BitwiseExclusiveOr, GenerateBitwiseExclusiveOr);
  47. Add(Instruction.BitwiseNot, GenerateBitwiseNot);
  48. Add(Instruction.BitwiseOr, GenerateBitwiseOr);
  49. Add(Instruction.Call, GenerateCall);
  50. Add(Instruction.Ceiling, GenerateCeiling);
  51. Add(Instruction.Clamp, GenerateClamp);
  52. Add(Instruction.ClampU32, GenerateClampU32);
  53. Add(Instruction.Comment, GenerateComment);
  54. Add(Instruction.CompareEqual, GenerateCompareEqual);
  55. Add(Instruction.CompareGreater, GenerateCompareGreater);
  56. Add(Instruction.CompareGreaterOrEqual, GenerateCompareGreaterOrEqual);
  57. Add(Instruction.CompareGreaterOrEqualU32, GenerateCompareGreaterOrEqualU32);
  58. Add(Instruction.CompareGreaterU32, GenerateCompareGreaterU32);
  59. Add(Instruction.CompareLess, GenerateCompareLess);
  60. Add(Instruction.CompareLessOrEqual, GenerateCompareLessOrEqual);
  61. Add(Instruction.CompareLessOrEqualU32, GenerateCompareLessOrEqualU32);
  62. Add(Instruction.CompareLessU32, GenerateCompareLessU32);
  63. Add(Instruction.CompareNotEqual, GenerateCompareNotEqual);
  64. Add(Instruction.ConditionalSelect, GenerateConditionalSelect);
  65. Add(Instruction.ConvertFP32ToFP64, GenerateConvertFP32ToFP64);
  66. Add(Instruction.ConvertFP32ToS32, GenerateConvertFP32ToS32);
  67. Add(Instruction.ConvertFP32ToU32, GenerateConvertFP32ToU32);
  68. Add(Instruction.ConvertFP64ToFP32, GenerateConvertFP64ToFP32);
  69. Add(Instruction.ConvertFP64ToS32, GenerateConvertFP64ToS32);
  70. Add(Instruction.ConvertFP64ToU32, GenerateConvertFP64ToU32);
  71. Add(Instruction.ConvertS32ToFP32, GenerateConvertS32ToFP32);
  72. Add(Instruction.ConvertS32ToFP64, GenerateConvertS32ToFP64);
  73. Add(Instruction.ConvertU32ToFP32, GenerateConvertU32ToFP32);
  74. Add(Instruction.ConvertU32ToFP64, GenerateConvertU32ToFP64);
  75. Add(Instruction.Cosine, GenerateCosine);
  76. Add(Instruction.Ddx, GenerateDdx);
  77. Add(Instruction.Ddy, GenerateDdy);
  78. Add(Instruction.Discard, GenerateDiscard);
  79. Add(Instruction.Divide, GenerateDivide);
  80. Add(Instruction.EmitVertex, GenerateEmitVertex);
  81. Add(Instruction.EndPrimitive, GenerateEndPrimitive);
  82. Add(Instruction.ExponentB2, GenerateExponentB2);
  83. Add(Instruction.FSIBegin, GenerateFSIBegin);
  84. Add(Instruction.FSIEnd, GenerateFSIEnd);
  85. Add(Instruction.FindLSB, GenerateFindLSB);
  86. Add(Instruction.FindMSBS32, GenerateFindMSBS32);
  87. Add(Instruction.FindMSBU32, GenerateFindMSBU32);
  88. Add(Instruction.Floor, GenerateFloor);
  89. Add(Instruction.FusedMultiplyAdd, GenerateFusedMultiplyAdd);
  90. Add(Instruction.GroupMemoryBarrier, GenerateGroupMemoryBarrier);
  91. Add(Instruction.ImageAtomic, GenerateImageAtomic);
  92. Add(Instruction.ImageLoad, GenerateImageLoad);
  93. Add(Instruction.ImageStore, GenerateImageStore);
  94. Add(Instruction.IsNan, GenerateIsNan);
  95. Add(Instruction.Load, GenerateLoad);
  96. Add(Instruction.LoadConstant, GenerateLoadConstant);
  97. Add(Instruction.LoadLocal, GenerateLoadLocal);
  98. Add(Instruction.LoadShared, GenerateLoadShared);
  99. Add(Instruction.LoadStorage, GenerateLoadStorage);
  100. Add(Instruction.Lod, GenerateLod);
  101. Add(Instruction.LogarithmB2, GenerateLogarithmB2);
  102. Add(Instruction.LogicalAnd, GenerateLogicalAnd);
  103. Add(Instruction.LogicalExclusiveOr, GenerateLogicalExclusiveOr);
  104. Add(Instruction.LogicalNot, GenerateLogicalNot);
  105. Add(Instruction.LogicalOr, GenerateLogicalOr);
  106. Add(Instruction.LoopBreak, GenerateLoopBreak);
  107. Add(Instruction.LoopContinue, GenerateLoopContinue);
  108. Add(Instruction.Maximum, GenerateMaximum);
  109. Add(Instruction.MaximumU32, GenerateMaximumU32);
  110. Add(Instruction.MemoryBarrier, GenerateMemoryBarrier);
  111. Add(Instruction.Minimum, GenerateMinimum);
  112. Add(Instruction.MinimumU32, GenerateMinimumU32);
  113. Add(Instruction.Multiply, GenerateMultiply);
  114. Add(Instruction.MultiplyHighS32, GenerateMultiplyHighS32);
  115. Add(Instruction.MultiplyHighU32, GenerateMultiplyHighU32);
  116. Add(Instruction.Negate, GenerateNegate);
  117. Add(Instruction.PackDouble2x32, GeneratePackDouble2x32);
  118. Add(Instruction.PackHalf2x16, GeneratePackHalf2x16);
  119. Add(Instruction.ReciprocalSquareRoot, GenerateReciprocalSquareRoot);
  120. Add(Instruction.Return, GenerateReturn);
  121. Add(Instruction.Round, GenerateRound);
  122. Add(Instruction.ShiftLeft, GenerateShiftLeft);
  123. Add(Instruction.ShiftRightS32, GenerateShiftRightS32);
  124. Add(Instruction.ShiftRightU32, GenerateShiftRightU32);
  125. Add(Instruction.Shuffle, GenerateShuffle);
  126. Add(Instruction.ShuffleDown, GenerateShuffleDown);
  127. Add(Instruction.ShuffleUp, GenerateShuffleUp);
  128. Add(Instruction.ShuffleXor, GenerateShuffleXor);
  129. Add(Instruction.Sine, GenerateSine);
  130. Add(Instruction.SquareRoot, GenerateSquareRoot);
  131. Add(Instruction.Store, GenerateStore);
  132. Add(Instruction.StoreLocal, GenerateStoreLocal);
  133. Add(Instruction.StoreShared, GenerateStoreShared);
  134. Add(Instruction.StoreShared16, GenerateStoreShared16);
  135. Add(Instruction.StoreShared8, GenerateStoreShared8);
  136. Add(Instruction.StoreStorage, GenerateStoreStorage);
  137. Add(Instruction.StoreStorage16, GenerateStoreStorage16);
  138. Add(Instruction.StoreStorage8, GenerateStoreStorage8);
  139. Add(Instruction.Subtract, GenerateSubtract);
  140. Add(Instruction.SwizzleAdd, GenerateSwizzleAdd);
  141. Add(Instruction.TextureSample, GenerateTextureSample);
  142. Add(Instruction.TextureSize, GenerateTextureSize);
  143. Add(Instruction.Truncate, GenerateTruncate);
  144. Add(Instruction.UnpackDouble2x32, GenerateUnpackDouble2x32);
  145. Add(Instruction.UnpackHalf2x16, GenerateUnpackHalf2x16);
  146. Add(Instruction.VectorExtract, GenerateVectorExtract);
  147. Add(Instruction.VoteAll, GenerateVoteAll);
  148. Add(Instruction.VoteAllEqual, GenerateVoteAllEqual);
  149. Add(Instruction.VoteAny, GenerateVoteAny);
  150. }
  151. private static void Add(Instruction inst, Func<CodeGenContext, AstOperation, OperationResult> handler)
  152. {
  153. InstTable[(int)(inst & Instruction.Mask)] = handler;
  154. }
  155. public static OperationResult Generate(CodeGenContext context, AstOperation operation)
  156. {
  157. var handler = InstTable[(int)(operation.Inst & Instruction.Mask)];
  158. if (handler != null)
  159. {
  160. return handler(context, operation);
  161. }
  162. else
  163. {
  164. throw new NotImplementedException(operation.Inst.ToString());
  165. }
  166. }
  167. private static OperationResult GenerateAbsolute(CodeGenContext context, AstOperation operation)
  168. {
  169. return GenerateUnary(context, operation, context.Delegates.GlslFAbs, context.Delegates.GlslSAbs);
  170. }
  171. private static OperationResult GenerateAdd(CodeGenContext context, AstOperation operation)
  172. {
  173. return GenerateBinary(context, operation, context.Delegates.FAdd, context.Delegates.IAdd);
  174. }
  175. private static OperationResult GenerateAtomicAdd(CodeGenContext context, AstOperation operation)
  176. {
  177. return GenerateAtomicMemoryBinary(context, operation, context.Delegates.AtomicIAdd);
  178. }
  179. private static OperationResult GenerateAtomicAnd(CodeGenContext context, AstOperation operation)
  180. {
  181. return GenerateAtomicMemoryBinary(context, operation, context.Delegates.AtomicAnd);
  182. }
  183. private static OperationResult GenerateAtomicCompareAndSwap(CodeGenContext context, AstOperation operation)
  184. {
  185. return GenerateAtomicMemoryCas(context, operation);
  186. }
  187. private static OperationResult GenerateAtomicMinS32(CodeGenContext context, AstOperation operation)
  188. {
  189. return GenerateAtomicMemoryBinary(context, operation, context.Delegates.AtomicSMin);
  190. }
  191. private static OperationResult GenerateAtomicMinU32(CodeGenContext context, AstOperation operation)
  192. {
  193. return GenerateAtomicMemoryBinary(context, operation, context.Delegates.AtomicUMin);
  194. }
  195. private static OperationResult GenerateAtomicMaxS32(CodeGenContext context, AstOperation operation)
  196. {
  197. return GenerateAtomicMemoryBinary(context, operation, context.Delegates.AtomicSMax);
  198. }
  199. private static OperationResult GenerateAtomicMaxU32(CodeGenContext context, AstOperation operation)
  200. {
  201. return GenerateAtomicMemoryBinary(context, operation, context.Delegates.AtomicUMax);
  202. }
  203. private static OperationResult GenerateAtomicOr(CodeGenContext context, AstOperation operation)
  204. {
  205. return GenerateAtomicMemoryBinary(context, operation, context.Delegates.AtomicOr);
  206. }
  207. private static OperationResult GenerateAtomicSwap(CodeGenContext context, AstOperation operation)
  208. {
  209. return GenerateAtomicMemoryBinary(context, operation, context.Delegates.AtomicExchange);
  210. }
  211. private static OperationResult GenerateAtomicXor(CodeGenContext context, AstOperation operation)
  212. {
  213. return GenerateAtomicMemoryBinary(context, operation, context.Delegates.AtomicXor);
  214. }
  215. private static OperationResult GenerateBallot(CodeGenContext context, AstOperation operation)
  216. {
  217. var source = operation.GetSource(0);
  218. var uvec4Type = context.TypeVector(context.TypeU32(), 4);
  219. var execution = context.Constant(context.TypeU32(), Scope.Subgroup);
  220. var maskVector = context.GroupNonUniformBallot(uvec4Type, execution, context.Get(AggregateType.Bool, source));
  221. var mask = context.CompositeExtract(context.TypeU32(), maskVector, (SpvLiteralInteger)0);
  222. return new OperationResult(AggregateType.U32, mask);
  223. }
  224. private static OperationResult GenerateBarrier(CodeGenContext context, AstOperation operation)
  225. {
  226. context.ControlBarrier(
  227. context.Constant(context.TypeU32(), Scope.Workgroup),
  228. context.Constant(context.TypeU32(), Scope.Workgroup),
  229. context.Constant(context.TypeU32(), MemorySemanticsMask.WorkgroupMemory | MemorySemanticsMask.AcquireRelease));
  230. return OperationResult.Invalid;
  231. }
  232. private static OperationResult GenerateBitCount(CodeGenContext context, AstOperation operation)
  233. {
  234. return GenerateUnaryS32(context, operation, context.Delegates.BitCount);
  235. }
  236. private static OperationResult GenerateBitfieldExtractS32(CodeGenContext context, AstOperation operation)
  237. {
  238. return GenerateBitfieldExtractS32(context, operation, context.Delegates.BitFieldSExtract);
  239. }
  240. private static OperationResult GenerateBitfieldExtractU32(CodeGenContext context, AstOperation operation)
  241. {
  242. return GenerateTernaryU32(context, operation, context.Delegates.BitFieldUExtract);
  243. }
  244. private static OperationResult GenerateBitfieldInsert(CodeGenContext context, AstOperation operation)
  245. {
  246. return GenerateBitfieldInsert(context, operation, context.Delegates.BitFieldInsert);
  247. }
  248. private static OperationResult GenerateBitfieldReverse(CodeGenContext context, AstOperation operation)
  249. {
  250. return GenerateUnaryS32(context, operation, context.Delegates.BitReverse);
  251. }
  252. private static OperationResult GenerateBitwiseAnd(CodeGenContext context, AstOperation operation)
  253. {
  254. return GenerateBinaryS32(context, operation, context.Delegates.BitwiseAnd);
  255. }
  256. private static OperationResult GenerateBitwiseExclusiveOr(CodeGenContext context, AstOperation operation)
  257. {
  258. return GenerateBinaryS32(context, operation, context.Delegates.BitwiseXor);
  259. }
  260. private static OperationResult GenerateBitwiseNot(CodeGenContext context, AstOperation operation)
  261. {
  262. return GenerateUnaryS32(context, operation, context.Delegates.Not);
  263. }
  264. private static OperationResult GenerateBitwiseOr(CodeGenContext context, AstOperation operation)
  265. {
  266. return GenerateBinaryS32(context, operation, context.Delegates.BitwiseOr);
  267. }
  268. private static OperationResult GenerateCall(CodeGenContext context, AstOperation operation)
  269. {
  270. AstOperand funcId = (AstOperand)operation.GetSource(0);
  271. Debug.Assert(funcId.Type == OperandType.Constant);
  272. (var function, var spvFunc) = context.GetFunction(funcId.Value);
  273. var args = new SpvInstruction[operation.SourcesCount - 1];
  274. var spvLocals = context.GetLocalForArgsPointers(funcId.Value);
  275. for (int i = 0; i < args.Length; i++)
  276. {
  277. var operand = (AstOperand)operation.GetSource(i + 1);
  278. if (i >= function.InArguments.Length)
  279. {
  280. args[i] = context.GetLocalPointer(operand);
  281. }
  282. else
  283. {
  284. var type = function.GetArgumentType(i);
  285. var value = context.Get(type, operand);
  286. var spvLocal = spvLocals[i];
  287. context.Store(spvLocal, value);
  288. args[i] = spvLocal;
  289. }
  290. }
  291. var retType = function.ReturnType;
  292. var result = context.FunctionCall(context.GetType(retType), spvFunc, args);
  293. return new OperationResult(retType, result);
  294. }
  295. private static OperationResult GenerateCeiling(CodeGenContext context, AstOperation operation)
  296. {
  297. return GenerateUnary(context, operation, context.Delegates.GlslCeil, null);
  298. }
  299. private static OperationResult GenerateClamp(CodeGenContext context, AstOperation operation)
  300. {
  301. return GenerateTernary(context, operation, context.Delegates.GlslFClamp, context.Delegates.GlslSClamp);
  302. }
  303. private static OperationResult GenerateClampU32(CodeGenContext context, AstOperation operation)
  304. {
  305. return GenerateTernaryU32(context, operation, context.Delegates.GlslUClamp);
  306. }
  307. private static OperationResult GenerateComment(CodeGenContext context, AstOperation operation)
  308. {
  309. return OperationResult.Invalid;
  310. }
  311. private static OperationResult GenerateCompareEqual(CodeGenContext context, AstOperation operation)
  312. {
  313. return GenerateCompare(context, operation, context.Delegates.FOrdEqual, context.Delegates.IEqual);
  314. }
  315. private static OperationResult GenerateCompareGreater(CodeGenContext context, AstOperation operation)
  316. {
  317. return GenerateCompare(context, operation, context.Delegates.FOrdGreaterThan, context.Delegates.SGreaterThan);
  318. }
  319. private static OperationResult GenerateCompareGreaterOrEqual(CodeGenContext context, AstOperation operation)
  320. {
  321. return GenerateCompare(context, operation, context.Delegates.FOrdGreaterThanEqual, context.Delegates.SGreaterThanEqual);
  322. }
  323. private static OperationResult GenerateCompareGreaterOrEqualU32(CodeGenContext context, AstOperation operation)
  324. {
  325. return GenerateCompareU32(context, operation, context.Delegates.UGreaterThanEqual);
  326. }
  327. private static OperationResult GenerateCompareGreaterU32(CodeGenContext context, AstOperation operation)
  328. {
  329. return GenerateCompareU32(context, operation, context.Delegates.UGreaterThan);
  330. }
  331. private static OperationResult GenerateCompareLess(CodeGenContext context, AstOperation operation)
  332. {
  333. return GenerateCompare(context, operation, context.Delegates.FOrdLessThan, context.Delegates.SLessThan);
  334. }
  335. private static OperationResult GenerateCompareLessOrEqual(CodeGenContext context, AstOperation operation)
  336. {
  337. return GenerateCompare(context, operation, context.Delegates.FOrdLessThanEqual, context.Delegates.SLessThanEqual);
  338. }
  339. private static OperationResult GenerateCompareLessOrEqualU32(CodeGenContext context, AstOperation operation)
  340. {
  341. return GenerateCompareU32(context, operation, context.Delegates.ULessThanEqual);
  342. }
  343. private static OperationResult GenerateCompareLessU32(CodeGenContext context, AstOperation operation)
  344. {
  345. return GenerateCompareU32(context, operation, context.Delegates.ULessThan);
  346. }
  347. private static OperationResult GenerateCompareNotEqual(CodeGenContext context, AstOperation operation)
  348. {
  349. return GenerateCompare(context, operation, context.Delegates.FOrdNotEqual, context.Delegates.INotEqual);
  350. }
  351. private static OperationResult GenerateConditionalSelect(CodeGenContext context, AstOperation operation)
  352. {
  353. var src1 = operation.GetSource(0);
  354. var src2 = operation.GetSource(1);
  355. var src3 = operation.GetSource(2);
  356. var cond = context.Get(AggregateType.Bool, src1);
  357. if (operation.Inst.HasFlag(Instruction.FP64))
  358. {
  359. return new OperationResult(AggregateType.FP64, context.Select(context.TypeFP64(), cond, context.GetFP64(src2), context.GetFP64(src3)));
  360. }
  361. else if (operation.Inst.HasFlag(Instruction.FP32))
  362. {
  363. return new OperationResult(AggregateType.FP32, context.Select(context.TypeFP32(), cond, context.GetFP32(src2), context.GetFP32(src3)));
  364. }
  365. else
  366. {
  367. return new OperationResult(AggregateType.S32, context.Select(context.TypeS32(), cond, context.GetS32(src2), context.GetS32(src3)));
  368. }
  369. }
  370. private static OperationResult GenerateConvertFP32ToFP64(CodeGenContext context, AstOperation operation)
  371. {
  372. var source = operation.GetSource(0);
  373. return new OperationResult(AggregateType.FP64, context.FConvert(context.TypeFP64(), context.GetFP32(source)));
  374. }
  375. private static OperationResult GenerateConvertFP32ToS32(CodeGenContext context, AstOperation operation)
  376. {
  377. var source = operation.GetSource(0);
  378. return new OperationResult(AggregateType.S32, context.ConvertFToS(context.TypeS32(), context.GetFP32(source)));
  379. }
  380. private static OperationResult GenerateConvertFP32ToU32(CodeGenContext context, AstOperation operation)
  381. {
  382. var source = operation.GetSource(0);
  383. return new OperationResult(AggregateType.U32, context.ConvertFToU(context.TypeU32(), context.GetFP32(source)));
  384. }
  385. private static OperationResult GenerateConvertFP64ToFP32(CodeGenContext context, AstOperation operation)
  386. {
  387. var source = operation.GetSource(0);
  388. return new OperationResult(AggregateType.FP32, context.FConvert(context.TypeFP32(), context.GetFP64(source)));
  389. }
  390. private static OperationResult GenerateConvertFP64ToS32(CodeGenContext context, AstOperation operation)
  391. {
  392. var source = operation.GetSource(0);
  393. return new OperationResult(AggregateType.S32, context.ConvertFToS(context.TypeS32(), context.GetFP64(source)));
  394. }
  395. private static OperationResult GenerateConvertFP64ToU32(CodeGenContext context, AstOperation operation)
  396. {
  397. var source = operation.GetSource(0);
  398. return new OperationResult(AggregateType.U32, context.ConvertFToU(context.TypeU32(), context.GetFP64(source)));
  399. }
  400. private static OperationResult GenerateConvertS32ToFP32(CodeGenContext context, AstOperation operation)
  401. {
  402. var source = operation.GetSource(0);
  403. return new OperationResult(AggregateType.FP32, context.ConvertSToF(context.TypeFP32(), context.GetS32(source)));
  404. }
  405. private static OperationResult GenerateConvertS32ToFP64(CodeGenContext context, AstOperation operation)
  406. {
  407. var source = operation.GetSource(0);
  408. return new OperationResult(AggregateType.FP64, context.ConvertSToF(context.TypeFP64(), context.GetS32(source)));
  409. }
  410. private static OperationResult GenerateConvertU32ToFP32(CodeGenContext context, AstOperation operation)
  411. {
  412. var source = operation.GetSource(0);
  413. return new OperationResult(AggregateType.FP32, context.ConvertUToF(context.TypeFP32(), context.GetU32(source)));
  414. }
  415. private static OperationResult GenerateConvertU32ToFP64(CodeGenContext context, AstOperation operation)
  416. {
  417. var source = operation.GetSource(0);
  418. return new OperationResult(AggregateType.FP64, context.ConvertUToF(context.TypeFP64(), context.GetU32(source)));
  419. }
  420. private static OperationResult GenerateCosine(CodeGenContext context, AstOperation operation)
  421. {
  422. return GenerateUnary(context, operation, context.Delegates.GlslCos, null);
  423. }
  424. private static OperationResult GenerateDdx(CodeGenContext context, AstOperation operation)
  425. {
  426. return GenerateUnaryFP32(context, operation, context.Delegates.DPdx);
  427. }
  428. private static OperationResult GenerateDdy(CodeGenContext context, AstOperation operation)
  429. {
  430. return GenerateUnaryFP32(context, operation, context.Delegates.DPdy);
  431. }
  432. private static OperationResult GenerateDiscard(CodeGenContext context, AstOperation operation)
  433. {
  434. context.Kill();
  435. return OperationResult.Invalid;
  436. }
  437. private static OperationResult GenerateDivide(CodeGenContext context, AstOperation operation)
  438. {
  439. return GenerateBinary(context, operation, context.Delegates.FDiv, context.Delegates.SDiv);
  440. }
  441. private static OperationResult GenerateEmitVertex(CodeGenContext context, AstOperation operation)
  442. {
  443. context.EmitVertex();
  444. return OperationResult.Invalid;
  445. }
  446. private static OperationResult GenerateEndPrimitive(CodeGenContext context, AstOperation operation)
  447. {
  448. context.EndPrimitive();
  449. return OperationResult.Invalid;
  450. }
  451. private static OperationResult GenerateExponentB2(CodeGenContext context, AstOperation operation)
  452. {
  453. return GenerateUnary(context, operation, context.Delegates.GlslExp2, null);
  454. }
  455. private static OperationResult GenerateFSIBegin(CodeGenContext context, AstOperation operation)
  456. {
  457. if (context.Config.GpuAccessor.QueryHostSupportsFragmentShaderInterlock())
  458. {
  459. context.BeginInvocationInterlockEXT();
  460. }
  461. return OperationResult.Invalid;
  462. }
  463. private static OperationResult GenerateFSIEnd(CodeGenContext context, AstOperation operation)
  464. {
  465. if (context.Config.GpuAccessor.QueryHostSupportsFragmentShaderInterlock())
  466. {
  467. context.EndInvocationInterlockEXT();
  468. }
  469. return OperationResult.Invalid;
  470. }
  471. private static OperationResult GenerateFindLSB(CodeGenContext context, AstOperation operation)
  472. {
  473. var source = context.GetU32(operation.GetSource(0));
  474. return new OperationResult(AggregateType.U32, context.GlslFindILsb(context.TypeU32(), source));
  475. }
  476. private static OperationResult GenerateFindMSBS32(CodeGenContext context, AstOperation operation)
  477. {
  478. var source = context.GetS32(operation.GetSource(0));
  479. return new OperationResult(AggregateType.U32, context.GlslFindSMsb(context.TypeU32(), source));
  480. }
  481. private static OperationResult GenerateFindMSBU32(CodeGenContext context, AstOperation operation)
  482. {
  483. var source = context.GetU32(operation.GetSource(0));
  484. return new OperationResult(AggregateType.U32, context.GlslFindUMsb(context.TypeU32(), source));
  485. }
  486. private static OperationResult GenerateFloor(CodeGenContext context, AstOperation operation)
  487. {
  488. return GenerateUnary(context, operation, context.Delegates.GlslFloor, null);
  489. }
  490. private static OperationResult GenerateFusedMultiplyAdd(CodeGenContext context, AstOperation operation)
  491. {
  492. return GenerateTernary(context, operation, context.Delegates.GlslFma, null);
  493. }
  494. private static OperationResult GenerateGroupMemoryBarrier(CodeGenContext context, AstOperation operation)
  495. {
  496. context.MemoryBarrier(context.Constant(context.TypeU32(), Scope.Workgroup), context.Constant(context.TypeU32(), DefaultMemorySemantics));
  497. return OperationResult.Invalid;
  498. }
  499. private static OperationResult GenerateImageAtomic(CodeGenContext context, AstOperation operation)
  500. {
  501. AstTextureOperation texOp = (AstTextureOperation)operation;
  502. bool isBindless = (texOp.Flags & TextureFlags.Bindless) != 0;
  503. var componentType = texOp.Format.GetComponentType();
  504. // TODO: Bindless texture support. For now we just return 0/do nothing.
  505. if (isBindless)
  506. {
  507. return new OperationResult(componentType, componentType switch
  508. {
  509. AggregateType.S32 => context.Constant(context.TypeS32(), 0),
  510. AggregateType.U32 => context.Constant(context.TypeU32(), 0u),
  511. _ => context.Constant(context.TypeFP32(), 0f),
  512. });
  513. }
  514. bool isArray = (texOp.Type & SamplerType.Array) != 0;
  515. bool isIndexed = (texOp.Type & SamplerType.Indexed) != 0;
  516. int srcIndex = isBindless ? 1 : 0;
  517. SpvInstruction Src(AggregateType type)
  518. {
  519. return context.Get(type, texOp.GetSource(srcIndex++));
  520. }
  521. SpvInstruction index = null;
  522. if (isIndexed)
  523. {
  524. index = Src(AggregateType.S32);
  525. }
  526. int coordsCount = texOp.Type.GetDimensions();
  527. int pCount = coordsCount + (isArray ? 1 : 0);
  528. SpvInstruction pCoords;
  529. if (pCount > 1)
  530. {
  531. SpvInstruction[] elems = new SpvInstruction[pCount];
  532. for (int i = 0; i < pCount; i++)
  533. {
  534. elems[i] = Src(AggregateType.S32);
  535. }
  536. var vectorType = context.TypeVector(context.TypeS32(), pCount);
  537. pCoords = context.CompositeConstruct(vectorType, elems);
  538. }
  539. else
  540. {
  541. pCoords = Src(AggregateType.S32);
  542. }
  543. SpvInstruction value = Src(componentType);
  544. (var imageType, var imageVariable) = context.Images[new TextureMeta(texOp.CbufSlot, texOp.Handle, texOp.Format)];
  545. var image = context.Load(imageType, imageVariable);
  546. SpvInstruction resultType = context.GetType(componentType);
  547. SpvInstruction imagePointerType = context.TypePointer(StorageClass.Image, resultType);
  548. var pointer = context.ImageTexelPointer(imagePointerType, imageVariable, pCoords, context.Constant(context.TypeU32(), 0));
  549. var one = context.Constant(context.TypeU32(), 1);
  550. var zero = context.Constant(context.TypeU32(), 0);
  551. var result = (texOp.Flags & TextureFlags.AtomicMask) switch
  552. {
  553. TextureFlags.Add => context.AtomicIAdd(resultType, pointer, one, zero, value),
  554. TextureFlags.Minimum => componentType == AggregateType.S32
  555. ? context.AtomicSMin(resultType, pointer, one, zero, value)
  556. : context.AtomicUMin(resultType, pointer, one, zero, value),
  557. TextureFlags.Maximum => componentType == AggregateType.S32
  558. ? context.AtomicSMax(resultType, pointer, one, zero, value)
  559. : context.AtomicUMax(resultType, pointer, one, zero, value),
  560. TextureFlags.Increment => context.AtomicIIncrement(resultType, pointer, one, zero),
  561. TextureFlags.Decrement => context.AtomicIDecrement(resultType, pointer, one, zero),
  562. TextureFlags.BitwiseAnd => context.AtomicAnd(resultType, pointer, one, zero, value),
  563. TextureFlags.BitwiseOr => context.AtomicOr(resultType, pointer, one, zero, value),
  564. TextureFlags.BitwiseXor => context.AtomicXor(resultType, pointer, one, zero, value),
  565. TextureFlags.Swap => context.AtomicExchange(resultType, pointer, one, zero, value),
  566. TextureFlags.CAS => context.AtomicCompareExchange(resultType, pointer, one, zero, zero, Src(componentType), value),
  567. _ => context.AtomicIAdd(resultType, pointer, one, zero, value),
  568. };
  569. return new OperationResult(componentType, result);
  570. }
  571. private static OperationResult GenerateImageLoad(CodeGenContext context, AstOperation operation)
  572. {
  573. AstTextureOperation texOp = (AstTextureOperation)operation;
  574. bool isBindless = (texOp.Flags & TextureFlags.Bindless) != 0;
  575. var componentType = texOp.Format.GetComponentType();
  576. // TODO: Bindless texture support. For now we just return 0/do nothing.
  577. if (isBindless)
  578. {
  579. return GetZeroOperationResult(context, texOp, componentType, isVector: true);
  580. }
  581. bool isArray = (texOp.Type & SamplerType.Array) != 0;
  582. bool isIndexed = (texOp.Type & SamplerType.Indexed) != 0;
  583. int srcIndex = isBindless ? 1 : 0;
  584. SpvInstruction Src(AggregateType type)
  585. {
  586. return context.Get(type, texOp.GetSource(srcIndex++));
  587. }
  588. SpvInstruction index = null;
  589. if (isIndexed)
  590. {
  591. index = Src(AggregateType.S32);
  592. }
  593. int coordsCount = texOp.Type.GetDimensions();
  594. int pCount = coordsCount + (isArray ? 1 : 0);
  595. SpvInstruction pCoords;
  596. if (pCount > 1)
  597. {
  598. SpvInstruction[] elems = new SpvInstruction[pCount];
  599. for (int i = 0; i < pCount; i++)
  600. {
  601. elems[i] = Src(AggregateType.S32);
  602. }
  603. var vectorType = context.TypeVector(context.TypeS32(), pCount);
  604. pCoords = context.CompositeConstruct(vectorType, elems);
  605. }
  606. else
  607. {
  608. pCoords = Src(AggregateType.S32);
  609. }
  610. pCoords = ScalingHelpers.ApplyScaling(context, texOp, pCoords, intCoords: true, isBindless, isIndexed, isArray, pCount);
  611. (var imageType, var imageVariable) = context.Images[new TextureMeta(texOp.CbufSlot, texOp.Handle, texOp.Format)];
  612. var image = context.Load(imageType, imageVariable);
  613. var imageComponentType = context.GetType(componentType);
  614. var swizzledResultType = texOp.GetVectorType(componentType);
  615. var texel = context.ImageRead(context.TypeVector(imageComponentType, 4), image, pCoords, ImageOperandsMask.MaskNone);
  616. var result = GetSwizzledResult(context, texel, swizzledResultType, texOp.Index);
  617. return new OperationResult(componentType, result);
  618. }
  619. private static OperationResult GenerateImageStore(CodeGenContext context, AstOperation operation)
  620. {
  621. AstTextureOperation texOp = (AstTextureOperation)operation;
  622. bool isBindless = (texOp.Flags & TextureFlags.Bindless) != 0;
  623. // TODO: Bindless texture support. For now we just return 0/do nothing.
  624. if (isBindless)
  625. {
  626. return OperationResult.Invalid;
  627. }
  628. bool isArray = (texOp.Type & SamplerType.Array) != 0;
  629. bool isIndexed = (texOp.Type & SamplerType.Indexed) != 0;
  630. int srcIndex = isBindless ? 1 : 0;
  631. SpvInstruction Src(AggregateType type)
  632. {
  633. return context.Get(type, texOp.GetSource(srcIndex++));
  634. }
  635. SpvInstruction index = null;
  636. if (isIndexed)
  637. {
  638. index = Src(AggregateType.S32);
  639. }
  640. int coordsCount = texOp.Type.GetDimensions();
  641. int pCount = coordsCount + (isArray ? 1 : 0);
  642. SpvInstruction pCoords;
  643. if (pCount > 1)
  644. {
  645. SpvInstruction[] elems = new SpvInstruction[pCount];
  646. for (int i = 0; i < pCount; i++)
  647. {
  648. elems[i] = Src(AggregateType.S32);
  649. }
  650. var vectorType = context.TypeVector(context.TypeS32(), pCount);
  651. pCoords = context.CompositeConstruct(vectorType, elems);
  652. }
  653. else
  654. {
  655. pCoords = Src(AggregateType.S32);
  656. }
  657. var componentType = texOp.Format.GetComponentType();
  658. const int ComponentsCount = 4;
  659. SpvInstruction[] cElems = new SpvInstruction[ComponentsCount];
  660. for (int i = 0; i < ComponentsCount; i++)
  661. {
  662. if (srcIndex < texOp.SourcesCount)
  663. {
  664. cElems[i] = Src(componentType);
  665. }
  666. else
  667. {
  668. cElems[i] = componentType switch
  669. {
  670. AggregateType.S32 => context.Constant(context.TypeS32(), 0),
  671. AggregateType.U32 => context.Constant(context.TypeU32(), 0u),
  672. _ => context.Constant(context.TypeFP32(), 0f),
  673. };
  674. }
  675. }
  676. var texel = context.CompositeConstruct(context.TypeVector(context.GetType(componentType), ComponentsCount), cElems);
  677. (var imageType, var imageVariable) = context.Images[new TextureMeta(texOp.CbufSlot, texOp.Handle, texOp.Format)];
  678. var image = context.Load(imageType, imageVariable);
  679. context.ImageWrite(image, pCoords, texel, ImageOperandsMask.MaskNone);
  680. return OperationResult.Invalid;
  681. }
  682. private static OperationResult GenerateIsNan(CodeGenContext context, AstOperation operation)
  683. {
  684. var source = operation.GetSource(0);
  685. SpvInstruction result;
  686. if (operation.Inst.HasFlag(Instruction.FP64))
  687. {
  688. result = context.IsNan(context.TypeBool(), context.GetFP64(source));
  689. }
  690. else
  691. {
  692. result = context.IsNan(context.TypeBool(), context.GetFP32(source));
  693. }
  694. return new OperationResult(AggregateType.Bool, result);
  695. }
  696. private static OperationResult GenerateLoad(CodeGenContext context, AstOperation operation)
  697. {
  698. return GenerateLoadOrStore(context, operation, isStore: false);
  699. }
  700. private static OperationResult GenerateLoadConstant(CodeGenContext context, AstOperation operation)
  701. {
  702. var src1 = operation.GetSource(0);
  703. var src2 = context.Get(AggregateType.S32, operation.GetSource(1));
  704. var i1 = context.Constant(context.TypeS32(), 0);
  705. var i2 = context.ShiftRightArithmetic(context.TypeS32(), src2, context.Constant(context.TypeS32(), 2));
  706. var i3 = context.BitwiseAnd(context.TypeS32(), src2, context.Constant(context.TypeS32(), 3));
  707. SpvInstruction value = null;
  708. if (context.Config.GpuAccessor.QueryHostHasVectorIndexingBug())
  709. {
  710. // Test for each component individually.
  711. for (int i = 0; i < 4; i++)
  712. {
  713. var component = context.Constant(context.TypeS32(), i);
  714. SpvInstruction elemPointer;
  715. if (context.UniformBuffersArray != null)
  716. {
  717. var ubVariable = context.UniformBuffersArray;
  718. var i0 = context.Get(AggregateType.S32, src1);
  719. elemPointer = context.AccessChain(context.TypePointer(StorageClass.Uniform, context.TypeFP32()), ubVariable, i0, i1, i2, component);
  720. }
  721. else
  722. {
  723. var ubVariable = context.UniformBuffers[((AstOperand)src1).Value];
  724. elemPointer = context.AccessChain(context.TypePointer(StorageClass.Uniform, context.TypeFP32()), ubVariable, i1, i2, component);
  725. }
  726. SpvInstruction newValue = context.Load(context.TypeFP32(), elemPointer);
  727. value = value != null ? context.Select(context.TypeFP32(), context.IEqual(context.TypeBool(), i3, component), newValue, value) : newValue;
  728. }
  729. }
  730. else
  731. {
  732. SpvInstruction elemPointer;
  733. if (context.UniformBuffersArray != null)
  734. {
  735. var ubVariable = context.UniformBuffersArray;
  736. var i0 = context.Get(AggregateType.S32, src1);
  737. elemPointer = context.AccessChain(context.TypePointer(StorageClass.Uniform, context.TypeFP32()), ubVariable, i0, i1, i2, i3);
  738. }
  739. else
  740. {
  741. var ubVariable = context.UniformBuffers[((AstOperand)src1).Value];
  742. elemPointer = context.AccessChain(context.TypePointer(StorageClass.Uniform, context.TypeFP32()), ubVariable, i1, i2, i3);
  743. }
  744. value = context.Load(context.TypeFP32(), elemPointer);
  745. }
  746. return new OperationResult(AggregateType.FP32, value);
  747. }
  748. private static OperationResult GenerateLoadLocal(CodeGenContext context, AstOperation operation)
  749. {
  750. return GenerateLoadLocalOrShared(context, operation, StorageClass.Private, context.LocalMemory);
  751. }
  752. private static OperationResult GenerateLoadShared(CodeGenContext context, AstOperation operation)
  753. {
  754. return GenerateLoadLocalOrShared(context, operation, StorageClass.Workgroup, context.SharedMemory);
  755. }
  756. private static OperationResult GenerateLoadLocalOrShared(
  757. CodeGenContext context,
  758. AstOperation operation,
  759. StorageClass storageClass,
  760. SpvInstruction memory)
  761. {
  762. var offset = context.Get(AggregateType.S32, operation.GetSource(0));
  763. var elemPointer = context.AccessChain(context.TypePointer(storageClass, context.TypeU32()), memory, offset);
  764. var value = context.Load(context.TypeU32(), elemPointer);
  765. return new OperationResult(AggregateType.U32, value);
  766. }
  767. private static OperationResult GenerateLoadStorage(CodeGenContext context, AstOperation operation)
  768. {
  769. var elemPointer = GetStorageElemPointer(context, operation);
  770. var value = context.Load(context.TypeU32(), elemPointer);
  771. return new OperationResult(AggregateType.U32, value);
  772. }
  773. private static OperationResult GenerateLod(CodeGenContext context, AstOperation operation)
  774. {
  775. AstTextureOperation texOp = (AstTextureOperation)operation;
  776. bool isBindless = (texOp.Flags & TextureFlags.Bindless) != 0;
  777. bool isIndexed = (texOp.Type & SamplerType.Indexed) != 0;
  778. // TODO: Bindless texture support. For now we just return 0.
  779. if (isBindless)
  780. {
  781. return new OperationResult(AggregateType.S32, context.Constant(context.TypeS32(), 0));
  782. }
  783. int srcIndex = 0;
  784. SpvInstruction Src(AggregateType type)
  785. {
  786. return context.Get(type, texOp.GetSource(srcIndex++));
  787. }
  788. SpvInstruction index = null;
  789. if (isIndexed)
  790. {
  791. index = Src(AggregateType.S32);
  792. }
  793. int pCount = texOp.Type.GetDimensions();
  794. SpvInstruction pCoords;
  795. if (pCount > 1)
  796. {
  797. SpvInstruction[] elems = new SpvInstruction[pCount];
  798. for (int i = 0; i < pCount; i++)
  799. {
  800. elems[i] = Src(AggregateType.FP32);
  801. }
  802. var vectorType = context.TypeVector(context.TypeFP32(), pCount);
  803. pCoords = context.CompositeConstruct(vectorType, elems);
  804. }
  805. else
  806. {
  807. pCoords = Src(AggregateType.FP32);
  808. }
  809. var meta = new TextureMeta(texOp.CbufSlot, texOp.Handle, texOp.Format);
  810. (_, var sampledImageType, var sampledImageVariable) = context.Samplers[meta];
  811. var image = context.Load(sampledImageType, sampledImageVariable);
  812. var resultType = context.TypeVector(context.TypeFP32(), 2);
  813. var packed = context.ImageQueryLod(resultType, image, pCoords);
  814. var result = context.CompositeExtract(context.TypeFP32(), packed, (SpvLiteralInteger)texOp.Index);
  815. return new OperationResult(AggregateType.FP32, result);
  816. }
  817. private static OperationResult GenerateLogarithmB2(CodeGenContext context, AstOperation operation)
  818. {
  819. return GenerateUnary(context, operation, context.Delegates.GlslLog2, null);
  820. }
  821. private static OperationResult GenerateLogicalAnd(CodeGenContext context, AstOperation operation)
  822. {
  823. return GenerateBinaryBool(context, operation, context.Delegates.LogicalAnd);
  824. }
  825. private static OperationResult GenerateLogicalExclusiveOr(CodeGenContext context, AstOperation operation)
  826. {
  827. return GenerateBinaryBool(context, operation, context.Delegates.LogicalNotEqual);
  828. }
  829. private static OperationResult GenerateLogicalNot(CodeGenContext context, AstOperation operation)
  830. {
  831. return GenerateUnaryBool(context, operation, context.Delegates.LogicalNot);
  832. }
  833. private static OperationResult GenerateLogicalOr(CodeGenContext context, AstOperation operation)
  834. {
  835. return GenerateBinaryBool(context, operation, context.Delegates.LogicalOr);
  836. }
  837. private static OperationResult GenerateLoopBreak(CodeGenContext context, AstOperation operation)
  838. {
  839. AstBlock loopBlock = context.CurrentBlock;
  840. while (loopBlock.Type != AstBlockType.DoWhile)
  841. {
  842. loopBlock = loopBlock.Parent;
  843. }
  844. context.Branch(context.GetNextLabel(loopBlock.Parent));
  845. return OperationResult.Invalid;
  846. }
  847. private static OperationResult GenerateLoopContinue(CodeGenContext context, AstOperation operation)
  848. {
  849. AstBlock loopBlock = context.CurrentBlock;
  850. while (loopBlock.Type != AstBlockType.DoWhile)
  851. {
  852. loopBlock = loopBlock.Parent;
  853. }
  854. (var loopTarget, var continueTarget) = context.LoopTargets[loopBlock];
  855. context.Branch(continueTarget);
  856. return OperationResult.Invalid;
  857. }
  858. private static OperationResult GenerateMaximum(CodeGenContext context, AstOperation operation)
  859. {
  860. return GenerateBinary(context, operation, context.Delegates.GlslFMax, context.Delegates.GlslSMax);
  861. }
  862. private static OperationResult GenerateMaximumU32(CodeGenContext context, AstOperation operation)
  863. {
  864. return GenerateBinaryU32(context, operation, context.Delegates.GlslUMax);
  865. }
  866. private static OperationResult GenerateMemoryBarrier(CodeGenContext context, AstOperation operation)
  867. {
  868. context.MemoryBarrier(context.Constant(context.TypeU32(), Scope.Device), context.Constant(context.TypeU32(), DefaultMemorySemantics));
  869. return OperationResult.Invalid;
  870. }
  871. private static OperationResult GenerateMinimum(CodeGenContext context, AstOperation operation)
  872. {
  873. return GenerateBinary(context, operation, context.Delegates.GlslFMin, context.Delegates.GlslSMin);
  874. }
  875. private static OperationResult GenerateMinimumU32(CodeGenContext context, AstOperation operation)
  876. {
  877. return GenerateBinaryU32(context, operation, context.Delegates.GlslUMin);
  878. }
  879. private static OperationResult GenerateMultiply(CodeGenContext context, AstOperation operation)
  880. {
  881. return GenerateBinary(context, operation, context.Delegates.FMul, context.Delegates.IMul);
  882. }
  883. private static OperationResult GenerateMultiplyHighS32(CodeGenContext context, AstOperation operation)
  884. {
  885. var src1 = operation.GetSource(0);
  886. var src2 = operation.GetSource(1);
  887. var resultType = context.TypeStruct(false, context.TypeS32(), context.TypeS32());
  888. var result = context.SMulExtended(resultType, context.GetS32(src1), context.GetS32(src2));
  889. result = context.CompositeExtract(context.TypeS32(), result, 1);
  890. return new OperationResult(AggregateType.S32, result);
  891. }
  892. private static OperationResult GenerateMultiplyHighU32(CodeGenContext context, AstOperation operation)
  893. {
  894. var src1 = operation.GetSource(0);
  895. var src2 = operation.GetSource(1);
  896. var resultType = context.TypeStruct(false, context.TypeU32(), context.TypeU32());
  897. var result = context.UMulExtended(resultType, context.GetU32(src1), context.GetU32(src2));
  898. result = context.CompositeExtract(context.TypeU32(), result, 1);
  899. return new OperationResult(AggregateType.U32, result);
  900. }
  901. private static OperationResult GenerateNegate(CodeGenContext context, AstOperation operation)
  902. {
  903. return GenerateUnary(context, operation, context.Delegates.FNegate, context.Delegates.SNegate);
  904. }
  905. private static OperationResult GeneratePackDouble2x32(CodeGenContext context, AstOperation operation)
  906. {
  907. var value0 = context.GetU32(operation.GetSource(0));
  908. var value1 = context.GetU32(operation.GetSource(1));
  909. var vector = context.CompositeConstruct(context.TypeVector(context.TypeU32(), 2), value0, value1);
  910. var result = context.GlslPackDouble2x32(context.TypeFP64(), vector);
  911. return new OperationResult(AggregateType.FP64, result);
  912. }
  913. private static OperationResult GeneratePackHalf2x16(CodeGenContext context, AstOperation operation)
  914. {
  915. var value0 = context.GetFP32(operation.GetSource(0));
  916. var value1 = context.GetFP32(operation.GetSource(1));
  917. var vector = context.CompositeConstruct(context.TypeVector(context.TypeFP32(), 2), value0, value1);
  918. var result = context.GlslPackHalf2x16(context.TypeU32(), vector);
  919. return new OperationResult(AggregateType.U32, result);
  920. }
  921. private static OperationResult GenerateReciprocalSquareRoot(CodeGenContext context, AstOperation operation)
  922. {
  923. return GenerateUnary(context, operation, context.Delegates.GlslInverseSqrt, null);
  924. }
  925. private static OperationResult GenerateReturn(CodeGenContext context, AstOperation operation)
  926. {
  927. context.Return();
  928. return OperationResult.Invalid;
  929. }
  930. private static OperationResult GenerateRound(CodeGenContext context, AstOperation operation)
  931. {
  932. return GenerateUnary(context, operation, context.Delegates.GlslRoundEven, null);
  933. }
  934. private static OperationResult GenerateShiftLeft(CodeGenContext context, AstOperation operation)
  935. {
  936. return GenerateBinaryS32(context, operation, context.Delegates.ShiftLeftLogical);
  937. }
  938. private static OperationResult GenerateShiftRightS32(CodeGenContext context, AstOperation operation)
  939. {
  940. return GenerateBinaryS32(context, operation, context.Delegates.ShiftRightArithmetic);
  941. }
  942. private static OperationResult GenerateShiftRightU32(CodeGenContext context, AstOperation operation)
  943. {
  944. return GenerateBinaryS32(context, operation, context.Delegates.ShiftRightLogical);
  945. }
  946. private static OperationResult GenerateShuffle(CodeGenContext context, AstOperation operation)
  947. {
  948. var x = context.GetFP32(operation.GetSource(0));
  949. var index = context.GetU32(operation.GetSource(1));
  950. var mask = context.GetU32(operation.GetSource(2));
  951. var const31 = context.Constant(context.TypeU32(), 31);
  952. var const8 = context.Constant(context.TypeU32(), 8);
  953. var clamp = context.BitwiseAnd(context.TypeU32(), mask, const31);
  954. var segMask = context.BitwiseAnd(context.TypeU32(), context.ShiftRightLogical(context.TypeU32(), mask, const8), const31);
  955. var notSegMask = context.Not(context.TypeU32(), segMask);
  956. var clampNotSegMask = context.BitwiseAnd(context.TypeU32(), clamp, notSegMask);
  957. var indexNotSegMask = context.BitwiseAnd(context.TypeU32(), index, notSegMask);
  958. var threadId = GetScalarInput(context, IoVariable.SubgroupLaneId);
  959. var minThreadId = context.BitwiseAnd(context.TypeU32(), threadId, segMask);
  960. var maxThreadId = context.BitwiseOr(context.TypeU32(), minThreadId, clampNotSegMask);
  961. var srcThreadId = context.BitwiseOr(context.TypeU32(), indexNotSegMask, minThreadId);
  962. var valid = context.ULessThanEqual(context.TypeBool(), srcThreadId, maxThreadId);
  963. var value = context.GroupNonUniformShuffle(context.TypeFP32(), context.Constant(context.TypeU32(), (int)Scope.Subgroup), x, srcThreadId);
  964. var result = context.Select(context.TypeFP32(), valid, value, x);
  965. var validLocal = (AstOperand)operation.GetSource(3);
  966. context.Store(context.GetLocalPointer(validLocal), context.BitcastIfNeeded(validLocal.VarType, AggregateType.Bool, valid));
  967. return new OperationResult(AggregateType.FP32, result);
  968. }
  969. private static OperationResult GenerateShuffleDown(CodeGenContext context, AstOperation operation)
  970. {
  971. var x = context.GetFP32(operation.GetSource(0));
  972. var index = context.GetU32(operation.GetSource(1));
  973. var mask = context.GetU32(operation.GetSource(2));
  974. var const31 = context.Constant(context.TypeU32(), 31);
  975. var const8 = context.Constant(context.TypeU32(), 8);
  976. var clamp = context.BitwiseAnd(context.TypeU32(), mask, const31);
  977. var segMask = context.BitwiseAnd(context.TypeU32(), context.ShiftRightLogical(context.TypeU32(), mask, const8), const31);
  978. var notSegMask = context.Not(context.TypeU32(), segMask);
  979. var clampNotSegMask = context.BitwiseAnd(context.TypeU32(), clamp, notSegMask);
  980. var threadId = GetScalarInput(context, IoVariable.SubgroupLaneId);
  981. var minThreadId = context.BitwiseAnd(context.TypeU32(), threadId, segMask);
  982. var maxThreadId = context.BitwiseOr(context.TypeU32(), minThreadId, clampNotSegMask);
  983. var srcThreadId = context.IAdd(context.TypeU32(), threadId, index);
  984. var valid = context.ULessThanEqual(context.TypeBool(), srcThreadId, maxThreadId);
  985. var value = context.GroupNonUniformShuffle(context.TypeFP32(), context.Constant(context.TypeU32(), (int)Scope.Subgroup), x, srcThreadId);
  986. var result = context.Select(context.TypeFP32(), valid, value, x);
  987. var validLocal = (AstOperand)operation.GetSource(3);
  988. context.Store(context.GetLocalPointer(validLocal), context.BitcastIfNeeded(validLocal.VarType, AggregateType.Bool, valid));
  989. return new OperationResult(AggregateType.FP32, result);
  990. }
  991. private static OperationResult GenerateShuffleUp(CodeGenContext context, AstOperation operation)
  992. {
  993. var x = context.GetFP32(operation.GetSource(0));
  994. var index = context.GetU32(operation.GetSource(1));
  995. var mask = context.GetU32(operation.GetSource(2));
  996. var const31 = context.Constant(context.TypeU32(), 31);
  997. var const8 = context.Constant(context.TypeU32(), 8);
  998. var segMask = context.BitwiseAnd(context.TypeU32(), context.ShiftRightLogical(context.TypeU32(), mask, const8), const31);
  999. var threadId = GetScalarInput(context, IoVariable.SubgroupLaneId);
  1000. var minThreadId = context.BitwiseAnd(context.TypeU32(), threadId, segMask);
  1001. var srcThreadId = context.ISub(context.TypeU32(), threadId, index);
  1002. var valid = context.SGreaterThanEqual(context.TypeBool(), srcThreadId, minThreadId);
  1003. var value = context.GroupNonUniformShuffle(context.TypeFP32(), context.Constant(context.TypeU32(), (int)Scope.Subgroup), x, srcThreadId);
  1004. var result = context.Select(context.TypeFP32(), valid, value, x);
  1005. var validLocal = (AstOperand)operation.GetSource(3);
  1006. context.Store(context.GetLocalPointer(validLocal), context.BitcastIfNeeded(validLocal.VarType, AggregateType.Bool, valid));
  1007. return new OperationResult(AggregateType.FP32, result);
  1008. }
  1009. private static OperationResult GenerateShuffleXor(CodeGenContext context, AstOperation operation)
  1010. {
  1011. var x = context.GetFP32(operation.GetSource(0));
  1012. var index = context.GetU32(operation.GetSource(1));
  1013. var mask = context.GetU32(operation.GetSource(2));
  1014. var const31 = context.Constant(context.TypeU32(), 31);
  1015. var const8 = context.Constant(context.TypeU32(), 8);
  1016. var clamp = context.BitwiseAnd(context.TypeU32(), mask, const31);
  1017. var segMask = context.BitwiseAnd(context.TypeU32(), context.ShiftRightLogical(context.TypeU32(), mask, const8), const31);
  1018. var notSegMask = context.Not(context.TypeU32(), segMask);
  1019. var clampNotSegMask = context.BitwiseAnd(context.TypeU32(), clamp, notSegMask);
  1020. var threadId = GetScalarInput(context, IoVariable.SubgroupLaneId);
  1021. var minThreadId = context.BitwiseAnd(context.TypeU32(), threadId, segMask);
  1022. var maxThreadId = context.BitwiseOr(context.TypeU32(), minThreadId, clampNotSegMask);
  1023. var srcThreadId = context.BitwiseXor(context.TypeU32(), threadId, index);
  1024. var valid = context.ULessThanEqual(context.TypeBool(), srcThreadId, maxThreadId);
  1025. var value = context.GroupNonUniformShuffle(context.TypeFP32(), context.Constant(context.TypeU32(), (int)Scope.Subgroup), x, srcThreadId);
  1026. var result = context.Select(context.TypeFP32(), valid, value, x);
  1027. var validLocal = (AstOperand)operation.GetSource(3);
  1028. context.Store(context.GetLocalPointer(validLocal), context.BitcastIfNeeded(validLocal.VarType, AggregateType.Bool, valid));
  1029. return new OperationResult(AggregateType.FP32, result);
  1030. }
  1031. private static OperationResult GenerateSine(CodeGenContext context, AstOperation operation)
  1032. {
  1033. return GenerateUnary(context, operation, context.Delegates.GlslSin, null);
  1034. }
  1035. private static OperationResult GenerateSquareRoot(CodeGenContext context, AstOperation operation)
  1036. {
  1037. return GenerateUnary(context, operation, context.Delegates.GlslSqrt, null);
  1038. }
  1039. private static OperationResult GenerateStore(CodeGenContext context, AstOperation operation)
  1040. {
  1041. return GenerateLoadOrStore(context, operation, isStore: true);
  1042. }
  1043. private static OperationResult GenerateStoreLocal(CodeGenContext context, AstOperation operation)
  1044. {
  1045. return GenerateStoreLocalOrShared(context, operation, StorageClass.Private, context.LocalMemory);
  1046. }
  1047. private static OperationResult GenerateStoreShared(CodeGenContext context, AstOperation operation)
  1048. {
  1049. return GenerateStoreLocalOrShared(context, operation, StorageClass.Workgroup, context.SharedMemory);
  1050. }
  1051. private static OperationResult GenerateStoreLocalOrShared(
  1052. CodeGenContext context,
  1053. AstOperation operation,
  1054. StorageClass storageClass,
  1055. SpvInstruction memory)
  1056. {
  1057. var offset = context.Get(AggregateType.S32, operation.GetSource(0));
  1058. var value = context.Get(AggregateType.U32, operation.GetSource(1));
  1059. var elemPointer = context.AccessChain(context.TypePointer(storageClass, context.TypeU32()), memory, offset);
  1060. context.Store(elemPointer, value);
  1061. return OperationResult.Invalid;
  1062. }
  1063. private static OperationResult GenerateStoreShared16(CodeGenContext context, AstOperation operation)
  1064. {
  1065. GenerateStoreSharedSmallInt(context, operation, 16);
  1066. return OperationResult.Invalid;
  1067. }
  1068. private static OperationResult GenerateStoreShared8(CodeGenContext context, AstOperation operation)
  1069. {
  1070. GenerateStoreSharedSmallInt(context, operation, 8);
  1071. return OperationResult.Invalid;
  1072. }
  1073. private static OperationResult GenerateStoreStorage(CodeGenContext context, AstOperation operation)
  1074. {
  1075. var elemPointer = GetStorageElemPointer(context, operation);
  1076. context.Store(elemPointer, context.Get(AggregateType.U32, operation.GetSource(2)));
  1077. return OperationResult.Invalid;
  1078. }
  1079. private static OperationResult GenerateStoreStorage16(CodeGenContext context, AstOperation operation)
  1080. {
  1081. GenerateStoreStorageSmallInt(context, operation, 16);
  1082. return OperationResult.Invalid;
  1083. }
  1084. private static OperationResult GenerateStoreStorage8(CodeGenContext context, AstOperation operation)
  1085. {
  1086. GenerateStoreStorageSmallInt(context, operation, 8);
  1087. return OperationResult.Invalid;
  1088. }
  1089. private static OperationResult GenerateSubtract(CodeGenContext context, AstOperation operation)
  1090. {
  1091. return GenerateBinary(context, operation, context.Delegates.FSub, context.Delegates.ISub);
  1092. }
  1093. private static OperationResult GenerateSwizzleAdd(CodeGenContext context, AstOperation operation)
  1094. {
  1095. var x = context.Get(AggregateType.FP32, operation.GetSource(0));
  1096. var y = context.Get(AggregateType.FP32, operation.GetSource(1));
  1097. var mask = context.Get(AggregateType.U32, operation.GetSource(2));
  1098. var v4float = context.TypeVector(context.TypeFP32(), 4);
  1099. var one = context.Constant(context.TypeFP32(), 1.0f);
  1100. var minusOne = context.Constant(context.TypeFP32(), -1.0f);
  1101. var zero = context.Constant(context.TypeFP32(), 0.0f);
  1102. var xLut = context.ConstantComposite(v4float, one, minusOne, one, zero);
  1103. var yLut = context.ConstantComposite(v4float, one, one, minusOne, one);
  1104. var three = context.Constant(context.TypeU32(), 3);
  1105. var threadId = GetScalarInput(context, IoVariable.SubgroupLaneId);
  1106. var shift = context.BitwiseAnd(context.TypeU32(), threadId, three);
  1107. shift = context.ShiftLeftLogical(context.TypeU32(), shift, context.Constant(context.TypeU32(), 1));
  1108. var lutIdx = context.ShiftRightLogical(context.TypeU32(), mask, shift);
  1109. lutIdx = context.BitwiseAnd(context.TypeU32(), lutIdx, three);
  1110. var xLutValue = context.VectorExtractDynamic(context.TypeFP32(), xLut, lutIdx);
  1111. var yLutValue = context.VectorExtractDynamic(context.TypeFP32(), yLut, lutIdx);
  1112. var xResult = context.FMul(context.TypeFP32(), x, xLutValue);
  1113. var yResult = context.FMul(context.TypeFP32(), y, yLutValue);
  1114. var result = context.FAdd(context.TypeFP32(), xResult, yResult);
  1115. return new OperationResult(AggregateType.FP32, result);
  1116. }
  1117. private static OperationResult GenerateTextureSample(CodeGenContext context, AstOperation operation)
  1118. {
  1119. AstTextureOperation texOp = (AstTextureOperation)operation;
  1120. bool isBindless = (texOp.Flags & TextureFlags.Bindless) != 0;
  1121. bool isGather = (texOp.Flags & TextureFlags.Gather) != 0;
  1122. bool hasDerivatives = (texOp.Flags & TextureFlags.Derivatives) != 0;
  1123. bool intCoords = (texOp.Flags & TextureFlags.IntCoords) != 0;
  1124. bool hasLodBias = (texOp.Flags & TextureFlags.LodBias) != 0;
  1125. bool hasLodLevel = (texOp.Flags & TextureFlags.LodLevel) != 0;
  1126. bool hasOffset = (texOp.Flags & TextureFlags.Offset) != 0;
  1127. bool hasOffsets = (texOp.Flags & TextureFlags.Offsets) != 0;
  1128. bool isArray = (texOp.Type & SamplerType.Array) != 0;
  1129. bool isIndexed = (texOp.Type & SamplerType.Indexed) != 0;
  1130. bool isMultisample = (texOp.Type & SamplerType.Multisample) != 0;
  1131. bool isShadow = (texOp.Type & SamplerType.Shadow) != 0;
  1132. bool colorIsVector = isGather || !isShadow;
  1133. // TODO: Bindless texture support. For now we just return 0.
  1134. if (isBindless)
  1135. {
  1136. return GetZeroOperationResult(context, texOp, AggregateType.FP32, colorIsVector);
  1137. }
  1138. // This combination is valid, but not available on GLSL.
  1139. // For now, ignore the LOD level and do a normal sample.
  1140. // TODO: How to implement it properly?
  1141. if (hasLodLevel && isArray && isShadow)
  1142. {
  1143. hasLodLevel = false;
  1144. }
  1145. int srcIndex = isBindless ? 1 : 0;
  1146. SpvInstruction Src(AggregateType type)
  1147. {
  1148. return context.Get(type, texOp.GetSource(srcIndex++));
  1149. }
  1150. SpvInstruction index = null;
  1151. if (isIndexed)
  1152. {
  1153. index = Src(AggregateType.S32);
  1154. }
  1155. int coordsCount = texOp.Type.GetDimensions();
  1156. int pCount = coordsCount;
  1157. int arrayIndexElem = -1;
  1158. if (isArray)
  1159. {
  1160. arrayIndexElem = pCount++;
  1161. }
  1162. AggregateType coordType = intCoords ? AggregateType.S32 : AggregateType.FP32;
  1163. SpvInstruction AssemblePVector(int count)
  1164. {
  1165. if (count > 1)
  1166. {
  1167. SpvInstruction[] elems = new SpvInstruction[count];
  1168. for (int index = 0; index < count; index++)
  1169. {
  1170. if (arrayIndexElem == index)
  1171. {
  1172. elems[index] = Src(AggregateType.S32);
  1173. if (!intCoords)
  1174. {
  1175. elems[index] = context.ConvertSToF(context.TypeFP32(), elems[index]);
  1176. }
  1177. }
  1178. else
  1179. {
  1180. elems[index] = Src(coordType);
  1181. }
  1182. }
  1183. var vectorType = context.TypeVector(intCoords ? context.TypeS32() : context.TypeFP32(), count);
  1184. return context.CompositeConstruct(vectorType, elems);
  1185. }
  1186. else
  1187. {
  1188. return Src(coordType);
  1189. }
  1190. }
  1191. SpvInstruction ApplyBias(SpvInstruction vector, SpvInstruction image)
  1192. {
  1193. int gatherBiasPrecision = context.Config.GpuAccessor.QueryHostGatherBiasPrecision();
  1194. if (isGather && gatherBiasPrecision != 0)
  1195. {
  1196. // GPU requires texture gather to be slightly offset to match NVIDIA behaviour when point is exactly between two texels.
  1197. // Offset by the gather precision divided by 2 to correct for rounding.
  1198. var sizeType = pCount == 1 ? context.TypeS32() : context.TypeVector(context.TypeS32(), pCount);
  1199. var pVectorType = pCount == 1 ? context.TypeFP32() : context.TypeVector(context.TypeFP32(), pCount);
  1200. var bias = context.Constant(context.TypeFP32(), (float)(1 << (gatherBiasPrecision + 1)));
  1201. var biasVector = context.CompositeConstruct(pVectorType, Enumerable.Repeat(bias, pCount).ToArray());
  1202. var one = context.Constant(context.TypeFP32(), 1f);
  1203. var oneVector = context.CompositeConstruct(pVectorType, Enumerable.Repeat(one, pCount).ToArray());
  1204. var divisor = context.FMul(
  1205. pVectorType,
  1206. context.ConvertSToF(pVectorType, context.ImageQuerySize(sizeType, image)),
  1207. biasVector);
  1208. vector = context.FAdd(pVectorType, vector, context.FDiv(pVectorType, oneVector, divisor));
  1209. }
  1210. return vector;
  1211. }
  1212. SpvInstruction pCoords = AssemblePVector(pCount);
  1213. pCoords = ScalingHelpers.ApplyScaling(context, texOp, pCoords, intCoords, isBindless, isIndexed, isArray, pCount);
  1214. SpvInstruction AssembleDerivativesVector(int count)
  1215. {
  1216. if (count > 1)
  1217. {
  1218. SpvInstruction[] elems = new SpvInstruction[count];
  1219. for (int index = 0; index < count; index++)
  1220. {
  1221. elems[index] = Src(AggregateType.FP32);
  1222. }
  1223. var vectorType = context.TypeVector(context.TypeFP32(), count);
  1224. return context.CompositeConstruct(vectorType, elems);
  1225. }
  1226. else
  1227. {
  1228. return Src(AggregateType.FP32);
  1229. }
  1230. }
  1231. SpvInstruction dRef = null;
  1232. if (isShadow)
  1233. {
  1234. dRef = Src(AggregateType.FP32);
  1235. }
  1236. SpvInstruction[] derivatives = null;
  1237. if (hasDerivatives)
  1238. {
  1239. derivatives = new[]
  1240. {
  1241. AssembleDerivativesVector(coordsCount), // dPdx
  1242. AssembleDerivativesVector(coordsCount) // dPdy
  1243. };
  1244. }
  1245. SpvInstruction sample = null;
  1246. SpvInstruction lod = null;
  1247. if (isMultisample)
  1248. {
  1249. sample = Src(AggregateType.S32);
  1250. }
  1251. else if (hasLodLevel)
  1252. {
  1253. lod = Src(coordType);
  1254. }
  1255. SpvInstruction AssembleOffsetVector(int count)
  1256. {
  1257. if (count > 1)
  1258. {
  1259. SpvInstruction[] elems = new SpvInstruction[count];
  1260. for (int index = 0; index < count; index++)
  1261. {
  1262. elems[index] = Src(AggregateType.S32);
  1263. }
  1264. var vectorType = context.TypeVector(context.TypeS32(), count);
  1265. return context.ConstantComposite(vectorType, elems);
  1266. }
  1267. else
  1268. {
  1269. return Src(AggregateType.S32);
  1270. }
  1271. }
  1272. SpvInstruction[] offsets = null;
  1273. if (hasOffset)
  1274. {
  1275. offsets = new[] { AssembleOffsetVector(coordsCount) };
  1276. }
  1277. else if (hasOffsets)
  1278. {
  1279. offsets = new[]
  1280. {
  1281. AssembleOffsetVector(coordsCount),
  1282. AssembleOffsetVector(coordsCount),
  1283. AssembleOffsetVector(coordsCount),
  1284. AssembleOffsetVector(coordsCount)
  1285. };
  1286. }
  1287. SpvInstruction lodBias = null;
  1288. if (hasLodBias)
  1289. {
  1290. lodBias = Src(AggregateType.FP32);
  1291. }
  1292. SpvInstruction compIdx = null;
  1293. // textureGather* optional extra component index,
  1294. // not needed for shadow samplers.
  1295. if (isGather && !isShadow)
  1296. {
  1297. compIdx = Src(AggregateType.S32);
  1298. }
  1299. var operandsList = new List<SpvInstruction>();
  1300. var operandsMask = ImageOperandsMask.MaskNone;
  1301. if (hasLodBias)
  1302. {
  1303. operandsMask |= ImageOperandsMask.Bias;
  1304. operandsList.Add(lodBias);
  1305. }
  1306. if (!isMultisample && hasLodLevel)
  1307. {
  1308. operandsMask |= ImageOperandsMask.Lod;
  1309. operandsList.Add(lod);
  1310. }
  1311. if (hasDerivatives)
  1312. {
  1313. operandsMask |= ImageOperandsMask.Grad;
  1314. operandsList.Add(derivatives[0]);
  1315. operandsList.Add(derivatives[1]);
  1316. }
  1317. if (hasOffset)
  1318. {
  1319. operandsMask |= ImageOperandsMask.ConstOffset;
  1320. operandsList.Add(offsets[0]);
  1321. }
  1322. else if (hasOffsets)
  1323. {
  1324. operandsMask |= ImageOperandsMask.ConstOffsets;
  1325. SpvInstruction arrayv2 = context.TypeArray(context.TypeVector(context.TypeS32(), 2), context.Constant(context.TypeU32(), 4));
  1326. operandsList.Add(context.ConstantComposite(arrayv2, offsets[0], offsets[1], offsets[2], offsets[3]));
  1327. }
  1328. if (isMultisample)
  1329. {
  1330. operandsMask |= ImageOperandsMask.Sample;
  1331. operandsList.Add(sample);
  1332. }
  1333. var resultType = colorIsVector ? context.TypeVector(context.TypeFP32(), 4) : context.TypeFP32();
  1334. var meta = new TextureMeta(texOp.CbufSlot, texOp.Handle, texOp.Format);
  1335. (var imageType, var sampledImageType, var sampledImageVariable) = context.Samplers[meta];
  1336. var image = context.Load(sampledImageType, sampledImageVariable);
  1337. if (intCoords)
  1338. {
  1339. image = context.Image(imageType, image);
  1340. }
  1341. pCoords = ApplyBias(pCoords, image);
  1342. var operands = operandsList.ToArray();
  1343. SpvInstruction result;
  1344. if (intCoords)
  1345. {
  1346. result = context.ImageFetch(resultType, image, pCoords, operandsMask, operands);
  1347. }
  1348. else if (isGather)
  1349. {
  1350. if (isShadow)
  1351. {
  1352. result = context.ImageDrefGather(resultType, image, pCoords, dRef, operandsMask, operands);
  1353. }
  1354. else
  1355. {
  1356. result = context.ImageGather(resultType, image, pCoords, compIdx, operandsMask, operands);
  1357. }
  1358. }
  1359. else if (isShadow)
  1360. {
  1361. if (hasLodLevel)
  1362. {
  1363. result = context.ImageSampleDrefExplicitLod(resultType, image, pCoords, dRef, operandsMask, operands);
  1364. }
  1365. else
  1366. {
  1367. result = context.ImageSampleDrefImplicitLod(resultType, image, pCoords, dRef, operandsMask, operands);
  1368. }
  1369. }
  1370. else if (hasDerivatives || hasLodLevel)
  1371. {
  1372. result = context.ImageSampleExplicitLod(resultType, image, pCoords, operandsMask, operands);
  1373. }
  1374. else
  1375. {
  1376. result = context.ImageSampleImplicitLod(resultType, image, pCoords, operandsMask, operands);
  1377. }
  1378. var swizzledResultType = AggregateType.FP32;
  1379. if (colorIsVector)
  1380. {
  1381. swizzledResultType = texOp.GetVectorType(swizzledResultType);
  1382. result = GetSwizzledResult(context, result, swizzledResultType, texOp.Index);
  1383. }
  1384. return new OperationResult(swizzledResultType, result);
  1385. }
  1386. private static OperationResult GenerateTextureSize(CodeGenContext context, AstOperation operation)
  1387. {
  1388. AstTextureOperation texOp = (AstTextureOperation)operation;
  1389. bool isBindless = (texOp.Flags & TextureFlags.Bindless) != 0;
  1390. // TODO: Bindless texture support. For now we just return 0.
  1391. if (isBindless)
  1392. {
  1393. return new OperationResult(AggregateType.S32, context.Constant(context.TypeS32(), 0));
  1394. }
  1395. bool isIndexed = (texOp.Type & SamplerType.Indexed) != 0;
  1396. SpvInstruction index = null;
  1397. if (isIndexed)
  1398. {
  1399. index = context.GetS32(texOp.GetSource(0));
  1400. }
  1401. var meta = new TextureMeta(texOp.CbufSlot, texOp.Handle, texOp.Format);
  1402. (var imageType, var sampledImageType, var sampledImageVariable) = context.Samplers[meta];
  1403. var image = context.Load(sampledImageType, sampledImageVariable);
  1404. image = context.Image(imageType, image);
  1405. if (texOp.Index == 3)
  1406. {
  1407. return new OperationResult(AggregateType.S32, context.ImageQueryLevels(context.TypeS32(), image));
  1408. }
  1409. else
  1410. {
  1411. var type = context.SamplersTypes[meta];
  1412. bool hasLod = !type.HasFlag(SamplerType.Multisample) && type != SamplerType.TextureBuffer;
  1413. int dimensions = (type & SamplerType.Mask) == SamplerType.TextureCube ? 2 : type.GetDimensions();
  1414. if (type.HasFlag(SamplerType.Array))
  1415. {
  1416. dimensions++;
  1417. }
  1418. var resultType = dimensions == 1 ? context.TypeS32() : context.TypeVector(context.TypeS32(), dimensions);
  1419. SpvInstruction result;
  1420. if (hasLod)
  1421. {
  1422. int lodSrcIndex = isBindless || isIndexed ? 1 : 0;
  1423. var lod = context.GetS32(operation.GetSource(lodSrcIndex));
  1424. result = context.ImageQuerySizeLod(resultType, image, lod);
  1425. }
  1426. else
  1427. {
  1428. result = context.ImageQuerySize(resultType, image);
  1429. }
  1430. if (dimensions != 1)
  1431. {
  1432. result = context.CompositeExtract(context.TypeS32(), result, (SpvLiteralInteger)texOp.Index);
  1433. }
  1434. if (texOp.Index < 2 || (type & SamplerType.Mask) == SamplerType.Texture3D)
  1435. {
  1436. result = ScalingHelpers.ApplyUnscaling(context, texOp.WithType(type), result, isBindless, isIndexed);
  1437. }
  1438. return new OperationResult(AggregateType.S32, result);
  1439. }
  1440. }
  1441. private static OperationResult GenerateTruncate(CodeGenContext context, AstOperation operation)
  1442. {
  1443. return GenerateUnary(context, operation, context.Delegates.GlslTrunc, null);
  1444. }
  1445. private static OperationResult GenerateUnpackDouble2x32(CodeGenContext context, AstOperation operation)
  1446. {
  1447. var value = context.GetFP64(operation.GetSource(0));
  1448. var vector = context.GlslUnpackDouble2x32(context.TypeVector(context.TypeU32(), 2), value);
  1449. var result = context.CompositeExtract(context.TypeU32(), vector, operation.Index);
  1450. return new OperationResult(AggregateType.U32, result);
  1451. }
  1452. private static OperationResult GenerateUnpackHalf2x16(CodeGenContext context, AstOperation operation)
  1453. {
  1454. var value = context.GetU32(operation.GetSource(0));
  1455. var vector = context.GlslUnpackHalf2x16(context.TypeVector(context.TypeFP32(), 2), value);
  1456. var result = context.CompositeExtract(context.TypeFP32(), vector, operation.Index);
  1457. return new OperationResult(AggregateType.FP32, result);
  1458. }
  1459. private static OperationResult GenerateVectorExtract(CodeGenContext context, AstOperation operation)
  1460. {
  1461. var vector = context.GetWithType(operation.GetSource(0), out AggregateType vectorType);
  1462. var scalarType = vectorType & ~AggregateType.ElementCountMask;
  1463. var resultType = context.GetType(scalarType);
  1464. SpvInstruction result;
  1465. if (operation.GetSource(1) is AstOperand indexOperand && indexOperand.Type == OperandType.Constant)
  1466. {
  1467. result = context.CompositeExtract(resultType, vector, (SpvLiteralInteger)indexOperand.Value);
  1468. }
  1469. else
  1470. {
  1471. var index = context.Get(AggregateType.S32, operation.GetSource(1));
  1472. result = context.VectorExtractDynamic(resultType, vector, index);
  1473. }
  1474. return new OperationResult(scalarType, result);
  1475. }
  1476. private static OperationResult GenerateVoteAll(CodeGenContext context, AstOperation operation)
  1477. {
  1478. var execution = context.Constant(context.TypeU32(), Scope.Subgroup);
  1479. var result = context.GroupNonUniformAll(context.TypeBool(), execution, context.Get(AggregateType.Bool, operation.GetSource(0)));
  1480. return new OperationResult(AggregateType.Bool, result);
  1481. }
  1482. private static OperationResult GenerateVoteAllEqual(CodeGenContext context, AstOperation operation)
  1483. {
  1484. var execution = context.Constant(context.TypeU32(), Scope.Subgroup);
  1485. var result = context.GroupNonUniformAllEqual(context.TypeBool(), execution, context.Get(AggregateType.Bool, operation.GetSource(0)));
  1486. return new OperationResult(AggregateType.Bool, result);
  1487. }
  1488. private static OperationResult GenerateVoteAny(CodeGenContext context, AstOperation operation)
  1489. {
  1490. var execution = context.Constant(context.TypeU32(), Scope.Subgroup);
  1491. var result = context.GroupNonUniformAny(context.TypeBool(), execution, context.Get(AggregateType.Bool, operation.GetSource(0)));
  1492. return new OperationResult(AggregateType.Bool, result);
  1493. }
  1494. private static OperationResult GenerateCompare(
  1495. CodeGenContext context,
  1496. AstOperation operation,
  1497. Func<SpvInstruction, SpvInstruction, SpvInstruction, SpvInstruction> emitF,
  1498. Func<SpvInstruction, SpvInstruction, SpvInstruction, SpvInstruction> emitI)
  1499. {
  1500. var src1 = operation.GetSource(0);
  1501. var src2 = operation.GetSource(1);
  1502. SpvInstruction result;
  1503. if (operation.Inst.HasFlag(Instruction.FP64))
  1504. {
  1505. result = emitF(context.TypeBool(), context.GetFP64(src1), context.GetFP64(src2));
  1506. }
  1507. else if (operation.Inst.HasFlag(Instruction.FP32))
  1508. {
  1509. result = emitF(context.TypeBool(), context.GetFP32(src1), context.GetFP32(src2));
  1510. }
  1511. else
  1512. {
  1513. result = emitI(context.TypeBool(), context.GetS32(src1), context.GetS32(src2));
  1514. }
  1515. return new OperationResult(AggregateType.Bool, result);
  1516. }
  1517. private static OperationResult GenerateCompareU32(
  1518. CodeGenContext context,
  1519. AstOperation operation,
  1520. Func<SpvInstruction, SpvInstruction, SpvInstruction, SpvInstruction> emitU)
  1521. {
  1522. var src1 = operation.GetSource(0);
  1523. var src2 = operation.GetSource(1);
  1524. var result = emitU(context.TypeBool(), context.GetU32(src1), context.GetU32(src2));
  1525. return new OperationResult(AggregateType.Bool, result);
  1526. }
  1527. private static OperationResult GenerateAtomicMemoryBinary(
  1528. CodeGenContext context,
  1529. AstOperation operation,
  1530. Func<SpvInstruction, SpvInstruction, SpvInstruction, SpvInstruction, SpvInstruction, SpvInstruction> emitU)
  1531. {
  1532. var value = context.GetU32(operation.GetSource(2));
  1533. SpvInstruction elemPointer;
  1534. if (operation.StorageKind == StorageKind.StorageBuffer)
  1535. {
  1536. elemPointer = GetStorageElemPointer(context, operation);
  1537. }
  1538. else if (operation.StorageKind == StorageKind.SharedMemory)
  1539. {
  1540. var offset = context.GetU32(operation.GetSource(0));
  1541. elemPointer = context.AccessChain(context.TypePointer(StorageClass.Workgroup, context.TypeU32()), context.SharedMemory, offset);
  1542. }
  1543. else
  1544. {
  1545. throw new InvalidOperationException($"Invalid storage kind \"{operation.StorageKind}\".");
  1546. }
  1547. var one = context.Constant(context.TypeU32(), 1);
  1548. var zero = context.Constant(context.TypeU32(), 0);
  1549. return new OperationResult(AggregateType.U32, emitU(context.TypeU32(), elemPointer, one, zero, value));
  1550. }
  1551. private static OperationResult GenerateAtomicMemoryCas(CodeGenContext context, AstOperation operation)
  1552. {
  1553. var value0 = context.GetU32(operation.GetSource(2));
  1554. var value1 = context.GetU32(operation.GetSource(3));
  1555. SpvInstruction elemPointer;
  1556. if (operation.StorageKind == StorageKind.StorageBuffer)
  1557. {
  1558. elemPointer = GetStorageElemPointer(context, operation);
  1559. }
  1560. else if (operation.StorageKind == StorageKind.SharedMemory)
  1561. {
  1562. var offset = context.GetU32(operation.GetSource(0));
  1563. elemPointer = context.AccessChain(context.TypePointer(StorageClass.Workgroup, context.TypeU32()), context.SharedMemory, offset);
  1564. }
  1565. else
  1566. {
  1567. throw new InvalidOperationException($"Invalid storage kind \"{operation.StorageKind}\".");
  1568. }
  1569. var one = context.Constant(context.TypeU32(), 1);
  1570. var zero = context.Constant(context.TypeU32(), 0);
  1571. return new OperationResult(AggregateType.U32, context.AtomicCompareExchange(context.TypeU32(), elemPointer, one, zero, zero, value1, value0));
  1572. }
  1573. private static OperationResult GenerateLoadOrStore(CodeGenContext context, AstOperation operation, bool isStore)
  1574. {
  1575. StorageKind storageKind = operation.StorageKind;
  1576. SpvInstruction pointer;
  1577. AggregateType varType;
  1578. int srcIndex = 0;
  1579. switch (storageKind)
  1580. {
  1581. case StorageKind.Input:
  1582. case StorageKind.InputPerPatch:
  1583. case StorageKind.Output:
  1584. case StorageKind.OutputPerPatch:
  1585. if (!(operation.GetSource(srcIndex++) is AstOperand varId) || varId.Type != OperandType.Constant)
  1586. {
  1587. throw new InvalidOperationException($"First input of {operation.Inst} with {storageKind} storage must be a constant operand.");
  1588. }
  1589. IoVariable ioVariable = (IoVariable)varId.Value;
  1590. bool isOutput = storageKind.IsOutput();
  1591. bool isPerPatch = storageKind.IsPerPatch();
  1592. int location = 0;
  1593. int component = 0;
  1594. if (context.Config.HasPerLocationInputOrOutput(ioVariable, isOutput))
  1595. {
  1596. if (!(operation.GetSource(srcIndex++) is AstOperand vecIndex) || vecIndex.Type != OperandType.Constant)
  1597. {
  1598. throw new InvalidOperationException($"Second input of {operation.Inst} with {storageKind} storage must be a constant operand.");
  1599. }
  1600. location = vecIndex.Value;
  1601. if (operation.SourcesCount > srcIndex &&
  1602. operation.GetSource(srcIndex) is AstOperand elemIndex &&
  1603. elemIndex.Type == OperandType.Constant &&
  1604. context.Config.HasPerLocationInputOrOutputComponent(ioVariable, location, elemIndex.Value, isOutput))
  1605. {
  1606. component = elemIndex.Value;
  1607. srcIndex++;
  1608. }
  1609. }
  1610. if (ioVariable == IoVariable.UserDefined)
  1611. {
  1612. varType = context.Config.GetUserDefinedType(location, isOutput);
  1613. }
  1614. else if (ioVariable == IoVariable.FragmentOutputColor)
  1615. {
  1616. varType = context.Config.GetFragmentOutputColorType(location);
  1617. }
  1618. else if (ioVariable == IoVariable.FragmentOutputIsBgra)
  1619. {
  1620. var pointerType = context.TypePointer(StorageClass.Uniform, context.TypeU32());
  1621. var elemIndex = context.Get(AggregateType.S32, operation.GetSource(srcIndex++));
  1622. pointer = context.AccessChain(pointerType, context.SupportBuffer, context.Constant(context.TypeU32(), 1), elemIndex);
  1623. varType = AggregateType.U32;
  1624. break;
  1625. }
  1626. else if (ioVariable == IoVariable.SupportBlockRenderScale)
  1627. {
  1628. var pointerType = context.TypePointer(StorageClass.Uniform, context.TypeFP32());
  1629. var elemIndex = context.Get(AggregateType.S32, operation.GetSource(srcIndex++));
  1630. pointer = context.AccessChain(pointerType, context.SupportBuffer, context.Constant(context.TypeU32(), 4), elemIndex);
  1631. varType = AggregateType.FP32;
  1632. break;
  1633. }
  1634. else if (ioVariable == IoVariable.SupportBlockViewInverse)
  1635. {
  1636. var pointerType = context.TypePointer(StorageClass.Uniform, context.TypeFP32());
  1637. var elemIndex = context.Get(AggregateType.S32, operation.GetSource(srcIndex++));
  1638. pointer = context.AccessChain(pointerType, context.SupportBuffer, context.Constant(context.TypeU32(), 2), elemIndex);
  1639. varType = AggregateType.FP32;
  1640. break;
  1641. }
  1642. else
  1643. {
  1644. (_, varType) = IoMap.GetSpirvBuiltIn(ioVariable);
  1645. }
  1646. varType &= AggregateType.ElementTypeMask;
  1647. int inputsCount = (isStore ? operation.SourcesCount - 1 : operation.SourcesCount) - srcIndex;
  1648. var storageClass = isOutput ? StorageClass.Output : StorageClass.Input;
  1649. var ioDefinition = new IoDefinition(storageKind, ioVariable, location, component);
  1650. var dict = isPerPatch
  1651. ? (isOutput ? context.OutputsPerPatch : context.InputsPerPatch)
  1652. : (isOutput ? context.Outputs : context.Inputs);
  1653. SpvInstruction baseObj = dict[ioDefinition];
  1654. SpvInstruction e0, e1, e2;
  1655. switch (inputsCount)
  1656. {
  1657. case 0:
  1658. pointer = baseObj;
  1659. break;
  1660. case 1:
  1661. e0 = context.Get(AggregateType.S32, operation.GetSource(srcIndex++));
  1662. pointer = context.AccessChain(context.TypePointer(storageClass, context.GetType(varType)), baseObj, e0);
  1663. break;
  1664. case 2:
  1665. e0 = context.Get(AggregateType.S32, operation.GetSource(srcIndex++));
  1666. e1 = context.Get(AggregateType.S32, operation.GetSource(srcIndex++));
  1667. pointer = context.AccessChain(context.TypePointer(storageClass, context.GetType(varType)), baseObj, e0, e1);
  1668. break;
  1669. case 3:
  1670. e0 = context.Get(AggregateType.S32, operation.GetSource(srcIndex++));
  1671. e1 = context.Get(AggregateType.S32, operation.GetSource(srcIndex++));
  1672. e2 = context.Get(AggregateType.S32, operation.GetSource(srcIndex++));
  1673. pointer = context.AccessChain(context.TypePointer(storageClass, context.GetType(varType)), baseObj, e0, e1, e2);
  1674. break;
  1675. default:
  1676. var indexes = new SpvInstruction[inputsCount];
  1677. int index = 0;
  1678. for (; index < inputsCount; srcIndex++, index++)
  1679. {
  1680. indexes[index] = context.Get(AggregateType.S32, operation.GetSource(srcIndex));
  1681. }
  1682. pointer = context.AccessChain(context.TypePointer(storageClass, context.GetType(varType)), baseObj, indexes);
  1683. break;
  1684. }
  1685. break;
  1686. default:
  1687. throw new InvalidOperationException($"Invalid storage kind {storageKind}.");
  1688. }
  1689. if (isStore)
  1690. {
  1691. context.Store(pointer, context.Get(varType, operation.GetSource(srcIndex)));
  1692. return OperationResult.Invalid;
  1693. }
  1694. else
  1695. {
  1696. var result = context.Load(context.GetType(varType), pointer);
  1697. return new OperationResult(varType, result);
  1698. }
  1699. }
  1700. private static SpvInstruction GetScalarInput(CodeGenContext context, IoVariable ioVariable)
  1701. {
  1702. (_, var varType) = IoMap.GetSpirvBuiltIn(ioVariable);
  1703. varType &= AggregateType.ElementTypeMask;
  1704. var ioDefinition = new IoDefinition(StorageKind.Input, ioVariable);
  1705. return context.Load(context.GetType(varType), context.Inputs[ioDefinition]);
  1706. }
  1707. private static void GenerateStoreSharedSmallInt(CodeGenContext context, AstOperation operation, int bitSize)
  1708. {
  1709. var offset = context.Get(AggregateType.U32, operation.GetSource(0));
  1710. var value = context.Get(AggregateType.U32, operation.GetSource(1));
  1711. var wordOffset = context.ShiftRightLogical(context.TypeU32(), offset, context.Constant(context.TypeU32(), 2));
  1712. var bitOffset = context.BitwiseAnd(context.TypeU32(), offset, context.Constant(context.TypeU32(), 3));
  1713. bitOffset = context.ShiftLeftLogical(context.TypeU32(), bitOffset, context.Constant(context.TypeU32(), 3));
  1714. var memory = context.SharedMemory;
  1715. var elemPointer = context.AccessChain(context.TypePointer(StorageClass.Workgroup, context.TypeU32()), memory, wordOffset);
  1716. GenerateStoreSmallInt(context, elemPointer, bitOffset, value, bitSize);
  1717. }
  1718. private static void GenerateStoreStorageSmallInt(CodeGenContext context, AstOperation operation, int bitSize)
  1719. {
  1720. var i0 = context.Get(AggregateType.S32, operation.GetSource(0));
  1721. var offset = context.Get(AggregateType.U32, operation.GetSource(1));
  1722. var value = context.Get(AggregateType.U32, operation.GetSource(2));
  1723. var wordOffset = context.ShiftRightLogical(context.TypeU32(), offset, context.Constant(context.TypeU32(), 2));
  1724. var bitOffset = context.BitwiseAnd(context.TypeU32(), offset, context.Constant(context.TypeU32(), 3));
  1725. bitOffset = context.ShiftLeftLogical(context.TypeU32(), bitOffset, context.Constant(context.TypeU32(), 3));
  1726. var sbVariable = context.StorageBuffersArray;
  1727. var i1 = context.Constant(context.TypeS32(), 0);
  1728. var elemPointer = context.AccessChain(context.TypePointer(StorageClass.Uniform, context.TypeU32()), sbVariable, i0, i1, wordOffset);
  1729. GenerateStoreSmallInt(context, elemPointer, bitOffset, value, bitSize);
  1730. }
  1731. private static void GenerateStoreSmallInt(
  1732. CodeGenContext context,
  1733. SpvInstruction elemPointer,
  1734. SpvInstruction bitOffset,
  1735. SpvInstruction value,
  1736. int bitSize)
  1737. {
  1738. var loopStart = context.Label();
  1739. var loopEnd = context.Label();
  1740. context.Branch(loopStart);
  1741. context.AddLabel(loopStart);
  1742. var oldValue = context.Load(context.TypeU32(), elemPointer);
  1743. var newValue = context.BitFieldInsert(context.TypeU32(), oldValue, value, bitOffset, context.Constant(context.TypeU32(), bitSize));
  1744. var one = context.Constant(context.TypeU32(), 1);
  1745. var zero = context.Constant(context.TypeU32(), 0);
  1746. var result = context.AtomicCompareExchange(context.TypeU32(), elemPointer, one, zero, zero, newValue, oldValue);
  1747. var failed = context.INotEqual(context.TypeBool(), result, oldValue);
  1748. context.LoopMerge(loopEnd, loopStart, LoopControlMask.MaskNone);
  1749. context.BranchConditional(failed, loopStart, loopEnd);
  1750. context.AddLabel(loopEnd);
  1751. }
  1752. private static OperationResult GetZeroOperationResult(
  1753. CodeGenContext context,
  1754. AstTextureOperation texOp,
  1755. AggregateType scalarType,
  1756. bool isVector)
  1757. {
  1758. var zero = scalarType switch
  1759. {
  1760. AggregateType.S32 => context.Constant(context.TypeS32(), 0),
  1761. AggregateType.U32 => context.Constant(context.TypeU32(), 0u),
  1762. _ => context.Constant(context.TypeFP32(), 0f),
  1763. };
  1764. if (isVector)
  1765. {
  1766. AggregateType outputType = texOp.GetVectorType(scalarType);
  1767. if ((outputType & AggregateType.ElementCountMask) != 0)
  1768. {
  1769. int componentsCount = BitOperations.PopCount((uint)texOp.Index);
  1770. SpvInstruction[] values = new SpvInstruction[componentsCount];
  1771. values.AsSpan().Fill(zero);
  1772. return new OperationResult(outputType, context.ConstantComposite(context.GetType(outputType), values));
  1773. }
  1774. }
  1775. return new OperationResult(scalarType, zero);
  1776. }
  1777. private static SpvInstruction GetSwizzledResult(CodeGenContext context, SpvInstruction vector, AggregateType swizzledResultType, int mask)
  1778. {
  1779. if ((swizzledResultType & AggregateType.ElementCountMask) != 0)
  1780. {
  1781. SpvLiteralInteger[] components = new SpvLiteralInteger[BitOperations.PopCount((uint)mask)];
  1782. int componentIndex = 0;
  1783. for (int i = 0; i < 4; i++)
  1784. {
  1785. if ((mask & (1 << i)) != 0)
  1786. {
  1787. components[componentIndex++] = i;
  1788. }
  1789. }
  1790. return context.VectorShuffle(context.GetType(swizzledResultType), vector, vector, components);
  1791. }
  1792. else
  1793. {
  1794. int componentIndex = (int)BitOperations.TrailingZeroCount(mask);
  1795. return context.CompositeExtract(context.GetType(swizzledResultType), vector, (SpvLiteralInteger)componentIndex);
  1796. }
  1797. }
  1798. private static SpvInstruction GetStorageElemPointer(CodeGenContext context, AstOperation operation)
  1799. {
  1800. var sbVariable = context.StorageBuffersArray;
  1801. var i0 = context.Get(AggregateType.S32, operation.GetSource(0));
  1802. var i1 = context.Constant(context.TypeS32(), 0);
  1803. var i2 = context.Get(AggregateType.S32, operation.GetSource(1));
  1804. return context.AccessChain(context.TypePointer(StorageClass.Uniform, context.TypeU32()), sbVariable, i0, i1, i2);
  1805. }
  1806. private static OperationResult GenerateUnary(
  1807. CodeGenContext context,
  1808. AstOperation operation,
  1809. Func<SpvInstruction, SpvInstruction, SpvInstruction> emitF,
  1810. Func<SpvInstruction, SpvInstruction, SpvInstruction> emitI)
  1811. {
  1812. var source = operation.GetSource(0);
  1813. if (operation.Inst.HasFlag(Instruction.FP64))
  1814. {
  1815. return new OperationResult(AggregateType.FP64, emitF(context.TypeFP64(), context.GetFP64(source)));
  1816. }
  1817. else if (operation.Inst.HasFlag(Instruction.FP32))
  1818. {
  1819. return new OperationResult(AggregateType.FP32, emitF(context.TypeFP32(), context.GetFP32(source)));
  1820. }
  1821. else
  1822. {
  1823. return new OperationResult(AggregateType.S32, emitI(context.TypeS32(), context.GetS32(source)));
  1824. }
  1825. }
  1826. private static OperationResult GenerateUnaryBool(
  1827. CodeGenContext context,
  1828. AstOperation operation,
  1829. Func<SpvInstruction, SpvInstruction, SpvInstruction> emitB)
  1830. {
  1831. var source = operation.GetSource(0);
  1832. return new OperationResult(AggregateType.Bool, emitB(context.TypeBool(), context.Get(AggregateType.Bool, source)));
  1833. }
  1834. private static OperationResult GenerateUnaryFP32(
  1835. CodeGenContext context,
  1836. AstOperation operation,
  1837. Func<SpvInstruction, SpvInstruction, SpvInstruction> emit)
  1838. {
  1839. var source = operation.GetSource(0);
  1840. return new OperationResult(AggregateType.FP32, emit(context.TypeFP32(), context.GetFP32(source)));
  1841. }
  1842. private static OperationResult GenerateUnaryS32(
  1843. CodeGenContext context,
  1844. AstOperation operation,
  1845. Func<SpvInstruction, SpvInstruction, SpvInstruction> emitS)
  1846. {
  1847. var source = operation.GetSource(0);
  1848. return new OperationResult(AggregateType.S32, emitS(context.TypeS32(), context.GetS32(source)));
  1849. }
  1850. private static OperationResult GenerateBinary(
  1851. CodeGenContext context,
  1852. AstOperation operation,
  1853. Func<SpvInstruction, SpvInstruction, SpvInstruction, SpvInstruction> emitF,
  1854. Func<SpvInstruction, SpvInstruction, SpvInstruction, SpvInstruction> emitI)
  1855. {
  1856. var src1 = operation.GetSource(0);
  1857. var src2 = operation.GetSource(1);
  1858. if (operation.Inst.HasFlag(Instruction.FP64))
  1859. {
  1860. var result = emitF(context.TypeFP64(), context.GetFP64(src1), context.GetFP64(src2));
  1861. if (!context.Config.GpuAccessor.QueryHostReducedPrecision())
  1862. {
  1863. context.Decorate(result, Decoration.NoContraction);
  1864. }
  1865. return new OperationResult(AggregateType.FP64, result);
  1866. }
  1867. else if (operation.Inst.HasFlag(Instruction.FP32))
  1868. {
  1869. var result = emitF(context.TypeFP32(), context.GetFP32(src1), context.GetFP32(src2));
  1870. if (!context.Config.GpuAccessor.QueryHostReducedPrecision())
  1871. {
  1872. context.Decorate(result, Decoration.NoContraction);
  1873. }
  1874. return new OperationResult(AggregateType.FP32, result);
  1875. }
  1876. else
  1877. {
  1878. return new OperationResult(AggregateType.S32, emitI(context.TypeS32(), context.GetS32(src1), context.GetS32(src2)));
  1879. }
  1880. }
  1881. private static OperationResult GenerateBinaryBool(
  1882. CodeGenContext context,
  1883. AstOperation operation,
  1884. Func<SpvInstruction, SpvInstruction, SpvInstruction, SpvInstruction> emitB)
  1885. {
  1886. var src1 = operation.GetSource(0);
  1887. var src2 = operation.GetSource(1);
  1888. return new OperationResult(AggregateType.Bool, emitB(context.TypeBool(), context.Get(AggregateType.Bool, src1), context.Get(AggregateType.Bool, src2)));
  1889. }
  1890. private static OperationResult GenerateBinaryS32(
  1891. CodeGenContext context,
  1892. AstOperation operation,
  1893. Func<SpvInstruction, SpvInstruction, SpvInstruction, SpvInstruction> emitS)
  1894. {
  1895. var src1 = operation.GetSource(0);
  1896. var src2 = operation.GetSource(1);
  1897. return new OperationResult(AggregateType.S32, emitS(context.TypeS32(), context.GetS32(src1), context.GetS32(src2)));
  1898. }
  1899. private static OperationResult GenerateBinaryU32(
  1900. CodeGenContext context,
  1901. AstOperation operation,
  1902. Func<SpvInstruction, SpvInstruction, SpvInstruction, SpvInstruction> emitU)
  1903. {
  1904. var src1 = operation.GetSource(0);
  1905. var src2 = operation.GetSource(1);
  1906. return new OperationResult(AggregateType.U32, emitU(context.TypeU32(), context.GetU32(src1), context.GetU32(src2)));
  1907. }
  1908. private static OperationResult GenerateTernary(
  1909. CodeGenContext context,
  1910. AstOperation operation,
  1911. Func<SpvInstruction, SpvInstruction, SpvInstruction, SpvInstruction, SpvInstruction> emitF,
  1912. Func<SpvInstruction, SpvInstruction, SpvInstruction, SpvInstruction, SpvInstruction> emitI)
  1913. {
  1914. var src1 = operation.GetSource(0);
  1915. var src2 = operation.GetSource(1);
  1916. var src3 = operation.GetSource(2);
  1917. if (operation.Inst.HasFlag(Instruction.FP64))
  1918. {
  1919. var result = emitF(context.TypeFP64(), context.GetFP64(src1), context.GetFP64(src2), context.GetFP64(src3));
  1920. if (!context.Config.GpuAccessor.QueryHostReducedPrecision())
  1921. {
  1922. context.Decorate(result, Decoration.NoContraction);
  1923. }
  1924. return new OperationResult(AggregateType.FP64, result);
  1925. }
  1926. else if (operation.Inst.HasFlag(Instruction.FP32))
  1927. {
  1928. var result = emitF(context.TypeFP32(), context.GetFP32(src1), context.GetFP32(src2), context.GetFP32(src3));
  1929. if (!context.Config.GpuAccessor.QueryHostReducedPrecision())
  1930. {
  1931. context.Decorate(result, Decoration.NoContraction);
  1932. }
  1933. return new OperationResult(AggregateType.FP32, result);
  1934. }
  1935. else
  1936. {
  1937. return new OperationResult(AggregateType.S32, emitI(context.TypeS32(), context.GetS32(src1), context.GetS32(src2), context.GetS32(src3)));
  1938. }
  1939. }
  1940. private static OperationResult GenerateTernaryU32(
  1941. CodeGenContext context,
  1942. AstOperation operation,
  1943. Func<SpvInstruction, SpvInstruction, SpvInstruction, SpvInstruction, SpvInstruction> emitU)
  1944. {
  1945. var src1 = operation.GetSource(0);
  1946. var src2 = operation.GetSource(1);
  1947. var src3 = operation.GetSource(2);
  1948. return new OperationResult(AggregateType.U32, emitU(
  1949. context.TypeU32(),
  1950. context.GetU32(src1),
  1951. context.GetU32(src2),
  1952. context.GetU32(src3)));
  1953. }
  1954. private static OperationResult GenerateBitfieldExtractS32(
  1955. CodeGenContext context,
  1956. AstOperation operation,
  1957. Func<SpvInstruction, SpvInstruction, SpvInstruction, SpvInstruction, SpvInstruction> emitS)
  1958. {
  1959. var src1 = operation.GetSource(0);
  1960. var src2 = operation.GetSource(1);
  1961. var src3 = operation.GetSource(2);
  1962. return new OperationResult(AggregateType.S32, emitS(
  1963. context.TypeS32(),
  1964. context.GetS32(src1),
  1965. context.GetU32(src2),
  1966. context.GetU32(src3)));
  1967. }
  1968. private static OperationResult GenerateBitfieldInsert(
  1969. CodeGenContext context,
  1970. AstOperation operation,
  1971. Func<SpvInstruction, SpvInstruction, SpvInstruction, SpvInstruction, SpvInstruction, SpvInstruction> emitS)
  1972. {
  1973. var src1 = operation.GetSource(0);
  1974. var src2 = operation.GetSource(1);
  1975. var src3 = operation.GetSource(2);
  1976. var src4 = operation.GetSource(3);
  1977. return new OperationResult(AggregateType.U32, emitS(
  1978. context.TypeU32(),
  1979. context.GetU32(src1),
  1980. context.GetU32(src2),
  1981. context.GetU32(src3),
  1982. context.GetU32(src4)));
  1983. }
  1984. }
  1985. }