blob: fec64e2adf260b4d9a1c7c71b0df07b71bd033fc [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,
Aart Bikdf011c32017-09-28 12:53:04 -070077 /*out*/ HInstruction** operand);
Aart Bik68ca7022017-09-26 16:44:23 -070078
Aart Bikdf011c32017-09-28 12:53:04 -070079// Detect a sign extension in instruction from the given type.
Aart Bikdbbac8f2017-09-01 13:06:08 -070080// Returns the promoted operand on success.
Aart Bikf3e61ee2017-04-12 17:09:20 -070081static bool IsSignExtensionAndGet(HInstruction* instruction,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +010082 DataType::Type type,
Aart Bikdf011c32017-09-28 12:53:04 -070083 /*out*/ HInstruction** operand) {
Aart Bikf3e61ee2017-04-12 17:09:20 -070084 // Accept any already wider constant that would be handled properly by sign
85 // extension when represented in the *width* of the given narrower data type
Aart Bikdf011c32017-09-28 12:53:04 -070086 // (the fact that Uint16 normally zero extends does not matter here).
Aart Bikf3e61ee2017-04-12 17:09:20 -070087 int64_t value = 0;
Aart Bik50e20d52017-05-05 14:07:29 -070088 if (IsInt64AndGet(instruction, /*out*/ &value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -070089 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +010090 case DataType::Type::kInt8:
Aart Bikdbbac8f2017-09-01 13:06:08 -070091 if (IsInt<8>(value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -070092 *operand = instruction;
93 return true;
94 }
95 return false;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +010096 case DataType::Type::kUint16:
97 case DataType::Type::kInt16:
Aart Bikdbbac8f2017-09-01 13:06:08 -070098 if (IsInt<16>(value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -070099 *operand = instruction;
100 return true;
101 }
102 return false;
103 default:
104 return false;
105 }
106 }
Aart Bikdf011c32017-09-28 12:53:04 -0700107 // An implicit widening conversion of any signed expression sign-extends.
108 if (instruction->GetType() == type) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700109 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100110 case DataType::Type::kInt8:
111 case DataType::Type::kInt16:
Aart Bikf3e61ee2017-04-12 17:09:20 -0700112 *operand = instruction;
113 return true;
114 default:
115 return false;
116 }
117 }
Aart Bikdf011c32017-09-28 12:53:04 -0700118 // An explicit widening conversion of a signed expression sign-extends.
Aart Bik68ca7022017-09-26 16:44:23 -0700119 if (instruction->IsTypeConversion()) {
Aart Bikdf011c32017-09-28 12:53:04 -0700120 HInstruction* conv = instruction->InputAt(0);
121 DataType::Type from = conv->GetType();
Aart Bik68ca7022017-09-26 16:44:23 -0700122 switch (instruction->GetType()) {
Aart Bikdf011c32017-09-28 12:53:04 -0700123 case DataType::Type::kInt32:
Aart Bik68ca7022017-09-26 16:44:23 -0700124 case DataType::Type::kInt64:
Aart Bikdf011c32017-09-28 12:53:04 -0700125 if (type == from && (from == DataType::Type::kInt8 ||
126 from == DataType::Type::kInt16 ||
127 from == DataType::Type::kInt32)) {
128 *operand = conv;
129 return true;
130 }
131 return false;
Aart Bik68ca7022017-09-26 16:44:23 -0700132 case DataType::Type::kInt16:
133 return type == DataType::Type::kUint16 &&
134 from == DataType::Type::kUint16 &&
Aart Bikdf011c32017-09-28 12:53:04 -0700135 IsZeroExtensionAndGet(instruction->InputAt(0), type, /*out*/ operand);
Aart Bik68ca7022017-09-26 16:44:23 -0700136 default:
137 return false;
138 }
Aart Bikdbbac8f2017-09-01 13:06:08 -0700139 }
Aart Bikf3e61ee2017-04-12 17:09:20 -0700140 return false;
141}
142
Aart Bikdf011c32017-09-28 12:53:04 -0700143// Detect a zero extension in instruction from the given type.
Aart Bikdbbac8f2017-09-01 13:06:08 -0700144// Returns the promoted operand on success.
Aart Bikf3e61ee2017-04-12 17:09:20 -0700145static bool IsZeroExtensionAndGet(HInstruction* instruction,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100146 DataType::Type type,
Aart Bikdf011c32017-09-28 12:53:04 -0700147 /*out*/ HInstruction** operand) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700148 // Accept any already wider constant that would be handled properly by zero
149 // extension when represented in the *width* of the given narrower data type
Aart Bikdf011c32017-09-28 12:53:04 -0700150 // (the fact that Int8/Int16 normally sign extend does not matter here).
Aart Bikf3e61ee2017-04-12 17:09:20 -0700151 int64_t value = 0;
Aart Bik50e20d52017-05-05 14:07:29 -0700152 if (IsInt64AndGet(instruction, /*out*/ &value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700153 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100154 case DataType::Type::kInt8:
Aart Bikdbbac8f2017-09-01 13:06:08 -0700155 if (IsUint<8>(value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700156 *operand = instruction;
157 return true;
158 }
159 return false;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100160 case DataType::Type::kUint16:
161 case DataType::Type::kInt16:
Aart Bikdbbac8f2017-09-01 13:06:08 -0700162 if (IsUint<16>(value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700163 *operand = instruction;
164 return true;
165 }
166 return false;
167 default:
168 return false;
169 }
170 }
Aart Bikdf011c32017-09-28 12:53:04 -0700171 // An implicit widening conversion of any unsigned expression zero-extends.
172 if (instruction->GetType() == type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100173 if (type == DataType::Type::kUint16) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700174 *operand = instruction;
175 return true;
176 }
177 }
178 // A sign (or zero) extension followed by an explicit removal of just the
179 // higher sign bits is equivalent to a zero extension of the underlying operand.
Aart Bikdf011c32017-09-28 12:53:04 -0700180 //
181 // TODO: move this into simplifier and use new type system instead.
182 //
Aart Bikf3e61ee2017-04-12 17:09:20 -0700183 if (instruction->IsAnd()) {
184 int64_t mask = 0;
185 HInstruction* a = instruction->InputAt(0);
186 HInstruction* b = instruction->InputAt(1);
187 // In (a & b) find (mask & b) or (a & mask) with sign or zero extension on the non-mask.
188 if ((IsInt64AndGet(a, /*out*/ &mask) && (IsSignExtensionAndGet(b, type, /*out*/ operand) ||
189 IsZeroExtensionAndGet(b, type, /*out*/ operand))) ||
190 (IsInt64AndGet(b, /*out*/ &mask) && (IsSignExtensionAndGet(a, type, /*out*/ operand) ||
191 IsZeroExtensionAndGet(a, type, /*out*/ operand)))) {
192 switch ((*operand)->GetType()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100193 case DataType::Type::kInt8:
Aart Bikdbbac8f2017-09-01 13:06:08 -0700194 return mask == std::numeric_limits<uint8_t>::max();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100195 case DataType::Type::kUint16:
196 case DataType::Type::kInt16:
Aart Bikdbbac8f2017-09-01 13:06:08 -0700197 return mask == std::numeric_limits<uint16_t>::max();
Aart Bikf3e61ee2017-04-12 17:09:20 -0700198 default: return false;
199 }
200 }
201 }
Aart Bikdf011c32017-09-28 12:53:04 -0700202 // An explicit widening conversion of an unsigned expression zero-extends.
Aart Bik68ca7022017-09-26 16:44:23 -0700203 if (instruction->IsTypeConversion()) {
Aart Bikdf011c32017-09-28 12:53:04 -0700204 HInstruction* conv = instruction->InputAt(0);
205 DataType::Type from = conv->GetType();
Aart Bik68ca7022017-09-26 16:44:23 -0700206 switch (instruction->GetType()) {
Aart Bikdf011c32017-09-28 12:53:04 -0700207 case DataType::Type::kInt32:
Aart Bik68ca7022017-09-26 16:44:23 -0700208 case DataType::Type::kInt64:
Aart Bikdf011c32017-09-28 12:53:04 -0700209 if (type == from && from == DataType::Type::kUint16) {
210 *operand = conv;
211 return true;
212 }
213 return false;
Aart Bik68ca7022017-09-26 16:44:23 -0700214 case DataType::Type::kUint16:
215 return type == DataType::Type::kInt16 &&
216 from == DataType::Type::kInt16 &&
Aart Bikdf011c32017-09-28 12:53:04 -0700217 IsSignExtensionAndGet(instruction->InputAt(0), type, /*out*/ operand);
Aart Bik68ca7022017-09-26 16:44:23 -0700218 default:
219 return false;
220 }
Aart Bikdbbac8f2017-09-01 13:06:08 -0700221 }
Aart Bikf3e61ee2017-04-12 17:09:20 -0700222 return false;
223}
224
Aart Bik304c8a52017-05-23 11:01:13 -0700225// Detect situations with same-extension narrower operands.
226// Returns true on success and sets is_unsigned accordingly.
227static bool IsNarrowerOperands(HInstruction* a,
228 HInstruction* b,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100229 DataType::Type type,
Aart Bik304c8a52017-05-23 11:01:13 -0700230 /*out*/ HInstruction** r,
231 /*out*/ HInstruction** s,
232 /*out*/ bool* is_unsigned) {
233 if (IsSignExtensionAndGet(a, type, r) && IsSignExtensionAndGet(b, type, s)) {
234 *is_unsigned = false;
235 return true;
236 } else if (IsZeroExtensionAndGet(a, type, r) && IsZeroExtensionAndGet(b, type, s)) {
237 *is_unsigned = true;
238 return true;
239 }
240 return false;
241}
242
243// As above, single operand.
244static bool IsNarrowerOperand(HInstruction* a,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100245 DataType::Type type,
Aart Bik304c8a52017-05-23 11:01:13 -0700246 /*out*/ HInstruction** r,
247 /*out*/ bool* is_unsigned) {
248 if (IsSignExtensionAndGet(a, type, r)) {
249 *is_unsigned = false;
250 return true;
251 } else if (IsZeroExtensionAndGet(a, type, r)) {
252 *is_unsigned = true;
253 return true;
254 }
255 return false;
256}
257
Aart Bikdbbac8f2017-09-01 13:06:08 -0700258// Compute relative vector length based on type difference.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100259static size_t GetOtherVL(DataType::Type other_type, DataType::Type vector_type, size_t vl) {
Aart Bikdbbac8f2017-09-01 13:06:08 -0700260 switch (other_type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100261 case DataType::Type::kBool:
262 case DataType::Type::kInt8:
Aart Bikdbbac8f2017-09-01 13:06:08 -0700263 switch (vector_type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100264 case DataType::Type::kBool:
265 case DataType::Type::kInt8: return vl;
Aart Bikdbbac8f2017-09-01 13:06:08 -0700266 default: break;
267 }
268 return vl;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100269 case DataType::Type::kUint16:
270 case DataType::Type::kInt16:
Aart Bikdbbac8f2017-09-01 13:06:08 -0700271 switch (vector_type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100272 case DataType::Type::kBool:
273 case DataType::Type::kInt8: return vl >> 1;
274 case DataType::Type::kUint16:
275 case DataType::Type::kInt16: return vl;
Aart Bikdbbac8f2017-09-01 13:06:08 -0700276 default: break;
277 }
278 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100279 case DataType::Type::kInt32:
Aart Bikdbbac8f2017-09-01 13:06:08 -0700280 switch (vector_type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100281 case DataType::Type::kBool:
282 case DataType::Type::kInt8: return vl >> 2;
283 case DataType::Type::kUint16:
284 case DataType::Type::kInt16: return vl >> 1;
285 case DataType::Type::kInt32: return vl;
Aart Bikdbbac8f2017-09-01 13:06:08 -0700286 default: break;
287 }
288 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100289 case DataType::Type::kInt64:
Aart Bikdbbac8f2017-09-01 13:06:08 -0700290 switch (vector_type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100291 case DataType::Type::kBool:
292 case DataType::Type::kInt8: return vl >> 3;
293 case DataType::Type::kUint16:
294 case DataType::Type::kInt16: return vl >> 2;
295 case DataType::Type::kInt32: return vl >> 1;
296 case DataType::Type::kInt64: return vl;
Aart Bikdbbac8f2017-09-01 13:06:08 -0700297 default: break;
298 }
299 break;
300 default:
301 break;
302 }
303 LOG(FATAL) << "Unsupported idiom conversion";
304 UNREACHABLE();
305}
306
Aart Bik5f805002017-05-16 16:42:41 -0700307// Detect up to two instructions a and b, and an acccumulated constant c.
308static bool IsAddConstHelper(HInstruction* instruction,
309 /*out*/ HInstruction** a,
310 /*out*/ HInstruction** b,
311 /*out*/ int64_t* c,
312 int32_t depth) {
313 static constexpr int32_t kMaxDepth = 8; // don't search too deep
314 int64_t value = 0;
315 if (IsInt64AndGet(instruction, &value)) {
316 *c += value;
317 return true;
318 } else if (instruction->IsAdd() && depth <= kMaxDepth) {
319 return IsAddConstHelper(instruction->InputAt(0), a, b, c, depth + 1) &&
320 IsAddConstHelper(instruction->InputAt(1), a, b, c, depth + 1);
321 } else if (*a == nullptr) {
322 *a = instruction;
323 return true;
324 } else if (*b == nullptr) {
325 *b = instruction;
326 return true;
327 }
328 return false; // too many non-const operands
329}
330
331// Detect a + b + c for an optional constant c.
332static bool IsAddConst(HInstruction* instruction,
333 /*out*/ HInstruction** a,
334 /*out*/ HInstruction** b,
335 /*out*/ int64_t* c) {
336 if (instruction->IsAdd()) {
337 // Try to find a + b and accumulated c.
338 if (IsAddConstHelper(instruction->InputAt(0), a, b, c, /*depth*/ 0) &&
339 IsAddConstHelper(instruction->InputAt(1), a, b, c, /*depth*/ 0) &&
340 *b != nullptr) {
341 return true;
342 }
343 // Found a + b.
344 *a = instruction->InputAt(0);
345 *b = instruction->InputAt(1);
346 *c = 0;
347 return true;
348 }
349 return false;
350}
351
Aart Bikdf011c32017-09-28 12:53:04 -0700352// Detect a + c for constant c.
353static bool IsAddConst(HInstruction* instruction,
354 /*out*/ HInstruction** a,
355 /*out*/ int64_t* c) {
356 if (instruction->IsAdd()) {
357 if (IsInt64AndGet(instruction->InputAt(0), c)) {
358 *a = instruction->InputAt(1);
359 return true;
360 } else if (IsInt64AndGet(instruction->InputAt(1), c)) {
361 *a = instruction->InputAt(0);
362 return true;
363 }
364 }
365 return false;
366}
367
Aart Bikb29f6842017-07-28 15:58:41 -0700368// Detect reductions of the following forms,
Aart Bikb29f6842017-07-28 15:58:41 -0700369// x = x_phi + ..
370// x = x_phi - ..
371// x = max(x_phi, ..)
372// x = min(x_phi, ..)
373static bool HasReductionFormat(HInstruction* reduction, HInstruction* phi) {
374 if (reduction->IsAdd()) {
Aart Bikdbbac8f2017-09-01 13:06:08 -0700375 return (reduction->InputAt(0) == phi && reduction->InputAt(1) != phi) ||
376 (reduction->InputAt(0) != phi && reduction->InputAt(1) == phi);
Aart Bikb29f6842017-07-28 15:58:41 -0700377 } else if (reduction->IsSub()) {
Aart Bikdbbac8f2017-09-01 13:06:08 -0700378 return (reduction->InputAt(0) == phi && reduction->InputAt(1) != phi);
Aart Bikb29f6842017-07-28 15:58:41 -0700379 } else if (reduction->IsInvokeStaticOrDirect()) {
380 switch (reduction->AsInvokeStaticOrDirect()->GetIntrinsic()) {
381 case Intrinsics::kMathMinIntInt:
382 case Intrinsics::kMathMinLongLong:
383 case Intrinsics::kMathMinFloatFloat:
384 case Intrinsics::kMathMinDoubleDouble:
385 case Intrinsics::kMathMaxIntInt:
386 case Intrinsics::kMathMaxLongLong:
387 case Intrinsics::kMathMaxFloatFloat:
388 case Intrinsics::kMathMaxDoubleDouble:
Aart Bikdbbac8f2017-09-01 13:06:08 -0700389 return (reduction->InputAt(0) == phi && reduction->InputAt(1) != phi) ||
390 (reduction->InputAt(0) != phi && reduction->InputAt(1) == phi);
Aart Bikb29f6842017-07-28 15:58:41 -0700391 default:
392 return false;
393 }
394 }
395 return false;
396}
397
Aart Bikdbbac8f2017-09-01 13:06:08 -0700398// Translates vector operation to reduction kind.
399static HVecReduce::ReductionKind GetReductionKind(HVecOperation* reduction) {
400 if (reduction->IsVecAdd() || reduction->IsVecSub() || reduction->IsVecSADAccumulate()) {
Aart Bik0148de42017-09-05 09:25:01 -0700401 return HVecReduce::kSum;
402 } else if (reduction->IsVecMin()) {
403 return HVecReduce::kMin;
404 } else if (reduction->IsVecMax()) {
405 return HVecReduce::kMax;
406 }
407 LOG(FATAL) << "Unsupported SIMD reduction";
408 UNREACHABLE();
409}
410
Aart Bikf8f5a162017-02-06 15:35:29 -0800411// Test vector restrictions.
412static bool HasVectorRestrictions(uint64_t restrictions, uint64_t tested) {
413 return (restrictions & tested) != 0;
414}
415
Aart Bikf3e61ee2017-04-12 17:09:20 -0700416// Insert an instruction.
Aart Bikf8f5a162017-02-06 15:35:29 -0800417static HInstruction* Insert(HBasicBlock* block, HInstruction* instruction) {
418 DCHECK(block != nullptr);
419 DCHECK(instruction != nullptr);
420 block->InsertInstructionBefore(instruction, block->GetLastInstruction());
421 return instruction;
422}
423
Artem Serov21c7e6f2017-07-27 16:04:42 +0100424// Check that instructions from the induction sets are fully removed: have no uses
425// and no other instructions use them.
426static bool CheckInductionSetFullyRemoved(ArenaSet<HInstruction*>* iset) {
427 for (HInstruction* instr : *iset) {
428 if (instr->GetBlock() != nullptr ||
429 !instr->GetUses().empty() ||
430 !instr->GetEnvUses().empty() ||
431 HasEnvironmentUsedByOthers(instr)) {
432 return false;
433 }
434 }
Artem Serov21c7e6f2017-07-27 16:04:42 +0100435 return true;
436}
437
Aart Bik281c6812016-08-26 11:31:48 -0700438//
Aart Bikb29f6842017-07-28 15:58:41 -0700439// Public methods.
Aart Bik281c6812016-08-26 11:31:48 -0700440//
441
442HLoopOptimization::HLoopOptimization(HGraph* graph,
Aart Bik92685a82017-03-06 11:13:43 -0800443 CompilerDriver* compiler_driver,
Aart Bikb92cc332017-09-06 15:53:17 -0700444 HInductionVarAnalysis* induction_analysis,
445 OptimizingCompilerStats* stats)
446 : HOptimization(graph, kLoopOptimizationPassName, stats),
Aart Bik92685a82017-03-06 11:13:43 -0800447 compiler_driver_(compiler_driver),
Aart Bik281c6812016-08-26 11:31:48 -0700448 induction_range_(induction_analysis),
Aart Bik96202302016-10-04 17:33:56 -0700449 loop_allocator_(nullptr),
Aart Bikf8f5a162017-02-06 15:35:29 -0800450 global_allocator_(graph_->GetArena()),
Aart Bik281c6812016-08-26 11:31:48 -0700451 top_loop_(nullptr),
Aart Bik8c4a8542016-10-06 11:36:57 -0700452 last_loop_(nullptr),
Aart Bik482095d2016-10-10 15:39:10 -0700453 iset_(nullptr),
Aart Bikb29f6842017-07-28 15:58:41 -0700454 reductions_(nullptr),
Aart Bikf8f5a162017-02-06 15:35:29 -0800455 simplified_(false),
456 vector_length_(0),
457 vector_refs_(nullptr),
Aart Bik14a68b42017-06-08 14:06:58 -0700458 vector_peeling_candidate_(nullptr),
459 vector_runtime_test_a_(nullptr),
460 vector_runtime_test_b_(nullptr),
Aart Bik0148de42017-09-05 09:25:01 -0700461 vector_map_(nullptr),
462 vector_permanent_map_(nullptr) {
Aart Bik281c6812016-08-26 11:31:48 -0700463}
464
465void HLoopOptimization::Run() {
Mingyao Yang01b47b02017-02-03 12:09:57 -0800466 // Skip if there is no loop or the graph has try-catch/irreducible loops.
Aart Bik281c6812016-08-26 11:31:48 -0700467 // TODO: make this less of a sledgehammer.
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800468 if (!graph_->HasLoops() || graph_->HasTryCatch() || graph_->HasIrreducibleLoops()) {
Aart Bik281c6812016-08-26 11:31:48 -0700469 return;
470 }
471
Aart Bik96202302016-10-04 17:33:56 -0700472 // Phase-local allocator that draws from the global pool. Since the allocator
473 // itself resides on the stack, it is destructed on exiting Run(), which
474 // implies its underlying memory is released immediately.
Aart Bikf8f5a162017-02-06 15:35:29 -0800475 ArenaAllocator allocator(global_allocator_->GetArenaPool());
Aart Bik96202302016-10-04 17:33:56 -0700476 loop_allocator_ = &allocator;
Nicolas Geoffrayebe16742016-10-05 09:55:42 +0100477
Aart Bik96202302016-10-04 17:33:56 -0700478 // Perform loop optimizations.
479 LocalRun();
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800480 if (top_loop_ == nullptr) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800481 graph_->SetHasLoops(false); // no more loops
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800482 }
483
Aart Bik96202302016-10-04 17:33:56 -0700484 // Detach.
485 loop_allocator_ = nullptr;
486 last_loop_ = top_loop_ = nullptr;
487}
488
Aart Bikb29f6842017-07-28 15:58:41 -0700489//
490// Loop setup and traversal.
491//
492
Aart Bik96202302016-10-04 17:33:56 -0700493void HLoopOptimization::LocalRun() {
494 // Build the linear order using the phase-local allocator. This step enables building
495 // a loop hierarchy that properly reflects the outer-inner and previous-next relation.
496 ArenaVector<HBasicBlock*> linear_order(loop_allocator_->Adapter(kArenaAllocLinearOrder));
497 LinearizeGraph(graph_, loop_allocator_, &linear_order);
498
Aart Bik281c6812016-08-26 11:31:48 -0700499 // Build the loop hierarchy.
Aart Bik96202302016-10-04 17:33:56 -0700500 for (HBasicBlock* block : linear_order) {
Aart Bik281c6812016-08-26 11:31:48 -0700501 if (block->IsLoopHeader()) {
502 AddLoop(block->GetLoopInformation());
503 }
504 }
Aart Bik96202302016-10-04 17:33:56 -0700505
Aart Bik8c4a8542016-10-06 11:36:57 -0700506 // Traverse the loop hierarchy inner-to-outer and optimize. Traversal can use
Aart Bikf8f5a162017-02-06 15:35:29 -0800507 // temporary data structures using the phase-local allocator. All new HIR
508 // should use the global allocator.
Aart Bik8c4a8542016-10-06 11:36:57 -0700509 if (top_loop_ != nullptr) {
510 ArenaSet<HInstruction*> iset(loop_allocator_->Adapter(kArenaAllocLoopOptimization));
Aart Bikb29f6842017-07-28 15:58:41 -0700511 ArenaSafeMap<HInstruction*, HInstruction*> reds(
512 std::less<HInstruction*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
Aart Bikf8f5a162017-02-06 15:35:29 -0800513 ArenaSet<ArrayReference> refs(loop_allocator_->Adapter(kArenaAllocLoopOptimization));
514 ArenaSafeMap<HInstruction*, HInstruction*> map(
515 std::less<HInstruction*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
Aart Bik0148de42017-09-05 09:25:01 -0700516 ArenaSafeMap<HInstruction*, HInstruction*> perm(
517 std::less<HInstruction*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
Aart Bikf8f5a162017-02-06 15:35:29 -0800518 // Attach.
Aart Bik8c4a8542016-10-06 11:36:57 -0700519 iset_ = &iset;
Aart Bikb29f6842017-07-28 15:58:41 -0700520 reductions_ = &reds;
Aart Bikf8f5a162017-02-06 15:35:29 -0800521 vector_refs_ = &refs;
522 vector_map_ = &map;
Aart Bik0148de42017-09-05 09:25:01 -0700523 vector_permanent_map_ = &perm;
Aart Bikf8f5a162017-02-06 15:35:29 -0800524 // Traverse.
Aart Bik8c4a8542016-10-06 11:36:57 -0700525 TraverseLoopsInnerToOuter(top_loop_);
Aart Bikf8f5a162017-02-06 15:35:29 -0800526 // Detach.
527 iset_ = nullptr;
Aart Bikb29f6842017-07-28 15:58:41 -0700528 reductions_ = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800529 vector_refs_ = nullptr;
530 vector_map_ = nullptr;
Aart Bik0148de42017-09-05 09:25:01 -0700531 vector_permanent_map_ = nullptr;
Aart Bik8c4a8542016-10-06 11:36:57 -0700532 }
Aart Bik281c6812016-08-26 11:31:48 -0700533}
534
535void HLoopOptimization::AddLoop(HLoopInformation* loop_info) {
536 DCHECK(loop_info != nullptr);
Aart Bikf8f5a162017-02-06 15:35:29 -0800537 LoopNode* node = new (loop_allocator_) LoopNode(loop_info);
Aart Bik281c6812016-08-26 11:31:48 -0700538 if (last_loop_ == nullptr) {
539 // First loop.
540 DCHECK(top_loop_ == nullptr);
541 last_loop_ = top_loop_ = node;
542 } else if (loop_info->IsIn(*last_loop_->loop_info)) {
543 // Inner loop.
544 node->outer = last_loop_;
545 DCHECK(last_loop_->inner == nullptr);
546 last_loop_ = last_loop_->inner = node;
547 } else {
548 // Subsequent loop.
549 while (last_loop_->outer != nullptr && !loop_info->IsIn(*last_loop_->outer->loop_info)) {
550 last_loop_ = last_loop_->outer;
551 }
552 node->outer = last_loop_->outer;
553 node->previous = last_loop_;
554 DCHECK(last_loop_->next == nullptr);
555 last_loop_ = last_loop_->next = node;
556 }
557}
558
559void HLoopOptimization::RemoveLoop(LoopNode* node) {
560 DCHECK(node != nullptr);
Aart Bik8c4a8542016-10-06 11:36:57 -0700561 DCHECK(node->inner == nullptr);
562 if (node->previous != nullptr) {
563 // Within sequence.
564 node->previous->next = node->next;
565 if (node->next != nullptr) {
566 node->next->previous = node->previous;
567 }
568 } else {
569 // First of sequence.
570 if (node->outer != nullptr) {
571 node->outer->inner = node->next;
572 } else {
573 top_loop_ = node->next;
574 }
575 if (node->next != nullptr) {
576 node->next->outer = node->outer;
577 node->next->previous = nullptr;
578 }
579 }
Aart Bik281c6812016-08-26 11:31:48 -0700580}
581
Aart Bikb29f6842017-07-28 15:58:41 -0700582bool HLoopOptimization::TraverseLoopsInnerToOuter(LoopNode* node) {
583 bool changed = false;
Aart Bik281c6812016-08-26 11:31:48 -0700584 for ( ; node != nullptr; node = node->next) {
Aart Bikb29f6842017-07-28 15:58:41 -0700585 // Visit inner loops first. Recompute induction information for this
586 // loop if the induction of any inner loop has changed.
587 if (TraverseLoopsInnerToOuter(node->inner)) {
Aart Bik482095d2016-10-10 15:39:10 -0700588 induction_range_.ReVisit(node->loop_info);
589 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800590 // Repeat simplifications in the loop-body until no more changes occur.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800591 // Note that since each simplification consists of eliminating code (without
592 // introducing new code), this process is always finite.
Aart Bikdf7822e2016-12-06 10:05:30 -0800593 do {
594 simplified_ = false;
Aart Bikdf7822e2016-12-06 10:05:30 -0800595 SimplifyInduction(node);
Aart Bik6b69e0a2017-01-11 10:20:43 -0800596 SimplifyBlocks(node);
Aart Bikb29f6842017-07-28 15:58:41 -0700597 changed = simplified_ || changed;
Aart Bikdf7822e2016-12-06 10:05:30 -0800598 } while (simplified_);
Aart Bikf8f5a162017-02-06 15:35:29 -0800599 // Optimize inner loop.
Aart Bik9abf8942016-10-14 09:49:42 -0700600 if (node->inner == nullptr) {
Aart Bikb29f6842017-07-28 15:58:41 -0700601 changed = OptimizeInnerLoop(node) || changed;
Aart Bik9abf8942016-10-14 09:49:42 -0700602 }
Aart Bik281c6812016-08-26 11:31:48 -0700603 }
Aart Bikb29f6842017-07-28 15:58:41 -0700604 return changed;
Aart Bik281c6812016-08-26 11:31:48 -0700605}
606
Aart Bikf8f5a162017-02-06 15:35:29 -0800607//
608// Optimization.
609//
610
Aart Bik281c6812016-08-26 11:31:48 -0700611void HLoopOptimization::SimplifyInduction(LoopNode* node) {
612 HBasicBlock* header = node->loop_info->GetHeader();
613 HBasicBlock* preheader = node->loop_info->GetPreHeader();
Aart Bik8c4a8542016-10-06 11:36:57 -0700614 // Scan the phis in the header to find opportunities to simplify an induction
615 // cycle that is only used outside the loop. Replace these uses, if any, with
616 // the last value and remove the induction cycle.
617 // Examples: for (int i = 0; x != null; i++) { .... no i .... }
618 // for (int i = 0; i < 10; i++, k++) { .... no k .... } return k;
Aart Bik281c6812016-08-26 11:31:48 -0700619 for (HInstructionIterator it(header->GetPhis()); !it.Done(); it.Advance()) {
620 HPhi* phi = it.Current()->AsPhi();
Aart Bikf8f5a162017-02-06 15:35:29 -0800621 if (TrySetPhiInduction(phi, /*restrict_uses*/ true) &&
622 TryAssignLastValue(node->loop_info, phi, preheader, /*collect_loop_uses*/ false)) {
Aart Bik671e48a2017-08-09 13:16:56 -0700623 // Note that it's ok to have replaced uses after the loop with the last value, without
624 // being able to remove the cycle. Environment uses (which are the reason we may not be
625 // able to remove the cycle) within the loop will still hold the right value. We must
626 // have tried first, however, to replace outside uses.
627 if (CanRemoveCycle()) {
628 simplified_ = true;
629 for (HInstruction* i : *iset_) {
630 RemoveFromCycle(i);
631 }
632 DCHECK(CheckInductionSetFullyRemoved(iset_));
Aart Bik281c6812016-08-26 11:31:48 -0700633 }
Aart Bik482095d2016-10-10 15:39:10 -0700634 }
635 }
636}
637
638void HLoopOptimization::SimplifyBlocks(LoopNode* node) {
Aart Bikdf7822e2016-12-06 10:05:30 -0800639 // Iterate over all basic blocks in the loop-body.
640 for (HBlocksInLoopIterator it(*node->loop_info); !it.Done(); it.Advance()) {
641 HBasicBlock* block = it.Current();
642 // Remove dead instructions from the loop-body.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800643 RemoveDeadInstructions(block->GetPhis());
644 RemoveDeadInstructions(block->GetInstructions());
Aart Bikdf7822e2016-12-06 10:05:30 -0800645 // Remove trivial control flow blocks from the loop-body.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800646 if (block->GetPredecessors().size() == 1 &&
647 block->GetSuccessors().size() == 1 &&
648 block->GetSingleSuccessor()->GetPredecessors().size() == 1) {
Aart Bikdf7822e2016-12-06 10:05:30 -0800649 simplified_ = true;
Aart Bik6b69e0a2017-01-11 10:20:43 -0800650 block->MergeWith(block->GetSingleSuccessor());
Aart Bikdf7822e2016-12-06 10:05:30 -0800651 } else if (block->GetSuccessors().size() == 2) {
652 // Trivial if block can be bypassed to either branch.
653 HBasicBlock* succ0 = block->GetSuccessors()[0];
654 HBasicBlock* succ1 = block->GetSuccessors()[1];
655 HBasicBlock* meet0 = nullptr;
656 HBasicBlock* meet1 = nullptr;
657 if (succ0 != succ1 &&
658 IsGotoBlock(succ0, &meet0) &&
659 IsGotoBlock(succ1, &meet1) &&
660 meet0 == meet1 && // meets again
661 meet0 != block && // no self-loop
662 meet0->GetPhis().IsEmpty()) { // not used for merging
663 simplified_ = true;
664 succ0->DisconnectAndDelete();
665 if (block->Dominates(meet0)) {
666 block->RemoveDominatedBlock(meet0);
667 succ1->AddDominatedBlock(meet0);
668 meet0->SetDominator(succ1);
Aart Bike3dedc52016-11-02 17:50:27 -0700669 }
Aart Bik482095d2016-10-10 15:39:10 -0700670 }
Aart Bik281c6812016-08-26 11:31:48 -0700671 }
Aart Bikdf7822e2016-12-06 10:05:30 -0800672 }
Aart Bik281c6812016-08-26 11:31:48 -0700673}
674
Aart Bikb29f6842017-07-28 15:58:41 -0700675bool HLoopOptimization::OptimizeInnerLoop(LoopNode* node) {
Aart Bik281c6812016-08-26 11:31:48 -0700676 HBasicBlock* header = node->loop_info->GetHeader();
677 HBasicBlock* preheader = node->loop_info->GetPreHeader();
Aart Bik9abf8942016-10-14 09:49:42 -0700678 // Ensure loop header logic is finite.
Aart Bikf8f5a162017-02-06 15:35:29 -0800679 int64_t trip_count = 0;
680 if (!induction_range_.IsFinite(node->loop_info, &trip_count)) {
Aart Bikb29f6842017-07-28 15:58:41 -0700681 return false;
Aart Bik9abf8942016-10-14 09:49:42 -0700682 }
Aart Bik281c6812016-08-26 11:31:48 -0700683 // Ensure there is only a single loop-body (besides the header).
684 HBasicBlock* body = nullptr;
685 for (HBlocksInLoopIterator it(*node->loop_info); !it.Done(); it.Advance()) {
686 if (it.Current() != header) {
687 if (body != nullptr) {
Aart Bikb29f6842017-07-28 15:58:41 -0700688 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700689 }
690 body = it.Current();
691 }
692 }
Andreas Gampef45d61c2017-06-07 10:29:33 -0700693 CHECK(body != nullptr);
Aart Bik281c6812016-08-26 11:31:48 -0700694 // Ensure there is only a single exit point.
695 if (header->GetSuccessors().size() != 2) {
Aart Bikb29f6842017-07-28 15:58:41 -0700696 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700697 }
698 HBasicBlock* exit = (header->GetSuccessors()[0] == body)
699 ? header->GetSuccessors()[1]
700 : header->GetSuccessors()[0];
Aart Bik8c4a8542016-10-06 11:36:57 -0700701 // Ensure exit can only be reached by exiting loop.
Aart Bik281c6812016-08-26 11:31:48 -0700702 if (exit->GetPredecessors().size() != 1) {
Aart Bikb29f6842017-07-28 15:58:41 -0700703 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700704 }
Aart Bik6b69e0a2017-01-11 10:20:43 -0800705 // Detect either an empty loop (no side effects other than plain iteration) or
706 // a trivial loop (just iterating once). Replace subsequent index uses, if any,
707 // with the last value and remove the loop, possibly after unrolling its body.
Aart Bikb29f6842017-07-28 15:58:41 -0700708 HPhi* main_phi = nullptr;
709 if (TrySetSimpleLoopHeader(header, &main_phi)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -0800710 bool is_empty = IsEmptyBody(body);
Aart Bikb29f6842017-07-28 15:58:41 -0700711 if (reductions_->empty() && // TODO: possible with some effort
712 (is_empty || trip_count == 1) &&
713 TryAssignLastValue(node->loop_info, main_phi, preheader, /*collect_loop_uses*/ true)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -0800714 if (!is_empty) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800715 // Unroll the loop-body, which sees initial value of the index.
Aart Bikb29f6842017-07-28 15:58:41 -0700716 main_phi->ReplaceWith(main_phi->InputAt(0));
Aart Bik6b69e0a2017-01-11 10:20:43 -0800717 preheader->MergeInstructionsWith(body);
718 }
719 body->DisconnectAndDelete();
720 exit->RemovePredecessor(header);
721 header->RemoveSuccessor(exit);
722 header->RemoveDominatedBlock(exit);
723 header->DisconnectAndDelete();
724 preheader->AddSuccessor(exit);
Aart Bikf8f5a162017-02-06 15:35:29 -0800725 preheader->AddInstruction(new (global_allocator_) HGoto());
Aart Bik6b69e0a2017-01-11 10:20:43 -0800726 preheader->AddDominatedBlock(exit);
727 exit->SetDominator(preheader);
728 RemoveLoop(node); // update hierarchy
Aart Bikb29f6842017-07-28 15:58:41 -0700729 return true;
Aart Bikf8f5a162017-02-06 15:35:29 -0800730 }
731 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800732 // Vectorize loop, if possible and valid.
Aart Bikb29f6842017-07-28 15:58:41 -0700733 if (kEnableVectorization &&
734 TrySetSimpleLoopHeader(header, &main_phi) &&
Aart Bikb29f6842017-07-28 15:58:41 -0700735 ShouldVectorize(node, body, trip_count) &&
736 TryAssignLastValue(node->loop_info, main_phi, preheader, /*collect_loop_uses*/ true)) {
737 Vectorize(node, body, exit, trip_count);
738 graph_->SetHasSIMD(true); // flag SIMD usage
Aart Bik21b85922017-09-06 13:29:16 -0700739 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorized);
Aart Bikb29f6842017-07-28 15:58:41 -0700740 return true;
Aart Bikf8f5a162017-02-06 15:35:29 -0800741 }
Aart Bikb29f6842017-07-28 15:58:41 -0700742 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -0800743}
744
745//
746// Loop vectorization. The implementation is based on the book by Aart J.C. Bik:
747// "The Software Vectorization Handbook. Applying Multimedia Extensions for Maximum Performance."
748// Intel Press, June, 2004 (http://www.aartbik.com/).
749//
750
Aart Bik14a68b42017-06-08 14:06:58 -0700751bool HLoopOptimization::ShouldVectorize(LoopNode* node, HBasicBlock* block, int64_t trip_count) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800752 // Reset vector bookkeeping.
753 vector_length_ = 0;
754 vector_refs_->clear();
Aart Bik14a68b42017-06-08 14:06:58 -0700755 vector_peeling_candidate_ = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800756 vector_runtime_test_a_ =
757 vector_runtime_test_b_= nullptr;
758
759 // Phis in the loop-body prevent vectorization.
760 if (!block->GetPhis().IsEmpty()) {
761 return false;
762 }
763
764 // Scan the loop-body, starting a right-hand-side tree traversal at each left-hand-side
765 // occurrence, which allows passing down attributes down the use tree.
766 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
767 if (!VectorizeDef(node, it.Current(), /*generate_code*/ false)) {
768 return false; // failure to vectorize a left-hand-side
769 }
770 }
771
Aart Bik14a68b42017-06-08 14:06:58 -0700772 // Does vectorization seem profitable?
773 if (!IsVectorizationProfitable(trip_count)) {
774 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -0800775 }
776
777 // Data dependence analysis. Find each pair of references with same type, where
778 // at least one is a write. Each such pair denotes a possible data dependence.
779 // This analysis exploits the property that differently typed arrays cannot be
780 // aliased, as well as the property that references either point to the same
781 // array or to two completely disjoint arrays, i.e., no partial aliasing.
782 // Other than a few simply heuristics, no detailed subscript analysis is done.
Aart Bikb29f6842017-07-28 15:58:41 -0700783 // The scan over references also finds a suitable dynamic loop peeling candidate.
784 const ArrayReference* candidate = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800785 for (auto i = vector_refs_->begin(); i != vector_refs_->end(); ++i) {
786 for (auto j = i; ++j != vector_refs_->end(); ) {
787 if (i->type == j->type && (i->lhs || j->lhs)) {
788 // Found same-typed a[i+x] vs. b[i+y], where at least one is a write.
789 HInstruction* a = i->base;
790 HInstruction* b = j->base;
791 HInstruction* x = i->offset;
792 HInstruction* y = j->offset;
793 if (a == b) {
794 // Found a[i+x] vs. a[i+y]. Accept if x == y (loop-independent data dependence).
795 // Conservatively assume a loop-carried data dependence otherwise, and reject.
796 if (x != y) {
797 return false;
798 }
799 } else {
800 // Found a[i+x] vs. b[i+y]. Accept if x == y (at worst loop-independent data dependence).
801 // Conservatively assume a potential loop-carried data dependence otherwise, avoided by
802 // generating an explicit a != b disambiguation runtime test on the two references.
803 if (x != y) {
Aart Bik37dc4df2017-06-28 14:08:00 -0700804 // To avoid excessive overhead, we only accept one a != b test.
805 if (vector_runtime_test_a_ == nullptr) {
806 // First test found.
807 vector_runtime_test_a_ = a;
808 vector_runtime_test_b_ = b;
809 } else if ((vector_runtime_test_a_ != a || vector_runtime_test_b_ != b) &&
810 (vector_runtime_test_a_ != b || vector_runtime_test_b_ != a)) {
811 return false; // second test would be needed
Aart Bikf8f5a162017-02-06 15:35:29 -0800812 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800813 }
814 }
815 }
816 }
817 }
818
Aart Bik14a68b42017-06-08 14:06:58 -0700819 // Consider dynamic loop peeling for alignment.
Aart Bikb29f6842017-07-28 15:58:41 -0700820 SetPeelingCandidate(candidate, trip_count);
Aart Bik14a68b42017-06-08 14:06:58 -0700821
Aart Bikf8f5a162017-02-06 15:35:29 -0800822 // Success!
823 return true;
824}
825
826void HLoopOptimization::Vectorize(LoopNode* node,
827 HBasicBlock* block,
828 HBasicBlock* exit,
829 int64_t trip_count) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800830 HBasicBlock* header = node->loop_info->GetHeader();
831 HBasicBlock* preheader = node->loop_info->GetPreHeader();
832
Aart Bik14a68b42017-06-08 14:06:58 -0700833 // Pick a loop unrolling factor for the vector loop.
834 uint32_t unroll = GetUnrollingFactor(block, trip_count);
835 uint32_t chunk = vector_length_ * unroll;
836
837 // A cleanup loop is needed, at least, for any unknown trip count or
838 // for a known trip count with remainder iterations after vectorization.
839 bool needs_cleanup = trip_count == 0 || (trip_count % chunk) != 0;
Aart Bikf8f5a162017-02-06 15:35:29 -0800840
841 // Adjust vector bookkeeping.
Aart Bikb29f6842017-07-28 15:58:41 -0700842 HPhi* main_phi = nullptr;
843 bool is_simple_loop_header = TrySetSimpleLoopHeader(header, &main_phi); // refills sets
Aart Bikf8f5a162017-02-06 15:35:29 -0800844 DCHECK(is_simple_loop_header);
Aart Bik14a68b42017-06-08 14:06:58 -0700845 vector_header_ = header;
846 vector_body_ = block;
Aart Bikf8f5a162017-02-06 15:35:29 -0800847
Aart Bikdbbac8f2017-09-01 13:06:08 -0700848 // Loop induction type.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100849 DataType::Type induc_type = main_phi->GetType();
850 DCHECK(induc_type == DataType::Type::kInt32 || induc_type == DataType::Type::kInt64)
851 << induc_type;
Aart Bikdbbac8f2017-09-01 13:06:08 -0700852
Aart Bikb29f6842017-07-28 15:58:41 -0700853 // Generate dynamic loop peeling trip count, if needed, under the assumption
854 // that the Android runtime guarantees at least "component size" alignment:
855 // ptc = (ALIGN - (&a[initial] % ALIGN)) / type-size
Aart Bik14a68b42017-06-08 14:06:58 -0700856 HInstruction* ptc = nullptr;
857 if (vector_peeling_candidate_ != nullptr) {
858 DCHECK_LT(vector_length_, trip_count) << "dynamic peeling currently requires known trip count";
859 //
860 // TODO: Implement this. Compute address of first access memory location and
861 // compute peeling factor to obtain kAlignedBase alignment.
862 //
863 needs_cleanup = true;
864 }
865
866 // Generate loop control:
Aart Bikf8f5a162017-02-06 15:35:29 -0800867 // stc = <trip-count>;
Aart Bik14a68b42017-06-08 14:06:58 -0700868 // vtc = stc - (stc - ptc) % chunk;
869 // i = 0;
Aart Bikf8f5a162017-02-06 15:35:29 -0800870 HInstruction* stc = induction_range_.GenerateTripCount(node->loop_info, graph_, preheader);
871 HInstruction* vtc = stc;
872 if (needs_cleanup) {
Aart Bik14a68b42017-06-08 14:06:58 -0700873 DCHECK(IsPowerOfTwo(chunk));
874 HInstruction* diff = stc;
875 if (ptc != nullptr) {
876 diff = Insert(preheader, new (global_allocator_) HSub(induc_type, stc, ptc));
877 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800878 HInstruction* rem = Insert(
879 preheader, new (global_allocator_) HAnd(induc_type,
Aart Bik14a68b42017-06-08 14:06:58 -0700880 diff,
Aart Bikdbbac8f2017-09-01 13:06:08 -0700881 graph_->GetConstant(induc_type, chunk - 1)));
Aart Bikf8f5a162017-02-06 15:35:29 -0800882 vtc = Insert(preheader, new (global_allocator_) HSub(induc_type, stc, rem));
883 }
Aart Bikdbbac8f2017-09-01 13:06:08 -0700884 vector_index_ = graph_->GetConstant(induc_type, 0);
Aart Bikf8f5a162017-02-06 15:35:29 -0800885
886 // Generate runtime disambiguation test:
887 // vtc = a != b ? vtc : 0;
888 if (vector_runtime_test_a_ != nullptr) {
889 HInstruction* rt = Insert(
890 preheader,
891 new (global_allocator_) HNotEqual(vector_runtime_test_a_, vector_runtime_test_b_));
892 vtc = Insert(preheader,
Aart Bikdbbac8f2017-09-01 13:06:08 -0700893 new (global_allocator_)
894 HSelect(rt, vtc, graph_->GetConstant(induc_type, 0), kNoDexPc));
Aart Bikf8f5a162017-02-06 15:35:29 -0800895 needs_cleanup = true;
896 }
897
Aart Bik14a68b42017-06-08 14:06:58 -0700898 // Generate dynamic peeling loop for alignment, if needed:
899 // for ( ; i < ptc; i += 1)
900 // <loop-body>
901 if (ptc != nullptr) {
902 vector_mode_ = kSequential;
903 GenerateNewLoop(node,
904 block,
905 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
906 vector_index_,
907 ptc,
Aart Bikdbbac8f2017-09-01 13:06:08 -0700908 graph_->GetConstant(induc_type, 1),
Aart Bik521b50f2017-09-09 10:44:45 -0700909 kNoUnrollingFactor);
Aart Bik14a68b42017-06-08 14:06:58 -0700910 }
911
912 // Generate vector loop, possibly further unrolled:
913 // for ( ; i < vtc; i += chunk)
Aart Bikf8f5a162017-02-06 15:35:29 -0800914 // <vectorized-loop-body>
915 vector_mode_ = kVector;
916 GenerateNewLoop(node,
917 block,
Aart Bik14a68b42017-06-08 14:06:58 -0700918 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
919 vector_index_,
Aart Bikf8f5a162017-02-06 15:35:29 -0800920 vtc,
Aart Bikdbbac8f2017-09-01 13:06:08 -0700921 graph_->GetConstant(induc_type, vector_length_), // increment per unroll
Aart Bik14a68b42017-06-08 14:06:58 -0700922 unroll);
Aart Bikf8f5a162017-02-06 15:35:29 -0800923 HLoopInformation* vloop = vector_header_->GetLoopInformation();
924
925 // Generate cleanup loop, if needed:
926 // for ( ; i < stc; i += 1)
927 // <loop-body>
928 if (needs_cleanup) {
929 vector_mode_ = kSequential;
930 GenerateNewLoop(node,
931 block,
932 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
Aart Bik14a68b42017-06-08 14:06:58 -0700933 vector_index_,
Aart Bikf8f5a162017-02-06 15:35:29 -0800934 stc,
Aart Bikdbbac8f2017-09-01 13:06:08 -0700935 graph_->GetConstant(induc_type, 1),
Aart Bik521b50f2017-09-09 10:44:45 -0700936 kNoUnrollingFactor);
Aart Bikf8f5a162017-02-06 15:35:29 -0800937 }
938
Aart Bik0148de42017-09-05 09:25:01 -0700939 // Link reductions to their final uses.
940 for (auto i = reductions_->begin(); i != reductions_->end(); ++i) {
941 if (i->first->IsPhi()) {
Aart Bikdbbac8f2017-09-01 13:06:08 -0700942 HInstruction* phi = i->first;
943 HInstruction* repl = ReduceAndExtractIfNeeded(i->second);
944 // Deal with regular uses.
945 for (const HUseListNode<HInstruction*>& use : phi->GetUses()) {
946 induction_range_.Replace(use.GetUser(), phi, repl); // update induction use
947 }
948 phi->ReplaceWith(repl);
Aart Bik0148de42017-09-05 09:25:01 -0700949 }
950 }
951
Aart Bikf8f5a162017-02-06 15:35:29 -0800952 // Remove the original loop by disconnecting the body block
953 // and removing all instructions from the header.
954 block->DisconnectAndDelete();
955 while (!header->GetFirstInstruction()->IsGoto()) {
956 header->RemoveInstruction(header->GetFirstInstruction());
957 }
Aart Bikb29f6842017-07-28 15:58:41 -0700958
Aart Bik14a68b42017-06-08 14:06:58 -0700959 // Update loop hierarchy: the old header now resides in the same outer loop
960 // as the old preheader. Note that we don't bother putting sequential
961 // loops back in the hierarchy at this point.
Aart Bikf8f5a162017-02-06 15:35:29 -0800962 header->SetLoopInformation(preheader->GetLoopInformation()); // outward
963 node->loop_info = vloop;
964}
965
966void HLoopOptimization::GenerateNewLoop(LoopNode* node,
967 HBasicBlock* block,
968 HBasicBlock* new_preheader,
969 HInstruction* lo,
970 HInstruction* hi,
Aart Bik14a68b42017-06-08 14:06:58 -0700971 HInstruction* step,
972 uint32_t unroll) {
973 DCHECK(unroll == 1 || vector_mode_ == kVector);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100974 DataType::Type induc_type = lo->GetType();
Aart Bikf8f5a162017-02-06 15:35:29 -0800975 // Prepare new loop.
Aart Bikf8f5a162017-02-06 15:35:29 -0800976 vector_preheader_ = new_preheader,
977 vector_header_ = vector_preheader_->GetSingleSuccessor();
978 vector_body_ = vector_header_->GetSuccessors()[1];
Aart Bik14a68b42017-06-08 14:06:58 -0700979 HPhi* phi = new (global_allocator_) HPhi(global_allocator_,
980 kNoRegNumber,
981 0,
982 HPhi::ToPhiType(induc_type));
Aart Bikb07d1bc2017-04-05 10:03:15 -0700983 // Generate header and prepare body.
Aart Bikf8f5a162017-02-06 15:35:29 -0800984 // for (i = lo; i < hi; i += step)
985 // <loop-body>
Aart Bik14a68b42017-06-08 14:06:58 -0700986 HInstruction* cond = new (global_allocator_) HAboveOrEqual(phi, hi);
987 vector_header_->AddPhi(phi);
Aart Bikf8f5a162017-02-06 15:35:29 -0800988 vector_header_->AddInstruction(cond);
989 vector_header_->AddInstruction(new (global_allocator_) HIf(cond));
Aart Bik14a68b42017-06-08 14:06:58 -0700990 vector_index_ = phi;
Aart Bik0148de42017-09-05 09:25:01 -0700991 vector_permanent_map_->clear(); // preserved over unrolling
Aart Bik14a68b42017-06-08 14:06:58 -0700992 for (uint32_t u = 0; u < unroll; u++) {
Aart Bik14a68b42017-06-08 14:06:58 -0700993 // Generate instruction map.
Aart Bik0148de42017-09-05 09:25:01 -0700994 vector_map_->clear();
Aart Bik14a68b42017-06-08 14:06:58 -0700995 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
996 bool vectorized_def = VectorizeDef(node, it.Current(), /*generate_code*/ true);
997 DCHECK(vectorized_def);
998 }
999 // Generate body from the instruction map, but in original program order.
1000 HEnvironment* env = vector_header_->GetFirstInstruction()->GetEnvironment();
1001 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
1002 auto i = vector_map_->find(it.Current());
1003 if (i != vector_map_->end() && !i->second->IsInBlock()) {
1004 Insert(vector_body_, i->second);
1005 // Deal with instructions that need an environment, such as the scalar intrinsics.
1006 if (i->second->NeedsEnvironment()) {
1007 i->second->CopyEnvironmentFromWithLoopPhiAdjustment(env, vector_header_);
1008 }
1009 }
1010 }
Aart Bik0148de42017-09-05 09:25:01 -07001011 // Generate the induction.
Aart Bik14a68b42017-06-08 14:06:58 -07001012 vector_index_ = new (global_allocator_) HAdd(induc_type, vector_index_, step);
1013 Insert(vector_body_, vector_index_);
Aart Bikf8f5a162017-02-06 15:35:29 -08001014 }
Aart Bik0148de42017-09-05 09:25:01 -07001015 // Finalize phi inputs for the reductions (if any).
1016 for (auto i = reductions_->begin(); i != reductions_->end(); ++i) {
1017 if (!i->first->IsPhi()) {
1018 DCHECK(i->second->IsPhi());
1019 GenerateVecReductionPhiInputs(i->second->AsPhi(), i->first);
1020 }
1021 }
Aart Bikb29f6842017-07-28 15:58:41 -07001022 // Finalize phi inputs for the loop index.
Aart Bik14a68b42017-06-08 14:06:58 -07001023 phi->AddInput(lo);
1024 phi->AddInput(vector_index_);
1025 vector_index_ = phi;
Aart Bikf8f5a162017-02-06 15:35:29 -08001026}
1027
Aart Bikf8f5a162017-02-06 15:35:29 -08001028bool HLoopOptimization::VectorizeDef(LoopNode* node,
1029 HInstruction* instruction,
1030 bool generate_code) {
1031 // Accept a left-hand-side array base[index] for
1032 // (1) supported vector type,
1033 // (2) loop-invariant base,
1034 // (3) unit stride index,
1035 // (4) vectorizable right-hand-side value.
1036 uint64_t restrictions = kNone;
1037 if (instruction->IsArraySet()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001038 DataType::Type type = instruction->AsArraySet()->GetComponentType();
Aart Bikf8f5a162017-02-06 15:35:29 -08001039 HInstruction* base = instruction->InputAt(0);
1040 HInstruction* index = instruction->InputAt(1);
1041 HInstruction* value = instruction->InputAt(2);
1042 HInstruction* offset = nullptr;
1043 if (TrySetVectorType(type, &restrictions) &&
1044 node->loop_info->IsDefinedOutOfTheLoop(base) &&
Aart Bik37dc4df2017-06-28 14:08:00 -07001045 induction_range_.IsUnitStride(instruction, index, graph_, &offset) &&
Aart Bikf8f5a162017-02-06 15:35:29 -08001046 VectorizeUse(node, value, generate_code, type, restrictions)) {
1047 if (generate_code) {
1048 GenerateVecSub(index, offset);
Aart Bik14a68b42017-06-08 14:06:58 -07001049 GenerateVecMem(instruction, vector_map_->Get(index), vector_map_->Get(value), offset, type);
Aart Bikf8f5a162017-02-06 15:35:29 -08001050 } else {
1051 vector_refs_->insert(ArrayReference(base, offset, type, /*lhs*/ true));
1052 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08001053 return true;
1054 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001055 return false;
1056 }
Aart Bik0148de42017-09-05 09:25:01 -07001057 // Accept a left-hand-side reduction for
1058 // (1) supported vector type,
1059 // (2) vectorizable right-hand-side value.
1060 auto redit = reductions_->find(instruction);
1061 if (redit != reductions_->end()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001062 DataType::Type type = instruction->GetType();
Aart Bikdbbac8f2017-09-01 13:06:08 -07001063 // Recognize SAD idiom or direct reduction.
1064 if (VectorizeSADIdiom(node, instruction, generate_code, type, restrictions) ||
1065 (TrySetVectorType(type, &restrictions) &&
1066 VectorizeUse(node, instruction, generate_code, type, restrictions))) {
Aart Bik0148de42017-09-05 09:25:01 -07001067 if (generate_code) {
1068 HInstruction* new_red = vector_map_->Get(instruction);
1069 vector_permanent_map_->Put(new_red, vector_map_->Get(redit->second));
1070 vector_permanent_map_->Overwrite(redit->second, new_red);
1071 }
1072 return true;
1073 }
1074 return false;
1075 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001076 // Branch back okay.
1077 if (instruction->IsGoto()) {
1078 return true;
1079 }
1080 // Otherwise accept only expressions with no effects outside the immediate loop-body.
1081 // Note that actual uses are inspected during right-hand-side tree traversal.
1082 return !IsUsedOutsideLoop(node->loop_info, instruction) && !instruction->DoesAnyWrite();
1083}
1084
Aart Bik304c8a52017-05-23 11:01:13 -07001085// TODO: saturation arithmetic.
Aart Bikf8f5a162017-02-06 15:35:29 -08001086bool HLoopOptimization::VectorizeUse(LoopNode* node,
1087 HInstruction* instruction,
1088 bool generate_code,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001089 DataType::Type type,
Aart Bikf8f5a162017-02-06 15:35:29 -08001090 uint64_t restrictions) {
1091 // Accept anything for which code has already been generated.
1092 if (generate_code) {
1093 if (vector_map_->find(instruction) != vector_map_->end()) {
1094 return true;
1095 }
1096 }
1097 // Continue the right-hand-side tree traversal, passing in proper
1098 // types and vector restrictions along the way. During code generation,
1099 // all new nodes are drawn from the global allocator.
1100 if (node->loop_info->IsDefinedOutOfTheLoop(instruction)) {
1101 // Accept invariant use, using scalar expansion.
1102 if (generate_code) {
1103 GenerateVecInv(instruction, type);
1104 }
1105 return true;
1106 } else if (instruction->IsArrayGet()) {
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001107 // Deal with vector restrictions.
1108 if (instruction->AsArrayGet()->IsStringCharAt() &&
1109 HasVectorRestrictions(restrictions, kNoStringCharAt)) {
1110 return false;
1111 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001112 // Accept a right-hand-side array base[index] for
1113 // (1) exact matching vector type,
1114 // (2) loop-invariant base,
1115 // (3) unit stride index,
1116 // (4) vectorizable right-hand-side value.
1117 HInstruction* base = instruction->InputAt(0);
1118 HInstruction* index = instruction->InputAt(1);
1119 HInstruction* offset = nullptr;
1120 if (type == instruction->GetType() &&
1121 node->loop_info->IsDefinedOutOfTheLoop(base) &&
Aart Bik37dc4df2017-06-28 14:08:00 -07001122 induction_range_.IsUnitStride(instruction, index, graph_, &offset)) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001123 if (generate_code) {
1124 GenerateVecSub(index, offset);
Aart Bik14a68b42017-06-08 14:06:58 -07001125 GenerateVecMem(instruction, vector_map_->Get(index), nullptr, offset, type);
Aart Bikf8f5a162017-02-06 15:35:29 -08001126 } else {
1127 vector_refs_->insert(ArrayReference(base, offset, type, /*lhs*/ false));
1128 }
1129 return true;
1130 }
Aart Bik0148de42017-09-05 09:25:01 -07001131 } else if (instruction->IsPhi()) {
1132 // Accept particular phi operations.
1133 if (reductions_->find(instruction) != reductions_->end()) {
1134 // Deal with vector restrictions.
1135 if (HasVectorRestrictions(restrictions, kNoReduction)) {
1136 return false;
1137 }
1138 // Accept a reduction.
1139 if (generate_code) {
1140 GenerateVecReductionPhi(instruction->AsPhi());
1141 }
1142 return true;
1143 }
1144 // TODO: accept right-hand-side induction?
1145 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001146 } else if (instruction->IsTypeConversion()) {
1147 // Accept particular type conversions.
1148 HTypeConversion* conversion = instruction->AsTypeConversion();
1149 HInstruction* opa = conversion->InputAt(0);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001150 DataType::Type from = conversion->GetInputType();
1151 DataType::Type to = conversion->GetResultType();
1152 if (DataType::IsIntegralType(from) && DataType::IsIntegralType(to)) {
1153 size_t size_vec = DataType::Size(type);
1154 size_t size_from = DataType::Size(from);
1155 size_t size_to = DataType::Size(to);
Aart Bikdf011c32017-09-28 12:53:04 -07001156 DataType::Type ctype = size_from == size_vec ? from : type;
Aart Bikdbbac8f2017-09-01 13:06:08 -07001157 // Accept an integral conversion
1158 // (1a) narrowing into vector type, "wider" operations cannot bring in higher order bits, or
1159 // (1b) widening from at least vector type, and
1160 // (2) vectorizable operand.
1161 if ((size_to < size_from &&
1162 size_to == size_vec &&
1163 VectorizeUse(node, opa, generate_code, type, restrictions | kNoHiBits)) ||
1164 (size_to >= size_from &&
1165 size_from >= size_vec &&
Aart Bikdf011c32017-09-28 12:53:04 -07001166 VectorizeUse(node, opa, generate_code, ctype, restrictions))) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001167 if (generate_code) {
1168 if (vector_mode_ == kVector) {
1169 vector_map_->Put(instruction, vector_map_->Get(opa)); // operand pass-through
1170 } else {
1171 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1172 }
1173 }
1174 return true;
1175 }
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001176 } else if (to == DataType::Type::kFloat32 && from == DataType::Type::kInt32) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001177 DCHECK_EQ(to, type);
1178 // Accept int to float conversion for
1179 // (1) supported int,
1180 // (2) vectorizable operand.
1181 if (TrySetVectorType(from, &restrictions) &&
1182 VectorizeUse(node, opa, generate_code, from, restrictions)) {
1183 if (generate_code) {
1184 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1185 }
1186 return true;
1187 }
1188 }
1189 return false;
1190 } else if (instruction->IsNeg() || instruction->IsNot() || instruction->IsBooleanNot()) {
1191 // Accept unary operator for vectorizable operand.
1192 HInstruction* opa = instruction->InputAt(0);
1193 if (VectorizeUse(node, opa, generate_code, type, restrictions)) {
1194 if (generate_code) {
1195 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1196 }
1197 return true;
1198 }
1199 } else if (instruction->IsAdd() || instruction->IsSub() ||
1200 instruction->IsMul() || instruction->IsDiv() ||
1201 instruction->IsAnd() || instruction->IsOr() || instruction->IsXor()) {
1202 // Deal with vector restrictions.
1203 if ((instruction->IsMul() && HasVectorRestrictions(restrictions, kNoMul)) ||
1204 (instruction->IsDiv() && HasVectorRestrictions(restrictions, kNoDiv))) {
1205 return false;
1206 }
1207 // Accept binary operator for vectorizable operands.
1208 HInstruction* opa = instruction->InputAt(0);
1209 HInstruction* opb = instruction->InputAt(1);
1210 if (VectorizeUse(node, opa, generate_code, type, restrictions) &&
1211 VectorizeUse(node, opb, generate_code, type, restrictions)) {
1212 if (generate_code) {
1213 GenerateVecOp(instruction, vector_map_->Get(opa), vector_map_->Get(opb), type);
1214 }
1215 return true;
1216 }
1217 } else if (instruction->IsShl() || instruction->IsShr() || instruction->IsUShr()) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001218 // Recognize halving add idiom.
Aart Bikf3e61ee2017-04-12 17:09:20 -07001219 if (VectorizeHalvingAddIdiom(node, instruction, generate_code, type, restrictions)) {
1220 return true;
1221 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001222 // Deal with vector restrictions.
Aart Bik304c8a52017-05-23 11:01:13 -07001223 HInstruction* opa = instruction->InputAt(0);
1224 HInstruction* opb = instruction->InputAt(1);
1225 HInstruction* r = opa;
1226 bool is_unsigned = false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001227 if ((HasVectorRestrictions(restrictions, kNoShift)) ||
1228 (instruction->IsShr() && HasVectorRestrictions(restrictions, kNoShr))) {
1229 return false; // unsupported instruction
Aart Bik304c8a52017-05-23 11:01:13 -07001230 } else if (HasVectorRestrictions(restrictions, kNoHiBits)) {
1231 // Shifts right need extra care to account for higher order bits.
1232 // TODO: less likely shr/unsigned and ushr/signed can by flipping signess.
1233 if (instruction->IsShr() &&
1234 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || is_unsigned)) {
1235 return false; // reject, unless all operands are sign-extension narrower
1236 } else if (instruction->IsUShr() &&
1237 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || !is_unsigned)) {
1238 return false; // reject, unless all operands are zero-extension narrower
1239 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001240 }
1241 // Accept shift operator for vectorizable/invariant operands.
1242 // TODO: accept symbolic, albeit loop invariant shift factors.
Aart Bik304c8a52017-05-23 11:01:13 -07001243 DCHECK(r != nullptr);
1244 if (generate_code && vector_mode_ != kVector) { // de-idiom
1245 r = opa;
1246 }
Aart Bik50e20d52017-05-05 14:07:29 -07001247 int64_t distance = 0;
Aart Bik304c8a52017-05-23 11:01:13 -07001248 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
Aart Bik50e20d52017-05-05 14:07:29 -07001249 IsInt64AndGet(opb, /*out*/ &distance)) {
Aart Bik65ffd8e2017-05-01 16:50:45 -07001250 // Restrict shift distance to packed data type width.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001251 int64_t max_distance = DataType::Size(type) * 8;
Aart Bik65ffd8e2017-05-01 16:50:45 -07001252 if (0 <= distance && distance < max_distance) {
1253 if (generate_code) {
Aart Bik304c8a52017-05-23 11:01:13 -07001254 GenerateVecOp(instruction, vector_map_->Get(r), opb, type);
Aart Bik65ffd8e2017-05-01 16:50:45 -07001255 }
1256 return true;
Aart Bikf8f5a162017-02-06 15:35:29 -08001257 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001258 }
1259 } else if (instruction->IsInvokeStaticOrDirect()) {
Aart Bik6daebeb2017-04-03 14:35:41 -07001260 // Accept particular intrinsics.
1261 HInvokeStaticOrDirect* invoke = instruction->AsInvokeStaticOrDirect();
1262 switch (invoke->GetIntrinsic()) {
1263 case Intrinsics::kMathAbsInt:
1264 case Intrinsics::kMathAbsLong:
1265 case Intrinsics::kMathAbsFloat:
1266 case Intrinsics::kMathAbsDouble: {
1267 // Deal with vector restrictions.
Aart Bik304c8a52017-05-23 11:01:13 -07001268 HInstruction* opa = instruction->InputAt(0);
1269 HInstruction* r = opa;
1270 bool is_unsigned = false;
1271 if (HasVectorRestrictions(restrictions, kNoAbs)) {
Aart Bik6daebeb2017-04-03 14:35:41 -07001272 return false;
Aart Bik304c8a52017-05-23 11:01:13 -07001273 } else if (HasVectorRestrictions(restrictions, kNoHiBits) &&
1274 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || is_unsigned)) {
1275 return false; // reject, unless operand is sign-extension narrower
Aart Bik6daebeb2017-04-03 14:35:41 -07001276 }
1277 // Accept ABS(x) for vectorizable operand.
Aart Bik304c8a52017-05-23 11:01:13 -07001278 DCHECK(r != nullptr);
1279 if (generate_code && vector_mode_ != kVector) { // de-idiom
1280 r = opa;
1281 }
1282 if (VectorizeUse(node, r, generate_code, type, restrictions)) {
Aart Bik6daebeb2017-04-03 14:35:41 -07001283 if (generate_code) {
Aart Bik304c8a52017-05-23 11:01:13 -07001284 GenerateVecOp(instruction, vector_map_->Get(r), nullptr, type);
Aart Bik6daebeb2017-04-03 14:35:41 -07001285 }
1286 return true;
1287 }
1288 return false;
1289 }
Aart Bikc8e93c72017-05-10 10:49:22 -07001290 case Intrinsics::kMathMinIntInt:
1291 case Intrinsics::kMathMinLongLong:
1292 case Intrinsics::kMathMinFloatFloat:
1293 case Intrinsics::kMathMinDoubleDouble:
1294 case Intrinsics::kMathMaxIntInt:
1295 case Intrinsics::kMathMaxLongLong:
1296 case Intrinsics::kMathMaxFloatFloat:
1297 case Intrinsics::kMathMaxDoubleDouble: {
1298 // Deal with vector restrictions.
Nicolas Geoffray92316902017-05-23 08:06:07 +00001299 HInstruction* opa = instruction->InputAt(0);
1300 HInstruction* opb = instruction->InputAt(1);
Aart Bik304c8a52017-05-23 11:01:13 -07001301 HInstruction* r = opa;
1302 HInstruction* s = opb;
1303 bool is_unsigned = false;
1304 if (HasVectorRestrictions(restrictions, kNoMinMax)) {
1305 return false;
1306 } else if (HasVectorRestrictions(restrictions, kNoHiBits) &&
1307 !IsNarrowerOperands(opa, opb, type, &r, &s, &is_unsigned)) {
1308 return false; // reject, unless all operands are same-extension narrower
1309 }
1310 // Accept MIN/MAX(x, y) for vectorizable operands.
Aart Bikdbbac8f2017-09-01 13:06:08 -07001311 DCHECK(r != nullptr);
1312 DCHECK(s != nullptr);
Aart Bik304c8a52017-05-23 11:01:13 -07001313 if (generate_code && vector_mode_ != kVector) { // de-idiom
1314 r = opa;
1315 s = opb;
1316 }
1317 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
1318 VectorizeUse(node, s, generate_code, type, restrictions)) {
Aart Bikc8e93c72017-05-10 10:49:22 -07001319 if (generate_code) {
Aart Bik304c8a52017-05-23 11:01:13 -07001320 GenerateVecOp(
1321 instruction, vector_map_->Get(r), vector_map_->Get(s), type, is_unsigned);
Aart Bikc8e93c72017-05-10 10:49:22 -07001322 }
1323 return true;
1324 }
1325 return false;
1326 }
Aart Bik6daebeb2017-04-03 14:35:41 -07001327 default:
1328 return false;
1329 } // switch
Aart Bik281c6812016-08-26 11:31:48 -07001330 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08001331 return false;
Aart Bik281c6812016-08-26 11:31:48 -07001332}
1333
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001334bool HLoopOptimization::TrySetVectorType(DataType::Type type, uint64_t* restrictions) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001335 const InstructionSetFeatures* features = compiler_driver_->GetInstructionSetFeatures();
1336 switch (compiler_driver_->GetInstructionSet()) {
1337 case kArm:
1338 case kThumb2:
Artem Serov8f7c4102017-06-21 11:21:37 +01001339 // Allow vectorization for all ARM devices, because Android assumes that
Aart Bikb29f6842017-07-28 15:58:41 -07001340 // ARM 32-bit always supports advanced SIMD (64-bit SIMD).
Artem Serov8f7c4102017-06-21 11:21:37 +01001341 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001342 case DataType::Type::kBool:
1343 case DataType::Type::kInt8:
Aart Bik0148de42017-09-05 09:25:01 -07001344 *restrictions |= kNoDiv | kNoReduction;
Artem Serov8f7c4102017-06-21 11:21:37 +01001345 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001346 case DataType::Type::kUint16:
1347 case DataType::Type::kInt16:
Aart Bik0148de42017-09-05 09:25:01 -07001348 *restrictions |= kNoDiv | kNoStringCharAt | kNoReduction;
Artem Serov8f7c4102017-06-21 11:21:37 +01001349 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001350 case DataType::Type::kInt32:
Aart Bik0148de42017-09-05 09:25:01 -07001351 *restrictions |= kNoDiv | kNoReduction;
Artem Serov8f7c4102017-06-21 11:21:37 +01001352 return TrySetVectorLength(2);
1353 default:
1354 break;
1355 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001356 return false;
1357 case kArm64:
1358 // Allow vectorization for all ARM devices, because Android assumes that
Aart Bikb29f6842017-07-28 15:58:41 -07001359 // ARMv8 AArch64 always supports advanced SIMD (128-bit SIMD).
Aart Bikf8f5a162017-02-06 15:35:29 -08001360 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001361 case DataType::Type::kBool:
1362 case DataType::Type::kInt8:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001363 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +01001364 return TrySetVectorLength(16);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001365 case DataType::Type::kUint16:
1366 case DataType::Type::kInt16:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001367 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +01001368 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001369 case DataType::Type::kInt32:
Aart Bikf8f5a162017-02-06 15:35:29 -08001370 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +01001371 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001372 case DataType::Type::kInt64:
Aart Bikc8e93c72017-05-10 10:49:22 -07001373 *restrictions |= kNoDiv | kNoMul | kNoMinMax;
Aart Bikf8f5a162017-02-06 15:35:29 -08001374 return TrySetVectorLength(2);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001375 case DataType::Type::kFloat32:
Aart Bik0148de42017-09-05 09:25:01 -07001376 *restrictions |= kNoReduction;
Artem Serovd4bccf12017-04-03 18:47:32 +01001377 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001378 case DataType::Type::kFloat64:
Aart Bik0148de42017-09-05 09:25:01 -07001379 *restrictions |= kNoReduction;
Aart Bikf8f5a162017-02-06 15:35:29 -08001380 return TrySetVectorLength(2);
1381 default:
1382 return false;
1383 }
1384 case kX86:
1385 case kX86_64:
Aart Bikb29f6842017-07-28 15:58:41 -07001386 // Allow vectorization for SSE4.1-enabled X86 devices only (128-bit SIMD).
Aart Bikf8f5a162017-02-06 15:35:29 -08001387 if (features->AsX86InstructionSetFeatures()->HasSSE4_1()) {
1388 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001389 case DataType::Type::kBool:
1390 case DataType::Type::kInt8:
Aart Bik0148de42017-09-05 09:25:01 -07001391 *restrictions |=
Aart Bikdbbac8f2017-09-01 13:06:08 -07001392 kNoMul | kNoDiv | kNoShift | kNoAbs | kNoSignedHAdd | kNoUnroundedHAdd | kNoSAD;
Aart Bikf8f5a162017-02-06 15:35:29 -08001393 return TrySetVectorLength(16);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001394 case DataType::Type::kUint16:
1395 case DataType::Type::kInt16:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001396 *restrictions |= kNoDiv | kNoAbs | kNoSignedHAdd | kNoUnroundedHAdd | kNoSAD;
Aart Bikf8f5a162017-02-06 15:35:29 -08001397 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001398 case DataType::Type::kInt32:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001399 *restrictions |= kNoDiv | kNoSAD;
Aart Bikf8f5a162017-02-06 15:35:29 -08001400 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001401 case DataType::Type::kInt64:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001402 *restrictions |= kNoMul | kNoDiv | kNoShr | kNoAbs | kNoMinMax | kNoSAD;
Aart Bikf8f5a162017-02-06 15:35:29 -08001403 return TrySetVectorLength(2);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001404 case DataType::Type::kFloat32:
Aart Bik0148de42017-09-05 09:25:01 -07001405 *restrictions |= kNoMinMax | kNoReduction; // minmax: -0.0 vs +0.0
Aart Bikf8f5a162017-02-06 15:35:29 -08001406 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001407 case DataType::Type::kFloat64:
Aart Bik0148de42017-09-05 09:25:01 -07001408 *restrictions |= kNoMinMax | kNoReduction; // minmax: -0.0 vs +0.0
Aart Bikf8f5a162017-02-06 15:35:29 -08001409 return TrySetVectorLength(2);
1410 default:
1411 break;
1412 } // switch type
1413 }
1414 return false;
1415 case kMips:
Lena Djokic51765b02017-06-22 13:49:59 +02001416 if (features->AsMipsInstructionSetFeatures()->HasMsa()) {
1417 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001418 case DataType::Type::kBool:
1419 case DataType::Type::kInt8:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001420 *restrictions |= kNoDiv | kNoReduction | kNoSAD;
Lena Djokic51765b02017-06-22 13:49:59 +02001421 return TrySetVectorLength(16);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001422 case DataType::Type::kUint16:
1423 case DataType::Type::kInt16:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001424 *restrictions |= kNoDiv | kNoStringCharAt | kNoReduction | kNoSAD;
Lena Djokic51765b02017-06-22 13:49:59 +02001425 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001426 case DataType::Type::kInt32:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001427 *restrictions |= kNoDiv | kNoReduction | kNoSAD;
Lena Djokic51765b02017-06-22 13:49:59 +02001428 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001429 case DataType::Type::kInt64:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001430 *restrictions |= kNoDiv | kNoReduction | kNoSAD;
Lena Djokic51765b02017-06-22 13:49:59 +02001431 return TrySetVectorLength(2);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001432 case DataType::Type::kFloat32:
Aart Bik0148de42017-09-05 09:25:01 -07001433 *restrictions |= kNoMinMax | kNoReduction; // min/max(x, NaN)
Lena Djokic51765b02017-06-22 13:49:59 +02001434 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001435 case DataType::Type::kFloat64:
Aart Bik0148de42017-09-05 09:25:01 -07001436 *restrictions |= kNoMinMax | kNoReduction; // min/max(x, NaN)
Lena Djokic51765b02017-06-22 13:49:59 +02001437 return TrySetVectorLength(2);
1438 default:
1439 break;
1440 } // switch type
1441 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001442 return false;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001443 case kMips64:
1444 if (features->AsMips64InstructionSetFeatures()->HasMsa()) {
1445 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001446 case DataType::Type::kBool:
1447 case DataType::Type::kInt8:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001448 *restrictions |= kNoDiv | kNoReduction | kNoSAD;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001449 return TrySetVectorLength(16);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001450 case DataType::Type::kUint16:
1451 case DataType::Type::kInt16:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001452 *restrictions |= kNoDiv | kNoStringCharAt | kNoReduction | kNoSAD;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001453 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001454 case DataType::Type::kInt32:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001455 *restrictions |= kNoDiv | kNoReduction | kNoSAD;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001456 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001457 case DataType::Type::kInt64:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001458 *restrictions |= kNoDiv | kNoReduction | kNoSAD;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001459 return TrySetVectorLength(2);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001460 case DataType::Type::kFloat32:
Aart Bik0148de42017-09-05 09:25:01 -07001461 *restrictions |= kNoMinMax | kNoReduction; // min/max(x, NaN)
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001462 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001463 case DataType::Type::kFloat64:
Aart Bik0148de42017-09-05 09:25:01 -07001464 *restrictions |= kNoMinMax | kNoReduction; // min/max(x, NaN)
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001465 return TrySetVectorLength(2);
1466 default:
1467 break;
1468 } // switch type
1469 }
1470 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001471 default:
1472 return false;
1473 } // switch instruction set
1474}
1475
1476bool HLoopOptimization::TrySetVectorLength(uint32_t length) {
1477 DCHECK(IsPowerOfTwo(length) && length >= 2u);
1478 // First time set?
1479 if (vector_length_ == 0) {
1480 vector_length_ = length;
1481 }
1482 // Different types are acceptable within a loop-body, as long as all the corresponding vector
1483 // lengths match exactly to obtain a uniform traversal through the vector iteration space
1484 // (idiomatic exceptions to this rule can be handled by further unrolling sub-expressions).
1485 return vector_length_ == length;
1486}
1487
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001488void HLoopOptimization::GenerateVecInv(HInstruction* org, DataType::Type type) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001489 if (vector_map_->find(org) == vector_map_->end()) {
1490 // In scalar code, just use a self pass-through for scalar invariants
1491 // (viz. expression remains itself).
1492 if (vector_mode_ == kSequential) {
1493 vector_map_->Put(org, org);
1494 return;
1495 }
1496 // In vector code, explicit scalar expansion is needed.
Aart Bik0148de42017-09-05 09:25:01 -07001497 HInstruction* vector = nullptr;
1498 auto it = vector_permanent_map_->find(org);
1499 if (it != vector_permanent_map_->end()) {
1500 vector = it->second; // reuse during unrolling
1501 } else {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001502 // Generates ReplicateScalar( (optional_type_conv) org ).
1503 HInstruction* input = org;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001504 DataType::Type input_type = input->GetType();
1505 if (type != input_type && (type == DataType::Type::kInt64 ||
1506 input_type == DataType::Type::kInt64)) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001507 input = Insert(vector_preheader_,
1508 new (global_allocator_) HTypeConversion(type, input, kNoDexPc));
1509 }
1510 vector = new (global_allocator_)
1511 HVecReplicateScalar(global_allocator_, input, type, vector_length_);
Aart Bik0148de42017-09-05 09:25:01 -07001512 vector_permanent_map_->Put(org, Insert(vector_preheader_, vector));
1513 }
1514 vector_map_->Put(org, vector);
Aart Bikf8f5a162017-02-06 15:35:29 -08001515 }
1516}
1517
1518void HLoopOptimization::GenerateVecSub(HInstruction* org, HInstruction* offset) {
1519 if (vector_map_->find(org) == vector_map_->end()) {
Aart Bik14a68b42017-06-08 14:06:58 -07001520 HInstruction* subscript = vector_index_;
Aart Bik37dc4df2017-06-28 14:08:00 -07001521 int64_t value = 0;
1522 if (!IsInt64AndGet(offset, &value) || value != 0) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001523 subscript = new (global_allocator_) HAdd(DataType::Type::kInt32, subscript, offset);
Aart Bikf8f5a162017-02-06 15:35:29 -08001524 if (org->IsPhi()) {
1525 Insert(vector_body_, subscript); // lacks layout placeholder
1526 }
1527 }
1528 vector_map_->Put(org, subscript);
1529 }
1530}
1531
1532void HLoopOptimization::GenerateVecMem(HInstruction* org,
1533 HInstruction* opa,
1534 HInstruction* opb,
Aart Bik14a68b42017-06-08 14:06:58 -07001535 HInstruction* offset,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001536 DataType::Type type) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001537 HInstruction* vector = nullptr;
1538 if (vector_mode_ == kVector) {
1539 // Vector store or load.
Aart Bik14a68b42017-06-08 14:06:58 -07001540 HInstruction* base = org->InputAt(0);
Aart Bikf8f5a162017-02-06 15:35:29 -08001541 if (opb != nullptr) {
1542 vector = new (global_allocator_) HVecStore(
Aart Bik14a68b42017-06-08 14:06:58 -07001543 global_allocator_, base, opa, opb, type, vector_length_);
Aart Bikf8f5a162017-02-06 15:35:29 -08001544 } else {
Aart Bikdb14fcf2017-04-25 15:53:58 -07001545 bool is_string_char_at = org->AsArrayGet()->IsStringCharAt();
Aart Bikf8f5a162017-02-06 15:35:29 -08001546 vector = new (global_allocator_) HVecLoad(
Aart Bik14a68b42017-06-08 14:06:58 -07001547 global_allocator_, base, opa, type, vector_length_, is_string_char_at);
1548 }
1549 // Known dynamically enforced alignment?
Aart Bik14a68b42017-06-08 14:06:58 -07001550 if (vector_peeling_candidate_ != nullptr &&
1551 vector_peeling_candidate_->base == base &&
1552 vector_peeling_candidate_->offset == offset) {
1553 vector->AsVecMemoryOperation()->SetAlignment(Alignment(kAlignedBase, 0));
Aart Bikf8f5a162017-02-06 15:35:29 -08001554 }
1555 } else {
1556 // Scalar store or load.
1557 DCHECK(vector_mode_ == kSequential);
1558 if (opb != nullptr) {
1559 vector = new (global_allocator_) HArraySet(org->InputAt(0), opa, opb, type, kNoDexPc);
1560 } else {
Aart Bikdb14fcf2017-04-25 15:53:58 -07001561 bool is_string_char_at = org->AsArrayGet()->IsStringCharAt();
1562 vector = new (global_allocator_) HArrayGet(
1563 org->InputAt(0), opa, type, kNoDexPc, is_string_char_at);
Aart Bikf8f5a162017-02-06 15:35:29 -08001564 }
1565 }
1566 vector_map_->Put(org, vector);
1567}
1568
Aart Bik0148de42017-09-05 09:25:01 -07001569void HLoopOptimization::GenerateVecReductionPhi(HPhi* phi) {
1570 DCHECK(reductions_->find(phi) != reductions_->end());
1571 DCHECK(reductions_->Get(phi->InputAt(1)) == phi);
1572 HInstruction* vector = nullptr;
1573 if (vector_mode_ == kSequential) {
1574 HPhi* new_phi = new (global_allocator_) HPhi(
1575 global_allocator_, kNoRegNumber, 0, phi->GetType());
1576 vector_header_->AddPhi(new_phi);
1577 vector = new_phi;
1578 } else {
1579 // Link vector reduction back to prior unrolled update, or a first phi.
1580 auto it = vector_permanent_map_->find(phi);
1581 if (it != vector_permanent_map_->end()) {
1582 vector = it->second;
1583 } else {
1584 HPhi* new_phi = new (global_allocator_) HPhi(
1585 global_allocator_, kNoRegNumber, 0, HVecOperation::kSIMDType);
1586 vector_header_->AddPhi(new_phi);
1587 vector = new_phi;
1588 }
1589 }
1590 vector_map_->Put(phi, vector);
1591}
1592
1593void HLoopOptimization::GenerateVecReductionPhiInputs(HPhi* phi, HInstruction* reduction) {
1594 HInstruction* new_phi = vector_map_->Get(phi);
1595 HInstruction* new_init = reductions_->Get(phi);
1596 HInstruction* new_red = vector_map_->Get(reduction);
1597 // Link unrolled vector loop back to new phi.
1598 for (; !new_phi->IsPhi(); new_phi = vector_permanent_map_->Get(new_phi)) {
1599 DCHECK(new_phi->IsVecOperation());
1600 }
1601 // Prepare the new initialization.
1602 if (vector_mode_ == kVector) {
1603 // Generate a [initial, 0, .., 0] vector.
Aart Bikdbbac8f2017-09-01 13:06:08 -07001604 HVecOperation* red_vector = new_red->AsVecOperation();
1605 size_t vector_length = red_vector->GetVectorLength();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001606 DataType::Type type = red_vector->GetPackedType();
Aart Bikdbbac8f2017-09-01 13:06:08 -07001607 new_init = Insert(vector_preheader_,
1608 new (global_allocator_) HVecSetScalars(global_allocator_,
1609 &new_init,
1610 type,
1611 vector_length,
1612 1));
Aart Bik0148de42017-09-05 09:25:01 -07001613 } else {
1614 new_init = ReduceAndExtractIfNeeded(new_init);
1615 }
1616 // Set the phi inputs.
1617 DCHECK(new_phi->IsPhi());
1618 new_phi->AsPhi()->AddInput(new_init);
1619 new_phi->AsPhi()->AddInput(new_red);
1620 // New feed value for next phi (safe mutation in iteration).
1621 reductions_->find(phi)->second = new_phi;
1622}
1623
1624HInstruction* HLoopOptimization::ReduceAndExtractIfNeeded(HInstruction* instruction) {
1625 if (instruction->IsPhi()) {
1626 HInstruction* input = instruction->InputAt(1);
1627 if (input->IsVecOperation()) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001628 HVecOperation* input_vector = input->AsVecOperation();
1629 size_t vector_length = input_vector->GetVectorLength();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001630 DataType::Type type = input_vector->GetPackedType();
Aart Bikdbbac8f2017-09-01 13:06:08 -07001631 HVecReduce::ReductionKind kind = GetReductionKind(input_vector);
Aart Bik0148de42017-09-05 09:25:01 -07001632 HBasicBlock* exit = instruction->GetBlock()->GetSuccessors()[0];
1633 // Generate a vector reduction and scalar extract
1634 // x = REDUCE( [x_1, .., x_n] )
1635 // y = x_1
1636 // along the exit of the defining loop.
Aart Bik0148de42017-09-05 09:25:01 -07001637 HInstruction* reduce = new (global_allocator_) HVecReduce(
Aart Bikdbbac8f2017-09-01 13:06:08 -07001638 global_allocator_, instruction, type, vector_length, kind);
Aart Bik0148de42017-09-05 09:25:01 -07001639 exit->InsertInstructionBefore(reduce, exit->GetFirstInstruction());
1640 instruction = new (global_allocator_) HVecExtractScalar(
Aart Bikdbbac8f2017-09-01 13:06:08 -07001641 global_allocator_, reduce, type, vector_length, 0);
Aart Bik0148de42017-09-05 09:25:01 -07001642 exit->InsertInstructionAfter(instruction, reduce);
1643 }
1644 }
1645 return instruction;
1646}
1647
Aart Bikf8f5a162017-02-06 15:35:29 -08001648#define GENERATE_VEC(x, y) \
1649 if (vector_mode_ == kVector) { \
1650 vector = (x); \
1651 } else { \
1652 DCHECK(vector_mode_ == kSequential); \
1653 vector = (y); \
1654 } \
1655 break;
1656
1657void HLoopOptimization::GenerateVecOp(HInstruction* org,
1658 HInstruction* opa,
1659 HInstruction* opb,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001660 DataType::Type type,
Aart Bik304c8a52017-05-23 11:01:13 -07001661 bool is_unsigned) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001662 HInstruction* vector = nullptr;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001663 DataType::Type org_type = org->GetType();
Aart Bikf8f5a162017-02-06 15:35:29 -08001664 switch (org->GetKind()) {
1665 case HInstruction::kNeg:
1666 DCHECK(opb == nullptr);
1667 GENERATE_VEC(
1668 new (global_allocator_) HVecNeg(global_allocator_, opa, type, vector_length_),
Aart Bikdbbac8f2017-09-01 13:06:08 -07001669 new (global_allocator_) HNeg(org_type, opa));
Aart Bikf8f5a162017-02-06 15:35:29 -08001670 case HInstruction::kNot:
1671 DCHECK(opb == nullptr);
1672 GENERATE_VEC(
1673 new (global_allocator_) HVecNot(global_allocator_, opa, type, vector_length_),
Aart Bikdbbac8f2017-09-01 13:06:08 -07001674 new (global_allocator_) HNot(org_type, opa));
Aart Bikf8f5a162017-02-06 15:35:29 -08001675 case HInstruction::kBooleanNot:
1676 DCHECK(opb == nullptr);
1677 GENERATE_VEC(
1678 new (global_allocator_) HVecNot(global_allocator_, opa, type, vector_length_),
1679 new (global_allocator_) HBooleanNot(opa));
1680 case HInstruction::kTypeConversion:
1681 DCHECK(opb == nullptr);
1682 GENERATE_VEC(
1683 new (global_allocator_) HVecCnv(global_allocator_, opa, type, vector_length_),
Aart Bikdbbac8f2017-09-01 13:06:08 -07001684 new (global_allocator_) HTypeConversion(org_type, opa, kNoDexPc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001685 case HInstruction::kAdd:
1686 GENERATE_VEC(
1687 new (global_allocator_) HVecAdd(global_allocator_, opa, opb, type, vector_length_),
Aart Bikdbbac8f2017-09-01 13:06:08 -07001688 new (global_allocator_) HAdd(org_type, opa, opb));
Aart Bikf8f5a162017-02-06 15:35:29 -08001689 case HInstruction::kSub:
1690 GENERATE_VEC(
1691 new (global_allocator_) HVecSub(global_allocator_, opa, opb, type, vector_length_),
Aart Bikdbbac8f2017-09-01 13:06:08 -07001692 new (global_allocator_) HSub(org_type, opa, opb));
Aart Bikf8f5a162017-02-06 15:35:29 -08001693 case HInstruction::kMul:
1694 GENERATE_VEC(
1695 new (global_allocator_) HVecMul(global_allocator_, opa, opb, type, vector_length_),
Aart Bikdbbac8f2017-09-01 13:06:08 -07001696 new (global_allocator_) HMul(org_type, opa, opb));
Aart Bikf8f5a162017-02-06 15:35:29 -08001697 case HInstruction::kDiv:
1698 GENERATE_VEC(
1699 new (global_allocator_) HVecDiv(global_allocator_, opa, opb, type, vector_length_),
Aart Bikdbbac8f2017-09-01 13:06:08 -07001700 new (global_allocator_) HDiv(org_type, opa, opb, kNoDexPc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001701 case HInstruction::kAnd:
1702 GENERATE_VEC(
1703 new (global_allocator_) HVecAnd(global_allocator_, opa, opb, type, vector_length_),
Aart Bikdbbac8f2017-09-01 13:06:08 -07001704 new (global_allocator_) HAnd(org_type, opa, opb));
Aart Bikf8f5a162017-02-06 15:35:29 -08001705 case HInstruction::kOr:
1706 GENERATE_VEC(
1707 new (global_allocator_) HVecOr(global_allocator_, opa, opb, type, vector_length_),
Aart Bikdbbac8f2017-09-01 13:06:08 -07001708 new (global_allocator_) HOr(org_type, opa, opb));
Aart Bikf8f5a162017-02-06 15:35:29 -08001709 case HInstruction::kXor:
1710 GENERATE_VEC(
1711 new (global_allocator_) HVecXor(global_allocator_, opa, opb, type, vector_length_),
Aart Bikdbbac8f2017-09-01 13:06:08 -07001712 new (global_allocator_) HXor(org_type, opa, opb));
Aart Bikf8f5a162017-02-06 15:35:29 -08001713 case HInstruction::kShl:
1714 GENERATE_VEC(
1715 new (global_allocator_) HVecShl(global_allocator_, opa, opb, type, vector_length_),
Aart Bikdbbac8f2017-09-01 13:06:08 -07001716 new (global_allocator_) HShl(org_type, opa, opb));
Aart Bikf8f5a162017-02-06 15:35:29 -08001717 case HInstruction::kShr:
1718 GENERATE_VEC(
1719 new (global_allocator_) HVecShr(global_allocator_, opa, opb, type, vector_length_),
Aart Bikdbbac8f2017-09-01 13:06:08 -07001720 new (global_allocator_) HShr(org_type, opa, opb));
Aart Bikf8f5a162017-02-06 15:35:29 -08001721 case HInstruction::kUShr:
1722 GENERATE_VEC(
1723 new (global_allocator_) HVecUShr(global_allocator_, opa, opb, type, vector_length_),
Aart Bikdbbac8f2017-09-01 13:06:08 -07001724 new (global_allocator_) HUShr(org_type, opa, opb));
Aart Bikf8f5a162017-02-06 15:35:29 -08001725 case HInstruction::kInvokeStaticOrDirect: {
Aart Bik6daebeb2017-04-03 14:35:41 -07001726 HInvokeStaticOrDirect* invoke = org->AsInvokeStaticOrDirect();
1727 if (vector_mode_ == kVector) {
1728 switch (invoke->GetIntrinsic()) {
1729 case Intrinsics::kMathAbsInt:
1730 case Intrinsics::kMathAbsLong:
1731 case Intrinsics::kMathAbsFloat:
1732 case Intrinsics::kMathAbsDouble:
1733 DCHECK(opb == nullptr);
1734 vector = new (global_allocator_) HVecAbs(global_allocator_, opa, type, vector_length_);
1735 break;
Aart Bikc8e93c72017-05-10 10:49:22 -07001736 case Intrinsics::kMathMinIntInt:
1737 case Intrinsics::kMathMinLongLong:
1738 case Intrinsics::kMathMinFloatFloat:
1739 case Intrinsics::kMathMinDoubleDouble: {
Aart Bikc8e93c72017-05-10 10:49:22 -07001740 vector = new (global_allocator_)
1741 HVecMin(global_allocator_, opa, opb, type, vector_length_, is_unsigned);
1742 break;
1743 }
1744 case Intrinsics::kMathMaxIntInt:
1745 case Intrinsics::kMathMaxLongLong:
1746 case Intrinsics::kMathMaxFloatFloat:
1747 case Intrinsics::kMathMaxDoubleDouble: {
Aart Bikc8e93c72017-05-10 10:49:22 -07001748 vector = new (global_allocator_)
1749 HVecMax(global_allocator_, opa, opb, type, vector_length_, is_unsigned);
1750 break;
1751 }
Aart Bik6daebeb2017-04-03 14:35:41 -07001752 default:
1753 LOG(FATAL) << "Unsupported SIMD intrinsic";
1754 UNREACHABLE();
1755 } // switch invoke
1756 } else {
Aart Bik24b905f2017-04-06 09:59:06 -07001757 // In scalar code, simply clone the method invoke, and replace its operands with the
1758 // corresponding new scalar instructions in the loop. The instruction will get an
1759 // environment while being inserted from the instruction map in original program order.
Aart Bik6daebeb2017-04-03 14:35:41 -07001760 DCHECK(vector_mode_ == kSequential);
Aart Bik6e92fb32017-06-05 14:05:09 -07001761 size_t num_args = invoke->GetNumberOfArguments();
Aart Bik6daebeb2017-04-03 14:35:41 -07001762 HInvokeStaticOrDirect* new_invoke = new (global_allocator_) HInvokeStaticOrDirect(
1763 global_allocator_,
Aart Bik6e92fb32017-06-05 14:05:09 -07001764 num_args,
Aart Bik6daebeb2017-04-03 14:35:41 -07001765 invoke->GetType(),
1766 invoke->GetDexPc(),
1767 invoke->GetDexMethodIndex(),
1768 invoke->GetResolvedMethod(),
1769 invoke->GetDispatchInfo(),
1770 invoke->GetInvokeType(),
1771 invoke->GetTargetMethod(),
1772 invoke->GetClinitCheckRequirement());
1773 HInputsRef inputs = invoke->GetInputs();
Aart Bik6e92fb32017-06-05 14:05:09 -07001774 size_t num_inputs = inputs.size();
1775 DCHECK_LE(num_args, num_inputs);
1776 DCHECK_EQ(num_inputs, new_invoke->GetInputs().size()); // both invokes agree
1777 for (size_t index = 0; index < num_inputs; ++index) {
1778 HInstruction* new_input = index < num_args
1779 ? vector_map_->Get(inputs[index])
1780 : inputs[index]; // beyond arguments: just pass through
1781 new_invoke->SetArgumentAt(index, new_input);
Aart Bik6daebeb2017-04-03 14:35:41 -07001782 }
Aart Bik98990262017-04-10 13:15:57 -07001783 new_invoke->SetIntrinsic(invoke->GetIntrinsic(),
1784 kNeedsEnvironmentOrCache,
1785 kNoSideEffects,
1786 kNoThrow);
Aart Bik6daebeb2017-04-03 14:35:41 -07001787 vector = new_invoke;
1788 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001789 break;
1790 }
1791 default:
1792 break;
1793 } // switch
1794 CHECK(vector != nullptr) << "Unsupported SIMD operator";
1795 vector_map_->Put(org, vector);
1796}
1797
1798#undef GENERATE_VEC
1799
1800//
Aart Bikf3e61ee2017-04-12 17:09:20 -07001801// Vectorization idioms.
1802//
1803
1804// Method recognizes the following idioms:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001805// rounding halving add (a + b + 1) >> 1 for unsigned/signed operands a, b
1806// truncated halving add (a + b) >> 1 for unsigned/signed operands a, b
Aart Bikf3e61ee2017-04-12 17:09:20 -07001807// Provided that the operands are promoted to a wider form to do the arithmetic and
1808// then cast back to narrower form, the idioms can be mapped into efficient SIMD
1809// implementation that operates directly in narrower form (plus one extra bit).
1810// TODO: current version recognizes implicit byte/short/char widening only;
1811// explicit widening from int to long could be added later.
1812bool HLoopOptimization::VectorizeHalvingAddIdiom(LoopNode* node,
1813 HInstruction* instruction,
1814 bool generate_code,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001815 DataType::Type type,
Aart Bikf3e61ee2017-04-12 17:09:20 -07001816 uint64_t restrictions) {
1817 // Test for top level arithmetic shift right x >> 1 or logical shift right x >>> 1
Aart Bik304c8a52017-05-23 11:01:13 -07001818 // (note whether the sign bit in wider precision is shifted in has no effect
Aart Bikf3e61ee2017-04-12 17:09:20 -07001819 // on the narrow precision computed by the idiom).
Aart Bikf3e61ee2017-04-12 17:09:20 -07001820 if ((instruction->IsShr() ||
1821 instruction->IsUShr()) &&
Aart Bik0148de42017-09-05 09:25:01 -07001822 IsInt64Value(instruction->InputAt(1), 1)) {
Aart Bik5f805002017-05-16 16:42:41 -07001823 // Test for (a + b + c) >> 1 for optional constant c.
1824 HInstruction* a = nullptr;
1825 HInstruction* b = nullptr;
1826 int64_t c = 0;
1827 if (IsAddConst(instruction->InputAt(0), /*out*/ &a, /*out*/ &b, /*out*/ &c)) {
Aart Bik304c8a52017-05-23 11:01:13 -07001828 DCHECK(a != nullptr && b != nullptr);
Aart Bik5f805002017-05-16 16:42:41 -07001829 // Accept c == 1 (rounded) or c == 0 (not rounded).
1830 bool is_rounded = false;
1831 if (c == 1) {
1832 is_rounded = true;
1833 } else if (c != 0) {
1834 return false;
1835 }
1836 // Accept consistent zero or sign extension on operands a and b.
Aart Bikf3e61ee2017-04-12 17:09:20 -07001837 HInstruction* r = nullptr;
1838 HInstruction* s = nullptr;
1839 bool is_unsigned = false;
Aart Bik304c8a52017-05-23 11:01:13 -07001840 if (!IsNarrowerOperands(a, b, type, &r, &s, &is_unsigned)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -07001841 return false;
1842 }
1843 // Deal with vector restrictions.
1844 if ((!is_unsigned && HasVectorRestrictions(restrictions, kNoSignedHAdd)) ||
1845 (!is_rounded && HasVectorRestrictions(restrictions, kNoUnroundedHAdd))) {
1846 return false;
1847 }
1848 // Accept recognized halving add for vectorizable operands. Vectorized code uses the
1849 // shorthand idiomatic operation. Sequential code uses the original scalar expressions.
Aart Bikdbbac8f2017-09-01 13:06:08 -07001850 DCHECK(r != nullptr);
1851 DCHECK(s != nullptr);
Aart Bik304c8a52017-05-23 11:01:13 -07001852 if (generate_code && vector_mode_ != kVector) { // de-idiom
1853 r = instruction->InputAt(0);
1854 s = instruction->InputAt(1);
1855 }
Aart Bikf3e61ee2017-04-12 17:09:20 -07001856 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
1857 VectorizeUse(node, s, generate_code, type, restrictions)) {
1858 if (generate_code) {
1859 if (vector_mode_ == kVector) {
1860 vector_map_->Put(instruction, new (global_allocator_) HVecHalvingAdd(
1861 global_allocator_,
1862 vector_map_->Get(r),
1863 vector_map_->Get(s),
1864 type,
1865 vector_length_,
1866 is_unsigned,
1867 is_rounded));
Aart Bik21b85922017-09-06 13:29:16 -07001868 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorizedIdiom);
Aart Bikf3e61ee2017-04-12 17:09:20 -07001869 } else {
Aart Bik304c8a52017-05-23 11:01:13 -07001870 GenerateVecOp(instruction, vector_map_->Get(r), vector_map_->Get(s), type);
Aart Bikf3e61ee2017-04-12 17:09:20 -07001871 }
1872 }
1873 return true;
1874 }
1875 }
1876 }
1877 return false;
1878}
1879
Aart Bikdbbac8f2017-09-01 13:06:08 -07001880// Method recognizes the following idiom:
1881// q += ABS(a - b) for signed operands a, b
1882// Provided that the operands have the same type or are promoted to a wider form.
1883// Since this may involve a vector length change, the idiom is handled by going directly
1884// to a sad-accumulate node (rather than relying combining finer grained nodes later).
1885// TODO: unsigned SAD too?
1886bool HLoopOptimization::VectorizeSADIdiom(LoopNode* node,
1887 HInstruction* instruction,
1888 bool generate_code,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001889 DataType::Type reduction_type,
Aart Bikdbbac8f2017-09-01 13:06:08 -07001890 uint64_t restrictions) {
1891 // Filter integral "q += ABS(a - b);" reduction, where ABS and SUB
1892 // are done in the same precision (either int or long).
1893 if (!instruction->IsAdd() ||
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001894 (reduction_type != DataType::Type::kInt32 && reduction_type != DataType::Type::kInt64)) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001895 return false;
1896 }
1897 HInstruction* q = instruction->InputAt(0);
1898 HInstruction* v = instruction->InputAt(1);
1899 HInstruction* a = nullptr;
1900 HInstruction* b = nullptr;
1901 if (v->IsInvokeStaticOrDirect() &&
1902 (v->AsInvokeStaticOrDirect()->GetIntrinsic() == Intrinsics::kMathAbsInt ||
1903 v->AsInvokeStaticOrDirect()->GetIntrinsic() == Intrinsics::kMathAbsLong)) {
1904 HInstruction* x = v->InputAt(0);
Aart Bikdf011c32017-09-28 12:53:04 -07001905 if (x->GetType() == reduction_type) {
1906 int64_t c = 0;
1907 if (x->IsSub()) {
1908 a = x->InputAt(0);
1909 b = x->InputAt(1);
1910 } else if (IsAddConst(x, /*out*/ &a, /*out*/ &c)) {
1911 b = graph_->GetConstant(reduction_type, -c); // hidden SUB!
1912 }
Aart Bikdbbac8f2017-09-01 13:06:08 -07001913 }
1914 }
1915 if (a == nullptr || b == nullptr) {
1916 return false;
1917 }
1918 // Accept same-type or consistent sign extension for narrower-type on operands a and b.
1919 // The same-type or narrower operands are called r (a or lower) and s (b or lower).
Aart Bikdf011c32017-09-28 12:53:04 -07001920 // We inspect the operands carefully to pick the most suited type.
Aart Bikdbbac8f2017-09-01 13:06:08 -07001921 HInstruction* r = a;
1922 HInstruction* s = b;
1923 bool is_unsigned = false;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001924 DataType::Type sub_type = a->GetType();
Aart Bikdf011c32017-09-28 12:53:04 -07001925 if (DataType::Size(b->GetType()) < DataType::Size(sub_type)) {
1926 sub_type = b->GetType();
1927 }
1928 if (a->IsTypeConversion() &&
1929 DataType::Size(a->InputAt(0)->GetType()) < DataType::Size(sub_type)) {
1930 sub_type = a->InputAt(0)->GetType();
1931 }
1932 if (b->IsTypeConversion() &&
1933 DataType::Size(b->InputAt(0)->GetType()) < DataType::Size(sub_type)) {
1934 sub_type = b->InputAt(0)->GetType();
Aart Bikdbbac8f2017-09-01 13:06:08 -07001935 }
1936 if (reduction_type != sub_type &&
1937 (!IsNarrowerOperands(a, b, sub_type, &r, &s, &is_unsigned) || is_unsigned)) {
1938 return false;
1939 }
1940 // Try same/narrower type and deal with vector restrictions.
1941 if (!TrySetVectorType(sub_type, &restrictions) || HasVectorRestrictions(restrictions, kNoSAD)) {
1942 return false;
1943 }
1944 // Accept SAD idiom for vectorizable operands. Vectorized code uses the shorthand
1945 // idiomatic operation. Sequential code uses the original scalar expressions.
1946 DCHECK(r != nullptr);
1947 DCHECK(s != nullptr);
1948 if (generate_code && vector_mode_ != kVector) { // de-idiom
1949 r = s = v->InputAt(0);
1950 }
1951 if (VectorizeUse(node, q, generate_code, sub_type, restrictions) &&
1952 VectorizeUse(node, r, generate_code, sub_type, restrictions) &&
1953 VectorizeUse(node, s, generate_code, sub_type, restrictions)) {
1954 if (generate_code) {
1955 if (vector_mode_ == kVector) {
1956 vector_map_->Put(instruction, new (global_allocator_) HVecSADAccumulate(
1957 global_allocator_,
1958 vector_map_->Get(q),
1959 vector_map_->Get(r),
1960 vector_map_->Get(s),
1961 reduction_type,
1962 GetOtherVL(reduction_type, sub_type, vector_length_)));
1963 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorizedIdiom);
1964 } else {
1965 GenerateVecOp(v, vector_map_->Get(r), nullptr, reduction_type);
1966 GenerateVecOp(instruction, vector_map_->Get(q), vector_map_->Get(v), reduction_type);
1967 }
1968 }
1969 return true;
1970 }
1971 return false;
1972}
1973
Aart Bikf3e61ee2017-04-12 17:09:20 -07001974//
Aart Bik14a68b42017-06-08 14:06:58 -07001975// Vectorization heuristics.
1976//
1977
1978bool HLoopOptimization::IsVectorizationProfitable(int64_t trip_count) {
1979 // Current heuristic: non-empty body with sufficient number
1980 // of iterations (if known).
1981 // TODO: refine by looking at e.g. operation count, alignment, etc.
1982 if (vector_length_ == 0) {
1983 return false; // nothing found
1984 } else if (0 < trip_count && trip_count < vector_length_) {
1985 return false; // insufficient iterations
1986 }
1987 return true;
1988}
1989
Aart Bikb29f6842017-07-28 15:58:41 -07001990void HLoopOptimization::SetPeelingCandidate(const ArrayReference* candidate,
1991 int64_t trip_count ATTRIBUTE_UNUSED) {
Aart Bik14a68b42017-06-08 14:06:58 -07001992 // Current heuristic: none.
1993 // TODO: implement
Aart Bikb29f6842017-07-28 15:58:41 -07001994 vector_peeling_candidate_ = candidate;
Aart Bik14a68b42017-06-08 14:06:58 -07001995}
1996
Artem Serovf26bb6c2017-09-01 10:59:03 +01001997static constexpr uint32_t ARM64_SIMD_MAXIMUM_UNROLL_FACTOR = 8;
1998static constexpr uint32_t ARM64_SIMD_HEURISTIC_MAX_BODY_SIZE = 50;
1999
Aart Bik14a68b42017-06-08 14:06:58 -07002000uint32_t HLoopOptimization::GetUnrollingFactor(HBasicBlock* block, int64_t trip_count) {
Aart Bik14a68b42017-06-08 14:06:58 -07002001 switch (compiler_driver_->GetInstructionSet()) {
Artem Serovf26bb6c2017-09-01 10:59:03 +01002002 case kArm64: {
Aart Bik521b50f2017-09-09 10:44:45 -07002003 // Don't unroll with insufficient iterations.
Artem Serovf26bb6c2017-09-01 10:59:03 +01002004 // TODO: Unroll loops with unknown trip count.
Aart Bik521b50f2017-09-09 10:44:45 -07002005 DCHECK_NE(vector_length_, 0u);
Artem Serovf26bb6c2017-09-01 10:59:03 +01002006 if (trip_count < 2 * vector_length_) {
Aart Bik521b50f2017-09-09 10:44:45 -07002007 return kNoUnrollingFactor;
Aart Bik14a68b42017-06-08 14:06:58 -07002008 }
Aart Bik521b50f2017-09-09 10:44:45 -07002009 // Don't unroll for large loop body size.
Artem Serovf26bb6c2017-09-01 10:59:03 +01002010 uint32_t instruction_count = block->GetInstructions().CountSize();
Aart Bik521b50f2017-09-09 10:44:45 -07002011 if (instruction_count >= ARM64_SIMD_HEURISTIC_MAX_BODY_SIZE) {
2012 return kNoUnrollingFactor;
2013 }
Artem Serovf26bb6c2017-09-01 10:59:03 +01002014 // Find a beneficial unroll factor with the following restrictions:
2015 // - At least one iteration of the transformed loop should be executed.
2016 // - The loop body shouldn't be "too big" (heuristic).
2017 uint32_t uf1 = ARM64_SIMD_HEURISTIC_MAX_BODY_SIZE / instruction_count;
2018 uint32_t uf2 = trip_count / vector_length_;
2019 uint32_t unroll_factor =
2020 TruncToPowerOfTwo(std::min({uf1, uf2, ARM64_SIMD_MAXIMUM_UNROLL_FACTOR}));
2021 DCHECK_GE(unroll_factor, 1u);
Artem Serovf26bb6c2017-09-01 10:59:03 +01002022 return unroll_factor;
Aart Bik14a68b42017-06-08 14:06:58 -07002023 }
Artem Serovf26bb6c2017-09-01 10:59:03 +01002024 case kX86:
2025 case kX86_64:
Aart Bik14a68b42017-06-08 14:06:58 -07002026 default:
Aart Bik521b50f2017-09-09 10:44:45 -07002027 return kNoUnrollingFactor;
Aart Bik14a68b42017-06-08 14:06:58 -07002028 }
2029}
2030
2031//
Aart Bikf8f5a162017-02-06 15:35:29 -08002032// Helpers.
2033//
2034
2035bool HLoopOptimization::TrySetPhiInduction(HPhi* phi, bool restrict_uses) {
Aart Bikb29f6842017-07-28 15:58:41 -07002036 // Start with empty phi induction.
2037 iset_->clear();
2038
Nicolas Geoffrayf57c1ae2017-06-28 17:40:18 +01002039 // Special case Phis that have equivalent in a debuggable setup. Our graph checker isn't
2040 // smart enough to follow strongly connected components (and it's probably not worth
2041 // it to make it so). See b/33775412.
2042 if (graph_->IsDebuggable() && phi->HasEquivalentPhi()) {
2043 return false;
2044 }
Aart Bikb29f6842017-07-28 15:58:41 -07002045
2046 // Lookup phi induction cycle.
Aart Bikcc42be02016-10-20 16:14:16 -07002047 ArenaSet<HInstruction*>* set = induction_range_.LookupCycle(phi);
2048 if (set != nullptr) {
2049 for (HInstruction* i : *set) {
Aart Bike3dedc52016-11-02 17:50:27 -07002050 // Check that, other than instructions that are no longer in the graph (removed earlier)
Aart Bikf8f5a162017-02-06 15:35:29 -08002051 // each instruction is removable and, when restrict uses are requested, other than for phi,
2052 // all uses are contained within the cycle.
Aart Bike3dedc52016-11-02 17:50:27 -07002053 if (!i->IsInBlock()) {
2054 continue;
2055 } else if (!i->IsRemovable()) {
2056 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08002057 } else if (i != phi && restrict_uses) {
Aart Bikb29f6842017-07-28 15:58:41 -07002058 // Deal with regular uses.
Aart Bikcc42be02016-10-20 16:14:16 -07002059 for (const HUseListNode<HInstruction*>& use : i->GetUses()) {
2060 if (set->find(use.GetUser()) == set->end()) {
2061 return false;
2062 }
2063 }
2064 }
Aart Bike3dedc52016-11-02 17:50:27 -07002065 iset_->insert(i); // copy
Aart Bikcc42be02016-10-20 16:14:16 -07002066 }
Aart Bikcc42be02016-10-20 16:14:16 -07002067 return true;
2068 }
2069 return false;
2070}
2071
Aart Bikb29f6842017-07-28 15:58:41 -07002072bool HLoopOptimization::TrySetPhiReduction(HPhi* phi) {
Aart Bikcc42be02016-10-20 16:14:16 -07002073 DCHECK(iset_->empty());
Aart Bikb29f6842017-07-28 15:58:41 -07002074 // Only unclassified phi cycles are candidates for reductions.
2075 if (induction_range_.IsClassified(phi)) {
2076 return false;
2077 }
2078 // Accept operations like x = x + .., provided that the phi and the reduction are
2079 // used exactly once inside the loop, and by each other.
2080 HInputsRef inputs = phi->GetInputs();
2081 if (inputs.size() == 2) {
2082 HInstruction* reduction = inputs[1];
2083 if (HasReductionFormat(reduction, phi)) {
2084 HLoopInformation* loop_info = phi->GetBlock()->GetLoopInformation();
2085 int32_t use_count = 0;
2086 bool single_use_inside_loop =
2087 // Reduction update only used by phi.
2088 reduction->GetUses().HasExactlyOneElement() &&
2089 !reduction->HasEnvironmentUses() &&
2090 // Reduction update is only use of phi inside the loop.
2091 IsOnlyUsedAfterLoop(loop_info, phi, /*collect_loop_uses*/ true, &use_count) &&
2092 iset_->size() == 1;
2093 iset_->clear(); // leave the way you found it
2094 if (single_use_inside_loop) {
2095 // Link reduction back, and start recording feed value.
2096 reductions_->Put(reduction, phi);
2097 reductions_->Put(phi, phi->InputAt(0));
2098 return true;
2099 }
2100 }
2101 }
2102 return false;
2103}
2104
2105bool HLoopOptimization::TrySetSimpleLoopHeader(HBasicBlock* block, /*out*/ HPhi** main_phi) {
2106 // Start with empty phi induction and reductions.
2107 iset_->clear();
2108 reductions_->clear();
2109
2110 // Scan the phis to find the following (the induction structure has already
2111 // been optimized, so we don't need to worry about trivial cases):
2112 // (1) optional reductions in loop,
2113 // (2) the main induction, used in loop control.
2114 HPhi* phi = nullptr;
2115 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
2116 if (TrySetPhiReduction(it.Current()->AsPhi())) {
2117 continue;
2118 } else if (phi == nullptr) {
2119 // Found the first candidate for main induction.
2120 phi = it.Current()->AsPhi();
2121 } else {
2122 return false;
2123 }
2124 }
2125
2126 // Then test for a typical loopheader:
2127 // s: SuspendCheck
2128 // c: Condition(phi, bound)
2129 // i: If(c)
2130 if (phi != nullptr && TrySetPhiInduction(phi, /*restrict_uses*/ false)) {
Aart Bikcc42be02016-10-20 16:14:16 -07002131 HInstruction* s = block->GetFirstInstruction();
2132 if (s != nullptr && s->IsSuspendCheck()) {
2133 HInstruction* c = s->GetNext();
Aart Bikd86c0852017-04-14 12:00:15 -07002134 if (c != nullptr &&
2135 c->IsCondition() &&
2136 c->GetUses().HasExactlyOneElement() && // only used for termination
2137 !c->HasEnvironmentUses()) { // unlikely, but not impossible
Aart Bikcc42be02016-10-20 16:14:16 -07002138 HInstruction* i = c->GetNext();
2139 if (i != nullptr && i->IsIf() && i->InputAt(0) == c) {
2140 iset_->insert(c);
2141 iset_->insert(s);
Aart Bikb29f6842017-07-28 15:58:41 -07002142 *main_phi = phi;
Aart Bikcc42be02016-10-20 16:14:16 -07002143 return true;
2144 }
2145 }
2146 }
2147 }
2148 return false;
2149}
2150
2151bool HLoopOptimization::IsEmptyBody(HBasicBlock* block) {
Aart Bikf8f5a162017-02-06 15:35:29 -08002152 if (!block->GetPhis().IsEmpty()) {
2153 return false;
2154 }
2155 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
2156 HInstruction* instruction = it.Current();
2157 if (!instruction->IsGoto() && iset_->find(instruction) == iset_->end()) {
2158 return false;
Aart Bikcc42be02016-10-20 16:14:16 -07002159 }
Aart Bikf8f5a162017-02-06 15:35:29 -08002160 }
2161 return true;
2162}
2163
2164bool HLoopOptimization::IsUsedOutsideLoop(HLoopInformation* loop_info,
2165 HInstruction* instruction) {
Aart Bikb29f6842017-07-28 15:58:41 -07002166 // Deal with regular uses.
Aart Bikf8f5a162017-02-06 15:35:29 -08002167 for (const HUseListNode<HInstruction*>& use : instruction->GetUses()) {
2168 if (use.GetUser()->GetBlock()->GetLoopInformation() != loop_info) {
2169 return true;
2170 }
Aart Bikcc42be02016-10-20 16:14:16 -07002171 }
2172 return false;
2173}
2174
Aart Bik482095d2016-10-10 15:39:10 -07002175bool HLoopOptimization::IsOnlyUsedAfterLoop(HLoopInformation* loop_info,
Aart Bik8c4a8542016-10-06 11:36:57 -07002176 HInstruction* instruction,
Aart Bik6b69e0a2017-01-11 10:20:43 -08002177 bool collect_loop_uses,
Aart Bik8c4a8542016-10-06 11:36:57 -07002178 /*out*/ int32_t* use_count) {
Aart Bikb29f6842017-07-28 15:58:41 -07002179 // Deal with regular uses.
Aart Bik8c4a8542016-10-06 11:36:57 -07002180 for (const HUseListNode<HInstruction*>& use : instruction->GetUses()) {
2181 HInstruction* user = use.GetUser();
2182 if (iset_->find(user) == iset_->end()) { // not excluded?
2183 HLoopInformation* other_loop_info = user->GetBlock()->GetLoopInformation();
Aart Bik482095d2016-10-10 15:39:10 -07002184 if (other_loop_info != nullptr && other_loop_info->IsIn(*loop_info)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -08002185 // If collect_loop_uses is set, simply keep adding those uses to the set.
2186 // Otherwise, reject uses inside the loop that were not already in the set.
2187 if (collect_loop_uses) {
2188 iset_->insert(user);
2189 continue;
2190 }
Aart Bik8c4a8542016-10-06 11:36:57 -07002191 return false;
2192 }
2193 ++*use_count;
2194 }
2195 }
2196 return true;
2197}
2198
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002199bool HLoopOptimization::TryReplaceWithLastValue(HLoopInformation* loop_info,
2200 HInstruction* instruction,
2201 HBasicBlock* block) {
2202 // Try to replace outside uses with the last value.
Aart Bik807868e2016-11-03 17:51:43 -07002203 if (induction_range_.CanGenerateLastValue(instruction)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -08002204 HInstruction* replacement = induction_range_.GenerateLastValue(instruction, graph_, block);
Aart Bikb29f6842017-07-28 15:58:41 -07002205 // Deal with regular uses.
Aart Bik6b69e0a2017-01-11 10:20:43 -08002206 const HUseList<HInstruction*>& uses = instruction->GetUses();
2207 for (auto it = uses.begin(), end = uses.end(); it != end;) {
2208 HInstruction* user = it->GetUser();
2209 size_t index = it->GetIndex();
2210 ++it; // increment before replacing
2211 if (iset_->find(user) == iset_->end()) { // not excluded?
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002212 if (kIsDebugBuild) {
2213 // We have checked earlier in 'IsOnlyUsedAfterLoop' that the use is after the loop.
2214 HLoopInformation* other_loop_info = user->GetBlock()->GetLoopInformation();
2215 CHECK(other_loop_info == nullptr || !other_loop_info->IsIn(*loop_info));
2216 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08002217 user->ReplaceInput(replacement, index);
2218 induction_range_.Replace(user, instruction, replacement); // update induction
2219 }
2220 }
Aart Bikb29f6842017-07-28 15:58:41 -07002221 // Deal with environment uses.
Aart Bik6b69e0a2017-01-11 10:20:43 -08002222 const HUseList<HEnvironment*>& env_uses = instruction->GetEnvUses();
2223 for (auto it = env_uses.begin(), end = env_uses.end(); it != end;) {
2224 HEnvironment* user = it->GetUser();
2225 size_t index = it->GetIndex();
2226 ++it; // increment before replacing
2227 if (iset_->find(user->GetHolder()) == iset_->end()) { // not excluded?
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002228 // Only update environment uses after the loop.
Aart Bik14a68b42017-06-08 14:06:58 -07002229 HLoopInformation* other_loop_info = user->GetHolder()->GetBlock()->GetLoopInformation();
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002230 if (other_loop_info == nullptr || !other_loop_info->IsIn(*loop_info)) {
2231 user->RemoveAsUserOfInput(index);
2232 user->SetRawEnvAt(index, replacement);
2233 replacement->AddEnvUseAt(user, index);
2234 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08002235 }
2236 }
Aart Bik807868e2016-11-03 17:51:43 -07002237 return true;
Aart Bik8c4a8542016-10-06 11:36:57 -07002238 }
Aart Bik807868e2016-11-03 17:51:43 -07002239 return false;
Aart Bik8c4a8542016-10-06 11:36:57 -07002240}
2241
Aart Bikf8f5a162017-02-06 15:35:29 -08002242bool HLoopOptimization::TryAssignLastValue(HLoopInformation* loop_info,
2243 HInstruction* instruction,
2244 HBasicBlock* block,
2245 bool collect_loop_uses) {
2246 // Assigning the last value is always successful if there are no uses.
2247 // Otherwise, it succeeds in a no early-exit loop by generating the
2248 // proper last value assignment.
2249 int32_t use_count = 0;
2250 return IsOnlyUsedAfterLoop(loop_info, instruction, collect_loop_uses, &use_count) &&
2251 (use_count == 0 ||
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002252 (!IsEarlyExit(loop_info) && TryReplaceWithLastValue(loop_info, instruction, block)));
Aart Bikf8f5a162017-02-06 15:35:29 -08002253}
2254
Aart Bik6b69e0a2017-01-11 10:20:43 -08002255void HLoopOptimization::RemoveDeadInstructions(const HInstructionList& list) {
2256 for (HBackwardInstructionIterator i(list); !i.Done(); i.Advance()) {
2257 HInstruction* instruction = i.Current();
2258 if (instruction->IsDeadAndRemovable()) {
2259 simplified_ = true;
2260 instruction->GetBlock()->RemoveInstructionOrPhi(instruction);
2261 }
2262 }
2263}
2264
Aart Bik14a68b42017-06-08 14:06:58 -07002265bool HLoopOptimization::CanRemoveCycle() {
2266 for (HInstruction* i : *iset_) {
2267 // We can never remove instructions that have environment
2268 // uses when we compile 'debuggable'.
2269 if (i->HasEnvironmentUses() && graph_->IsDebuggable()) {
2270 return false;
2271 }
2272 // A deoptimization should never have an environment input removed.
2273 for (const HUseListNode<HEnvironment*>& use : i->GetEnvUses()) {
2274 if (use.GetUser()->GetHolder()->IsDeoptimize()) {
2275 return false;
2276 }
2277 }
2278 }
2279 return true;
2280}
2281
Aart Bik281c6812016-08-26 11:31:48 -07002282} // namespace art