CodeGenContext.cs 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656
  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. public StructuredProgramInfo Info { get; }
  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. public Instruction GetWithType(IAstNode node, out AggregateType type)
  199. {
  200. if (node is AstOperation operation)
  201. {
  202. var opResult = Instructions.Generate(this, operation);
  203. type = opResult.Type;
  204. return opResult.Value;
  205. }
  206. else if (node is AstOperand operand)
  207. {
  208. switch (operand.Type)
  209. {
  210. case IrOperandType.LocalVariable:
  211. type = operand.VarType;
  212. return GetLocal(type, operand);
  213. default:
  214. throw new ArgumentException($"Invalid operand type \"{operand.Type}\".");
  215. }
  216. }
  217. throw new NotImplementedException(node.GetType().Name);
  218. }
  219. private Instruction GetUndefined(AggregateType type)
  220. {
  221. return type switch
  222. {
  223. AggregateType.Bool => ConstantFalse(TypeBool()),
  224. AggregateType.FP32 => Constant(TypeFP32(), 0f),
  225. AggregateType.FP64 => Constant(TypeFP64(), 0d),
  226. _ => Constant(GetType(type), 0)
  227. };
  228. }
  229. public Instruction GetAttributeElemPointer(int attr, bool isOutAttr, Instruction index, out AggregateType elemType)
  230. {
  231. var storageClass = isOutAttr ? StorageClass.Output : StorageClass.Input;
  232. var attrInfo = AttributeInfo.From(Config, attr, isOutAttr);
  233. int attrOffset = attrInfo.BaseValue;
  234. AggregateType type = attrInfo.Type;
  235. Instruction ioVariable, elemIndex;
  236. Instruction invocationId = null;
  237. if (Config.Stage == ShaderStage.TessellationControl && isOutAttr)
  238. {
  239. invocationId = Load(TypeS32(), Inputs[AttributeConsts.InvocationId]);
  240. }
  241. bool isUserAttr = attr >= AttributeConsts.UserAttributeBase && attr < AttributeConsts.UserAttributeEnd;
  242. if (isUserAttr &&
  243. ((!isOutAttr && Config.UsedFeatures.HasFlag(FeatureFlags.IaIndexing)) ||
  244. (isOutAttr && Config.UsedFeatures.HasFlag(FeatureFlags.OaIndexing))))
  245. {
  246. elemType = AggregateType.FP32;
  247. ioVariable = isOutAttr ? OutputsArray : InputsArray;
  248. elemIndex = Constant(TypeU32(), attrInfo.GetInnermostIndex());
  249. var vecIndex = Constant(TypeU32(), (attr - AttributeConsts.UserAttributeBase) >> 4);
  250. bool isArray = AttributeInfo.IsArrayAttributeSpirv(Config.Stage, isOutAttr);
  251. if (invocationId != null && isArray)
  252. {
  253. return AccessChain(TypePointer(storageClass, GetType(elemType)), ioVariable, invocationId, index, vecIndex, elemIndex);
  254. }
  255. else if (invocationId != null)
  256. {
  257. return AccessChain(TypePointer(storageClass, GetType(elemType)), ioVariable, invocationId, vecIndex, elemIndex);
  258. }
  259. else if (isArray)
  260. {
  261. return AccessChain(TypePointer(storageClass, GetType(elemType)), ioVariable, index, vecIndex, elemIndex);
  262. }
  263. else
  264. {
  265. return AccessChain(TypePointer(storageClass, GetType(elemType)), ioVariable, vecIndex, elemIndex);
  266. }
  267. }
  268. bool isViewportInverse = attr == AttributeConsts.SupportBlockViewInverseX || attr == AttributeConsts.SupportBlockViewInverseY;
  269. if (isViewportInverse)
  270. {
  271. elemType = AggregateType.FP32;
  272. elemIndex = Constant(TypeU32(), (attr - AttributeConsts.SupportBlockViewInverseX) >> 2);
  273. return AccessChain(TypePointer(StorageClass.Uniform, TypeFP32()), SupportBuffer, Constant(TypeU32(), 2), elemIndex);
  274. }
  275. elemType = attrInfo.Type & AggregateType.ElementTypeMask;
  276. if (isUserAttr && Config.TransformFeedbackEnabled &&
  277. ((isOutAttr && Config.LastInVertexPipeline) ||
  278. (!isOutAttr && Config.Stage == ShaderStage.Fragment)))
  279. {
  280. attrOffset = attr;
  281. type = elemType;
  282. if (Config.LastInPipeline && isOutAttr)
  283. {
  284. int components = Info.GetTransformFeedbackOutputComponents(attr);
  285. if (components > 1)
  286. {
  287. attrOffset &= ~0xf;
  288. type = components switch
  289. {
  290. 2 => AggregateType.Vector2 | AggregateType.FP32,
  291. 3 => AggregateType.Vector3 | AggregateType.FP32,
  292. 4 => AggregateType.Vector4 | AggregateType.FP32,
  293. _ => AggregateType.FP32
  294. };
  295. attrInfo = new AttributeInfo(attrOffset, (attr - attrOffset) / 4, components, type, false);
  296. }
  297. }
  298. }
  299. ioVariable = isOutAttr ? Outputs[attrOffset] : Inputs[attrOffset];
  300. bool isIndexed = AttributeInfo.IsArrayAttributeSpirv(Config.Stage, isOutAttr) && (!attrInfo.IsBuiltin || AttributeInfo.IsArrayBuiltIn(attr));
  301. if ((type & (AggregateType.Array | AggregateType.ElementCountMask)) == 0)
  302. {
  303. if (invocationId != null)
  304. {
  305. return isIndexed
  306. ? AccessChain(TypePointer(storageClass, GetType(elemType)), ioVariable, invocationId, index)
  307. : AccessChain(TypePointer(storageClass, GetType(elemType)), ioVariable, invocationId);
  308. }
  309. else
  310. {
  311. return isIndexed ? AccessChain(TypePointer(storageClass, GetType(elemType)), ioVariable, index) : ioVariable;
  312. }
  313. }
  314. elemIndex = Constant(TypeU32(), attrInfo.GetInnermostIndex());
  315. if (invocationId != null && isIndexed)
  316. {
  317. return AccessChain(TypePointer(storageClass, GetType(elemType)), ioVariable, invocationId, index, elemIndex);
  318. }
  319. else if (invocationId != null)
  320. {
  321. return AccessChain(TypePointer(storageClass, GetType(elemType)), ioVariable, invocationId, elemIndex);
  322. }
  323. else if (isIndexed)
  324. {
  325. return AccessChain(TypePointer(storageClass, GetType(elemType)), ioVariable, index, elemIndex);
  326. }
  327. else
  328. {
  329. return AccessChain(TypePointer(storageClass, GetType(elemType)), ioVariable, elemIndex);
  330. }
  331. }
  332. public Instruction GetAttributeElemPointer(Instruction attrIndex, bool isOutAttr, Instruction index, out AggregateType elemType)
  333. {
  334. var storageClass = isOutAttr ? StorageClass.Output : StorageClass.Input;
  335. Instruction invocationId = null;
  336. if (Config.Stage == ShaderStage.TessellationControl && isOutAttr)
  337. {
  338. invocationId = Load(TypeS32(), Inputs[AttributeConsts.InvocationId]);
  339. }
  340. elemType = AggregateType.FP32;
  341. var ioVariable = isOutAttr ? OutputsArray : InputsArray;
  342. var vecIndex = ShiftRightLogical(TypeS32(), attrIndex, Constant(TypeS32(), 2));
  343. var elemIndex = BitwiseAnd(TypeS32(), attrIndex, Constant(TypeS32(), 3));
  344. bool isArray = AttributeInfo.IsArrayAttributeSpirv(Config.Stage, isOutAttr);
  345. if (invocationId != null && isArray)
  346. {
  347. return AccessChain(TypePointer(storageClass, GetType(elemType)), ioVariable, invocationId, index, vecIndex, elemIndex);
  348. }
  349. else if (invocationId != null)
  350. {
  351. return AccessChain(TypePointer(storageClass, GetType(elemType)), ioVariable, invocationId, vecIndex, elemIndex);
  352. }
  353. else if (isArray)
  354. {
  355. return AccessChain(TypePointer(storageClass, GetType(elemType)), ioVariable, index, vecIndex, elemIndex);
  356. }
  357. else
  358. {
  359. return AccessChain(TypePointer(storageClass, GetType(elemType)), ioVariable, vecIndex, elemIndex);
  360. }
  361. }
  362. public Instruction GetAttribute(AggregateType type, int attr, bool isOutAttr, Instruction index = null)
  363. {
  364. if (!AttributeInfo.Validate(Config, attr, isOutAttr: false))
  365. {
  366. return GetConstant(type, new AstOperand(IrOperandType.Constant, 0));
  367. }
  368. var elemPointer = GetAttributeElemPointer(attr, isOutAttr, index, out var elemType);
  369. var value = Load(GetType(elemType), elemPointer);
  370. if (Config.Stage == ShaderStage.Fragment)
  371. {
  372. if (attr == AttributeConsts.PositionX || attr == AttributeConsts.PositionY)
  373. {
  374. var pointerType = TypePointer(StorageClass.Uniform, TypeFP32());
  375. var fieldIndex = Constant(TypeU32(), 4);
  376. var scaleIndex = Constant(TypeU32(), 0);
  377. var scaleElemPointer = AccessChain(pointerType, SupportBuffer, fieldIndex, scaleIndex);
  378. var scale = Load(TypeFP32(), scaleElemPointer);
  379. value = FDiv(TypeFP32(), value, scale);
  380. }
  381. else if (attr == AttributeConsts.FrontFacing && Config.GpuAccessor.QueryHostHasFrontFacingBug())
  382. {
  383. // Workaround for what appears to be a bug on Intel compiler.
  384. var valueFloat = Select(TypeFP32(), value, Constant(TypeFP32(), 1f), Constant(TypeFP32(), 0f));
  385. var valueAsInt = Bitcast(TypeS32(), valueFloat);
  386. var valueNegated = SNegate(TypeS32(), valueAsInt);
  387. value = SLessThan(TypeBool(), valueNegated, Constant(TypeS32(), 0));
  388. }
  389. }
  390. return BitcastIfNeeded(type, elemType, value);
  391. }
  392. public Instruction GetAttributePerPatchElemPointer(int attr, bool isOutAttr, out AggregateType elemType)
  393. {
  394. var storageClass = isOutAttr ? StorageClass.Output : StorageClass.Input;
  395. var attrInfo = AttributeInfo.FromPatch(Config, attr, isOutAttr);
  396. int attrOffset = attrInfo.BaseValue;
  397. Instruction ioVariable = isOutAttr ? OutputsPerPatch[attrOffset] : InputsPerPatch[attrOffset];
  398. elemType = attrInfo.Type & AggregateType.ElementTypeMask;
  399. if ((attrInfo.Type & (AggregateType.Array | AggregateType.ElementCountMask)) == 0)
  400. {
  401. return ioVariable;
  402. }
  403. var elemIndex = Constant(TypeU32(), attrInfo.GetInnermostIndex());
  404. return AccessChain(TypePointer(storageClass, GetType(elemType)), ioVariable, elemIndex);
  405. }
  406. public Instruction GetAttributePerPatch(AggregateType type, int attr, bool isOutAttr)
  407. {
  408. if (!AttributeInfo.ValidatePerPatch(Config, attr, isOutAttr: false))
  409. {
  410. return GetConstant(type, new AstOperand(IrOperandType.Constant, 0));
  411. }
  412. var elemPointer = GetAttributePerPatchElemPointer(attr, isOutAttr, out var elemType);
  413. return BitcastIfNeeded(type, elemType, Load(GetType(elemType), elemPointer));
  414. }
  415. public Instruction GetAttribute(AggregateType type, Instruction attr, bool isOutAttr, Instruction index = null)
  416. {
  417. var elemPointer = GetAttributeElemPointer(attr, isOutAttr, index, out var elemType);
  418. return BitcastIfNeeded(type, elemType, Load(GetType(elemType), elemPointer));
  419. }
  420. public Instruction GetConstant(AggregateType type, AstOperand operand)
  421. {
  422. return type switch
  423. {
  424. AggregateType.Bool => operand.Value != 0 ? ConstantTrue(TypeBool()) : ConstantFalse(TypeBool()),
  425. AggregateType.FP32 => Constant(TypeFP32(), BitConverter.Int32BitsToSingle(operand.Value)),
  426. AggregateType.FP64 => Constant(TypeFP64(), (double)BitConverter.Int32BitsToSingle(operand.Value)),
  427. AggregateType.S32 => Constant(TypeS32(), operand.Value),
  428. AggregateType.U32 => Constant(TypeU32(), (uint)operand.Value),
  429. _ => throw new ArgumentException($"Invalid type \"{type}\".")
  430. };
  431. }
  432. public Instruction GetConstantBuffer(AggregateType type, AstOperand operand)
  433. {
  434. var i1 = Constant(TypeS32(), 0);
  435. var i2 = Constant(TypeS32(), operand.CbufOffset >> 2);
  436. var i3 = Constant(TypeU32(), operand.CbufOffset & 3);
  437. Instruction elemPointer;
  438. if (UniformBuffersArray != null)
  439. {
  440. var ubVariable = UniformBuffersArray;
  441. var i0 = Constant(TypeS32(), operand.CbufSlot);
  442. elemPointer = AccessChain(TypePointer(StorageClass.Uniform, TypeFP32()), ubVariable, i0, i1, i2, i3);
  443. }
  444. else
  445. {
  446. var ubVariable = UniformBuffers[operand.CbufSlot];
  447. elemPointer = AccessChain(TypePointer(StorageClass.Uniform, TypeFP32()), ubVariable, i1, i2, i3);
  448. }
  449. return BitcastIfNeeded(type, AggregateType.FP32, Load(TypeFP32(), elemPointer));
  450. }
  451. public Instruction GetLocalPointer(AstOperand local)
  452. {
  453. return _locals[local];
  454. }
  455. public Instruction[] GetLocalForArgsPointers(int funcIndex)
  456. {
  457. return _localForArgs[funcIndex];
  458. }
  459. public Instruction GetArgumentPointer(AstOperand funcArg)
  460. {
  461. return _funcArgs[funcArg.Value];
  462. }
  463. public Instruction GetLocal(AggregateType dstType, AstOperand local)
  464. {
  465. var srcType = local.VarType;
  466. return BitcastIfNeeded(dstType, srcType, Load(GetType(srcType), GetLocalPointer(local)));
  467. }
  468. public Instruction GetArgument(AggregateType dstType, AstOperand funcArg)
  469. {
  470. var srcType = funcArg.VarType;
  471. return BitcastIfNeeded(dstType, srcType, Load(GetType(srcType), GetArgumentPointer(funcArg)));
  472. }
  473. public (StructuredFunction, Instruction) GetFunction(int funcIndex)
  474. {
  475. return _functions[funcIndex];
  476. }
  477. public Instruction GetType(AggregateType type, int length = 1)
  478. {
  479. if ((type & AggregateType.Array) != 0)
  480. {
  481. return TypeArray(GetType(type & ~AggregateType.Array), Constant(TypeU32(), length));
  482. }
  483. else if ((type & AggregateType.ElementCountMask) != 0)
  484. {
  485. int vectorLength = (type & AggregateType.ElementCountMask) switch
  486. {
  487. AggregateType.Vector2 => 2,
  488. AggregateType.Vector3 => 3,
  489. AggregateType.Vector4 => 4,
  490. _ => 1
  491. };
  492. return TypeVector(GetType(type & ~AggregateType.ElementCountMask), vectorLength);
  493. }
  494. return type switch
  495. {
  496. AggregateType.Void => TypeVoid(),
  497. AggregateType.Bool => TypeBool(),
  498. AggregateType.FP32 => TypeFP32(),
  499. AggregateType.FP64 => TypeFP64(),
  500. AggregateType.S32 => TypeS32(),
  501. AggregateType.U32 => TypeU32(),
  502. _ => throw new ArgumentException($"Invalid attribute type \"{type}\".")
  503. };
  504. }
  505. public Instruction BitcastIfNeeded(AggregateType dstType, AggregateType srcType, Instruction value)
  506. {
  507. if (dstType == srcType)
  508. {
  509. return value;
  510. }
  511. if (dstType == AggregateType.Bool)
  512. {
  513. return INotEqual(TypeBool(), BitcastIfNeeded(AggregateType.S32, srcType, value), Constant(TypeS32(), 0));
  514. }
  515. else if (srcType == AggregateType.Bool)
  516. {
  517. var intTrue = Constant(TypeS32(), IrConsts.True);
  518. var intFalse = Constant(TypeS32(), IrConsts.False);
  519. return BitcastIfNeeded(dstType, AggregateType.S32, Select(TypeS32(), value, intTrue, intFalse));
  520. }
  521. else
  522. {
  523. return Bitcast(GetType(dstType, 1), value);
  524. }
  525. }
  526. public Instruction TypeS32()
  527. {
  528. return TypeInt(32, true);
  529. }
  530. public Instruction TypeU32()
  531. {
  532. return TypeInt(32, false);
  533. }
  534. public Instruction TypeFP32()
  535. {
  536. return TypeFloat(32);
  537. }
  538. public Instruction TypeFP64()
  539. {
  540. return TypeFloat(64);
  541. }
  542. }
  543. }