validate_cfg.cpp 41 KB

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