GlslDecompiler.cs 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. using System.Linq;
  5. using System.Text;
  6. namespace Ryujinx.Graphics.Gal.Shader
  7. {
  8. public class GlslDecompiler
  9. {
  10. private delegate string GetInstExpr(ShaderIrOp Op);
  11. private Dictionary<ShaderIrInst, GetInstExpr> InstsExpr;
  12. private enum OperType
  13. {
  14. Bool,
  15. F32,
  16. I32
  17. }
  18. private const string IdentationStr = " ";
  19. private const int MaxVertexInput = 3;
  20. private GlslDecl Decl;
  21. private ShaderHeader Header, HeaderB;
  22. private ShaderIrBlock[] Blocks, BlocksB;
  23. private StringBuilder SB;
  24. public GlslDecompiler()
  25. {
  26. InstsExpr = new Dictionary<ShaderIrInst, GetInstExpr>()
  27. {
  28. { ShaderIrInst.Abs, GetAbsExpr },
  29. { ShaderIrInst.Add, GetAddExpr },
  30. { ShaderIrInst.And, GetAndExpr },
  31. { ShaderIrInst.Asr, GetAsrExpr },
  32. { ShaderIrInst.Band, GetBandExpr },
  33. { ShaderIrInst.Bnot, GetBnotExpr },
  34. { ShaderIrInst.Bor, GetBorExpr },
  35. { ShaderIrInst.Bxor, GetBxorExpr },
  36. { ShaderIrInst.Ceil, GetCeilExpr },
  37. { ShaderIrInst.Ceq, GetCeqExpr },
  38. { ShaderIrInst.Cge, GetCgeExpr },
  39. { ShaderIrInst.Cgt, GetCgtExpr },
  40. { ShaderIrInst.Clamps, GetClampsExpr },
  41. { ShaderIrInst.Clampu, GetClampuExpr },
  42. { ShaderIrInst.Cle, GetCleExpr },
  43. { ShaderIrInst.Clt, GetCltExpr },
  44. { ShaderIrInst.Cne, GetCneExpr },
  45. { ShaderIrInst.Cut, GetCutExpr },
  46. { ShaderIrInst.Exit, GetExitExpr },
  47. { ShaderIrInst.Fabs, GetAbsExpr },
  48. { ShaderIrInst.Fadd, GetAddExpr },
  49. { ShaderIrInst.Fceq, GetCeqExpr },
  50. { ShaderIrInst.Fcequ, GetCequExpr },
  51. { ShaderIrInst.Fcge, GetCgeExpr },
  52. { ShaderIrInst.Fcgeu, GetCgeuExpr },
  53. { ShaderIrInst.Fcgt, GetCgtExpr },
  54. { ShaderIrInst.Fcgtu, GetCgtuExpr },
  55. { ShaderIrInst.Fclamp, GetFclampExpr },
  56. { ShaderIrInst.Fcle, GetCleExpr },
  57. { ShaderIrInst.Fcleu, GetCleuExpr },
  58. { ShaderIrInst.Fclt, GetCltExpr },
  59. { ShaderIrInst.Fcltu, GetCltuExpr },
  60. { ShaderIrInst.Fcnan, GetCnanExpr },
  61. { ShaderIrInst.Fcne, GetCneExpr },
  62. { ShaderIrInst.Fcneu, GetCneuExpr },
  63. { ShaderIrInst.Fcnum, GetCnumExpr },
  64. { ShaderIrInst.Fcos, GetFcosExpr },
  65. { ShaderIrInst.Fex2, GetFex2Expr },
  66. { ShaderIrInst.Ffma, GetFfmaExpr },
  67. { ShaderIrInst.Flg2, GetFlg2Expr },
  68. { ShaderIrInst.Floor, GetFloorExpr },
  69. { ShaderIrInst.Fmax, GetMaxExpr },
  70. { ShaderIrInst.Fmin, GetMinExpr },
  71. { ShaderIrInst.Fmul, GetMulExpr },
  72. { ShaderIrInst.Fneg, GetNegExpr },
  73. { ShaderIrInst.Frcp, GetFrcpExpr },
  74. { ShaderIrInst.Frsq, GetFrsqExpr },
  75. { ShaderIrInst.Fsin, GetFsinExpr },
  76. { ShaderIrInst.Fsqrt, GetFsqrtExpr },
  77. { ShaderIrInst.Ftos, GetFtosExpr },
  78. { ShaderIrInst.Ftou, GetFtouExpr },
  79. { ShaderIrInst.Ipa, GetIpaExpr },
  80. { ShaderIrInst.Kil, GetKilExpr },
  81. { ShaderIrInst.Lsl, GetLslExpr },
  82. { ShaderIrInst.Lsr, GetLsrExpr },
  83. { ShaderIrInst.Max, GetMaxExpr },
  84. { ShaderIrInst.Min, GetMinExpr },
  85. { ShaderIrInst.Mul, GetMulExpr },
  86. { ShaderIrInst.Neg, GetNegExpr },
  87. { ShaderIrInst.Not, GetNotExpr },
  88. { ShaderIrInst.Or, GetOrExpr },
  89. { ShaderIrInst.Stof, GetStofExpr },
  90. { ShaderIrInst.Sub, GetSubExpr },
  91. { ShaderIrInst.Texq, GetTexqExpr },
  92. { ShaderIrInst.Texs, GetTexsExpr },
  93. { ShaderIrInst.Trunc, GetTruncExpr },
  94. { ShaderIrInst.Txlf, GetTxlfExpr },
  95. { ShaderIrInst.Utof, GetUtofExpr },
  96. { ShaderIrInst.Xor, GetXorExpr }
  97. };
  98. }
  99. public GlslProgram Decompile(
  100. IGalMemory Memory,
  101. long VpAPosition,
  102. long VpBPosition,
  103. GalShaderType ShaderType)
  104. {
  105. Header = new ShaderHeader(Memory, VpAPosition);
  106. HeaderB = new ShaderHeader(Memory, VpBPosition);
  107. Blocks = ShaderDecoder.Decode(Memory, VpAPosition);
  108. BlocksB = ShaderDecoder.Decode(Memory, VpBPosition);
  109. GlslDecl DeclVpA = new GlslDecl(Blocks, ShaderType);
  110. GlslDecl DeclVpB = new GlslDecl(BlocksB, ShaderType);
  111. Decl = GlslDecl.Merge(DeclVpA, DeclVpB);
  112. return Decompile();
  113. }
  114. public GlslProgram Decompile(IGalMemory Memory, long Position, GalShaderType ShaderType)
  115. {
  116. Header = new ShaderHeader(Memory, Position);
  117. HeaderB = null;
  118. Blocks = ShaderDecoder.Decode(Memory, Position);
  119. BlocksB = null;
  120. Decl = new GlslDecl(Blocks, ShaderType);
  121. return Decompile();
  122. }
  123. private GlslProgram Decompile()
  124. {
  125. SB = new StringBuilder();
  126. SB.AppendLine("#version 410 core");
  127. PrintDeclHeader();
  128. PrintDeclTextures();
  129. PrintDeclUniforms();
  130. PrintDeclAttributes();
  131. PrintDeclInAttributes();
  132. PrintDeclOutAttributes();
  133. PrintDeclGprs();
  134. PrintDeclPreds();
  135. if (BlocksB != null)
  136. {
  137. PrintBlockScope(Blocks[0], null, null, "void " + GlslDecl.ProgramAName + "()", IdentationStr);
  138. SB.AppendLine();
  139. PrintBlockScope(BlocksB[0], null, null, "void " + GlslDecl.ProgramBName + "()", IdentationStr);
  140. }
  141. else
  142. {
  143. PrintBlockScope(Blocks[0], null, null, "void " + GlslDecl.ProgramName + "()", IdentationStr);
  144. }
  145. SB.AppendLine();
  146. PrintMain();
  147. string GlslCode = SB.ToString();
  148. return new GlslProgram(
  149. GlslCode,
  150. Decl.Textures.Values,
  151. Decl.Uniforms.Values);
  152. }
  153. private void PrintDeclHeader()
  154. {
  155. if (Decl.ShaderType == GalShaderType.Geometry)
  156. {
  157. int MaxVertices = Header.MaxOutputVertexCount;
  158. string OutputTopology;
  159. switch (Header.OutputTopology)
  160. {
  161. case ShaderHeader.PointList: OutputTopology = "points"; break;
  162. case ShaderHeader.LineStrip: OutputTopology = "line_strip"; break;
  163. case ShaderHeader.TriangleStrip: OutputTopology = "triangle_strip"; break;
  164. default: throw new InvalidOperationException();
  165. }
  166. SB.AppendLine("#extension GL_ARB_enhanced_layouts : require");
  167. SB.AppendLine();
  168. SB.AppendLine("// Stubbed. Maxwell geometry shaders don't inform input geometry type");
  169. SB.AppendLine("layout(triangles) in;" + Environment.NewLine);
  170. SB.AppendLine($"layout({OutputTopology}, max_vertices = {MaxVertices}) out;");
  171. SB.AppendLine();
  172. }
  173. }
  174. private void PrintDeclTextures()
  175. {
  176. PrintDecls(Decl.Textures, "uniform sampler2D");
  177. }
  178. private void PrintDeclUniforms()
  179. {
  180. if (Decl.ShaderType == GalShaderType.Vertex)
  181. {
  182. SB.AppendLine("uniform vec2 " + GlslDecl.FlipUniformName + ";");
  183. }
  184. SB.AppendLine();
  185. foreach (ShaderDeclInfo DeclInfo in Decl.Uniforms.Values.OrderBy(DeclKeySelector))
  186. {
  187. SB.AppendLine($"layout (std140) uniform {DeclInfo.Name} {{");
  188. SB.AppendLine($"{IdentationStr}vec4 {DeclInfo.Name}_data[{GlslDecl.MaxUboSize}];");
  189. SB.AppendLine("};");
  190. }
  191. if (Decl.Uniforms.Count > 0)
  192. {
  193. SB.AppendLine();
  194. }
  195. }
  196. private void PrintDeclAttributes()
  197. {
  198. string GeometryArray = (Decl.ShaderType == GalShaderType.Geometry) ? "[" + MaxVertexInput + "]" : "";
  199. PrintDecls(Decl.Attributes, Suffix: GeometryArray);
  200. }
  201. private void PrintDeclInAttributes()
  202. {
  203. if (Decl.ShaderType == GalShaderType.Fragment)
  204. {
  205. SB.AppendLine("layout (location = " + GlslDecl.PositionOutAttrLocation + ") in vec4 " + GlslDecl.PositionOutAttrName + ";");
  206. }
  207. if (Decl.ShaderType == GalShaderType.Geometry)
  208. {
  209. if (Decl.InAttributes.Count > 0)
  210. {
  211. SB.AppendLine("in Vertex {");
  212. foreach (ShaderDeclInfo DeclInfo in Decl.InAttributes.Values.OrderBy(DeclKeySelector))
  213. {
  214. if (DeclInfo.Index >= 0)
  215. {
  216. SB.AppendLine(IdentationStr + "layout (location = " + DeclInfo.Index + ") vec4 " + DeclInfo.Name + "; ");
  217. }
  218. }
  219. SB.AppendLine("} block_in[];" + Environment.NewLine);
  220. }
  221. }
  222. else
  223. {
  224. PrintDeclAttributes(Decl.InAttributes.Values, "in");
  225. }
  226. }
  227. private void PrintDeclOutAttributes()
  228. {
  229. if (Decl.ShaderType != GalShaderType.Fragment)
  230. {
  231. SB.AppendLine("layout (location = " + GlslDecl.PositionOutAttrLocation + ") out vec4 " + GlslDecl.PositionOutAttrName + ";");
  232. }
  233. PrintDeclAttributes(Decl.OutAttributes.Values, "out");
  234. }
  235. private void PrintDeclAttributes(IEnumerable<ShaderDeclInfo> Decls, string InOut)
  236. {
  237. int Count = 0;
  238. foreach (ShaderDeclInfo DeclInfo in Decls.OrderBy(DeclKeySelector))
  239. {
  240. if (DeclInfo.Index >= 0)
  241. {
  242. SB.AppendLine("layout (location = " + DeclInfo.Index + ") " + InOut + " vec4 " + DeclInfo.Name + ";");
  243. Count++;
  244. }
  245. }
  246. if (Count > 0)
  247. {
  248. SB.AppendLine();
  249. }
  250. }
  251. private void PrintDeclGprs()
  252. {
  253. PrintDecls(Decl.Gprs);
  254. }
  255. private void PrintDeclPreds()
  256. {
  257. PrintDecls(Decl.Preds, "bool");
  258. }
  259. private void PrintDecls(IReadOnlyDictionary<int, ShaderDeclInfo> Dict, string CustomType = null, string Suffix = "")
  260. {
  261. foreach (ShaderDeclInfo DeclInfo in Dict.Values.OrderBy(DeclKeySelector))
  262. {
  263. string Name;
  264. if (CustomType != null)
  265. {
  266. Name = CustomType + " " + DeclInfo.Name + Suffix + ";";
  267. }
  268. else if (DeclInfo.Name == GlslDecl.FragmentOutputName)
  269. {
  270. Name = "layout (location = 0) out vec4 " + DeclInfo.Name + Suffix + ";" + Environment.NewLine;
  271. }
  272. else
  273. {
  274. Name = GetDecl(DeclInfo) + Suffix + ";";
  275. }
  276. SB.AppendLine(Name);
  277. }
  278. if (Dict.Count > 0)
  279. {
  280. SB.AppendLine();
  281. }
  282. }
  283. private int DeclKeySelector(ShaderDeclInfo DeclInfo)
  284. {
  285. return DeclInfo.Cbuf << 24 | DeclInfo.Index;
  286. }
  287. private string GetDecl(ShaderDeclInfo DeclInfo)
  288. {
  289. if (DeclInfo.Size == 4)
  290. {
  291. return "vec4 " + DeclInfo.Name;
  292. }
  293. else
  294. {
  295. return "float " + DeclInfo.Name;
  296. }
  297. }
  298. private void PrintMain()
  299. {
  300. SB.AppendLine("void main() {");
  301. foreach (KeyValuePair<int, ShaderDeclInfo> KV in Decl.InAttributes)
  302. {
  303. if (!Decl.Attributes.TryGetValue(KV.Key, out ShaderDeclInfo Attr))
  304. {
  305. continue;
  306. }
  307. ShaderDeclInfo DeclInfo = KV.Value;
  308. if (Decl.ShaderType == GalShaderType.Geometry)
  309. {
  310. for (int Vertex = 0; Vertex < MaxVertexInput; Vertex++)
  311. {
  312. string Dst = Attr.Name + "[" + Vertex + "]";
  313. string Src = "block_in[" + Vertex + "]." + DeclInfo.Name;
  314. SB.AppendLine(IdentationStr + Dst + " = " + Src + ";");
  315. }
  316. }
  317. else
  318. {
  319. SB.AppendLine(IdentationStr + Attr.Name + " = " + DeclInfo.Name + ";");
  320. }
  321. }
  322. if (BlocksB != null)
  323. {
  324. SB.AppendLine(IdentationStr + GlslDecl.ProgramAName + "();");
  325. SB.AppendLine(IdentationStr + GlslDecl.ProgramBName + "();");
  326. }
  327. else
  328. {
  329. SB.AppendLine(IdentationStr + GlslDecl.ProgramName + "();");
  330. }
  331. if (Decl.ShaderType != GalShaderType.Geometry)
  332. {
  333. PrintAttrToOutput();
  334. }
  335. SB.AppendLine("}");
  336. }
  337. private void PrintAttrToOutput(string Identation = IdentationStr)
  338. {
  339. foreach (KeyValuePair<int, ShaderDeclInfo> KV in Decl.OutAttributes)
  340. {
  341. if (!Decl.Attributes.TryGetValue(KV.Key, out ShaderDeclInfo Attr))
  342. {
  343. continue;
  344. }
  345. ShaderDeclInfo DeclInfo = KV.Value;
  346. string Name = Attr.Name;
  347. if (Decl.ShaderType == GalShaderType.Geometry)
  348. {
  349. Name += "[0]";
  350. }
  351. SB.AppendLine(Identation + DeclInfo.Name + " = " + Name + ";");
  352. }
  353. if (Decl.ShaderType == GalShaderType.Vertex)
  354. {
  355. SB.AppendLine(Identation + "gl_Position.xy *= " + GlslDecl.FlipUniformName + ";");
  356. }
  357. if (Decl.ShaderType != GalShaderType.Fragment)
  358. {
  359. SB.AppendLine(Identation + GlslDecl.PositionOutAttrName + " = gl_Position;");
  360. SB.AppendLine(Identation + GlslDecl.PositionOutAttrName + ".w = 1;");
  361. }
  362. }
  363. private void PrintBlockScope(
  364. ShaderIrBlock Block,
  365. ShaderIrBlock EndBlock,
  366. ShaderIrBlock LoopBlock,
  367. string ScopeName,
  368. string Identation,
  369. bool IsDoWhile = false)
  370. {
  371. string UpIdent = Identation.Substring(0, Identation.Length - IdentationStr.Length);
  372. if (IsDoWhile)
  373. {
  374. SB.AppendLine(UpIdent + "do {");
  375. }
  376. else
  377. {
  378. SB.AppendLine(UpIdent + ScopeName + " {");
  379. }
  380. while (Block != null && Block != EndBlock)
  381. {
  382. ShaderIrNode[] Nodes = Block.GetNodes();
  383. Block = PrintNodes(Block, EndBlock, LoopBlock, Identation, Nodes);
  384. }
  385. if (IsDoWhile)
  386. {
  387. SB.AppendLine(UpIdent + "} " + ScopeName + ";");
  388. }
  389. else
  390. {
  391. SB.AppendLine(UpIdent + "}");
  392. }
  393. }
  394. private ShaderIrBlock PrintNodes(
  395. ShaderIrBlock Block,
  396. ShaderIrBlock EndBlock,
  397. ShaderIrBlock LoopBlock,
  398. string Identation,
  399. params ShaderIrNode[] Nodes)
  400. {
  401. /*
  402. * Notes about control flow and if-else/loop generation:
  403. * The code assumes that the program has sane control flow,
  404. * that is, there's no jumps to a location after another jump or
  405. * jump target (except for the end of an if-else block), and backwards
  406. * jumps to a location before the last loop dominator.
  407. * Such cases needs to be transformed on a step before the GLSL code
  408. * generation to ensure that we have sane graphs to work with.
  409. * TODO: Such transformation is not yet implemented.
  410. */
  411. string NewIdent = Identation + IdentationStr;
  412. ShaderIrBlock LoopTail = GetLoopTailBlock(Block);
  413. if (LoopTail != null && LoopBlock != Block)
  414. {
  415. //Shoock! kuma shock! We have a loop here!
  416. //The entire sequence needs to be inside a do-while block.
  417. ShaderIrBlock LoopEnd = GetDownBlock(LoopTail);
  418. PrintBlockScope(Block, LoopEnd, Block, "while (false)", NewIdent, IsDoWhile: true);
  419. return LoopEnd;
  420. }
  421. foreach (ShaderIrNode Node in Nodes)
  422. {
  423. if (Node is ShaderIrCond Cond)
  424. {
  425. string IfExpr = GetSrcExpr(Cond.Pred, true);
  426. if (Cond.Not)
  427. {
  428. IfExpr = "!(" + IfExpr + ")";
  429. }
  430. if (Cond.Child is ShaderIrOp Op && Op.Inst == ShaderIrInst.Bra)
  431. {
  432. //Branch is a loop branch and would result in infinite recursion.
  433. if (Block.Branch.Position <= Block.Position)
  434. {
  435. SB.AppendLine(Identation + "if (" + IfExpr + ") {");
  436. SB.AppendLine(Identation + IdentationStr + "continue;");
  437. SB.AppendLine(Identation + "}");
  438. continue;
  439. }
  440. string SubScopeName = "if (!" + IfExpr + ")";
  441. PrintBlockScope(Block.Next, Block.Branch, LoopBlock, SubScopeName, NewIdent);
  442. ShaderIrBlock IfElseEnd = GetUpBlock(Block.Branch).Branch;
  443. if (IfElseEnd?.Position > Block.Branch.Position)
  444. {
  445. PrintBlockScope(Block.Branch, IfElseEnd, LoopBlock, "else", NewIdent);
  446. return IfElseEnd;
  447. }
  448. return Block.Branch;
  449. }
  450. else
  451. {
  452. SB.AppendLine(Identation + "if (" + IfExpr + ") {");
  453. PrintNodes(Block, EndBlock, LoopBlock, NewIdent, Cond.Child);
  454. SB.AppendLine(Identation + "}");
  455. }
  456. }
  457. else if (Node is ShaderIrAsg Asg)
  458. {
  459. if (IsValidOutOper(Asg.Dst))
  460. {
  461. string Expr = GetSrcExpr(Asg.Src, true);
  462. Expr = GetExprWithCast(Asg.Dst, Asg.Src, Expr);
  463. SB.AppendLine(Identation + GetDstOperName(Asg.Dst) + " = " + Expr + ";");
  464. }
  465. }
  466. else if (Node is ShaderIrOp Op)
  467. {
  468. if (Op.Inst == ShaderIrInst.Bra)
  469. {
  470. if (Block.Branch.Position <= Block.Position)
  471. {
  472. SB.AppendLine(Identation + "continue;");
  473. }
  474. }
  475. else if (Op.Inst == ShaderIrInst.Emit)
  476. {
  477. PrintAttrToOutput(Identation);
  478. SB.AppendLine(Identation + "EmitVertex();");
  479. }
  480. else
  481. {
  482. SB.AppendLine(Identation + GetSrcExpr(Op, true) + ";");
  483. }
  484. }
  485. else if (Node is ShaderIrCmnt Cmnt)
  486. {
  487. SB.AppendLine(Identation + "// " + Cmnt.Comment);
  488. }
  489. else
  490. {
  491. throw new InvalidOperationException();
  492. }
  493. }
  494. return Block.Next;
  495. }
  496. private ShaderIrBlock GetUpBlock(ShaderIrBlock Block)
  497. {
  498. return Blocks.FirstOrDefault(x => x.EndPosition == Block.Position);
  499. }
  500. private ShaderIrBlock GetDownBlock(ShaderIrBlock Block)
  501. {
  502. return Blocks.FirstOrDefault(x => x.Position == Block.EndPosition);
  503. }
  504. private ShaderIrBlock GetLoopTailBlock(ShaderIrBlock LoopHead)
  505. {
  506. ShaderIrBlock Tail = null;
  507. foreach (ShaderIrBlock Block in LoopHead.Sources)
  508. {
  509. if (Block.Position >= LoopHead.Position)
  510. {
  511. if (Tail == null || Tail.Position < Block.Position)
  512. {
  513. Tail = Block;
  514. }
  515. }
  516. }
  517. return Tail;
  518. }
  519. private bool IsValidOutOper(ShaderIrNode Node)
  520. {
  521. if (Node is ShaderIrOperGpr Gpr && Gpr.IsConst)
  522. {
  523. return false;
  524. }
  525. else if (Node is ShaderIrOperPred Pred && Pred.IsConst)
  526. {
  527. return false;
  528. }
  529. return true;
  530. }
  531. private string GetDstOperName(ShaderIrNode Node)
  532. {
  533. if (Node is ShaderIrOperAbuf Abuf)
  534. {
  535. return GetOutAbufName(Abuf);
  536. }
  537. else if (Node is ShaderIrOperGpr Gpr)
  538. {
  539. return GetName(Gpr);
  540. }
  541. else if (Node is ShaderIrOperPred Pred)
  542. {
  543. return GetName(Pred);
  544. }
  545. throw new ArgumentException(nameof(Node));
  546. }
  547. private string GetSrcExpr(ShaderIrNode Node, bool Entry = false)
  548. {
  549. switch (Node)
  550. {
  551. case ShaderIrOperAbuf Abuf: return GetName (Abuf);
  552. case ShaderIrOperCbuf Cbuf: return GetName (Cbuf);
  553. case ShaderIrOperGpr Gpr: return GetName (Gpr);
  554. case ShaderIrOperImm Imm: return GetValue(Imm);
  555. case ShaderIrOperImmf Immf: return GetValue(Immf);
  556. case ShaderIrOperPred Pred: return GetName (Pred);
  557. case ShaderIrOp Op:
  558. string Expr;
  559. if (InstsExpr.TryGetValue(Op.Inst, out GetInstExpr GetExpr))
  560. {
  561. Expr = GetExpr(Op);
  562. }
  563. else
  564. {
  565. throw new NotImplementedException(Op.Inst.ToString());
  566. }
  567. if (!Entry && NeedsParentheses(Op))
  568. {
  569. Expr = "(" + Expr + ")";
  570. }
  571. return Expr;
  572. default: throw new ArgumentException(nameof(Node));
  573. }
  574. }
  575. private static bool NeedsParentheses(ShaderIrOp Op)
  576. {
  577. switch (Op.Inst)
  578. {
  579. case ShaderIrInst.Ipa:
  580. case ShaderIrInst.Texq:
  581. case ShaderIrInst.Texs:
  582. case ShaderIrInst.Txlf:
  583. return false;
  584. }
  585. return true;
  586. }
  587. private string GetName(ShaderIrOperCbuf Cbuf)
  588. {
  589. if (!Decl.Uniforms.TryGetValue(Cbuf.Index, out ShaderDeclInfo DeclInfo))
  590. {
  591. throw new InvalidOperationException();
  592. }
  593. if (Cbuf.Offs != null)
  594. {
  595. string Offset = "floatBitsToInt(" + GetSrcExpr(Cbuf.Offs) + ")";
  596. string Index = "(" + Cbuf.Pos * 4 + " + " + Offset + ")";
  597. return $"{DeclInfo.Name}_data[{Index} / 16][({Index} / 4) % 4]";
  598. }
  599. else
  600. {
  601. return $"{DeclInfo.Name}_data[{Cbuf.Pos / 4}][{Cbuf.Pos % 4}]";
  602. }
  603. }
  604. private string GetOutAbufName(ShaderIrOperAbuf Abuf)
  605. {
  606. if (Decl.ShaderType == GalShaderType.Geometry)
  607. {
  608. switch (Abuf.Offs)
  609. {
  610. case GlslDecl.LayerAttr: return "gl_Layer";
  611. }
  612. }
  613. return GetAttrTempName(Abuf);
  614. }
  615. private string GetName(ShaderIrOperAbuf Abuf)
  616. {
  617. //Handle special scalar read-only attributes here.
  618. if (Decl.ShaderType == GalShaderType.Vertex)
  619. {
  620. switch (Abuf.Offs)
  621. {
  622. case GlslDecl.VertexIdAttr: return "gl_VertexID";
  623. case GlslDecl.InstanceIdAttr: return "gl_InstanceID";
  624. }
  625. }
  626. else if (Decl.ShaderType == GalShaderType.TessEvaluation)
  627. {
  628. switch (Abuf.Offs)
  629. {
  630. case GlslDecl.TessCoordAttrX: return "gl_TessCoord.x";
  631. case GlslDecl.TessCoordAttrY: return "gl_TessCoord.y";
  632. case GlslDecl.TessCoordAttrZ: return "gl_TessCoord.z";
  633. }
  634. }
  635. else if (Decl.ShaderType == GalShaderType.Fragment)
  636. {
  637. switch (Abuf.Offs)
  638. {
  639. //Note: It's a guess that Maxwell's face is 1 when gl_FrontFacing == true
  640. case GlslDecl.FaceAttr: return "(gl_FrontFacing ? 1 : 0)";
  641. }
  642. }
  643. return GetAttrTempName(Abuf);
  644. }
  645. private string GetAttrTempName(ShaderIrOperAbuf Abuf)
  646. {
  647. int Index = Abuf.Offs >> 4;
  648. int Elem = (Abuf.Offs >> 2) & 3;
  649. string Swizzle = "." + GetAttrSwizzle(Elem);
  650. if (!Decl.Attributes.TryGetValue(Index, out ShaderDeclInfo DeclInfo))
  651. {
  652. //Handle special vec4 attributes here
  653. //(for example, index 7 is aways gl_Position).
  654. if (Index == GlslDecl.GlPositionVec4Index)
  655. {
  656. string Name =
  657. Decl.ShaderType != GalShaderType.Vertex &&
  658. Decl.ShaderType != GalShaderType.Geometry ? GlslDecl.PositionOutAttrName : "gl_Position";
  659. return Name + Swizzle;
  660. }
  661. throw new InvalidOperationException();
  662. }
  663. if (Decl.ShaderType == GalShaderType.Geometry)
  664. {
  665. string Vertex = "floatBitsToInt(" + GetSrcExpr(Abuf.Vertex) + ")";
  666. return DeclInfo.Name + "[" + Vertex + "]" + Swizzle;
  667. }
  668. else
  669. {
  670. return DeclInfo.Name + Swizzle;
  671. }
  672. }
  673. private string GetName(ShaderIrOperGpr Gpr)
  674. {
  675. return Gpr.IsConst ? "0" : GetNameWithSwizzle(Decl.Gprs, Gpr.Index);
  676. }
  677. private string GetValue(ShaderIrOperImm Imm)
  678. {
  679. //Only use hex is the value is too big and would likely be hard to read as int.
  680. if (Imm.Value > 0xfff ||
  681. Imm.Value < -0xfff)
  682. {
  683. return "0x" + Imm.Value.ToString("x8", CultureInfo.InvariantCulture);
  684. }
  685. else
  686. {
  687. return GetIntConst(Imm.Value);
  688. }
  689. }
  690. private string GetValue(ShaderIrOperImmf Immf)
  691. {
  692. return GetFloatConst(Immf.Value);
  693. }
  694. private string GetName(ShaderIrOperPred Pred)
  695. {
  696. return Pred.IsConst ? "true" : GetNameWithSwizzle(Decl.Preds, Pred.Index);
  697. }
  698. private string GetNameWithSwizzle(IReadOnlyDictionary<int, ShaderDeclInfo> Dict, int Index)
  699. {
  700. int VecIndex = Index >> 2;
  701. if (Dict.TryGetValue(VecIndex, out ShaderDeclInfo DeclInfo))
  702. {
  703. if (DeclInfo.Size > 1 && Index < VecIndex + DeclInfo.Size)
  704. {
  705. return DeclInfo.Name + "." + GetAttrSwizzle(Index & 3);
  706. }
  707. }
  708. if (!Dict.TryGetValue(Index, out DeclInfo))
  709. {
  710. throw new InvalidOperationException();
  711. }
  712. return DeclInfo.Name;
  713. }
  714. private string GetAttrSwizzle(int Elem)
  715. {
  716. return "xyzw".Substring(Elem, 1);
  717. }
  718. private string GetAbsExpr(ShaderIrOp Op) => GetUnaryCall(Op, "abs");
  719. private string GetAddExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "+");
  720. private string GetAndExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "&");
  721. private string GetAsrExpr(ShaderIrOp Op) => GetBinaryExpr(Op, ">>");
  722. private string GetBandExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "&&");
  723. private string GetBnotExpr(ShaderIrOp Op) => GetUnaryExpr(Op, "!");
  724. private string GetBorExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "||");
  725. private string GetBxorExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "^^");
  726. private string GetCeilExpr(ShaderIrOp Op) => GetUnaryCall(Op, "ceil");
  727. private string GetClampsExpr(ShaderIrOp Op)
  728. {
  729. return "clamp(" + GetOperExpr(Op, Op.OperandA) + ", " +
  730. GetOperExpr(Op, Op.OperandB) + ", " +
  731. GetOperExpr(Op, Op.OperandC) + ")";
  732. }
  733. private string GetClampuExpr(ShaderIrOp Op)
  734. {
  735. return "int(clamp(uint(" + GetOperExpr(Op, Op.OperandA) + "), " +
  736. "uint(" + GetOperExpr(Op, Op.OperandB) + "), " +
  737. "uint(" + GetOperExpr(Op, Op.OperandC) + ")))";
  738. }
  739. private string GetCeqExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "==");
  740. private string GetCequExpr(ShaderIrOp Op) => GetBinaryExprWithNaN(Op, "==");
  741. private string GetCgeExpr(ShaderIrOp Op) => GetBinaryExpr(Op, ">=");
  742. private string GetCgeuExpr(ShaderIrOp Op) => GetBinaryExprWithNaN(Op, ">=");
  743. private string GetCgtExpr(ShaderIrOp Op) => GetBinaryExpr(Op, ">");
  744. private string GetCgtuExpr(ShaderIrOp Op) => GetBinaryExprWithNaN(Op, ">");
  745. private string GetCleExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "<=");
  746. private string GetCleuExpr(ShaderIrOp Op) => GetBinaryExprWithNaN(Op, "<=");
  747. private string GetCltExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "<");
  748. private string GetCltuExpr(ShaderIrOp Op) => GetBinaryExprWithNaN(Op, "<");
  749. private string GetCnanExpr(ShaderIrOp Op) => GetUnaryCall(Op, "isnan");
  750. private string GetCneExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "!=");
  751. private string GetCutExpr(ShaderIrOp Op) => "EndPrimitive()";
  752. private string GetCneuExpr(ShaderIrOp Op) => GetBinaryExprWithNaN(Op, "!=");
  753. private string GetCnumExpr(ShaderIrOp Op) => GetUnaryCall(Op, "!isnan");
  754. private string GetExitExpr(ShaderIrOp Op) => "return";
  755. private string GetFcosExpr(ShaderIrOp Op) => GetUnaryCall(Op, "cos");
  756. private string GetFex2Expr(ShaderIrOp Op) => GetUnaryCall(Op, "exp2");
  757. private string GetFfmaExpr(ShaderIrOp Op) => GetTernaryExpr(Op, "*", "+");
  758. private string GetFclampExpr(ShaderIrOp Op) => GetTernaryCall(Op, "clamp");
  759. private string GetFlg2Expr(ShaderIrOp Op) => GetUnaryCall(Op, "log2");
  760. private string GetFloorExpr(ShaderIrOp Op) => GetUnaryCall(Op, "floor");
  761. private string GetFrcpExpr(ShaderIrOp Op) => GetUnaryExpr(Op, "1 / ");
  762. private string GetFrsqExpr(ShaderIrOp Op) => GetUnaryCall(Op, "inversesqrt");
  763. private string GetFsinExpr(ShaderIrOp Op) => GetUnaryCall(Op, "sin");
  764. private string GetFsqrtExpr(ShaderIrOp Op) => GetUnaryCall(Op, "sqrt");
  765. private string GetFtosExpr(ShaderIrOp Op)
  766. {
  767. return "int(" + GetOperExpr(Op, Op.OperandA) + ")";
  768. }
  769. private string GetFtouExpr(ShaderIrOp Op)
  770. {
  771. return "int(uint(" + GetOperExpr(Op, Op.OperandA) + "))";
  772. }
  773. private string GetIpaExpr(ShaderIrOp Op) => GetSrcExpr(Op.OperandA);
  774. private string GetKilExpr(ShaderIrOp Op) => "discard";
  775. private string GetLslExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "<<");
  776. private string GetLsrExpr(ShaderIrOp Op)
  777. {
  778. return "int(uint(" + GetOperExpr(Op, Op.OperandA) + ") >> " +
  779. GetOperExpr(Op, Op.OperandB) + ")";
  780. }
  781. private string GetMaxExpr(ShaderIrOp Op) => GetBinaryCall(Op, "max");
  782. private string GetMinExpr(ShaderIrOp Op) => GetBinaryCall(Op, "min");
  783. private string GetMulExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "*");
  784. private string GetNegExpr(ShaderIrOp Op) => GetUnaryExpr(Op, "-");
  785. private string GetNotExpr(ShaderIrOp Op) => GetUnaryExpr(Op, "~");
  786. private string GetOrExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "|");
  787. private string GetStofExpr(ShaderIrOp Op)
  788. {
  789. return "float(" + GetOperExpr(Op, Op.OperandA) + ")";
  790. }
  791. private string GetSubExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "-");
  792. private string GetTexqExpr(ShaderIrOp Op)
  793. {
  794. ShaderIrMetaTexq Meta = (ShaderIrMetaTexq)Op.MetaData;
  795. string Ch = "xyzw".Substring(Meta.Elem, 1);
  796. if (Meta.Info == ShaderTexqInfo.Dimension)
  797. {
  798. string Sampler = GetTexSamplerName(Op);
  799. string Lod = GetOperExpr(Op, Op.OperandA); //???
  800. return "textureSize(" + Sampler + ", " + Lod + ")." + Ch;
  801. }
  802. else
  803. {
  804. throw new NotImplementedException(Meta.Info.ToString());
  805. }
  806. }
  807. private string GetTexsExpr(ShaderIrOp Op)
  808. {
  809. ShaderIrMetaTex Meta = (ShaderIrMetaTex)Op.MetaData;
  810. string Sampler = GetTexSamplerName(Op);
  811. string Coords = GetTexSamplerCoords(Op);
  812. string Ch = "rgba".Substring(Meta.Elem, 1);
  813. return "texture(" + Sampler + ", " + Coords + ")." + Ch;
  814. }
  815. private string GetTxlfExpr(ShaderIrOp Op)
  816. {
  817. ShaderIrMetaTex Meta = (ShaderIrMetaTex)Op.MetaData;
  818. string Sampler = GetTexSamplerName(Op);
  819. string Coords = GetITexSamplerCoords(Op);
  820. string Ch = "rgba".Substring(Meta.Elem, 1);
  821. return "texelFetch(" + Sampler + ", " + Coords + ", 0)." + Ch;
  822. }
  823. private string GetTruncExpr(ShaderIrOp Op) => GetUnaryCall(Op, "trunc");
  824. private string GetUtofExpr(ShaderIrOp Op)
  825. {
  826. return "float(uint(" + GetOperExpr(Op, Op.OperandA) + "))";
  827. }
  828. private string GetXorExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "^");
  829. private string GetUnaryCall(ShaderIrOp Op, string FuncName)
  830. {
  831. return FuncName + "(" + GetOperExpr(Op, Op.OperandA) + ")";
  832. }
  833. private string GetBinaryCall(ShaderIrOp Op, string FuncName)
  834. {
  835. return FuncName + "(" + GetOperExpr(Op, Op.OperandA) + ", " +
  836. GetOperExpr(Op, Op.OperandB) + ")";
  837. }
  838. private string GetTernaryCall(ShaderIrOp Op, string FuncName)
  839. {
  840. return FuncName + "(" + GetOperExpr(Op, Op.OperandA) + ", " +
  841. GetOperExpr(Op, Op.OperandB) + ", " +
  842. GetOperExpr(Op, Op.OperandC) + ")";
  843. }
  844. private string GetUnaryExpr(ShaderIrOp Op, string Opr)
  845. {
  846. return Opr + GetOperExpr(Op, Op.OperandA);
  847. }
  848. private string GetBinaryExpr(ShaderIrOp Op, string Opr)
  849. {
  850. return GetOperExpr(Op, Op.OperandA) + " " + Opr + " " +
  851. GetOperExpr(Op, Op.OperandB);
  852. }
  853. private string GetBinaryExprWithNaN(ShaderIrOp Op, string Opr)
  854. {
  855. string A = GetOperExpr(Op, Op.OperandA);
  856. string B = GetOperExpr(Op, Op.OperandB);
  857. string NaNCheck =
  858. " || isnan(" + A + ")" +
  859. " || isnan(" + B + ")";
  860. return A + " " + Opr + " " + B + NaNCheck;
  861. }
  862. private string GetTernaryExpr(ShaderIrOp Op, string Opr1, string Opr2)
  863. {
  864. return GetOperExpr(Op, Op.OperandA) + " " + Opr1 + " " +
  865. GetOperExpr(Op, Op.OperandB) + " " + Opr2 + " " +
  866. GetOperExpr(Op, Op.OperandC);
  867. }
  868. private string GetTexSamplerName(ShaderIrOp Op)
  869. {
  870. ShaderIrOperImm Node = (ShaderIrOperImm)Op.OperandC;
  871. int Handle = ((ShaderIrOperImm)Op.OperandC).Value;
  872. if (!Decl.Textures.TryGetValue(Handle, out ShaderDeclInfo DeclInfo))
  873. {
  874. throw new InvalidOperationException();
  875. }
  876. return DeclInfo.Name;
  877. }
  878. private string GetTexSamplerCoords(ShaderIrOp Op)
  879. {
  880. return "vec2(" + GetOperExpr(Op, Op.OperandA) + ", " +
  881. GetOperExpr(Op, Op.OperandB) + ")";
  882. }
  883. private string GetITexSamplerCoords(ShaderIrOp Op)
  884. {
  885. return "ivec2(" + GetOperExpr(Op, Op.OperandA) + ", " +
  886. GetOperExpr(Op, Op.OperandB) + ")";
  887. }
  888. private string GetOperExpr(ShaderIrOp Op, ShaderIrNode Oper)
  889. {
  890. return GetExprWithCast(Op, Oper, GetSrcExpr(Oper));
  891. }
  892. private static string GetExprWithCast(ShaderIrNode Dst, ShaderIrNode Src, string Expr)
  893. {
  894. //Note: The "DstType" (of the cast) is the type that the operation
  895. //uses on the source operands, while the "SrcType" is the destination
  896. //type of the operand result (if it is a operation) or just the type
  897. //of the variable for registers/uniforms/attributes.
  898. OperType DstType = GetSrcNodeType(Dst);
  899. OperType SrcType = GetDstNodeType(Src);
  900. if (DstType != SrcType)
  901. {
  902. //Check for invalid casts
  903. //(like bool to int/float and others).
  904. if (SrcType != OperType.F32 &&
  905. SrcType != OperType.I32)
  906. {
  907. throw new InvalidOperationException();
  908. }
  909. switch (Src)
  910. {
  911. case ShaderIrOperGpr Gpr:
  912. {
  913. //When the Gpr is ZR, just return the 0 value directly,
  914. //since the float encoding for 0 is 0.
  915. if (Gpr.IsConst)
  916. {
  917. return "0";
  918. }
  919. break;
  920. }
  921. case ShaderIrOperImm Imm:
  922. {
  923. //For integer immediates being used as float,
  924. //it's better (for readability) to just return the float value.
  925. if (DstType == OperType.F32)
  926. {
  927. float Value = BitConverter.Int32BitsToSingle(Imm.Value);
  928. if (!float.IsNaN(Value) && !float.IsInfinity(Value))
  929. {
  930. return GetFloatConst(Value);
  931. }
  932. }
  933. break;
  934. }
  935. }
  936. switch (DstType)
  937. {
  938. case OperType.F32: Expr = "intBitsToFloat(" + Expr + ")"; break;
  939. case OperType.I32: Expr = "floatBitsToInt(" + Expr + ")"; break;
  940. }
  941. }
  942. return Expr;
  943. }
  944. private static string GetIntConst(int Value)
  945. {
  946. string Expr = Value.ToString(CultureInfo.InvariantCulture);
  947. return Value < 0 ? "(" + Expr + ")" : Expr;
  948. }
  949. private static string GetFloatConst(float Value)
  950. {
  951. string Expr = Value.ToString(CultureInfo.InvariantCulture);
  952. return Value < 0 ? "(" + Expr + ")" : Expr;
  953. }
  954. private static OperType GetDstNodeType(ShaderIrNode Node)
  955. {
  956. //Special case instructions with the result type different
  957. //from the input types (like integer <-> float conversion) here.
  958. if (Node is ShaderIrOp Op)
  959. {
  960. switch (Op.Inst)
  961. {
  962. case ShaderIrInst.Stof:
  963. case ShaderIrInst.Txlf:
  964. case ShaderIrInst.Utof:
  965. return OperType.F32;
  966. case ShaderIrInst.Ftos:
  967. case ShaderIrInst.Ftou:
  968. return OperType.I32;
  969. }
  970. }
  971. return GetSrcNodeType(Node);
  972. }
  973. private static OperType GetSrcNodeType(ShaderIrNode Node)
  974. {
  975. switch (Node)
  976. {
  977. case ShaderIrOperAbuf Abuf:
  978. return Abuf.Offs == GlslDecl.LayerAttr ||
  979. Abuf.Offs == GlslDecl.InstanceIdAttr ||
  980. Abuf.Offs == GlslDecl.VertexIdAttr ||
  981. Abuf.Offs == GlslDecl.FaceAttr
  982. ? OperType.I32
  983. : OperType.F32;
  984. case ShaderIrOperCbuf Cbuf: return OperType.F32;
  985. case ShaderIrOperGpr Gpr: return OperType.F32;
  986. case ShaderIrOperImm Imm: return OperType.I32;
  987. case ShaderIrOperImmf Immf: return OperType.F32;
  988. case ShaderIrOperPred Pred: return OperType.Bool;
  989. case ShaderIrOp Op:
  990. if (Op.Inst > ShaderIrInst.B_Start &&
  991. Op.Inst < ShaderIrInst.B_End)
  992. {
  993. return OperType.Bool;
  994. }
  995. else if (Op.Inst > ShaderIrInst.F_Start &&
  996. Op.Inst < ShaderIrInst.F_End)
  997. {
  998. return OperType.F32;
  999. }
  1000. else if (Op.Inst > ShaderIrInst.I_Start &&
  1001. Op.Inst < ShaderIrInst.I_End)
  1002. {
  1003. return OperType.I32;
  1004. }
  1005. break;
  1006. }
  1007. throw new ArgumentException(nameof(Node));
  1008. }
  1009. }
  1010. }