• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2016 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include "select_generator.h"
18 
19 #include "optimizing/nodes.h"
20 #include "reference_type_propagation.h"
21 
22 namespace art HIDDEN {
23 
24 static constexpr size_t kMaxInstructionsInBranch = 1u;
25 
HSelectGenerator(HGraph * graph,OptimizingCompilerStats * stats,const char * name)26 HSelectGenerator::HSelectGenerator(HGraph* graph,
27                                    OptimizingCompilerStats* stats,
28                                    const char* name)
29     : HOptimization(graph, name, stats) {
30 }
31 
32 // Returns true if `block` has only one predecessor, ends with a Goto
33 // or a Return and contains at most `kMaxInstructionsInBranch` other
34 // movable instruction with no side-effects.
IsSimpleBlock(HBasicBlock * block)35 static bool IsSimpleBlock(HBasicBlock* block) {
36   if (block->GetPredecessors().size() != 1u) {
37     return false;
38   }
39   DCHECK(block->GetPhis().IsEmpty());
40 
41   size_t num_instructions = 0u;
42   for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
43     HInstruction* instruction = it.Current();
44     if (instruction->IsControlFlow()) {
45       return instruction->IsGoto() || instruction->IsReturn();
46     } else if (instruction->CanBeMoved() &&
47                !instruction->HasSideEffects() &&
48                !instruction->CanThrow()) {
49       if (instruction->IsSelect() && instruction->AsSelect()->GetCondition()->GetBlock() == block) {
50         // Count one HCondition and HSelect in the same block as a single instruction.
51         // This enables finding nested selects.
52         continue;
53       } else if (++num_instructions > kMaxInstructionsInBranch) {
54         return false;  // bail as soon as we exceed number of allowed instructions
55       }
56     } else {
57       return false;
58     }
59   }
60 
61   LOG(FATAL) << "Unreachable";
62   UNREACHABLE();
63 }
64 
65 // Returns true if 'block1' and 'block2' are empty and merge into the
66 // same single successor.
BlocksMergeTogether(HBasicBlock * block1,HBasicBlock * block2)67 static bool BlocksMergeTogether(HBasicBlock* block1, HBasicBlock* block2) {
68   return block1->GetSingleSuccessor() == block2->GetSingleSuccessor();
69 }
70 
71 // Returns nullptr if `block` has either no phis or there is more than one phi. Otherwise returns
72 // that phi.
GetSinglePhi(HBasicBlock * block,size_t index1,size_t index2)73 static HPhi* GetSinglePhi(HBasicBlock* block, size_t index1, size_t index2) {
74   DCHECK_NE(index1, index2);
75 
76   HPhi* select_phi = nullptr;
77   for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
78     HPhi* phi = it.Current()->AsPhi();
79     if (select_phi == nullptr) {
80       // First phi found.
81       select_phi = phi;
82     } else {
83       // More than one phi found, return null.
84       return nullptr;
85     }
86   }
87   return select_phi;
88 }
89 
TryGenerateSelectSimpleDiamondPattern(HBasicBlock * block,ScopedArenaSafeMap<HInstruction *,HSelect * > * cache)90 bool HSelectGenerator::TryGenerateSelectSimpleDiamondPattern(
91     HBasicBlock* block, ScopedArenaSafeMap<HInstruction*, HSelect*>* cache) {
92   DCHECK(block->GetLastInstruction()->IsIf());
93   HIf* if_instruction = block->GetLastInstruction()->AsIf();
94   HBasicBlock* true_block = if_instruction->IfTrueSuccessor();
95   HBasicBlock* false_block = if_instruction->IfFalseSuccessor();
96   DCHECK_NE(true_block, false_block);
97 
98   if (!IsSimpleBlock(true_block) ||
99       !IsSimpleBlock(false_block) ||
100       !BlocksMergeTogether(true_block, false_block)) {
101     return false;
102   }
103   HBasicBlock* merge_block = true_block->GetSingleSuccessor();
104 
105   // If the branches are not empty, move instructions in front of the If.
106   // TODO(dbrazdil): This puts an instruction between If and its condition.
107   //                 Implement moving of conditions to first users if possible.
108   while (!true_block->IsSingleGoto() && !true_block->IsSingleReturn()) {
109     HInstruction* instr = true_block->GetFirstInstruction();
110     DCHECK(!instr->CanThrow());
111     instr->MoveBefore(if_instruction);
112   }
113   while (!false_block->IsSingleGoto() && !false_block->IsSingleReturn()) {
114     HInstruction* instr = false_block->GetFirstInstruction();
115     DCHECK(!instr->CanThrow());
116     instr->MoveBefore(if_instruction);
117   }
118   DCHECK(true_block->IsSingleGoto() || true_block->IsSingleReturn());
119   DCHECK(false_block->IsSingleGoto() || false_block->IsSingleReturn());
120 
121   // Find the resulting true/false values.
122   size_t predecessor_index_true = merge_block->GetPredecessorIndexOf(true_block);
123   size_t predecessor_index_false = merge_block->GetPredecessorIndexOf(false_block);
124   DCHECK_NE(predecessor_index_true, predecessor_index_false);
125 
126   bool both_successors_return = true_block->IsSingleReturn() && false_block->IsSingleReturn();
127   // TODO(solanes): Extend to support multiple phis? e.g.
128   //   int a, b;
129   //   if (bool) {
130   //     a = 0; b = 1;
131   //   } else {
132   //     a = 1; b = 2;
133   //   }
134   //   // use a and b
135   HPhi* phi = GetSinglePhi(merge_block, predecessor_index_true, predecessor_index_false);
136 
137   HInstruction* true_value = nullptr;
138   HInstruction* false_value = nullptr;
139   if (both_successors_return) {
140     true_value = true_block->GetFirstInstruction()->InputAt(0);
141     false_value = false_block->GetFirstInstruction()->InputAt(0);
142   } else if (phi != nullptr) {
143     true_value = phi->InputAt(predecessor_index_true);
144     false_value = phi->InputAt(predecessor_index_false);
145   } else {
146     return false;
147   }
148   DCHECK(both_successors_return || phi != nullptr);
149 
150   // Create the Select instruction and insert it in front of the If.
151   HInstruction* condition = if_instruction->InputAt(0);
152   HSelect* select = new (graph_->GetAllocator()) HSelect(condition,
153                                                           true_value,
154                                                           false_value,
155                                                           if_instruction->GetDexPc());
156   if (both_successors_return) {
157     if (true_value->GetType() == DataType::Type::kReference) {
158       DCHECK(false_value->GetType() == DataType::Type::kReference);
159       ReferenceTypePropagation::FixUpInstructionType(select, graph_->GetHandleCache());
160     }
161   } else if (phi->GetType() == DataType::Type::kReference) {
162     select->SetReferenceTypeInfoIfValid(phi->GetReferenceTypeInfo());
163   }
164   block->InsertInstructionBefore(select, if_instruction);
165 
166   // Remove the true branch which removes the corresponding Phi
167   // input if needed. If left only with the false branch, the Phi is
168   // automatically removed.
169   if (both_successors_return) {
170     false_block->GetFirstInstruction()->ReplaceInput(select, 0);
171   } else {
172     phi->ReplaceInput(select, predecessor_index_false);
173   }
174 
175   bool only_two_predecessors = (merge_block->GetPredecessors().size() == 2u);
176   true_block->DisconnectAndDelete();
177 
178   // Merge remaining blocks which are now connected with Goto.
179   DCHECK_EQ(block->GetSingleSuccessor(), false_block);
180   block->MergeWith(false_block);
181   if (!both_successors_return && only_two_predecessors) {
182     DCHECK_EQ(only_two_predecessors, phi->GetBlock() == nullptr);
183     DCHECK_EQ(block->GetSingleSuccessor(), merge_block);
184     block->MergeWith(merge_block);
185   }
186 
187   MaybeRecordStat(stats_, MethodCompilationStat::kSelectGenerated);
188 
189   // Very simple way of finding common subexpressions in the generated HSelect statements
190   // (since this runs after GVN). Lookup by condition, and reuse latest one if possible
191   // (due to post order, latest select is most likely replacement). If needed, we could
192   // improve this by e.g. using the operands in the map as well.
193   auto it = cache->find(condition);
194   if (it == cache->end()) {
195     cache->Put(condition, select);
196   } else {
197     // Found cached value. See if latest can replace cached in the HIR.
198     HSelect* cached_select = it->second;
199     DCHECK_EQ(cached_select->GetCondition(), select->GetCondition());
200     if (cached_select->GetTrueValue() == select->GetTrueValue() &&
201         cached_select->GetFalseValue() == select->GetFalseValue() &&
202         select->StrictlyDominates(cached_select)) {
203       cached_select->ReplaceWith(select);
204       cached_select->GetBlock()->RemoveInstruction(cached_select);
205     }
206     it->second = select;  // always cache latest
207   }
208 
209   // No need to update dominance information, as we are simplifying
210   // a simple diamond shape, where the join block is merged with the
211   // entry block. Any following blocks would have had the join block
212   // as a dominator, and `MergeWith` handles changing that to the
213   // entry block
214   return true;
215 }
216 
TryFixupDoubleDiamondPattern(HBasicBlock * block)217 HBasicBlock* HSelectGenerator::TryFixupDoubleDiamondPattern(HBasicBlock* block) {
218   DCHECK(block->GetLastInstruction()->IsIf());
219   HIf* if_instruction = block->GetLastInstruction()->AsIf();
220   HBasicBlock* true_block = if_instruction->IfTrueSuccessor();
221   HBasicBlock* false_block = if_instruction->IfFalseSuccessor();
222   DCHECK_NE(true_block, false_block);
223 
224   // One branch must be a single goto, and the other one the inner if.
225   if (true_block->IsSingleGoto() == false_block->IsSingleGoto()) {
226     return nullptr;
227   }
228 
229   HBasicBlock* single_goto = true_block->IsSingleGoto() ? true_block : false_block;
230   HBasicBlock* inner_if_block = true_block->IsSingleGoto() ? false_block : true_block;
231 
232   // The innner if branch has to be a block with just a comparison and an if.
233   if (!inner_if_block->EndsWithIf() ||
234       inner_if_block->GetLastInstruction()->AsIf()->InputAt(0) !=
235           inner_if_block->GetFirstInstruction() ||
236       inner_if_block->GetLastInstruction()->GetPrevious() !=
237           inner_if_block->GetFirstInstruction() ||
238       !inner_if_block->GetFirstInstruction()->IsCondition()) {
239     return nullptr;
240   }
241 
242   HIf* inner_if_instruction = inner_if_block->GetLastInstruction()->AsIf();
243   HBasicBlock* inner_if_true_block = inner_if_instruction->IfTrueSuccessor();
244   HBasicBlock* inner_if_false_block = inner_if_instruction->IfFalseSuccessor();
245   if (!inner_if_true_block->IsSingleGoto() || !inner_if_false_block->IsSingleGoto()) {
246     return nullptr;
247   }
248 
249   // One must merge into the outer condition and the other must not.
250   if (BlocksMergeTogether(single_goto, inner_if_true_block) ==
251       BlocksMergeTogether(single_goto, inner_if_false_block)) {
252     return nullptr;
253   }
254 
255   // First merge merges the outer if with one of the inner if branches. The block must be a Phi and
256   // a Goto.
257   HBasicBlock* first_merge = single_goto->GetSingleSuccessor();
258   if (first_merge->GetNumberOfPredecessors() != 2 ||
259       first_merge->GetPhis().CountSize() != 1 ||
260       !first_merge->GetLastInstruction()->IsGoto() ||
261       first_merge->GetFirstInstruction() != first_merge->GetLastInstruction()) {
262     return nullptr;
263   }
264 
265   HPhi* first_phi = first_merge->GetFirstPhi()->AsPhi();
266 
267   // Second merge is first_merge and the remainder branch merging. It must be phi + goto, or phi +
268   // return. Depending on the first merge, we define the second merge.
269   HBasicBlock* merges_into_second_merge =
270     BlocksMergeTogether(single_goto, inner_if_true_block)
271       ? inner_if_false_block
272       : inner_if_true_block;
273   if (!BlocksMergeTogether(first_merge, merges_into_second_merge)) {
274     return nullptr;
275   }
276 
277   HBasicBlock* second_merge = merges_into_second_merge->GetSingleSuccessor();
278   if (second_merge->GetNumberOfPredecessors() != 2 ||
279       second_merge->GetPhis().CountSize() != 1 ||
280       !(second_merge->GetLastInstruction()->IsGoto() ||
281         second_merge->GetLastInstruction()->IsReturn()) ||
282       second_merge->GetFirstInstruction() != second_merge->GetLastInstruction()) {
283     return nullptr;
284   }
285 
286   size_t index = second_merge->GetPredecessorIndexOf(merges_into_second_merge);
287   HPhi* second_phi = second_merge->GetFirstPhi()->AsPhi();
288 
289   // Merge the phis.
290   first_phi->AddInput(second_phi->InputAt(index));
291   merges_into_second_merge->ReplaceSuccessor(second_merge, first_merge);
292   second_phi->ReplaceWith(first_phi);
293   second_merge->RemovePhi(second_phi);
294 
295   // Sort out the new domination before merging the blocks
296   DCHECK_EQ(second_merge->GetSinglePredecessor(), first_merge);
297   second_merge->GetDominator()->RemoveDominatedBlock(second_merge);
298   second_merge->SetDominator(first_merge);
299   first_merge->AddDominatedBlock(second_merge);
300   first_merge->MergeWith(second_merge);
301 
302   // No need to update dominance information. There's a chance that `merges_into_second_merge`
303   // doesn't come before `first_merge` but we don't need to fix it since `merges_into_second_merge`
304   // will disappear from the graph altogether when doing the follow-up
305   // TryGenerateSelectSimpleDiamondPattern.
306 
307   return inner_if_block;
308 }
309 
Run()310 bool HSelectGenerator::Run() {
311   bool did_select = false;
312   // Select cache with local allocator.
313   ScopedArenaAllocator allocator(graph_->GetArenaStack());
314   ScopedArenaSafeMap<HInstruction*, HSelect*> cache(std::less<HInstruction*>(),
315                                                     allocator.Adapter(kArenaAllocSelectGenerator));
316 
317   // Iterate in post order in the unlikely case that removing one occurrence of
318   // the selection pattern empties a branch block of another occurrence.
319   for (HBasicBlock* block : graph_->GetPostOrder()) {
320     if (!block->EndsWithIf()) {
321       continue;
322     }
323 
324     if (TryGenerateSelectSimpleDiamondPattern(block, &cache)) {
325       did_select = true;
326     } else {
327       // Try to fix up the odd version of the double diamond pattern. If we could do it, it means
328       // that we can generate two selects.
329       HBasicBlock* inner_if_block = TryFixupDoubleDiamondPattern(block);
330       if (inner_if_block != nullptr) {
331         // Generate the selects now since `inner_if_block` should be after `block` in PostOrder.
332         bool result = TryGenerateSelectSimpleDiamondPattern(inner_if_block, &cache);
333         DCHECK(result);
334         result = TryGenerateSelectSimpleDiamondPattern(block, &cache);
335         DCHECK(result);
336         did_select = true;
337       }
338     }
339   }
340 
341   return did_select;
342 }
343 
344 }  // namespace art
345