StructuredProgramContext.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  1. using Ryujinx.Graphics.Shader.IntermediateRepresentation;
  2. using Ryujinx.Graphics.Shader.Translation;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Numerics;
  6. using static Ryujinx.Graphics.Shader.StructuredIr.AstHelper;
  7. namespace Ryujinx.Graphics.Shader.StructuredIr
  8. {
  9. class StructuredProgramContext
  10. {
  11. private HashSet<BasicBlock> _loopTails;
  12. private Stack<(AstBlock Block, int CurrEndIndex, int LoopEndIndex)> _blockStack;
  13. private Dictionary<Operand, AstOperand> _localsMap;
  14. private Dictionary<int, AstAssignment> _gotoTempAsgs;
  15. private List<GotoStatement> _gotos;
  16. private AstBlock _currBlock;
  17. private int _currEndIndex;
  18. private int _loopEndIndex;
  19. public StructuredFunction CurrentFunction { get; private set; }
  20. public StructuredProgramInfo Info { get; }
  21. public ShaderDefinitions Definitions { get; }
  22. public ResourceManager ResourceManager { get; }
  23. public bool DebugMode { get; }
  24. public StructuredProgramContext(
  25. AttributeUsage attributeUsage,
  26. ShaderDefinitions definitions,
  27. ResourceManager resourceManager,
  28. bool precise,
  29. bool debugMode)
  30. {
  31. Info = new StructuredProgramInfo(precise);
  32. Definitions = definitions;
  33. ResourceManager = resourceManager;
  34. DebugMode = debugMode;
  35. if (definitions.GpPassthrough)
  36. {
  37. int passthroughAttributes = attributeUsage.PassthroughAttributes;
  38. while (passthroughAttributes != 0)
  39. {
  40. int index = BitOperations.TrailingZeroCount(passthroughAttributes);
  41. Info.IoDefinitions.Add(new IoDefinition(StorageKind.Input, IoVariable.UserDefined, index));
  42. passthroughAttributes &= ~(1 << index);
  43. }
  44. Info.IoDefinitions.Add(new IoDefinition(StorageKind.Input, IoVariable.Position));
  45. Info.IoDefinitions.Add(new IoDefinition(StorageKind.Input, IoVariable.PointSize));
  46. Info.IoDefinitions.Add(new IoDefinition(StorageKind.Input, IoVariable.ClipDistance));
  47. }
  48. }
  49. public void EnterFunction(
  50. int blocksCount,
  51. string name,
  52. AggregateType returnType,
  53. AggregateType[] inArguments,
  54. AggregateType[] outArguments)
  55. {
  56. _loopTails = [];
  57. _blockStack = new Stack<(AstBlock, int, int)>();
  58. _localsMap = new Dictionary<Operand, AstOperand>();
  59. _gotoTempAsgs = new Dictionary<int, AstAssignment>();
  60. _gotos = [];
  61. _currBlock = new AstBlock(AstBlockType.Main);
  62. _currEndIndex = blocksCount;
  63. _loopEndIndex = blocksCount;
  64. CurrentFunction = new StructuredFunction(_currBlock, name, returnType, inArguments, outArguments);
  65. }
  66. public void LeaveFunction()
  67. {
  68. Info.Functions.Add(CurrentFunction);
  69. }
  70. public void EnterBlock(BasicBlock block)
  71. {
  72. while (_currEndIndex == block.Index)
  73. {
  74. (_currBlock, _currEndIndex, _loopEndIndex) = _blockStack.Pop();
  75. }
  76. if (_gotoTempAsgs.TryGetValue(block.Index, out AstAssignment gotoTempAsg))
  77. {
  78. AddGotoTempReset(block, gotoTempAsg);
  79. }
  80. LookForDoWhileStatements(block);
  81. }
  82. public void LeaveBlock(BasicBlock block, Operation branchOp)
  83. {
  84. LookForIfStatements(block, branchOp);
  85. }
  86. private void LookForDoWhileStatements(BasicBlock block)
  87. {
  88. // Check if we have any predecessor whose index is greater than the
  89. // current block, this indicates a loop.
  90. bool done = false;
  91. foreach (BasicBlock predecessor in block.Predecessors.OrderByDescending(x => x.Index))
  92. {
  93. // If not a loop, break.
  94. if (predecessor.Index < block.Index)
  95. {
  96. break;
  97. }
  98. // Check if we can create a do-while loop here (only possible if the loop end
  99. // falls inside the current scope), if not add a goto instead.
  100. if (predecessor.Index < _currEndIndex && !done)
  101. {
  102. // Create do-while loop block. We must avoid inserting a goto at the end
  103. // of the loop later, when the tail block is processed. So we add the predecessor
  104. // to a list of loop tails to prevent it from being processed later.
  105. Operation branchOp = (Operation)predecessor.GetLastOp();
  106. NewBlock(AstBlockType.DoWhile, branchOp, predecessor.Index + 1);
  107. _loopTails.Add(predecessor);
  108. done = true;
  109. }
  110. else
  111. {
  112. // Failed to create loop. Since this block is the loop head, we reset the
  113. // goto condition variable here. The variable is always reset on the jump
  114. // target, and this block is the jump target for some loop.
  115. AddGotoTempReset(block, GetGotoTempAsg(block.Index));
  116. break;
  117. }
  118. }
  119. }
  120. private void LookForIfStatements(BasicBlock block, Operation branchOp)
  121. {
  122. if (block.Branch == null)
  123. {
  124. return;
  125. }
  126. // We can only enclose the "if" when the branch lands before
  127. // the end of the current block. If the current enclosing block
  128. // is not a loop, then we can also do so if the branch lands
  129. // right at the end of the current block. When it is a loop,
  130. // this is not valid as the loop condition would be evaluated,
  131. // and it could erroneously jump back to the start of the loop.
  132. bool inRange =
  133. block.Branch.Index < _currEndIndex ||
  134. (block.Branch.Index == _currEndIndex && block.Branch.Index < _loopEndIndex);
  135. bool isLoop = block.Branch.Index <= block.Index;
  136. if (inRange && !isLoop)
  137. {
  138. NewBlock(AstBlockType.If, branchOp, block.Branch.Index);
  139. }
  140. else if (!_loopTails.Contains(block))
  141. {
  142. AstAssignment gotoTempAsg = GetGotoTempAsg(block.Branch.Index);
  143. // We use DoWhile type here, as the condition should be true for
  144. // unconditional branches, or it should jump if the condition is true otherwise.
  145. IAstNode cond = GetBranchCond(AstBlockType.DoWhile, branchOp);
  146. AddNode(Assign(gotoTempAsg.Destination, cond));
  147. AstOperation branch = new(branchOp.Inst);
  148. AddNode(branch);
  149. GotoStatement gotoStmt = new(branch, gotoTempAsg, isLoop);
  150. _gotos.Add(gotoStmt);
  151. }
  152. }
  153. private AstAssignment GetGotoTempAsg(int index)
  154. {
  155. if (_gotoTempAsgs.TryGetValue(index, out AstAssignment gotoTempAsg))
  156. {
  157. return gotoTempAsg;
  158. }
  159. AstOperand gotoTemp = NewTemp(AggregateType.Bool);
  160. gotoTempAsg = Assign(gotoTemp, Const(IrConsts.False));
  161. _gotoTempAsgs.Add(index, gotoTempAsg);
  162. return gotoTempAsg;
  163. }
  164. private void AddGotoTempReset(BasicBlock block, AstAssignment gotoTempAsg)
  165. {
  166. // If it was already added, we don't need to add it again.
  167. if (gotoTempAsg.Parent != null)
  168. {
  169. return;
  170. }
  171. AddNode(gotoTempAsg);
  172. // For block 0, we don't need to add the extra "reset" at the beginning,
  173. // because it is already the first node to be executed on the shader,
  174. // so it is reset to false by the "local" assignment anyway.
  175. if (block.Index != 0)
  176. {
  177. CurrentFunction.MainBlock.AddFirst(Assign(gotoTempAsg.Destination, Const(IrConsts.False)));
  178. }
  179. }
  180. private void NewBlock(AstBlockType type, Operation branchOp, int endIndex)
  181. {
  182. NewBlock(type, GetBranchCond(type, branchOp), endIndex);
  183. }
  184. private void NewBlock(AstBlockType type, IAstNode cond, int endIndex)
  185. {
  186. AstBlock childBlock = new(type, cond);
  187. AddNode(childBlock);
  188. _blockStack.Push((_currBlock, _currEndIndex, _loopEndIndex));
  189. _currBlock = childBlock;
  190. _currEndIndex = endIndex;
  191. if (type == AstBlockType.DoWhile)
  192. {
  193. _loopEndIndex = endIndex;
  194. }
  195. }
  196. private IAstNode GetBranchCond(AstBlockType type, Operation branchOp)
  197. {
  198. IAstNode cond;
  199. if (branchOp.Inst == Instruction.Branch)
  200. {
  201. // If the branch is not conditional, the condition is a constant.
  202. // For if it's false (always jump over, if block never executed).
  203. // For loops it's always true (always loop).
  204. cond = Const(type == AstBlockType.If ? IrConsts.False : IrConsts.True);
  205. }
  206. else
  207. {
  208. cond = GetOperand(branchOp.GetSource(0));
  209. Instruction invInst = type == AstBlockType.If
  210. ? Instruction.BranchIfTrue
  211. : Instruction.BranchIfFalse;
  212. if (branchOp.Inst == invInst)
  213. {
  214. cond = new AstOperation(Instruction.LogicalNot, cond);
  215. }
  216. }
  217. return cond;
  218. }
  219. public void AddNode(IAstNode node)
  220. {
  221. _currBlock.Add(node);
  222. }
  223. public GotoStatement[] GetGotos()
  224. {
  225. return _gotos.ToArray();
  226. }
  227. public AstOperand NewTemp(AggregateType type)
  228. {
  229. AstOperand newTemp = Local(type);
  230. CurrentFunction.Locals.Add(newTemp);
  231. return newTemp;
  232. }
  233. public IAstNode GetOperandOrCbLoad(Operand operand)
  234. {
  235. if (operand.Type == OperandType.ConstantBuffer)
  236. {
  237. int cbufSlot = operand.GetCbufSlot();
  238. int cbufOffset = operand.GetCbufOffset();
  239. int binding = ResourceManager.GetConstantBufferBinding(cbufSlot);
  240. int vecIndex = cbufOffset >> 2;
  241. int elemIndex = cbufOffset & 3;
  242. ResourceManager.SetUsedConstantBufferBinding(binding);
  243. IAstNode[] sources =
  244. [
  245. new AstOperand(OperandType.Constant, binding),
  246. new AstOperand(OperandType.Constant, 0),
  247. new AstOperand(OperandType.Constant, vecIndex),
  248. new AstOperand(OperandType.Constant, elemIndex)
  249. ];
  250. return new AstOperation(Instruction.Load, StorageKind.ConstantBuffer, false, sources, sources.Length);
  251. }
  252. return GetOperand(operand);
  253. }
  254. public AstOperand GetOperand(Operand operand)
  255. {
  256. if (operand == null)
  257. {
  258. return null;
  259. }
  260. if (operand.Type != OperandType.LocalVariable)
  261. {
  262. return new AstOperand(operand);
  263. }
  264. if (!_localsMap.TryGetValue(operand, out AstOperand astOperand))
  265. {
  266. astOperand = new AstOperand(operand);
  267. _localsMap.Add(operand, astOperand);
  268. CurrentFunction.Locals.Add(astOperand);
  269. }
  270. return astOperand;
  271. }
  272. }
  273. }