if_conversion.cpp 11 KB

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