Decoder.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  1. using Ryujinx.Graphics.Shader.Instructions;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using static Ryujinx.Graphics.Shader.IntermediateRepresentation.OperandHelper;
  6. namespace Ryujinx.Graphics.Shader.Decoders
  7. {
  8. static class Decoder
  9. {
  10. public static Block[] Decode(IGpuAccessor gpuAccessor, ulong startAddress)
  11. {
  12. List<Block> blocks = new List<Block>();
  13. Queue<Block> workQueue = new Queue<Block>();
  14. Dictionary<ulong, Block> visited = new Dictionary<ulong, Block>();
  15. Block GetBlock(ulong blkAddress)
  16. {
  17. if (!visited.TryGetValue(blkAddress, out Block block))
  18. {
  19. block = new Block(blkAddress);
  20. workQueue.Enqueue(block);
  21. visited.Add(blkAddress, block);
  22. }
  23. return block;
  24. }
  25. GetBlock(0);
  26. while (workQueue.TryDequeue(out Block currBlock))
  27. {
  28. // Check if the current block is inside another block.
  29. if (BinarySearch(blocks, currBlock.Address, out int nBlkIndex))
  30. {
  31. Block nBlock = blocks[nBlkIndex];
  32. if (nBlock.Address == currBlock.Address)
  33. {
  34. throw new InvalidOperationException("Found duplicate block address on the list.");
  35. }
  36. nBlock.Split(currBlock);
  37. blocks.Insert(nBlkIndex + 1, currBlock);
  38. continue;
  39. }
  40. // If we have a block after the current one, set the limit address.
  41. ulong limitAddress = ulong.MaxValue;
  42. if (nBlkIndex != blocks.Count)
  43. {
  44. Block nBlock = blocks[nBlkIndex];
  45. int nextIndex = nBlkIndex + 1;
  46. if (nBlock.Address < currBlock.Address && nextIndex < blocks.Count)
  47. {
  48. limitAddress = blocks[nextIndex].Address;
  49. }
  50. else if (nBlock.Address > currBlock.Address)
  51. {
  52. limitAddress = blocks[nBlkIndex].Address;
  53. }
  54. }
  55. FillBlock(gpuAccessor, currBlock, limitAddress, startAddress);
  56. if (currBlock.OpCodes.Count != 0)
  57. {
  58. // We should have blocks for all possible branch targets,
  59. // including those from SSY/PBK instructions.
  60. foreach (OpCodePush pushOp in currBlock.PushOpCodes)
  61. {
  62. GetBlock(pushOp.GetAbsoluteAddress());
  63. }
  64. // Set child blocks. "Branch" is the block the branch instruction
  65. // points to (when taken), "Next" is the block at the next address,
  66. // executed when the branch is not taken. For Unconditional Branches
  67. // or end of program, Next is null.
  68. OpCode lastOp = currBlock.GetLastOp();
  69. if (lastOp is OpCodeBranch opBr)
  70. {
  71. currBlock.Branch = GetBlock(opBr.GetAbsoluteAddress());
  72. }
  73. else if (lastOp is OpCodeBranchIndir opBrIndir)
  74. {
  75. // An indirect branch could go anywhere, we don't know the target.
  76. // Those instructions are usually used on a switch to jump table
  77. // compiler optimization, and in those cases the possible targets
  78. // seems to be always right after the BRX itself. We can assume
  79. // that the possible targets are all the blocks in-between the
  80. // instruction right after the BRX, and the common target that
  81. // all the "cases" should eventually jump to, acting as the
  82. // switch break.
  83. Block firstTarget = GetBlock(currBlock.EndAddress);
  84. firstTarget.BrIndir = opBrIndir;
  85. opBrIndir.PossibleTargets.Add(firstTarget);
  86. }
  87. if (!IsUnconditionalBranch(lastOp))
  88. {
  89. currBlock.Next = GetBlock(currBlock.EndAddress);
  90. }
  91. }
  92. // Insert the new block on the list (sorted by address).
  93. if (blocks.Count != 0)
  94. {
  95. Block nBlock = blocks[nBlkIndex];
  96. blocks.Insert(nBlkIndex + (nBlock.Address < currBlock.Address ? 1 : 0), currBlock);
  97. }
  98. else
  99. {
  100. blocks.Add(currBlock);
  101. }
  102. // Do we have a block after the current one?
  103. if (currBlock.BrIndir != null && HasBlockAfter(gpuAccessor, currBlock, startAddress))
  104. {
  105. bool targetVisited = visited.ContainsKey(currBlock.EndAddress);
  106. Block possibleTarget = GetBlock(currBlock.EndAddress);
  107. currBlock.BrIndir.PossibleTargets.Add(possibleTarget);
  108. if (!targetVisited)
  109. {
  110. possibleTarget.BrIndir = currBlock.BrIndir;
  111. }
  112. }
  113. }
  114. foreach (Block block in blocks.Where(x => x.PushOpCodes.Count != 0))
  115. {
  116. for (int pushOpIndex = 0; pushOpIndex < block.PushOpCodes.Count; pushOpIndex++)
  117. {
  118. PropagatePushOp(visited, block, pushOpIndex);
  119. }
  120. }
  121. return blocks.ToArray();
  122. }
  123. private static bool HasBlockAfter(IGpuAccessor gpuAccessor, Block currBlock, ulong startAdddress)
  124. {
  125. if (!gpuAccessor.MemoryMapped(startAdddress + currBlock.EndAddress) ||
  126. !gpuAccessor.MemoryMapped(startAdddress + currBlock.EndAddress + 7))
  127. {
  128. return false;
  129. }
  130. ulong inst = gpuAccessor.MemoryRead<ulong>(startAdddress + currBlock.EndAddress);
  131. return inst != 0UL;
  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. IGpuAccessor gpuAccessor,
  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. ulong opAddress = address;
  179. address += 8;
  180. long opCode = gpuAccessor.MemoryRead<long>(startAddress + opAddress);
  181. (InstEmitter emitter, OpCodeTable.OpActivator opActivator) = OpCodeTable.GetEmitter(opCode);
  182. if (emitter == null)
  183. {
  184. // TODO: Warning, illegal encoding.
  185. block.OpCodes.Add(new OpCode(null, opAddress, opCode));
  186. continue;
  187. }
  188. if (opActivator == null)
  189. {
  190. throw new ArgumentNullException(nameof(opActivator));
  191. }
  192. OpCode op = (OpCode)opActivator(emitter, opAddress, opCode);
  193. block.OpCodes.Add(op);
  194. }
  195. while (!IsBranch(block.GetLastOp()));
  196. block.EndAddress = address;
  197. block.UpdatePushOps();
  198. }
  199. private static bool IsUnconditionalBranch(OpCode opCode)
  200. {
  201. return IsUnconditional(opCode) && IsBranch(opCode);
  202. }
  203. private static bool IsUnconditional(OpCode opCode)
  204. {
  205. if (opCode is OpCodeExit op && op.Condition != Condition.Always)
  206. {
  207. return false;
  208. }
  209. return opCode.Predicate.Index == RegisterConsts.PredicateTrueIndex && !opCode.InvertPredicate;
  210. }
  211. private static bool IsBranch(OpCode opCode)
  212. {
  213. return (opCode is OpCodeBranch opBranch && !opBranch.PushTarget) ||
  214. opCode is OpCodeBranchIndir ||
  215. opCode is OpCodeBranchPop ||
  216. opCode is OpCodeExit;
  217. }
  218. private static bool IsExit(OpCode opCode)
  219. {
  220. return opCode is OpCodeExit;
  221. }
  222. private struct PathBlockState
  223. {
  224. public Block Block { get; }
  225. private enum RestoreType
  226. {
  227. None,
  228. PopPushOp,
  229. PushBranchOp
  230. }
  231. private RestoreType _restoreType;
  232. private ulong _restoreValue;
  233. public bool ReturningFromVisit => _restoreType != RestoreType.None;
  234. public PathBlockState(Block block)
  235. {
  236. Block = block;
  237. _restoreType = RestoreType.None;
  238. _restoreValue = 0;
  239. }
  240. public PathBlockState(int oldStackSize)
  241. {
  242. Block = null;
  243. _restoreType = RestoreType.PopPushOp;
  244. _restoreValue = (ulong)oldStackSize;
  245. }
  246. public PathBlockState(ulong syncAddress)
  247. {
  248. Block = null;
  249. _restoreType = RestoreType.PushBranchOp;
  250. _restoreValue = syncAddress;
  251. }
  252. public void RestoreStackState(Stack<ulong> branchStack)
  253. {
  254. if (_restoreType == RestoreType.PushBranchOp)
  255. {
  256. branchStack.Push(_restoreValue);
  257. }
  258. else if (_restoreType == RestoreType.PopPushOp)
  259. {
  260. while (branchStack.Count > (uint)_restoreValue)
  261. {
  262. branchStack.Pop();
  263. }
  264. }
  265. }
  266. }
  267. private static void PropagatePushOp(Dictionary<ulong, Block> blocks, Block currBlock, int pushOpIndex)
  268. {
  269. OpCodePush pushOp = currBlock.PushOpCodes[pushOpIndex];
  270. Stack<PathBlockState> workQueue = new Stack<PathBlockState>();
  271. HashSet<Block> visited = new HashSet<Block>();
  272. Stack<ulong> branchStack = new Stack<ulong>();
  273. void Push(PathBlockState pbs)
  274. {
  275. // When block is null, this means we are pushing a restore operation.
  276. // Restore operations are used to undo the work done inside a block
  277. // when we return from it, for example it pops addresses pushed by
  278. // SSY/PBK instructions inside the block, and pushes addresses poped
  279. // by SYNC/BRK.
  280. // For blocks, if it's already visited, we just ignore to avoid going
  281. // around in circles and getting stuck here.
  282. if (pbs.Block == null || !visited.Contains(pbs.Block))
  283. {
  284. workQueue.Push(pbs);
  285. }
  286. }
  287. Push(new PathBlockState(currBlock));
  288. while (workQueue.TryPop(out PathBlockState pbs))
  289. {
  290. if (pbs.ReturningFromVisit)
  291. {
  292. pbs.RestoreStackState(branchStack);
  293. continue;
  294. }
  295. Block current = pbs.Block;
  296. // If the block was already processed, we just ignore it, otherwise
  297. // we would push the same child blocks of an already processed block,
  298. // and go around in circles until memory is exhausted.
  299. if (!visited.Add(current))
  300. {
  301. continue;
  302. }
  303. int pushOpsCount = current.PushOpCodes.Count;
  304. if (pushOpsCount != 0)
  305. {
  306. Push(new PathBlockState(branchStack.Count));
  307. for (int index = pushOpIndex; index < pushOpsCount; index++)
  308. {
  309. branchStack.Push(current.PushOpCodes[index].GetAbsoluteAddress());
  310. }
  311. }
  312. pushOpIndex = 0;
  313. if (current.Next != null)
  314. {
  315. Push(new PathBlockState(current.Next));
  316. }
  317. if (current.Branch != null)
  318. {
  319. Push(new PathBlockState(current.Branch));
  320. }
  321. else if (current.GetLastOp() is OpCodeBranchIndir brIndir)
  322. {
  323. // By adding them in descending order (sorted by address), we process the blocks
  324. // in order (of ascending address), since we work with a LIFO.
  325. foreach (Block possibleTarget in brIndir.PossibleTargets.OrderByDescending(x => x.Address))
  326. {
  327. Push(new PathBlockState(possibleTarget));
  328. }
  329. }
  330. else if (current.GetLastOp() is OpCodeBranchPop op)
  331. {
  332. ulong targetAddress = branchStack.Pop();
  333. if (branchStack.Count == 0)
  334. {
  335. branchStack.Push(targetAddress);
  336. op.Targets.Add(pushOp, op.Targets.Count);
  337. pushOp.PopOps.TryAdd(op, Local());
  338. }
  339. else
  340. {
  341. // First we push the target address (this will be used to push the
  342. // address back into the SSY/PBK stack when we return from that block),
  343. // then we push the block itself into the work "queue" (well, it's a stack)
  344. // for processing.
  345. Push(new PathBlockState(targetAddress));
  346. Push(new PathBlockState(blocks[targetAddress]));
  347. }
  348. }
  349. }
  350. }
  351. }
  352. }