SpvPostProcess.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  1. //
  2. // Copyright (C) 2018 Google, Inc.
  3. //
  4. // All rights reserved.
  5. //
  6. // Redistribution and use in source and binary forms, with or without
  7. // modification, are permitted provided that the following conditions
  8. // are met:
  9. //
  10. // Redistributions of source code must retain the above copyright
  11. // notice, this list of conditions and the following disclaimer.
  12. //
  13. // Redistributions in binary form must reproduce the above
  14. // copyright notice, this list of conditions and the following
  15. // disclaimer in the documentation and/or other materials provided
  16. // with the distribution.
  17. //
  18. // Neither the name of 3Dlabs Inc. Ltd. nor the names of its
  19. // contributors may be used to endorse or promote products derived
  20. // from this software without specific prior written permission.
  21. //
  22. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  23. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  24. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
  25. // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
  26. // COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
  27. // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
  28. // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  29. // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  30. // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  31. // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
  32. // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  33. // POSSIBILITY OF SUCH DAMAGE.
  34. //
  35. // Post-processing for SPIR-V IR, in internal form, not standard binary form.
  36. //
  37. #include <cassert>
  38. #include <cstdlib>
  39. #include <unordered_set>
  40. #include <algorithm>
  41. #include "SpvBuilder.h"
  42. #include "spirv.hpp"
  43. #include "GlslangToSpv.h"
  44. #include "SpvBuilder.h"
  45. namespace spv {
  46. #include "GLSL.std.450.h"
  47. #include "GLSL.ext.KHR.h"
  48. #include "GLSL.ext.EXT.h"
  49. #include "GLSL.ext.AMD.h"
  50. #include "GLSL.ext.NV.h"
  51. }
  52. namespace spv {
  53. // Hook to visit each operand type and result type of an instruction.
  54. // Will be called multiple times for one instruction, once for each typed
  55. // operand and the result.
  56. void Builder::postProcessType(const Instruction& inst, Id typeId)
  57. {
  58. // Characterize the type being questioned
  59. Id basicTypeOp = getMostBasicTypeClass(typeId);
  60. int width = 0;
  61. if (basicTypeOp == OpTypeFloat || basicTypeOp == OpTypeInt)
  62. width = getScalarTypeWidth(typeId);
  63. // Do opcode-specific checks
  64. switch (inst.getOpCode()) {
  65. case OpLoad:
  66. case OpStore:
  67. if (basicTypeOp == OpTypeStruct) {
  68. if (containsType(typeId, OpTypeInt, 8))
  69. addCapability(CapabilityInt8);
  70. if (containsType(typeId, OpTypeInt, 16))
  71. addCapability(CapabilityInt16);
  72. if (containsType(typeId, OpTypeFloat, 16))
  73. addCapability(CapabilityFloat16);
  74. } else {
  75. StorageClass storageClass = getStorageClass(inst.getIdOperand(0));
  76. if (width == 8) {
  77. switch (storageClass) {
  78. case StorageClassPhysicalStorageBufferEXT:
  79. case StorageClassUniform:
  80. case StorageClassStorageBuffer:
  81. case StorageClassPushConstant:
  82. break;
  83. default:
  84. addCapability(CapabilityInt8);
  85. break;
  86. }
  87. } else if (width == 16) {
  88. switch (storageClass) {
  89. case StorageClassPhysicalStorageBufferEXT:
  90. case StorageClassUniform:
  91. case StorageClassStorageBuffer:
  92. case StorageClassPushConstant:
  93. case StorageClassInput:
  94. case StorageClassOutput:
  95. break;
  96. default:
  97. if (basicTypeOp == OpTypeInt)
  98. addCapability(CapabilityInt16);
  99. if (basicTypeOp == OpTypeFloat)
  100. addCapability(CapabilityFloat16);
  101. break;
  102. }
  103. }
  104. }
  105. break;
  106. case OpAccessChain:
  107. case OpPtrAccessChain:
  108. case OpCopyObject:
  109. break;
  110. case OpFConvert:
  111. case OpSConvert:
  112. case OpUConvert:
  113. // Look for any 8/16-bit storage capabilities. If there are none, assume that
  114. // the convert instruction requires the Float16/Int8/16 capability.
  115. if (containsType(typeId, OpTypeFloat, 16) || containsType(typeId, OpTypeInt, 16)) {
  116. bool foundStorage = false;
  117. for (auto it = capabilities.begin(); it != capabilities.end(); ++it) {
  118. spv::Capability cap = *it;
  119. if (cap == spv::CapabilityStorageInputOutput16 ||
  120. cap == spv::CapabilityStoragePushConstant16 ||
  121. cap == spv::CapabilityStorageUniformBufferBlock16 ||
  122. cap == spv::CapabilityStorageUniform16) {
  123. foundStorage = true;
  124. break;
  125. }
  126. }
  127. if (!foundStorage) {
  128. if (containsType(typeId, OpTypeFloat, 16))
  129. addCapability(CapabilityFloat16);
  130. if (containsType(typeId, OpTypeInt, 16))
  131. addCapability(CapabilityInt16);
  132. }
  133. }
  134. if (containsType(typeId, OpTypeInt, 8)) {
  135. bool foundStorage = false;
  136. for (auto it = capabilities.begin(); it != capabilities.end(); ++it) {
  137. spv::Capability cap = *it;
  138. if (cap == spv::CapabilityStoragePushConstant8 ||
  139. cap == spv::CapabilityUniformAndStorageBuffer8BitAccess ||
  140. cap == spv::CapabilityStorageBuffer8BitAccess) {
  141. foundStorage = true;
  142. break;
  143. }
  144. }
  145. if (!foundStorage) {
  146. addCapability(CapabilityInt8);
  147. }
  148. }
  149. break;
  150. case OpExtInst:
  151. switch (inst.getImmediateOperand(1)) {
  152. case GLSLstd450Frexp:
  153. case GLSLstd450FrexpStruct:
  154. if (getSpvVersion() < glslang::EShTargetSpv_1_3 && containsType(typeId, OpTypeInt, 16))
  155. addExtension(spv::E_SPV_AMD_gpu_shader_int16);
  156. break;
  157. case GLSLstd450InterpolateAtCentroid:
  158. case GLSLstd450InterpolateAtSample:
  159. case GLSLstd450InterpolateAtOffset:
  160. if (getSpvVersion() < glslang::EShTargetSpv_1_3 && containsType(typeId, OpTypeFloat, 16))
  161. addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
  162. break;
  163. default:
  164. break;
  165. }
  166. break;
  167. default:
  168. if (basicTypeOp == OpTypeFloat && width == 16)
  169. addCapability(CapabilityFloat16);
  170. if (basicTypeOp == OpTypeInt && width == 16)
  171. addCapability(CapabilityInt16);
  172. if (basicTypeOp == OpTypeInt && width == 8)
  173. addCapability(CapabilityInt8);
  174. break;
  175. }
  176. }
  177. // Called for each instruction that resides in a block.
  178. void Builder::postProcess(Instruction& inst)
  179. {
  180. // Add capabilities based simply on the opcode.
  181. switch (inst.getOpCode()) {
  182. case OpExtInst:
  183. switch (inst.getImmediateOperand(1)) {
  184. case GLSLstd450InterpolateAtCentroid:
  185. case GLSLstd450InterpolateAtSample:
  186. case GLSLstd450InterpolateAtOffset:
  187. addCapability(CapabilityInterpolationFunction);
  188. break;
  189. default:
  190. break;
  191. }
  192. break;
  193. case OpDPdxFine:
  194. case OpDPdyFine:
  195. case OpFwidthFine:
  196. case OpDPdxCoarse:
  197. case OpDPdyCoarse:
  198. case OpFwidthCoarse:
  199. addCapability(CapabilityDerivativeControl);
  200. break;
  201. case OpImageQueryLod:
  202. case OpImageQuerySize:
  203. case OpImageQuerySizeLod:
  204. case OpImageQuerySamples:
  205. case OpImageQueryLevels:
  206. addCapability(CapabilityImageQuery);
  207. break;
  208. case OpGroupNonUniformPartitionNV:
  209. addExtension(E_SPV_NV_shader_subgroup_partitioned);
  210. addCapability(CapabilityGroupNonUniformPartitionedNV);
  211. break;
  212. case OpLoad:
  213. case OpStore:
  214. {
  215. // For any load/store to a PhysicalStorageBufferEXT, walk the accesschain
  216. // index list to compute the misalignment. The pre-existing alignment value
  217. // (set via Builder::AccessChain::alignment) only accounts for the base of
  218. // the reference type and any scalar component selection in the accesschain,
  219. // and this function computes the rest from the SPIR-V Offset decorations.
  220. Instruction *accessChain = module.getInstruction(inst.getIdOperand(0));
  221. if (accessChain->getOpCode() == OpAccessChain) {
  222. Instruction *base = module.getInstruction(accessChain->getIdOperand(0));
  223. // Get the type of the base of the access chain. It must be a pointer type.
  224. Id typeId = base->getTypeId();
  225. Instruction *type = module.getInstruction(typeId);
  226. assert(type->getOpCode() == OpTypePointer);
  227. if (type->getImmediateOperand(0) != StorageClassPhysicalStorageBufferEXT) {
  228. break;
  229. }
  230. // Get the pointee type.
  231. typeId = type->getIdOperand(1);
  232. type = module.getInstruction(typeId);
  233. // Walk the index list for the access chain. For each index, find any
  234. // misalignment that can apply when accessing the member/element via
  235. // Offset/ArrayStride/MatrixStride decorations, and bitwise OR them all
  236. // together.
  237. int alignment = 0;
  238. for (int i = 1; i < accessChain->getNumOperands(); ++i) {
  239. Instruction *idx = module.getInstruction(accessChain->getIdOperand(i));
  240. if (type->getOpCode() == OpTypeStruct) {
  241. assert(idx->getOpCode() == OpConstant);
  242. unsigned int c = idx->getImmediateOperand(0);
  243. const auto function = [&](const std::unique_ptr<Instruction>& decoration) {
  244. if (decoration.get()->getOpCode() == OpMemberDecorate &&
  245. decoration.get()->getIdOperand(0) == typeId &&
  246. decoration.get()->getImmediateOperand(1) == c &&
  247. (decoration.get()->getImmediateOperand(2) == DecorationOffset ||
  248. decoration.get()->getImmediateOperand(2) == DecorationMatrixStride)) {
  249. alignment |= decoration.get()->getImmediateOperand(3);
  250. }
  251. };
  252. std::for_each(decorations.begin(), decorations.end(), function);
  253. // get the next member type
  254. typeId = type->getIdOperand(c);
  255. type = module.getInstruction(typeId);
  256. } else if (type->getOpCode() == OpTypeArray ||
  257. type->getOpCode() == OpTypeRuntimeArray) {
  258. const auto function = [&](const std::unique_ptr<Instruction>& decoration) {
  259. if (decoration.get()->getOpCode() == OpDecorate &&
  260. decoration.get()->getIdOperand(0) == typeId &&
  261. decoration.get()->getImmediateOperand(1) == DecorationArrayStride) {
  262. alignment |= decoration.get()->getImmediateOperand(2);
  263. }
  264. };
  265. std::for_each(decorations.begin(), decorations.end(), function);
  266. // Get the element type
  267. typeId = type->getIdOperand(0);
  268. type = module.getInstruction(typeId);
  269. } else {
  270. // Once we get to any non-aggregate type, we're done.
  271. break;
  272. }
  273. }
  274. assert(inst.getNumOperands() >= 3);
  275. unsigned int memoryAccess = inst.getImmediateOperand((inst.getOpCode() == OpStore) ? 2 : 1);
  276. assert(memoryAccess & MemoryAccessAlignedMask);
  277. static_cast<void>(memoryAccess);
  278. // Compute the index of the alignment operand.
  279. int alignmentIdx = 2;
  280. if (inst.getOpCode() == OpStore)
  281. alignmentIdx++;
  282. // Merge new and old (mis)alignment
  283. alignment |= inst.getImmediateOperand(alignmentIdx);
  284. // Pick the LSB
  285. alignment = alignment & ~(alignment & (alignment-1));
  286. // update the Aligned operand
  287. inst.setImmediateOperand(alignmentIdx, alignment);
  288. }
  289. break;
  290. }
  291. default:
  292. break;
  293. }
  294. // Checks based on type
  295. if (inst.getTypeId() != NoType)
  296. postProcessType(inst, inst.getTypeId());
  297. for (int op = 0; op < inst.getNumOperands(); ++op) {
  298. if (inst.isIdOperand(op)) {
  299. // In blocks, these are always result ids, but we are relying on
  300. // getTypeId() to return NoType for things like OpLabel.
  301. if (getTypeId(inst.getIdOperand(op)) != NoType)
  302. postProcessType(inst, getTypeId(inst.getIdOperand(op)));
  303. }
  304. }
  305. }
  306. // Called for each instruction in a reachable block.
  307. void Builder::postProcessReachable(const Instruction&)
  308. {
  309. // did have code here, but questionable to do so without deleting the instructions
  310. }
  311. // comment in header
  312. void Builder::postProcess()
  313. {
  314. std::unordered_set<const Block*> reachableBlocks;
  315. std::unordered_set<Id> unreachableDefinitions;
  316. // Collect IDs defined in unreachable blocks. For each function, label the
  317. // reachable blocks first. Then for each unreachable block, collect the
  318. // result IDs of the instructions in it.
  319. for (auto fi = module.getFunctions().cbegin(); fi != module.getFunctions().cend(); fi++) {
  320. Function* f = *fi;
  321. Block* entry = f->getEntryBlock();
  322. inReadableOrder(entry, [&reachableBlocks](const Block* b) { reachableBlocks.insert(b); });
  323. for (auto bi = f->getBlocks().cbegin(); bi != f->getBlocks().cend(); bi++) {
  324. Block* b = *bi;
  325. if (reachableBlocks.count(b) == 0) {
  326. for (auto ii = b->getInstructions().cbegin(); ii != b->getInstructions().cend(); ii++)
  327. unreachableDefinitions.insert(ii->get()->getResultId());
  328. }
  329. }
  330. }
  331. // Remove unneeded decorations, for unreachable instructions
  332. decorations.erase(std::remove_if(decorations.begin(), decorations.end(),
  333. [&unreachableDefinitions](std::unique_ptr<Instruction>& I) -> bool {
  334. Id decoration_id = I.get()->getIdOperand(0);
  335. return unreachableDefinitions.count(decoration_id) != 0;
  336. }),
  337. decorations.end());
  338. // Add per-instruction capabilities, extensions, etc.,
  339. // Look for any 8/16 bit type in physical storage buffer class, and set the
  340. // appropriate capability. This happens in createSpvVariable for other storage
  341. // classes, but there isn't always a variable for physical storage buffer.
  342. for (int t = 0; t < (int)groupedTypes[OpTypePointer].size(); ++t) {
  343. Instruction* type = groupedTypes[OpTypePointer][t];
  344. if (type->getImmediateOperand(0) == (unsigned)StorageClassPhysicalStorageBufferEXT) {
  345. if (containsType(type->getIdOperand(1), OpTypeInt, 8)) {
  346. addExtension(spv::E_SPV_KHR_8bit_storage);
  347. addCapability(spv::CapabilityStorageBuffer8BitAccess);
  348. }
  349. if (containsType(type->getIdOperand(1), OpTypeInt, 16) ||
  350. containsType(type->getIdOperand(1), OpTypeFloat, 16)) {
  351. addExtension(spv::E_SPV_KHR_16bit_storage);
  352. addCapability(spv::CapabilityStorageBuffer16BitAccess);
  353. }
  354. }
  355. }
  356. // process all reachable instructions...
  357. for (auto bi = reachableBlocks.cbegin(); bi != reachableBlocks.cend(); ++bi) {
  358. const Block* block = *bi;
  359. const auto function = [this](const std::unique_ptr<Instruction>& inst) { postProcessReachable(*inst.get()); };
  360. std::for_each(block->getInstructions().begin(), block->getInstructions().end(), function);
  361. }
  362. // process all block-contained instructions
  363. for (auto fi = module.getFunctions().cbegin(); fi != module.getFunctions().cend(); fi++) {
  364. Function* f = *fi;
  365. for (auto bi = f->getBlocks().cbegin(); bi != f->getBlocks().cend(); bi++) {
  366. Block* b = *bi;
  367. for (auto ii = b->getInstructions().cbegin(); ii != b->getInstructions().cend(); ii++)
  368. postProcess(*ii->get());
  369. // For all local variables that contain pointers to PhysicalStorageBufferEXT, check whether
  370. // there is an existing restrict/aliased decoration. If we don't find one, add Aliased as the
  371. // default.
  372. for (auto vi = b->getLocalVariables().cbegin(); vi != b->getLocalVariables().cend(); vi++) {
  373. const Instruction& inst = *vi->get();
  374. Id resultId = inst.getResultId();
  375. if (containsPhysicalStorageBufferOrArray(getDerefTypeId(resultId))) {
  376. bool foundDecoration = false;
  377. const auto function = [&](const std::unique_ptr<Instruction>& decoration) {
  378. if (decoration.get()->getIdOperand(0) == resultId &&
  379. decoration.get()->getOpCode() == OpDecorate &&
  380. (decoration.get()->getImmediateOperand(1) == spv::DecorationAliasedPointerEXT ||
  381. decoration.get()->getImmediateOperand(1) == spv::DecorationRestrictPointerEXT)) {
  382. foundDecoration = true;
  383. }
  384. };
  385. std::for_each(decorations.begin(), decorations.end(), function);
  386. if (!foundDecoration) {
  387. addDecoration(resultId, spv::DecorationAliasedPointerEXT);
  388. }
  389. }
  390. }
  391. }
  392. }
  393. }
  394. }; // end spv namespace