validate_decorations.cpp 72 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713
  1. // Copyright (c) 2017 Google Inc.
  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 <cassert>
  16. #include <string>
  17. #include <tuple>
  18. #include <unordered_map>
  19. #include <unordered_set>
  20. #include <utility>
  21. #include <vector>
  22. #include "source/diagnostic.h"
  23. #include "source/opcode.h"
  24. #include "source/spirv_constant.h"
  25. #include "source/spirv_target_env.h"
  26. #include "source/spirv_validator_options.h"
  27. #include "source/val/validate_scopes.h"
  28. #include "source/val/validation_state.h"
  29. namespace spvtools {
  30. namespace val {
  31. namespace {
  32. // Distinguish between row and column major matrix layouts.
  33. enum MatrixLayout { kRowMajor, kColumnMajor };
  34. // A functor for hashing a pair of integers.
  35. struct PairHash {
  36. std::size_t operator()(const std::pair<uint32_t, uint32_t> pair) const {
  37. const uint32_t a = pair.first;
  38. const uint32_t b = pair.second;
  39. const uint32_t rotated_b = (b >> 2) | ((b & 3) << 30);
  40. return a ^ rotated_b;
  41. }
  42. };
  43. // A functor for hashing decoration types.
  44. struct SpvDecorationHash {
  45. std::size_t operator()(SpvDecoration dec) const {
  46. return static_cast<std::size_t>(dec);
  47. }
  48. };
  49. // Struct member layout attributes that are inherited through arrays.
  50. struct LayoutConstraints {
  51. explicit LayoutConstraints(
  52. MatrixLayout the_majorness = MatrixLayout::kColumnMajor,
  53. uint32_t stride = 0)
  54. : majorness(the_majorness), matrix_stride(stride) {}
  55. MatrixLayout majorness;
  56. uint32_t matrix_stride;
  57. };
  58. // A type for mapping (struct id, member id) to layout constraints.
  59. using MemberConstraints = std::unordered_map<std::pair<uint32_t, uint32_t>,
  60. LayoutConstraints, PairHash>;
  61. // Returns the array stride of the given array type.
  62. uint32_t GetArrayStride(uint32_t array_id, ValidationState_t& vstate) {
  63. for (auto& decoration : vstate.id_decorations(array_id)) {
  64. if (SpvDecorationArrayStride == decoration.dec_type()) {
  65. return decoration.params()[0];
  66. }
  67. }
  68. return 0;
  69. }
  70. // Returns true if the given variable has a BuiltIn decoration.
  71. bool isBuiltInVar(uint32_t var_id, ValidationState_t& vstate) {
  72. const auto& decorations = vstate.id_decorations(var_id);
  73. return std::any_of(
  74. decorations.begin(), decorations.end(),
  75. [](const Decoration& d) { return SpvDecorationBuiltIn == d.dec_type(); });
  76. }
  77. // Returns true if the given structure type has any members with BuiltIn
  78. // decoration.
  79. bool isBuiltInStruct(uint32_t struct_id, ValidationState_t& vstate) {
  80. const auto& decorations = vstate.id_decorations(struct_id);
  81. return std::any_of(
  82. decorations.begin(), decorations.end(), [](const Decoration& d) {
  83. return SpvDecorationBuiltIn == d.dec_type() &&
  84. Decoration::kInvalidMember != d.struct_member_index();
  85. });
  86. }
  87. // Returns true if the given ID has the Import LinkageAttributes decoration.
  88. bool hasImportLinkageAttribute(uint32_t id, ValidationState_t& vstate) {
  89. const auto& decorations = vstate.id_decorations(id);
  90. return std::any_of(decorations.begin(), decorations.end(),
  91. [](const Decoration& d) {
  92. return SpvDecorationLinkageAttributes == d.dec_type() &&
  93. d.params().size() >= 2u &&
  94. d.params().back() == SpvLinkageTypeImport;
  95. });
  96. }
  97. // Returns a vector of all members of a structure.
  98. std::vector<uint32_t> getStructMembers(uint32_t struct_id,
  99. ValidationState_t& vstate) {
  100. const auto inst = vstate.FindDef(struct_id);
  101. return std::vector<uint32_t>(inst->words().begin() + 2, inst->words().end());
  102. }
  103. // Returns a vector of all members of a structure that have specific type.
  104. std::vector<uint32_t> getStructMembers(uint32_t struct_id, SpvOp type,
  105. ValidationState_t& vstate) {
  106. std::vector<uint32_t> members;
  107. for (auto id : getStructMembers(struct_id, vstate)) {
  108. if (type == vstate.FindDef(id)->opcode()) {
  109. members.push_back(id);
  110. }
  111. }
  112. return members;
  113. }
  114. // Returns whether the given structure is missing Offset decoration for any
  115. // member. Handles also nested structures.
  116. bool isMissingOffsetInStruct(uint32_t struct_id, ValidationState_t& vstate) {
  117. const auto* inst = vstate.FindDef(struct_id);
  118. std::vector<bool> hasOffset;
  119. std::vector<uint32_t> struct_members;
  120. if (inst->opcode() == SpvOpTypeStruct) {
  121. // Check offsets of member decorations.
  122. struct_members = getStructMembers(struct_id, vstate);
  123. hasOffset.resize(struct_members.size(), false);
  124. for (auto& decoration : vstate.id_decorations(struct_id)) {
  125. if (SpvDecorationOffset == decoration.dec_type() &&
  126. Decoration::kInvalidMember != decoration.struct_member_index()) {
  127. // Offset 0xffffffff is not valid so ignore it for simplicity's sake.
  128. if (decoration.params()[0] == 0xffffffff) return true;
  129. hasOffset[decoration.struct_member_index()] = true;
  130. }
  131. }
  132. } else if (inst->opcode() == SpvOpTypeArray ||
  133. inst->opcode() == SpvOpTypeRuntimeArray) {
  134. hasOffset.resize(1, true);
  135. struct_members.push_back(inst->GetOperandAs<uint32_t>(1u));
  136. }
  137. // Look through nested structs (which may be in an array).
  138. bool nestedStructsMissingOffset = false;
  139. for (auto id : struct_members) {
  140. if (isMissingOffsetInStruct(id, vstate)) {
  141. nestedStructsMissingOffset = true;
  142. break;
  143. }
  144. }
  145. return nestedStructsMissingOffset ||
  146. !std::all_of(hasOffset.begin(), hasOffset.end(),
  147. [](const bool b) { return b; });
  148. }
  149. // Rounds x up to the next alignment. Assumes alignment is a power of two.
  150. uint32_t align(uint32_t x, uint32_t alignment) {
  151. return (x + alignment - 1) & ~(alignment - 1);
  152. }
  153. // Returns base alignment of struct member. If |roundUp| is true, also
  154. // ensure that structs and arrays are aligned at least to a multiple of 16
  155. // bytes.
  156. uint32_t getBaseAlignment(uint32_t member_id, bool roundUp,
  157. const LayoutConstraints& inherited,
  158. MemberConstraints& constraints,
  159. ValidationState_t& vstate) {
  160. const auto inst = vstate.FindDef(member_id);
  161. const auto& words = inst->words();
  162. // Minimal alignment is byte-aligned.
  163. uint32_t baseAlignment = 1;
  164. switch (inst->opcode()) {
  165. case SpvOpTypeInt:
  166. case SpvOpTypeFloat:
  167. baseAlignment = words[2] / 8;
  168. break;
  169. case SpvOpTypeVector: {
  170. const auto componentId = words[2];
  171. const auto numComponents = words[3];
  172. const auto componentAlignment = getBaseAlignment(
  173. componentId, roundUp, inherited, constraints, vstate);
  174. baseAlignment =
  175. componentAlignment * (numComponents == 3 ? 4 : numComponents);
  176. break;
  177. }
  178. case SpvOpTypeMatrix: {
  179. const auto column_type = words[2];
  180. if (inherited.majorness == kColumnMajor) {
  181. baseAlignment = getBaseAlignment(column_type, roundUp, inherited,
  182. constraints, vstate);
  183. } else {
  184. // A row-major matrix of C columns has a base alignment equal to the
  185. // base alignment of a vector of C matrix components.
  186. const auto num_columns = words[3];
  187. const auto component_inst = vstate.FindDef(column_type);
  188. const auto component_id = component_inst->words()[2];
  189. const auto componentAlignment = getBaseAlignment(
  190. component_id, roundUp, inherited, constraints, vstate);
  191. baseAlignment =
  192. componentAlignment * (num_columns == 3 ? 4 : num_columns);
  193. }
  194. } break;
  195. case SpvOpTypeArray:
  196. case SpvOpTypeRuntimeArray:
  197. baseAlignment =
  198. getBaseAlignment(words[2], roundUp, inherited, constraints, vstate);
  199. if (roundUp) baseAlignment = align(baseAlignment, 16u);
  200. break;
  201. case SpvOpTypeStruct: {
  202. const auto members = getStructMembers(member_id, vstate);
  203. for (uint32_t memberIdx = 0, numMembers = uint32_t(members.size());
  204. memberIdx < numMembers; ++memberIdx) {
  205. const auto id = members[memberIdx];
  206. const auto& constraint =
  207. constraints[std::make_pair(member_id, memberIdx)];
  208. baseAlignment = std::max(
  209. baseAlignment,
  210. getBaseAlignment(id, roundUp, constraint, constraints, vstate));
  211. }
  212. if (roundUp) baseAlignment = align(baseAlignment, 16u);
  213. break;
  214. }
  215. case SpvOpTypePointer:
  216. baseAlignment = vstate.pointer_size_and_alignment();
  217. break;
  218. default:
  219. assert(0);
  220. break;
  221. }
  222. return baseAlignment;
  223. }
  224. // Returns scalar alignment of a type.
  225. uint32_t getScalarAlignment(uint32_t type_id, ValidationState_t& vstate) {
  226. const auto inst = vstate.FindDef(type_id);
  227. const auto& words = inst->words();
  228. switch (inst->opcode()) {
  229. case SpvOpTypeInt:
  230. case SpvOpTypeFloat:
  231. return words[2] / 8;
  232. case SpvOpTypeVector:
  233. case SpvOpTypeMatrix:
  234. case SpvOpTypeArray:
  235. case SpvOpTypeRuntimeArray: {
  236. const auto compositeMemberTypeId = words[2];
  237. return getScalarAlignment(compositeMemberTypeId, vstate);
  238. }
  239. case SpvOpTypeStruct: {
  240. const auto members = getStructMembers(type_id, vstate);
  241. uint32_t max_member_alignment = 1;
  242. for (uint32_t memberIdx = 0, numMembers = uint32_t(members.size());
  243. memberIdx < numMembers; ++memberIdx) {
  244. const auto id = members[memberIdx];
  245. uint32_t member_alignment = getScalarAlignment(id, vstate);
  246. if (member_alignment > max_member_alignment) {
  247. max_member_alignment = member_alignment;
  248. }
  249. }
  250. return max_member_alignment;
  251. } break;
  252. case SpvOpTypePointer:
  253. return vstate.pointer_size_and_alignment();
  254. default:
  255. assert(0);
  256. break;
  257. }
  258. return 1;
  259. }
  260. // Returns size of a struct member. Doesn't include padding at the end of struct
  261. // or array. Assumes that in the struct case, all members have offsets.
  262. uint32_t getSize(uint32_t member_id, const LayoutConstraints& inherited,
  263. MemberConstraints& constraints, ValidationState_t& vstate) {
  264. const auto inst = vstate.FindDef(member_id);
  265. const auto& words = inst->words();
  266. switch (inst->opcode()) {
  267. case SpvOpTypeInt:
  268. case SpvOpTypeFloat:
  269. return words[2] / 8;
  270. case SpvOpTypeVector: {
  271. const auto componentId = words[2];
  272. const auto numComponents = words[3];
  273. const auto componentSize =
  274. getSize(componentId, inherited, constraints, vstate);
  275. const auto size = componentSize * numComponents;
  276. return size;
  277. }
  278. case SpvOpTypeArray: {
  279. const auto sizeInst = vstate.FindDef(words[3]);
  280. if (spvOpcodeIsSpecConstant(sizeInst->opcode())) return 0;
  281. assert(SpvOpConstant == sizeInst->opcode());
  282. const uint32_t num_elem = sizeInst->words()[3];
  283. const uint32_t elem_type = words[2];
  284. const uint32_t elem_size =
  285. getSize(elem_type, inherited, constraints, vstate);
  286. // Account for gaps due to alignments in the first N-1 elements,
  287. // then add the size of the last element.
  288. const auto size =
  289. (num_elem - 1) * GetArrayStride(member_id, vstate) + elem_size;
  290. return size;
  291. }
  292. case SpvOpTypeRuntimeArray:
  293. return 0;
  294. case SpvOpTypeMatrix: {
  295. const auto num_columns = words[3];
  296. if (inherited.majorness == kColumnMajor) {
  297. return num_columns * inherited.matrix_stride;
  298. } else {
  299. // Row major case.
  300. const auto column_type = words[2];
  301. const auto component_inst = vstate.FindDef(column_type);
  302. const auto num_rows = component_inst->words()[3];
  303. const auto scalar_elem_type = component_inst->words()[2];
  304. const uint32_t scalar_elem_size =
  305. getSize(scalar_elem_type, inherited, constraints, vstate);
  306. return (num_rows - 1) * inherited.matrix_stride +
  307. num_columns * scalar_elem_size;
  308. }
  309. }
  310. case SpvOpTypeStruct: {
  311. const auto& members = getStructMembers(member_id, vstate);
  312. if (members.empty()) return 0;
  313. const auto lastIdx = uint32_t(members.size() - 1);
  314. const auto& lastMember = members.back();
  315. uint32_t offset = 0xffffffff;
  316. // Find the offset of the last element and add the size.
  317. for (auto& decoration : vstate.id_decorations(member_id)) {
  318. if (SpvDecorationOffset == decoration.dec_type() &&
  319. decoration.struct_member_index() == (int)lastIdx) {
  320. offset = decoration.params()[0];
  321. }
  322. }
  323. // This check depends on the fact that all members have offsets. This
  324. // has been checked earlier in the flow.
  325. assert(offset != 0xffffffff);
  326. const auto& constraint = constraints[std::make_pair(lastMember, lastIdx)];
  327. return offset + getSize(lastMember, constraint, constraints, vstate);
  328. }
  329. case SpvOpTypePointer:
  330. return vstate.pointer_size_and_alignment();
  331. default:
  332. assert(0);
  333. return 0;
  334. }
  335. }
  336. // A member is defined to improperly straddle if either of the following are
  337. // true:
  338. // - It is a vector with total size less than or equal to 16 bytes, and has
  339. // Offset decorations placing its first byte at F and its last byte at L, where
  340. // floor(F / 16) != floor(L / 16).
  341. // - It is a vector with total size greater than 16 bytes and has its Offset
  342. // decorations placing its first byte at a non-integer multiple of 16.
  343. bool hasImproperStraddle(uint32_t id, uint32_t offset,
  344. const LayoutConstraints& inherited,
  345. MemberConstraints& constraints,
  346. ValidationState_t& vstate) {
  347. const auto size = getSize(id, inherited, constraints, vstate);
  348. const auto F = offset;
  349. const auto L = offset + size - 1;
  350. if (size <= 16) {
  351. if ((F >> 4) != (L >> 4)) return true;
  352. } else {
  353. if (F % 16 != 0) return true;
  354. }
  355. return false;
  356. }
  357. // Returns true if |offset| satsifies an alignment to |alignment|. In the case
  358. // of |alignment| of zero, the |offset| must also be zero.
  359. bool IsAlignedTo(uint32_t offset, uint32_t alignment) {
  360. if (alignment == 0) return offset == 0;
  361. return 0 == (offset % alignment);
  362. }
  363. // Returns SPV_SUCCESS if the given struct satisfies standard layout rules for
  364. // Block or BufferBlocks in Vulkan. Otherwise emits a diagnostic and returns
  365. // something other than SPV_SUCCESS. Matrices inherit the specified column
  366. // or row major-ness.
  367. spv_result_t checkLayout(uint32_t struct_id, const char* storage_class_str,
  368. const char* decoration_str, bool blockRules,
  369. bool scalar_block_layout,
  370. uint32_t incoming_offset,
  371. MemberConstraints& constraints,
  372. ValidationState_t& vstate) {
  373. if (vstate.options()->skip_block_layout) return SPV_SUCCESS;
  374. // blockRules are the same as bufferBlock rules if the uniform buffer
  375. // standard layout extension is being used.
  376. if (vstate.options()->uniform_buffer_standard_layout) blockRules = false;
  377. // Relaxed layout and scalar layout can both be in effect at the same time.
  378. // For example, relaxed layout is implied by Vulkan 1.1. But scalar layout
  379. // is more permissive than relaxed layout.
  380. const bool relaxed_block_layout = vstate.IsRelaxedBlockLayout();
  381. auto fail = [&vstate, struct_id, storage_class_str, decoration_str,
  382. blockRules, relaxed_block_layout,
  383. scalar_block_layout](uint32_t member_idx) -> DiagnosticStream {
  384. DiagnosticStream ds =
  385. std::move(vstate.diag(SPV_ERROR_INVALID_ID, vstate.FindDef(struct_id))
  386. << "Structure id " << struct_id << " decorated as "
  387. << decoration_str << " for variable in " << storage_class_str
  388. << " storage class must follow "
  389. << (scalar_block_layout
  390. ? "scalar "
  391. : (relaxed_block_layout ? "relaxed " : "standard "))
  392. << (blockRules ? "uniform buffer" : "storage buffer")
  393. << " layout rules: member " << member_idx << " ");
  394. return ds;
  395. };
  396. const auto& members = getStructMembers(struct_id, vstate);
  397. // To check for member overlaps, we want to traverse the members in
  398. // offset order.
  399. struct MemberOffsetPair {
  400. uint32_t member;
  401. uint32_t offset;
  402. };
  403. std::vector<MemberOffsetPair> member_offsets;
  404. member_offsets.reserve(members.size());
  405. for (uint32_t memberIdx = 0, numMembers = uint32_t(members.size());
  406. memberIdx < numMembers; memberIdx++) {
  407. uint32_t offset = 0xffffffff;
  408. for (auto& decoration : vstate.id_decorations(struct_id)) {
  409. if (decoration.struct_member_index() == (int)memberIdx) {
  410. switch (decoration.dec_type()) {
  411. case SpvDecorationOffset:
  412. offset = decoration.params()[0];
  413. break;
  414. default:
  415. break;
  416. }
  417. }
  418. }
  419. member_offsets.push_back(
  420. MemberOffsetPair{memberIdx, incoming_offset + offset});
  421. }
  422. std::stable_sort(
  423. member_offsets.begin(), member_offsets.end(),
  424. [](const MemberOffsetPair& lhs, const MemberOffsetPair& rhs) {
  425. return lhs.offset < rhs.offset;
  426. });
  427. // Now scan from lowest offest to highest offset.
  428. uint32_t nextValidOffset = 0;
  429. for (size_t ordered_member_idx = 0;
  430. ordered_member_idx < member_offsets.size(); ordered_member_idx++) {
  431. const auto& member_offset = member_offsets[ordered_member_idx];
  432. const auto memberIdx = member_offset.member;
  433. const auto offset = member_offset.offset;
  434. auto id = members[member_offset.member];
  435. const LayoutConstraints& constraint =
  436. constraints[std::make_pair(struct_id, uint32_t(memberIdx))];
  437. // Scalar layout takes precedence because it's more permissive, and implying
  438. // an alignment that divides evenly into the alignment that would otherwise
  439. // be used.
  440. const auto alignment =
  441. scalar_block_layout
  442. ? getScalarAlignment(id, vstate)
  443. : getBaseAlignment(id, blockRules, constraint, constraints, vstate);
  444. const auto inst = vstate.FindDef(id);
  445. const auto opcode = inst->opcode();
  446. const auto size = getSize(id, constraint, constraints, vstate);
  447. // Check offset.
  448. if (offset == 0xffffffff)
  449. return fail(memberIdx) << "is missing an Offset decoration";
  450. if (!scalar_block_layout && relaxed_block_layout &&
  451. opcode == SpvOpTypeVector) {
  452. // In relaxed block layout, the vector offset must be aligned to the
  453. // vector's scalar element type.
  454. const auto componentId = inst->words()[2];
  455. const auto scalar_alignment = getScalarAlignment(componentId, vstate);
  456. if (!IsAlignedTo(offset, scalar_alignment)) {
  457. return fail(memberIdx)
  458. << "at offset " << offset
  459. << " is not aligned to scalar element size " << scalar_alignment;
  460. }
  461. } else {
  462. // Without relaxed block layout, the offset must be divisible by the
  463. // alignment requirement.
  464. if (!IsAlignedTo(offset, alignment)) {
  465. return fail(memberIdx)
  466. << "at offset " << offset << " is not aligned to " << alignment;
  467. }
  468. }
  469. if (offset < nextValidOffset)
  470. return fail(memberIdx) << "at offset " << offset
  471. << " overlaps previous member ending at offset "
  472. << nextValidOffset - 1;
  473. if (!scalar_block_layout && relaxed_block_layout) {
  474. // Check improper straddle of vectors.
  475. if (SpvOpTypeVector == opcode &&
  476. hasImproperStraddle(id, offset, constraint, constraints, vstate))
  477. return fail(memberIdx)
  478. << "is an improperly straddling vector at offset " << offset;
  479. }
  480. // Check struct members recursively.
  481. spv_result_t recursive_status = SPV_SUCCESS;
  482. if (SpvOpTypeStruct == opcode &&
  483. SPV_SUCCESS != (recursive_status = checkLayout(
  484. id, storage_class_str, decoration_str, blockRules,
  485. scalar_block_layout,
  486. offset, constraints, vstate)))
  487. return recursive_status;
  488. // Check matrix stride.
  489. if (SpvOpTypeMatrix == opcode) {
  490. const auto stride = constraint.matrix_stride;
  491. if (!IsAlignedTo(stride, alignment)) {
  492. return fail(memberIdx) << "is a matrix with stride " << stride
  493. << " not satisfying alignment to " << alignment;
  494. }
  495. }
  496. // Check arrays and runtime arrays recursively.
  497. auto array_inst = inst;
  498. auto array_alignment = alignment;
  499. while (array_inst->opcode() == SpvOpTypeArray ||
  500. array_inst->opcode() == SpvOpTypeRuntimeArray) {
  501. const auto typeId = array_inst->word(2);
  502. const auto element_inst = vstate.FindDef(typeId);
  503. // Check array stride.
  504. uint32_t array_stride = 0;
  505. for (auto& decoration : vstate.id_decorations(array_inst->id())) {
  506. if (SpvDecorationArrayStride == decoration.dec_type()) {
  507. array_stride = decoration.params()[0];
  508. if (array_stride == 0) {
  509. return fail(memberIdx) << "contains an array with stride 0";
  510. }
  511. if (!IsAlignedTo(array_stride, array_alignment))
  512. return fail(memberIdx)
  513. << "contains an array with stride " << decoration.params()[0]
  514. << " not satisfying alignment to " << alignment;
  515. }
  516. }
  517. bool is_int32 = false;
  518. bool is_const = false;
  519. uint32_t num_elements = 0;
  520. if (array_inst->opcode() == SpvOpTypeArray) {
  521. std::tie(is_int32, is_const, num_elements) =
  522. vstate.EvalInt32IfConst(array_inst->word(3));
  523. }
  524. num_elements = std::max(1u, num_elements);
  525. // Check each element recursively if it is a struct. There is a
  526. // limitation to this check if the array size is a spec constant or is a
  527. // runtime array then we will only check a single element. This means
  528. // some improper straddles might be missed.
  529. if (SpvOpTypeStruct == element_inst->opcode()) {
  530. std::vector<bool> seen(16, false);
  531. for (uint32_t i = 0; i < num_elements; ++i) {
  532. uint32_t next_offset = i * array_stride + offset;
  533. // Stop checking if offsets repeat in terms of 16-byte multiples.
  534. if (seen[next_offset % 16]) {
  535. break;
  536. }
  537. if (SPV_SUCCESS !=
  538. (recursive_status = checkLayout(
  539. typeId, storage_class_str, decoration_str, blockRules,
  540. scalar_block_layout, next_offset, constraints, vstate)))
  541. return recursive_status;
  542. seen[next_offset % 16] = true;
  543. }
  544. }
  545. // Proceed to the element in case it is an array.
  546. array_inst = element_inst;
  547. array_alignment = scalar_block_layout
  548. ? getScalarAlignment(array_inst->id(), vstate)
  549. : getBaseAlignment(array_inst->id(), blockRules,
  550. constraint, constraints, vstate);
  551. const auto element_size =
  552. getSize(element_inst->id(), constraint, constraints, vstate);
  553. if (element_size > array_stride) {
  554. return fail(memberIdx)
  555. << "contains an array with stride " << array_stride
  556. << ", but with an element size of " << element_size;
  557. }
  558. }
  559. nextValidOffset = offset + size;
  560. if (!scalar_block_layout && blockRules &&
  561. (SpvOpTypeArray == opcode || SpvOpTypeStruct == opcode)) {
  562. // Uniform block rules don't permit anything in the padding of a struct
  563. // or array.
  564. nextValidOffset = align(nextValidOffset, alignment);
  565. }
  566. }
  567. return SPV_SUCCESS;
  568. }
  569. // Returns true if variable or structure id has given decoration. Handles also
  570. // nested structures.
  571. bool hasDecoration(uint32_t id, SpvDecoration decoration,
  572. ValidationState_t& vstate) {
  573. for (auto& dec : vstate.id_decorations(id)) {
  574. if (decoration == dec.dec_type()) return true;
  575. }
  576. if (SpvOpTypeStruct != vstate.FindDef(id)->opcode()) {
  577. return false;
  578. }
  579. for (auto member_id : getStructMembers(id, SpvOpTypeStruct, vstate)) {
  580. if (hasDecoration(member_id, decoration, vstate)) {
  581. return true;
  582. }
  583. }
  584. return false;
  585. }
  586. // Returns true if all ids of given type have a specified decoration.
  587. bool checkForRequiredDecoration(uint32_t struct_id, SpvDecoration decoration,
  588. SpvOp type, ValidationState_t& vstate) {
  589. const auto& members = getStructMembers(struct_id, vstate);
  590. for (size_t memberIdx = 0; memberIdx < members.size(); memberIdx++) {
  591. const auto id = members[memberIdx];
  592. if (type != vstate.FindDef(id)->opcode()) continue;
  593. bool found = false;
  594. for (auto& dec : vstate.id_decorations(id)) {
  595. if (decoration == dec.dec_type()) found = true;
  596. }
  597. for (auto& dec : vstate.id_decorations(struct_id)) {
  598. if (decoration == dec.dec_type() &&
  599. (int)memberIdx == dec.struct_member_index()) {
  600. found = true;
  601. }
  602. }
  603. if (!found) {
  604. return false;
  605. }
  606. }
  607. for (auto id : getStructMembers(struct_id, SpvOpTypeStruct, vstate)) {
  608. if (!checkForRequiredDecoration(id, decoration, type, vstate)) {
  609. return false;
  610. }
  611. }
  612. return true;
  613. }
  614. spv_result_t CheckLinkageAttrOfFunctions(ValidationState_t& vstate) {
  615. for (const auto& function : vstate.functions()) {
  616. if (function.block_count() == 0u) {
  617. // A function declaration (an OpFunction with no basic blocks), must have
  618. // a Linkage Attributes Decoration with the Import Linkage Type.
  619. if (!hasImportLinkageAttribute(function.id(), vstate)) {
  620. return vstate.diag(SPV_ERROR_INVALID_BINARY,
  621. vstate.FindDef(function.id()))
  622. << "Function declaration (id " << function.id()
  623. << ") must have a LinkageAttributes decoration with the Import "
  624. "Linkage type.";
  625. }
  626. } else {
  627. if (hasImportLinkageAttribute(function.id(), vstate)) {
  628. return vstate.diag(SPV_ERROR_INVALID_BINARY,
  629. vstate.FindDef(function.id()))
  630. << "Function definition (id " << function.id()
  631. << ") may not be decorated with Import Linkage type.";
  632. }
  633. }
  634. }
  635. return SPV_SUCCESS;
  636. }
  637. // Checks whether an imported variable is initialized by this module.
  638. spv_result_t CheckImportedVariableInitialization(ValidationState_t& vstate) {
  639. // According the SPIR-V Spec 2.16.1, it is illegal to initialize an imported
  640. // variable. This means that a module-scope OpVariable with initialization
  641. // value cannot be marked with the Import Linkage Type (import type id = 1).
  642. for (auto global_var_id : vstate.global_vars()) {
  643. // Initializer <id> is an optional argument for OpVariable. If initializer
  644. // <id> is present, the instruction will have 5 words.
  645. auto variable_instr = vstate.FindDef(global_var_id);
  646. if (variable_instr->words().size() == 5u &&
  647. hasImportLinkageAttribute(global_var_id, vstate)) {
  648. return vstate.diag(SPV_ERROR_INVALID_ID, variable_instr)
  649. << "A module-scope OpVariable with initialization value "
  650. "cannot be marked with the Import Linkage Type.";
  651. }
  652. }
  653. return SPV_SUCCESS;
  654. }
  655. // Checks whether a builtin variable is valid.
  656. spv_result_t CheckBuiltInVariable(uint32_t var_id, ValidationState_t& vstate) {
  657. const auto& decorations = vstate.id_decorations(var_id);
  658. for (const auto& d : decorations) {
  659. if (spvIsVulkanEnv(vstate.context()->target_env)) {
  660. if (d.dec_type() == SpvDecorationLocation ||
  661. d.dec_type() == SpvDecorationComponent) {
  662. return vstate.diag(SPV_ERROR_INVALID_ID, vstate.FindDef(var_id))
  663. << "A BuiltIn variable (id " << var_id
  664. << ") cannot have any Location or Component decorations";
  665. }
  666. }
  667. }
  668. return SPV_SUCCESS;
  669. }
  670. // Checks whether proper decorations have been appied to the entry points.
  671. spv_result_t CheckDecorationsOfEntryPoints(ValidationState_t& vstate) {
  672. for (uint32_t entry_point : vstate.entry_points()) {
  673. const auto& descs = vstate.entry_point_descriptions(entry_point);
  674. int num_builtin_inputs = 0;
  675. int num_builtin_outputs = 0;
  676. int num_workgroup_variables = 0;
  677. int num_workgroup_variables_with_block = 0;
  678. int num_workgroup_variables_with_aliased = 0;
  679. for (const auto& desc : descs) {
  680. std::unordered_set<Instruction*> seen_vars;
  681. for (auto interface : desc.interfaces) {
  682. Instruction* var_instr = vstate.FindDef(interface);
  683. if (!var_instr || SpvOpVariable != var_instr->opcode()) {
  684. return vstate.diag(SPV_ERROR_INVALID_ID, var_instr)
  685. << "Interfaces passed to OpEntryPoint must be of type "
  686. "OpTypeVariable. Found Op"
  687. << spvOpcodeString(var_instr->opcode()) << ".";
  688. }
  689. const SpvStorageClass storage_class =
  690. var_instr->GetOperandAs<SpvStorageClass>(2);
  691. if (vstate.version() >= SPV_SPIRV_VERSION_WORD(1, 4)) {
  692. // Starting in 1.4, OpEntryPoint must list all global variables
  693. // it statically uses and those interfaces must be unique.
  694. if (storage_class == SpvStorageClassFunction) {
  695. return vstate.diag(SPV_ERROR_INVALID_ID, var_instr)
  696. << "OpEntryPoint interfaces should only list global "
  697. "variables";
  698. }
  699. if (!seen_vars.insert(var_instr).second) {
  700. return vstate.diag(SPV_ERROR_INVALID_ID, var_instr)
  701. << "Non-unique OpEntryPoint interface "
  702. << vstate.getIdName(interface) << " is disallowed";
  703. }
  704. } else {
  705. if (storage_class != SpvStorageClassInput &&
  706. storage_class != SpvStorageClassOutput) {
  707. return vstate.diag(SPV_ERROR_INVALID_ID, var_instr)
  708. << "OpEntryPoint interfaces must be OpVariables with "
  709. "Storage Class of Input(1) or Output(3). Found Storage "
  710. "Class "
  711. << storage_class << " for Entry Point id " << entry_point
  712. << ".";
  713. }
  714. }
  715. const uint32_t ptr_id = var_instr->word(1);
  716. Instruction* ptr_instr = vstate.FindDef(ptr_id);
  717. // It is guaranteed (by validator ID checks) that ptr_instr is
  718. // OpTypePointer. Word 3 of this instruction is the type being pointed
  719. // to.
  720. const uint32_t type_id = ptr_instr->word(3);
  721. Instruction* type_instr = vstate.FindDef(type_id);
  722. if (type_instr && SpvOpTypeStruct == type_instr->opcode() &&
  723. isBuiltInStruct(type_id, vstate)) {
  724. if (storage_class == SpvStorageClassInput) ++num_builtin_inputs;
  725. if (storage_class == SpvStorageClassOutput) ++num_builtin_outputs;
  726. if (num_builtin_inputs > 1 || num_builtin_outputs > 1) break;
  727. if (auto error = CheckBuiltInVariable(interface, vstate))
  728. return error;
  729. } else if (isBuiltInVar(interface, vstate)) {
  730. if (auto error = CheckBuiltInVariable(interface, vstate))
  731. return error;
  732. }
  733. if (storage_class == SpvStorageClassWorkgroup) {
  734. ++num_workgroup_variables;
  735. if (type_instr && SpvOpTypeStruct == type_instr->opcode()) {
  736. if (hasDecoration(type_id, SpvDecorationBlock, vstate))
  737. ++num_workgroup_variables_with_block;
  738. if (hasDecoration(var_instr->id(), SpvDecorationAliased, vstate))
  739. ++num_workgroup_variables_with_aliased;
  740. }
  741. }
  742. }
  743. if (num_builtin_inputs > 1 || num_builtin_outputs > 1) {
  744. return vstate.diag(SPV_ERROR_INVALID_BINARY,
  745. vstate.FindDef(entry_point))
  746. << "There must be at most one object per Storage Class that can "
  747. "contain a structure type containing members decorated with "
  748. "BuiltIn, consumed per entry-point. Entry Point id "
  749. << entry_point << " does not meet this requirement.";
  750. }
  751. // The LinkageAttributes Decoration cannot be applied to functions
  752. // targeted by an OpEntryPoint instruction
  753. for (auto& decoration : vstate.id_decorations(entry_point)) {
  754. if (SpvDecorationLinkageAttributes == decoration.dec_type()) {
  755. const char* linkage_name =
  756. reinterpret_cast<const char*>(&decoration.params()[0]);
  757. return vstate.diag(SPV_ERROR_INVALID_BINARY,
  758. vstate.FindDef(entry_point))
  759. << "The LinkageAttributes Decoration (Linkage name: "
  760. << linkage_name << ") cannot be applied to function id "
  761. << entry_point
  762. << " because it is targeted by an OpEntryPoint instruction.";
  763. }
  764. }
  765. if (vstate.HasCapability(SpvCapabilityWorkgroupMemoryExplicitLayoutKHR) &&
  766. num_workgroup_variables > 0 &&
  767. num_workgroup_variables_with_block > 0) {
  768. if (num_workgroup_variables != num_workgroup_variables_with_block) {
  769. return vstate.diag(SPV_ERROR_INVALID_BINARY, vstate.FindDef(entry_point))
  770. << "When declaring WorkgroupMemoryExplicitLayoutKHR, "
  771. "either all or none of the Workgroup Storage Class variables "
  772. "in the entry point interface must point to struct types "
  773. "decorated with Block. Entry point id "
  774. << entry_point << " does not meet this requirement.";
  775. }
  776. if (num_workgroup_variables_with_block > 1 &&
  777. num_workgroup_variables_with_block !=
  778. num_workgroup_variables_with_aliased) {
  779. return vstate.diag(SPV_ERROR_INVALID_BINARY, vstate.FindDef(entry_point))
  780. << "When declaring WorkgroupMemoryExplicitLayoutKHR, "
  781. "if more than one Workgroup Storage Class variable in "
  782. "the entry point interface point to a type decorated "
  783. "with Block, all of them must be decorated with Aliased. "
  784. "Entry point id "
  785. << entry_point << " does not meet this requirement.";
  786. }
  787. }
  788. }
  789. }
  790. return SPV_SUCCESS;
  791. }
  792. // Load |constraints| with all the member constraints for structs contained
  793. // within the given array type.
  794. void ComputeMemberConstraintsForArray(MemberConstraints* constraints,
  795. uint32_t array_id,
  796. const LayoutConstraints& inherited,
  797. ValidationState_t& vstate);
  798. // Load |constraints| with all the member constraints for the given struct,
  799. // and all its contained structs.
  800. void ComputeMemberConstraintsForStruct(MemberConstraints* constraints,
  801. uint32_t struct_id,
  802. const LayoutConstraints& inherited,
  803. ValidationState_t& vstate) {
  804. assert(constraints);
  805. const auto& members = getStructMembers(struct_id, vstate);
  806. for (uint32_t memberIdx = 0, numMembers = uint32_t(members.size());
  807. memberIdx < numMembers; memberIdx++) {
  808. LayoutConstraints& constraint =
  809. (*constraints)[std::make_pair(struct_id, memberIdx)];
  810. constraint = inherited;
  811. for (auto& decoration : vstate.id_decorations(struct_id)) {
  812. if (decoration.struct_member_index() == (int)memberIdx) {
  813. switch (decoration.dec_type()) {
  814. case SpvDecorationRowMajor:
  815. constraint.majorness = kRowMajor;
  816. break;
  817. case SpvDecorationColMajor:
  818. constraint.majorness = kColumnMajor;
  819. break;
  820. case SpvDecorationMatrixStride:
  821. constraint.matrix_stride = decoration.params()[0];
  822. break;
  823. default:
  824. break;
  825. }
  826. }
  827. }
  828. // Now recurse
  829. auto member_type_id = members[memberIdx];
  830. const auto member_type_inst = vstate.FindDef(member_type_id);
  831. const auto opcode = member_type_inst->opcode();
  832. switch (opcode) {
  833. case SpvOpTypeArray:
  834. case SpvOpTypeRuntimeArray:
  835. ComputeMemberConstraintsForArray(constraints, member_type_id, inherited,
  836. vstate);
  837. break;
  838. case SpvOpTypeStruct:
  839. ComputeMemberConstraintsForStruct(constraints, member_type_id,
  840. inherited, vstate);
  841. break;
  842. default:
  843. break;
  844. }
  845. }
  846. }
  847. void ComputeMemberConstraintsForArray(MemberConstraints* constraints,
  848. uint32_t array_id,
  849. const LayoutConstraints& inherited,
  850. ValidationState_t& vstate) {
  851. assert(constraints);
  852. auto elem_type_id = vstate.FindDef(array_id)->words()[2];
  853. const auto elem_type_inst = vstate.FindDef(elem_type_id);
  854. const auto opcode = elem_type_inst->opcode();
  855. switch (opcode) {
  856. case SpvOpTypeArray:
  857. case SpvOpTypeRuntimeArray:
  858. ComputeMemberConstraintsForArray(constraints, elem_type_id, inherited,
  859. vstate);
  860. break;
  861. case SpvOpTypeStruct:
  862. ComputeMemberConstraintsForStruct(constraints, elem_type_id, inherited,
  863. vstate);
  864. break;
  865. default:
  866. break;
  867. }
  868. }
  869. spv_result_t CheckDecorationsOfBuffers(ValidationState_t& vstate) {
  870. // Set of entry points that are known to use a push constant.
  871. std::unordered_set<uint32_t> uses_push_constant;
  872. for (const auto& inst : vstate.ordered_instructions()) {
  873. const auto& words = inst.words();
  874. if (SpvOpVariable == inst.opcode()) {
  875. const auto var_id = inst.id();
  876. // For storage class / decoration combinations, see Vulkan 14.5.4 "Offset
  877. // and Stride Assignment".
  878. const auto storageClass = words[3];
  879. const bool uniform = storageClass == SpvStorageClassUniform;
  880. const bool uniform_constant =
  881. storageClass == SpvStorageClassUniformConstant;
  882. const bool push_constant = storageClass == SpvStorageClassPushConstant;
  883. const bool storage_buffer = storageClass == SpvStorageClassStorageBuffer;
  884. if (spvIsVulkanEnv(vstate.context()->target_env)) {
  885. // Vulkan 14.5.1: There must be no more than one PushConstant block
  886. // per entry point.
  887. if (push_constant) {
  888. auto entry_points = vstate.EntryPointReferences(var_id);
  889. for (auto ep_id : entry_points) {
  890. const bool already_used = !uses_push_constant.insert(ep_id).second;
  891. if (already_used) {
  892. return vstate.diag(SPV_ERROR_INVALID_ID, vstate.FindDef(var_id))
  893. << "Entry point id '" << ep_id
  894. << "' uses more than one PushConstant interface.\n"
  895. << "From Vulkan spec, section 14.5.1:\n"
  896. << "There must be no more than one push constant block "
  897. << "statically used per shader entry point.";
  898. }
  899. }
  900. }
  901. // Vulkan 14.5.2: Check DescriptorSet and Binding decoration for
  902. // UniformConstant which cannot be a struct.
  903. if (uniform_constant) {
  904. auto entry_points = vstate.EntryPointReferences(var_id);
  905. if (!entry_points.empty() &&
  906. !hasDecoration(var_id, SpvDecorationDescriptorSet, vstate)) {
  907. return vstate.diag(SPV_ERROR_INVALID_ID, vstate.FindDef(var_id))
  908. << "UniformConstant id '" << var_id
  909. << "' is missing DescriptorSet decoration.\n"
  910. << "From Vulkan spec, section 14.5.2:\n"
  911. << "These variables must have DescriptorSet and Binding "
  912. "decorations specified";
  913. }
  914. if (!entry_points.empty() &&
  915. !hasDecoration(var_id, SpvDecorationBinding, vstate)) {
  916. return vstate.diag(SPV_ERROR_INVALID_ID, vstate.FindDef(var_id))
  917. << "UniformConstant id '" << var_id
  918. << "' is missing Binding decoration.\n"
  919. << "From Vulkan spec, section 14.5.2:\n"
  920. << "These variables must have DescriptorSet and Binding "
  921. "decorations specified";
  922. }
  923. }
  924. }
  925. if (spvIsOpenGLEnv(vstate.context()->target_env)) {
  926. bool has_block = hasDecoration(var_id, SpvDecorationBlock, vstate);
  927. bool has_buffer_block =
  928. hasDecoration(var_id, SpvDecorationBufferBlock, vstate);
  929. if ((uniform && (has_block || has_buffer_block)) ||
  930. (storage_buffer && has_block)) {
  931. auto entry_points = vstate.EntryPointReferences(var_id);
  932. if (!entry_points.empty() &&
  933. !hasDecoration(var_id, SpvDecorationBinding, vstate)) {
  934. return vstate.diag(SPV_ERROR_INVALID_ID, vstate.FindDef(var_id))
  935. << (uniform ? "Uniform" : "Storage Buffer") << " id '"
  936. << var_id << "' is missing Binding decoration.\n"
  937. << "From ARB_gl_spirv extension:\n"
  938. << "Uniform and shader storage block variables must "
  939. << "also be decorated with a *Binding*.";
  940. }
  941. }
  942. }
  943. const bool phys_storage_buffer =
  944. storageClass == SpvStorageClassPhysicalStorageBufferEXT;
  945. const bool workgroup =
  946. storageClass == SpvStorageClassWorkgroup &&
  947. vstate.HasCapability(SpvCapabilityWorkgroupMemoryExplicitLayoutKHR);
  948. if (uniform || push_constant || storage_buffer || phys_storage_buffer ||
  949. workgroup) {
  950. const auto ptrInst = vstate.FindDef(words[1]);
  951. assert(SpvOpTypePointer == ptrInst->opcode());
  952. auto id = ptrInst->words()[3];
  953. auto id_inst = vstate.FindDef(id);
  954. // Jump through one level of arraying.
  955. if (!workgroup && (id_inst->opcode() == SpvOpTypeArray ||
  956. id_inst->opcode() == SpvOpTypeRuntimeArray)) {
  957. id = id_inst->GetOperandAs<uint32_t>(1u);
  958. id_inst = vstate.FindDef(id);
  959. }
  960. // Struct requirement is checked on variables so just move on here.
  961. if (SpvOpTypeStruct != id_inst->opcode()) continue;
  962. MemberConstraints constraints;
  963. ComputeMemberConstraintsForStruct(&constraints, id, LayoutConstraints(),
  964. vstate);
  965. // Prepare for messages
  966. const char* sc_str =
  967. uniform ? "Uniform"
  968. : (push_constant ? "PushConstant"
  969. : (workgroup ? "Workgroup"
  970. : "StorageBuffer"));
  971. if (spvIsVulkanEnv(vstate.context()->target_env)) {
  972. const bool block = hasDecoration(id, SpvDecorationBlock, vstate);
  973. const bool buffer_block =
  974. hasDecoration(id, SpvDecorationBufferBlock, vstate);
  975. if (storage_buffer && buffer_block) {
  976. return vstate.diag(SPV_ERROR_INVALID_ID, vstate.FindDef(var_id))
  977. << "Storage buffer id '" << var_id
  978. << " In Vulkan, BufferBlock is disallowed on variables in "
  979. "the StorageBuffer storage class";
  980. }
  981. // Vulkan 14.5.1/2: Check Block decoration for PushConstant, Uniform
  982. // and StorageBuffer variables. Uniform can also use BufferBlock.
  983. if (push_constant && !block) {
  984. return vstate.diag(SPV_ERROR_INVALID_ID, vstate.FindDef(id))
  985. << "PushConstant id '" << id
  986. << "' is missing Block decoration.\n"
  987. << "From Vulkan spec, section 14.5.1:\n"
  988. << "Such variables must be identified with a Block "
  989. "decoration";
  990. }
  991. if (storage_buffer && !block) {
  992. return vstate.diag(SPV_ERROR_INVALID_ID, vstate.FindDef(id))
  993. << "StorageBuffer id '" << id
  994. << "' is missing Block decoration.\n"
  995. << "From Vulkan spec, section 14.5.2:\n"
  996. << "Such variables must be identified with a Block "
  997. "decoration";
  998. }
  999. if (uniform && !block && !buffer_block) {
  1000. return vstate.diag(SPV_ERROR_INVALID_ID, vstate.FindDef(id))
  1001. << "Uniform id '" << id
  1002. << "' is missing Block or BufferBlock decoration.\n"
  1003. << "From Vulkan spec, section 14.5.2:\n"
  1004. << "Such variables must be identified with a Block or "
  1005. "BufferBlock decoration";
  1006. }
  1007. // Vulkan 14.5.2: Check DescriptorSet and Binding decoration for
  1008. // Uniform and StorageBuffer variables.
  1009. if (uniform || storage_buffer) {
  1010. auto entry_points = vstate.EntryPointReferences(var_id);
  1011. if (!entry_points.empty() &&
  1012. !hasDecoration(var_id, SpvDecorationDescriptorSet, vstate)) {
  1013. return vstate.diag(SPV_ERROR_INVALID_ID, vstate.FindDef(var_id))
  1014. << sc_str << " id '" << var_id
  1015. << "' is missing DescriptorSet decoration.\n"
  1016. << "From Vulkan spec, section 14.5.2:\n"
  1017. << "These variables must have DescriptorSet and Binding "
  1018. "decorations specified";
  1019. }
  1020. if (!entry_points.empty() &&
  1021. !hasDecoration(var_id, SpvDecorationBinding, vstate)) {
  1022. return vstate.diag(SPV_ERROR_INVALID_ID, vstate.FindDef(var_id))
  1023. << sc_str << " id '" << var_id
  1024. << "' is missing Binding decoration.\n"
  1025. << "From Vulkan spec, section 14.5.2:\n"
  1026. << "These variables must have DescriptorSet and Binding "
  1027. "decorations specified";
  1028. }
  1029. }
  1030. }
  1031. for (const auto& dec : vstate.id_decorations(id)) {
  1032. const bool blockDeco = SpvDecorationBlock == dec.dec_type();
  1033. const bool bufferDeco = SpvDecorationBufferBlock == dec.dec_type();
  1034. const bool blockRules = uniform && blockDeco;
  1035. const bool bufferRules =
  1036. (uniform && bufferDeco) ||
  1037. ((push_constant || storage_buffer ||
  1038. phys_storage_buffer || workgroup) && blockDeco);
  1039. if (uniform && blockDeco) {
  1040. vstate.RegisterPointerToUniformBlock(ptrInst->id());
  1041. vstate.RegisterStructForUniformBlock(id);
  1042. }
  1043. if ((uniform && bufferDeco) ||
  1044. ((storage_buffer || phys_storage_buffer) && blockDeco)) {
  1045. vstate.RegisterPointerToStorageBuffer(ptrInst->id());
  1046. vstate.RegisterStructForStorageBuffer(id);
  1047. }
  1048. if (blockRules || bufferRules) {
  1049. const char* deco_str = blockDeco ? "Block" : "BufferBlock";
  1050. spv_result_t recursive_status = SPV_SUCCESS;
  1051. const bool scalar_block_layout = workgroup ?
  1052. vstate.options()->workgroup_scalar_block_layout :
  1053. vstate.options()->scalar_block_layout;
  1054. if (isMissingOffsetInStruct(id, vstate)) {
  1055. return vstate.diag(SPV_ERROR_INVALID_ID, vstate.FindDef(id))
  1056. << "Structure id " << id << " decorated as " << deco_str
  1057. << " must be explicitly laid out with Offset "
  1058. "decorations.";
  1059. } else if (hasDecoration(id, SpvDecorationGLSLShared, vstate)) {
  1060. return vstate.diag(SPV_ERROR_INVALID_ID, vstate.FindDef(id))
  1061. << "Structure id " << id << " decorated as " << deco_str
  1062. << " must not use GLSLShared decoration.";
  1063. } else if (hasDecoration(id, SpvDecorationGLSLPacked, vstate)) {
  1064. return vstate.diag(SPV_ERROR_INVALID_ID, vstate.FindDef(id))
  1065. << "Structure id " << id << " decorated as " << deco_str
  1066. << " must not use GLSLPacked decoration.";
  1067. } else if (!checkForRequiredDecoration(id, SpvDecorationArrayStride,
  1068. SpvOpTypeArray, vstate)) {
  1069. return vstate.diag(SPV_ERROR_INVALID_ID, vstate.FindDef(id))
  1070. << "Structure id " << id << " decorated as " << deco_str
  1071. << " must be explicitly laid out with ArrayStride "
  1072. "decorations.";
  1073. } else if (!checkForRequiredDecoration(id,
  1074. SpvDecorationMatrixStride,
  1075. SpvOpTypeMatrix, vstate)) {
  1076. return vstate.diag(SPV_ERROR_INVALID_ID, vstate.FindDef(id))
  1077. << "Structure id " << id << " decorated as " << deco_str
  1078. << " must be explicitly laid out with MatrixStride "
  1079. "decorations.";
  1080. } else if (blockRules &&
  1081. (SPV_SUCCESS != (recursive_status = checkLayout(
  1082. id, sc_str, deco_str, true,
  1083. scalar_block_layout, 0,
  1084. constraints, vstate)))) {
  1085. return recursive_status;
  1086. } else if (bufferRules &&
  1087. (SPV_SUCCESS != (recursive_status = checkLayout(
  1088. id, sc_str, deco_str, false,
  1089. scalar_block_layout, 0,
  1090. constraints, vstate)))) {
  1091. return recursive_status;
  1092. }
  1093. }
  1094. }
  1095. }
  1096. }
  1097. }
  1098. return SPV_SUCCESS;
  1099. }
  1100. // Returns true if |decoration| cannot be applied to the same id more than once.
  1101. bool AtMostOncePerId(SpvDecoration decoration) {
  1102. return decoration == SpvDecorationArrayStride;
  1103. }
  1104. // Returns true if |decoration| cannot be applied to the same member more than
  1105. // once.
  1106. bool AtMostOncePerMember(SpvDecoration decoration) {
  1107. switch (decoration) {
  1108. case SpvDecorationOffset:
  1109. case SpvDecorationMatrixStride:
  1110. case SpvDecorationRowMajor:
  1111. case SpvDecorationColMajor:
  1112. return true;
  1113. default:
  1114. return false;
  1115. }
  1116. }
  1117. // Returns the string name for |decoration|.
  1118. const char* GetDecorationName(SpvDecoration decoration) {
  1119. switch (decoration) {
  1120. case SpvDecorationAliased:
  1121. return "Aliased";
  1122. case SpvDecorationRestrict:
  1123. return "Restrict";
  1124. case SpvDecorationArrayStride:
  1125. return "ArrayStride";
  1126. case SpvDecorationOffset:
  1127. return "Offset";
  1128. case SpvDecorationMatrixStride:
  1129. return "MatrixStride";
  1130. case SpvDecorationRowMajor:
  1131. return "RowMajor";
  1132. case SpvDecorationColMajor:
  1133. return "ColMajor";
  1134. case SpvDecorationBlock:
  1135. return "Block";
  1136. case SpvDecorationBufferBlock:
  1137. return "BufferBlock";
  1138. default:
  1139. return "";
  1140. }
  1141. }
  1142. spv_result_t CheckDecorationsCompatibility(ValidationState_t& vstate) {
  1143. using PerIDKey = std::tuple<SpvDecoration, uint32_t>;
  1144. using PerMemberKey = std::tuple<SpvDecoration, uint32_t, uint32_t>;
  1145. // An Array of pairs where the decorations in the pair cannot both be applied
  1146. // to the same id.
  1147. static const SpvDecoration mutually_exclusive_per_id[][2] = {
  1148. {SpvDecorationBlock, SpvDecorationBufferBlock},
  1149. {SpvDecorationRestrict, SpvDecorationAliased}};
  1150. static const auto num_mutually_exclusive_per_id_pairs =
  1151. sizeof(mutually_exclusive_per_id) / (2 * sizeof(SpvDecoration));
  1152. // An Array of pairs where the decorations in the pair cannot both be applied
  1153. // to the same member.
  1154. static const SpvDecoration mutually_exclusive_per_member[][2] = {
  1155. {SpvDecorationRowMajor, SpvDecorationColMajor}};
  1156. static const auto num_mutually_exclusive_per_mem_pairs =
  1157. sizeof(mutually_exclusive_per_member) / (2 * sizeof(SpvDecoration));
  1158. std::set<PerIDKey> seen_per_id;
  1159. std::set<PerMemberKey> seen_per_member;
  1160. for (const auto& inst : vstate.ordered_instructions()) {
  1161. const auto& words = inst.words();
  1162. if (SpvOpDecorate == inst.opcode()) {
  1163. const auto id = words[1];
  1164. const auto dec_type = static_cast<SpvDecoration>(words[2]);
  1165. const auto k = PerIDKey(dec_type, id);
  1166. const auto already_used = !seen_per_id.insert(k).second;
  1167. if (already_used && AtMostOncePerId(dec_type)) {
  1168. return vstate.diag(SPV_ERROR_INVALID_ID, vstate.FindDef(id))
  1169. << "ID '" << id << "' decorated with "
  1170. << GetDecorationName(dec_type)
  1171. << " multiple times is not allowed.";
  1172. }
  1173. // Verify certain mutually exclusive decorations are not both applied on
  1174. // an ID.
  1175. for (uint32_t pair_idx = 0;
  1176. pair_idx < num_mutually_exclusive_per_id_pairs; ++pair_idx) {
  1177. SpvDecoration excl_dec_type = SpvDecorationMax;
  1178. if (mutually_exclusive_per_id[pair_idx][0] == dec_type) {
  1179. excl_dec_type = mutually_exclusive_per_id[pair_idx][1];
  1180. } else if (mutually_exclusive_per_id[pair_idx][1] == dec_type) {
  1181. excl_dec_type = mutually_exclusive_per_id[pair_idx][0];
  1182. } else {
  1183. continue;
  1184. }
  1185. const auto excl_k = PerIDKey(excl_dec_type, id);
  1186. if (seen_per_id.find(excl_k) != seen_per_id.end()) {
  1187. return vstate.diag(SPV_ERROR_INVALID_ID, vstate.FindDef(id))
  1188. << "ID '" << id << "' decorated with both "
  1189. << GetDecorationName(dec_type) << " and "
  1190. << GetDecorationName(excl_dec_type) << " is not allowed.";
  1191. }
  1192. }
  1193. } else if (SpvOpMemberDecorate == inst.opcode()) {
  1194. const auto id = words[1];
  1195. const auto member_id = words[2];
  1196. const auto dec_type = static_cast<SpvDecoration>(words[3]);
  1197. const auto k = PerMemberKey(dec_type, id, member_id);
  1198. const auto already_used = !seen_per_member.insert(k).second;
  1199. if (already_used && AtMostOncePerMember(dec_type)) {
  1200. return vstate.diag(SPV_ERROR_INVALID_ID, vstate.FindDef(id))
  1201. << "ID '" << id << "', member '" << member_id
  1202. << "' decorated with " << GetDecorationName(dec_type)
  1203. << " multiple times is not allowed.";
  1204. }
  1205. // Verify certain mutually exclusive decorations are not both applied on
  1206. // a (ID, member) tuple.
  1207. for (uint32_t pair_idx = 0;
  1208. pair_idx < num_mutually_exclusive_per_mem_pairs; ++pair_idx) {
  1209. SpvDecoration excl_dec_type = SpvDecorationMax;
  1210. if (mutually_exclusive_per_member[pair_idx][0] == dec_type) {
  1211. excl_dec_type = mutually_exclusive_per_member[pair_idx][1];
  1212. } else if (mutually_exclusive_per_member[pair_idx][1] == dec_type) {
  1213. excl_dec_type = mutually_exclusive_per_member[pair_idx][0];
  1214. } else {
  1215. continue;
  1216. }
  1217. const auto excl_k = PerMemberKey(excl_dec_type, id, member_id);
  1218. if (seen_per_member.find(excl_k) != seen_per_member.end()) {
  1219. return vstate.diag(SPV_ERROR_INVALID_ID, vstate.FindDef(id))
  1220. << "ID '" << id << "', member '" << member_id
  1221. << "' decorated with both " << GetDecorationName(dec_type)
  1222. << " and " << GetDecorationName(excl_dec_type)
  1223. << " is not allowed.";
  1224. }
  1225. }
  1226. }
  1227. }
  1228. return SPV_SUCCESS;
  1229. }
  1230. spv_result_t CheckVulkanMemoryModelDeprecatedDecorations(
  1231. ValidationState_t& vstate) {
  1232. if (vstate.memory_model() != SpvMemoryModelVulkanKHR) return SPV_SUCCESS;
  1233. std::string msg;
  1234. std::ostringstream str(msg);
  1235. for (const auto& def : vstate.all_definitions()) {
  1236. const auto inst = def.second;
  1237. const auto id = inst->id();
  1238. for (const auto& dec : vstate.id_decorations(id)) {
  1239. const auto member = dec.struct_member_index();
  1240. if (dec.dec_type() == SpvDecorationCoherent ||
  1241. dec.dec_type() == SpvDecorationVolatile) {
  1242. str << (dec.dec_type() == SpvDecorationCoherent ? "Coherent"
  1243. : "Volatile");
  1244. str << " decoration targeting " << vstate.getIdName(id);
  1245. if (member != Decoration::kInvalidMember) {
  1246. str << " (member index " << member << ")";
  1247. }
  1248. str << " is banned when using the Vulkan memory model.";
  1249. return vstate.diag(SPV_ERROR_INVALID_ID, inst) << str.str();
  1250. }
  1251. }
  1252. }
  1253. return SPV_SUCCESS;
  1254. }
  1255. // Returns SPV_SUCCESS if validation rules are satisfied for FPRoundingMode
  1256. // decorations. Otherwise emits a diagnostic and returns something other than
  1257. // SPV_SUCCESS.
  1258. spv_result_t CheckFPRoundingModeForShaders(ValidationState_t& vstate,
  1259. const Instruction& inst,
  1260. const Decoration& decoration) {
  1261. // Validates width-only conversion instruction for floating-point object
  1262. // i.e., OpFConvert
  1263. if (inst.opcode() != SpvOpFConvert) {
  1264. return vstate.diag(SPV_ERROR_INVALID_ID, &inst)
  1265. << "FPRoundingMode decoration can be applied only to a "
  1266. "width-only conversion instruction for floating-point "
  1267. "object.";
  1268. }
  1269. if (spvIsVulkanEnv(vstate.context()->target_env)) {
  1270. const auto mode = decoration.params()[0];
  1271. if ((mode != SpvFPRoundingModeRTE) && (mode != SpvFPRoundingModeRTZ)) {
  1272. return vstate.diag(SPV_ERROR_INVALID_ID, &inst)
  1273. << vstate.VkErrorID(4675)
  1274. << "In Vulkan, the FPRoundingMode mode must only by RTE or RTZ.";
  1275. }
  1276. }
  1277. // Validates Object operand of an OpStore
  1278. for (const auto& use : inst.uses()) {
  1279. const auto store = use.first;
  1280. if (store->opcode() == SpvOpFConvert) continue;
  1281. if (spvOpcodeIsDebug(store->opcode())) continue;
  1282. if (store->IsNonSemantic()) continue;
  1283. if (spvOpcodeIsDecoration(store->opcode())) continue;
  1284. if (store->opcode() != SpvOpStore) {
  1285. return vstate.diag(SPV_ERROR_INVALID_ID, &inst)
  1286. << "FPRoundingMode decoration can be applied only to the "
  1287. "Object operand of an OpStore.";
  1288. }
  1289. if (use.second != 2) {
  1290. return vstate.diag(SPV_ERROR_INVALID_ID, &inst)
  1291. << "FPRoundingMode decoration can be applied only to the "
  1292. "Object operand of an OpStore.";
  1293. }
  1294. const auto ptr_inst = vstate.FindDef(store->GetOperandAs<uint32_t>(0));
  1295. const auto ptr_type = vstate.FindDef(ptr_inst->GetOperandAs<uint32_t>(0));
  1296. const auto half_float_id = ptr_type->GetOperandAs<uint32_t>(2);
  1297. if (!vstate.IsFloatScalarOrVectorType(half_float_id) ||
  1298. vstate.GetBitWidth(half_float_id) != 16) {
  1299. return vstate.diag(SPV_ERROR_INVALID_ID, &inst)
  1300. << "FPRoundingMode decoration can be applied only to the "
  1301. "Object operand of an OpStore storing through a pointer "
  1302. "to "
  1303. "a 16-bit floating-point scalar or vector object.";
  1304. }
  1305. // Validates storage class of the pointer to the OpStore
  1306. const auto storage = ptr_type->GetOperandAs<uint32_t>(1);
  1307. if (storage != SpvStorageClassStorageBuffer &&
  1308. storage != SpvStorageClassUniform &&
  1309. storage != SpvStorageClassPushConstant &&
  1310. storage != SpvStorageClassInput && storage != SpvStorageClassOutput &&
  1311. storage != SpvStorageClassPhysicalStorageBufferEXT) {
  1312. return vstate.diag(SPV_ERROR_INVALID_ID, &inst)
  1313. << "FPRoundingMode decoration can be applied only to the "
  1314. "Object operand of an OpStore in the StorageBuffer, "
  1315. "PhysicalStorageBufferEXT, Uniform, PushConstant, Input, or "
  1316. "Output Storage Classes.";
  1317. }
  1318. }
  1319. return SPV_SUCCESS;
  1320. }
  1321. // Returns SPV_SUCCESS if validation rules are satisfied for the NonWritable
  1322. // decoration. Otherwise emits a diagnostic and returns something other than
  1323. // SPV_SUCCESS. The |inst| parameter is the object being decorated. This must
  1324. // be called after TypePass and AnnotateCheckDecorationsOfBuffers are called.
  1325. spv_result_t CheckNonWritableDecoration(ValidationState_t& vstate,
  1326. const Instruction& inst,
  1327. const Decoration& decoration) {
  1328. assert(inst.id() && "Parser ensures the target of the decoration has an ID");
  1329. if (decoration.struct_member_index() == Decoration::kInvalidMember) {
  1330. // The target must be a memory object declaration.
  1331. // First, it must be a variable or function parameter.
  1332. const auto opcode = inst.opcode();
  1333. const auto type_id = inst.type_id();
  1334. if (opcode != SpvOpVariable && opcode != SpvOpFunctionParameter) {
  1335. return vstate.diag(SPV_ERROR_INVALID_ID, &inst)
  1336. << "Target of NonWritable decoration must be a memory object "
  1337. "declaration (a variable or a function parameter)";
  1338. }
  1339. const auto var_storage_class = opcode == SpvOpVariable
  1340. ? inst.GetOperandAs<SpvStorageClass>(2)
  1341. : SpvStorageClassMax;
  1342. if ((var_storage_class == SpvStorageClassFunction ||
  1343. var_storage_class == SpvStorageClassPrivate) &&
  1344. vstate.features().nonwritable_var_in_function_or_private) {
  1345. // New permitted feature in SPIR-V 1.4.
  1346. } else if (
  1347. // It may point to a UBO, SSBO, or storage image.
  1348. vstate.IsPointerToUniformBlock(type_id) ||
  1349. vstate.IsPointerToStorageBuffer(type_id) ||
  1350. vstate.IsPointerToStorageImage(type_id)) {
  1351. } else {
  1352. return vstate.diag(SPV_ERROR_INVALID_ID, &inst)
  1353. << "Target of NonWritable decoration is invalid: must point to a "
  1354. "storage image, uniform block, "
  1355. << (vstate.features().nonwritable_var_in_function_or_private
  1356. ? "storage buffer, or variable in Private or Function "
  1357. "storage class"
  1358. : "or storage buffer");
  1359. }
  1360. }
  1361. return SPV_SUCCESS;
  1362. }
  1363. // Returns SPV_SUCCESS if validation rules are satisfied for Uniform or
  1364. // UniformId decorations. Otherwise emits a diagnostic and returns something
  1365. // other than SPV_SUCCESS. Assumes each decoration on a group has been
  1366. // propagated down to the group members. The |inst| parameter is the object
  1367. // being decorated.
  1368. spv_result_t CheckUniformDecoration(ValidationState_t& vstate,
  1369. const Instruction& inst,
  1370. const Decoration& decoration) {
  1371. const char* const dec_name =
  1372. decoration.dec_type() == SpvDecorationUniform ? "Uniform" : "UniformId";
  1373. // Uniform or UniformId must decorate an "object"
  1374. // - has a result ID
  1375. // - is an instantiation of a non-void type. So it has a type ID, and that
  1376. // type is not void.
  1377. // We already know the result ID is non-zero.
  1378. if (inst.type_id() == 0) {
  1379. return vstate.diag(SPV_ERROR_INVALID_ID, &inst)
  1380. << dec_name << " decoration applied to a non-object";
  1381. }
  1382. if (Instruction* type_inst = vstate.FindDef(inst.type_id())) {
  1383. if (type_inst->opcode() == SpvOpTypeVoid) {
  1384. return vstate.diag(SPV_ERROR_INVALID_ID, &inst)
  1385. << dec_name << " decoration applied to a value with void type";
  1386. }
  1387. } else {
  1388. // We might never get here because this would have been rejected earlier in
  1389. // the flow.
  1390. return vstate.diag(SPV_ERROR_INVALID_ID, &inst)
  1391. << dec_name << " decoration applied to an object with invalid type";
  1392. }
  1393. // Use of Uniform with OpDecorate is checked elsewhere.
  1394. // Use of UniformId with OpDecorateId is checked elsewhere.
  1395. if (decoration.dec_type() == SpvDecorationUniformId) {
  1396. assert(decoration.params().size() == 1 &&
  1397. "Grammar ensures UniformId has one parameter");
  1398. // The scope id is an execution scope.
  1399. if (auto error =
  1400. ValidateExecutionScope(vstate, &inst, decoration.params()[0]))
  1401. return error;
  1402. }
  1403. return SPV_SUCCESS;
  1404. }
  1405. // Returns SPV_SUCCESS if validation rules are satisfied for NoSignedWrap or
  1406. // NoUnsignedWrap decorations. Otherwise emits a diagnostic and returns
  1407. // something other than SPV_SUCCESS. Assumes each decoration on a group has been
  1408. // propagated down to the group members.
  1409. spv_result_t CheckIntegerWrapDecoration(ValidationState_t& vstate,
  1410. const Instruction& inst,
  1411. const Decoration& decoration) {
  1412. switch (inst.opcode()) {
  1413. case SpvOpIAdd:
  1414. case SpvOpISub:
  1415. case SpvOpIMul:
  1416. case SpvOpShiftLeftLogical:
  1417. case SpvOpSNegate:
  1418. return SPV_SUCCESS;
  1419. case SpvOpExtInst:
  1420. // TODO(dneto): Only certain extended instructions allow these
  1421. // decorations. For now allow anything.
  1422. return SPV_SUCCESS;
  1423. default:
  1424. break;
  1425. }
  1426. return vstate.diag(SPV_ERROR_INVALID_ID, &inst)
  1427. << (decoration.dec_type() == SpvDecorationNoSignedWrap
  1428. ? "NoSignedWrap"
  1429. : "NoUnsignedWrap")
  1430. << " decoration may not be applied to "
  1431. << spvOpcodeString(inst.opcode());
  1432. }
  1433. // Returns SPV_SUCCESS if validation rules are satisfied for the Component
  1434. // decoration. Otherwise emits a diagnostic and returns something other than
  1435. // SPV_SUCCESS.
  1436. spv_result_t CheckComponentDecoration(ValidationState_t& vstate,
  1437. const Instruction& inst,
  1438. const Decoration& decoration) {
  1439. assert(inst.id() && "Parser ensures the target of the decoration has an ID");
  1440. uint32_t type_id;
  1441. if (decoration.struct_member_index() == Decoration::kInvalidMember) {
  1442. // The target must be a memory object declaration.
  1443. const auto opcode = inst.opcode();
  1444. if (opcode != SpvOpVariable && opcode != SpvOpFunctionParameter) {
  1445. return vstate.diag(SPV_ERROR_INVALID_ID, &inst)
  1446. << "Target of Component decoration must be a memory object "
  1447. "declaration (a variable or a function parameter)";
  1448. }
  1449. // Only valid for the Input and Output Storage Classes.
  1450. const auto storage_class = opcode == SpvOpVariable
  1451. ? inst.GetOperandAs<SpvStorageClass>(2)
  1452. : SpvStorageClassMax;
  1453. if (storage_class != SpvStorageClassInput &&
  1454. storage_class != SpvStorageClassOutput &&
  1455. storage_class != SpvStorageClassMax) {
  1456. return vstate.diag(SPV_ERROR_INVALID_ID, &inst)
  1457. << "Target of Component decoration is invalid: must point to a "
  1458. "Storage Class of Input(1) or Output(3). Found Storage "
  1459. "Class "
  1460. << storage_class;
  1461. }
  1462. type_id = inst.type_id();
  1463. if (vstate.IsPointerType(type_id)) {
  1464. const auto pointer = vstate.FindDef(type_id);
  1465. type_id = pointer->GetOperandAs<uint32_t>(2);
  1466. }
  1467. } else {
  1468. if (inst.opcode() != SpvOpTypeStruct) {
  1469. return vstate.diag(SPV_ERROR_INVALID_DATA, &inst)
  1470. << "Attempted to get underlying data type via member index for "
  1471. "non-struct type.";
  1472. }
  1473. type_id = inst.word(decoration.struct_member_index() + 2);
  1474. }
  1475. if (spvIsVulkanEnv(vstate.context()->target_env)) {
  1476. // Strip the array, if present.
  1477. if (vstate.GetIdOpcode(type_id) == SpvOpTypeArray) {
  1478. type_id = vstate.FindDef(type_id)->word(2u);
  1479. }
  1480. if (!vstate.IsIntScalarOrVectorType(type_id) &&
  1481. !vstate.IsFloatScalarOrVectorType(type_id)) {
  1482. return vstate.diag(SPV_ERROR_INVALID_ID, &inst)
  1483. << "Component decoration specified for type "
  1484. << vstate.getIdName(type_id) << " that is not a scalar or vector";
  1485. }
  1486. // For 16-, and 32-bit types, it is invalid if this sequence of components
  1487. // gets larger than 3.
  1488. const auto bit_width = vstate.GetBitWidth(type_id);
  1489. if (bit_width == 16 || bit_width == 32) {
  1490. assert(decoration.params().size() == 1 &&
  1491. "Grammar ensures Component has one parameter");
  1492. const auto component = decoration.params()[0];
  1493. const auto last_component = component + vstate.GetDimension(type_id) - 1;
  1494. if (last_component > 3) {
  1495. return vstate.diag(SPV_ERROR_INVALID_ID, &inst)
  1496. << "Sequence of components starting with " << component
  1497. << " and ending with " << last_component
  1498. << " gets larger than 3";
  1499. }
  1500. }
  1501. }
  1502. return SPV_SUCCESS;
  1503. }
  1504. // Returns SPV_SUCCESS if validation rules are satisfied for the Block
  1505. // decoration. Otherwise emits a diagnostic and returns something other than
  1506. // SPV_SUCCESS.
  1507. spv_result_t CheckBlockDecoration(ValidationState_t& vstate,
  1508. const Instruction& inst,
  1509. const Decoration& decoration) {
  1510. assert(inst.id() && "Parser ensures the target of the decoration has an ID");
  1511. if (inst.opcode() != SpvOpTypeStruct) {
  1512. const char* const dec_name =
  1513. decoration.dec_type() == SpvDecorationBlock ? "Block" : "BufferBlock";
  1514. return vstate.diag(SPV_ERROR_INVALID_ID, &inst)
  1515. << dec_name << " decoration on a non-struct type.";
  1516. }
  1517. return SPV_SUCCESS;
  1518. }
  1519. spv_result_t CheckLocationDecoration(ValidationState_t& vstate,
  1520. const Instruction& inst,
  1521. const Decoration& decoration) {
  1522. if (inst.opcode() == SpvOpVariable) return SPV_SUCCESS;
  1523. if (decoration.struct_member_index() != Decoration::kInvalidMember &&
  1524. inst.opcode() == SpvOpTypeStruct) {
  1525. return SPV_SUCCESS;
  1526. }
  1527. return vstate.diag(SPV_ERROR_INVALID_ID, &inst)
  1528. << "Location decoration can only be applied to a variable or member "
  1529. "of a structure type";
  1530. }
  1531. #define PASS_OR_BAIL_AT_LINE(X, LINE) \
  1532. { \
  1533. spv_result_t e##LINE = (X); \
  1534. if (e##LINE != SPV_SUCCESS) return e##LINE; \
  1535. } static_assert(true, "require extra semicolon")
  1536. #define PASS_OR_BAIL(X) PASS_OR_BAIL_AT_LINE(X, __LINE__)
  1537. // Check rules for decorations where we start from the decoration rather
  1538. // than the decorated object. Assumes each decoration on a group have been
  1539. // propagated down to the group members.
  1540. spv_result_t CheckDecorationsFromDecoration(ValidationState_t& vstate) {
  1541. // Some rules are only checked for shaders.
  1542. const bool is_shader = vstate.HasCapability(SpvCapabilityShader);
  1543. for (const auto& kv : vstate.id_decorations()) {
  1544. const uint32_t id = kv.first;
  1545. const auto& decorations = kv.second;
  1546. if (decorations.empty()) continue;
  1547. const Instruction* inst = vstate.FindDef(id);
  1548. assert(inst);
  1549. // We assume the decorations applied to a decoration group have already
  1550. // been propagated down to the group members.
  1551. if (inst->opcode() == SpvOpDecorationGroup) continue;
  1552. for (const auto& decoration : decorations) {
  1553. switch (decoration.dec_type()) {
  1554. case SpvDecorationComponent:
  1555. PASS_OR_BAIL(CheckComponentDecoration(vstate, *inst, decoration));
  1556. break;
  1557. case SpvDecorationFPRoundingMode:
  1558. if (is_shader)
  1559. PASS_OR_BAIL(
  1560. CheckFPRoundingModeForShaders(vstate, *inst, decoration));
  1561. break;
  1562. case SpvDecorationNonWritable:
  1563. PASS_OR_BAIL(CheckNonWritableDecoration(vstate, *inst, decoration));
  1564. break;
  1565. case SpvDecorationUniform:
  1566. case SpvDecorationUniformId:
  1567. PASS_OR_BAIL(CheckUniformDecoration(vstate, *inst, decoration));
  1568. break;
  1569. case SpvDecorationNoSignedWrap:
  1570. case SpvDecorationNoUnsignedWrap:
  1571. PASS_OR_BAIL(CheckIntegerWrapDecoration(vstate, *inst, decoration));
  1572. break;
  1573. case SpvDecorationBlock:
  1574. case SpvDecorationBufferBlock:
  1575. PASS_OR_BAIL(CheckBlockDecoration(vstate, *inst, decoration));
  1576. break;
  1577. case SpvDecorationLocation:
  1578. PASS_OR_BAIL(CheckLocationDecoration(vstate, *inst, decoration));
  1579. break;
  1580. default:
  1581. break;
  1582. }
  1583. }
  1584. }
  1585. return SPV_SUCCESS;
  1586. }
  1587. } // namespace
  1588. spv_result_t ValidateDecorations(ValidationState_t& vstate) {
  1589. if (auto error = CheckImportedVariableInitialization(vstate)) return error;
  1590. if (auto error = CheckDecorationsOfEntryPoints(vstate)) return error;
  1591. if (auto error = CheckDecorationsOfBuffers(vstate)) return error;
  1592. if (auto error = CheckDecorationsCompatibility(vstate)) return error;
  1593. if (auto error = CheckLinkageAttrOfFunctions(vstate)) return error;
  1594. if (auto error = CheckVulkanMemoryModelDeprecatedDecorations(vstate))
  1595. return error;
  1596. if (auto error = CheckDecorationsFromDecoration(vstate)) return error;
  1597. return SPV_SUCCESS;
  1598. }
  1599. } // namespace val
  1600. } // namespace spvtools