function.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  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 "source/val/function.h"
  15. #include <algorithm>
  16. #include <cassert>
  17. #include <sstream>
  18. #include <unordered_map>
  19. #include <utility>
  20. #include "source/cfa.h"
  21. #include "source/val/basic_block.h"
  22. #include "source/val/construct.h"
  23. #include "source/val/validate.h"
  24. namespace spvtools {
  25. namespace val {
  26. // Universal Limit of ResultID + 1
  27. static const uint32_t kInvalidId = 0x400000;
  28. Function::Function(uint32_t function_id, uint32_t result_type_id,
  29. spv::FunctionControlMask function_control,
  30. uint32_t function_type_id)
  31. : id_(function_id),
  32. function_type_id_(function_type_id),
  33. result_type_id_(result_type_id),
  34. function_control_(function_control),
  35. declaration_type_(FunctionDecl::kFunctionDeclUnknown),
  36. end_has_been_registered_(false),
  37. blocks_(),
  38. current_block_(nullptr),
  39. pseudo_entry_block_(0),
  40. pseudo_exit_block_(kInvalidId),
  41. cfg_constructs_(),
  42. variable_ids_(),
  43. parameter_ids_() {}
  44. bool Function::IsFirstBlock(uint32_t block_id) const {
  45. return !ordered_blocks_.empty() && *first_block() == block_id;
  46. }
  47. spv_result_t Function::RegisterFunctionParameter(uint32_t parameter_id,
  48. uint32_t type_id) {
  49. assert(current_block_ == nullptr &&
  50. "RegisterFunctionParameter can only be called when parsing the binary "
  51. "outside of a block");
  52. // TODO(umar): Validate function parameter type order and count
  53. // TODO(umar): Use these variables to validate parameter type
  54. (void)parameter_id;
  55. (void)type_id;
  56. return SPV_SUCCESS;
  57. }
  58. spv_result_t Function::RegisterLoopMerge(uint32_t merge_id,
  59. uint32_t continue_id) {
  60. RegisterBlock(merge_id, false);
  61. RegisterBlock(continue_id, false);
  62. BasicBlock& merge_block = blocks_.at(merge_id);
  63. BasicBlock& continue_target_block = blocks_.at(continue_id);
  64. assert(current_block_ &&
  65. "RegisterLoopMerge must be called when called within a block");
  66. current_block_->RegisterStructuralSuccessor(&merge_block);
  67. current_block_->RegisterStructuralSuccessor(&continue_target_block);
  68. current_block_->set_type(kBlockTypeLoop);
  69. merge_block.set_type(kBlockTypeMerge);
  70. continue_target_block.set_type(kBlockTypeContinue);
  71. Construct& loop_construct =
  72. AddConstruct({ConstructType::kLoop, current_block_, &merge_block});
  73. Construct& continue_construct =
  74. AddConstruct({ConstructType::kContinue, &continue_target_block});
  75. continue_construct.set_corresponding_constructs({&loop_construct});
  76. loop_construct.set_corresponding_constructs({&continue_construct});
  77. merge_block_header_[&merge_block] = current_block_;
  78. if (continue_target_headers_.find(&continue_target_block) ==
  79. continue_target_headers_.end()) {
  80. continue_target_headers_[&continue_target_block] = {current_block_};
  81. } else {
  82. continue_target_headers_[&continue_target_block].push_back(current_block_);
  83. }
  84. return SPV_SUCCESS;
  85. }
  86. spv_result_t Function::RegisterSelectionMerge(uint32_t merge_id) {
  87. RegisterBlock(merge_id, false);
  88. BasicBlock& merge_block = blocks_.at(merge_id);
  89. current_block_->set_type(kBlockTypeSelection);
  90. merge_block.set_type(kBlockTypeMerge);
  91. merge_block_header_[&merge_block] = current_block_;
  92. current_block_->RegisterStructuralSuccessor(&merge_block);
  93. AddConstruct({ConstructType::kSelection, current_block(), &merge_block});
  94. return SPV_SUCCESS;
  95. }
  96. spv_result_t Function::RegisterSetFunctionDeclType(FunctionDecl type) {
  97. assert(declaration_type_ == FunctionDecl::kFunctionDeclUnknown);
  98. declaration_type_ = type;
  99. return SPV_SUCCESS;
  100. }
  101. spv_result_t Function::RegisterBlock(uint32_t block_id, bool is_definition) {
  102. assert(
  103. declaration_type_ == FunctionDecl::kFunctionDeclDefinition &&
  104. "RegisterBlocks can only be called after declaration_type_ is defined");
  105. std::unordered_map<uint32_t, BasicBlock>::iterator inserted_block;
  106. bool success = false;
  107. tie(inserted_block, success) =
  108. blocks_.insert({block_id, BasicBlock(block_id)});
  109. if (is_definition) { // new block definition
  110. assert(current_block_ == nullptr &&
  111. "Register Block can only be called when parsing a binary outside of "
  112. "a BasicBlock");
  113. undefined_blocks_.erase(block_id);
  114. current_block_ = &inserted_block->second;
  115. ordered_blocks_.push_back(current_block_);
  116. } else if (success) { // Block doesn't exist but this is not a definition
  117. undefined_blocks_.insert(block_id);
  118. }
  119. return SPV_SUCCESS;
  120. }
  121. void Function::RegisterBlockEnd(std::vector<uint32_t> next_list) {
  122. assert(
  123. current_block_ &&
  124. "RegisterBlockEnd can only be called when parsing a binary in a block");
  125. std::vector<BasicBlock*> next_blocks;
  126. next_blocks.reserve(next_list.size());
  127. std::unordered_map<uint32_t, BasicBlock>::iterator inserted_block;
  128. bool success;
  129. for (uint32_t successor_id : next_list) {
  130. tie(inserted_block, success) =
  131. blocks_.insert({successor_id, BasicBlock(successor_id)});
  132. if (success) {
  133. undefined_blocks_.insert(successor_id);
  134. }
  135. next_blocks.push_back(&inserted_block->second);
  136. }
  137. if (current_block_->is_type(kBlockTypeLoop)) {
  138. // For each loop header, record the set of its successors, and include
  139. // its continue target if the continue target is not the loop header
  140. // itself.
  141. std::vector<BasicBlock*>& next_blocks_plus_continue_target =
  142. loop_header_successors_plus_continue_target_map_[current_block_];
  143. next_blocks_plus_continue_target = next_blocks;
  144. auto continue_target =
  145. FindConstructForEntryBlock(current_block_, ConstructType::kLoop)
  146. .corresponding_constructs()
  147. .back()
  148. ->entry_block();
  149. if (continue_target != current_block_) {
  150. next_blocks_plus_continue_target.push_back(continue_target);
  151. }
  152. }
  153. current_block_->RegisterSuccessors(next_blocks);
  154. current_block_ = nullptr;
  155. return;
  156. }
  157. void Function::RegisterFunctionEnd() {
  158. if (!end_has_been_registered_) {
  159. end_has_been_registered_ = true;
  160. ComputeAugmentedCFG();
  161. }
  162. }
  163. size_t Function::block_count() const { return blocks_.size(); }
  164. size_t Function::undefined_block_count() const {
  165. return undefined_blocks_.size();
  166. }
  167. const std::vector<BasicBlock*>& Function::ordered_blocks() const {
  168. return ordered_blocks_;
  169. }
  170. std::vector<BasicBlock*>& Function::ordered_blocks() { return ordered_blocks_; }
  171. const BasicBlock* Function::current_block() const { return current_block_; }
  172. BasicBlock* Function::current_block() { return current_block_; }
  173. const std::list<Construct>& Function::constructs() const {
  174. return cfg_constructs_;
  175. }
  176. std::list<Construct>& Function::constructs() { return cfg_constructs_; }
  177. const BasicBlock* Function::first_block() const {
  178. if (ordered_blocks_.empty()) return nullptr;
  179. return ordered_blocks_[0];
  180. }
  181. BasicBlock* Function::first_block() {
  182. if (ordered_blocks_.empty()) return nullptr;
  183. return ordered_blocks_[0];
  184. }
  185. bool Function::IsBlockType(uint32_t merge_block_id, BlockType type) const {
  186. bool ret = false;
  187. const BasicBlock* block;
  188. std::tie(block, std::ignore) = GetBlock(merge_block_id);
  189. if (block) {
  190. ret = block->is_type(type);
  191. }
  192. return ret;
  193. }
  194. std::pair<const BasicBlock*, bool> Function::GetBlock(uint32_t block_id) const {
  195. const auto b = blocks_.find(block_id);
  196. if (b != end(blocks_)) {
  197. const BasicBlock* block = &(b->second);
  198. bool defined =
  199. undefined_blocks_.find(block->id()) == std::end(undefined_blocks_);
  200. return std::make_pair(block, defined);
  201. } else {
  202. return std::make_pair(nullptr, false);
  203. }
  204. }
  205. std::pair<BasicBlock*, bool> Function::GetBlock(uint32_t block_id) {
  206. const BasicBlock* out;
  207. bool defined;
  208. std::tie(out, defined) =
  209. const_cast<const Function*>(this)->GetBlock(block_id);
  210. return std::make_pair(const_cast<BasicBlock*>(out), defined);
  211. }
  212. Function::GetBlocksFunction Function::AugmentedCFGSuccessorsFunction() const {
  213. return [this](const BasicBlock* block) {
  214. auto where = augmented_successors_map_.find(block);
  215. return where == augmented_successors_map_.end() ? block->successors()
  216. : &(*where).second;
  217. };
  218. }
  219. Function::GetBlocksFunction Function::AugmentedCFGPredecessorsFunction() const {
  220. return [this](const BasicBlock* block) {
  221. auto where = augmented_predecessors_map_.find(block);
  222. return where == augmented_predecessors_map_.end() ? block->predecessors()
  223. : &(*where).second;
  224. };
  225. }
  226. Function::GetBlocksFunction Function::AugmentedStructuralCFGSuccessorsFunction()
  227. const {
  228. return [this](const BasicBlock* block) {
  229. auto where = augmented_successors_map_.find(block);
  230. return where == augmented_successors_map_.end()
  231. ? block->structural_successors()
  232. : &(*where).second;
  233. };
  234. }
  235. Function::GetBlocksFunction
  236. Function::AugmentedStructuralCFGPredecessorsFunction() const {
  237. return [this](const BasicBlock* block) {
  238. auto where = augmented_predecessors_map_.find(block);
  239. return where == augmented_predecessors_map_.end()
  240. ? block->structural_predecessors()
  241. : &(*where).second;
  242. };
  243. }
  244. void Function::ComputeAugmentedCFG() {
  245. // Compute the successors of the pseudo-entry block, and
  246. // the predecessors of the pseudo exit block.
  247. auto succ_func = [](const BasicBlock* b) {
  248. return b->structural_successors();
  249. };
  250. auto pred_func = [](const BasicBlock* b) {
  251. return b->structural_predecessors();
  252. };
  253. CFA<BasicBlock>::ComputeAugmentedCFG(
  254. ordered_blocks_, &pseudo_entry_block_, &pseudo_exit_block_,
  255. &augmented_successors_map_, &augmented_predecessors_map_, succ_func,
  256. pred_func);
  257. }
  258. Construct& Function::AddConstruct(const Construct& new_construct) {
  259. cfg_constructs_.push_back(new_construct);
  260. auto& result = cfg_constructs_.back();
  261. entry_block_to_construct_[std::make_pair(new_construct.entry_block(),
  262. new_construct.type())] = &result;
  263. return result;
  264. }
  265. Construct& Function::FindConstructForEntryBlock(const BasicBlock* entry_block,
  266. ConstructType type) {
  267. auto where =
  268. entry_block_to_construct_.find(std::make_pair(entry_block, type));
  269. assert(where != entry_block_to_construct_.end());
  270. auto construct_ptr = (*where).second;
  271. assert(construct_ptr);
  272. return *construct_ptr;
  273. }
  274. int Function::GetBlockDepth(BasicBlock* bb) {
  275. // Guard against nullptr.
  276. if (!bb) {
  277. return 0;
  278. }
  279. // Only calculate the depth if it's not already calculated.
  280. // This function uses memoization to avoid duplicate CFG depth calculations.
  281. if (block_depth_.find(bb) != block_depth_.end()) {
  282. return block_depth_[bb];
  283. }
  284. // Avoid recursion. Something is wrong if the same block is encountered
  285. // multiple times.
  286. block_depth_[bb] = 0;
  287. BasicBlock* bb_dom = bb->immediate_dominator();
  288. if (!bb_dom || bb == bb_dom) {
  289. // This block has no dominator, so it's at depth 0.
  290. block_depth_[bb] = 0;
  291. } else if (bb->is_type(kBlockTypeContinue)) {
  292. // This rule must precede the rule for merge blocks in order to set up
  293. // depths correctly. If a block is both a merge and continue then the merge
  294. // is nested within the continue's loop (or the graph is incorrect).
  295. // The depth of the continue block entry point is 1 + loop header depth.
  296. Construct* continue_construct =
  297. entry_block_to_construct_[std::make_pair(bb, ConstructType::kContinue)];
  298. assert(continue_construct);
  299. // Continue construct has only 1 corresponding construct (loop header).
  300. Construct* loop_construct =
  301. continue_construct->corresponding_constructs()[0];
  302. assert(loop_construct);
  303. BasicBlock* loop_header = loop_construct->entry_block();
  304. // The continue target may be the loop itself (while 1).
  305. // In such cases, the depth of the continue block is: 1 + depth of the
  306. // loop's dominator block.
  307. if (loop_header == bb) {
  308. block_depth_[bb] = 1 + GetBlockDepth(bb_dom);
  309. } else {
  310. block_depth_[bb] = 1 + GetBlockDepth(loop_header);
  311. }
  312. } else if (bb->is_type(kBlockTypeMerge)) {
  313. // If this is a merge block, its depth is equal to the block before
  314. // branching.
  315. BasicBlock* header = merge_block_header_[bb];
  316. assert(header);
  317. block_depth_[bb] = GetBlockDepth(header);
  318. } else if (bb_dom->is_type(kBlockTypeSelection) ||
  319. bb_dom->is_type(kBlockTypeLoop)) {
  320. // The dominator of the given block is a header block. So, the nesting
  321. // depth of this block is: 1 + nesting depth of the header.
  322. block_depth_[bb] = 1 + GetBlockDepth(bb_dom);
  323. } else {
  324. block_depth_[bb] = GetBlockDepth(bb_dom);
  325. }
  326. return block_depth_[bb];
  327. }
  328. void Function::RegisterExecutionModelLimitation(spv::ExecutionModel model,
  329. const std::string& message) {
  330. execution_model_limitations_.push_back(
  331. [model, message](spv::ExecutionModel in_model, std::string* out_message) {
  332. if (model != in_model) {
  333. if (out_message) {
  334. *out_message = message;
  335. }
  336. return false;
  337. }
  338. return true;
  339. });
  340. }
  341. bool Function::IsCompatibleWithExecutionModel(spv::ExecutionModel model,
  342. std::string* reason) const {
  343. bool return_value = true;
  344. std::stringstream ss_reason;
  345. for (const auto& is_compatible : execution_model_limitations_) {
  346. std::string message;
  347. if (!is_compatible(model, &message)) {
  348. if (!reason) return false;
  349. return_value = false;
  350. if (!message.empty()) {
  351. ss_reason << message << "\n";
  352. }
  353. }
  354. }
  355. if (!return_value && reason) {
  356. *reason = ss_reason.str();
  357. }
  358. return return_value;
  359. }
  360. bool Function::CheckLimitations(const ValidationState_t& _,
  361. const Function* entry_point,
  362. std::string* reason) const {
  363. bool return_value = true;
  364. std::stringstream ss_reason;
  365. for (const auto& is_compatible : limitations_) {
  366. std::string message;
  367. if (!is_compatible(_, entry_point, &message)) {
  368. if (!reason) return false;
  369. return_value = false;
  370. if (!message.empty()) {
  371. ss_reason << message << "\n";
  372. }
  373. }
  374. }
  375. if (!return_value && reason) {
  376. *reason = ss_reason.str();
  377. }
  378. return return_value;
  379. }
  380. } // namespace val
  381. } // namespace spvtools