GlslDecompiler.cs 46 KB

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