• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
18 #include "block_merge_util.h"
19 
20 namespace spvtools {
21 namespace opt {
22 namespace blockmergeutil {
23 namespace {
24 
25 // Returns true if |block| contains a merge instruction.
IsHeader(BasicBlock * block)26 bool IsHeader(BasicBlock* block) { return block->GetMergeInst() != nullptr; }
27 
28 // Returns true if |id| contains a merge instruction.
IsHeader(IRContext * context,uint32_t id)29 bool IsHeader(IRContext* context, uint32_t id) {
30   return IsHeader(
31       context->get_instr_block(context->get_def_use_mgr()->GetDef(id)));
32 }
33 
34 // Returns true if |id| is the merge target of a merge instruction.
IsMerge(IRContext * context,uint32_t id)35 bool IsMerge(IRContext* context, uint32_t id) {
36   return !context->get_def_use_mgr()->WhileEachUse(
37       id, [](Instruction* user, uint32_t index) {
38         spv::Op op = user->opcode();
39         if ((op == spv::Op::OpLoopMerge || op == spv::Op::OpSelectionMerge) &&
40             index == 0u) {
41           return false;
42         }
43         return true;
44       });
45 }
46 
47 // Returns true if |block| is the merge target of a merge instruction.
IsMerge(IRContext * context,BasicBlock * block)48 bool IsMerge(IRContext* context, BasicBlock* block) {
49   return IsMerge(context, block->id());
50 }
51 
52 // Returns true if |id| is the continue target of a merge instruction.
IsContinue(IRContext * context,uint32_t id)53 bool IsContinue(IRContext* context, uint32_t id) {
54   return !context->get_def_use_mgr()->WhileEachUse(
55       id, [](Instruction* user, uint32_t index) {
56         spv::Op op = user->opcode();
57         if (op == spv::Op::OpLoopMerge && index == 1u) {
58           return false;
59         }
60         return true;
61       });
62 }
63 
64 // Removes any OpPhi instructions in |block|, which should have exactly one
65 // predecessor, replacing uses of OpPhi ids with the ids associated with the
66 // predecessor.
EliminateOpPhiInstructions(IRContext * context,BasicBlock * block)67 void EliminateOpPhiInstructions(IRContext* context, BasicBlock* block) {
68   block->ForEachPhiInst([context](Instruction* phi) {
69     assert(2 == phi->NumInOperands() &&
70            "A block can only have one predecessor for block merging to make "
71            "sense.");
72     context->ReplaceAllUsesWith(phi->result_id(),
73                                 phi->GetSingleWordInOperand(0));
74     context->KillInst(phi);
75   });
76 }
77 
78 }  // Anonymous namespace
79 
CanMergeWithSuccessor(IRContext * context,BasicBlock * block)80 bool CanMergeWithSuccessor(IRContext* context, BasicBlock* block) {
81   // Find block with single successor which has no other predecessors.
82   auto ii = block->end();
83   --ii;
84   Instruction* br = &*ii;
85   if (br->opcode() != spv::Op::OpBranch) {
86     return false;
87   }
88 
89   const uint32_t lab_id = br->GetSingleWordInOperand(0);
90   if (context->cfg()->preds(lab_id).size() != 1) {
91     return false;
92   }
93 
94   bool pred_is_merge = IsMerge(context, block);
95   bool succ_is_merge = IsMerge(context, lab_id);
96   if (pred_is_merge && succ_is_merge) {
97     // Cannot merge two merges together.
98     return false;
99   }
100 
101   if (pred_is_merge && IsContinue(context, lab_id)) {
102     // Cannot merge a continue target with a merge block.
103     return false;
104   }
105 
106   Instruction* merge_inst = block->GetMergeInst();
107   const bool pred_is_header = IsHeader(block);
108   if (pred_is_header && lab_id != merge_inst->GetSingleWordInOperand(0u)) {
109     bool succ_is_header = IsHeader(context, lab_id);
110     if (pred_is_header && succ_is_header) {
111       // Cannot merge two headers together when the successor is not the merge
112       // block of the predecessor.
113       return false;
114     }
115 
116     // If this is a header block and the successor is not its merge, we must
117     // be careful about which blocks we are willing to merge together.
118     // OpLoopMerge must be followed by a conditional or unconditional branch.
119     // The merge must be a loop merge because a selection merge cannot be
120     // followed by an unconditional branch.
121     BasicBlock* succ_block = context->get_instr_block(lab_id);
122     spv::Op succ_term_op = succ_block->terminator()->opcode();
123     assert(merge_inst->opcode() == spv::Op::OpLoopMerge);
124     if (succ_term_op != spv::Op::OpBranch &&
125         succ_term_op != spv::Op::OpBranchConditional) {
126       return false;
127     }
128   }
129 
130   if (succ_is_merge || IsContinue(context, lab_id)) {
131     auto* struct_cfg = context->GetStructuredCFGAnalysis();
132     auto switch_block_id = struct_cfg->ContainingSwitch(block->id());
133     if (switch_block_id) {
134       auto switch_merge_id = struct_cfg->SwitchMergeBlock(switch_block_id);
135       const auto* switch_inst =
136           &*block->GetParent()->FindBlock(switch_block_id)->tail();
137       for (uint32_t i = 1; i < switch_inst->NumInOperands(); i += 2) {
138         auto target_id = switch_inst->GetSingleWordInOperand(i);
139         if (target_id == block->id() && target_id != switch_merge_id) {
140           // Case constructs must be structurally dominated by the OpSwitch.
141           // Since the successor is the merge/continue for another construct,
142           // merging the blocks would break that requirement.
143           return false;
144         }
145       }
146     }
147   }
148 
149   return true;
150 }
151 
MergeWithSuccessor(IRContext * context,Function * func,Function::iterator bi)152 void MergeWithSuccessor(IRContext* context, Function* func,
153                         Function::iterator bi) {
154   assert(CanMergeWithSuccessor(context, &*bi) &&
155          "Precondition failure for MergeWithSuccessor: it must be legal to "
156          "merge the block and its successor.");
157 
158   auto ii = bi->end();
159   --ii;
160   Instruction* br = &*ii;
161   const uint32_t lab_id = br->GetSingleWordInOperand(0);
162   Instruction* merge_inst = bi->GetMergeInst();
163   bool pred_is_header = IsHeader(&*bi);
164 
165   // Merge blocks.
166   context->KillInst(br);
167   auto sbi = bi;
168   for (; sbi != func->end(); ++sbi)
169     if (sbi->id() == lab_id) break;
170   // If bi is sbi's only predecessor, it dominates sbi and thus
171   // sbi must follow bi in func's ordering.
172   assert(sbi != func->end());
173 
174   if (sbi->tail()->opcode() == spv::Op::OpSwitch &&
175       sbi->MergeBlockIdIfAny() != 0) {
176     context->InvalidateAnalyses(IRContext::Analysis::kAnalysisStructuredCFG);
177   }
178 
179   // Update the inst-to-block mapping for the instructions in sbi.
180   for (auto& inst : *sbi) {
181     context->set_instr_block(&inst, &*bi);
182   }
183 
184   EliminateOpPhiInstructions(context, &*sbi);
185 
186   // Now actually move the instructions.
187   bi->AddInstructions(&*sbi);
188 
189   if (merge_inst) {
190     if (pred_is_header && lab_id == merge_inst->GetSingleWordInOperand(0u)) {
191       // Merging the header and merge blocks, so remove the structured control
192       // flow declaration.
193       context->KillInst(merge_inst);
194     } else {
195       // Move OpLine/OpNoLine information to merge_inst. This solves
196       // the validation error that OpLine is placed between OpLoopMerge
197       // and OpBranchConditional.
198       auto terminator = bi->terminator();
199       auto& vec = terminator->dbg_line_insts();
200       if (vec.size() > 0) {
201         merge_inst->ClearDbgLineInsts();
202         auto& new_vec = merge_inst->dbg_line_insts();
203         new_vec.insert(new_vec.end(), vec.begin(), vec.end());
204         terminator->ClearDbgLineInsts();
205         for (auto& l_inst : new_vec)
206           context->get_def_use_mgr()->AnalyzeInstDefUse(&l_inst);
207       }
208       // Clear debug scope of terminator to avoid DebugScope
209       // emitted between terminator and merge.
210       terminator->SetDebugScope(DebugScope(kNoDebugScope, kNoInlinedAt));
211       // Move the merge instruction to just before the terminator.
212       merge_inst->InsertBefore(terminator);
213     }
214   }
215   context->ReplaceAllUsesWith(lab_id, bi->id());
216   context->KillInst(sbi->GetLabelInst());
217   (void)sbi.Erase();
218 }
219 
220 }  // namespace blockmergeutil
221 }  // namespace opt
222 }  // namespace spvtools
223