1 // Copyright (c) 2015-2016 The Khronos Group 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
15 #include <algorithm>
16 #include <cassert>
17 #include <functional>
18 #include <iostream>
19 #include <iterator>
20 #include <map>
21 #include <string>
22 #include <tuple>
23 #include <unordered_map>
24 #include <unordered_set>
25 #include <utility>
26 #include <vector>
27
28 #include "source/cfa.h"
29 #include "source/opcode.h"
30 #include "source/spirv_constant.h"
31 #include "source/spirv_target_env.h"
32 #include "source/spirv_validator_options.h"
33 #include "source/val/basic_block.h"
34 #include "source/val/construct.h"
35 #include "source/val/function.h"
36 #include "source/val/validate.h"
37 #include "source/val/validation_state.h"
38
39 namespace spvtools {
40 namespace val {
41 namespace {
42
ValidatePhi(ValidationState_t & _,const Instruction * inst)43 spv_result_t ValidatePhi(ValidationState_t& _, const Instruction* inst) {
44 auto block = inst->block();
45 size_t num_in_ops = inst->words().size() - 3;
46 if (num_in_ops % 2 != 0) {
47 return _.diag(SPV_ERROR_INVALID_ID, inst)
48 << "OpPhi does not have an equal number of incoming values and "
49 "basic blocks.";
50 }
51
52 if (_.IsVoidType(inst->type_id())) {
53 return _.diag(SPV_ERROR_INVALID_DATA, inst)
54 << "OpPhi must not have void result type";
55 }
56 if (_.IsPointerType(inst->type_id()) &&
57 _.addressing_model() == SpvAddressingModelLogical) {
58 if (!_.features().variable_pointers) {
59 return _.diag(SPV_ERROR_INVALID_DATA, inst)
60 << "Using pointers with OpPhi requires capability "
61 << "VariablePointers or VariablePointersStorageBuffer";
62 }
63 }
64
65 const Instruction* type_inst = _.FindDef(inst->type_id());
66 assert(type_inst);
67 const SpvOp type_opcode = type_inst->opcode();
68
69 if (!_.options()->before_hlsl_legalization) {
70 if (type_opcode == SpvOpTypeSampledImage ||
71 (_.HasCapability(SpvCapabilityShader) &&
72 (type_opcode == SpvOpTypeImage || type_opcode == SpvOpTypeSampler))) {
73 return _.diag(SPV_ERROR_INVALID_ID, inst)
74 << "Result type cannot be Op" << spvOpcodeString(type_opcode);
75 }
76 }
77
78 // Create a uniqued vector of predecessor ids for comparison against
79 // incoming values. OpBranchConditional %cond %label %label produces two
80 // predecessors in the CFG.
81 std::vector<uint32_t> pred_ids;
82 std::transform(block->predecessors()->begin(), block->predecessors()->end(),
83 std::back_inserter(pred_ids),
84 [](const BasicBlock* b) { return b->id(); });
85 std::sort(pred_ids.begin(), pred_ids.end());
86 pred_ids.erase(std::unique(pred_ids.begin(), pred_ids.end()), pred_ids.end());
87
88 size_t num_edges = num_in_ops / 2;
89 if (num_edges != pred_ids.size()) {
90 return _.diag(SPV_ERROR_INVALID_ID, inst)
91 << "OpPhi's number of incoming blocks (" << num_edges
92 << ") does not match block's predecessor count ("
93 << block->predecessors()->size() << ").";
94 }
95
96 std::unordered_set<uint32_t> observed_predecessors;
97
98 for (size_t i = 3; i < inst->words().size(); ++i) {
99 auto inc_id = inst->word(i);
100 if (i % 2 == 1) {
101 // Incoming value type must match the phi result type.
102 auto inc_type_id = _.GetTypeId(inc_id);
103 if (inst->type_id() != inc_type_id) {
104 return _.diag(SPV_ERROR_INVALID_ID, inst)
105 << "OpPhi's result type <id> " << _.getIdName(inst->type_id())
106 << " does not match incoming value <id> " << _.getIdName(inc_id)
107 << " type <id> " << _.getIdName(inc_type_id) << ".";
108 }
109 } else {
110 if (_.GetIdOpcode(inc_id) != SpvOpLabel) {
111 return _.diag(SPV_ERROR_INVALID_ID, inst)
112 << "OpPhi's incoming basic block <id> " << _.getIdName(inc_id)
113 << " is not an OpLabel.";
114 }
115
116 // Incoming basic block must be an immediate predecessor of the phi's
117 // block.
118 if (!std::binary_search(pred_ids.begin(), pred_ids.end(), inc_id)) {
119 return _.diag(SPV_ERROR_INVALID_ID, inst)
120 << "OpPhi's incoming basic block <id> " << _.getIdName(inc_id)
121 << " is not a predecessor of <id> " << _.getIdName(block->id())
122 << ".";
123 }
124
125 // We must not have already seen this predecessor as one of the phi's
126 // operands.
127 if (observed_predecessors.count(inc_id) != 0) {
128 return _.diag(SPV_ERROR_INVALID_ID, inst)
129 << "OpPhi references incoming basic block <id> "
130 << _.getIdName(inc_id) << " multiple times.";
131 }
132
133 // Note the fact that we have now observed this predecessor.
134 observed_predecessors.insert(inc_id);
135 }
136 }
137
138 return SPV_SUCCESS;
139 }
140
ValidateBranch(ValidationState_t & _,const Instruction * inst)141 spv_result_t ValidateBranch(ValidationState_t& _, const Instruction* inst) {
142 // target operands must be OpLabel
143 const auto id = inst->GetOperandAs<uint32_t>(0);
144 const auto target = _.FindDef(id);
145 if (!target || SpvOpLabel != target->opcode()) {
146 return _.diag(SPV_ERROR_INVALID_ID, inst)
147 << "'Target Label' operands for OpBranch must be the ID "
148 "of an OpLabel instruction";
149 }
150
151 return SPV_SUCCESS;
152 }
153
ValidateBranchConditional(ValidationState_t & _,const Instruction * inst)154 spv_result_t ValidateBranchConditional(ValidationState_t& _,
155 const Instruction* inst) {
156 // num_operands is either 3 or 5 --- if 5, the last two need to be literal
157 // integers
158 const auto num_operands = inst->operands().size();
159 if (num_operands != 3 && num_operands != 5) {
160 return _.diag(SPV_ERROR_INVALID_ID, inst)
161 << "OpBranchConditional requires either 3 or 5 parameters";
162 }
163
164 // grab the condition operand and check that it is a bool
165 const auto cond_id = inst->GetOperandAs<uint32_t>(0);
166 const auto cond_op = _.FindDef(cond_id);
167 if (!cond_op || !cond_op->type_id() ||
168 !_.IsBoolScalarType(cond_op->type_id())) {
169 return _.diag(SPV_ERROR_INVALID_ID, inst) << "Condition operand for "
170 "OpBranchConditional must be "
171 "of boolean type";
172 }
173
174 // target operands must be OpLabel
175 // note that we don't need to check that the target labels are in the same
176 // function,
177 // PerformCfgChecks already checks for that
178 const auto true_id = inst->GetOperandAs<uint32_t>(1);
179 const auto true_target = _.FindDef(true_id);
180 if (!true_target || SpvOpLabel != true_target->opcode()) {
181 return _.diag(SPV_ERROR_INVALID_ID, inst)
182 << "The 'True Label' operand for OpBranchConditional must be the "
183 "ID of an OpLabel instruction";
184 }
185
186 const auto false_id = inst->GetOperandAs<uint32_t>(2);
187 const auto false_target = _.FindDef(false_id);
188 if (!false_target || SpvOpLabel != false_target->opcode()) {
189 return _.diag(SPV_ERROR_INVALID_ID, inst)
190 << "The 'False Label' operand for OpBranchConditional must be the "
191 "ID of an OpLabel instruction";
192 }
193
194 if (_.version() >= SPV_SPIRV_VERSION_WORD(1, 6) && true_id == false_id) {
195 return _.diag(SPV_ERROR_INVALID_ID, inst)
196 << "In SPIR-V 1.6 or later, True Label and False Label must be "
197 "different labels";
198 }
199
200 return SPV_SUCCESS;
201 }
202
ValidateSwitch(ValidationState_t & _,const Instruction * inst)203 spv_result_t ValidateSwitch(ValidationState_t& _, const Instruction* inst) {
204 const auto num_operands = inst->operands().size();
205 // At least two operands (selector, default), any more than that are
206 // literal/target.
207
208 const auto sel_type_id = _.GetOperandTypeId(inst, 0);
209 if (!_.IsIntScalarType(sel_type_id)) {
210 return _.diag(SPV_ERROR_INVALID_ID, inst)
211 << "Selector type must be OpTypeInt";
212 }
213
214 const auto default_label = _.FindDef(inst->GetOperandAs<uint32_t>(1));
215 if (default_label->opcode() != SpvOpLabel) {
216 return _.diag(SPV_ERROR_INVALID_ID, inst)
217 << "Default must be an OpLabel instruction";
218 }
219
220 // target operands must be OpLabel
221 for (size_t i = 2; i < num_operands; i += 2) {
222 // literal, id
223 const auto id = inst->GetOperandAs<uint32_t>(i + 1);
224 const auto target = _.FindDef(id);
225 if (!target || SpvOpLabel != target->opcode()) {
226 return _.diag(SPV_ERROR_INVALID_ID, inst)
227 << "'Target Label' operands for OpSwitch must be IDs of an "
228 "OpLabel instruction";
229 }
230 }
231
232 return SPV_SUCCESS;
233 }
234
ValidateReturnValue(ValidationState_t & _,const Instruction * inst)235 spv_result_t ValidateReturnValue(ValidationState_t& _,
236 const Instruction* inst) {
237 const auto value_id = inst->GetOperandAs<uint32_t>(0);
238 const auto value = _.FindDef(value_id);
239 if (!value || !value->type_id()) {
240 return _.diag(SPV_ERROR_INVALID_ID, inst)
241 << "OpReturnValue Value <id> '" << _.getIdName(value_id)
242 << "' does not represent a value.";
243 }
244 auto value_type = _.FindDef(value->type_id());
245 if (!value_type || SpvOpTypeVoid == value_type->opcode()) {
246 return _.diag(SPV_ERROR_INVALID_ID, inst)
247 << "OpReturnValue value's type <id> '"
248 << _.getIdName(value->type_id()) << "' is missing or void.";
249 }
250
251 if (_.addressing_model() == SpvAddressingModelLogical &&
252 SpvOpTypePointer == value_type->opcode() &&
253 !_.features().variable_pointers && !_.options()->relax_logical_pointer) {
254 return _.diag(SPV_ERROR_INVALID_ID, inst)
255 << "OpReturnValue value's type <id> '"
256 << _.getIdName(value->type_id())
257 << "' is a pointer, which is invalid in the Logical addressing "
258 "model.";
259 }
260
261 const auto function = inst->function();
262 const auto return_type = _.FindDef(function->GetResultTypeId());
263 if (!return_type || return_type->id() != value_type->id()) {
264 return _.diag(SPV_ERROR_INVALID_ID, inst)
265 << "OpReturnValue Value <id> '" << _.getIdName(value_id)
266 << "'s type does not match OpFunction's return type.";
267 }
268
269 return SPV_SUCCESS;
270 }
271
ValidateLoopMerge(ValidationState_t & _,const Instruction * inst)272 spv_result_t ValidateLoopMerge(ValidationState_t& _, const Instruction* inst) {
273 const auto merge_id = inst->GetOperandAs<uint32_t>(0);
274 const auto merge = _.FindDef(merge_id);
275 if (!merge || merge->opcode() != SpvOpLabel) {
276 return _.diag(SPV_ERROR_INVALID_ID, inst)
277 << "Merge Block " << _.getIdName(merge_id) << " must be an OpLabel";
278 }
279 if (merge_id == inst->block()->id()) {
280 return _.diag(SPV_ERROR_INVALID_ID, inst)
281 << "Merge Block may not be the block containing the OpLoopMerge\n";
282 }
283
284 const auto continue_id = inst->GetOperandAs<uint32_t>(1);
285 const auto continue_target = _.FindDef(continue_id);
286 if (!continue_target || continue_target->opcode() != SpvOpLabel) {
287 return _.diag(SPV_ERROR_INVALID_ID, inst)
288 << "Continue Target " << _.getIdName(continue_id)
289 << " must be an OpLabel";
290 }
291
292 if (merge_id == continue_id) {
293 return _.diag(SPV_ERROR_INVALID_ID, inst)
294 << "Merge Block and Continue Target must be different ids";
295 }
296
297 const auto loop_control = inst->GetOperandAs<uint32_t>(2);
298 if ((loop_control >> SpvLoopControlUnrollShift) & 0x1 &&
299 (loop_control >> SpvLoopControlDontUnrollShift) & 0x1) {
300 return _.diag(SPV_ERROR_INVALID_DATA, inst)
301 << "Unroll and DontUnroll loop controls must not both be specified";
302 }
303 if ((loop_control >> SpvLoopControlDontUnrollShift) & 0x1 &&
304 (loop_control >> SpvLoopControlPeelCountShift) & 0x1) {
305 return _.diag(SPV_ERROR_INVALID_DATA, inst) << "PeelCount and DontUnroll "
306 "loop controls must not "
307 "both be specified";
308 }
309 if ((loop_control >> SpvLoopControlDontUnrollShift) & 0x1 &&
310 (loop_control >> SpvLoopControlPartialCountShift) & 0x1) {
311 return _.diag(SPV_ERROR_INVALID_DATA, inst) << "PartialCount and "
312 "DontUnroll loop controls "
313 "must not both be specified";
314 }
315
316 uint32_t operand = 3;
317 if ((loop_control >> SpvLoopControlDependencyLengthShift) & 0x1) {
318 ++operand;
319 }
320 if ((loop_control >> SpvLoopControlMinIterationsShift) & 0x1) {
321 ++operand;
322 }
323 if ((loop_control >> SpvLoopControlMaxIterationsShift) & 0x1) {
324 ++operand;
325 }
326 if ((loop_control >> SpvLoopControlIterationMultipleShift) & 0x1) {
327 if (inst->operands().size() < operand ||
328 inst->GetOperandAs<uint32_t>(operand) == 0) {
329 return _.diag(SPV_ERROR_INVALID_DATA, inst) << "IterationMultiple loop "
330 "control operand must be "
331 "greater than zero";
332 }
333 ++operand;
334 }
335 if ((loop_control >> SpvLoopControlPeelCountShift) & 0x1) {
336 ++operand;
337 }
338 if ((loop_control >> SpvLoopControlPartialCountShift) & 0x1) {
339 ++operand;
340 }
341
342 // That the right number of operands is present is checked by the parser. The
343 // above code tracks operands for expanded validation checking in the future.
344
345 return SPV_SUCCESS;
346 }
347
348 } // namespace
349
printDominatorList(const BasicBlock & b)350 void printDominatorList(const BasicBlock& b) {
351 std::cout << b.id() << " is dominated by: ";
352 const BasicBlock* bb = &b;
353 while (bb->immediate_dominator() != bb) {
354 bb = bb->immediate_dominator();
355 std::cout << bb->id() << " ";
356 }
357 }
358
359 #define CFG_ASSERT(ASSERT_FUNC, TARGET) \
360 if (spv_result_t rcode = ASSERT_FUNC(_, TARGET)) return rcode
361
FirstBlockAssert(ValidationState_t & _,uint32_t target)362 spv_result_t FirstBlockAssert(ValidationState_t& _, uint32_t target) {
363 if (_.current_function().IsFirstBlock(target)) {
364 return _.diag(SPV_ERROR_INVALID_CFG, _.FindDef(_.current_function().id()))
365 << "First block " << _.getIdName(target) << " of function "
366 << _.getIdName(_.current_function().id()) << " is targeted by block "
367 << _.getIdName(_.current_function().current_block()->id());
368 }
369 return SPV_SUCCESS;
370 }
371
MergeBlockAssert(ValidationState_t & _,uint32_t merge_block)372 spv_result_t MergeBlockAssert(ValidationState_t& _, uint32_t merge_block) {
373 if (_.current_function().IsBlockType(merge_block, kBlockTypeMerge)) {
374 return _.diag(SPV_ERROR_INVALID_CFG, _.FindDef(_.current_function().id()))
375 << "Block " << _.getIdName(merge_block)
376 << " is already a merge block for another header";
377 }
378 return SPV_SUCCESS;
379 }
380
381 /// Update the continue construct's exit blocks once the backedge blocks are
382 /// identified in the CFG.
UpdateContinueConstructExitBlocks(Function & function,const std::vector<std::pair<uint32_t,uint32_t>> & back_edges)383 void UpdateContinueConstructExitBlocks(
384 Function& function,
385 const std::vector<std::pair<uint32_t, uint32_t>>& back_edges) {
386 auto& constructs = function.constructs();
387 // TODO(umar): Think of a faster way to do this
388 for (auto& edge : back_edges) {
389 uint32_t back_edge_block_id;
390 uint32_t loop_header_block_id;
391 std::tie(back_edge_block_id, loop_header_block_id) = edge;
392 auto is_this_header = [=](Construct& c) {
393 return c.type() == ConstructType::kLoop &&
394 c.entry_block()->id() == loop_header_block_id;
395 };
396
397 for (auto construct : constructs) {
398 if (is_this_header(construct)) {
399 Construct* continue_construct =
400 construct.corresponding_constructs().back();
401 assert(continue_construct->type() == ConstructType::kContinue);
402
403 BasicBlock* back_edge_block;
404 std::tie(back_edge_block, std::ignore) =
405 function.GetBlock(back_edge_block_id);
406 continue_construct->set_exit(back_edge_block);
407 }
408 }
409 }
410 }
411
ConstructNames(ConstructType type)412 std::tuple<std::string, std::string, std::string> ConstructNames(
413 ConstructType type) {
414 std::string construct_name, header_name, exit_name;
415
416 switch (type) {
417 case ConstructType::kSelection:
418 construct_name = "selection";
419 header_name = "selection header";
420 exit_name = "merge block";
421 break;
422 case ConstructType::kLoop:
423 construct_name = "loop";
424 header_name = "loop header";
425 exit_name = "merge block";
426 break;
427 case ConstructType::kContinue:
428 construct_name = "continue";
429 header_name = "continue target";
430 exit_name = "back-edge block";
431 break;
432 case ConstructType::kCase:
433 construct_name = "case";
434 header_name = "case entry block";
435 exit_name = "case exit block";
436 break;
437 default:
438 assert(1 == 0 && "Not defined type");
439 }
440
441 return std::make_tuple(construct_name, header_name, exit_name);
442 }
443
444 /// Constructs an error message for construct validation errors
ConstructErrorString(const Construct & construct,const std::string & header_string,const std::string & exit_string,const std::string & dominate_text)445 std::string ConstructErrorString(const Construct& construct,
446 const std::string& header_string,
447 const std::string& exit_string,
448 const std::string& dominate_text) {
449 std::string construct_name, header_name, exit_name;
450 std::tie(construct_name, header_name, exit_name) =
451 ConstructNames(construct.type());
452
453 // TODO(umar): Add header block for continue constructs to error message
454 return "The " + construct_name + " construct with the " + header_name + " " +
455 header_string + " " + dominate_text + " the " + exit_name + " " +
456 exit_string;
457 }
458
459 // Finds the fall through case construct of |target_block| and records it in
460 // |case_fall_through|. Returns SPV_ERROR_INVALID_CFG if the case construct
461 // headed by |target_block| branches to multiple case constructs.
FindCaseFallThrough(ValidationState_t & _,BasicBlock * target_block,uint32_t * case_fall_through,const BasicBlock * merge,const std::unordered_set<uint32_t> & case_targets,Function * function)462 spv_result_t FindCaseFallThrough(
463 ValidationState_t& _, BasicBlock* target_block, uint32_t* case_fall_through,
464 const BasicBlock* merge, const std::unordered_set<uint32_t>& case_targets,
465 Function* function) {
466 std::vector<BasicBlock*> stack;
467 stack.push_back(target_block);
468 std::unordered_set<const BasicBlock*> visited;
469 bool target_reachable = target_block->reachable();
470 int target_depth = function->GetBlockDepth(target_block);
471 while (!stack.empty()) {
472 auto block = stack.back();
473 stack.pop_back();
474
475 if (block == merge) continue;
476
477 if (!visited.insert(block).second) continue;
478
479 if (target_reachable && block->reachable() &&
480 target_block->dominates(*block)) {
481 // Still in the case construct.
482 for (auto successor : *block->successors()) {
483 stack.push_back(successor);
484 }
485 } else {
486 // Exiting the case construct to non-merge block.
487 if (!case_targets.count(block->id())) {
488 int depth = function->GetBlockDepth(block);
489 if ((depth < target_depth) ||
490 (depth == target_depth && block->is_type(kBlockTypeContinue))) {
491 continue;
492 }
493
494 return _.diag(SPV_ERROR_INVALID_CFG, target_block->label())
495 << "Case construct that targets "
496 << _.getIdName(target_block->id())
497 << " has invalid branch to block " << _.getIdName(block->id())
498 << " (not another case construct, corresponding merge, outer "
499 "loop merge or outer loop continue)";
500 }
501
502 if (*case_fall_through == 0u) {
503 if (target_block != block) {
504 *case_fall_through = block->id();
505 }
506 } else if (*case_fall_through != block->id()) {
507 // Case construct has at most one branch to another case construct.
508 return _.diag(SPV_ERROR_INVALID_CFG, target_block->label())
509 << "Case construct that targets "
510 << _.getIdName(target_block->id())
511 << " has branches to multiple other case construct targets "
512 << _.getIdName(*case_fall_through) << " and "
513 << _.getIdName(block->id());
514 }
515 }
516 }
517
518 return SPV_SUCCESS;
519 }
520
StructuredSwitchChecks(ValidationState_t & _,Function * function,const Instruction * switch_inst,const BasicBlock * header,const BasicBlock * merge)521 spv_result_t StructuredSwitchChecks(ValidationState_t& _, Function* function,
522 const Instruction* switch_inst,
523 const BasicBlock* header,
524 const BasicBlock* merge) {
525 std::unordered_set<uint32_t> case_targets;
526 for (uint32_t i = 1; i < switch_inst->operands().size(); i += 2) {
527 uint32_t target = switch_inst->GetOperandAs<uint32_t>(i);
528 if (target != merge->id()) case_targets.insert(target);
529 }
530 // Tracks how many times each case construct is targeted by another case
531 // construct.
532 std::map<uint32_t, uint32_t> num_fall_through_targeted;
533 uint32_t default_case_fall_through = 0u;
534 uint32_t default_target = switch_inst->GetOperandAs<uint32_t>(1u);
535 bool default_appears_multiple_times = false;
536 for (uint32_t i = 3; i < switch_inst->operands().size(); i += 2) {
537 if (default_target == switch_inst->GetOperandAs<uint32_t>(i)) {
538 default_appears_multiple_times = true;
539 break;
540 }
541 }
542 std::unordered_map<uint32_t, uint32_t> seen_to_fall_through;
543 for (uint32_t i = 1; i < switch_inst->operands().size(); i += 2) {
544 uint32_t target = switch_inst->GetOperandAs<uint32_t>(i);
545 if (target == merge->id()) continue;
546
547 uint32_t case_fall_through = 0u;
548 auto seen_iter = seen_to_fall_through.find(target);
549 if (seen_iter == seen_to_fall_through.end()) {
550 const auto target_block = function->GetBlock(target).first;
551 // OpSwitch must dominate all its case constructs.
552 if (header->reachable() && target_block->reachable() &&
553 !header->dominates(*target_block)) {
554 return _.diag(SPV_ERROR_INVALID_CFG, header->label())
555 << "Selection header " << _.getIdName(header->id())
556 << " does not dominate its case construct "
557 << _.getIdName(target);
558 }
559
560 if (auto error = FindCaseFallThrough(_, target_block, &case_fall_through,
561 merge, case_targets, function)) {
562 return error;
563 }
564
565 // Track how many time the fall through case has been targeted.
566 if (case_fall_through != 0u) {
567 auto where = num_fall_through_targeted.lower_bound(case_fall_through);
568 if (where == num_fall_through_targeted.end() ||
569 where->first != case_fall_through) {
570 num_fall_through_targeted.insert(
571 where, std::make_pair(case_fall_through, 1));
572 } else {
573 where->second++;
574 }
575 }
576 seen_to_fall_through.insert(std::make_pair(target, case_fall_through));
577 } else {
578 case_fall_through = seen_iter->second;
579 }
580
581 if (case_fall_through == default_target &&
582 !default_appears_multiple_times) {
583 case_fall_through = default_case_fall_through;
584 }
585 if (case_fall_through != 0u) {
586 bool is_default = i == 1;
587 if (is_default) {
588 default_case_fall_through = case_fall_through;
589 } else {
590 // Allow code like:
591 // case x:
592 // case y:
593 // ...
594 // case z:
595 //
596 // Where x and y target the same block and fall through to z.
597 uint32_t j = i;
598 while ((j + 2 < switch_inst->operands().size()) &&
599 target == switch_inst->GetOperandAs<uint32_t>(j + 2)) {
600 j += 2;
601 }
602 // If Target T1 branches to Target T2, or if Target T1 branches to the
603 // Default target and the Default target branches to Target T2, then T1
604 // must immediately precede T2 in the list of OpSwitch Target operands.
605 if ((switch_inst->operands().size() < j + 2) ||
606 (case_fall_through != switch_inst->GetOperandAs<uint32_t>(j + 2))) {
607 return _.diag(SPV_ERROR_INVALID_CFG, switch_inst)
608 << "Case construct that targets " << _.getIdName(target)
609 << " has branches to the case construct that targets "
610 << _.getIdName(case_fall_through)
611 << ", but does not immediately precede it in the "
612 "OpSwitch's target list";
613 }
614 }
615 }
616 }
617
618 // Each case construct must be branched to by at most one other case
619 // construct.
620 for (const auto& pair : num_fall_through_targeted) {
621 if (pair.second > 1) {
622 return _.diag(SPV_ERROR_INVALID_CFG, _.FindDef(pair.first))
623 << "Multiple case constructs have branches to the case construct "
624 "that targets "
625 << _.getIdName(pair.first);
626 }
627 }
628
629 return SPV_SUCCESS;
630 }
631
632 // Validates that all CFG divergences (i.e. conditional branch or switch) are
633 // structured correctly. Either divergence is preceded by a merge instruction
634 // or the divergence introduces at most one unseen label.
ValidateStructuredSelections(ValidationState_t & _,const std::vector<const BasicBlock * > & postorder)635 spv_result_t ValidateStructuredSelections(
636 ValidationState_t& _, const std::vector<const BasicBlock*>& postorder) {
637 std::unordered_set<uint32_t> seen;
638 for (auto iter = postorder.rbegin(); iter != postorder.rend(); ++iter) {
639 const auto* block = *iter;
640 const auto* terminator = block->terminator();
641 if (!terminator) continue;
642 const auto index = terminator - &_.ordered_instructions()[0];
643 auto* merge = &_.ordered_instructions()[index - 1];
644 // Marks merges and continues as seen.
645 if (merge->opcode() == SpvOpSelectionMerge) {
646 seen.insert(merge->GetOperandAs<uint32_t>(0));
647 } else if (merge->opcode() == SpvOpLoopMerge) {
648 seen.insert(merge->GetOperandAs<uint32_t>(0));
649 seen.insert(merge->GetOperandAs<uint32_t>(1));
650 } else {
651 // Only track the pointer if it is a merge instruction.
652 merge = nullptr;
653 }
654
655 // Skip unreachable blocks.
656 if (!block->reachable()) continue;
657
658 if (terminator->opcode() == SpvOpBranchConditional) {
659 const auto true_label = terminator->GetOperandAs<uint32_t>(1);
660 const auto false_label = terminator->GetOperandAs<uint32_t>(2);
661 // Mark the upcoming blocks as seen now, but only error out if this block
662 // was missing a merge instruction and both labels hadn't been seen
663 // previously.
664 const bool true_label_unseen = seen.insert(true_label).second;
665 const bool false_label_unseen = seen.insert(false_label).second;
666 if (!merge && true_label_unseen && false_label_unseen) {
667 return _.diag(SPV_ERROR_INVALID_CFG, terminator)
668 << "Selection must be structured";
669 }
670 } else if (terminator->opcode() == SpvOpSwitch) {
671 if (!merge) {
672 return _.diag(SPV_ERROR_INVALID_CFG, terminator)
673 << "OpSwitch must be preceded by an OpSelectionMerge "
674 "instruction";
675 }
676 // Mark the targets as seen.
677 for (uint32_t i = 1; i < terminator->operands().size(); i += 2) {
678 const auto target = terminator->GetOperandAs<uint32_t>(i);
679 seen.insert(target);
680 }
681 }
682 }
683
684 return SPV_SUCCESS;
685 }
686
StructuredControlFlowChecks(ValidationState_t & _,Function * function,const std::vector<std::pair<uint32_t,uint32_t>> & back_edges,const std::vector<const BasicBlock * > & postorder)687 spv_result_t StructuredControlFlowChecks(
688 ValidationState_t& _, Function* function,
689 const std::vector<std::pair<uint32_t, uint32_t>>& back_edges,
690 const std::vector<const BasicBlock*>& postorder) {
691 /// Check all backedges target only loop headers and have exactly one
692 /// back-edge branching to it
693
694 // Map a loop header to blocks with back-edges to the loop header.
695 std::map<uint32_t, std::unordered_set<uint32_t>> loop_latch_blocks;
696 for (auto back_edge : back_edges) {
697 uint32_t back_edge_block;
698 uint32_t header_block;
699 std::tie(back_edge_block, header_block) = back_edge;
700 if (!function->IsBlockType(header_block, kBlockTypeLoop)) {
701 return _.diag(SPV_ERROR_INVALID_CFG, _.FindDef(back_edge_block))
702 << "Back-edges (" << _.getIdName(back_edge_block) << " -> "
703 << _.getIdName(header_block)
704 << ") can only be formed between a block and a loop header.";
705 }
706 loop_latch_blocks[header_block].insert(back_edge_block);
707 }
708
709 // Check the loop headers have exactly one back-edge branching to it
710 for (BasicBlock* loop_header : function->ordered_blocks()) {
711 if (!loop_header->reachable()) continue;
712 if (!loop_header->is_type(kBlockTypeLoop)) continue;
713 auto loop_header_id = loop_header->id();
714 auto num_latch_blocks = loop_latch_blocks[loop_header_id].size();
715 if (num_latch_blocks != 1) {
716 return _.diag(SPV_ERROR_INVALID_CFG, _.FindDef(loop_header_id))
717 << "Loop header " << _.getIdName(loop_header_id)
718 << " is targeted by " << num_latch_blocks
719 << " back-edge blocks but the standard requires exactly one";
720 }
721 }
722
723 // Check construct rules
724 for (const Construct& construct : function->constructs()) {
725 auto header = construct.entry_block();
726 auto merge = construct.exit_block();
727
728 if (header->reachable() && !merge) {
729 std::string construct_name, header_name, exit_name;
730 std::tie(construct_name, header_name, exit_name) =
731 ConstructNames(construct.type());
732 return _.diag(SPV_ERROR_INTERNAL, _.FindDef(header->id()))
733 << "Construct " + construct_name + " with " + header_name + " " +
734 _.getIdName(header->id()) + " does not have a " +
735 exit_name + ". This may be a bug in the validator.";
736 }
737
738 // If the exit block is reachable then it's dominated by the
739 // header.
740 if (merge && merge->reachable()) {
741 if (!header->dominates(*merge)) {
742 return _.diag(SPV_ERROR_INVALID_CFG, _.FindDef(merge->id()))
743 << ConstructErrorString(construct, _.getIdName(header->id()),
744 _.getIdName(merge->id()),
745 "does not dominate");
746 }
747 // If it's really a merge block for a selection or loop, then it must be
748 // *strictly* dominated by the header.
749 if (construct.ExitBlockIsMergeBlock() && (header == merge)) {
750 return _.diag(SPV_ERROR_INVALID_CFG, _.FindDef(merge->id()))
751 << ConstructErrorString(construct, _.getIdName(header->id()),
752 _.getIdName(merge->id()),
753 "does not strictly dominate");
754 }
755 }
756 // Check post-dominance for continue constructs. But dominance and
757 // post-dominance only make sense when the construct is reachable.
758 if (header->reachable() && construct.type() == ConstructType::kContinue) {
759 if (!merge->postdominates(*header)) {
760 return _.diag(SPV_ERROR_INVALID_CFG, _.FindDef(merge->id()))
761 << ConstructErrorString(construct, _.getIdName(header->id()),
762 _.getIdName(merge->id()),
763 "is not post dominated by");
764 }
765 }
766
767 Construct::ConstructBlockSet construct_blocks = construct.blocks(function);
768 std::string construct_name, header_name, exit_name;
769 std::tie(construct_name, header_name, exit_name) =
770 ConstructNames(construct.type());
771 for (auto block : construct_blocks) {
772 // Check that all exits from the construct are via structured exits.
773 for (auto succ : *block->successors()) {
774 if (block->reachable() && !construct_blocks.count(succ) &&
775 !construct.IsStructuredExit(_, succ)) {
776 return _.diag(SPV_ERROR_INVALID_CFG, _.FindDef(block->id()))
777 << "block <ID> " << _.getIdName(block->id()) << " exits the "
778 << construct_name << " headed by <ID> "
779 << _.getIdName(header->id())
780 << ", but not via a structured exit";
781 }
782 }
783 if (block == header) continue;
784 // Check that for all non-header blocks, all predecessors are within this
785 // construct.
786 for (auto pred : *block->predecessors()) {
787 if (pred->reachable() && !construct_blocks.count(pred)) {
788 return _.diag(SPV_ERROR_INVALID_CFG, _.FindDef(pred->id()))
789 << "block <ID> " << pred->id() << " branches to the "
790 << construct_name << " construct, but not to the "
791 << header_name << " <ID> " << header->id();
792 }
793 }
794
795 if (block->is_type(BlockType::kBlockTypeSelection) ||
796 block->is_type(BlockType::kBlockTypeLoop)) {
797 size_t index = (block->terminator() - &_.ordered_instructions()[0]) - 1;
798 const auto& merge_inst = _.ordered_instructions()[index];
799 if (merge_inst.opcode() == SpvOpSelectionMerge ||
800 merge_inst.opcode() == SpvOpLoopMerge) {
801 uint32_t merge_id = merge_inst.GetOperandAs<uint32_t>(0);
802 auto merge_block = function->GetBlock(merge_id).first;
803 if (merge_block->reachable() &&
804 !construct_blocks.count(merge_block)) {
805 return _.diag(SPV_ERROR_INVALID_CFG, _.FindDef(block->id()))
806 << "Header block " << _.getIdName(block->id())
807 << " is contained in the " << construct_name
808 << " construct headed by " << _.getIdName(header->id())
809 << ", but its merge block " << _.getIdName(merge_id)
810 << " is not";
811 }
812 }
813 }
814 }
815
816 // Checks rules for case constructs.
817 if (construct.type() == ConstructType::kSelection &&
818 header->terminator()->opcode() == SpvOpSwitch) {
819 const auto terminator = header->terminator();
820 if (auto error =
821 StructuredSwitchChecks(_, function, terminator, header, merge)) {
822 return error;
823 }
824 }
825 }
826
827 if (auto error = ValidateStructuredSelections(_, postorder)) {
828 return error;
829 }
830
831 return SPV_SUCCESS;
832 }
833
PerformCfgChecks(ValidationState_t & _)834 spv_result_t PerformCfgChecks(ValidationState_t& _) {
835 for (auto& function : _.functions()) {
836 // Check all referenced blocks are defined within a function
837 if (function.undefined_block_count() != 0) {
838 std::string undef_blocks("{");
839 bool first = true;
840 for (auto undefined_block : function.undefined_blocks()) {
841 undef_blocks += _.getIdName(undefined_block);
842 if (!first) {
843 undef_blocks += " ";
844 }
845 first = false;
846 }
847 return _.diag(SPV_ERROR_INVALID_CFG, _.FindDef(function.id()))
848 << "Block(s) " << undef_blocks << "}"
849 << " are referenced but not defined in function "
850 << _.getIdName(function.id());
851 }
852
853 // Set each block's immediate dominator and immediate postdominator,
854 // and find all back-edges.
855 //
856 // We want to analyze all the blocks in the function, even in degenerate
857 // control flow cases including unreachable blocks. So use the augmented
858 // CFG to ensure we cover all the blocks.
859 std::vector<const BasicBlock*> postorder;
860 std::vector<const BasicBlock*> postdom_postorder;
861 std::vector<std::pair<uint32_t, uint32_t>> back_edges;
862 auto ignore_block = [](const BasicBlock*) {};
863 auto ignore_edge = [](const BasicBlock*, const BasicBlock*) {};
864 if (!function.ordered_blocks().empty()) {
865 /// calculate dominators
866 CFA<BasicBlock>::DepthFirstTraversal(
867 function.first_block(), function.AugmentedCFGSuccessorsFunction(),
868 ignore_block, [&](const BasicBlock* b) { postorder.push_back(b); },
869 ignore_edge);
870 auto edges = CFA<BasicBlock>::CalculateDominators(
871 postorder, function.AugmentedCFGPredecessorsFunction());
872 for (auto edge : edges) {
873 if (edge.first != edge.second)
874 edge.first->SetImmediateDominator(edge.second);
875 }
876
877 /// calculate post dominators
878 CFA<BasicBlock>::DepthFirstTraversal(
879 function.pseudo_exit_block(),
880 function.AugmentedCFGPredecessorsFunction(), ignore_block,
881 [&](const BasicBlock* b) { postdom_postorder.push_back(b); },
882 ignore_edge);
883 auto postdom_edges = CFA<BasicBlock>::CalculateDominators(
884 postdom_postorder, function.AugmentedCFGSuccessorsFunction());
885 for (auto edge : postdom_edges) {
886 edge.first->SetImmediatePostDominator(edge.second);
887 }
888 /// calculate back edges.
889 CFA<BasicBlock>::DepthFirstTraversal(
890 function.pseudo_entry_block(),
891 function
892 .AugmentedCFGSuccessorsFunctionIncludingHeaderToContinueEdge(),
893 ignore_block, ignore_block,
894 [&](const BasicBlock* from, const BasicBlock* to) {
895 back_edges.emplace_back(from->id(), to->id());
896 });
897 }
898 UpdateContinueConstructExitBlocks(function, back_edges);
899
900 auto& blocks = function.ordered_blocks();
901 if (!blocks.empty()) {
902 // Check if the order of blocks in the binary appear before the blocks
903 // they dominate
904 for (auto block = begin(blocks) + 1; block != end(blocks); ++block) {
905 if (auto idom = (*block)->immediate_dominator()) {
906 if (idom != function.pseudo_entry_block() &&
907 block == std::find(begin(blocks), block, idom)) {
908 return _.diag(SPV_ERROR_INVALID_CFG, _.FindDef(idom->id()))
909 << "Block " << _.getIdName((*block)->id())
910 << " appears in the binary before its dominator "
911 << _.getIdName(idom->id());
912 }
913 }
914 }
915 // If we have structured control flow, check that no block has a control
916 // flow nesting depth larger than the limit.
917 if (_.HasCapability(SpvCapabilityShader)) {
918 const int control_flow_nesting_depth_limit =
919 _.options()->universal_limits_.max_control_flow_nesting_depth;
920 for (auto block = begin(blocks); block != end(blocks); ++block) {
921 if (function.GetBlockDepth(*block) >
922 control_flow_nesting_depth_limit) {
923 return _.diag(SPV_ERROR_INVALID_CFG, _.FindDef((*block)->id()))
924 << "Maximum Control Flow nesting depth exceeded.";
925 }
926 }
927 }
928 }
929
930 /// Structured control flow checks are only required for shader capabilities
931 if (_.HasCapability(SpvCapabilityShader)) {
932 if (auto error =
933 StructuredControlFlowChecks(_, &function, back_edges, postorder))
934 return error;
935 }
936 }
937 return SPV_SUCCESS;
938 }
939
CfgPass(ValidationState_t & _,const Instruction * inst)940 spv_result_t CfgPass(ValidationState_t& _, const Instruction* inst) {
941 SpvOp opcode = inst->opcode();
942 switch (opcode) {
943 case SpvOpLabel:
944 if (auto error = _.current_function().RegisterBlock(inst->id()))
945 return error;
946
947 // TODO(github:1661) This should be done in the
948 // ValidationState::RegisterInstruction method but because of the order of
949 // passes the OpLabel ends up not being part of the basic block it starts.
950 _.current_function().current_block()->set_label(inst);
951 break;
952 case SpvOpLoopMerge: {
953 uint32_t merge_block = inst->GetOperandAs<uint32_t>(0);
954 uint32_t continue_block = inst->GetOperandAs<uint32_t>(1);
955 CFG_ASSERT(MergeBlockAssert, merge_block);
956
957 if (auto error = _.current_function().RegisterLoopMerge(merge_block,
958 continue_block))
959 return error;
960 } break;
961 case SpvOpSelectionMerge: {
962 uint32_t merge_block = inst->GetOperandAs<uint32_t>(0);
963 CFG_ASSERT(MergeBlockAssert, merge_block);
964
965 if (auto error = _.current_function().RegisterSelectionMerge(merge_block))
966 return error;
967 } break;
968 case SpvOpBranch: {
969 uint32_t target = inst->GetOperandAs<uint32_t>(0);
970 CFG_ASSERT(FirstBlockAssert, target);
971
972 _.current_function().RegisterBlockEnd({target});
973 } break;
974 case SpvOpBranchConditional: {
975 uint32_t tlabel = inst->GetOperandAs<uint32_t>(1);
976 uint32_t flabel = inst->GetOperandAs<uint32_t>(2);
977 CFG_ASSERT(FirstBlockAssert, tlabel);
978 CFG_ASSERT(FirstBlockAssert, flabel);
979
980 _.current_function().RegisterBlockEnd({tlabel, flabel});
981 } break;
982
983 case SpvOpSwitch: {
984 std::vector<uint32_t> cases;
985 for (size_t i = 1; i < inst->operands().size(); i += 2) {
986 uint32_t target = inst->GetOperandAs<uint32_t>(i);
987 CFG_ASSERT(FirstBlockAssert, target);
988 cases.push_back(target);
989 }
990 _.current_function().RegisterBlockEnd({cases});
991 } break;
992 case SpvOpReturn: {
993 const uint32_t return_type = _.current_function().GetResultTypeId();
994 const Instruction* return_type_inst = _.FindDef(return_type);
995 assert(return_type_inst);
996 if (return_type_inst->opcode() != SpvOpTypeVoid)
997 return _.diag(SPV_ERROR_INVALID_CFG, inst)
998 << "OpReturn can only be called from a function with void "
999 << "return type.";
1000 _.current_function().RegisterBlockEnd(std::vector<uint32_t>());
1001 break;
1002 }
1003 case SpvOpKill:
1004 case SpvOpReturnValue:
1005 case SpvOpUnreachable:
1006 case SpvOpTerminateInvocation:
1007 case SpvOpIgnoreIntersectionKHR:
1008 case SpvOpTerminateRayKHR:
1009 _.current_function().RegisterBlockEnd(std::vector<uint32_t>());
1010 if (opcode == SpvOpKill) {
1011 _.current_function().RegisterExecutionModelLimitation(
1012 SpvExecutionModelFragment,
1013 "OpKill requires Fragment execution model");
1014 }
1015 if (opcode == SpvOpTerminateInvocation) {
1016 _.current_function().RegisterExecutionModelLimitation(
1017 SpvExecutionModelFragment,
1018 "OpTerminateInvocation requires Fragment execution model");
1019 }
1020 if (opcode == SpvOpIgnoreIntersectionKHR) {
1021 _.current_function().RegisterExecutionModelLimitation(
1022 SpvExecutionModelAnyHitKHR,
1023 "OpIgnoreIntersectionKHR requires AnyHit execution model");
1024 }
1025 if (opcode == SpvOpTerminateRayKHR) {
1026 _.current_function().RegisterExecutionModelLimitation(
1027 SpvExecutionModelAnyHitKHR,
1028 "OpTerminateRayKHR requires AnyHit execution model");
1029 }
1030
1031 break;
1032 default:
1033 break;
1034 }
1035 return SPV_SUCCESS;
1036 }
1037
ReachabilityPass(ValidationState_t & _)1038 void ReachabilityPass(ValidationState_t& _) {
1039 for (auto& f : _.functions()) {
1040 std::vector<BasicBlock*> stack;
1041 auto entry = f.first_block();
1042 // Skip function declarations.
1043 if (entry) stack.push_back(entry);
1044
1045 while (!stack.empty()) {
1046 auto block = stack.back();
1047 stack.pop_back();
1048
1049 if (block->reachable()) continue;
1050
1051 block->set_reachable(true);
1052 for (auto succ : *block->successors()) {
1053 stack.push_back(succ);
1054 }
1055 }
1056 }
1057 }
1058
ControlFlowPass(ValidationState_t & _,const Instruction * inst)1059 spv_result_t ControlFlowPass(ValidationState_t& _, const Instruction* inst) {
1060 switch (inst->opcode()) {
1061 case SpvOpPhi:
1062 if (auto error = ValidatePhi(_, inst)) return error;
1063 break;
1064 case SpvOpBranch:
1065 if (auto error = ValidateBranch(_, inst)) return error;
1066 break;
1067 case SpvOpBranchConditional:
1068 if (auto error = ValidateBranchConditional(_, inst)) return error;
1069 break;
1070 case SpvOpReturnValue:
1071 if (auto error = ValidateReturnValue(_, inst)) return error;
1072 break;
1073 case SpvOpSwitch:
1074 if (auto error = ValidateSwitch(_, inst)) return error;
1075 break;
1076 case SpvOpLoopMerge:
1077 if (auto error = ValidateLoopMerge(_, inst)) return error;
1078 break;
1079 default:
1080 break;
1081 }
1082
1083 return SPV_SUCCESS;
1084 }
1085
1086 } // namespace val
1087 } // namespace spvtools
1088