Module.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  1. using System.Collections.Generic;
  2. using System.Diagnostics;
  3. using System.IO;
  4. using static Spv.Specification;
  5. namespace Spv.Generator
  6. {
  7. public partial class Module
  8. {
  9. // TODO: Register on SPIR-V registry.
  10. private const int GeneratorId = 0;
  11. private readonly uint _version;
  12. private uint _bound;
  13. // Follow spec order here while keeping it as simple as possible.
  14. private List<Capability> _capabilities;
  15. private List<string> _extensions;
  16. private Dictionary<DeterministicStringKey, Instruction> _extInstImports;
  17. private AddressingModel _addressingModel;
  18. private MemoryModel _memoryModel;
  19. private List<Instruction> _entrypoints;
  20. private List<Instruction> _executionModes;
  21. private List<Instruction> _debug;
  22. private List<Instruction> _annotations;
  23. // In the declaration block.
  24. private Dictionary<TypeDeclarationKey, Instruction> _typeDeclarations;
  25. // In the declaration block.
  26. private List<Instruction> _globals;
  27. // In the declaration block.
  28. private Dictionary<ConstantKey, Instruction> _constants;
  29. // In the declaration block, for function that aren't defined in the module.
  30. private List<Instruction> _functionsDeclarations;
  31. private List<Instruction> _functionsDefinitions;
  32. private GeneratorPool<Instruction> _instPool;
  33. private GeneratorPool<LiteralInteger> _integerPool;
  34. public Module(uint version, GeneratorPool<Instruction> instPool = null, GeneratorPool<LiteralInteger> integerPool = null)
  35. {
  36. _version = version;
  37. _bound = 1;
  38. _capabilities = new List<Capability>();
  39. _extensions = new List<string>();
  40. _extInstImports = new Dictionary<DeterministicStringKey, Instruction>();
  41. _addressingModel = AddressingModel.Logical;
  42. _memoryModel = MemoryModel.Simple;
  43. _entrypoints = new List<Instruction>();
  44. _executionModes = new List<Instruction>();
  45. _debug = new List<Instruction>();
  46. _annotations = new List<Instruction>();
  47. _typeDeclarations = new Dictionary<TypeDeclarationKey, Instruction>();
  48. _constants = new Dictionary<ConstantKey, Instruction>();
  49. _globals = new List<Instruction>();
  50. _functionsDeclarations = new List<Instruction>();
  51. _functionsDefinitions = new List<Instruction>();
  52. _instPool = instPool ?? new GeneratorPool<Instruction>();
  53. _integerPool = integerPool ?? new GeneratorPool<LiteralInteger>();
  54. LiteralInteger.RegisterPool(_integerPool);
  55. }
  56. private uint GetNewId()
  57. {
  58. return _bound++;
  59. }
  60. public void AddCapability(Capability capability)
  61. {
  62. _capabilities.Add(capability);
  63. }
  64. public void AddExtension(string extension)
  65. {
  66. _extensions.Add(extension);
  67. }
  68. public Instruction NewInstruction(Op opcode, uint id = Instruction.InvalidId, Instruction resultType = null)
  69. {
  70. var result = _instPool.Allocate();
  71. result.Set(opcode, id, resultType);
  72. return result;
  73. }
  74. public Instruction AddExtInstImport(string import)
  75. {
  76. var key = new DeterministicStringKey(import);
  77. if (_extInstImports.TryGetValue(key, out Instruction extInstImport))
  78. {
  79. // Update the duplicate instance to use the good id so it ends up being encoded correctly.
  80. return extInstImport;
  81. }
  82. Instruction instruction = NewInstruction(Op.OpExtInstImport);
  83. instruction.AddOperand(import);
  84. instruction.SetId(GetNewId());
  85. _extInstImports.Add(key, instruction);
  86. return instruction;
  87. }
  88. private void AddTypeDeclaration(Instruction instruction, bool forceIdAllocation)
  89. {
  90. var key = new TypeDeclarationKey(instruction);
  91. if (!forceIdAllocation)
  92. {
  93. if (_typeDeclarations.TryGetValue(key, out Instruction typeDeclaration))
  94. {
  95. // Update the duplicate instance to use the good id so it ends up being encoded correctly.
  96. instruction.SetId(typeDeclaration.Id);
  97. return;
  98. }
  99. }
  100. instruction.SetId(GetNewId());
  101. _typeDeclarations.Add(key, instruction);
  102. }
  103. public void AddEntryPoint(ExecutionModel executionModel, Instruction function, string name, params Instruction[] interfaces)
  104. {
  105. Debug.Assert(function.Opcode == Op.OpFunction);
  106. Instruction entryPoint = NewInstruction(Op.OpEntryPoint);
  107. entryPoint.AddOperand(executionModel);
  108. entryPoint.AddOperand(function);
  109. entryPoint.AddOperand(name);
  110. entryPoint.AddOperand(interfaces);
  111. _entrypoints.Add(entryPoint);
  112. }
  113. public void AddExecutionMode(Instruction function, ExecutionMode mode, params Operand[] parameters)
  114. {
  115. Debug.Assert(function.Opcode == Op.OpFunction);
  116. Instruction executionModeInstruction = NewInstruction(Op.OpExecutionMode);
  117. executionModeInstruction.AddOperand(function);
  118. executionModeInstruction.AddOperand(mode);
  119. executionModeInstruction.AddOperand(parameters);
  120. _executionModes.Add(executionModeInstruction);
  121. }
  122. private void AddToFunctionDefinitions(Instruction instruction)
  123. {
  124. Debug.Assert(instruction.Opcode != Op.OpTypeInt);
  125. _functionsDefinitions.Add(instruction);
  126. }
  127. private void AddAnnotation(Instruction annotation)
  128. {
  129. _annotations.Add(annotation);
  130. }
  131. private void AddDebug(Instruction debug)
  132. {
  133. _debug.Add(debug);
  134. }
  135. public void AddLabel(Instruction label)
  136. {
  137. Debug.Assert(label.Opcode == Op.OpLabel);
  138. label.SetId(GetNewId());
  139. AddToFunctionDefinitions(label);
  140. }
  141. public void AddLocalVariable(Instruction variable)
  142. {
  143. // TODO: Ensure it has the local modifier.
  144. Debug.Assert(variable.Opcode == Op.OpVariable);
  145. variable.SetId(GetNewId());
  146. AddToFunctionDefinitions(variable);
  147. }
  148. public void AddGlobalVariable(Instruction variable)
  149. {
  150. // TODO: Ensure it has the global modifier.
  151. // TODO: All constants opcodes (OpSpecXXX and the rest of the OpConstantXXX).
  152. Debug.Assert(variable.Opcode == Op.OpVariable);
  153. variable.SetId(GetNewId());
  154. _globals.Add(variable);
  155. }
  156. private void AddConstant(Instruction constant)
  157. {
  158. Debug.Assert(constant.Opcode == Op.OpConstant ||
  159. constant.Opcode == Op.OpConstantFalse ||
  160. constant.Opcode == Op.OpConstantTrue ||
  161. constant.Opcode == Op.OpConstantNull ||
  162. constant.Opcode == Op.OpConstantComposite);
  163. var key = new ConstantKey(constant);
  164. if (_constants.TryGetValue(key, out Instruction global))
  165. {
  166. // Update the duplicate instance to use the good id so it ends up being encoded correctly.
  167. constant.SetId(global.Id);
  168. return;
  169. }
  170. constant.SetId(GetNewId());
  171. _constants.Add(key, constant);
  172. }
  173. public Instruction ExtInst(Instruction resultType, Instruction set, LiteralInteger instruction, params Operand[] parameters)
  174. {
  175. Instruction result = NewInstruction(Op.OpExtInst, GetNewId(), resultType);
  176. result.AddOperand(set);
  177. result.AddOperand(instruction);
  178. result.AddOperand(parameters);
  179. AddToFunctionDefinitions(result);
  180. return result;
  181. }
  182. public void SetMemoryModel(AddressingModel addressingModel, MemoryModel memoryModel)
  183. {
  184. _addressingModel = addressingModel;
  185. _memoryModel = memoryModel;
  186. }
  187. // TODO: Find a way to make the auto generate one used.
  188. public Instruction OpenClPrintf(Instruction resultType, Instruction format, params Instruction[] additionalarguments)
  189. {
  190. Instruction result = NewInstruction(Op.OpExtInst, GetNewId(), resultType);
  191. result.AddOperand(AddExtInstImport("OpenCL.std"));
  192. result.AddOperand((LiteralInteger)184);
  193. result.AddOperand(format);
  194. result.AddOperand(additionalarguments);
  195. AddToFunctionDefinitions(result);
  196. return result;
  197. }
  198. public byte[] Generate()
  199. {
  200. // Estimate the size needed for the generated code, to avoid expanding the MemoryStream.
  201. int sizeEstimate = 1024 + _functionsDefinitions.Count * 32;
  202. using (MemoryStream stream = new MemoryStream(sizeEstimate))
  203. {
  204. BinaryWriter writer = new BinaryWriter(stream, System.Text.Encoding.ASCII);
  205. // Header
  206. writer.Write(MagicNumber);
  207. writer.Write(_version);
  208. writer.Write(GeneratorId);
  209. writer.Write(_bound);
  210. writer.Write(0u);
  211. // 1.
  212. foreach (Capability capability in _capabilities)
  213. {
  214. Instruction capabilityInstruction = NewInstruction(Op.OpCapability);
  215. capabilityInstruction.AddOperand(capability);
  216. capabilityInstruction.Write(writer);
  217. }
  218. // 2.
  219. foreach (string extension in _extensions)
  220. {
  221. Instruction extensionInstruction = NewInstruction(Op.OpExtension);
  222. extensionInstruction.AddOperand(extension);
  223. extensionInstruction.Write(writer);
  224. }
  225. // 3.
  226. foreach (Instruction extInstImport in _extInstImports.Values)
  227. {
  228. extInstImport.Write(writer);
  229. }
  230. // 4.
  231. Instruction memoryModelInstruction = NewInstruction(Op.OpMemoryModel);
  232. memoryModelInstruction.AddOperand(_addressingModel);
  233. memoryModelInstruction.AddOperand(_memoryModel);
  234. memoryModelInstruction.Write(writer);
  235. // 5.
  236. foreach (Instruction entrypoint in _entrypoints)
  237. {
  238. entrypoint.Write(writer);
  239. }
  240. // 6.
  241. foreach (Instruction executionMode in _executionModes)
  242. {
  243. executionMode.Write(writer);
  244. }
  245. // 7.
  246. // TODO: Order debug information correctly.
  247. foreach (Instruction debug in _debug)
  248. {
  249. debug.Write(writer);
  250. }
  251. // 8.
  252. foreach (Instruction annotation in _annotations)
  253. {
  254. annotation.Write(writer);
  255. }
  256. // Ensure that everything is in the right order in the declarations section.
  257. List<Instruction> declarations = new List<Instruction>();
  258. declarations.AddRange(_typeDeclarations.Values);
  259. declarations.AddRange(_globals);
  260. declarations.AddRange(_constants.Values);
  261. declarations.Sort((Instruction x, Instruction y) => x.Id.CompareTo(y.Id));
  262. // 9.
  263. foreach (Instruction declaration in declarations)
  264. {
  265. declaration.Write(writer);
  266. }
  267. // 10.
  268. foreach (Instruction functionDeclaration in _functionsDeclarations)
  269. {
  270. functionDeclaration.Write(writer);
  271. }
  272. // 11.
  273. foreach (Instruction functionDefinition in _functionsDefinitions)
  274. {
  275. functionDefinition.Write(writer);
  276. }
  277. _instPool.Clear();
  278. _integerPool.Clear();
  279. LiteralInteger.UnregisterPool();
  280. return stream.ToArray();
  281. }
  282. }
  283. }
  284. }