CodeGenContext.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571
  1. using Ryujinx.Graphics.Shader.StructuredIr;
  2. using Ryujinx.Graphics.Shader.Translation;
  3. using Spv.Generator;
  4. using System;
  5. using System.Collections.Generic;
  6. using static Spv.Specification;
  7. namespace Ryujinx.Graphics.Shader.CodeGen.Spirv
  8. {
  9. using IrConsts = IntermediateRepresentation.IrConsts;
  10. using IrOperandType = IntermediateRepresentation.OperandType;
  11. partial class CodeGenContext : Module
  12. {
  13. private const uint SpirvVersionMajor = 1;
  14. private const uint SpirvVersionMinor = 3;
  15. private const uint SpirvVersionRevision = 0;
  16. private const uint SpirvVersionPacked = (SpirvVersionMajor << 16) | (SpirvVersionMinor << 8) | SpirvVersionRevision;
  17. private readonly StructuredProgramInfo _info;
  18. public ShaderConfig Config { get; }
  19. public int InputVertices { get; }
  20. public Dictionary<int, Instruction> UniformBuffers { get; } = new Dictionary<int, Instruction>();
  21. public Instruction SupportBuffer { get; set; }
  22. public Instruction UniformBuffersArray { get; set; }
  23. public Instruction StorageBuffersArray { get; set; }
  24. public Instruction LocalMemory { get; set; }
  25. public Instruction SharedMemory { get; set; }
  26. public Instruction InputsArray { get; set; }
  27. public Instruction OutputsArray { get; set; }
  28. public Dictionary<TextureMeta, SamplerType> SamplersTypes { get; } = new Dictionary<TextureMeta, SamplerType>();
  29. public Dictionary<TextureMeta, (Instruction, Instruction, Instruction)> Samplers { get; } = new Dictionary<TextureMeta, (Instruction, Instruction, Instruction)>();
  30. public Dictionary<TextureMeta, (Instruction, Instruction)> Images { get; } = new Dictionary<TextureMeta, (Instruction, Instruction)>();
  31. public Dictionary<int, Instruction> Inputs { get; } = new Dictionary<int, Instruction>();
  32. public Dictionary<int, Instruction> Outputs { get; } = new Dictionary<int, Instruction>();
  33. public Dictionary<int, Instruction> InputsPerPatch { get; } = new Dictionary<int, Instruction>();
  34. public Dictionary<int, Instruction> OutputsPerPatch { get; } = new Dictionary<int, Instruction>();
  35. public Instruction CoordTemp { get; set; }
  36. private readonly Dictionary<AstOperand, Instruction> _locals = new Dictionary<AstOperand, Instruction>();
  37. private readonly Dictionary<int, Instruction[]> _localForArgs = new Dictionary<int, Instruction[]>();
  38. private readonly Dictionary<int, Instruction> _funcArgs = new Dictionary<int, Instruction>();
  39. private readonly Dictionary<int, (StructuredFunction, Instruction)> _functions = new Dictionary<int, (StructuredFunction, Instruction)>();
  40. private class BlockState
  41. {
  42. private int _entryCount;
  43. private readonly List<Instruction> _labels = new List<Instruction>();
  44. public Instruction GetNextLabel(CodeGenContext context)
  45. {
  46. return GetLabel(context, _entryCount);
  47. }
  48. public Instruction GetNextLabelAutoIncrement(CodeGenContext context)
  49. {
  50. return GetLabel(context, _entryCount++);
  51. }
  52. public Instruction GetLabel(CodeGenContext context, int index)
  53. {
  54. while (index >= _labels.Count)
  55. {
  56. _labels.Add(context.Label());
  57. }
  58. return _labels[index];
  59. }
  60. }
  61. private readonly Dictionary<AstBlock, BlockState> _labels = new Dictionary<AstBlock, BlockState>();
  62. public Dictionary<AstBlock, (Instruction, Instruction)> LoopTargets { get; set; }
  63. public AstBlock CurrentBlock { get; private set; }
  64. public SpirvDelegates Delegates { get; }
  65. public CodeGenContext(
  66. StructuredProgramInfo info,
  67. ShaderConfig config,
  68. GeneratorPool<Instruction> instPool,
  69. GeneratorPool<LiteralInteger> integerPool) : base(SpirvVersionPacked, instPool, integerPool)
  70. {
  71. _info = info;
  72. Config = config;
  73. if (config.Stage == ShaderStage.Geometry)
  74. {
  75. InputTopology inPrimitive = config.GpuAccessor.QueryPrimitiveTopology();
  76. InputVertices = inPrimitive switch
  77. {
  78. InputTopology.Points => 1,
  79. InputTopology.Lines => 2,
  80. InputTopology.LinesAdjacency => 2,
  81. InputTopology.Triangles => 3,
  82. InputTopology.TrianglesAdjacency => 3,
  83. _ => throw new InvalidOperationException($"Invalid input topology \"{inPrimitive}\".")
  84. };
  85. }
  86. AddCapability(Capability.Shader);
  87. AddCapability(Capability.Float64);
  88. SetMemoryModel(AddressingModel.Logical, MemoryModel.GLSL450);
  89. Delegates = new SpirvDelegates(this);
  90. }
  91. public void StartFunction()
  92. {
  93. _locals.Clear();
  94. _localForArgs.Clear();
  95. _funcArgs.Clear();
  96. }
  97. public void EnterBlock(AstBlock block)
  98. {
  99. CurrentBlock = block;
  100. AddLabel(GetBlockStateLazy(block).GetNextLabelAutoIncrement(this));
  101. }
  102. public Instruction GetFirstLabel(AstBlock block)
  103. {
  104. return GetBlockStateLazy(block).GetLabel(this, 0);
  105. }
  106. public Instruction GetNextLabel(AstBlock block)
  107. {
  108. return GetBlockStateLazy(block).GetNextLabel(this);
  109. }
  110. private BlockState GetBlockStateLazy(AstBlock block)
  111. {
  112. if (!_labels.TryGetValue(block, out var blockState))
  113. {
  114. blockState = new BlockState();
  115. _labels.Add(block, blockState);
  116. }
  117. return blockState;
  118. }
  119. public Instruction NewBlock()
  120. {
  121. var label = Label();
  122. Branch(label);
  123. AddLabel(label);
  124. return label;
  125. }
  126. public Instruction[] GetMainInterface()
  127. {
  128. var mainInterface = new List<Instruction>();
  129. mainInterface.AddRange(Inputs.Values);
  130. mainInterface.AddRange(Outputs.Values);
  131. mainInterface.AddRange(InputsPerPatch.Values);
  132. mainInterface.AddRange(OutputsPerPatch.Values);
  133. if (InputsArray != null)
  134. {
  135. mainInterface.Add(InputsArray);
  136. }
  137. if (OutputsArray != null)
  138. {
  139. mainInterface.Add(OutputsArray);
  140. }
  141. return mainInterface.ToArray();
  142. }
  143. public void DeclareLocal(AstOperand local, Instruction spvLocal)
  144. {
  145. _locals.Add(local, spvLocal);
  146. }
  147. public void DeclareLocalForArgs(int funcIndex, Instruction[] spvLocals)
  148. {
  149. _localForArgs.Add(funcIndex, spvLocals);
  150. }
  151. public void DeclareArgument(int argIndex, Instruction spvLocal)
  152. {
  153. _funcArgs.Add(argIndex, spvLocal);
  154. }
  155. public void DeclareFunction(int funcIndex, StructuredFunction function, Instruction spvFunc)
  156. {
  157. _functions.Add(funcIndex, (function, spvFunc));
  158. }
  159. public Instruction GetFP32(IAstNode node)
  160. {
  161. return Get(AggregateType.FP32, node);
  162. }
  163. public Instruction GetFP64(IAstNode node)
  164. {
  165. return Get(AggregateType.FP64, node);
  166. }
  167. public Instruction GetS32(IAstNode node)
  168. {
  169. return Get(AggregateType.S32, node);
  170. }
  171. public Instruction GetU32(IAstNode node)
  172. {
  173. return Get(AggregateType.U32, node);
  174. }
  175. public Instruction Get(AggregateType type, IAstNode node)
  176. {
  177. if (node is AstOperation operation)
  178. {
  179. var opResult = Instructions.Generate(this, operation);
  180. return BitcastIfNeeded(type, opResult.Type, opResult.Value);
  181. }
  182. else if (node is AstOperand operand)
  183. {
  184. return operand.Type switch
  185. {
  186. IrOperandType.Argument => GetArgument(type, operand),
  187. IrOperandType.Attribute => GetAttribute(type, operand.Value & AttributeConsts.Mask, (operand.Value & AttributeConsts.LoadOutputMask) != 0),
  188. IrOperandType.AttributePerPatch => GetAttributePerPatch(type, operand.Value & AttributeConsts.Mask, (operand.Value & AttributeConsts.LoadOutputMask) != 0),
  189. IrOperandType.Constant => GetConstant(type, operand),
  190. IrOperandType.ConstantBuffer => GetConstantBuffer(type, operand),
  191. IrOperandType.LocalVariable => GetLocal(type, operand),
  192. IrOperandType.Undefined => GetUndefined(type),
  193. _ => throw new ArgumentException($"Invalid operand type \"{operand.Type}\".")
  194. };
  195. }
  196. throw new NotImplementedException(node.GetType().Name);
  197. }
  198. private Instruction GetUndefined(AggregateType type)
  199. {
  200. return type switch
  201. {
  202. AggregateType.Bool => ConstantFalse(TypeBool()),
  203. AggregateType.FP32 => Constant(TypeFP32(), 0f),
  204. AggregateType.FP64 => Constant(TypeFP64(), 0d),
  205. _ => Constant(GetType(type), 0)
  206. };
  207. }
  208. public Instruction GetAttributeElemPointer(int attr, bool isOutAttr, Instruction index, out AggregateType elemType)
  209. {
  210. var storageClass = isOutAttr ? StorageClass.Output : StorageClass.Input;
  211. var attrInfo = AttributeInfo.From(Config, attr, isOutAttr);
  212. int attrOffset = attrInfo.BaseValue;
  213. AggregateType type = attrInfo.Type;
  214. Instruction ioVariable, elemIndex;
  215. bool isUserAttr = attr >= AttributeConsts.UserAttributeBase && attr < AttributeConsts.UserAttributeEnd;
  216. if (isUserAttr &&
  217. ((!isOutAttr && Config.UsedFeatures.HasFlag(FeatureFlags.IaIndexing)) ||
  218. (isOutAttr && Config.UsedFeatures.HasFlag(FeatureFlags.OaIndexing))))
  219. {
  220. elemType = AggregateType.FP32;
  221. ioVariable = isOutAttr ? OutputsArray : InputsArray;
  222. elemIndex = Constant(TypeU32(), attrInfo.GetInnermostIndex());
  223. var vecIndex = Constant(TypeU32(), (attr - AttributeConsts.UserAttributeBase) >> 4);
  224. if (AttributeInfo.IsArrayAttributeSpirv(Config.Stage, isOutAttr))
  225. {
  226. return AccessChain(TypePointer(storageClass, GetType(elemType)), ioVariable, index, vecIndex, elemIndex);
  227. }
  228. else
  229. {
  230. return AccessChain(TypePointer(storageClass, GetType(elemType)), ioVariable, vecIndex, elemIndex);
  231. }
  232. }
  233. bool isViewportInverse = attr == AttributeConsts.SupportBlockViewInverseX || attr == AttributeConsts.SupportBlockViewInverseY;
  234. if (isViewportInverse)
  235. {
  236. elemType = AggregateType.FP32;
  237. elemIndex = Constant(TypeU32(), (attr - AttributeConsts.SupportBlockViewInverseX) >> 2);
  238. return AccessChain(TypePointer(StorageClass.Uniform, TypeFP32()), SupportBuffer, Constant(TypeU32(), 2), elemIndex);
  239. }
  240. elemType = attrInfo.Type & AggregateType.ElementTypeMask;
  241. if (isUserAttr && Config.TransformFeedbackEnabled &&
  242. ((isOutAttr && Config.LastInVertexPipeline) ||
  243. (!isOutAttr && Config.Stage == ShaderStage.Fragment)))
  244. {
  245. attrOffset = attr;
  246. type = elemType;
  247. }
  248. ioVariable = isOutAttr ? Outputs[attrOffset] : Inputs[attrOffset];
  249. bool isIndexed = AttributeInfo.IsArrayAttributeSpirv(Config.Stage, isOutAttr) && (!attrInfo.IsBuiltin || AttributeInfo.IsArrayBuiltIn(attr));
  250. if ((type & (AggregateType.Array | AggregateType.Vector)) == 0)
  251. {
  252. return isIndexed ? AccessChain(TypePointer(storageClass, GetType(elemType)), ioVariable, index) : ioVariable;
  253. }
  254. elemIndex = Constant(TypeU32(), attrInfo.GetInnermostIndex());
  255. if (isIndexed)
  256. {
  257. return AccessChain(TypePointer(storageClass, GetType(elemType)), ioVariable, index, elemIndex);
  258. }
  259. else
  260. {
  261. return AccessChain(TypePointer(storageClass, GetType(elemType)), ioVariable, elemIndex);
  262. }
  263. }
  264. public Instruction GetAttributeElemPointer(Instruction attrIndex, bool isOutAttr, Instruction index, out AggregateType elemType)
  265. {
  266. var storageClass = isOutAttr ? StorageClass.Output : StorageClass.Input;
  267. elemType = AggregateType.FP32;
  268. var ioVariable = isOutAttr ? OutputsArray : InputsArray;
  269. var vecIndex = ShiftRightLogical(TypeS32(), attrIndex, Constant(TypeS32(), 2));
  270. var elemIndex = BitwiseAnd(TypeS32(), attrIndex, Constant(TypeS32(), 3));
  271. if (AttributeInfo.IsArrayAttributeSpirv(Config.Stage, isOutAttr))
  272. {
  273. return AccessChain(TypePointer(storageClass, GetType(elemType)), ioVariable, index, vecIndex, elemIndex);
  274. }
  275. else
  276. {
  277. return AccessChain(TypePointer(storageClass, GetType(elemType)), ioVariable, vecIndex, elemIndex);
  278. }
  279. }
  280. public Instruction GetAttribute(AggregateType type, int attr, bool isOutAttr, Instruction index = null)
  281. {
  282. if (!AttributeInfo.Validate(Config, attr, isOutAttr: false))
  283. {
  284. return GetConstant(type, new AstOperand(IrOperandType.Constant, 0));
  285. }
  286. var elemPointer = GetAttributeElemPointer(attr, isOutAttr, index, out var elemType);
  287. var value = Load(GetType(elemType), elemPointer);
  288. if (Config.Stage == ShaderStage.Fragment)
  289. {
  290. if (attr == AttributeConsts.PositionX || attr == AttributeConsts.PositionY)
  291. {
  292. var pointerType = TypePointer(StorageClass.Uniform, TypeFP32());
  293. var fieldIndex = Constant(TypeU32(), 4);
  294. var scaleIndex = Constant(TypeU32(), 0);
  295. var scaleElemPointer = AccessChain(pointerType, SupportBuffer, fieldIndex, scaleIndex);
  296. var scale = Load(TypeFP32(), scaleElemPointer);
  297. value = FDiv(TypeFP32(), value, scale);
  298. }
  299. else if (attr == AttributeConsts.FrontFacing && Config.GpuAccessor.QueryHostHasFrontFacingBug())
  300. {
  301. // Workaround for what appears to be a bug on Intel compiler.
  302. var valueFloat = Select(TypeFP32(), value, Constant(TypeFP32(), 1f), Constant(TypeFP32(), 0f));
  303. var valueAsInt = Bitcast(TypeS32(), valueFloat);
  304. var valueNegated = SNegate(TypeS32(), valueAsInt);
  305. value = SLessThan(TypeBool(), valueNegated, Constant(TypeS32(), 0));
  306. }
  307. }
  308. return BitcastIfNeeded(type, elemType, value);
  309. }
  310. public Instruction GetAttributePerPatchElemPointer(int attr, bool isOutAttr, out AggregateType elemType)
  311. {
  312. var storageClass = isOutAttr ? StorageClass.Output : StorageClass.Input;
  313. var attrInfo = AttributeInfo.From(Config, attr, isOutAttr);
  314. int attrOffset = attrInfo.BaseValue;
  315. Instruction ioVariable;
  316. bool isUserAttr = attr >= AttributeConsts.UserAttributeBase && attr < AttributeConsts.UserAttributeEnd;
  317. elemType = attrInfo.Type & AggregateType.ElementTypeMask;
  318. ioVariable = isOutAttr ? OutputsPerPatch[attrOffset] : InputsPerPatch[attrOffset];
  319. if ((attrInfo.Type & (AggregateType.Array | AggregateType.Vector)) == 0)
  320. {
  321. return ioVariable;
  322. }
  323. var elemIndex = Constant(TypeU32(), attrInfo.GetInnermostIndex());
  324. return AccessChain(TypePointer(storageClass, GetType(elemType)), ioVariable, elemIndex);
  325. }
  326. public Instruction GetAttributePerPatch(AggregateType type, int attr, bool isOutAttr)
  327. {
  328. if (!AttributeInfo.Validate(Config, attr, isOutAttr: false))
  329. {
  330. return GetConstant(type, new AstOperand(IrOperandType.Constant, 0));
  331. }
  332. var elemPointer = GetAttributePerPatchElemPointer(attr, isOutAttr, out var elemType);
  333. return BitcastIfNeeded(type, elemType, Load(GetType(elemType), elemPointer));
  334. }
  335. public Instruction GetAttribute(AggregateType type, Instruction attr, bool isOutAttr, Instruction index = null)
  336. {
  337. var elemPointer = GetAttributeElemPointer(attr, isOutAttr, index, out var elemType);
  338. return BitcastIfNeeded(type, elemType, Load(GetType(elemType), elemPointer));
  339. }
  340. public Instruction GetConstant(AggregateType type, AstOperand operand)
  341. {
  342. return type switch
  343. {
  344. AggregateType.Bool => operand.Value != 0 ? ConstantTrue(TypeBool()) : ConstantFalse(TypeBool()),
  345. AggregateType.FP32 => Constant(TypeFP32(), BitConverter.Int32BitsToSingle(operand.Value)),
  346. AggregateType.FP64 => Constant(TypeFP64(), (double)BitConverter.Int32BitsToSingle(operand.Value)),
  347. AggregateType.S32 => Constant(TypeS32(), operand.Value),
  348. AggregateType.U32 => Constant(TypeU32(), (uint)operand.Value),
  349. _ => throw new ArgumentException($"Invalid type \"{type}\".")
  350. };
  351. }
  352. public Instruction GetConstantBuffer(AggregateType type, AstOperand operand)
  353. {
  354. var i1 = Constant(TypeS32(), 0);
  355. var i2 = Constant(TypeS32(), operand.CbufOffset >> 2);
  356. var i3 = Constant(TypeU32(), operand.CbufOffset & 3);
  357. Instruction elemPointer;
  358. if (UniformBuffersArray != null)
  359. {
  360. var ubVariable = UniformBuffersArray;
  361. var i0 = Constant(TypeS32(), operand.CbufSlot);
  362. elemPointer = AccessChain(TypePointer(StorageClass.Uniform, TypeFP32()), ubVariable, i0, i1, i2, i3);
  363. }
  364. else
  365. {
  366. var ubVariable = UniformBuffers[operand.CbufSlot];
  367. elemPointer = AccessChain(TypePointer(StorageClass.Uniform, TypeFP32()), ubVariable, i1, i2, i3);
  368. }
  369. return BitcastIfNeeded(type, AggregateType.FP32, Load(TypeFP32(), elemPointer));
  370. }
  371. public Instruction GetLocalPointer(AstOperand local)
  372. {
  373. return _locals[local];
  374. }
  375. public Instruction[] GetLocalForArgsPointers(int funcIndex)
  376. {
  377. return _localForArgs[funcIndex];
  378. }
  379. public Instruction GetArgumentPointer(AstOperand funcArg)
  380. {
  381. return _funcArgs[funcArg.Value];
  382. }
  383. public Instruction GetLocal(AggregateType dstType, AstOperand local)
  384. {
  385. var srcType = local.VarType.Convert();
  386. return BitcastIfNeeded(dstType, srcType, Load(GetType(srcType), GetLocalPointer(local)));
  387. }
  388. public Instruction GetArgument(AggregateType dstType, AstOperand funcArg)
  389. {
  390. var srcType = funcArg.VarType.Convert();
  391. return BitcastIfNeeded(dstType, srcType, Load(GetType(srcType), GetArgumentPointer(funcArg)));
  392. }
  393. public (StructuredFunction, Instruction) GetFunction(int funcIndex)
  394. {
  395. return _functions[funcIndex];
  396. }
  397. public TransformFeedbackOutput GetTransformFeedbackOutput(int location, int component)
  398. {
  399. int index = (AttributeConsts.UserAttributeBase / 4) + location * 4 + component;
  400. return _info.TransformFeedbackOutputs[index];
  401. }
  402. public TransformFeedbackOutput GetTransformFeedbackOutput(int location)
  403. {
  404. int index = location / 4;
  405. return _info.TransformFeedbackOutputs[index];
  406. }
  407. public Instruction GetType(AggregateType type, int length = 1)
  408. {
  409. if (type.HasFlag(AggregateType.Array))
  410. {
  411. return TypeArray(GetType(type & ~AggregateType.Array), Constant(TypeU32(), length));
  412. }
  413. else if (type.HasFlag(AggregateType.Vector))
  414. {
  415. return TypeVector(GetType(type & ~AggregateType.Vector), length);
  416. }
  417. return type switch
  418. {
  419. AggregateType.Void => TypeVoid(),
  420. AggregateType.Bool => TypeBool(),
  421. AggregateType.FP32 => TypeFP32(),
  422. AggregateType.FP64 => TypeFP64(),
  423. AggregateType.S32 => TypeS32(),
  424. AggregateType.U32 => TypeU32(),
  425. _ => throw new ArgumentException($"Invalid attribute type \"{type}\".")
  426. };
  427. }
  428. public Instruction BitcastIfNeeded(AggregateType dstType, AggregateType srcType, Instruction value)
  429. {
  430. if (dstType == srcType)
  431. {
  432. return value;
  433. }
  434. if (dstType == AggregateType.Bool)
  435. {
  436. return INotEqual(TypeBool(), BitcastIfNeeded(AggregateType.S32, srcType, value), Constant(TypeS32(), 0));
  437. }
  438. else if (srcType == AggregateType.Bool)
  439. {
  440. var intTrue = Constant(TypeS32(), IrConsts.True);
  441. var intFalse = Constant(TypeS32(), IrConsts.False);
  442. return BitcastIfNeeded(dstType, AggregateType.S32, Select(TypeS32(), value, intTrue, intFalse));
  443. }
  444. else
  445. {
  446. return Bitcast(GetType(dstType, 1), value);
  447. }
  448. }
  449. public Instruction TypeS32()
  450. {
  451. return TypeInt(32, true);
  452. }
  453. public Instruction TypeU32()
  454. {
  455. return TypeInt(32, false);
  456. }
  457. public Instruction TypeFP32()
  458. {
  459. return TypeFloat(32);
  460. }
  461. public Instruction TypeFP64()
  462. {
  463. return TypeFloat(64);
  464. }
  465. }
  466. }