xref: /aosp_15_r20/art/compiler/optimizing/loop_optimization.cc (revision 795d594fd825385562da6b089ea9b2033f3abf5a)
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 "loop_optimization.h"
18 
19 #include "arch/arm/instruction_set_features_arm.h"
20 #include "arch/arm64/instruction_set_features_arm64.h"
21 #include "arch/instruction_set.h"
22 #include "arch/x86/instruction_set_features_x86.h"
23 #include "arch/x86_64/instruction_set_features_x86_64.h"
24 #include "code_generator.h"
25 #include "driver/compiler_options.h"
26 #include "linear_order.h"
27 #include "mirror/array-inl.h"
28 #include "mirror/string.h"
29 
30 namespace art HIDDEN {
31 
32 // Enables vectorization (SIMDization) in the loop optimizer.
33 static constexpr bool kEnableVectorization = true;
34 
35 //
36 // Static helpers.
37 //
38 
39 // Base alignment for arrays/strings guaranteed by the Android runtime.
BaseAlignment()40 static uint32_t BaseAlignment() {
41   return kObjectAlignment;
42 }
43 
44 // Hidden offset for arrays/strings guaranteed by the Android runtime.
HiddenOffset(DataType::Type type,bool is_string_char_at)45 static uint32_t HiddenOffset(DataType::Type type, bool is_string_char_at) {
46   return is_string_char_at
47       ? mirror::String::ValueOffset().Uint32Value()
48       : mirror::Array::DataOffset(DataType::Size(type)).Uint32Value();
49 }
50 
51 // Remove the instruction from the graph. A bit more elaborate than the usual
52 // instruction removal, since there may be a cycle in the use structure.
RemoveFromCycle(HInstruction * instruction)53 static void RemoveFromCycle(HInstruction* instruction) {
54   instruction->RemoveAsUserOfAllInputs();
55   instruction->RemoveEnvironmentUsers();
56   instruction->GetBlock()->RemoveInstructionOrPhi(instruction, /*ensure_safety=*/ false);
57   RemoveEnvironmentUses(instruction);
58   ResetEnvironmentInputRecords(instruction);
59 }
60 
61 // Detect a goto block and sets succ to the single successor.
IsGotoBlock(HBasicBlock * block,HBasicBlock ** succ)62 static bool IsGotoBlock(HBasicBlock* block, /*out*/ HBasicBlock** succ) {
63   if (block->GetPredecessors().size() == 1 &&
64       block->GetSuccessors().size() == 1 &&
65       block->IsSingleGoto()) {
66     *succ = block->GetSingleSuccessor();
67     return true;
68   }
69   return false;
70 }
71 
72 // Detect an early exit loop.
IsEarlyExit(HLoopInformation * loop_info)73 static bool IsEarlyExit(HLoopInformation* loop_info) {
74   HBlocksInLoopReversePostOrderIterator it_loop(*loop_info);
75   for (it_loop.Advance(); !it_loop.Done(); it_loop.Advance()) {
76     for (HBasicBlock* successor : it_loop.Current()->GetSuccessors()) {
77       if (!loop_info->Contains(*successor)) {
78         return true;
79       }
80     }
81   }
82   return false;
83 }
84 
85 // Forward declaration.
86 static bool IsZeroExtensionAndGet(HInstruction* instruction,
87                                   DataType::Type type,
88                                   /*out*/ HInstruction** operand);
89 
90 // Detect a sign extension in instruction from the given type.
91 // Returns the promoted operand on success.
IsSignExtensionAndGet(HInstruction * instruction,DataType::Type type,HInstruction ** operand)92 static bool IsSignExtensionAndGet(HInstruction* instruction,
93                                   DataType::Type type,
94                                   /*out*/ HInstruction** operand) {
95   // Accept any already wider constant that would be handled properly by sign
96   // extension when represented in the *width* of the given narrower data type
97   // (the fact that Uint8/Uint16 normally zero extend does not matter here).
98   int64_t value = 0;
99   if (IsInt64AndGet(instruction, /*out*/ &value)) {
100     switch (type) {
101       case DataType::Type::kUint8:
102       case DataType::Type::kInt8:
103         if (IsInt<8>(value)) {
104           *operand = instruction;
105           return true;
106         }
107         return false;
108       case DataType::Type::kUint16:
109       case DataType::Type::kInt16:
110         if (IsInt<16>(value)) {
111           *operand = instruction;
112           return true;
113         }
114         return false;
115       default:
116         return false;
117     }
118   }
119   // An implicit widening conversion of any signed expression sign-extends.
120   if (instruction->GetType() == type) {
121     switch (type) {
122       case DataType::Type::kInt8:
123       case DataType::Type::kInt16:
124         *operand = instruction;
125         return true;
126       default:
127         return false;
128     }
129   }
130   // An explicit widening conversion of a signed expression sign-extends.
131   if (instruction->IsTypeConversion()) {
132     HInstruction* conv = instruction->InputAt(0);
133     DataType::Type from = conv->GetType();
134     switch (instruction->GetType()) {
135       case DataType::Type::kInt32:
136       case DataType::Type::kInt64:
137         if (type == from && (from == DataType::Type::kInt8 ||
138                              from == DataType::Type::kInt16 ||
139                              from == DataType::Type::kInt32)) {
140           *operand = conv;
141           return true;
142         }
143         return false;
144       case DataType::Type::kInt16:
145         return type == DataType::Type::kUint16 &&
146                from == DataType::Type::kUint16 &&
147                IsZeroExtensionAndGet(instruction->InputAt(0), type, /*out*/ operand);
148       default:
149         return false;
150     }
151   }
152   return false;
153 }
154 
155 // Detect a zero extension in instruction from the given type.
156 // Returns the promoted operand on success.
IsZeroExtensionAndGet(HInstruction * instruction,DataType::Type type,HInstruction ** operand)157 static bool IsZeroExtensionAndGet(HInstruction* instruction,
158                                   DataType::Type type,
159                                   /*out*/ HInstruction** operand) {
160   // Accept any already wider constant that would be handled properly by zero
161   // extension when represented in the *width* of the given narrower data type
162   // (the fact that Int8/Int16 normally sign extend does not matter here).
163   int64_t value = 0;
164   if (IsInt64AndGet(instruction, /*out*/ &value)) {
165     switch (type) {
166       case DataType::Type::kUint8:
167       case DataType::Type::kInt8:
168         if (IsUint<8>(value)) {
169           *operand = instruction;
170           return true;
171         }
172         return false;
173       case DataType::Type::kUint16:
174       case DataType::Type::kInt16:
175         if (IsUint<16>(value)) {
176           *operand = instruction;
177           return true;
178         }
179         return false;
180       default:
181         return false;
182     }
183   }
184   // An implicit widening conversion of any unsigned expression zero-extends.
185   if (instruction->GetType() == type) {
186     switch (type) {
187       case DataType::Type::kUint8:
188       case DataType::Type::kUint16:
189         *operand = instruction;
190         return true;
191       default:
192         return false;
193     }
194   }
195   // An explicit widening conversion of an unsigned expression zero-extends.
196   if (instruction->IsTypeConversion()) {
197     HInstruction* conv = instruction->InputAt(0);
198     DataType::Type from = conv->GetType();
199     switch (instruction->GetType()) {
200       case DataType::Type::kInt32:
201       case DataType::Type::kInt64:
202         if (type == from && from == DataType::Type::kUint16) {
203           *operand = conv;
204           return true;
205         }
206         return false;
207       case DataType::Type::kUint16:
208         return type == DataType::Type::kInt16 &&
209                from == DataType::Type::kInt16 &&
210                IsSignExtensionAndGet(instruction->InputAt(0), type, /*out*/ operand);
211       default:
212         return false;
213     }
214   }
215   return false;
216 }
217 
218 // Detect situations with same-extension narrower operands.
219 // Returns true on success and sets is_unsigned accordingly.
IsNarrowerOperands(HInstruction * a,HInstruction * b,DataType::Type type,HInstruction ** r,HInstruction ** s,bool * is_unsigned)220 static bool IsNarrowerOperands(HInstruction* a,
221                                HInstruction* b,
222                                DataType::Type type,
223                                /*out*/ HInstruction** r,
224                                /*out*/ HInstruction** s,
225                                /*out*/ bool* is_unsigned) {
226   DCHECK(a != nullptr && b != nullptr);
227   // Look for a matching sign extension.
228   DataType::Type stype = HVecOperation::ToSignedType(type);
229   if (IsSignExtensionAndGet(a, stype, r) && IsSignExtensionAndGet(b, stype, s)) {
230     *is_unsigned = false;
231     return true;
232   }
233   // Look for a matching zero extension.
234   DataType::Type utype = HVecOperation::ToUnsignedType(type);
235   if (IsZeroExtensionAndGet(a, utype, r) && IsZeroExtensionAndGet(b, utype, s)) {
236     *is_unsigned = true;
237     return true;
238   }
239   return false;
240 }
241 
242 // As above, single operand.
IsNarrowerOperand(HInstruction * a,DataType::Type type,HInstruction ** r,bool * is_unsigned)243 static bool IsNarrowerOperand(HInstruction* a,
244                               DataType::Type type,
245                               /*out*/ HInstruction** r,
246                               /*out*/ bool* is_unsigned) {
247   DCHECK(a != nullptr);
248   // Look for a matching sign extension.
249   DataType::Type stype = HVecOperation::ToSignedType(type);
250   if (IsSignExtensionAndGet(a, stype, r)) {
251     *is_unsigned = false;
252     return true;
253   }
254   // Look for a matching zero extension.
255   DataType::Type utype = HVecOperation::ToUnsignedType(type);
256   if (IsZeroExtensionAndGet(a, utype, r)) {
257     *is_unsigned = true;
258     return true;
259   }
260   return false;
261 }
262 
263 // Compute relative vector length based on type difference.
GetOtherVL(DataType::Type other_type,DataType::Type vector_type,uint32_t vl)264 static uint32_t GetOtherVL(DataType::Type other_type, DataType::Type vector_type, uint32_t vl) {
265   DCHECK(DataType::IsIntegralType(other_type));
266   DCHECK(DataType::IsIntegralType(vector_type));
267   DCHECK_GE(DataType::SizeShift(other_type), DataType::SizeShift(vector_type));
268   return vl >> (DataType::SizeShift(other_type) - DataType::SizeShift(vector_type));
269 }
270 
271 // Detect up to two added operands a and b and an acccumulated constant c.
IsAddConst(HInstruction * instruction,HInstruction ** a,HInstruction ** b,int64_t * c,int32_t depth=8)272 static bool IsAddConst(HInstruction* instruction,
273                        /*out*/ HInstruction** a,
274                        /*out*/ HInstruction** b,
275                        /*out*/ int64_t* c,
276                        int32_t depth = 8) {  // don't search too deep
277   int64_t value = 0;
278   // Enter add/sub while still within reasonable depth.
279   if (depth > 0) {
280     if (instruction->IsAdd()) {
281       return IsAddConst(instruction->InputAt(0), a, b, c, depth - 1) &&
282              IsAddConst(instruction->InputAt(1), a, b, c, depth - 1);
283     } else if (instruction->IsSub() &&
284                IsInt64AndGet(instruction->InputAt(1), &value)) {
285       *c -= value;
286       return IsAddConst(instruction->InputAt(0), a, b, c, depth - 1);
287     }
288   }
289   // Otherwise, deal with leaf nodes.
290   if (IsInt64AndGet(instruction, &value)) {
291     *c += value;
292     return true;
293   } else if (*a == nullptr) {
294     *a = instruction;
295     return true;
296   } else if (*b == nullptr) {
297     *b = instruction;
298     return true;
299   }
300   return false;  // too many operands
301 }
302 
303 // Detect a + b + c with optional constant c.
IsAddConst2(HGraph * graph,HInstruction * instruction,HInstruction ** a,HInstruction ** b,int64_t * c)304 static bool IsAddConst2(HGraph* graph,
305                         HInstruction* instruction,
306                         /*out*/ HInstruction** a,
307                         /*out*/ HInstruction** b,
308                         /*out*/ int64_t* c) {
309   // We want an actual add/sub and not the trivial case where {b: 0, c: 0}.
310   if (IsAddOrSub(instruction) && IsAddConst(instruction, a, b, c) && *a != nullptr) {
311     if (*b == nullptr) {
312       // Constant is usually already present, unless accumulated.
313       *b = graph->GetConstant(instruction->GetType(), (*c));
314       *c = 0;
315     }
316     return true;
317   }
318   return false;
319 }
320 
321 // Detect a direct a - b or a hidden a - (-c).
IsSubConst2(HGraph * graph,HInstruction * instruction,HInstruction ** a,HInstruction ** b)322 static bool IsSubConst2(HGraph* graph,
323                         HInstruction* instruction,
324                         /*out*/ HInstruction** a,
325                         /*out*/ HInstruction** b) {
326   int64_t c = 0;
327   if (instruction->IsSub()) {
328     *a = instruction->InputAt(0);
329     *b = instruction->InputAt(1);
330     return true;
331   } else if (IsAddConst(instruction, a, b, &c) && *a != nullptr && *b == nullptr) {
332     // Constant for the hidden subtraction.
333     *b = graph->GetConstant(instruction->GetType(), -c);
334     return true;
335   }
336   return false;
337 }
338 
339 // Detect reductions of the following forms,
340 //   x = x_phi + ..
341 //   x = x_phi - ..
HasReductionFormat(HInstruction * reduction,HInstruction * phi)342 static bool HasReductionFormat(HInstruction* reduction, HInstruction* phi) {
343   if (reduction->IsAdd()) {
344     return (reduction->InputAt(0) == phi && reduction->InputAt(1) != phi) ||
345            (reduction->InputAt(0) != phi && reduction->InputAt(1) == phi);
346   } else if (reduction->IsSub()) {
347     return (reduction->InputAt(0) == phi && reduction->InputAt(1) != phi);
348   }
349   return false;
350 }
351 
352 // Translates vector operation to reduction kind.
GetReductionKind(HVecOperation * reduction)353 static HVecReduce::ReductionKind GetReductionKind(HVecOperation* reduction) {
354   if (reduction->IsVecAdd()  ||
355       reduction->IsVecSub() ||
356       reduction->IsVecSADAccumulate() ||
357       reduction->IsVecDotProd()) {
358     return HVecReduce::kSum;
359   }
360   LOG(FATAL) << "Unsupported SIMD reduction " << reduction->GetId();
361   UNREACHABLE();
362 }
363 
364 // Test vector restrictions.
HasVectorRestrictions(uint64_t restrictions,uint64_t tested)365 static bool HasVectorRestrictions(uint64_t restrictions, uint64_t tested) {
366   return (restrictions & tested) != 0;
367 }
368 
369 // Insert an instruction at the end of the block, with safe checks.
Insert(HBasicBlock * block,HInstruction * instruction)370 inline HInstruction* Insert(HBasicBlock* block, HInstruction* instruction) {
371   DCHECK(block != nullptr);
372   DCHECK(instruction != nullptr);
373   block->InsertInstructionBefore(instruction, block->GetLastInstruction());
374   return instruction;
375 }
376 
377 // Check that instructions from the induction sets are fully removed: have no uses
378 // and no other instructions use them.
CheckInductionSetFullyRemoved(ScopedArenaSet<HInstruction * > * iset)379 static bool CheckInductionSetFullyRemoved(ScopedArenaSet<HInstruction*>* iset) {
380   for (HInstruction* instr : *iset) {
381     if (instr->GetBlock() != nullptr ||
382         !instr->GetUses().empty() ||
383         !instr->GetEnvUses().empty() ||
384         HasEnvironmentUsedByOthers(instr)) {
385       return false;
386     }
387   }
388   return true;
389 }
390 
391 // Tries to statically evaluate condition of the specified "HIf" for other condition checks.
TryToEvaluateIfCondition(HIf * instruction,HGraph * graph)392 static void TryToEvaluateIfCondition(HIf* instruction, HGraph* graph) {
393   HInstruction* cond = instruction->InputAt(0);
394 
395   // If a condition 'cond' is evaluated in an HIf instruction then in the successors of the
396   // IF_BLOCK we statically know the value of the condition 'cond' (TRUE in TRUE_SUCC, FALSE in
397   // FALSE_SUCC). Using that we can replace another evaluation (use) EVAL of the same 'cond'
398   // with TRUE value (FALSE value) if every path from the ENTRY_BLOCK to EVAL_BLOCK contains the
399   // edge HIF_BLOCK->TRUE_SUCC (HIF_BLOCK->FALSE_SUCC).
400   //     if (cond) {               if(cond) {
401   //       if (cond) {}              if (1) {}
402   //     } else {        =======>  } else {
403   //       if (cond) {}              if (0) {}
404   //     }                         }
405   if (!cond->IsConstant()) {
406     HBasicBlock* true_succ = instruction->IfTrueSuccessor();
407     HBasicBlock* false_succ = instruction->IfFalseSuccessor();
408 
409     DCHECK_EQ(true_succ->GetPredecessors().size(), 1u);
410     DCHECK_EQ(false_succ->GetPredecessors().size(), 1u);
411 
412     const HUseList<HInstruction*>& uses = cond->GetUses();
413     for (auto it = uses.begin(), end = uses.end(); it != end; /* ++it below */) {
414       HInstruction* user = it->GetUser();
415       size_t index = it->GetIndex();
416       HBasicBlock* user_block = user->GetBlock();
417       // Increment `it` now because `*it` may disappear thanks to user->ReplaceInput().
418       ++it;
419       if (true_succ->Dominates(user_block)) {
420         user->ReplaceInput(graph->GetIntConstant(1), index);
421       } else if (false_succ->Dominates(user_block)) {
422         user->ReplaceInput(graph->GetIntConstant(0), index);
423       }
424     }
425   }
426 }
427 
428 // Peel the first 'count' iterations of the loop.
PeelByCount(HLoopInformation * loop_info,int count,InductionVarRange * induction_range)429 static void PeelByCount(HLoopInformation* loop_info,
430                         int count,
431                         InductionVarRange* induction_range) {
432   for (int i = 0; i < count; i++) {
433     // Perform peeling.
434     LoopClonerSimpleHelper helper(loop_info, induction_range);
435     helper.DoPeeling();
436   }
437 }
438 
439 // Returns the narrower type out of instructions a and b types.
GetNarrowerType(HInstruction * a,HInstruction * b)440 static DataType::Type GetNarrowerType(HInstruction* a, HInstruction* b) {
441   DataType::Type type = a->GetType();
442   if (DataType::Size(b->GetType()) < DataType::Size(type)) {
443     type = b->GetType();
444   }
445   if (a->IsTypeConversion() &&
446       DataType::Size(a->InputAt(0)->GetType()) < DataType::Size(type)) {
447     type = a->InputAt(0)->GetType();
448   }
449   if (b->IsTypeConversion() &&
450       DataType::Size(b->InputAt(0)->GetType()) < DataType::Size(type)) {
451     type = b->InputAt(0)->GetType();
452   }
453   return type;
454 }
455 
456 // Returns whether the loop is of a diamond structure:
457 //
458 //                header <----------------+
459 //                  |                     |
460 //             diamond_hif                |
461 //                /   \                   |
462 //     diamond_true  diamond_false        |
463 //                \   /                   |
464 //              back_edge                 |
465 //                  |                     |
466 //                  +---------------------+
HasLoopDiamondStructure(HLoopInformation * loop_info)467 static bool HasLoopDiamondStructure(HLoopInformation* loop_info) {
468   HBasicBlock* header = loop_info->GetHeader();
469   if (loop_info->NumberOfBackEdges() != 1 || header->GetSuccessors().size() != 2) {
470     return false;
471   }
472   HBasicBlock* header_succ_0 = header->GetSuccessors()[0];
473   HBasicBlock* header_succ_1 = header->GetSuccessors()[1];
474   HBasicBlock* diamond_top = loop_info->Contains(*header_succ_0) ?
475                                   header_succ_0 :
476                                   header_succ_1;
477   if (!diamond_top->GetLastInstruction()->IsIf()) {
478     return false;
479   }
480 
481   HIf* diamond_hif = diamond_top->GetLastInstruction()->AsIf();
482   HBasicBlock* diamond_true = diamond_hif->IfTrueSuccessor();
483   HBasicBlock* diamond_false = diamond_hif->IfFalseSuccessor();
484 
485   if (diamond_true->GetSuccessors().size() != 1 || diamond_false->GetSuccessors().size() != 1) {
486     return false;
487   }
488 
489   HBasicBlock* back_edge = diamond_true->GetSingleSuccessor();
490   if (back_edge != diamond_false->GetSingleSuccessor() ||
491       back_edge != loop_info->GetBackEdges()[0]) {
492     return false;
493   }
494 
495   DCHECK_EQ(loop_info->GetBlocks().NumSetBits(), 5u);
496   return true;
497 }
498 
IsPredicatedLoopControlFlowSupported(HLoopInformation * loop_info)499 static bool IsPredicatedLoopControlFlowSupported(HLoopInformation* loop_info) {
500   size_t num_of_blocks = loop_info->GetBlocks().NumSetBits();
501   return num_of_blocks == 2 || HasLoopDiamondStructure(loop_info);
502 }
503 
504 //
505 // Public methods.
506 //
507 
HLoopOptimization(HGraph * graph,const CodeGenerator & codegen,HInductionVarAnalysis * induction_analysis,OptimizingCompilerStats * stats,const char * name)508 HLoopOptimization::HLoopOptimization(HGraph* graph,
509                                      const CodeGenerator& codegen,
510                                      HInductionVarAnalysis* induction_analysis,
511                                      OptimizingCompilerStats* stats,
512                                      const char* name)
513     : HOptimization(graph, name, stats),
514       compiler_options_(&codegen.GetCompilerOptions()),
515       simd_register_size_(codegen.GetSIMDRegisterWidth()),
516       induction_range_(induction_analysis),
517       loop_allocator_(nullptr),
518       global_allocator_(graph_->GetAllocator()),
519       top_loop_(nullptr),
520       last_loop_(nullptr),
521       iset_(nullptr),
522       reductions_(nullptr),
523       simplified_(false),
524       predicated_vectorization_mode_(codegen.SupportsPredicatedSIMD()),
525       vector_length_(0),
526       vector_refs_(nullptr),
527       vector_static_peeling_factor_(0),
528       vector_dynamic_peeling_candidate_(nullptr),
529       vector_runtime_test_a_(nullptr),
530       vector_runtime_test_b_(nullptr),
531       vector_map_(nullptr),
532       vector_permanent_map_(nullptr),
533       vector_external_set_(nullptr),
534       predicate_info_map_(nullptr),
535       synthesis_mode_(LoopSynthesisMode::kSequential),
536       vector_preheader_(nullptr),
537       vector_header_(nullptr),
538       vector_body_(nullptr),
539       vector_index_(nullptr),
540       arch_loop_helper_(ArchNoOptsLoopHelper::Create(codegen, global_allocator_)) {}
541 
Run()542 bool HLoopOptimization::Run() {
543   // Skip if there is no loop or the graph has irreducible loops.
544   // TODO: make this less of a sledgehammer.
545   if (!graph_->HasLoops() || graph_->HasIrreducibleLoops()) {
546     return false;
547   }
548 
549   // Phase-local allocator.
550   ScopedArenaAllocator allocator(graph_->GetArenaStack());
551   loop_allocator_ = &allocator;
552 
553   // Perform loop optimizations.
554   const bool did_loop_opt = LocalRun();
555   if (top_loop_ == nullptr) {
556     graph_->SetHasLoops(false);  // no more loops
557   }
558 
559   // Detach allocator.
560   loop_allocator_ = nullptr;
561 
562   return did_loop_opt;
563 }
564 
565 //
566 // Loop setup and traversal.
567 //
568 
LocalRun()569 bool HLoopOptimization::LocalRun() {
570   // Build the linear order using the phase-local allocator. This step enables building
571   // a loop hierarchy that properly reflects the outer-inner and previous-next relation.
572   ScopedArenaVector<HBasicBlock*> linear_order(loop_allocator_->Adapter(kArenaAllocLinearOrder));
573   LinearizeGraph(graph_, &linear_order);
574 
575   // Build the loop hierarchy.
576   for (HBasicBlock* block : linear_order) {
577     if (block->IsLoopHeader()) {
578       AddLoop(block->GetLoopInformation());
579     }
580   }
581   DCHECK(top_loop_ != nullptr);
582 
583   // Traverse the loop hierarchy inner-to-outer and optimize. Traversal can use
584   // temporary data structures using the phase-local allocator. All new HIR
585   // should use the global allocator.
586   ScopedArenaSet<HInstruction*> iset(loop_allocator_->Adapter(kArenaAllocLoopOptimization));
587   ScopedArenaSafeMap<HInstruction*, HInstruction*> reds(
588       std::less<HInstruction*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
589   ScopedArenaSet<ArrayReference> refs(loop_allocator_->Adapter(kArenaAllocLoopOptimization));
590   ScopedArenaSafeMap<HInstruction*, HInstruction*> map(
591       std::less<HInstruction*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
592   ScopedArenaSafeMap<HInstruction*, HInstruction*> perm(
593       std::less<HInstruction*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
594   ScopedArenaSet<HInstruction*> ext_set(loop_allocator_->Adapter(kArenaAllocLoopOptimization));
595   ScopedArenaSafeMap<HBasicBlock*, BlockPredicateInfo*> pred(
596       std::less<HBasicBlock*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
597   // Attach.
598   iset_ = &iset;
599   reductions_ = &reds;
600   vector_refs_ = &refs;
601   vector_map_ = &map;
602   vector_permanent_map_ = &perm;
603   vector_external_set_ = &ext_set;
604   predicate_info_map_ = &pred;
605   // Traverse.
606   const bool did_loop_opt = TraverseLoopsInnerToOuter(top_loop_);
607   // Detach.
608   iset_ = nullptr;
609   reductions_ = nullptr;
610   vector_refs_ = nullptr;
611   vector_map_ = nullptr;
612   vector_permanent_map_ = nullptr;
613   vector_external_set_ = nullptr;
614   predicate_info_map_ = nullptr;
615 
616   return did_loop_opt;
617 }
618 
AddLoop(HLoopInformation * loop_info)619 void HLoopOptimization::AddLoop(HLoopInformation* loop_info) {
620   DCHECK(loop_info != nullptr);
621   LoopNode* node = new (loop_allocator_) LoopNode(loop_info);
622   if (last_loop_ == nullptr) {
623     // First loop.
624     DCHECK(top_loop_ == nullptr);
625     last_loop_ = top_loop_ = node;
626   } else if (loop_info->IsIn(*last_loop_->loop_info)) {
627     // Inner loop.
628     node->outer = last_loop_;
629     DCHECK(last_loop_->inner == nullptr);
630     last_loop_ = last_loop_->inner = node;
631   } else {
632     // Subsequent loop.
633     while (last_loop_->outer != nullptr && !loop_info->IsIn(*last_loop_->outer->loop_info)) {
634       last_loop_ = last_loop_->outer;
635     }
636     node->outer = last_loop_->outer;
637     node->previous = last_loop_;
638     DCHECK(last_loop_->next == nullptr);
639     last_loop_ = last_loop_->next = node;
640   }
641 }
642 
RemoveLoop(LoopNode * node)643 void HLoopOptimization::RemoveLoop(LoopNode* node) {
644   DCHECK(node != nullptr);
645   DCHECK(node->inner == nullptr);
646   if (node->previous != nullptr) {
647     // Within sequence.
648     node->previous->next = node->next;
649     if (node->next != nullptr) {
650       node->next->previous = node->previous;
651     }
652   } else {
653     // First of sequence.
654     if (node->outer != nullptr) {
655       node->outer->inner = node->next;
656     } else {
657       top_loop_ = node->next;
658     }
659     if (node->next != nullptr) {
660       node->next->outer = node->outer;
661       node->next->previous = nullptr;
662     }
663   }
664 }
665 
TraverseLoopsInnerToOuter(LoopNode * node)666 bool HLoopOptimization::TraverseLoopsInnerToOuter(LoopNode* node) {
667   bool changed = false;
668   for ( ; node != nullptr; node = node->next) {
669     // Visit inner loops first. Recompute induction information for this
670     // loop if the induction of any inner loop has changed.
671     if (TraverseLoopsInnerToOuter(node->inner)) {
672       induction_range_.ReVisit(node->loop_info);
673       changed = true;
674     }
675 
676     CalculateAndSetTryCatchKind(node);
677     if (node->try_catch_kind == LoopNode::TryCatchKind::kHasTryCatch) {
678       // The current optimizations assume that the loops do not contain try/catches.
679       // TODO(solanes, 227283906): Assess if we can modify them to work with try/catches.
680       continue;
681     }
682 
683     DCHECK(node->try_catch_kind == LoopNode::TryCatchKind::kNoTryCatch)
684         << "kind: " << static_cast<int>(node->try_catch_kind)
685         << ". LoopOptimization requires the loops to not have try catches.";
686 
687     // Repeat simplifications in the loop-body until no more changes occur.
688     // Note that since each simplification consists of eliminating code (without
689     // introducing new code), this process is always finite.
690     do {
691       simplified_ = false;
692       SimplifyInduction(node);
693       SimplifyBlocks(node);
694       changed = simplified_ || changed;
695     } while (simplified_);
696     // Optimize inner loop.
697     if (node->inner == nullptr) {
698       changed = OptimizeInnerLoop(node) || changed;
699     }
700   }
701   return changed;
702 }
703 
CalculateAndSetTryCatchKind(LoopNode * node)704 void HLoopOptimization::CalculateAndSetTryCatchKind(LoopNode* node) {
705   DCHECK(node != nullptr);
706   DCHECK(node->try_catch_kind == LoopNode::TryCatchKind::kUnknown)
707       << "kind: " << static_cast<int>(node->try_catch_kind)
708       << ". SetTryCatchKind should be called only once per LoopNode.";
709 
710   // If a inner loop has a try catch, then the outer loop has one too (as it contains `inner`).
711   // Knowing this, we could skip iterating through all of the outer loop's parents with a simple
712   // check.
713   for (LoopNode* inner = node->inner; inner != nullptr; inner = inner->next) {
714     DCHECK(inner->try_catch_kind != LoopNode::TryCatchKind::kUnknown)
715         << "kind: " << static_cast<int>(inner->try_catch_kind)
716         << ". Should have updated the inner loop before the outer loop.";
717 
718     if (inner->try_catch_kind == LoopNode::TryCatchKind::kHasTryCatch) {
719       node->try_catch_kind = LoopNode::TryCatchKind::kHasTryCatch;
720       return;
721     }
722   }
723 
724   for (HBlocksInLoopIterator it_loop(*node->loop_info); !it_loop.Done(); it_loop.Advance()) {
725     HBasicBlock* block = it_loop.Current();
726     if (block->GetTryCatchInformation() != nullptr) {
727       node->try_catch_kind = LoopNode::TryCatchKind::kHasTryCatch;
728       return;
729     }
730   }
731 
732   node->try_catch_kind = LoopNode::TryCatchKind::kNoTryCatch;
733 }
734 
735 //
736 // This optimization applies to loops with plain simple operations
737 // (I.e. no calls to java code or runtime) with a known small trip_count * instr_count
738 // value.
739 //
TryToRemoveSuspendCheckFromLoopHeader(LoopAnalysisInfo * analysis_info,bool generate_code)740 bool HLoopOptimization::TryToRemoveSuspendCheckFromLoopHeader(LoopAnalysisInfo* analysis_info,
741                                                               bool generate_code) {
742   if (!graph_->SuspendChecksAreAllowedToNoOp()) {
743     return false;
744   }
745 
746   int64_t trip_count = analysis_info->GetTripCount();
747 
748   if (trip_count == LoopAnalysisInfo::kUnknownTripCount) {
749     return false;
750   }
751 
752   int64_t instruction_count = analysis_info->GetNumberOfInstructions();
753   int64_t total_instruction_count = trip_count * instruction_count;
754 
755   // The inclusion of the HasInstructionsPreventingScalarOpts() prevents this
756   // optimization from being applied to loops that have calls.
757   bool can_optimize =
758       total_instruction_count <= HLoopOptimization::kMaxTotalInstRemoveSuspendCheck &&
759       !analysis_info->HasInstructionsPreventingScalarOpts();
760 
761   if (!can_optimize) {
762     return false;
763   }
764 
765   // If we should do the optimization, disable codegen for the SuspendCheck.
766   if (generate_code) {
767     HLoopInformation* loop_info = analysis_info->GetLoopInfo();
768     HBasicBlock* header = loop_info->GetHeader();
769     HSuspendCheck* instruction = header->GetLoopInformation()->GetSuspendCheck();
770     // As other optimizations depend on SuspendCheck
771     // (e.g: CHAGuardVisitor::HoistGuard), disable its codegen instead of
772     // removing the SuspendCheck instruction.
773     instruction->SetIsNoOp(true);
774   }
775 
776   return true;
777 }
778 
779 //
780 // Optimization.
781 //
782 
SimplifyInduction(LoopNode * node)783 void HLoopOptimization::SimplifyInduction(LoopNode* node) {
784   HBasicBlock* header = node->loop_info->GetHeader();
785   HBasicBlock* preheader = node->loop_info->GetPreHeader();
786   // Scan the phis in the header to find opportunities to simplify an induction
787   // cycle that is only used outside the loop. Replace these uses, if any, with
788   // the last value and remove the induction cycle.
789   // Examples: for (int i = 0; x != null;   i++) { .... no i .... }
790   //           for (int i = 0; i < 10; i++, k++) { .... no k .... } return k;
791   for (HInstructionIterator it(header->GetPhis()); !it.Done(); it.Advance()) {
792     HPhi* phi = it.Current()->AsPhi();
793     if (TrySetPhiInduction(phi, /*restrict_uses*/ true) &&
794         TryAssignLastValue(node->loop_info, phi, preheader, /*collect_loop_uses*/ false)) {
795       // Note that it's ok to have replaced uses after the loop with the last value, without
796       // being able to remove the cycle. Environment uses (which are the reason we may not be
797       // able to remove the cycle) within the loop will still hold the right value. We must
798       // have tried first, however, to replace outside uses.
799       if (CanRemoveCycle()) {
800         simplified_ = true;
801         for (HInstruction* i : *iset_) {
802           RemoveFromCycle(i);
803         }
804         DCHECK(CheckInductionSetFullyRemoved(iset_));
805       }
806     }
807   }
808 }
809 
SimplifyBlocks(LoopNode * node)810 void HLoopOptimization::SimplifyBlocks(LoopNode* node) {
811   // Iterate over all basic blocks in the loop-body.
812   for (HBlocksInLoopIterator it(*node->loop_info); !it.Done(); it.Advance()) {
813     HBasicBlock* block = it.Current();
814     // Remove dead instructions from the loop-body.
815     RemoveDeadInstructions(block->GetPhis());
816     RemoveDeadInstructions(block->GetInstructions());
817     // Remove trivial control flow blocks from the loop-body.
818     if (block->GetPredecessors().size() == 1 &&
819         block->GetSuccessors().size() == 1 &&
820         block->GetSingleSuccessor()->GetPredecessors().size() == 1) {
821       simplified_ = true;
822       block->MergeWith(block->GetSingleSuccessor());
823     } else if (block->GetSuccessors().size() == 2) {
824       // Trivial if block can be bypassed to either branch.
825       HBasicBlock* succ0 = block->GetSuccessors()[0];
826       HBasicBlock* succ1 = block->GetSuccessors()[1];
827       HBasicBlock* meet0 = nullptr;
828       HBasicBlock* meet1 = nullptr;
829       if (succ0 != succ1 &&
830           IsGotoBlock(succ0, &meet0) &&
831           IsGotoBlock(succ1, &meet1) &&
832           meet0 == meet1 &&  // meets again
833           meet0 != block &&  // no self-loop
834           meet0->GetPhis().IsEmpty()) {  // not used for merging
835         simplified_ = true;
836         succ0->DisconnectAndDelete();
837         if (block->Dominates(meet0)) {
838           block->RemoveDominatedBlock(meet0);
839           succ1->AddDominatedBlock(meet0);
840           meet0->SetDominator(succ1);
841         }
842       }
843     }
844   }
845 }
846 
847 // Checks whether the loop has exit structure suitable for InnerLoopFinite optimization:
848 //  - has single loop exit.
849 //  - the exit block has only single predecessor - a block inside the loop.
850 //
851 // In that case returns single exit basic block (outside the loop); otherwise nullptr.
GetInnerLoopFiniteSingleExit(HLoopInformation * loop_info)852 static HBasicBlock* GetInnerLoopFiniteSingleExit(HLoopInformation* loop_info) {
853   HBasicBlock* exit = nullptr;
854   for (HBlocksInLoopIterator block_it(*loop_info);
855        !block_it.Done();
856        block_it.Advance()) {
857     HBasicBlock* block = block_it.Current();
858 
859     // Check whether one of the successor is loop exit.
860     for (HBasicBlock* successor : block->GetSuccessors()) {
861       if (!loop_info->Contains(*successor)) {
862         if (exit != nullptr) {
863           // The loop has more than one exit.
864           return nullptr;
865         }
866         exit = successor;
867 
868         // Ensure exit can only be reached by exiting loop.
869         if (successor->GetPredecessors().size() != 1) {
870           return nullptr;
871         }
872       }
873     }
874   }
875   return exit;
876 }
877 
TryOptimizeInnerLoopFinite(LoopNode * node)878 bool HLoopOptimization::TryOptimizeInnerLoopFinite(LoopNode* node) {
879   HBasicBlock* header = node->loop_info->GetHeader();
880   HBasicBlock* preheader = node->loop_info->GetPreHeader();
881   // Ensure loop header logic is finite.
882   int64_t trip_count = 0;
883   if (!induction_range_.IsFinite(node->loop_info, &trip_count)) {
884     return false;
885   }
886   // Check loop exits.
887   HBasicBlock* exit = GetInnerLoopFiniteSingleExit(node->loop_info);
888   if (exit == nullptr) {
889     return false;
890   }
891 
892   HBasicBlock* body = (header->GetSuccessors()[0] == exit)
893     ? header->GetSuccessors()[1]
894     : header->GetSuccessors()[0];
895   // Detect either an empty loop (no side effects other than plain iteration) or
896   // a trivial loop (just iterating once). Replace subsequent index uses, if any,
897   // with the last value and remove the loop, possibly after unrolling its body.
898   HPhi* main_phi = nullptr;
899   size_t num_of_blocks = header->GetLoopInformation()->GetBlocks().NumSetBits();
900 
901   if (num_of_blocks == 2 && TrySetSimpleLoopHeader(header, &main_phi)) {
902     bool is_empty = IsEmptyBody(body);
903     if (reductions_->empty() &&  // TODO: possible with some effort
904         (is_empty || trip_count == 1) &&
905         TryAssignLastValue(node->loop_info, main_phi, preheader, /*collect_loop_uses*/ true)) {
906       if (!is_empty) {
907         // Unroll the loop-body, which sees initial value of the index.
908         main_phi->ReplaceWith(main_phi->InputAt(0));
909         preheader->MergeInstructionsWith(body);
910       }
911       body->DisconnectAndDelete();
912       exit->RemovePredecessor(header);
913       header->RemoveSuccessor(exit);
914       header->RemoveDominatedBlock(exit);
915       header->DisconnectAndDelete();
916       preheader->AddSuccessor(exit);
917       preheader->AddInstruction(new (global_allocator_) HGoto());
918       preheader->AddDominatedBlock(exit);
919       exit->SetDominator(preheader);
920       RemoveLoop(node);  // update hierarchy
921       return true;
922     }
923   }
924   // Vectorize loop, if possible and valid.
925   if (!kEnableVectorization ||
926       // Disable vectorization for debuggable graphs: this is a workaround for the bug
927       // in 'GenerateNewLoop' which caused the SuspendCheck environment to be invalid.
928       // TODO: b/138601207, investigate other possible cases with wrong environment values and
929       // possibly switch back vectorization on for debuggable graphs.
930       graph_->IsDebuggable()) {
931     return false;
932   }
933 
934   if (kForceTryPredicatedSIMD && IsInPredicatedVectorizationMode()) {
935     return TryVectorizePredicated(node, body, exit, main_phi, trip_count);
936   } else {
937     return TryVectorizedTraditional(node, body, exit, main_phi, trip_count);
938   }
939 }
940 
TryVectorizePredicated(LoopNode * node,HBasicBlock * body,HBasicBlock * exit,HPhi * main_phi,int64_t trip_count)941 bool HLoopOptimization::TryVectorizePredicated(LoopNode* node,
942                                                HBasicBlock* body,
943                                                HBasicBlock* exit,
944                                                HPhi* main_phi,
945                                                int64_t trip_count) {
946   if (!IsPredicatedLoopControlFlowSupported(node->loop_info) ||
947       !ShouldVectorizeCommon(node, main_phi, trip_count)) {
948     return false;
949   }
950 
951   // Currently we can only generate cleanup loops for loops with 2 basic block.
952   //
953   // TODO: Support array disambiguation tests for CF loops.
954   if (NeedsArrayRefsDisambiguationTest() &&
955       node->loop_info->GetBlocks().NumSetBits() != 2) {
956     return false;
957   }
958 
959   VectorizePredicated(node, body, exit);
960   MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorized);
961   graph_->SetHasPredicatedSIMD(true);  // flag SIMD usage
962   return true;
963 }
964 
TryVectorizedTraditional(LoopNode * node,HBasicBlock * body,HBasicBlock * exit,HPhi * main_phi,int64_t trip_count)965 bool HLoopOptimization::TryVectorizedTraditional(LoopNode* node,
966                                                  HBasicBlock* body,
967                                                  HBasicBlock* exit,
968                                                  HPhi* main_phi,
969                                                  int64_t trip_count) {
970   HBasicBlock* header = node->loop_info->GetHeader();
971   size_t num_of_blocks = header->GetLoopInformation()->GetBlocks().NumSetBits();
972 
973   if (num_of_blocks != 2 || !ShouldVectorizeCommon(node, main_phi, trip_count)) {
974     return false;
975   }
976   VectorizeTraditional(node, body, exit, trip_count);
977   MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorized);
978   graph_->SetHasTraditionalSIMD(true);  // flag SIMD usage
979   return true;
980 }
981 
OptimizeInnerLoop(LoopNode * node)982 bool HLoopOptimization::OptimizeInnerLoop(LoopNode* node) {
983   return TryOptimizeInnerLoopFinite(node) || TryLoopScalarOpts(node);
984 }
985 
986 //
987 // Scalar loop peeling and unrolling: generic part methods.
988 //
989 
TryUnrollingForBranchPenaltyReduction(LoopAnalysisInfo * analysis_info,bool generate_code)990 bool HLoopOptimization::TryUnrollingForBranchPenaltyReduction(LoopAnalysisInfo* analysis_info,
991                                                               bool generate_code) {
992   if (analysis_info->GetNumberOfExits() > 1) {
993     return false;
994   }
995 
996   uint32_t unrolling_factor = arch_loop_helper_->GetScalarUnrollingFactor(analysis_info);
997   if (unrolling_factor == LoopAnalysisInfo::kNoUnrollingFactor) {
998     return false;
999   }
1000 
1001   if (generate_code) {
1002     // TODO: support other unrolling factors.
1003     DCHECK_EQ(unrolling_factor, 2u);
1004 
1005     // Perform unrolling.
1006     HLoopInformation* loop_info = analysis_info->GetLoopInfo();
1007     LoopClonerSimpleHelper helper(loop_info, &induction_range_);
1008     helper.DoUnrolling();
1009 
1010     // Remove the redundant loop check after unrolling.
1011     HIf* copy_hif =
1012         helper.GetBasicBlockMap()->Get(loop_info->GetHeader())->GetLastInstruction()->AsIf();
1013     int32_t constant = loop_info->Contains(*copy_hif->IfTrueSuccessor()) ? 1 : 0;
1014     copy_hif->ReplaceInput(graph_->GetIntConstant(constant), 0u);
1015   }
1016   return true;
1017 }
1018 
TryPeelingForLoopInvariantExitsElimination(LoopAnalysisInfo * analysis_info,bool generate_code)1019 bool HLoopOptimization::TryPeelingForLoopInvariantExitsElimination(LoopAnalysisInfo* analysis_info,
1020                                                                    bool generate_code) {
1021   HLoopInformation* loop_info = analysis_info->GetLoopInfo();
1022   if (!arch_loop_helper_->IsLoopPeelingEnabled()) {
1023     return false;
1024   }
1025 
1026   if (analysis_info->GetNumberOfInvariantExits() == 0) {
1027     return false;
1028   }
1029 
1030   if (generate_code) {
1031     // Perform peeling.
1032     LoopClonerSimpleHelper helper(loop_info, &induction_range_);
1033     helper.DoPeeling();
1034 
1035     // Statically evaluate loop check after peeling for loop invariant condition.
1036     const SuperblockCloner::HInstructionMap* hir_map = helper.GetInstructionMap();
1037     for (auto entry : *hir_map) {
1038       HInstruction* copy = entry.second;
1039       if (copy->IsIf()) {
1040         TryToEvaluateIfCondition(copy->AsIf(), graph_);
1041       }
1042     }
1043   }
1044 
1045   return true;
1046 }
1047 
TryFullUnrolling(LoopAnalysisInfo * analysis_info,bool generate_code)1048 bool HLoopOptimization::TryFullUnrolling(LoopAnalysisInfo* analysis_info, bool generate_code) {
1049   // Fully unroll loops with a known and small trip count.
1050   int64_t trip_count = analysis_info->GetTripCount();
1051   if (!arch_loop_helper_->IsLoopPeelingEnabled() ||
1052       trip_count == LoopAnalysisInfo::kUnknownTripCount ||
1053       !arch_loop_helper_->IsFullUnrollingBeneficial(analysis_info)) {
1054     return false;
1055   }
1056 
1057   if (generate_code) {
1058     // Peeling of the N first iterations (where N equals to the trip count) will effectively
1059     // eliminate the loop: after peeling we will have N sequential iterations copied into the loop
1060     // preheader and the original loop. The trip count of this loop will be 0 as the sequential
1061     // iterations are executed first and there are exactly N of them. Thus we can statically
1062     // evaluate the loop exit condition to 'false' and fully eliminate it.
1063     //
1064     // Here is an example of full unrolling of a loop with a trip count 2:
1065     //
1066     //                                           loop_cond_1
1067     //                                           loop_body_1        <- First iteration.
1068     //                                               |
1069     //                             \                 v
1070     //                            ==\            loop_cond_2
1071     //                            ==/            loop_body_2        <- Second iteration.
1072     //                             /                 |
1073     //               <-                              v     <-
1074     //     loop_cond   \                         loop_cond   \      <- This cond is always false.
1075     //     loop_body  _/                         loop_body  _/
1076     //
1077     HLoopInformation* loop_info = analysis_info->GetLoopInfo();
1078     PeelByCount(loop_info, trip_count, &induction_range_);
1079     HIf* loop_hif = loop_info->GetHeader()->GetLastInstruction()->AsIf();
1080     int32_t constant = loop_info->Contains(*loop_hif->IfTrueSuccessor()) ? 0 : 1;
1081     loop_hif->ReplaceInput(graph_->GetIntConstant(constant), 0u);
1082   }
1083 
1084   return true;
1085 }
1086 
TryLoopScalarOpts(LoopNode * node)1087 bool HLoopOptimization::TryLoopScalarOpts(LoopNode* node) {
1088   HLoopInformation* loop_info = node->loop_info;
1089   int64_t trip_count = LoopAnalysis::GetLoopTripCount(loop_info, &induction_range_);
1090   if (trip_count == 0) {
1091     // Mark the loop as dead.
1092     HIf* loop_hif = loop_info->GetHeader()->GetLastInstruction()->AsIf();
1093     int32_t constant = loop_info->Contains(*loop_hif->IfTrueSuccessor()) ? 0 : 1;
1094     loop_hif->ReplaceInput(graph_->GetIntConstant(constant), 0u);
1095     return true;
1096   }
1097 
1098   LoopAnalysisInfo analysis_info(loop_info);
1099   LoopAnalysis::CalculateLoopBasicProperties(loop_info, &analysis_info, trip_count);
1100   if (analysis_info.HasInstructionsPreventingScalarOpts() ||
1101       arch_loop_helper_->IsLoopNonBeneficialForScalarOpts(&analysis_info)) {
1102     return false;
1103   }
1104 
1105   if (!TryFullUnrolling(&analysis_info, /*generate_code*/ false) &&
1106       !TryPeelingForLoopInvariantExitsElimination(&analysis_info, /*generate_code*/ false) &&
1107       !TryUnrollingForBranchPenaltyReduction(&analysis_info, /*generate_code*/ false) &&
1108       !TryToRemoveSuspendCheckFromLoopHeader(&analysis_info, /*generate_code*/ false)) {
1109     return false;
1110   }
1111 
1112   // Try the suspend check removal even for non-clonable loops. Also this
1113   // optimization doesn't interfere with other scalar loop optimizations so it can
1114   // be done prior to them.
1115   bool removed_suspend_check = TryToRemoveSuspendCheckFromLoopHeader(&analysis_info);
1116 
1117   // Run 'IsLoopClonable' the last as it might be time-consuming.
1118   if (!LoopClonerHelper::IsLoopClonable(loop_info)) {
1119     return false;
1120   }
1121 
1122   return TryFullUnrolling(&analysis_info) ||
1123          TryPeelingForLoopInvariantExitsElimination(&analysis_info) ||
1124          TryUnrollingForBranchPenaltyReduction(&analysis_info) || removed_suspend_check;
1125 }
1126 
1127 //
1128 // Loop vectorization. The implementation is based on the book by Aart J.C. Bik:
1129 // "The Software Vectorization Handbook. Applying Multimedia Extensions for Maximum Performance."
1130 // Intel Press, June, 2004 (http://www.aartbik.com/).
1131 //
1132 
1133 
CanVectorizeDataFlow(LoopNode * node,HBasicBlock * header,bool collect_alignment_info)1134 bool HLoopOptimization::CanVectorizeDataFlow(LoopNode* node,
1135                                              HBasicBlock* header,
1136                                              bool collect_alignment_info) {
1137   // Reset vector bookkeeping.
1138   vector_length_ = 0;
1139   vector_refs_->clear();
1140   vector_static_peeling_factor_ = 0;
1141   vector_dynamic_peeling_candidate_ = nullptr;
1142   vector_runtime_test_a_ =
1143   vector_runtime_test_b_ = nullptr;
1144 
1145   // Traverse the data flow of the loop, in the original program order.
1146   for (HBlocksInLoopReversePostOrderIterator block_it(*header->GetLoopInformation());
1147        !block_it.Done();
1148        block_it.Advance()) {
1149     HBasicBlock* block = block_it.Current();
1150 
1151     if (block == header) {
1152       // The header is of a certain structure (TrySetSimpleLoopHeader) and doesn't need to be
1153       // processed here.
1154       continue;
1155     }
1156 
1157     // Phis in the loop-body prevent vectorization.
1158     // TODO: Enable vectorization of CF loops with Phis.
1159     if (!block->GetPhis().IsEmpty()) {
1160       return false;
1161     }
1162 
1163     // Scan the loop-body instructions, starting a right-hand-side tree traversal at each
1164     // left-hand-side occurrence, which allows passing down attributes down the use tree.
1165     for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
1166       if (!VectorizeDef(node, it.Current(), /*generate_code*/ false)) {
1167         return false;  // failure to vectorize a left-hand-side
1168       }
1169     }
1170   }
1171 
1172   // Prepare alignment analysis:
1173   // (1) find desired alignment (SIMD vector size in bytes).
1174   // (2) initialize static loop peeling votes (peeling factor that will
1175   //     make one particular reference aligned), never to exceed (1).
1176   // (3) variable to record how many references share same alignment.
1177   // (4) variable to record suitable candidate for dynamic loop peeling.
1178   size_t desired_alignment = GetVectorSizeInBytes();
1179   ScopedArenaVector<uint32_t> peeling_votes(desired_alignment, 0u,
1180       loop_allocator_->Adapter(kArenaAllocLoopOptimization));
1181 
1182   uint32_t max_num_same_alignment = 0;
1183   const ArrayReference* peeling_candidate = nullptr;
1184 
1185   // Data dependence analysis. Find each pair of references with same type, where
1186   // at least one is a write. Each such pair denotes a possible data dependence.
1187   // This analysis exploits the property that differently typed arrays cannot be
1188   // aliased, as well as the property that references either point to the same
1189   // array or to two completely disjoint arrays, i.e., no partial aliasing.
1190   // Other than a few simply heuristics, no detailed subscript analysis is done.
1191   // The scan over references also prepares finding a suitable alignment strategy.
1192   for (auto i = vector_refs_->begin(); i != vector_refs_->end(); ++i) {
1193     uint32_t num_same_alignment = 0;
1194     // Scan over all next references.
1195     for (auto j = i; ++j != vector_refs_->end(); ) {
1196       if (i->type == j->type && (i->lhs || j->lhs)) {
1197         // Found same-typed a[i+x] vs. b[i+y], where at least one is a write.
1198         HInstruction* a = i->base;
1199         HInstruction* b = j->base;
1200         HInstruction* x = i->offset;
1201         HInstruction* y = j->offset;
1202         if (a == b) {
1203           // Found a[i+x] vs. a[i+y]. Accept if x == y (loop-independent data dependence).
1204           // Conservatively assume a loop-carried data dependence otherwise, and reject.
1205           if (x != y) {
1206             return false;
1207           }
1208           // Count the number of references that have the same alignment (since
1209           // base and offset are the same) and where at least one is a write, so
1210           // e.g. a[i] = a[i] + b[i] counts a[i] but not b[i]).
1211           num_same_alignment++;
1212         } else {
1213           // Found a[i+x] vs. b[i+y]. Accept if x == y (at worst loop-independent data dependence).
1214           // Conservatively assume a potential loop-carried data dependence otherwise, avoided by
1215           // generating an explicit a != b disambiguation runtime test on the two references.
1216           if (x != y) {
1217             // To avoid excessive overhead, we only accept one a != b test.
1218             if (vector_runtime_test_a_ == nullptr) {
1219               // First test found.
1220               vector_runtime_test_a_ = a;
1221               vector_runtime_test_b_ = b;
1222             } else if ((vector_runtime_test_a_ != a || vector_runtime_test_b_ != b) &&
1223                        (vector_runtime_test_a_ != b || vector_runtime_test_b_ != a)) {
1224               return false;  // second test would be needed
1225             }
1226           }
1227         }
1228       }
1229     }
1230     // Update information for finding suitable alignment strategy:
1231     // (1) update votes for static loop peeling,
1232     // (2) update suitable candidate for dynamic loop peeling.
1233     Alignment alignment = ComputeAlignment(i->offset, i->type, i->is_string_char_at);
1234     if (alignment.Base() >= desired_alignment) {
1235       // If the array/string object has a known, sufficient alignment, use the
1236       // initial offset to compute the static loop peeling vote (this always
1237       // works, since elements have natural alignment).
1238       uint32_t offset = alignment.Offset() & (desired_alignment - 1u);
1239       uint32_t vote = (offset == 0)
1240           ? 0
1241           : ((desired_alignment - offset) >> DataType::SizeShift(i->type));
1242       DCHECK_LT(vote, 16u);
1243       ++peeling_votes[vote];
1244     } else if (BaseAlignment() >= desired_alignment &&
1245                num_same_alignment > max_num_same_alignment) {
1246       // Otherwise, if the array/string object has a known, sufficient alignment
1247       // for just the base but with an unknown offset, record the candidate with
1248       // the most occurrences for dynamic loop peeling (again, the peeling always
1249       // works, since elements have natural alignment).
1250       max_num_same_alignment = num_same_alignment;
1251       peeling_candidate = &(*i);
1252     }
1253   }  // for i
1254 
1255   if (collect_alignment_info) {
1256     // Update the info on alignment strategy.
1257     SetAlignmentStrategy(peeling_votes, peeling_candidate);
1258   }
1259 
1260   // Success!
1261   return true;
1262 }
1263 
ShouldVectorizeCommon(LoopNode * node,HPhi * main_phi,int64_t trip_count)1264 bool HLoopOptimization::ShouldVectorizeCommon(LoopNode* node,
1265                                               HPhi* main_phi,
1266                                               int64_t trip_count) {
1267   HBasicBlock* header = node->loop_info->GetHeader();
1268   HBasicBlock* preheader = node->loop_info->GetPreHeader();
1269 
1270   bool enable_alignment_strategies = !IsInPredicatedVectorizationMode();
1271   if (!TrySetSimpleLoopHeader(header, &main_phi) ||
1272       !CanVectorizeDataFlow(node, header, enable_alignment_strategies) ||
1273       !IsVectorizationProfitable(trip_count) ||
1274       !TryAssignLastValue(node->loop_info, main_phi, preheader, /*collect_loop_uses*/ true)) {
1275     return false;
1276   }
1277 
1278   return true;
1279 }
1280 
VectorizePredicated(LoopNode * node,HBasicBlock * block,HBasicBlock * exit)1281 void HLoopOptimization::VectorizePredicated(LoopNode* node,
1282                                             HBasicBlock* block,
1283                                             HBasicBlock* exit) {
1284   DCHECK(IsInPredicatedVectorizationMode());
1285 
1286   vector_external_set_->clear();
1287 
1288   HBasicBlock* header = node->loop_info->GetHeader();
1289   HBasicBlock* preheader = node->loop_info->GetPreHeader();
1290 
1291   // Adjust vector bookkeeping.
1292   HPhi* main_phi = nullptr;
1293   bool is_simple_loop_header = TrySetSimpleLoopHeader(header, &main_phi);  // refills sets
1294   DCHECK(is_simple_loop_header);
1295   vector_header_ = header;
1296   vector_body_ = block;
1297 
1298   // Loop induction type.
1299   DataType::Type induc_type = main_phi->GetType();
1300   DCHECK(induc_type == DataType::Type::kInt32 || induc_type == DataType::Type::kInt64)
1301       << induc_type;
1302 
1303   // Generate loop control:
1304   // stc = <trip-count>;
1305   // vtc = <vector trip-count>
1306   HInstruction* stc = induction_range_.GenerateTripCount(node->loop_info, graph_, preheader);
1307   HInstruction* vtc = stc;
1308   vector_index_ = graph_->GetConstant(induc_type, 0);
1309   bool needs_disambiguation_test = false;
1310   // Generate runtime disambiguation test:
1311   // vtc = a != b ? vtc : 0;
1312   if (NeedsArrayRefsDisambiguationTest()) {
1313     HInstruction* rt = Insert(
1314         preheader,
1315         new (global_allocator_) HNotEqual(vector_runtime_test_a_, vector_runtime_test_b_));
1316     vtc = Insert(preheader,
1317                  new (global_allocator_)
1318                  HSelect(rt, vtc, graph_->GetConstant(induc_type, 0), kNoDexPc));
1319     needs_disambiguation_test = true;
1320   }
1321 
1322   // Generate vector loop:
1323   // for ( ; i < vtc; i += vector_length)
1324   //    <vectorized-loop-body>
1325   HBasicBlock* preheader_for_vector_loop =
1326       graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit);
1327   synthesis_mode_ = LoopSynthesisMode::kVector;
1328   GenerateNewLoopPredicated(node,
1329                             preheader_for_vector_loop,
1330                             vector_index_,
1331                             vtc,
1332                             graph_->GetConstant(induc_type, vector_length_));
1333 
1334   // Generate scalar loop, if needed:
1335   // for ( ; i < stc; i += 1)
1336   //    <loop-body>
1337   if (needs_disambiguation_test) {
1338     synthesis_mode_ = LoopSynthesisMode::kSequential;
1339     HBasicBlock* preheader_for_cleanup_loop =
1340         graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit);
1341     // Use "Traditional" version for the sequential loop.
1342     GenerateNewLoopScalarOrTraditional(node,
1343                                        preheader_for_cleanup_loop,
1344                                        vector_index_,
1345                                        stc,
1346                                        graph_->GetConstant(induc_type, 1),
1347                                        LoopAnalysisInfo::kNoUnrollingFactor);
1348   }
1349 
1350   FinalizeVectorization(node);
1351 
1352   // Assign governing predicates for the predicated instructions inserted during vectorization
1353   // outside the loop.
1354   for (auto it : *vector_external_set_) {
1355     DCHECK(it->IsVecOperation());
1356     HVecOperation* vec_op = it->AsVecOperation();
1357 
1358     HVecPredSetAll* set_pred = new (global_allocator_) HVecPredSetAll(global_allocator_,
1359                                                                       graph_->GetIntConstant(1),
1360                                                                       vec_op->GetPackedType(),
1361                                                                       vec_op->GetVectorLength(),
1362                                                                       0u);
1363     vec_op->GetBlock()->InsertInstructionBefore(set_pred, vec_op);
1364     vec_op->SetMergingGoverningPredicate(set_pred);
1365   }
1366 }
1367 
VectorizeTraditional(LoopNode * node,HBasicBlock * block,HBasicBlock * exit,int64_t trip_count)1368 void HLoopOptimization::VectorizeTraditional(LoopNode* node,
1369                                              HBasicBlock* block,
1370                                              HBasicBlock* exit,
1371                                              int64_t trip_count) {
1372   DCHECK(!IsInPredicatedVectorizationMode());
1373 
1374   vector_external_set_->clear();
1375 
1376   HBasicBlock* header = node->loop_info->GetHeader();
1377   HBasicBlock* preheader = node->loop_info->GetPreHeader();
1378 
1379   // Pick a loop unrolling factor for the vector loop.
1380   uint32_t unroll = arch_loop_helper_->GetSIMDUnrollingFactor(
1381       block, trip_count, MaxNumberPeeled(), vector_length_);
1382   uint32_t chunk = vector_length_ * unroll;
1383 
1384   DCHECK(trip_count == 0 || (trip_count >= MaxNumberPeeled() + chunk));
1385 
1386   // A cleanup loop is needed, at least, for any unknown trip count or
1387   // for a known trip count with remainder iterations after vectorization.
1388   bool needs_cleanup =
1389       (trip_count == 0 || ((trip_count - vector_static_peeling_factor_) % chunk) != 0);
1390 
1391   // Adjust vector bookkeeping.
1392   HPhi* main_phi = nullptr;
1393   bool is_simple_loop_header = TrySetSimpleLoopHeader(header, &main_phi);  // refills sets
1394   DCHECK(is_simple_loop_header);
1395   vector_header_ = header;
1396   vector_body_ = block;
1397 
1398   // Loop induction type.
1399   DataType::Type induc_type = main_phi->GetType();
1400   DCHECK(induc_type == DataType::Type::kInt32 || induc_type == DataType::Type::kInt64)
1401       << induc_type;
1402 
1403   // Generate the trip count for static or dynamic loop peeling, if needed:
1404   // ptc = <peeling factor>;
1405   HInstruction* ptc = nullptr;
1406   if (vector_static_peeling_factor_ != 0) {
1407     // Static loop peeling for SIMD alignment (using the most suitable
1408     // fixed peeling factor found during prior alignment analysis).
1409     DCHECK(vector_dynamic_peeling_candidate_ == nullptr);
1410     ptc = graph_->GetConstant(induc_type, vector_static_peeling_factor_);
1411   } else if (vector_dynamic_peeling_candidate_ != nullptr) {
1412     // Dynamic loop peeling for SIMD alignment (using the most suitable
1413     // candidate found during prior alignment analysis):
1414     // rem = offset % ALIGN;    // adjusted as #elements
1415     // ptc = rem == 0 ? 0 : (ALIGN - rem);
1416     uint32_t shift = DataType::SizeShift(vector_dynamic_peeling_candidate_->type);
1417     uint32_t align = GetVectorSizeInBytes() >> shift;
1418     uint32_t hidden_offset = HiddenOffset(vector_dynamic_peeling_candidate_->type,
1419                                           vector_dynamic_peeling_candidate_->is_string_char_at);
1420     HInstruction* adjusted_offset = graph_->GetConstant(induc_type, hidden_offset >> shift);
1421     HInstruction* offset = Insert(preheader, new (global_allocator_) HAdd(
1422         induc_type, vector_dynamic_peeling_candidate_->offset, adjusted_offset));
1423     HInstruction* rem = Insert(preheader, new (global_allocator_) HAnd(
1424         induc_type, offset, graph_->GetConstant(induc_type, align - 1u)));
1425     HInstruction* sub = Insert(preheader, new (global_allocator_) HSub(
1426         induc_type, graph_->GetConstant(induc_type, align), rem));
1427     HInstruction* cond = Insert(preheader, new (global_allocator_) HEqual(
1428         rem, graph_->GetConstant(induc_type, 0)));
1429     ptc = Insert(preheader, new (global_allocator_) HSelect(
1430         cond, graph_->GetConstant(induc_type, 0), sub, kNoDexPc));
1431     needs_cleanup = true;  // don't know the exact amount
1432   }
1433 
1434   // Generate loop control:
1435   // stc = <trip-count>;
1436   // ptc = min(stc, ptc);
1437   // vtc = stc - (stc - ptc) % chunk;
1438   // i = 0;
1439   HInstruction* stc = induction_range_.GenerateTripCount(node->loop_info, graph_, preheader);
1440   HInstruction* vtc = stc;
1441   if (needs_cleanup) {
1442     DCHECK(IsPowerOfTwo(chunk));
1443     HInstruction* diff = stc;
1444     if (ptc != nullptr) {
1445       if (trip_count == 0) {
1446         HInstruction* cond = Insert(preheader, new (global_allocator_) HAboveOrEqual(stc, ptc));
1447         ptc = Insert(preheader, new (global_allocator_) HSelect(cond, ptc, stc, kNoDexPc));
1448       }
1449       diff = Insert(preheader, new (global_allocator_) HSub(induc_type, stc, ptc));
1450     }
1451     HInstruction* rem = Insert(
1452         preheader, new (global_allocator_) HAnd(induc_type,
1453                                                 diff,
1454                                                 graph_->GetConstant(induc_type, chunk - 1)));
1455     vtc = Insert(preheader, new (global_allocator_) HSub(induc_type, stc, rem));
1456   }
1457   vector_index_ = graph_->GetConstant(induc_type, 0);
1458 
1459   // Generate runtime disambiguation test:
1460   // vtc = a != b ? vtc : 0;
1461   if (NeedsArrayRefsDisambiguationTest()) {
1462     HInstruction* rt = Insert(
1463         preheader,
1464         new (global_allocator_) HNotEqual(vector_runtime_test_a_, vector_runtime_test_b_));
1465     vtc = Insert(preheader,
1466                  new (global_allocator_)
1467                  HSelect(rt, vtc, graph_->GetConstant(induc_type, 0), kNoDexPc));
1468     needs_cleanup = true;
1469   }
1470 
1471   // Generate alignment peeling loop, if needed:
1472   // for ( ; i < ptc; i += 1)
1473   //    <loop-body>
1474   //
1475   // NOTE: The alignment forced by the peeling loop is preserved even if data is
1476   //       moved around during suspend checks, since all analysis was based on
1477   //       nothing more than the Android runtime alignment conventions.
1478   if (ptc != nullptr) {
1479     synthesis_mode_ = LoopSynthesisMode::kSequential;
1480     HBasicBlock* preheader_for_peeling_loop =
1481         graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit);
1482     GenerateNewLoopScalarOrTraditional(node,
1483                                        preheader_for_peeling_loop,
1484                                        vector_index_,
1485                                        ptc,
1486                                        graph_->GetConstant(induc_type, 1),
1487                                        LoopAnalysisInfo::kNoUnrollingFactor);
1488   }
1489 
1490   // Generate vector loop, possibly further unrolled:
1491   // for ( ; i < vtc; i += chunk)
1492   //    <vectorized-loop-body>
1493   synthesis_mode_ = LoopSynthesisMode::kVector;
1494   HBasicBlock* preheader_for_vector_loop =
1495       graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit);
1496   GenerateNewLoopScalarOrTraditional(node,
1497                                      preheader_for_vector_loop,
1498                                      vector_index_,
1499                                      vtc,
1500                                      graph_->GetConstant(induc_type, vector_length_),  // per unroll
1501                                      unroll);
1502 
1503   // Generate cleanup loop, if needed:
1504   // for ( ; i < stc; i += 1)
1505   //    <loop-body>
1506   if (needs_cleanup) {
1507     synthesis_mode_ = LoopSynthesisMode::kSequential;
1508     HBasicBlock* preheader_for_cleanup_loop =
1509         graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit);
1510     GenerateNewLoopScalarOrTraditional(node,
1511                                        preheader_for_cleanup_loop,
1512                                        vector_index_,
1513                                        stc,
1514                                        graph_->GetConstant(induc_type, 1),
1515                                        LoopAnalysisInfo::kNoUnrollingFactor);
1516   }
1517 
1518   FinalizeVectorization(node);
1519 }
1520 
FinalizeVectorization(LoopNode * node)1521 void HLoopOptimization::FinalizeVectorization(LoopNode* node) {
1522   HBasicBlock* header = node->loop_info->GetHeader();
1523   HBasicBlock* preheader = node->loop_info->GetPreHeader();
1524   HLoopInformation* vloop = vector_header_->GetLoopInformation();
1525   // Link reductions to their final uses.
1526   for (auto i = reductions_->begin(); i != reductions_->end(); ++i) {
1527     if (i->first->IsPhi()) {
1528       HInstruction* phi = i->first;
1529       HInstruction* repl = ReduceAndExtractIfNeeded(i->second);
1530       // Deal with regular uses.
1531       for (const HUseListNode<HInstruction*>& use : phi->GetUses()) {
1532         induction_range_.Replace(use.GetUser(), phi, repl);  // update induction use
1533       }
1534       phi->ReplaceWith(repl);
1535     }
1536   }
1537 
1538   // Remove the original loop.
1539   for (HBlocksInLoopPostOrderIterator it_loop(*node->loop_info);
1540        !it_loop.Done();
1541        it_loop.Advance()) {
1542     HBasicBlock* cur_block = it_loop.Current();
1543     if (cur_block == node->loop_info->GetHeader()) {
1544       continue;
1545     }
1546     cur_block->DisconnectAndDelete();
1547   }
1548 
1549   while (!header->GetFirstInstruction()->IsGoto()) {
1550     header->RemoveInstruction(header->GetFirstInstruction());
1551   }
1552 
1553   // Update loop hierarchy: the old header now resides in the same outer loop
1554   // as the old preheader. Note that we don't bother putting sequential
1555   // loops back in the hierarchy at this point.
1556   header->SetLoopInformation(preheader->GetLoopInformation());  // outward
1557   node->loop_info = vloop;
1558 }
1559 
InitializeForNewLoop(HBasicBlock * new_preheader,HInstruction * lo)1560 HPhi* HLoopOptimization::InitializeForNewLoop(HBasicBlock* new_preheader, HInstruction* lo) {
1561   DataType::Type induc_type = lo->GetType();
1562   // Prepare new loop.
1563   vector_preheader_ = new_preheader,
1564   vector_header_ = vector_preheader_->GetSingleSuccessor();
1565   vector_body_ = vector_header_->GetSuccessors()[1];
1566   HPhi* phi = new (global_allocator_) HPhi(global_allocator_,
1567                                            kNoRegNumber,
1568                                            0,
1569                                            HPhi::ToPhiType(induc_type));
1570   vector_header_->AddPhi(phi);
1571   vector_index_ = phi;
1572   vector_permanent_map_->clear();
1573   predicate_info_map_->clear();
1574 
1575   return phi;
1576 }
1577 
GenerateNewLoopScalarOrTraditional(LoopNode * node,HBasicBlock * new_preheader,HInstruction * lo,HInstruction * hi,HInstruction * step,uint32_t unroll)1578 void HLoopOptimization::GenerateNewLoopScalarOrTraditional(LoopNode* node,
1579                                                            HBasicBlock* new_preheader,
1580                                                            HInstruction* lo,
1581                                                            HInstruction* hi,
1582                                                            HInstruction* step,
1583                                                            uint32_t unroll) {
1584   DCHECK(unroll == 1 || synthesis_mode_ == LoopSynthesisMode::kVector);
1585   DataType::Type induc_type = lo->GetType();
1586   HPhi* phi = InitializeForNewLoop(new_preheader, lo);
1587 
1588   // Generate loop exit check.
1589   HInstruction* cond = new (global_allocator_) HAboveOrEqual(phi, hi);
1590   vector_header_->AddInstruction(cond);
1591   vector_header_->AddInstruction(new (global_allocator_) HIf(cond));
1592 
1593   for (uint32_t u = 0; u < unroll; u++) {
1594     GenerateNewLoopBodyOnce(node, induc_type, step);
1595   }
1596 
1597   FinalizePhisForNewLoop(phi, lo);
1598 }
1599 
GenerateNewLoopPredicated(LoopNode * node,HBasicBlock * new_preheader,HInstruction * lo,HInstruction * hi,HInstruction * step)1600 void HLoopOptimization::GenerateNewLoopPredicated(LoopNode* node,
1601                                                   HBasicBlock* new_preheader,
1602                                                   HInstruction* lo,
1603                                                   HInstruction* hi,
1604                                                   HInstruction* step) {
1605   DCHECK(IsInPredicatedVectorizationMode());
1606   DCHECK(synthesis_mode_ == LoopSynthesisMode::kVector);
1607   DataType::Type induc_type = lo->GetType();
1608   HPhi* phi = InitializeForNewLoop(new_preheader, lo);
1609 
1610   // Generate loop exit check.
1611   HVecPredWhile* pred_while =
1612       new (global_allocator_) HVecPredWhile(global_allocator_,
1613                                             phi,
1614                                             hi,
1615                                             HVecPredWhile::CondKind::kLO,
1616                                             DataType::Type::kInt32,
1617                                             vector_length_,
1618                                             0u);
1619 
1620   HInstruction* cond =
1621       new (global_allocator_) HVecPredToBoolean(global_allocator_,
1622                                                 pred_while,
1623                                                 HVecPredToBoolean::PCondKind::kNFirst,
1624                                                 DataType::Type::kInt32,
1625                                                 vector_length_,
1626                                                 0u);
1627 
1628   vector_header_->AddInstruction(pred_while);
1629   vector_header_->AddInstruction(cond);
1630   vector_header_->AddInstruction(new (global_allocator_) HIf(cond));
1631 
1632   PreparePredicateInfoMap(node);
1633   GenerateNewLoopBodyOnce(node, induc_type, step);
1634   InitPredicateInfoMap(node, pred_while);
1635 
1636   // Assign governing predicates for instructions in the loop; the traversal order doesn't matter.
1637   for (HBlocksInLoopIterator block_it(*node->loop_info);
1638        !block_it.Done();
1639        block_it.Advance()) {
1640     HBasicBlock* cur_block = block_it.Current();
1641 
1642     for (HInstructionIterator it(cur_block->GetInstructions()); !it.Done(); it.Advance()) {
1643       auto i = vector_map_->find(it.Current());
1644       if (i != vector_map_->end()) {
1645         HInstruction* instr = i->second;
1646 
1647         if (!instr->IsVecOperation()) {
1648           continue;
1649         }
1650         // There are cases when a vector instruction, which corresponds to some instruction in the
1651         // original scalar loop, is located not in the newly created vector loop but
1652         // in the vector loop preheader (and hence recorded in vector_external_set_).
1653         //
1654         // Governing predicates will be set for such instructions separately.
1655         bool in_vector_loop = vector_header_->GetLoopInformation()->Contains(*instr->GetBlock());
1656         DCHECK_IMPLIES(!in_vector_loop,
1657                         vector_external_set_->find(instr) != vector_external_set_->end());
1658 
1659         if (in_vector_loop &&
1660             !instr->AsVecOperation()->IsPredicated()) {
1661           HVecOperation* op = instr->AsVecOperation();
1662           HVecPredSetOperation* pred = predicate_info_map_->Get(cur_block)->GetControlPredicate();
1663           op->SetMergingGoverningPredicate(pred);
1664         }
1665       }
1666     }
1667   }
1668 
1669   FinalizePhisForNewLoop(phi, lo);
1670 }
1671 
GenerateNewLoopBodyOnce(LoopNode * node,DataType::Type induc_type,HInstruction * step)1672 void HLoopOptimization::GenerateNewLoopBodyOnce(LoopNode* node,
1673                                                 DataType::Type induc_type,
1674                                                 HInstruction* step) {
1675   // Generate instruction map.
1676   vector_map_->clear();
1677   HLoopInformation* loop_info = node->loop_info;
1678 
1679   // Traverse the data flow of the loop, in the original program order.
1680   for (HBlocksInLoopReversePostOrderIterator block_it(*loop_info);
1681       !block_it.Done();
1682       block_it.Advance()) {
1683     HBasicBlock* cur_block = block_it.Current();
1684 
1685     if (cur_block == loop_info->GetHeader()) {
1686       continue;
1687     }
1688 
1689     for (HInstructionIterator it(cur_block->GetInstructions()); !it.Done(); it.Advance()) {
1690       bool vectorized_def = VectorizeDef(node, it.Current(), /*generate_code*/ true);
1691       DCHECK(vectorized_def);
1692     }
1693   }
1694 
1695   // Generate body from the instruction map, in the original program order.
1696   HEnvironment* env = vector_header_->GetFirstInstruction()->GetEnvironment();
1697   for (HBlocksInLoopReversePostOrderIterator block_it(*loop_info);
1698         !block_it.Done();
1699         block_it.Advance()) {
1700     HBasicBlock* cur_block = block_it.Current();
1701 
1702     if (cur_block == loop_info->GetHeader()) {
1703       continue;
1704     }
1705 
1706     for (HInstructionIterator it(cur_block->GetInstructions()); !it.Done(); it.Advance()) {
1707       auto i = vector_map_->find(it.Current());
1708       if (i != vector_map_->end() && !i->second->IsInBlock()) {
1709         Insert(vector_body_, i->second);
1710         // Deal with instructions that need an environment, such as the scalar intrinsics.
1711         if (i->second->NeedsEnvironment()) {
1712           i->second->CopyEnvironmentFromWithLoopPhiAdjustment(env, vector_header_);
1713         }
1714       }
1715     }
1716   }
1717   // Generate the induction.
1718   vector_index_ = new (global_allocator_) HAdd(induc_type, vector_index_, step);
1719   Insert(vector_body_, vector_index_);
1720 }
1721 
FinalizePhisForNewLoop(HPhi * phi,HInstruction * lo)1722 void HLoopOptimization::FinalizePhisForNewLoop(HPhi* phi, HInstruction* lo) {
1723   // Finalize phi inputs for the reductions (if any).
1724   for (auto i = reductions_->begin(); i != reductions_->end(); ++i) {
1725     if (!i->first->IsPhi()) {
1726       DCHECK(i->second->IsPhi());
1727       GenerateVecReductionPhiInputs(i->second->AsPhi(), i->first);
1728     }
1729   }
1730   // Finalize phi inputs for the loop index.
1731   phi->AddInput(lo);
1732   phi->AddInput(vector_index_);
1733   vector_index_ = phi;
1734 }
1735 
VectorizeDef(LoopNode * node,HInstruction * instruction,bool generate_code)1736 bool HLoopOptimization::VectorizeDef(LoopNode* node,
1737                                      HInstruction* instruction,
1738                                      bool generate_code) {
1739   // Accept a left-hand-side array base[index] for
1740   // (1) supported vector type,
1741   // (2) loop-invariant base,
1742   // (3) unit stride index,
1743   // (4) vectorizable right-hand-side value.
1744   uint64_t restrictions = kNone;
1745   // Don't accept expressions that can throw.
1746   if (instruction->CanThrow()) {
1747     return false;
1748   }
1749   if (instruction->IsArraySet()) {
1750     DataType::Type type = instruction->AsArraySet()->GetComponentType();
1751     HInstruction* base = instruction->InputAt(0);
1752     HInstruction* index = instruction->InputAt(1);
1753     HInstruction* value = instruction->InputAt(2);
1754     HInstruction* offset = nullptr;
1755     // For narrow types, explicit type conversion may have been
1756     // optimized way, so set the no hi bits restriction here.
1757     if (DataType::Size(type) <= 2) {
1758       restrictions |= kNoHiBits;
1759     }
1760     if (TrySetVectorType(type, &restrictions) &&
1761         node->loop_info->IsDefinedOutOfTheLoop(base) &&
1762         induction_range_.IsUnitStride(instruction->GetBlock(), index, graph_, &offset) &&
1763         VectorizeUse(node, value, generate_code, type, restrictions)) {
1764       if (generate_code) {
1765         GenerateVecSub(index, offset);
1766         GenerateVecMem(instruction, vector_map_->Get(index), vector_map_->Get(value), offset, type);
1767       } else {
1768         vector_refs_->insert(ArrayReference(base, offset, type, /*lhs*/ true));
1769       }
1770       return true;
1771     }
1772     return false;
1773   }
1774   // Accept a left-hand-side reduction for
1775   // (1) supported vector type,
1776   // (2) vectorizable right-hand-side value.
1777   auto redit = reductions_->find(instruction);
1778   if (redit != reductions_->end()) {
1779     DataType::Type type = instruction->GetType();
1780     // Recognize SAD idiom or direct reduction.
1781     if (VectorizeSADIdiom(node, instruction, generate_code, type, restrictions) ||
1782         VectorizeDotProdIdiom(node, instruction, generate_code, type, restrictions) ||
1783         (TrySetVectorType(type, &restrictions) &&
1784          VectorizeUse(node, instruction, generate_code, type, restrictions))) {
1785       DCHECK(!instruction->IsPhi());
1786       if (generate_code) {
1787         HInstruction* new_red_vec_op = vector_map_->Get(instruction);
1788         HInstruction* original_phi = redit->second;
1789         DCHECK(original_phi->IsPhi());
1790         vector_permanent_map_->Put(new_red_vec_op, vector_map_->Get(original_phi));
1791         vector_permanent_map_->Overwrite(original_phi, new_red_vec_op);
1792       }
1793       return true;
1794     }
1795     return false;
1796   }
1797   // Branch back okay.
1798   if (instruction->IsGoto()) {
1799     return true;
1800   }
1801 
1802   if (instruction->IsIf()) {
1803     return VectorizeIfCondition(node, instruction, generate_code, restrictions);
1804   }
1805   // Otherwise accept only expressions with no effects outside the immediate loop-body.
1806   // Note that actual uses are inspected during right-hand-side tree traversal.
1807   return !IsUsedOutsideLoop(node->loop_info, instruction)
1808          && !instruction->DoesAnyWrite();
1809 }
1810 
VectorizeUse(LoopNode * node,HInstruction * instruction,bool generate_code,DataType::Type type,uint64_t restrictions)1811 bool HLoopOptimization::VectorizeUse(LoopNode* node,
1812                                      HInstruction* instruction,
1813                                      bool generate_code,
1814                                      DataType::Type type,
1815                                      uint64_t restrictions) {
1816   // Accept anything for which code has already been generated.
1817   if (generate_code) {
1818     if (vector_map_->find(instruction) != vector_map_->end()) {
1819       return true;
1820     }
1821   }
1822   // Continue the right-hand-side tree traversal, passing in proper
1823   // types and vector restrictions along the way. During code generation,
1824   // all new nodes are drawn from the global allocator.
1825   if (node->loop_info->IsDefinedOutOfTheLoop(instruction)) {
1826     // Accept invariant use, using scalar expansion.
1827     if (generate_code) {
1828       GenerateVecInv(instruction, type);
1829     }
1830     return true;
1831   } else if (instruction->IsArrayGet()) {
1832     // Deal with vector restrictions.
1833     bool is_string_char_at = instruction->AsArrayGet()->IsStringCharAt();
1834 
1835     if (is_string_char_at && (HasVectorRestrictions(restrictions, kNoStringCharAt))) {
1836       return false;
1837     }
1838     // Accept a right-hand-side array base[index] for
1839     // (1) matching vector type (exact match or signed/unsigned integral type of the same size),
1840     // (2) loop-invariant base,
1841     // (3) unit stride index,
1842     // (4) vectorizable right-hand-side value.
1843     HInstruction* base = instruction->InputAt(0);
1844     HInstruction* index = instruction->InputAt(1);
1845     HInstruction* offset = nullptr;
1846     if (HVecOperation::ToSignedType(type) == HVecOperation::ToSignedType(instruction->GetType()) &&
1847         node->loop_info->IsDefinedOutOfTheLoop(base) &&
1848         induction_range_.IsUnitStride(instruction->GetBlock(), index, graph_, &offset)) {
1849       if (generate_code) {
1850         GenerateVecSub(index, offset);
1851         GenerateVecMem(instruction, vector_map_->Get(index), nullptr, offset, type);
1852       } else {
1853         vector_refs_->insert(ArrayReference(base, offset, type, /*lhs*/ false, is_string_char_at));
1854       }
1855       return true;
1856     }
1857   } else if (instruction->IsPhi()) {
1858     // Accept particular phi operations.
1859     if (reductions_->find(instruction) != reductions_->end()) {
1860       // Deal with vector restrictions.
1861       if (HasVectorRestrictions(restrictions, kNoReduction)) {
1862         return false;
1863       }
1864       // Accept a reduction.
1865       if (generate_code) {
1866         GenerateVecReductionPhi(instruction->AsPhi());
1867       }
1868       return true;
1869     }
1870     // TODO: accept right-hand-side induction?
1871     return false;
1872   } else if (instruction->IsTypeConversion()) {
1873     // Accept particular type conversions.
1874     HTypeConversion* conversion = instruction->AsTypeConversion();
1875     HInstruction* opa = conversion->InputAt(0);
1876     DataType::Type from = conversion->GetInputType();
1877     DataType::Type to = conversion->GetResultType();
1878     if (DataType::IsIntegralType(from) && DataType::IsIntegralType(to)) {
1879       uint32_t size_vec = DataType::Size(type);
1880       uint32_t size_from = DataType::Size(from);
1881       uint32_t size_to = DataType::Size(to);
1882       // Accept an integral conversion
1883       // (1a) narrowing into vector type, "wider" operations cannot bring in higher order bits, or
1884       // (1b) widening from at least vector type, and
1885       // (2) vectorizable operand.
1886       if ((size_to < size_from &&
1887            size_to == size_vec &&
1888            VectorizeUse(node, opa, generate_code, type, restrictions | kNoHiBits)) ||
1889           (size_to >= size_from &&
1890            size_from >= size_vec &&
1891            VectorizeUse(node, opa, generate_code, type, restrictions))) {
1892         if (generate_code) {
1893           if (synthesis_mode_ == LoopSynthesisMode::kVector) {
1894             vector_map_->Put(instruction, vector_map_->Get(opa));  // operand pass-through
1895           } else {
1896             GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1897           }
1898         }
1899         return true;
1900       }
1901     } else if (to == DataType::Type::kFloat32 && from == DataType::Type::kInt32) {
1902       DCHECK_EQ(to, type);
1903       // Accept int to float conversion for
1904       // (1) supported int,
1905       // (2) vectorizable operand.
1906       if (TrySetVectorType(from, &restrictions) &&
1907           VectorizeUse(node, opa, generate_code, from, restrictions)) {
1908         if (generate_code) {
1909           GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1910         }
1911         return true;
1912       }
1913     }
1914     return false;
1915   } else if (instruction->IsNeg() || instruction->IsNot() || instruction->IsBooleanNot()) {
1916     // Accept unary operator for vectorizable operand.
1917     HInstruction* opa = instruction->InputAt(0);
1918     if (VectorizeUse(node, opa, generate_code, type, restrictions)) {
1919       if (generate_code) {
1920         GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1921       }
1922       return true;
1923     }
1924   } else if (instruction->IsAdd() || instruction->IsSub() ||
1925              instruction->IsMul() || instruction->IsDiv() ||
1926              instruction->IsAnd() || instruction->IsOr()  || instruction->IsXor()) {
1927     // Deal with vector restrictions.
1928     if ((instruction->IsMul() && HasVectorRestrictions(restrictions, kNoMul)) ||
1929         (instruction->IsDiv() && HasVectorRestrictions(restrictions, kNoDiv))) {
1930       return false;
1931     }
1932     // Accept binary operator for vectorizable operands.
1933     HInstruction* opa = instruction->InputAt(0);
1934     HInstruction* opb = instruction->InputAt(1);
1935     if (VectorizeUse(node, opa, generate_code, type, restrictions) &&
1936         VectorizeUse(node, opb, generate_code, type, restrictions)) {
1937       if (generate_code) {
1938         GenerateVecOp(instruction, vector_map_->Get(opa), vector_map_->Get(opb), type);
1939       }
1940       return true;
1941     }
1942   } else if (instruction->IsShl() || instruction->IsShr() || instruction->IsUShr()) {
1943     // Recognize halving add idiom.
1944     if (VectorizeHalvingAddIdiom(node, instruction, generate_code, type, restrictions)) {
1945       return true;
1946     }
1947     // Deal with vector restrictions.
1948     HInstruction* opa = instruction->InputAt(0);
1949     HInstruction* opb = instruction->InputAt(1);
1950     HInstruction* r = opa;
1951     bool is_unsigned = false;
1952     if ((HasVectorRestrictions(restrictions, kNoShift)) ||
1953         (instruction->IsShr() && HasVectorRestrictions(restrictions, kNoShr))) {
1954       return false;  // unsupported instruction
1955     } else if (HasVectorRestrictions(restrictions, kNoHiBits)) {
1956       // Shifts right need extra care to account for higher order bits.
1957       // TODO: less likely shr/unsigned and ushr/signed can by flipping signess.
1958       if (instruction->IsShr() &&
1959           (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || is_unsigned)) {
1960         return false;  // reject, unless all operands are sign-extension narrower
1961       } else if (instruction->IsUShr() &&
1962                  (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || !is_unsigned)) {
1963         return false;  // reject, unless all operands are zero-extension narrower
1964       }
1965     }
1966     // Accept shift operator for vectorizable/invariant operands.
1967     // TODO: accept symbolic, albeit loop invariant shift factors.
1968     DCHECK(r != nullptr);
1969     if (generate_code && synthesis_mode_ != LoopSynthesisMode::kVector) {  // de-idiom
1970       r = opa;
1971     }
1972     int64_t distance = 0;
1973     if (VectorizeUse(node, r, generate_code, type, restrictions) &&
1974         IsInt64AndGet(opb, /*out*/ &distance)) {
1975       // Restrict shift distance to packed data type width.
1976       int64_t max_distance = DataType::Size(type) * 8;
1977       if (0 <= distance && distance < max_distance) {
1978         if (generate_code) {
1979           GenerateVecOp(instruction, vector_map_->Get(r), opb, type);
1980         }
1981         return true;
1982       }
1983     }
1984   } else if (instruction->IsAbs()) {
1985     // Deal with vector restrictions.
1986     HInstruction* opa = instruction->InputAt(0);
1987     HInstruction* r = opa;
1988     bool is_unsigned = false;
1989     if (HasVectorRestrictions(restrictions, kNoAbs)) {
1990       return false;
1991     } else if (HasVectorRestrictions(restrictions, kNoHiBits) &&
1992                (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || is_unsigned)) {
1993       return false;  // reject, unless operand is sign-extension narrower
1994     }
1995     // Accept ABS(x) for vectorizable operand.
1996     DCHECK(r != nullptr);
1997     if (generate_code && synthesis_mode_ != LoopSynthesisMode::kVector) {  // de-idiom
1998       r = opa;
1999     }
2000     if (VectorizeUse(node, r, generate_code, type, restrictions)) {
2001       if (generate_code) {
2002         GenerateVecOp(instruction,
2003                       vector_map_->Get(r),
2004                       nullptr,
2005                       HVecOperation::ToProperType(type, is_unsigned));
2006       }
2007       return true;
2008     }
2009   }
2010   return false;
2011 }
2012 
GetVectorSizeInBytes()2013 uint32_t HLoopOptimization::GetVectorSizeInBytes() {
2014   return simd_register_size_;
2015 }
2016 
TrySetVectorType(DataType::Type type,uint64_t * restrictions)2017 bool HLoopOptimization::TrySetVectorType(DataType::Type type, uint64_t* restrictions) {
2018   const InstructionSetFeatures* features = compiler_options_->GetInstructionSetFeatures();
2019   switch (compiler_options_->GetInstructionSet()) {
2020     case InstructionSet::kArm:
2021     case InstructionSet::kThumb2:
2022       // Allow vectorization for all ARM devices, because Android assumes that
2023       // ARM 32-bit always supports advanced SIMD (64-bit SIMD).
2024       *restrictions |= kNoIfCond;
2025       switch (type) {
2026         case DataType::Type::kBool:
2027         case DataType::Type::kUint8:
2028         case DataType::Type::kInt8:
2029           *restrictions |= kNoDiv | kNoReduction | kNoDotProd;
2030           return TrySetVectorLength(type, 8);
2031         case DataType::Type::kUint16:
2032         case DataType::Type::kInt16:
2033           *restrictions |= kNoDiv | kNoStringCharAt | kNoReduction | kNoDotProd;
2034           return TrySetVectorLength(type, 4);
2035         case DataType::Type::kInt32:
2036           *restrictions |= kNoDiv | kNoWideSAD;
2037           return TrySetVectorLength(type, 2);
2038         default:
2039           break;
2040       }
2041       return false;
2042     case InstructionSet::kArm64:
2043       if (IsInPredicatedVectorizationMode()) {
2044         // SVE vectorization.
2045         size_t vector_length = simd_register_size_ / DataType::Size(type);
2046         DCHECK_EQ(simd_register_size_ % DataType::Size(type), 0u);
2047         switch (type) {
2048           case DataType::Type::kBool:
2049             *restrictions |= kNoDiv |
2050                              kNoSignedHAdd |
2051                              kNoUnsignedHAdd |
2052                              kNoUnroundedHAdd |
2053                              kNoSAD |
2054                              kNoIfCond;
2055             return TrySetVectorLength(type, vector_length);
2056           case DataType::Type::kUint8:
2057           case DataType::Type::kInt8:
2058             *restrictions |= kNoDiv |
2059                              kNoSignedHAdd |
2060                              kNoUnsignedHAdd |
2061                              kNoUnroundedHAdd |
2062                              kNoSAD;
2063             return TrySetVectorLength(type, vector_length);
2064           case DataType::Type::kUint16:
2065           case DataType::Type::kInt16:
2066             *restrictions |= kNoDiv |
2067                              kNoStringCharAt |   // TODO: support in predicated mode.
2068                              kNoSignedHAdd |
2069                              kNoUnsignedHAdd |
2070                              kNoUnroundedHAdd |
2071                              kNoSAD |
2072                              kNoDotProd;
2073             return TrySetVectorLength(type, vector_length);
2074           case DataType::Type::kInt32:
2075             *restrictions |= kNoDiv | kNoSAD;
2076             return TrySetVectorLength(type, vector_length);
2077           case DataType::Type::kInt64:
2078             *restrictions |= kNoDiv | kNoSAD | kNoIfCond;
2079             return TrySetVectorLength(type, vector_length);
2080           case DataType::Type::kFloat32:
2081             *restrictions |= kNoReduction | kNoIfCond;
2082             return TrySetVectorLength(type, vector_length);
2083           case DataType::Type::kFloat64:
2084             *restrictions |= kNoReduction | kNoIfCond;
2085             return TrySetVectorLength(type, vector_length);
2086           default:
2087             break;
2088         }
2089         return false;
2090       } else {
2091         // Allow vectorization for all ARM devices, because Android assumes that
2092         // ARMv8 AArch64 always supports advanced SIMD (128-bit SIMD).
2093         *restrictions |= kNoIfCond;
2094         switch (type) {
2095           case DataType::Type::kBool:
2096           case DataType::Type::kUint8:
2097           case DataType::Type::kInt8:
2098             *restrictions |= kNoDiv;
2099             return TrySetVectorLength(type, 16);
2100           case DataType::Type::kUint16:
2101           case DataType::Type::kInt16:
2102             *restrictions |= kNoDiv;
2103             return TrySetVectorLength(type, 8);
2104           case DataType::Type::kInt32:
2105             *restrictions |= kNoDiv;
2106             return TrySetVectorLength(type, 4);
2107           case DataType::Type::kInt64:
2108             *restrictions |= kNoDiv | kNoMul;
2109             return TrySetVectorLength(type, 2);
2110           case DataType::Type::kFloat32:
2111             *restrictions |= kNoReduction;
2112             return TrySetVectorLength(type, 4);
2113           case DataType::Type::kFloat64:
2114             *restrictions |= kNoReduction;
2115             return TrySetVectorLength(type, 2);
2116           default:
2117             break;
2118         }
2119         return false;
2120       }
2121     case InstructionSet::kX86:
2122     case InstructionSet::kX86_64:
2123       // Allow vectorization for SSE4.1-enabled X86 devices only (128-bit SIMD).
2124       *restrictions |= kNoIfCond;
2125       if (features->AsX86InstructionSetFeatures()->HasSSE4_1()) {
2126         switch (type) {
2127           case DataType::Type::kBool:
2128           case DataType::Type::kUint8:
2129           case DataType::Type::kInt8:
2130             *restrictions |= kNoMul |
2131                              kNoDiv |
2132                              kNoShift |
2133                              kNoAbs |
2134                              kNoSignedHAdd |
2135                              kNoUnroundedHAdd |
2136                              kNoSAD |
2137                              kNoDotProd;
2138             return TrySetVectorLength(type, 16);
2139           case DataType::Type::kUint16:
2140             *restrictions |= kNoDiv |
2141                              kNoAbs |
2142                              kNoSignedHAdd |
2143                              kNoUnroundedHAdd |
2144                              kNoSAD |
2145                              kNoDotProd;
2146             return TrySetVectorLength(type, 8);
2147           case DataType::Type::kInt16:
2148             *restrictions |= kNoDiv |
2149                              kNoAbs |
2150                              kNoSignedHAdd |
2151                              kNoUnroundedHAdd |
2152                              kNoSAD;
2153             return TrySetVectorLength(type, 8);
2154           case DataType::Type::kInt32:
2155             *restrictions |= kNoDiv | kNoSAD;
2156             return TrySetVectorLength(type, 4);
2157           case DataType::Type::kInt64:
2158             *restrictions |= kNoMul | kNoDiv | kNoShr | kNoAbs | kNoSAD;
2159             return TrySetVectorLength(type, 2);
2160           case DataType::Type::kFloat32:
2161             *restrictions |= kNoReduction;
2162             return TrySetVectorLength(type, 4);
2163           case DataType::Type::kFloat64:
2164             *restrictions |= kNoReduction;
2165             return TrySetVectorLength(type, 2);
2166           default:
2167             break;
2168         }  // switch type
2169       }
2170       return false;
2171     default:
2172       return false;
2173   }  // switch instruction set
2174 }
2175 
TrySetVectorLengthImpl(uint32_t length)2176 bool HLoopOptimization::TrySetVectorLengthImpl(uint32_t length) {
2177   DCHECK(IsPowerOfTwo(length) && length >= 2u);
2178   // First time set?
2179   if (vector_length_ == 0) {
2180     vector_length_ = length;
2181   }
2182   // Different types are acceptable within a loop-body, as long as all the corresponding vector
2183   // lengths match exactly to obtain a uniform traversal through the vector iteration space
2184   // (idiomatic exceptions to this rule can be handled by further unrolling sub-expressions).
2185   return vector_length_ == length;
2186 }
2187 
GenerateVecInv(HInstruction * org,DataType::Type type)2188 void HLoopOptimization::GenerateVecInv(HInstruction* org, DataType::Type type) {
2189   if (vector_map_->find(org) == vector_map_->end()) {
2190     // In scalar code, just use a self pass-through for scalar invariants
2191     // (viz. expression remains itself).
2192     if (synthesis_mode_ == LoopSynthesisMode::kSequential) {
2193       vector_map_->Put(org, org);
2194       return;
2195     }
2196     // In vector code, explicit scalar expansion is needed.
2197     HInstruction* vector = nullptr;
2198     auto it = vector_permanent_map_->find(org);
2199     if (it != vector_permanent_map_->end()) {
2200       vector = it->second;  // reuse during unrolling
2201     } else {
2202       // Generates ReplicateScalar( (optional_type_conv) org ).
2203       HInstruction* input = org;
2204       DataType::Type input_type = input->GetType();
2205       if (type != input_type && (type == DataType::Type::kInt64 ||
2206                                  input_type == DataType::Type::kInt64)) {
2207         input = Insert(vector_preheader_,
2208                        new (global_allocator_) HTypeConversion(type, input, kNoDexPc));
2209       }
2210       vector = new (global_allocator_)
2211           HVecReplicateScalar(global_allocator_, input, type, vector_length_, kNoDexPc);
2212       vector_permanent_map_->Put(org, Insert(vector_preheader_, vector));
2213       MaybeInsertInVectorExternalSet(vector);
2214     }
2215     vector_map_->Put(org, vector);
2216   }
2217 }
2218 
GenerateVecSub(HInstruction * org,HInstruction * offset)2219 void HLoopOptimization::GenerateVecSub(HInstruction* org, HInstruction* offset) {
2220   if (vector_map_->find(org) == vector_map_->end()) {
2221     HInstruction* subscript = vector_index_;
2222     int64_t value = 0;
2223     if (!IsInt64AndGet(offset, &value) || value != 0) {
2224       subscript = new (global_allocator_) HAdd(DataType::Type::kInt32, subscript, offset);
2225       if (org->IsPhi()) {
2226         Insert(vector_body_, subscript);  // lacks layout placeholder
2227       }
2228     }
2229     vector_map_->Put(org, subscript);
2230   }
2231 }
2232 
GenerateVecMem(HInstruction * org,HInstruction * opa,HInstruction * opb,HInstruction * offset,DataType::Type type)2233 void HLoopOptimization::GenerateVecMem(HInstruction* org,
2234                                        HInstruction* opa,
2235                                        HInstruction* opb,
2236                                        HInstruction* offset,
2237                                        DataType::Type type) {
2238   uint32_t dex_pc = org->GetDexPc();
2239   HInstruction* vector = nullptr;
2240   if (synthesis_mode_ == LoopSynthesisMode::kVector) {
2241     // Vector store or load.
2242     bool is_string_char_at = false;
2243     HInstruction* base = org->InputAt(0);
2244     if (opb != nullptr) {
2245       vector = new (global_allocator_) HVecStore(
2246           global_allocator_, base, opa, opb, type, org->GetSideEffects(), vector_length_, dex_pc);
2247     } else  {
2248       is_string_char_at = org->AsArrayGet()->IsStringCharAt();
2249       vector = new (global_allocator_) HVecLoad(global_allocator_,
2250                                                 base,
2251                                                 opa,
2252                                                 type,
2253                                                 org->GetSideEffects(),
2254                                                 vector_length_,
2255                                                 is_string_char_at,
2256                                                 dex_pc);
2257     }
2258     // Known (forced/adjusted/original) alignment?
2259     if (vector_dynamic_peeling_candidate_ != nullptr) {
2260       if (vector_dynamic_peeling_candidate_->offset == offset &&  // TODO: diffs too?
2261           DataType::Size(vector_dynamic_peeling_candidate_->type) == DataType::Size(type) &&
2262           vector_dynamic_peeling_candidate_->is_string_char_at == is_string_char_at) {
2263         vector->AsVecMemoryOperation()->SetAlignment(  // forced
2264             Alignment(GetVectorSizeInBytes(), 0));
2265       }
2266     } else {
2267       vector->AsVecMemoryOperation()->SetAlignment(  // adjusted/original
2268           ComputeAlignment(offset, type, is_string_char_at, vector_static_peeling_factor_));
2269     }
2270   } else {
2271     // Scalar store or load.
2272     DCHECK(synthesis_mode_ == LoopSynthesisMode::kSequential);
2273     if (opb != nullptr) {
2274       DataType::Type component_type = org->AsArraySet()->GetComponentType();
2275       vector = new (global_allocator_) HArraySet(
2276           org->InputAt(0), opa, opb, component_type, org->GetSideEffects(), dex_pc);
2277     } else  {
2278       bool is_string_char_at = org->AsArrayGet()->IsStringCharAt();
2279       vector = new (global_allocator_) HArrayGet(
2280           org->InputAt(0), opa, org->GetType(), org->GetSideEffects(), dex_pc, is_string_char_at);
2281     }
2282   }
2283   vector_map_->Put(org, vector);
2284 }
2285 
GenerateVecReductionPhi(HPhi * orig_phi)2286 void HLoopOptimization::GenerateVecReductionPhi(HPhi* orig_phi) {
2287   DCHECK(reductions_->find(orig_phi) != reductions_->end());
2288   DCHECK(reductions_->Get(orig_phi->InputAt(1)) == orig_phi);
2289   HInstruction* vector = nullptr;
2290   if (synthesis_mode_ == LoopSynthesisMode::kSequential) {
2291     HPhi* new_phi = new (global_allocator_) HPhi(
2292         global_allocator_, kNoRegNumber, 0, orig_phi->GetType());
2293     vector_header_->AddPhi(new_phi);
2294     vector = new_phi;
2295   } else {
2296     // Link vector reduction back to prior unrolled update, or a first phi.
2297     auto it = vector_permanent_map_->find(orig_phi);
2298     if (it != vector_permanent_map_->end()) {
2299       vector = it->second;
2300     } else {
2301       HPhi* new_phi = new (global_allocator_) HPhi(
2302           global_allocator_, kNoRegNumber, 0, HVecOperation::kSIMDType);
2303       vector_header_->AddPhi(new_phi);
2304       vector = new_phi;
2305     }
2306   }
2307   vector_map_->Put(orig_phi, vector);
2308 }
2309 
GenerateVecReductionPhiInputs(HPhi * phi,HInstruction * reduction)2310 void HLoopOptimization::GenerateVecReductionPhiInputs(HPhi* phi, HInstruction* reduction) {
2311   HInstruction* new_phi = vector_map_->Get(phi);
2312   HInstruction* new_init = reductions_->Get(phi);
2313   HInstruction* new_red = vector_map_->Get(reduction);
2314   // Link unrolled vector loop back to new phi.
2315   for (; !new_phi->IsPhi(); new_phi = vector_permanent_map_->Get(new_phi)) {
2316     DCHECK(new_phi->IsVecOperation());
2317   }
2318   // Prepare the new initialization.
2319   if (synthesis_mode_ == LoopSynthesisMode::kVector) {
2320     // Generate a [initial, 0, .., 0] vector for add or
2321     // a [initial, initial, .., initial] vector for min/max.
2322     HVecOperation* red_vector = new_red->AsVecOperation();
2323     HVecReduce::ReductionKind kind = GetReductionKind(red_vector);
2324     uint32_t vector_length = red_vector->GetVectorLength();
2325     DataType::Type type = red_vector->GetPackedType();
2326     if (kind == HVecReduce::ReductionKind::kSum) {
2327       new_init = Insert(vector_preheader_,
2328                         new (global_allocator_) HVecSetScalars(global_allocator_,
2329                                                                &new_init,
2330                                                                type,
2331                                                                vector_length,
2332                                                                1,
2333                                                                kNoDexPc));
2334     } else {
2335       new_init = Insert(vector_preheader_,
2336                         new (global_allocator_) HVecReplicateScalar(global_allocator_,
2337                                                                     new_init,
2338                                                                     type,
2339                                                                     vector_length,
2340                                                                     kNoDexPc));
2341     }
2342     MaybeInsertInVectorExternalSet(new_init);
2343   } else {
2344     new_init = ReduceAndExtractIfNeeded(new_init);
2345   }
2346   // Set the phi inputs.
2347   DCHECK(new_phi->IsPhi());
2348   new_phi->AsPhi()->AddInput(new_init);
2349   new_phi->AsPhi()->AddInput(new_red);
2350   // New feed value for next phi (safe mutation in iteration).
2351   reductions_->find(phi)->second = new_phi;
2352 }
2353 
ReduceAndExtractIfNeeded(HInstruction * instruction)2354 HInstruction* HLoopOptimization::ReduceAndExtractIfNeeded(HInstruction* instruction) {
2355   if (instruction->IsPhi()) {
2356     HInstruction* input = instruction->InputAt(1);
2357     if (HVecOperation::ReturnsSIMDValue(input)) {
2358       DCHECK(!input->IsPhi());
2359       HVecOperation* input_vector = input->AsVecOperation();
2360       uint32_t vector_length = input_vector->GetVectorLength();
2361       DataType::Type type = input_vector->GetPackedType();
2362       HVecReduce::ReductionKind kind = GetReductionKind(input_vector);
2363       HBasicBlock* exit = instruction->GetBlock()->GetSuccessors()[0];
2364       // Generate a vector reduction and scalar extract
2365       //    x = REDUCE( [x_1, .., x_n] )
2366       //    y = x_1
2367       // along the exit of the defining loop.
2368       HVecReduce* reduce = new (global_allocator_) HVecReduce(
2369           global_allocator_, instruction, type, vector_length, kind, kNoDexPc);
2370       exit->InsertInstructionBefore(reduce, exit->GetFirstInstruction());
2371       MaybeInsertInVectorExternalSet(reduce);
2372       instruction = new (global_allocator_) HVecExtractScalar(
2373           global_allocator_, reduce, type, vector_length, 0, kNoDexPc);
2374       exit->InsertInstructionAfter(instruction, reduce);
2375 
2376       MaybeInsertInVectorExternalSet(instruction);
2377     }
2378   }
2379   return instruction;
2380 }
2381 
2382 #define GENERATE_VEC(x, y)                                     \
2383   if (synthesis_mode_ == LoopSynthesisMode::kVector) {         \
2384     vector = (x);                                              \
2385   } else {                                                     \
2386     DCHECK(synthesis_mode_ == LoopSynthesisMode::kSequential); \
2387     vector = (y);                                              \
2388   }                                                            \
2389   break;
2390 
2391 // Some instructions in the scalar loop body can only occur in loops with control flow; for such
2392 // loops we don't support clean ups loop (generated via kSequential); see TryVectorizePredicated.
2393 #define GENERATE_PRED_VEC(x)                              \
2394   DCHECK_EQ(synthesis_mode_, LoopSynthesisMode::kVector); \
2395   vector = (x);                                           \
2396   break;
2397 
GenerateVecOp(HInstruction * org,HInstruction * opa,HInstruction * opb,DataType::Type type)2398 HInstruction* HLoopOptimization::GenerateVecOp(HInstruction* org,
2399                                                HInstruction* opa,
2400                                                HInstruction* opb,
2401                                                DataType::Type type) {
2402   uint32_t dex_pc = org->GetDexPc();
2403   HInstruction* vector = nullptr;
2404   DataType::Type org_type = org->GetType();
2405   switch (org->GetKind()) {
2406     case HInstruction::kNeg:
2407       DCHECK(opb == nullptr);
2408       GENERATE_VEC(
2409         new (global_allocator_) HVecNeg(global_allocator_, opa, type, vector_length_, dex_pc),
2410         new (global_allocator_) HNeg(org_type, opa, dex_pc));
2411     case HInstruction::kNot:
2412       DCHECK(opb == nullptr);
2413       GENERATE_VEC(
2414         new (global_allocator_) HVecNot(global_allocator_, opa, type, vector_length_, dex_pc),
2415         new (global_allocator_) HNot(org_type, opa, dex_pc));
2416     case HInstruction::kBooleanNot:
2417       DCHECK(opb == nullptr);
2418       GENERATE_VEC(
2419         new (global_allocator_) HVecNot(global_allocator_, opa, type, vector_length_, dex_pc),
2420         new (global_allocator_) HBooleanNot(opa, dex_pc));
2421     case HInstruction::kTypeConversion:
2422       DCHECK(opb == nullptr);
2423       GENERATE_VEC(
2424         new (global_allocator_) HVecCnv(global_allocator_, opa, type, vector_length_, dex_pc),
2425         new (global_allocator_) HTypeConversion(org_type, opa, dex_pc));
2426     case HInstruction::kAdd:
2427       GENERATE_VEC(
2428         new (global_allocator_) HVecAdd(global_allocator_, opa, opb, type, vector_length_, dex_pc),
2429         new (global_allocator_) HAdd(org_type, opa, opb, dex_pc));
2430     case HInstruction::kSub:
2431       GENERATE_VEC(
2432         new (global_allocator_) HVecSub(global_allocator_, opa, opb, type, vector_length_, dex_pc),
2433         new (global_allocator_) HSub(org_type, opa, opb, dex_pc));
2434     case HInstruction::kMul:
2435       GENERATE_VEC(
2436         new (global_allocator_) HVecMul(global_allocator_, opa, opb, type, vector_length_, dex_pc),
2437         new (global_allocator_) HMul(org_type, opa, opb, dex_pc));
2438     case HInstruction::kDiv:
2439       GENERATE_VEC(
2440         new (global_allocator_) HVecDiv(global_allocator_, opa, opb, type, vector_length_, dex_pc),
2441         new (global_allocator_) HDiv(org_type, opa, opb, dex_pc));
2442     case HInstruction::kAnd:
2443       GENERATE_VEC(
2444         new (global_allocator_) HVecAnd(global_allocator_, opa, opb, type, vector_length_, dex_pc),
2445         new (global_allocator_) HAnd(org_type, opa, opb, dex_pc));
2446     case HInstruction::kOr:
2447       GENERATE_VEC(
2448         new (global_allocator_) HVecOr(global_allocator_, opa, opb, type, vector_length_, dex_pc),
2449         new (global_allocator_) HOr(org_type, opa, opb, dex_pc));
2450     case HInstruction::kXor:
2451       GENERATE_VEC(
2452         new (global_allocator_) HVecXor(global_allocator_, opa, opb, type, vector_length_, dex_pc),
2453         new (global_allocator_) HXor(org_type, opa, opb, dex_pc));
2454     case HInstruction::kShl:
2455       GENERATE_VEC(
2456         new (global_allocator_) HVecShl(global_allocator_, opa, opb, type, vector_length_, dex_pc),
2457         new (global_allocator_) HShl(org_type, opa, opb, dex_pc));
2458     case HInstruction::kShr:
2459       GENERATE_VEC(
2460         new (global_allocator_) HVecShr(global_allocator_, opa, opb, type, vector_length_, dex_pc),
2461         new (global_allocator_) HShr(org_type, opa, opb, dex_pc));
2462     case HInstruction::kUShr:
2463       GENERATE_VEC(
2464         new (global_allocator_) HVecUShr(global_allocator_, opa, opb, type, vector_length_, dex_pc),
2465         new (global_allocator_) HUShr(org_type, opa, opb, dex_pc));
2466     case HInstruction::kAbs:
2467       DCHECK(opb == nullptr);
2468       GENERATE_VEC(
2469         new (global_allocator_) HVecAbs(global_allocator_, opa, type, vector_length_, dex_pc),
2470         new (global_allocator_) HAbs(org_type, opa, dex_pc));
2471     case HInstruction::kEqual:
2472       GENERATE_PRED_VEC(
2473         new (global_allocator_)
2474           HVecEqual(global_allocator_, opa, opb, type, vector_length_, dex_pc));
2475     case HInstruction::kNotEqual:
2476       GENERATE_PRED_VEC(
2477         new (global_allocator_)
2478           HVecNotEqual(global_allocator_, opa, opb, type, vector_length_, dex_pc));
2479     case HInstruction::kLessThan:
2480       GENERATE_PRED_VEC(
2481         new (global_allocator_)
2482           HVecLessThan(global_allocator_, opa, opb, type, vector_length_, dex_pc));
2483     case HInstruction::kLessThanOrEqual:
2484       GENERATE_PRED_VEC(
2485         new (global_allocator_)
2486           HVecLessThanOrEqual(global_allocator_, opa, opb, type, vector_length_, dex_pc));
2487     case HInstruction::kGreaterThan:
2488       GENERATE_PRED_VEC(
2489         new (global_allocator_)
2490           HVecGreaterThan(global_allocator_, opa, opb, type, vector_length_, dex_pc));
2491     case HInstruction::kGreaterThanOrEqual:
2492       GENERATE_PRED_VEC(
2493         new (global_allocator_)
2494           HVecGreaterThanOrEqual(global_allocator_, opa, opb, type, vector_length_, dex_pc));
2495     case HInstruction::kBelow:
2496       GENERATE_PRED_VEC(
2497         new (global_allocator_)
2498           HVecBelow(global_allocator_, opa, opb, type, vector_length_, dex_pc));
2499     case HInstruction::kBelowOrEqual:
2500       GENERATE_PRED_VEC(
2501         new (global_allocator_)
2502           HVecBelowOrEqual(global_allocator_, opa, opb, type, vector_length_, dex_pc));
2503     case HInstruction::kAbove:
2504       GENERATE_PRED_VEC(
2505         new (global_allocator_)
2506           HVecAbove(global_allocator_, opa, opb, type, vector_length_, dex_pc));
2507     case HInstruction::kAboveOrEqual:
2508       GENERATE_PRED_VEC(
2509         new (global_allocator_)
2510           HVecAboveOrEqual(global_allocator_, opa, opb, type, vector_length_, dex_pc));
2511     default:
2512       break;
2513   }  // switch
2514   CHECK(vector != nullptr) << "Unsupported SIMD operator";
2515   vector_map_->Put(org, vector);
2516   return vector;
2517 }
2518 
2519 #undef GENERATE_VEC
2520 
2521 //
2522 // Vectorization idioms.
2523 //
2524 
2525 // Method recognizes the following idioms:
2526 //   rounding  halving add (a + b + 1) >> 1 for unsigned/signed operands a, b
2527 //   truncated halving add (a + b)     >> 1 for unsigned/signed operands a, b
2528 // Provided that the operands are promoted to a wider form to do the arithmetic and
2529 // then cast back to narrower form, the idioms can be mapped into efficient SIMD
2530 // implementation that operates directly in narrower form (plus one extra bit).
2531 // TODO: current version recognizes implicit byte/short/char widening only;
2532 //       explicit widening from int to long could be added later.
VectorizeHalvingAddIdiom(LoopNode * node,HInstruction * instruction,bool generate_code,DataType::Type type,uint64_t restrictions)2533 bool HLoopOptimization::VectorizeHalvingAddIdiom(LoopNode* node,
2534                                                  HInstruction* instruction,
2535                                                  bool generate_code,
2536                                                  DataType::Type type,
2537                                                  uint64_t restrictions) {
2538   // Test for top level arithmetic shift right x >> 1 or logical shift right x >>> 1
2539   // (note whether the sign bit in wider precision is shifted in has no effect
2540   // on the narrow precision computed by the idiom).
2541   if ((instruction->IsShr() ||
2542        instruction->IsUShr()) &&
2543       IsInt64Value(instruction->InputAt(1), 1)) {
2544     // Test for (a + b + c) >> 1 for optional constant c.
2545     HInstruction* a = nullptr;
2546     HInstruction* b = nullptr;
2547     int64_t       c = 0;
2548     if (IsAddConst2(graph_, instruction->InputAt(0), /*out*/ &a, /*out*/ &b, /*out*/ &c)) {
2549       // Accept c == 1 (rounded) or c == 0 (not rounded).
2550       bool is_rounded = false;
2551       if (c == 1) {
2552         is_rounded = true;
2553       } else if (c != 0) {
2554         return false;
2555       }
2556       // Accept consistent zero or sign extension on operands a and b.
2557       HInstruction* r = nullptr;
2558       HInstruction* s = nullptr;
2559       bool is_unsigned = false;
2560       if (!IsNarrowerOperands(a, b, type, &r, &s, &is_unsigned)) {
2561         return false;
2562       }
2563       // Deal with vector restrictions.
2564       if ((is_unsigned && HasVectorRestrictions(restrictions, kNoUnsignedHAdd)) ||
2565           (!is_unsigned && HasVectorRestrictions(restrictions, kNoSignedHAdd)) ||
2566           (!is_rounded && HasVectorRestrictions(restrictions, kNoUnroundedHAdd))) {
2567         return false;
2568       }
2569       // Accept recognized halving add for vectorizable operands. Vectorized code uses the
2570       // shorthand idiomatic operation. Sequential code uses the original scalar expressions.
2571       DCHECK(r != nullptr && s != nullptr);
2572       if (generate_code && synthesis_mode_ != LoopSynthesisMode::kVector) {  // de-idiom
2573         r = instruction->InputAt(0);
2574         s = instruction->InputAt(1);
2575       }
2576       if (VectorizeUse(node, r, generate_code, type, restrictions) &&
2577           VectorizeUse(node, s, generate_code, type, restrictions)) {
2578         if (generate_code) {
2579           if (synthesis_mode_ == LoopSynthesisMode::kVector) {
2580             vector_map_->Put(instruction, new (global_allocator_) HVecHalvingAdd(
2581                 global_allocator_,
2582                 vector_map_->Get(r),
2583                 vector_map_->Get(s),
2584                 HVecOperation::ToProperType(type, is_unsigned),
2585                 vector_length_,
2586                 is_rounded,
2587                 kNoDexPc));
2588             MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorizedIdiom);
2589           } else {
2590             GenerateVecOp(instruction, vector_map_->Get(r), vector_map_->Get(s), type);
2591           }
2592         }
2593         return true;
2594       }
2595     }
2596   }
2597   return false;
2598 }
2599 
2600 // Method recognizes the following idiom:
2601 //   q += ABS(a - b) for signed operands a, b
2602 // Provided that the operands have the same type or are promoted to a wider form.
2603 // Since this may involve a vector length change, the idiom is handled by going directly
2604 // to a sad-accumulate node (rather than relying combining finer grained nodes later).
2605 // TODO: unsigned SAD too?
VectorizeSADIdiom(LoopNode * node,HInstruction * instruction,bool generate_code,DataType::Type reduction_type,uint64_t restrictions)2606 bool HLoopOptimization::VectorizeSADIdiom(LoopNode* node,
2607                                           HInstruction* instruction,
2608                                           bool generate_code,
2609                                           DataType::Type reduction_type,
2610                                           uint64_t restrictions) {
2611   // Filter integral "q += ABS(a - b);" reduction, where ABS and SUB
2612   // are done in the same precision (either int or long).
2613   if (!instruction->IsAdd() ||
2614       (reduction_type != DataType::Type::kInt32 && reduction_type != DataType::Type::kInt64)) {
2615     return false;
2616   }
2617   HInstruction* acc = instruction->InputAt(0);
2618   HInstruction* abs = instruction->InputAt(1);
2619   HInstruction* a = nullptr;
2620   HInstruction* b = nullptr;
2621   if (abs->IsAbs() &&
2622       abs->GetType() == reduction_type &&
2623       IsSubConst2(graph_, abs->InputAt(0), /*out*/ &a, /*out*/ &b)) {
2624     DCHECK(a != nullptr && b != nullptr);
2625   } else {
2626     return false;
2627   }
2628   // Accept same-type or consistent sign extension for narrower-type on operands a and b.
2629   // The same-type or narrower operands are called r (a or lower) and s (b or lower).
2630   // We inspect the operands carefully to pick the most suited type.
2631   HInstruction* r = a;
2632   HInstruction* s = b;
2633   bool is_unsigned = false;
2634   DataType::Type sub_type = GetNarrowerType(a, b);
2635   if (reduction_type != sub_type &&
2636       (!IsNarrowerOperands(a, b, sub_type, &r, &s, &is_unsigned) || is_unsigned)) {
2637     return false;
2638   }
2639   // Try same/narrower type and deal with vector restrictions.
2640   if (!TrySetVectorType(sub_type, &restrictions) ||
2641       HasVectorRestrictions(restrictions, kNoSAD) ||
2642       (reduction_type != sub_type && HasVectorRestrictions(restrictions, kNoWideSAD))) {
2643     return false;
2644   }
2645   // Accept SAD idiom for vectorizable operands. Vectorized code uses the shorthand
2646   // idiomatic operation. Sequential code uses the original scalar expressions.
2647   DCHECK(r != nullptr && s != nullptr);
2648   if (generate_code && synthesis_mode_ != LoopSynthesisMode::kVector) {  // de-idiom
2649     r = s = abs->InputAt(0);
2650   }
2651   if (VectorizeUse(node, acc, generate_code, sub_type, restrictions) &&
2652       VectorizeUse(node, r, generate_code, sub_type, restrictions) &&
2653       VectorizeUse(node, s, generate_code, sub_type, restrictions)) {
2654     if (generate_code) {
2655       if (synthesis_mode_ == LoopSynthesisMode::kVector) {
2656         vector_map_->Put(instruction, new (global_allocator_) HVecSADAccumulate(
2657             global_allocator_,
2658             vector_map_->Get(acc),
2659             vector_map_->Get(r),
2660             vector_map_->Get(s),
2661             HVecOperation::ToProperType(reduction_type, is_unsigned),
2662             GetOtherVL(reduction_type, sub_type, vector_length_),
2663             kNoDexPc));
2664         MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorizedIdiom);
2665       } else {
2666         // "GenerateVecOp()" must not be called more than once for each original loop body
2667         // instruction. As the SAD idiom processes both "current" instruction ("instruction")
2668         // and its ABS input in one go, we must check that for the scalar case the ABS instruction
2669         // has not yet been processed.
2670         if (vector_map_->find(abs) == vector_map_->end()) {
2671           GenerateVecOp(abs, vector_map_->Get(r), nullptr, reduction_type);
2672         }
2673         GenerateVecOp(instruction, vector_map_->Get(acc), vector_map_->Get(abs), reduction_type);
2674       }
2675     }
2676     return true;
2677   }
2678   return false;
2679 }
2680 
2681 // Method recognises the following dot product idiom:
2682 //   q += a * b for operands a, b whose type is narrower than the reduction one.
2683 // Provided that the operands have the same type or are promoted to a wider form.
2684 // Since this may involve a vector length change, the idiom is handled by going directly
2685 // to a dot product node (rather than relying combining finer grained nodes later).
VectorizeDotProdIdiom(LoopNode * node,HInstruction * instruction,bool generate_code,DataType::Type reduction_type,uint64_t restrictions)2686 bool HLoopOptimization::VectorizeDotProdIdiom(LoopNode* node,
2687                                               HInstruction* instruction,
2688                                               bool generate_code,
2689                                               DataType::Type reduction_type,
2690                                               uint64_t restrictions) {
2691   if (!instruction->IsAdd() || reduction_type != DataType::Type::kInt32) {
2692     return false;
2693   }
2694 
2695   HInstruction* const acc = instruction->InputAt(0);
2696   HInstruction* const mul = instruction->InputAt(1);
2697   if (!mul->IsMul() || mul->GetType() != reduction_type) {
2698     return false;
2699   }
2700 
2701   HInstruction* const mul_left = mul->InputAt(0);
2702   HInstruction* const mul_right = mul->InputAt(1);
2703   HInstruction* r = mul_left;
2704   HInstruction* s = mul_right;
2705   DataType::Type op_type = GetNarrowerType(mul_left, mul_right);
2706   bool is_unsigned = false;
2707 
2708   if (!IsNarrowerOperands(mul_left, mul_right, op_type, &r, &s, &is_unsigned)) {
2709     return false;
2710   }
2711   op_type = HVecOperation::ToProperType(op_type, is_unsigned);
2712 
2713   if (!TrySetVectorType(op_type, &restrictions) ||
2714       HasVectorRestrictions(restrictions, kNoDotProd)) {
2715     return false;
2716   }
2717 
2718   DCHECK(r != nullptr && s != nullptr);
2719   // Accept dot product idiom for vectorizable operands. Vectorized code uses the shorthand
2720   // idiomatic operation. Sequential code uses the original scalar expressions.
2721   if (generate_code && synthesis_mode_ != LoopSynthesisMode::kVector) {  // de-idiom
2722     r = mul_left;
2723     s = mul_right;
2724   }
2725   if (VectorizeUse(node, acc, generate_code, op_type, restrictions) &&
2726       VectorizeUse(node, r, generate_code, op_type, restrictions) &&
2727       VectorizeUse(node, s, generate_code, op_type, restrictions)) {
2728     if (generate_code) {
2729       if (synthesis_mode_ == LoopSynthesisMode::kVector) {
2730         vector_map_->Put(instruction, new (global_allocator_) HVecDotProd(
2731             global_allocator_,
2732             vector_map_->Get(acc),
2733             vector_map_->Get(r),
2734             vector_map_->Get(s),
2735             reduction_type,
2736             is_unsigned,
2737             GetOtherVL(reduction_type, op_type, vector_length_),
2738             kNoDexPc));
2739         MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorizedIdiom);
2740       } else {
2741         // "GenerateVecOp()" must not be called more than once for each original loop body
2742         // instruction. As the DotProd idiom processes both "current" instruction ("instruction")
2743         // and its MUL input in one go, we must check that for the scalar case the MUL instruction
2744         // has not yet been processed.
2745         if (vector_map_->find(mul) == vector_map_->end()) {
2746           GenerateVecOp(mul, vector_map_->Get(r), vector_map_->Get(s), reduction_type);
2747         }
2748         GenerateVecOp(instruction, vector_map_->Get(acc), vector_map_->Get(mul), reduction_type);
2749       }
2750     }
2751     return true;
2752   }
2753   return false;
2754 }
2755 
VectorizeIfCondition(LoopNode * node,HInstruction * hif,bool generate_code,uint64_t restrictions)2756 bool HLoopOptimization::VectorizeIfCondition(LoopNode* node,
2757                                              HInstruction* hif,
2758                                              bool generate_code,
2759                                              uint64_t restrictions) {
2760   DCHECK(hif->IsIf());
2761   HInstruction* if_input = hif->InputAt(0);
2762 
2763   if (!if_input->HasOnlyOneNonEnvironmentUse()) {
2764     // Avoid the complications of the condition used as materialized boolean.
2765     return false;
2766   }
2767 
2768   if (!if_input->IsCondition()) {
2769     return false;
2770   }
2771 
2772   HCondition* cond = if_input->AsCondition();
2773   HInstruction* opa = cond->InputAt(0);
2774   HInstruction* opb = cond->InputAt(1);
2775   DataType::Type type = GetNarrowerType(opa, opb);
2776 
2777   if (!DataType::IsIntegralType(type)) {
2778     return false;
2779   }
2780 
2781   bool is_unsigned = false;
2782   HInstruction* opa_promoted = opa;
2783   HInstruction* opb_promoted = opb;
2784   bool is_int_case = DataType::Type::kInt32 == opa->GetType() &&
2785                      DataType::Type::kInt32 == opb->GetType();
2786 
2787   // Condition arguments should be either both int32 or consistently extended signed/unsigned
2788   // narrower operands.
2789   if (!is_int_case &&
2790       !IsNarrowerOperands(opa, opb, type, &opa_promoted, &opb_promoted, &is_unsigned)) {
2791     return false;
2792   }
2793   type = HVecOperation::ToProperType(type, is_unsigned);
2794 
2795   // For narrow types, explicit type conversion may have been
2796   // optimized way, so set the no hi bits restriction here.
2797   if (DataType::Size(type) <= 2) {
2798     restrictions |= kNoHiBits;
2799   }
2800 
2801   if (!TrySetVectorType(type, &restrictions) ||
2802       HasVectorRestrictions(restrictions, kNoIfCond)) {
2803     return false;
2804   }
2805 
2806   if (generate_code && synthesis_mode_ != LoopSynthesisMode::kVector) {  // de-idiom
2807     opa_promoted = opa;
2808     opb_promoted = opb;
2809   }
2810 
2811   if (VectorizeUse(node, opa_promoted, generate_code, type, restrictions) &&
2812       VectorizeUse(node, opb_promoted, generate_code, type, restrictions)) {
2813     if (generate_code) {
2814       HInstruction* vec_cond = GenerateVecOp(cond,
2815                                              vector_map_->Get(opa_promoted),
2816                                              vector_map_->Get(opb_promoted),
2817                                              type);
2818       DCHECK_EQ(synthesis_mode_, LoopSynthesisMode::kVector);
2819       HInstruction* vec_pred_not = new (global_allocator_)
2820           HVecPredNot(global_allocator_, vec_cond, type, vector_length_, hif->GetDexPc());
2821 
2822       vector_map_->Put(hif, vec_pred_not);
2823       BlockPredicateInfo* pred_info = predicate_info_map_->Get(hif->GetBlock());
2824       pred_info->SetControlFlowInfo(vec_cond->AsVecPredSetOperation(),
2825                                     vec_pred_not->AsVecPredSetOperation());
2826     }
2827     return true;
2828   }
2829 
2830   return false;
2831 }
2832 
2833 //
2834 // Vectorization heuristics.
2835 //
2836 
ComputeAlignment(HInstruction * offset,DataType::Type type,bool is_string_char_at,uint32_t peeling)2837 Alignment HLoopOptimization::ComputeAlignment(HInstruction* offset,
2838                                               DataType::Type type,
2839                                               bool is_string_char_at,
2840                                               uint32_t peeling) {
2841   // Combine the alignment and hidden offset that is guaranteed by
2842   // the Android runtime with a known starting index adjusted as bytes.
2843   int64_t value = 0;
2844   if (IsInt64AndGet(offset, /*out*/ &value)) {
2845     uint32_t start_offset =
2846         HiddenOffset(type, is_string_char_at) + (value + peeling) * DataType::Size(type);
2847     return Alignment(BaseAlignment(), start_offset & (BaseAlignment() - 1u));
2848   }
2849   // Otherwise, the Android runtime guarantees at least natural alignment.
2850   return Alignment(DataType::Size(type), 0);
2851 }
2852 
SetAlignmentStrategy(const ScopedArenaVector<uint32_t> & peeling_votes,const ArrayReference * peeling_candidate)2853 void HLoopOptimization::SetAlignmentStrategy(const ScopedArenaVector<uint32_t>& peeling_votes,
2854                                              const ArrayReference* peeling_candidate) {
2855   // Current heuristic: pick the best static loop peeling factor, if any,
2856   // or otherwise use dynamic loop peeling on suggested peeling candidate.
2857   uint32_t max_vote = 0;
2858   for (size_t i = 0; i < peeling_votes.size(); i++) {
2859     if (peeling_votes[i] > max_vote) {
2860       max_vote = peeling_votes[i];
2861       vector_static_peeling_factor_ = i;
2862     }
2863   }
2864   if (max_vote == 0) {
2865     vector_dynamic_peeling_candidate_ = peeling_candidate;
2866   }
2867 }
2868 
MaxNumberPeeled()2869 uint32_t HLoopOptimization::MaxNumberPeeled() {
2870   if (vector_dynamic_peeling_candidate_ != nullptr) {
2871     return vector_length_ - 1u;  // worst-case
2872   }
2873   return vector_static_peeling_factor_;  // known exactly
2874 }
2875 
IsVectorizationProfitable(int64_t trip_count)2876 bool HLoopOptimization::IsVectorizationProfitable(int64_t trip_count) {
2877   // Current heuristic: non-empty body with sufficient number of iterations (if known).
2878   // TODO: refine by looking at e.g. operation count, alignment, etc.
2879   // TODO: trip count is really unsigned entity, provided the guarding test
2880   //       is satisfied; deal with this more carefully later
2881   uint32_t max_peel = MaxNumberPeeled();
2882   // Peeling is not supported in predicated mode.
2883   DCHECK_IMPLIES(IsInPredicatedVectorizationMode(), max_peel == 0u);
2884   if (vector_length_ == 0) {
2885     return false;  // nothing found
2886   } else if (trip_count < 0) {
2887     return false;  // guard against non-taken/large
2888   } else if ((0 < trip_count) && (trip_count < (vector_length_ + max_peel))) {
2889     return false;  // insufficient iterations
2890   }
2891   return true;
2892 }
2893 
2894 //
2895 // Helpers.
2896 //
2897 
TrySetPhiInduction(HPhi * phi,bool restrict_uses)2898 bool HLoopOptimization::TrySetPhiInduction(HPhi* phi, bool restrict_uses) {
2899   // Start with empty phi induction.
2900   iset_->clear();
2901 
2902   // Special case Phis that have equivalent in a debuggable setup. Our graph checker isn't
2903   // smart enough to follow strongly connected components (and it's probably not worth
2904   // it to make it so). See b/33775412.
2905   if (graph_->IsDebuggable() && phi->HasEquivalentPhi()) {
2906     return false;
2907   }
2908 
2909   // Lookup phi induction cycle.
2910   ArenaSet<HInstruction*>* set = induction_range_.LookupCycle(phi);
2911   if (set != nullptr) {
2912     for (HInstruction* i : *set) {
2913       // Check that, other than instructions that are no longer in the graph (removed earlier)
2914       // each instruction is removable and, when restrict uses are requested, other than for phi,
2915       // all uses are contained within the cycle.
2916       if (!i->IsInBlock()) {
2917         continue;
2918       } else if (!i->IsRemovable()) {
2919         return false;
2920       } else if (i != phi && restrict_uses) {
2921         // Deal with regular uses.
2922         for (const HUseListNode<HInstruction*>& use : i->GetUses()) {
2923           if (set->find(use.GetUser()) == set->end()) {
2924             return false;
2925           }
2926         }
2927       }
2928       iset_->insert(i);  // copy
2929     }
2930     return true;
2931   }
2932   return false;
2933 }
2934 
TrySetPhiReduction(HPhi * phi)2935 bool HLoopOptimization::TrySetPhiReduction(HPhi* phi) {
2936   DCHECK(phi->IsLoopHeaderPhi());
2937   // Only unclassified phi cycles are candidates for reductions.
2938   if (induction_range_.IsClassified(phi)) {
2939     return false;
2940   }
2941   // Accept operations like x = x + .., provided that the phi and the reduction are
2942   // used exactly once inside the loop, and by each other.
2943   HInputsRef inputs = phi->GetInputs();
2944   if (inputs.size() == 2) {
2945     HInstruction* reduction = inputs[1];
2946     if (HasReductionFormat(reduction, phi)) {
2947       HLoopInformation* loop_info = phi->GetBlock()->GetLoopInformation();
2948       DCHECK(loop_info->Contains(*reduction->GetBlock()));
2949       const bool single_use_inside_loop =
2950           // Reduction update only used by phi.
2951           reduction->GetUses().HasExactlyOneElement() &&
2952           !reduction->HasEnvironmentUses() &&
2953           // Reduction update is only use of phi inside the loop.
2954           std::none_of(phi->GetUses().begin(),
2955                        phi->GetUses().end(),
2956                        [loop_info, reduction](const HUseListNode<HInstruction*>& use) {
2957                          HInstruction* user = use.GetUser();
2958                          return user != reduction && loop_info->Contains(*user->GetBlock());
2959                        });
2960       if (single_use_inside_loop) {
2961         // Link reduction back, and start recording feed value.
2962         reductions_->Put(reduction, phi);
2963         reductions_->Put(phi, phi->InputAt(0));
2964         return true;
2965       }
2966     }
2967   }
2968   return false;
2969 }
2970 
TrySetSimpleLoopHeader(HBasicBlock * block,HPhi ** main_phi)2971 bool HLoopOptimization::TrySetSimpleLoopHeader(HBasicBlock* block, /*out*/ HPhi** main_phi) {
2972   // Start with empty phi induction and reductions.
2973   iset_->clear();
2974   reductions_->clear();
2975 
2976   // Scan the phis to find the following (the induction structure has already
2977   // been optimized, so we don't need to worry about trivial cases):
2978   // (1) optional reductions in loop,
2979   // (2) the main induction, used in loop control.
2980   HPhi* phi = nullptr;
2981   for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
2982     if (TrySetPhiReduction(it.Current()->AsPhi())) {
2983       continue;
2984     } else if (phi == nullptr) {
2985       // Found the first candidate for main induction.
2986       phi = it.Current()->AsPhi();
2987     } else {
2988       return false;
2989     }
2990   }
2991 
2992   // Then test for a typical loopheader:
2993   //   s:  SuspendCheck
2994   //   c:  Condition(phi, bound)
2995   //   i:  If(c)
2996   if (phi != nullptr && TrySetPhiInduction(phi, /*restrict_uses*/ false)) {
2997     HInstruction* s = block->GetFirstInstruction();
2998     if (s != nullptr && s->IsSuspendCheck()) {
2999       HInstruction* c = s->GetNext();
3000       if (c != nullptr &&
3001           c->IsCondition() &&
3002           c->GetUses().HasExactlyOneElement() &&  // only used for termination
3003           !c->HasEnvironmentUses()) {  // unlikely, but not impossible
3004         HInstruction* i = c->GetNext();
3005         if (i != nullptr && i->IsIf() && i->InputAt(0) == c) {
3006           iset_->insert(c);
3007           iset_->insert(s);
3008           *main_phi = phi;
3009           return true;
3010         }
3011       }
3012     }
3013   }
3014   return false;
3015 }
3016 
IsEmptyBody(HBasicBlock * block)3017 bool HLoopOptimization::IsEmptyBody(HBasicBlock* block) {
3018   if (!block->GetPhis().IsEmpty()) {
3019     return false;
3020   }
3021   for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
3022     HInstruction* instruction = it.Current();
3023     if (!instruction->IsGoto() && iset_->find(instruction) == iset_->end()) {
3024       return false;
3025     }
3026   }
3027   return true;
3028 }
3029 
IsUsedOutsideLoop(HLoopInformation * loop_info,HInstruction * instruction)3030 bool HLoopOptimization::IsUsedOutsideLoop(HLoopInformation* loop_info,
3031                                           HInstruction* instruction) {
3032   // Deal with regular uses.
3033   for (const HUseListNode<HInstruction*>& use : instruction->GetUses()) {
3034     if (use.GetUser()->GetBlock()->GetLoopInformation() != loop_info) {
3035       return true;
3036     }
3037   }
3038   return false;
3039 }
3040 
IsOnlyUsedAfterLoop(HLoopInformation * loop_info,HInstruction * instruction,bool collect_loop_uses,uint32_t * use_count)3041 bool HLoopOptimization::IsOnlyUsedAfterLoop(HLoopInformation* loop_info,
3042                                             HInstruction* instruction,
3043                                             bool collect_loop_uses,
3044                                             /*out*/ uint32_t* use_count) {
3045   // Deal with regular uses.
3046   for (const HUseListNode<HInstruction*>& use : instruction->GetUses()) {
3047     HInstruction* user = use.GetUser();
3048     if (iset_->find(user) == iset_->end()) {  // not excluded?
3049       if (loop_info->Contains(*user->GetBlock())) {
3050         // If collect_loop_uses is set, simply keep adding those uses to the set.
3051         // Otherwise, reject uses inside the loop that were not already in the set.
3052         if (collect_loop_uses) {
3053           iset_->insert(user);
3054           continue;
3055         }
3056         return false;
3057       }
3058       ++*use_count;
3059     }
3060   }
3061   return true;
3062 }
3063 
TryReplaceWithLastValue(HLoopInformation * loop_info,HInstruction * instruction,HBasicBlock * block)3064 bool HLoopOptimization::TryReplaceWithLastValue(HLoopInformation* loop_info,
3065                                                 HInstruction* instruction,
3066                                                 HBasicBlock* block) {
3067   // Try to replace outside uses with the last value.
3068   if (induction_range_.CanGenerateLastValue(instruction)) {
3069     HInstruction* replacement = induction_range_.GenerateLastValue(instruction, graph_, block);
3070     // Deal with regular uses.
3071     const HUseList<HInstruction*>& uses = instruction->GetUses();
3072     for (auto it = uses.begin(), end = uses.end(); it != end;) {
3073       HInstruction* user = it->GetUser();
3074       size_t index = it->GetIndex();
3075       ++it;  // increment before replacing
3076       if (iset_->find(user) == iset_->end()) {  // not excluded?
3077         if (kIsDebugBuild) {
3078           // We have checked earlier in 'IsOnlyUsedAfterLoop' that the use is after the loop.
3079           HLoopInformation* other_loop_info = user->GetBlock()->GetLoopInformation();
3080           CHECK(other_loop_info == nullptr || !other_loop_info->IsIn(*loop_info));
3081         }
3082         user->ReplaceInput(replacement, index);
3083         induction_range_.Replace(user, instruction, replacement);  // update induction
3084       }
3085     }
3086     // Deal with environment uses.
3087     const HUseList<HEnvironment*>& env_uses = instruction->GetEnvUses();
3088     for (auto it = env_uses.begin(), end = env_uses.end(); it != end;) {
3089       HEnvironment* user = it->GetUser();
3090       size_t index = it->GetIndex();
3091       ++it;  // increment before replacing
3092       if (iset_->find(user->GetHolder()) == iset_->end()) {  // not excluded?
3093         // Only update environment uses after the loop.
3094         HLoopInformation* other_loop_info = user->GetHolder()->GetBlock()->GetLoopInformation();
3095         if (other_loop_info == nullptr || !other_loop_info->IsIn(*loop_info)) {
3096           user->RemoveAsUserOfInput(index);
3097           user->SetRawEnvAt(index, replacement);
3098           replacement->AddEnvUseAt(user, index);
3099         }
3100       }
3101     }
3102     return true;
3103   }
3104   return false;
3105 }
3106 
TryAssignLastValue(HLoopInformation * loop_info,HInstruction * instruction,HBasicBlock * block,bool collect_loop_uses)3107 bool HLoopOptimization::TryAssignLastValue(HLoopInformation* loop_info,
3108                                            HInstruction* instruction,
3109                                            HBasicBlock* block,
3110                                            bool collect_loop_uses) {
3111   // Assigning the last value is always successful if there are no uses.
3112   // Otherwise, it succeeds in a no early-exit loop by generating the
3113   // proper last value assignment.
3114   uint32_t use_count = 0;
3115   return IsOnlyUsedAfterLoop(loop_info, instruction, collect_loop_uses, &use_count) &&
3116       (use_count == 0 ||
3117        (!IsEarlyExit(loop_info) && TryReplaceWithLastValue(loop_info, instruction, block)));
3118 }
3119 
RemoveDeadInstructions(const HInstructionList & list)3120 void HLoopOptimization::RemoveDeadInstructions(const HInstructionList& list) {
3121   for (HBackwardInstructionIterator i(list); !i.Done(); i.Advance()) {
3122     HInstruction* instruction = i.Current();
3123     if (instruction->IsDeadAndRemovable()) {
3124       simplified_ = true;
3125       instruction->GetBlock()->RemoveInstructionOrPhi(instruction);
3126     }
3127   }
3128 }
3129 
CanRemoveCycle()3130 bool HLoopOptimization::CanRemoveCycle() {
3131   for (HInstruction* i : *iset_) {
3132     // We can never remove instructions that have environment
3133     // uses when we compile 'debuggable'.
3134     if (i->HasEnvironmentUses() && graph_->IsDebuggable()) {
3135       return false;
3136     }
3137     // A deoptimization should never have an environment input removed.
3138     for (const HUseListNode<HEnvironment*>& use : i->GetEnvUses()) {
3139       if (use.GetUser()->GetHolder()->IsDeoptimize()) {
3140         return false;
3141       }
3142     }
3143   }
3144   return true;
3145 }
3146 
PreparePredicateInfoMap(LoopNode * node)3147 void HLoopOptimization::PreparePredicateInfoMap(LoopNode* node) {
3148   HLoopInformation* loop_info = node->loop_info;
3149 
3150   DCHECK(IsPredicatedLoopControlFlowSupported(loop_info));
3151 
3152   for (HBlocksInLoopIterator block_it(*loop_info);
3153       !block_it.Done();
3154       block_it.Advance()) {
3155     HBasicBlock* cur_block = block_it.Current();
3156     BlockPredicateInfo* pred_info = new (loop_allocator_) BlockPredicateInfo();
3157 
3158     predicate_info_map_->Put(cur_block, pred_info);
3159   }
3160 }
3161 
InitPredicateInfoMap(LoopNode * node,HVecPredSetOperation * loop_main_pred)3162 void HLoopOptimization::InitPredicateInfoMap(LoopNode* node,
3163                                              HVecPredSetOperation* loop_main_pred) {
3164   HLoopInformation* loop_info = node->loop_info;
3165   HBasicBlock* header = loop_info->GetHeader();
3166   BlockPredicateInfo* header_info = predicate_info_map_->Get(header);
3167   // Loop header is a special case; it doesn't have a false predicate because we
3168   // would just exit the loop then.
3169   header_info->SetControlFlowInfo(loop_main_pred, loop_main_pred);
3170 
3171   size_t blocks_in_loop = header->GetLoopInformation()->GetBlocks().NumSetBits();
3172   if (blocks_in_loop == 2) {
3173     for (HBasicBlock* successor : header->GetSuccessors()) {
3174       if (loop_info->Contains(*successor)) {
3175         // This is loop second block - body.
3176         BlockPredicateInfo* body_info = predicate_info_map_->Get(successor);
3177         body_info->SetControlPredicate(loop_main_pred);
3178         return;
3179       }
3180     }
3181     LOG(FATAL) << "Unreachable";
3182     UNREACHABLE();
3183   }
3184 
3185   // TODO: support predicated vectorization of CF loop of more complex structure.
3186   DCHECK(HasLoopDiamondStructure(loop_info));
3187   HBasicBlock* header_succ_0 = header->GetSuccessors()[0];
3188   HBasicBlock* header_succ_1 = header->GetSuccessors()[1];
3189   HBasicBlock* diamond_top = loop_info->Contains(*header_succ_0) ?
3190                              header_succ_0 :
3191                              header_succ_1;
3192 
3193   HIf* diamond_hif = diamond_top->GetLastInstruction()->AsIf();
3194   HBasicBlock* diamond_true = diamond_hif->IfTrueSuccessor();
3195   HBasicBlock* diamond_false = diamond_hif->IfFalseSuccessor();
3196   HBasicBlock* back_edge = diamond_true->GetSingleSuccessor();
3197 
3198   BlockPredicateInfo* diamond_top_info = predicate_info_map_->Get(diamond_top);
3199   BlockPredicateInfo* diamond_true_info = predicate_info_map_->Get(diamond_true);
3200   BlockPredicateInfo* diamond_false_info = predicate_info_map_->Get(diamond_false);
3201   BlockPredicateInfo* back_edge_info = predicate_info_map_->Get(back_edge);
3202 
3203   diamond_top_info->SetControlPredicate(header_info->GetTruePredicate());
3204 
3205   diamond_true_info->SetControlPredicate(diamond_top_info->GetTruePredicate());
3206   diamond_false_info->SetControlPredicate(diamond_top_info->GetFalsePredicate());
3207 
3208   back_edge_info->SetControlPredicate(header_info->GetTruePredicate());
3209 }
3210 
MaybeInsertInVectorExternalSet(HInstruction * instruction)3211 void HLoopOptimization::MaybeInsertInVectorExternalSet(HInstruction* instruction) {
3212   if (IsInPredicatedVectorizationMode()) {
3213     vector_external_set_->insert(instruction);
3214   }
3215 }
3216 
operator <<(std::ostream & os,const HLoopOptimization::LoopSynthesisMode & mode)3217 std::ostream& operator<<(std::ostream& os, const HLoopOptimization::LoopSynthesisMode& mode) {
3218   switch (mode) {
3219     case HLoopOptimization::LoopSynthesisMode::kSequential:
3220       return os << "kSequential";
3221     case HLoopOptimization::LoopSynthesisMode::kVector:
3222       return os << "kVector";
3223   }
3224   return os;
3225 }
3226 
3227 }  // namespace art
3228