OperandManager.cs 22 KB

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