block_merge_util.cpp 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  1. // Copyright (c) 2017 The Khronos Group Inc.
  2. // Copyright (c) 2017 Valve Corporation
  3. // Copyright (c) 2017 LunarG Inc.
  4. // Copyright (c) 2019 Google LLC
  5. //
  6. // Licensed under the Apache License, Version 2.0 (the "License");
  7. // you may not use this file except in compliance with the License.
  8. // You may obtain a copy of the License at
  9. //
  10. // http://www.apache.org/licenses/LICENSE-2.0
  11. //
  12. // Unless required by applicable law or agreed to in writing, software
  13. // distributed under the License is distributed on an "AS IS" BASIS,
  14. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. // See the License for the specific language governing permissions and
  16. // limitations under the License.
  17. #include "block_merge_util.h"
  18. namespace spvtools {
  19. namespace opt {
  20. namespace blockmergeutil {
  21. namespace {
  22. // Returns true if |block| contains a merge instruction.
  23. bool IsHeader(BasicBlock* block) { return block->GetMergeInst() != nullptr; }
  24. // Returns true if |id| contains a merge instruction.
  25. bool IsHeader(IRContext* context, uint32_t id) {
  26. return IsHeader(
  27. context->get_instr_block(context->get_def_use_mgr()->GetDef(id)));
  28. }
  29. // Returns true if |id| is the merge target of a merge instruction.
  30. bool IsMerge(IRContext* context, uint32_t id) {
  31. return !context->get_def_use_mgr()->WhileEachUse(
  32. id, [](Instruction* user, uint32_t index) {
  33. spv::Op op = user->opcode();
  34. if ((op == spv::Op::OpLoopMerge || op == spv::Op::OpSelectionMerge) &&
  35. index == 0u) {
  36. return false;
  37. }
  38. return true;
  39. });
  40. }
  41. // Returns true if |block| is the merge target of a merge instruction.
  42. bool IsMerge(IRContext* context, BasicBlock* block) {
  43. return IsMerge(context, block->id());
  44. }
  45. // Returns true if |id| is the continue target of a merge instruction.
  46. bool IsContinue(IRContext* context, uint32_t id) {
  47. return !context->get_def_use_mgr()->WhileEachUse(
  48. id, [](Instruction* user, uint32_t index) {
  49. spv::Op op = user->opcode();
  50. if (op == spv::Op::OpLoopMerge && index == 1u) {
  51. return false;
  52. }
  53. return true;
  54. });
  55. }
  56. // Removes any OpPhi instructions in |block|, which should have exactly one
  57. // predecessor, replacing uses of OpPhi ids with the ids associated with the
  58. // predecessor.
  59. void EliminateOpPhiInstructions(IRContext* context, BasicBlock* block) {
  60. block->ForEachPhiInst([context](Instruction* phi) {
  61. assert(2 == phi->NumInOperands() &&
  62. "A block can only have one predecessor for block merging to make "
  63. "sense.");
  64. context->ReplaceAllUsesWith(phi->result_id(),
  65. phi->GetSingleWordInOperand(0));
  66. context->KillInst(phi);
  67. });
  68. }
  69. } // Anonymous namespace
  70. bool CanMergeWithSuccessor(IRContext* context, BasicBlock* block) {
  71. // Find block with single successor which has no other predecessors.
  72. auto ii = block->end();
  73. --ii;
  74. Instruction* br = &*ii;
  75. if (br->opcode() != spv::Op::OpBranch) {
  76. return false;
  77. }
  78. const uint32_t lab_id = br->GetSingleWordInOperand(0);
  79. if (context->cfg()->preds(lab_id).size() != 1) {
  80. return false;
  81. }
  82. bool pred_is_merge = IsMerge(context, block);
  83. bool succ_is_merge = IsMerge(context, lab_id);
  84. if (pred_is_merge && succ_is_merge) {
  85. // Cannot merge two merges together.
  86. return false;
  87. }
  88. if (pred_is_merge && IsContinue(context, lab_id)) {
  89. // Cannot merge a continue target with a merge block.
  90. return false;
  91. }
  92. Instruction* merge_inst = block->GetMergeInst();
  93. const bool pred_is_header = IsHeader(block);
  94. if (pred_is_header && lab_id != merge_inst->GetSingleWordInOperand(0u)) {
  95. bool succ_is_header = IsHeader(context, lab_id);
  96. if (pred_is_header && succ_is_header) {
  97. // Cannot merge two headers together when the successor is not the merge
  98. // block of the predecessor.
  99. return false;
  100. }
  101. // If this is a header block and the successor is not its merge, we must
  102. // be careful about which blocks we are willing to merge together.
  103. // OpLoopMerge must be followed by a conditional or unconditional branch.
  104. // The merge must be a loop merge because a selection merge cannot be
  105. // followed by an unconditional branch.
  106. BasicBlock* succ_block = context->get_instr_block(lab_id);
  107. spv::Op succ_term_op = succ_block->terminator()->opcode();
  108. assert(merge_inst->opcode() == spv::Op::OpLoopMerge);
  109. if (succ_term_op != spv::Op::OpBranch &&
  110. succ_term_op != spv::Op::OpBranchConditional) {
  111. return false;
  112. }
  113. }
  114. if (succ_is_merge || IsContinue(context, lab_id)) {
  115. auto* struct_cfg = context->GetStructuredCFGAnalysis();
  116. auto switch_block_id = struct_cfg->ContainingSwitch(block->id());
  117. if (switch_block_id) {
  118. auto switch_merge_id = struct_cfg->SwitchMergeBlock(switch_block_id);
  119. const auto* switch_inst =
  120. &*block->GetParent()->FindBlock(switch_block_id)->tail();
  121. for (uint32_t i = 1; i < switch_inst->NumInOperands(); i += 2) {
  122. auto target_id = switch_inst->GetSingleWordInOperand(i);
  123. if (target_id == block->id() && target_id != switch_merge_id) {
  124. // Case constructs must be structurally dominated by the OpSwitch.
  125. // Since the successor is the merge/continue for another construct,
  126. // merging the blocks would break that requirement.
  127. return false;
  128. }
  129. }
  130. }
  131. }
  132. return true;
  133. }
  134. void MergeWithSuccessor(IRContext* context, Function* func,
  135. Function::iterator bi) {
  136. assert(CanMergeWithSuccessor(context, &*bi) &&
  137. "Precondition failure for MergeWithSuccessor: it must be legal to "
  138. "merge the block and its successor.");
  139. auto ii = bi->end();
  140. --ii;
  141. Instruction* br = &*ii;
  142. const uint32_t lab_id = br->GetSingleWordInOperand(0);
  143. Instruction* merge_inst = bi->GetMergeInst();
  144. bool pred_is_header = IsHeader(&*bi);
  145. // Merge blocks.
  146. context->KillInst(br);
  147. auto sbi = bi;
  148. for (; sbi != func->end(); ++sbi)
  149. if (sbi->id() == lab_id) break;
  150. // If bi is sbi's only predecessor, it dominates sbi and thus
  151. // sbi must follow bi in func's ordering.
  152. assert(sbi != func->end());
  153. if (sbi->tail()->opcode() == spv::Op::OpSwitch &&
  154. sbi->MergeBlockIdIfAny() != 0) {
  155. context->InvalidateAnalyses(IRContext::Analysis::kAnalysisStructuredCFG);
  156. }
  157. // Update the inst-to-block mapping for the instructions in sbi.
  158. for (auto& inst : *sbi) {
  159. context->set_instr_block(&inst, &*bi);
  160. }
  161. EliminateOpPhiInstructions(context, &*sbi);
  162. // Now actually move the instructions.
  163. bi->AddInstructions(&*sbi);
  164. if (merge_inst) {
  165. if (pred_is_header && lab_id == merge_inst->GetSingleWordInOperand(0u)) {
  166. // Merging the header and merge blocks, so remove the structured control
  167. // flow declaration.
  168. context->KillInst(merge_inst);
  169. } else {
  170. // Move OpLine/OpNoLine information to merge_inst. This solves
  171. // the validation error that OpLine is placed between OpLoopMerge
  172. // and OpBranchConditional.
  173. auto terminator = bi->terminator();
  174. auto& vec = terminator->dbg_line_insts();
  175. if (vec.size() > 0) {
  176. merge_inst->ClearDbgLineInsts();
  177. auto& new_vec = merge_inst->dbg_line_insts();
  178. new_vec.insert(new_vec.end(), vec.begin(), vec.end());
  179. terminator->ClearDbgLineInsts();
  180. for (auto& l_inst : new_vec)
  181. context->get_def_use_mgr()->AnalyzeInstDefUse(&l_inst);
  182. }
  183. // Clear debug scope of terminator to avoid DebugScope
  184. // emitted between terminator and merge.
  185. terminator->SetDebugScope(DebugScope(kNoDebugScope, kNoInlinedAt));
  186. // Move the merge instruction to just before the terminator.
  187. merge_inst->InsertBefore(terminator);
  188. }
  189. }
  190. context->ReplaceAllUsesWith(lab_id, bi->id());
  191. context->KillInst(sbi->GetLabelInst());
  192. (void)sbi.Erase();
  193. }
  194. } // namespace blockmergeutil
  195. } // namespace opt
  196. } // namespace spvtools