Decoder.cs 16 KB

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