StructuredProgramContext.cs 11 KB

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