validate_cfg.cpp 42 KB

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