• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2016 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include "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.
Insert(HBasicBlock * block,HInstruction * instruction)370 static 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 //
457 // Public methods.
458 //
459 
HLoopOptimization(HGraph * graph,const CodeGenerator & codegen,HInductionVarAnalysis * induction_analysis,OptimizingCompilerStats * stats,const char * name)460 HLoopOptimization::HLoopOptimization(HGraph* graph,
461                                      const CodeGenerator& codegen,
462                                      HInductionVarAnalysis* induction_analysis,
463                                      OptimizingCompilerStats* stats,
464                                      const char* name)
465     : HOptimization(graph, name, stats),
466       compiler_options_(&codegen.GetCompilerOptions()),
467       simd_register_size_(codegen.GetSIMDRegisterWidth()),
468       induction_range_(induction_analysis),
469       loop_allocator_(nullptr),
470       global_allocator_(graph_->GetAllocator()),
471       top_loop_(nullptr),
472       last_loop_(nullptr),
473       iset_(nullptr),
474       reductions_(nullptr),
475       simplified_(false),
476       predicated_vectorization_mode_(codegen.SupportsPredicatedSIMD()),
477       vector_length_(0),
478       vector_refs_(nullptr),
479       vector_static_peeling_factor_(0),
480       vector_dynamic_peeling_candidate_(nullptr),
481       vector_runtime_test_a_(nullptr),
482       vector_runtime_test_b_(nullptr),
483       vector_map_(nullptr),
484       vector_permanent_map_(nullptr),
485       vector_mode_(kSequential),
486       vector_preheader_(nullptr),
487       vector_header_(nullptr),
488       vector_body_(nullptr),
489       vector_index_(nullptr),
490       arch_loop_helper_(ArchNoOptsLoopHelper::Create(codegen, global_allocator_)) {
491 }
492 
Run()493 bool HLoopOptimization::Run() {
494   // Skip if there is no loop or the graph has irreducible loops.
495   // TODO: make this less of a sledgehammer.
496   if (!graph_->HasLoops() || graph_->HasIrreducibleLoops()) {
497     return false;
498   }
499 
500   // Phase-local allocator.
501   ScopedArenaAllocator allocator(graph_->GetArenaStack());
502   loop_allocator_ = &allocator;
503 
504   // Perform loop optimizations.
505   const bool did_loop_opt = LocalRun();
506   if (top_loop_ == nullptr) {
507     graph_->SetHasLoops(false);  // no more loops
508   }
509 
510   // Detach allocator.
511   loop_allocator_ = nullptr;
512 
513   return did_loop_opt;
514 }
515 
516 //
517 // Loop setup and traversal.
518 //
519 
LocalRun()520 bool HLoopOptimization::LocalRun() {
521   // Build the linear order using the phase-local allocator. This step enables building
522   // a loop hierarchy that properly reflects the outer-inner and previous-next relation.
523   ScopedArenaVector<HBasicBlock*> linear_order(loop_allocator_->Adapter(kArenaAllocLinearOrder));
524   LinearizeGraph(graph_, &linear_order);
525 
526   // Build the loop hierarchy.
527   for (HBasicBlock* block : linear_order) {
528     if (block->IsLoopHeader()) {
529       AddLoop(block->GetLoopInformation());
530     }
531   }
532   DCHECK(top_loop_ != nullptr);
533 
534   // Traverse the loop hierarchy inner-to-outer and optimize. Traversal can use
535   // temporary data structures using the phase-local allocator. All new HIR
536   // should use the global allocator.
537   ScopedArenaSet<HInstruction*> iset(loop_allocator_->Adapter(kArenaAllocLoopOptimization));
538   ScopedArenaSafeMap<HInstruction*, HInstruction*> reds(
539       std::less<HInstruction*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
540   ScopedArenaSet<ArrayReference> refs(loop_allocator_->Adapter(kArenaAllocLoopOptimization));
541   ScopedArenaSafeMap<HInstruction*, HInstruction*> map(
542       std::less<HInstruction*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
543   ScopedArenaSafeMap<HInstruction*, HInstruction*> perm(
544       std::less<HInstruction*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
545   // Attach.
546   iset_ = &iset;
547   reductions_ = &reds;
548   vector_refs_ = &refs;
549   vector_map_ = &map;
550   vector_permanent_map_ = &perm;
551   // Traverse.
552   const bool did_loop_opt = TraverseLoopsInnerToOuter(top_loop_);
553   // Detach.
554   iset_ = nullptr;
555   reductions_ = nullptr;
556   vector_refs_ = nullptr;
557   vector_map_ = nullptr;
558   vector_permanent_map_ = nullptr;
559   return did_loop_opt;
560 }
561 
AddLoop(HLoopInformation * loop_info)562 void HLoopOptimization::AddLoop(HLoopInformation* loop_info) {
563   DCHECK(loop_info != nullptr);
564   LoopNode* node = new (loop_allocator_) LoopNode(loop_info);
565   if (last_loop_ == nullptr) {
566     // First loop.
567     DCHECK(top_loop_ == nullptr);
568     last_loop_ = top_loop_ = node;
569   } else if (loop_info->IsIn(*last_loop_->loop_info)) {
570     // Inner loop.
571     node->outer = last_loop_;
572     DCHECK(last_loop_->inner == nullptr);
573     last_loop_ = last_loop_->inner = node;
574   } else {
575     // Subsequent loop.
576     while (last_loop_->outer != nullptr && !loop_info->IsIn(*last_loop_->outer->loop_info)) {
577       last_loop_ = last_loop_->outer;
578     }
579     node->outer = last_loop_->outer;
580     node->previous = last_loop_;
581     DCHECK(last_loop_->next == nullptr);
582     last_loop_ = last_loop_->next = node;
583   }
584 }
585 
RemoveLoop(LoopNode * node)586 void HLoopOptimization::RemoveLoop(LoopNode* node) {
587   DCHECK(node != nullptr);
588   DCHECK(node->inner == nullptr);
589   if (node->previous != nullptr) {
590     // Within sequence.
591     node->previous->next = node->next;
592     if (node->next != nullptr) {
593       node->next->previous = node->previous;
594     }
595   } else {
596     // First of sequence.
597     if (node->outer != nullptr) {
598       node->outer->inner = node->next;
599     } else {
600       top_loop_ = node->next;
601     }
602     if (node->next != nullptr) {
603       node->next->outer = node->outer;
604       node->next->previous = nullptr;
605     }
606   }
607 }
608 
TraverseLoopsInnerToOuter(LoopNode * node)609 bool HLoopOptimization::TraverseLoopsInnerToOuter(LoopNode* node) {
610   bool changed = false;
611   for ( ; node != nullptr; node = node->next) {
612     // Visit inner loops first. Recompute induction information for this
613     // loop if the induction of any inner loop has changed.
614     if (TraverseLoopsInnerToOuter(node->inner)) {
615       induction_range_.ReVisit(node->loop_info);
616       changed = true;
617     }
618 
619     CalculateAndSetTryCatchKind(node);
620     if (node->try_catch_kind == LoopNode::TryCatchKind::kHasTryCatch) {
621       // The current optimizations assume that the loops do not contain try/catches.
622       // TODO(solanes, 227283906): Assess if we can modify them to work with try/catches.
623       continue;
624     }
625 
626     DCHECK(node->try_catch_kind == LoopNode::TryCatchKind::kNoTryCatch)
627         << "kind: " << static_cast<int>(node->try_catch_kind)
628         << ". LoopOptimization requires the loops to not have try catches.";
629 
630     // Repeat simplifications in the loop-body until no more changes occur.
631     // Note that since each simplification consists of eliminating code (without
632     // introducing new code), this process is always finite.
633     do {
634       simplified_ = false;
635       SimplifyInduction(node);
636       SimplifyBlocks(node);
637       changed = simplified_ || changed;
638     } while (simplified_);
639     // Optimize inner loop.
640     if (node->inner == nullptr) {
641       changed = OptimizeInnerLoop(node) || changed;
642     }
643   }
644   return changed;
645 }
646 
CalculateAndSetTryCatchKind(LoopNode * node)647 void HLoopOptimization::CalculateAndSetTryCatchKind(LoopNode* node) {
648   DCHECK(node != nullptr);
649   DCHECK(node->try_catch_kind == LoopNode::TryCatchKind::kUnknown)
650       << "kind: " << static_cast<int>(node->try_catch_kind)
651       << ". SetTryCatchKind should be called only once per LoopNode.";
652 
653   // If a inner loop has a try catch, then the outer loop has one too (as it contains `inner`).
654   // Knowing this, we could skip iterating through all of the outer loop's parents with a simple
655   // check.
656   for (LoopNode* inner = node->inner; inner != nullptr; inner = inner->next) {
657     DCHECK(inner->try_catch_kind != LoopNode::TryCatchKind::kUnknown)
658         << "kind: " << static_cast<int>(inner->try_catch_kind)
659         << ". Should have updated the inner loop before the outer loop.";
660 
661     if (inner->try_catch_kind == LoopNode::TryCatchKind::kHasTryCatch) {
662       node->try_catch_kind = LoopNode::TryCatchKind::kHasTryCatch;
663       return;
664     }
665   }
666 
667   for (HBlocksInLoopIterator it_loop(*node->loop_info); !it_loop.Done(); it_loop.Advance()) {
668     HBasicBlock* block = it_loop.Current();
669     if (block->GetTryCatchInformation() != nullptr) {
670       node->try_catch_kind = LoopNode::TryCatchKind::kHasTryCatch;
671       return;
672     }
673   }
674 
675   node->try_catch_kind = LoopNode::TryCatchKind::kNoTryCatch;
676 }
677 
678 //
679 // This optimization applies to loops with plain simple operations
680 // (I.e. no calls to java code or runtime) with a known small trip_count * instr_count
681 // value.
682 //
TryToRemoveSuspendCheckFromLoopHeader(LoopAnalysisInfo * analysis_info,bool generate_code)683 bool HLoopOptimization::TryToRemoveSuspendCheckFromLoopHeader(LoopAnalysisInfo* analysis_info,
684                                                               bool generate_code) {
685   if (!graph_->SuspendChecksAreAllowedToNoOp()) {
686     return false;
687   }
688 
689   int64_t trip_count = analysis_info->GetTripCount();
690 
691   if (trip_count == LoopAnalysisInfo::kUnknownTripCount) {
692     return false;
693   }
694 
695   int64_t instruction_count = analysis_info->GetNumberOfInstructions();
696   int64_t total_instruction_count = trip_count * instruction_count;
697 
698   // The inclusion of the HasInstructionsPreventingScalarOpts() prevents this
699   // optimization from being applied to loops that have calls.
700   bool can_optimize =
701       total_instruction_count <= HLoopOptimization::kMaxTotalInstRemoveSuspendCheck &&
702       !analysis_info->HasInstructionsPreventingScalarOpts();
703 
704   if (!can_optimize) {
705     return false;
706   }
707 
708   // If we should do the optimization, disable codegen for the SuspendCheck.
709   if (generate_code) {
710     HLoopInformation* loop_info = analysis_info->GetLoopInfo();
711     HBasicBlock* header = loop_info->GetHeader();
712     HSuspendCheck* instruction = header->GetLoopInformation()->GetSuspendCheck();
713     // As other optimizations depend on SuspendCheck
714     // (e.g: CHAGuardVisitor::HoistGuard), disable its codegen instead of
715     // removing the SuspendCheck instruction.
716     instruction->SetIsNoOp(true);
717   }
718 
719   return true;
720 }
721 
722 //
723 // Optimization.
724 //
725 
SimplifyInduction(LoopNode * node)726 void HLoopOptimization::SimplifyInduction(LoopNode* node) {
727   HBasicBlock* header = node->loop_info->GetHeader();
728   HBasicBlock* preheader = node->loop_info->GetPreHeader();
729   // Scan the phis in the header to find opportunities to simplify an induction
730   // cycle that is only used outside the loop. Replace these uses, if any, with
731   // the last value and remove the induction cycle.
732   // Examples: for (int i = 0; x != null;   i++) { .... no i .... }
733   //           for (int i = 0; i < 10; i++, k++) { .... no k .... } return k;
734   for (HInstructionIterator it(header->GetPhis()); !it.Done(); it.Advance()) {
735     HPhi* phi = it.Current()->AsPhi();
736     if (TrySetPhiInduction(phi, /*restrict_uses*/ true) &&
737         TryAssignLastValue(node->loop_info, phi, preheader, /*collect_loop_uses*/ false)) {
738       // Note that it's ok to have replaced uses after the loop with the last value, without
739       // being able to remove the cycle. Environment uses (which are the reason we may not be
740       // able to remove the cycle) within the loop will still hold the right value. We must
741       // have tried first, however, to replace outside uses.
742       if (CanRemoveCycle()) {
743         simplified_ = true;
744         for (HInstruction* i : *iset_) {
745           RemoveFromCycle(i);
746         }
747         DCHECK(CheckInductionSetFullyRemoved(iset_));
748       }
749     }
750   }
751 }
752 
SimplifyBlocks(LoopNode * node)753 void HLoopOptimization::SimplifyBlocks(LoopNode* node) {
754   // Iterate over all basic blocks in the loop-body.
755   for (HBlocksInLoopIterator it(*node->loop_info); !it.Done(); it.Advance()) {
756     HBasicBlock* block = it.Current();
757     // Remove dead instructions from the loop-body.
758     RemoveDeadInstructions(block->GetPhis());
759     RemoveDeadInstructions(block->GetInstructions());
760     // Remove trivial control flow blocks from the loop-body.
761     if (block->GetPredecessors().size() == 1 &&
762         block->GetSuccessors().size() == 1 &&
763         block->GetSingleSuccessor()->GetPredecessors().size() == 1) {
764       simplified_ = true;
765       block->MergeWith(block->GetSingleSuccessor());
766     } else if (block->GetSuccessors().size() == 2) {
767       // Trivial if block can be bypassed to either branch.
768       HBasicBlock* succ0 = block->GetSuccessors()[0];
769       HBasicBlock* succ1 = block->GetSuccessors()[1];
770       HBasicBlock* meet0 = nullptr;
771       HBasicBlock* meet1 = nullptr;
772       if (succ0 != succ1 &&
773           IsGotoBlock(succ0, &meet0) &&
774           IsGotoBlock(succ1, &meet1) &&
775           meet0 == meet1 &&  // meets again
776           meet0 != block &&  // no self-loop
777           meet0->GetPhis().IsEmpty()) {  // not used for merging
778         simplified_ = true;
779         succ0->DisconnectAndDelete();
780         if (block->Dominates(meet0)) {
781           block->RemoveDominatedBlock(meet0);
782           succ1->AddDominatedBlock(meet0);
783           meet0->SetDominator(succ1);
784         }
785       }
786     }
787   }
788 }
789 
TryOptimizeInnerLoopFinite(LoopNode * node)790 bool HLoopOptimization::TryOptimizeInnerLoopFinite(LoopNode* node) {
791   HBasicBlock* header = node->loop_info->GetHeader();
792   HBasicBlock* preheader = node->loop_info->GetPreHeader();
793   // Ensure loop header logic is finite.
794   int64_t trip_count = 0;
795   if (!induction_range_.IsFinite(node->loop_info, &trip_count)) {
796     return false;
797   }
798   // Ensure there is only a single loop-body (besides the header).
799   HBasicBlock* body = nullptr;
800   for (HBlocksInLoopIterator it(*node->loop_info); !it.Done(); it.Advance()) {
801     if (it.Current() != header) {
802       if (body != nullptr) {
803         return false;
804       }
805       body = it.Current();
806     }
807   }
808   CHECK(body != nullptr);
809   // Ensure there is only a single exit point.
810   if (header->GetSuccessors().size() != 2) {
811     return false;
812   }
813   HBasicBlock* exit = (header->GetSuccessors()[0] == body)
814       ? header->GetSuccessors()[1]
815       : header->GetSuccessors()[0];
816   // Ensure exit can only be reached by exiting loop.
817   if (exit->GetPredecessors().size() != 1) {
818     return false;
819   }
820   // Detect either an empty loop (no side effects other than plain iteration) or
821   // a trivial loop (just iterating once). Replace subsequent index uses, if any,
822   // with the last value and remove the loop, possibly after unrolling its body.
823   HPhi* main_phi = nullptr;
824   if (TrySetSimpleLoopHeader(header, &main_phi)) {
825     bool is_empty = IsEmptyBody(body);
826     if (reductions_->empty() &&  // TODO: possible with some effort
827         (is_empty || trip_count == 1) &&
828         TryAssignLastValue(node->loop_info, main_phi, preheader, /*collect_loop_uses*/ true)) {
829       if (!is_empty) {
830         // Unroll the loop-body, which sees initial value of the index.
831         main_phi->ReplaceWith(main_phi->InputAt(0));
832         preheader->MergeInstructionsWith(body);
833       }
834       body->DisconnectAndDelete();
835       exit->RemovePredecessor(header);
836       header->RemoveSuccessor(exit);
837       header->RemoveDominatedBlock(exit);
838       header->DisconnectAndDelete();
839       preheader->AddSuccessor(exit);
840       preheader->AddInstruction(new (global_allocator_) HGoto());
841       preheader->AddDominatedBlock(exit);
842       exit->SetDominator(preheader);
843       RemoveLoop(node);  // update hierarchy
844       return true;
845     }
846   }
847   // Vectorize loop, if possible and valid.
848   if (kEnableVectorization &&
849       // Disable vectorization for debuggable graphs: this is a workaround for the bug
850       // in 'GenerateNewLoop' which caused the SuspendCheck environment to be invalid.
851       // TODO: b/138601207, investigate other possible cases with wrong environment values and
852       // possibly switch back vectorization on for debuggable graphs.
853       !graph_->IsDebuggable() &&
854       TrySetSimpleLoopHeader(header, &main_phi) &&
855       ShouldVectorize(node, body, trip_count) &&
856       TryAssignLastValue(node->loop_info, main_phi, preheader, /*collect_loop_uses*/ true)) {
857     Vectorize(node, body, exit, trip_count);
858     graph_->SetHasSIMD(true);  // flag SIMD usage
859     MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorized);
860     return true;
861   }
862   return false;
863 }
864 
OptimizeInnerLoop(LoopNode * node)865 bool HLoopOptimization::OptimizeInnerLoop(LoopNode* node) {
866   return TryOptimizeInnerLoopFinite(node) || TryLoopScalarOpts(node);
867 }
868 
869 //
870 // Scalar loop peeling and unrolling: generic part methods.
871 //
872 
TryUnrollingForBranchPenaltyReduction(LoopAnalysisInfo * analysis_info,bool generate_code)873 bool HLoopOptimization::TryUnrollingForBranchPenaltyReduction(LoopAnalysisInfo* analysis_info,
874                                                               bool generate_code) {
875   if (analysis_info->GetNumberOfExits() > 1) {
876     return false;
877   }
878 
879   uint32_t unrolling_factor = arch_loop_helper_->GetScalarUnrollingFactor(analysis_info);
880   if (unrolling_factor == LoopAnalysisInfo::kNoUnrollingFactor) {
881     return false;
882   }
883 
884   if (generate_code) {
885     // TODO: support other unrolling factors.
886     DCHECK_EQ(unrolling_factor, 2u);
887 
888     // Perform unrolling.
889     HLoopInformation* loop_info = analysis_info->GetLoopInfo();
890     LoopClonerSimpleHelper helper(loop_info, &induction_range_);
891     helper.DoUnrolling();
892 
893     // Remove the redundant loop check after unrolling.
894     HIf* copy_hif =
895         helper.GetBasicBlockMap()->Get(loop_info->GetHeader())->GetLastInstruction()->AsIf();
896     int32_t constant = loop_info->Contains(*copy_hif->IfTrueSuccessor()) ? 1 : 0;
897     copy_hif->ReplaceInput(graph_->GetIntConstant(constant), 0u);
898   }
899   return true;
900 }
901 
TryPeelingForLoopInvariantExitsElimination(LoopAnalysisInfo * analysis_info,bool generate_code)902 bool HLoopOptimization::TryPeelingForLoopInvariantExitsElimination(LoopAnalysisInfo* analysis_info,
903                                                                    bool generate_code) {
904   HLoopInformation* loop_info = analysis_info->GetLoopInfo();
905   if (!arch_loop_helper_->IsLoopPeelingEnabled()) {
906     return false;
907   }
908 
909   if (analysis_info->GetNumberOfInvariantExits() == 0) {
910     return false;
911   }
912 
913   if (generate_code) {
914     // Perform peeling.
915     LoopClonerSimpleHelper helper(loop_info, &induction_range_);
916     helper.DoPeeling();
917 
918     // Statically evaluate loop check after peeling for loop invariant condition.
919     const SuperblockCloner::HInstructionMap* hir_map = helper.GetInstructionMap();
920     for (auto entry : *hir_map) {
921       HInstruction* copy = entry.second;
922       if (copy->IsIf()) {
923         TryToEvaluateIfCondition(copy->AsIf(), graph_);
924       }
925     }
926   }
927 
928   return true;
929 }
930 
TryFullUnrolling(LoopAnalysisInfo * analysis_info,bool generate_code)931 bool HLoopOptimization::TryFullUnrolling(LoopAnalysisInfo* analysis_info, bool generate_code) {
932   // Fully unroll loops with a known and small trip count.
933   int64_t trip_count = analysis_info->GetTripCount();
934   if (!arch_loop_helper_->IsLoopPeelingEnabled() ||
935       trip_count == LoopAnalysisInfo::kUnknownTripCount ||
936       !arch_loop_helper_->IsFullUnrollingBeneficial(analysis_info)) {
937     return false;
938   }
939 
940   if (generate_code) {
941     // Peeling of the N first iterations (where N equals to the trip count) will effectively
942     // eliminate the loop: after peeling we will have N sequential iterations copied into the loop
943     // preheader and the original loop. The trip count of this loop will be 0 as the sequential
944     // iterations are executed first and there are exactly N of them. Thus we can statically
945     // evaluate the loop exit condition to 'false' and fully eliminate it.
946     //
947     // Here is an example of full unrolling of a loop with a trip count 2:
948     //
949     //                                           loop_cond_1
950     //                                           loop_body_1        <- First iteration.
951     //                                               |
952     //                             \                 v
953     //                            ==\            loop_cond_2
954     //                            ==/            loop_body_2        <- Second iteration.
955     //                             /                 |
956     //               <-                              v     <-
957     //     loop_cond   \                         loop_cond   \      <- This cond is always false.
958     //     loop_body  _/                         loop_body  _/
959     //
960     HLoopInformation* loop_info = analysis_info->GetLoopInfo();
961     PeelByCount(loop_info, trip_count, &induction_range_);
962     HIf* loop_hif = loop_info->GetHeader()->GetLastInstruction()->AsIf();
963     int32_t constant = loop_info->Contains(*loop_hif->IfTrueSuccessor()) ? 0 : 1;
964     loop_hif->ReplaceInput(graph_->GetIntConstant(constant), 0u);
965   }
966 
967   return true;
968 }
969 
TryLoopScalarOpts(LoopNode * node)970 bool HLoopOptimization::TryLoopScalarOpts(LoopNode* node) {
971   HLoopInformation* loop_info = node->loop_info;
972   int64_t trip_count = LoopAnalysis::GetLoopTripCount(loop_info, &induction_range_);
973   LoopAnalysisInfo analysis_info(loop_info);
974   LoopAnalysis::CalculateLoopBasicProperties(loop_info, &analysis_info, trip_count);
975 
976   if (analysis_info.HasInstructionsPreventingScalarOpts() ||
977       arch_loop_helper_->IsLoopNonBeneficialForScalarOpts(&analysis_info)) {
978     return false;
979   }
980 
981   if (!TryFullUnrolling(&analysis_info, /*generate_code*/ false) &&
982       !TryPeelingForLoopInvariantExitsElimination(&analysis_info, /*generate_code*/ false) &&
983       !TryUnrollingForBranchPenaltyReduction(&analysis_info, /*generate_code*/ false) &&
984       !TryToRemoveSuspendCheckFromLoopHeader(&analysis_info, /*generate_code*/ false)) {
985     return false;
986   }
987 
988   // Try the suspend check removal even for non-clonable loops. Also this
989   // optimization doesn't interfere with other scalar loop optimizations so it can
990   // be done prior to them.
991   bool removed_suspend_check = TryToRemoveSuspendCheckFromLoopHeader(&analysis_info);
992 
993   // Run 'IsLoopClonable' the last as it might be time-consuming.
994   if (!LoopClonerHelper::IsLoopClonable(loop_info)) {
995     return false;
996   }
997 
998   return TryFullUnrolling(&analysis_info) ||
999          TryPeelingForLoopInvariantExitsElimination(&analysis_info) ||
1000          TryUnrollingForBranchPenaltyReduction(&analysis_info) || removed_suspend_check;
1001 }
1002 
1003 //
1004 // Loop vectorization. The implementation is based on the book by Aart J.C. Bik:
1005 // "The Software Vectorization Handbook. Applying Multimedia Extensions for Maximum Performance."
1006 // Intel Press, June, 2004 (http://www.aartbik.com/).
1007 //
1008 
ShouldVectorize(LoopNode * node,HBasicBlock * block,int64_t trip_count)1009 bool HLoopOptimization::ShouldVectorize(LoopNode* node, HBasicBlock* block, int64_t trip_count) {
1010   // Reset vector bookkeeping.
1011   vector_length_ = 0;
1012   vector_refs_->clear();
1013   vector_static_peeling_factor_ = 0;
1014   vector_dynamic_peeling_candidate_ = nullptr;
1015   vector_runtime_test_a_ =
1016   vector_runtime_test_b_ = nullptr;
1017 
1018   // Phis in the loop-body prevent vectorization.
1019   if (!block->GetPhis().IsEmpty()) {
1020     return false;
1021   }
1022 
1023   // Scan the loop-body, starting a right-hand-side tree traversal at each left-hand-side
1024   // occurrence, which allows passing down attributes down the use tree.
1025   for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
1026     if (!VectorizeDef(node, it.Current(), /*generate_code*/ false)) {
1027       return false;  // failure to vectorize a left-hand-side
1028     }
1029   }
1030 
1031   // Prepare alignment analysis:
1032   // (1) find desired alignment (SIMD vector size in bytes).
1033   // (2) initialize static loop peeling votes (peeling factor that will
1034   //     make one particular reference aligned), never to exceed (1).
1035   // (3) variable to record how many references share same alignment.
1036   // (4) variable to record suitable candidate for dynamic loop peeling.
1037   size_t desired_alignment = GetVectorSizeInBytes();
1038   ScopedArenaVector<uint32_t> peeling_votes(desired_alignment, 0u,
1039       loop_allocator_->Adapter(kArenaAllocLoopOptimization));
1040 
1041   uint32_t max_num_same_alignment = 0;
1042   const ArrayReference* peeling_candidate = nullptr;
1043 
1044   // Data dependence analysis. Find each pair of references with same type, where
1045   // at least one is a write. Each such pair denotes a possible data dependence.
1046   // This analysis exploits the property that differently typed arrays cannot be
1047   // aliased, as well as the property that references either point to the same
1048   // array or to two completely disjoint arrays, i.e., no partial aliasing.
1049   // Other than a few simply heuristics, no detailed subscript analysis is done.
1050   // The scan over references also prepares finding a suitable alignment strategy.
1051   for (auto i = vector_refs_->begin(); i != vector_refs_->end(); ++i) {
1052     uint32_t num_same_alignment = 0;
1053     // Scan over all next references.
1054     for (auto j = i; ++j != vector_refs_->end(); ) {
1055       if (i->type == j->type && (i->lhs || j->lhs)) {
1056         // Found same-typed a[i+x] vs. b[i+y], where at least one is a write.
1057         HInstruction* a = i->base;
1058         HInstruction* b = j->base;
1059         HInstruction* x = i->offset;
1060         HInstruction* y = j->offset;
1061         if (a == b) {
1062           // Found a[i+x] vs. a[i+y]. Accept if x == y (loop-independent data dependence).
1063           // Conservatively assume a loop-carried data dependence otherwise, and reject.
1064           if (x != y) {
1065             return false;
1066           }
1067           // Count the number of references that have the same alignment (since
1068           // base and offset are the same) and where at least one is a write, so
1069           // e.g. a[i] = a[i] + b[i] counts a[i] but not b[i]).
1070           num_same_alignment++;
1071         } else {
1072           // Found a[i+x] vs. b[i+y]. Accept if x == y (at worst loop-independent data dependence).
1073           // Conservatively assume a potential loop-carried data dependence otherwise, avoided by
1074           // generating an explicit a != b disambiguation runtime test on the two references.
1075           if (x != y) {
1076             // To avoid excessive overhead, we only accept one a != b test.
1077             if (vector_runtime_test_a_ == nullptr) {
1078               // First test found.
1079               vector_runtime_test_a_ = a;
1080               vector_runtime_test_b_ = b;
1081             } else if ((vector_runtime_test_a_ != a || vector_runtime_test_b_ != b) &&
1082                        (vector_runtime_test_a_ != b || vector_runtime_test_b_ != a)) {
1083               return false;  // second test would be needed
1084             }
1085           }
1086         }
1087       }
1088     }
1089     // Update information for finding suitable alignment strategy:
1090     // (1) update votes for static loop peeling,
1091     // (2) update suitable candidate for dynamic loop peeling.
1092     Alignment alignment = ComputeAlignment(i->offset, i->type, i->is_string_char_at);
1093     if (alignment.Base() >= desired_alignment) {
1094       // If the array/string object has a known, sufficient alignment, use the
1095       // initial offset to compute the static loop peeling vote (this always
1096       // works, since elements have natural alignment).
1097       uint32_t offset = alignment.Offset() & (desired_alignment - 1u);
1098       uint32_t vote = (offset == 0)
1099           ? 0
1100           : ((desired_alignment - offset) >> DataType::SizeShift(i->type));
1101       DCHECK_LT(vote, 16u);
1102       ++peeling_votes[vote];
1103     } else if (BaseAlignment() >= desired_alignment &&
1104                num_same_alignment > max_num_same_alignment) {
1105       // Otherwise, if the array/string object has a known, sufficient alignment
1106       // for just the base but with an unknown offset, record the candidate with
1107       // the most occurrences for dynamic loop peeling (again, the peeling always
1108       // works, since elements have natural alignment).
1109       max_num_same_alignment = num_same_alignment;
1110       peeling_candidate = &(*i);
1111     }
1112   }  // for i
1113 
1114   if (!IsInPredicatedVectorizationMode()) {
1115     // Find a suitable alignment strategy.
1116     SetAlignmentStrategy(peeling_votes, peeling_candidate);
1117   }
1118 
1119   // Does vectorization seem profitable?
1120   if (!IsVectorizationProfitable(trip_count)) {
1121     return false;
1122   }
1123 
1124   // Success!
1125   return true;
1126 }
1127 
Vectorize(LoopNode * node,HBasicBlock * block,HBasicBlock * exit,int64_t trip_count)1128 void HLoopOptimization::Vectorize(LoopNode* node,
1129                                   HBasicBlock* block,
1130                                   HBasicBlock* exit,
1131                                   int64_t trip_count) {
1132   HBasicBlock* header = node->loop_info->GetHeader();
1133   HBasicBlock* preheader = node->loop_info->GetPreHeader();
1134 
1135   // Pick a loop unrolling factor for the vector loop.
1136   uint32_t unroll = arch_loop_helper_->GetSIMDUnrollingFactor(
1137       block, trip_count, MaxNumberPeeled(), vector_length_);
1138   uint32_t chunk = vector_length_ * unroll;
1139 
1140   DCHECK(trip_count == 0 || (trip_count >= MaxNumberPeeled() + chunk));
1141 
1142   // A cleanup loop is needed, at least, for any unknown trip count or
1143   // for a known trip count with remainder iterations after vectorization.
1144   bool needs_cleanup = !IsInPredicatedVectorizationMode() &&
1145       (trip_count == 0 || ((trip_count - vector_static_peeling_factor_) % chunk) != 0);
1146 
1147   // Adjust vector bookkeeping.
1148   HPhi* main_phi = nullptr;
1149   bool is_simple_loop_header = TrySetSimpleLoopHeader(header, &main_phi);  // refills sets
1150   DCHECK(is_simple_loop_header);
1151   vector_header_ = header;
1152   vector_body_ = block;
1153 
1154   // Loop induction type.
1155   DataType::Type induc_type = main_phi->GetType();
1156   DCHECK(induc_type == DataType::Type::kInt32 || induc_type == DataType::Type::kInt64)
1157       << induc_type;
1158 
1159   // Generate the trip count for static or dynamic loop peeling, if needed:
1160   // ptc = <peeling factor>;
1161   HInstruction* ptc = nullptr;
1162   if (vector_static_peeling_factor_ != 0) {
1163     DCHECK(!IsInPredicatedVectorizationMode());
1164     // Static loop peeling for SIMD alignment (using the most suitable
1165     // fixed peeling factor found during prior alignment analysis).
1166     DCHECK(vector_dynamic_peeling_candidate_ == nullptr);
1167     ptc = graph_->GetConstant(induc_type, vector_static_peeling_factor_);
1168   } else if (vector_dynamic_peeling_candidate_ != nullptr) {
1169     DCHECK(!IsInPredicatedVectorizationMode());
1170     // Dynamic loop peeling for SIMD alignment (using the most suitable
1171     // candidate found during prior alignment analysis):
1172     // rem = offset % ALIGN;    // adjusted as #elements
1173     // ptc = rem == 0 ? 0 : (ALIGN - rem);
1174     uint32_t shift = DataType::SizeShift(vector_dynamic_peeling_candidate_->type);
1175     uint32_t align = GetVectorSizeInBytes() >> shift;
1176     uint32_t hidden_offset = HiddenOffset(vector_dynamic_peeling_candidate_->type,
1177                                           vector_dynamic_peeling_candidate_->is_string_char_at);
1178     HInstruction* adjusted_offset = graph_->GetConstant(induc_type, hidden_offset >> shift);
1179     HInstruction* offset = Insert(preheader, new (global_allocator_) HAdd(
1180         induc_type, vector_dynamic_peeling_candidate_->offset, adjusted_offset));
1181     HInstruction* rem = Insert(preheader, new (global_allocator_) HAnd(
1182         induc_type, offset, graph_->GetConstant(induc_type, align - 1u)));
1183     HInstruction* sub = Insert(preheader, new (global_allocator_) HSub(
1184         induc_type, graph_->GetConstant(induc_type, align), rem));
1185     HInstruction* cond = Insert(preheader, new (global_allocator_) HEqual(
1186         rem, graph_->GetConstant(induc_type, 0)));
1187     ptc = Insert(preheader, new (global_allocator_) HSelect(
1188         cond, graph_->GetConstant(induc_type, 0), sub, kNoDexPc));
1189     needs_cleanup = true;  // don't know the exact amount
1190   }
1191 
1192   // Generate loop control:
1193   // stc = <trip-count>;
1194   // ptc = min(stc, ptc);
1195   // vtc = stc - (stc - ptc) % chunk;
1196   // i = 0;
1197   HInstruction* stc = induction_range_.GenerateTripCount(node->loop_info, graph_, preheader);
1198   HInstruction* vtc = stc;
1199   if (needs_cleanup) {
1200     DCHECK(!IsInPredicatedVectorizationMode());
1201     DCHECK(IsPowerOfTwo(chunk));
1202     HInstruction* diff = stc;
1203     if (ptc != nullptr) {
1204       if (trip_count == 0) {
1205         HInstruction* cond = Insert(preheader, new (global_allocator_) HAboveOrEqual(stc, ptc));
1206         ptc = Insert(preheader, new (global_allocator_) HSelect(cond, ptc, stc, kNoDexPc));
1207       }
1208       diff = Insert(preheader, new (global_allocator_) HSub(induc_type, stc, ptc));
1209     }
1210     HInstruction* rem = Insert(
1211         preheader, new (global_allocator_) HAnd(induc_type,
1212                                                 diff,
1213                                                 graph_->GetConstant(induc_type, chunk - 1)));
1214     vtc = Insert(preheader, new (global_allocator_) HSub(induc_type, stc, rem));
1215   }
1216   vector_index_ = graph_->GetConstant(induc_type, 0);
1217 
1218   // Generate runtime disambiguation test:
1219   // vtc = a != b ? vtc : 0;
1220   if (vector_runtime_test_a_ != nullptr) {
1221     HInstruction* rt = Insert(
1222         preheader,
1223         new (global_allocator_) HNotEqual(vector_runtime_test_a_, vector_runtime_test_b_));
1224     vtc = Insert(preheader,
1225                  new (global_allocator_)
1226                  HSelect(rt, vtc, graph_->GetConstant(induc_type, 0), kNoDexPc));
1227     needs_cleanup = true;
1228   }
1229 
1230   // Generate alignment peeling loop, if needed:
1231   // for ( ; i < ptc; i += 1)
1232   //    <loop-body>
1233   //
1234   // NOTE: The alignment forced by the peeling loop is preserved even if data is
1235   //       moved around during suspend checks, since all analysis was based on
1236   //       nothing more than the Android runtime alignment conventions.
1237   if (ptc != nullptr) {
1238     DCHECK(!IsInPredicatedVectorizationMode());
1239     vector_mode_ = kSequential;
1240     GenerateNewLoop(node,
1241                     block,
1242                     graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
1243                     vector_index_,
1244                     ptc,
1245                     graph_->GetConstant(induc_type, 1),
1246                     LoopAnalysisInfo::kNoUnrollingFactor);
1247   }
1248 
1249   // Generate vector loop, possibly further unrolled:
1250   // for ( ; i < vtc; i += chunk)
1251   //    <vectorized-loop-body>
1252   vector_mode_ = kVector;
1253   GenerateNewLoop(node,
1254                   block,
1255                   graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
1256                   vector_index_,
1257                   vtc,
1258                   graph_->GetConstant(induc_type, vector_length_),  // increment per unroll
1259                   unroll);
1260   HLoopInformation* vloop = vector_header_->GetLoopInformation();
1261 
1262   // Generate cleanup loop, if needed:
1263   // for ( ; i < stc; i += 1)
1264   //    <loop-body>
1265   if (needs_cleanup) {
1266     DCHECK_IMPLIES(IsInPredicatedVectorizationMode(), vector_runtime_test_a_ != nullptr);
1267     vector_mode_ = kSequential;
1268     GenerateNewLoop(node,
1269                     block,
1270                     graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
1271                     vector_index_,
1272                     stc,
1273                     graph_->GetConstant(induc_type, 1),
1274                     LoopAnalysisInfo::kNoUnrollingFactor);
1275   }
1276 
1277   // Link reductions to their final uses.
1278   for (auto i = reductions_->begin(); i != reductions_->end(); ++i) {
1279     if (i->first->IsPhi()) {
1280       HInstruction* phi = i->first;
1281       HInstruction* repl = ReduceAndExtractIfNeeded(i->second);
1282       // Deal with regular uses.
1283       for (const HUseListNode<HInstruction*>& use : phi->GetUses()) {
1284         induction_range_.Replace(use.GetUser(), phi, repl);  // update induction use
1285       }
1286       phi->ReplaceWith(repl);
1287     }
1288   }
1289 
1290   // Remove the original loop by disconnecting the body block
1291   // and removing all instructions from the header.
1292   block->DisconnectAndDelete();
1293   while (!header->GetFirstInstruction()->IsGoto()) {
1294     header->RemoveInstruction(header->GetFirstInstruction());
1295   }
1296 
1297   // Update loop hierarchy: the old header now resides in the same outer loop
1298   // as the old preheader. Note that we don't bother putting sequential
1299   // loops back in the hierarchy at this point.
1300   header->SetLoopInformation(preheader->GetLoopInformation());  // outward
1301   node->loop_info = vloop;
1302 }
1303 
GenerateNewLoop(LoopNode * node,HBasicBlock * block,HBasicBlock * new_preheader,HInstruction * lo,HInstruction * hi,HInstruction * step,uint32_t unroll)1304 void HLoopOptimization::GenerateNewLoop(LoopNode* node,
1305                                         HBasicBlock* block,
1306                                         HBasicBlock* new_preheader,
1307                                         HInstruction* lo,
1308                                         HInstruction* hi,
1309                                         HInstruction* step,
1310                                         uint32_t unroll) {
1311   DCHECK(unroll == 1 || vector_mode_ == kVector);
1312   DataType::Type induc_type = lo->GetType();
1313   // Prepare new loop.
1314   vector_preheader_ = new_preheader,
1315   vector_header_ = vector_preheader_->GetSingleSuccessor();
1316   vector_body_ = vector_header_->GetSuccessors()[1];
1317   HPhi* phi = new (global_allocator_) HPhi(global_allocator_,
1318                                            kNoRegNumber,
1319                                            0,
1320                                            HPhi::ToPhiType(induc_type));
1321   // Generate header and prepare body.
1322   // for (i = lo; i < hi; i += step)
1323   //    <loop-body>
1324   HInstruction* cond = nullptr;
1325   HInstruction* set_pred = nullptr;
1326   if (IsInPredicatedVectorizationMode()) {
1327     HVecPredWhile* pred_while =
1328         new (global_allocator_) HVecPredWhile(global_allocator_,
1329                                               phi,
1330                                               hi,
1331                                               HVecPredWhile::CondKind::kLO,
1332                                               DataType::Type::kInt32,
1333                                               vector_length_,
1334                                               0u);
1335 
1336     cond = new (global_allocator_) HVecPredCondition(global_allocator_,
1337                                                      pred_while,
1338                                                      HVecPredCondition::PCondKind::kNFirst,
1339                                                      DataType::Type::kInt32,
1340                                                      vector_length_,
1341                                                      0u);
1342 
1343     vector_header_->AddPhi(phi);
1344     vector_header_->AddInstruction(pred_while);
1345     vector_header_->AddInstruction(cond);
1346     set_pred = pred_while;
1347   } else {
1348     cond = new (global_allocator_) HAboveOrEqual(phi, hi);
1349     vector_header_->AddPhi(phi);
1350     vector_header_->AddInstruction(cond);
1351   }
1352 
1353   vector_header_->AddInstruction(new (global_allocator_) HIf(cond));
1354   vector_index_ = phi;
1355   vector_permanent_map_->clear();  // preserved over unrolling
1356   for (uint32_t u = 0; u < unroll; u++) {
1357     // Generate instruction map.
1358     vector_map_->clear();
1359     for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
1360       bool vectorized_def = VectorizeDef(node, it.Current(), /*generate_code*/ true);
1361       DCHECK(vectorized_def);
1362     }
1363     // Generate body from the instruction map, but in original program order.
1364     HEnvironment* env = vector_header_->GetFirstInstruction()->GetEnvironment();
1365     for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
1366       auto i = vector_map_->find(it.Current());
1367       if (i != vector_map_->end() && !i->second->IsInBlock()) {
1368         Insert(vector_body_, i->second);
1369         if (IsInPredicatedVectorizationMode() && i->second->IsVecOperation()) {
1370           HVecOperation* op = i->second->AsVecOperation();
1371           op->SetMergingGoverningPredicate(set_pred);
1372         }
1373         // Deal with instructions that need an environment, such as the scalar intrinsics.
1374         if (i->second->NeedsEnvironment()) {
1375           i->second->CopyEnvironmentFromWithLoopPhiAdjustment(env, vector_header_);
1376         }
1377       }
1378     }
1379     // Generate the induction.
1380     vector_index_ = new (global_allocator_) HAdd(induc_type, vector_index_, step);
1381     Insert(vector_body_, vector_index_);
1382   }
1383   // Finalize phi inputs for the reductions (if any).
1384   for (auto i = reductions_->begin(); i != reductions_->end(); ++i) {
1385     if (!i->first->IsPhi()) {
1386       DCHECK(i->second->IsPhi());
1387       GenerateVecReductionPhiInputs(i->second->AsPhi(), i->first);
1388     }
1389   }
1390   // Finalize phi inputs for the loop index.
1391   phi->AddInput(lo);
1392   phi->AddInput(vector_index_);
1393   vector_index_ = phi;
1394 }
1395 
VectorizeDef(LoopNode * node,HInstruction * instruction,bool generate_code)1396 bool HLoopOptimization::VectorizeDef(LoopNode* node,
1397                                      HInstruction* instruction,
1398                                      bool generate_code) {
1399   // Accept a left-hand-side array base[index] for
1400   // (1) supported vector type,
1401   // (2) loop-invariant base,
1402   // (3) unit stride index,
1403   // (4) vectorizable right-hand-side value.
1404   uint64_t restrictions = kNone;
1405   // Don't accept expressions that can throw.
1406   if (instruction->CanThrow()) {
1407     return false;
1408   }
1409   if (instruction->IsArraySet()) {
1410     DataType::Type type = instruction->AsArraySet()->GetComponentType();
1411     HInstruction* base = instruction->InputAt(0);
1412     HInstruction* index = instruction->InputAt(1);
1413     HInstruction* value = instruction->InputAt(2);
1414     HInstruction* offset = nullptr;
1415     // For narrow types, explicit type conversion may have been
1416     // optimized way, so set the no hi bits restriction here.
1417     if (DataType::Size(type) <= 2) {
1418       restrictions |= kNoHiBits;
1419     }
1420     if (TrySetVectorType(type, &restrictions) &&
1421         node->loop_info->IsDefinedOutOfTheLoop(base) &&
1422         induction_range_.IsUnitStride(instruction->GetBlock(), index, graph_, &offset) &&
1423         VectorizeUse(node, value, generate_code, type, restrictions)) {
1424       if (generate_code) {
1425         GenerateVecSub(index, offset);
1426         GenerateVecMem(instruction, vector_map_->Get(index), vector_map_->Get(value), offset, type);
1427       } else {
1428         vector_refs_->insert(ArrayReference(base, offset, type, /*lhs*/ true));
1429       }
1430       return true;
1431     }
1432     return false;
1433   }
1434   // Accept a left-hand-side reduction for
1435   // (1) supported vector type,
1436   // (2) vectorizable right-hand-side value.
1437   auto redit = reductions_->find(instruction);
1438   if (redit != reductions_->end()) {
1439     DataType::Type type = instruction->GetType();
1440     // Recognize SAD idiom or direct reduction.
1441     if (VectorizeSADIdiom(node, instruction, generate_code, type, restrictions) ||
1442         VectorizeDotProdIdiom(node, instruction, generate_code, type, restrictions) ||
1443         (TrySetVectorType(type, &restrictions) &&
1444          VectorizeUse(node, instruction, generate_code, type, restrictions))) {
1445       if (generate_code) {
1446         HInstruction* new_red = vector_map_->Get(instruction);
1447         vector_permanent_map_->Put(new_red, vector_map_->Get(redit->second));
1448         vector_permanent_map_->Overwrite(redit->second, new_red);
1449       }
1450       return true;
1451     }
1452     return false;
1453   }
1454   // Branch back okay.
1455   if (instruction->IsGoto()) {
1456     return true;
1457   }
1458   // Otherwise accept only expressions with no effects outside the immediate loop-body.
1459   // Note that actual uses are inspected during right-hand-side tree traversal.
1460   return !IsUsedOutsideLoop(node->loop_info, instruction)
1461          && !instruction->DoesAnyWrite();
1462 }
1463 
VectorizeUse(LoopNode * node,HInstruction * instruction,bool generate_code,DataType::Type type,uint64_t restrictions)1464 bool HLoopOptimization::VectorizeUse(LoopNode* node,
1465                                      HInstruction* instruction,
1466                                      bool generate_code,
1467                                      DataType::Type type,
1468                                      uint64_t restrictions) {
1469   // Accept anything for which code has already been generated.
1470   if (generate_code) {
1471     if (vector_map_->find(instruction) != vector_map_->end()) {
1472       return true;
1473     }
1474   }
1475   // Continue the right-hand-side tree traversal, passing in proper
1476   // types and vector restrictions along the way. During code generation,
1477   // all new nodes are drawn from the global allocator.
1478   if (node->loop_info->IsDefinedOutOfTheLoop(instruction)) {
1479     // Accept invariant use, using scalar expansion.
1480     if (generate_code) {
1481       GenerateVecInv(instruction, type);
1482     }
1483     return true;
1484   } else if (instruction->IsArrayGet()) {
1485     // Deal with vector restrictions.
1486     bool is_string_char_at = instruction->AsArrayGet()->IsStringCharAt();
1487 
1488     if (is_string_char_at && (HasVectorRestrictions(restrictions, kNoStringCharAt) ||
1489                               IsInPredicatedVectorizationMode())) {
1490       // TODO: Support CharAt for predicated mode.
1491       return false;
1492     }
1493     // Accept a right-hand-side array base[index] for
1494     // (1) matching vector type (exact match or signed/unsigned integral type of the same size),
1495     // (2) loop-invariant base,
1496     // (3) unit stride index,
1497     // (4) vectorizable right-hand-side value.
1498     HInstruction* base = instruction->InputAt(0);
1499     HInstruction* index = instruction->InputAt(1);
1500     HInstruction* offset = nullptr;
1501     if (HVecOperation::ToSignedType(type) == HVecOperation::ToSignedType(instruction->GetType()) &&
1502         node->loop_info->IsDefinedOutOfTheLoop(base) &&
1503         induction_range_.IsUnitStride(instruction->GetBlock(), index, graph_, &offset)) {
1504       if (generate_code) {
1505         GenerateVecSub(index, offset);
1506         GenerateVecMem(instruction, vector_map_->Get(index), nullptr, offset, type);
1507       } else {
1508         vector_refs_->insert(ArrayReference(base, offset, type, /*lhs*/ false, is_string_char_at));
1509       }
1510       return true;
1511     }
1512   } else if (instruction->IsPhi()) {
1513     // Accept particular phi operations.
1514     if (reductions_->find(instruction) != reductions_->end()) {
1515       // Deal with vector restrictions.
1516       if (HasVectorRestrictions(restrictions, kNoReduction)) {
1517         return false;
1518       }
1519       // Accept a reduction.
1520       if (generate_code) {
1521         GenerateVecReductionPhi(instruction->AsPhi());
1522       }
1523       return true;
1524     }
1525     // TODO: accept right-hand-side induction?
1526     return false;
1527   } else if (instruction->IsTypeConversion()) {
1528     // Accept particular type conversions.
1529     HTypeConversion* conversion = instruction->AsTypeConversion();
1530     HInstruction* opa = conversion->InputAt(0);
1531     DataType::Type from = conversion->GetInputType();
1532     DataType::Type to = conversion->GetResultType();
1533     if (DataType::IsIntegralType(from) && DataType::IsIntegralType(to)) {
1534       uint32_t size_vec = DataType::Size(type);
1535       uint32_t size_from = DataType::Size(from);
1536       uint32_t size_to = DataType::Size(to);
1537       // Accept an integral conversion
1538       // (1a) narrowing into vector type, "wider" operations cannot bring in higher order bits, or
1539       // (1b) widening from at least vector type, and
1540       // (2) vectorizable operand.
1541       if ((size_to < size_from &&
1542            size_to == size_vec &&
1543            VectorizeUse(node, opa, generate_code, type, restrictions | kNoHiBits)) ||
1544           (size_to >= size_from &&
1545            size_from >= size_vec &&
1546            VectorizeUse(node, opa, generate_code, type, restrictions))) {
1547         if (generate_code) {
1548           if (vector_mode_ == kVector) {
1549             vector_map_->Put(instruction, vector_map_->Get(opa));  // operand pass-through
1550           } else {
1551             GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1552           }
1553         }
1554         return true;
1555       }
1556     } else if (to == DataType::Type::kFloat32 && from == DataType::Type::kInt32) {
1557       DCHECK_EQ(to, type);
1558       // Accept int to float conversion for
1559       // (1) supported int,
1560       // (2) vectorizable operand.
1561       if (TrySetVectorType(from, &restrictions) &&
1562           VectorizeUse(node, opa, generate_code, from, restrictions)) {
1563         if (generate_code) {
1564           GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1565         }
1566         return true;
1567       }
1568     }
1569     return false;
1570   } else if (instruction->IsNeg() || instruction->IsNot() || instruction->IsBooleanNot()) {
1571     // Accept unary operator for vectorizable operand.
1572     HInstruction* opa = instruction->InputAt(0);
1573     if (VectorizeUse(node, opa, generate_code, type, restrictions)) {
1574       if (generate_code) {
1575         GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1576       }
1577       return true;
1578     }
1579   } else if (instruction->IsAdd() || instruction->IsSub() ||
1580              instruction->IsMul() || instruction->IsDiv() ||
1581              instruction->IsAnd() || instruction->IsOr()  || instruction->IsXor()) {
1582     // Deal with vector restrictions.
1583     if ((instruction->IsMul() && HasVectorRestrictions(restrictions, kNoMul)) ||
1584         (instruction->IsDiv() && HasVectorRestrictions(restrictions, kNoDiv))) {
1585       return false;
1586     }
1587     // Accept binary operator for vectorizable operands.
1588     HInstruction* opa = instruction->InputAt(0);
1589     HInstruction* opb = instruction->InputAt(1);
1590     if (VectorizeUse(node, opa, generate_code, type, restrictions) &&
1591         VectorizeUse(node, opb, generate_code, type, restrictions)) {
1592       if (generate_code) {
1593         GenerateVecOp(instruction, vector_map_->Get(opa), vector_map_->Get(opb), type);
1594       }
1595       return true;
1596     }
1597   } else if (instruction->IsShl() || instruction->IsShr() || instruction->IsUShr()) {
1598     // Recognize halving add idiom.
1599     if (VectorizeHalvingAddIdiom(node, instruction, generate_code, type, restrictions)) {
1600       return true;
1601     }
1602     // Deal with vector restrictions.
1603     HInstruction* opa = instruction->InputAt(0);
1604     HInstruction* opb = instruction->InputAt(1);
1605     HInstruction* r = opa;
1606     bool is_unsigned = false;
1607     if ((HasVectorRestrictions(restrictions, kNoShift)) ||
1608         (instruction->IsShr() && HasVectorRestrictions(restrictions, kNoShr))) {
1609       return false;  // unsupported instruction
1610     } else if (HasVectorRestrictions(restrictions, kNoHiBits)) {
1611       // Shifts right need extra care to account for higher order bits.
1612       // TODO: less likely shr/unsigned and ushr/signed can by flipping signess.
1613       if (instruction->IsShr() &&
1614           (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || is_unsigned)) {
1615         return false;  // reject, unless all operands are sign-extension narrower
1616       } else if (instruction->IsUShr() &&
1617                  (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || !is_unsigned)) {
1618         return false;  // reject, unless all operands are zero-extension narrower
1619       }
1620     }
1621     // Accept shift operator for vectorizable/invariant operands.
1622     // TODO: accept symbolic, albeit loop invariant shift factors.
1623     DCHECK(r != nullptr);
1624     if (generate_code && vector_mode_ != kVector) {  // de-idiom
1625       r = opa;
1626     }
1627     int64_t distance = 0;
1628     if (VectorizeUse(node, r, generate_code, type, restrictions) &&
1629         IsInt64AndGet(opb, /*out*/ &distance)) {
1630       // Restrict shift distance to packed data type width.
1631       int64_t max_distance = DataType::Size(type) * 8;
1632       if (0 <= distance && distance < max_distance) {
1633         if (generate_code) {
1634           GenerateVecOp(instruction, vector_map_->Get(r), opb, type);
1635         }
1636         return true;
1637       }
1638     }
1639   } else if (instruction->IsAbs()) {
1640     // Deal with vector restrictions.
1641     HInstruction* opa = instruction->InputAt(0);
1642     HInstruction* r = opa;
1643     bool is_unsigned = false;
1644     if (HasVectorRestrictions(restrictions, kNoAbs)) {
1645       return false;
1646     } else if (HasVectorRestrictions(restrictions, kNoHiBits) &&
1647                (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || is_unsigned)) {
1648       return false;  // reject, unless operand is sign-extension narrower
1649     }
1650     // Accept ABS(x) for vectorizable operand.
1651     DCHECK(r != nullptr);
1652     if (generate_code && vector_mode_ != kVector) {  // de-idiom
1653       r = opa;
1654     }
1655     if (VectorizeUse(node, r, generate_code, type, restrictions)) {
1656       if (generate_code) {
1657         GenerateVecOp(instruction,
1658                       vector_map_->Get(r),
1659                       nullptr,
1660                       HVecOperation::ToProperType(type, is_unsigned));
1661       }
1662       return true;
1663     }
1664   }
1665   return false;
1666 }
1667 
GetVectorSizeInBytes()1668 uint32_t HLoopOptimization::GetVectorSizeInBytes() {
1669   return simd_register_size_;
1670 }
1671 
TrySetVectorType(DataType::Type type,uint64_t * restrictions)1672 bool HLoopOptimization::TrySetVectorType(DataType::Type type, uint64_t* restrictions) {
1673   const InstructionSetFeatures* features = compiler_options_->GetInstructionSetFeatures();
1674   switch (compiler_options_->GetInstructionSet()) {
1675     case InstructionSet::kArm:
1676     case InstructionSet::kThumb2:
1677       // Allow vectorization for all ARM devices, because Android assumes that
1678       // ARM 32-bit always supports advanced SIMD (64-bit SIMD).
1679       switch (type) {
1680         case DataType::Type::kBool:
1681         case DataType::Type::kUint8:
1682         case DataType::Type::kInt8:
1683           *restrictions |= kNoDiv | kNoReduction | kNoDotProd;
1684           return TrySetVectorLength(type, 8);
1685         case DataType::Type::kUint16:
1686         case DataType::Type::kInt16:
1687           *restrictions |= kNoDiv | kNoStringCharAt | kNoReduction | kNoDotProd;
1688           return TrySetVectorLength(type, 4);
1689         case DataType::Type::kInt32:
1690           *restrictions |= kNoDiv | kNoWideSAD;
1691           return TrySetVectorLength(type, 2);
1692         default:
1693           break;
1694       }
1695       return false;
1696     case InstructionSet::kArm64:
1697       if (IsInPredicatedVectorizationMode()) {
1698         // SVE vectorization.
1699         CHECK(features->AsArm64InstructionSetFeatures()->HasSVE());
1700         size_t vector_length = simd_register_size_ / DataType::Size(type);
1701         DCHECK_EQ(simd_register_size_ % DataType::Size(type), 0u);
1702         switch (type) {
1703           case DataType::Type::kBool:
1704           case DataType::Type::kUint8:
1705           case DataType::Type::kInt8:
1706             *restrictions |= kNoDiv |
1707                              kNoSignedHAdd |
1708                              kNoUnsignedHAdd |
1709                              kNoUnroundedHAdd |
1710                              kNoSAD;
1711             return TrySetVectorLength(type, vector_length);
1712           case DataType::Type::kUint16:
1713           case DataType::Type::kInt16:
1714             *restrictions |= kNoDiv |
1715                              kNoSignedHAdd |
1716                              kNoUnsignedHAdd |
1717                              kNoUnroundedHAdd |
1718                              kNoSAD |
1719                              kNoDotProd;
1720             return TrySetVectorLength(type, vector_length);
1721           case DataType::Type::kInt32:
1722             *restrictions |= kNoDiv | kNoSAD;
1723             return TrySetVectorLength(type, vector_length);
1724           case DataType::Type::kInt64:
1725             *restrictions |= kNoDiv | kNoSAD;
1726             return TrySetVectorLength(type, vector_length);
1727           case DataType::Type::kFloat32:
1728             *restrictions |= kNoReduction;
1729             return TrySetVectorLength(type, vector_length);
1730           case DataType::Type::kFloat64:
1731             *restrictions |= kNoReduction;
1732             return TrySetVectorLength(type, vector_length);
1733           default:
1734             break;
1735         }
1736         return false;
1737       } else {
1738         // Allow vectorization for all ARM devices, because Android assumes that
1739         // ARMv8 AArch64 always supports advanced SIMD (128-bit SIMD).
1740         switch (type) {
1741           case DataType::Type::kBool:
1742           case DataType::Type::kUint8:
1743           case DataType::Type::kInt8:
1744             *restrictions |= kNoDiv;
1745             return TrySetVectorLength(type, 16);
1746           case DataType::Type::kUint16:
1747           case DataType::Type::kInt16:
1748             *restrictions |= kNoDiv;
1749             return TrySetVectorLength(type, 8);
1750           case DataType::Type::kInt32:
1751             *restrictions |= kNoDiv;
1752             return TrySetVectorLength(type, 4);
1753           case DataType::Type::kInt64:
1754             *restrictions |= kNoDiv | kNoMul;
1755             return TrySetVectorLength(type, 2);
1756           case DataType::Type::kFloat32:
1757             *restrictions |= kNoReduction;
1758             return TrySetVectorLength(type, 4);
1759           case DataType::Type::kFloat64:
1760             *restrictions |= kNoReduction;
1761             return TrySetVectorLength(type, 2);
1762           default:
1763             break;
1764         }
1765         return false;
1766       }
1767     case InstructionSet::kX86:
1768     case InstructionSet::kX86_64:
1769       // Allow vectorization for SSE4.1-enabled X86 devices only (128-bit SIMD).
1770       if (features->AsX86InstructionSetFeatures()->HasSSE4_1()) {
1771         switch (type) {
1772           case DataType::Type::kBool:
1773           case DataType::Type::kUint8:
1774           case DataType::Type::kInt8:
1775             *restrictions |= kNoMul |
1776                              kNoDiv |
1777                              kNoShift |
1778                              kNoAbs |
1779                              kNoSignedHAdd |
1780                              kNoUnroundedHAdd |
1781                              kNoSAD |
1782                              kNoDotProd;
1783             return TrySetVectorLength(type, 16);
1784           case DataType::Type::kUint16:
1785             *restrictions |= kNoDiv |
1786                              kNoAbs |
1787                              kNoSignedHAdd |
1788                              kNoUnroundedHAdd |
1789                              kNoSAD |
1790                              kNoDotProd;
1791             return TrySetVectorLength(type, 8);
1792           case DataType::Type::kInt16:
1793             *restrictions |= kNoDiv |
1794                              kNoAbs |
1795                              kNoSignedHAdd |
1796                              kNoUnroundedHAdd |
1797                              kNoSAD;
1798             return TrySetVectorLength(type, 8);
1799           case DataType::Type::kInt32:
1800             *restrictions |= kNoDiv | kNoSAD;
1801             return TrySetVectorLength(type, 4);
1802           case DataType::Type::kInt64:
1803             *restrictions |= kNoMul | kNoDiv | kNoShr | kNoAbs | kNoSAD;
1804             return TrySetVectorLength(type, 2);
1805           case DataType::Type::kFloat32:
1806             *restrictions |= kNoReduction;
1807             return TrySetVectorLength(type, 4);
1808           case DataType::Type::kFloat64:
1809             *restrictions |= kNoReduction;
1810             return TrySetVectorLength(type, 2);
1811           default:
1812             break;
1813         }  // switch type
1814       }
1815       return false;
1816     default:
1817       return false;
1818   }  // switch instruction set
1819 }
1820 
TrySetVectorLengthImpl(uint32_t length)1821 bool HLoopOptimization::TrySetVectorLengthImpl(uint32_t length) {
1822   DCHECK(IsPowerOfTwo(length) && length >= 2u);
1823   // First time set?
1824   if (vector_length_ == 0) {
1825     vector_length_ = length;
1826   }
1827   // Different types are acceptable within a loop-body, as long as all the corresponding vector
1828   // lengths match exactly to obtain a uniform traversal through the vector iteration space
1829   // (idiomatic exceptions to this rule can be handled by further unrolling sub-expressions).
1830   return vector_length_ == length;
1831 }
1832 
GenerateVecInv(HInstruction * org,DataType::Type type)1833 void HLoopOptimization::GenerateVecInv(HInstruction* org, DataType::Type type) {
1834   if (vector_map_->find(org) == vector_map_->end()) {
1835     // In scalar code, just use a self pass-through for scalar invariants
1836     // (viz. expression remains itself).
1837     if (vector_mode_ == kSequential) {
1838       vector_map_->Put(org, org);
1839       return;
1840     }
1841     // In vector code, explicit scalar expansion is needed.
1842     HInstruction* vector = nullptr;
1843     auto it = vector_permanent_map_->find(org);
1844     if (it != vector_permanent_map_->end()) {
1845       vector = it->second;  // reuse during unrolling
1846     } else {
1847       // Generates ReplicateScalar( (optional_type_conv) org ).
1848       HInstruction* input = org;
1849       DataType::Type input_type = input->GetType();
1850       if (type != input_type && (type == DataType::Type::kInt64 ||
1851                                  input_type == DataType::Type::kInt64)) {
1852         input = Insert(vector_preheader_,
1853                        new (global_allocator_) HTypeConversion(type, input, kNoDexPc));
1854       }
1855       vector = new (global_allocator_)
1856           HVecReplicateScalar(global_allocator_, input, type, vector_length_, kNoDexPc);
1857       vector_permanent_map_->Put(org, Insert(vector_preheader_, vector));
1858       if (IsInPredicatedVectorizationMode()) {
1859         HVecPredSetAll* set_pred = new (global_allocator_) HVecPredSetAll(global_allocator_,
1860                                                                           graph_->GetIntConstant(1),
1861                                                                           type,
1862                                                                           vector_length_,
1863                                                                           0u);
1864         vector_preheader_->InsertInstructionBefore(set_pred, vector);
1865         vector->AsVecOperation()->SetMergingGoverningPredicate(set_pred);
1866       }
1867     }
1868     vector_map_->Put(org, vector);
1869   }
1870 }
1871 
GenerateVecSub(HInstruction * org,HInstruction * offset)1872 void HLoopOptimization::GenerateVecSub(HInstruction* org, HInstruction* offset) {
1873   if (vector_map_->find(org) == vector_map_->end()) {
1874     HInstruction* subscript = vector_index_;
1875     int64_t value = 0;
1876     if (!IsInt64AndGet(offset, &value) || value != 0) {
1877       subscript = new (global_allocator_) HAdd(DataType::Type::kInt32, subscript, offset);
1878       if (org->IsPhi()) {
1879         Insert(vector_body_, subscript);  // lacks layout placeholder
1880       }
1881     }
1882     vector_map_->Put(org, subscript);
1883   }
1884 }
1885 
GenerateVecMem(HInstruction * org,HInstruction * opa,HInstruction * opb,HInstruction * offset,DataType::Type type)1886 void HLoopOptimization::GenerateVecMem(HInstruction* org,
1887                                        HInstruction* opa,
1888                                        HInstruction* opb,
1889                                        HInstruction* offset,
1890                                        DataType::Type type) {
1891   uint32_t dex_pc = org->GetDexPc();
1892   HInstruction* vector = nullptr;
1893   if (vector_mode_ == kVector) {
1894     // Vector store or load.
1895     bool is_string_char_at = false;
1896     HInstruction* base = org->InputAt(0);
1897     if (opb != nullptr) {
1898       vector = new (global_allocator_) HVecStore(
1899           global_allocator_, base, opa, opb, type, org->GetSideEffects(), vector_length_, dex_pc);
1900     } else  {
1901       is_string_char_at = org->AsArrayGet()->IsStringCharAt();
1902       vector = new (global_allocator_) HVecLoad(global_allocator_,
1903                                                 base,
1904                                                 opa,
1905                                                 type,
1906                                                 org->GetSideEffects(),
1907                                                 vector_length_,
1908                                                 is_string_char_at,
1909                                                 dex_pc);
1910     }
1911     // Known (forced/adjusted/original) alignment?
1912     if (vector_dynamic_peeling_candidate_ != nullptr) {
1913       if (vector_dynamic_peeling_candidate_->offset == offset &&  // TODO: diffs too?
1914           DataType::Size(vector_dynamic_peeling_candidate_->type) == DataType::Size(type) &&
1915           vector_dynamic_peeling_candidate_->is_string_char_at == is_string_char_at) {
1916         vector->AsVecMemoryOperation()->SetAlignment(  // forced
1917             Alignment(GetVectorSizeInBytes(), 0));
1918       }
1919     } else {
1920       vector->AsVecMemoryOperation()->SetAlignment(  // adjusted/original
1921           ComputeAlignment(offset, type, is_string_char_at, vector_static_peeling_factor_));
1922     }
1923   } else {
1924     // Scalar store or load.
1925     DCHECK(vector_mode_ == kSequential);
1926     if (opb != nullptr) {
1927       DataType::Type component_type = org->AsArraySet()->GetComponentType();
1928       vector = new (global_allocator_) HArraySet(
1929           org->InputAt(0), opa, opb, component_type, org->GetSideEffects(), dex_pc);
1930     } else  {
1931       bool is_string_char_at = org->AsArrayGet()->IsStringCharAt();
1932       vector = new (global_allocator_) HArrayGet(
1933           org->InputAt(0), opa, org->GetType(), org->GetSideEffects(), dex_pc, is_string_char_at);
1934     }
1935   }
1936   vector_map_->Put(org, vector);
1937 }
1938 
GenerateVecReductionPhi(HPhi * phi)1939 void HLoopOptimization::GenerateVecReductionPhi(HPhi* phi) {
1940   DCHECK(reductions_->find(phi) != reductions_->end());
1941   DCHECK(reductions_->Get(phi->InputAt(1)) == phi);
1942   HInstruction* vector = nullptr;
1943   if (vector_mode_ == kSequential) {
1944     HPhi* new_phi = new (global_allocator_) HPhi(
1945         global_allocator_, kNoRegNumber, 0, phi->GetType());
1946     vector_header_->AddPhi(new_phi);
1947     vector = new_phi;
1948   } else {
1949     // Link vector reduction back to prior unrolled update, or a first phi.
1950     auto it = vector_permanent_map_->find(phi);
1951     if (it != vector_permanent_map_->end()) {
1952       vector = it->second;
1953     } else {
1954       HPhi* new_phi = new (global_allocator_) HPhi(
1955           global_allocator_, kNoRegNumber, 0, HVecOperation::kSIMDType);
1956       vector_header_->AddPhi(new_phi);
1957       vector = new_phi;
1958     }
1959   }
1960   vector_map_->Put(phi, vector);
1961 }
1962 
GenerateVecReductionPhiInputs(HPhi * phi,HInstruction * reduction)1963 void HLoopOptimization::GenerateVecReductionPhiInputs(HPhi* phi, HInstruction* reduction) {
1964   HInstruction* new_phi = vector_map_->Get(phi);
1965   HInstruction* new_init = reductions_->Get(phi);
1966   HInstruction* new_red = vector_map_->Get(reduction);
1967   // Link unrolled vector loop back to new phi.
1968   for (; !new_phi->IsPhi(); new_phi = vector_permanent_map_->Get(new_phi)) {
1969     DCHECK(new_phi->IsVecOperation());
1970   }
1971   // Prepare the new initialization.
1972   if (vector_mode_ == kVector) {
1973     // Generate a [initial, 0, .., 0] vector for add or
1974     // a [initial, initial, .., initial] vector for min/max.
1975     HVecOperation* red_vector = new_red->AsVecOperation();
1976     HVecReduce::ReductionKind kind = GetReductionKind(red_vector);
1977     uint32_t vector_length = red_vector->GetVectorLength();
1978     DataType::Type type = red_vector->GetPackedType();
1979     if (kind == HVecReduce::ReductionKind::kSum) {
1980       new_init = Insert(vector_preheader_,
1981                         new (global_allocator_) HVecSetScalars(global_allocator_,
1982                                                                &new_init,
1983                                                                type,
1984                                                                vector_length,
1985                                                                1,
1986                                                                kNoDexPc));
1987     } else {
1988       new_init = Insert(vector_preheader_,
1989                         new (global_allocator_) HVecReplicateScalar(global_allocator_,
1990                                                                     new_init,
1991                                                                     type,
1992                                                                     vector_length,
1993                                                                     kNoDexPc));
1994     }
1995     if (IsInPredicatedVectorizationMode()) {
1996       HVecPredSetAll* set_pred = new (global_allocator_) HVecPredSetAll(global_allocator_,
1997                                                                         graph_->GetIntConstant(1),
1998                                                                         type,
1999                                                                         vector_length,
2000                                                                         0u);
2001       vector_preheader_->InsertInstructionBefore(set_pred, new_init);
2002       new_init->AsVecOperation()->SetMergingGoverningPredicate(set_pred);
2003     }
2004   } else {
2005     new_init = ReduceAndExtractIfNeeded(new_init);
2006   }
2007   // Set the phi inputs.
2008   DCHECK(new_phi->IsPhi());
2009   new_phi->AsPhi()->AddInput(new_init);
2010   new_phi->AsPhi()->AddInput(new_red);
2011   // New feed value for next phi (safe mutation in iteration).
2012   reductions_->find(phi)->second = new_phi;
2013 }
2014 
ReduceAndExtractIfNeeded(HInstruction * instruction)2015 HInstruction* HLoopOptimization::ReduceAndExtractIfNeeded(HInstruction* instruction) {
2016   if (instruction->IsPhi()) {
2017     HInstruction* input = instruction->InputAt(1);
2018     if (HVecOperation::ReturnsSIMDValue(input)) {
2019       DCHECK(!input->IsPhi());
2020       HVecOperation* input_vector = input->AsVecOperation();
2021       uint32_t vector_length = input_vector->GetVectorLength();
2022       DataType::Type type = input_vector->GetPackedType();
2023       HVecReduce::ReductionKind kind = GetReductionKind(input_vector);
2024       HBasicBlock* exit = instruction->GetBlock()->GetSuccessors()[0];
2025       // Generate a vector reduction and scalar extract
2026       //    x = REDUCE( [x_1, .., x_n] )
2027       //    y = x_1
2028       // along the exit of the defining loop.
2029       HInstruction* reduce = new (global_allocator_) HVecReduce(
2030           global_allocator_, instruction, type, vector_length, kind, kNoDexPc);
2031       exit->InsertInstructionBefore(reduce, exit->GetFirstInstruction());
2032       instruction = new (global_allocator_) HVecExtractScalar(
2033           global_allocator_, reduce, type, vector_length, 0, kNoDexPc);
2034       exit->InsertInstructionAfter(instruction, reduce);
2035 
2036       if (IsInPredicatedVectorizationMode()) {
2037         HVecPredSetAll* set_pred = new (global_allocator_) HVecPredSetAll(global_allocator_,
2038                                                                           graph_->GetIntConstant(1),
2039                                                                           type,
2040                                                                           vector_length,
2041                                                                           0u);
2042         exit->InsertInstructionBefore(set_pred, reduce);
2043         reduce->AsVecOperation()->SetMergingGoverningPredicate(set_pred);
2044         instruction->AsVecOperation()->SetMergingGoverningPredicate(set_pred);
2045       }
2046     }
2047   }
2048   return instruction;
2049 }
2050 
2051 #define GENERATE_VEC(x, y) \
2052   if (vector_mode_ == kVector) { \
2053     vector = (x); \
2054   } else { \
2055     DCHECK(vector_mode_ == kSequential); \
2056     vector = (y); \
2057   } \
2058   break;
2059 
GenerateVecOp(HInstruction * org,HInstruction * opa,HInstruction * opb,DataType::Type type)2060 void HLoopOptimization::GenerateVecOp(HInstruction* org,
2061                                       HInstruction* opa,
2062                                       HInstruction* opb,
2063                                       DataType::Type type) {
2064   uint32_t dex_pc = org->GetDexPc();
2065   HInstruction* vector = nullptr;
2066   DataType::Type org_type = org->GetType();
2067   switch (org->GetKind()) {
2068     case HInstruction::kNeg:
2069       DCHECK(opb == nullptr);
2070       GENERATE_VEC(
2071         new (global_allocator_) HVecNeg(global_allocator_, opa, type, vector_length_, dex_pc),
2072         new (global_allocator_) HNeg(org_type, opa, dex_pc));
2073     case HInstruction::kNot:
2074       DCHECK(opb == nullptr);
2075       GENERATE_VEC(
2076         new (global_allocator_) HVecNot(global_allocator_, opa, type, vector_length_, dex_pc),
2077         new (global_allocator_) HNot(org_type, opa, dex_pc));
2078     case HInstruction::kBooleanNot:
2079       DCHECK(opb == nullptr);
2080       GENERATE_VEC(
2081         new (global_allocator_) HVecNot(global_allocator_, opa, type, vector_length_, dex_pc),
2082         new (global_allocator_) HBooleanNot(opa, dex_pc));
2083     case HInstruction::kTypeConversion:
2084       DCHECK(opb == nullptr);
2085       GENERATE_VEC(
2086         new (global_allocator_) HVecCnv(global_allocator_, opa, type, vector_length_, dex_pc),
2087         new (global_allocator_) HTypeConversion(org_type, opa, dex_pc));
2088     case HInstruction::kAdd:
2089       GENERATE_VEC(
2090         new (global_allocator_) HVecAdd(global_allocator_, opa, opb, type, vector_length_, dex_pc),
2091         new (global_allocator_) HAdd(org_type, opa, opb, dex_pc));
2092     case HInstruction::kSub:
2093       GENERATE_VEC(
2094         new (global_allocator_) HVecSub(global_allocator_, opa, opb, type, vector_length_, dex_pc),
2095         new (global_allocator_) HSub(org_type, opa, opb, dex_pc));
2096     case HInstruction::kMul:
2097       GENERATE_VEC(
2098         new (global_allocator_) HVecMul(global_allocator_, opa, opb, type, vector_length_, dex_pc),
2099         new (global_allocator_) HMul(org_type, opa, opb, dex_pc));
2100     case HInstruction::kDiv:
2101       GENERATE_VEC(
2102         new (global_allocator_) HVecDiv(global_allocator_, opa, opb, type, vector_length_, dex_pc),
2103         new (global_allocator_) HDiv(org_type, opa, opb, dex_pc));
2104     case HInstruction::kAnd:
2105       GENERATE_VEC(
2106         new (global_allocator_) HVecAnd(global_allocator_, opa, opb, type, vector_length_, dex_pc),
2107         new (global_allocator_) HAnd(org_type, opa, opb, dex_pc));
2108     case HInstruction::kOr:
2109       GENERATE_VEC(
2110         new (global_allocator_) HVecOr(global_allocator_, opa, opb, type, vector_length_, dex_pc),
2111         new (global_allocator_) HOr(org_type, opa, opb, dex_pc));
2112     case HInstruction::kXor:
2113       GENERATE_VEC(
2114         new (global_allocator_) HVecXor(global_allocator_, opa, opb, type, vector_length_, dex_pc),
2115         new (global_allocator_) HXor(org_type, opa, opb, dex_pc));
2116     case HInstruction::kShl:
2117       GENERATE_VEC(
2118         new (global_allocator_) HVecShl(global_allocator_, opa, opb, type, vector_length_, dex_pc),
2119         new (global_allocator_) HShl(org_type, opa, opb, dex_pc));
2120     case HInstruction::kShr:
2121       GENERATE_VEC(
2122         new (global_allocator_) HVecShr(global_allocator_, opa, opb, type, vector_length_, dex_pc),
2123         new (global_allocator_) HShr(org_type, opa, opb, dex_pc));
2124     case HInstruction::kUShr:
2125       GENERATE_VEC(
2126         new (global_allocator_) HVecUShr(global_allocator_, opa, opb, type, vector_length_, dex_pc),
2127         new (global_allocator_) HUShr(org_type, opa, opb, dex_pc));
2128     case HInstruction::kAbs:
2129       DCHECK(opb == nullptr);
2130       GENERATE_VEC(
2131         new (global_allocator_) HVecAbs(global_allocator_, opa, type, vector_length_, dex_pc),
2132         new (global_allocator_) HAbs(org_type, opa, dex_pc));
2133     default:
2134       break;
2135   }  // switch
2136   CHECK(vector != nullptr) << "Unsupported SIMD operator";
2137   vector_map_->Put(org, vector);
2138 }
2139 
2140 #undef GENERATE_VEC
2141 
2142 //
2143 // Vectorization idioms.
2144 //
2145 
2146 // Method recognizes the following idioms:
2147 //   rounding  halving add (a + b + 1) >> 1 for unsigned/signed operands a, b
2148 //   truncated halving add (a + b)     >> 1 for unsigned/signed operands a, b
2149 // Provided that the operands are promoted to a wider form to do the arithmetic and
2150 // then cast back to narrower form, the idioms can be mapped into efficient SIMD
2151 // implementation that operates directly in narrower form (plus one extra bit).
2152 // TODO: current version recognizes implicit byte/short/char widening only;
2153 //       explicit widening from int to long could be added later.
VectorizeHalvingAddIdiom(LoopNode * node,HInstruction * instruction,bool generate_code,DataType::Type type,uint64_t restrictions)2154 bool HLoopOptimization::VectorizeHalvingAddIdiom(LoopNode* node,
2155                                                  HInstruction* instruction,
2156                                                  bool generate_code,
2157                                                  DataType::Type type,
2158                                                  uint64_t restrictions) {
2159   // Test for top level arithmetic shift right x >> 1 or logical shift right x >>> 1
2160   // (note whether the sign bit in wider precision is shifted in has no effect
2161   // on the narrow precision computed by the idiom).
2162   if ((instruction->IsShr() ||
2163        instruction->IsUShr()) &&
2164       IsInt64Value(instruction->InputAt(1), 1)) {
2165     // Test for (a + b + c) >> 1 for optional constant c.
2166     HInstruction* a = nullptr;
2167     HInstruction* b = nullptr;
2168     int64_t       c = 0;
2169     if (IsAddConst2(graph_, instruction->InputAt(0), /*out*/ &a, /*out*/ &b, /*out*/ &c)) {
2170       // Accept c == 1 (rounded) or c == 0 (not rounded).
2171       bool is_rounded = false;
2172       if (c == 1) {
2173         is_rounded = true;
2174       } else if (c != 0) {
2175         return false;
2176       }
2177       // Accept consistent zero or sign extension on operands a and b.
2178       HInstruction* r = nullptr;
2179       HInstruction* s = nullptr;
2180       bool is_unsigned = false;
2181       if (!IsNarrowerOperands(a, b, type, &r, &s, &is_unsigned)) {
2182         return false;
2183       }
2184       // Deal with vector restrictions.
2185       if ((is_unsigned && HasVectorRestrictions(restrictions, kNoUnsignedHAdd)) ||
2186           (!is_unsigned && HasVectorRestrictions(restrictions, kNoSignedHAdd)) ||
2187           (!is_rounded && HasVectorRestrictions(restrictions, kNoUnroundedHAdd))) {
2188         return false;
2189       }
2190       // Accept recognized halving add for vectorizable operands. Vectorized code uses the
2191       // shorthand idiomatic operation. Sequential code uses the original scalar expressions.
2192       DCHECK(r != nullptr && s != nullptr);
2193       if (generate_code && vector_mode_ != kVector) {  // de-idiom
2194         r = instruction->InputAt(0);
2195         s = instruction->InputAt(1);
2196       }
2197       if (VectorizeUse(node, r, generate_code, type, restrictions) &&
2198           VectorizeUse(node, s, generate_code, type, restrictions)) {
2199         if (generate_code) {
2200           if (vector_mode_ == kVector) {
2201             vector_map_->Put(instruction, new (global_allocator_) HVecHalvingAdd(
2202                 global_allocator_,
2203                 vector_map_->Get(r),
2204                 vector_map_->Get(s),
2205                 HVecOperation::ToProperType(type, is_unsigned),
2206                 vector_length_,
2207                 is_rounded,
2208                 kNoDexPc));
2209             MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorizedIdiom);
2210           } else {
2211             GenerateVecOp(instruction, vector_map_->Get(r), vector_map_->Get(s), type);
2212           }
2213         }
2214         return true;
2215       }
2216     }
2217   }
2218   return false;
2219 }
2220 
2221 // Method recognizes the following idiom:
2222 //   q += ABS(a - b) for signed operands a, b
2223 // Provided that the operands have the same type or are promoted to a wider form.
2224 // Since this may involve a vector length change, the idiom is handled by going directly
2225 // to a sad-accumulate node (rather than relying combining finer grained nodes later).
2226 // TODO: unsigned SAD too?
VectorizeSADIdiom(LoopNode * node,HInstruction * instruction,bool generate_code,DataType::Type reduction_type,uint64_t restrictions)2227 bool HLoopOptimization::VectorizeSADIdiom(LoopNode* node,
2228                                           HInstruction* instruction,
2229                                           bool generate_code,
2230                                           DataType::Type reduction_type,
2231                                           uint64_t restrictions) {
2232   // Filter integral "q += ABS(a - b);" reduction, where ABS and SUB
2233   // are done in the same precision (either int or long).
2234   if (!instruction->IsAdd() ||
2235       (reduction_type != DataType::Type::kInt32 && reduction_type != DataType::Type::kInt64)) {
2236     return false;
2237   }
2238   HInstruction* acc = instruction->InputAt(0);
2239   HInstruction* abs = instruction->InputAt(1);
2240   HInstruction* a = nullptr;
2241   HInstruction* b = nullptr;
2242   if (abs->IsAbs() &&
2243       abs->GetType() == reduction_type &&
2244       IsSubConst2(graph_, abs->InputAt(0), /*out*/ &a, /*out*/ &b)) {
2245     DCHECK(a != nullptr && b != nullptr);
2246   } else {
2247     return false;
2248   }
2249   // Accept same-type or consistent sign extension for narrower-type on operands a and b.
2250   // The same-type or narrower operands are called r (a or lower) and s (b or lower).
2251   // We inspect the operands carefully to pick the most suited type.
2252   HInstruction* r = a;
2253   HInstruction* s = b;
2254   bool is_unsigned = false;
2255   DataType::Type sub_type = GetNarrowerType(a, b);
2256   if (reduction_type != sub_type &&
2257       (!IsNarrowerOperands(a, b, sub_type, &r, &s, &is_unsigned) || is_unsigned)) {
2258     return false;
2259   }
2260   // Try same/narrower type and deal with vector restrictions.
2261   if (!TrySetVectorType(sub_type, &restrictions) ||
2262       HasVectorRestrictions(restrictions, kNoSAD) ||
2263       (reduction_type != sub_type && HasVectorRestrictions(restrictions, kNoWideSAD))) {
2264     return false;
2265   }
2266   // Accept SAD idiom for vectorizable operands. Vectorized code uses the shorthand
2267   // idiomatic operation. Sequential code uses the original scalar expressions.
2268   DCHECK(r != nullptr && s != nullptr);
2269   if (generate_code && vector_mode_ != kVector) {  // de-idiom
2270     r = s = abs->InputAt(0);
2271   }
2272   if (VectorizeUse(node, acc, generate_code, sub_type, restrictions) &&
2273       VectorizeUse(node, r, generate_code, sub_type, restrictions) &&
2274       VectorizeUse(node, s, generate_code, sub_type, restrictions)) {
2275     if (generate_code) {
2276       if (vector_mode_ == kVector) {
2277         vector_map_->Put(instruction, new (global_allocator_) HVecSADAccumulate(
2278             global_allocator_,
2279             vector_map_->Get(acc),
2280             vector_map_->Get(r),
2281             vector_map_->Get(s),
2282             HVecOperation::ToProperType(reduction_type, is_unsigned),
2283             GetOtherVL(reduction_type, sub_type, vector_length_),
2284             kNoDexPc));
2285         MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorizedIdiom);
2286       } else {
2287         // "GenerateVecOp()" must not be called more than once for each original loop body
2288         // instruction. As the SAD idiom processes both "current" instruction ("instruction")
2289         // and its ABS input in one go, we must check that for the scalar case the ABS instruction
2290         // has not yet been processed.
2291         if (vector_map_->find(abs) == vector_map_->end()) {
2292           GenerateVecOp(abs, vector_map_->Get(r), nullptr, reduction_type);
2293         }
2294         GenerateVecOp(instruction, vector_map_->Get(acc), vector_map_->Get(abs), reduction_type);
2295       }
2296     }
2297     return true;
2298   }
2299   return false;
2300 }
2301 
2302 // Method recognises the following dot product idiom:
2303 //   q += a * b for operands a, b whose type is narrower than the reduction one.
2304 // Provided that the operands have the same type or are promoted to a wider form.
2305 // Since this may involve a vector length change, the idiom is handled by going directly
2306 // 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)2307 bool HLoopOptimization::VectorizeDotProdIdiom(LoopNode* node,
2308                                               HInstruction* instruction,
2309                                               bool generate_code,
2310                                               DataType::Type reduction_type,
2311                                               uint64_t restrictions) {
2312   if (!instruction->IsAdd() || reduction_type != DataType::Type::kInt32) {
2313     return false;
2314   }
2315 
2316   HInstruction* const acc = instruction->InputAt(0);
2317   HInstruction* const mul = instruction->InputAt(1);
2318   if (!mul->IsMul() || mul->GetType() != reduction_type) {
2319     return false;
2320   }
2321 
2322   HInstruction* const mul_left = mul->InputAt(0);
2323   HInstruction* const mul_right = mul->InputAt(1);
2324   HInstruction* r = mul_left;
2325   HInstruction* s = mul_right;
2326   DataType::Type op_type = GetNarrowerType(mul_left, mul_right);
2327   bool is_unsigned = false;
2328 
2329   if (!IsNarrowerOperands(mul_left, mul_right, op_type, &r, &s, &is_unsigned)) {
2330     return false;
2331   }
2332   op_type = HVecOperation::ToProperType(op_type, is_unsigned);
2333 
2334   if (!TrySetVectorType(op_type, &restrictions) ||
2335       HasVectorRestrictions(restrictions, kNoDotProd)) {
2336     return false;
2337   }
2338 
2339   DCHECK(r != nullptr && s != nullptr);
2340   // Accept dot product idiom for vectorizable operands. Vectorized code uses the shorthand
2341   // idiomatic operation. Sequential code uses the original scalar expressions.
2342   if (generate_code && vector_mode_ != kVector) {  // de-idiom
2343     r = mul_left;
2344     s = mul_right;
2345   }
2346   if (VectorizeUse(node, acc, generate_code, op_type, restrictions) &&
2347       VectorizeUse(node, r, generate_code, op_type, restrictions) &&
2348       VectorizeUse(node, s, generate_code, op_type, restrictions)) {
2349     if (generate_code) {
2350       if (vector_mode_ == kVector) {
2351         vector_map_->Put(instruction, new (global_allocator_) HVecDotProd(
2352             global_allocator_,
2353             vector_map_->Get(acc),
2354             vector_map_->Get(r),
2355             vector_map_->Get(s),
2356             reduction_type,
2357             is_unsigned,
2358             GetOtherVL(reduction_type, op_type, vector_length_),
2359             kNoDexPc));
2360         MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorizedIdiom);
2361       } else {
2362         // "GenerateVecOp()" must not be called more than once for each original loop body
2363         // instruction. As the DotProd idiom processes both "current" instruction ("instruction")
2364         // and its MUL input in one go, we must check that for the scalar case the MUL instruction
2365         // has not yet been processed.
2366         if (vector_map_->find(mul) == vector_map_->end()) {
2367           GenerateVecOp(mul, vector_map_->Get(r), vector_map_->Get(s), reduction_type);
2368         }
2369         GenerateVecOp(instruction, vector_map_->Get(acc), vector_map_->Get(mul), reduction_type);
2370       }
2371     }
2372     return true;
2373   }
2374   return false;
2375 }
2376 
2377 //
2378 // Vectorization heuristics.
2379 //
2380 
ComputeAlignment(HInstruction * offset,DataType::Type type,bool is_string_char_at,uint32_t peeling)2381 Alignment HLoopOptimization::ComputeAlignment(HInstruction* offset,
2382                                               DataType::Type type,
2383                                               bool is_string_char_at,
2384                                               uint32_t peeling) {
2385   // Combine the alignment and hidden offset that is guaranteed by
2386   // the Android runtime with a known starting index adjusted as bytes.
2387   int64_t value = 0;
2388   if (IsInt64AndGet(offset, /*out*/ &value)) {
2389     uint32_t start_offset =
2390         HiddenOffset(type, is_string_char_at) + (value + peeling) * DataType::Size(type);
2391     return Alignment(BaseAlignment(), start_offset & (BaseAlignment() - 1u));
2392   }
2393   // Otherwise, the Android runtime guarantees at least natural alignment.
2394   return Alignment(DataType::Size(type), 0);
2395 }
2396 
SetAlignmentStrategy(const ScopedArenaVector<uint32_t> & peeling_votes,const ArrayReference * peeling_candidate)2397 void HLoopOptimization::SetAlignmentStrategy(const ScopedArenaVector<uint32_t>& peeling_votes,
2398                                              const ArrayReference* peeling_candidate) {
2399   // Current heuristic: pick the best static loop peeling factor, if any,
2400   // or otherwise use dynamic loop peeling on suggested peeling candidate.
2401   uint32_t max_vote = 0;
2402   for (size_t i = 0; i < peeling_votes.size(); i++) {
2403     if (peeling_votes[i] > max_vote) {
2404       max_vote = peeling_votes[i];
2405       vector_static_peeling_factor_ = i;
2406     }
2407   }
2408   if (max_vote == 0) {
2409     vector_dynamic_peeling_candidate_ = peeling_candidate;
2410   }
2411 }
2412 
MaxNumberPeeled()2413 uint32_t HLoopOptimization::MaxNumberPeeled() {
2414   if (vector_dynamic_peeling_candidate_ != nullptr) {
2415     return vector_length_ - 1u;  // worst-case
2416   }
2417   return vector_static_peeling_factor_;  // known exactly
2418 }
2419 
IsVectorizationProfitable(int64_t trip_count)2420 bool HLoopOptimization::IsVectorizationProfitable(int64_t trip_count) {
2421   // Current heuristic: non-empty body with sufficient number of iterations (if known).
2422   // TODO: refine by looking at e.g. operation count, alignment, etc.
2423   // TODO: trip count is really unsigned entity, provided the guarding test
2424   //       is satisfied; deal with this more carefully later
2425   uint32_t max_peel = MaxNumberPeeled();
2426   if (vector_length_ == 0) {
2427     return false;  // nothing found
2428   } else if (trip_count < 0) {
2429     return false;  // guard against non-taken/large
2430   } else if ((0 < trip_count) && (trip_count < (vector_length_ + max_peel))) {
2431     return false;  // insufficient iterations
2432   }
2433   return true;
2434 }
2435 
2436 //
2437 // Helpers.
2438 //
2439 
TrySetPhiInduction(HPhi * phi,bool restrict_uses)2440 bool HLoopOptimization::TrySetPhiInduction(HPhi* phi, bool restrict_uses) {
2441   // Start with empty phi induction.
2442   iset_->clear();
2443 
2444   // Special case Phis that have equivalent in a debuggable setup. Our graph checker isn't
2445   // smart enough to follow strongly connected components (and it's probably not worth
2446   // it to make it so). See b/33775412.
2447   if (graph_->IsDebuggable() && phi->HasEquivalentPhi()) {
2448     return false;
2449   }
2450 
2451   // Lookup phi induction cycle.
2452   ArenaSet<HInstruction*>* set = induction_range_.LookupCycle(phi);
2453   if (set != nullptr) {
2454     for (HInstruction* i : *set) {
2455       // Check that, other than instructions that are no longer in the graph (removed earlier)
2456       // each instruction is removable and, when restrict uses are requested, other than for phi,
2457       // all uses are contained within the cycle.
2458       if (!i->IsInBlock()) {
2459         continue;
2460       } else if (!i->IsRemovable()) {
2461         return false;
2462       } else if (i != phi && restrict_uses) {
2463         // Deal with regular uses.
2464         for (const HUseListNode<HInstruction*>& use : i->GetUses()) {
2465           if (set->find(use.GetUser()) == set->end()) {
2466             return false;
2467           }
2468         }
2469       }
2470       iset_->insert(i);  // copy
2471     }
2472     return true;
2473   }
2474   return false;
2475 }
2476 
TrySetPhiReduction(HPhi * phi)2477 bool HLoopOptimization::TrySetPhiReduction(HPhi* phi) {
2478   DCHECK(phi->IsLoopHeaderPhi());
2479   // Only unclassified phi cycles are candidates for reductions.
2480   if (induction_range_.IsClassified(phi)) {
2481     return false;
2482   }
2483   // Accept operations like x = x + .., provided that the phi and the reduction are
2484   // used exactly once inside the loop, and by each other.
2485   HInputsRef inputs = phi->GetInputs();
2486   if (inputs.size() == 2) {
2487     HInstruction* reduction = inputs[1];
2488     if (HasReductionFormat(reduction, phi)) {
2489       HLoopInformation* loop_info = phi->GetBlock()->GetLoopInformation();
2490       DCHECK(loop_info->Contains(*reduction->GetBlock()));
2491       const bool single_use_inside_loop =
2492           // Reduction update only used by phi.
2493           reduction->GetUses().HasExactlyOneElement() &&
2494           !reduction->HasEnvironmentUses() &&
2495           // Reduction update is only use of phi inside the loop.
2496           std::none_of(phi->GetUses().begin(),
2497                        phi->GetUses().end(),
2498                        [loop_info, reduction](const HUseListNode<HInstruction*>& use) {
2499                          HInstruction* user = use.GetUser();
2500                          return user != reduction && loop_info->Contains(*user->GetBlock());
2501                        });
2502       if (single_use_inside_loop) {
2503         // Link reduction back, and start recording feed value.
2504         reductions_->Put(reduction, phi);
2505         reductions_->Put(phi, phi->InputAt(0));
2506         return true;
2507       }
2508     }
2509   }
2510   return false;
2511 }
2512 
TrySetSimpleLoopHeader(HBasicBlock * block,HPhi ** main_phi)2513 bool HLoopOptimization::TrySetSimpleLoopHeader(HBasicBlock* block, /*out*/ HPhi** main_phi) {
2514   // Start with empty phi induction and reductions.
2515   iset_->clear();
2516   reductions_->clear();
2517 
2518   // Scan the phis to find the following (the induction structure has already
2519   // been optimized, so we don't need to worry about trivial cases):
2520   // (1) optional reductions in loop,
2521   // (2) the main induction, used in loop control.
2522   HPhi* phi = nullptr;
2523   for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
2524     if (TrySetPhiReduction(it.Current()->AsPhi())) {
2525       continue;
2526     } else if (phi == nullptr) {
2527       // Found the first candidate for main induction.
2528       phi = it.Current()->AsPhi();
2529     } else {
2530       return false;
2531     }
2532   }
2533 
2534   // Then test for a typical loopheader:
2535   //   s:  SuspendCheck
2536   //   c:  Condition(phi, bound)
2537   //   i:  If(c)
2538   if (phi != nullptr && TrySetPhiInduction(phi, /*restrict_uses*/ false)) {
2539     HInstruction* s = block->GetFirstInstruction();
2540     if (s != nullptr && s->IsSuspendCheck()) {
2541       HInstruction* c = s->GetNext();
2542       if (c != nullptr &&
2543           c->IsCondition() &&
2544           c->GetUses().HasExactlyOneElement() &&  // only used for termination
2545           !c->HasEnvironmentUses()) {  // unlikely, but not impossible
2546         HInstruction* i = c->GetNext();
2547         if (i != nullptr && i->IsIf() && i->InputAt(0) == c) {
2548           iset_->insert(c);
2549           iset_->insert(s);
2550           *main_phi = phi;
2551           return true;
2552         }
2553       }
2554     }
2555   }
2556   return false;
2557 }
2558 
IsEmptyBody(HBasicBlock * block)2559 bool HLoopOptimization::IsEmptyBody(HBasicBlock* block) {
2560   if (!block->GetPhis().IsEmpty()) {
2561     return false;
2562   }
2563   for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
2564     HInstruction* instruction = it.Current();
2565     if (!instruction->IsGoto() && iset_->find(instruction) == iset_->end()) {
2566       return false;
2567     }
2568   }
2569   return true;
2570 }
2571 
IsUsedOutsideLoop(HLoopInformation * loop_info,HInstruction * instruction)2572 bool HLoopOptimization::IsUsedOutsideLoop(HLoopInformation* loop_info,
2573                                           HInstruction* instruction) {
2574   // Deal with regular uses.
2575   for (const HUseListNode<HInstruction*>& use : instruction->GetUses()) {
2576     if (use.GetUser()->GetBlock()->GetLoopInformation() != loop_info) {
2577       return true;
2578     }
2579   }
2580   return false;
2581 }
2582 
IsOnlyUsedAfterLoop(HLoopInformation * loop_info,HInstruction * instruction,bool collect_loop_uses,uint32_t * use_count)2583 bool HLoopOptimization::IsOnlyUsedAfterLoop(HLoopInformation* loop_info,
2584                                             HInstruction* instruction,
2585                                             bool collect_loop_uses,
2586                                             /*out*/ uint32_t* use_count) {
2587   // Deal with regular uses.
2588   for (const HUseListNode<HInstruction*>& use : instruction->GetUses()) {
2589     HInstruction* user = use.GetUser();
2590     if (iset_->find(user) == iset_->end()) {  // not excluded?
2591       if (loop_info->Contains(*user->GetBlock())) {
2592         // If collect_loop_uses is set, simply keep adding those uses to the set.
2593         // Otherwise, reject uses inside the loop that were not already in the set.
2594         if (collect_loop_uses) {
2595           iset_->insert(user);
2596           continue;
2597         }
2598         return false;
2599       }
2600       ++*use_count;
2601     }
2602   }
2603   return true;
2604 }
2605 
TryReplaceWithLastValue(HLoopInformation * loop_info,HInstruction * instruction,HBasicBlock * block)2606 bool HLoopOptimization::TryReplaceWithLastValue(HLoopInformation* loop_info,
2607                                                 HInstruction* instruction,
2608                                                 HBasicBlock* block) {
2609   // Try to replace outside uses with the last value.
2610   if (induction_range_.CanGenerateLastValue(instruction)) {
2611     HInstruction* replacement = induction_range_.GenerateLastValue(instruction, graph_, block);
2612     // Deal with regular uses.
2613     const HUseList<HInstruction*>& uses = instruction->GetUses();
2614     for (auto it = uses.begin(), end = uses.end(); it != end;) {
2615       HInstruction* user = it->GetUser();
2616       size_t index = it->GetIndex();
2617       ++it;  // increment before replacing
2618       if (iset_->find(user) == iset_->end()) {  // not excluded?
2619         if (kIsDebugBuild) {
2620           // We have checked earlier in 'IsOnlyUsedAfterLoop' that the use is after the loop.
2621           HLoopInformation* other_loop_info = user->GetBlock()->GetLoopInformation();
2622           CHECK(other_loop_info == nullptr || !other_loop_info->IsIn(*loop_info));
2623         }
2624         user->ReplaceInput(replacement, index);
2625         induction_range_.Replace(user, instruction, replacement);  // update induction
2626       }
2627     }
2628     // Deal with environment uses.
2629     const HUseList<HEnvironment*>& env_uses = instruction->GetEnvUses();
2630     for (auto it = env_uses.begin(), end = env_uses.end(); it != end;) {
2631       HEnvironment* user = it->GetUser();
2632       size_t index = it->GetIndex();
2633       ++it;  // increment before replacing
2634       if (iset_->find(user->GetHolder()) == iset_->end()) {  // not excluded?
2635         // Only update environment uses after the loop.
2636         HLoopInformation* other_loop_info = user->GetHolder()->GetBlock()->GetLoopInformation();
2637         if (other_loop_info == nullptr || !other_loop_info->IsIn(*loop_info)) {
2638           user->RemoveAsUserOfInput(index);
2639           user->SetRawEnvAt(index, replacement);
2640           replacement->AddEnvUseAt(user, index);
2641         }
2642       }
2643     }
2644     return true;
2645   }
2646   return false;
2647 }
2648 
TryAssignLastValue(HLoopInformation * loop_info,HInstruction * instruction,HBasicBlock * block,bool collect_loop_uses)2649 bool HLoopOptimization::TryAssignLastValue(HLoopInformation* loop_info,
2650                                            HInstruction* instruction,
2651                                            HBasicBlock* block,
2652                                            bool collect_loop_uses) {
2653   // Assigning the last value is always successful if there are no uses.
2654   // Otherwise, it succeeds in a no early-exit loop by generating the
2655   // proper last value assignment.
2656   uint32_t use_count = 0;
2657   return IsOnlyUsedAfterLoop(loop_info, instruction, collect_loop_uses, &use_count) &&
2658       (use_count == 0 ||
2659        (!IsEarlyExit(loop_info) && TryReplaceWithLastValue(loop_info, instruction, block)));
2660 }
2661 
RemoveDeadInstructions(const HInstructionList & list)2662 void HLoopOptimization::RemoveDeadInstructions(const HInstructionList& list) {
2663   for (HBackwardInstructionIterator i(list); !i.Done(); i.Advance()) {
2664     HInstruction* instruction = i.Current();
2665     if (instruction->IsDeadAndRemovable()) {
2666       simplified_ = true;
2667       instruction->GetBlock()->RemoveInstructionOrPhi(instruction);
2668     }
2669   }
2670 }
2671 
CanRemoveCycle()2672 bool HLoopOptimization::CanRemoveCycle() {
2673   for (HInstruction* i : *iset_) {
2674     // We can never remove instructions that have environment
2675     // uses when we compile 'debuggable'.
2676     if (i->HasEnvironmentUses() && graph_->IsDebuggable()) {
2677       return false;
2678     }
2679     // A deoptimization should never have an environment input removed.
2680     for (const HUseListNode<HEnvironment*>& use : i->GetEnvUses()) {
2681       if (use.GetUser()->GetHolder()->IsDeoptimize()) {
2682         return false;
2683       }
2684     }
2685   }
2686   return true;
2687 }
2688 
2689 }  // namespace art
2690