GlslDecompiler.cs 46 KB

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