blob: 4143462c7177414c5874cf6018d18733e3b612bf [file] [log] [blame]
Aart Bik281c6812016-08-26 11:31:48 -07001/*
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
Aart Bikf8f5a162017-02-06 15:35:29 -080019#include "arch/arm/instruction_set_features_arm.h"
20#include "arch/arm64/instruction_set_features_arm64.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070021#include "arch/instruction_set.h"
Aart Bikf8f5a162017-02-06 15:35:29 -080022#include "arch/mips/instruction_set_features_mips.h"
23#include "arch/mips64/instruction_set_features_mips64.h"
24#include "arch/x86/instruction_set_features_x86.h"
25#include "arch/x86_64/instruction_set_features_x86_64.h"
Aart Bik92685a82017-03-06 11:13:43 -080026#include "driver/compiler_driver.h"
Aart Bik96202302016-10-04 17:33:56 -070027#include "linear_order.h"
Aart Bik281c6812016-08-26 11:31:48 -070028
29namespace art {
30
Aart Bikf8f5a162017-02-06 15:35:29 -080031// Enables vectorization (SIMDization) in the loop optimizer.
32static constexpr bool kEnableVectorization = true;
33
Aart Bik14a68b42017-06-08 14:06:58 -070034// All current SIMD targets want 16-byte alignment.
35static constexpr size_t kAlignedBase = 16;
36
Aart Bik9abf8942016-10-14 09:49:42 -070037// Remove the instruction from the graph. A bit more elaborate than the usual
38// instruction removal, since there may be a cycle in the use structure.
Aart Bik281c6812016-08-26 11:31:48 -070039static void RemoveFromCycle(HInstruction* instruction) {
Aart Bik281c6812016-08-26 11:31:48 -070040 instruction->RemoveAsUserOfAllInputs();
41 instruction->RemoveEnvironmentUsers();
42 instruction->GetBlock()->RemoveInstructionOrPhi(instruction, /*ensure_safety=*/ false);
Artem Serov21c7e6f2017-07-27 16:04:42 +010043 RemoveEnvironmentUses(instruction);
44 ResetEnvironmentInputRecords(instruction);
Aart Bik281c6812016-08-26 11:31:48 -070045}
46
Aart Bik807868e2016-11-03 17:51:43 -070047// Detect a goto block and sets succ to the single successor.
Aart Bike3dedc52016-11-02 17:50:27 -070048static bool IsGotoBlock(HBasicBlock* block, /*out*/ HBasicBlock** succ) {
49 if (block->GetPredecessors().size() == 1 &&
50 block->GetSuccessors().size() == 1 &&
51 block->IsSingleGoto()) {
52 *succ = block->GetSingleSuccessor();
53 return true;
54 }
55 return false;
56}
57
Aart Bik807868e2016-11-03 17:51:43 -070058// Detect an early exit loop.
59static bool IsEarlyExit(HLoopInformation* loop_info) {
60 HBlocksInLoopReversePostOrderIterator it_loop(*loop_info);
61 for (it_loop.Advance(); !it_loop.Done(); it_loop.Advance()) {
62 for (HBasicBlock* successor : it_loop.Current()->GetSuccessors()) {
63 if (!loop_info->Contains(*successor)) {
64 return true;
65 }
66 }
67 }
68 return false;
69}
70
Aart Bikf3e61ee2017-04-12 17:09:20 -070071// Detect a sign extension from the given type. Returns the promoted operand on success.
72static bool IsSignExtensionAndGet(HInstruction* instruction,
73 Primitive::Type type,
74 /*out*/ HInstruction** operand) {
75 // Accept any already wider constant that would be handled properly by sign
76 // extension when represented in the *width* of the given narrower data type
77 // (the fact that char normally zero extends does not matter here).
78 int64_t value = 0;
Aart Bik50e20d52017-05-05 14:07:29 -070079 if (IsInt64AndGet(instruction, /*out*/ &value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -070080 switch (type) {
81 case Primitive::kPrimByte:
82 if (std::numeric_limits<int8_t>::min() <= value &&
83 std::numeric_limits<int8_t>::max() >= value) {
84 *operand = instruction;
85 return true;
86 }
87 return false;
88 case Primitive::kPrimChar:
89 case Primitive::kPrimShort:
90 if (std::numeric_limits<int16_t>::min() <= value &&
91 std::numeric_limits<int16_t>::max() <= value) {
92 *operand = instruction;
93 return true;
94 }
95 return false;
96 default:
97 return false;
98 }
99 }
100 // An implicit widening conversion of a signed integer to an integral type sign-extends
101 // the two's-complement representation of the integer value to fill the wider format.
102 if (instruction->GetType() == type && (instruction->IsArrayGet() ||
103 instruction->IsStaticFieldGet() ||
104 instruction->IsInstanceFieldGet())) {
105 switch (type) {
106 case Primitive::kPrimByte:
107 case Primitive::kPrimShort:
108 *operand = instruction;
109 return true;
110 default:
111 return false;
112 }
113 }
114 // TODO: perhaps explicit conversions later too?
115 // (this may return something different from instruction)
116 return false;
117}
118
119// Detect a zero extension from the given type. Returns the promoted operand on success.
120static bool IsZeroExtensionAndGet(HInstruction* instruction,
121 Primitive::Type type,
122 /*out*/ HInstruction** operand) {
123 // Accept any already wider constant that would be handled properly by zero
124 // extension when represented in the *width* of the given narrower data type
125 // (the fact that byte/short normally sign extend does not matter here).
126 int64_t value = 0;
Aart Bik50e20d52017-05-05 14:07:29 -0700127 if (IsInt64AndGet(instruction, /*out*/ &value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700128 switch (type) {
129 case Primitive::kPrimByte:
130 if (std::numeric_limits<uint8_t>::min() <= value &&
131 std::numeric_limits<uint8_t>::max() >= value) {
132 *operand = instruction;
133 return true;
134 }
135 return false;
136 case Primitive::kPrimChar:
137 case Primitive::kPrimShort:
138 if (std::numeric_limits<uint16_t>::min() <= value &&
139 std::numeric_limits<uint16_t>::max() <= value) {
140 *operand = instruction;
141 return true;
142 }
143 return false;
144 default:
145 return false;
146 }
147 }
148 // An implicit widening conversion of a char to an integral type zero-extends
149 // the representation of the char value to fill the wider format.
150 if (instruction->GetType() == type && (instruction->IsArrayGet() ||
151 instruction->IsStaticFieldGet() ||
152 instruction->IsInstanceFieldGet())) {
153 if (type == Primitive::kPrimChar) {
154 *operand = instruction;
155 return true;
156 }
157 }
158 // A sign (or zero) extension followed by an explicit removal of just the
159 // higher sign bits is equivalent to a zero extension of the underlying operand.
160 if (instruction->IsAnd()) {
161 int64_t mask = 0;
162 HInstruction* a = instruction->InputAt(0);
163 HInstruction* b = instruction->InputAt(1);
164 // In (a & b) find (mask & b) or (a & mask) with sign or zero extension on the non-mask.
165 if ((IsInt64AndGet(a, /*out*/ &mask) && (IsSignExtensionAndGet(b, type, /*out*/ operand) ||
166 IsZeroExtensionAndGet(b, type, /*out*/ operand))) ||
167 (IsInt64AndGet(b, /*out*/ &mask) && (IsSignExtensionAndGet(a, type, /*out*/ operand) ||
168 IsZeroExtensionAndGet(a, type, /*out*/ operand)))) {
169 switch ((*operand)->GetType()) {
170 case Primitive::kPrimByte: return mask == std::numeric_limits<uint8_t>::max();
171 case Primitive::kPrimChar:
172 case Primitive::kPrimShort: return mask == std::numeric_limits<uint16_t>::max();
173 default: return false;
174 }
175 }
176 }
177 // TODO: perhaps explicit conversions later too?
178 return false;
179}
180
Aart Bik304c8a52017-05-23 11:01:13 -0700181// Detect situations with same-extension narrower operands.
182// Returns true on success and sets is_unsigned accordingly.
183static bool IsNarrowerOperands(HInstruction* a,
184 HInstruction* b,
185 Primitive::Type type,
186 /*out*/ HInstruction** r,
187 /*out*/ HInstruction** s,
188 /*out*/ bool* is_unsigned) {
189 if (IsSignExtensionAndGet(a, type, r) && IsSignExtensionAndGet(b, type, s)) {
190 *is_unsigned = false;
191 return true;
192 } else if (IsZeroExtensionAndGet(a, type, r) && IsZeroExtensionAndGet(b, type, s)) {
193 *is_unsigned = true;
194 return true;
195 }
196 return false;
197}
198
199// As above, single operand.
200static bool IsNarrowerOperand(HInstruction* a,
201 Primitive::Type type,
202 /*out*/ HInstruction** r,
203 /*out*/ bool* is_unsigned) {
204 if (IsSignExtensionAndGet(a, type, r)) {
205 *is_unsigned = false;
206 return true;
207 } else if (IsZeroExtensionAndGet(a, type, r)) {
208 *is_unsigned = true;
209 return true;
210 }
211 return false;
212}
213
Aart Bik5f805002017-05-16 16:42:41 -0700214// Detect up to two instructions a and b, and an acccumulated constant c.
215static bool IsAddConstHelper(HInstruction* instruction,
216 /*out*/ HInstruction** a,
217 /*out*/ HInstruction** b,
218 /*out*/ int64_t* c,
219 int32_t depth) {
220 static constexpr int32_t kMaxDepth = 8; // don't search too deep
221 int64_t value = 0;
222 if (IsInt64AndGet(instruction, &value)) {
223 *c += value;
224 return true;
225 } else if (instruction->IsAdd() && depth <= kMaxDepth) {
226 return IsAddConstHelper(instruction->InputAt(0), a, b, c, depth + 1) &&
227 IsAddConstHelper(instruction->InputAt(1), a, b, c, depth + 1);
228 } else if (*a == nullptr) {
229 *a = instruction;
230 return true;
231 } else if (*b == nullptr) {
232 *b = instruction;
233 return true;
234 }
235 return false; // too many non-const operands
236}
237
238// Detect a + b + c for an optional constant c.
239static bool IsAddConst(HInstruction* instruction,
240 /*out*/ HInstruction** a,
241 /*out*/ HInstruction** b,
242 /*out*/ int64_t* c) {
243 if (instruction->IsAdd()) {
244 // Try to find a + b and accumulated c.
245 if (IsAddConstHelper(instruction->InputAt(0), a, b, c, /*depth*/ 0) &&
246 IsAddConstHelper(instruction->InputAt(1), a, b, c, /*depth*/ 0) &&
247 *b != nullptr) {
248 return true;
249 }
250 // Found a + b.
251 *a = instruction->InputAt(0);
252 *b = instruction->InputAt(1);
253 *c = 0;
254 return true;
255 }
256 return false;
257}
258
Aart Bikb29f6842017-07-28 15:58:41 -0700259// Detect reductions of the following forms,
260// under assumption phi has only *one* use:
261// x = x_phi + ..
262// x = x_phi - ..
263// x = max(x_phi, ..)
264// x = min(x_phi, ..)
265static bool HasReductionFormat(HInstruction* reduction, HInstruction* phi) {
266 if (reduction->IsAdd()) {
267 return reduction->InputAt(0) == phi || reduction->InputAt(1) == phi;
268 } else if (reduction->IsSub()) {
269 return reduction->InputAt(0) == phi;
270 } else if (reduction->IsInvokeStaticOrDirect()) {
271 switch (reduction->AsInvokeStaticOrDirect()->GetIntrinsic()) {
272 case Intrinsics::kMathMinIntInt:
273 case Intrinsics::kMathMinLongLong:
274 case Intrinsics::kMathMinFloatFloat:
275 case Intrinsics::kMathMinDoubleDouble:
276 case Intrinsics::kMathMaxIntInt:
277 case Intrinsics::kMathMaxLongLong:
278 case Intrinsics::kMathMaxFloatFloat:
279 case Intrinsics::kMathMaxDoubleDouble:
280 return reduction->InputAt(0) == phi || reduction->InputAt(1) == phi;
281 default:
282 return false;
283 }
284 }
285 return false;
286}
287
Aart Bikf8f5a162017-02-06 15:35:29 -0800288// Test vector restrictions.
289static bool HasVectorRestrictions(uint64_t restrictions, uint64_t tested) {
290 return (restrictions & tested) != 0;
291}
292
Aart Bikf3e61ee2017-04-12 17:09:20 -0700293// Insert an instruction.
Aart Bikf8f5a162017-02-06 15:35:29 -0800294static HInstruction* Insert(HBasicBlock* block, HInstruction* instruction) {
295 DCHECK(block != nullptr);
296 DCHECK(instruction != nullptr);
297 block->InsertInstructionBefore(instruction, block->GetLastInstruction());
298 return instruction;
299}
300
Artem Serov21c7e6f2017-07-27 16:04:42 +0100301// Check that instructions from the induction sets are fully removed: have no uses
302// and no other instructions use them.
303static bool CheckInductionSetFullyRemoved(ArenaSet<HInstruction*>* iset) {
304 for (HInstruction* instr : *iset) {
305 if (instr->GetBlock() != nullptr ||
306 !instr->GetUses().empty() ||
307 !instr->GetEnvUses().empty() ||
308 HasEnvironmentUsedByOthers(instr)) {
309 return false;
310 }
311 }
Artem Serov21c7e6f2017-07-27 16:04:42 +0100312 return true;
313}
314
Aart Bik281c6812016-08-26 11:31:48 -0700315//
Aart Bikb29f6842017-07-28 15:58:41 -0700316// Public methods.
Aart Bik281c6812016-08-26 11:31:48 -0700317//
318
319HLoopOptimization::HLoopOptimization(HGraph* graph,
Aart Bik92685a82017-03-06 11:13:43 -0800320 CompilerDriver* compiler_driver,
Aart Bik281c6812016-08-26 11:31:48 -0700321 HInductionVarAnalysis* induction_analysis)
322 : HOptimization(graph, kLoopOptimizationPassName),
Aart Bik92685a82017-03-06 11:13:43 -0800323 compiler_driver_(compiler_driver),
Aart Bik281c6812016-08-26 11:31:48 -0700324 induction_range_(induction_analysis),
Aart Bik96202302016-10-04 17:33:56 -0700325 loop_allocator_(nullptr),
Aart Bikf8f5a162017-02-06 15:35:29 -0800326 global_allocator_(graph_->GetArena()),
Aart Bik281c6812016-08-26 11:31:48 -0700327 top_loop_(nullptr),
Aart Bik8c4a8542016-10-06 11:36:57 -0700328 last_loop_(nullptr),
Aart Bik482095d2016-10-10 15:39:10 -0700329 iset_(nullptr),
Aart Bikb29f6842017-07-28 15:58:41 -0700330 reductions_(nullptr),
Aart Bikf8f5a162017-02-06 15:35:29 -0800331 simplified_(false),
332 vector_length_(0),
333 vector_refs_(nullptr),
Aart Bik14a68b42017-06-08 14:06:58 -0700334 vector_peeling_candidate_(nullptr),
335 vector_runtime_test_a_(nullptr),
336 vector_runtime_test_b_(nullptr),
Aart Bikf8f5a162017-02-06 15:35:29 -0800337 vector_map_(nullptr) {
Aart Bik281c6812016-08-26 11:31:48 -0700338}
339
340void HLoopOptimization::Run() {
Mingyao Yang01b47b02017-02-03 12:09:57 -0800341 // Skip if there is no loop or the graph has try-catch/irreducible loops.
Aart Bik281c6812016-08-26 11:31:48 -0700342 // TODO: make this less of a sledgehammer.
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800343 if (!graph_->HasLoops() || graph_->HasTryCatch() || graph_->HasIrreducibleLoops()) {
Aart Bik281c6812016-08-26 11:31:48 -0700344 return;
345 }
346
Aart Bik96202302016-10-04 17:33:56 -0700347 // Phase-local allocator that draws from the global pool. Since the allocator
348 // itself resides on the stack, it is destructed on exiting Run(), which
349 // implies its underlying memory is released immediately.
Aart Bikf8f5a162017-02-06 15:35:29 -0800350 ArenaAllocator allocator(global_allocator_->GetArenaPool());
Aart Bik96202302016-10-04 17:33:56 -0700351 loop_allocator_ = &allocator;
Nicolas Geoffrayebe16742016-10-05 09:55:42 +0100352
Aart Bik96202302016-10-04 17:33:56 -0700353 // Perform loop optimizations.
354 LocalRun();
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800355 if (top_loop_ == nullptr) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800356 graph_->SetHasLoops(false); // no more loops
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800357 }
358
Aart Bik96202302016-10-04 17:33:56 -0700359 // Detach.
360 loop_allocator_ = nullptr;
361 last_loop_ = top_loop_ = nullptr;
362}
363
Aart Bikb29f6842017-07-28 15:58:41 -0700364//
365// Loop setup and traversal.
366//
367
Aart Bik96202302016-10-04 17:33:56 -0700368void HLoopOptimization::LocalRun() {
369 // Build the linear order using the phase-local allocator. This step enables building
370 // a loop hierarchy that properly reflects the outer-inner and previous-next relation.
371 ArenaVector<HBasicBlock*> linear_order(loop_allocator_->Adapter(kArenaAllocLinearOrder));
372 LinearizeGraph(graph_, loop_allocator_, &linear_order);
373
Aart Bik281c6812016-08-26 11:31:48 -0700374 // Build the loop hierarchy.
Aart Bik96202302016-10-04 17:33:56 -0700375 for (HBasicBlock* block : linear_order) {
Aart Bik281c6812016-08-26 11:31:48 -0700376 if (block->IsLoopHeader()) {
377 AddLoop(block->GetLoopInformation());
378 }
379 }
Aart Bik96202302016-10-04 17:33:56 -0700380
Aart Bik8c4a8542016-10-06 11:36:57 -0700381 // Traverse the loop hierarchy inner-to-outer and optimize. Traversal can use
Aart Bikf8f5a162017-02-06 15:35:29 -0800382 // temporary data structures using the phase-local allocator. All new HIR
383 // should use the global allocator.
Aart Bik8c4a8542016-10-06 11:36:57 -0700384 if (top_loop_ != nullptr) {
385 ArenaSet<HInstruction*> iset(loop_allocator_->Adapter(kArenaAllocLoopOptimization));
Aart Bikb29f6842017-07-28 15:58:41 -0700386 ArenaSafeMap<HInstruction*, HInstruction*> reds(
387 std::less<HInstruction*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
Aart Bikf8f5a162017-02-06 15:35:29 -0800388 ArenaSet<ArrayReference> refs(loop_allocator_->Adapter(kArenaAllocLoopOptimization));
389 ArenaSafeMap<HInstruction*, HInstruction*> map(
390 std::less<HInstruction*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
391 // Attach.
Aart Bik8c4a8542016-10-06 11:36:57 -0700392 iset_ = &iset;
Aart Bikb29f6842017-07-28 15:58:41 -0700393 reductions_ = &reds;
Aart Bikf8f5a162017-02-06 15:35:29 -0800394 vector_refs_ = &refs;
395 vector_map_ = &map;
396 // Traverse.
Aart Bik8c4a8542016-10-06 11:36:57 -0700397 TraverseLoopsInnerToOuter(top_loop_);
Aart Bikf8f5a162017-02-06 15:35:29 -0800398 // Detach.
399 iset_ = nullptr;
Aart Bikb29f6842017-07-28 15:58:41 -0700400 reductions_ = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800401 vector_refs_ = nullptr;
402 vector_map_ = nullptr;
Aart Bik8c4a8542016-10-06 11:36:57 -0700403 }
Aart Bik281c6812016-08-26 11:31:48 -0700404}
405
406void HLoopOptimization::AddLoop(HLoopInformation* loop_info) {
407 DCHECK(loop_info != nullptr);
Aart Bikf8f5a162017-02-06 15:35:29 -0800408 LoopNode* node = new (loop_allocator_) LoopNode(loop_info);
Aart Bik281c6812016-08-26 11:31:48 -0700409 if (last_loop_ == nullptr) {
410 // First loop.
411 DCHECK(top_loop_ == nullptr);
412 last_loop_ = top_loop_ = node;
413 } else if (loop_info->IsIn(*last_loop_->loop_info)) {
414 // Inner loop.
415 node->outer = last_loop_;
416 DCHECK(last_loop_->inner == nullptr);
417 last_loop_ = last_loop_->inner = node;
418 } else {
419 // Subsequent loop.
420 while (last_loop_->outer != nullptr && !loop_info->IsIn(*last_loop_->outer->loop_info)) {
421 last_loop_ = last_loop_->outer;
422 }
423 node->outer = last_loop_->outer;
424 node->previous = last_loop_;
425 DCHECK(last_loop_->next == nullptr);
426 last_loop_ = last_loop_->next = node;
427 }
428}
429
430void HLoopOptimization::RemoveLoop(LoopNode* node) {
431 DCHECK(node != nullptr);
Aart Bik8c4a8542016-10-06 11:36:57 -0700432 DCHECK(node->inner == nullptr);
433 if (node->previous != nullptr) {
434 // Within sequence.
435 node->previous->next = node->next;
436 if (node->next != nullptr) {
437 node->next->previous = node->previous;
438 }
439 } else {
440 // First of sequence.
441 if (node->outer != nullptr) {
442 node->outer->inner = node->next;
443 } else {
444 top_loop_ = node->next;
445 }
446 if (node->next != nullptr) {
447 node->next->outer = node->outer;
448 node->next->previous = nullptr;
449 }
450 }
Aart Bik281c6812016-08-26 11:31:48 -0700451}
452
Aart Bikb29f6842017-07-28 15:58:41 -0700453bool HLoopOptimization::TraverseLoopsInnerToOuter(LoopNode* node) {
454 bool changed = false;
Aart Bik281c6812016-08-26 11:31:48 -0700455 for ( ; node != nullptr; node = node->next) {
Aart Bikb29f6842017-07-28 15:58:41 -0700456 // Visit inner loops first. Recompute induction information for this
457 // loop if the induction of any inner loop has changed.
458 if (TraverseLoopsInnerToOuter(node->inner)) {
Aart Bik482095d2016-10-10 15:39:10 -0700459 induction_range_.ReVisit(node->loop_info);
460 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800461 // Repeat simplifications in the loop-body until no more changes occur.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800462 // Note that since each simplification consists of eliminating code (without
463 // introducing new code), this process is always finite.
Aart Bikdf7822e2016-12-06 10:05:30 -0800464 do {
465 simplified_ = false;
Aart Bikdf7822e2016-12-06 10:05:30 -0800466 SimplifyInduction(node);
Aart Bik6b69e0a2017-01-11 10:20:43 -0800467 SimplifyBlocks(node);
Aart Bikb29f6842017-07-28 15:58:41 -0700468 changed = simplified_ || changed;
Aart Bikdf7822e2016-12-06 10:05:30 -0800469 } while (simplified_);
Aart Bikf8f5a162017-02-06 15:35:29 -0800470 // Optimize inner loop.
Aart Bik9abf8942016-10-14 09:49:42 -0700471 if (node->inner == nullptr) {
Aart Bikb29f6842017-07-28 15:58:41 -0700472 changed = OptimizeInnerLoop(node) || changed;
Aart Bik9abf8942016-10-14 09:49:42 -0700473 }
Aart Bik281c6812016-08-26 11:31:48 -0700474 }
Aart Bikb29f6842017-07-28 15:58:41 -0700475 return changed;
Aart Bik281c6812016-08-26 11:31:48 -0700476}
477
Aart Bikf8f5a162017-02-06 15:35:29 -0800478//
479// Optimization.
480//
481
Aart Bik281c6812016-08-26 11:31:48 -0700482void HLoopOptimization::SimplifyInduction(LoopNode* node) {
483 HBasicBlock* header = node->loop_info->GetHeader();
484 HBasicBlock* preheader = node->loop_info->GetPreHeader();
Aart Bik8c4a8542016-10-06 11:36:57 -0700485 // Scan the phis in the header to find opportunities to simplify an induction
486 // cycle that is only used outside the loop. Replace these uses, if any, with
487 // the last value and remove the induction cycle.
488 // Examples: for (int i = 0; x != null; i++) { .... no i .... }
489 // for (int i = 0; i < 10; i++, k++) { .... no k .... } return k;
Aart Bik281c6812016-08-26 11:31:48 -0700490 for (HInstructionIterator it(header->GetPhis()); !it.Done(); it.Advance()) {
491 HPhi* phi = it.Current()->AsPhi();
Aart Bikf8f5a162017-02-06 15:35:29 -0800492 if (TrySetPhiInduction(phi, /*restrict_uses*/ true) &&
Aart Bikb29f6842017-07-28 15:58:41 -0700493 CanRemoveCycle() &&
Aart Bikf8f5a162017-02-06 15:35:29 -0800494 TryAssignLastValue(node->loop_info, phi, preheader, /*collect_loop_uses*/ false)) {
Aart Bikb29f6842017-07-28 15:58:41 -0700495 simplified_ = true;
496 for (HInstruction* i : *iset_) {
497 RemoveFromCycle(i);
Aart Bik281c6812016-08-26 11:31:48 -0700498 }
Aart Bikb29f6842017-07-28 15:58:41 -0700499 DCHECK(CheckInductionSetFullyRemoved(iset_));
Aart Bik482095d2016-10-10 15:39:10 -0700500 }
501 }
502}
503
504void HLoopOptimization::SimplifyBlocks(LoopNode* node) {
Aart Bikdf7822e2016-12-06 10:05:30 -0800505 // Iterate over all basic blocks in the loop-body.
506 for (HBlocksInLoopIterator it(*node->loop_info); !it.Done(); it.Advance()) {
507 HBasicBlock* block = it.Current();
508 // Remove dead instructions from the loop-body.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800509 RemoveDeadInstructions(block->GetPhis());
510 RemoveDeadInstructions(block->GetInstructions());
Aart Bikdf7822e2016-12-06 10:05:30 -0800511 // Remove trivial control flow blocks from the loop-body.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800512 if (block->GetPredecessors().size() == 1 &&
513 block->GetSuccessors().size() == 1 &&
514 block->GetSingleSuccessor()->GetPredecessors().size() == 1) {
Aart Bikdf7822e2016-12-06 10:05:30 -0800515 simplified_ = true;
Aart Bik6b69e0a2017-01-11 10:20:43 -0800516 block->MergeWith(block->GetSingleSuccessor());
Aart Bikdf7822e2016-12-06 10:05:30 -0800517 } else if (block->GetSuccessors().size() == 2) {
518 // Trivial if block can be bypassed to either branch.
519 HBasicBlock* succ0 = block->GetSuccessors()[0];
520 HBasicBlock* succ1 = block->GetSuccessors()[1];
521 HBasicBlock* meet0 = nullptr;
522 HBasicBlock* meet1 = nullptr;
523 if (succ0 != succ1 &&
524 IsGotoBlock(succ0, &meet0) &&
525 IsGotoBlock(succ1, &meet1) &&
526 meet0 == meet1 && // meets again
527 meet0 != block && // no self-loop
528 meet0->GetPhis().IsEmpty()) { // not used for merging
529 simplified_ = true;
530 succ0->DisconnectAndDelete();
531 if (block->Dominates(meet0)) {
532 block->RemoveDominatedBlock(meet0);
533 succ1->AddDominatedBlock(meet0);
534 meet0->SetDominator(succ1);
Aart Bike3dedc52016-11-02 17:50:27 -0700535 }
Aart Bik482095d2016-10-10 15:39:10 -0700536 }
Aart Bik281c6812016-08-26 11:31:48 -0700537 }
Aart Bikdf7822e2016-12-06 10:05:30 -0800538 }
Aart Bik281c6812016-08-26 11:31:48 -0700539}
540
Aart Bikb29f6842017-07-28 15:58:41 -0700541bool HLoopOptimization::OptimizeInnerLoop(LoopNode* node) {
Aart Bik281c6812016-08-26 11:31:48 -0700542 HBasicBlock* header = node->loop_info->GetHeader();
543 HBasicBlock* preheader = node->loop_info->GetPreHeader();
Aart Bik9abf8942016-10-14 09:49:42 -0700544 // Ensure loop header logic is finite.
Aart Bikf8f5a162017-02-06 15:35:29 -0800545 int64_t trip_count = 0;
546 if (!induction_range_.IsFinite(node->loop_info, &trip_count)) {
Aart Bikb29f6842017-07-28 15:58:41 -0700547 return false;
Aart Bik9abf8942016-10-14 09:49:42 -0700548 }
Aart Bik281c6812016-08-26 11:31:48 -0700549 // Ensure there is only a single loop-body (besides the header).
550 HBasicBlock* body = nullptr;
551 for (HBlocksInLoopIterator it(*node->loop_info); !it.Done(); it.Advance()) {
552 if (it.Current() != header) {
553 if (body != nullptr) {
Aart Bikb29f6842017-07-28 15:58:41 -0700554 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700555 }
556 body = it.Current();
557 }
558 }
Andreas Gampef45d61c2017-06-07 10:29:33 -0700559 CHECK(body != nullptr);
Aart Bik281c6812016-08-26 11:31:48 -0700560 // Ensure there is only a single exit point.
561 if (header->GetSuccessors().size() != 2) {
Aart Bikb29f6842017-07-28 15:58:41 -0700562 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700563 }
564 HBasicBlock* exit = (header->GetSuccessors()[0] == body)
565 ? header->GetSuccessors()[1]
566 : header->GetSuccessors()[0];
Aart Bik8c4a8542016-10-06 11:36:57 -0700567 // Ensure exit can only be reached by exiting loop.
Aart Bik281c6812016-08-26 11:31:48 -0700568 if (exit->GetPredecessors().size() != 1) {
Aart Bikb29f6842017-07-28 15:58:41 -0700569 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700570 }
Aart Bik6b69e0a2017-01-11 10:20:43 -0800571 // Detect either an empty loop (no side effects other than plain iteration) or
572 // a trivial loop (just iterating once). Replace subsequent index uses, if any,
573 // with the last value and remove the loop, possibly after unrolling its body.
Aart Bikb29f6842017-07-28 15:58:41 -0700574 HPhi* main_phi = nullptr;
575 if (TrySetSimpleLoopHeader(header, &main_phi)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -0800576 bool is_empty = IsEmptyBody(body);
Aart Bikb29f6842017-07-28 15:58:41 -0700577 if (reductions_->empty() && // TODO: possible with some effort
578 (is_empty || trip_count == 1) &&
579 TryAssignLastValue(node->loop_info, main_phi, preheader, /*collect_loop_uses*/ true)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -0800580 if (!is_empty) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800581 // Unroll the loop-body, which sees initial value of the index.
Aart Bikb29f6842017-07-28 15:58:41 -0700582 main_phi->ReplaceWith(main_phi->InputAt(0));
Aart Bik6b69e0a2017-01-11 10:20:43 -0800583 preheader->MergeInstructionsWith(body);
584 }
585 body->DisconnectAndDelete();
586 exit->RemovePredecessor(header);
587 header->RemoveSuccessor(exit);
588 header->RemoveDominatedBlock(exit);
589 header->DisconnectAndDelete();
590 preheader->AddSuccessor(exit);
Aart Bikf8f5a162017-02-06 15:35:29 -0800591 preheader->AddInstruction(new (global_allocator_) HGoto());
Aart Bik6b69e0a2017-01-11 10:20:43 -0800592 preheader->AddDominatedBlock(exit);
593 exit->SetDominator(preheader);
594 RemoveLoop(node); // update hierarchy
Aart Bikb29f6842017-07-28 15:58:41 -0700595 return true;
Aart Bikf8f5a162017-02-06 15:35:29 -0800596 }
597 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800598 // Vectorize loop, if possible and valid.
Aart Bikb29f6842017-07-28 15:58:41 -0700599 if (kEnableVectorization &&
600 TrySetSimpleLoopHeader(header, &main_phi) &&
601 reductions_->empty() && // TODO: possible with some effort
602 ShouldVectorize(node, body, trip_count) &&
603 TryAssignLastValue(node->loop_info, main_phi, preheader, /*collect_loop_uses*/ true)) {
604 Vectorize(node, body, exit, trip_count);
605 graph_->SetHasSIMD(true); // flag SIMD usage
606 return true;
Aart Bikf8f5a162017-02-06 15:35:29 -0800607 }
Aart Bikb29f6842017-07-28 15:58:41 -0700608 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -0800609}
610
611//
612// Loop vectorization. The implementation is based on the book by Aart J.C. Bik:
613// "The Software Vectorization Handbook. Applying Multimedia Extensions for Maximum Performance."
614// Intel Press, June, 2004 (http://www.aartbik.com/).
615//
616
Aart Bik14a68b42017-06-08 14:06:58 -0700617bool HLoopOptimization::ShouldVectorize(LoopNode* node, HBasicBlock* block, int64_t trip_count) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800618 // Reset vector bookkeeping.
619 vector_length_ = 0;
620 vector_refs_->clear();
Aart Bik14a68b42017-06-08 14:06:58 -0700621 vector_peeling_candidate_ = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800622 vector_runtime_test_a_ =
623 vector_runtime_test_b_= nullptr;
624
625 // Phis in the loop-body prevent vectorization.
626 if (!block->GetPhis().IsEmpty()) {
627 return false;
628 }
629
630 // Scan the loop-body, starting a right-hand-side tree traversal at each left-hand-side
631 // occurrence, which allows passing down attributes down the use tree.
632 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
633 if (!VectorizeDef(node, it.Current(), /*generate_code*/ false)) {
634 return false; // failure to vectorize a left-hand-side
635 }
636 }
637
Aart Bik14a68b42017-06-08 14:06:58 -0700638 // Does vectorization seem profitable?
639 if (!IsVectorizationProfitable(trip_count)) {
640 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -0800641 }
642
643 // Data dependence analysis. Find each pair of references with same type, where
644 // at least one is a write. Each such pair denotes a possible data dependence.
645 // This analysis exploits the property that differently typed arrays cannot be
646 // aliased, as well as the property that references either point to the same
647 // array or to two completely disjoint arrays, i.e., no partial aliasing.
648 // Other than a few simply heuristics, no detailed subscript analysis is done.
Aart Bikb29f6842017-07-28 15:58:41 -0700649 // The scan over references also finds a suitable dynamic loop peeling candidate.
650 const ArrayReference* candidate = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800651 for (auto i = vector_refs_->begin(); i != vector_refs_->end(); ++i) {
652 for (auto j = i; ++j != vector_refs_->end(); ) {
653 if (i->type == j->type && (i->lhs || j->lhs)) {
654 // Found same-typed a[i+x] vs. b[i+y], where at least one is a write.
655 HInstruction* a = i->base;
656 HInstruction* b = j->base;
657 HInstruction* x = i->offset;
658 HInstruction* y = j->offset;
659 if (a == b) {
660 // Found a[i+x] vs. a[i+y]. Accept if x == y (loop-independent data dependence).
661 // Conservatively assume a loop-carried data dependence otherwise, and reject.
662 if (x != y) {
663 return false;
664 }
665 } else {
666 // Found a[i+x] vs. b[i+y]. Accept if x == y (at worst loop-independent data dependence).
667 // Conservatively assume a potential loop-carried data dependence otherwise, avoided by
668 // generating an explicit a != b disambiguation runtime test on the two references.
669 if (x != y) {
Aart Bik37dc4df2017-06-28 14:08:00 -0700670 // To avoid excessive overhead, we only accept one a != b test.
671 if (vector_runtime_test_a_ == nullptr) {
672 // First test found.
673 vector_runtime_test_a_ = a;
674 vector_runtime_test_b_ = b;
675 } else if ((vector_runtime_test_a_ != a || vector_runtime_test_b_ != b) &&
676 (vector_runtime_test_a_ != b || vector_runtime_test_b_ != a)) {
677 return false; // second test would be needed
Aart Bikf8f5a162017-02-06 15:35:29 -0800678 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800679 }
680 }
681 }
682 }
683 }
684
Aart Bik14a68b42017-06-08 14:06:58 -0700685 // Consider dynamic loop peeling for alignment.
Aart Bikb29f6842017-07-28 15:58:41 -0700686 SetPeelingCandidate(candidate, trip_count);
Aart Bik14a68b42017-06-08 14:06:58 -0700687
Aart Bikf8f5a162017-02-06 15:35:29 -0800688 // Success!
689 return true;
690}
691
692void HLoopOptimization::Vectorize(LoopNode* node,
693 HBasicBlock* block,
694 HBasicBlock* exit,
695 int64_t trip_count) {
696 Primitive::Type induc_type = Primitive::kPrimInt;
697 HBasicBlock* header = node->loop_info->GetHeader();
698 HBasicBlock* preheader = node->loop_info->GetPreHeader();
699
Aart Bik14a68b42017-06-08 14:06:58 -0700700 // Pick a loop unrolling factor for the vector loop.
701 uint32_t unroll = GetUnrollingFactor(block, trip_count);
702 uint32_t chunk = vector_length_ * unroll;
703
704 // A cleanup loop is needed, at least, for any unknown trip count or
705 // for a known trip count with remainder iterations after vectorization.
706 bool needs_cleanup = trip_count == 0 || (trip_count % chunk) != 0;
Aart Bikf8f5a162017-02-06 15:35:29 -0800707
708 // Adjust vector bookkeeping.
Aart Bikb29f6842017-07-28 15:58:41 -0700709 HPhi* main_phi = nullptr;
710 bool is_simple_loop_header = TrySetSimpleLoopHeader(header, &main_phi); // refills sets
Aart Bikf8f5a162017-02-06 15:35:29 -0800711 DCHECK(is_simple_loop_header);
Aart Bik14a68b42017-06-08 14:06:58 -0700712 vector_header_ = header;
713 vector_body_ = block;
Aart Bikf8f5a162017-02-06 15:35:29 -0800714
Aart Bikb29f6842017-07-28 15:58:41 -0700715 // Generate dynamic loop peeling trip count, if needed, under the assumption
716 // that the Android runtime guarantees at least "component size" alignment:
717 // ptc = (ALIGN - (&a[initial] % ALIGN)) / type-size
Aart Bik14a68b42017-06-08 14:06:58 -0700718 HInstruction* ptc = nullptr;
719 if (vector_peeling_candidate_ != nullptr) {
720 DCHECK_LT(vector_length_, trip_count) << "dynamic peeling currently requires known trip count";
721 //
722 // TODO: Implement this. Compute address of first access memory location and
723 // compute peeling factor to obtain kAlignedBase alignment.
724 //
725 needs_cleanup = true;
726 }
727
728 // Generate loop control:
Aart Bikf8f5a162017-02-06 15:35:29 -0800729 // stc = <trip-count>;
Aart Bik14a68b42017-06-08 14:06:58 -0700730 // vtc = stc - (stc - ptc) % chunk;
731 // i = 0;
Aart Bikf8f5a162017-02-06 15:35:29 -0800732 HInstruction* stc = induction_range_.GenerateTripCount(node->loop_info, graph_, preheader);
733 HInstruction* vtc = stc;
734 if (needs_cleanup) {
Aart Bik14a68b42017-06-08 14:06:58 -0700735 DCHECK(IsPowerOfTwo(chunk));
736 HInstruction* diff = stc;
737 if (ptc != nullptr) {
738 diff = Insert(preheader, new (global_allocator_) HSub(induc_type, stc, ptc));
739 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800740 HInstruction* rem = Insert(
741 preheader, new (global_allocator_) HAnd(induc_type,
Aart Bik14a68b42017-06-08 14:06:58 -0700742 diff,
743 graph_->GetIntConstant(chunk - 1)));
Aart Bikf8f5a162017-02-06 15:35:29 -0800744 vtc = Insert(preheader, new (global_allocator_) HSub(induc_type, stc, rem));
745 }
Aart Bik14a68b42017-06-08 14:06:58 -0700746 vector_index_ = graph_->GetIntConstant(0);
Aart Bikf8f5a162017-02-06 15:35:29 -0800747
748 // Generate runtime disambiguation test:
749 // vtc = a != b ? vtc : 0;
750 if (vector_runtime_test_a_ != nullptr) {
751 HInstruction* rt = Insert(
752 preheader,
753 new (global_allocator_) HNotEqual(vector_runtime_test_a_, vector_runtime_test_b_));
754 vtc = Insert(preheader,
755 new (global_allocator_) HSelect(rt, vtc, graph_->GetIntConstant(0), kNoDexPc));
756 needs_cleanup = true;
757 }
758
Aart Bik14a68b42017-06-08 14:06:58 -0700759 // Generate dynamic peeling loop for alignment, if needed:
760 // for ( ; i < ptc; i += 1)
761 // <loop-body>
762 if (ptc != nullptr) {
763 vector_mode_ = kSequential;
764 GenerateNewLoop(node,
765 block,
766 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
767 vector_index_,
768 ptc,
769 graph_->GetIntConstant(1),
770 /*unroll*/ 1);
771 }
772
773 // Generate vector loop, possibly further unrolled:
774 // for ( ; i < vtc; i += chunk)
Aart Bikf8f5a162017-02-06 15:35:29 -0800775 // <vectorized-loop-body>
776 vector_mode_ = kVector;
777 GenerateNewLoop(node,
778 block,
Aart Bik14a68b42017-06-08 14:06:58 -0700779 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
780 vector_index_,
Aart Bikf8f5a162017-02-06 15:35:29 -0800781 vtc,
Aart Bik14a68b42017-06-08 14:06:58 -0700782 graph_->GetIntConstant(vector_length_), // increment per unroll
783 unroll);
Aart Bikf8f5a162017-02-06 15:35:29 -0800784 HLoopInformation* vloop = vector_header_->GetLoopInformation();
785
786 // Generate cleanup loop, if needed:
787 // for ( ; i < stc; i += 1)
788 // <loop-body>
789 if (needs_cleanup) {
790 vector_mode_ = kSequential;
791 GenerateNewLoop(node,
792 block,
793 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
Aart Bik14a68b42017-06-08 14:06:58 -0700794 vector_index_,
Aart Bikf8f5a162017-02-06 15:35:29 -0800795 stc,
Aart Bik14a68b42017-06-08 14:06:58 -0700796 graph_->GetIntConstant(1),
797 /*unroll*/ 1);
Aart Bikf8f5a162017-02-06 15:35:29 -0800798 }
799
800 // Remove the original loop by disconnecting the body block
801 // and removing all instructions from the header.
802 block->DisconnectAndDelete();
803 while (!header->GetFirstInstruction()->IsGoto()) {
804 header->RemoveInstruction(header->GetFirstInstruction());
805 }
Aart Bikb29f6842017-07-28 15:58:41 -0700806
Aart Bik14a68b42017-06-08 14:06:58 -0700807 // Update loop hierarchy: the old header now resides in the same outer loop
808 // as the old preheader. Note that we don't bother putting sequential
809 // loops back in the hierarchy at this point.
Aart Bikf8f5a162017-02-06 15:35:29 -0800810 header->SetLoopInformation(preheader->GetLoopInformation()); // outward
811 node->loop_info = vloop;
812}
813
814void HLoopOptimization::GenerateNewLoop(LoopNode* node,
815 HBasicBlock* block,
816 HBasicBlock* new_preheader,
817 HInstruction* lo,
818 HInstruction* hi,
Aart Bik14a68b42017-06-08 14:06:58 -0700819 HInstruction* step,
820 uint32_t unroll) {
821 DCHECK(unroll == 1 || vector_mode_ == kVector);
Aart Bikf8f5a162017-02-06 15:35:29 -0800822 Primitive::Type induc_type = Primitive::kPrimInt;
823 // Prepare new loop.
Aart Bikf8f5a162017-02-06 15:35:29 -0800824 vector_preheader_ = new_preheader,
825 vector_header_ = vector_preheader_->GetSingleSuccessor();
826 vector_body_ = vector_header_->GetSuccessors()[1];
Aart Bik14a68b42017-06-08 14:06:58 -0700827 HPhi* phi = new (global_allocator_) HPhi(global_allocator_,
828 kNoRegNumber,
829 0,
830 HPhi::ToPhiType(induc_type));
Aart Bikb07d1bc2017-04-05 10:03:15 -0700831 // Generate header and prepare body.
Aart Bikf8f5a162017-02-06 15:35:29 -0800832 // for (i = lo; i < hi; i += step)
833 // <loop-body>
Aart Bik14a68b42017-06-08 14:06:58 -0700834 HInstruction* cond = new (global_allocator_) HAboveOrEqual(phi, hi);
835 vector_header_->AddPhi(phi);
Aart Bikf8f5a162017-02-06 15:35:29 -0800836 vector_header_->AddInstruction(cond);
837 vector_header_->AddInstruction(new (global_allocator_) HIf(cond));
Aart Bik14a68b42017-06-08 14:06:58 -0700838 vector_index_ = phi;
839 for (uint32_t u = 0; u < unroll; u++) {
840 // Clear map, leaving loop invariants setup during unrolling.
841 if (u == 0) {
842 vector_map_->clear();
843 } else {
844 for (auto i = vector_map_->begin(); i != vector_map_->end(); ) {
845 if (i->second->IsVecReplicateScalar()) {
846 DCHECK(node->loop_info->IsDefinedOutOfTheLoop(i->first));
847 ++i;
848 } else {
849 i = vector_map_->erase(i);
850 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800851 }
852 }
Aart Bik14a68b42017-06-08 14:06:58 -0700853 // Generate instruction map.
854 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
855 bool vectorized_def = VectorizeDef(node, it.Current(), /*generate_code*/ true);
856 DCHECK(vectorized_def);
857 }
858 // Generate body from the instruction map, but in original program order.
859 HEnvironment* env = vector_header_->GetFirstInstruction()->GetEnvironment();
860 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
861 auto i = vector_map_->find(it.Current());
862 if (i != vector_map_->end() && !i->second->IsInBlock()) {
863 Insert(vector_body_, i->second);
864 // Deal with instructions that need an environment, such as the scalar intrinsics.
865 if (i->second->NeedsEnvironment()) {
866 i->second->CopyEnvironmentFromWithLoopPhiAdjustment(env, vector_header_);
867 }
868 }
869 }
870 vector_index_ = new (global_allocator_) HAdd(induc_type, vector_index_, step);
871 Insert(vector_body_, vector_index_);
Aart Bikf8f5a162017-02-06 15:35:29 -0800872 }
Aart Bikb29f6842017-07-28 15:58:41 -0700873 // Finalize phi inputs for the loop index.
Aart Bik14a68b42017-06-08 14:06:58 -0700874 phi->AddInput(lo);
875 phi->AddInput(vector_index_);
876 vector_index_ = phi;
Aart Bikf8f5a162017-02-06 15:35:29 -0800877}
878
Aart Bikf8f5a162017-02-06 15:35:29 -0800879bool HLoopOptimization::VectorizeDef(LoopNode* node,
880 HInstruction* instruction,
881 bool generate_code) {
882 // Accept a left-hand-side array base[index] for
883 // (1) supported vector type,
884 // (2) loop-invariant base,
885 // (3) unit stride index,
886 // (4) vectorizable right-hand-side value.
887 uint64_t restrictions = kNone;
888 if (instruction->IsArraySet()) {
889 Primitive::Type type = instruction->AsArraySet()->GetComponentType();
890 HInstruction* base = instruction->InputAt(0);
891 HInstruction* index = instruction->InputAt(1);
892 HInstruction* value = instruction->InputAt(2);
893 HInstruction* offset = nullptr;
894 if (TrySetVectorType(type, &restrictions) &&
895 node->loop_info->IsDefinedOutOfTheLoop(base) &&
Aart Bik37dc4df2017-06-28 14:08:00 -0700896 induction_range_.IsUnitStride(instruction, index, graph_, &offset) &&
Aart Bikf8f5a162017-02-06 15:35:29 -0800897 VectorizeUse(node, value, generate_code, type, restrictions)) {
898 if (generate_code) {
899 GenerateVecSub(index, offset);
Aart Bik14a68b42017-06-08 14:06:58 -0700900 GenerateVecMem(instruction, vector_map_->Get(index), vector_map_->Get(value), offset, type);
Aart Bikf8f5a162017-02-06 15:35:29 -0800901 } else {
902 vector_refs_->insert(ArrayReference(base, offset, type, /*lhs*/ true));
903 }
Aart Bik6b69e0a2017-01-11 10:20:43 -0800904 return true;
905 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800906 return false;
907 }
908 // Branch back okay.
909 if (instruction->IsGoto()) {
910 return true;
911 }
912 // Otherwise accept only expressions with no effects outside the immediate loop-body.
913 // Note that actual uses are inspected during right-hand-side tree traversal.
914 return !IsUsedOutsideLoop(node->loop_info, instruction) && !instruction->DoesAnyWrite();
915}
916
Aart Bik304c8a52017-05-23 11:01:13 -0700917// TODO: saturation arithmetic.
Aart Bikf8f5a162017-02-06 15:35:29 -0800918bool HLoopOptimization::VectorizeUse(LoopNode* node,
919 HInstruction* instruction,
920 bool generate_code,
921 Primitive::Type type,
922 uint64_t restrictions) {
923 // Accept anything for which code has already been generated.
924 if (generate_code) {
925 if (vector_map_->find(instruction) != vector_map_->end()) {
926 return true;
927 }
928 }
929 // Continue the right-hand-side tree traversal, passing in proper
930 // types and vector restrictions along the way. During code generation,
931 // all new nodes are drawn from the global allocator.
932 if (node->loop_info->IsDefinedOutOfTheLoop(instruction)) {
933 // Accept invariant use, using scalar expansion.
934 if (generate_code) {
935 GenerateVecInv(instruction, type);
936 }
937 return true;
938 } else if (instruction->IsArrayGet()) {
Goran Jakovljevic19680d32017-05-11 10:38:36 +0200939 // Deal with vector restrictions.
940 if (instruction->AsArrayGet()->IsStringCharAt() &&
941 HasVectorRestrictions(restrictions, kNoStringCharAt)) {
942 return false;
943 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800944 // Accept a right-hand-side array base[index] for
945 // (1) exact matching vector type,
946 // (2) loop-invariant base,
947 // (3) unit stride index,
948 // (4) vectorizable right-hand-side value.
949 HInstruction* base = instruction->InputAt(0);
950 HInstruction* index = instruction->InputAt(1);
951 HInstruction* offset = nullptr;
952 if (type == instruction->GetType() &&
953 node->loop_info->IsDefinedOutOfTheLoop(base) &&
Aart Bik37dc4df2017-06-28 14:08:00 -0700954 induction_range_.IsUnitStride(instruction, index, graph_, &offset)) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800955 if (generate_code) {
956 GenerateVecSub(index, offset);
Aart Bik14a68b42017-06-08 14:06:58 -0700957 GenerateVecMem(instruction, vector_map_->Get(index), nullptr, offset, type);
Aart Bikf8f5a162017-02-06 15:35:29 -0800958 } else {
959 vector_refs_->insert(ArrayReference(base, offset, type, /*lhs*/ false));
960 }
961 return true;
962 }
963 } else if (instruction->IsTypeConversion()) {
964 // Accept particular type conversions.
965 HTypeConversion* conversion = instruction->AsTypeConversion();
966 HInstruction* opa = conversion->InputAt(0);
967 Primitive::Type from = conversion->GetInputType();
968 Primitive::Type to = conversion->GetResultType();
969 if ((to == Primitive::kPrimByte ||
970 to == Primitive::kPrimChar ||
971 to == Primitive::kPrimShort) && from == Primitive::kPrimInt) {
972 // Accept a "narrowing" type conversion from a "wider" computation for
973 // (1) conversion into final required type,
974 // (2) vectorizable operand,
975 // (3) "wider" operations cannot bring in higher order bits.
976 if (to == type && VectorizeUse(node, opa, generate_code, type, restrictions | kNoHiBits)) {
977 if (generate_code) {
978 if (vector_mode_ == kVector) {
979 vector_map_->Put(instruction, vector_map_->Get(opa)); // operand pass-through
980 } else {
981 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
982 }
983 }
984 return true;
985 }
986 } else if (to == Primitive::kPrimFloat && from == Primitive::kPrimInt) {
987 DCHECK_EQ(to, type);
988 // Accept int to float conversion for
989 // (1) supported int,
990 // (2) vectorizable operand.
991 if (TrySetVectorType(from, &restrictions) &&
992 VectorizeUse(node, opa, generate_code, from, restrictions)) {
993 if (generate_code) {
994 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
995 }
996 return true;
997 }
998 }
999 return false;
1000 } else if (instruction->IsNeg() || instruction->IsNot() || instruction->IsBooleanNot()) {
1001 // Accept unary operator for vectorizable operand.
1002 HInstruction* opa = instruction->InputAt(0);
1003 if (VectorizeUse(node, opa, generate_code, type, restrictions)) {
1004 if (generate_code) {
1005 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1006 }
1007 return true;
1008 }
1009 } else if (instruction->IsAdd() || instruction->IsSub() ||
1010 instruction->IsMul() || instruction->IsDiv() ||
1011 instruction->IsAnd() || instruction->IsOr() || instruction->IsXor()) {
1012 // Deal with vector restrictions.
1013 if ((instruction->IsMul() && HasVectorRestrictions(restrictions, kNoMul)) ||
1014 (instruction->IsDiv() && HasVectorRestrictions(restrictions, kNoDiv))) {
1015 return false;
1016 }
1017 // Accept binary operator for vectorizable operands.
1018 HInstruction* opa = instruction->InputAt(0);
1019 HInstruction* opb = instruction->InputAt(1);
1020 if (VectorizeUse(node, opa, generate_code, type, restrictions) &&
1021 VectorizeUse(node, opb, generate_code, type, restrictions)) {
1022 if (generate_code) {
1023 GenerateVecOp(instruction, vector_map_->Get(opa), vector_map_->Get(opb), type);
1024 }
1025 return true;
1026 }
1027 } else if (instruction->IsShl() || instruction->IsShr() || instruction->IsUShr()) {
Aart Bikf3e61ee2017-04-12 17:09:20 -07001028 // Recognize vectorization idioms.
1029 if (VectorizeHalvingAddIdiom(node, instruction, generate_code, type, restrictions)) {
1030 return true;
1031 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001032 // Deal with vector restrictions.
Aart Bik304c8a52017-05-23 11:01:13 -07001033 HInstruction* opa = instruction->InputAt(0);
1034 HInstruction* opb = instruction->InputAt(1);
1035 HInstruction* r = opa;
1036 bool is_unsigned = false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001037 if ((HasVectorRestrictions(restrictions, kNoShift)) ||
1038 (instruction->IsShr() && HasVectorRestrictions(restrictions, kNoShr))) {
1039 return false; // unsupported instruction
Aart Bik304c8a52017-05-23 11:01:13 -07001040 } else if (HasVectorRestrictions(restrictions, kNoHiBits)) {
1041 // Shifts right need extra care to account for higher order bits.
1042 // TODO: less likely shr/unsigned and ushr/signed can by flipping signess.
1043 if (instruction->IsShr() &&
1044 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || is_unsigned)) {
1045 return false; // reject, unless all operands are sign-extension narrower
1046 } else if (instruction->IsUShr() &&
1047 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || !is_unsigned)) {
1048 return false; // reject, unless all operands are zero-extension narrower
1049 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001050 }
1051 // Accept shift operator for vectorizable/invariant operands.
1052 // TODO: accept symbolic, albeit loop invariant shift factors.
Aart Bik304c8a52017-05-23 11:01:13 -07001053 DCHECK(r != nullptr);
1054 if (generate_code && vector_mode_ != kVector) { // de-idiom
1055 r = opa;
1056 }
Aart Bik50e20d52017-05-05 14:07:29 -07001057 int64_t distance = 0;
Aart Bik304c8a52017-05-23 11:01:13 -07001058 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
Aart Bik50e20d52017-05-05 14:07:29 -07001059 IsInt64AndGet(opb, /*out*/ &distance)) {
Aart Bik65ffd8e2017-05-01 16:50:45 -07001060 // Restrict shift distance to packed data type width.
1061 int64_t max_distance = Primitive::ComponentSize(type) * 8;
1062 if (0 <= distance && distance < max_distance) {
1063 if (generate_code) {
Aart Bik304c8a52017-05-23 11:01:13 -07001064 GenerateVecOp(instruction, vector_map_->Get(r), opb, type);
Aart Bik65ffd8e2017-05-01 16:50:45 -07001065 }
1066 return true;
Aart Bikf8f5a162017-02-06 15:35:29 -08001067 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001068 }
1069 } else if (instruction->IsInvokeStaticOrDirect()) {
Aart Bik6daebeb2017-04-03 14:35:41 -07001070 // Accept particular intrinsics.
1071 HInvokeStaticOrDirect* invoke = instruction->AsInvokeStaticOrDirect();
1072 switch (invoke->GetIntrinsic()) {
1073 case Intrinsics::kMathAbsInt:
1074 case Intrinsics::kMathAbsLong:
1075 case Intrinsics::kMathAbsFloat:
1076 case Intrinsics::kMathAbsDouble: {
1077 // Deal with vector restrictions.
Aart Bik304c8a52017-05-23 11:01:13 -07001078 HInstruction* opa = instruction->InputAt(0);
1079 HInstruction* r = opa;
1080 bool is_unsigned = false;
1081 if (HasVectorRestrictions(restrictions, kNoAbs)) {
Aart Bik6daebeb2017-04-03 14:35:41 -07001082 return false;
Aart Bik304c8a52017-05-23 11:01:13 -07001083 } else if (HasVectorRestrictions(restrictions, kNoHiBits) &&
1084 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || is_unsigned)) {
1085 return false; // reject, unless operand is sign-extension narrower
Aart Bik6daebeb2017-04-03 14:35:41 -07001086 }
1087 // Accept ABS(x) for vectorizable operand.
Aart Bik304c8a52017-05-23 11:01:13 -07001088 DCHECK(r != nullptr);
1089 if (generate_code && vector_mode_ != kVector) { // de-idiom
1090 r = opa;
1091 }
1092 if (VectorizeUse(node, r, generate_code, type, restrictions)) {
Aart Bik6daebeb2017-04-03 14:35:41 -07001093 if (generate_code) {
Aart Bik304c8a52017-05-23 11:01:13 -07001094 GenerateVecOp(instruction, vector_map_->Get(r), nullptr, type);
Aart Bik6daebeb2017-04-03 14:35:41 -07001095 }
1096 return true;
1097 }
1098 return false;
1099 }
Aart Bikc8e93c72017-05-10 10:49:22 -07001100 case Intrinsics::kMathMinIntInt:
1101 case Intrinsics::kMathMinLongLong:
1102 case Intrinsics::kMathMinFloatFloat:
1103 case Intrinsics::kMathMinDoubleDouble:
1104 case Intrinsics::kMathMaxIntInt:
1105 case Intrinsics::kMathMaxLongLong:
1106 case Intrinsics::kMathMaxFloatFloat:
1107 case Intrinsics::kMathMaxDoubleDouble: {
1108 // Deal with vector restrictions.
Nicolas Geoffray92316902017-05-23 08:06:07 +00001109 HInstruction* opa = instruction->InputAt(0);
1110 HInstruction* opb = instruction->InputAt(1);
Aart Bik304c8a52017-05-23 11:01:13 -07001111 HInstruction* r = opa;
1112 HInstruction* s = opb;
1113 bool is_unsigned = false;
1114 if (HasVectorRestrictions(restrictions, kNoMinMax)) {
1115 return false;
1116 } else if (HasVectorRestrictions(restrictions, kNoHiBits) &&
1117 !IsNarrowerOperands(opa, opb, type, &r, &s, &is_unsigned)) {
1118 return false; // reject, unless all operands are same-extension narrower
1119 }
1120 // Accept MIN/MAX(x, y) for vectorizable operands.
1121 DCHECK(r != nullptr && s != nullptr);
1122 if (generate_code && vector_mode_ != kVector) { // de-idiom
1123 r = opa;
1124 s = opb;
1125 }
1126 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
1127 VectorizeUse(node, s, generate_code, type, restrictions)) {
Aart Bikc8e93c72017-05-10 10:49:22 -07001128 if (generate_code) {
Aart Bik304c8a52017-05-23 11:01:13 -07001129 GenerateVecOp(
1130 instruction, vector_map_->Get(r), vector_map_->Get(s), type, is_unsigned);
Aart Bikc8e93c72017-05-10 10:49:22 -07001131 }
1132 return true;
1133 }
1134 return false;
1135 }
Aart Bik6daebeb2017-04-03 14:35:41 -07001136 default:
1137 return false;
1138 } // switch
Aart Bik281c6812016-08-26 11:31:48 -07001139 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08001140 return false;
Aart Bik281c6812016-08-26 11:31:48 -07001141}
1142
Aart Bikf8f5a162017-02-06 15:35:29 -08001143bool HLoopOptimization::TrySetVectorType(Primitive::Type type, uint64_t* restrictions) {
1144 const InstructionSetFeatures* features = compiler_driver_->GetInstructionSetFeatures();
1145 switch (compiler_driver_->GetInstructionSet()) {
1146 case kArm:
1147 case kThumb2:
Artem Serov8f7c4102017-06-21 11:21:37 +01001148 // Allow vectorization for all ARM devices, because Android assumes that
Aart Bikb29f6842017-07-28 15:58:41 -07001149 // ARM 32-bit always supports advanced SIMD (64-bit SIMD).
Artem Serov8f7c4102017-06-21 11:21:37 +01001150 switch (type) {
1151 case Primitive::kPrimBoolean:
1152 case Primitive::kPrimByte:
1153 *restrictions |= kNoDiv;
1154 return TrySetVectorLength(8);
1155 case Primitive::kPrimChar:
1156 case Primitive::kPrimShort:
1157 *restrictions |= kNoDiv | kNoStringCharAt;
1158 return TrySetVectorLength(4);
1159 case Primitive::kPrimInt:
1160 *restrictions |= kNoDiv;
1161 return TrySetVectorLength(2);
1162 default:
1163 break;
1164 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001165 return false;
1166 case kArm64:
1167 // Allow vectorization for all ARM devices, because Android assumes that
Aart Bikb29f6842017-07-28 15:58:41 -07001168 // ARMv8 AArch64 always supports advanced SIMD (128-bit SIMD).
Aart Bikf8f5a162017-02-06 15:35:29 -08001169 switch (type) {
1170 case Primitive::kPrimBoolean:
1171 case Primitive::kPrimByte:
Aart Bik304c8a52017-05-23 11:01:13 -07001172 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +01001173 return TrySetVectorLength(16);
Aart Bikf8f5a162017-02-06 15:35:29 -08001174 case Primitive::kPrimChar:
1175 case Primitive::kPrimShort:
Aart Bik304c8a52017-05-23 11:01:13 -07001176 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +01001177 return TrySetVectorLength(8);
Aart Bikf8f5a162017-02-06 15:35:29 -08001178 case Primitive::kPrimInt:
1179 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +01001180 return TrySetVectorLength(4);
Artem Serovb31f91f2017-04-05 11:31:19 +01001181 case Primitive::kPrimLong:
Aart Bikc8e93c72017-05-10 10:49:22 -07001182 *restrictions |= kNoDiv | kNoMul | kNoMinMax;
Aart Bikf8f5a162017-02-06 15:35:29 -08001183 return TrySetVectorLength(2);
1184 case Primitive::kPrimFloat:
Artem Serovd4bccf12017-04-03 18:47:32 +01001185 return TrySetVectorLength(4);
Artem Serovb31f91f2017-04-05 11:31:19 +01001186 case Primitive::kPrimDouble:
Aart Bikf8f5a162017-02-06 15:35:29 -08001187 return TrySetVectorLength(2);
1188 default:
1189 return false;
1190 }
1191 case kX86:
1192 case kX86_64:
Aart Bikb29f6842017-07-28 15:58:41 -07001193 // Allow vectorization for SSE4.1-enabled X86 devices only (128-bit SIMD).
Aart Bikf8f5a162017-02-06 15:35:29 -08001194 if (features->AsX86InstructionSetFeatures()->HasSSE4_1()) {
1195 switch (type) {
1196 case Primitive::kPrimBoolean:
1197 case Primitive::kPrimByte:
Aart Bikf3e61ee2017-04-12 17:09:20 -07001198 *restrictions |= kNoMul | kNoDiv | kNoShift | kNoAbs | kNoSignedHAdd | kNoUnroundedHAdd;
Aart Bikf8f5a162017-02-06 15:35:29 -08001199 return TrySetVectorLength(16);
1200 case Primitive::kPrimChar:
1201 case Primitive::kPrimShort:
Aart Bikf3e61ee2017-04-12 17:09:20 -07001202 *restrictions |= kNoDiv | kNoAbs | kNoSignedHAdd | kNoUnroundedHAdd;
Aart Bikf8f5a162017-02-06 15:35:29 -08001203 return TrySetVectorLength(8);
1204 case Primitive::kPrimInt:
1205 *restrictions |= kNoDiv;
1206 return TrySetVectorLength(4);
1207 case Primitive::kPrimLong:
Aart Bikc8e93c72017-05-10 10:49:22 -07001208 *restrictions |= kNoMul | kNoDiv | kNoShr | kNoAbs | kNoMinMax;
Aart Bikf8f5a162017-02-06 15:35:29 -08001209 return TrySetVectorLength(2);
1210 case Primitive::kPrimFloat:
Aart Bikc8e93c72017-05-10 10:49:22 -07001211 *restrictions |= kNoMinMax; // -0.0 vs +0.0
Aart Bikf8f5a162017-02-06 15:35:29 -08001212 return TrySetVectorLength(4);
1213 case Primitive::kPrimDouble:
Aart Bikc8e93c72017-05-10 10:49:22 -07001214 *restrictions |= kNoMinMax; // -0.0 vs +0.0
Aart Bikf8f5a162017-02-06 15:35:29 -08001215 return TrySetVectorLength(2);
1216 default:
1217 break;
1218 } // switch type
1219 }
1220 return false;
1221 case kMips:
Lena Djokic51765b02017-06-22 13:49:59 +02001222 if (features->AsMipsInstructionSetFeatures()->HasMsa()) {
1223 switch (type) {
1224 case Primitive::kPrimBoolean:
1225 case Primitive::kPrimByte:
1226 *restrictions |= kNoDiv;
1227 return TrySetVectorLength(16);
1228 case Primitive::kPrimChar:
1229 case Primitive::kPrimShort:
1230 *restrictions |= kNoDiv | kNoStringCharAt;
1231 return TrySetVectorLength(8);
1232 case Primitive::kPrimInt:
1233 *restrictions |= kNoDiv;
1234 return TrySetVectorLength(4);
1235 case Primitive::kPrimLong:
1236 *restrictions |= kNoDiv;
1237 return TrySetVectorLength(2);
1238 case Primitive::kPrimFloat:
1239 *restrictions |= kNoMinMax; // min/max(x, NaN)
1240 return TrySetVectorLength(4);
1241 case Primitive::kPrimDouble:
1242 *restrictions |= kNoMinMax; // min/max(x, NaN)
1243 return TrySetVectorLength(2);
1244 default:
1245 break;
1246 } // switch type
1247 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001248 return false;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001249 case kMips64:
1250 if (features->AsMips64InstructionSetFeatures()->HasMsa()) {
1251 switch (type) {
1252 case Primitive::kPrimBoolean:
1253 case Primitive::kPrimByte:
Goran Jakovljevic8fea1e12017-06-06 13:28:42 +02001254 *restrictions |= kNoDiv;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001255 return TrySetVectorLength(16);
1256 case Primitive::kPrimChar:
1257 case Primitive::kPrimShort:
Goran Jakovljevic8fea1e12017-06-06 13:28:42 +02001258 *restrictions |= kNoDiv | kNoStringCharAt;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001259 return TrySetVectorLength(8);
1260 case Primitive::kPrimInt:
Goran Jakovljevic8fea1e12017-06-06 13:28:42 +02001261 *restrictions |= kNoDiv;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001262 return TrySetVectorLength(4);
1263 case Primitive::kPrimLong:
Goran Jakovljevic8fea1e12017-06-06 13:28:42 +02001264 *restrictions |= kNoDiv;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001265 return TrySetVectorLength(2);
1266 case Primitive::kPrimFloat:
Goran Jakovljevic8fea1e12017-06-06 13:28:42 +02001267 *restrictions |= kNoMinMax; // min/max(x, NaN)
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001268 return TrySetVectorLength(4);
1269 case Primitive::kPrimDouble:
Goran Jakovljevic8fea1e12017-06-06 13:28:42 +02001270 *restrictions |= kNoMinMax; // min/max(x, NaN)
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001271 return TrySetVectorLength(2);
1272 default:
1273 break;
1274 } // switch type
1275 }
1276 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001277 default:
1278 return false;
1279 } // switch instruction set
1280}
1281
1282bool HLoopOptimization::TrySetVectorLength(uint32_t length) {
1283 DCHECK(IsPowerOfTwo(length) && length >= 2u);
1284 // First time set?
1285 if (vector_length_ == 0) {
1286 vector_length_ = length;
1287 }
1288 // Different types are acceptable within a loop-body, as long as all the corresponding vector
1289 // lengths match exactly to obtain a uniform traversal through the vector iteration space
1290 // (idiomatic exceptions to this rule can be handled by further unrolling sub-expressions).
1291 return vector_length_ == length;
1292}
1293
1294void HLoopOptimization::GenerateVecInv(HInstruction* org, Primitive::Type type) {
1295 if (vector_map_->find(org) == vector_map_->end()) {
1296 // In scalar code, just use a self pass-through for scalar invariants
1297 // (viz. expression remains itself).
1298 if (vector_mode_ == kSequential) {
1299 vector_map_->Put(org, org);
1300 return;
1301 }
1302 // In vector code, explicit scalar expansion is needed.
1303 HInstruction* vector = new (global_allocator_) HVecReplicateScalar(
1304 global_allocator_, org, type, vector_length_);
1305 vector_map_->Put(org, Insert(vector_preheader_, vector));
1306 }
1307}
1308
1309void HLoopOptimization::GenerateVecSub(HInstruction* org, HInstruction* offset) {
1310 if (vector_map_->find(org) == vector_map_->end()) {
Aart Bik14a68b42017-06-08 14:06:58 -07001311 HInstruction* subscript = vector_index_;
Aart Bik37dc4df2017-06-28 14:08:00 -07001312 int64_t value = 0;
1313 if (!IsInt64AndGet(offset, &value) || value != 0) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001314 subscript = new (global_allocator_) HAdd(Primitive::kPrimInt, subscript, offset);
1315 if (org->IsPhi()) {
1316 Insert(vector_body_, subscript); // lacks layout placeholder
1317 }
1318 }
1319 vector_map_->Put(org, subscript);
1320 }
1321}
1322
1323void HLoopOptimization::GenerateVecMem(HInstruction* org,
1324 HInstruction* opa,
1325 HInstruction* opb,
Aart Bik14a68b42017-06-08 14:06:58 -07001326 HInstruction* offset,
Aart Bikf8f5a162017-02-06 15:35:29 -08001327 Primitive::Type type) {
1328 HInstruction* vector = nullptr;
1329 if (vector_mode_ == kVector) {
1330 // Vector store or load.
Aart Bik14a68b42017-06-08 14:06:58 -07001331 HInstruction* base = org->InputAt(0);
Aart Bikf8f5a162017-02-06 15:35:29 -08001332 if (opb != nullptr) {
1333 vector = new (global_allocator_) HVecStore(
Aart Bik14a68b42017-06-08 14:06:58 -07001334 global_allocator_, base, opa, opb, type, vector_length_);
Aart Bikf8f5a162017-02-06 15:35:29 -08001335 } else {
Aart Bikdb14fcf2017-04-25 15:53:58 -07001336 bool is_string_char_at = org->AsArrayGet()->IsStringCharAt();
Aart Bikf8f5a162017-02-06 15:35:29 -08001337 vector = new (global_allocator_) HVecLoad(
Aart Bik14a68b42017-06-08 14:06:58 -07001338 global_allocator_, base, opa, type, vector_length_, is_string_char_at);
1339 }
1340 // Known dynamically enforced alignment?
Aart Bik14a68b42017-06-08 14:06:58 -07001341 if (vector_peeling_candidate_ != nullptr &&
1342 vector_peeling_candidate_->base == base &&
1343 vector_peeling_candidate_->offset == offset) {
1344 vector->AsVecMemoryOperation()->SetAlignment(Alignment(kAlignedBase, 0));
Aart Bikf8f5a162017-02-06 15:35:29 -08001345 }
1346 } else {
1347 // Scalar store or load.
1348 DCHECK(vector_mode_ == kSequential);
1349 if (opb != nullptr) {
1350 vector = new (global_allocator_) HArraySet(org->InputAt(0), opa, opb, type, kNoDexPc);
1351 } else {
Aart Bikdb14fcf2017-04-25 15:53:58 -07001352 bool is_string_char_at = org->AsArrayGet()->IsStringCharAt();
1353 vector = new (global_allocator_) HArrayGet(
1354 org->InputAt(0), opa, type, kNoDexPc, is_string_char_at);
Aart Bikf8f5a162017-02-06 15:35:29 -08001355 }
1356 }
1357 vector_map_->Put(org, vector);
1358}
1359
1360#define GENERATE_VEC(x, y) \
1361 if (vector_mode_ == kVector) { \
1362 vector = (x); \
1363 } else { \
1364 DCHECK(vector_mode_ == kSequential); \
1365 vector = (y); \
1366 } \
1367 break;
1368
1369void HLoopOptimization::GenerateVecOp(HInstruction* org,
1370 HInstruction* opa,
1371 HInstruction* opb,
Aart Bik304c8a52017-05-23 11:01:13 -07001372 Primitive::Type type,
1373 bool is_unsigned) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001374 if (vector_mode_ == kSequential) {
Aart Bik304c8a52017-05-23 11:01:13 -07001375 // Non-converting scalar code follows implicit integral promotion.
1376 if (!org->IsTypeConversion() && (type == Primitive::kPrimBoolean ||
1377 type == Primitive::kPrimByte ||
1378 type == Primitive::kPrimChar ||
1379 type == Primitive::kPrimShort)) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001380 type = Primitive::kPrimInt;
1381 }
1382 }
1383 HInstruction* vector = nullptr;
1384 switch (org->GetKind()) {
1385 case HInstruction::kNeg:
1386 DCHECK(opb == nullptr);
1387 GENERATE_VEC(
1388 new (global_allocator_) HVecNeg(global_allocator_, opa, type, vector_length_),
1389 new (global_allocator_) HNeg(type, opa));
1390 case HInstruction::kNot:
1391 DCHECK(opb == nullptr);
1392 GENERATE_VEC(
1393 new (global_allocator_) HVecNot(global_allocator_, opa, type, vector_length_),
1394 new (global_allocator_) HNot(type, opa));
1395 case HInstruction::kBooleanNot:
1396 DCHECK(opb == nullptr);
1397 GENERATE_VEC(
1398 new (global_allocator_) HVecNot(global_allocator_, opa, type, vector_length_),
1399 new (global_allocator_) HBooleanNot(opa));
1400 case HInstruction::kTypeConversion:
1401 DCHECK(opb == nullptr);
1402 GENERATE_VEC(
1403 new (global_allocator_) HVecCnv(global_allocator_, opa, type, vector_length_),
1404 new (global_allocator_) HTypeConversion(type, opa, kNoDexPc));
1405 case HInstruction::kAdd:
1406 GENERATE_VEC(
1407 new (global_allocator_) HVecAdd(global_allocator_, opa, opb, type, vector_length_),
1408 new (global_allocator_) HAdd(type, opa, opb));
1409 case HInstruction::kSub:
1410 GENERATE_VEC(
1411 new (global_allocator_) HVecSub(global_allocator_, opa, opb, type, vector_length_),
1412 new (global_allocator_) HSub(type, opa, opb));
1413 case HInstruction::kMul:
1414 GENERATE_VEC(
1415 new (global_allocator_) HVecMul(global_allocator_, opa, opb, type, vector_length_),
1416 new (global_allocator_) HMul(type, opa, opb));
1417 case HInstruction::kDiv:
1418 GENERATE_VEC(
1419 new (global_allocator_) HVecDiv(global_allocator_, opa, opb, type, vector_length_),
1420 new (global_allocator_) HDiv(type, opa, opb, kNoDexPc));
1421 case HInstruction::kAnd:
1422 GENERATE_VEC(
1423 new (global_allocator_) HVecAnd(global_allocator_, opa, opb, type, vector_length_),
1424 new (global_allocator_) HAnd(type, opa, opb));
1425 case HInstruction::kOr:
1426 GENERATE_VEC(
1427 new (global_allocator_) HVecOr(global_allocator_, opa, opb, type, vector_length_),
1428 new (global_allocator_) HOr(type, opa, opb));
1429 case HInstruction::kXor:
1430 GENERATE_VEC(
1431 new (global_allocator_) HVecXor(global_allocator_, opa, opb, type, vector_length_),
1432 new (global_allocator_) HXor(type, opa, opb));
1433 case HInstruction::kShl:
1434 GENERATE_VEC(
1435 new (global_allocator_) HVecShl(global_allocator_, opa, opb, type, vector_length_),
1436 new (global_allocator_) HShl(type, opa, opb));
1437 case HInstruction::kShr:
1438 GENERATE_VEC(
1439 new (global_allocator_) HVecShr(global_allocator_, opa, opb, type, vector_length_),
1440 new (global_allocator_) HShr(type, opa, opb));
1441 case HInstruction::kUShr:
1442 GENERATE_VEC(
1443 new (global_allocator_) HVecUShr(global_allocator_, opa, opb, type, vector_length_),
1444 new (global_allocator_) HUShr(type, opa, opb));
1445 case HInstruction::kInvokeStaticOrDirect: {
Aart Bik6daebeb2017-04-03 14:35:41 -07001446 HInvokeStaticOrDirect* invoke = org->AsInvokeStaticOrDirect();
1447 if (vector_mode_ == kVector) {
1448 switch (invoke->GetIntrinsic()) {
1449 case Intrinsics::kMathAbsInt:
1450 case Intrinsics::kMathAbsLong:
1451 case Intrinsics::kMathAbsFloat:
1452 case Intrinsics::kMathAbsDouble:
1453 DCHECK(opb == nullptr);
1454 vector = new (global_allocator_) HVecAbs(global_allocator_, opa, type, vector_length_);
1455 break;
Aart Bikc8e93c72017-05-10 10:49:22 -07001456 case Intrinsics::kMathMinIntInt:
1457 case Intrinsics::kMathMinLongLong:
1458 case Intrinsics::kMathMinFloatFloat:
1459 case Intrinsics::kMathMinDoubleDouble: {
Aart Bikc8e93c72017-05-10 10:49:22 -07001460 vector = new (global_allocator_)
1461 HVecMin(global_allocator_, opa, opb, type, vector_length_, is_unsigned);
1462 break;
1463 }
1464 case Intrinsics::kMathMaxIntInt:
1465 case Intrinsics::kMathMaxLongLong:
1466 case Intrinsics::kMathMaxFloatFloat:
1467 case Intrinsics::kMathMaxDoubleDouble: {
Aart Bikc8e93c72017-05-10 10:49:22 -07001468 vector = new (global_allocator_)
1469 HVecMax(global_allocator_, opa, opb, type, vector_length_, is_unsigned);
1470 break;
1471 }
Aart Bik6daebeb2017-04-03 14:35:41 -07001472 default:
1473 LOG(FATAL) << "Unsupported SIMD intrinsic";
1474 UNREACHABLE();
1475 } // switch invoke
1476 } else {
Aart Bik24b905f2017-04-06 09:59:06 -07001477 // In scalar code, simply clone the method invoke, and replace its operands with the
1478 // corresponding new scalar instructions in the loop. The instruction will get an
1479 // environment while being inserted from the instruction map in original program order.
Aart Bik6daebeb2017-04-03 14:35:41 -07001480 DCHECK(vector_mode_ == kSequential);
Aart Bik6e92fb32017-06-05 14:05:09 -07001481 size_t num_args = invoke->GetNumberOfArguments();
Aart Bik6daebeb2017-04-03 14:35:41 -07001482 HInvokeStaticOrDirect* new_invoke = new (global_allocator_) HInvokeStaticOrDirect(
1483 global_allocator_,
Aart Bik6e92fb32017-06-05 14:05:09 -07001484 num_args,
Aart Bik6daebeb2017-04-03 14:35:41 -07001485 invoke->GetType(),
1486 invoke->GetDexPc(),
1487 invoke->GetDexMethodIndex(),
1488 invoke->GetResolvedMethod(),
1489 invoke->GetDispatchInfo(),
1490 invoke->GetInvokeType(),
1491 invoke->GetTargetMethod(),
1492 invoke->GetClinitCheckRequirement());
1493 HInputsRef inputs = invoke->GetInputs();
Aart Bik6e92fb32017-06-05 14:05:09 -07001494 size_t num_inputs = inputs.size();
1495 DCHECK_LE(num_args, num_inputs);
1496 DCHECK_EQ(num_inputs, new_invoke->GetInputs().size()); // both invokes agree
1497 for (size_t index = 0; index < num_inputs; ++index) {
1498 HInstruction* new_input = index < num_args
1499 ? vector_map_->Get(inputs[index])
1500 : inputs[index]; // beyond arguments: just pass through
1501 new_invoke->SetArgumentAt(index, new_input);
Aart Bik6daebeb2017-04-03 14:35:41 -07001502 }
Aart Bik98990262017-04-10 13:15:57 -07001503 new_invoke->SetIntrinsic(invoke->GetIntrinsic(),
1504 kNeedsEnvironmentOrCache,
1505 kNoSideEffects,
1506 kNoThrow);
Aart Bik6daebeb2017-04-03 14:35:41 -07001507 vector = new_invoke;
1508 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001509 break;
1510 }
1511 default:
1512 break;
1513 } // switch
1514 CHECK(vector != nullptr) << "Unsupported SIMD operator";
1515 vector_map_->Put(org, vector);
1516}
1517
1518#undef GENERATE_VEC
1519
1520//
Aart Bikf3e61ee2017-04-12 17:09:20 -07001521// Vectorization idioms.
1522//
1523
1524// Method recognizes the following idioms:
1525// rounding halving add (a + b + 1) >> 1 for unsigned/signed operands a, b
1526// regular halving add (a + b) >> 1 for unsigned/signed operands a, b
1527// Provided that the operands are promoted to a wider form to do the arithmetic and
1528// then cast back to narrower form, the idioms can be mapped into efficient SIMD
1529// implementation that operates directly in narrower form (plus one extra bit).
1530// TODO: current version recognizes implicit byte/short/char widening only;
1531// explicit widening from int to long could be added later.
1532bool HLoopOptimization::VectorizeHalvingAddIdiom(LoopNode* node,
1533 HInstruction* instruction,
1534 bool generate_code,
1535 Primitive::Type type,
1536 uint64_t restrictions) {
1537 // Test for top level arithmetic shift right x >> 1 or logical shift right x >>> 1
Aart Bik304c8a52017-05-23 11:01:13 -07001538 // (note whether the sign bit in wider precision is shifted in has no effect
Aart Bikf3e61ee2017-04-12 17:09:20 -07001539 // on the narrow precision computed by the idiom).
Aart Bik5f805002017-05-16 16:42:41 -07001540 int64_t distance = 0;
Aart Bikf3e61ee2017-04-12 17:09:20 -07001541 if ((instruction->IsShr() ||
1542 instruction->IsUShr()) &&
Aart Bik5f805002017-05-16 16:42:41 -07001543 IsInt64AndGet(instruction->InputAt(1), /*out*/ &distance) && distance == 1) {
1544 // Test for (a + b + c) >> 1 for optional constant c.
1545 HInstruction* a = nullptr;
1546 HInstruction* b = nullptr;
1547 int64_t c = 0;
1548 if (IsAddConst(instruction->InputAt(0), /*out*/ &a, /*out*/ &b, /*out*/ &c)) {
Aart Bik304c8a52017-05-23 11:01:13 -07001549 DCHECK(a != nullptr && b != nullptr);
Aart Bik5f805002017-05-16 16:42:41 -07001550 // Accept c == 1 (rounded) or c == 0 (not rounded).
1551 bool is_rounded = false;
1552 if (c == 1) {
1553 is_rounded = true;
1554 } else if (c != 0) {
1555 return false;
1556 }
1557 // Accept consistent zero or sign extension on operands a and b.
Aart Bikf3e61ee2017-04-12 17:09:20 -07001558 HInstruction* r = nullptr;
1559 HInstruction* s = nullptr;
1560 bool is_unsigned = false;
Aart Bik304c8a52017-05-23 11:01:13 -07001561 if (!IsNarrowerOperands(a, b, type, &r, &s, &is_unsigned)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -07001562 return false;
1563 }
1564 // Deal with vector restrictions.
1565 if ((!is_unsigned && HasVectorRestrictions(restrictions, kNoSignedHAdd)) ||
1566 (!is_rounded && HasVectorRestrictions(restrictions, kNoUnroundedHAdd))) {
1567 return false;
1568 }
1569 // Accept recognized halving add for vectorizable operands. Vectorized code uses the
1570 // shorthand idiomatic operation. Sequential code uses the original scalar expressions.
1571 DCHECK(r != nullptr && s != nullptr);
Aart Bik304c8a52017-05-23 11:01:13 -07001572 if (generate_code && vector_mode_ != kVector) { // de-idiom
1573 r = instruction->InputAt(0);
1574 s = instruction->InputAt(1);
1575 }
Aart Bikf3e61ee2017-04-12 17:09:20 -07001576 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
1577 VectorizeUse(node, s, generate_code, type, restrictions)) {
1578 if (generate_code) {
1579 if (vector_mode_ == kVector) {
1580 vector_map_->Put(instruction, new (global_allocator_) HVecHalvingAdd(
1581 global_allocator_,
1582 vector_map_->Get(r),
1583 vector_map_->Get(s),
1584 type,
1585 vector_length_,
1586 is_unsigned,
1587 is_rounded));
1588 } else {
Aart Bik304c8a52017-05-23 11:01:13 -07001589 GenerateVecOp(instruction, vector_map_->Get(r), vector_map_->Get(s), type);
Aart Bikf3e61ee2017-04-12 17:09:20 -07001590 }
1591 }
1592 return true;
1593 }
1594 }
1595 }
1596 return false;
1597}
1598
1599//
Aart Bik14a68b42017-06-08 14:06:58 -07001600// Vectorization heuristics.
1601//
1602
1603bool HLoopOptimization::IsVectorizationProfitable(int64_t trip_count) {
1604 // Current heuristic: non-empty body with sufficient number
1605 // of iterations (if known).
1606 // TODO: refine by looking at e.g. operation count, alignment, etc.
1607 if (vector_length_ == 0) {
1608 return false; // nothing found
1609 } else if (0 < trip_count && trip_count < vector_length_) {
1610 return false; // insufficient iterations
1611 }
1612 return true;
1613}
1614
Aart Bikb29f6842017-07-28 15:58:41 -07001615void HLoopOptimization::SetPeelingCandidate(const ArrayReference* candidate,
1616 int64_t trip_count ATTRIBUTE_UNUSED) {
Aart Bik14a68b42017-06-08 14:06:58 -07001617 // Current heuristic: none.
1618 // TODO: implement
Aart Bikb29f6842017-07-28 15:58:41 -07001619 vector_peeling_candidate_ = candidate;
Aart Bik14a68b42017-06-08 14:06:58 -07001620}
1621
1622uint32_t HLoopOptimization::GetUnrollingFactor(HBasicBlock* block, int64_t trip_count) {
1623 // Current heuristic: unroll by 2 on ARM64/X86 for large known trip
1624 // counts and small loop bodies.
1625 // TODO: refine with operation count, remaining iterations, etc.
1626 // Artem had some really cool ideas for this already.
1627 switch (compiler_driver_->GetInstructionSet()) {
1628 case kArm64:
1629 case kX86:
1630 case kX86_64: {
1631 size_t num_instructions = block->GetInstructions().CountSize();
1632 if (num_instructions <= 10 && trip_count >= 4 * vector_length_) {
1633 return 2;
1634 }
1635 return 1;
1636 }
1637 default:
1638 return 1;
1639 }
1640}
1641
1642//
Aart Bikf8f5a162017-02-06 15:35:29 -08001643// Helpers.
1644//
1645
1646bool HLoopOptimization::TrySetPhiInduction(HPhi* phi, bool restrict_uses) {
Aart Bikb29f6842017-07-28 15:58:41 -07001647 // Start with empty phi induction.
1648 iset_->clear();
1649
Nicolas Geoffrayf57c1ae2017-06-28 17:40:18 +01001650 // Special case Phis that have equivalent in a debuggable setup. Our graph checker isn't
1651 // smart enough to follow strongly connected components (and it's probably not worth
1652 // it to make it so). See b/33775412.
1653 if (graph_->IsDebuggable() && phi->HasEquivalentPhi()) {
1654 return false;
1655 }
Aart Bikb29f6842017-07-28 15:58:41 -07001656
1657 // Lookup phi induction cycle.
Aart Bikcc42be02016-10-20 16:14:16 -07001658 ArenaSet<HInstruction*>* set = induction_range_.LookupCycle(phi);
1659 if (set != nullptr) {
1660 for (HInstruction* i : *set) {
Aart Bike3dedc52016-11-02 17:50:27 -07001661 // Check that, other than instructions that are no longer in the graph (removed earlier)
Aart Bikf8f5a162017-02-06 15:35:29 -08001662 // each instruction is removable and, when restrict uses are requested, other than for phi,
1663 // all uses are contained within the cycle.
Aart Bike3dedc52016-11-02 17:50:27 -07001664 if (!i->IsInBlock()) {
1665 continue;
1666 } else if (!i->IsRemovable()) {
1667 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001668 } else if (i != phi && restrict_uses) {
Aart Bikb29f6842017-07-28 15:58:41 -07001669 // Deal with regular uses.
Aart Bikcc42be02016-10-20 16:14:16 -07001670 for (const HUseListNode<HInstruction*>& use : i->GetUses()) {
1671 if (set->find(use.GetUser()) == set->end()) {
1672 return false;
1673 }
1674 }
1675 }
Aart Bike3dedc52016-11-02 17:50:27 -07001676 iset_->insert(i); // copy
Aart Bikcc42be02016-10-20 16:14:16 -07001677 }
Aart Bikcc42be02016-10-20 16:14:16 -07001678 return true;
1679 }
1680 return false;
1681}
1682
Aart Bikb29f6842017-07-28 15:58:41 -07001683bool HLoopOptimization::TrySetPhiReduction(HPhi* phi) {
Aart Bikcc42be02016-10-20 16:14:16 -07001684 DCHECK(iset_->empty());
Aart Bikb29f6842017-07-28 15:58:41 -07001685 // Only unclassified phi cycles are candidates for reductions.
1686 if (induction_range_.IsClassified(phi)) {
1687 return false;
1688 }
1689 // Accept operations like x = x + .., provided that the phi and the reduction are
1690 // used exactly once inside the loop, and by each other.
1691 HInputsRef inputs = phi->GetInputs();
1692 if (inputs.size() == 2) {
1693 HInstruction* reduction = inputs[1];
1694 if (HasReductionFormat(reduction, phi)) {
1695 HLoopInformation* loop_info = phi->GetBlock()->GetLoopInformation();
1696 int32_t use_count = 0;
1697 bool single_use_inside_loop =
1698 // Reduction update only used by phi.
1699 reduction->GetUses().HasExactlyOneElement() &&
1700 !reduction->HasEnvironmentUses() &&
1701 // Reduction update is only use of phi inside the loop.
1702 IsOnlyUsedAfterLoop(loop_info, phi, /*collect_loop_uses*/ true, &use_count) &&
1703 iset_->size() == 1;
1704 iset_->clear(); // leave the way you found it
1705 if (single_use_inside_loop) {
1706 // Link reduction back, and start recording feed value.
1707 reductions_->Put(reduction, phi);
1708 reductions_->Put(phi, phi->InputAt(0));
1709 return true;
1710 }
1711 }
1712 }
1713 return false;
1714}
1715
1716bool HLoopOptimization::TrySetSimpleLoopHeader(HBasicBlock* block, /*out*/ HPhi** main_phi) {
1717 // Start with empty phi induction and reductions.
1718 iset_->clear();
1719 reductions_->clear();
1720
1721 // Scan the phis to find the following (the induction structure has already
1722 // been optimized, so we don't need to worry about trivial cases):
1723 // (1) optional reductions in loop,
1724 // (2) the main induction, used in loop control.
1725 HPhi* phi = nullptr;
1726 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
1727 if (TrySetPhiReduction(it.Current()->AsPhi())) {
1728 continue;
1729 } else if (phi == nullptr) {
1730 // Found the first candidate for main induction.
1731 phi = it.Current()->AsPhi();
1732 } else {
1733 return false;
1734 }
1735 }
1736
1737 // Then test for a typical loopheader:
1738 // s: SuspendCheck
1739 // c: Condition(phi, bound)
1740 // i: If(c)
1741 if (phi != nullptr && TrySetPhiInduction(phi, /*restrict_uses*/ false)) {
Aart Bikcc42be02016-10-20 16:14:16 -07001742 HInstruction* s = block->GetFirstInstruction();
1743 if (s != nullptr && s->IsSuspendCheck()) {
1744 HInstruction* c = s->GetNext();
Aart Bikd86c0852017-04-14 12:00:15 -07001745 if (c != nullptr &&
1746 c->IsCondition() &&
1747 c->GetUses().HasExactlyOneElement() && // only used for termination
1748 !c->HasEnvironmentUses()) { // unlikely, but not impossible
Aart Bikcc42be02016-10-20 16:14:16 -07001749 HInstruction* i = c->GetNext();
1750 if (i != nullptr && i->IsIf() && i->InputAt(0) == c) {
1751 iset_->insert(c);
1752 iset_->insert(s);
Aart Bikb29f6842017-07-28 15:58:41 -07001753 *main_phi = phi;
Aart Bikcc42be02016-10-20 16:14:16 -07001754 return true;
1755 }
1756 }
1757 }
1758 }
1759 return false;
1760}
1761
1762bool HLoopOptimization::IsEmptyBody(HBasicBlock* block) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001763 if (!block->GetPhis().IsEmpty()) {
1764 return false;
1765 }
1766 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
1767 HInstruction* instruction = it.Current();
1768 if (!instruction->IsGoto() && iset_->find(instruction) == iset_->end()) {
1769 return false;
Aart Bikcc42be02016-10-20 16:14:16 -07001770 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001771 }
1772 return true;
1773}
1774
1775bool HLoopOptimization::IsUsedOutsideLoop(HLoopInformation* loop_info,
1776 HInstruction* instruction) {
Aart Bikb29f6842017-07-28 15:58:41 -07001777 // Deal with regular uses.
Aart Bikf8f5a162017-02-06 15:35:29 -08001778 for (const HUseListNode<HInstruction*>& use : instruction->GetUses()) {
1779 if (use.GetUser()->GetBlock()->GetLoopInformation() != loop_info) {
1780 return true;
1781 }
Aart Bikcc42be02016-10-20 16:14:16 -07001782 }
1783 return false;
1784}
1785
Aart Bik482095d2016-10-10 15:39:10 -07001786bool HLoopOptimization::IsOnlyUsedAfterLoop(HLoopInformation* loop_info,
Aart Bik8c4a8542016-10-06 11:36:57 -07001787 HInstruction* instruction,
Aart Bik6b69e0a2017-01-11 10:20:43 -08001788 bool collect_loop_uses,
Aart Bik8c4a8542016-10-06 11:36:57 -07001789 /*out*/ int32_t* use_count) {
Aart Bikb29f6842017-07-28 15:58:41 -07001790 // Deal with regular uses.
Aart Bik8c4a8542016-10-06 11:36:57 -07001791 for (const HUseListNode<HInstruction*>& use : instruction->GetUses()) {
1792 HInstruction* user = use.GetUser();
1793 if (iset_->find(user) == iset_->end()) { // not excluded?
1794 HLoopInformation* other_loop_info = user->GetBlock()->GetLoopInformation();
Aart Bik482095d2016-10-10 15:39:10 -07001795 if (other_loop_info != nullptr && other_loop_info->IsIn(*loop_info)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -08001796 // If collect_loop_uses is set, simply keep adding those uses to the set.
1797 // Otherwise, reject uses inside the loop that were not already in the set.
1798 if (collect_loop_uses) {
1799 iset_->insert(user);
1800 continue;
1801 }
Aart Bik8c4a8542016-10-06 11:36:57 -07001802 return false;
1803 }
1804 ++*use_count;
1805 }
1806 }
1807 return true;
1808}
1809
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01001810bool HLoopOptimization::TryReplaceWithLastValue(HLoopInformation* loop_info,
1811 HInstruction* instruction,
1812 HBasicBlock* block) {
1813 // Try to replace outside uses with the last value.
Aart Bik807868e2016-11-03 17:51:43 -07001814 if (induction_range_.CanGenerateLastValue(instruction)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -08001815 HInstruction* replacement = induction_range_.GenerateLastValue(instruction, graph_, block);
Aart Bikb29f6842017-07-28 15:58:41 -07001816 // Deal with regular uses.
Aart Bik6b69e0a2017-01-11 10:20:43 -08001817 const HUseList<HInstruction*>& uses = instruction->GetUses();
1818 for (auto it = uses.begin(), end = uses.end(); it != end;) {
1819 HInstruction* user = it->GetUser();
1820 size_t index = it->GetIndex();
1821 ++it; // increment before replacing
1822 if (iset_->find(user) == iset_->end()) { // not excluded?
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01001823 if (kIsDebugBuild) {
1824 // We have checked earlier in 'IsOnlyUsedAfterLoop' that the use is after the loop.
1825 HLoopInformation* other_loop_info = user->GetBlock()->GetLoopInformation();
1826 CHECK(other_loop_info == nullptr || !other_loop_info->IsIn(*loop_info));
1827 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08001828 user->ReplaceInput(replacement, index);
1829 induction_range_.Replace(user, instruction, replacement); // update induction
1830 }
1831 }
Aart Bikb29f6842017-07-28 15:58:41 -07001832 // Deal with environment uses.
Aart Bik6b69e0a2017-01-11 10:20:43 -08001833 const HUseList<HEnvironment*>& env_uses = instruction->GetEnvUses();
1834 for (auto it = env_uses.begin(), end = env_uses.end(); it != end;) {
1835 HEnvironment* user = it->GetUser();
1836 size_t index = it->GetIndex();
1837 ++it; // increment before replacing
1838 if (iset_->find(user->GetHolder()) == iset_->end()) { // not excluded?
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01001839 // Only update environment uses after the loop.
Aart Bik14a68b42017-06-08 14:06:58 -07001840 HLoopInformation* other_loop_info = user->GetHolder()->GetBlock()->GetLoopInformation();
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01001841 if (other_loop_info == nullptr || !other_loop_info->IsIn(*loop_info)) {
1842 user->RemoveAsUserOfInput(index);
1843 user->SetRawEnvAt(index, replacement);
1844 replacement->AddEnvUseAt(user, index);
1845 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08001846 }
1847 }
Aart Bik807868e2016-11-03 17:51:43 -07001848 return true;
Aart Bik8c4a8542016-10-06 11:36:57 -07001849 }
Aart Bik807868e2016-11-03 17:51:43 -07001850 return false;
Aart Bik8c4a8542016-10-06 11:36:57 -07001851}
1852
Aart Bikf8f5a162017-02-06 15:35:29 -08001853bool HLoopOptimization::TryAssignLastValue(HLoopInformation* loop_info,
1854 HInstruction* instruction,
1855 HBasicBlock* block,
1856 bool collect_loop_uses) {
1857 // Assigning the last value is always successful if there are no uses.
1858 // Otherwise, it succeeds in a no early-exit loop by generating the
1859 // proper last value assignment.
1860 int32_t use_count = 0;
1861 return IsOnlyUsedAfterLoop(loop_info, instruction, collect_loop_uses, &use_count) &&
1862 (use_count == 0 ||
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01001863 (!IsEarlyExit(loop_info) && TryReplaceWithLastValue(loop_info, instruction, block)));
Aart Bikf8f5a162017-02-06 15:35:29 -08001864}
1865
Aart Bik6b69e0a2017-01-11 10:20:43 -08001866void HLoopOptimization::RemoveDeadInstructions(const HInstructionList& list) {
1867 for (HBackwardInstructionIterator i(list); !i.Done(); i.Advance()) {
1868 HInstruction* instruction = i.Current();
1869 if (instruction->IsDeadAndRemovable()) {
1870 simplified_ = true;
1871 instruction->GetBlock()->RemoveInstructionOrPhi(instruction);
1872 }
1873 }
1874}
1875
Aart Bik14a68b42017-06-08 14:06:58 -07001876bool HLoopOptimization::CanRemoveCycle() {
1877 for (HInstruction* i : *iset_) {
1878 // We can never remove instructions that have environment
1879 // uses when we compile 'debuggable'.
1880 if (i->HasEnvironmentUses() && graph_->IsDebuggable()) {
1881 return false;
1882 }
1883 // A deoptimization should never have an environment input removed.
1884 for (const HUseListNode<HEnvironment*>& use : i->GetEnvUses()) {
1885 if (use.GetUser()->GetHolder()->IsDeoptimize()) {
1886 return false;
1887 }
1888 }
1889 }
1890 return true;
1891}
1892
Aart Bik281c6812016-08-26 11:31:48 -07001893} // namespace art