Decoder.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  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. GetBlock(0);
  35. ulong maxAddress = (ulong)code.Length - headerSize;
  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 = maxAddress;
  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, headerSize);
  66. if (currBlock.OpCodes.Count != 0)
  67. {
  68. // We should have blocks for all possible branch targets,
  69. // including those from SSY/PBK instructions.
  70. foreach (OpCodePush pushOp in currBlock.PushOpCodes)
  71. {
  72. GetBlock(pushOp.GetAbsoluteAddress());
  73. }
  74. // Set child blocks. "Branch" is the block the branch instruction
  75. // points to (when taken), "Next" is the block at the next address,
  76. // executed when the branch is not taken. For Unconditional Branches
  77. // or end of program, Next is null.
  78. OpCode lastOp = currBlock.GetLastOp();
  79. if (lastOp is OpCodeBranch opBr)
  80. {
  81. currBlock.Branch = GetBlock(opBr.GetAbsoluteAddress());
  82. }
  83. else if (lastOp is OpCodeBranchIndir opBrIndir)
  84. {
  85. // An indirect branch could go anywhere, we don't know the target.
  86. // Those instructions are usually used on a switch to jump table
  87. // compiler optimization, and in those cases the possible targets
  88. // seems to be always right after the BRX itself. We can assume
  89. // that the possible targets are all the blocks in-between the
  90. // instruction right after the BRX, and the common target that
  91. // all the "cases" should eventually jump to, acting as the
  92. // switch break.
  93. Block firstTarget = GetBlock(currBlock.EndAddress);
  94. firstTarget.BrIndir = opBrIndir;
  95. opBrIndir.PossibleTargets.Add(firstTarget);
  96. }
  97. if (!IsUnconditionalBranch(lastOp))
  98. {
  99. currBlock.Next = GetBlock(currBlock.EndAddress);
  100. }
  101. }
  102. // Insert the new block on the list (sorted by address).
  103. if (blocks.Count != 0)
  104. {
  105. Block nBlock = blocks[nBlkIndex];
  106. blocks.Insert(nBlkIndex + (nBlock.Address < currBlock.Address ? 1 : 0), currBlock);
  107. }
  108. else
  109. {
  110. blocks.Add(currBlock);
  111. }
  112. // Do we have a block after the current one?
  113. if (!IsExit(currBlock.GetLastOp()) && currBlock.BrIndir != null && currBlock.EndAddress < maxAddress)
  114. {
  115. bool targetVisited = visited.ContainsKey(currBlock.EndAddress);
  116. Block possibleTarget = GetBlock(currBlock.EndAddress);
  117. currBlock.BrIndir.PossibleTargets.Add(possibleTarget);
  118. if (!targetVisited)
  119. {
  120. possibleTarget.BrIndir = currBlock.BrIndir;
  121. }
  122. }
  123. }
  124. foreach (Block block in blocks.Where(x => x.PushOpCodes.Count != 0))
  125. {
  126. for (int pushOpIndex = 0; pushOpIndex < block.PushOpCodes.Count; pushOpIndex++)
  127. {
  128. PropagatePushOp(visited, block, pushOpIndex);
  129. }
  130. }
  131. return blocks.ToArray();
  132. }
  133. private static bool BinarySearch(List<Block> blocks, ulong address, out int index)
  134. {
  135. index = 0;
  136. int left = 0;
  137. int right = blocks.Count - 1;
  138. while (left <= right)
  139. {
  140. int size = right - left;
  141. int middle = left + (size >> 1);
  142. Block block = blocks[middle];
  143. index = middle;
  144. if (address >= block.Address && address < block.EndAddress)
  145. {
  146. return true;
  147. }
  148. if (address < block.Address)
  149. {
  150. right = middle - 1;
  151. }
  152. else
  153. {
  154. left = middle + 1;
  155. }
  156. }
  157. return false;
  158. }
  159. private static void FillBlock(
  160. Span<byte> code,
  161. Block block,
  162. ulong limitAddress,
  163. ulong startAddress)
  164. {
  165. ulong address = block.Address;
  166. do
  167. {
  168. if (address + 7 >= limitAddress)
  169. {
  170. break;
  171. }
  172. // Ignore scheduling instructions, which are written every 32 bytes.
  173. if ((address & 0x1f) == 0)
  174. {
  175. address += 8;
  176. continue;
  177. }
  178. uint word0 = BinaryPrimitives.ReadUInt32LittleEndian(code.Slice((int)(startAddress + address)));
  179. uint word1 = BinaryPrimitives.ReadUInt32LittleEndian(code.Slice((int)(startAddress + address + 4)));
  180. ulong opAddress = address;
  181. address += 8;
  182. long opCode = word0 | (long)word1 << 32;
  183. (InstEmitter emitter, Type opCodeType) = OpCodeTable.GetEmitter(opCode);
  184. if (emitter == null)
  185. {
  186. // TODO: Warning, illegal encoding.
  187. block.OpCodes.Add(new OpCode(null, opAddress, opCode));
  188. continue;
  189. }
  190. OpCode op = MakeOpCode(opCodeType, emitter, opAddress, opCode);
  191. block.OpCodes.Add(op);
  192. }
  193. while (!IsBranch(block.GetLastOp()));
  194. block.EndAddress = address;
  195. block.UpdatePushOps();
  196. }
  197. private static bool IsUnconditionalBranch(OpCode opCode)
  198. {
  199. return IsUnconditional(opCode) && IsBranch(opCode);
  200. }
  201. private static bool IsUnconditional(OpCode opCode)
  202. {
  203. if (opCode is OpCodeExit op && op.Condition != Condition.Always)
  204. {
  205. return false;
  206. }
  207. return opCode.Predicate.Index == RegisterConsts.PredicateTrueIndex && !opCode.InvertPredicate;
  208. }
  209. private static bool IsBranch(OpCode opCode)
  210. {
  211. return (opCode is OpCodeBranch opBranch && !opBranch.PushTarget) ||
  212. opCode is OpCodeBranchIndir ||
  213. opCode is OpCodeBranchPop ||
  214. opCode is OpCodeExit;
  215. }
  216. private static bool IsExit(OpCode opCode)
  217. {
  218. return opCode is OpCodeExit;
  219. }
  220. private static OpCode MakeOpCode(Type type, InstEmitter emitter, ulong address, long opCode)
  221. {
  222. if (type == null)
  223. {
  224. throw new ArgumentNullException(nameof(type));
  225. }
  226. OpActivator createInstance = _opActivators.GetOrAdd(type, CacheOpActivator);
  227. return (OpCode)createInstance(emitter, address, opCode);
  228. }
  229. private static OpActivator CacheOpActivator(Type type)
  230. {
  231. Type[] argTypes = new Type[] { typeof(InstEmitter), typeof(ulong), typeof(long) };
  232. DynamicMethod mthd = new DynamicMethod($"Make{type.Name}", type, argTypes);
  233. ILGenerator generator = mthd.GetILGenerator();
  234. generator.Emit(OpCodes.Ldarg_0);
  235. generator.Emit(OpCodes.Ldarg_1);
  236. generator.Emit(OpCodes.Ldarg_2);
  237. generator.Emit(OpCodes.Newobj, type.GetConstructor(argTypes));
  238. generator.Emit(OpCodes.Ret);
  239. return (OpActivator)mthd.CreateDelegate(typeof(OpActivator));
  240. }
  241. private struct PathBlockState
  242. {
  243. public Block Block { get; }
  244. private enum RestoreType
  245. {
  246. None,
  247. PopPushOp,
  248. PushBranchOp
  249. }
  250. private RestoreType _restoreType;
  251. private ulong _restoreValue;
  252. public bool ReturningFromVisit => _restoreType != RestoreType.None;
  253. public PathBlockState(Block block)
  254. {
  255. Block = block;
  256. _restoreType = RestoreType.None;
  257. _restoreValue = 0;
  258. }
  259. public PathBlockState(int oldStackSize)
  260. {
  261. Block = null;
  262. _restoreType = RestoreType.PopPushOp;
  263. _restoreValue = (ulong)oldStackSize;
  264. }
  265. public PathBlockState(ulong syncAddress)
  266. {
  267. Block = null;
  268. _restoreType = RestoreType.PushBranchOp;
  269. _restoreValue = syncAddress;
  270. }
  271. public void RestoreStackState(Stack<ulong> branchStack)
  272. {
  273. if (_restoreType == RestoreType.PushBranchOp)
  274. {
  275. branchStack.Push(_restoreValue);
  276. }
  277. else if (_restoreType == RestoreType.PopPushOp)
  278. {
  279. while (branchStack.Count > (uint)_restoreValue)
  280. {
  281. branchStack.Pop();
  282. }
  283. }
  284. }
  285. }
  286. private static void PropagatePushOp(Dictionary<ulong, Block> blocks, Block currBlock, int pushOpIndex)
  287. {
  288. OpCodePush pushOp = currBlock.PushOpCodes[pushOpIndex];
  289. Stack<PathBlockState> workQueue = new Stack<PathBlockState>();
  290. HashSet<Block> visited = new HashSet<Block>();
  291. Stack<ulong> branchStack = new Stack<ulong>();
  292. void Push(PathBlockState pbs)
  293. {
  294. if (pbs.Block == null || visited.Add(pbs.Block))
  295. {
  296. workQueue.Push(pbs);
  297. }
  298. }
  299. Push(new PathBlockState(currBlock));
  300. while (workQueue.TryPop(out PathBlockState pbs))
  301. {
  302. if (pbs.ReturningFromVisit)
  303. {
  304. pbs.RestoreStackState(branchStack);
  305. continue;
  306. }
  307. Block current = pbs.Block;
  308. int pushOpsCount = current.PushOpCodes.Count;
  309. if (pushOpsCount != 0)
  310. {
  311. Push(new PathBlockState(branchStack.Count));
  312. for (int index = pushOpIndex; index < pushOpsCount; index++)
  313. {
  314. branchStack.Push(current.PushOpCodes[index].GetAbsoluteAddress());
  315. }
  316. }
  317. pushOpIndex = 0;
  318. if (current.Next != null)
  319. {
  320. Push(new PathBlockState(current.Next));
  321. }
  322. if (current.Branch != null)
  323. {
  324. Push(new PathBlockState(current.Branch));
  325. }
  326. else if (current.GetLastOp() is OpCodeBranchIndir brIndir)
  327. {
  328. foreach (Block possibleTarget in brIndir.PossibleTargets)
  329. {
  330. Push(new PathBlockState(possibleTarget));
  331. }
  332. }
  333. else if (current.GetLastOp() is OpCodeBranchPop op)
  334. {
  335. ulong syncAddress = branchStack.Pop();
  336. if (branchStack.Count == 0)
  337. {
  338. branchStack.Push(syncAddress);
  339. op.Targets.Add(pushOp, op.Targets.Count);
  340. pushOp.PopOps.TryAdd(op, Local());
  341. }
  342. else
  343. {
  344. Push(new PathBlockState(syncAddress));
  345. Push(new PathBlockState(blocks[syncAddress]));
  346. }
  347. }
  348. }
  349. }
  350. }
  351. }