OperandManager.cs 22 KB

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