Decoder.cs 15 KB

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