Decoder.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623
  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, out bool hasBindless)
  11. {
  12. hasBindless = false;
  13. List<Block[]> funcs = new List<Block[]>();
  14. Queue<ulong> funcQueue = new Queue<ulong>();
  15. HashSet<ulong> funcVisited = new HashSet<ulong>();
  16. void EnqueueFunction(ulong funcAddress)
  17. {
  18. if (funcVisited.Add(funcAddress))
  19. {
  20. funcQueue.Enqueue(funcAddress);
  21. }
  22. }
  23. funcQueue.Enqueue(0);
  24. while (funcQueue.TryDequeue(out ulong funcAddress))
  25. {
  26. List<Block> blocks = new List<Block>();
  27. Queue<Block> workQueue = new Queue<Block>();
  28. Dictionary<ulong, Block> visited = new Dictionary<ulong, Block>();
  29. Block GetBlock(ulong blkAddress)
  30. {
  31. if (!visited.TryGetValue(blkAddress, out Block block))
  32. {
  33. block = new Block(blkAddress);
  34. workQueue.Enqueue(block);
  35. visited.Add(blkAddress, block);
  36. }
  37. return block;
  38. }
  39. GetBlock(funcAddress);
  40. bool hasNewTarget;
  41. do
  42. {
  43. while (workQueue.TryDequeue(out Block currBlock))
  44. {
  45. // Check if the current block is inside another block.
  46. if (BinarySearch(blocks, currBlock.Address, out int nBlkIndex))
  47. {
  48. Block nBlock = blocks[nBlkIndex];
  49. if (nBlock.Address == currBlock.Address)
  50. {
  51. throw new InvalidOperationException("Found duplicate block address on the list.");
  52. }
  53. nBlock.Split(currBlock);
  54. blocks.Insert(nBlkIndex + 1, currBlock);
  55. continue;
  56. }
  57. // If we have a block after the current one, set the limit address.
  58. ulong limitAddress = ulong.MaxValue;
  59. if (nBlkIndex != blocks.Count)
  60. {
  61. Block nBlock = blocks[nBlkIndex];
  62. int nextIndex = nBlkIndex + 1;
  63. if (nBlock.Address < currBlock.Address && nextIndex < blocks.Count)
  64. {
  65. limitAddress = blocks[nextIndex].Address;
  66. }
  67. else if (nBlock.Address > currBlock.Address)
  68. {
  69. limitAddress = blocks[nBlkIndex].Address;
  70. }
  71. }
  72. FillBlock(gpuAccessor, currBlock, limitAddress, startAddress, out bool blockHasBindless);
  73. hasBindless |= blockHasBindless;
  74. if (currBlock.OpCodes.Count != 0)
  75. {
  76. // We should have blocks for all possible branch targets,
  77. // including those from SSY/PBK instructions.
  78. foreach (OpCodePush pushOp in currBlock.PushOpCodes)
  79. {
  80. GetBlock(pushOp.GetAbsoluteAddress());
  81. }
  82. // Set child blocks. "Branch" is the block the branch instruction
  83. // points to (when taken), "Next" is the block at the next address,
  84. // executed when the branch is not taken. For Unconditional Branches
  85. // or end of program, Next is null.
  86. OpCode lastOp = currBlock.GetLastOp();
  87. if (lastOp is OpCodeBranch opBr)
  88. {
  89. if (lastOp.Emitter == InstEmit.Cal)
  90. {
  91. EnqueueFunction(opBr.GetAbsoluteAddress());
  92. }
  93. else
  94. {
  95. currBlock.Branch = GetBlock(opBr.GetAbsoluteAddress());
  96. }
  97. }
  98. if (!IsUnconditionalBranch(lastOp))
  99. {
  100. currBlock.Next = GetBlock(currBlock.EndAddress);
  101. }
  102. }
  103. // Insert the new block on the list (sorted by address).
  104. if (blocks.Count != 0)
  105. {
  106. Block nBlock = blocks[nBlkIndex];
  107. blocks.Insert(nBlkIndex + (nBlock.Address < currBlock.Address ? 1 : 0), currBlock);
  108. }
  109. else
  110. {
  111. blocks.Add(currBlock);
  112. }
  113. }
  114. // Propagate SSY/PBK addresses into their uses (SYNC/BRK).
  115. foreach (Block block in blocks.Where(x => x.PushOpCodes.Count != 0))
  116. {
  117. for (int pushOpIndex = 0; pushOpIndex < block.PushOpCodes.Count; pushOpIndex++)
  118. {
  119. PropagatePushOp(visited, block, pushOpIndex);
  120. }
  121. }
  122. // Try to find target for BRX (indirect branch) instructions.
  123. hasNewTarget = false;
  124. foreach (Block block in blocks)
  125. {
  126. if (block.GetLastOp() is OpCodeBranchIndir opBrIndir && opBrIndir.PossibleTargets.Count == 0)
  127. {
  128. ulong baseOffset = opBrIndir.Address + 8 + (ulong)opBrIndir.Offset;
  129. // An indirect branch could go anywhere,
  130. // try to get the possible target offsets from the constant buffer.
  131. (int cbBaseOffset, int cbOffsetsCount) = FindBrxTargetRange(block, opBrIndir.Ra.Index);
  132. if (cbOffsetsCount != 0)
  133. {
  134. hasNewTarget = true;
  135. }
  136. for (int i = 0; i < cbOffsetsCount; i++)
  137. {
  138. uint targetOffset = gpuAccessor.ConstantBuffer1Read(cbBaseOffset + i * 4);
  139. Block target = GetBlock(baseOffset + targetOffset);
  140. opBrIndir.PossibleTargets.Add(target);
  141. target.Predecessors.Add(block);
  142. }
  143. }
  144. }
  145. // If we discovered new branch targets from the BRX instruction,
  146. // we need another round of decoding to decode the new blocks.
  147. // Additionally, we may have more SSY/PBK targets to propagate,
  148. // and new BRX instructions.
  149. }
  150. while (hasNewTarget);
  151. funcs.Add(blocks.ToArray());
  152. }
  153. return funcs.ToArray();
  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. out bool hasBindless)
  187. {
  188. ulong address = block.Address;
  189. hasBindless = false;
  190. do
  191. {
  192. if (address + 7 >= limitAddress)
  193. {
  194. break;
  195. }
  196. // Ignore scheduling instructions, which are written every 32 bytes.
  197. if ((address & 0x1f) == 0)
  198. {
  199. address += 8;
  200. continue;
  201. }
  202. ulong opAddress = address;
  203. address += 8;
  204. long opCode = gpuAccessor.MemoryRead<long>(startAddress + opAddress);
  205. (InstEmitter emitter, OpCodeTable.MakeOp makeOp) = OpCodeTable.GetEmitter(opCode);
  206. if (emitter == null)
  207. {
  208. // TODO: Warning, illegal encoding.
  209. block.OpCodes.Add(new OpCode(null, opAddress, opCode));
  210. continue;
  211. }
  212. if (makeOp == null)
  213. {
  214. throw new ArgumentNullException(nameof(makeOp));
  215. }
  216. OpCode op = makeOp(emitter, opAddress, opCode);
  217. // We check these patterns to figure out the presence of bindless access
  218. hasBindless |= (op is OpCodeImage image && image.IsBindless) ||
  219. (op is OpCodeTxd txd && txd.IsBindless) ||
  220. (op is OpCodeTld4B) ||
  221. (emitter == InstEmit.TexB) ||
  222. (emitter == InstEmit.TldB) ||
  223. (emitter == InstEmit.TmmlB) ||
  224. (emitter == InstEmit.TxqB);
  225. block.OpCodes.Add(op);
  226. }
  227. while (!IsControlFlowChange(block.GetLastOp()));
  228. block.EndAddress = address;
  229. block.UpdatePushOps();
  230. }
  231. private static bool IsUnconditionalBranch(OpCode opCode)
  232. {
  233. return IsUnconditional(opCode) && IsControlFlowChange(opCode);
  234. }
  235. private static bool IsUnconditional(OpCode opCode)
  236. {
  237. if (opCode is OpCodeExit op && op.Condition != Condition.Always)
  238. {
  239. return false;
  240. }
  241. return opCode.Predicate.Index == RegisterConsts.PredicateTrueIndex && !opCode.InvertPredicate;
  242. }
  243. private static bool IsControlFlowChange(OpCode opCode)
  244. {
  245. return (opCode is OpCodeBranch opBranch && !opBranch.PushTarget) ||
  246. opCode is OpCodeBranchIndir ||
  247. opCode is OpCodeBranchPop ||
  248. opCode is OpCodeExit;
  249. }
  250. private static (int, int) FindBrxTargetRange(Block block, int brxReg)
  251. {
  252. // Try to match the following pattern:
  253. //
  254. // IMNMX.U32 Rx, Rx, UpperBound, PT
  255. // SHL Rx, Rx, 0x2
  256. // LDC Rx, c[0x1][Rx+BaseOffset]
  257. //
  258. // Here, Rx is an arbitrary register, "UpperBound" and "BaseOffset" are constants.
  259. // The above pattern is assumed to be generated by the compiler before BRX,
  260. // as the instruction is usually used to implement jump tables for switch statement optimizations.
  261. // On a successful match, "BaseOffset" is the offset in bytes where the jump offsets are
  262. // located on the constant buffer, and "UpperBound" is the total number of offsets for the BRX, minus 1.
  263. HashSet<Block> visited = new HashSet<Block>();
  264. var ldcLocation = FindFirstRegWrite(visited, new BlockLocation(block, block.OpCodes.Count - 1), brxReg);
  265. if (ldcLocation.Block == null || ldcLocation.Block.OpCodes[ldcLocation.Index] is not OpCodeLdc opLdc)
  266. {
  267. return (0, 0);
  268. }
  269. if (opLdc.Slot != 1 || opLdc.IndexMode != CbIndexMode.Default)
  270. {
  271. return (0, 0);
  272. }
  273. var shlLocation = FindFirstRegWrite(visited, ldcLocation, opLdc.Ra.Index);
  274. if (shlLocation.Block == null || shlLocation.Block.OpCodes[shlLocation.Index] is not OpCodeAluImm opShl)
  275. {
  276. return (0, 0);
  277. }
  278. if (opShl.Emitter != InstEmit.Shl || opShl.Immediate != 2)
  279. {
  280. return (0, 0);
  281. }
  282. var imnmxLocation = FindFirstRegWrite(visited, shlLocation, opShl.Ra.Index);
  283. if (imnmxLocation.Block == null || imnmxLocation.Block.OpCodes[imnmxLocation.Index] is not OpCodeAluImm opImnmx)
  284. {
  285. return (0, 0);
  286. }
  287. bool isImnmxS32 = opImnmx.RawOpCode.Extract(48);
  288. if (opImnmx.Emitter != InstEmit.Imnmx || isImnmxS32 || !opImnmx.Predicate39.IsPT || opImnmx.InvertP)
  289. {
  290. return (0, 0);
  291. }
  292. return (opLdc.Offset, opImnmx.Immediate + 1);
  293. }
  294. private struct BlockLocation
  295. {
  296. public Block Block { get; }
  297. public int Index { get; }
  298. public BlockLocation(Block block, int index)
  299. {
  300. Block = block;
  301. Index = index;
  302. }
  303. }
  304. private static BlockLocation FindFirstRegWrite(HashSet<Block> visited, BlockLocation location, int regIndex)
  305. {
  306. Queue<BlockLocation> toVisit = new Queue<BlockLocation>();
  307. toVisit.Enqueue(location);
  308. visited.Add(location.Block);
  309. while (toVisit.TryDequeue(out var currentLocation))
  310. {
  311. Block block = currentLocation.Block;
  312. for (int i = currentLocation.Index - 1; i >= 0; i--)
  313. {
  314. if (WritesToRegister(block.OpCodes[i], regIndex))
  315. {
  316. return new BlockLocation(block, i);
  317. }
  318. }
  319. foreach (Block predecessor in block.Predecessors)
  320. {
  321. if (visited.Add(predecessor))
  322. {
  323. toVisit.Enqueue(new BlockLocation(predecessor, predecessor.OpCodes.Count));
  324. }
  325. }
  326. }
  327. return new BlockLocation(null, 0);
  328. }
  329. private static bool WritesToRegister(OpCode opCode, int regIndex)
  330. {
  331. // Predicate instruction only ever writes to predicate, so we shouldn't check those.
  332. if (opCode.Emitter == InstEmit.Fsetp ||
  333. opCode.Emitter == InstEmit.Hsetp2 ||
  334. opCode.Emitter == InstEmit.Isetp ||
  335. opCode.Emitter == InstEmit.R2p)
  336. {
  337. return false;
  338. }
  339. return opCode is IOpCodeRd opRd && opRd.Rd.Index == regIndex;
  340. }
  341. private enum MergeType
  342. {
  343. Brk = 0,
  344. Sync = 1
  345. }
  346. private struct PathBlockState
  347. {
  348. public Block Block { get; }
  349. private enum RestoreType
  350. {
  351. None,
  352. PopPushOp,
  353. PushBranchOp
  354. }
  355. private RestoreType _restoreType;
  356. private ulong _restoreValue;
  357. private MergeType _restoreMergeType;
  358. public bool ReturningFromVisit => _restoreType != RestoreType.None;
  359. public PathBlockState(Block block)
  360. {
  361. Block = block;
  362. _restoreType = RestoreType.None;
  363. _restoreValue = 0;
  364. _restoreMergeType = default;
  365. }
  366. public PathBlockState(int oldStackSize)
  367. {
  368. Block = null;
  369. _restoreType = RestoreType.PopPushOp;
  370. _restoreValue = (ulong)oldStackSize;
  371. _restoreMergeType = default;
  372. }
  373. public PathBlockState(ulong syncAddress, MergeType mergeType)
  374. {
  375. Block = null;
  376. _restoreType = RestoreType.PushBranchOp;
  377. _restoreValue = syncAddress;
  378. _restoreMergeType = mergeType;
  379. }
  380. public void RestoreStackState(Stack<(ulong, MergeType)> branchStack)
  381. {
  382. if (_restoreType == RestoreType.PushBranchOp)
  383. {
  384. branchStack.Push((_restoreValue, _restoreMergeType));
  385. }
  386. else if (_restoreType == RestoreType.PopPushOp)
  387. {
  388. while (branchStack.Count > (uint)_restoreValue)
  389. {
  390. branchStack.Pop();
  391. }
  392. }
  393. }
  394. }
  395. private static void PropagatePushOp(Dictionary<ulong, Block> blocks, Block currBlock, int pushOpIndex)
  396. {
  397. OpCodePush pushOp = currBlock.PushOpCodes[pushOpIndex];
  398. Block target = blocks[pushOp.GetAbsoluteAddress()];
  399. Stack<PathBlockState> workQueue = new Stack<PathBlockState>();
  400. HashSet<Block> visited = new HashSet<Block>();
  401. Stack<(ulong, MergeType)> branchStack = new Stack<(ulong, MergeType)>();
  402. void Push(PathBlockState pbs)
  403. {
  404. // When block is null, this means we are pushing a restore operation.
  405. // Restore operations are used to undo the work done inside a block
  406. // when we return from it, for example it pops addresses pushed by
  407. // SSY/PBK instructions inside the block, and pushes addresses poped
  408. // by SYNC/BRK.
  409. // For blocks, if it's already visited, we just ignore to avoid going
  410. // around in circles and getting stuck here.
  411. if (pbs.Block == null || !visited.Contains(pbs.Block))
  412. {
  413. workQueue.Push(pbs);
  414. }
  415. }
  416. Push(new PathBlockState(currBlock));
  417. while (workQueue.TryPop(out PathBlockState pbs))
  418. {
  419. if (pbs.ReturningFromVisit)
  420. {
  421. pbs.RestoreStackState(branchStack);
  422. continue;
  423. }
  424. Block current = pbs.Block;
  425. // If the block was already processed, we just ignore it, otherwise
  426. // we would push the same child blocks of an already processed block,
  427. // and go around in circles until memory is exhausted.
  428. if (!visited.Add(current))
  429. {
  430. continue;
  431. }
  432. int pushOpsCount = current.PushOpCodes.Count;
  433. if (pushOpsCount != 0)
  434. {
  435. Push(new PathBlockState(branchStack.Count));
  436. for (int index = pushOpIndex; index < pushOpsCount; index++)
  437. {
  438. OpCodePush currentPushOp = current.PushOpCodes[index];
  439. MergeType pushMergeType = currentPushOp.Emitter == InstEmit.Ssy ? MergeType.Sync : MergeType.Brk;
  440. branchStack.Push((currentPushOp.GetAbsoluteAddress(), pushMergeType));
  441. }
  442. }
  443. pushOpIndex = 0;
  444. if (current.Next != null)
  445. {
  446. Push(new PathBlockState(current.Next));
  447. }
  448. if (current.Branch != null)
  449. {
  450. Push(new PathBlockState(current.Branch));
  451. }
  452. else if (current.GetLastOp() is OpCodeBranchIndir brIndir)
  453. {
  454. // By adding them in descending order (sorted by address), we process the blocks
  455. // in order (of ascending address), since we work with a LIFO.
  456. foreach (Block possibleTarget in brIndir.PossibleTargets.OrderByDescending(x => x.Address))
  457. {
  458. Push(new PathBlockState(possibleTarget));
  459. }
  460. }
  461. else if (current.GetLastOp() is OpCodeBranchPop op)
  462. {
  463. MergeType popMergeType = op.Emitter == InstEmit.Sync ? MergeType.Sync : MergeType.Brk;
  464. bool found = true;
  465. ulong targetAddress = 0UL;
  466. MergeType mergeType;
  467. do
  468. {
  469. if (branchStack.Count == 0)
  470. {
  471. found = false;
  472. break;
  473. }
  474. (targetAddress, mergeType) = branchStack.Pop();
  475. // Push the target address (this will be used to push the address
  476. // back into the SSY/PBK stack when we return from that block),
  477. Push(new PathBlockState(targetAddress, mergeType));
  478. }
  479. while (mergeType != popMergeType);
  480. // Make sure we found the correct address,
  481. // the push and pop instruction types must match, so:
  482. // - BRK can only consume addresses pushed by PBK.
  483. // - SYNC can only consume addresses pushed by SSY.
  484. if (found)
  485. {
  486. if (branchStack.Count == 0)
  487. {
  488. // If the entire stack was consumed, then the current pop instruction
  489. // just consumed the address from our push instruction.
  490. if (op.Targets.TryAdd(pushOp, op.Targets.Count))
  491. {
  492. pushOp.PopOps.Add(op, Local());
  493. target.Predecessors.Add(current);
  494. }
  495. }
  496. else
  497. {
  498. // Push the block itself into the work "queue" (well, it's a stack)
  499. // for processing.
  500. Push(new PathBlockState(blocks[targetAddress]));
  501. }
  502. }
  503. }
  504. }
  505. }
  506. }
  507. }