Decoder.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  1. using Ryujinx.Graphics.Gal;
  2. using Ryujinx.Graphics.Shader.Instructions;
  3. using System;
  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 const long HeaderSize = 0x50;
  14. private delegate object OpActivator(InstEmitter emitter, ulong address, long opCode);
  15. private static ConcurrentDictionary<Type, OpActivator> _opActivators;
  16. static Decoder()
  17. {
  18. _opActivators = new ConcurrentDictionary<Type, OpActivator>();
  19. }
  20. public static Block[] Decode(IGalMemory memory, ulong address)
  21. {
  22. List<Block> blocks = new List<Block>();
  23. Queue<Block> workQueue = new Queue<Block>();
  24. Dictionary<ulong, Block> visited = new Dictionary<ulong, Block>();
  25. Block GetBlock(ulong blkAddress)
  26. {
  27. if (!visited.TryGetValue(blkAddress, out Block block))
  28. {
  29. block = new Block(blkAddress);
  30. workQueue.Enqueue(block);
  31. visited.Add(blkAddress, block);
  32. }
  33. return block;
  34. }
  35. ulong startAddress = address + HeaderSize;
  36. GetBlock(startAddress);
  37. while (workQueue.TryDequeue(out Block currBlock))
  38. {
  39. //Check if the current block is inside another block.
  40. if (BinarySearch(blocks, currBlock.Address, out int nBlkIndex))
  41. {
  42. Block nBlock = blocks[nBlkIndex];
  43. if (nBlock.Address == currBlock.Address)
  44. {
  45. throw new InvalidOperationException("Found duplicate block address on the list.");
  46. }
  47. nBlock.Split(currBlock);
  48. blocks.Insert(nBlkIndex + 1, currBlock);
  49. continue;
  50. }
  51. //If we have a block after the current one, set the limit address.
  52. ulong limitAddress = ulong.MaxValue;
  53. if (nBlkIndex != blocks.Count)
  54. {
  55. Block nBlock = blocks[nBlkIndex];
  56. int nextIndex = nBlkIndex + 1;
  57. if (nBlock.Address < currBlock.Address && nextIndex < blocks.Count)
  58. {
  59. limitAddress = blocks[nextIndex].Address;
  60. }
  61. else if (nBlock.Address > currBlock.Address)
  62. {
  63. limitAddress = blocks[nBlkIndex].Address;
  64. }
  65. }
  66. FillBlock(memory, currBlock, limitAddress, startAddress);
  67. if (currBlock.OpCodes.Count != 0)
  68. {
  69. foreach (OpCodeSsy ssyOp in currBlock.SsyOpCodes)
  70. {
  71. GetBlock(ssyOp.GetAbsoluteAddress());
  72. }
  73. //Set child blocks. "Branch" is the block the branch instruction
  74. //points to (when taken), "Next" is the block at the next address,
  75. //executed when the branch is not taken. For Unconditional Branches
  76. //or end of program, Next is null.
  77. OpCode lastOp = currBlock.GetLastOp();
  78. if (lastOp is OpCodeBranch op)
  79. {
  80. currBlock.Branch = GetBlock(op.GetAbsoluteAddress());
  81. }
  82. if (!IsUnconditionalBranch(lastOp))
  83. {
  84. currBlock.Next = GetBlock(currBlock.EndAddress);
  85. }
  86. }
  87. //Insert the new block on the list (sorted by address).
  88. if (blocks.Count != 0)
  89. {
  90. Block nBlock = blocks[nBlkIndex];
  91. blocks.Insert(nBlkIndex + (nBlock.Address < currBlock.Address ? 1 : 0), currBlock);
  92. }
  93. else
  94. {
  95. blocks.Add(currBlock);
  96. }
  97. }
  98. foreach (Block ssyBlock in blocks.Where(x => x.SsyOpCodes.Count != 0))
  99. {
  100. for (int ssyIndex = 0; ssyIndex < ssyBlock.SsyOpCodes.Count; ssyIndex++)
  101. {
  102. PropagateSsy(visited, ssyBlock, ssyIndex);
  103. }
  104. }
  105. return blocks.ToArray();
  106. }
  107. private static bool BinarySearch(List<Block> blocks, ulong address, out int index)
  108. {
  109. index = 0;
  110. int left = 0;
  111. int right = blocks.Count - 1;
  112. while (left <= right)
  113. {
  114. int size = right - left;
  115. int middle = left + (size >> 1);
  116. Block block = blocks[middle];
  117. index = middle;
  118. if (address >= block.Address && address < block.EndAddress)
  119. {
  120. return true;
  121. }
  122. if (address < block.Address)
  123. {
  124. right = middle - 1;
  125. }
  126. else
  127. {
  128. left = middle + 1;
  129. }
  130. }
  131. return false;
  132. }
  133. private static void FillBlock(
  134. IGalMemory memory,
  135. Block block,
  136. ulong limitAddress,
  137. ulong startAddress)
  138. {
  139. ulong address = block.Address;
  140. do
  141. {
  142. if (address >= limitAddress)
  143. {
  144. break;
  145. }
  146. //Ignore scheduling instructions, which are written every 32 bytes.
  147. if (((address - startAddress) & 0x1f) == 0)
  148. {
  149. address += 8;
  150. continue;
  151. }
  152. uint word0 = (uint)memory.ReadInt32((long)(address + 0));
  153. uint word1 = (uint)memory.ReadInt32((long)(address + 4));
  154. ulong opAddress = address;
  155. address += 8;
  156. long opCode = word0 | (long)word1 << 32;
  157. (InstEmitter emitter, Type opCodeType) = OpCodeTable.GetEmitter(opCode);
  158. if (emitter == null)
  159. {
  160. //TODO: Warning, illegal encoding.
  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. }