validate_cfg.cpp 45 KB

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