Decoder.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  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. while (workQueue.TryDequeue(out Block currBlock))
  36. {
  37. // Check if the current block is inside another block.
  38. if (BinarySearch(blocks, currBlock.Address, out int nBlkIndex))
  39. {
  40. Block nBlock = blocks[nBlkIndex];
  41. if (nBlock.Address == currBlock.Address)
  42. {
  43. throw new InvalidOperationException("Found duplicate block address on the list.");
  44. }
  45. nBlock.Split(currBlock);
  46. blocks.Insert(nBlkIndex + 1, currBlock);
  47. continue;
  48. }
  49. // If we have a block after the current one, set the limit address.
  50. ulong limitAddress = (ulong)code.Length - headerSize;
  51. if (nBlkIndex != blocks.Count)
  52. {
  53. Block nBlock = blocks[nBlkIndex];
  54. int nextIndex = nBlkIndex + 1;
  55. if (nBlock.Address < currBlock.Address && nextIndex < blocks.Count)
  56. {
  57. limitAddress = blocks[nextIndex].Address;
  58. }
  59. else if (nBlock.Address > currBlock.Address)
  60. {
  61. limitAddress = blocks[nBlkIndex].Address;
  62. }
  63. }
  64. FillBlock(code, currBlock, limitAddress, headerSize);
  65. if (currBlock.OpCodes.Count != 0)
  66. {
  67. // We should have blocks for all possible branch targets,
  68. // including those from SSY/PBK instructions.
  69. foreach (OpCodePush pushOp in currBlock.PushOpCodes)
  70. {
  71. GetBlock(pushOp.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 opBr)
  79. {
  80. currBlock.Branch = GetBlock(opBr.GetAbsoluteAddress());
  81. }
  82. else if (lastOp is OpCodeBranchIndir opBrIndir)
  83. {
  84. // An indirect branch could go anywhere, we don't know the target.
  85. // Those instructions are usually used on a switch to jump table
  86. // compiler optimization, and in those cases the possible targets
  87. // seems to be always right after the BRX itself. We can assume
  88. // that the possible targets are all the blocks in-between the
  89. // instruction right after the BRX, and the common target that
  90. // all the "cases" should eventually jump to, acting as the
  91. // switch break.
  92. Block firstTarget = GetBlock(currBlock.EndAddress);
  93. firstTarget.BrIndir = opBrIndir;
  94. opBrIndir.PossibleTargets.Add(firstTarget);
  95. }
  96. if (!IsUnconditionalBranch(lastOp))
  97. {
  98. currBlock.Next = GetBlock(currBlock.EndAddress);
  99. }
  100. }
  101. // Insert the new block on the list (sorted by address).
  102. if (blocks.Count != 0)
  103. {
  104. Block nBlock = blocks[nBlkIndex];
  105. blocks.Insert(nBlkIndex + (nBlock.Address < currBlock.Address ? 1 : 0), currBlock);
  106. }
  107. else
  108. {
  109. blocks.Add(currBlock);
  110. }
  111. // Do we have a block after the current one?
  112. if (!IsExit(currBlock.GetLastOp()) && currBlock.BrIndir != null)
  113. {
  114. bool targetVisited = visited.ContainsKey(currBlock.EndAddress);
  115. Block possibleTarget = GetBlock(currBlock.EndAddress);
  116. currBlock.BrIndir.PossibleTargets.Add(possibleTarget);
  117. if (!targetVisited)
  118. {
  119. possibleTarget.BrIndir = currBlock.BrIndir;
  120. }
  121. }
  122. }
  123. foreach (Block block in blocks.Where(x => x.PushOpCodes.Count != 0))
  124. {
  125. for (int pushOpIndex = 0; pushOpIndex < block.PushOpCodes.Count; pushOpIndex++)
  126. {
  127. PropagatePushOp(visited, block, pushOpIndex);
  128. }
  129. }
  130. return blocks.ToArray();
  131. }
  132. private static bool BinarySearch(List<Block> blocks, ulong address, out int index)
  133. {
  134. index = 0;
  135. int left = 0;
  136. int right = blocks.Count - 1;
  137. while (left <= right)
  138. {
  139. int size = right - left;
  140. int middle = left + (size >> 1);
  141. Block block = blocks[middle];
  142. index = middle;
  143. if (address >= block.Address && address < block.EndAddress)
  144. {
  145. return true;
  146. }
  147. if (address < block.Address)
  148. {
  149. right = middle - 1;
  150. }
  151. else
  152. {
  153. left = middle + 1;
  154. }
  155. }
  156. return false;
  157. }
  158. private static void FillBlock(
  159. Span<byte> code,
  160. Block block,
  161. ulong limitAddress,
  162. ulong startAddress)
  163. {
  164. ulong address = block.Address;
  165. do
  166. {
  167. if (address + 7 >= limitAddress)
  168. {
  169. break;
  170. }
  171. // Ignore scheduling instructions, which are written every 32 bytes.
  172. if ((address & 0x1f) == 0)
  173. {
  174. address += 8;
  175. continue;
  176. }
  177. uint word0 = BinaryPrimitives.ReadUInt32LittleEndian(code.Slice((int)(startAddress + address)));
  178. uint word1 = BinaryPrimitives.ReadUInt32LittleEndian(code.Slice((int)(startAddress + address + 4)));
  179. ulong opAddress = address;
  180. address += 8;
  181. long opCode = word0 | (long)word1 << 32;
  182. (InstEmitter emitter, Type opCodeType) = OpCodeTable.GetEmitter(opCode);
  183. if (emitter == null)
  184. {
  185. // TODO: Warning, illegal encoding.
  186. block.OpCodes.Add(new OpCode(null, opAddress, opCode));
  187. continue;
  188. }
  189. OpCode op = MakeOpCode(opCodeType, emitter, opAddress, opCode);
  190. block.OpCodes.Add(op);
  191. }
  192. while (!IsBranch(block.GetLastOp()));
  193. block.EndAddress = address;
  194. block.UpdatePushOps();
  195. }
  196. private static bool IsUnconditionalBranch(OpCode opCode)
  197. {
  198. return IsUnconditional(opCode) && IsBranch(opCode);
  199. }
  200. private static bool IsUnconditional(OpCode opCode)
  201. {
  202. if (opCode is OpCodeExit op && op.Condition != Condition.Always)
  203. {
  204. return false;
  205. }
  206. return opCode.Predicate.Index == RegisterConsts.PredicateTrueIndex && !opCode.InvertPredicate;
  207. }
  208. private static bool IsBranch(OpCode opCode)
  209. {
  210. return (opCode is OpCodeBranch opBranch && !opBranch.PushTarget) ||
  211. opCode is OpCodeBranchIndir ||
  212. opCode is OpCodeBranchPop ||
  213. opCode is OpCodeExit;
  214. }
  215. private static bool IsExit(OpCode opCode)
  216. {
  217. return opCode is OpCodeExit;
  218. }
  219. private static OpCode MakeOpCode(Type type, InstEmitter emitter, ulong address, long opCode)
  220. {
  221. if (type == null)
  222. {
  223. throw new ArgumentNullException(nameof(type));
  224. }
  225. OpActivator createInstance = _opActivators.GetOrAdd(type, CacheOpActivator);
  226. return (OpCode)createInstance(emitter, address, opCode);
  227. }
  228. private static OpActivator CacheOpActivator(Type type)
  229. {
  230. Type[] argTypes = new Type[] { typeof(InstEmitter), typeof(ulong), typeof(long) };
  231. DynamicMethod mthd = new DynamicMethod($"Make{type.Name}", type, argTypes);
  232. ILGenerator generator = mthd.GetILGenerator();
  233. generator.Emit(OpCodes.Ldarg_0);
  234. generator.Emit(OpCodes.Ldarg_1);
  235. generator.Emit(OpCodes.Ldarg_2);
  236. generator.Emit(OpCodes.Newobj, type.GetConstructor(argTypes));
  237. generator.Emit(OpCodes.Ret);
  238. return (OpActivator)mthd.CreateDelegate(typeof(OpActivator));
  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. if (pbs.Block == null || visited.Add(pbs.Block))
  294. {
  295. workQueue.Push(pbs);
  296. }
  297. }
  298. Push(new PathBlockState(currBlock));
  299. while (workQueue.TryPop(out PathBlockState pbs))
  300. {
  301. if (pbs.ReturningFromVisit)
  302. {
  303. pbs.RestoreStackState(branchStack);
  304. continue;
  305. }
  306. Block current = pbs.Block;
  307. int pushOpsCount = current.PushOpCodes.Count;
  308. if (pushOpsCount != 0)
  309. {
  310. Push(new PathBlockState(branchStack.Count));
  311. for (int index = pushOpIndex; index < pushOpsCount; index++)
  312. {
  313. branchStack.Push(current.PushOpCodes[index].GetAbsoluteAddress());
  314. }
  315. }
  316. pushOpIndex = 0;
  317. if (current.Next != null)
  318. {
  319. Push(new PathBlockState(current.Next));
  320. }
  321. if (current.Branch != null)
  322. {
  323. Push(new PathBlockState(current.Branch));
  324. }
  325. else if (current.GetLastOp() is OpCodeBranchIndir brIndir)
  326. {
  327. foreach (Block possibleTarget in brIndir.PossibleTargets)
  328. {
  329. Push(new PathBlockState(possibleTarget));
  330. }
  331. }
  332. else if (current.GetLastOp() is OpCodeBranchPop op)
  333. {
  334. ulong syncAddress = branchStack.Pop();
  335. if (branchStack.Count == 0)
  336. {
  337. branchStack.Push(syncAddress);
  338. op.Targets.Add(pushOp, op.Targets.Count);
  339. pushOp.PopOps.TryAdd(op, Local());
  340. }
  341. else
  342. {
  343. Push(new PathBlockState(syncAddress));
  344. Push(new PathBlockState(blocks[syncAddress]));
  345. }
  346. }
  347. }
  348. }
  349. }
  350. }