validate_interfaces.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547
  1. // Copyright (c) 2018 Google LLC.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. #include <algorithm>
  15. #include <vector>
  16. #include "source/diagnostic.h"
  17. #include "source/spirv_constant.h"
  18. #include "source/spirv_target_env.h"
  19. #include "source/val/function.h"
  20. #include "source/val/instruction.h"
  21. #include "source/val/validate.h"
  22. #include "source/val/validation_state.h"
  23. namespace spvtools {
  24. namespace val {
  25. namespace {
  26. // Limit the number of checked locations to 4096. Multiplied by 4 to represent
  27. // all the components. This limit is set to be well beyond practical use cases.
  28. const uint32_t kMaxLocations = 4096 * 4;
  29. // Returns true if \c inst is an input or output variable.
  30. bool is_interface_variable(const Instruction* inst, bool is_spv_1_4) {
  31. if (is_spv_1_4) {
  32. // Starting in SPIR-V 1.4, all global variables are interface variables.
  33. return inst->opcode() == SpvOpVariable &&
  34. inst->word(3u) != SpvStorageClassFunction;
  35. } else {
  36. return inst->opcode() == SpvOpVariable &&
  37. (inst->word(3u) == SpvStorageClassInput ||
  38. inst->word(3u) == SpvStorageClassOutput);
  39. }
  40. }
  41. // Checks that \c var is listed as an interface in all the entry points that use
  42. // it.
  43. spv_result_t check_interface_variable(ValidationState_t& _,
  44. const Instruction* var) {
  45. std::vector<const Function*> functions;
  46. std::vector<const Instruction*> uses;
  47. for (auto use : var->uses()) {
  48. uses.push_back(use.first);
  49. }
  50. for (uint32_t i = 0; i < uses.size(); ++i) {
  51. const auto user = uses[i];
  52. if (const Function* func = user->function()) {
  53. functions.push_back(func);
  54. } else {
  55. // In the rare case that the variable is used by another instruction in
  56. // the global scope, continue searching for an instruction used in a
  57. // function.
  58. for (auto use : user->uses()) {
  59. uses.push_back(use.first);
  60. }
  61. }
  62. }
  63. std::sort(functions.begin(), functions.end(),
  64. [](const Function* lhs, const Function* rhs) {
  65. return lhs->id() < rhs->id();
  66. });
  67. functions.erase(std::unique(functions.begin(), functions.end()),
  68. functions.end());
  69. std::vector<uint32_t> entry_points;
  70. for (const auto func : functions) {
  71. for (auto id : _.FunctionEntryPoints(func->id())) {
  72. entry_points.push_back(id);
  73. }
  74. }
  75. std::sort(entry_points.begin(), entry_points.end());
  76. entry_points.erase(std::unique(entry_points.begin(), entry_points.end()),
  77. entry_points.end());
  78. for (auto id : entry_points) {
  79. for (const auto& desc : _.entry_point_descriptions(id)) {
  80. bool found = false;
  81. for (auto interface : desc.interfaces) {
  82. if (var->id() == interface) {
  83. found = true;
  84. break;
  85. }
  86. }
  87. if (!found) {
  88. return _.diag(SPV_ERROR_INVALID_ID, var)
  89. << "Interface variable id <" << var->id()
  90. << "> is used by entry point '" << desc.name << "' id <" << id
  91. << ">, but is not listed as an interface";
  92. }
  93. }
  94. }
  95. return SPV_SUCCESS;
  96. }
  97. // This function assumes a base location has been determined already. As such
  98. // any further location decorations are invalid.
  99. // TODO: if this code turns out to be slow, there is an opportunity to cache
  100. // the result for a given type id.
  101. spv_result_t NumConsumedLocations(ValidationState_t& _, const Instruction* type,
  102. uint32_t* num_locations) {
  103. *num_locations = 0;
  104. switch (type->opcode()) {
  105. case SpvOpTypeInt:
  106. case SpvOpTypeFloat:
  107. // Scalars always consume a single location.
  108. *num_locations = 1;
  109. break;
  110. case SpvOpTypeVector:
  111. // 3- and 4-component 64-bit vectors consume two locations.
  112. if ((_.ContainsSizedIntOrFloatType(type->id(), SpvOpTypeInt, 64) ||
  113. _.ContainsSizedIntOrFloatType(type->id(), SpvOpTypeFloat, 64)) &&
  114. (type->GetOperandAs<uint32_t>(2) > 2)) {
  115. *num_locations = 2;
  116. } else {
  117. *num_locations = 1;
  118. }
  119. break;
  120. case SpvOpTypeMatrix:
  121. // Matrices consume locations equal to the underlying vector type for
  122. // each column.
  123. NumConsumedLocations(_, _.FindDef(type->GetOperandAs<uint32_t>(1)),
  124. num_locations);
  125. *num_locations *= type->GetOperandAs<uint32_t>(2);
  126. break;
  127. case SpvOpTypeArray: {
  128. // Arrays consume locations equal to the underlying type times the number
  129. // of elements in the vector.
  130. NumConsumedLocations(_, _.FindDef(type->GetOperandAs<uint32_t>(1)),
  131. num_locations);
  132. bool is_int = false;
  133. bool is_const = false;
  134. uint32_t value = 0;
  135. // Attempt to evaluate the number of array elements.
  136. std::tie(is_int, is_const, value) =
  137. _.EvalInt32IfConst(type->GetOperandAs<uint32_t>(2));
  138. if (is_int && is_const) *num_locations *= value;
  139. break;
  140. }
  141. case SpvOpTypeStruct: {
  142. // Members cannot have location decorations at this point.
  143. if (_.HasDecoration(type->id(), SpvDecorationLocation)) {
  144. return _.diag(SPV_ERROR_INVALID_DATA, type)
  145. << "Members cannot be assigned a location";
  146. }
  147. // Structs consume locations equal to the sum of the locations consumed
  148. // by the members.
  149. for (uint32_t i = 1; i < type->operands().size(); ++i) {
  150. uint32_t member_locations = 0;
  151. if (auto error = NumConsumedLocations(
  152. _, _.FindDef(type->GetOperandAs<uint32_t>(i)),
  153. &member_locations)) {
  154. return error;
  155. }
  156. *num_locations += member_locations;
  157. }
  158. break;
  159. }
  160. default:
  161. break;
  162. }
  163. return SPV_SUCCESS;
  164. }
  165. // Returns the number of components consumed by types that support a component
  166. // decoration.
  167. uint32_t NumConsumedComponents(ValidationState_t& _, const Instruction* type) {
  168. uint32_t num_components = 0;
  169. switch (type->opcode()) {
  170. case SpvOpTypeInt:
  171. case SpvOpTypeFloat:
  172. // 64-bit types consume two components.
  173. if (type->GetOperandAs<uint32_t>(1) == 64) {
  174. num_components = 2;
  175. } else {
  176. num_components = 1;
  177. }
  178. break;
  179. case SpvOpTypeVector:
  180. // Vectors consume components equal to the underlying type's consumption
  181. // times the number of elements in the vector. Note that 3- and 4-element
  182. // vectors cannot have a component decoration (i.e. assumed to be zero).
  183. num_components =
  184. NumConsumedComponents(_, _.FindDef(type->GetOperandAs<uint32_t>(1)));
  185. num_components *= type->GetOperandAs<uint32_t>(2);
  186. break;
  187. case SpvOpTypeArray:
  188. // Skip the array.
  189. return NumConsumedComponents(_,
  190. _.FindDef(type->GetOperandAs<uint32_t>(1)));
  191. default:
  192. // This is an error that is validated elsewhere.
  193. break;
  194. }
  195. return num_components;
  196. }
  197. // Populates |locations| (and/or |output_index1_locations|) with the use
  198. // location and component coordinates for |variable|. Indices are calculated as
  199. // 4 * location + component.
  200. spv_result_t GetLocationsForVariable(
  201. ValidationState_t& _, const Instruction* entry_point,
  202. const Instruction* variable, std::unordered_set<uint32_t>* locations,
  203. std::unordered_set<uint32_t>* output_index1_locations) {
  204. const bool is_fragment = entry_point->GetOperandAs<SpvExecutionModel>(0) ==
  205. SpvExecutionModelFragment;
  206. const bool is_output =
  207. variable->GetOperandAs<SpvStorageClass>(2) == SpvStorageClassOutput;
  208. auto ptr_type_id = variable->GetOperandAs<uint32_t>(0);
  209. auto ptr_type = _.FindDef(ptr_type_id);
  210. auto type_id = ptr_type->GetOperandAs<uint32_t>(2);
  211. auto type = _.FindDef(type_id);
  212. // Check for Location, Component and Index decorations on the variable. The
  213. // validator allows duplicate decorations if the location/component/index are
  214. // equal. Also track Patch and PerTaskNV decorations.
  215. bool has_location = false;
  216. uint32_t location = 0;
  217. bool has_component = false;
  218. uint32_t component = 0;
  219. bool has_index = false;
  220. uint32_t index = 0;
  221. bool has_patch = false;
  222. bool has_per_task_nv = false;
  223. bool has_per_vertex_nv = false;
  224. for (auto& dec : _.id_decorations(variable->id())) {
  225. if (dec.dec_type() == SpvDecorationLocation) {
  226. if (has_location && dec.params()[0] != location) {
  227. return _.diag(SPV_ERROR_INVALID_DATA, variable)
  228. << "Variable has conflicting location decorations";
  229. }
  230. has_location = true;
  231. location = dec.params()[0];
  232. } else if (dec.dec_type() == SpvDecorationComponent) {
  233. if (has_component && dec.params()[0] != component) {
  234. return _.diag(SPV_ERROR_INVALID_DATA, variable)
  235. << "Variable has conflicting component decorations";
  236. }
  237. has_component = true;
  238. component = dec.params()[0];
  239. } else if (dec.dec_type() == SpvDecorationIndex) {
  240. if (!is_output || !is_fragment) {
  241. return _.diag(SPV_ERROR_INVALID_DATA, variable)
  242. << "Index can only be applied to Fragment output variables";
  243. }
  244. if (has_index && dec.params()[0] != index) {
  245. return _.diag(SPV_ERROR_INVALID_DATA, variable)
  246. << "Variable has conflicting index decorations";
  247. }
  248. has_index = true;
  249. index = dec.params()[0];
  250. } else if (dec.dec_type() == SpvDecorationBuiltIn) {
  251. // Don't check built-ins.
  252. return SPV_SUCCESS;
  253. } else if (dec.dec_type() == SpvDecorationPatch) {
  254. has_patch = true;
  255. } else if (dec.dec_type() == SpvDecorationPerTaskNV) {
  256. has_per_task_nv = true;
  257. } else if (dec.dec_type() == SpvDecorationPerVertexNV) {
  258. has_per_vertex_nv = true;
  259. }
  260. }
  261. // Vulkan 14.1.3: Tessellation control and mesh per-vertex outputs and
  262. // tessellation control, evaluation and geometry per-vertex inputs have a
  263. // layer of arraying that is not included in interface matching.
  264. bool is_arrayed = false;
  265. switch (entry_point->GetOperandAs<SpvExecutionModel>(0)) {
  266. case SpvExecutionModelTessellationControl:
  267. if (!has_patch) {
  268. is_arrayed = true;
  269. }
  270. break;
  271. case SpvExecutionModelTessellationEvaluation:
  272. if (!is_output && !has_patch) {
  273. is_arrayed = true;
  274. }
  275. break;
  276. case SpvExecutionModelGeometry:
  277. if (!is_output) {
  278. is_arrayed = true;
  279. }
  280. break;
  281. case SpvExecutionModelFragment:
  282. if (!is_output && has_per_vertex_nv) {
  283. is_arrayed = true;
  284. }
  285. break;
  286. case SpvExecutionModelMeshNV:
  287. if (is_output && !has_per_task_nv) {
  288. is_arrayed = true;
  289. }
  290. break;
  291. default:
  292. break;
  293. }
  294. // Unpack arrayness.
  295. if (is_arrayed && (type->opcode() == SpvOpTypeArray ||
  296. type->opcode() == SpvOpTypeRuntimeArray)) {
  297. type_id = type->GetOperandAs<uint32_t>(1);
  298. type = _.FindDef(type_id);
  299. }
  300. if (type->opcode() == SpvOpTypeStruct) {
  301. // Don't check built-ins.
  302. if (_.HasDecoration(type_id, SpvDecorationBuiltIn)) return SPV_SUCCESS;
  303. }
  304. // Only block-decorated structs don't need a location on the variable.
  305. const bool is_block = _.HasDecoration(type_id, SpvDecorationBlock);
  306. if (!has_location && !is_block) {
  307. return _.diag(SPV_ERROR_INVALID_DATA, variable)
  308. << "Variable must be decorated with a location";
  309. }
  310. const std::string storage_class = is_output ? "output" : "input";
  311. if (has_location) {
  312. auto sub_type = type;
  313. bool is_int = false;
  314. bool is_const = false;
  315. uint32_t array_size = 1;
  316. // If the variable is still arrayed, mark the locations/components per
  317. // index.
  318. if (type->opcode() == SpvOpTypeArray) {
  319. // Determine the array size if possible and get the element type.
  320. std::tie(is_int, is_const, array_size) =
  321. _.EvalInt32IfConst(type->GetOperandAs<uint32_t>(2));
  322. if (!is_int || !is_const) array_size = 1;
  323. auto sub_type_id = type->GetOperandAs<uint32_t>(1);
  324. sub_type = _.FindDef(sub_type_id);
  325. }
  326. for (uint32_t array_idx = 0; array_idx < array_size; ++array_idx) {
  327. uint32_t num_locations = 0;
  328. if (auto error = NumConsumedLocations(_, sub_type, &num_locations))
  329. return error;
  330. uint32_t num_components = NumConsumedComponents(_, sub_type);
  331. uint32_t array_location = location + (num_locations * array_idx);
  332. uint32_t start = array_location * 4;
  333. if (kMaxLocations <= start) {
  334. // Too many locations, give up.
  335. break;
  336. }
  337. uint32_t end = (array_location + num_locations) * 4;
  338. if (num_components != 0) {
  339. start += component;
  340. end = array_location * 4 + component + num_components;
  341. }
  342. auto locs = locations;
  343. if (has_index && index == 1) locs = output_index1_locations;
  344. for (uint32_t i = start; i < end; ++i) {
  345. if (!locs->insert(i).second) {
  346. return _.diag(SPV_ERROR_INVALID_DATA, entry_point)
  347. << "Entry-point has conflicting " << storage_class
  348. << " location assignment at location " << i / 4
  349. << ", component " << i % 4;
  350. }
  351. }
  352. }
  353. } else {
  354. // For Block-decorated structs with no location assigned to the variable,
  355. // each member of the block must be assigned a location. Also record any
  356. // member component assignments. The validator allows duplicate decorations
  357. // if they agree on the location/component.
  358. std::unordered_map<uint32_t, uint32_t> member_locations;
  359. std::unordered_map<uint32_t, uint32_t> member_components;
  360. for (auto& dec : _.id_decorations(type_id)) {
  361. if (dec.dec_type() == SpvDecorationLocation) {
  362. auto where = member_locations.find(dec.struct_member_index());
  363. if (where == member_locations.end()) {
  364. member_locations[dec.struct_member_index()] = dec.params()[0];
  365. } else if (where->second != dec.params()[0]) {
  366. return _.diag(SPV_ERROR_INVALID_DATA, type)
  367. << "Member index " << dec.struct_member_index()
  368. << " has conflicting location assignments";
  369. }
  370. } else if (dec.dec_type() == SpvDecorationComponent) {
  371. auto where = member_components.find(dec.struct_member_index());
  372. if (where == member_components.end()) {
  373. member_components[dec.struct_member_index()] = dec.params()[0];
  374. } else if (where->second != dec.params()[0]) {
  375. return _.diag(SPV_ERROR_INVALID_DATA, type)
  376. << "Member index " << dec.struct_member_index()
  377. << " has conflicting component assignments";
  378. }
  379. }
  380. }
  381. for (uint32_t i = 1; i < type->operands().size(); ++i) {
  382. auto where = member_locations.find(i - 1);
  383. if (where == member_locations.end()) {
  384. return _.diag(SPV_ERROR_INVALID_DATA, type)
  385. << "Member index " << i - 1
  386. << " is missing a location assignment";
  387. }
  388. location = where->second;
  389. auto member = _.FindDef(type->GetOperandAs<uint32_t>(i));
  390. uint32_t num_locations = 0;
  391. if (auto error = NumConsumedLocations(_, member, &num_locations))
  392. return error;
  393. // If the component is not specified, it is assumed to be zero.
  394. uint32_t num_components = NumConsumedComponents(_, member);
  395. component = 0;
  396. if (member_components.count(i - 1)) {
  397. component = member_components[i - 1];
  398. }
  399. uint32_t start = location * 4;
  400. if (kMaxLocations <= start) {
  401. // Too many locations, give up.
  402. continue;
  403. }
  404. if (member->opcode() == SpvOpTypeArray && num_components >= 1 &&
  405. num_components < 4) {
  406. // When an array has an element that takes less than a location in
  407. // size, calculate the used locations in a strided manner.
  408. for (uint32_t l = location; l < num_locations + location; ++l) {
  409. for (uint32_t c = component; c < component + num_components; ++c) {
  410. uint32_t check = 4 * l + c;
  411. if (!locations->insert(check).second) {
  412. return _.diag(SPV_ERROR_INVALID_DATA, entry_point)
  413. << "Entry-point has conflicting " << storage_class
  414. << " location assignment at location " << l
  415. << ", component " << c;
  416. }
  417. }
  418. }
  419. } else {
  420. // TODO: There is a hole here is the member is an array of 3- or
  421. // 4-element vectors of 64-bit types.
  422. uint32_t end = (location + num_locations) * 4;
  423. if (num_components != 0) {
  424. start += component;
  425. end = location * 4 + component + num_components;
  426. }
  427. for (uint32_t l = start; l < end; ++l) {
  428. if (!locations->insert(l).second) {
  429. return _.diag(SPV_ERROR_INVALID_DATA, entry_point)
  430. << "Entry-point has conflicting " << storage_class
  431. << " location assignment at location " << l / 4
  432. << ", component " << l % 4;
  433. }
  434. }
  435. }
  436. }
  437. }
  438. return SPV_SUCCESS;
  439. }
  440. spv_result_t ValidateLocations(ValidationState_t& _,
  441. const Instruction* entry_point) {
  442. // According to Vulkan 14.1 only the following execution models have
  443. // locations assigned.
  444. switch (entry_point->GetOperandAs<SpvExecutionModel>(0)) {
  445. case SpvExecutionModelVertex:
  446. case SpvExecutionModelTessellationControl:
  447. case SpvExecutionModelTessellationEvaluation:
  448. case SpvExecutionModelGeometry:
  449. case SpvExecutionModelFragment:
  450. break;
  451. default:
  452. return SPV_SUCCESS;
  453. }
  454. // Locations are stored as a combined location and component values.
  455. std::unordered_set<uint32_t> input_locations;
  456. std::unordered_set<uint32_t> output_locations_index0;
  457. std::unordered_set<uint32_t> output_locations_index1;
  458. std::unordered_set<uint32_t> seen;
  459. for (uint32_t i = 3; i < entry_point->operands().size(); ++i) {
  460. auto interface_id = entry_point->GetOperandAs<uint32_t>(i);
  461. auto interface_var = _.FindDef(interface_id);
  462. auto storage_class = interface_var->GetOperandAs<SpvStorageClass>(2);
  463. if (storage_class != SpvStorageClassInput &&
  464. storage_class != SpvStorageClassOutput) {
  465. continue;
  466. }
  467. if (!seen.insert(interface_id).second) {
  468. // Pre-1.4 an interface variable could be listed multiple times in an
  469. // entry point. Validation for 1.4 or later is done elsewhere.
  470. continue;
  471. }
  472. auto locations = (storage_class == SpvStorageClassInput)
  473. ? &input_locations
  474. : &output_locations_index0;
  475. if (auto error = GetLocationsForVariable(
  476. _, entry_point, interface_var, locations, &output_locations_index1))
  477. return error;
  478. }
  479. return SPV_SUCCESS;
  480. }
  481. } // namespace
  482. spv_result_t ValidateInterfaces(ValidationState_t& _) {
  483. bool is_spv_1_4 = _.version() >= SPV_SPIRV_VERSION_WORD(1, 4);
  484. for (auto& inst : _.ordered_instructions()) {
  485. if (is_interface_variable(&inst, is_spv_1_4)) {
  486. if (auto error = check_interface_variable(_, &inst)) {
  487. return error;
  488. }
  489. }
  490. }
  491. if (spvIsVulkanEnv(_.context()->target_env)) {
  492. for (auto& inst : _.ordered_instructions()) {
  493. if (inst.opcode() == SpvOpEntryPoint) {
  494. if (auto error = ValidateLocations(_, &inst)) {
  495. return error;
  496. }
  497. }
  498. if (inst.opcode() == SpvOpTypeVoid) break;
  499. }
  500. }
  501. return SPV_SUCCESS;
  502. }
  503. } // namespace val
  504. } // namespace spvtools