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