1 // Copyright (c) 2018 Google LLC.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 #include "source/opcode.h"
16 #include "source/spirv_target_env.h"
17 #include "source/val/instruction.h"
18 #include "source/val/validate.h"
19 #include "source/val/validation_state.h"
20
21 namespace spvtools {
22 namespace val {
23 namespace {
24
25 // Returns true if the decoration takes ID parameters.
26 // TODO(dneto): This can be generated from the grammar.
DecorationTakesIdParameters(spv::Decoration type)27 bool DecorationTakesIdParameters(spv::Decoration type) {
28 switch (type) {
29 case spv::Decoration::UniformId:
30 case spv::Decoration::AlignmentId:
31 case spv::Decoration::MaxByteOffsetId:
32 case spv::Decoration::HlslCounterBufferGOOGLE:
33 return true;
34 default:
35 break;
36 }
37 return false;
38 }
39
IsMemberDecorationOnly(spv::Decoration dec)40 bool IsMemberDecorationOnly(spv::Decoration dec) {
41 switch (dec) {
42 case spv::Decoration::RowMajor:
43 case spv::Decoration::ColMajor:
44 case spv::Decoration::MatrixStride:
45 // SPIR-V spec bug? Offset is generated on variables when dealing with
46 // transform feedback.
47 // case spv::Decoration::Offset:
48 return true;
49 default:
50 break;
51 }
52 return false;
53 }
54
IsNotMemberDecoration(spv::Decoration dec)55 bool IsNotMemberDecoration(spv::Decoration dec) {
56 switch (dec) {
57 case spv::Decoration::SpecId:
58 case spv::Decoration::Block:
59 case spv::Decoration::BufferBlock:
60 case spv::Decoration::ArrayStride:
61 case spv::Decoration::GLSLShared:
62 case spv::Decoration::GLSLPacked:
63 case spv::Decoration::CPacked:
64 // TODO: https://github.com/KhronosGroup/glslang/issues/703:
65 // glslang applies Restrict to structure members.
66 // case spv::Decoration::Restrict:
67 case spv::Decoration::Aliased:
68 case spv::Decoration::Constant:
69 case spv::Decoration::Uniform:
70 case spv::Decoration::UniformId:
71 case spv::Decoration::SaturatedConversion:
72 case spv::Decoration::Index:
73 case spv::Decoration::Binding:
74 case spv::Decoration::DescriptorSet:
75 case spv::Decoration::FuncParamAttr:
76 case spv::Decoration::FPRoundingMode:
77 case spv::Decoration::FPFastMathMode:
78 case spv::Decoration::LinkageAttributes:
79 case spv::Decoration::NoContraction:
80 case spv::Decoration::InputAttachmentIndex:
81 case spv::Decoration::Alignment:
82 case spv::Decoration::MaxByteOffset:
83 case spv::Decoration::AlignmentId:
84 case spv::Decoration::MaxByteOffsetId:
85 case spv::Decoration::NoSignedWrap:
86 case spv::Decoration::NoUnsignedWrap:
87 case spv::Decoration::NonUniform:
88 case spv::Decoration::RestrictPointer:
89 case spv::Decoration::AliasedPointer:
90 case spv::Decoration::CounterBuffer:
91 return true;
92 default:
93 break;
94 }
95 return false;
96 }
97
ValidateDecorationTarget(ValidationState_t & _,spv::Decoration dec,const Instruction * inst,const Instruction * target)98 spv_result_t ValidateDecorationTarget(ValidationState_t& _, spv::Decoration dec,
99 const Instruction* inst,
100 const Instruction* target) {
101 auto fail = [&_, dec, inst, target](uint32_t vuid) -> DiagnosticStream {
102 DiagnosticStream ds = std::move(
103 _.diag(SPV_ERROR_INVALID_ID, inst)
104 << _.VkErrorID(vuid) << _.SpvDecorationString(dec)
105 << " decoration on target <id> " << _.getIdName(target->id()) << " ");
106 return ds;
107 };
108 switch (dec) {
109 case spv::Decoration::SpecId:
110 if (!spvOpcodeIsScalarSpecConstant(target->opcode())) {
111 return fail(0) << "must be a scalar specialization constant";
112 }
113 break;
114 case spv::Decoration::Block:
115 case spv::Decoration::BufferBlock:
116 case spv::Decoration::GLSLShared:
117 case spv::Decoration::GLSLPacked:
118 case spv::Decoration::CPacked:
119 if (target->opcode() != spv::Op::OpTypeStruct) {
120 return fail(0) << "must be a structure type";
121 }
122 break;
123 case spv::Decoration::ArrayStride:
124 if (target->opcode() != spv::Op::OpTypeArray &&
125 target->opcode() != spv::Op::OpTypeRuntimeArray &&
126 target->opcode() != spv::Op::OpTypePointer) {
127 return fail(0) << "must be an array or pointer type";
128 }
129 break;
130 case spv::Decoration::BuiltIn:
131 if (target->opcode() != spv::Op::OpVariable &&
132 !spvOpcodeIsConstant(target->opcode())) {
133 return _.diag(SPV_ERROR_INVALID_DATA, inst)
134 << "BuiltIns can only target variables, structure members or "
135 "constants";
136 }
137 if (_.HasCapability(spv::Capability::Shader) &&
138 inst->GetOperandAs<spv::BuiltIn>(2) == spv::BuiltIn::WorkgroupSize) {
139 if (!spvOpcodeIsConstant(target->opcode())) {
140 return fail(0) << "must be a constant for WorkgroupSize";
141 }
142 } else if (target->opcode() != spv::Op::OpVariable) {
143 return fail(0) << "must be a variable";
144 }
145 break;
146 case spv::Decoration::NoPerspective:
147 case spv::Decoration::Flat:
148 case spv::Decoration::Patch:
149 case spv::Decoration::Centroid:
150 case spv::Decoration::Sample:
151 case spv::Decoration::Restrict:
152 case spv::Decoration::Aliased:
153 case spv::Decoration::Volatile:
154 case spv::Decoration::Coherent:
155 case spv::Decoration::NonWritable:
156 case spv::Decoration::NonReadable:
157 case spv::Decoration::XfbBuffer:
158 case spv::Decoration::XfbStride:
159 case spv::Decoration::Component:
160 case spv::Decoration::Stream:
161 case spv::Decoration::RestrictPointer:
162 case spv::Decoration::AliasedPointer:
163 if (target->opcode() != spv::Op::OpVariable &&
164 target->opcode() != spv::Op::OpFunctionParameter) {
165 return fail(0) << "must be a memory object declaration";
166 }
167 if (_.GetIdOpcode(target->type_id()) != spv::Op::OpTypePointer) {
168 return fail(0) << "must be a pointer type";
169 }
170 break;
171 case spv::Decoration::Invariant:
172 case spv::Decoration::Constant:
173 case spv::Decoration::Location:
174 case spv::Decoration::Index:
175 case spv::Decoration::Binding:
176 case spv::Decoration::DescriptorSet:
177 case spv::Decoration::InputAttachmentIndex:
178 if (target->opcode() != spv::Op::OpVariable) {
179 return fail(0) << "must be a variable";
180 }
181 break;
182 default:
183 break;
184 }
185
186 if (spvIsVulkanEnv(_.context()->target_env)) {
187 // The following were all checked as pointer types above.
188 spv::StorageClass sc = spv::StorageClass::Uniform;
189 const auto type = _.FindDef(target->type_id());
190 if (type && type->operands().size() > 2) {
191 sc = type->GetOperandAs<spv::StorageClass>(1);
192 }
193 switch (dec) {
194 case spv::Decoration::Location:
195 case spv::Decoration::Component:
196 // Location is used for input, output, tile image, and ray tracing
197 // stages.
198 if (sc != spv::StorageClass::Input && sc != spv::StorageClass::Output &&
199 sc != spv::StorageClass::RayPayloadKHR &&
200 sc != spv::StorageClass::IncomingRayPayloadKHR &&
201 sc != spv::StorageClass::HitAttributeKHR &&
202 sc != spv::StorageClass::CallableDataKHR &&
203 sc != spv::StorageClass::IncomingCallableDataKHR &&
204 sc != spv::StorageClass::ShaderRecordBufferKHR &&
205 sc != spv::StorageClass::HitObjectAttributeNV &&
206 sc != spv::StorageClass::TileImageEXT) {
207 return _.diag(SPV_ERROR_INVALID_ID, target)
208 << _.VkErrorID(6672) << _.SpvDecorationString(dec)
209 << " decoration must not be applied to this storage class";
210 }
211 break;
212 case spv::Decoration::Index:
213 // Langauge from SPIR-V definition of Index
214 if (sc != spv::StorageClass::Output) {
215 return fail(0) << "must be in the Output storage class";
216 }
217 break;
218 case spv::Decoration::Binding:
219 case spv::Decoration::DescriptorSet:
220 if (sc != spv::StorageClass::StorageBuffer &&
221 sc != spv::StorageClass::Uniform &&
222 sc != spv::StorageClass::UniformConstant) {
223 return fail(6491) << "must be in the StorageBuffer, Uniform, or "
224 "UniformConstant storage class";
225 }
226 break;
227 case spv::Decoration::InputAttachmentIndex:
228 if (sc != spv::StorageClass::UniformConstant) {
229 return fail(6678) << "must be in the UniformConstant storage class";
230 }
231 break;
232 case spv::Decoration::Flat:
233 case spv::Decoration::NoPerspective:
234 case spv::Decoration::Centroid:
235 case spv::Decoration::Sample:
236 if (sc != spv::StorageClass::Input && sc != spv::StorageClass::Output) {
237 return fail(4670) << "storage class must be Input or Output";
238 }
239 break;
240 case spv::Decoration::PerVertexKHR:
241 if (sc != spv::StorageClass::Input) {
242 return fail(6777) << "storage class must be Input";
243 }
244 break;
245 default:
246 break;
247 }
248 }
249 return SPV_SUCCESS;
250 }
251
ValidateDecorate(ValidationState_t & _,const Instruction * inst)252 spv_result_t ValidateDecorate(ValidationState_t& _, const Instruction* inst) {
253 const auto decoration = inst->GetOperandAs<spv::Decoration>(1);
254 const auto target_id = inst->GetOperandAs<uint32_t>(0);
255 const auto target = _.FindDef(target_id);
256 if (!target) {
257 return _.diag(SPV_ERROR_INVALID_ID, inst) << "target is not defined";
258 }
259
260 if (spvIsVulkanEnv(_.context()->target_env)) {
261 if ((decoration == spv::Decoration::GLSLShared) ||
262 (decoration == spv::Decoration::GLSLPacked)) {
263 return _.diag(SPV_ERROR_INVALID_ID, inst)
264 << _.VkErrorID(4669) << "OpDecorate decoration '"
265 << _.SpvDecorationString(decoration)
266 << "' is not valid for the Vulkan execution environment.";
267 }
268 }
269
270 if (DecorationTakesIdParameters(decoration)) {
271 return _.diag(SPV_ERROR_INVALID_ID, inst)
272 << "Decorations taking ID parameters may not be used with "
273 "OpDecorateId";
274 }
275
276 if (target->opcode() != spv::Op::OpDecorationGroup) {
277 if (IsMemberDecorationOnly(decoration)) {
278 return _.diag(SPV_ERROR_INVALID_ID, inst)
279 << _.SpvDecorationString(decoration)
280 << " can only be applied to structure members";
281 }
282
283 if (auto error = ValidateDecorationTarget(_, decoration, inst, target)) {
284 return error;
285 }
286 }
287
288 // TODO: Add validations for all decorations.
289 return SPV_SUCCESS;
290 }
291
ValidateDecorateId(ValidationState_t & _,const Instruction * inst)292 spv_result_t ValidateDecorateId(ValidationState_t& _, const Instruction* inst) {
293 const auto decoration = inst->GetOperandAs<spv::Decoration>(1);
294 if (!DecorationTakesIdParameters(decoration)) {
295 return _.diag(SPV_ERROR_INVALID_ID, inst)
296 << "Decorations that don't take ID parameters may not be used with "
297 "OpDecorateId";
298 }
299
300 // No member decorations take id parameters, so we don't bother checking if
301 // we are using a member only decoration here.
302
303 // TODO: Add validations for these decorations.
304 // UniformId is covered elsewhere.
305 return SPV_SUCCESS;
306 }
307
ValidateMemberDecorate(ValidationState_t & _,const Instruction * inst)308 spv_result_t ValidateMemberDecorate(ValidationState_t& _,
309 const Instruction* inst) {
310 const auto struct_type_id = inst->GetOperandAs<uint32_t>(0);
311 const auto struct_type = _.FindDef(struct_type_id);
312 if (!struct_type || spv::Op::OpTypeStruct != struct_type->opcode()) {
313 return _.diag(SPV_ERROR_INVALID_ID, inst)
314 << "OpMemberDecorate Structure type <id> "
315 << _.getIdName(struct_type_id) << " is not a struct type.";
316 }
317 const auto member = inst->GetOperandAs<uint32_t>(1);
318 const auto member_count =
319 static_cast<uint32_t>(struct_type->words().size() - 2);
320 if (member_count <= member) {
321 return _.diag(SPV_ERROR_INVALID_ID, inst)
322 << "Index " << member
323 << " provided in OpMemberDecorate for struct <id> "
324 << _.getIdName(struct_type_id)
325 << " is out of bounds. The structure has " << member_count
326 << " members. Largest valid index is " << member_count - 1 << ".";
327 }
328
329 const auto decoration = inst->GetOperandAs<spv::Decoration>(2);
330 if (IsNotMemberDecoration(decoration)) {
331 return _.diag(SPV_ERROR_INVALID_ID, inst)
332 << _.SpvDecorationString(decoration)
333 << " cannot be applied to structure members";
334 }
335
336 return SPV_SUCCESS;
337 }
338
ValidateDecorationGroup(ValidationState_t & _,const Instruction * inst)339 spv_result_t ValidateDecorationGroup(ValidationState_t& _,
340 const Instruction* inst) {
341 const auto decoration_group_id = inst->GetOperandAs<uint32_t>(0);
342 const auto decoration_group = _.FindDef(decoration_group_id);
343 for (auto pair : decoration_group->uses()) {
344 auto use = pair.first;
345 if (use->opcode() != spv::Op::OpDecorate &&
346 use->opcode() != spv::Op::OpGroupDecorate &&
347 use->opcode() != spv::Op::OpGroupMemberDecorate &&
348 use->opcode() != spv::Op::OpName &&
349 use->opcode() != spv::Op::OpDecorateId && !use->IsNonSemantic()) {
350 return _.diag(SPV_ERROR_INVALID_ID, inst)
351 << "Result id of OpDecorationGroup can only "
352 << "be targeted by OpName, OpGroupDecorate, "
353 << "OpDecorate, OpDecorateId, and OpGroupMemberDecorate";
354 }
355 }
356 return SPV_SUCCESS;
357 }
358
ValidateGroupDecorate(ValidationState_t & _,const Instruction * inst)359 spv_result_t ValidateGroupDecorate(ValidationState_t& _,
360 const Instruction* inst) {
361 const auto decoration_group_id = inst->GetOperandAs<uint32_t>(0);
362 auto decoration_group = _.FindDef(decoration_group_id);
363 if (!decoration_group ||
364 spv::Op::OpDecorationGroup != decoration_group->opcode()) {
365 return _.diag(SPV_ERROR_INVALID_ID, inst)
366 << "OpGroupDecorate Decoration group <id> "
367 << _.getIdName(decoration_group_id) << " is not a decoration group.";
368 }
369 for (unsigned i = 1; i < inst->operands().size(); ++i) {
370 auto target_id = inst->GetOperandAs<uint32_t>(i);
371 auto target = _.FindDef(target_id);
372 if (!target || target->opcode() == spv::Op::OpDecorationGroup) {
373 return _.diag(SPV_ERROR_INVALID_ID, inst)
374 << "OpGroupDecorate may not target OpDecorationGroup <id> "
375 << _.getIdName(target_id);
376 }
377 }
378 return SPV_SUCCESS;
379 }
380
ValidateGroupMemberDecorate(ValidationState_t & _,const Instruction * inst)381 spv_result_t ValidateGroupMemberDecorate(ValidationState_t& _,
382 const Instruction* inst) {
383 const auto decoration_group_id = inst->GetOperandAs<uint32_t>(0);
384 const auto decoration_group = _.FindDef(decoration_group_id);
385 if (!decoration_group ||
386 spv::Op::OpDecorationGroup != decoration_group->opcode()) {
387 return _.diag(SPV_ERROR_INVALID_ID, inst)
388 << "OpGroupMemberDecorate Decoration group <id> "
389 << _.getIdName(decoration_group_id) << " is not a decoration group.";
390 }
391 // Grammar checks ensures that the number of arguments to this instruction
392 // is an odd number: 1 decoration group + (id,literal) pairs.
393 for (size_t i = 1; i + 1 < inst->operands().size(); i += 2) {
394 const uint32_t struct_id = inst->GetOperandAs<uint32_t>(i);
395 const uint32_t index = inst->GetOperandAs<uint32_t>(i + 1);
396 auto struct_instr = _.FindDef(struct_id);
397 if (!struct_instr || spv::Op::OpTypeStruct != struct_instr->opcode()) {
398 return _.diag(SPV_ERROR_INVALID_ID, inst)
399 << "OpGroupMemberDecorate Structure type <id> "
400 << _.getIdName(struct_id) << " is not a struct type.";
401 }
402 const uint32_t num_struct_members =
403 static_cast<uint32_t>(struct_instr->words().size() - 2);
404 if (index >= num_struct_members) {
405 return _.diag(SPV_ERROR_INVALID_ID, inst)
406 << "Index " << index
407 << " provided in OpGroupMemberDecorate for struct <id> "
408 << _.getIdName(struct_id)
409 << " is out of bounds. The structure has " << num_struct_members
410 << " members. Largest valid index is " << num_struct_members - 1
411 << ".";
412 }
413 }
414 return SPV_SUCCESS;
415 }
416
417 // Registers necessary decoration(s) for the appropriate IDs based on the
418 // instruction.
RegisterDecorations(ValidationState_t & _,const Instruction * inst)419 spv_result_t RegisterDecorations(ValidationState_t& _,
420 const Instruction* inst) {
421 switch (inst->opcode()) {
422 case spv::Op::OpDecorate:
423 case spv::Op::OpDecorateId: {
424 const uint32_t target_id = inst->word(1);
425 const spv::Decoration dec_type =
426 static_cast<spv::Decoration>(inst->word(2));
427 std::vector<uint32_t> dec_params;
428 if (inst->words().size() > 3) {
429 dec_params.insert(dec_params.end(), inst->words().begin() + 3,
430 inst->words().end());
431 }
432 _.RegisterDecorationForId(target_id, Decoration(dec_type, dec_params));
433 break;
434 }
435 case spv::Op::OpMemberDecorate: {
436 const uint32_t struct_id = inst->word(1);
437 const uint32_t index = inst->word(2);
438 const spv::Decoration dec_type =
439 static_cast<spv::Decoration>(inst->word(3));
440 std::vector<uint32_t> dec_params;
441 if (inst->words().size() > 4) {
442 dec_params.insert(dec_params.end(), inst->words().begin() + 4,
443 inst->words().end());
444 }
445 _.RegisterDecorationForId(struct_id,
446 Decoration(dec_type, dec_params, index));
447 break;
448 }
449 case spv::Op::OpDecorationGroup: {
450 // We don't need to do anything right now. Assigning decorations to groups
451 // will be taken care of via OpGroupDecorate.
452 break;
453 }
454 case spv::Op::OpGroupDecorate: {
455 // Word 1 is the group <id>. All subsequent words are target <id>s that
456 // are going to be decorated with the decorations.
457 const uint32_t decoration_group_id = inst->word(1);
458 std::set<Decoration>& group_decorations =
459 _.id_decorations(decoration_group_id);
460 for (size_t i = 2; i < inst->words().size(); ++i) {
461 const uint32_t target_id = inst->word(i);
462 _.RegisterDecorationsForId(target_id, group_decorations.begin(),
463 group_decorations.end());
464 }
465 break;
466 }
467 case spv::Op::OpGroupMemberDecorate: {
468 // Word 1 is the Decoration Group <id> followed by (struct<id>,literal)
469 // pairs. All decorations of the group should be applied to all the struct
470 // members that are specified in the instructions.
471 const uint32_t decoration_group_id = inst->word(1);
472 std::set<Decoration>& group_decorations =
473 _.id_decorations(decoration_group_id);
474 // Grammar checks ensures that the number of arguments to this instruction
475 // is an odd number: 1 decoration group + (id,literal) pairs.
476 for (size_t i = 2; i + 1 < inst->words().size(); i = i + 2) {
477 const uint32_t struct_id = inst->word(i);
478 const uint32_t index = inst->word(i + 1);
479 // ID validation phase ensures this is in fact a struct instruction and
480 // that the index is not out of bound.
481 _.RegisterDecorationsForStructMember(struct_id, index,
482 group_decorations.begin(),
483 group_decorations.end());
484 }
485 break;
486 }
487 default:
488 break;
489 }
490 return SPV_SUCCESS;
491 }
492
493 } // namespace
494
AnnotationPass(ValidationState_t & _,const Instruction * inst)495 spv_result_t AnnotationPass(ValidationState_t& _, const Instruction* inst) {
496 switch (inst->opcode()) {
497 case spv::Op::OpDecorate:
498 if (auto error = ValidateDecorate(_, inst)) return error;
499 break;
500 case spv::Op::OpDecorateId:
501 if (auto error = ValidateDecorateId(_, inst)) return error;
502 break;
503 // TODO(dneto): spv::Op::OpDecorateStringGOOGLE
504 // See https://github.com/KhronosGroup/SPIRV-Tools/issues/2253
505 case spv::Op::OpMemberDecorate:
506 if (auto error = ValidateMemberDecorate(_, inst)) return error;
507 break;
508 case spv::Op::OpDecorationGroup:
509 if (auto error = ValidateDecorationGroup(_, inst)) return error;
510 break;
511 case spv::Op::OpGroupDecorate:
512 if (auto error = ValidateGroupDecorate(_, inst)) return error;
513 break;
514 case spv::Op::OpGroupMemberDecorate:
515 if (auto error = ValidateGroupMemberDecorate(_, inst)) return error;
516 break;
517 default:
518 break;
519 }
520
521 // In order to validate decoration rules, we need to know all the decorations
522 // that are applied to any given <id>.
523 RegisterDecorations(_, inst);
524
525 return SPV_SUCCESS;
526 }
527
528 } // namespace val
529 } // namespace spvtools
530