validate_cfg.cpp 45 KB

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