blob: 7e370182295b1e0321a61aad542dbb70a8562e15 [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 Bik521b50f2017-09-09 10:44:45 -070037// No loop unrolling factor (just one copy of the loop-body).
38static constexpr uint32_t kNoUnrollingFactor = 1;
39
Aart Bik9abf8942016-10-14 09:49:42 -070040// Remove the instruction from the graph. A bit more elaborate than the usual
41// instruction removal, since there may be a cycle in the use structure.
Aart Bik281c6812016-08-26 11:31:48 -070042static void RemoveFromCycle(HInstruction* instruction) {
Aart Bik281c6812016-08-26 11:31:48 -070043 instruction->RemoveAsUserOfAllInputs();
44 instruction->RemoveEnvironmentUsers();
45 instruction->GetBlock()->RemoveInstructionOrPhi(instruction, /*ensure_safety=*/ false);
Artem Serov21c7e6f2017-07-27 16:04:42 +010046 RemoveEnvironmentUses(instruction);
47 ResetEnvironmentInputRecords(instruction);
Aart Bik281c6812016-08-26 11:31:48 -070048}
49
Aart Bik807868e2016-11-03 17:51:43 -070050// Detect a goto block and sets succ to the single successor.
Aart Bike3dedc52016-11-02 17:50:27 -070051static bool IsGotoBlock(HBasicBlock* block, /*out*/ HBasicBlock** succ) {
52 if (block->GetPredecessors().size() == 1 &&
53 block->GetSuccessors().size() == 1 &&
54 block->IsSingleGoto()) {
55 *succ = block->GetSingleSuccessor();
56 return true;
57 }
58 return false;
59}
60
Aart Bik807868e2016-11-03 17:51:43 -070061// Detect an early exit loop.
62static bool IsEarlyExit(HLoopInformation* loop_info) {
63 HBlocksInLoopReversePostOrderIterator it_loop(*loop_info);
64 for (it_loop.Advance(); !it_loop.Done(); it_loop.Advance()) {
65 for (HBasicBlock* successor : it_loop.Current()->GetSuccessors()) {
66 if (!loop_info->Contains(*successor)) {
67 return true;
68 }
69 }
70 }
71 return false;
72}
73
Aart Bik68ca7022017-09-26 16:44:23 -070074// Forward declaration.
75static bool IsZeroExtensionAndGet(HInstruction* instruction,
76 DataType::Type type,
77 /*out*/ HInstruction** operand,
78 bool to64 = false);
79
Aart Bikdbbac8f2017-09-01 13:06:08 -070080// Detect a sign extension in instruction from the given type. The to64 parameter
81// denotes if result is long, and thus sign extension from int can be included.
82// Returns the promoted operand on success.
Aart Bikf3e61ee2017-04-12 17:09:20 -070083static bool IsSignExtensionAndGet(HInstruction* instruction,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +010084 DataType::Type type,
Aart Bikdbbac8f2017-09-01 13:06:08 -070085 /*out*/ HInstruction** operand,
86 bool to64 = false) {
Aart Bikf3e61ee2017-04-12 17:09:20 -070087 // Accept any already wider constant that would be handled properly by sign
88 // extension when represented in the *width* of the given narrower data type
89 // (the fact that char normally zero extends does not matter here).
90 int64_t value = 0;
Aart Bik50e20d52017-05-05 14:07:29 -070091 if (IsInt64AndGet(instruction, /*out*/ &value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -070092 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +010093 case DataType::Type::kInt8:
Aart Bikdbbac8f2017-09-01 13:06:08 -070094 if (IsInt<8>(value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -070095 *operand = instruction;
96 return true;
97 }
98 return false;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +010099 case DataType::Type::kUint16:
100 case DataType::Type::kInt16:
Aart Bikdbbac8f2017-09-01 13:06:08 -0700101 if (IsInt<16>(value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700102 *operand = instruction;
103 return true;
104 }
105 return false;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100106 case DataType::Type::kInt32:
Aart Bikdbbac8f2017-09-01 13:06:08 -0700107 if (IsInt<32>(value)) {
108 *operand = instruction;
109 return to64;
110 }
111 return false;
Aart Bikf3e61ee2017-04-12 17:09:20 -0700112 default:
113 return false;
114 }
115 }
116 // An implicit widening conversion of a signed integer to an integral type sign-extends
117 // the two's-complement representation of the integer value to fill the wider format.
118 if (instruction->GetType() == type && (instruction->IsArrayGet() ||
119 instruction->IsStaticFieldGet() ||
120 instruction->IsInstanceFieldGet())) {
121 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100122 case DataType::Type::kInt8:
123 case DataType::Type::kInt16:
Aart Bikf3e61ee2017-04-12 17:09:20 -0700124 *operand = instruction;
125 return true;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100126 case DataType::Type::kInt32:
Aart Bikdbbac8f2017-09-01 13:06:08 -0700127 *operand = instruction;
128 return to64;
Aart Bikf3e61ee2017-04-12 17:09:20 -0700129 default:
130 return false;
131 }
132 }
Aart Bik68ca7022017-09-26 16:44:23 -0700133 // Explicit type conversions.
134 if (instruction->IsTypeConversion()) {
135 DataType::Type from = instruction->InputAt(0)->GetType();
136 switch (instruction->GetType()) {
137 case DataType::Type::kInt64:
138 return IsSignExtensionAndGet(instruction->InputAt(0), type, /*out*/ operand, /*to64*/ true);
139 case DataType::Type::kInt16:
140 return type == DataType::Type::kUint16 &&
141 from == DataType::Type::kUint16 &&
142 IsZeroExtensionAndGet(instruction->InputAt(0), type, /*out*/ operand, to64);
143 default:
144 return false;
145 }
Aart Bikdbbac8f2017-09-01 13:06:08 -0700146 }
Aart Bikf3e61ee2017-04-12 17:09:20 -0700147 return false;
148}
149
Aart Bikdbbac8f2017-09-01 13:06:08 -0700150// Detect a zero extension in instruction from the given type. The to64 parameter
151// denotes if result is long, and thus zero extension from int can be included.
152// Returns the promoted operand on success.
Aart Bikf3e61ee2017-04-12 17:09:20 -0700153static bool IsZeroExtensionAndGet(HInstruction* instruction,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100154 DataType::Type type,
Aart Bikdbbac8f2017-09-01 13:06:08 -0700155 /*out*/ HInstruction** operand,
Aart Bik68ca7022017-09-26 16:44:23 -0700156 bool to64) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700157 // Accept any already wider constant that would be handled properly by zero
158 // extension when represented in the *width* of the given narrower data type
Aart Bikdbbac8f2017-09-01 13:06:08 -0700159 // (the fact that byte/short/int normally sign extend does not matter here).
Aart Bikf3e61ee2017-04-12 17:09:20 -0700160 int64_t value = 0;
Aart Bik50e20d52017-05-05 14:07:29 -0700161 if (IsInt64AndGet(instruction, /*out*/ &value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700162 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100163 case DataType::Type::kInt8:
Aart Bikdbbac8f2017-09-01 13:06:08 -0700164 if (IsUint<8>(value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700165 *operand = instruction;
166 return true;
167 }
168 return false;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100169 case DataType::Type::kUint16:
170 case DataType::Type::kInt16:
Aart Bikdbbac8f2017-09-01 13:06:08 -0700171 if (IsUint<16>(value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700172 *operand = instruction;
173 return true;
174 }
175 return false;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100176 case DataType::Type::kInt32:
Aart Bikdbbac8f2017-09-01 13:06:08 -0700177 if (IsUint<32>(value)) {
178 *operand = instruction;
179 return to64;
180 }
181 return false;
Aart Bikf3e61ee2017-04-12 17:09:20 -0700182 default:
183 return false;
184 }
185 }
186 // An implicit widening conversion of a char to an integral type zero-extends
187 // the representation of the char value to fill the wider format.
188 if (instruction->GetType() == type && (instruction->IsArrayGet() ||
189 instruction->IsStaticFieldGet() ||
190 instruction->IsInstanceFieldGet())) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100191 if (type == DataType::Type::kUint16) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700192 *operand = instruction;
193 return true;
194 }
195 }
196 // A sign (or zero) extension followed by an explicit removal of just the
197 // higher sign bits is equivalent to a zero extension of the underlying operand.
198 if (instruction->IsAnd()) {
199 int64_t mask = 0;
200 HInstruction* a = instruction->InputAt(0);
201 HInstruction* b = instruction->InputAt(1);
202 // In (a & b) find (mask & b) or (a & mask) with sign or zero extension on the non-mask.
203 if ((IsInt64AndGet(a, /*out*/ &mask) && (IsSignExtensionAndGet(b, type, /*out*/ operand) ||
204 IsZeroExtensionAndGet(b, type, /*out*/ operand))) ||
205 (IsInt64AndGet(b, /*out*/ &mask) && (IsSignExtensionAndGet(a, type, /*out*/ operand) ||
206 IsZeroExtensionAndGet(a, type, /*out*/ operand)))) {
207 switch ((*operand)->GetType()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100208 case DataType::Type::kInt8:
Aart Bikdbbac8f2017-09-01 13:06:08 -0700209 return mask == std::numeric_limits<uint8_t>::max();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100210 case DataType::Type::kUint16:
211 case DataType::Type::kInt16:
Aart Bikdbbac8f2017-09-01 13:06:08 -0700212 return mask == std::numeric_limits<uint16_t>::max();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100213 case DataType::Type::kInt32:
Aart Bikdbbac8f2017-09-01 13:06:08 -0700214 return mask == std::numeric_limits<uint32_t>::max() && to64;
Aart Bikf3e61ee2017-04-12 17:09:20 -0700215 default: return false;
216 }
217 }
218 }
Aart Bik68ca7022017-09-26 16:44:23 -0700219 // Explicit type conversions.
220 if (instruction->IsTypeConversion()) {
221 DataType::Type from = instruction->InputAt(0)->GetType();
222 switch (instruction->GetType()) {
223 case DataType::Type::kInt64:
224 return IsZeroExtensionAndGet(instruction->InputAt(0), type, /*out*/ operand, /*to64*/ true);
225 case DataType::Type::kUint16:
226 return type == DataType::Type::kInt16 &&
227 from == DataType::Type::kInt16 &&
228 IsSignExtensionAndGet(instruction->InputAt(0), type, /*out*/ operand, to64);
229 default:
230 return false;
231 }
Aart Bikdbbac8f2017-09-01 13:06:08 -0700232 }
Aart Bikf3e61ee2017-04-12 17:09:20 -0700233 return false;
234}
235
Aart Bik304c8a52017-05-23 11:01:13 -0700236// Detect situations with same-extension narrower operands.
237// Returns true on success and sets is_unsigned accordingly.
238static bool IsNarrowerOperands(HInstruction* a,
239 HInstruction* b,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100240 DataType::Type type,
Aart Bik304c8a52017-05-23 11:01:13 -0700241 /*out*/ HInstruction** r,
242 /*out*/ HInstruction** s,
243 /*out*/ bool* is_unsigned) {
244 if (IsSignExtensionAndGet(a, type, r) && IsSignExtensionAndGet(b, type, s)) {
245 *is_unsigned = false;
246 return true;
247 } else if (IsZeroExtensionAndGet(a, type, r) && IsZeroExtensionAndGet(b, type, s)) {
248 *is_unsigned = true;
249 return true;
250 }
251 return false;
252}
253
254// As above, single operand.
255static bool IsNarrowerOperand(HInstruction* a,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100256 DataType::Type type,
Aart Bik304c8a52017-05-23 11:01:13 -0700257 /*out*/ HInstruction** r,
258 /*out*/ bool* is_unsigned) {
259 if (IsSignExtensionAndGet(a, type, r)) {
260 *is_unsigned = false;
261 return true;
262 } else if (IsZeroExtensionAndGet(a, type, r)) {
263 *is_unsigned = true;
264 return true;
265 }
266 return false;
267}
268
Aart Bikdbbac8f2017-09-01 13:06:08 -0700269// Compute relative vector length based on type difference.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100270static size_t GetOtherVL(DataType::Type other_type, DataType::Type vector_type, size_t vl) {
Aart Bikdbbac8f2017-09-01 13:06:08 -0700271 switch (other_type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100272 case DataType::Type::kBool:
273 case DataType::Type::kInt8:
Aart Bikdbbac8f2017-09-01 13:06:08 -0700274 switch (vector_type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100275 case DataType::Type::kBool:
276 case DataType::Type::kInt8: return vl;
Aart Bikdbbac8f2017-09-01 13:06:08 -0700277 default: break;
278 }
279 return vl;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100280 case DataType::Type::kUint16:
281 case DataType::Type::kInt16:
Aart Bikdbbac8f2017-09-01 13:06:08 -0700282 switch (vector_type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100283 case DataType::Type::kBool:
284 case DataType::Type::kInt8: return vl >> 1;
285 case DataType::Type::kUint16:
286 case DataType::Type::kInt16: return vl;
Aart Bikdbbac8f2017-09-01 13:06:08 -0700287 default: break;
288 }
289 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100290 case DataType::Type::kInt32:
Aart Bikdbbac8f2017-09-01 13:06:08 -0700291 switch (vector_type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100292 case DataType::Type::kBool:
293 case DataType::Type::kInt8: return vl >> 2;
294 case DataType::Type::kUint16:
295 case DataType::Type::kInt16: return vl >> 1;
296 case DataType::Type::kInt32: return vl;
Aart Bikdbbac8f2017-09-01 13:06:08 -0700297 default: break;
298 }
299 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100300 case DataType::Type::kInt64:
Aart Bikdbbac8f2017-09-01 13:06:08 -0700301 switch (vector_type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100302 case DataType::Type::kBool:
303 case DataType::Type::kInt8: return vl >> 3;
304 case DataType::Type::kUint16:
305 case DataType::Type::kInt16: return vl >> 2;
306 case DataType::Type::kInt32: return vl >> 1;
307 case DataType::Type::kInt64: return vl;
Aart Bikdbbac8f2017-09-01 13:06:08 -0700308 default: break;
309 }
310 break;
311 default:
312 break;
313 }
314 LOG(FATAL) << "Unsupported idiom conversion";
315 UNREACHABLE();
316}
317
Aart Bik5f805002017-05-16 16:42:41 -0700318// Detect up to two instructions a and b, and an acccumulated constant c.
319static bool IsAddConstHelper(HInstruction* instruction,
320 /*out*/ HInstruction** a,
321 /*out*/ HInstruction** b,
322 /*out*/ int64_t* c,
323 int32_t depth) {
324 static constexpr int32_t kMaxDepth = 8; // don't search too deep
325 int64_t value = 0;
326 if (IsInt64AndGet(instruction, &value)) {
327 *c += value;
328 return true;
329 } else if (instruction->IsAdd() && depth <= kMaxDepth) {
330 return IsAddConstHelper(instruction->InputAt(0), a, b, c, depth + 1) &&
331 IsAddConstHelper(instruction->InputAt(1), a, b, c, depth + 1);
332 } else if (*a == nullptr) {
333 *a = instruction;
334 return true;
335 } else if (*b == nullptr) {
336 *b = instruction;
337 return true;
338 }
339 return false; // too many non-const operands
340}
341
342// Detect a + b + c for an optional constant c.
343static bool IsAddConst(HInstruction* instruction,
344 /*out*/ HInstruction** a,
345 /*out*/ HInstruction** b,
346 /*out*/ int64_t* c) {
347 if (instruction->IsAdd()) {
348 // Try to find a + b and accumulated c.
349 if (IsAddConstHelper(instruction->InputAt(0), a, b, c, /*depth*/ 0) &&
350 IsAddConstHelper(instruction->InputAt(1), a, b, c, /*depth*/ 0) &&
351 *b != nullptr) {
352 return true;
353 }
354 // Found a + b.
355 *a = instruction->InputAt(0);
356 *b = instruction->InputAt(1);
357 *c = 0;
358 return true;
359 }
360 return false;
361}
362
Aart Bikb29f6842017-07-28 15:58:41 -0700363// Detect reductions of the following forms,
Aart Bikb29f6842017-07-28 15:58:41 -0700364// x = x_phi + ..
365// x = x_phi - ..
366// x = max(x_phi, ..)
367// x = min(x_phi, ..)
368static bool HasReductionFormat(HInstruction* reduction, HInstruction* phi) {
369 if (reduction->IsAdd()) {
Aart Bikdbbac8f2017-09-01 13:06:08 -0700370 return (reduction->InputAt(0) == phi && reduction->InputAt(1) != phi) ||
371 (reduction->InputAt(0) != phi && reduction->InputAt(1) == phi);
Aart Bikb29f6842017-07-28 15:58:41 -0700372 } else if (reduction->IsSub()) {
Aart Bikdbbac8f2017-09-01 13:06:08 -0700373 return (reduction->InputAt(0) == phi && reduction->InputAt(1) != phi);
Aart Bikb29f6842017-07-28 15:58:41 -0700374 } else if (reduction->IsInvokeStaticOrDirect()) {
375 switch (reduction->AsInvokeStaticOrDirect()->GetIntrinsic()) {
376 case Intrinsics::kMathMinIntInt:
377 case Intrinsics::kMathMinLongLong:
378 case Intrinsics::kMathMinFloatFloat:
379 case Intrinsics::kMathMinDoubleDouble:
380 case Intrinsics::kMathMaxIntInt:
381 case Intrinsics::kMathMaxLongLong:
382 case Intrinsics::kMathMaxFloatFloat:
383 case Intrinsics::kMathMaxDoubleDouble:
Aart Bikdbbac8f2017-09-01 13:06:08 -0700384 return (reduction->InputAt(0) == phi && reduction->InputAt(1) != phi) ||
385 (reduction->InputAt(0) != phi && reduction->InputAt(1) == phi);
Aart Bikb29f6842017-07-28 15:58:41 -0700386 default:
387 return false;
388 }
389 }
390 return false;
391}
392
Aart Bikdbbac8f2017-09-01 13:06:08 -0700393// Translates vector operation to reduction kind.
394static HVecReduce::ReductionKind GetReductionKind(HVecOperation* reduction) {
395 if (reduction->IsVecAdd() || reduction->IsVecSub() || reduction->IsVecSADAccumulate()) {
Aart Bik0148de42017-09-05 09:25:01 -0700396 return HVecReduce::kSum;
397 } else if (reduction->IsVecMin()) {
398 return HVecReduce::kMin;
399 } else if (reduction->IsVecMax()) {
400 return HVecReduce::kMax;
401 }
402 LOG(FATAL) << "Unsupported SIMD reduction";
403 UNREACHABLE();
404}
405
Aart Bikf8f5a162017-02-06 15:35:29 -0800406// Test vector restrictions.
407static bool HasVectorRestrictions(uint64_t restrictions, uint64_t tested) {
408 return (restrictions & tested) != 0;
409}
410
Aart Bikf3e61ee2017-04-12 17:09:20 -0700411// Insert an instruction.
Aart Bikf8f5a162017-02-06 15:35:29 -0800412static HInstruction* Insert(HBasicBlock* block, HInstruction* instruction) {
413 DCHECK(block != nullptr);
414 DCHECK(instruction != nullptr);
415 block->InsertInstructionBefore(instruction, block->GetLastInstruction());
416 return instruction;
417}
418
Artem Serov21c7e6f2017-07-27 16:04:42 +0100419// Check that instructions from the induction sets are fully removed: have no uses
420// and no other instructions use them.
421static bool CheckInductionSetFullyRemoved(ArenaSet<HInstruction*>* iset) {
422 for (HInstruction* instr : *iset) {
423 if (instr->GetBlock() != nullptr ||
424 !instr->GetUses().empty() ||
425 !instr->GetEnvUses().empty() ||
426 HasEnvironmentUsedByOthers(instr)) {
427 return false;
428 }
429 }
Artem Serov21c7e6f2017-07-27 16:04:42 +0100430 return true;
431}
432
Aart Bik281c6812016-08-26 11:31:48 -0700433//
Aart Bikb29f6842017-07-28 15:58:41 -0700434// Public methods.
Aart Bik281c6812016-08-26 11:31:48 -0700435//
436
437HLoopOptimization::HLoopOptimization(HGraph* graph,
Aart Bik92685a82017-03-06 11:13:43 -0800438 CompilerDriver* compiler_driver,
Aart Bikb92cc332017-09-06 15:53:17 -0700439 HInductionVarAnalysis* induction_analysis,
440 OptimizingCompilerStats* stats)
441 : HOptimization(graph, kLoopOptimizationPassName, stats),
Aart Bik92685a82017-03-06 11:13:43 -0800442 compiler_driver_(compiler_driver),
Aart Bik281c6812016-08-26 11:31:48 -0700443 induction_range_(induction_analysis),
Aart Bik96202302016-10-04 17:33:56 -0700444 loop_allocator_(nullptr),
Aart Bikf8f5a162017-02-06 15:35:29 -0800445 global_allocator_(graph_->GetArena()),
Aart Bik281c6812016-08-26 11:31:48 -0700446 top_loop_(nullptr),
Aart Bik8c4a8542016-10-06 11:36:57 -0700447 last_loop_(nullptr),
Aart Bik482095d2016-10-10 15:39:10 -0700448 iset_(nullptr),
Aart Bikb29f6842017-07-28 15:58:41 -0700449 reductions_(nullptr),
Aart Bikf8f5a162017-02-06 15:35:29 -0800450 simplified_(false),
451 vector_length_(0),
452 vector_refs_(nullptr),
Aart Bik14a68b42017-06-08 14:06:58 -0700453 vector_peeling_candidate_(nullptr),
454 vector_runtime_test_a_(nullptr),
455 vector_runtime_test_b_(nullptr),
Aart Bik0148de42017-09-05 09:25:01 -0700456 vector_map_(nullptr),
457 vector_permanent_map_(nullptr) {
Aart Bik281c6812016-08-26 11:31:48 -0700458}
459
460void HLoopOptimization::Run() {
Mingyao Yang01b47b02017-02-03 12:09:57 -0800461 // Skip if there is no loop or the graph has try-catch/irreducible loops.
Aart Bik281c6812016-08-26 11:31:48 -0700462 // TODO: make this less of a sledgehammer.
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800463 if (!graph_->HasLoops() || graph_->HasTryCatch() || graph_->HasIrreducibleLoops()) {
Aart Bik281c6812016-08-26 11:31:48 -0700464 return;
465 }
466
Aart Bik96202302016-10-04 17:33:56 -0700467 // Phase-local allocator that draws from the global pool. Since the allocator
468 // itself resides on the stack, it is destructed on exiting Run(), which
469 // implies its underlying memory is released immediately.
Aart Bikf8f5a162017-02-06 15:35:29 -0800470 ArenaAllocator allocator(global_allocator_->GetArenaPool());
Aart Bik96202302016-10-04 17:33:56 -0700471 loop_allocator_ = &allocator;
Nicolas Geoffrayebe16742016-10-05 09:55:42 +0100472
Aart Bik96202302016-10-04 17:33:56 -0700473 // Perform loop optimizations.
474 LocalRun();
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800475 if (top_loop_ == nullptr) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800476 graph_->SetHasLoops(false); // no more loops
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800477 }
478
Aart Bik96202302016-10-04 17:33:56 -0700479 // Detach.
480 loop_allocator_ = nullptr;
481 last_loop_ = top_loop_ = nullptr;
482}
483
Aart Bikb29f6842017-07-28 15:58:41 -0700484//
485// Loop setup and traversal.
486//
487
Aart Bik96202302016-10-04 17:33:56 -0700488void HLoopOptimization::LocalRun() {
489 // Build the linear order using the phase-local allocator. This step enables building
490 // a loop hierarchy that properly reflects the outer-inner and previous-next relation.
491 ArenaVector<HBasicBlock*> linear_order(loop_allocator_->Adapter(kArenaAllocLinearOrder));
492 LinearizeGraph(graph_, loop_allocator_, &linear_order);
493
Aart Bik281c6812016-08-26 11:31:48 -0700494 // Build the loop hierarchy.
Aart Bik96202302016-10-04 17:33:56 -0700495 for (HBasicBlock* block : linear_order) {
Aart Bik281c6812016-08-26 11:31:48 -0700496 if (block->IsLoopHeader()) {
497 AddLoop(block->GetLoopInformation());
498 }
499 }
Aart Bik96202302016-10-04 17:33:56 -0700500
Aart Bik8c4a8542016-10-06 11:36:57 -0700501 // Traverse the loop hierarchy inner-to-outer and optimize. Traversal can use
Aart Bikf8f5a162017-02-06 15:35:29 -0800502 // temporary data structures using the phase-local allocator. All new HIR
503 // should use the global allocator.
Aart Bik8c4a8542016-10-06 11:36:57 -0700504 if (top_loop_ != nullptr) {
505 ArenaSet<HInstruction*> iset(loop_allocator_->Adapter(kArenaAllocLoopOptimization));
Aart Bikb29f6842017-07-28 15:58:41 -0700506 ArenaSafeMap<HInstruction*, HInstruction*> reds(
507 std::less<HInstruction*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
Aart Bikf8f5a162017-02-06 15:35:29 -0800508 ArenaSet<ArrayReference> refs(loop_allocator_->Adapter(kArenaAllocLoopOptimization));
509 ArenaSafeMap<HInstruction*, HInstruction*> map(
510 std::less<HInstruction*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
Aart Bik0148de42017-09-05 09:25:01 -0700511 ArenaSafeMap<HInstruction*, HInstruction*> perm(
512 std::less<HInstruction*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
Aart Bikf8f5a162017-02-06 15:35:29 -0800513 // Attach.
Aart Bik8c4a8542016-10-06 11:36:57 -0700514 iset_ = &iset;
Aart Bikb29f6842017-07-28 15:58:41 -0700515 reductions_ = &reds;
Aart Bikf8f5a162017-02-06 15:35:29 -0800516 vector_refs_ = &refs;
517 vector_map_ = &map;
Aart Bik0148de42017-09-05 09:25:01 -0700518 vector_permanent_map_ = &perm;
Aart Bikf8f5a162017-02-06 15:35:29 -0800519 // Traverse.
Aart Bik8c4a8542016-10-06 11:36:57 -0700520 TraverseLoopsInnerToOuter(top_loop_);
Aart Bikf8f5a162017-02-06 15:35:29 -0800521 // Detach.
522 iset_ = nullptr;
Aart Bikb29f6842017-07-28 15:58:41 -0700523 reductions_ = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800524 vector_refs_ = nullptr;
525 vector_map_ = nullptr;
Aart Bik0148de42017-09-05 09:25:01 -0700526 vector_permanent_map_ = nullptr;
Aart Bik8c4a8542016-10-06 11:36:57 -0700527 }
Aart Bik281c6812016-08-26 11:31:48 -0700528}
529
530void HLoopOptimization::AddLoop(HLoopInformation* loop_info) {
531 DCHECK(loop_info != nullptr);
Aart Bikf8f5a162017-02-06 15:35:29 -0800532 LoopNode* node = new (loop_allocator_) LoopNode(loop_info);
Aart Bik281c6812016-08-26 11:31:48 -0700533 if (last_loop_ == nullptr) {
534 // First loop.
535 DCHECK(top_loop_ == nullptr);
536 last_loop_ = top_loop_ = node;
537 } else if (loop_info->IsIn(*last_loop_->loop_info)) {
538 // Inner loop.
539 node->outer = last_loop_;
540 DCHECK(last_loop_->inner == nullptr);
541 last_loop_ = last_loop_->inner = node;
542 } else {
543 // Subsequent loop.
544 while (last_loop_->outer != nullptr && !loop_info->IsIn(*last_loop_->outer->loop_info)) {
545 last_loop_ = last_loop_->outer;
546 }
547 node->outer = last_loop_->outer;
548 node->previous = last_loop_;
549 DCHECK(last_loop_->next == nullptr);
550 last_loop_ = last_loop_->next = node;
551 }
552}
553
554void HLoopOptimization::RemoveLoop(LoopNode* node) {
555 DCHECK(node != nullptr);
Aart Bik8c4a8542016-10-06 11:36:57 -0700556 DCHECK(node->inner == nullptr);
557 if (node->previous != nullptr) {
558 // Within sequence.
559 node->previous->next = node->next;
560 if (node->next != nullptr) {
561 node->next->previous = node->previous;
562 }
563 } else {
564 // First of sequence.
565 if (node->outer != nullptr) {
566 node->outer->inner = node->next;
567 } else {
568 top_loop_ = node->next;
569 }
570 if (node->next != nullptr) {
571 node->next->outer = node->outer;
572 node->next->previous = nullptr;
573 }
574 }
Aart Bik281c6812016-08-26 11:31:48 -0700575}
576
Aart Bikb29f6842017-07-28 15:58:41 -0700577bool HLoopOptimization::TraverseLoopsInnerToOuter(LoopNode* node) {
578 bool changed = false;
Aart Bik281c6812016-08-26 11:31:48 -0700579 for ( ; node != nullptr; node = node->next) {
Aart Bikb29f6842017-07-28 15:58:41 -0700580 // Visit inner loops first. Recompute induction information for this
581 // loop if the induction of any inner loop has changed.
582 if (TraverseLoopsInnerToOuter(node->inner)) {
Aart Bik482095d2016-10-10 15:39:10 -0700583 induction_range_.ReVisit(node->loop_info);
584 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800585 // Repeat simplifications in the loop-body until no more changes occur.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800586 // Note that since each simplification consists of eliminating code (without
587 // introducing new code), this process is always finite.
Aart Bikdf7822e2016-12-06 10:05:30 -0800588 do {
589 simplified_ = false;
Aart Bikdf7822e2016-12-06 10:05:30 -0800590 SimplifyInduction(node);
Aart Bik6b69e0a2017-01-11 10:20:43 -0800591 SimplifyBlocks(node);
Aart Bikb29f6842017-07-28 15:58:41 -0700592 changed = simplified_ || changed;
Aart Bikdf7822e2016-12-06 10:05:30 -0800593 } while (simplified_);
Aart Bikf8f5a162017-02-06 15:35:29 -0800594 // Optimize inner loop.
Aart Bik9abf8942016-10-14 09:49:42 -0700595 if (node->inner == nullptr) {
Aart Bikb29f6842017-07-28 15:58:41 -0700596 changed = OptimizeInnerLoop(node) || changed;
Aart Bik9abf8942016-10-14 09:49:42 -0700597 }
Aart Bik281c6812016-08-26 11:31:48 -0700598 }
Aart Bikb29f6842017-07-28 15:58:41 -0700599 return changed;
Aart Bik281c6812016-08-26 11:31:48 -0700600}
601
Aart Bikf8f5a162017-02-06 15:35:29 -0800602//
603// Optimization.
604//
605
Aart Bik281c6812016-08-26 11:31:48 -0700606void HLoopOptimization::SimplifyInduction(LoopNode* node) {
607 HBasicBlock* header = node->loop_info->GetHeader();
608 HBasicBlock* preheader = node->loop_info->GetPreHeader();
Aart Bik8c4a8542016-10-06 11:36:57 -0700609 // Scan the phis in the header to find opportunities to simplify an induction
610 // cycle that is only used outside the loop. Replace these uses, if any, with
611 // the last value and remove the induction cycle.
612 // Examples: for (int i = 0; x != null; i++) { .... no i .... }
613 // for (int i = 0; i < 10; i++, k++) { .... no k .... } return k;
Aart Bik281c6812016-08-26 11:31:48 -0700614 for (HInstructionIterator it(header->GetPhis()); !it.Done(); it.Advance()) {
615 HPhi* phi = it.Current()->AsPhi();
Aart Bikf8f5a162017-02-06 15:35:29 -0800616 if (TrySetPhiInduction(phi, /*restrict_uses*/ true) &&
617 TryAssignLastValue(node->loop_info, phi, preheader, /*collect_loop_uses*/ false)) {
Aart Bik671e48a2017-08-09 13:16:56 -0700618 // Note that it's ok to have replaced uses after the loop with the last value, without
619 // being able to remove the cycle. Environment uses (which are the reason we may not be
620 // able to remove the cycle) within the loop will still hold the right value. We must
621 // have tried first, however, to replace outside uses.
622 if (CanRemoveCycle()) {
623 simplified_ = true;
624 for (HInstruction* i : *iset_) {
625 RemoveFromCycle(i);
626 }
627 DCHECK(CheckInductionSetFullyRemoved(iset_));
Aart Bik281c6812016-08-26 11:31:48 -0700628 }
Aart Bik482095d2016-10-10 15:39:10 -0700629 }
630 }
631}
632
633void HLoopOptimization::SimplifyBlocks(LoopNode* node) {
Aart Bikdf7822e2016-12-06 10:05:30 -0800634 // Iterate over all basic blocks in the loop-body.
635 for (HBlocksInLoopIterator it(*node->loop_info); !it.Done(); it.Advance()) {
636 HBasicBlock* block = it.Current();
637 // Remove dead instructions from the loop-body.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800638 RemoveDeadInstructions(block->GetPhis());
639 RemoveDeadInstructions(block->GetInstructions());
Aart Bikdf7822e2016-12-06 10:05:30 -0800640 // Remove trivial control flow blocks from the loop-body.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800641 if (block->GetPredecessors().size() == 1 &&
642 block->GetSuccessors().size() == 1 &&
643 block->GetSingleSuccessor()->GetPredecessors().size() == 1) {
Aart Bikdf7822e2016-12-06 10:05:30 -0800644 simplified_ = true;
Aart Bik6b69e0a2017-01-11 10:20:43 -0800645 block->MergeWith(block->GetSingleSuccessor());
Aart Bikdf7822e2016-12-06 10:05:30 -0800646 } else if (block->GetSuccessors().size() == 2) {
647 // Trivial if block can be bypassed to either branch.
648 HBasicBlock* succ0 = block->GetSuccessors()[0];
649 HBasicBlock* succ1 = block->GetSuccessors()[1];
650 HBasicBlock* meet0 = nullptr;
651 HBasicBlock* meet1 = nullptr;
652 if (succ0 != succ1 &&
653 IsGotoBlock(succ0, &meet0) &&
654 IsGotoBlock(succ1, &meet1) &&
655 meet0 == meet1 && // meets again
656 meet0 != block && // no self-loop
657 meet0->GetPhis().IsEmpty()) { // not used for merging
658 simplified_ = true;
659 succ0->DisconnectAndDelete();
660 if (block->Dominates(meet0)) {
661 block->RemoveDominatedBlock(meet0);
662 succ1->AddDominatedBlock(meet0);
663 meet0->SetDominator(succ1);
Aart Bike3dedc52016-11-02 17:50:27 -0700664 }
Aart Bik482095d2016-10-10 15:39:10 -0700665 }
Aart Bik281c6812016-08-26 11:31:48 -0700666 }
Aart Bikdf7822e2016-12-06 10:05:30 -0800667 }
Aart Bik281c6812016-08-26 11:31:48 -0700668}
669
Aart Bikb29f6842017-07-28 15:58:41 -0700670bool HLoopOptimization::OptimizeInnerLoop(LoopNode* node) {
Aart Bik281c6812016-08-26 11:31:48 -0700671 HBasicBlock* header = node->loop_info->GetHeader();
672 HBasicBlock* preheader = node->loop_info->GetPreHeader();
Aart Bik9abf8942016-10-14 09:49:42 -0700673 // Ensure loop header logic is finite.
Aart Bikf8f5a162017-02-06 15:35:29 -0800674 int64_t trip_count = 0;
675 if (!induction_range_.IsFinite(node->loop_info, &trip_count)) {
Aart Bikb29f6842017-07-28 15:58:41 -0700676 return false;
Aart Bik9abf8942016-10-14 09:49:42 -0700677 }
Aart Bik281c6812016-08-26 11:31:48 -0700678 // Ensure there is only a single loop-body (besides the header).
679 HBasicBlock* body = nullptr;
680 for (HBlocksInLoopIterator it(*node->loop_info); !it.Done(); it.Advance()) {
681 if (it.Current() != header) {
682 if (body != nullptr) {
Aart Bikb29f6842017-07-28 15:58:41 -0700683 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700684 }
685 body = it.Current();
686 }
687 }
Andreas Gampef45d61c2017-06-07 10:29:33 -0700688 CHECK(body != nullptr);
Aart Bik281c6812016-08-26 11:31:48 -0700689 // Ensure there is only a single exit point.
690 if (header->GetSuccessors().size() != 2) {
Aart Bikb29f6842017-07-28 15:58:41 -0700691 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700692 }
693 HBasicBlock* exit = (header->GetSuccessors()[0] == body)
694 ? header->GetSuccessors()[1]
695 : header->GetSuccessors()[0];
Aart Bik8c4a8542016-10-06 11:36:57 -0700696 // Ensure exit can only be reached by exiting loop.
Aart Bik281c6812016-08-26 11:31:48 -0700697 if (exit->GetPredecessors().size() != 1) {
Aart Bikb29f6842017-07-28 15:58:41 -0700698 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700699 }
Aart Bik6b69e0a2017-01-11 10:20:43 -0800700 // Detect either an empty loop (no side effects other than plain iteration) or
701 // a trivial loop (just iterating once). Replace subsequent index uses, if any,
702 // with the last value and remove the loop, possibly after unrolling its body.
Aart Bikb29f6842017-07-28 15:58:41 -0700703 HPhi* main_phi = nullptr;
704 if (TrySetSimpleLoopHeader(header, &main_phi)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -0800705 bool is_empty = IsEmptyBody(body);
Aart Bikb29f6842017-07-28 15:58:41 -0700706 if (reductions_->empty() && // TODO: possible with some effort
707 (is_empty || trip_count == 1) &&
708 TryAssignLastValue(node->loop_info, main_phi, preheader, /*collect_loop_uses*/ true)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -0800709 if (!is_empty) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800710 // Unroll the loop-body, which sees initial value of the index.
Aart Bikb29f6842017-07-28 15:58:41 -0700711 main_phi->ReplaceWith(main_phi->InputAt(0));
Aart Bik6b69e0a2017-01-11 10:20:43 -0800712 preheader->MergeInstructionsWith(body);
713 }
714 body->DisconnectAndDelete();
715 exit->RemovePredecessor(header);
716 header->RemoveSuccessor(exit);
717 header->RemoveDominatedBlock(exit);
718 header->DisconnectAndDelete();
719 preheader->AddSuccessor(exit);
Aart Bikf8f5a162017-02-06 15:35:29 -0800720 preheader->AddInstruction(new (global_allocator_) HGoto());
Aart Bik6b69e0a2017-01-11 10:20:43 -0800721 preheader->AddDominatedBlock(exit);
722 exit->SetDominator(preheader);
723 RemoveLoop(node); // update hierarchy
Aart Bikb29f6842017-07-28 15:58:41 -0700724 return true;
Aart Bikf8f5a162017-02-06 15:35:29 -0800725 }
726 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800727 // Vectorize loop, if possible and valid.
Aart Bikb29f6842017-07-28 15:58:41 -0700728 if (kEnableVectorization &&
729 TrySetSimpleLoopHeader(header, &main_phi) &&
Aart Bikb29f6842017-07-28 15:58:41 -0700730 ShouldVectorize(node, body, trip_count) &&
731 TryAssignLastValue(node->loop_info, main_phi, preheader, /*collect_loop_uses*/ true)) {
732 Vectorize(node, body, exit, trip_count);
733 graph_->SetHasSIMD(true); // flag SIMD usage
Aart Bik21b85922017-09-06 13:29:16 -0700734 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorized);
Aart Bikb29f6842017-07-28 15:58:41 -0700735 return true;
Aart Bikf8f5a162017-02-06 15:35:29 -0800736 }
Aart Bikb29f6842017-07-28 15:58:41 -0700737 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -0800738}
739
740//
741// Loop vectorization. The implementation is based on the book by Aart J.C. Bik:
742// "The Software Vectorization Handbook. Applying Multimedia Extensions for Maximum Performance."
743// Intel Press, June, 2004 (http://www.aartbik.com/).
744//
745
Aart Bik14a68b42017-06-08 14:06:58 -0700746bool HLoopOptimization::ShouldVectorize(LoopNode* node, HBasicBlock* block, int64_t trip_count) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800747 // Reset vector bookkeeping.
748 vector_length_ = 0;
749 vector_refs_->clear();
Aart Bik14a68b42017-06-08 14:06:58 -0700750 vector_peeling_candidate_ = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800751 vector_runtime_test_a_ =
752 vector_runtime_test_b_= nullptr;
753
754 // Phis in the loop-body prevent vectorization.
755 if (!block->GetPhis().IsEmpty()) {
756 return false;
757 }
758
759 // Scan the loop-body, starting a right-hand-side tree traversal at each left-hand-side
760 // occurrence, which allows passing down attributes down the use tree.
761 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
762 if (!VectorizeDef(node, it.Current(), /*generate_code*/ false)) {
763 return false; // failure to vectorize a left-hand-side
764 }
765 }
766
Aart Bik14a68b42017-06-08 14:06:58 -0700767 // Does vectorization seem profitable?
768 if (!IsVectorizationProfitable(trip_count)) {
769 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -0800770 }
771
772 // Data dependence analysis. Find each pair of references with same type, where
773 // at least one is a write. Each such pair denotes a possible data dependence.
774 // This analysis exploits the property that differently typed arrays cannot be
775 // aliased, as well as the property that references either point to the same
776 // array or to two completely disjoint arrays, i.e., no partial aliasing.
777 // Other than a few simply heuristics, no detailed subscript analysis is done.
Aart Bikb29f6842017-07-28 15:58:41 -0700778 // The scan over references also finds a suitable dynamic loop peeling candidate.
779 const ArrayReference* candidate = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800780 for (auto i = vector_refs_->begin(); i != vector_refs_->end(); ++i) {
781 for (auto j = i; ++j != vector_refs_->end(); ) {
782 if (i->type == j->type && (i->lhs || j->lhs)) {
783 // Found same-typed a[i+x] vs. b[i+y], where at least one is a write.
784 HInstruction* a = i->base;
785 HInstruction* b = j->base;
786 HInstruction* x = i->offset;
787 HInstruction* y = j->offset;
788 if (a == b) {
789 // Found a[i+x] vs. a[i+y]. Accept if x == y (loop-independent data dependence).
790 // Conservatively assume a loop-carried data dependence otherwise, and reject.
791 if (x != y) {
792 return false;
793 }
794 } else {
795 // Found a[i+x] vs. b[i+y]. Accept if x == y (at worst loop-independent data dependence).
796 // Conservatively assume a potential loop-carried data dependence otherwise, avoided by
797 // generating an explicit a != b disambiguation runtime test on the two references.
798 if (x != y) {
Aart Bik37dc4df2017-06-28 14:08:00 -0700799 // To avoid excessive overhead, we only accept one a != b test.
800 if (vector_runtime_test_a_ == nullptr) {
801 // First test found.
802 vector_runtime_test_a_ = a;
803 vector_runtime_test_b_ = b;
804 } else if ((vector_runtime_test_a_ != a || vector_runtime_test_b_ != b) &&
805 (vector_runtime_test_a_ != b || vector_runtime_test_b_ != a)) {
806 return false; // second test would be needed
Aart Bikf8f5a162017-02-06 15:35:29 -0800807 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800808 }
809 }
810 }
811 }
812 }
813
Aart Bik14a68b42017-06-08 14:06:58 -0700814 // Consider dynamic loop peeling for alignment.
Aart Bikb29f6842017-07-28 15:58:41 -0700815 SetPeelingCandidate(candidate, trip_count);
Aart Bik14a68b42017-06-08 14:06:58 -0700816
Aart Bikf8f5a162017-02-06 15:35:29 -0800817 // Success!
818 return true;
819}
820
821void HLoopOptimization::Vectorize(LoopNode* node,
822 HBasicBlock* block,
823 HBasicBlock* exit,
824 int64_t trip_count) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800825 HBasicBlock* header = node->loop_info->GetHeader();
826 HBasicBlock* preheader = node->loop_info->GetPreHeader();
827
Aart Bik14a68b42017-06-08 14:06:58 -0700828 // Pick a loop unrolling factor for the vector loop.
829 uint32_t unroll = GetUnrollingFactor(block, trip_count);
830 uint32_t chunk = vector_length_ * unroll;
831
832 // A cleanup loop is needed, at least, for any unknown trip count or
833 // for a known trip count with remainder iterations after vectorization.
834 bool needs_cleanup = trip_count == 0 || (trip_count % chunk) != 0;
Aart Bikf8f5a162017-02-06 15:35:29 -0800835
836 // Adjust vector bookkeeping.
Aart Bikb29f6842017-07-28 15:58:41 -0700837 HPhi* main_phi = nullptr;
838 bool is_simple_loop_header = TrySetSimpleLoopHeader(header, &main_phi); // refills sets
Aart Bikf8f5a162017-02-06 15:35:29 -0800839 DCHECK(is_simple_loop_header);
Aart Bik14a68b42017-06-08 14:06:58 -0700840 vector_header_ = header;
841 vector_body_ = block;
Aart Bikf8f5a162017-02-06 15:35:29 -0800842
Aart Bikdbbac8f2017-09-01 13:06:08 -0700843 // Loop induction type.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100844 DataType::Type induc_type = main_phi->GetType();
845 DCHECK(induc_type == DataType::Type::kInt32 || induc_type == DataType::Type::kInt64)
846 << induc_type;
Aart Bikdbbac8f2017-09-01 13:06:08 -0700847
Aart Bikb29f6842017-07-28 15:58:41 -0700848 // Generate dynamic loop peeling trip count, if needed, under the assumption
849 // that the Android runtime guarantees at least "component size" alignment:
850 // ptc = (ALIGN - (&a[initial] % ALIGN)) / type-size
Aart Bik14a68b42017-06-08 14:06:58 -0700851 HInstruction* ptc = nullptr;
852 if (vector_peeling_candidate_ != nullptr) {
853 DCHECK_LT(vector_length_, trip_count) << "dynamic peeling currently requires known trip count";
854 //
855 // TODO: Implement this. Compute address of first access memory location and
856 // compute peeling factor to obtain kAlignedBase alignment.
857 //
858 needs_cleanup = true;
859 }
860
861 // Generate loop control:
Aart Bikf8f5a162017-02-06 15:35:29 -0800862 // stc = <trip-count>;
Aart Bik14a68b42017-06-08 14:06:58 -0700863 // vtc = stc - (stc - ptc) % chunk;
864 // i = 0;
Aart Bikf8f5a162017-02-06 15:35:29 -0800865 HInstruction* stc = induction_range_.GenerateTripCount(node->loop_info, graph_, preheader);
866 HInstruction* vtc = stc;
867 if (needs_cleanup) {
Aart Bik14a68b42017-06-08 14:06:58 -0700868 DCHECK(IsPowerOfTwo(chunk));
869 HInstruction* diff = stc;
870 if (ptc != nullptr) {
871 diff = Insert(preheader, new (global_allocator_) HSub(induc_type, stc, ptc));
872 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800873 HInstruction* rem = Insert(
874 preheader, new (global_allocator_) HAnd(induc_type,
Aart Bik14a68b42017-06-08 14:06:58 -0700875 diff,
Aart Bikdbbac8f2017-09-01 13:06:08 -0700876 graph_->GetConstant(induc_type, chunk - 1)));
Aart Bikf8f5a162017-02-06 15:35:29 -0800877 vtc = Insert(preheader, new (global_allocator_) HSub(induc_type, stc, rem));
878 }
Aart Bikdbbac8f2017-09-01 13:06:08 -0700879 vector_index_ = graph_->GetConstant(induc_type, 0);
Aart Bikf8f5a162017-02-06 15:35:29 -0800880
881 // Generate runtime disambiguation test:
882 // vtc = a != b ? vtc : 0;
883 if (vector_runtime_test_a_ != nullptr) {
884 HInstruction* rt = Insert(
885 preheader,
886 new (global_allocator_) HNotEqual(vector_runtime_test_a_, vector_runtime_test_b_));
887 vtc = Insert(preheader,
Aart Bikdbbac8f2017-09-01 13:06:08 -0700888 new (global_allocator_)
889 HSelect(rt, vtc, graph_->GetConstant(induc_type, 0), kNoDexPc));
Aart Bikf8f5a162017-02-06 15:35:29 -0800890 needs_cleanup = true;
891 }
892
Aart Bik14a68b42017-06-08 14:06:58 -0700893 // Generate dynamic peeling loop for alignment, if needed:
894 // for ( ; i < ptc; i += 1)
895 // <loop-body>
896 if (ptc != nullptr) {
897 vector_mode_ = kSequential;
898 GenerateNewLoop(node,
899 block,
900 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
901 vector_index_,
902 ptc,
Aart Bikdbbac8f2017-09-01 13:06:08 -0700903 graph_->GetConstant(induc_type, 1),
Aart Bik521b50f2017-09-09 10:44:45 -0700904 kNoUnrollingFactor);
Aart Bik14a68b42017-06-08 14:06:58 -0700905 }
906
907 // Generate vector loop, possibly further unrolled:
908 // for ( ; i < vtc; i += chunk)
Aart Bikf8f5a162017-02-06 15:35:29 -0800909 // <vectorized-loop-body>
910 vector_mode_ = kVector;
911 GenerateNewLoop(node,
912 block,
Aart Bik14a68b42017-06-08 14:06:58 -0700913 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
914 vector_index_,
Aart Bikf8f5a162017-02-06 15:35:29 -0800915 vtc,
Aart Bikdbbac8f2017-09-01 13:06:08 -0700916 graph_->GetConstant(induc_type, vector_length_), // increment per unroll
Aart Bik14a68b42017-06-08 14:06:58 -0700917 unroll);
Aart Bikf8f5a162017-02-06 15:35:29 -0800918 HLoopInformation* vloop = vector_header_->GetLoopInformation();
919
920 // Generate cleanup loop, if needed:
921 // for ( ; i < stc; i += 1)
922 // <loop-body>
923 if (needs_cleanup) {
924 vector_mode_ = kSequential;
925 GenerateNewLoop(node,
926 block,
927 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
Aart Bik14a68b42017-06-08 14:06:58 -0700928 vector_index_,
Aart Bikf8f5a162017-02-06 15:35:29 -0800929 stc,
Aart Bikdbbac8f2017-09-01 13:06:08 -0700930 graph_->GetConstant(induc_type, 1),
Aart Bik521b50f2017-09-09 10:44:45 -0700931 kNoUnrollingFactor);
Aart Bikf8f5a162017-02-06 15:35:29 -0800932 }
933
Aart Bik0148de42017-09-05 09:25:01 -0700934 // Link reductions to their final uses.
935 for (auto i = reductions_->begin(); i != reductions_->end(); ++i) {
936 if (i->first->IsPhi()) {
Aart Bikdbbac8f2017-09-01 13:06:08 -0700937 HInstruction* phi = i->first;
938 HInstruction* repl = ReduceAndExtractIfNeeded(i->second);
939 // Deal with regular uses.
940 for (const HUseListNode<HInstruction*>& use : phi->GetUses()) {
941 induction_range_.Replace(use.GetUser(), phi, repl); // update induction use
942 }
943 phi->ReplaceWith(repl);
Aart Bik0148de42017-09-05 09:25:01 -0700944 }
945 }
946
Aart Bikf8f5a162017-02-06 15:35:29 -0800947 // Remove the original loop by disconnecting the body block
948 // and removing all instructions from the header.
949 block->DisconnectAndDelete();
950 while (!header->GetFirstInstruction()->IsGoto()) {
951 header->RemoveInstruction(header->GetFirstInstruction());
952 }
Aart Bikb29f6842017-07-28 15:58:41 -0700953
Aart Bik14a68b42017-06-08 14:06:58 -0700954 // Update loop hierarchy: the old header now resides in the same outer loop
955 // as the old preheader. Note that we don't bother putting sequential
956 // loops back in the hierarchy at this point.
Aart Bikf8f5a162017-02-06 15:35:29 -0800957 header->SetLoopInformation(preheader->GetLoopInformation()); // outward
958 node->loop_info = vloop;
959}
960
961void HLoopOptimization::GenerateNewLoop(LoopNode* node,
962 HBasicBlock* block,
963 HBasicBlock* new_preheader,
964 HInstruction* lo,
965 HInstruction* hi,
Aart Bik14a68b42017-06-08 14:06:58 -0700966 HInstruction* step,
967 uint32_t unroll) {
968 DCHECK(unroll == 1 || vector_mode_ == kVector);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100969 DataType::Type induc_type = lo->GetType();
Aart Bikf8f5a162017-02-06 15:35:29 -0800970 // Prepare new loop.
Aart Bikf8f5a162017-02-06 15:35:29 -0800971 vector_preheader_ = new_preheader,
972 vector_header_ = vector_preheader_->GetSingleSuccessor();
973 vector_body_ = vector_header_->GetSuccessors()[1];
Aart Bik14a68b42017-06-08 14:06:58 -0700974 HPhi* phi = new (global_allocator_) HPhi(global_allocator_,
975 kNoRegNumber,
976 0,
977 HPhi::ToPhiType(induc_type));
Aart Bikb07d1bc2017-04-05 10:03:15 -0700978 // Generate header and prepare body.
Aart Bikf8f5a162017-02-06 15:35:29 -0800979 // for (i = lo; i < hi; i += step)
980 // <loop-body>
Aart Bik14a68b42017-06-08 14:06:58 -0700981 HInstruction* cond = new (global_allocator_) HAboveOrEqual(phi, hi);
982 vector_header_->AddPhi(phi);
Aart Bikf8f5a162017-02-06 15:35:29 -0800983 vector_header_->AddInstruction(cond);
984 vector_header_->AddInstruction(new (global_allocator_) HIf(cond));
Aart Bik14a68b42017-06-08 14:06:58 -0700985 vector_index_ = phi;
Aart Bik0148de42017-09-05 09:25:01 -0700986 vector_permanent_map_->clear(); // preserved over unrolling
Aart Bik14a68b42017-06-08 14:06:58 -0700987 for (uint32_t u = 0; u < unroll; u++) {
Aart Bik14a68b42017-06-08 14:06:58 -0700988 // Generate instruction map.
Aart Bik0148de42017-09-05 09:25:01 -0700989 vector_map_->clear();
Aart Bik14a68b42017-06-08 14:06:58 -0700990 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
991 bool vectorized_def = VectorizeDef(node, it.Current(), /*generate_code*/ true);
992 DCHECK(vectorized_def);
993 }
994 // Generate body from the instruction map, but in original program order.
995 HEnvironment* env = vector_header_->GetFirstInstruction()->GetEnvironment();
996 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
997 auto i = vector_map_->find(it.Current());
998 if (i != vector_map_->end() && !i->second->IsInBlock()) {
999 Insert(vector_body_, i->second);
1000 // Deal with instructions that need an environment, such as the scalar intrinsics.
1001 if (i->second->NeedsEnvironment()) {
1002 i->second->CopyEnvironmentFromWithLoopPhiAdjustment(env, vector_header_);
1003 }
1004 }
1005 }
Aart Bik0148de42017-09-05 09:25:01 -07001006 // Generate the induction.
Aart Bik14a68b42017-06-08 14:06:58 -07001007 vector_index_ = new (global_allocator_) HAdd(induc_type, vector_index_, step);
1008 Insert(vector_body_, vector_index_);
Aart Bikf8f5a162017-02-06 15:35:29 -08001009 }
Aart Bik0148de42017-09-05 09:25:01 -07001010 // Finalize phi inputs for the reductions (if any).
1011 for (auto i = reductions_->begin(); i != reductions_->end(); ++i) {
1012 if (!i->first->IsPhi()) {
1013 DCHECK(i->second->IsPhi());
1014 GenerateVecReductionPhiInputs(i->second->AsPhi(), i->first);
1015 }
1016 }
Aart Bikb29f6842017-07-28 15:58:41 -07001017 // Finalize phi inputs for the loop index.
Aart Bik14a68b42017-06-08 14:06:58 -07001018 phi->AddInput(lo);
1019 phi->AddInput(vector_index_);
1020 vector_index_ = phi;
Aart Bikf8f5a162017-02-06 15:35:29 -08001021}
1022
Aart Bikf8f5a162017-02-06 15:35:29 -08001023bool HLoopOptimization::VectorizeDef(LoopNode* node,
1024 HInstruction* instruction,
1025 bool generate_code) {
1026 // Accept a left-hand-side array base[index] for
1027 // (1) supported vector type,
1028 // (2) loop-invariant base,
1029 // (3) unit stride index,
1030 // (4) vectorizable right-hand-side value.
1031 uint64_t restrictions = kNone;
1032 if (instruction->IsArraySet()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001033 DataType::Type type = instruction->AsArraySet()->GetComponentType();
Aart Bikf8f5a162017-02-06 15:35:29 -08001034 HInstruction* base = instruction->InputAt(0);
1035 HInstruction* index = instruction->InputAt(1);
1036 HInstruction* value = instruction->InputAt(2);
1037 HInstruction* offset = nullptr;
1038 if (TrySetVectorType(type, &restrictions) &&
1039 node->loop_info->IsDefinedOutOfTheLoop(base) &&
Aart Bik37dc4df2017-06-28 14:08:00 -07001040 induction_range_.IsUnitStride(instruction, index, graph_, &offset) &&
Aart Bikf8f5a162017-02-06 15:35:29 -08001041 VectorizeUse(node, value, generate_code, type, restrictions)) {
1042 if (generate_code) {
1043 GenerateVecSub(index, offset);
Aart Bik14a68b42017-06-08 14:06:58 -07001044 GenerateVecMem(instruction, vector_map_->Get(index), vector_map_->Get(value), offset, type);
Aart Bikf8f5a162017-02-06 15:35:29 -08001045 } else {
1046 vector_refs_->insert(ArrayReference(base, offset, type, /*lhs*/ true));
1047 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08001048 return true;
1049 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001050 return false;
1051 }
Aart Bik0148de42017-09-05 09:25:01 -07001052 // Accept a left-hand-side reduction for
1053 // (1) supported vector type,
1054 // (2) vectorizable right-hand-side value.
1055 auto redit = reductions_->find(instruction);
1056 if (redit != reductions_->end()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001057 DataType::Type type = instruction->GetType();
Aart Bikdbbac8f2017-09-01 13:06:08 -07001058 // Recognize SAD idiom or direct reduction.
1059 if (VectorizeSADIdiom(node, instruction, generate_code, type, restrictions) ||
1060 (TrySetVectorType(type, &restrictions) &&
1061 VectorizeUse(node, instruction, generate_code, type, restrictions))) {
Aart Bik0148de42017-09-05 09:25:01 -07001062 if (generate_code) {
1063 HInstruction* new_red = vector_map_->Get(instruction);
1064 vector_permanent_map_->Put(new_red, vector_map_->Get(redit->second));
1065 vector_permanent_map_->Overwrite(redit->second, new_red);
1066 }
1067 return true;
1068 }
1069 return false;
1070 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001071 // Branch back okay.
1072 if (instruction->IsGoto()) {
1073 return true;
1074 }
1075 // Otherwise accept only expressions with no effects outside the immediate loop-body.
1076 // Note that actual uses are inspected during right-hand-side tree traversal.
1077 return !IsUsedOutsideLoop(node->loop_info, instruction) && !instruction->DoesAnyWrite();
1078}
1079
Aart Bik304c8a52017-05-23 11:01:13 -07001080// TODO: saturation arithmetic.
Aart Bikf8f5a162017-02-06 15:35:29 -08001081bool HLoopOptimization::VectorizeUse(LoopNode* node,
1082 HInstruction* instruction,
1083 bool generate_code,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001084 DataType::Type type,
Aart Bikf8f5a162017-02-06 15:35:29 -08001085 uint64_t restrictions) {
1086 // Accept anything for which code has already been generated.
1087 if (generate_code) {
1088 if (vector_map_->find(instruction) != vector_map_->end()) {
1089 return true;
1090 }
1091 }
1092 // Continue the right-hand-side tree traversal, passing in proper
1093 // types and vector restrictions along the way. During code generation,
1094 // all new nodes are drawn from the global allocator.
1095 if (node->loop_info->IsDefinedOutOfTheLoop(instruction)) {
1096 // Accept invariant use, using scalar expansion.
1097 if (generate_code) {
1098 GenerateVecInv(instruction, type);
1099 }
1100 return true;
1101 } else if (instruction->IsArrayGet()) {
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001102 // Deal with vector restrictions.
1103 if (instruction->AsArrayGet()->IsStringCharAt() &&
1104 HasVectorRestrictions(restrictions, kNoStringCharAt)) {
1105 return false;
1106 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001107 // Accept a right-hand-side array base[index] for
1108 // (1) exact matching vector type,
1109 // (2) loop-invariant base,
1110 // (3) unit stride index,
1111 // (4) vectorizable right-hand-side value.
1112 HInstruction* base = instruction->InputAt(0);
1113 HInstruction* index = instruction->InputAt(1);
1114 HInstruction* offset = nullptr;
1115 if (type == instruction->GetType() &&
1116 node->loop_info->IsDefinedOutOfTheLoop(base) &&
Aart Bik37dc4df2017-06-28 14:08:00 -07001117 induction_range_.IsUnitStride(instruction, index, graph_, &offset)) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001118 if (generate_code) {
1119 GenerateVecSub(index, offset);
Aart Bik14a68b42017-06-08 14:06:58 -07001120 GenerateVecMem(instruction, vector_map_->Get(index), nullptr, offset, type);
Aart Bikf8f5a162017-02-06 15:35:29 -08001121 } else {
1122 vector_refs_->insert(ArrayReference(base, offset, type, /*lhs*/ false));
1123 }
1124 return true;
1125 }
Aart Bik0148de42017-09-05 09:25:01 -07001126 } else if (instruction->IsPhi()) {
1127 // Accept particular phi operations.
1128 if (reductions_->find(instruction) != reductions_->end()) {
1129 // Deal with vector restrictions.
1130 if (HasVectorRestrictions(restrictions, kNoReduction)) {
1131 return false;
1132 }
1133 // Accept a reduction.
1134 if (generate_code) {
1135 GenerateVecReductionPhi(instruction->AsPhi());
1136 }
1137 return true;
1138 }
1139 // TODO: accept right-hand-side induction?
1140 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001141 } else if (instruction->IsTypeConversion()) {
1142 // Accept particular type conversions.
1143 HTypeConversion* conversion = instruction->AsTypeConversion();
1144 HInstruction* opa = conversion->InputAt(0);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001145 DataType::Type from = conversion->GetInputType();
1146 DataType::Type to = conversion->GetResultType();
1147 if (DataType::IsIntegralType(from) && DataType::IsIntegralType(to)) {
1148 size_t size_vec = DataType::Size(type);
1149 size_t size_from = DataType::Size(from);
1150 size_t size_to = DataType::Size(to);
Aart Bikdbbac8f2017-09-01 13:06:08 -07001151 // Accept an integral conversion
1152 // (1a) narrowing into vector type, "wider" operations cannot bring in higher order bits, or
1153 // (1b) widening from at least vector type, and
1154 // (2) vectorizable operand.
1155 if ((size_to < size_from &&
1156 size_to == size_vec &&
1157 VectorizeUse(node, opa, generate_code, type, restrictions | kNoHiBits)) ||
1158 (size_to >= size_from &&
1159 size_from >= size_vec &&
1160 VectorizeUse(node, opa, generate_code, type, restrictions))) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001161 if (generate_code) {
1162 if (vector_mode_ == kVector) {
1163 vector_map_->Put(instruction, vector_map_->Get(opa)); // operand pass-through
1164 } else {
1165 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1166 }
1167 }
1168 return true;
1169 }
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001170 } else if (to == DataType::Type::kFloat32 && from == DataType::Type::kInt32) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001171 DCHECK_EQ(to, type);
1172 // Accept int to float conversion for
1173 // (1) supported int,
1174 // (2) vectorizable operand.
1175 if (TrySetVectorType(from, &restrictions) &&
1176 VectorizeUse(node, opa, generate_code, from, restrictions)) {
1177 if (generate_code) {
1178 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1179 }
1180 return true;
1181 }
1182 }
1183 return false;
1184 } else if (instruction->IsNeg() || instruction->IsNot() || instruction->IsBooleanNot()) {
1185 // Accept unary operator for vectorizable operand.
1186 HInstruction* opa = instruction->InputAt(0);
1187 if (VectorizeUse(node, opa, generate_code, type, restrictions)) {
1188 if (generate_code) {
1189 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1190 }
1191 return true;
1192 }
1193 } else if (instruction->IsAdd() || instruction->IsSub() ||
1194 instruction->IsMul() || instruction->IsDiv() ||
1195 instruction->IsAnd() || instruction->IsOr() || instruction->IsXor()) {
1196 // Deal with vector restrictions.
1197 if ((instruction->IsMul() && HasVectorRestrictions(restrictions, kNoMul)) ||
1198 (instruction->IsDiv() && HasVectorRestrictions(restrictions, kNoDiv))) {
1199 return false;
1200 }
1201 // Accept binary operator for vectorizable operands.
1202 HInstruction* opa = instruction->InputAt(0);
1203 HInstruction* opb = instruction->InputAt(1);
1204 if (VectorizeUse(node, opa, generate_code, type, restrictions) &&
1205 VectorizeUse(node, opb, generate_code, type, restrictions)) {
1206 if (generate_code) {
1207 GenerateVecOp(instruction, vector_map_->Get(opa), vector_map_->Get(opb), type);
1208 }
1209 return true;
1210 }
1211 } else if (instruction->IsShl() || instruction->IsShr() || instruction->IsUShr()) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001212 // Recognize halving add idiom.
Aart Bikf3e61ee2017-04-12 17:09:20 -07001213 if (VectorizeHalvingAddIdiom(node, instruction, generate_code, type, restrictions)) {
1214 return true;
1215 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001216 // Deal with vector restrictions.
Aart Bik304c8a52017-05-23 11:01:13 -07001217 HInstruction* opa = instruction->InputAt(0);
1218 HInstruction* opb = instruction->InputAt(1);
1219 HInstruction* r = opa;
1220 bool is_unsigned = false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001221 if ((HasVectorRestrictions(restrictions, kNoShift)) ||
1222 (instruction->IsShr() && HasVectorRestrictions(restrictions, kNoShr))) {
1223 return false; // unsupported instruction
Aart Bik304c8a52017-05-23 11:01:13 -07001224 } else if (HasVectorRestrictions(restrictions, kNoHiBits)) {
1225 // Shifts right need extra care to account for higher order bits.
1226 // TODO: less likely shr/unsigned and ushr/signed can by flipping signess.
1227 if (instruction->IsShr() &&
1228 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || is_unsigned)) {
1229 return false; // reject, unless all operands are sign-extension narrower
1230 } else if (instruction->IsUShr() &&
1231 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || !is_unsigned)) {
1232 return false; // reject, unless all operands are zero-extension narrower
1233 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001234 }
1235 // Accept shift operator for vectorizable/invariant operands.
1236 // TODO: accept symbolic, albeit loop invariant shift factors.
Aart Bik304c8a52017-05-23 11:01:13 -07001237 DCHECK(r != nullptr);
1238 if (generate_code && vector_mode_ != kVector) { // de-idiom
1239 r = opa;
1240 }
Aart Bik50e20d52017-05-05 14:07:29 -07001241 int64_t distance = 0;
Aart Bik304c8a52017-05-23 11:01:13 -07001242 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
Aart Bik50e20d52017-05-05 14:07:29 -07001243 IsInt64AndGet(opb, /*out*/ &distance)) {
Aart Bik65ffd8e2017-05-01 16:50:45 -07001244 // Restrict shift distance to packed data type width.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001245 int64_t max_distance = DataType::Size(type) * 8;
Aart Bik65ffd8e2017-05-01 16:50:45 -07001246 if (0 <= distance && distance < max_distance) {
1247 if (generate_code) {
Aart Bik304c8a52017-05-23 11:01:13 -07001248 GenerateVecOp(instruction, vector_map_->Get(r), opb, type);
Aart Bik65ffd8e2017-05-01 16:50:45 -07001249 }
1250 return true;
Aart Bikf8f5a162017-02-06 15:35:29 -08001251 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001252 }
1253 } else if (instruction->IsInvokeStaticOrDirect()) {
Aart Bik6daebeb2017-04-03 14:35:41 -07001254 // Accept particular intrinsics.
1255 HInvokeStaticOrDirect* invoke = instruction->AsInvokeStaticOrDirect();
1256 switch (invoke->GetIntrinsic()) {
1257 case Intrinsics::kMathAbsInt:
1258 case Intrinsics::kMathAbsLong:
1259 case Intrinsics::kMathAbsFloat:
1260 case Intrinsics::kMathAbsDouble: {
1261 // Deal with vector restrictions.
Aart Bik304c8a52017-05-23 11:01:13 -07001262 HInstruction* opa = instruction->InputAt(0);
1263 HInstruction* r = opa;
1264 bool is_unsigned = false;
1265 if (HasVectorRestrictions(restrictions, kNoAbs)) {
Aart Bik6daebeb2017-04-03 14:35:41 -07001266 return false;
Aart Bik304c8a52017-05-23 11:01:13 -07001267 } else if (HasVectorRestrictions(restrictions, kNoHiBits) &&
1268 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || is_unsigned)) {
1269 return false; // reject, unless operand is sign-extension narrower
Aart Bik6daebeb2017-04-03 14:35:41 -07001270 }
1271 // Accept ABS(x) for vectorizable operand.
Aart Bik304c8a52017-05-23 11:01:13 -07001272 DCHECK(r != nullptr);
1273 if (generate_code && vector_mode_ != kVector) { // de-idiom
1274 r = opa;
1275 }
1276 if (VectorizeUse(node, r, generate_code, type, restrictions)) {
Aart Bik6daebeb2017-04-03 14:35:41 -07001277 if (generate_code) {
Aart Bik304c8a52017-05-23 11:01:13 -07001278 GenerateVecOp(instruction, vector_map_->Get(r), nullptr, type);
Aart Bik6daebeb2017-04-03 14:35:41 -07001279 }
1280 return true;
1281 }
1282 return false;
1283 }
Aart Bikc8e93c72017-05-10 10:49:22 -07001284 case Intrinsics::kMathMinIntInt:
1285 case Intrinsics::kMathMinLongLong:
1286 case Intrinsics::kMathMinFloatFloat:
1287 case Intrinsics::kMathMinDoubleDouble:
1288 case Intrinsics::kMathMaxIntInt:
1289 case Intrinsics::kMathMaxLongLong:
1290 case Intrinsics::kMathMaxFloatFloat:
1291 case Intrinsics::kMathMaxDoubleDouble: {
1292 // Deal with vector restrictions.
Nicolas Geoffray92316902017-05-23 08:06:07 +00001293 HInstruction* opa = instruction->InputAt(0);
1294 HInstruction* opb = instruction->InputAt(1);
Aart Bik304c8a52017-05-23 11:01:13 -07001295 HInstruction* r = opa;
1296 HInstruction* s = opb;
1297 bool is_unsigned = false;
1298 if (HasVectorRestrictions(restrictions, kNoMinMax)) {
1299 return false;
1300 } else if (HasVectorRestrictions(restrictions, kNoHiBits) &&
1301 !IsNarrowerOperands(opa, opb, type, &r, &s, &is_unsigned)) {
1302 return false; // reject, unless all operands are same-extension narrower
1303 }
1304 // Accept MIN/MAX(x, y) for vectorizable operands.
Aart Bikdbbac8f2017-09-01 13:06:08 -07001305 DCHECK(r != nullptr);
1306 DCHECK(s != nullptr);
Aart Bik304c8a52017-05-23 11:01:13 -07001307 if (generate_code && vector_mode_ != kVector) { // de-idiom
1308 r = opa;
1309 s = opb;
1310 }
1311 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
1312 VectorizeUse(node, s, generate_code, type, restrictions)) {
Aart Bikc8e93c72017-05-10 10:49:22 -07001313 if (generate_code) {
Aart Bik304c8a52017-05-23 11:01:13 -07001314 GenerateVecOp(
1315 instruction, vector_map_->Get(r), vector_map_->Get(s), type, is_unsigned);
Aart Bikc8e93c72017-05-10 10:49:22 -07001316 }
1317 return true;
1318 }
1319 return false;
1320 }
Aart Bik6daebeb2017-04-03 14:35:41 -07001321 default:
1322 return false;
1323 } // switch
Aart Bik281c6812016-08-26 11:31:48 -07001324 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08001325 return false;
Aart Bik281c6812016-08-26 11:31:48 -07001326}
1327
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001328bool HLoopOptimization::TrySetVectorType(DataType::Type type, uint64_t* restrictions) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001329 const InstructionSetFeatures* features = compiler_driver_->GetInstructionSetFeatures();
1330 switch (compiler_driver_->GetInstructionSet()) {
1331 case kArm:
1332 case kThumb2:
Artem Serov8f7c4102017-06-21 11:21:37 +01001333 // Allow vectorization for all ARM devices, because Android assumes that
Aart Bikb29f6842017-07-28 15:58:41 -07001334 // ARM 32-bit always supports advanced SIMD (64-bit SIMD).
Artem Serov8f7c4102017-06-21 11:21:37 +01001335 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001336 case DataType::Type::kBool:
1337 case DataType::Type::kInt8:
Aart Bik0148de42017-09-05 09:25:01 -07001338 *restrictions |= kNoDiv | kNoReduction;
Artem Serov8f7c4102017-06-21 11:21:37 +01001339 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001340 case DataType::Type::kUint16:
1341 case DataType::Type::kInt16:
Aart Bik0148de42017-09-05 09:25:01 -07001342 *restrictions |= kNoDiv | kNoStringCharAt | kNoReduction;
Artem Serov8f7c4102017-06-21 11:21:37 +01001343 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001344 case DataType::Type::kInt32:
Aart Bik0148de42017-09-05 09:25:01 -07001345 *restrictions |= kNoDiv | kNoReduction;
Artem Serov8f7c4102017-06-21 11:21:37 +01001346 return TrySetVectorLength(2);
1347 default:
1348 break;
1349 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001350 return false;
1351 case kArm64:
1352 // Allow vectorization for all ARM devices, because Android assumes that
Aart Bikb29f6842017-07-28 15:58:41 -07001353 // ARMv8 AArch64 always supports advanced SIMD (128-bit SIMD).
Aart Bikf8f5a162017-02-06 15:35:29 -08001354 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001355 case DataType::Type::kBool:
1356 case DataType::Type::kInt8:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001357 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +01001358 return TrySetVectorLength(16);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001359 case DataType::Type::kUint16:
1360 case DataType::Type::kInt16:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001361 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +01001362 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001363 case DataType::Type::kInt32:
Aart Bikf8f5a162017-02-06 15:35:29 -08001364 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +01001365 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001366 case DataType::Type::kInt64:
Aart Bikc8e93c72017-05-10 10:49:22 -07001367 *restrictions |= kNoDiv | kNoMul | kNoMinMax;
Aart Bikf8f5a162017-02-06 15:35:29 -08001368 return TrySetVectorLength(2);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001369 case DataType::Type::kFloat32:
Aart Bik0148de42017-09-05 09:25:01 -07001370 *restrictions |= kNoReduction;
Artem Serovd4bccf12017-04-03 18:47:32 +01001371 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001372 case DataType::Type::kFloat64:
Aart Bik0148de42017-09-05 09:25:01 -07001373 *restrictions |= kNoReduction;
Aart Bikf8f5a162017-02-06 15:35:29 -08001374 return TrySetVectorLength(2);
1375 default:
1376 return false;
1377 }
1378 case kX86:
1379 case kX86_64:
Aart Bikb29f6842017-07-28 15:58:41 -07001380 // Allow vectorization for SSE4.1-enabled X86 devices only (128-bit SIMD).
Aart Bikf8f5a162017-02-06 15:35:29 -08001381 if (features->AsX86InstructionSetFeatures()->HasSSE4_1()) {
1382 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001383 case DataType::Type::kBool:
1384 case DataType::Type::kInt8:
Aart Bik0148de42017-09-05 09:25:01 -07001385 *restrictions |=
Aart Bikdbbac8f2017-09-01 13:06:08 -07001386 kNoMul | kNoDiv | kNoShift | kNoAbs | kNoSignedHAdd | kNoUnroundedHAdd | kNoSAD;
Aart Bikf8f5a162017-02-06 15:35:29 -08001387 return TrySetVectorLength(16);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001388 case DataType::Type::kUint16:
1389 case DataType::Type::kInt16:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001390 *restrictions |= kNoDiv | kNoAbs | kNoSignedHAdd | kNoUnroundedHAdd | kNoSAD;
Aart Bikf8f5a162017-02-06 15:35:29 -08001391 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001392 case DataType::Type::kInt32:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001393 *restrictions |= kNoDiv | kNoSAD;
Aart Bikf8f5a162017-02-06 15:35:29 -08001394 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001395 case DataType::Type::kInt64:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001396 *restrictions |= kNoMul | kNoDiv | kNoShr | kNoAbs | kNoMinMax | kNoSAD;
Aart Bikf8f5a162017-02-06 15:35:29 -08001397 return TrySetVectorLength(2);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001398 case DataType::Type::kFloat32:
Aart Bik0148de42017-09-05 09:25:01 -07001399 *restrictions |= kNoMinMax | kNoReduction; // minmax: -0.0 vs +0.0
Aart Bikf8f5a162017-02-06 15:35:29 -08001400 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001401 case DataType::Type::kFloat64:
Aart Bik0148de42017-09-05 09:25:01 -07001402 *restrictions |= kNoMinMax | kNoReduction; // minmax: -0.0 vs +0.0
Aart Bikf8f5a162017-02-06 15:35:29 -08001403 return TrySetVectorLength(2);
1404 default:
1405 break;
1406 } // switch type
1407 }
1408 return false;
1409 case kMips:
Lena Djokic51765b02017-06-22 13:49:59 +02001410 if (features->AsMipsInstructionSetFeatures()->HasMsa()) {
1411 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001412 case DataType::Type::kBool:
1413 case DataType::Type::kInt8:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001414 *restrictions |= kNoDiv | kNoReduction | kNoSAD;
Lena Djokic51765b02017-06-22 13:49:59 +02001415 return TrySetVectorLength(16);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001416 case DataType::Type::kUint16:
1417 case DataType::Type::kInt16:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001418 *restrictions |= kNoDiv | kNoStringCharAt | kNoReduction | kNoSAD;
Lena Djokic51765b02017-06-22 13:49:59 +02001419 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001420 case DataType::Type::kInt32:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001421 *restrictions |= kNoDiv | kNoReduction | kNoSAD;
Lena Djokic51765b02017-06-22 13:49:59 +02001422 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001423 case DataType::Type::kInt64:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001424 *restrictions |= kNoDiv | kNoReduction | kNoSAD;
Lena Djokic51765b02017-06-22 13:49:59 +02001425 return TrySetVectorLength(2);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001426 case DataType::Type::kFloat32:
Aart Bik0148de42017-09-05 09:25:01 -07001427 *restrictions |= kNoMinMax | kNoReduction; // min/max(x, NaN)
Lena Djokic51765b02017-06-22 13:49:59 +02001428 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001429 case DataType::Type::kFloat64:
Aart Bik0148de42017-09-05 09:25:01 -07001430 *restrictions |= kNoMinMax | kNoReduction; // min/max(x, NaN)
Lena Djokic51765b02017-06-22 13:49:59 +02001431 return TrySetVectorLength(2);
1432 default:
1433 break;
1434 } // switch type
1435 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001436 return false;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001437 case kMips64:
1438 if (features->AsMips64InstructionSetFeatures()->HasMsa()) {
1439 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001440 case DataType::Type::kBool:
1441 case DataType::Type::kInt8:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001442 *restrictions |= kNoDiv | kNoReduction | kNoSAD;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001443 return TrySetVectorLength(16);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001444 case DataType::Type::kUint16:
1445 case DataType::Type::kInt16:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001446 *restrictions |= kNoDiv | kNoStringCharAt | kNoReduction | kNoSAD;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001447 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001448 case DataType::Type::kInt32:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001449 *restrictions |= kNoDiv | kNoReduction | kNoSAD;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001450 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001451 case DataType::Type::kInt64:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001452 *restrictions |= kNoDiv | kNoReduction | kNoSAD;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001453 return TrySetVectorLength(2);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001454 case DataType::Type::kFloat32:
Aart Bik0148de42017-09-05 09:25:01 -07001455 *restrictions |= kNoMinMax | kNoReduction; // min/max(x, NaN)
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001456 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001457 case DataType::Type::kFloat64:
Aart Bik0148de42017-09-05 09:25:01 -07001458 *restrictions |= kNoMinMax | kNoReduction; // min/max(x, NaN)
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001459 return TrySetVectorLength(2);
1460 default:
1461 break;
1462 } // switch type
1463 }
1464 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001465 default:
1466 return false;
1467 } // switch instruction set
1468}
1469
1470bool HLoopOptimization::TrySetVectorLength(uint32_t length) {
1471 DCHECK(IsPowerOfTwo(length) && length >= 2u);
1472 // First time set?
1473 if (vector_length_ == 0) {
1474 vector_length_ = length;
1475 }
1476 // Different types are acceptable within a loop-body, as long as all the corresponding vector
1477 // lengths match exactly to obtain a uniform traversal through the vector iteration space
1478 // (idiomatic exceptions to this rule can be handled by further unrolling sub-expressions).
1479 return vector_length_ == length;
1480}
1481
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001482void HLoopOptimization::GenerateVecInv(HInstruction* org, DataType::Type type) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001483 if (vector_map_->find(org) == vector_map_->end()) {
1484 // In scalar code, just use a self pass-through for scalar invariants
1485 // (viz. expression remains itself).
1486 if (vector_mode_ == kSequential) {
1487 vector_map_->Put(org, org);
1488 return;
1489 }
1490 // In vector code, explicit scalar expansion is needed.
Aart Bik0148de42017-09-05 09:25:01 -07001491 HInstruction* vector = nullptr;
1492 auto it = vector_permanent_map_->find(org);
1493 if (it != vector_permanent_map_->end()) {
1494 vector = it->second; // reuse during unrolling
1495 } else {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001496 // Generates ReplicateScalar( (optional_type_conv) org ).
1497 HInstruction* input = org;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001498 DataType::Type input_type = input->GetType();
1499 if (type != input_type && (type == DataType::Type::kInt64 ||
1500 input_type == DataType::Type::kInt64)) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001501 input = Insert(vector_preheader_,
1502 new (global_allocator_) HTypeConversion(type, input, kNoDexPc));
1503 }
1504 vector = new (global_allocator_)
1505 HVecReplicateScalar(global_allocator_, input, type, vector_length_);
Aart Bik0148de42017-09-05 09:25:01 -07001506 vector_permanent_map_->Put(org, Insert(vector_preheader_, vector));
1507 }
1508 vector_map_->Put(org, vector);
Aart Bikf8f5a162017-02-06 15:35:29 -08001509 }
1510}
1511
1512void HLoopOptimization::GenerateVecSub(HInstruction* org, HInstruction* offset) {
1513 if (vector_map_->find(org) == vector_map_->end()) {
Aart Bik14a68b42017-06-08 14:06:58 -07001514 HInstruction* subscript = vector_index_;
Aart Bik37dc4df2017-06-28 14:08:00 -07001515 int64_t value = 0;
1516 if (!IsInt64AndGet(offset, &value) || value != 0) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001517 subscript = new (global_allocator_) HAdd(DataType::Type::kInt32, subscript, offset);
Aart Bikf8f5a162017-02-06 15:35:29 -08001518 if (org->IsPhi()) {
1519 Insert(vector_body_, subscript); // lacks layout placeholder
1520 }
1521 }
1522 vector_map_->Put(org, subscript);
1523 }
1524}
1525
1526void HLoopOptimization::GenerateVecMem(HInstruction* org,
1527 HInstruction* opa,
1528 HInstruction* opb,
Aart Bik14a68b42017-06-08 14:06:58 -07001529 HInstruction* offset,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001530 DataType::Type type) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001531 HInstruction* vector = nullptr;
1532 if (vector_mode_ == kVector) {
1533 // Vector store or load.
Aart Bik14a68b42017-06-08 14:06:58 -07001534 HInstruction* base = org->InputAt(0);
Aart Bikf8f5a162017-02-06 15:35:29 -08001535 if (opb != nullptr) {
1536 vector = new (global_allocator_) HVecStore(
Aart Bik14a68b42017-06-08 14:06:58 -07001537 global_allocator_, base, opa, opb, type, vector_length_);
Aart Bikf8f5a162017-02-06 15:35:29 -08001538 } else {
Aart Bikdb14fcf2017-04-25 15:53:58 -07001539 bool is_string_char_at = org->AsArrayGet()->IsStringCharAt();
Aart Bikf8f5a162017-02-06 15:35:29 -08001540 vector = new (global_allocator_) HVecLoad(
Aart Bik14a68b42017-06-08 14:06:58 -07001541 global_allocator_, base, opa, type, vector_length_, is_string_char_at);
1542 }
1543 // Known dynamically enforced alignment?
Aart Bik14a68b42017-06-08 14:06:58 -07001544 if (vector_peeling_candidate_ != nullptr &&
1545 vector_peeling_candidate_->base == base &&
1546 vector_peeling_candidate_->offset == offset) {
1547 vector->AsVecMemoryOperation()->SetAlignment(Alignment(kAlignedBase, 0));
Aart Bikf8f5a162017-02-06 15:35:29 -08001548 }
1549 } else {
1550 // Scalar store or load.
1551 DCHECK(vector_mode_ == kSequential);
1552 if (opb != nullptr) {
1553 vector = new (global_allocator_) HArraySet(org->InputAt(0), opa, opb, type, kNoDexPc);
1554 } else {
Aart Bikdb14fcf2017-04-25 15:53:58 -07001555 bool is_string_char_at = org->AsArrayGet()->IsStringCharAt();
1556 vector = new (global_allocator_) HArrayGet(
1557 org->InputAt(0), opa, type, kNoDexPc, is_string_char_at);
Aart Bikf8f5a162017-02-06 15:35:29 -08001558 }
1559 }
1560 vector_map_->Put(org, vector);
1561}
1562
Aart Bik0148de42017-09-05 09:25:01 -07001563void HLoopOptimization::GenerateVecReductionPhi(HPhi* phi) {
1564 DCHECK(reductions_->find(phi) != reductions_->end());
1565 DCHECK(reductions_->Get(phi->InputAt(1)) == phi);
1566 HInstruction* vector = nullptr;
1567 if (vector_mode_ == kSequential) {
1568 HPhi* new_phi = new (global_allocator_) HPhi(
1569 global_allocator_, kNoRegNumber, 0, phi->GetType());
1570 vector_header_->AddPhi(new_phi);
1571 vector = new_phi;
1572 } else {
1573 // Link vector reduction back to prior unrolled update, or a first phi.
1574 auto it = vector_permanent_map_->find(phi);
1575 if (it != vector_permanent_map_->end()) {
1576 vector = it->second;
1577 } else {
1578 HPhi* new_phi = new (global_allocator_) HPhi(
1579 global_allocator_, kNoRegNumber, 0, HVecOperation::kSIMDType);
1580 vector_header_->AddPhi(new_phi);
1581 vector = new_phi;
1582 }
1583 }
1584 vector_map_->Put(phi, vector);
1585}
1586
1587void HLoopOptimization::GenerateVecReductionPhiInputs(HPhi* phi, HInstruction* reduction) {
1588 HInstruction* new_phi = vector_map_->Get(phi);
1589 HInstruction* new_init = reductions_->Get(phi);
1590 HInstruction* new_red = vector_map_->Get(reduction);
1591 // Link unrolled vector loop back to new phi.
1592 for (; !new_phi->IsPhi(); new_phi = vector_permanent_map_->Get(new_phi)) {
1593 DCHECK(new_phi->IsVecOperation());
1594 }
1595 // Prepare the new initialization.
1596 if (vector_mode_ == kVector) {
1597 // Generate a [initial, 0, .., 0] vector.
Aart Bikdbbac8f2017-09-01 13:06:08 -07001598 HVecOperation* red_vector = new_red->AsVecOperation();
1599 size_t vector_length = red_vector->GetVectorLength();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001600 DataType::Type type = red_vector->GetPackedType();
Aart Bikdbbac8f2017-09-01 13:06:08 -07001601 new_init = Insert(vector_preheader_,
1602 new (global_allocator_) HVecSetScalars(global_allocator_,
1603 &new_init,
1604 type,
1605 vector_length,
1606 1));
Aart Bik0148de42017-09-05 09:25:01 -07001607 } else {
1608 new_init = ReduceAndExtractIfNeeded(new_init);
1609 }
1610 // Set the phi inputs.
1611 DCHECK(new_phi->IsPhi());
1612 new_phi->AsPhi()->AddInput(new_init);
1613 new_phi->AsPhi()->AddInput(new_red);
1614 // New feed value for next phi (safe mutation in iteration).
1615 reductions_->find(phi)->second = new_phi;
1616}
1617
1618HInstruction* HLoopOptimization::ReduceAndExtractIfNeeded(HInstruction* instruction) {
1619 if (instruction->IsPhi()) {
1620 HInstruction* input = instruction->InputAt(1);
1621 if (input->IsVecOperation()) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001622 HVecOperation* input_vector = input->AsVecOperation();
1623 size_t vector_length = input_vector->GetVectorLength();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001624 DataType::Type type = input_vector->GetPackedType();
Aart Bikdbbac8f2017-09-01 13:06:08 -07001625 HVecReduce::ReductionKind kind = GetReductionKind(input_vector);
Aart Bik0148de42017-09-05 09:25:01 -07001626 HBasicBlock* exit = instruction->GetBlock()->GetSuccessors()[0];
1627 // Generate a vector reduction and scalar extract
1628 // x = REDUCE( [x_1, .., x_n] )
1629 // y = x_1
1630 // along the exit of the defining loop.
Aart Bik0148de42017-09-05 09:25:01 -07001631 HInstruction* reduce = new (global_allocator_) HVecReduce(
Aart Bikdbbac8f2017-09-01 13:06:08 -07001632 global_allocator_, instruction, type, vector_length, kind);
Aart Bik0148de42017-09-05 09:25:01 -07001633 exit->InsertInstructionBefore(reduce, exit->GetFirstInstruction());
1634 instruction = new (global_allocator_) HVecExtractScalar(
Aart Bikdbbac8f2017-09-01 13:06:08 -07001635 global_allocator_, reduce, type, vector_length, 0);
Aart Bik0148de42017-09-05 09:25:01 -07001636 exit->InsertInstructionAfter(instruction, reduce);
1637 }
1638 }
1639 return instruction;
1640}
1641
Aart Bikf8f5a162017-02-06 15:35:29 -08001642#define GENERATE_VEC(x, y) \
1643 if (vector_mode_ == kVector) { \
1644 vector = (x); \
1645 } else { \
1646 DCHECK(vector_mode_ == kSequential); \
1647 vector = (y); \
1648 } \
1649 break;
1650
1651void HLoopOptimization::GenerateVecOp(HInstruction* org,
1652 HInstruction* opa,
1653 HInstruction* opb,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001654 DataType::Type type,
Aart Bik304c8a52017-05-23 11:01:13 -07001655 bool is_unsigned) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001656 HInstruction* vector = nullptr;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001657 DataType::Type org_type = org->GetType();
Aart Bikf8f5a162017-02-06 15:35:29 -08001658 switch (org->GetKind()) {
1659 case HInstruction::kNeg:
1660 DCHECK(opb == nullptr);
1661 GENERATE_VEC(
1662 new (global_allocator_) HVecNeg(global_allocator_, opa, type, vector_length_),
Aart Bikdbbac8f2017-09-01 13:06:08 -07001663 new (global_allocator_) HNeg(org_type, opa));
Aart Bikf8f5a162017-02-06 15:35:29 -08001664 case HInstruction::kNot:
1665 DCHECK(opb == nullptr);
1666 GENERATE_VEC(
1667 new (global_allocator_) HVecNot(global_allocator_, opa, type, vector_length_),
Aart Bikdbbac8f2017-09-01 13:06:08 -07001668 new (global_allocator_) HNot(org_type, opa));
Aart Bikf8f5a162017-02-06 15:35:29 -08001669 case HInstruction::kBooleanNot:
1670 DCHECK(opb == nullptr);
1671 GENERATE_VEC(
1672 new (global_allocator_) HVecNot(global_allocator_, opa, type, vector_length_),
1673 new (global_allocator_) HBooleanNot(opa));
1674 case HInstruction::kTypeConversion:
1675 DCHECK(opb == nullptr);
1676 GENERATE_VEC(
1677 new (global_allocator_) HVecCnv(global_allocator_, opa, type, vector_length_),
Aart Bikdbbac8f2017-09-01 13:06:08 -07001678 new (global_allocator_) HTypeConversion(org_type, opa, kNoDexPc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001679 case HInstruction::kAdd:
1680 GENERATE_VEC(
1681 new (global_allocator_) HVecAdd(global_allocator_, opa, opb, type, vector_length_),
Aart Bikdbbac8f2017-09-01 13:06:08 -07001682 new (global_allocator_) HAdd(org_type, opa, opb));
Aart Bikf8f5a162017-02-06 15:35:29 -08001683 case HInstruction::kSub:
1684 GENERATE_VEC(
1685 new (global_allocator_) HVecSub(global_allocator_, opa, opb, type, vector_length_),
Aart Bikdbbac8f2017-09-01 13:06:08 -07001686 new (global_allocator_) HSub(org_type, opa, opb));
Aart Bikf8f5a162017-02-06 15:35:29 -08001687 case HInstruction::kMul:
1688 GENERATE_VEC(
1689 new (global_allocator_) HVecMul(global_allocator_, opa, opb, type, vector_length_),
Aart Bikdbbac8f2017-09-01 13:06:08 -07001690 new (global_allocator_) HMul(org_type, opa, opb));
Aart Bikf8f5a162017-02-06 15:35:29 -08001691 case HInstruction::kDiv:
1692 GENERATE_VEC(
1693 new (global_allocator_) HVecDiv(global_allocator_, opa, opb, type, vector_length_),
Aart Bikdbbac8f2017-09-01 13:06:08 -07001694 new (global_allocator_) HDiv(org_type, opa, opb, kNoDexPc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001695 case HInstruction::kAnd:
1696 GENERATE_VEC(
1697 new (global_allocator_) HVecAnd(global_allocator_, opa, opb, type, vector_length_),
Aart Bikdbbac8f2017-09-01 13:06:08 -07001698 new (global_allocator_) HAnd(org_type, opa, opb));
Aart Bikf8f5a162017-02-06 15:35:29 -08001699 case HInstruction::kOr:
1700 GENERATE_VEC(
1701 new (global_allocator_) HVecOr(global_allocator_, opa, opb, type, vector_length_),
Aart Bikdbbac8f2017-09-01 13:06:08 -07001702 new (global_allocator_) HOr(org_type, opa, opb));
Aart Bikf8f5a162017-02-06 15:35:29 -08001703 case HInstruction::kXor:
1704 GENERATE_VEC(
1705 new (global_allocator_) HVecXor(global_allocator_, opa, opb, type, vector_length_),
Aart Bikdbbac8f2017-09-01 13:06:08 -07001706 new (global_allocator_) HXor(org_type, opa, opb));
Aart Bikf8f5a162017-02-06 15:35:29 -08001707 case HInstruction::kShl:
1708 GENERATE_VEC(
1709 new (global_allocator_) HVecShl(global_allocator_, opa, opb, type, vector_length_),
Aart Bikdbbac8f2017-09-01 13:06:08 -07001710 new (global_allocator_) HShl(org_type, opa, opb));
Aart Bikf8f5a162017-02-06 15:35:29 -08001711 case HInstruction::kShr:
1712 GENERATE_VEC(
1713 new (global_allocator_) HVecShr(global_allocator_, opa, opb, type, vector_length_),
Aart Bikdbbac8f2017-09-01 13:06:08 -07001714 new (global_allocator_) HShr(org_type, opa, opb));
Aart Bikf8f5a162017-02-06 15:35:29 -08001715 case HInstruction::kUShr:
1716 GENERATE_VEC(
1717 new (global_allocator_) HVecUShr(global_allocator_, opa, opb, type, vector_length_),
Aart Bikdbbac8f2017-09-01 13:06:08 -07001718 new (global_allocator_) HUShr(org_type, opa, opb));
Aart Bikf8f5a162017-02-06 15:35:29 -08001719 case HInstruction::kInvokeStaticOrDirect: {
Aart Bik6daebeb2017-04-03 14:35:41 -07001720 HInvokeStaticOrDirect* invoke = org->AsInvokeStaticOrDirect();
1721 if (vector_mode_ == kVector) {
1722 switch (invoke->GetIntrinsic()) {
1723 case Intrinsics::kMathAbsInt:
1724 case Intrinsics::kMathAbsLong:
1725 case Intrinsics::kMathAbsFloat:
1726 case Intrinsics::kMathAbsDouble:
1727 DCHECK(opb == nullptr);
1728 vector = new (global_allocator_) HVecAbs(global_allocator_, opa, type, vector_length_);
1729 break;
Aart Bikc8e93c72017-05-10 10:49:22 -07001730 case Intrinsics::kMathMinIntInt:
1731 case Intrinsics::kMathMinLongLong:
1732 case Intrinsics::kMathMinFloatFloat:
1733 case Intrinsics::kMathMinDoubleDouble: {
Aart Bikc8e93c72017-05-10 10:49:22 -07001734 vector = new (global_allocator_)
1735 HVecMin(global_allocator_, opa, opb, type, vector_length_, is_unsigned);
1736 break;
1737 }
1738 case Intrinsics::kMathMaxIntInt:
1739 case Intrinsics::kMathMaxLongLong:
1740 case Intrinsics::kMathMaxFloatFloat:
1741 case Intrinsics::kMathMaxDoubleDouble: {
Aart Bikc8e93c72017-05-10 10:49:22 -07001742 vector = new (global_allocator_)
1743 HVecMax(global_allocator_, opa, opb, type, vector_length_, is_unsigned);
1744 break;
1745 }
Aart Bik6daebeb2017-04-03 14:35:41 -07001746 default:
1747 LOG(FATAL) << "Unsupported SIMD intrinsic";
1748 UNREACHABLE();
1749 } // switch invoke
1750 } else {
Aart Bik24b905f2017-04-06 09:59:06 -07001751 // In scalar code, simply clone the method invoke, and replace its operands with the
1752 // corresponding new scalar instructions in the loop. The instruction will get an
1753 // environment while being inserted from the instruction map in original program order.
Aart Bik6daebeb2017-04-03 14:35:41 -07001754 DCHECK(vector_mode_ == kSequential);
Aart Bik6e92fb32017-06-05 14:05:09 -07001755 size_t num_args = invoke->GetNumberOfArguments();
Aart Bik6daebeb2017-04-03 14:35:41 -07001756 HInvokeStaticOrDirect* new_invoke = new (global_allocator_) HInvokeStaticOrDirect(
1757 global_allocator_,
Aart Bik6e92fb32017-06-05 14:05:09 -07001758 num_args,
Aart Bik6daebeb2017-04-03 14:35:41 -07001759 invoke->GetType(),
1760 invoke->GetDexPc(),
1761 invoke->GetDexMethodIndex(),
1762 invoke->GetResolvedMethod(),
1763 invoke->GetDispatchInfo(),
1764 invoke->GetInvokeType(),
1765 invoke->GetTargetMethod(),
1766 invoke->GetClinitCheckRequirement());
1767 HInputsRef inputs = invoke->GetInputs();
Aart Bik6e92fb32017-06-05 14:05:09 -07001768 size_t num_inputs = inputs.size();
1769 DCHECK_LE(num_args, num_inputs);
1770 DCHECK_EQ(num_inputs, new_invoke->GetInputs().size()); // both invokes agree
1771 for (size_t index = 0; index < num_inputs; ++index) {
1772 HInstruction* new_input = index < num_args
1773 ? vector_map_->Get(inputs[index])
1774 : inputs[index]; // beyond arguments: just pass through
1775 new_invoke->SetArgumentAt(index, new_input);
Aart Bik6daebeb2017-04-03 14:35:41 -07001776 }
Aart Bik98990262017-04-10 13:15:57 -07001777 new_invoke->SetIntrinsic(invoke->GetIntrinsic(),
1778 kNeedsEnvironmentOrCache,
1779 kNoSideEffects,
1780 kNoThrow);
Aart Bik6daebeb2017-04-03 14:35:41 -07001781 vector = new_invoke;
1782 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001783 break;
1784 }
1785 default:
1786 break;
1787 } // switch
1788 CHECK(vector != nullptr) << "Unsupported SIMD operator";
1789 vector_map_->Put(org, vector);
1790}
1791
1792#undef GENERATE_VEC
1793
1794//
Aart Bikf3e61ee2017-04-12 17:09:20 -07001795// Vectorization idioms.
1796//
1797
1798// Method recognizes the following idioms:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001799// rounding halving add (a + b + 1) >> 1 for unsigned/signed operands a, b
1800// truncated halving add (a + b) >> 1 for unsigned/signed operands a, b
Aart Bikf3e61ee2017-04-12 17:09:20 -07001801// Provided that the operands are promoted to a wider form to do the arithmetic and
1802// then cast back to narrower form, the idioms can be mapped into efficient SIMD
1803// implementation that operates directly in narrower form (plus one extra bit).
1804// TODO: current version recognizes implicit byte/short/char widening only;
1805// explicit widening from int to long could be added later.
1806bool HLoopOptimization::VectorizeHalvingAddIdiom(LoopNode* node,
1807 HInstruction* instruction,
1808 bool generate_code,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001809 DataType::Type type,
Aart Bikf3e61ee2017-04-12 17:09:20 -07001810 uint64_t restrictions) {
1811 // Test for top level arithmetic shift right x >> 1 or logical shift right x >>> 1
Aart Bik304c8a52017-05-23 11:01:13 -07001812 // (note whether the sign bit in wider precision is shifted in has no effect
Aart Bikf3e61ee2017-04-12 17:09:20 -07001813 // on the narrow precision computed by the idiom).
Aart Bikf3e61ee2017-04-12 17:09:20 -07001814 if ((instruction->IsShr() ||
1815 instruction->IsUShr()) &&
Aart Bik0148de42017-09-05 09:25:01 -07001816 IsInt64Value(instruction->InputAt(1), 1)) {
Aart Bik5f805002017-05-16 16:42:41 -07001817 // Test for (a + b + c) >> 1 for optional constant c.
1818 HInstruction* a = nullptr;
1819 HInstruction* b = nullptr;
1820 int64_t c = 0;
1821 if (IsAddConst(instruction->InputAt(0), /*out*/ &a, /*out*/ &b, /*out*/ &c)) {
Aart Bik304c8a52017-05-23 11:01:13 -07001822 DCHECK(a != nullptr && b != nullptr);
Aart Bik5f805002017-05-16 16:42:41 -07001823 // Accept c == 1 (rounded) or c == 0 (not rounded).
1824 bool is_rounded = false;
1825 if (c == 1) {
1826 is_rounded = true;
1827 } else if (c != 0) {
1828 return false;
1829 }
1830 // Accept consistent zero or sign extension on operands a and b.
Aart Bikf3e61ee2017-04-12 17:09:20 -07001831 HInstruction* r = nullptr;
1832 HInstruction* s = nullptr;
1833 bool is_unsigned = false;
Aart Bik304c8a52017-05-23 11:01:13 -07001834 if (!IsNarrowerOperands(a, b, type, &r, &s, &is_unsigned)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -07001835 return false;
1836 }
1837 // Deal with vector restrictions.
1838 if ((!is_unsigned && HasVectorRestrictions(restrictions, kNoSignedHAdd)) ||
1839 (!is_rounded && HasVectorRestrictions(restrictions, kNoUnroundedHAdd))) {
1840 return false;
1841 }
1842 // Accept recognized halving add for vectorizable operands. Vectorized code uses the
1843 // shorthand idiomatic operation. Sequential code uses the original scalar expressions.
Aart Bikdbbac8f2017-09-01 13:06:08 -07001844 DCHECK(r != nullptr);
1845 DCHECK(s != nullptr);
Aart Bik304c8a52017-05-23 11:01:13 -07001846 if (generate_code && vector_mode_ != kVector) { // de-idiom
1847 r = instruction->InputAt(0);
1848 s = instruction->InputAt(1);
1849 }
Aart Bikf3e61ee2017-04-12 17:09:20 -07001850 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
1851 VectorizeUse(node, s, generate_code, type, restrictions)) {
1852 if (generate_code) {
1853 if (vector_mode_ == kVector) {
1854 vector_map_->Put(instruction, new (global_allocator_) HVecHalvingAdd(
1855 global_allocator_,
1856 vector_map_->Get(r),
1857 vector_map_->Get(s),
1858 type,
1859 vector_length_,
1860 is_unsigned,
1861 is_rounded));
Aart Bik21b85922017-09-06 13:29:16 -07001862 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorizedIdiom);
Aart Bikf3e61ee2017-04-12 17:09:20 -07001863 } else {
Aart Bik304c8a52017-05-23 11:01:13 -07001864 GenerateVecOp(instruction, vector_map_->Get(r), vector_map_->Get(s), type);
Aart Bikf3e61ee2017-04-12 17:09:20 -07001865 }
1866 }
1867 return true;
1868 }
1869 }
1870 }
1871 return false;
1872}
1873
Aart Bikdbbac8f2017-09-01 13:06:08 -07001874// Method recognizes the following idiom:
1875// q += ABS(a - b) for signed operands a, b
1876// Provided that the operands have the same type or are promoted to a wider form.
1877// Since this may involve a vector length change, the idiom is handled by going directly
1878// to a sad-accumulate node (rather than relying combining finer grained nodes later).
1879// TODO: unsigned SAD too?
1880bool HLoopOptimization::VectorizeSADIdiom(LoopNode* node,
1881 HInstruction* instruction,
1882 bool generate_code,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001883 DataType::Type reduction_type,
Aart Bikdbbac8f2017-09-01 13:06:08 -07001884 uint64_t restrictions) {
1885 // Filter integral "q += ABS(a - b);" reduction, where ABS and SUB
1886 // are done in the same precision (either int or long).
1887 if (!instruction->IsAdd() ||
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001888 (reduction_type != DataType::Type::kInt32 && reduction_type != DataType::Type::kInt64)) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001889 return false;
1890 }
1891 HInstruction* q = instruction->InputAt(0);
1892 HInstruction* v = instruction->InputAt(1);
1893 HInstruction* a = nullptr;
1894 HInstruction* b = nullptr;
1895 if (v->IsInvokeStaticOrDirect() &&
1896 (v->AsInvokeStaticOrDirect()->GetIntrinsic() == Intrinsics::kMathAbsInt ||
1897 v->AsInvokeStaticOrDirect()->GetIntrinsic() == Intrinsics::kMathAbsLong)) {
1898 HInstruction* x = v->InputAt(0);
1899 if (x->IsSub() && x->GetType() == reduction_type) {
1900 a = x->InputAt(0);
1901 b = x->InputAt(1);
1902 }
1903 }
1904 if (a == nullptr || b == nullptr) {
1905 return false;
1906 }
1907 // Accept same-type or consistent sign extension for narrower-type on operands a and b.
1908 // The same-type or narrower operands are called r (a or lower) and s (b or lower).
1909 HInstruction* r = a;
1910 HInstruction* s = b;
1911 bool is_unsigned = false;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001912 DataType::Type sub_type = a->GetType();
Aart Bikdbbac8f2017-09-01 13:06:08 -07001913 if (a->IsTypeConversion()) {
Aart Bik68ca7022017-09-26 16:44:23 -07001914 HInstruction* hunt = a;
1915 while (hunt->IsTypeConversion()) {
1916 hunt = hunt->InputAt(0);
1917 }
1918 sub_type = hunt->GetType();
Aart Bikdbbac8f2017-09-01 13:06:08 -07001919 } else if (b->IsTypeConversion()) {
Aart Bik68ca7022017-09-26 16:44:23 -07001920 HInstruction* hunt = a;
1921 while (hunt->IsTypeConversion()) {
1922 hunt = hunt->InputAt(0);
1923 }
1924 sub_type = hunt->GetType();
Aart Bikdbbac8f2017-09-01 13:06:08 -07001925 }
1926 if (reduction_type != sub_type &&
1927 (!IsNarrowerOperands(a, b, sub_type, &r, &s, &is_unsigned) || is_unsigned)) {
1928 return false;
1929 }
1930 // Try same/narrower type and deal with vector restrictions.
1931 if (!TrySetVectorType(sub_type, &restrictions) || HasVectorRestrictions(restrictions, kNoSAD)) {
1932 return false;
1933 }
1934 // Accept SAD idiom for vectorizable operands. Vectorized code uses the shorthand
1935 // idiomatic operation. Sequential code uses the original scalar expressions.
1936 DCHECK(r != nullptr);
1937 DCHECK(s != nullptr);
1938 if (generate_code && vector_mode_ != kVector) { // de-idiom
1939 r = s = v->InputAt(0);
1940 }
1941 if (VectorizeUse(node, q, generate_code, sub_type, restrictions) &&
1942 VectorizeUse(node, r, generate_code, sub_type, restrictions) &&
1943 VectorizeUse(node, s, generate_code, sub_type, restrictions)) {
1944 if (generate_code) {
1945 if (vector_mode_ == kVector) {
1946 vector_map_->Put(instruction, new (global_allocator_) HVecSADAccumulate(
1947 global_allocator_,
1948 vector_map_->Get(q),
1949 vector_map_->Get(r),
1950 vector_map_->Get(s),
1951 reduction_type,
1952 GetOtherVL(reduction_type, sub_type, vector_length_)));
1953 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorizedIdiom);
1954 } else {
1955 GenerateVecOp(v, vector_map_->Get(r), nullptr, reduction_type);
1956 GenerateVecOp(instruction, vector_map_->Get(q), vector_map_->Get(v), reduction_type);
1957 }
1958 }
1959 return true;
1960 }
1961 return false;
1962}
1963
Aart Bikf3e61ee2017-04-12 17:09:20 -07001964//
Aart Bik14a68b42017-06-08 14:06:58 -07001965// Vectorization heuristics.
1966//
1967
1968bool HLoopOptimization::IsVectorizationProfitable(int64_t trip_count) {
1969 // Current heuristic: non-empty body with sufficient number
1970 // of iterations (if known).
1971 // TODO: refine by looking at e.g. operation count, alignment, etc.
1972 if (vector_length_ == 0) {
1973 return false; // nothing found
1974 } else if (0 < trip_count && trip_count < vector_length_) {
1975 return false; // insufficient iterations
1976 }
1977 return true;
1978}
1979
Aart Bikb29f6842017-07-28 15:58:41 -07001980void HLoopOptimization::SetPeelingCandidate(const ArrayReference* candidate,
1981 int64_t trip_count ATTRIBUTE_UNUSED) {
Aart Bik14a68b42017-06-08 14:06:58 -07001982 // Current heuristic: none.
1983 // TODO: implement
Aart Bikb29f6842017-07-28 15:58:41 -07001984 vector_peeling_candidate_ = candidate;
Aart Bik14a68b42017-06-08 14:06:58 -07001985}
1986
Artem Serovf26bb6c2017-09-01 10:59:03 +01001987static constexpr uint32_t ARM64_SIMD_MAXIMUM_UNROLL_FACTOR = 8;
1988static constexpr uint32_t ARM64_SIMD_HEURISTIC_MAX_BODY_SIZE = 50;
1989
Aart Bik14a68b42017-06-08 14:06:58 -07001990uint32_t HLoopOptimization::GetUnrollingFactor(HBasicBlock* block, int64_t trip_count) {
Aart Bik14a68b42017-06-08 14:06:58 -07001991 switch (compiler_driver_->GetInstructionSet()) {
Artem Serovf26bb6c2017-09-01 10:59:03 +01001992 case kArm64: {
Aart Bik521b50f2017-09-09 10:44:45 -07001993 // Don't unroll with insufficient iterations.
Artem Serovf26bb6c2017-09-01 10:59:03 +01001994 // TODO: Unroll loops with unknown trip count.
Aart Bik521b50f2017-09-09 10:44:45 -07001995 DCHECK_NE(vector_length_, 0u);
Artem Serovf26bb6c2017-09-01 10:59:03 +01001996 if (trip_count < 2 * vector_length_) {
Aart Bik521b50f2017-09-09 10:44:45 -07001997 return kNoUnrollingFactor;
Aart Bik14a68b42017-06-08 14:06:58 -07001998 }
Aart Bik521b50f2017-09-09 10:44:45 -07001999 // Don't unroll for large loop body size.
Artem Serovf26bb6c2017-09-01 10:59:03 +01002000 uint32_t instruction_count = block->GetInstructions().CountSize();
Aart Bik521b50f2017-09-09 10:44:45 -07002001 if (instruction_count >= ARM64_SIMD_HEURISTIC_MAX_BODY_SIZE) {
2002 return kNoUnrollingFactor;
2003 }
Artem Serovf26bb6c2017-09-01 10:59:03 +01002004 // Find a beneficial unroll factor with the following restrictions:
2005 // - At least one iteration of the transformed loop should be executed.
2006 // - The loop body shouldn't be "too big" (heuristic).
2007 uint32_t uf1 = ARM64_SIMD_HEURISTIC_MAX_BODY_SIZE / instruction_count;
2008 uint32_t uf2 = trip_count / vector_length_;
2009 uint32_t unroll_factor =
2010 TruncToPowerOfTwo(std::min({uf1, uf2, ARM64_SIMD_MAXIMUM_UNROLL_FACTOR}));
2011 DCHECK_GE(unroll_factor, 1u);
Artem Serovf26bb6c2017-09-01 10:59:03 +01002012 return unroll_factor;
Aart Bik14a68b42017-06-08 14:06:58 -07002013 }
Artem Serovf26bb6c2017-09-01 10:59:03 +01002014 case kX86:
2015 case kX86_64:
Aart Bik14a68b42017-06-08 14:06:58 -07002016 default:
Aart Bik521b50f2017-09-09 10:44:45 -07002017 return kNoUnrollingFactor;
Aart Bik14a68b42017-06-08 14:06:58 -07002018 }
2019}
2020
2021//
Aart Bikf8f5a162017-02-06 15:35:29 -08002022// Helpers.
2023//
2024
2025bool HLoopOptimization::TrySetPhiInduction(HPhi* phi, bool restrict_uses) {
Aart Bikb29f6842017-07-28 15:58:41 -07002026 // Start with empty phi induction.
2027 iset_->clear();
2028
Nicolas Geoffrayf57c1ae2017-06-28 17:40:18 +01002029 // Special case Phis that have equivalent in a debuggable setup. Our graph checker isn't
2030 // smart enough to follow strongly connected components (and it's probably not worth
2031 // it to make it so). See b/33775412.
2032 if (graph_->IsDebuggable() && phi->HasEquivalentPhi()) {
2033 return false;
2034 }
Aart Bikb29f6842017-07-28 15:58:41 -07002035
2036 // Lookup phi induction cycle.
Aart Bikcc42be02016-10-20 16:14:16 -07002037 ArenaSet<HInstruction*>* set = induction_range_.LookupCycle(phi);
2038 if (set != nullptr) {
2039 for (HInstruction* i : *set) {
Aart Bike3dedc52016-11-02 17:50:27 -07002040 // Check that, other than instructions that are no longer in the graph (removed earlier)
Aart Bikf8f5a162017-02-06 15:35:29 -08002041 // each instruction is removable and, when restrict uses are requested, other than for phi,
2042 // all uses are contained within the cycle.
Aart Bike3dedc52016-11-02 17:50:27 -07002043 if (!i->IsInBlock()) {
2044 continue;
2045 } else if (!i->IsRemovable()) {
2046 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08002047 } else if (i != phi && restrict_uses) {
Aart Bikb29f6842017-07-28 15:58:41 -07002048 // Deal with regular uses.
Aart Bikcc42be02016-10-20 16:14:16 -07002049 for (const HUseListNode<HInstruction*>& use : i->GetUses()) {
2050 if (set->find(use.GetUser()) == set->end()) {
2051 return false;
2052 }
2053 }
2054 }
Aart Bike3dedc52016-11-02 17:50:27 -07002055 iset_->insert(i); // copy
Aart Bikcc42be02016-10-20 16:14:16 -07002056 }
Aart Bikcc42be02016-10-20 16:14:16 -07002057 return true;
2058 }
2059 return false;
2060}
2061
Aart Bikb29f6842017-07-28 15:58:41 -07002062bool HLoopOptimization::TrySetPhiReduction(HPhi* phi) {
Aart Bikcc42be02016-10-20 16:14:16 -07002063 DCHECK(iset_->empty());
Aart Bikb29f6842017-07-28 15:58:41 -07002064 // Only unclassified phi cycles are candidates for reductions.
2065 if (induction_range_.IsClassified(phi)) {
2066 return false;
2067 }
2068 // Accept operations like x = x + .., provided that the phi and the reduction are
2069 // used exactly once inside the loop, and by each other.
2070 HInputsRef inputs = phi->GetInputs();
2071 if (inputs.size() == 2) {
2072 HInstruction* reduction = inputs[1];
2073 if (HasReductionFormat(reduction, phi)) {
2074 HLoopInformation* loop_info = phi->GetBlock()->GetLoopInformation();
2075 int32_t use_count = 0;
2076 bool single_use_inside_loop =
2077 // Reduction update only used by phi.
2078 reduction->GetUses().HasExactlyOneElement() &&
2079 !reduction->HasEnvironmentUses() &&
2080 // Reduction update is only use of phi inside the loop.
2081 IsOnlyUsedAfterLoop(loop_info, phi, /*collect_loop_uses*/ true, &use_count) &&
2082 iset_->size() == 1;
2083 iset_->clear(); // leave the way you found it
2084 if (single_use_inside_loop) {
2085 // Link reduction back, and start recording feed value.
2086 reductions_->Put(reduction, phi);
2087 reductions_->Put(phi, phi->InputAt(0));
2088 return true;
2089 }
2090 }
2091 }
2092 return false;
2093}
2094
2095bool HLoopOptimization::TrySetSimpleLoopHeader(HBasicBlock* block, /*out*/ HPhi** main_phi) {
2096 // Start with empty phi induction and reductions.
2097 iset_->clear();
2098 reductions_->clear();
2099
2100 // Scan the phis to find the following (the induction structure has already
2101 // been optimized, so we don't need to worry about trivial cases):
2102 // (1) optional reductions in loop,
2103 // (2) the main induction, used in loop control.
2104 HPhi* phi = nullptr;
2105 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
2106 if (TrySetPhiReduction(it.Current()->AsPhi())) {
2107 continue;
2108 } else if (phi == nullptr) {
2109 // Found the first candidate for main induction.
2110 phi = it.Current()->AsPhi();
2111 } else {
2112 return false;
2113 }
2114 }
2115
2116 // Then test for a typical loopheader:
2117 // s: SuspendCheck
2118 // c: Condition(phi, bound)
2119 // i: If(c)
2120 if (phi != nullptr && TrySetPhiInduction(phi, /*restrict_uses*/ false)) {
Aart Bikcc42be02016-10-20 16:14:16 -07002121 HInstruction* s = block->GetFirstInstruction();
2122 if (s != nullptr && s->IsSuspendCheck()) {
2123 HInstruction* c = s->GetNext();
Aart Bikd86c0852017-04-14 12:00:15 -07002124 if (c != nullptr &&
2125 c->IsCondition() &&
2126 c->GetUses().HasExactlyOneElement() && // only used for termination
2127 !c->HasEnvironmentUses()) { // unlikely, but not impossible
Aart Bikcc42be02016-10-20 16:14:16 -07002128 HInstruction* i = c->GetNext();
2129 if (i != nullptr && i->IsIf() && i->InputAt(0) == c) {
2130 iset_->insert(c);
2131 iset_->insert(s);
Aart Bikb29f6842017-07-28 15:58:41 -07002132 *main_phi = phi;
Aart Bikcc42be02016-10-20 16:14:16 -07002133 return true;
2134 }
2135 }
2136 }
2137 }
2138 return false;
2139}
2140
2141bool HLoopOptimization::IsEmptyBody(HBasicBlock* block) {
Aart Bikf8f5a162017-02-06 15:35:29 -08002142 if (!block->GetPhis().IsEmpty()) {
2143 return false;
2144 }
2145 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
2146 HInstruction* instruction = it.Current();
2147 if (!instruction->IsGoto() && iset_->find(instruction) == iset_->end()) {
2148 return false;
Aart Bikcc42be02016-10-20 16:14:16 -07002149 }
Aart Bikf8f5a162017-02-06 15:35:29 -08002150 }
2151 return true;
2152}
2153
2154bool HLoopOptimization::IsUsedOutsideLoop(HLoopInformation* loop_info,
2155 HInstruction* instruction) {
Aart Bikb29f6842017-07-28 15:58:41 -07002156 // Deal with regular uses.
Aart Bikf8f5a162017-02-06 15:35:29 -08002157 for (const HUseListNode<HInstruction*>& use : instruction->GetUses()) {
2158 if (use.GetUser()->GetBlock()->GetLoopInformation() != loop_info) {
2159 return true;
2160 }
Aart Bikcc42be02016-10-20 16:14:16 -07002161 }
2162 return false;
2163}
2164
Aart Bik482095d2016-10-10 15:39:10 -07002165bool HLoopOptimization::IsOnlyUsedAfterLoop(HLoopInformation* loop_info,
Aart Bik8c4a8542016-10-06 11:36:57 -07002166 HInstruction* instruction,
Aart Bik6b69e0a2017-01-11 10:20:43 -08002167 bool collect_loop_uses,
Aart Bik8c4a8542016-10-06 11:36:57 -07002168 /*out*/ int32_t* use_count) {
Aart Bikb29f6842017-07-28 15:58:41 -07002169 // Deal with regular uses.
Aart Bik8c4a8542016-10-06 11:36:57 -07002170 for (const HUseListNode<HInstruction*>& use : instruction->GetUses()) {
2171 HInstruction* user = use.GetUser();
2172 if (iset_->find(user) == iset_->end()) { // not excluded?
2173 HLoopInformation* other_loop_info = user->GetBlock()->GetLoopInformation();
Aart Bik482095d2016-10-10 15:39:10 -07002174 if (other_loop_info != nullptr && other_loop_info->IsIn(*loop_info)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -08002175 // If collect_loop_uses is set, simply keep adding those uses to the set.
2176 // Otherwise, reject uses inside the loop that were not already in the set.
2177 if (collect_loop_uses) {
2178 iset_->insert(user);
2179 continue;
2180 }
Aart Bik8c4a8542016-10-06 11:36:57 -07002181 return false;
2182 }
2183 ++*use_count;
2184 }
2185 }
2186 return true;
2187}
2188
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002189bool HLoopOptimization::TryReplaceWithLastValue(HLoopInformation* loop_info,
2190 HInstruction* instruction,
2191 HBasicBlock* block) {
2192 // Try to replace outside uses with the last value.
Aart Bik807868e2016-11-03 17:51:43 -07002193 if (induction_range_.CanGenerateLastValue(instruction)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -08002194 HInstruction* replacement = induction_range_.GenerateLastValue(instruction, graph_, block);
Aart Bikb29f6842017-07-28 15:58:41 -07002195 // Deal with regular uses.
Aart Bik6b69e0a2017-01-11 10:20:43 -08002196 const HUseList<HInstruction*>& uses = instruction->GetUses();
2197 for (auto it = uses.begin(), end = uses.end(); it != end;) {
2198 HInstruction* user = it->GetUser();
2199 size_t index = it->GetIndex();
2200 ++it; // increment before replacing
2201 if (iset_->find(user) == iset_->end()) { // not excluded?
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002202 if (kIsDebugBuild) {
2203 // We have checked earlier in 'IsOnlyUsedAfterLoop' that the use is after the loop.
2204 HLoopInformation* other_loop_info = user->GetBlock()->GetLoopInformation();
2205 CHECK(other_loop_info == nullptr || !other_loop_info->IsIn(*loop_info));
2206 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08002207 user->ReplaceInput(replacement, index);
2208 induction_range_.Replace(user, instruction, replacement); // update induction
2209 }
2210 }
Aart Bikb29f6842017-07-28 15:58:41 -07002211 // Deal with environment uses.
Aart Bik6b69e0a2017-01-11 10:20:43 -08002212 const HUseList<HEnvironment*>& env_uses = instruction->GetEnvUses();
2213 for (auto it = env_uses.begin(), end = env_uses.end(); it != end;) {
2214 HEnvironment* user = it->GetUser();
2215 size_t index = it->GetIndex();
2216 ++it; // increment before replacing
2217 if (iset_->find(user->GetHolder()) == iset_->end()) { // not excluded?
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002218 // Only update environment uses after the loop.
Aart Bik14a68b42017-06-08 14:06:58 -07002219 HLoopInformation* other_loop_info = user->GetHolder()->GetBlock()->GetLoopInformation();
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002220 if (other_loop_info == nullptr || !other_loop_info->IsIn(*loop_info)) {
2221 user->RemoveAsUserOfInput(index);
2222 user->SetRawEnvAt(index, replacement);
2223 replacement->AddEnvUseAt(user, index);
2224 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08002225 }
2226 }
Aart Bik807868e2016-11-03 17:51:43 -07002227 return true;
Aart Bik8c4a8542016-10-06 11:36:57 -07002228 }
Aart Bik807868e2016-11-03 17:51:43 -07002229 return false;
Aart Bik8c4a8542016-10-06 11:36:57 -07002230}
2231
Aart Bikf8f5a162017-02-06 15:35:29 -08002232bool HLoopOptimization::TryAssignLastValue(HLoopInformation* loop_info,
2233 HInstruction* instruction,
2234 HBasicBlock* block,
2235 bool collect_loop_uses) {
2236 // Assigning the last value is always successful if there are no uses.
2237 // Otherwise, it succeeds in a no early-exit loop by generating the
2238 // proper last value assignment.
2239 int32_t use_count = 0;
2240 return IsOnlyUsedAfterLoop(loop_info, instruction, collect_loop_uses, &use_count) &&
2241 (use_count == 0 ||
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002242 (!IsEarlyExit(loop_info) && TryReplaceWithLastValue(loop_info, instruction, block)));
Aart Bikf8f5a162017-02-06 15:35:29 -08002243}
2244
Aart Bik6b69e0a2017-01-11 10:20:43 -08002245void HLoopOptimization::RemoveDeadInstructions(const HInstructionList& list) {
2246 for (HBackwardInstructionIterator i(list); !i.Done(); i.Advance()) {
2247 HInstruction* instruction = i.Current();
2248 if (instruction->IsDeadAndRemovable()) {
2249 simplified_ = true;
2250 instruction->GetBlock()->RemoveInstructionOrPhi(instruction);
2251 }
2252 }
2253}
2254
Aart Bik14a68b42017-06-08 14:06:58 -07002255bool HLoopOptimization::CanRemoveCycle() {
2256 for (HInstruction* i : *iset_) {
2257 // We can never remove instructions that have environment
2258 // uses when we compile 'debuggable'.
2259 if (i->HasEnvironmentUses() && graph_->IsDebuggable()) {
2260 return false;
2261 }
2262 // A deoptimization should never have an environment input removed.
2263 for (const HUseListNode<HEnvironment*>& use : i->GetEnvUses()) {
2264 if (use.GetUser()->GetHolder()->IsDeoptimize()) {
2265 return false;
2266 }
2267 }
2268 }
2269 return true;
2270}
2271
Aart Bik281c6812016-08-26 11:31:48 -07002272} // namespace art