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