Rewriter.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  1. using Ryujinx.Graphics.Shader.IntermediateRepresentation;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.Linq;
  5. using static Ryujinx.Graphics.Shader.IntermediateRepresentation.OperandHelper;
  6. using static Ryujinx.Graphics.Shader.Translation.GlobalMemory;
  7. namespace Ryujinx.Graphics.Shader.Translation
  8. {
  9. static class Rewriter
  10. {
  11. public static void RunPass(BasicBlock[] blocks, ShaderConfig config)
  12. {
  13. for (int blkIndex = 0; blkIndex < blocks.Length; blkIndex++)
  14. {
  15. BasicBlock block = blocks[blkIndex];
  16. for (LinkedListNode<INode> node = block.Operations.First; node != null; node = node.Next)
  17. {
  18. if (!(node.Value is Operation operation))
  19. {
  20. continue;
  21. }
  22. if (UsesGlobalMemory(operation.Inst))
  23. {
  24. node = RewriteGlobalAccess(node, config);
  25. }
  26. if (operation is TextureOperation texOp)
  27. {
  28. if (texOp.Inst == Instruction.TextureSample)
  29. {
  30. node = RewriteTextureSample(node, config);
  31. }
  32. if (texOp.Type == SamplerType.TextureBuffer)
  33. {
  34. node = InsertSnormNormalization(node, config);
  35. }
  36. }
  37. }
  38. }
  39. }
  40. private static LinkedListNode<INode> RewriteGlobalAccess(LinkedListNode<INode> node, ShaderConfig config)
  41. {
  42. Operation operation = (Operation)node.Value;
  43. bool isAtomic = operation.Inst.IsAtomic();
  44. bool isWrite = isAtomic || operation.Inst == Instruction.StoreGlobal;
  45. Operation storageOp;
  46. Operand PrependOperation(Instruction inst, params Operand[] sources)
  47. {
  48. Operand local = Local();
  49. node.List.AddBefore(node, new Operation(inst, local, sources));
  50. return local;
  51. }
  52. Operand addrLow = operation.GetSource(0);
  53. Operand addrHigh = operation.GetSource(1);
  54. Operand sbBaseAddrLow = Const(0);
  55. Operand sbSlot = Const(0);
  56. for (int slot = 0; slot < StorageMaxCount; slot++)
  57. {
  58. config.SetUsedStorageBuffer(slot, isWrite);
  59. int cbOffset = GetStorageCbOffset(config.Stage, slot);
  60. Operand baseAddrLow = config.CreateCbuf(0, cbOffset);
  61. Operand baseAddrHigh = config.CreateCbuf(0, cbOffset + 1);
  62. Operand size = config.CreateCbuf(0, cbOffset + 2);
  63. Operand offset = PrependOperation(Instruction.Subtract, addrLow, baseAddrLow);
  64. Operand borrow = PrependOperation(Instruction.CompareLessU32, addrLow, baseAddrLow);
  65. Operand inRangeLow = PrependOperation(Instruction.CompareLessU32, offset, size);
  66. Operand addrHighBorrowed = PrependOperation(Instruction.Add, addrHigh, borrow);
  67. Operand inRangeHigh = PrependOperation(Instruction.CompareEqual, addrHighBorrowed, baseAddrHigh);
  68. Operand inRange = PrependOperation(Instruction.BitwiseAnd, inRangeLow, inRangeHigh);
  69. sbBaseAddrLow = PrependOperation(Instruction.ConditionalSelect, inRange, baseAddrLow, sbBaseAddrLow);
  70. sbSlot = PrependOperation(Instruction.ConditionalSelect, inRange, Const(slot), sbSlot);
  71. }
  72. Operand alignMask = Const(-config.GpuAccessor.QueryStorageBufferOffsetAlignment());
  73. Operand baseAddrTrunc = PrependOperation(Instruction.BitwiseAnd, sbBaseAddrLow, alignMask);
  74. Operand byteOffset = PrependOperation(Instruction.Subtract, addrLow, baseAddrTrunc);
  75. Operand wordOffset = PrependOperation(Instruction.ShiftRightU32, byteOffset, Const(2));
  76. Operand[] sources = new Operand[operation.SourcesCount];
  77. sources[0] = sbSlot;
  78. sources[1] = wordOffset;
  79. for (int index = 2; index < operation.SourcesCount; index++)
  80. {
  81. sources[index] = operation.GetSource(index);
  82. }
  83. if (isAtomic)
  84. {
  85. Instruction inst = (operation.Inst & ~Instruction.MrMask) | Instruction.MrStorage;
  86. storageOp = new Operation(inst, operation.Dest, sources);
  87. }
  88. else if (operation.Inst == Instruction.LoadGlobal)
  89. {
  90. storageOp = new Operation(Instruction.LoadStorage, operation.Dest, sources);
  91. }
  92. else
  93. {
  94. storageOp = new Operation(Instruction.StoreStorage, null, sources);
  95. }
  96. for (int index = 0; index < operation.SourcesCount; index++)
  97. {
  98. operation.SetSource(index, null);
  99. }
  100. LinkedListNode<INode> oldNode = node;
  101. node = node.List.AddBefore(node, storageOp);
  102. node.List.Remove(oldNode);
  103. return node;
  104. }
  105. private static LinkedListNode<INode> RewriteTextureSample(LinkedListNode<INode> node, ShaderConfig config)
  106. {
  107. TextureOperation texOp = (TextureOperation)node.Value;
  108. bool hasOffset = (texOp.Flags & TextureFlags.Offset) != 0;
  109. bool hasOffsets = (texOp.Flags & TextureFlags.Offsets) != 0;
  110. bool hasInvalidOffset = (hasOffset || hasOffsets) && !config.GpuAccessor.QuerySupportsNonConstantTextureOffset();
  111. bool isRect = config.GpuAccessor.QueryIsTextureRectangle(texOp.Handle, texOp.CbufSlot);
  112. if (!(hasInvalidOffset || isRect))
  113. {
  114. return node;
  115. }
  116. bool isBindless = (texOp.Flags & TextureFlags.Bindless) != 0;
  117. bool isGather = (texOp.Flags & TextureFlags.Gather) != 0;
  118. bool hasDerivatives = (texOp.Flags & TextureFlags.Derivatives) != 0;
  119. bool intCoords = (texOp.Flags & TextureFlags.IntCoords) != 0;
  120. bool hasLodBias = (texOp.Flags & TextureFlags.LodBias) != 0;
  121. bool hasLodLevel = (texOp.Flags & TextureFlags.LodLevel) != 0;
  122. bool isArray = (texOp.Type & SamplerType.Array) != 0;
  123. bool isIndexed = (texOp.Type & SamplerType.Indexed) != 0;
  124. bool isMultisample = (texOp.Type & SamplerType.Multisample) != 0;
  125. bool isShadow = (texOp.Type & SamplerType.Shadow) != 0;
  126. int coordsCount = texOp.Type.GetDimensions();
  127. int offsetsCount;
  128. if (hasOffsets)
  129. {
  130. offsetsCount = coordsCount * 4;
  131. }
  132. else if (hasOffset)
  133. {
  134. offsetsCount = coordsCount;
  135. }
  136. else
  137. {
  138. offsetsCount = 0;
  139. }
  140. Operand[] offsets = new Operand[offsetsCount];
  141. Operand[] sources = new Operand[texOp.SourcesCount - offsetsCount];
  142. int copyCount = 0;
  143. if (isBindless || isIndexed)
  144. {
  145. copyCount++;
  146. }
  147. Operand[] lodSources = new Operand[copyCount + coordsCount];
  148. for (int index = 0; index < lodSources.Length; index++)
  149. {
  150. lodSources[index] = texOp.GetSource(index);
  151. }
  152. copyCount += coordsCount;
  153. if (isArray)
  154. {
  155. copyCount++;
  156. }
  157. if (isShadow)
  158. {
  159. copyCount++;
  160. }
  161. if (hasDerivatives)
  162. {
  163. copyCount += coordsCount * 2;
  164. }
  165. if (isMultisample)
  166. {
  167. copyCount++;
  168. }
  169. else if (hasLodLevel)
  170. {
  171. copyCount++;
  172. }
  173. int srcIndex = 0;
  174. int dstIndex = 0;
  175. for (int index = 0; index < copyCount; index++)
  176. {
  177. sources[dstIndex++] = texOp.GetSource(srcIndex++);
  178. }
  179. bool areAllOffsetsConstant = true;
  180. for (int index = 0; index < offsetsCount; index++)
  181. {
  182. Operand offset = texOp.GetSource(srcIndex++);
  183. areAllOffsetsConstant &= offset.Type == OperandType.Constant;
  184. offsets[index] = offset;
  185. }
  186. hasInvalidOffset &= !areAllOffsetsConstant;
  187. if (!(hasInvalidOffset || isRect))
  188. {
  189. return node;
  190. }
  191. if (hasLodBias)
  192. {
  193. sources[dstIndex++] = texOp.GetSource(srcIndex++);
  194. }
  195. if (isGather && !isShadow)
  196. {
  197. sources[dstIndex++] = texOp.GetSource(srcIndex++);
  198. }
  199. int coordsIndex = isBindless || isIndexed ? 1 : 0;
  200. int componentIndex = texOp.Index;
  201. Operand Int(Operand value)
  202. {
  203. Operand res = Local();
  204. node.List.AddBefore(node, new Operation(Instruction.ConvertFPToS32, res, value));
  205. return res;
  206. }
  207. Operand Float(Operand value)
  208. {
  209. Operand res = Local();
  210. node.List.AddBefore(node, new Operation(Instruction.ConvertS32ToFP, res, value));
  211. return res;
  212. }
  213. // Emulate texture rectangle by normalizing the coordinates on the shader.
  214. // When sampler*Rect is used, the coords are expected to the in the [0, W or H] range,
  215. // and otherwise, it is expected to be in the [0, 1] range.
  216. // We normalize by dividing the coords by the texture size.
  217. if (isRect && !intCoords)
  218. {
  219. for (int index = 0; index < coordsCount; index++)
  220. {
  221. Operand coordSize = Local();
  222. Operand[] texSizeSources;
  223. if (isBindless || isIndexed)
  224. {
  225. texSizeSources = new Operand[] { sources[0], Const(0) };
  226. }
  227. else
  228. {
  229. texSizeSources = new Operand[] { Const(0) };
  230. }
  231. node.List.AddBefore(node, new TextureOperation(
  232. Instruction.TextureSize,
  233. texOp.Type,
  234. texOp.Format,
  235. texOp.Flags,
  236. texOp.Handle,
  237. index,
  238. coordSize,
  239. texSizeSources));
  240. Operand source = sources[coordsIndex + index];
  241. Operand coordNormalized = Local();
  242. node.List.AddBefore(node, new Operation(Instruction.FP32 | Instruction.Divide, coordNormalized, source, Float(coordSize)));
  243. sources[coordsIndex + index] = coordNormalized;
  244. }
  245. }
  246. // Technically, non-constant texture offsets are not allowed (according to the spec),
  247. // however some GPUs does support that.
  248. // For GPUs where it is not supported, we can replace the instruction with the following:
  249. // For texture*Offset, we replace it by texture*, and add the offset to the P coords.
  250. // The offset can be calculated as offset / textureSize(lod), where lod = textureQueryLod(coords).
  251. // For texelFetchOffset, we replace it by texelFetch and add the offset to the P coords directly.
  252. // For textureGatherOffset, we take advantage of the fact that the operation is already broken down
  253. // to read the 4 pixels separately, and just replace it with 4 textureGather with a different offset
  254. // for each pixel.
  255. if (hasInvalidOffset)
  256. {
  257. if (intCoords)
  258. {
  259. for (int index = 0; index < coordsCount; index++)
  260. {
  261. Operand source = sources[coordsIndex + index];
  262. Operand coordPlusOffset = Local();
  263. node.List.AddBefore(node, new Operation(Instruction.Add, coordPlusOffset, source, offsets[index]));
  264. sources[coordsIndex + index] = coordPlusOffset;
  265. }
  266. }
  267. else
  268. {
  269. Operand lod = Local();
  270. node.List.AddBefore(node, new TextureOperation(
  271. Instruction.Lod,
  272. texOp.Type,
  273. texOp.Format,
  274. texOp.Flags,
  275. texOp.Handle,
  276. 1,
  277. lod,
  278. lodSources));
  279. for (int index = 0; index < coordsCount; index++)
  280. {
  281. Operand coordSize = Local();
  282. Operand[] texSizeSources;
  283. if (isBindless || isIndexed)
  284. {
  285. texSizeSources = new Operand[] { sources[0], Int(lod) };
  286. }
  287. else
  288. {
  289. texSizeSources = new Operand[] { Int(lod) };
  290. }
  291. node.List.AddBefore(node, new TextureOperation(
  292. Instruction.TextureSize,
  293. texOp.Type,
  294. texOp.Format,
  295. texOp.Flags,
  296. texOp.Handle,
  297. index,
  298. coordSize,
  299. texSizeSources));
  300. Operand offset = Local();
  301. Operand intOffset = offsets[index + (hasOffsets ? texOp.Index * coordsCount : 0)];
  302. node.List.AddBefore(node, new Operation(Instruction.FP32 | Instruction.Divide, offset, Float(intOffset), Float(coordSize)));
  303. Operand source = sources[coordsIndex + index];
  304. Operand coordPlusOffset = Local();
  305. node.List.AddBefore(node, new Operation(Instruction.FP32 | Instruction.Add, coordPlusOffset, source, offset));
  306. sources[coordsIndex + index] = coordPlusOffset;
  307. }
  308. }
  309. if (isGather && !isShadow)
  310. {
  311. Operand gatherComponent = sources[dstIndex - 1];
  312. Debug.Assert(gatherComponent.Type == OperandType.Constant);
  313. componentIndex = gatherComponent.Value;
  314. }
  315. }
  316. TextureOperation newTexOp = new TextureOperation(
  317. Instruction.TextureSample,
  318. texOp.Type,
  319. texOp.Format,
  320. texOp.Flags & ~(TextureFlags.Offset | TextureFlags.Offsets),
  321. texOp.Handle,
  322. componentIndex,
  323. texOp.Dest,
  324. sources);
  325. for (int index = 0; index < texOp.SourcesCount; index++)
  326. {
  327. texOp.SetSource(index, null);
  328. }
  329. LinkedListNode<INode> oldNode = node;
  330. node = node.List.AddBefore(node, newTexOp);
  331. node.List.Remove(oldNode);
  332. return node;
  333. }
  334. private static LinkedListNode<INode> InsertSnormNormalization(LinkedListNode<INode> node, ShaderConfig config)
  335. {
  336. TextureOperation texOp = (TextureOperation)node.Value;
  337. TextureFormat format = config.GpuAccessor.QueryTextureFormat(texOp.Handle, texOp.CbufSlot);
  338. int maxPositive = format switch
  339. {
  340. TextureFormat.R8Snorm => sbyte.MaxValue,
  341. TextureFormat.R8G8Snorm => sbyte.MaxValue,
  342. TextureFormat.R8G8B8A8Snorm => sbyte.MaxValue,
  343. TextureFormat.R16Snorm => short.MaxValue,
  344. TextureFormat.R16G16Snorm => short.MaxValue,
  345. TextureFormat.R16G16B16A16Snorm => short.MaxValue,
  346. _ => 0
  347. };
  348. // The value being 0 means that the format is not a SNORM format, so there's nothing to do here.
  349. if (maxPositive == 0)
  350. {
  351. return node;
  352. }
  353. // Do normalization. We assume SINT formats are being used as replacement for SNORM (that is not supported).
  354. INode[] uses = texOp.Dest.UseOps.ToArray();
  355. Operation convOp = new Operation(Instruction.ConvertS32ToFP, Local(), texOp.Dest);
  356. Operation normOp = new Operation(Instruction.FP32 | Instruction.Multiply, Local(), convOp.Dest, ConstF(1f / maxPositive));
  357. node = node.List.AddAfter(node, convOp);
  358. node = node.List.AddAfter(node, normOp);
  359. foreach (INode useOp in uses)
  360. {
  361. if (!(useOp is Operation op))
  362. {
  363. continue;
  364. }
  365. // Replace all uses of the texture pixel value with the normalized value.
  366. for (int index = 0; index < op.SourcesCount; index++)
  367. {
  368. if (op.GetSource(index) == texOp.Dest)
  369. {
  370. op.SetSource(index, normOp.Dest);
  371. }
  372. }
  373. }
  374. return node;
  375. }
  376. }
  377. }