validate_memory.cpp 67 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656
  1. // Copyright (c) 2018 Google LLC.
  2. // Modifications Copyright (C) 2020 Advanced Micro Devices, Inc. All rights
  3. // reserved.
  4. //
  5. // Licensed under the Apache License, Version 2.0 (the "License");
  6. // you may not use this file except in compliance with the License.
  7. // You may obtain a copy of the License at
  8. //
  9. // http://www.apache.org/licenses/LICENSE-2.0
  10. //
  11. // Unless required by applicable law or agreed to in writing, software
  12. // distributed under the License is distributed on an "AS IS" BASIS,
  13. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. // See the License for the specific language governing permissions and
  15. // limitations under the License.
  16. #include <algorithm>
  17. #include <string>
  18. #include <vector>
  19. #include "source/opcode.h"
  20. #include "source/spirv_target_env.h"
  21. #include "source/val/instruction.h"
  22. #include "source/val/validate.h"
  23. #include "source/val/validate_scopes.h"
  24. #include "source/val/validation_state.h"
  25. namespace spvtools {
  26. namespace val {
  27. namespace {
  28. bool AreLayoutCompatibleStructs(ValidationState_t&, const Instruction*,
  29. const Instruction*);
  30. bool HaveLayoutCompatibleMembers(ValidationState_t&, const Instruction*,
  31. const Instruction*);
  32. bool HaveSameLayoutDecorations(ValidationState_t&, const Instruction*,
  33. const Instruction*);
  34. bool HasConflictingMemberOffsets(const std::vector<Decoration>&,
  35. const std::vector<Decoration>&);
  36. bool IsAllowedTypeOrArrayOfSame(ValidationState_t& _, const Instruction* type,
  37. std::initializer_list<uint32_t> allowed) {
  38. if (std::find(allowed.begin(), allowed.end(), type->opcode()) !=
  39. allowed.end()) {
  40. return true;
  41. }
  42. if (type->opcode() == SpvOpTypeArray ||
  43. type->opcode() == SpvOpTypeRuntimeArray) {
  44. auto elem_type = _.FindDef(type->word(2));
  45. return std::find(allowed.begin(), allowed.end(), elem_type->opcode()) !=
  46. allowed.end();
  47. }
  48. return false;
  49. }
  50. // Returns true if the two instructions represent structs that, as far as the
  51. // validator can tell, have the exact same data layout.
  52. bool AreLayoutCompatibleStructs(ValidationState_t& _, const Instruction* type1,
  53. const Instruction* type2) {
  54. if (type1->opcode() != SpvOpTypeStruct) {
  55. return false;
  56. }
  57. if (type2->opcode() != SpvOpTypeStruct) {
  58. return false;
  59. }
  60. if (!HaveLayoutCompatibleMembers(_, type1, type2)) return false;
  61. return HaveSameLayoutDecorations(_, type1, type2);
  62. }
  63. // Returns true if the operands to the OpTypeStruct instruction defining the
  64. // types are the same or are layout compatible types. |type1| and |type2| must
  65. // be OpTypeStruct instructions.
  66. bool HaveLayoutCompatibleMembers(ValidationState_t& _, const Instruction* type1,
  67. const Instruction* type2) {
  68. assert(type1->opcode() == SpvOpTypeStruct &&
  69. "type1 must be an OpTypeStruct instruction.");
  70. assert(type2->opcode() == SpvOpTypeStruct &&
  71. "type2 must be an OpTypeStruct instruction.");
  72. const auto& type1_operands = type1->operands();
  73. const auto& type2_operands = type2->operands();
  74. if (type1_operands.size() != type2_operands.size()) {
  75. return false;
  76. }
  77. for (size_t operand = 2; operand < type1_operands.size(); ++operand) {
  78. if (type1->word(operand) != type2->word(operand)) {
  79. auto def1 = _.FindDef(type1->word(operand));
  80. auto def2 = _.FindDef(type2->word(operand));
  81. if (!AreLayoutCompatibleStructs(_, def1, def2)) {
  82. return false;
  83. }
  84. }
  85. }
  86. return true;
  87. }
  88. // Returns true if all decorations that affect the data layout of the struct
  89. // (like Offset), are the same for the two types. |type1| and |type2| must be
  90. // OpTypeStruct instructions.
  91. bool HaveSameLayoutDecorations(ValidationState_t& _, const Instruction* type1,
  92. const Instruction* type2) {
  93. assert(type1->opcode() == SpvOpTypeStruct &&
  94. "type1 must be an OpTypeStruct instruction.");
  95. assert(type2->opcode() == SpvOpTypeStruct &&
  96. "type2 must be an OpTypeStruct instruction.");
  97. const std::vector<Decoration>& type1_decorations =
  98. _.id_decorations(type1->id());
  99. const std::vector<Decoration>& type2_decorations =
  100. _.id_decorations(type2->id());
  101. // TODO: Will have to add other check for arrays an matricies if we want to
  102. // handle them.
  103. if (HasConflictingMemberOffsets(type1_decorations, type2_decorations)) {
  104. return false;
  105. }
  106. return true;
  107. }
  108. bool HasConflictingMemberOffsets(
  109. const std::vector<Decoration>& type1_decorations,
  110. const std::vector<Decoration>& type2_decorations) {
  111. {
  112. // We are interested in conflicting decoration. If a decoration is in one
  113. // list but not the other, then we will assume the code is correct. We are
  114. // looking for things we know to be wrong.
  115. //
  116. // We do not have to traverse type2_decoration because, after traversing
  117. // type1_decorations, anything new will not be found in
  118. // type1_decoration. Therefore, it cannot lead to a conflict.
  119. for (const Decoration& decoration : type1_decorations) {
  120. switch (decoration.dec_type()) {
  121. case SpvDecorationOffset: {
  122. // Since these affect the layout of the struct, they must be present
  123. // in both structs.
  124. auto compare = [&decoration](const Decoration& rhs) {
  125. if (rhs.dec_type() != SpvDecorationOffset) return false;
  126. return decoration.struct_member_index() ==
  127. rhs.struct_member_index();
  128. };
  129. auto i = std::find_if(type2_decorations.begin(),
  130. type2_decorations.end(), compare);
  131. if (i != type2_decorations.end() &&
  132. decoration.params().front() != i->params().front()) {
  133. return true;
  134. }
  135. } break;
  136. default:
  137. // This decoration does not affect the layout of the structure, so
  138. // just moving on.
  139. break;
  140. }
  141. }
  142. }
  143. return false;
  144. }
  145. // If |skip_builtin| is true, returns true if |storage| contains bool within
  146. // it and no storage that contains the bool is builtin.
  147. // If |skip_builtin| is false, returns true if |storage| contains bool within
  148. // it.
  149. bool ContainsInvalidBool(ValidationState_t& _, const Instruction* storage,
  150. bool skip_builtin) {
  151. if (skip_builtin) {
  152. for (const Decoration& decoration : _.id_decorations(storage->id())) {
  153. if (decoration.dec_type() == SpvDecorationBuiltIn) return false;
  154. }
  155. }
  156. const size_t elem_type_index = 1;
  157. uint32_t elem_type_id;
  158. Instruction* elem_type;
  159. switch (storage->opcode()) {
  160. case SpvOpTypeBool:
  161. return true;
  162. case SpvOpTypeVector:
  163. case SpvOpTypeMatrix:
  164. case SpvOpTypeArray:
  165. case SpvOpTypeRuntimeArray:
  166. elem_type_id = storage->GetOperandAs<uint32_t>(elem_type_index);
  167. elem_type = _.FindDef(elem_type_id);
  168. return ContainsInvalidBool(_, elem_type, skip_builtin);
  169. case SpvOpTypeStruct:
  170. for (size_t member_type_index = 1;
  171. member_type_index < storage->operands().size();
  172. ++member_type_index) {
  173. auto member_type_id =
  174. storage->GetOperandAs<uint32_t>(member_type_index);
  175. auto member_type = _.FindDef(member_type_id);
  176. if (ContainsInvalidBool(_, member_type, skip_builtin)) return true;
  177. }
  178. default:
  179. break;
  180. }
  181. return false;
  182. }
  183. bool ContainsCooperativeMatrix(ValidationState_t& _,
  184. const Instruction* storage) {
  185. const size_t elem_type_index = 1;
  186. uint32_t elem_type_id;
  187. Instruction* elem_type;
  188. switch (storage->opcode()) {
  189. case SpvOpTypeCooperativeMatrixNV:
  190. return true;
  191. case SpvOpTypeArray:
  192. case SpvOpTypeRuntimeArray:
  193. elem_type_id = storage->GetOperandAs<uint32_t>(elem_type_index);
  194. elem_type = _.FindDef(elem_type_id);
  195. return ContainsCooperativeMatrix(_, elem_type);
  196. case SpvOpTypeStruct:
  197. for (size_t member_type_index = 1;
  198. member_type_index < storage->operands().size();
  199. ++member_type_index) {
  200. auto member_type_id =
  201. storage->GetOperandAs<uint32_t>(member_type_index);
  202. auto member_type = _.FindDef(member_type_id);
  203. if (ContainsCooperativeMatrix(_, member_type)) return true;
  204. }
  205. break;
  206. default:
  207. break;
  208. }
  209. return false;
  210. }
  211. std::pair<SpvStorageClass, SpvStorageClass> GetStorageClass(
  212. ValidationState_t& _, const Instruction* inst) {
  213. SpvStorageClass dst_sc = SpvStorageClassMax;
  214. SpvStorageClass src_sc = SpvStorageClassMax;
  215. switch (inst->opcode()) {
  216. case SpvOpCooperativeMatrixLoadNV:
  217. case SpvOpLoad: {
  218. auto load_pointer = _.FindDef(inst->GetOperandAs<uint32_t>(2));
  219. auto load_pointer_type = _.FindDef(load_pointer->type_id());
  220. dst_sc = load_pointer_type->GetOperandAs<SpvStorageClass>(1);
  221. break;
  222. }
  223. case SpvOpCooperativeMatrixStoreNV:
  224. case SpvOpStore: {
  225. auto store_pointer = _.FindDef(inst->GetOperandAs<uint32_t>(0));
  226. auto store_pointer_type = _.FindDef(store_pointer->type_id());
  227. dst_sc = store_pointer_type->GetOperandAs<SpvStorageClass>(1);
  228. break;
  229. }
  230. case SpvOpCopyMemory:
  231. case SpvOpCopyMemorySized: {
  232. auto dst = _.FindDef(inst->GetOperandAs<uint32_t>(0));
  233. auto dst_type = _.FindDef(dst->type_id());
  234. dst_sc = dst_type->GetOperandAs<SpvStorageClass>(1);
  235. auto src = _.FindDef(inst->GetOperandAs<uint32_t>(1));
  236. auto src_type = _.FindDef(src->type_id());
  237. src_sc = src_type->GetOperandAs<SpvStorageClass>(1);
  238. break;
  239. }
  240. default:
  241. break;
  242. }
  243. return std::make_pair(dst_sc, src_sc);
  244. }
  245. // Returns the number of instruction words taken up by a memory access
  246. // argument and its implied operands.
  247. int MemoryAccessNumWords(uint32_t mask) {
  248. int result = 1; // Count the mask
  249. if (mask & SpvMemoryAccessAlignedMask) ++result;
  250. if (mask & SpvMemoryAccessMakePointerAvailableKHRMask) ++result;
  251. if (mask & SpvMemoryAccessMakePointerVisibleKHRMask) ++result;
  252. return result;
  253. }
  254. // Returns the scope ID operand for MakeAvailable memory access with mask
  255. // at the given operand index.
  256. // This function is only called for OpLoad, OpStore, OpCopyMemory and
  257. // OpCopyMemorySized, OpCooperativeMatrixLoadNV, and
  258. // OpCooperativeMatrixStoreNV.
  259. uint32_t GetMakeAvailableScope(const Instruction* inst, uint32_t mask,
  260. uint32_t mask_index) {
  261. assert(mask & SpvMemoryAccessMakePointerAvailableKHRMask);
  262. uint32_t this_bit = uint32_t(SpvMemoryAccessMakePointerAvailableKHRMask);
  263. uint32_t index =
  264. mask_index - 1 + MemoryAccessNumWords(mask & (this_bit | (this_bit - 1)));
  265. return inst->GetOperandAs<uint32_t>(index);
  266. }
  267. // This function is only called for OpLoad, OpStore, OpCopyMemory,
  268. // OpCopyMemorySized, OpCooperativeMatrixLoadNV, and
  269. // OpCooperativeMatrixStoreNV.
  270. uint32_t GetMakeVisibleScope(const Instruction* inst, uint32_t mask,
  271. uint32_t mask_index) {
  272. assert(mask & SpvMemoryAccessMakePointerVisibleKHRMask);
  273. uint32_t this_bit = uint32_t(SpvMemoryAccessMakePointerVisibleKHRMask);
  274. uint32_t index =
  275. mask_index - 1 + MemoryAccessNumWords(mask & (this_bit | (this_bit - 1)));
  276. return inst->GetOperandAs<uint32_t>(index);
  277. }
  278. bool DoesStructContainRTA(const ValidationState_t& _, const Instruction* inst) {
  279. for (size_t member_index = 1; member_index < inst->operands().size();
  280. ++member_index) {
  281. const auto member_id = inst->GetOperandAs<uint32_t>(member_index);
  282. const auto member_type = _.FindDef(member_id);
  283. if (member_type->opcode() == SpvOpTypeRuntimeArray) return true;
  284. }
  285. return false;
  286. }
  287. spv_result_t CheckMemoryAccess(ValidationState_t& _, const Instruction* inst,
  288. uint32_t index) {
  289. SpvStorageClass dst_sc, src_sc;
  290. std::tie(dst_sc, src_sc) = GetStorageClass(_, inst);
  291. if (inst->operands().size() <= index) {
  292. if (src_sc == SpvStorageClassPhysicalStorageBufferEXT ||
  293. dst_sc == SpvStorageClassPhysicalStorageBufferEXT) {
  294. return _.diag(SPV_ERROR_INVALID_ID, inst)
  295. << "Memory accesses with PhysicalStorageBufferEXT must use "
  296. "Aligned.";
  297. }
  298. return SPV_SUCCESS;
  299. }
  300. const uint32_t mask = inst->GetOperandAs<uint32_t>(index);
  301. if (mask & SpvMemoryAccessMakePointerAvailableKHRMask) {
  302. if (inst->opcode() == SpvOpLoad ||
  303. inst->opcode() == SpvOpCooperativeMatrixLoadNV) {
  304. return _.diag(SPV_ERROR_INVALID_ID, inst)
  305. << "MakePointerAvailableKHR cannot be used with OpLoad.";
  306. }
  307. if (!(mask & SpvMemoryAccessNonPrivatePointerKHRMask)) {
  308. return _.diag(SPV_ERROR_INVALID_ID, inst)
  309. << "NonPrivatePointerKHR must be specified if "
  310. "MakePointerAvailableKHR is specified.";
  311. }
  312. // Check the associated scope for MakeAvailableKHR.
  313. const auto available_scope = GetMakeAvailableScope(inst, mask, index);
  314. if (auto error = ValidateMemoryScope(_, inst, available_scope))
  315. return error;
  316. }
  317. if (mask & SpvMemoryAccessMakePointerVisibleKHRMask) {
  318. if (inst->opcode() == SpvOpStore ||
  319. inst->opcode() == SpvOpCooperativeMatrixStoreNV) {
  320. return _.diag(SPV_ERROR_INVALID_ID, inst)
  321. << "MakePointerVisibleKHR cannot be used with OpStore.";
  322. }
  323. if (!(mask & SpvMemoryAccessNonPrivatePointerKHRMask)) {
  324. return _.diag(SPV_ERROR_INVALID_ID, inst)
  325. << "NonPrivatePointerKHR must be specified if "
  326. << "MakePointerVisibleKHR is specified.";
  327. }
  328. // Check the associated scope for MakeVisibleKHR.
  329. const auto visible_scope = GetMakeVisibleScope(inst, mask, index);
  330. if (auto error = ValidateMemoryScope(_, inst, visible_scope)) return error;
  331. }
  332. if (mask & SpvMemoryAccessNonPrivatePointerKHRMask) {
  333. if (dst_sc != SpvStorageClassUniform &&
  334. dst_sc != SpvStorageClassWorkgroup &&
  335. dst_sc != SpvStorageClassCrossWorkgroup &&
  336. dst_sc != SpvStorageClassGeneric && dst_sc != SpvStorageClassImage &&
  337. dst_sc != SpvStorageClassStorageBuffer &&
  338. dst_sc != SpvStorageClassPhysicalStorageBufferEXT) {
  339. return _.diag(SPV_ERROR_INVALID_ID, inst)
  340. << "NonPrivatePointerKHR requires a pointer in Uniform, "
  341. << "Workgroup, CrossWorkgroup, Generic, Image or StorageBuffer "
  342. << "storage classes.";
  343. }
  344. if (src_sc != SpvStorageClassMax && src_sc != SpvStorageClassUniform &&
  345. src_sc != SpvStorageClassWorkgroup &&
  346. src_sc != SpvStorageClassCrossWorkgroup &&
  347. src_sc != SpvStorageClassGeneric && src_sc != SpvStorageClassImage &&
  348. src_sc != SpvStorageClassStorageBuffer &&
  349. src_sc != SpvStorageClassPhysicalStorageBufferEXT) {
  350. return _.diag(SPV_ERROR_INVALID_ID, inst)
  351. << "NonPrivatePointerKHR requires a pointer in Uniform, "
  352. << "Workgroup, CrossWorkgroup, Generic, Image or StorageBuffer "
  353. << "storage classes.";
  354. }
  355. }
  356. if (!(mask & SpvMemoryAccessAlignedMask)) {
  357. if (src_sc == SpvStorageClassPhysicalStorageBufferEXT ||
  358. dst_sc == SpvStorageClassPhysicalStorageBufferEXT) {
  359. return _.diag(SPV_ERROR_INVALID_ID, inst)
  360. << "Memory accesses with PhysicalStorageBufferEXT must use "
  361. "Aligned.";
  362. }
  363. }
  364. return SPV_SUCCESS;
  365. }
  366. spv_result_t ValidateVariable(ValidationState_t& _, const Instruction* inst) {
  367. auto result_type = _.FindDef(inst->type_id());
  368. if (!result_type || result_type->opcode() != SpvOpTypePointer) {
  369. return _.diag(SPV_ERROR_INVALID_ID, inst)
  370. << "OpVariable Result Type <id> '" << _.getIdName(inst->type_id())
  371. << "' is not a pointer type.";
  372. }
  373. const auto type_index = 2;
  374. const auto value_id = result_type->GetOperandAs<uint32_t>(type_index);
  375. auto value_type = _.FindDef(value_id);
  376. const auto initializer_index = 3;
  377. const auto storage_class_index = 2;
  378. if (initializer_index < inst->operands().size()) {
  379. const auto initializer_id = inst->GetOperandAs<uint32_t>(initializer_index);
  380. const auto initializer = _.FindDef(initializer_id);
  381. const auto is_module_scope_var =
  382. initializer && (initializer->opcode() == SpvOpVariable) &&
  383. (initializer->GetOperandAs<SpvStorageClass>(storage_class_index) !=
  384. SpvStorageClassFunction);
  385. const auto is_constant =
  386. initializer && spvOpcodeIsConstant(initializer->opcode());
  387. if (!initializer || !(is_constant || is_module_scope_var)) {
  388. return _.diag(SPV_ERROR_INVALID_ID, inst)
  389. << "OpVariable Initializer <id> '" << _.getIdName(initializer_id)
  390. << "' is not a constant or module-scope variable.";
  391. }
  392. if (initializer->type_id() != value_id) {
  393. return _.diag(SPV_ERROR_INVALID_ID, inst)
  394. << "Initializer type must match the type pointed to by the Result "
  395. "Type";
  396. }
  397. }
  398. auto storage_class = inst->GetOperandAs<SpvStorageClass>(storage_class_index);
  399. if (storage_class != SpvStorageClassWorkgroup &&
  400. storage_class != SpvStorageClassCrossWorkgroup &&
  401. storage_class != SpvStorageClassPrivate &&
  402. storage_class != SpvStorageClassFunction &&
  403. storage_class != SpvStorageClassRayPayloadNV &&
  404. storage_class != SpvStorageClassIncomingRayPayloadNV &&
  405. storage_class != SpvStorageClassHitAttributeNV &&
  406. storage_class != SpvStorageClassCallableDataNV &&
  407. storage_class != SpvStorageClassIncomingCallableDataNV) {
  408. bool storage_input_or_output = storage_class == SpvStorageClassInput ||
  409. storage_class == SpvStorageClassOutput;
  410. bool builtin = false;
  411. if (storage_input_or_output) {
  412. for (const Decoration& decoration : _.id_decorations(inst->id())) {
  413. if (decoration.dec_type() == SpvDecorationBuiltIn) {
  414. builtin = true;
  415. break;
  416. }
  417. }
  418. }
  419. if (!(storage_input_or_output && builtin) &&
  420. ContainsInvalidBool(_, value_type, storage_input_or_output)) {
  421. return _.diag(SPV_ERROR_INVALID_ID, inst)
  422. << "If OpTypeBool is stored in conjunction with OpVariable, it "
  423. << "can only be used with non-externally visible shader Storage "
  424. << "Classes: Workgroup, CrossWorkgroup, Private, and Function";
  425. }
  426. }
  427. if (!_.IsValidStorageClass(storage_class)) {
  428. return _.diag(SPV_ERROR_INVALID_BINARY, inst)
  429. << "Invalid storage class for target environment";
  430. }
  431. if (storage_class == SpvStorageClassGeneric) {
  432. return _.diag(SPV_ERROR_INVALID_BINARY, inst)
  433. << "OpVariable storage class cannot be Generic";
  434. }
  435. if (inst->function() && storage_class != SpvStorageClassFunction) {
  436. return _.diag(SPV_ERROR_INVALID_LAYOUT, inst)
  437. << "Variables must have a function[7] storage class inside"
  438. " of a function";
  439. }
  440. if (!inst->function() && storage_class == SpvStorageClassFunction) {
  441. return _.diag(SPV_ERROR_INVALID_LAYOUT, inst)
  442. << "Variables can not have a function[7] storage class "
  443. "outside of a function";
  444. }
  445. // SPIR-V 3.32.8: Check that pointer type and variable type have the same
  446. // storage class.
  447. const auto result_storage_class_index = 1;
  448. const auto result_storage_class =
  449. result_type->GetOperandAs<uint32_t>(result_storage_class_index);
  450. if (storage_class != result_storage_class) {
  451. return _.diag(SPV_ERROR_INVALID_ID, inst)
  452. << "From SPIR-V spec, section 3.32.8 on OpVariable:\n"
  453. << "Its Storage Class operand must be the same as the Storage Class "
  454. << "operand of the result type.";
  455. }
  456. // Variable pointer related restrictions.
  457. const auto pointee = _.FindDef(result_type->word(3));
  458. if (_.addressing_model() == SpvAddressingModelLogical &&
  459. !_.options()->relax_logical_pointer) {
  460. // VariablePointersStorageBuffer is implied by VariablePointers.
  461. if (pointee->opcode() == SpvOpTypePointer) {
  462. if (!_.HasCapability(SpvCapabilityVariablePointersStorageBuffer)) {
  463. return _.diag(SPV_ERROR_INVALID_ID, inst)
  464. << "In Logical addressing, variables may not allocate a pointer "
  465. << "type";
  466. } else if (storage_class != SpvStorageClassFunction &&
  467. storage_class != SpvStorageClassPrivate) {
  468. return _.diag(SPV_ERROR_INVALID_ID, inst)
  469. << "In Logical addressing with variable pointers, variables "
  470. << "that allocate pointers must be in Function or Private "
  471. << "storage classes";
  472. }
  473. }
  474. }
  475. // Vulkan 14.5.1: Check type of PushConstant variables.
  476. // Vulkan 14.5.2: Check type of UniformConstant and Uniform variables.
  477. if (spvIsVulkanEnv(_.context()->target_env)) {
  478. if (storage_class == SpvStorageClassPushConstant) {
  479. if (!IsAllowedTypeOrArrayOfSame(_, pointee, {SpvOpTypeStruct})) {
  480. return _.diag(SPV_ERROR_INVALID_ID, inst)
  481. << "PushConstant OpVariable <id> '" << _.getIdName(inst->id())
  482. << "' has illegal type.\n"
  483. << "From Vulkan spec, section 14.5.1:\n"
  484. << "Such variables must be typed as OpTypeStruct, "
  485. << "or an array of this type";
  486. }
  487. }
  488. if (storage_class == SpvStorageClassUniformConstant) {
  489. if (!IsAllowedTypeOrArrayOfSame(
  490. _, pointee,
  491. {SpvOpTypeImage, SpvOpTypeSampler, SpvOpTypeSampledImage,
  492. SpvOpTypeAccelerationStructureKHR})) {
  493. return _.diag(SPV_ERROR_INVALID_ID, inst)
  494. << _.VkErrorID(4655) << "UniformConstant OpVariable <id> '"
  495. << _.getIdName(inst->id()) << "' has illegal type.\n"
  496. << "Variables identified with the UniformConstant storage class "
  497. << "are used only as handles to refer to opaque resources. Such "
  498. << "variables must be typed as OpTypeImage, OpTypeSampler, "
  499. << "OpTypeSampledImage, OpTypeAccelerationStructureKHR, "
  500. << "or an array of one of these types.";
  501. }
  502. }
  503. if (storage_class == SpvStorageClassUniform) {
  504. if (!IsAllowedTypeOrArrayOfSame(_, pointee, {SpvOpTypeStruct})) {
  505. return _.diag(SPV_ERROR_INVALID_ID, inst)
  506. << "Uniform OpVariable <id> '" << _.getIdName(inst->id())
  507. << "' has illegal type.\n"
  508. << "From Vulkan spec, section 14.5.2:\n"
  509. << "Variables identified with the Uniform storage class are "
  510. << "used to access transparent buffer backed resources. Such "
  511. << "variables must be typed as OpTypeStruct, or an array of "
  512. << "this type";
  513. }
  514. }
  515. if (storage_class == SpvStorageClassStorageBuffer) {
  516. if (!IsAllowedTypeOrArrayOfSame(_, pointee, {SpvOpTypeStruct})) {
  517. return _.diag(SPV_ERROR_INVALID_ID, inst)
  518. << "StorageBuffer OpVariable <id> '" << _.getIdName(inst->id())
  519. << "' has illegal type.\n"
  520. << "From Vulkan spec, section 14.5.2:\n"
  521. << "Variables identified with the StorageBuffer storage class "
  522. "are used to access transparent buffer backed resources. "
  523. "Such variables must be typed as OpTypeStruct, or an array "
  524. "of this type";
  525. }
  526. }
  527. // Check for invalid use of Invariant
  528. if (storage_class != SpvStorageClassInput &&
  529. storage_class != SpvStorageClassOutput) {
  530. if (_.HasDecoration(inst->id(), SpvDecorationInvariant)) {
  531. return _.diag(SPV_ERROR_INVALID_ID, inst)
  532. << _.VkErrorID(4677)
  533. << "Variable decorated with Invariant must only be identified "
  534. "with the Input or Output storage class in Vulkan "
  535. "environment.";
  536. }
  537. // Need to check if only the members in a struct are decorated
  538. if (value_type && value_type->opcode() == SpvOpTypeStruct) {
  539. if (_.HasDecoration(value_id, SpvDecorationInvariant)) {
  540. return _.diag(SPV_ERROR_INVALID_ID, inst)
  541. << _.VkErrorID(4677)
  542. << "Variable struct member decorated with Invariant must only "
  543. "be identified with the Input or Output storage class in "
  544. "Vulkan environment.";
  545. }
  546. }
  547. }
  548. }
  549. // Vulkan Appendix A: Check that if contains initializer, then
  550. // storage class is Output, Private, or Function.
  551. if (inst->operands().size() > 3 && storage_class != SpvStorageClassOutput &&
  552. storage_class != SpvStorageClassPrivate &&
  553. storage_class != SpvStorageClassFunction) {
  554. if (spvIsVulkanEnv(_.context()->target_env)) {
  555. if (storage_class == SpvStorageClassWorkgroup) {
  556. auto init_id = inst->GetOperandAs<uint32_t>(3);
  557. auto init = _.FindDef(init_id);
  558. if (init->opcode() != SpvOpConstantNull) {
  559. return _.diag(SPV_ERROR_INVALID_ID, inst)
  560. << "Variable initializers in Workgroup storage class are "
  561. "limited to OpConstantNull";
  562. }
  563. } else {
  564. return _.diag(SPV_ERROR_INVALID_ID, inst)
  565. << _.VkErrorID(4651) << "OpVariable, <id> '"
  566. << _.getIdName(inst->id())
  567. << "', has a disallowed initializer & storage class "
  568. << "combination.\n"
  569. << "From " << spvLogStringForEnv(_.context()->target_env)
  570. << " spec:\n"
  571. << "Variable declarations that include initializers must have "
  572. << "one of the following storage classes: Output, Private, "
  573. << "Function or Workgroup";
  574. }
  575. }
  576. }
  577. if (storage_class == SpvStorageClassPhysicalStorageBufferEXT) {
  578. return _.diag(SPV_ERROR_INVALID_ID, inst)
  579. << "PhysicalStorageBufferEXT must not be used with OpVariable.";
  580. }
  581. auto pointee_base = pointee;
  582. while (pointee_base->opcode() == SpvOpTypeArray) {
  583. pointee_base = _.FindDef(pointee_base->GetOperandAs<uint32_t>(1u));
  584. }
  585. if (pointee_base->opcode() == SpvOpTypePointer) {
  586. if (pointee_base->GetOperandAs<uint32_t>(1u) ==
  587. SpvStorageClassPhysicalStorageBufferEXT) {
  588. // check for AliasedPointerEXT/RestrictPointerEXT
  589. bool foundAliased =
  590. _.HasDecoration(inst->id(), SpvDecorationAliasedPointerEXT);
  591. bool foundRestrict =
  592. _.HasDecoration(inst->id(), SpvDecorationRestrictPointerEXT);
  593. if (!foundAliased && !foundRestrict) {
  594. return _.diag(SPV_ERROR_INVALID_ID, inst)
  595. << "OpVariable " << inst->id()
  596. << ": expected AliasedPointerEXT or RestrictPointerEXT for "
  597. << "PhysicalStorageBufferEXT pointer.";
  598. }
  599. if (foundAliased && foundRestrict) {
  600. return _.diag(SPV_ERROR_INVALID_ID, inst)
  601. << "OpVariable " << inst->id()
  602. << ": can't specify both AliasedPointerEXT and "
  603. << "RestrictPointerEXT for PhysicalStorageBufferEXT pointer.";
  604. }
  605. }
  606. }
  607. // Vulkan specific validation rules for OpTypeRuntimeArray
  608. if (spvIsVulkanEnv(_.context()->target_env)) {
  609. // OpTypeRuntimeArray should only ever be in a container like OpTypeStruct,
  610. // so should never appear as a bare variable.
  611. // Unless the module has the RuntimeDescriptorArrayEXT capability.
  612. if (value_type && value_type->opcode() == SpvOpTypeRuntimeArray) {
  613. if (!_.HasCapability(SpvCapabilityRuntimeDescriptorArrayEXT)) {
  614. return _.diag(SPV_ERROR_INVALID_ID, inst)
  615. << "OpVariable, <id> '" << _.getIdName(inst->id())
  616. << "', is attempting to create memory for an illegal type, "
  617. << "OpTypeRuntimeArray.\nFor Vulkan OpTypeRuntimeArray can only "
  618. << "appear as the final member of an OpTypeStruct, thus cannot "
  619. << "be instantiated via OpVariable";
  620. } else {
  621. // A bare variable OpTypeRuntimeArray is allowed in this context, but
  622. // still need to check the storage class.
  623. if (storage_class != SpvStorageClassStorageBuffer &&
  624. storage_class != SpvStorageClassUniform &&
  625. storage_class != SpvStorageClassUniformConstant) {
  626. return _.diag(SPV_ERROR_INVALID_ID, inst)
  627. << "For Vulkan with RuntimeDescriptorArrayEXT, a variable "
  628. << "containing OpTypeRuntimeArray must have storage class of "
  629. << "StorageBuffer, Uniform, or UniformConstant.";
  630. }
  631. }
  632. }
  633. // If an OpStruct has an OpTypeRuntimeArray somewhere within it, then it
  634. // must either have the storage class StorageBuffer and be decorated
  635. // with Block, or it must be in the Uniform storage class and be decorated
  636. // as BufferBlock.
  637. if (value_type && value_type->opcode() == SpvOpTypeStruct) {
  638. if (DoesStructContainRTA(_, value_type)) {
  639. if (storage_class == SpvStorageClassStorageBuffer) {
  640. if (!_.HasDecoration(value_id, SpvDecorationBlock)) {
  641. return _.diag(SPV_ERROR_INVALID_ID, inst)
  642. << "For Vulkan, an OpTypeStruct variable containing an "
  643. << "OpTypeRuntimeArray must be decorated with Block if it "
  644. << "has storage class StorageBuffer.";
  645. }
  646. } else if (storage_class == SpvStorageClassUniform) {
  647. if (!_.HasDecoration(value_id, SpvDecorationBufferBlock)) {
  648. return _.diag(SPV_ERROR_INVALID_ID, inst)
  649. << "For Vulkan, an OpTypeStruct variable containing an "
  650. << "OpTypeRuntimeArray must be decorated with BufferBlock "
  651. << "if it has storage class Uniform.";
  652. }
  653. } else {
  654. return _.diag(SPV_ERROR_INVALID_ID, inst)
  655. << "For Vulkan, OpTypeStruct variables containing "
  656. << "OpTypeRuntimeArray must have storage class of "
  657. << "StorageBuffer or Uniform.";
  658. }
  659. }
  660. }
  661. }
  662. // Cooperative matrix types can only be allocated in Function or Private
  663. if ((storage_class != SpvStorageClassFunction &&
  664. storage_class != SpvStorageClassPrivate) &&
  665. ContainsCooperativeMatrix(_, pointee)) {
  666. return _.diag(SPV_ERROR_INVALID_ID, inst)
  667. << "Cooperative matrix types (or types containing them) can only be "
  668. "allocated "
  669. << "in Function or Private storage classes or as function "
  670. "parameters";
  671. }
  672. if (_.HasCapability(SpvCapabilityShader)) {
  673. // Don't allow variables containing 16-bit elements without the appropriate
  674. // capabilities.
  675. if ((!_.HasCapability(SpvCapabilityInt16) &&
  676. _.ContainsSizedIntOrFloatType(value_id, SpvOpTypeInt, 16)) ||
  677. (!_.HasCapability(SpvCapabilityFloat16) &&
  678. _.ContainsSizedIntOrFloatType(value_id, SpvOpTypeFloat, 16))) {
  679. auto underlying_type = value_type;
  680. while (underlying_type->opcode() == SpvOpTypePointer) {
  681. storage_class = underlying_type->GetOperandAs<SpvStorageClass>(1u);
  682. underlying_type =
  683. _.FindDef(underlying_type->GetOperandAs<uint32_t>(2u));
  684. }
  685. bool storage_class_ok = true;
  686. std::string sc_name = _.grammar().lookupOperandName(
  687. SPV_OPERAND_TYPE_STORAGE_CLASS, storage_class);
  688. switch (storage_class) {
  689. case SpvStorageClassStorageBuffer:
  690. case SpvStorageClassPhysicalStorageBufferEXT:
  691. if (!_.HasCapability(SpvCapabilityStorageBuffer16BitAccess)) {
  692. storage_class_ok = false;
  693. }
  694. break;
  695. case SpvStorageClassUniform:
  696. if (!_.HasCapability(
  697. SpvCapabilityUniformAndStorageBuffer16BitAccess)) {
  698. if (underlying_type->opcode() == SpvOpTypeArray ||
  699. underlying_type->opcode() == SpvOpTypeRuntimeArray) {
  700. underlying_type =
  701. _.FindDef(underlying_type->GetOperandAs<uint32_t>(1u));
  702. }
  703. if (!_.HasCapability(SpvCapabilityStorageBuffer16BitAccess) ||
  704. !_.HasDecoration(underlying_type->id(),
  705. SpvDecorationBufferBlock)) {
  706. storage_class_ok = false;
  707. }
  708. }
  709. break;
  710. case SpvStorageClassPushConstant:
  711. if (!_.HasCapability(SpvCapabilityStoragePushConstant16)) {
  712. storage_class_ok = false;
  713. }
  714. break;
  715. case SpvStorageClassInput:
  716. case SpvStorageClassOutput:
  717. if (!_.HasCapability(SpvCapabilityStorageInputOutput16)) {
  718. storage_class_ok = false;
  719. }
  720. break;
  721. case SpvStorageClassWorkgroup:
  722. if (!_.HasCapability(SpvCapabilityWorkgroupMemoryExplicitLayout16BitAccessKHR)) {
  723. storage_class_ok = false;
  724. }
  725. break;
  726. default:
  727. return _.diag(SPV_ERROR_INVALID_ID, inst)
  728. << "Cannot allocate a variable containing a 16-bit type in "
  729. << sc_name << " storage class";
  730. }
  731. if (!storage_class_ok) {
  732. return _.diag(SPV_ERROR_INVALID_ID, inst)
  733. << "Allocating a variable containing a 16-bit element in "
  734. << sc_name << " storage class requires an additional capability";
  735. }
  736. }
  737. // Don't allow variables containing 8-bit elements without the appropriate
  738. // capabilities.
  739. if (!_.HasCapability(SpvCapabilityInt8) &&
  740. _.ContainsSizedIntOrFloatType(value_id, SpvOpTypeInt, 8)) {
  741. auto underlying_type = value_type;
  742. while (underlying_type->opcode() == SpvOpTypePointer) {
  743. storage_class = underlying_type->GetOperandAs<SpvStorageClass>(1u);
  744. underlying_type =
  745. _.FindDef(underlying_type->GetOperandAs<uint32_t>(2u));
  746. }
  747. bool storage_class_ok = true;
  748. std::string sc_name = _.grammar().lookupOperandName(
  749. SPV_OPERAND_TYPE_STORAGE_CLASS, storage_class);
  750. switch (storage_class) {
  751. case SpvStorageClassStorageBuffer:
  752. case SpvStorageClassPhysicalStorageBufferEXT:
  753. if (!_.HasCapability(SpvCapabilityStorageBuffer8BitAccess)) {
  754. storage_class_ok = false;
  755. }
  756. break;
  757. case SpvStorageClassUniform:
  758. if (!_.HasCapability(
  759. SpvCapabilityUniformAndStorageBuffer8BitAccess)) {
  760. if (underlying_type->opcode() == SpvOpTypeArray ||
  761. underlying_type->opcode() == SpvOpTypeRuntimeArray) {
  762. underlying_type =
  763. _.FindDef(underlying_type->GetOperandAs<uint32_t>(1u));
  764. }
  765. if (!_.HasCapability(SpvCapabilityStorageBuffer8BitAccess) ||
  766. !_.HasDecoration(underlying_type->id(),
  767. SpvDecorationBufferBlock)) {
  768. storage_class_ok = false;
  769. }
  770. }
  771. break;
  772. case SpvStorageClassPushConstant:
  773. if (!_.HasCapability(SpvCapabilityStoragePushConstant8)) {
  774. storage_class_ok = false;
  775. }
  776. break;
  777. case SpvStorageClassWorkgroup:
  778. if (!_.HasCapability(SpvCapabilityWorkgroupMemoryExplicitLayout8BitAccessKHR)) {
  779. storage_class_ok = false;
  780. }
  781. break;
  782. default:
  783. return _.diag(SPV_ERROR_INVALID_ID, inst)
  784. << "Cannot allocate a variable containing a 8-bit type in "
  785. << sc_name << " storage class";
  786. }
  787. if (!storage_class_ok) {
  788. return _.diag(SPV_ERROR_INVALID_ID, inst)
  789. << "Allocating a variable containing a 8-bit element in "
  790. << sc_name << " storage class requires an additional capability";
  791. }
  792. }
  793. }
  794. return SPV_SUCCESS;
  795. }
  796. spv_result_t ValidateLoad(ValidationState_t& _, const Instruction* inst) {
  797. const auto result_type = _.FindDef(inst->type_id());
  798. if (!result_type) {
  799. return _.diag(SPV_ERROR_INVALID_ID, inst)
  800. << "OpLoad Result Type <id> '" << _.getIdName(inst->type_id())
  801. << "' is not defined.";
  802. }
  803. const bool uses_variable_pointers =
  804. _.features().variable_pointers ||
  805. _.features().variable_pointers_storage_buffer;
  806. const auto pointer_index = 2;
  807. const auto pointer_id = inst->GetOperandAs<uint32_t>(pointer_index);
  808. const auto pointer = _.FindDef(pointer_id);
  809. if (!pointer ||
  810. ((_.addressing_model() == SpvAddressingModelLogical) &&
  811. ((!uses_variable_pointers &&
  812. !spvOpcodeReturnsLogicalPointer(pointer->opcode())) ||
  813. (uses_variable_pointers &&
  814. !spvOpcodeReturnsLogicalVariablePointer(pointer->opcode()))))) {
  815. return _.diag(SPV_ERROR_INVALID_ID, inst)
  816. << "OpLoad Pointer <id> '" << _.getIdName(pointer_id)
  817. << "' is not a logical pointer.";
  818. }
  819. const auto pointer_type = _.FindDef(pointer->type_id());
  820. if (!pointer_type || pointer_type->opcode() != SpvOpTypePointer) {
  821. return _.diag(SPV_ERROR_INVALID_ID, inst)
  822. << "OpLoad type for pointer <id> '" << _.getIdName(pointer_id)
  823. << "' is not a pointer type.";
  824. }
  825. const auto pointee_type = _.FindDef(pointer_type->GetOperandAs<uint32_t>(2));
  826. if (!pointee_type || result_type->id() != pointee_type->id()) {
  827. return _.diag(SPV_ERROR_INVALID_ID, inst)
  828. << "OpLoad Result Type <id> '" << _.getIdName(inst->type_id())
  829. << "' does not match Pointer <id> '" << _.getIdName(pointer->id())
  830. << "'s type.";
  831. }
  832. if (auto error = CheckMemoryAccess(_, inst, 3)) return error;
  833. if (_.HasCapability(SpvCapabilityShader) &&
  834. _.ContainsLimitedUseIntOrFloatType(inst->type_id()) &&
  835. result_type->opcode() != SpvOpTypePointer) {
  836. if (result_type->opcode() != SpvOpTypeInt &&
  837. result_type->opcode() != SpvOpTypeFloat &&
  838. result_type->opcode() != SpvOpTypeVector &&
  839. result_type->opcode() != SpvOpTypeMatrix) {
  840. return _.diag(SPV_ERROR_INVALID_ID, inst)
  841. << "8- or 16-bit loads must be a scalar, vector or matrix type";
  842. }
  843. }
  844. return SPV_SUCCESS;
  845. }
  846. spv_result_t ValidateStore(ValidationState_t& _, const Instruction* inst) {
  847. const bool uses_variable_pointer =
  848. _.features().variable_pointers ||
  849. _.features().variable_pointers_storage_buffer;
  850. const auto pointer_index = 0;
  851. const auto pointer_id = inst->GetOperandAs<uint32_t>(pointer_index);
  852. const auto pointer = _.FindDef(pointer_id);
  853. if (!pointer ||
  854. (_.addressing_model() == SpvAddressingModelLogical &&
  855. ((!uses_variable_pointer &&
  856. !spvOpcodeReturnsLogicalPointer(pointer->opcode())) ||
  857. (uses_variable_pointer &&
  858. !spvOpcodeReturnsLogicalVariablePointer(pointer->opcode()))))) {
  859. return _.diag(SPV_ERROR_INVALID_ID, inst)
  860. << "OpStore Pointer <id> '" << _.getIdName(pointer_id)
  861. << "' is not a logical pointer.";
  862. }
  863. const auto pointer_type = _.FindDef(pointer->type_id());
  864. if (!pointer_type || pointer_type->opcode() != SpvOpTypePointer) {
  865. return _.diag(SPV_ERROR_INVALID_ID, inst)
  866. << "OpStore type for pointer <id> '" << _.getIdName(pointer_id)
  867. << "' is not a pointer type.";
  868. }
  869. const auto type_id = pointer_type->GetOperandAs<uint32_t>(2);
  870. const auto type = _.FindDef(type_id);
  871. if (!type || SpvOpTypeVoid == type->opcode()) {
  872. return _.diag(SPV_ERROR_INVALID_ID, inst)
  873. << "OpStore Pointer <id> '" << _.getIdName(pointer_id)
  874. << "'s type is void.";
  875. }
  876. // validate storage class
  877. {
  878. uint32_t data_type;
  879. uint32_t storage_class;
  880. if (!_.GetPointerTypeInfo(pointer_type->id(), &data_type, &storage_class)) {
  881. return _.diag(SPV_ERROR_INVALID_ID, inst)
  882. << "OpStore Pointer <id> '" << _.getIdName(pointer_id)
  883. << "' is not pointer type";
  884. }
  885. if (storage_class == SpvStorageClassUniformConstant ||
  886. storage_class == SpvStorageClassInput ||
  887. storage_class == SpvStorageClassPushConstant) {
  888. return _.diag(SPV_ERROR_INVALID_ID, inst)
  889. << "OpStore Pointer <id> '" << _.getIdName(pointer_id)
  890. << "' storage class is read-only";
  891. }
  892. if (spvIsVulkanEnv(_.context()->target_env) &&
  893. storage_class == SpvStorageClassUniform) {
  894. auto base_ptr = _.TracePointer(pointer);
  895. if (base_ptr->opcode() == SpvOpVariable) {
  896. // If it's not a variable a different check should catch the problem.
  897. auto base_type = _.FindDef(base_ptr->GetOperandAs<uint32_t>(0));
  898. // Get the pointed-to type.
  899. base_type = _.FindDef(base_type->GetOperandAs<uint32_t>(2u));
  900. if (base_type->opcode() == SpvOpTypeArray ||
  901. base_type->opcode() == SpvOpTypeRuntimeArray) {
  902. base_type = _.FindDef(base_type->GetOperandAs<uint32_t>(1u));
  903. }
  904. if (_.HasDecoration(base_type->id(), SpvDecorationBlock)) {
  905. return _.diag(SPV_ERROR_INVALID_ID, inst)
  906. << "In the Vulkan environment, cannot store to Uniform Blocks";
  907. }
  908. }
  909. }
  910. }
  911. const auto object_index = 1;
  912. const auto object_id = inst->GetOperandAs<uint32_t>(object_index);
  913. const auto object = _.FindDef(object_id);
  914. if (!object || !object->type_id()) {
  915. return _.diag(SPV_ERROR_INVALID_ID, inst)
  916. << "OpStore Object <id> '" << _.getIdName(object_id)
  917. << "' is not an object.";
  918. }
  919. const auto object_type = _.FindDef(object->type_id());
  920. if (!object_type || SpvOpTypeVoid == object_type->opcode()) {
  921. return _.diag(SPV_ERROR_INVALID_ID, inst)
  922. << "OpStore Object <id> '" << _.getIdName(object_id)
  923. << "'s type is void.";
  924. }
  925. if (type->id() != object_type->id()) {
  926. if (!_.options()->relax_struct_store || type->opcode() != SpvOpTypeStruct ||
  927. object_type->opcode() != SpvOpTypeStruct) {
  928. return _.diag(SPV_ERROR_INVALID_ID, inst)
  929. << "OpStore Pointer <id> '" << _.getIdName(pointer_id)
  930. << "'s type does not match Object <id> '"
  931. << _.getIdName(object->id()) << "'s type.";
  932. }
  933. // TODO: Check for layout compatible matricies and arrays as well.
  934. if (!AreLayoutCompatibleStructs(_, type, object_type)) {
  935. return _.diag(SPV_ERROR_INVALID_ID, inst)
  936. << "OpStore Pointer <id> '" << _.getIdName(pointer_id)
  937. << "'s layout does not match Object <id> '"
  938. << _.getIdName(object->id()) << "'s layout.";
  939. }
  940. }
  941. if (auto error = CheckMemoryAccess(_, inst, 2)) return error;
  942. if (_.HasCapability(SpvCapabilityShader) &&
  943. _.ContainsLimitedUseIntOrFloatType(inst->type_id()) &&
  944. object_type->opcode() != SpvOpTypePointer) {
  945. if (object_type->opcode() != SpvOpTypeInt &&
  946. object_type->opcode() != SpvOpTypeFloat &&
  947. object_type->opcode() != SpvOpTypeVector &&
  948. object_type->opcode() != SpvOpTypeMatrix) {
  949. return _.diag(SPV_ERROR_INVALID_ID, inst)
  950. << "8- or 16-bit stores must be a scalar, vector or matrix type";
  951. }
  952. }
  953. return SPV_SUCCESS;
  954. }
  955. spv_result_t ValidateCopyMemoryMemoryAccess(ValidationState_t& _,
  956. const Instruction* inst) {
  957. assert(inst->opcode() == SpvOpCopyMemory ||
  958. inst->opcode() == SpvOpCopyMemorySized);
  959. const uint32_t first_access_index = inst->opcode() == SpvOpCopyMemory ? 2 : 3;
  960. if (inst->operands().size() > first_access_index) {
  961. if (auto error = CheckMemoryAccess(_, inst, first_access_index))
  962. return error;
  963. const auto first_access = inst->GetOperandAs<uint32_t>(first_access_index);
  964. const uint32_t second_access_index =
  965. first_access_index + MemoryAccessNumWords(first_access);
  966. if (inst->operands().size() > second_access_index) {
  967. if (_.features().copy_memory_permits_two_memory_accesses) {
  968. if (auto error = CheckMemoryAccess(_, inst, second_access_index))
  969. return error;
  970. // In the two-access form in SPIR-V 1.4 and later:
  971. // - the first is the target (write) access and it can't have
  972. // make-visible.
  973. // - the second is the source (read) access and it can't have
  974. // make-available.
  975. if (first_access & SpvMemoryAccessMakePointerVisibleKHRMask) {
  976. return _.diag(SPV_ERROR_INVALID_DATA, inst)
  977. << "Target memory access must not include "
  978. "MakePointerVisibleKHR";
  979. }
  980. const auto second_access =
  981. inst->GetOperandAs<uint32_t>(second_access_index);
  982. if (second_access & SpvMemoryAccessMakePointerAvailableKHRMask) {
  983. return _.diag(SPV_ERROR_INVALID_DATA, inst)
  984. << "Source memory access must not include "
  985. "MakePointerAvailableKHR";
  986. }
  987. } else {
  988. return _.diag(SPV_ERROR_INVALID_DATA, inst)
  989. << spvOpcodeString(static_cast<SpvOp>(inst->opcode()))
  990. << " with two memory access operands requires SPIR-V 1.4 or "
  991. "later";
  992. }
  993. }
  994. }
  995. return SPV_SUCCESS;
  996. }
  997. spv_result_t ValidateCopyMemory(ValidationState_t& _, const Instruction* inst) {
  998. const auto target_index = 0;
  999. const auto target_id = inst->GetOperandAs<uint32_t>(target_index);
  1000. const auto target = _.FindDef(target_id);
  1001. if (!target) {
  1002. return _.diag(SPV_ERROR_INVALID_ID, inst)
  1003. << "Target operand <id> '" << _.getIdName(target_id)
  1004. << "' is not defined.";
  1005. }
  1006. const auto source_index = 1;
  1007. const auto source_id = inst->GetOperandAs<uint32_t>(source_index);
  1008. const auto source = _.FindDef(source_id);
  1009. if (!source) {
  1010. return _.diag(SPV_ERROR_INVALID_ID, inst)
  1011. << "Source operand <id> '" << _.getIdName(source_id)
  1012. << "' is not defined.";
  1013. }
  1014. const auto target_pointer_type = _.FindDef(target->type_id());
  1015. if (!target_pointer_type ||
  1016. target_pointer_type->opcode() != SpvOpTypePointer) {
  1017. return _.diag(SPV_ERROR_INVALID_ID, inst)
  1018. << "Target operand <id> '" << _.getIdName(target_id)
  1019. << "' is not a pointer.";
  1020. }
  1021. const auto source_pointer_type = _.FindDef(source->type_id());
  1022. if (!source_pointer_type ||
  1023. source_pointer_type->opcode() != SpvOpTypePointer) {
  1024. return _.diag(SPV_ERROR_INVALID_ID, inst)
  1025. << "Source operand <id> '" << _.getIdName(source_id)
  1026. << "' is not a pointer.";
  1027. }
  1028. if (inst->opcode() == SpvOpCopyMemory) {
  1029. const auto target_type =
  1030. _.FindDef(target_pointer_type->GetOperandAs<uint32_t>(2));
  1031. if (!target_type || target_type->opcode() == SpvOpTypeVoid) {
  1032. return _.diag(SPV_ERROR_INVALID_ID, inst)
  1033. << "Target operand <id> '" << _.getIdName(target_id)
  1034. << "' cannot be a void pointer.";
  1035. }
  1036. const auto source_type =
  1037. _.FindDef(source_pointer_type->GetOperandAs<uint32_t>(2));
  1038. if (!source_type || source_type->opcode() == SpvOpTypeVoid) {
  1039. return _.diag(SPV_ERROR_INVALID_ID, inst)
  1040. << "Source operand <id> '" << _.getIdName(source_id)
  1041. << "' cannot be a void pointer.";
  1042. }
  1043. if (target_type->id() != source_type->id()) {
  1044. return _.diag(SPV_ERROR_INVALID_ID, inst)
  1045. << "Target <id> '" << _.getIdName(source_id)
  1046. << "'s type does not match Source <id> '"
  1047. << _.getIdName(source_type->id()) << "'s type.";
  1048. }
  1049. if (auto error = CheckMemoryAccess(_, inst, 2)) return error;
  1050. } else {
  1051. const auto size_id = inst->GetOperandAs<uint32_t>(2);
  1052. const auto size = _.FindDef(size_id);
  1053. if (!size) {
  1054. return _.diag(SPV_ERROR_INVALID_ID, inst)
  1055. << "Size operand <id> '" << _.getIdName(size_id)
  1056. << "' is not defined.";
  1057. }
  1058. const auto size_type = _.FindDef(size->type_id());
  1059. if (!_.IsIntScalarType(size_type->id())) {
  1060. return _.diag(SPV_ERROR_INVALID_ID, inst)
  1061. << "Size operand <id> '" << _.getIdName(size_id)
  1062. << "' must be a scalar integer type.";
  1063. }
  1064. bool is_zero = true;
  1065. switch (size->opcode()) {
  1066. case SpvOpConstantNull:
  1067. return _.diag(SPV_ERROR_INVALID_ID, inst)
  1068. << "Size operand <id> '" << _.getIdName(size_id)
  1069. << "' cannot be a constant zero.";
  1070. case SpvOpConstant:
  1071. if (size_type->word(3) == 1 &&
  1072. size->word(size->words().size() - 1) & 0x80000000) {
  1073. return _.diag(SPV_ERROR_INVALID_ID, inst)
  1074. << "Size operand <id> '" << _.getIdName(size_id)
  1075. << "' cannot have the sign bit set to 1.";
  1076. }
  1077. for (size_t i = 3; is_zero && i < size->words().size(); ++i) {
  1078. is_zero &= (size->word(i) == 0);
  1079. }
  1080. if (is_zero) {
  1081. return _.diag(SPV_ERROR_INVALID_ID, inst)
  1082. << "Size operand <id> '" << _.getIdName(size_id)
  1083. << "' cannot be a constant zero.";
  1084. }
  1085. break;
  1086. default:
  1087. // Cannot infer any other opcodes.
  1088. break;
  1089. }
  1090. if (auto error = CheckMemoryAccess(_, inst, 3)) return error;
  1091. }
  1092. if (auto error = ValidateCopyMemoryMemoryAccess(_, inst)) return error;
  1093. // Get past the pointers to avoid checking a pointer copy.
  1094. auto sub_type = _.FindDef(target_pointer_type->GetOperandAs<uint32_t>(2));
  1095. while (sub_type->opcode() == SpvOpTypePointer) {
  1096. sub_type = _.FindDef(sub_type->GetOperandAs<uint32_t>(2));
  1097. }
  1098. if (_.HasCapability(SpvCapabilityShader) &&
  1099. _.ContainsLimitedUseIntOrFloatType(sub_type->id())) {
  1100. return _.diag(SPV_ERROR_INVALID_ID, inst)
  1101. << "Cannot copy memory of objects containing 8- or 16-bit types";
  1102. }
  1103. return SPV_SUCCESS;
  1104. }
  1105. spv_result_t ValidateAccessChain(ValidationState_t& _,
  1106. const Instruction* inst) {
  1107. std::string instr_name =
  1108. "Op" + std::string(spvOpcodeString(static_cast<SpvOp>(inst->opcode())));
  1109. // The result type must be OpTypePointer.
  1110. auto result_type = _.FindDef(inst->type_id());
  1111. if (SpvOpTypePointer != result_type->opcode()) {
  1112. return _.diag(SPV_ERROR_INVALID_ID, inst)
  1113. << "The Result Type of " << instr_name << " <id> '"
  1114. << _.getIdName(inst->id()) << "' must be OpTypePointer. Found Op"
  1115. << spvOpcodeString(static_cast<SpvOp>(result_type->opcode())) << ".";
  1116. }
  1117. // Result type is a pointer. Find out what it's pointing to.
  1118. // This will be used to make sure the indexing results in the same type.
  1119. // OpTypePointer word 3 is the type being pointed to.
  1120. const auto result_type_pointee = _.FindDef(result_type->word(3));
  1121. // Base must be a pointer, pointing to the base of a composite object.
  1122. const auto base_index = 2;
  1123. const auto base_id = inst->GetOperandAs<uint32_t>(base_index);
  1124. const auto base = _.FindDef(base_id);
  1125. const auto base_type = _.FindDef(base->type_id());
  1126. if (!base_type || SpvOpTypePointer != base_type->opcode()) {
  1127. return _.diag(SPV_ERROR_INVALID_ID, inst)
  1128. << "The Base <id> '" << _.getIdName(base_id) << "' in " << instr_name
  1129. << " instruction must be a pointer.";
  1130. }
  1131. // The result pointer storage class and base pointer storage class must match.
  1132. // Word 2 of OpTypePointer is the Storage Class.
  1133. auto result_type_storage_class = result_type->word(2);
  1134. auto base_type_storage_class = base_type->word(2);
  1135. if (result_type_storage_class != base_type_storage_class) {
  1136. return _.diag(SPV_ERROR_INVALID_ID, inst)
  1137. << "The result pointer storage class and base "
  1138. "pointer storage class in "
  1139. << instr_name << " do not match.";
  1140. }
  1141. // The type pointed to by OpTypePointer (word 3) must be a composite type.
  1142. auto type_pointee = _.FindDef(base_type->word(3));
  1143. // Check Universal Limit (SPIR-V Spec. Section 2.17).
  1144. // The number of indexes passed to OpAccessChain may not exceed 255
  1145. // The instruction includes 4 words + N words (for N indexes)
  1146. size_t num_indexes = inst->words().size() - 4;
  1147. if (inst->opcode() == SpvOpPtrAccessChain ||
  1148. inst->opcode() == SpvOpInBoundsPtrAccessChain) {
  1149. // In pointer access chains, the element operand is required, but not
  1150. // counted as an index.
  1151. --num_indexes;
  1152. }
  1153. const size_t num_indexes_limit =
  1154. _.options()->universal_limits_.max_access_chain_indexes;
  1155. if (num_indexes > num_indexes_limit) {
  1156. return _.diag(SPV_ERROR_INVALID_ID, inst)
  1157. << "The number of indexes in " << instr_name << " may not exceed "
  1158. << num_indexes_limit << ". Found " << num_indexes << " indexes.";
  1159. }
  1160. // Indexes walk the type hierarchy to the desired depth, potentially down to
  1161. // scalar granularity. The first index in Indexes will select the top-level
  1162. // member/element/component/element of the base composite. All composite
  1163. // constituents use zero-based numbering, as described by their OpType...
  1164. // instruction. The second index will apply similarly to that result, and so
  1165. // on. Once any non-composite type is reached, there must be no remaining
  1166. // (unused) indexes.
  1167. auto starting_index = 4;
  1168. if (inst->opcode() == SpvOpPtrAccessChain ||
  1169. inst->opcode() == SpvOpInBoundsPtrAccessChain) {
  1170. ++starting_index;
  1171. }
  1172. for (size_t i = starting_index; i < inst->words().size(); ++i) {
  1173. const uint32_t cur_word = inst->words()[i];
  1174. // Earlier ID checks ensure that cur_word definition exists.
  1175. auto cur_word_instr = _.FindDef(cur_word);
  1176. // The index must be a scalar integer type (See OpAccessChain in the Spec.)
  1177. auto index_type = _.FindDef(cur_word_instr->type_id());
  1178. if (!index_type || SpvOpTypeInt != index_type->opcode()) {
  1179. return _.diag(SPV_ERROR_INVALID_ID, inst)
  1180. << "Indexes passed to " << instr_name
  1181. << " must be of type integer.";
  1182. }
  1183. switch (type_pointee->opcode()) {
  1184. case SpvOpTypeMatrix:
  1185. case SpvOpTypeVector:
  1186. case SpvOpTypeCooperativeMatrixNV:
  1187. case SpvOpTypeArray:
  1188. case SpvOpTypeRuntimeArray: {
  1189. // In OpTypeMatrix, OpTypeVector, SpvOpTypeCooperativeMatrixNV,
  1190. // OpTypeArray, and OpTypeRuntimeArray, word 2 is the Element Type.
  1191. type_pointee = _.FindDef(type_pointee->word(2));
  1192. break;
  1193. }
  1194. case SpvOpTypeStruct: {
  1195. // In case of structures, there is an additional constraint on the
  1196. // index: the index must be an OpConstant.
  1197. if (SpvOpConstant != cur_word_instr->opcode()) {
  1198. return _.diag(SPV_ERROR_INVALID_ID, cur_word_instr)
  1199. << "The <id> passed to " << instr_name
  1200. << " to index into a "
  1201. "structure must be an OpConstant.";
  1202. }
  1203. // Get the index value from the OpConstant (word 3 of OpConstant).
  1204. // OpConstant could be a signed integer. But it's okay to treat it as
  1205. // unsigned because a negative constant int would never be seen as
  1206. // correct as a struct offset, since structs can't have more than 2
  1207. // billion members.
  1208. const uint32_t cur_index = cur_word_instr->word(3);
  1209. // The index points to the struct member we want, therefore, the index
  1210. // should be less than the number of struct members.
  1211. const uint32_t num_struct_members =
  1212. static_cast<uint32_t>(type_pointee->words().size() - 2);
  1213. if (cur_index >= num_struct_members) {
  1214. return _.diag(SPV_ERROR_INVALID_ID, cur_word_instr)
  1215. << "Index is out of bounds: " << instr_name
  1216. << " can not find index " << cur_index
  1217. << " into the structure <id> '"
  1218. << _.getIdName(type_pointee->id()) << "'. This structure has "
  1219. << num_struct_members << " members. Largest valid index is "
  1220. << num_struct_members - 1 << ".";
  1221. }
  1222. // Struct members IDs start at word 2 of OpTypeStruct.
  1223. auto structMemberId = type_pointee->word(cur_index + 2);
  1224. type_pointee = _.FindDef(structMemberId);
  1225. break;
  1226. }
  1227. default: {
  1228. // Give an error. reached non-composite type while indexes still remain.
  1229. return _.diag(SPV_ERROR_INVALID_ID, cur_word_instr)
  1230. << instr_name
  1231. << " reached non-composite type while indexes "
  1232. "still remain to be traversed.";
  1233. }
  1234. }
  1235. }
  1236. // At this point, we have fully walked down from the base using the indeces.
  1237. // The type being pointed to should be the same as the result type.
  1238. if (type_pointee->id() != result_type_pointee->id()) {
  1239. return _.diag(SPV_ERROR_INVALID_ID, inst)
  1240. << instr_name << " result type (Op"
  1241. << spvOpcodeString(static_cast<SpvOp>(result_type_pointee->opcode()))
  1242. << ") does not match the type that results from indexing into the "
  1243. "base "
  1244. "<id> (Op"
  1245. << spvOpcodeString(static_cast<SpvOp>(type_pointee->opcode()))
  1246. << ").";
  1247. }
  1248. return SPV_SUCCESS;
  1249. }
  1250. spv_result_t ValidatePtrAccessChain(ValidationState_t& _,
  1251. const Instruction* inst) {
  1252. if (_.addressing_model() == SpvAddressingModelLogical) {
  1253. if (!_.features().variable_pointers &&
  1254. !_.features().variable_pointers_storage_buffer) {
  1255. return _.diag(SPV_ERROR_INVALID_DATA, inst)
  1256. << "Generating variable pointers requires capability "
  1257. << "VariablePointers or VariablePointersStorageBuffer";
  1258. }
  1259. }
  1260. return ValidateAccessChain(_, inst);
  1261. }
  1262. spv_result_t ValidateArrayLength(ValidationState_t& state,
  1263. const Instruction* inst) {
  1264. std::string instr_name =
  1265. "Op" + std::string(spvOpcodeString(static_cast<SpvOp>(inst->opcode())));
  1266. // Result type must be a 32-bit unsigned int.
  1267. auto result_type = state.FindDef(inst->type_id());
  1268. if (result_type->opcode() != SpvOpTypeInt ||
  1269. result_type->GetOperandAs<uint32_t>(1) != 32 ||
  1270. result_type->GetOperandAs<uint32_t>(2) != 0) {
  1271. return state.diag(SPV_ERROR_INVALID_ID, inst)
  1272. << "The Result Type of " << instr_name << " <id> '"
  1273. << state.getIdName(inst->id())
  1274. << "' must be OpTypeInt with width 32 and signedness 0.";
  1275. }
  1276. // The structure that is passed in must be an pointer to a structure, whose
  1277. // last element is a runtime array.
  1278. auto pointer = state.FindDef(inst->GetOperandAs<uint32_t>(2));
  1279. auto pointer_type = state.FindDef(pointer->type_id());
  1280. if (pointer_type->opcode() != SpvOpTypePointer) {
  1281. return state.diag(SPV_ERROR_INVALID_ID, inst)
  1282. << "The Struture's type in " << instr_name << " <id> '"
  1283. << state.getIdName(inst->id())
  1284. << "' must be a pointer to an OpTypeStruct.";
  1285. }
  1286. auto structure_type = state.FindDef(pointer_type->GetOperandAs<uint32_t>(2));
  1287. if (structure_type->opcode() != SpvOpTypeStruct) {
  1288. return state.diag(SPV_ERROR_INVALID_ID, inst)
  1289. << "The Struture's type in " << instr_name << " <id> '"
  1290. << state.getIdName(inst->id())
  1291. << "' must be a pointer to an OpTypeStruct.";
  1292. }
  1293. auto num_of_members = structure_type->operands().size() - 1;
  1294. auto last_member =
  1295. state.FindDef(structure_type->GetOperandAs<uint32_t>(num_of_members));
  1296. if (last_member->opcode() != SpvOpTypeRuntimeArray) {
  1297. return state.diag(SPV_ERROR_INVALID_ID, inst)
  1298. << "The Struture's last member in " << instr_name << " <id> '"
  1299. << state.getIdName(inst->id()) << "' must be an OpTypeRuntimeArray.";
  1300. }
  1301. // The array member must the the index of the last element (the run time
  1302. // array).
  1303. if (inst->GetOperandAs<uint32_t>(3) != num_of_members - 1) {
  1304. return state.diag(SPV_ERROR_INVALID_ID, inst)
  1305. << "The array member in " << instr_name << " <id> '"
  1306. << state.getIdName(inst->id())
  1307. << "' must be an the last member of the struct.";
  1308. }
  1309. return SPV_SUCCESS;
  1310. }
  1311. spv_result_t ValidateCooperativeMatrixLengthNV(ValidationState_t& state,
  1312. const Instruction* inst) {
  1313. std::string instr_name =
  1314. "Op" + std::string(spvOpcodeString(static_cast<SpvOp>(inst->opcode())));
  1315. // Result type must be a 32-bit unsigned int.
  1316. auto result_type = state.FindDef(inst->type_id());
  1317. if (result_type->opcode() != SpvOpTypeInt ||
  1318. result_type->GetOperandAs<uint32_t>(1) != 32 ||
  1319. result_type->GetOperandAs<uint32_t>(2) != 0) {
  1320. return state.diag(SPV_ERROR_INVALID_ID, inst)
  1321. << "The Result Type of " << instr_name << " <id> '"
  1322. << state.getIdName(inst->id())
  1323. << "' must be OpTypeInt with width 32 and signedness 0.";
  1324. }
  1325. auto type_id = inst->GetOperandAs<uint32_t>(2);
  1326. auto type = state.FindDef(type_id);
  1327. if (type->opcode() != SpvOpTypeCooperativeMatrixNV) {
  1328. return state.diag(SPV_ERROR_INVALID_ID, inst)
  1329. << "The type in " << instr_name << " <id> '"
  1330. << state.getIdName(type_id)
  1331. << "' must be OpTypeCooperativeMatrixNV.";
  1332. }
  1333. return SPV_SUCCESS;
  1334. }
  1335. spv_result_t ValidateCooperativeMatrixLoadStoreNV(ValidationState_t& _,
  1336. const Instruction* inst) {
  1337. uint32_t type_id;
  1338. const char* opname;
  1339. if (inst->opcode() == SpvOpCooperativeMatrixLoadNV) {
  1340. type_id = inst->type_id();
  1341. opname = "SpvOpCooperativeMatrixLoadNV";
  1342. } else {
  1343. // get Object operand's type
  1344. type_id = _.FindDef(inst->GetOperandAs<uint32_t>(1))->type_id();
  1345. opname = "SpvOpCooperativeMatrixStoreNV";
  1346. }
  1347. auto matrix_type = _.FindDef(type_id);
  1348. if (matrix_type->opcode() != SpvOpTypeCooperativeMatrixNV) {
  1349. if (inst->opcode() == SpvOpCooperativeMatrixLoadNV) {
  1350. return _.diag(SPV_ERROR_INVALID_ID, inst)
  1351. << "SpvOpCooperativeMatrixLoadNV Result Type <id> '"
  1352. << _.getIdName(type_id) << "' is not a cooperative matrix type.";
  1353. } else {
  1354. return _.diag(SPV_ERROR_INVALID_ID, inst)
  1355. << "SpvOpCooperativeMatrixStoreNV Object type <id> '"
  1356. << _.getIdName(type_id) << "' is not a cooperative matrix type.";
  1357. }
  1358. }
  1359. const bool uses_variable_pointers =
  1360. _.features().variable_pointers ||
  1361. _.features().variable_pointers_storage_buffer;
  1362. const auto pointer_index =
  1363. (inst->opcode() == SpvOpCooperativeMatrixLoadNV) ? 2u : 0u;
  1364. const auto pointer_id = inst->GetOperandAs<uint32_t>(pointer_index);
  1365. const auto pointer = _.FindDef(pointer_id);
  1366. if (!pointer ||
  1367. ((_.addressing_model() == SpvAddressingModelLogical) &&
  1368. ((!uses_variable_pointers &&
  1369. !spvOpcodeReturnsLogicalPointer(pointer->opcode())) ||
  1370. (uses_variable_pointers &&
  1371. !spvOpcodeReturnsLogicalVariablePointer(pointer->opcode()))))) {
  1372. return _.diag(SPV_ERROR_INVALID_ID, inst)
  1373. << opname << " Pointer <id> '" << _.getIdName(pointer_id)
  1374. << "' is not a logical pointer.";
  1375. }
  1376. const auto pointer_type_id = pointer->type_id();
  1377. const auto pointer_type = _.FindDef(pointer_type_id);
  1378. if (!pointer_type || pointer_type->opcode() != SpvOpTypePointer) {
  1379. return _.diag(SPV_ERROR_INVALID_ID, inst)
  1380. << opname << " type for pointer <id> '" << _.getIdName(pointer_id)
  1381. << "' is not a pointer type.";
  1382. }
  1383. const auto storage_class_index = 1u;
  1384. const auto storage_class =
  1385. pointer_type->GetOperandAs<uint32_t>(storage_class_index);
  1386. if (storage_class != SpvStorageClassWorkgroup &&
  1387. storage_class != SpvStorageClassStorageBuffer &&
  1388. storage_class != SpvStorageClassPhysicalStorageBufferEXT) {
  1389. return _.diag(SPV_ERROR_INVALID_ID, inst)
  1390. << opname << " storage class for pointer type <id> '"
  1391. << _.getIdName(pointer_type_id)
  1392. << "' is not Workgroup or StorageBuffer.";
  1393. }
  1394. const auto pointee_id = pointer_type->GetOperandAs<uint32_t>(2);
  1395. const auto pointee_type = _.FindDef(pointee_id);
  1396. if (!pointee_type || !(_.IsIntScalarOrVectorType(pointee_id) ||
  1397. _.IsFloatScalarOrVectorType(pointee_id))) {
  1398. return _.diag(SPV_ERROR_INVALID_ID, inst)
  1399. << opname << " Pointer <id> '" << _.getIdName(pointer->id())
  1400. << "'s Type must be a scalar or vector type.";
  1401. }
  1402. const auto stride_index =
  1403. (inst->opcode() == SpvOpCooperativeMatrixLoadNV) ? 3u : 2u;
  1404. const auto stride_id = inst->GetOperandAs<uint32_t>(stride_index);
  1405. const auto stride = _.FindDef(stride_id);
  1406. if (!stride || !_.IsIntScalarType(stride->type_id())) {
  1407. return _.diag(SPV_ERROR_INVALID_ID, inst)
  1408. << "Stride operand <id> '" << _.getIdName(stride_id)
  1409. << "' must be a scalar integer type.";
  1410. }
  1411. const auto colmajor_index =
  1412. (inst->opcode() == SpvOpCooperativeMatrixLoadNV) ? 4u : 3u;
  1413. const auto colmajor_id = inst->GetOperandAs<uint32_t>(colmajor_index);
  1414. const auto colmajor = _.FindDef(colmajor_id);
  1415. if (!colmajor || !_.IsBoolScalarType(colmajor->type_id()) ||
  1416. !(spvOpcodeIsConstant(colmajor->opcode()) ||
  1417. spvOpcodeIsSpecConstant(colmajor->opcode()))) {
  1418. return _.diag(SPV_ERROR_INVALID_ID, inst)
  1419. << "Column Major operand <id> '" << _.getIdName(colmajor_id)
  1420. << "' must be a boolean constant instruction.";
  1421. }
  1422. const auto memory_access_index =
  1423. (inst->opcode() == SpvOpCooperativeMatrixLoadNV) ? 5u : 4u;
  1424. if (inst->operands().size() > memory_access_index) {
  1425. if (auto error = CheckMemoryAccess(_, inst, memory_access_index))
  1426. return error;
  1427. }
  1428. return SPV_SUCCESS;
  1429. }
  1430. spv_result_t ValidatePtrComparison(ValidationState_t& _,
  1431. const Instruction* inst) {
  1432. if (_.addressing_model() == SpvAddressingModelLogical &&
  1433. !_.features().variable_pointers_storage_buffer) {
  1434. return _.diag(SPV_ERROR_INVALID_ID, inst)
  1435. << "Instruction cannot be used without a variable pointers "
  1436. "capability";
  1437. }
  1438. const auto result_type = _.FindDef(inst->type_id());
  1439. if (inst->opcode() == SpvOpPtrDiff) {
  1440. if (!result_type || result_type->opcode() != SpvOpTypeInt) {
  1441. return _.diag(SPV_ERROR_INVALID_ID, inst)
  1442. << "Result Type must be an integer scalar";
  1443. }
  1444. } else {
  1445. if (!result_type || result_type->opcode() != SpvOpTypeBool) {
  1446. return _.diag(SPV_ERROR_INVALID_ID, inst)
  1447. << "Result Type must be OpTypeBool";
  1448. }
  1449. }
  1450. const auto op1 = _.FindDef(inst->GetOperandAs<uint32_t>(2u));
  1451. const auto op2 = _.FindDef(inst->GetOperandAs<uint32_t>(3u));
  1452. if (!op1 || !op2 || op1->type_id() != op2->type_id()) {
  1453. return _.diag(SPV_ERROR_INVALID_ID, inst)
  1454. << "The types of Operand 1 and Operand 2 must match";
  1455. }
  1456. const auto op1_type = _.FindDef(op1->type_id());
  1457. if (!op1_type || op1_type->opcode() != SpvOpTypePointer) {
  1458. return _.diag(SPV_ERROR_INVALID_ID, inst)
  1459. << "Operand type must be a pointer";
  1460. }
  1461. SpvStorageClass sc = op1_type->GetOperandAs<SpvStorageClass>(1u);
  1462. if (_.addressing_model() == SpvAddressingModelLogical) {
  1463. if (sc != SpvStorageClassWorkgroup && sc != SpvStorageClassStorageBuffer) {
  1464. return _.diag(SPV_ERROR_INVALID_ID, inst)
  1465. << "Invalid pointer storage class";
  1466. }
  1467. if (sc == SpvStorageClassWorkgroup && !_.features().variable_pointers) {
  1468. return _.diag(SPV_ERROR_INVALID_ID, inst)
  1469. << "Workgroup storage class pointer requires VariablePointers "
  1470. "capability to be specified";
  1471. }
  1472. } else if (sc == SpvStorageClassPhysicalStorageBuffer) {
  1473. return _.diag(SPV_ERROR_INVALID_ID, inst)
  1474. << "Cannot use a pointer in the PhysicalStorageBuffer storage class";
  1475. }
  1476. return SPV_SUCCESS;
  1477. }
  1478. } // namespace
  1479. spv_result_t MemoryPass(ValidationState_t& _, const Instruction* inst) {
  1480. switch (inst->opcode()) {
  1481. case SpvOpVariable:
  1482. if (auto error = ValidateVariable(_, inst)) return error;
  1483. break;
  1484. case SpvOpLoad:
  1485. if (auto error = ValidateLoad(_, inst)) return error;
  1486. break;
  1487. case SpvOpStore:
  1488. if (auto error = ValidateStore(_, inst)) return error;
  1489. break;
  1490. case SpvOpCopyMemory:
  1491. case SpvOpCopyMemorySized:
  1492. if (auto error = ValidateCopyMemory(_, inst)) return error;
  1493. break;
  1494. case SpvOpPtrAccessChain:
  1495. if (auto error = ValidatePtrAccessChain(_, inst)) return error;
  1496. break;
  1497. case SpvOpAccessChain:
  1498. case SpvOpInBoundsAccessChain:
  1499. case SpvOpInBoundsPtrAccessChain:
  1500. if (auto error = ValidateAccessChain(_, inst)) return error;
  1501. break;
  1502. case SpvOpArrayLength:
  1503. if (auto error = ValidateArrayLength(_, inst)) return error;
  1504. break;
  1505. case SpvOpCooperativeMatrixLoadNV:
  1506. case SpvOpCooperativeMatrixStoreNV:
  1507. if (auto error = ValidateCooperativeMatrixLoadStoreNV(_, inst))
  1508. return error;
  1509. break;
  1510. case SpvOpCooperativeMatrixLengthNV:
  1511. if (auto error = ValidateCooperativeMatrixLengthNV(_, inst)) return error;
  1512. break;
  1513. case SpvOpPtrEqual:
  1514. case SpvOpPtrNotEqual:
  1515. case SpvOpPtrDiff:
  1516. if (auto error = ValidatePtrComparison(_, inst)) return error;
  1517. break;
  1518. case SpvOpImageTexelPointer:
  1519. case SpvOpGenericPtrMemSemantics:
  1520. default:
  1521. break;
  1522. }
  1523. return SPV_SUCCESS;
  1524. }
  1525. } // namespace val
  1526. } // namespace spvtools