OperandManager.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479
  1. using Ryujinx.Graphics.Shader.IntermediateRepresentation;
  2. using Ryujinx.Graphics.Shader.StructuredIr;
  3. using Ryujinx.Graphics.Shader.Translation;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Diagnostics;
  7. using static Ryujinx.Graphics.Shader.StructuredIr.InstructionInfo;
  8. namespace Ryujinx.Graphics.Shader.CodeGen.Glsl
  9. {
  10. class OperandManager
  11. {
  12. private static string[] _stagePrefixes = new string[] { "cp", "vp", "tcp", "tep", "gp", "fp" };
  13. private struct BuiltInAttribute
  14. {
  15. public string Name { get; }
  16. public VariableType Type { get; }
  17. public BuiltInAttribute(string name, VariableType type)
  18. {
  19. Name = name;
  20. Type = type;
  21. }
  22. }
  23. private static Dictionary<int, BuiltInAttribute> _builtInAttributes =
  24. new Dictionary<int, BuiltInAttribute>()
  25. {
  26. { AttributeConsts.TessLevelOuter0, new BuiltInAttribute("gl_TessLevelOuter[0]", VariableType.F32) },
  27. { AttributeConsts.TessLevelOuter1, new BuiltInAttribute("gl_TessLevelOuter[1]", VariableType.F32) },
  28. { AttributeConsts.TessLevelOuter2, new BuiltInAttribute("gl_TessLevelOuter[2]", VariableType.F32) },
  29. { AttributeConsts.TessLevelOuter3, new BuiltInAttribute("gl_TessLevelOuter[3]", VariableType.F32) },
  30. { AttributeConsts.TessLevelInner0, new BuiltInAttribute("gl_TessLevelInner[0]", VariableType.F32) },
  31. { AttributeConsts.TessLevelInner1, new BuiltInAttribute("gl_TessLevelInner[1]", VariableType.F32) },
  32. { AttributeConsts.Layer, new BuiltInAttribute("gl_Layer", VariableType.S32) },
  33. { AttributeConsts.PointSize, new BuiltInAttribute("gl_PointSize", VariableType.F32) },
  34. { AttributeConsts.PositionX, new BuiltInAttribute("gl_Position.x", VariableType.F32) },
  35. { AttributeConsts.PositionY, new BuiltInAttribute("gl_Position.y", VariableType.F32) },
  36. { AttributeConsts.PositionZ, new BuiltInAttribute("gl_Position.z", VariableType.F32) },
  37. { AttributeConsts.PositionW, new BuiltInAttribute("gl_Position.w", VariableType.F32) },
  38. { AttributeConsts.ClipDistance0, new BuiltInAttribute("gl_ClipDistance[0]", VariableType.F32) },
  39. { AttributeConsts.ClipDistance1, new BuiltInAttribute("gl_ClipDistance[1]", VariableType.F32) },
  40. { AttributeConsts.ClipDistance2, new BuiltInAttribute("gl_ClipDistance[2]", VariableType.F32) },
  41. { AttributeConsts.ClipDistance3, new BuiltInAttribute("gl_ClipDistance[3]", VariableType.F32) },
  42. { AttributeConsts.ClipDistance4, new BuiltInAttribute("gl_ClipDistance[4]", VariableType.F32) },
  43. { AttributeConsts.ClipDistance5, new BuiltInAttribute("gl_ClipDistance[5]", VariableType.F32) },
  44. { AttributeConsts.ClipDistance6, new BuiltInAttribute("gl_ClipDistance[6]", VariableType.F32) },
  45. { AttributeConsts.ClipDistance7, new BuiltInAttribute("gl_ClipDistance[7]", VariableType.F32) },
  46. { AttributeConsts.PointCoordX, new BuiltInAttribute("gl_PointCoord.x", VariableType.F32) },
  47. { AttributeConsts.PointCoordY, new BuiltInAttribute("gl_PointCoord.y", VariableType.F32) },
  48. { AttributeConsts.TessCoordX, new BuiltInAttribute("gl_TessCoord.x", VariableType.F32) },
  49. { AttributeConsts.TessCoordY, new BuiltInAttribute("gl_TessCoord.y", VariableType.F32) },
  50. { AttributeConsts.InstanceId, new BuiltInAttribute("gl_InstanceID", VariableType.S32) },
  51. { AttributeConsts.VertexId, new BuiltInAttribute("gl_VertexID", VariableType.S32) },
  52. { AttributeConsts.FrontFacing, new BuiltInAttribute("gl_FrontFacing", VariableType.Bool) },
  53. // Special.
  54. { AttributeConsts.FragmentOutputDepth, new BuiltInAttribute("gl_FragDepth", VariableType.F32) },
  55. { AttributeConsts.ThreadKill, new BuiltInAttribute("gl_HelperInvocation", VariableType.Bool) },
  56. { AttributeConsts.ThreadIdX, new BuiltInAttribute("gl_LocalInvocationID.x", VariableType.U32) },
  57. { AttributeConsts.ThreadIdY, new BuiltInAttribute("gl_LocalInvocationID.y", VariableType.U32) },
  58. { AttributeConsts.ThreadIdZ, new BuiltInAttribute("gl_LocalInvocationID.z", VariableType.U32) },
  59. { AttributeConsts.CtaIdX, new BuiltInAttribute("gl_WorkGroupID.x", VariableType.U32) },
  60. { AttributeConsts.CtaIdY, new BuiltInAttribute("gl_WorkGroupID.y", VariableType.U32) },
  61. { AttributeConsts.CtaIdZ, new BuiltInAttribute("gl_WorkGroupID.z", VariableType.U32) },
  62. { AttributeConsts.LaneId, new BuiltInAttribute(null, VariableType.U32) },
  63. { AttributeConsts.InvocationId, new BuiltInAttribute("gl_InvocationID", VariableType.S32) },
  64. { AttributeConsts.PrimitiveId, new BuiltInAttribute("gl_PrimitiveID", VariableType.S32) },
  65. { AttributeConsts.PatchVerticesIn, new BuiltInAttribute("gl_PatchVerticesIn", VariableType.S32) },
  66. { AttributeConsts.EqMask, new BuiltInAttribute(null, VariableType.U32) },
  67. { AttributeConsts.GeMask, new BuiltInAttribute(null, VariableType.U32) },
  68. { AttributeConsts.GtMask, new BuiltInAttribute(null, VariableType.U32) },
  69. { AttributeConsts.LeMask, new BuiltInAttribute(null, VariableType.U32) },
  70. { AttributeConsts.LtMask, new BuiltInAttribute(null, VariableType.U32) },
  71. // Support uniforms.
  72. { AttributeConsts.FragmentOutputIsBgraBase + 0, new BuiltInAttribute($"{DefaultNames.SupportBlockIsBgraName}[0]", VariableType.Bool) },
  73. { AttributeConsts.FragmentOutputIsBgraBase + 4, new BuiltInAttribute($"{DefaultNames.SupportBlockIsBgraName}[1]", VariableType.Bool) },
  74. { AttributeConsts.FragmentOutputIsBgraBase + 8, new BuiltInAttribute($"{DefaultNames.SupportBlockIsBgraName}[2]", VariableType.Bool) },
  75. { AttributeConsts.FragmentOutputIsBgraBase + 12, new BuiltInAttribute($"{DefaultNames.SupportBlockIsBgraName}[3]", VariableType.Bool) },
  76. { AttributeConsts.FragmentOutputIsBgraBase + 16, new BuiltInAttribute($"{DefaultNames.SupportBlockIsBgraName}[4]", VariableType.Bool) },
  77. { AttributeConsts.FragmentOutputIsBgraBase + 20, new BuiltInAttribute($"{DefaultNames.SupportBlockIsBgraName}[5]", VariableType.Bool) },
  78. { AttributeConsts.FragmentOutputIsBgraBase + 24, new BuiltInAttribute($"{DefaultNames.SupportBlockIsBgraName}[6]", VariableType.Bool) },
  79. { AttributeConsts.FragmentOutputIsBgraBase + 28, new BuiltInAttribute($"{DefaultNames.SupportBlockIsBgraName}[7]", VariableType.Bool) },
  80. { AttributeConsts.SupportBlockViewInverseX, new BuiltInAttribute($"{DefaultNames.SupportBlockViewportInverse}.x", VariableType.F32) },
  81. { AttributeConsts.SupportBlockViewInverseY, new BuiltInAttribute($"{DefaultNames.SupportBlockViewportInverse}.y", VariableType.F32) }
  82. };
  83. private Dictionary<AstOperand, string> _locals;
  84. public OperandManager()
  85. {
  86. _locals = new Dictionary<AstOperand, string>();
  87. }
  88. public string DeclareLocal(AstOperand operand)
  89. {
  90. string name = $"{DefaultNames.LocalNamePrefix}_{_locals.Count}";
  91. _locals.Add(operand, name);
  92. return name;
  93. }
  94. public string GetExpression(AstOperand operand, ShaderConfig config)
  95. {
  96. return operand.Type switch
  97. {
  98. OperandType.Argument => GetArgumentName(operand.Value),
  99. OperandType.Attribute => GetAttributeName(operand.Value, config, perPatch: false),
  100. OperandType.AttributePerPatch => GetAttributeName(operand.Value, config, perPatch: true),
  101. OperandType.Constant => NumberFormatter.FormatInt(operand.Value),
  102. OperandType.ConstantBuffer => GetConstantBufferName(operand, config),
  103. OperandType.LocalVariable => _locals[operand],
  104. OperandType.Undefined => DefaultNames.UndefinedName,
  105. _ => throw new ArgumentException($"Invalid operand type \"{operand.Type}\".")
  106. };
  107. }
  108. private static string GetConstantBufferName(AstOperand operand, ShaderConfig config)
  109. {
  110. return GetConstantBufferName(operand.CbufSlot, operand.CbufOffset, config.Stage, config.UsedFeatures.HasFlag(FeatureFlags.CbIndexing));
  111. }
  112. public static string GetConstantBufferName(int slot, int offset, ShaderStage stage, bool cbIndexable)
  113. {
  114. return $"{GetUbName(stage, slot, cbIndexable)}[{offset >> 2}].{GetSwizzleMask(offset & 3)}";
  115. }
  116. private static string GetVec4Indexed(string vectorName, string indexExpr, bool indexElement)
  117. {
  118. if (indexElement)
  119. {
  120. return $"{vectorName}[{indexExpr}]";
  121. }
  122. string result = $"{vectorName}.x";
  123. for (int i = 1; i < 4; i++)
  124. {
  125. result = $"(({indexExpr}) == {i}) ? ({vectorName}.{GetSwizzleMask(i)}) : ({result})";
  126. }
  127. return $"({result})";
  128. }
  129. public static string GetConstantBufferName(int slot, string offsetExpr, ShaderStage stage, bool cbIndexable, bool indexElement)
  130. {
  131. return GetVec4Indexed(GetUbName(stage, slot, cbIndexable) + $"[{offsetExpr} >> 2]", offsetExpr + " & 3", indexElement);
  132. }
  133. public static string GetConstantBufferName(string slotExpr, string offsetExpr, ShaderStage stage, bool indexElement)
  134. {
  135. return GetVec4Indexed(GetUbName(stage, slotExpr) + $"[{offsetExpr} >> 2]", offsetExpr + " & 3", indexElement);
  136. }
  137. public static string GetOutAttributeName(int value, ShaderConfig config, bool perPatch)
  138. {
  139. return GetAttributeName(value, config, perPatch, isOutAttr: true);
  140. }
  141. public static string GetAttributeName(int value, ShaderConfig config, bool perPatch, bool isOutAttr = false, string indexExpr = "0")
  142. {
  143. if ((value & AttributeConsts.LoadOutputMask) != 0)
  144. {
  145. isOutAttr = true;
  146. }
  147. value &= AttributeConsts.Mask & ~3;
  148. char swzMask = GetSwizzleMask((value >> 2) & 3);
  149. if (value >= AttributeConsts.UserAttributeBase && value < AttributeConsts.UserAttributeEnd)
  150. {
  151. value -= AttributeConsts.UserAttributeBase;
  152. string prefix = isOutAttr
  153. ? DefaultNames.OAttributePrefix
  154. : DefaultNames.IAttributePrefix;
  155. bool indexable = config.UsedFeatures.HasFlag(isOutAttr ? FeatureFlags.OaIndexing : FeatureFlags.IaIndexing);
  156. if (!indexable && perPatch)
  157. {
  158. prefix = DefaultNames.PerPatchAttributePrefix;
  159. }
  160. if (indexable)
  161. {
  162. string name = prefix;
  163. if (config.Stage == ShaderStage.Geometry && !isOutAttr)
  164. {
  165. name += $"[{indexExpr}]";
  166. }
  167. return name + $"[{(value >> 4)}]." + swzMask;
  168. }
  169. else if (config.TransformFeedbackEnabled && (config.Stage != ShaderStage.Vertex || isOutAttr))
  170. {
  171. string name = $"{prefix}{(value >> 4)}_{swzMask}";
  172. if (!perPatch && IsArrayAttribute(config.Stage, isOutAttr))
  173. {
  174. name += isOutAttr ? "[gl_InvocationID]" : $"[{indexExpr}]";
  175. }
  176. return name;
  177. }
  178. else
  179. {
  180. string name = $"{prefix}{(value >> 4)}";
  181. if (!perPatch && IsArrayAttribute(config.Stage, isOutAttr))
  182. {
  183. name += isOutAttr ? "[gl_InvocationID]" : $"[{indexExpr}]";
  184. }
  185. return name + '.' + swzMask;
  186. }
  187. }
  188. else
  189. {
  190. if (value >= AttributeConsts.FragmentOutputColorBase && value < AttributeConsts.FragmentOutputColorEnd)
  191. {
  192. value -= AttributeConsts.FragmentOutputColorBase;
  193. return $"{DefaultNames.OAttributePrefix}{(value >> 4)}.{swzMask}";
  194. }
  195. else if (_builtInAttributes.TryGetValue(value, out BuiltInAttribute builtInAttr))
  196. {
  197. string subgroupMask = value switch
  198. {
  199. AttributeConsts.EqMask => "Eq",
  200. AttributeConsts.GeMask => "Ge",
  201. AttributeConsts.GtMask => "Gt",
  202. AttributeConsts.LeMask => "Le",
  203. AttributeConsts.LtMask => "Lt",
  204. _ => null
  205. };
  206. if (subgroupMask != null)
  207. {
  208. return config.GpuAccessor.QueryHostSupportsShaderBallot()
  209. ? $"unpackUint2x32(gl_SubGroup{subgroupMask}MaskARB).x"
  210. : $"gl_Subgroup{subgroupMask}Mask.x";
  211. }
  212. else if (value == AttributeConsts.LaneId)
  213. {
  214. return config.GpuAccessor.QueryHostSupportsShaderBallot()
  215. ? "gl_SubGroupInvocationARB"
  216. : "gl_SubgroupInvocationID";
  217. }
  218. if (config.Stage == ShaderStage.Fragment)
  219. {
  220. // TODO: There must be a better way to handle this...
  221. switch (value)
  222. {
  223. case AttributeConsts.PositionX: return $"(gl_FragCoord.x / {DefaultNames.SupportBlockRenderScaleName}[0])";
  224. case AttributeConsts.PositionY: return $"(gl_FragCoord.y / {DefaultNames.SupportBlockRenderScaleName}[0])";
  225. case AttributeConsts.PositionZ: return "gl_FragCoord.z";
  226. case AttributeConsts.PositionW: return "gl_FragCoord.w";
  227. case AttributeConsts.FrontFacing:
  228. if (config.GpuAccessor.QueryHostHasFrontFacingBug())
  229. {
  230. // This is required for Intel on Windows, gl_FrontFacing sometimes returns incorrect
  231. // (flipped) values. Doing this seems to fix it.
  232. return "(-floatBitsToInt(float(gl_FrontFacing)) < 0)";
  233. }
  234. break;
  235. }
  236. }
  237. string name = builtInAttr.Name;
  238. if (!perPatch && IsArrayAttribute(config.Stage, isOutAttr) && IsArrayBuiltIn(value))
  239. {
  240. name = isOutAttr ? $"gl_out[gl_InvocationID].{name}" : $"gl_in[{indexExpr}].{name}";
  241. }
  242. return name;
  243. }
  244. }
  245. // TODO: Warn about unknown built-in attribute.
  246. return isOutAttr ? "// bad_attr0x" + value.ToString("X") : "0.0";
  247. }
  248. public static string GetAttributeName(string attrExpr, ShaderConfig config, bool isOutAttr = false, string indexExpr = "0")
  249. {
  250. string name = isOutAttr
  251. ? DefaultNames.OAttributePrefix
  252. : DefaultNames.IAttributePrefix;
  253. if (config.Stage == ShaderStage.Geometry && !isOutAttr)
  254. {
  255. name += $"[{indexExpr}]";
  256. }
  257. return $"{name}[{attrExpr} >> 2][{attrExpr} & 3]";
  258. }
  259. public static bool IsArrayAttribute(ShaderStage stage, bool isOutAttr)
  260. {
  261. if (isOutAttr)
  262. {
  263. return stage == ShaderStage.TessellationControl;
  264. }
  265. else
  266. {
  267. return stage == ShaderStage.TessellationControl ||
  268. stage == ShaderStage.TessellationEvaluation ||
  269. stage == ShaderStage.Geometry;
  270. }
  271. }
  272. private static bool IsArrayBuiltIn(int attr)
  273. {
  274. if (attr <= AttributeConsts.TessLevelInner1 ||
  275. attr == AttributeConsts.TessCoordX ||
  276. attr == AttributeConsts.TessCoordY)
  277. {
  278. return false;
  279. }
  280. return (attr & AttributeConsts.SpecialMask) == 0;
  281. }
  282. public static string GetUbName(ShaderStage stage, int slot, bool cbIndexable)
  283. {
  284. if (cbIndexable)
  285. {
  286. return GetUbName(stage, NumberFormatter.FormatInt(slot, VariableType.S32));
  287. }
  288. return $"{GetShaderStagePrefix(stage)}_{DefaultNames.UniformNamePrefix}{slot}_{DefaultNames.UniformNameSuffix}";
  289. }
  290. private static string GetUbName(ShaderStage stage, string slotExpr)
  291. {
  292. return $"{GetShaderStagePrefix(stage)}_{DefaultNames.UniformNamePrefix}[{slotExpr}].{DefaultNames.DataName}";
  293. }
  294. public static string GetSamplerName(ShaderStage stage, AstTextureOperation texOp, string indexExpr)
  295. {
  296. return GetSamplerName(stage, texOp.CbufSlot, texOp.Handle, texOp.Type.HasFlag(SamplerType.Indexed), indexExpr);
  297. }
  298. public static string GetSamplerName(ShaderStage stage, int cbufSlot, int handle, bool indexed, string indexExpr)
  299. {
  300. string suffix = cbufSlot < 0 ? $"_tcb_{handle:X}" : $"_cb{cbufSlot}_{handle:X}";
  301. if (indexed)
  302. {
  303. suffix += $"a[{indexExpr}]";
  304. }
  305. return GetShaderStagePrefix(stage) + "_" + DefaultNames.SamplerNamePrefix + suffix;
  306. }
  307. public static string GetImageName(ShaderStage stage, AstTextureOperation texOp, string indexExpr)
  308. {
  309. return GetImageName(stage, texOp.CbufSlot, texOp.Handle, texOp.Format, texOp.Type.HasFlag(SamplerType.Indexed), indexExpr);
  310. }
  311. public static string GetImageName(
  312. ShaderStage stage,
  313. int cbufSlot,
  314. int handle,
  315. TextureFormat format,
  316. bool indexed,
  317. string indexExpr)
  318. {
  319. string suffix = cbufSlot < 0
  320. ? $"_tcb_{handle:X}_{format.ToGlslFormat()}"
  321. : $"_cb{cbufSlot}_{handle:X}_{format.ToGlslFormat()}";
  322. if (indexed)
  323. {
  324. suffix += $"a[{indexExpr}]";
  325. }
  326. return GetShaderStagePrefix(stage) + "_" + DefaultNames.ImageNamePrefix + suffix;
  327. }
  328. public static string GetShaderStagePrefix(ShaderStage stage)
  329. {
  330. int index = (int)stage;
  331. if ((uint)index >= _stagePrefixes.Length)
  332. {
  333. return "invalid";
  334. }
  335. return _stagePrefixes[index];
  336. }
  337. private static char GetSwizzleMask(int value)
  338. {
  339. return "xyzw"[value];
  340. }
  341. public static string GetArgumentName(int argIndex)
  342. {
  343. return $"{DefaultNames.ArgumentNamePrefix}{argIndex}";
  344. }
  345. public static VariableType GetNodeDestType(CodeGenContext context, IAstNode node)
  346. {
  347. if (node is AstOperation operation)
  348. {
  349. if (operation.Inst == Instruction.LoadAttribute)
  350. {
  351. // Load attribute basically just returns the attribute value.
  352. // Some built-in attributes may have different types, so we need
  353. // to return the type based on the attribute that is being read.
  354. if (operation.GetSource(0) is AstOperand operand && operand.Type == OperandType.Constant)
  355. {
  356. if (_builtInAttributes.TryGetValue(operand.Value & ~3, out BuiltInAttribute builtInAttr))
  357. {
  358. return builtInAttr.Type;
  359. }
  360. }
  361. return OperandInfo.GetVarType(OperandType.Attribute);
  362. }
  363. else if (operation.Inst == Instruction.Call)
  364. {
  365. AstOperand funcId = (AstOperand)operation.GetSource(0);
  366. Debug.Assert(funcId.Type == OperandType.Constant);
  367. return context.GetFunction(funcId.Value).ReturnType;
  368. }
  369. else if (operation is AstTextureOperation texOp &&
  370. (texOp.Inst == Instruction.ImageLoad ||
  371. texOp.Inst == Instruction.ImageStore ||
  372. texOp.Inst == Instruction.ImageAtomic))
  373. {
  374. return texOp.Format.GetComponentType();
  375. }
  376. return GetDestVarType(operation.Inst);
  377. }
  378. else if (node is AstOperand operand)
  379. {
  380. if (operand.Type == OperandType.Argument)
  381. {
  382. int argIndex = operand.Value;
  383. return context.CurrentFunction.GetArgumentType(argIndex);
  384. }
  385. return GetOperandVarType(operand);
  386. }
  387. else
  388. {
  389. throw new ArgumentException($"Invalid node type \"{node?.GetType().Name ?? "null"}\".");
  390. }
  391. }
  392. private static VariableType GetOperandVarType(AstOperand operand)
  393. {
  394. if (operand.Type == OperandType.Attribute)
  395. {
  396. if (_builtInAttributes.TryGetValue(operand.Value & ~3, out BuiltInAttribute builtInAttr))
  397. {
  398. return builtInAttr.Type;
  399. }
  400. }
  401. return OperandInfo.GetVarType(operand);
  402. }
  403. }
  404. }