if_conversion.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  1. // Copyright (c) 2018 Google LLC
  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/opt/if_conversion.h"
  15. #include <memory>
  16. #include <vector>
  17. #include "source/opt/value_number_table.h"
  18. namespace spvtools {
  19. namespace opt {
  20. Pass::Status IfConversion::Process() {
  21. const ValueNumberTable& vn_table = *context()->GetValueNumberTable();
  22. bool modified = false;
  23. std::vector<Instruction*> to_kill;
  24. for (auto& func : *get_module()) {
  25. DominatorAnalysis* dominators = context()->GetDominatorAnalysis(&func);
  26. for (auto& block : func) {
  27. // Check if it is possible for |block| to have phis that can be
  28. // transformed.
  29. BasicBlock* common = nullptr;
  30. if (!CheckBlock(&block, dominators, &common)) continue;
  31. // Get an insertion point.
  32. auto iter = block.begin();
  33. while (iter != block.end() && iter->opcode() == SpvOpPhi) {
  34. ++iter;
  35. }
  36. InstructionBuilder builder(
  37. context(), &*iter,
  38. IRContext::kAnalysisDefUse | IRContext::kAnalysisInstrToBlockMapping);
  39. block.ForEachPhiInst([this, &builder, &modified, &common, &to_kill,
  40. dominators, &block, &vn_table](Instruction* phi) {
  41. // This phi is not compatible, but subsequent phis might be.
  42. if (!CheckType(phi->type_id())) return;
  43. // We cannot transform cases where the phi is used by another phi in the
  44. // same block due to instruction ordering restrictions.
  45. // TODO(alan-baker): If all inappropriate uses could also be
  46. // transformed, we could still remove this phi.
  47. if (!CheckPhiUsers(phi, &block)) return;
  48. // Identify the incoming values associated with the true and false
  49. // branches. If |then_block| dominates |inc0| or if the true edge
  50. // branches straight to this block and |common| is |inc0|, then |inc0|
  51. // is on the true branch. Otherwise the |inc1| is on the true branch.
  52. BasicBlock* inc0 = GetIncomingBlock(phi, 0u);
  53. Instruction* branch = common->terminator();
  54. uint32_t condition = branch->GetSingleWordInOperand(0u);
  55. BasicBlock* then_block = GetBlock(branch->GetSingleWordInOperand(1u));
  56. Instruction* true_value = nullptr;
  57. Instruction* false_value = nullptr;
  58. if ((then_block == &block && inc0 == common) ||
  59. dominators->Dominates(then_block, inc0)) {
  60. true_value = GetIncomingValue(phi, 0u);
  61. false_value = GetIncomingValue(phi, 1u);
  62. } else {
  63. true_value = GetIncomingValue(phi, 1u);
  64. false_value = GetIncomingValue(phi, 0u);
  65. }
  66. BasicBlock* true_def_block = context()->get_instr_block(true_value);
  67. BasicBlock* false_def_block = context()->get_instr_block(false_value);
  68. uint32_t true_vn = vn_table.GetValueNumber(true_value);
  69. uint32_t false_vn = vn_table.GetValueNumber(false_value);
  70. if (true_vn != 0 && true_vn == false_vn) {
  71. Instruction* inst_to_use = nullptr;
  72. // Try to pick an instruction that is not in a side node. If we can't
  73. // pick either the true for false branch as long as they can be
  74. // legally moved.
  75. if (!true_def_block ||
  76. dominators->Dominates(true_def_block, &block)) {
  77. inst_to_use = true_value;
  78. } else if (!false_def_block ||
  79. dominators->Dominates(false_def_block, &block)) {
  80. inst_to_use = false_value;
  81. } else if (CanHoistInstruction(true_value, common, dominators)) {
  82. inst_to_use = true_value;
  83. } else if (CanHoistInstruction(false_value, common, dominators)) {
  84. inst_to_use = false_value;
  85. }
  86. if (inst_to_use != nullptr) {
  87. modified = true;
  88. HoistInstruction(inst_to_use, common, dominators);
  89. context()->KillNamesAndDecorates(phi);
  90. context()->ReplaceAllUsesWith(phi->result_id(),
  91. inst_to_use->result_id());
  92. }
  93. return;
  94. }
  95. // If either incoming value is defined in a block that does not dominate
  96. // this phi, then we cannot eliminate the phi with a select.
  97. // TODO(alan-baker): Perform code motion where it makes sense to enable
  98. // the transform in this case.
  99. if (true_def_block && !dominators->Dominates(true_def_block, &block))
  100. return;
  101. if (false_def_block && !dominators->Dominates(false_def_block, &block))
  102. return;
  103. analysis::Type* data_ty =
  104. context()->get_type_mgr()->GetType(true_value->type_id());
  105. if (analysis::Vector* vec_data_ty = data_ty->AsVector()) {
  106. condition = SplatCondition(vec_data_ty, condition, &builder);
  107. }
  108. Instruction* select = builder.AddSelect(phi->type_id(), condition,
  109. true_value->result_id(),
  110. false_value->result_id());
  111. context()->ReplaceAllUsesWith(phi->result_id(), select->result_id());
  112. to_kill.push_back(phi);
  113. modified = true;
  114. return;
  115. });
  116. }
  117. }
  118. for (auto inst : to_kill) {
  119. context()->KillInst(inst);
  120. }
  121. return modified ? Status::SuccessWithChange : Status::SuccessWithoutChange;
  122. }
  123. bool IfConversion::CheckBlock(BasicBlock* block, DominatorAnalysis* dominators,
  124. BasicBlock** common) {
  125. const std::vector<uint32_t>& preds = cfg()->preds(block->id());
  126. // TODO(alan-baker): Extend to more than two predecessors
  127. if (preds.size() != 2) return false;
  128. BasicBlock* inc0 = context()->get_instr_block(preds[0]);
  129. if (dominators->Dominates(block, inc0)) return false;
  130. BasicBlock* inc1 = context()->get_instr_block(preds[1]);
  131. if (dominators->Dominates(block, inc1)) return false;
  132. // All phis will have the same common dominator, so cache the result
  133. // for this block. If there is no common dominator, then we cannot transform
  134. // any phi in this basic block.
  135. *common = dominators->CommonDominator(inc0, inc1);
  136. if (!*common || cfg()->IsPseudoEntryBlock(*common)) return false;
  137. Instruction* branch = (*common)->terminator();
  138. if (branch->opcode() != SpvOpBranchConditional) return false;
  139. return true;
  140. }
  141. bool IfConversion::CheckPhiUsers(Instruction* phi, BasicBlock* block) {
  142. return get_def_use_mgr()->WhileEachUser(phi, [block,
  143. this](Instruction* user) {
  144. if (user->opcode() == SpvOpPhi && context()->get_instr_block(user) == block)
  145. return false;
  146. return true;
  147. });
  148. }
  149. uint32_t IfConversion::SplatCondition(analysis::Vector* vec_data_ty,
  150. uint32_t cond,
  151. InstructionBuilder* builder) {
  152. // If the data inputs to OpSelect are vectors, the condition for
  153. // OpSelect must be a boolean vector with the same number of
  154. // components. So splat the condition for the branch into a vector
  155. // type.
  156. analysis::Bool bool_ty;
  157. analysis::Vector bool_vec_ty(&bool_ty, vec_data_ty->element_count());
  158. uint32_t bool_vec_id =
  159. context()->get_type_mgr()->GetTypeInstruction(&bool_vec_ty);
  160. std::vector<uint32_t> ids(vec_data_ty->element_count(), cond);
  161. return builder->AddCompositeConstruct(bool_vec_id, ids)->result_id();
  162. }
  163. bool IfConversion::CheckType(uint32_t id) {
  164. Instruction* type = get_def_use_mgr()->GetDef(id);
  165. SpvOp op = type->opcode();
  166. if (spvOpcodeIsScalarType(op) || op == SpvOpTypePointer ||
  167. op == SpvOpTypeVector)
  168. return true;
  169. return false;
  170. }
  171. BasicBlock* IfConversion::GetBlock(uint32_t id) {
  172. return context()->get_instr_block(get_def_use_mgr()->GetDef(id));
  173. }
  174. BasicBlock* IfConversion::GetIncomingBlock(Instruction* phi,
  175. uint32_t predecessor) {
  176. uint32_t in_index = 2 * predecessor + 1;
  177. return GetBlock(phi->GetSingleWordInOperand(in_index));
  178. }
  179. Instruction* IfConversion::GetIncomingValue(Instruction* phi,
  180. uint32_t predecessor) {
  181. uint32_t in_index = 2 * predecessor;
  182. return get_def_use_mgr()->GetDef(phi->GetSingleWordInOperand(in_index));
  183. }
  184. void IfConversion::HoistInstruction(Instruction* inst, BasicBlock* target_block,
  185. DominatorAnalysis* dominators) {
  186. BasicBlock* inst_block = context()->get_instr_block(inst);
  187. if (!inst_block) {
  188. // This is in the header, and dominates everything.
  189. return;
  190. }
  191. if (dominators->Dominates(inst_block, target_block)) {
  192. // Already in position. No work to do.
  193. return;
  194. }
  195. assert(inst->IsOpcodeCodeMotionSafe() &&
  196. "Trying to move an instruction that is not safe to move.");
  197. // First hoist all instructions it depends on.
  198. analysis::DefUseManager* def_use_mgr = context()->get_def_use_mgr();
  199. inst->ForEachInId(
  200. [this, target_block, def_use_mgr, dominators](uint32_t* id) {
  201. Instruction* operand_inst = def_use_mgr->GetDef(*id);
  202. HoistInstruction(operand_inst, target_block, dominators);
  203. });
  204. Instruction* insertion_pos = target_block->terminator();
  205. if ((insertion_pos)->PreviousNode()->opcode() == SpvOpSelectionMerge) {
  206. insertion_pos = insertion_pos->PreviousNode();
  207. }
  208. inst->RemoveFromList();
  209. insertion_pos->InsertBefore(std::unique_ptr<Instruction>(inst));
  210. context()->set_instr_block(inst, target_block);
  211. }
  212. bool IfConversion::CanHoistInstruction(Instruction* inst,
  213. BasicBlock* target_block,
  214. DominatorAnalysis* dominators) {
  215. BasicBlock* inst_block = context()->get_instr_block(inst);
  216. if (!inst_block) {
  217. // This is in the header, and dominates everything.
  218. return true;
  219. }
  220. if (dominators->Dominates(inst_block, target_block)) {
  221. // Already in position. No work to do.
  222. return true;
  223. }
  224. if (!inst->IsOpcodeCodeMotionSafe()) {
  225. return false;
  226. }
  227. // Check all instruction |inst| depends on.
  228. analysis::DefUseManager* def_use_mgr = context()->get_def_use_mgr();
  229. return inst->WhileEachInId(
  230. [this, target_block, def_use_mgr, dominators](uint32_t* id) {
  231. Instruction* operand_inst = def_use_mgr->GetDef(*id);
  232. return CanHoistInstruction(operand_inst, target_block, dominators);
  233. });
  234. }
  235. } // namespace opt
  236. } // namespace spvtools