Decoder.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  1. using Ryujinx.Graphics.Shader.Instructions;
  2. using System;
  3. using System.Buffers.Binary;
  4. using System.Collections.Concurrent;
  5. using System.Collections.Generic;
  6. using System.Linq;
  7. using System.Reflection.Emit;
  8. using static Ryujinx.Graphics.Shader.IntermediateRepresentation.OperandHelper;
  9. namespace Ryujinx.Graphics.Shader.Decoders
  10. {
  11. static class Decoder
  12. {
  13. private delegate object OpActivator(InstEmitter emitter, ulong address, long opCode);
  14. private static ConcurrentDictionary<Type, OpActivator> _opActivators;
  15. static Decoder()
  16. {
  17. _opActivators = new ConcurrentDictionary<Type, OpActivator>();
  18. }
  19. public static Block[] Decode(Span<byte> code, ulong headerSize)
  20. {
  21. List<Block> blocks = new List<Block>();
  22. Queue<Block> workQueue = new Queue<Block>();
  23. Dictionary<ulong, Block> visited = new Dictionary<ulong, Block>();
  24. Block GetBlock(ulong blkAddress)
  25. {
  26. if (!visited.TryGetValue(blkAddress, out Block block))
  27. {
  28. block = new Block(blkAddress);
  29. workQueue.Enqueue(block);
  30. visited.Add(blkAddress, block);
  31. }
  32. return block;
  33. }
  34. ulong startAddress = headerSize;
  35. GetBlock(startAddress);
  36. while (workQueue.TryDequeue(out Block currBlock))
  37. {
  38. // Check if the current block is inside another block.
  39. if (BinarySearch(blocks, currBlock.Address, out int nBlkIndex))
  40. {
  41. Block nBlock = blocks[nBlkIndex];
  42. if (nBlock.Address == currBlock.Address)
  43. {
  44. throw new InvalidOperationException("Found duplicate block address on the list.");
  45. }
  46. nBlock.Split(currBlock);
  47. blocks.Insert(nBlkIndex + 1, currBlock);
  48. continue;
  49. }
  50. // If we have a block after the current one, set the limit address.
  51. ulong limitAddress = (ulong)code.Length;
  52. if (nBlkIndex != blocks.Count)
  53. {
  54. Block nBlock = blocks[nBlkIndex];
  55. int nextIndex = nBlkIndex + 1;
  56. if (nBlock.Address < currBlock.Address && nextIndex < blocks.Count)
  57. {
  58. limitAddress = blocks[nextIndex].Address;
  59. }
  60. else if (nBlock.Address > currBlock.Address)
  61. {
  62. limitAddress = blocks[nBlkIndex].Address;
  63. }
  64. }
  65. FillBlock(code, currBlock, limitAddress, startAddress);
  66. if (currBlock.OpCodes.Count != 0)
  67. {
  68. foreach (OpCodeSsy ssyOp in currBlock.SsyOpCodes)
  69. {
  70. GetBlock(ssyOp.GetAbsoluteAddress());
  71. }
  72. // Set child blocks. "Branch" is the block the branch instruction
  73. // points to (when taken), "Next" is the block at the next address,
  74. // executed when the branch is not taken. For Unconditional Branches
  75. // or end of program, Next is null.
  76. OpCode lastOp = currBlock.GetLastOp();
  77. if (lastOp is OpCodeBranch op)
  78. {
  79. currBlock.Branch = GetBlock(op.GetAbsoluteAddress());
  80. }
  81. if (!IsUnconditionalBranch(lastOp))
  82. {
  83. currBlock.Next = GetBlock(currBlock.EndAddress);
  84. }
  85. }
  86. // Insert the new block on the list (sorted by address).
  87. if (blocks.Count != 0)
  88. {
  89. Block nBlock = blocks[nBlkIndex];
  90. blocks.Insert(nBlkIndex + (nBlock.Address < currBlock.Address ? 1 : 0), currBlock);
  91. }
  92. else
  93. {
  94. blocks.Add(currBlock);
  95. }
  96. }
  97. foreach (Block ssyBlock in blocks.Where(x => x.SsyOpCodes.Count != 0))
  98. {
  99. for (int ssyIndex = 0; ssyIndex < ssyBlock.SsyOpCodes.Count; ssyIndex++)
  100. {
  101. PropagateSsy(visited, ssyBlock, ssyIndex);
  102. }
  103. }
  104. return blocks.ToArray();
  105. }
  106. private static bool BinarySearch(List<Block> blocks, ulong address, out int index)
  107. {
  108. index = 0;
  109. int left = 0;
  110. int right = blocks.Count - 1;
  111. while (left <= right)
  112. {
  113. int size = right - left;
  114. int middle = left + (size >> 1);
  115. Block block = blocks[middle];
  116. index = middle;
  117. if (address >= block.Address && address < block.EndAddress)
  118. {
  119. return true;
  120. }
  121. if (address < block.Address)
  122. {
  123. right = middle - 1;
  124. }
  125. else
  126. {
  127. left = middle + 1;
  128. }
  129. }
  130. return false;
  131. }
  132. private static void FillBlock(
  133. Span<byte> code,
  134. Block block,
  135. ulong limitAddress,
  136. ulong startAddress)
  137. {
  138. ulong address = block.Address;
  139. do
  140. {
  141. if (address >= limitAddress)
  142. {
  143. break;
  144. }
  145. // Ignore scheduling instructions, which are written every 32 bytes.
  146. if (((address - startAddress) & 0x1f) == 0)
  147. {
  148. address += 8;
  149. continue;
  150. }
  151. uint word0 = BinaryPrimitives.ReadUInt32LittleEndian(code.Slice((int)address));
  152. uint word1 = BinaryPrimitives.ReadUInt32LittleEndian(code.Slice((int)address + 4));
  153. ulong opAddress = address;
  154. address += 8;
  155. long opCode = word0 | (long)word1 << 32;
  156. (InstEmitter emitter, Type opCodeType) = OpCodeTable.GetEmitter(opCode);
  157. if (emitter == null)
  158. {
  159. // TODO: Warning, illegal encoding.
  160. block.OpCodes.Add(new OpCode(null, opAddress, opCode));
  161. continue;
  162. }
  163. OpCode op = MakeOpCode(opCodeType, emitter, opAddress, opCode);
  164. block.OpCodes.Add(op);
  165. }
  166. while (!IsBranch(block.GetLastOp()));
  167. block.EndAddress = address;
  168. block.UpdateSsyOpCodes();
  169. }
  170. private static bool IsUnconditionalBranch(OpCode opCode)
  171. {
  172. return IsUnconditional(opCode) && IsBranch(opCode);
  173. }
  174. private static bool IsUnconditional(OpCode opCode)
  175. {
  176. if (opCode is OpCodeExit op && op.Condition != Condition.Always)
  177. {
  178. return false;
  179. }
  180. return opCode.Predicate.Index == RegisterConsts.PredicateTrueIndex && !opCode.InvertPredicate;
  181. }
  182. private static bool IsBranch(OpCode opCode)
  183. {
  184. return (opCode is OpCodeBranch && opCode.Emitter != InstEmit.Ssy) ||
  185. opCode is OpCodeSync ||
  186. opCode is OpCodeExit;
  187. }
  188. private static OpCode MakeOpCode(Type type, InstEmitter emitter, ulong address, long opCode)
  189. {
  190. if (type == null)
  191. {
  192. throw new ArgumentNullException(nameof(type));
  193. }
  194. OpActivator createInstance = _opActivators.GetOrAdd(type, CacheOpActivator);
  195. return (OpCode)createInstance(emitter, address, opCode);
  196. }
  197. private static OpActivator CacheOpActivator(Type type)
  198. {
  199. Type[] argTypes = new Type[] { typeof(InstEmitter), typeof(ulong), typeof(long) };
  200. DynamicMethod mthd = new DynamicMethod($"Make{type.Name}", type, argTypes);
  201. ILGenerator generator = mthd.GetILGenerator();
  202. generator.Emit(OpCodes.Ldarg_0);
  203. generator.Emit(OpCodes.Ldarg_1);
  204. generator.Emit(OpCodes.Ldarg_2);
  205. generator.Emit(OpCodes.Newobj, type.GetConstructor(argTypes));
  206. generator.Emit(OpCodes.Ret);
  207. return (OpActivator)mthd.CreateDelegate(typeof(OpActivator));
  208. }
  209. private struct PathBlockState
  210. {
  211. public Block Block { get; }
  212. private enum RestoreType
  213. {
  214. None,
  215. PopSsy,
  216. PushSync
  217. }
  218. private RestoreType _restoreType;
  219. private ulong _restoreValue;
  220. public bool ReturningFromVisit => _restoreType != RestoreType.None;
  221. public PathBlockState(Block block)
  222. {
  223. Block = block;
  224. _restoreType = RestoreType.None;
  225. _restoreValue = 0;
  226. }
  227. public PathBlockState(int oldSsyStackSize)
  228. {
  229. Block = null;
  230. _restoreType = RestoreType.PopSsy;
  231. _restoreValue = (ulong)oldSsyStackSize;
  232. }
  233. public PathBlockState(ulong syncAddress)
  234. {
  235. Block = null;
  236. _restoreType = RestoreType.PushSync;
  237. _restoreValue = syncAddress;
  238. }
  239. public void RestoreStackState(Stack<ulong> ssyStack)
  240. {
  241. if (_restoreType == RestoreType.PushSync)
  242. {
  243. ssyStack.Push(_restoreValue);
  244. }
  245. else if (_restoreType == RestoreType.PopSsy)
  246. {
  247. while (ssyStack.Count > (uint)_restoreValue)
  248. {
  249. ssyStack.Pop();
  250. }
  251. }
  252. }
  253. }
  254. private static void PropagateSsy(Dictionary<ulong, Block> blocks, Block ssyBlock, int ssyIndex)
  255. {
  256. OpCodeSsy ssyOp = ssyBlock.SsyOpCodes[ssyIndex];
  257. Stack<PathBlockState> workQueue = new Stack<PathBlockState>();
  258. HashSet<Block> visited = new HashSet<Block>();
  259. Stack<ulong> ssyStack = new Stack<ulong>();
  260. void Push(PathBlockState pbs)
  261. {
  262. if (pbs.Block == null || visited.Add(pbs.Block))
  263. {
  264. workQueue.Push(pbs);
  265. }
  266. }
  267. Push(new PathBlockState(ssyBlock));
  268. while (workQueue.TryPop(out PathBlockState pbs))
  269. {
  270. if (pbs.ReturningFromVisit)
  271. {
  272. pbs.RestoreStackState(ssyStack);
  273. continue;
  274. }
  275. Block current = pbs.Block;
  276. int ssyOpCodesCount = current.SsyOpCodes.Count;
  277. if (ssyOpCodesCount != 0)
  278. {
  279. Push(new PathBlockState(ssyStack.Count));
  280. for (int index = ssyIndex; index < ssyOpCodesCount; index++)
  281. {
  282. ssyStack.Push(current.SsyOpCodes[index].GetAbsoluteAddress());
  283. }
  284. }
  285. ssyIndex = 0;
  286. if (current.Next != null)
  287. {
  288. Push(new PathBlockState(current.Next));
  289. }
  290. if (current.Branch != null)
  291. {
  292. Push(new PathBlockState(current.Branch));
  293. }
  294. else if (current.GetLastOp() is OpCodeSync op)
  295. {
  296. ulong syncAddress = ssyStack.Pop();
  297. if (ssyStack.Count == 0)
  298. {
  299. ssyStack.Push(syncAddress);
  300. op.Targets.Add(ssyOp, op.Targets.Count);
  301. ssyOp.Syncs.TryAdd(op, Local());
  302. }
  303. else
  304. {
  305. Push(new PathBlockState(syncAddress));
  306. Push(new PathBlockState(blocks[syncAddress]));
  307. }
  308. }
  309. }
  310. }
  311. }
  312. }